omni-notify-mcp 1.3.387 → 1.3.389

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.
Files changed (48) hide show
  1. package/dist/agentGateway.js +7 -32
  2. package/dist/daemon.js +1 -1
  3. package/dist/gateway/conversationOwner.js +125 -0
  4. package/dist/gateway/mcpDoor.js +3 -3
  5. package/dist/gateway/mcpEvents.js +1 -1
  6. package/dist/gateway/oauthDoor.js +1 -1
  7. package/dist/gateway/panel.js +1 -1
  8. package/dist/gateway/passkeyDoor.js +1 -1
  9. package/dist/gateway/publicAccess.js +1 -1
  10. package/dist/gateway/restDoor.js +2 -14
  11. package/dist/gateway/terminalDoor.js +17 -102
  12. package/dist/gateway/terminalPage.js +1 -1
  13. package/dist/shared/agentSession.js +132 -15
  14. package/dist/shared/conversation/claudeProvider.js +357 -0
  15. package/dist/{gateway → shared/conversation}/cliSession.js +28 -10
  16. package/dist/{gateway → shared/conversation}/codexArchive.js +1 -1
  17. package/dist/shared/conversation/codexProvider.js +193 -0
  18. package/dist/shared/conversation/conversationOwner.js +44 -0
  19. package/dist/shared/conversation/conversations.js +907 -0
  20. package/dist/shared/conversation/copilotProvider.js +150 -0
  21. package/dist/shared/conversation/nativeTerminal.js +522 -0
  22. package/dist/{gateway → shared/conversation}/nativeTerminalWorker.js +2 -2
  23. package/dist/shared/conversation/opencodeProvider.js +289 -0
  24. package/dist/shared/conversation/ownerContext.js +1 -0
  25. package/dist/shared/conversation/providers.js +30 -0
  26. package/dist/shared/conversation/sessionDriver.js +1028 -0
  27. package/dist/shared/conversation/terminalTransport.js +101 -0
  28. package/package.json +2 -2
  29. package/dist/gateway/agentStream.js +0 -88
  30. package/dist/gateway/claudeProvider.js +0 -355
  31. package/dist/gateway/codexProvider.js +0 -190
  32. package/dist/gateway/conversations.js +0 -906
  33. package/dist/gateway/copilotProvider.js +0 -148
  34. package/dist/gateway/nativeTerminal.js +0 -506
  35. package/dist/gateway/opencodeProvider.js +0 -287
  36. package/dist/gateway/providers.js +0 -23
  37. package/dist/gateway/sessionDriver.js +0 -1022
  38. package/dist/googlehome/foyer-client.js +0 -210
  39. package/dist/googlehome/foyer-codec.js +0 -318
  40. package/dist/googlehome/gpsoauth.js +0 -119
  41. package/dist/googlehome/index.js +0 -267
  42. package/dist/index.js +0 -41
  43. package/dist/shared/webhost/openedWorkspaces.js +0 -62
  44. package/scripts/shared/ownerGuard.cs +0 -665
  45. package/scripts/shared/ownerGuard.ps1 +0 -31
  46. /package/dist/{gateway → shared/conversation}/nativeCliInvocation.js +0 -0
  47. /package/dist/{gateway → shared/conversation}/opencodeEvents.mjs +0 -0
  48. /package/dist/{gateway → shared/conversation}/provider.js +0 -0
@@ -2,19 +2,19 @@
2
2
  * The agent gateway's chat side (#2052): a Telegram, Slack, Discord or Teams message that starts with `!` goes to
3
3
  * the agent; everything else is left to the inbox exactly as before.
4
4
  *
5
- * One conversation per chat or Slack thread, kept in the conversations store (`gateway/conversations.ts`) beside
6
- * the REST door's, and driven by the one session driver (`gateway/sessionDriver.ts`, #2051): the start line, the
5
+ * One conversation per chat or Slack thread, kept in the conversations store (`shared/conversation/conversations.ts`,
6
+ * owned by `gateway/conversationOwner.ts`) beside
7
+ * the REST door's, and driven by the one session driver (`shared/conversation/sessionDriver.ts`, #2051): the start line, the
7
8
  * status lines, a permission question and the answer come back to the chat, the answer split at 500 characters
8
9
  * with (k/N) parts. `/stop` ends the chat's conversation and `/new` ends it so the next `!` opens a fresh one.
9
10
  * An email thread (#2105) is one conversation for good, and gets only its answer, question or failure, each whole.
10
11
  * Every conversation starts in Meni's workspace root, as the web page's and the MCP door's do.
11
12
  */
12
- import { fileURLToPath } from "url";
13
13
  import { splitForNotify } from "./chunk.js";
14
14
  import { masterMuted } from "./notify.js";
15
- import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
16
- import { SessionDriver } from "./gateway/sessionDriver.js";
17
- import { clearOpenCodeLogs } from "./gateway/opencodeProvider.js";
15
+ import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversationOwner.js";
16
+ import { conversationOwner } from "./gateway/conversationOwner.js";
17
+ import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
18
18
  import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
19
19
  export const AGENT_PREFIX = "!";
20
20
  /** A chat: the newest conversation not stopped (`/new` and `/stop` end it), and every line of the turn, the answer split at 500. */
@@ -40,36 +40,11 @@ const MAIL = {
40
40
  const CARRIAGE = { telegram: CHAT, slack: CHAT, discord: CHAT, teams: CHAT, ntfy: CHAT, sms: CHAT, email: MAIL };
41
41
  const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
42
42
  const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
43
- function driverOptions() {
44
- const guardDir = fileURLToPath(new URL("../scripts/shared/", import.meta.url));
45
- // GATE: a stand-in CLI, a warm spare a test asks for, a smaller capacity and shorter idle, silent, stall and archive spells are read ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1; without it the CLI is `claude`, the spare is kept, and the numbers are Meni's ten slots, his 8-hour idle spell, his 2- and 15-minute turn bounds and his 8-hour archive bound.
46
- if (process.env.NOTIFY_MCP_TEST_ENDPOINTS !== "1")
47
- return { guardDir };
48
- const script = process.env.NOTIFY_AGENT_CLI_SCRIPT;
49
- const copilot = process.env.NOTIFY_AGENT_COPILOT_SCRIPT;
50
- const codex = process.env.NOTIFY_AGENT_CODEX_SCRIPT;
51
- const opencode = process.env.NOTIFY_AGENT_OPENCODE_SCRIPT;
52
- return {
53
- guardDir,
54
- spare: process.env.NOTIFY_AGENT_SPARE === "1" ? true : undefined,
55
- clis: {
56
- ...(script ? { claude: { cmd: process.execPath, args: [script] } } : {}),
57
- ...(copilot ? { copilot: { cmd: process.execPath, args: [copilot] } } : {}),
58
- ...(codex ? { codex: { cmd: process.execPath, args: [codex] } } : {}),
59
- ...(opencode ? { opencode: { cmd: process.execPath, args: [opencode] } } : {}),
60
- },
61
- capacity: process.env.NOTIFY_AGENT_CAPACITY ? Number(process.env.NOTIFY_AGENT_CAPACITY) : undefined,
62
- idleMs: process.env.NOTIFY_AGENT_IDLE_MS ? Number(process.env.NOTIFY_AGENT_IDLE_MS) : undefined,
63
- silentMs: process.env.NOTIFY_AGENT_SILENT_MS ? Number(process.env.NOTIFY_AGENT_SILENT_MS) : undefined,
64
- stallMs: process.env.NOTIFY_AGENT_STALL_MS ? Number(process.env.NOTIFY_AGENT_STALL_MS) : undefined,
65
- archiveIdleMs: process.env.NOTIFY_AGENT_ARCHIVE_IDLE_MS ? Number(process.env.NOTIFY_AGENT_ARCHIVE_IDLE_MS) : undefined,
66
- };
67
- }
68
43
  export class AgentGateway {
69
44
  driver;
70
45
  static self;
71
46
  static instance() {
72
- return (AgentGateway.self ??= new AgentGateway(new SessionDriver(driverOptions())));
47
+ return (AgentGateway.self ??= new AgentGateway(conversationOwner.driver));
73
48
  }
74
49
  /** The messages waiting on their answer, by conversation and user event. */
75
50
  turns = new Map();
package/dist/daemon.js CHANGED
@@ -14,7 +14,7 @@ import { join } from "path";
14
14
  import { fileURLToPath } from "url";
15
15
  import { DAEMON_BEAT_PATH, CONFIG_DIR, DAEMON_TAG, PACKAGE_VERSION, startNotifyServer, takePendingInbox, yieldGateway } from "./notify.js";
16
16
  import { startNotifyDoor } from "./gateway/notifyDoor.js";
17
- import { writeRecordFile } from "./gateway/conversations.js";
17
+ import { writeRecordFile } from "./gateway/conversationOwner.js";
18
18
  import { announceTakeover, inThisBoot } from "./shared/webhost/originHandover.js";
19
19
  import { TunnelRunner } from "./gateway/tunnel.js";
20
20
  const HEARTBEAT_MS = 10_000;
@@ -0,0 +1,125 @@
1
+ import { existsSync } from "fs";
2
+ import { fileURLToPath } from "url";
3
+ import { CONFIG_DIR, masterMuted } from "../notify.js";
4
+ let personId;
5
+ void import("./passkeyDoor.js").then((door) => { personId = door.personId; });
6
+ import { createConversationOwner } from "../shared/conversation/conversationOwner.js";
7
+ function driverOptions() {
8
+ const bundledGuard = new URL("../scripts/shared/", import.meta.url);
9
+ const guardDir = fileURLToPath(existsSync(bundledGuard) ? bundledGuard : new URL("../../scripts/shared/", import.meta.url));
10
+ // GATE: a stand-in CLI, a warm spare a test asks for, a smaller capacity and shorter idle, silent, stall and archive spells are read ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1; without it the CLI is `claude`, the spare is kept, and the numbers are Meni's ten slots, his 8-hour idle spell, his 2- and 15-minute turn bounds and his 8-hour archive bound.
11
+ if (process.env.NOTIFY_MCP_TEST_ENDPOINTS !== "1")
12
+ return { guardDir };
13
+ const script = process.env.NOTIFY_AGENT_CLI_SCRIPT;
14
+ const copilot = process.env.NOTIFY_AGENT_COPILOT_SCRIPT;
15
+ const codex = process.env.NOTIFY_AGENT_CODEX_SCRIPT;
16
+ const opencode = process.env.NOTIFY_AGENT_OPENCODE_SCRIPT;
17
+ return {
18
+ guardDir,
19
+ spare: process.env.NOTIFY_AGENT_SPARE === "1" ? true : undefined,
20
+ clis: {
21
+ ...(script ? { claude: { cmd: process.execPath, args: [script] } } : {}),
22
+ ...(copilot ? { copilot: { cmd: process.execPath, args: [copilot] } } : {}),
23
+ ...(codex ? { codex: { cmd: process.execPath, args: [codex] } } : {}),
24
+ ...(opencode ? { opencode: { cmd: process.execPath, args: [opencode] } } : {}),
25
+ },
26
+ capacity: process.env.NOTIFY_AGENT_CAPACITY ? Number(process.env.NOTIFY_AGENT_CAPACITY) : undefined,
27
+ idleMs: process.env.NOTIFY_AGENT_IDLE_MS ? Number(process.env.NOTIFY_AGENT_IDLE_MS) : undefined,
28
+ silentMs: process.env.NOTIFY_AGENT_SILENT_MS ? Number(process.env.NOTIFY_AGENT_SILENT_MS) : undefined,
29
+ stallMs: process.env.NOTIFY_AGENT_STALL_MS ? Number(process.env.NOTIFY_AGENT_STALL_MS) : undefined,
30
+ archiveIdleMs: process.env.NOTIFY_AGENT_ARCHIVE_IDLE_MS ? Number(process.env.NOTIFY_AGENT_ARCHIVE_IDLE_MS) : undefined,
31
+ };
32
+ }
33
+ export const conversationOwner = createConversationOwner({
34
+ get configDir() { return CONFIG_DIR; },
35
+ personId: () => personId(),
36
+ masterMuted: () => masterMuted(),
37
+ driver: driverOptions(),
38
+ });
39
+ export const { agentDir, storeChanged, SCOPE_HEADER } = conversationOwner.store;
40
+ export function titleOf(...args) { return conversationOwner.store.titleOf(...args); }
41
+ export function lifecycleOf(...args) { return conversationOwner.store.lifecycleOf(...args); }
42
+ export function describeConversation(...args) { return conversationOwner.store.describeConversation(...args); }
43
+ export function monotonicMs(...args) { return conversationOwner.store.monotonicMs(...args); }
44
+ export function conversationEnabled(...args) { return conversationOwner.store.conversationEnabled(...args); }
45
+ export function setConversationEnabled(...args) { return conversationOwner.store.setConversationEnabled(...args); }
46
+ export function conversationRefusal(...args) { return conversationOwner.store.conversationRefusal(...args); }
47
+ export function requireConversationEnabled(...args) { return conversationOwner.store.requireConversationEnabled(...args); }
48
+ export function writeRecordFile(...args) { return conversationOwner.store.writeRecordFile(...args); }
49
+ export function readConversation(...args) { return conversationOwner.store.readConversation(...args); }
50
+ export function pidAlive(...args) { return conversationOwner.store.pidAlive(...args); }
51
+ export function listConversations(...args) { return conversationOwner.store.listConversations(...args); }
52
+ export function shelvedConversations(...args) { return conversationOwner.store.shelvedConversations(...args); }
53
+ export function inScope(...args) { return conversationOwner.store.inScope(...args); }
54
+ export function creatorOf(...args) { return conversationOwner.store.creatorOf(...args); }
55
+ export function requireInScope(...args) { return conversationOwner.store.requireInScope(...args); }
56
+ export function scopedConversation(...args) { return conversationOwner.store.scopedConversation(...args); }
57
+ export function openConversationOf(...args) { return conversationOwner.store.openConversationOf(...args); }
58
+ export function turnInFlight(...args) { return conversationOwner.store.turnInFlight(...args); }
59
+ export function refersToRunningWork(...args) { return conversationOwner.store.refersToRunningWork(...args); }
60
+ export function routeAsk(...args) { return conversationOwner.store.routeAsk(...args); }
61
+ export function openConversationsOf(...args) { return conversationOwner.store.openConversationsOf(...args); }
62
+ export function stopTargetOf(...args) { return conversationOwner.store.stopTargetOf(...args); }
63
+ export function clockOf(...args) { return conversationOwner.store.clockOf(...args); }
64
+ export function updateConversation(...args) { return conversationOwner.store.updateConversation(...args); }
65
+ export function editOwed(...args) { return conversationOwner.store.editOwed(...args); }
66
+ export function eventsSize(...args) { return conversationOwner.store.eventsSize(...args); }
67
+ export function readEvents(...args) { return conversationOwner.store.readEvents(...args); }
68
+ export async function waitForEvents(...args) { return conversationOwner.store.waitForEvents(...args); }
69
+ export function lastEventNumber(...args) { return conversationOwner.store.lastEventNumber(...args); }
70
+ export function stampWaitReturn(...args) { return conversationOwner.store.stampWaitReturn(...args); }
71
+ export function appendEvent(...args) { return conversationOwner.store.appendEvent(...args); }
72
+ export function hasBoard(...args) { return conversationOwner.store.hasBoard(...args); }
73
+ export function allowedProjects(...args) { return conversationOwner.store.allowedProjects(...args); }
74
+ export function workspaceRoot(...args) { return conversationOwner.store.workspaceRoot(...args); }
75
+ export function rootFolder(...args) { return conversationOwner.store.rootFolder(...args); }
76
+ export function isRootFolder(...args) { return conversationOwner.store.isRootFolder(...args); }
77
+ export function listedFolders(...args) { return conversationOwner.store.listedFolders(...args); }
78
+ export function isAllowedFolder(...args) { return conversationOwner.store.isAllowedFolder(...args); }
79
+ export function allowedFolder(...args) { return conversationOwner.store.allowedFolder(...args); }
80
+ export function workspaceOf(...args) { return conversationOwner.store.workspaceOf(...args); }
81
+ export function conversationInScope(...args) { return conversationOwner.store.conversationInScope(...args); }
82
+ export function namedWorkspace(...args) { return conversationOwner.store.namedWorkspace(...args); }
83
+ export function viewerOfHeaders(...args) { return conversationOwner.store.viewerOfHeaders(...args); }
84
+ export function resolveProject(...args) { return conversationOwner.store.resolveProject(...args); }
85
+ export function namedProject(...args) { return conversationOwner.store.namedProject(...args); }
86
+ export function createdFolder(...args) { return conversationOwner.store.createdFolder(...args); }
87
+ export function namedProvider(...args) { return conversationOwner.store.namedProvider(...args); }
88
+ export function creationPending(...args) { return conversationOwner.store.creationPending(...args); }
89
+ export function creationsPending(...args) { return conversationOwner.store.creationsPending(...args); }
90
+ export function createdIn(folder, provider, chatOf, make) { return conversationOwner.store.createdIn(folder, provider, chatOf, make); }
91
+ export function createdOn(project, provider, chatOf, make) { return conversationOwner.store.createdOn(project, provider, chatOf, make); }
92
+ export function requireOwnCli(...args) { return conversationOwner.store.requireOwnCli(...args); }
93
+ export function listProjects(...args) { return conversationOwner.store.listProjects(...args); }
94
+ export function startConversation(...args) { return conversationOwner.store.startConversation(...args); }
95
+ export function openConversation(...args) { return conversationOwner.store.openConversation(...args); }
96
+ export function setConversationProject(...args) { return conversationOwner.store.setConversationProject(...args); }
97
+ export function sendToConversation(...args) { return conversationOwner.store.sendToConversation(...args); }
98
+ export function queueNoticeOf(...args) { return conversationOwner.store.queueNoticeOf(...args); }
99
+ export function reopenConversation(...args) { return conversationOwner.store.reopenConversation(...args); }
100
+ export function resumeConversation(...args) { return conversationOwner.store.resumeConversation(...args); }
101
+ export async function waitForTurn(...args) { return conversationOwner.store.waitForTurn(...args); }
102
+ export function stopConversation(...args) { return conversationOwner.store.stopConversation(...args); }
103
+ export function archiveConversation(...args) { return conversationOwner.store.archiveConversation(...args); }
104
+ export function unarchiveConversation(...args) { return conversationOwner.store.unarchiveConversation(...args); }
105
+ export function deleteConversation(...args) { return conversationOwner.store.deleteConversation(...args); }
106
+ export function shelfInLog(...args) { return conversationOwner.store.shelfInLog(...args); }
107
+ export function purgeConversation(...args) { return conversationOwner.store.purgeConversation(...args); }
108
+ export function stoppedInLog(...args) { return conversationOwner.store.stoppedInLog(...args); }
109
+ export function resumedInLog(...args) { return conversationOwner.store.resumedInLog(...args); }
110
+ export { GatewayError, MAX_WAIT_SECONDS, CONVERSATION_SWITCH_FILE, CONVERSATION_OFF_MESSAGE, CONVERSATION_MUTED_MESSAGE } from "../shared/conversation/conversations.js";
111
+ export const SessionDriver = conversationOwner.Driver;
112
+ export { IDLE_MS, SILENT_MS, STALL_MS, ARCHIVE_IDLE_MS, SPARE_IDLE_MS } from "../shared/conversation/sessionDriver.js";
113
+ export const { terminalHolder, NativeTerminal, terminalArriving, nativeTerminals, openDrivenTerminal, closeNativeTerminal, nativeTerminal, consoleSession, removeEndedDaemonsSpools } = conversationOwner.terminals;
114
+ export const PROVIDER_CHOICES = conversationOwner.registry.choices;
115
+ export const PROVIDER_NAMES = conversationOwner.registry.names;
116
+ export const providerFor = (name) => conversationOwner.registry.get(name);
117
+ export const providerAvailability = (project, model, clis = {}) => conversationOwner.registry.availability(project, model, clis);
118
+ export const { claudeProvider } = conversationOwner.registry.drivers.claude;
119
+ export const { codexProvider, codexLog } = conversationOwner.registry.drivers.codex;
120
+ export const { copilotProvider, copilotStartupDiagnostic } = conversationOwner.registry.drivers.copilot;
121
+ export const { opencodeProvider, OpenCodeLog, clearOpenCodeLogs } = conversationOwner.registry.drivers.opencode;
122
+ export { AgentTurnFailed, agentEnv, nativeAgentEnv, nativeCliRefusal } from "../shared/conversation/provider.js";
123
+ export { CliSession, CliEnded, LoggedCliSession, folderKey, plain, sameText, endsWithTyped, tailOf, logRow } from "../shared/conversation/cliSession.js";
124
+ export { nativeCliInvocation } from "../shared/conversation/nativeCliInvocation.js";
125
+ export { archiveCodexThread } from "../shared/conversation/codexArchive.js";
@@ -21,13 +21,13 @@ import { performance } from "perf_hooks";
21
21
  import { z } from "zod";
22
22
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
23
23
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24
- import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, createdOn, creationPending, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversations.js";
24
+ import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, createdOn, creationPending, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversationOwner.js";
25
25
  import { workspacesFile } from "../shared/webhost/workspaceList.js";
26
- import { PROVIDER_NAMES } from "./providers.js";
26
+ import { PROVIDER_NAMES } from "./conversationOwner.js";
27
27
  import { iconsFor } from "./iconDoor.js";
28
28
  import { grantClient, publicBase } from "./oauthDoor.js";
29
29
  import { bearer, fromThisMachine, personId, sessionSignIn, tokenProves } from "./passkeyDoor.js";
30
- import { closeNativeTerminal, consoleSession, nativeTerminal, terminalArriving } from "./nativeTerminal.js";
30
+ import { closeNativeTerminal, consoleSession, nativeTerminal, terminalArriving } from "./conversationOwner.js";
31
31
  import { dimensions, openTerminal, terminalListing, validFiles } from "./terminalDoor.js";
32
32
  import { conversationSwitchRead, panelState, saveConversationSwitch, saveSetting } from "./panel.js";
33
33
  import { wizard } from "./publicAccess.js";
@@ -21,7 +21,7 @@ import { BlockList, isIP } from "net";
21
21
  import { join } from "path";
22
22
  import { z } from "zod";
23
23
  import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
24
- import { agentDir, GatewayError, readConversation, readEvents, requireConversationEnabled, writeRecordFile } from "./conversations.js";
24
+ import { agentDir, GatewayError, readConversation, readEvents, requireConversationEnabled, writeRecordFile } from "./conversationOwner.js";
25
25
  /** What the door adds to the capabilities its initialize answers: `events`, a key the SDK's capability type does not name. */
26
26
  export const EVENTS_CAPABILITY = { events: {} };
27
27
  const TURN_COMPLETED = "agent.turn_completed";
@@ -2,7 +2,7 @@ import { createHash, createHmac, timingSafeEqual } from "crypto";
2
2
  import { existsSync, readFileSync, renameSync, writeFileSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { CONFIG_DIR } from "../notify.js";
5
- import { GatewayError } from "./conversations.js";
5
+ import { GatewayError } from "./conversationOwner.js";
6
6
  import { ICON_HEAD, logoUri } from "./iconDoor.js";
7
7
  import { HOST_RE, LOOPBACK_HOSTS, PASSKEY_SCRIPT, approvalStands, digest, doorState, escapeHtml, mint, fromThisMachine, sessionApproval, tokenProves, tokenStands } from "./passkeyDoor.js";
8
8
  export const MCP_PATH = "/mcp";
@@ -7,7 +7,7 @@
7
7
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
8
8
  import { dirname, join } from "path";
9
9
  import { CONFIG_DIR, deliveryReport, isDndActive } from "../notify.js";
10
- import { GatewayError, conversationEnabled, setConversationEnabled } from "./conversations.js";
10
+ import { GatewayError, conversationEnabled, setConversationEnabled } from "./conversationOwner.js";
11
11
  const CHANNEL_KEYS = ["desktop", "telegram", "slack", "sms", "ntfy", "discord", "teams"];
12
12
  const CONFIG_PATH = join(CONFIG_DIR, "config.json");
13
13
  // Every config field the notify server reads, one editable row each. A field the server no longer reads is not listed: a control for it would change nothing.
@@ -7,7 +7,7 @@ import { join } from "path";
7
7
  import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
8
8
  import QRCode from "qrcode";
9
9
  import { CONFIG_DIR, readGatewaySettings, smsReachesOwner, textOwner } from "../notify.js";
10
- import { GatewayError } from "./conversations.js";
10
+ import { GatewayError } from "./conversationOwner.js";
11
11
  import { ICON_HEAD } from "./iconDoor.js";
12
12
  const PASSKEY_PREFIX = "/passkey/";
13
13
  const ENROL_PATH = "/passkey/enrol";
@@ -14,7 +14,7 @@ import { execFile } from "child_process";
14
14
  import { promisify } from "util";
15
15
  import { CONFIG_DIR } from "../notify.js";
16
16
  import { GATEWAY_STATE_FILE, TUNNEL_BINARY } from "./tunnel.js";
17
- import { GatewayError } from "./conversations.js";
17
+ import { GatewayError } from "./conversationOwner.js";
18
18
  import { readConfig, writeConfigValue } from "./panel.js";
19
19
  const run = promisify(execFile);
20
20
  const RELEASE_API = "https://api.github.com/repos/cloudflare/cloudflared/releases/latest";
@@ -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, namedProject, workspaceOf, readEvents, turnInFlight, } from "./conversations.js";
12
+ import { GatewayError, archiveConversation, conversationOwner, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, namedProject, workspaceOf, readEvents, turnInFlight, } from "./conversationOwner.js";
13
13
  import { CHAT_HEADERS } from "./chatPage.js";
14
14
  import { isIconPath, serveIcon } from "./iconDoor.js";
15
15
  import { handleMcp } from "./mcpDoor.js";
@@ -21,7 +21,6 @@ import { PANEL_PAGES, panelHtml } from "./panelPage.js";
21
21
  import { wizard } from "./publicAccess.js";
22
22
  import { terminalHtml } from "./terminalPage.js";
23
23
  import { AgentGateway } from "../agentGateway.js";
24
- import { consoleSession } from "./nativeTerminal.js";
25
24
  import { ServiceHost } from "../shared/webhost/bullseyeWebHost.js";
26
25
  import { sameRoot, workspacesHere } from "../shared/webhost/workspaceList.js";
27
26
  export const BAD_TOKEN_ERROR = "missing or wrong token";
@@ -170,18 +169,7 @@ async function route(req, url, arrivedAt) {
170
169
  if (method === "DELETE") {
171
170
  const expected = url.searchParams.get("expectedConsumed");
172
171
  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();
172
+ const stopped = await conversationOwner.stopIfCurrent(id, { expectedConsumed: Number(expected), expectedInputVersion: url.searchParams.get("expectedInputVersion") });
185
173
  return { status: 200, body: stopped };
186
174
  }
187
175
  return { status: 200, body: stopConversation(id) };
@@ -1,19 +1,9 @@
1
- import { WebSocketServer, WebSocket } from "ws";
2
- import { GatewayError, createdOn, creatorOf, deleteConversation, openConversation, requireOwnCli, requireConversationEnabled, scopedConversation, conversationInScope, viewerOfHeaders } from "./conversations.js";
3
- import { closeNativeTerminal, consoleSession, nativeTerminal, nativeTerminals, terminalArriving } from "./nativeTerminal.js";
1
+ import { WebSocketServer } from "ws";
2
+ import { attachTerminalSocket, dimensions, streamTerminal } from "../shared/conversation/terminalTransport.js";
3
+ export { dimensions, validFiles } from "../shared/conversation/terminalTransport.js";
4
+ import { GatewayError, closeNativeTerminal, consoleSession, conversationInScope, createdOn, creatorOf, deleteConversation, nativeTerminal, nativeTerminals, openConversation, PROVIDER_NAMES, providerFor, requireOwnCli, requireConversationEnabled, scopedConversation, terminalArriving, viewerOfHeaders } from "./conversationOwner.js";
4
5
  import { AgentGateway } from "../agentGateway.js";
5
6
  import { bearer, bearerAdmitted, fromThisMachine, personId, sessionExpiresAt } from "./passkeyDoor.js";
6
- import { PROVIDER_NAMES, providerFor } from "./providers.js";
7
- export function dimensions(body) {
8
- const cols = Number(body.cols), rows = Number(body.rows);
9
- if (!Number.isInteger(cols) || cols <= 0 || cols > 1000 || !Number.isInteger(rows) || rows <= 0 || rows > 500)
10
- throw new GatewayError(400, "Terminal size must be whole columns 1-1000 and rows 1-500.");
11
- return { cols, rows };
12
- }
13
- /** Whether a transfer names files by name and base64 contents, the one check the socket and the agent_terminal_files tool share. */
14
- export function validFiles(files) {
15
- return Array.isArray(files) && files.length > 0 && !files.some((file) => !file || typeof file.name !== "string" || typeof file.data !== "string" || (file.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(file.data)));
16
- }
17
7
  export function terminalSockets(server, token) {
18
8
  const sockets = new WebSocketServer({ noServer: true, handleProtocols: () => "bn-terminal" });
19
9
  server.on("upgrade", (req, socket, head) => {
@@ -41,76 +31,11 @@ export function terminalSockets(server, token) {
41
31
  const given = bearer(req);
42
32
  const terminal = nativeTerminal(personId(), match[1]);
43
33
  sockets.handleUpgrade(req, socket, head, (ws) => {
44
- const detach = terminal.attach();
45
- const disconnected = new AbortController();
46
- const expires = sessionExpiresAt(given);
47
- const expiry = expires === undefined ? undefined : setTimeout(() => ws.close(1008, "Sign in again"), Math.max(0, expires - Date.now()));
48
- ws.on("close", () => { clearTimeout(expiry); disconnected.abort(); detach(); });
49
- ws.on("error", () => ws.terminate());
50
- const failed = (error) => {
51
- // OWNER: the socket operation cannot continue; the connected browser receives the reason and reattaches explicitly.
52
- if (ws.readyState === WebSocket.OPEN)
53
- ws.send(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
54
- ws.close(1008, "Terminal disconnected");
55
- };
56
- let input = Promise.resolve();
57
- ws.on("message", (data, binary) => {
58
- input = input.then(async () => {
59
- if (!bearerAdmitted(req, token)) {
60
- ws.close(1008, "Sign in again");
61
- return;
62
- }
63
- requireConversationEnabled();
64
- if (binary) {
65
- const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
66
- await terminal.input(bytes.toString("base64"), true);
67
- return;
68
- }
69
- const body = JSON.parse(data.toString());
70
- if (body.kind === "resize") {
71
- const size = dimensions(body);
72
- await terminal.resize(size.cols, size.rows);
73
- }
74
- else if (body.kind === "input" && typeof body.data === "string")
75
- await terminal.input(body.data, body.binary === true);
76
- else if (body.kind === "files") {
77
- if (!validFiles(body.files)) {
78
- ws.send(JSON.stringify({ files: true, error: "File transfer failed: expected file names and base64 contents." }));
79
- return;
80
- }
81
- try {
82
- const paths = await terminal.inputFiles(body.files);
83
- if (ws.readyState === WebSocket.OPEN)
84
- ws.send(JSON.stringify({ files: true, paths }));
85
- }
86
- catch (error) {
87
- // OWNER: disk or CLI refusal belongs on this terminal's notice; the worker rolls back undelivered files.
88
- if (ws.readyState === WebSocket.OPEN)
89
- ws.send(JSON.stringify({ files: true, error: "File transfer failed: " + (error instanceof Error ? error.message : String(error)) }));
90
- }
91
- }
92
- else
93
- ws.close(1008, "Expected input, files or resize");
94
- }).catch(failed);
34
+ attachTerminalSocket(ws, terminal, {
35
+ admitted: () => bearerAdmitted(req, token),
36
+ requireEnabled: () => requireConversationEnabled(),
37
+ get expiresAt() { return sessionExpiresAt(given); },
95
38
  });
96
- void (async () => {
97
- let after;
98
- while (!disconnected.signal.aborted && ws.readyState === WebSocket.OPEN) {
99
- const frame = await terminal.read(after, disconnected.signal);
100
- if (!bearerAdmitted(req, token)) {
101
- ws.close(1008, "Sign in again");
102
- return;
103
- }
104
- if (disconnected.signal.aborted || ws.readyState !== WebSocket.OPEN)
105
- return;
106
- await new Promise((resolve, reject) => ws.send(JSON.stringify(frame), (error) => error ? reject(error) : resolve()));
107
- after = frame.n;
108
- if (frame.ended) {
109
- ws.close(1000, "CLI ended");
110
- return;
111
- }
112
- }
113
- })().catch(failed);
114
39
  });
115
40
  }
116
41
  catch (error) {
@@ -153,25 +78,15 @@ export async function terminalConsole(req, res, url) {
153
78
  res.end();
154
79
  return;
155
80
  }
156
- const detach = terminal.attach();
157
- try {
158
- let cursor = after;
159
- for (;;) {
160
- const frame = await terminal.read(cursor, disconnected.signal);
161
- if (disconnected.signal.aborted || res.writableEnded)
162
- return;
163
- if (frame.data !== "" || frame.reset)
164
- res.write(`data: ${JSON.stringify({ seq: frame.n, ts: new Date().toISOString(), kind: "output", text: frame.data, reset: frame.reset })}\n\n`);
165
- cursor = frame.n;
166
- if (frame.ended) {
167
- res.end();
168
- return;
169
- }
170
- }
171
- }
172
- finally {
173
- detach();
174
- }
81
+ const ended = await streamTerminal(terminal, after, disconnected.signal, (frame) => {
82
+ if (res.writableEnded)
83
+ return "closed";
84
+ if (frame.data !== "" || frame.reset)
85
+ res.write(`data: ${JSON.stringify({ seq: frame.n, ts: new Date().toISOString(), kind: "output", text: frame.data, reset: frame.reset })}\n\n`);
86
+ return "open";
87
+ });
88
+ if (ended === "ended")
89
+ res.end();
175
90
  }
176
91
  /**
177
92
  * The CLIs New Agent can open, as the page offers them: every provider whose conversations run in their OWN interactive
@@ -3,7 +3,7 @@ import { createRequire } from "module";
3
3
  import { fileURLToPath } from "url";
4
4
  import { CONVERSATIONS_VIEWS, PAGE_STYLE, SIGN_IN_SCRIPT, servingLine, storedStamp } from "./chatPage.js";
5
5
  import { PASSKEY_SCRIPT } from "./passkeyDoor.js";
6
- import { PROVIDER_CHOICES } from "./providers.js";
6
+ import { PROVIDER_CHOICES } from "./conversationOwner.js";
7
7
  import { notificationStatusScript } from "./panelPage.js";
8
8
  import { ICON_HEAD } from "./iconDoor.js";
9
9
  const require = createRequire(import.meta.url);