omni-notify-mcp 1.3.319 → 1.3.321

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.
@@ -12,13 +12,11 @@
12
12
  import { fileURLToPath } from "url";
13
13
  import { splitForNotify } from "./chunk.js";
14
14
  import { masterMuted } from "./notify.js";
15
- import { appendEvent, isConsoleSession, CONVERSATION_MUTED_MESSAGE, conversationRefusal, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
15
+ import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
16
16
  import { SessionDriver } from "./gateway/sessionDriver.js";
17
17
  import { DEFAULT_PROVIDER } from "./gateway/provider.js";
18
18
  import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
19
19
  export const AGENT_PREFIX = "!";
20
- /** A chat door's own words when a message points at a browser CLI console session: the chat does not drive a live CLI, so it says so plainly and names where that session IS reachable. */
21
- const CONSOLE_NOT_IN_CHAT = "That is a live CLI console session opened in the browser — this chat does not type into it. Use /terminal in BN, or reach the SAME session from MCP/REST by its id (agent_send types into it, agent_stream streams its console).";
22
20
  /** A chat: the newest conversation not stopped (`/new` and `/stop` end it), and every line of the turn, the answer split at 500. */
23
21
  const CHAT = {
24
22
  conversationOf: openConversationOf,
@@ -167,8 +165,6 @@ export class AgentGateway {
167
165
  }
168
166
  /** Acts on one addressed message. Resolves when its answer (or its failure) has been sent back. */
169
167
  async handle(key, platform, act, reply, origin = {}) {
170
- if (act.kind === "say" && listConversations(true).some((c) => isConsoleSession(c) && act.text.includes(c.id)))
171
- return reply(CONSOLE_NOT_IN_CHAT);
172
168
  const arrived = monotonicMs();
173
169
  const carriage = CARRIAGE[platform];
174
170
  const refusal = conversationRefusal();
@@ -251,14 +251,12 @@ function agentLine(record) {
251
251
  * The project picker on a conversation's row (#2723, #2900): only the allowed projects BN lists that hold a board, no typed path.
252
252
  * The pick posts the project NAME to POST /v1/conversations/{id}/project, and the row shows the new project once the
253
253
  * record carries it; a refusal — a turn running, a folder that is not there — says why beside the picker.
254
- * A CLI console session's folder is NOT changeable and never was: its CLI runs in the folder it was started in and its
255
- * terminal cannot be moved out from under itself, so the slot is shown with the one folder it has and says why (#3614).
256
254
  */
257
- function projectPicker(c, folders, after, fixed) {
255
+ function projectPicker(c, folders, after) {
258
256
  var box = el("span", "pick");
259
257
  var pick = el("select");
260
258
  pick.setAttribute("aria-label", "project folder");
261
- var choices = [{ name: c.project ? base(c.project) : "no project", path: c.project || "" }].concat(fixed ? [] : folders);
259
+ var choices = [{ name: c.project ? base(c.project) : "no project", path: c.project || "" }].concat(folders);
262
260
  var seen = {};
263
261
  choices.forEach(function (choice) {
264
262
  if (seen[choice.path]) return;
@@ -269,15 +267,6 @@ function projectPicker(c, folders, after, fixed) {
269
267
  });
270
268
  pick.value = c.project || "";
271
269
  var note = null;
272
- if (fixed) {
273
- pick.disabled = true;
274
- pick.title = "A CLI console session keeps the folder its own CLI was started in: that CLI cannot be moved out from under itself. Its row shows the one folder it has.";
275
- box.title = pick.title;
276
- box.append(pick);
277
- box.onclick = function (e) { e.stopPropagation(); };
278
- box.pick = pick;
279
- return box;
280
- }
281
270
  var write = async function (folder) {
282
271
  pick.disabled = true;
283
272
  try { await api("POST", "/v1/conversations/" + c.id + "/project", { project: base(folder) }); await after(); pick.disabled = false; }
@@ -314,8 +303,6 @@ async function listView(shelf) {
314
303
  try { folders = (await api("GET", "/v1/projects")).projects.filter(function (p) { return p.board; }).map(function (p) { return { name: p.name, path: p.path }; }); }
315
304
  catch (err) { if (err.message === "signed out") return; foldersNote = "The project folders could not be read — " + err.message + "."; }
316
305
  if (mine !== view) return;
317
- // The whole path, because a row's own door is not always the conversation's: closing a console session's CLI goes to
318
- // that session's terminal, which is the endpoint the view's own Close CLI uses (#3614).
319
306
  var act = async function (button, method, path) {
320
307
  button.disabled = true;
321
308
  try { await api(method, path); await paint(); }
@@ -336,7 +323,7 @@ async function listView(shelf) {
336
323
  var keyOf = function (col) { return col.key || "_check"; };
337
324
  var value = function (c, key) {
338
325
  if (key === "project") return c.project ? base(c.project).toLowerCase() : "";
339
- if (key === "state") return (cliLed(c) ? "interactive-only " : "") + c.state;
326
+ if (key === "state") return c.state;
340
327
  if (key === "provider") return c.provider;
341
328
  if (key === "origin") return originOf(c);
342
329
  if (key === "id") return c.id;
@@ -354,7 +341,7 @@ async function listView(shelf) {
354
341
  return cmp * sort.dir;
355
342
  });
356
343
  };
357
- var stateText = function (c) { return cliLed(c) ? "🖥️ CLI · " + c.state : c.state; };
344
+ var stateText = function (c) { return c.state; };
358
345
  var textOf = function (c, col) {
359
346
  if (col.key === "project") return c.project ? base(c.project) : "No project";
360
347
  if (col.key === "state") return stateText(c);
@@ -374,26 +361,11 @@ async function listView(shelf) {
374
361
  };
375
362
 
376
363
  var scroll = null, table = null, headRow = null, body = null, countEl = null, noticeEl = null, selectAll = null, emptyRow = null;
377
- // The console sessions that still have a CLI behind them (#3614), so Close CLI is offered only where it acts.
378
- // null means the listing could not be read: an unknown is never drawn as "gone", so the slot stays offered.
379
- var running = null;
380
364
  /** Whether this row's stop slot has anything to act on — the ONE rule both the row's button and the batch button use, so a row the batch would not act on is never offered as one it would. */
381
365
  var stoppable = function (c) {
382
- return cliLed(c) ? (running === null || running[c.id] === true) : c.state !== "closed";
366
+ return c.state !== "closed";
383
367
  };
384
368
  var haltState = function (button, c) {
385
- if (cliLed(c)) {
386
- var live = stoppable(c);
387
- button.disabled = !live;
388
- button.title = live
389
- ? c.mode === "interactive-only"
390
- ? "Closes this session's own CLI now — that process ends and its record stays as history."
391
- : "Closes the CLI this page opened on this conversation now — that process ends and the conversation stays open on the same agent session, ready for its next message."
392
- : c.mode === "interactive-only"
393
- ? "This session's CLI has already ended, so there is nothing to close; its record is what is left."
394
- : "The CLI this page opened on this conversation has already ended, so there is nothing to close; a message resumes the same agent session.";
395
- return;
396
- }
397
369
  button.disabled = !stoppable(c);
398
370
  button.title = button.disabled ? "This conversation is already stopped. A message resumes it." : "Stops this conversation — it runs no further turn, and a later message resumes it.";
399
371
  };
@@ -485,22 +457,17 @@ async function listView(shelf) {
485
457
  return;
486
458
  }
487
459
  if (col.plain) {
488
- // ONE action row for every kind of session (#3614): Open, the stop slot, Archive/Restore, Delete, then the
489
- // project slot — the same places on every row. What differs is only what the stop slot really does there, and
490
- // it is never given another row's word for it.
491
- var console = cliLed(first);
460
+ // ONE action row for every session (#3614, #3916): Open, Stop, Archive/Restore, Delete, then the project slot.
492
461
  var actrow = el("div", "actrow");
493
462
  var acts = el("div", "acts");
494
463
  var open = el("button", "", "📂 Open");
495
464
  open.onclick = function (e) { e.stopPropagation(); go("term", node.c.id); };
496
465
  acts.append(open);
497
- // A turn conversation is STOPPED — its agent runs no further turn and a later message resumes it. A console
498
- // session's own CLI is CLOSED — that process ends and the record stays as history. Never the same label.
499
- var halt = el("button", "halt", console ? "⏹ Close CLI" : "⏹ Stop");
466
+ // A conversation is STOPPED — its CLI ends, it runs no further turn and a later message resumes the same session.
467
+ var halt = el("button", "halt", "⏹ Stop");
500
468
  halt.onclick = function (e) {
501
469
  e.stopPropagation();
502
- if (cliLed(node.c)) act(halt, "DELETE", "/v1/terminals/" + node.c.id);
503
- else act(halt, "DELETE", "/v1/conversations/" + node.c.id);
470
+ act(halt, "DELETE", "/v1/conversations/" + node.c.id);
504
471
  };
505
472
  acts.append(halt);
506
473
  node.halt = halt;
@@ -510,7 +477,7 @@ async function listView(shelf) {
510
477
  drop.onclick = function (e) { e.stopPropagation(); act(drop, "POST", "/v1/conversations/" + node.c.id + "/delete"); };
511
478
  acts.append(move, drop);
512
479
  actrow.append(acts);
513
- node.pick = projectPicker(node.c, folders, paint, console);
480
+ node.pick = projectPicker(node.c, folders, paint);
514
481
  actrow.append(node.pick);
515
482
  cell.append(actrow);
516
483
  tr.append(cell);
@@ -582,8 +549,7 @@ async function listView(shelf) {
582
549
  countEl.textContent = n === 0 ? "Select conversations to act on them." : n + " selected";
583
550
  if (selectAll !== null) { selectAll.checked = shown.length > 0 && n === shown.length; selectAll.indeterminate = n > 0 && n < shown.length; }
584
551
  [buttons.move, buttons.delete, buttons.clear].forEach(function (b) { if (b) b.disabled = n === 0; });
585
- // Stop is offered only when at least one picked row has something to stop (#3614): a conversation already stopped
586
- // has none, and a console session whose CLI has ended has nothing left to close.
552
+ // Stop is offered only when at least one picked row has something to stop (#3614): a conversation already stopped has none.
587
553
  if (buttons.stop) buttons.stop.disabled = !shown.some(function (c) { return picked[c.id] === true && stoppable(c); });
588
554
  };
589
555
 
@@ -599,13 +565,12 @@ async function listView(shelf) {
599
565
  var runBatch = async function (which) {
600
566
  var chosen = shown.filter(function (c) { return picked[c.id]; });
601
567
  if (chosen.length === 0) return;
602
- // The batch applies to each row the SAME act that row's own button applies (#3614): a turn conversation is
603
- // stopped, a console session's own CLI is closed. One word is never used for the other.
568
+ // The batch applies to each row the SAME act that row's own button applies (#3614).
604
569
  var call = function (c) {
605
570
  if (which !== "stop") return api("POST", "/v1/conversations/" + c.id + (which === "delete" ? "/delete" : archived ? "/unarchive" : "/archive"));
606
- return cliLed(c) ? api("DELETE", "/v1/terminals/" + c.id) : api("DELETE", "/v1/conversations/" + c.id);
571
+ return api("DELETE", "/v1/conversations/" + c.id);
607
572
  };
608
- var word = which === "stop" ? "stopped or closed" : which === "delete" ? "deleted" : archived ? "restored" : "archived";
573
+ var word = which === "stop" ? "stopped" : which === "delete" ? "deleted" : archived ? "restored" : "archived";
609
574
  // A row with nothing to stop is left alone and named as having nothing to stop — never called and then reported as
610
575
  // a failure for refusing, which is what a 404 for an already-ended CLI would look like (#3614).
611
576
  var acts = which === "stop" ? chosen.filter(stoppable) : chosen;
@@ -642,7 +607,7 @@ async function listView(shelf) {
642
607
  bar.append(b);
643
608
  return b;
644
609
  };
645
- if (!archived) mkButton("Stop / Close CLI", "", "stop");
610
+ if (!archived) mkButton("Stop", "", "stop");
646
611
  mkButton(archived ? "Restore" : "Archive", "", "move");
647
612
  mkButton("Delete", "bad", "delete");
648
613
  buttons.clear = el("button", "", "Clear");
@@ -700,21 +665,6 @@ async function listView(shelf) {
700
665
  rows = data.conversations.slice();
701
666
  if (table === null) build();
702
667
  render();
703
- // Which console sessions still have a CLI behind them — a SECOND read, so the rows are on screen first and the
704
- // Close CLI slot settles the moment it lands. It is never allowed to hold the list up: its own handler can sit
705
- // for the close wait, and a list that renders nothing until then would be the worse fault. A read that failed
706
- // leaves the last reading standing and never turns an unknown into "gone".
707
- return api("GET", "/v1/terminals").then(function (listing) {
708
- if (mine !== view) return;
709
- var live = {};
710
- listing.terminals.forEach(function (t) { if (!t.ended) live[t.id] = true; });
711
- running = live;
712
- render();
713
- }, function (err) {
714
- // OWNER: this list's own second read — a console listing that failed leaves the last reading standing and never turns an unknown into "gone", and the list itself carries on.
715
- if (!(err instanceof Error)) throw err;
716
- if (err.message === "signed out") return;
717
- });
718
668
  });
719
669
  };
720
670
  var again = function () { timer = setTimeout(run, 8000); };
@@ -14,7 +14,7 @@ import { randomBytes, randomUUID } from "crypto";
14
14
  import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync, watch } from "fs";
15
15
  import { homedir } from "os";
16
16
  import { dirname, join, resolve } from "path";
17
- import { openDrivenTerminal } from "./nativeTerminal.js";
17
+ import { CliSession, endsWithTyped, folderKey, plain, sameText } from "./cliSession.js";
18
18
  import { AgentTurnFailed } from "./provider.js";
19
19
  /** The CLI's own config folder, where its sessions and its config file live. */
20
20
  function configDir() {
@@ -34,11 +34,6 @@ function transcriptWritten(sessionId) {
34
34
  return false;
35
35
  return readdirSync(projects).some((dir) => existsSync(join(projects, dir, `${sessionId}.jsonl`)));
36
36
  }
37
- /** A folder path as the CLI's config keys it: forward slashes, and case-folded on Windows, whose paths ignore case. */
38
- function folderKey(folder) {
39
- const key = resolve(folder).replace(/\\/g, "/").replace(/\/+$/, "");
40
- return process.platform === "win32" ? key.toLowerCase() : key;
41
- }
42
37
  /**
43
38
  * Whether the person has trusted this folder, or a folder above it, in the CLI's own "Yes, I trust this folder" — read
44
39
  * from the CLI's config file, never written. The interactive CLI asks that question before anything else in a folder
@@ -59,19 +54,12 @@ function folderTrusted(folder) {
59
54
  }
60
55
  }
61
56
  const BN_REACHES_HIM_ON_THE_PAGE = "mcp__notify__notify,mcp__notify__ask,mcp__notify__reply,mcp__notify__wait_for_inbox";
62
- // GATE: how often Enter is pressed again while the CLI has not yet taken a typed prompt — CLI 2.1.322 drops an Enter that arrives before it can submit (measured: the first ~6 s after it starts), and an Enter on an empty prompt does nothing, so the press is repeated until the UserPromptSubmit hook arrives.
63
- const ENTER_EVERY_MS = 1_000;
64
57
  /** The path under BN's door a session's hooks are posted to; the key after it names the session. */
65
58
  export const CLAUDE_HOOK_PATH = "/v1/claude-hooks/";
66
59
  /** The hooks a session's CLI posts: a prompt taken, a tool about to run and one that ran, a notice to the person, a prompt ended, and a prompt that ended in an API failure. */
67
60
  const HOOKED = ["UserPromptSubmit", "PreToolUse", "PostToolUse", "Notification", "Stop", "StopFailure"];
68
61
  /** The notices the CLI raises while it waits on the person's own answer on its screen: a permission question, or a question an MCP server asks. */
69
62
  const ASKS_THE_PERSON = new Set(["permission_prompt", "elicitation_dialog"]);
70
- /**
71
- * A prompt starting with one of these is a command to the interactive CLI, not words to the agent — "!" runs the rest
72
- * in a shell and "/" a slash command — while the headless CLI read both as plain words. A leading space keeps them words.
73
- */
74
- const CLI_COMMAND_START = /^[!/]/;
75
63
  /**
76
64
  * A prompt another Claude session sent this CLI (Claude Code wraps it in `<cross-session-message>`). A conversation's
77
65
  * CLI takes its turns from BN and from the person at its screen only: the headless CLI it replaced could never be sent
@@ -80,14 +68,13 @@ const CLI_COMMAND_START = /^[!/]/;
80
68
  */
81
69
  const FROM_ANOTHER_SESSION = /<cross-session-message[\s>]/;
82
70
  /**
83
- * Where a session's CLI reports its turns: BN's own door, once it is listening, and the person that door serves, who
84
- * holds every conversation's CLI. The door binds before the driver boots (notify.ts `bindGatewayPort` then
85
- * `startOwnedWork`), so every session is opened with a port to report to.
71
+ * Where a session's CLI reports its turns: BN's own door, once it is listening. The door binds before the driver boots
72
+ * (notify.ts `bindGatewayPort` then `startOwnedWork`), so every session is opened with a port to report to.
86
73
  */
87
74
  const sessions = new Map();
88
- let door;
75
+ let hookPort;
89
76
  export const claudeHooks = {
90
- listening(port, person) { door = { port, person }; },
77
+ listening(port) { hookPort = port; },
91
78
  /** One hook a session's CLI posted, and its answer; undefined when the key names no session of this process (it ended, or BN restarted past it). */
92
79
  deliver(key, hook) {
93
80
  const session = sessions.get(key);
@@ -97,23 +84,6 @@ export const claudeHooks = {
97
84
  return session(hook);
98
85
  },
99
86
  };
100
- /**
101
- * A prompt as the CLI reports it taken, compared on its words: line endings and the edges' whitespace are the terminal's,
102
- * not the prompt's, and a long paste the CLI hands on wrapped in its own `<pasted_content id="N">` tags (measured on CLI
103
- * 2.1.322: a 24-line, 1816-character paste was taken as the same text inside that wrapper) is compared by what it wraps.
104
- */
105
- function plain(prompt) {
106
- return prompt.replace(/\r\n?/g, "\n").replace(/<pasted_content id="([^"]*)">\n?([\s\S]*?)\n?<\/pasted_content id="\1">/g, "$2").trim();
107
- }
108
- function sameText(taken, typed) {
109
- return plain(taken) === plain(typed);
110
- }
111
- /** A prompt the CLI took with the typed words at its end: they went in after text already standing in its input box. */
112
- function endsWithTyped(taken, typed) {
113
- return plain(taken).endsWith(plain(typed));
114
- }
115
- // GATE: how many Ctrl+U presses clear one line of text the CLI put back into its input box — measured on CLI 2.1.322: one press empties the line, the next joins it to the line above.
116
- const CLEARS_PER_LINE = 2;
117
87
  /**
118
88
  * Whether the CLI has written, in the complete lines past `turn.from`, the record it writes once a prompt is over — after
119
89
  * every Stop hook let it end (measured on CLI 2.1.322: a Stop a hook refused is followed by `hook_blocking_error` and the
@@ -135,115 +105,44 @@ function promptOver(transcript, turn) {
135
105
  turn.from += complete;
136
106
  return tail.subarray(0, complete).toString("utf8").includes('"subtype":"turn_duration"');
137
107
  }
138
- class ClaudeCliSession {
139
- spec;
140
- terminal;
108
+ class ClaudeCliSession extends CliSession {
141
109
  key = randomBytes(16).toString("hex");
142
- /** The CLI resumes a session it already wrote, rather than creating one. */
143
- resumes;
144
- turn;
145
- /** Every prompt the CLI took and has not ended, in the order it took them — the driver's and any typed in the browser. */
146
- open = [];
147
110
  /** Every prompt id the CLI has reported taking — a prompt taken under one of these joined a prompt already running. */
148
111
  seen = new Set();
149
- waiting = [];
150
- /** Lines of a refused prompt the CLI put back into its input box (measured on CLI 2.1.322), cleared before the next paste. */
151
- restored = 0;
152
- /** BN asked this CLI to end: a turn it still held is refused as ended, and nothing of its record is written after. */
153
- ending = false;
154
- /** The sink of the driver's message from the moment it is asked until it ends — also while it waits behind a prompt typed in the browser — so a tool any prompt of the CLI runs counts as the CLI at work. */
155
- listening;
156
112
  /** Settles once the CLI has drawn its first output: its input editor is up, so a typed paste reaches it. */
157
113
  drawn;
158
- constructor(spec, onGone) {
159
- this.spec = spec;
114
+ constructor(spec) {
160
115
  if (!folderTrusted(spec.project))
161
116
  throw spec.failures.fail(`Claude Code has not been trusted in ${spec.project}, so its CLI would stop on "Do you trust this folder?" before reading any message — run claude in that folder once and answer "Yes, I trust this folder", then send the message again`);
162
- const reportTo = door;
163
- this.resumes = spec.started || transcriptWritten(spec.sessionId);
164
- const hook = [{ hooks: [{ type: "http", url: `http://127.0.0.1:${reportTo.port}${CLAUDE_HOOK_PATH}${this.key}` }] }];
117
+ super(spec, claudeProvider, spec.started || transcriptWritten(spec.sessionId));
118
+ const hook = [{ hooks: [{ type: "http", url: `http://127.0.0.1:${hookPort}${CLAUDE_HOOK_PATH}${this.key}` }] }];
165
119
  const settings = JSON.stringify({ hooks: Object.fromEntries(HOOKED.map((name) => [name, hook])) });
166
- const args = [
120
+ sessions.set(this.key, (event) => this.hook(event));
121
+ this.launch([
167
122
  ...(spec.model === undefined ? [] : ["--model", spec.model]),
168
123
  ...(spec.title === undefined ? [] : ["--name", spec.title]),
169
124
  ...(this.resumes ? ["--resume", spec.sessionId] : ["--session-id", spec.sessionId]),
170
125
  "--permission-mode", "bypassPermissions", "--disallowedTools", BN_REACHES_HIM_ON_THE_PAGE, "--settings", settings,
171
- ];
172
- sessions.set(this.key, (event) => this.hook(event));
173
- this.terminal = openDrivenTerminal(reportTo.person(), { id: spec.id, provider: claudeProvider, project: spec.project, cmd: spec.cli.cmd, args: [...spec.cli.args, ...args], cols: 100, rows: 30 });
126
+ ]);
174
127
  let draw;
175
128
  this.drawn = new Promise((resolve) => { draw = resolve; });
176
129
  this.terminal.onOutput(() => draw());
177
- this.terminal.onEnded(() => {
178
- sessions.delete(this.key);
179
- const turn = this.turn;
180
- this.turn = undefined;
181
- this.open.length = 0;
182
- for (const wake of this.waiting.splice(0))
183
- wake();
184
- // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
185
- if (turn !== undefined) {
186
- clearInterval(turn.enter);
187
- turn.watcher?.close();
188
- if (this.ending)
189
- turn.reject(new AgentTurnFailed("the agent's session was ended", "❌ BN ended this conversation's CLI before the turn answered — nothing more of it was read."));
190
- else
191
- void this.lost(turn.sink).then(turn.reject);
192
- }
193
- onGone();
194
- });
195
- }
196
- get pid() {
197
- return this.terminal.info().pid;
130
+ this.watchEnd();
198
131
  }
199
- /** A turn of the driver's, or a prompt someone typed into this CLI, has not ended. */
200
- get working() {
201
- return this.turn !== undefined || this.open.length > 0;
132
+ closed() {
133
+ sessions.delete(this.key);
202
134
  }
203
- adopt(conversation) {
204
- this.terminal.rekey(conversation);
135
+ ready() {
136
+ return this.drawn;
205
137
  }
206
- async quiet() {
207
- while (this.open.length > 0)
208
- await new Promise((wake) => this.waiting.push(wake));
138
+ newTurn(turn) {
139
+ return { ...turn, from: 0 };
209
140
  }
210
- async ask(message, sink, _timeoutMs, _token) {
211
- const prompt = message.replace(/\x1b/g, "");
212
- this.listening = sink;
213
- try {
214
- await this.quiet();
215
- if (this.terminal.info().ended)
216
- throw await this.lost(sink);
217
- return await new Promise((resolve, reject) => {
218
- const turn = { prompt, sink, resolve, reject, from: 0 };
219
- this.turn = turn;
220
- void this.type(turn, prompt).catch((err) => this.settle(turn, () => reject(new AgentTurnFailed(`the prompt could not be typed into the agent's CLI: ${err.message}`))));
221
- });
222
- }
223
- finally {
224
- this.listening = undefined;
225
- }
141
+ released(turn) {
142
+ turn.watcher?.close();
226
143
  }
227
- /** Types the prompt once the CLI has drawn its screen, then presses Enter until the CLI says it took it. */
228
- async type(turn, prompt) {
229
- const refusal = await this.terminal.started;
230
- // NULL-OK: field refusal is OPTIONAL and therefore it is ok to check for NULL
231
- if (refusal !== undefined || this.turn !== turn)
232
- return;
233
- turn.sink.pid(this.terminal.info().pid);
234
- await this.drawn;
235
- if (this.turn !== turn)
236
- return;
237
- if (this.restored > 0)
238
- await this.terminal.input("\x15".repeat(this.restored * CLEARS_PER_LINE + 1), false);
239
- this.restored = 0;
240
- await this.terminal.input(`\x1b[200~${CLI_COMMAND_START.test(prompt) ? ` ${prompt}` : prompt}\x1b[201~`, false);
241
- const press = () => {
242
- if (this.turn === turn && turn.promptId === undefined && !this.terminal.info().ended)
243
- void this.terminal.input("\r", false).catch((err) => this.settle(turn, () => turn.reject(new AgentTurnFailed(`Enter could not be pressed in the agent's CLI: ${err.message}`))));
244
- };
245
- press();
246
- turn.enter = setInterval(press, ENTER_EVERY_MS);
144
+ adopt(conversation) {
145
+ this.terminal.rekey(conversation);
247
146
  }
248
147
  /**
249
148
  * One hook the CLI posted and its answer: a prompt from another Claude session is refused, and so is the driver's
@@ -253,7 +152,7 @@ class ClaudeCliSession {
253
152
  hook(event) {
254
153
  if (event.hook_event_name === "UserPromptSubmit" && typeof event.prompt === "string") {
255
154
  const turn = this.turn;
256
- const typing = turn !== undefined && turn.promptId === undefined && endsWithTyped(event.prompt, turn.prompt);
155
+ const typing = turn !== undefined && !turn.taken && endsWithTyped(event.prompt, turn.prompt);
257
156
  if (FROM_ANOTHER_SESSION.test(event.prompt)) {
258
157
  this.restored = plain(event.prompt).split("\n").length;
259
158
  if (typing)
@@ -272,7 +171,7 @@ class ClaudeCliSession {
272
171
  /** A prompt taken (the driver's, or one typed in the browser), a tool any prompt runs, a wait on the person, or a prompt ended. */
273
172
  react(event) {
274
173
  const turn = this.turn;
275
- const mine = turn !== undefined && turn.promptId !== undefined;
174
+ const mine = turn !== undefined && turn.taken;
276
175
  switch (event.hook_event_name) {
277
176
  case "UserPromptSubmit": return this.taken(event);
278
177
  case "PreToolUse":
@@ -309,18 +208,16 @@ class ClaudeCliSession {
309
208
  this.seen.add(event.prompt_id);
310
209
  this.open.push(event.prompt_id);
311
210
  // NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
312
- if (turn === undefined || turn.promptId !== undefined || typeof event.prompt !== "string" || !sameText(event.prompt, turn.prompt))
211
+ if (turn === undefined || turn.taken || typeof event.prompt !== "string" || !sameText(event.prompt, turn.prompt))
313
212
  return;
314
213
  turn.promptId = event.prompt_id;
315
214
  turn.joined = joined;
316
- clearInterval(turn.enter);
317
215
  if (event.permission_mode !== "bypassPermissions") {
318
216
  this.end();
319
217
  this.settle(turn, () => turn.reject(new AgentTurnFailed(`the Claude CLI runs in "${String(event.permission_mode)}" mode, not bypassPermissions, because this machine never accepted bypass-permissions mode`, `❌ This machine's Claude CLI has never accepted bypass-permissions mode, so it would stop on a permission question for every tool — BN stopped the turn. Set "skipDangerousModePermissionPrompt": true in ~/.claude/settings.json (or start claude --dangerously-skip-permissions once and accept), then send the message again.`)));
320
218
  return;
321
219
  }
322
- turn.sink.started();
323
- turn.sink.stdout();
220
+ this.takenNow(turn);
324
221
  }
325
222
  /**
326
223
  * The CLI ended a prompt. The driver's turn ends with its own prompt, or inside a later one the CLI ran it together
@@ -354,8 +251,7 @@ class ClaudeCliSession {
354
251
  this.settle(turn, () => turn.reject(new AgentTurnFailed("the Claude CLI's Stop hook carried no transcript_path, so BN cannot tell whether a Stop hook sent the agent on after this Stop")));
355
252
  }
356
253
  if (this.open.length === 0)
357
- for (const wake of this.waiting.splice(0))
358
- wake();
254
+ this.wake();
359
255
  }
360
256
  /** The turn answers with its prompt's latest Stop once the CLI records that prompt over in its transcript. */
361
257
  answerOnceOver(turn, transcript) {
@@ -398,41 +294,20 @@ class ClaudeCliSession {
398
294
  idle(why) {
399
295
  this.open.length = 0;
400
296
  const turn = this.turn;
401
- if (turn !== undefined && turn.promptId !== undefined)
297
+ if (turn !== undefined && turn.taken)
402
298
  this.settle(turn, () => turn.reject(new AgentTurnFailed(why, `❌ The agent's turn did not end with an answer: ${why}. Send the message again to run it.`)));
403
- for (const wake of this.waiting.splice(0))
404
- wake();
405
- }
406
- /** Ends the driver's turn once, with what `end` decides. */
407
- settle(turn, end) {
408
- if (this.turn !== turn)
409
- return;
410
- this.turn = undefined;
411
- clearInterval(turn.enter);
412
- turn.watcher?.close();
413
- end();
299
+ this.wake();
414
300
  }
415
- /** The failure of a CLI that ended without the answer it was asked for, in the CLI's own last words on its screen. */
416
- async lost(sink) {
417
- const screen = (await this.terminal.screenText()).split("\n").map((line) => line.trim()).filter((line) => line !== "");
418
- const said = (this.terminal.info().failure ?? screen.slice(-3).join(" / ")) || "the CLI showed no reason on its screen";
419
- const how = this.resumes ? `resuming session ${this.spec.sessionId}` : `creating session ${this.spec.sessionId}`;
420
- process.stderr.write(`[agent-gateway] ${this.spec.id}: the Claude CLI ended while ${how} in ${this.spec.project}: ${said.slice(0, 300)}\n`);
421
- if (this.resumes && !transcriptWritten(this.spec.sessionId)) {
422
- sink.sessionId(randomUUID(), false);
423
- const lostText = `this conversation's agent session ${this.spec.sessionId} cannot be resumed — its saved history is no longer on disk under ${projectsDir()} (the Claude CLI ended while ${how} in ${this.spec.project}: ${said.slice(0, 200)})`;
424
- return new AgentTurnFailed(lostText, `❌ ${lostText[0].toUpperCase()}${lostText.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.`);
425
- }
426
- return new AgentTurnFailed(`the agent's CLI ended without an answer while ${how}: ${said.slice(0, 300)}`, `❌ The agent's CLI ended without an answer while ${how}: ${said.slice(0, 300)}`);
301
+ starting() {
302
+ return `creating session ${this.spec.sessionId}`;
427
303
  }
428
- end() {
429
- this.ending = true;
430
- this.terminal.close().catch((err) => {
431
- // OWNER: the driver's free/stop is the trigger root and cannot wait on the kill — a CLI the machine refuses to end is reported here and stays listed with that refusal on its terminal row.
432
- this.terminal.refuse(err.message);
433
- process.stderr.write(`[agent-gateway] the CLI of ${this.spec.id} could not be ended: ${err.message}\n`);
434
- });
435
- return "";
304
+ /** A session resumed whose saved history is gone: the next message runs in a new session of the same conversation. */
305
+ sessionLost(how, said, sink) {
306
+ if (!this.resumes || transcriptWritten(this.spec.sessionId))
307
+ return undefined;
308
+ sink.sessionId(randomUUID(), false);
309
+ const lostText = `this conversation's agent session ${this.spec.sessionId} cannot be resumed — its saved history is no longer on disk under ${projectsDir()} (the Claude CLI ended while ${how} in ${this.spec.project}: ${said.slice(0, 200)})`;
310
+ return new AgentTurnFailed(lostText, `❌ ${lostText[0].toUpperCase()}${lostText.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.`);
436
311
  }
437
312
  }
438
313
  export const claudeProvider = {
@@ -441,5 +316,5 @@ export const claudeProvider = {
441
316
  command: "claude",
442
317
  nativeArgs: (model) => model ? ["--model", model] : [],
443
318
  console: true,
444
- open: (spec) => new ClaudeCliSession(spec, spec.onGone),
319
+ open: (spec) => new ClaudeCliSession(spec),
445
320
  };