omni-notify-mcp 1.3.381 → 1.3.382

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.
@@ -239,6 +239,7 @@ export class LoggedCliSession extends CliSession {
239
239
  finder;
240
240
  /** Every line submitted through this CLI's terminal — by the browser or by the driver — while its log is not found yet. */
241
241
  submitted = [];
242
+ unacknowledged = [];
242
243
  /** The last failure to read the log reported, so a failure that repeats on every read is reported once. */
243
244
  lastReported;
244
245
  reader;
@@ -257,6 +258,7 @@ export class LoggedCliSession extends CliSession {
257
258
  this.bind(cli.log.resumed(spec.sessionId), true);
258
259
  this.launch(cli.args(spec, this.resumes), cli.env);
259
260
  this.terminal.onSubmit((line) => {
261
+ this.unacknowledged.push(line);
260
262
  // NULL-OK: field log is OPTIONAL and therefore it is ok to check for NULL
261
263
  if (this.log === undefined)
262
264
  this.submitted.push(line);
@@ -271,6 +273,7 @@ export class LoggedCliSession extends CliSession {
271
273
  this.reader.unref();
272
274
  this.watchEnd();
273
275
  }
276
+ get pendingInput() { return this.unacknowledged.length > 0; }
274
277
  closed() {
275
278
  clearInterval(this.reader);
276
279
  clearTimeout(this.still);
@@ -374,7 +377,10 @@ export class LoggedCliSession extends CliSession {
374
377
  this.learnedId = true;
375
378
  this.spec.learned(news.id);
376
379
  return;
377
- case "taken":
380
+ case "taken": {
381
+ const acknowledged = this.unacknowledged.findIndex((line) => sameText(news.text, line));
382
+ if (acknowledged >= 0)
383
+ this.unacknowledged.splice(acknowledged, 1);
378
384
  this.listening?.stdout();
379
385
  if (turn === undefined || turn.taken || !endsWithTyped(news.text, turn.prompt)) {
380
386
  this.open.push("theirs");
@@ -388,6 +394,7 @@ export class LoggedCliSession extends CliSession {
388
394
  this.open.push("mine");
389
395
  this.takenNow(turn);
390
396
  return;
397
+ }
391
398
  case "busy":
392
399
  this.listening?.stdout();
393
400
  return;
@@ -17,6 +17,7 @@ import { homedir } from "os";
17
17
  import { join } from "path";
18
18
  import { CONFIG_DIR } from "../notify.js";
19
19
  import { LoggedCliSession, folderKey, logRow } from "./cliSession.js";
20
+ import { nativeCliRefusal } from "./provider.js";
20
21
  /** The conversation's own folder under BN's config, named by a hash of its stable name so one conversation never sees another's sessions. */
21
22
  function stateDir(name) {
22
23
  return join(CONFIG_DIR, "agent", "copilot", createHash("sha256").update(name).digest("hex").slice(0, 16));
@@ -115,7 +116,7 @@ function copilotCli(configDir) {
115
116
  ...(resumes ? ["--resume", spec.sessionId] : []),
116
117
  ],
117
118
  log: new CopilotLog(configDir),
118
- refusal: (spec) => folderTrusted(spec.project) ? undefined : `Copilot has not been trusted in ${spec.project}, so its CLI would stop on "Do you trust the files in this folder?" before reading any message — run copilot in that folder once and answer "Yes, and remember this folder for future sessions", then send the message again`,
119
+ refusal: (spec) => copilotProvider.refusal(spec.project, spec.model, spec.cli),
119
120
  };
120
121
  }
121
122
  export const copilotProvider = {
@@ -123,5 +124,9 @@ export const copilotProvider = {
123
124
  label: "Copilot",
124
125
  command: "copilot",
125
126
  nativeArgs: (model) => model ? ["--model", model] : [],
126
- open: (spec) => new LoggedCliSession(spec, copilotCli(stateDir(spec.name ?? spec.sessionId))),
127
+ refusal: (project, _model, cli) => folderTrusted(project) ? nativeCliRefusal("copilot", project, cli) : `Copilot has not been trusted in ${project}, so its CLI would stop on "Do you trust the files in this folder?" before reading any message — run copilot in that folder once and answer "Yes, and remember this folder for future sessions", then send the message again`,
128
+ open: (spec) => {
129
+ const configDir = stateDir(spec.name ?? spec.sessionId);
130
+ return Object.assign(new LoggedCliSession(spec, copilotCli(configDir)), { storePath: join(configDir, "session-state") });
131
+ },
127
132
  };
@@ -0,0 +1,61 @@
1
+ import { accessSync, constants, readFileSync, statSync } from "fs";
2
+ import { delimiter, dirname, isAbsolute, join, resolve } from "path";
3
+ /** The same executable, shim entry and environment are checked for the picker and the native PTY launch. */
4
+ export function nativeCliInvocation(command, args, env = process.env, platform = process.platform) {
5
+ const windows = platform === "win32";
6
+ const hasPath = isAbsolute(command) || /[\\/]/.test(command);
7
+ const candidates = hasPath ? [command] : (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean).flatMap((directory) => windows && !/\.(exe|com|cmd|bat)$/i.test(command) ? [".exe", ".com", ".cmd", ".bat"].map((extension) => join(directory, command + extension)) : [join(directory, command)]);
8
+ let executable;
9
+ let last = "not found on the native launch PATH";
10
+ for (const candidate of candidates) {
11
+ try {
12
+ accessSync(candidate, windows ? constants.F_OK : constants.X_OK);
13
+ if (!statSync(candidate).isFile()) {
14
+ last = candidate + " is not a file";
15
+ continue;
16
+ }
17
+ executable = candidate;
18
+ break;
19
+ }
20
+ catch (error) {
21
+ if (!["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(String(error.code)))
22
+ throw error;
23
+ // OWNER: filesystem availability is external; return the same missing executable fact without changing PATH.
24
+ last = candidate + ": " + error.code;
25
+ }
26
+ }
27
+ if (executable === undefined)
28
+ return { reason: command + " cannot start: " + last };
29
+ let launch = { command: executable, args: [...args] };
30
+ if (windows && /\.(cmd|bat)$/i.test(executable)) {
31
+ let shim;
32
+ try {
33
+ shim = readFileSync(executable, "utf8");
34
+ }
35
+ catch (error) {
36
+ if (!["ENOENT", "EACCES", "EPERM"].includes(String(error.code)))
37
+ throw error;
38
+ // OWNER: the native shim can disappear or lose access after discovery; the same read-only predicate refuses it.
39
+ return { reason: command + " cannot start: shim " + executable + ": " + error.code };
40
+ }
41
+ const script = /"%dp0%[\\/]([^"\r\n]+\.m?js)"/i.exec(shim);
42
+ const binary = /^"%dp0%[\\/]([^"\r\n]+\.exe)"[ \t]+%\*[ \t]*$/im.exec(shim);
43
+ if (script)
44
+ launch = { command: process.execPath, args: [resolve(dirname(executable), script[1]), ...args] };
45
+ else if (binary)
46
+ launch = { command: resolve(dirname(executable), binary[1]), args: [...args] };
47
+ }
48
+ const entry = launch.command === process.execPath && /\.[cm]?js$/i.test(launch.args[0] ?? "") ? launch.args[0] : launch.command;
49
+ try {
50
+ accessSync(entry, windows || entry !== launch.command ? constants.R_OK : constants.X_OK);
51
+ if (!statSync(entry).isFile())
52
+ return { reason: command + " cannot start: native entry " + entry + " is not a file" };
53
+ }
54
+ catch (error) {
55
+ if (!["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(String(error.code)))
56
+ throw error;
57
+ // OWNER: an installed shim may outlive its native entry; expose the missing entry instead of offering a broken CLI.
58
+ return { reason: command + " cannot start: native entry " + entry + ": " + error.code };
59
+ }
60
+ return launch;
61
+ }
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "crypto";
1
2
  import { spawn, spawnSync } from "child_process";
2
3
  import { EventEmitter } from "events";
3
4
  import { appendFile, readdir, rm } from "fs/promises";
@@ -8,7 +9,7 @@ import { fileURLToPath } from "url";
8
9
  import headless from "@xterm/headless";
9
10
  import serializer from "@xterm/addon-serialize";
10
11
  import { GatewayError, MAX_WAIT_SECONDS } from "./conversations.js";
11
- import { agentEnv } from "./provider.js";
12
+ import { nativeAgentEnv } from "./provider.js";
12
13
  const { Terminal } = headless;
13
14
  const { SerializeAddon } = serializer;
14
15
  /** Whether a process id still names a live process: EPERM means it exists and this account may not signal it. */
@@ -75,6 +76,8 @@ export class NativeTerminal {
75
76
  closing;
76
77
  failure;
77
78
  processId;
79
+ inputEpoch = randomUUID();
80
+ submissions = 0;
78
81
  /** What the open answers with: nothing once the CLI is up, or the reason this machine refused to start it — so a
79
82
  * refusal reaches the person who asked rather than a record that is reaped before anyone reads it. */
80
83
  started;
@@ -141,12 +144,7 @@ export class NativeTerminal {
141
144
  this.events.emit("change");
142
145
  this.reap();
143
146
  });
144
- const env = agentEnv(spec.project);
145
- env.TERM = "xterm-256color";
146
- // A CLI opened in the browser is the person's own interactive session, never a nested child of whatever launched
147
- // this daemon: inheriting the marker suppresses its transcripts and its connectors on screen.
148
- delete env.CLAUDE_CODE_CHILD_SESSION;
149
- Object.assign(env, spec.env);
147
+ const env = nativeAgentEnv(spec.project, spec.env);
150
148
  this.child.send({ kind: "start", command: spec.cmd, args: spec.args, project: spec.project, cols: spec.cols, rows: spec.rows, env, ownerPid: process.pid });
151
149
  }
152
150
  /** The record this CLI answers for. */
@@ -198,7 +196,7 @@ export class NativeTerminal {
198
196
  this.reap();
199
197
  };
200
198
  }
201
- info() { return { id: this.id, provider: this.provider, project: this.project, createdAt: this.createdAt, pid: this.processId, ended: this.ended, starting: !this.ended && this.processId === undefined, failure: this.failure, cols: this.screen.cols, rows: this.screen.rows }; }
199
+ info() { return { id: this.id, provider: this.provider, project: this.project, createdAt: this.createdAt, inputVersion: `${this.inputEpoch}:${this.submissions}`, pid: this.processId, ended: this.ended, starting: !this.ended && this.processId === undefined, failure: this.failure, cols: this.screen.cols, rows: this.screen.rows }; }
202
200
  async read(after, signal) {
203
201
  this.readers++;
204
202
  try {
@@ -272,17 +270,19 @@ export class NativeTerminal {
272
270
  const key = data[at++];
273
271
  if (this.pasting)
274
272
  this.typing += key === "\r" ? "\n" : key;
275
- else if (key === "\r") {
273
+ else if (key === "\r" || key === "\n") {
276
274
  const line = this.typing;
277
275
  this.typing = "";
278
- if (line.trim() !== "")
276
+ if (line.trim() !== "") {
277
+ this.submissions++;
279
278
  this.events.emit("submitted", line);
279
+ }
280
280
  }
281
281
  else if (key === "\x7f" || key === "\b")
282
282
  this.typing = this.typing.slice(0, -1);
283
283
  else if (key === "\x15")
284
284
  this.typing = "";
285
- else if (key >= " " || key === "\n" || key === "\t")
285
+ else if (key >= " " || key === "\t")
286
286
  this.typing += key;
287
287
  }
288
288
  }
@@ -409,8 +409,8 @@ export class NativeTerminal {
409
409
  this.events.emit("change");
410
410
  this.reap();
411
411
  }
412
- live() { if (this.ended)
413
- throw new GatewayError(409, "This CLI has ended; open a new native terminal."); }
412
+ live() { if (this.ended || this.closing !== undefined)
413
+ throw new GatewayError(409, "This CLI is closing or has ended; open a new native terminal."); }
414
414
  }
415
415
  const terminals = new Map();
416
416
  /** Tells whoever waits on an id that a CLI is now registered under it. */
@@ -1,9 +1,10 @@
1
1
  import { createRequire } from "module";
2
- import { existsSync, readFileSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from "fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from "fs";
3
3
  import { homedir } from "os";
4
- import { dirname, delimiter, join, resolve } from "path";
4
+ import { join } from "path";
5
5
  import { fileURLToPath } from "url";
6
6
  import { spawnSync } from "child_process";
7
+ import { nativeCliInvocation } from "./nativeCliInvocation.js";
7
8
  import { ownerBoundLaunch } from "../shared/agentSession.js";
8
9
  const require = createRequire(import.meta.url);
9
10
  const packaged = fileURLToPath(new URL("../vendor/node-pty/lib/index.js", import.meta.url));
@@ -11,25 +12,6 @@ let library;
11
12
  /** node-pty is loaded on the first CLI, so a platform this build carries no native binary for answers with its own
12
13
  * reason instead of the worker dying at startup where nothing could say why. */
13
14
  function pty() { return (library ??= require(existsSync(packaged) ? packaged : "node-pty")); }
14
- function invocation(command, args) {
15
- if (process.platform !== "win32")
16
- return { command, args };
17
- const directories = (process.env.PATH || "").split(delimiter);
18
- const extensions = [".exe", ".com", ".cmd", ".bat"];
19
- const executable = directories.flatMap((directory) => extensions.map((extension) => join(directory, command + extension))).find(existsSync);
20
- if (!executable)
21
- return { command, args };
22
- if (/\.(cmd|bat)$/i.test(executable)) {
23
- const shim = readFileSync(executable, "utf8");
24
- const script = /"%dp0%[\\/]([^"\r\n]+\.m?js)"/i.exec(shim);
25
- if (script)
26
- return { command: process.execPath, args: [resolve(dirname(executable), script[1]), ...args] };
27
- const binary = /^"%dp0%[\\/]([^"\r\n]+\.exe)"[ \t]+%\*[ \t]*$/im.exec(shim);
28
- if (binary)
29
- return { command: resolve(dirname(executable), binary[1]), args };
30
- }
31
- return { command: executable, args };
32
- }
33
15
  let terminal;
34
16
  let started = false;
35
17
  let ending = false;
@@ -100,7 +82,12 @@ process.on("message", (message) => {
100
82
  started = true;
101
83
  let launched;
102
84
  try {
103
- const launch = invocation(message.command, message.args);
85
+ const launch = nativeCliInvocation(message.command, message.args, message.env);
86
+ if (launch.reason !== undefined) {
87
+ send({ kind: "unavailable", message: launch.reason });
88
+ process.exit(0);
89
+ return;
90
+ }
104
91
  const bundledGuard = new URL("../scripts/shared/", import.meta.url);
105
92
  const guardDir = fileURLToPath(existsSync(bundledGuard) ? bundledGuard : new URL("../../scripts/shared/", import.meta.url));
106
93
  const guarded = ownerBoundLaunch({ cmd: launch.command, args: launch.args }, message.ownerPid, message.project, guardDir);
@@ -22,6 +22,7 @@ import autoSwitch from "../shared/webhost/autoSwitch.cjs";
22
22
  import { OpenCodeTurnMemory } from "../shared/agentSession.js";
23
23
  import { CliEnded, LoggedCliSession } from "./cliSession.js";
24
24
  import { CONFIG_DIR } from "../notify.js";
25
+ import { AgentTurnFailed, nativeCliRefusal } from "./provider.js";
25
26
  // GATE: the words of a retry status that mean the provider rate-limited THIS key; any other retry (a 5xx, a dropped connection) is the CLI riding out a fault the key did not cause
26
27
  const RATE_LIMITED = /rate.?limit|too many requests/i;
27
28
  const ROUTE_REFUSALS = new Set(["OPENCODE_NO_KEY", "KEYPLAN_UNREADABLE", "REFUSAL_UNREADABLE"]);
@@ -176,9 +177,11 @@ function opencodeCli(spec, memory) {
176
177
  return {
177
178
  get provider() { return opencodeProvider; },
178
179
  args: (_spec, resumes) => ["--auto", "-m", route.model, ...(resumes ? ["-s", spec.sessionId] : [])],
180
+ nativeModel: route.model,
181
+ storePath: join(route.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share"), "opencode", "opencode.db"),
179
182
  env: { ...route.env, BN_OPENCODE_LOG: file, OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: [EVENT_PLUGIN.href], autoupdate: false }) },
180
183
  log: new OpenCodeLog(file, spec.started ? spec.sessionId : undefined, key),
181
- refusal: () => undefined,
184
+ refusal: () => nativeCliRefusal("opencode", spec.project, spec.cli, route.env),
182
185
  };
183
186
  }
184
187
  /**
@@ -189,6 +192,9 @@ function opencodeCli(spec, memory) {
189
192
  class OpenCodeSession {
190
193
  spec;
191
194
  inner;
195
+ /** The database of the exact native route opened, published to the owning conversation record. */
196
+ storePath;
197
+ nativeModel;
192
198
  /** The session id the CLI wrote, or the record's own when it was already written. */
193
199
  written;
194
200
  carrying = false;
@@ -216,10 +222,14 @@ class OpenCodeSession {
216
222
  },
217
223
  learned: (id) => { this.written = id; this.spec.learned(id); },
218
224
  };
219
- return new LoggedCliSession(own, opencodeCli(own, this.memory));
225
+ const cli = opencodeCli(own, this.memory);
226
+ this.storePath = cli.storePath;
227
+ this.nativeModel = cli.nativeModel;
228
+ return new LoggedCliSession(own, cli);
220
229
  }
221
230
  get pid() { return this.inner.pid; }
222
231
  get working() { return this.inner.working; }
232
+ get pendingInput() { return this.inner.pendingInput; }
223
233
  quiet() { return this.inner.quiet(); }
224
234
  end() { this.stopped = true; return this.inner.end(); }
225
235
  async ask(prompt, sink, timeoutMs, token) {
@@ -261,5 +271,17 @@ export const opencodeProvider = {
261
271
  label: "OpenCode",
262
272
  command: "opencode",
263
273
  nativeArgs: (model) => model ? ["-m", model] : [],
274
+ refusal: (project, model, cli) => {
275
+ try {
276
+ const route = routeOf(model, (message) => new AgentTurnFailed(message));
277
+ return nativeCliRefusal("opencode", project, cli, route.env);
278
+ }
279
+ catch (error) {
280
+ if (!(error instanceof AgentTurnFailed))
281
+ throw error;
282
+ // OWNER: the native route could not be made from its current free models and keys; expose the same refusal startup uses.
283
+ return error.message;
284
+ }
285
+ },
264
286
  open: (spec) => new OpenCodeSession(spec),
265
287
  };
@@ -1,3 +1,12 @@
1
+ /**
2
+ * The provider seam (#2058): everything the session driver must know about one agent CLI, and nothing else.
3
+ *
4
+ * One conversation names its provider in the record (`provider`). The driver asks the registry (`providers.ts`) for
5
+ * that provider, opens its session and runs turns; it never builds a CLI's arguments, reads its stdout or parses its
6
+ * answer itself. A provider supplies, in its own file: how a turn is launched (create and resume), how its output is
7
+ * read, and where its session id comes from.
8
+ */
9
+ import { nativeCliInvocation } from "./nativeCliInvocation.js";
1
10
  /** A turn that did not produce an answer: the CLI would not start, exited without one, or asked for something BN does not answer. */
2
11
  export class AgentTurnFailed extends Error {
3
12
  /** The failed line the conversation shows when this failure has its own wording; the driver writes its default when it is absent. */
@@ -17,3 +26,13 @@ export class AgentTurnFailed extends Error {
17
26
  export function agentEnv(project) {
18
27
  return { ...process.env, CLAUDE_PROJECT_DIR: project };
19
28
  }
29
+ /** The native PTY and its preflight use exactly this process environment. */
30
+ export function nativeAgentEnv(project, extra) {
31
+ const env = agentEnv(project);
32
+ env.TERM = "xterm-256color";
33
+ delete env.CLAUDE_CODE_CHILD_SESSION;
34
+ return Object.assign(env, extra);
35
+ }
36
+ export function nativeCliRefusal(command, project, cli = { cmd: command, args: [] }, env) {
37
+ return nativeCliInvocation(cli.cmd, cli.args, nativeAgentEnv(project, env)).reason;
38
+ }
@@ -9,6 +9,13 @@ import { opencodeProvider } from "./opencodeProvider.js";
9
9
  const providers = [claudeProvider, codexProvider, copilotProvider, opencodeProvider];
10
10
  /** Each provider's record name beside the words its start line uses, for the page that offers the choice (#3353). */
11
11
  export const PROVIDER_CHOICES = providers.map((p) => ({ name: p.name, label: p.label }));
12
+ /** The owning providers compute these known startup facts; the actual open repeats the same validation. */
13
+ export function providerAvailability(project, model, clis = {}) {
14
+ return providers.map((provider) => {
15
+ const reason = provider.refusal?.(project, model, clis[provider.name]);
16
+ return { name: provider.name, label: provider.label, ...(reason === undefined ? {} : { reason }) };
17
+ });
18
+ }
12
19
  /** The names a conversation may name. */
13
20
  export const PROVIDER_NAMES = PROVIDER_CHOICES.map((p) => p.name);
14
21
  export function providerFor(name) {
@@ -9,7 +9,7 @@
9
9
  * once a passkey is enrolled the gateway token is honoured only on a request from this machine.
10
10
  */
11
11
  import { createServer } from "http";
12
- import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversations.js";
12
+ import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, namedProject, workspaceOf, readEvents, turnInFlight, } from "./conversations.js";
13
13
  import { CHAT_HEADERS } from "./chatPage.js";
14
14
  import { isIconPath, serveIcon } from "./iconDoor.js";
15
15
  import { handleMcp } from "./mcpDoor.js";
@@ -20,6 +20,8 @@ import { conversationSwitchRead, panelState, saveConversationSwitch, saveSetting
20
20
  import { PANEL_PAGES, panelHtml } from "./panelPage.js";
21
21
  import { wizard } from "./publicAccess.js";
22
22
  import { terminalHtml } from "./terminalPage.js";
23
+ import { AgentGateway } from "../agentGateway.js";
24
+ import { consoleSession } from "./nativeTerminal.js";
23
25
  import { ServiceHost } from "../shared/webhost/bullseyeWebHost.js";
24
26
  import { sameRoot, workspacesHere } from "../shared/webhost/workspaceList.js";
25
27
  export const BAD_TOKEN_ERROR = "missing or wrong token";
@@ -126,6 +128,14 @@ async function route(req, url, arrivedAt) {
126
128
  // The conversation page's project picker offers the folders that hold a board (#2723), so it reads them from the one list BN resolves projects with.
127
129
  if (resource === "projects" && parts.length === 2 && method === "GET")
128
130
  return { status: 200, body: listProjects(viewerOfHeaders(req.headers, fromThisMachine(req))) };
131
+ if (resource === "providers" && parts.length === 2 && method === "GET") {
132
+ requireConversationEnabled();
133
+ const project = namedProject(url.searchParams.get("project"));
134
+ const viewer = viewerOfHeaders(req.headers, fromThisMachine(req));
135
+ if (viewer !== undefined && !sameRoot(workspaceOf(project), viewer.folder))
136
+ throw new GatewayError(403, "This provider startup reading belongs to another workspace");
137
+ return { status: 200, body: { providers: AgentGateway.instance().driver.availability(project) } };
138
+ }
129
139
  if (resource !== "conversations")
130
140
  throw new GatewayError(404, "unknown route");
131
141
  requireConversationEnabled();
@@ -152,10 +162,30 @@ async function route(req, url, arrivedAt) {
152
162
  }
153
163
  }
154
164
  else if (sub === undefined) {
155
- if (method === "GET")
156
- return { status: 200, body: readConversation(id) };
157
- if (method === "DELETE")
165
+ if (method === "GET") {
166
+ const current = readConversation(id);
167
+ const native = AgentGateway.instance().driver.nativeState(id);
168
+ return { status: 200, body: { ...current, ...native, working: native.working || turnInFlight(readEvents(id), current) !== undefined } };
169
+ }
170
+ if (method === "DELETE") {
171
+ const expected = url.searchParams.get("expectedConsumed");
172
+ if (expected !== null) {
173
+ const turn = Number(expected);
174
+ if (!Number.isSafeInteger(turn) || turn < 0)
175
+ throw new GatewayError(400, "expectedConsumed must name the native turn read before Stop");
176
+ const current = readConversation(id);
177
+ const native = AgentGateway.instance().driver.nativeState(id);
178
+ const version = url.searchParams.get("expectedInputVersion");
179
+ if (version === null || version !== native.inputVersion || current.consumed !== turn || native.working || native.pendingInput || turnInFlight(readEvents(id), current) !== undefined)
180
+ throw new GatewayError(409, "The native conversation has newer or unfinished work; nothing was stopped. Read its current turn before Stop.");
181
+ const terminal = consoleSession(id);
182
+ const stopped = AgentGateway.instance().driver.stop(id);
183
+ if (terminal !== undefined)
184
+ await terminal.close();
185
+ return { status: 200, body: stopped };
186
+ }
158
187
  return { status: 200, body: stopConversation(id) };
188
+ }
159
189
  }
160
190
  else if (sub === "project" && method === "POST") {
161
191
  return { status: 200, body: setConversationProject(id, requiredText(await readJson(req), "project")) };
@@ -24,9 +24,9 @@ import { mkdirSync, watch } from "fs";
24
24
  import { basename } from "path";
25
25
  import { DEFAULT_CAPACITY } from "../shared/agentSession.js";
26
26
  import { AgentTurnFailed } from "./provider.js";
27
- import { PROVIDER_NAMES, providerFor } from "./providers.js";
27
+ import { PROVIDER_NAMES, providerFor, providerAvailability } from "./providers.js";
28
28
  import { consoleSession } from "./nativeTerminal.js";
29
- import { GatewayError, agentDir, appendEvent, archiveConversation, conversationRefusal, eventsSize, listConversations, monotonicMs, purgeConversation, allowedFolder, isAllowedFolder, readConversation, readEvents, reopenConversation, resumeConversation, titleOf, turnInFlight, hasBoard, resumedInLog, shelfInLog, storeChanged, stopConversation, stoppedInLog, updateConversation, } from "./conversations.js";
29
+ import { GatewayError, agentDir, appendEvent, archiveConversation, conversationRefusal, eventsSize, listConversations, monotonicMs, purgeConversation, allowedFolder, isAllowedFolder, pidAlive, readConversation, readEvents, reopenConversation, resumeConversation, titleOf, turnInFlight, hasBoard, resumedInLog, shelfInLog, storeChanged, stopConversation, stoppedInLog, updateConversation, } from "./conversations.js";
30
30
  // GATE: a conversation silent this long (8 hours, the passkey sign-in's own span) frees its process; its next message resumes the session.
31
31
  export const IDLE_MS = 8 * 60 * 60_000;
32
32
  // GATE: Meni's ruling 6A — a turn that has said nothing for this long posts one status line, and another after each such spell.
@@ -59,7 +59,7 @@ function spareProjectOf(conversations, holding) {
59
59
  }
60
60
  /** A turn of the driver's is running in the session, or one the person typed into its CLI: its process is not idle. */
61
61
  function inUse(live) {
62
- return live.busy || live.session.working === true;
62
+ return live.busy || live.session.working === true || live.session.pendingInput === true;
63
63
  }
64
64
  const NEVER = { isCancellationRequested: false, onCancellationRequested: () => ({ dispose: () => { } }) };
65
65
  export class SessionDriver {
@@ -241,6 +241,14 @@ export class SessionDriver {
241
241
  spare.session.adopt?.(c.id);
242
242
  return spare;
243
243
  }
244
+ availability(project, model) { return providerAvailability(project, model, this.clis); }
245
+ /** Current native ownership, including a prompt typed directly into the provider CLI. */
246
+ nativeState(id) {
247
+ const live = this.lives.get(id);
248
+ const terminal = consoleSession(id)?.info();
249
+ const pid = terminal?.pid;
250
+ return { working: live !== undefined && (live.busy || live.session.working === true), pendingInput: live?.session.pendingInput === true, nativePid: pid !== undefined && pidAlive(pid) ? pid : undefined, inputVersion: terminal?.inputVersion, nativeModel: live?.session.nativeModel };
251
+ }
244
252
  /** No turn running and none in line: the store can pass to another process without losing an answer. */
245
253
  quiet() {
246
254
  return this.driving.size === 0 && this.waiting.length === 0;
@@ -660,7 +668,7 @@ export class SessionDriver {
660
668
  ended: () => { }, settleStalled: () => { }, stalled: false, lastOutputAt: Date.now(),
661
669
  };
662
670
  this.lives.set(c.id, live);
663
- updateConversation(c.id, { state: "running", pid: session.pid });
671
+ updateConversation(c.id, { state: "running", pid: session.pid, storePath: session.storePath });
664
672
  return live;
665
673
  }
666
674
  async turn(c, live, message) {
@@ -725,7 +733,7 @@ export class SessionDriver {
725
733
  live.idleTimer = setTimeout(() => {
726
734
  if (this.lives.get(id) !== live || live.busy)
727
735
  return;
728
- if (live.session.working === true || this.watched(id))
736
+ if (live.session.working === true || live.session.pendingInput === true || this.watched(id))
729
737
  this.idleLater(id, live);
730
738
  else
731
739
  this.free(id, "idle");