omni-notify-mcp 1.3.366 → 1.3.367
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.
- package/dist/agentGateway.js +296 -0
- package/dist/daemon.js +131 -0
- package/dist/gateway/chatPage.js +727 -0
- package/dist/gateway/conversations.js +792 -0
- package/dist/gateway/lanProbe.js +86 -0
- package/dist/gateway/mcpDoor.js +390 -0
- package/dist/gateway/mcpEvents.js +448 -0
- package/dist/gateway/nativeTerminalWorker.js +170 -0
- package/dist/gateway/notifyDoor.js +165 -0
- package/dist/gateway/oauthDoor.js +345 -0
- package/dist/gateway/opencodeEvents.mjs +13 -0
- package/dist/gateway/opencodeProvider.js +249 -0
- package/dist/gateway/panel.js +189 -0
- package/dist/gateway/panelPage.js +214 -0
- package/dist/gateway/providers.js +16 -0
- package/dist/gateway/publicAccess.js +374 -0
- package/dist/gateway/restDoor.js +283 -0
- package/dist/gateway/sessionDriver.js +1014 -0
- package/dist/gateway/terminalDoor.js +247 -0
- package/dist/gateway/terminalPage.js +306 -0
- package/dist/gateway/tunnel.js +166 -0
- package/dist/messaging/emailInbound.js +292 -0
- package/dist/notify.js +2846 -0
- package/dist/shared/webhost/autoSwitch.cjs +1762 -0
- package/dist/shared/webhost/bullseyeWebHost.js +1329 -0
- package/dist/shared/webhost/originHandover.js +552 -0
- package/dist/shared/webhost/package.json +1 -0
- package/dist/shared/webhost/webviewShim.js +342 -0
- package/dist/shared/webhost/workspaceList.js +633 -0
- package/package.json +1 -1
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversations store — the ONE place every Agent Gateway conversation lives, whatever door it came in by.
|
|
3
|
+
* One conversation is a record `<config dir>/agent/<id>.json` plus an append-only event log `<id>.events.jsonl`
|
|
4
|
+
* beside it, so a conversation lives on disk and never in a connection: a BN restart between a send and its read
|
|
5
|
+
* loses nothing, and the next message resumes the session the record names.
|
|
6
|
+
*
|
|
7
|
+
* Writers: a door (REST, a chat, MCP) creates a record, appends the user's words and closes it; the session driver
|
|
8
|
+
* (`sessionDriver.ts`) is the only other writer and owns everything about the session, and honours a Stop, Archive,
|
|
9
|
+
* Unarchive or Delete asked of it. Only the driver removes a deleted conversation's files, once its process is reaped.
|
|
10
|
+
*/
|
|
11
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
|
|
12
|
+
import { randomUUID } from "crypto";
|
|
13
|
+
import { performance } from "perf_hooks";
|
|
14
|
+
import { EventEmitter } from "events";
|
|
15
|
+
import { basename, dirname, join, resolve } from "path";
|
|
16
|
+
import { CONFIG_DIR, masterMuted } from "../notify.js";
|
|
17
|
+
import { PROVIDER_NAMES, providerFor } from "./providers.js";
|
|
18
|
+
import { workspacesFile, workspacesHere } from "../shared/webhost/workspaceList.js";
|
|
19
|
+
/** The title the agent's session carries in Claude's session list: the project and the first request, so one session is told from another at a glance. A conversation opened with no message yet is named by its project alone. */
|
|
20
|
+
export function titleOf(meta, events) {
|
|
21
|
+
// A conversation opened with no message, and one whose project was picked before its first message, hold no user line yet.
|
|
22
|
+
const asked = events.find((e) => e.role === "user");
|
|
23
|
+
// NULL-OK: field asked is OPTIONAL and therefore it is ok to check for NULL
|
|
24
|
+
const ask = (asked?.text ?? "").replace(/\s+/g, " ").trim();
|
|
25
|
+
const where = meta.project === undefined ? "no project" : basename(meta.project);
|
|
26
|
+
return ask.length === 0 ? `BN · ${where}` : `BN · ${where} · ${ask.length > 60 ? `${ask.slice(0, 59)}…` : ask}`;
|
|
27
|
+
}
|
|
28
|
+
export function lifecycleOf(meta, events) {
|
|
29
|
+
if (meta.state === "closed" || shelfInLog(events) !== undefined)
|
|
30
|
+
return "completed";
|
|
31
|
+
return turnInFlight(events, meta) === undefined ? "idle" : "active";
|
|
32
|
+
}
|
|
33
|
+
export function describeConversation(meta) {
|
|
34
|
+
const events = readEvents(meta.id);
|
|
35
|
+
return { ...meta, title: titleOf(meta, events), lifecycle: lifecycleOf(meta, events) };
|
|
36
|
+
}
|
|
37
|
+
export function monotonicMs() {
|
|
38
|
+
return Math.round(performance.now());
|
|
39
|
+
}
|
|
40
|
+
/** Thrown for a request the caller got wrong; the door turns it into the status code. */
|
|
41
|
+
export class GatewayError extends Error {
|
|
42
|
+
status;
|
|
43
|
+
facts;
|
|
44
|
+
/** `facts` ride beside the words in the refusal's body, so a caller acts on what was refused without parsing the message. */
|
|
45
|
+
constructor(status, message, facts = {}) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.status = status;
|
|
48
|
+
this.facts = facts;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** The service's own store for the agent-conversation On/Off switch, beside config.json in the config dir: BN's page flips it, this process reads it, and BullseyeSync carries it to every machine. */
|
|
52
|
+
export const CONVERSATION_SWITCH_FILE = "conversation-switch.json";
|
|
53
|
+
/** `NOTIFY_CONVERSATION_SWITCH_FILE` names the store somewhere else, the way `NOTIFY_MCP_CONFIG_DIR` moves the whole config dir. */
|
|
54
|
+
const switchPath = () => process.env.NOTIFY_CONVERSATION_SWITCH_FILE ?? join(CONFIG_DIR, CONVERSATION_SWITCH_FILE);
|
|
55
|
+
/** Whether the switch is On. A machine that has never been switched has no file and the switch is Off; a file that is not an On/Off value throws, so a broken store is never read as Off. */
|
|
56
|
+
export function conversationEnabled() {
|
|
57
|
+
if (!existsSync(switchPath()))
|
|
58
|
+
return false;
|
|
59
|
+
const stored = JSON.parse(readFileSync(switchPath(), "utf8"));
|
|
60
|
+
if (typeof stored.enabled !== "boolean")
|
|
61
|
+
throw new TypeError(`${switchPath()} carries no on/off value`);
|
|
62
|
+
return stored.enabled;
|
|
63
|
+
}
|
|
64
|
+
/** Turns the switch On or Off: a staged file renamed over the store, then read back, so the write is done only when the re-read holds it. */
|
|
65
|
+
export function setConversationEnabled(enabled) {
|
|
66
|
+
mkdirSync(dirname(switchPath()), { recursive: true });
|
|
67
|
+
const staged = `${switchPath()}.${process.pid}.tmp`;
|
|
68
|
+
writeFileSync(staged, JSON.stringify({ enabled }));
|
|
69
|
+
renameSync(staged, switchPath());
|
|
70
|
+
if (conversationEnabled() !== enabled)
|
|
71
|
+
throw new Error(`${switchPath()} did not hold — wrote ${enabled}, read back ${!enabled}`);
|
|
72
|
+
}
|
|
73
|
+
export const CONVERSATION_OFF_MESSAGE = "The BN agent conversation is switched off. Turn the On switch beside Agent conversations on BN's Settings page to use it; nothing was started.";
|
|
74
|
+
export const CONVERSATION_MUTED_MESSAGE = "BN is muted: Mute everything is On in the BN Notify tab, so nothing was started and nothing is sent.";
|
|
75
|
+
/** Why no conversation may run right now, or undefined when one may: Mute everything wins over the conversation switch. */
|
|
76
|
+
export function conversationRefusal() {
|
|
77
|
+
return masterMuted() ? CONVERSATION_MUTED_MESSAGE : conversationEnabled() ? undefined : CONVERSATION_OFF_MESSAGE;
|
|
78
|
+
}
|
|
79
|
+
export function requireConversationEnabled() {
|
|
80
|
+
const why = conversationRefusal();
|
|
81
|
+
if (why !== undefined)
|
|
82
|
+
throw new GatewayError(403, why);
|
|
83
|
+
}
|
|
84
|
+
export const agentDir = () => join(CONFIG_DIR, "agent");
|
|
85
|
+
const metaPath = (id) => join(agentDir(), `${id}.json`);
|
|
86
|
+
const eventsPath = (id) => join(agentDir(), `${id}.events.jsonl`);
|
|
87
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
88
|
+
// GATE: the codes Windows refuses a replace with while another handle holds the record open — a door reading it in this or another BN process, a scanner — and a share refusal from an editor or a backup agent: each is tried again, briefly.
|
|
89
|
+
const RENAME_REFUSED = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
90
|
+
// GATE: five tries, waiting 10, 20, 40 and 80 ms — 150 ms at the outside — so a record a lock refuses for a moment still lands, and one it refuses for good fails the write exactly as a single attempt did.
|
|
91
|
+
const RENAME_TRIES = 5;
|
|
92
|
+
const RENAME_FIRST_WAIT_MS = 10;
|
|
93
|
+
/** Sleeps this thread, the only way a synchronous write waits out a lock another process holds. */
|
|
94
|
+
function sleepSync(ms) {
|
|
95
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
96
|
+
}
|
|
97
|
+
/** Removes the staged file a given-up write left, so a refusal leaves no half-record beside the real one; one the OS itself still refuses to release is named and left for this process's next write to replace. */
|
|
98
|
+
function dropStaged(staged) {
|
|
99
|
+
try {
|
|
100
|
+
rmSync(staged, { force: true, maxRetries: 3, retryDelay: 20 });
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
const code = err.code ?? "";
|
|
104
|
+
if (!RENAME_REFUSED.has(code))
|
|
105
|
+
throw err;
|
|
106
|
+
process.stderr.write(`[store] the staged file ${staged} could not be removed (${code}) — this process's next write of it replaces the file\n`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Writes the record by staging it beside itself and renaming it over the old one, so no reader ever sees half a record.
|
|
111
|
+
* Windows refuses that rename with EPERM while any other handle holds the destination open without sharing the delete,
|
|
112
|
+
* and the record has several readers — every door's list and read, a scanner on a file just closed — beside the writers a
|
|
113
|
+
* handover leaves standing: so a refused rename is tried again, five times over 150 ms, before the write is given up and
|
|
114
|
+
* its caller told, and the staged file of a write that is given up is removed.
|
|
115
|
+
*/
|
|
116
|
+
function writeMeta(meta) {
|
|
117
|
+
writeRecordFile(metaPath(meta.id), JSON.stringify(meta, null, 2));
|
|
118
|
+
}
|
|
119
|
+
/** Writes one store file — an agent-dir record, or the daemon's heartbeat in the config dir — the way a record is written: staged beside itself and renamed over the old one, a refused rename tried again. */
|
|
120
|
+
export function writeRecordFile(final, text) {
|
|
121
|
+
const staged = `${final}.${process.pid}.tmp`;
|
|
122
|
+
for (let attempt = 0;; attempt++) {
|
|
123
|
+
try {
|
|
124
|
+
writeFileSync(staged, text);
|
|
125
|
+
renameSync(staged, final);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
if (!RENAME_REFUSED.has(err.code ?? "") || attempt === RENAME_TRIES - 1) {
|
|
130
|
+
dropStaged(staged);
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
sleepSync(RENAME_FIRST_WAIT_MS << attempt);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function readConversation(id) {
|
|
138
|
+
if (!UUID.test(id))
|
|
139
|
+
throw new GatewayError(404, "no such conversation");
|
|
140
|
+
const meta = recordAt(metaPath(id));
|
|
141
|
+
// NULL-OK: field meta is OPTIONAL and therefore it is ok to check for NULL
|
|
142
|
+
if (meta === undefined)
|
|
143
|
+
throw new GatewayError(404, "no such conversation");
|
|
144
|
+
return meta;
|
|
145
|
+
}
|
|
146
|
+
function recordAt(file) {
|
|
147
|
+
const text = textAt(file);
|
|
148
|
+
// NULL-OK: field text is OPTIONAL and therefore it is ok to check for NULL
|
|
149
|
+
return text === undefined ? undefined : JSON.parse(text);
|
|
150
|
+
}
|
|
151
|
+
/** The file's text, or undefined when there is no such file — the driver removes a deleted conversation's files, so a file listed or checked a moment ago can be gone by the time it is read. */
|
|
152
|
+
function textAt(file) {
|
|
153
|
+
try {
|
|
154
|
+
return readFileSync(file, "utf8");
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
if (err.code === "ENOENT")
|
|
158
|
+
return undefined;
|
|
159
|
+
throw err;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Whether a process id still names a live process: EPERM means it exists and this account may not signal it. */
|
|
163
|
+
export function pidAlive(pid) {
|
|
164
|
+
try {
|
|
165
|
+
process.kill(pid, 0);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
const code = error.code;
|
|
170
|
+
if (code === "EPERM")
|
|
171
|
+
return true;
|
|
172
|
+
if (code === "ESRCH")
|
|
173
|
+
return false;
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
let sweptStaged = false;
|
|
178
|
+
/** Removes every <name>.json.<pid>.tmp of the agent store whose writer is no longer a live process: a BN killed between a staged write and its rename leaves one nothing else ever removes. Runs once per BN process, on the store's first listing at boot. */
|
|
179
|
+
function sweepDeadStaged() {
|
|
180
|
+
sweptStaged = true;
|
|
181
|
+
for (const name of readdirSync(agentDir())) {
|
|
182
|
+
const writer = /\.json\.(\d+)\.tmp$/.exec(name)?.[1];
|
|
183
|
+
// NULL-OK: field writer is OPTIONAL and therefore it is ok to check for NULL
|
|
184
|
+
if (writer !== undefined && !pidAlive(Number(writer)))
|
|
185
|
+
dropStaged(join(agentDir(), name));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Every conversation, newest first. */
|
|
189
|
+
export function listConversations() {
|
|
190
|
+
if (!existsSync(agentDir()))
|
|
191
|
+
return [];
|
|
192
|
+
if (!sweptStaged)
|
|
193
|
+
sweepDeadStaged();
|
|
194
|
+
return readdirSync(agentDir())
|
|
195
|
+
.filter((name) => name.endsWith(".json") && UUID.test(name.slice(0, -5)))
|
|
196
|
+
.flatMap((name) => recordAt(join(agentDir(), name)) ?? [])
|
|
197
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
198
|
+
}
|
|
199
|
+
/** The conversations a door shows on one shelf, newest first; a deleted one is on neither. */
|
|
200
|
+
export function shelvedConversations(shelf, viewer) {
|
|
201
|
+
return listConversations().filter((c) => c.shelf !== "deleted" && (c.shelf === "archived") === (shelf === "archived") && inScope(c, viewer));
|
|
202
|
+
}
|
|
203
|
+
/** Whether a conversation is shown to a viewer: one in the viewer's workspace, or one the viewer itself created. */
|
|
204
|
+
export function inScope(meta, viewer) {
|
|
205
|
+
if (viewer === undefined)
|
|
206
|
+
return true;
|
|
207
|
+
// NULL-OK: field project is OPTIONAL and therefore it is ok to check for NULL
|
|
208
|
+
if (meta.project !== undefined && sameFolder(meta.project, viewer.folder))
|
|
209
|
+
return true;
|
|
210
|
+
// NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
|
|
211
|
+
return meta.chat !== undefined && meta.chat === viewer.creator;
|
|
212
|
+
}
|
|
213
|
+
/** A viewer is refused a conversation outside its scope in the words a missing one gets: it never learns another workspace's work exists. */
|
|
214
|
+
export function requireInScope(meta, viewer) {
|
|
215
|
+
if (!inScope(meta, viewer))
|
|
216
|
+
throw new GatewayError(404, "conversation not found in this workspace");
|
|
217
|
+
return meta;
|
|
218
|
+
}
|
|
219
|
+
/** The conversation an id names, proven to be in the viewer's scope: every door that takes an id reads it through here. */
|
|
220
|
+
export function scopedConversation(id, viewer) {
|
|
221
|
+
return requireInScope(readConversation(id), viewer);
|
|
222
|
+
}
|
|
223
|
+
/** The conversation a chat is holding — its newest one not stopped — so the chat's next message goes on with the same agent. */
|
|
224
|
+
export function openConversationOf(chat) {
|
|
225
|
+
return listConversations().find((c) => c.chat === chat && c.state !== "closed");
|
|
226
|
+
}
|
|
227
|
+
/** The turn a conversation is in the middle of, or undefined; a stopped conversation is in no turn, and neither is a start left behind by a stop the log has since resumed. It is the turn whose start line has no answer or failure after it, else the first message the driver has accepted but not yet begun, picked the way the driver picks its next turn, so a message queued before a stop and run after its resume counts — a turn stored and waiting for its process or slot is the turn a later message waits behind. `startedAt` is that turn's start, or when it was stored while it has not started. */
|
|
228
|
+
export function turnInFlight(events, meta) {
|
|
229
|
+
if (stoppedInLog(events))
|
|
230
|
+
return undefined;
|
|
231
|
+
const mark = events.filter((e) => e.kind === "stopped" || e.kind === "resumed").at(-1)?.n ?? 0;
|
|
232
|
+
const start = events.filter((e) => e.kind === "start" && e.turn !== undefined && e.n > mark).at(-1);
|
|
233
|
+
// NULL-OK: field start is OPTIONAL and therefore it is ok to check for NULL
|
|
234
|
+
if (start !== undefined && !events.some((e) => e.turn === start.turn && e.n > start.n && (e.kind === "answer" || e.kind === "failed"))) {
|
|
235
|
+
return { turn: start.turn, startedAt: start.ts, started: true };
|
|
236
|
+
}
|
|
237
|
+
const stored = events.find((e) => e.role === "user" && e.n > meta.consumed && !(meta.answered ?? []).includes(e.n) && !events.some((x) => x.turn === e.n && (x.kind === "answer" || x.kind === "failed")));
|
|
238
|
+
// NULL-OK: field stored is OPTIONAL and therefore it is ok to check for NULL
|
|
239
|
+
return stored === undefined ? undefined : { turn: stored.n, startedAt: stored.ts, started: false };
|
|
240
|
+
}
|
|
241
|
+
/** Words that point back at the work already under way: an ask carrying one is about that work, so it waits behind the running turn instead of starting its own conversation. A bare demonstrative is deliberately absent — "now that the build is done, what is the release version" is no reference to anything running — as is a word that could be about anything ("again", "also", "why", "the last"), because an ask carrying no back-reference runs on its own agent, and waiting silently is the defect this rule exists to end. */
|
|
242
|
+
const REFERS_TO_THE_TURN = new RegExp(String.raw `(?:^|[\s,;:("'])(?:` +
|
|
243
|
+
[
|
|
244
|
+
"the above", "the same",
|
|
245
|
+
"your answer", "your reply", "your result", "your output",
|
|
246
|
+
"what you", "what did you", "what have you", "did you", "have you",
|
|
247
|
+
].join("|") +
|
|
248
|
+
String.raw `)(?=[\s,.;:!?)"']|$)`, "i");
|
|
249
|
+
/** An ask that opens with a bare continuation word — "continue", "please carry on", "ok, keep going", "and then?", "what about the tests?" — points back at the work under way, whatever short word it carries first. A continuation word inside a longer sentence ("how do I resume a paused sync job") is about the sentence's own subject and is left to start its own agent. */
|
|
250
|
+
const CONTINUES_THE_TURN = /^\s*(?:(?:please|ok|okay|now|so|yes)[\s,]+)*(?:and|then|what about|how about|continue|carry on|go on|keep going|resume)\b/i;
|
|
251
|
+
/** A whole short ask that only checks on, or halts, the work under way — "are you done?", "how is the backup going?", "stop" — carries no trigger word and names nothing of its own, so it can only be about that work. */
|
|
252
|
+
const CHECKS_ON_THE_TURN = new RegExp(String.raw `^\s*(?:(?:please|ok|okay|so|hey)[\s,]+)*(?:` +
|
|
253
|
+
[
|
|
254
|
+
"are you (?:done|finished|still|there|ready)",
|
|
255
|
+
"is (?:it|that|this) (?:done|finished|ready|running|stuck)",
|
|
256
|
+
String.raw `how(?:'s| is| are)\s.{1,60}?\sgoing`,
|
|
257
|
+
"how far",
|
|
258
|
+
"any (?:news|progress|updates?|luck)",
|
|
259
|
+
"still (?:working|running)",
|
|
260
|
+
"done yet",
|
|
261
|
+
"stop|cancel|abort|wait|hold on|never ?mind",
|
|
262
|
+
].join("|") +
|
|
263
|
+
String.raw `)[\s?!.]*$`, "i");
|
|
264
|
+
export function refersToRunningWork(text) {
|
|
265
|
+
return REFERS_TO_THE_TURN.test(text) || CONTINUES_THE_TURN.test(text) || CHECKS_ON_THE_TURN.test(text);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* The conversation of `chat` an ask goes to, or undefined when it starts its own. An ask that points at the work under way goes to the OLDEST conversation that is busy (the original line of work;
|
|
269
|
+
* neither an idle nor a busy detour steals it), and an independent one goes to the newest open conversation when that is idle and starts its own when it is busy.
|
|
270
|
+
*/
|
|
271
|
+
export function routeAsk(chat, text) {
|
|
272
|
+
const newest = openConversationOf(chat);
|
|
273
|
+
// NULL-OK: field newest is OPTIONAL and therefore it is ok to check for NULL
|
|
274
|
+
if (newest === undefined)
|
|
275
|
+
return undefined;
|
|
276
|
+
const working = workingOf(chat);
|
|
277
|
+
if (refersToRunningWork(text))
|
|
278
|
+
return working.at(-1) ?? newest;
|
|
279
|
+
return working.some((c) => c.id === newest.id) ? undefined : newest;
|
|
280
|
+
}
|
|
281
|
+
/** Every conversation of the chat not stopped, newest first. */
|
|
282
|
+
export function openConversationsOf(chat) {
|
|
283
|
+
return listConversations().filter((c) => c.chat === chat && c.state !== "closed");
|
|
284
|
+
}
|
|
285
|
+
/** The chat's open conversations in the middle of a turn, newest first. */
|
|
286
|
+
function workingOf(chat) {
|
|
287
|
+
return openConversationsOf(chat).filter((c) => turnInFlight(readEvents(c.id), c) !== undefined);
|
|
288
|
+
}
|
|
289
|
+
/** The conversation a `stop` ends: the oldest at work (the original line of work), else the newest open one. */
|
|
290
|
+
export function stopTargetOf(chat) {
|
|
291
|
+
return workingOf(chat).at(-1) ?? openConversationOf(chat);
|
|
292
|
+
}
|
|
293
|
+
/** HH:MM on this machine's own clock, the form the queue notice and the timing view use. */
|
|
294
|
+
export function clockOf(iso) {
|
|
295
|
+
const at = new Date(iso);
|
|
296
|
+
return `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`;
|
|
297
|
+
}
|
|
298
|
+
/** Writes fields onto the record as it is on disk now. A closed conversation stays closed. */
|
|
299
|
+
export function updateConversation(id, patch) {
|
|
300
|
+
const meta = readConversation(id);
|
|
301
|
+
const next = { ...meta, ...patch, updatedAt: new Date().toISOString() };
|
|
302
|
+
if (meta.state === "closed")
|
|
303
|
+
next.state = "closed";
|
|
304
|
+
writeMeta(next);
|
|
305
|
+
return next;
|
|
306
|
+
}
|
|
307
|
+
/** Edits which turns of a door's conversation are still owed to its thread; a record already purged owes nothing, so there is nothing to write. */
|
|
308
|
+
export function editOwed(id, edit) {
|
|
309
|
+
if (!existsSync(metaPath(id)))
|
|
310
|
+
return;
|
|
311
|
+
const owed = { ...readConversation(id).owed };
|
|
312
|
+
edit(owed);
|
|
313
|
+
updateConversation(id, { owed });
|
|
314
|
+
}
|
|
315
|
+
/** The log's size in bytes, so a reader re-reads it only when it grew. */
|
|
316
|
+
export function eventsSize(id) {
|
|
317
|
+
return existsSync(eventsPath(id)) ? statSync(eventsPath(id)).size : 0;
|
|
318
|
+
}
|
|
319
|
+
function logLines(id) {
|
|
320
|
+
return wholeLines(textAt(eventsPath(id)) ?? "");
|
|
321
|
+
}
|
|
322
|
+
function wholeLines(text) {
|
|
323
|
+
// A writer killed mid-append leaves a fragment with no newline after it: a line counts only once its own newline is in the file, so the fragment is never read as an event.
|
|
324
|
+
return text.slice(0, text.lastIndexOf("\n") + 1).split("\n").filter((line) => line.length > 0);
|
|
325
|
+
}
|
|
326
|
+
/** The log in order; each event's `n` is its position, so two processes appending at once never share a number. */
|
|
327
|
+
export function readEvents(id, after = 0) {
|
|
328
|
+
readConversation(id);
|
|
329
|
+
return logLines(id)
|
|
330
|
+
.map((line, i) => ({ line, n: i + 1 }))
|
|
331
|
+
.flatMap(({ line, n }) => {
|
|
332
|
+
try {
|
|
333
|
+
return [{ ...JSON.parse(line), n }];
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
if (!(err instanceof SyntaxError))
|
|
337
|
+
throw err;
|
|
338
|
+
// OWNER: a line a killed writer left half-written is not an event — it is named and skipped, and the events around it still read.
|
|
339
|
+
process.stderr.write(`[agent-gateway] unreadable line ${n} of ${id}: ${line.slice(0, 120)}\n`);
|
|
340
|
+
return [];
|
|
341
|
+
}
|
|
342
|
+
})
|
|
343
|
+
.filter((event) => event.n > after);
|
|
344
|
+
}
|
|
345
|
+
// GATE: the longest a read may wait for a new event, one second under the 55 s BLOCKING_TOOL_MAX_SECONDS in notify.ts so no call is held past it.
|
|
346
|
+
export const MAX_WAIT_SECONDS = 54;
|
|
347
|
+
/** Fires in this process after every event appended, so a reader waiting on the log and the driver's beat wake at once instead of on their next tick. */
|
|
348
|
+
export const storeChanged = new EventEmitter();
|
|
349
|
+
// GATE: the longest a waiter sleeps between reads when no in-process write woke it — an event another process appended is picked up within this.
|
|
350
|
+
const POLL_MS = 250;
|
|
351
|
+
/** Resolves on the next in-process append or after `ms`, whichever is first. */
|
|
352
|
+
function sleepUntilChange(ms) {
|
|
353
|
+
return new Promise((resolve) => {
|
|
354
|
+
const done = () => { clearTimeout(timer); storeChanged.off("change", done); resolve(); };
|
|
355
|
+
const timer = setTimeout(done, ms);
|
|
356
|
+
storeChanged.once("change", done);
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
/** Returns the events past `after` as soon as there is one, or the empty list once the wait (capped) runs out. */
|
|
360
|
+
export async function waitForEvents(id, after, waitSeconds) {
|
|
361
|
+
const deadline = Date.now() + Math.min(waitSeconds, MAX_WAIT_SECONDS) * 1000;
|
|
362
|
+
for (;;) {
|
|
363
|
+
const events = readEvents(id, after);
|
|
364
|
+
if (events.length > 0 || Date.now() >= deadline)
|
|
365
|
+
return events;
|
|
366
|
+
await sleepUntilChange(Math.min(POLL_MS, Math.max(0, deadline - Date.now())));
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/** The position of the last event in a conversation's log, 0 when it has none — the watermark a door call takes the moment it arrives. */
|
|
370
|
+
export function lastEventNumber(id) {
|
|
371
|
+
return logLines(id).length;
|
|
372
|
+
}
|
|
373
|
+
/** The one write after a door call (agent_wait, agent_prompt) that handed a turn's end to its caller: a `returned` line carrying the monotonic milliseconds the call held and the position of the end it reports (`returnsN`). `readTo` is the position the caller had already read (`after`, or the message the call itself sent): the last end past it is the one this call delivered, whether it was stored before the call arrived or during it — a call arriving a moment after the answer still delivered it. A read from the start (`readTo` 0) carries no cursor, so `from` — the log's last position when the call arrived — is its floor instead: an end that arrived during the call is stamped, and a catch-up over the history hands back no line. A second reader of the same end writes nothing — the line already there is matched by the position it names, or by its turn for one written before that field existed. The duplicate check and the append are not atomic, so two processes stamping one end in the same moment can leave two lines — a duplicate line and nothing worse. */
|
|
374
|
+
export function stampWaitReturn(id, door, events, waitedMs, readTo, from) {
|
|
375
|
+
const floor = readTo === 0 ? from : readTo;
|
|
376
|
+
const ended = events.filter((e) => e.turn !== undefined && TURN_ENDS.has(e.kind) && e.n > floor).at(-1);
|
|
377
|
+
// NULL-OK: field ended is OPTIONAL and therefore it is ok to check for NULL
|
|
378
|
+
if (ended === undefined)
|
|
379
|
+
return undefined;
|
|
380
|
+
if (readEvents(id, ended.n).some((e) => e.kind === "returned" && (e.returnsN === ended.n || (e.returnsN === undefined && e.turn === ended.turn))))
|
|
381
|
+
return undefined;
|
|
382
|
+
return appendEvent(id, { role: "system", kind: "returned", turn: ended.turn, returnsN: ended.n, waitedMs, text: `${door} returned this turn's ${ended.kind} to its caller after holding the call ${waitedMs} ms` });
|
|
383
|
+
}
|
|
384
|
+
export function appendEvent(id, entry) {
|
|
385
|
+
return appendEvents(id, [entry])[0];
|
|
386
|
+
}
|
|
387
|
+
/** Appends the entries in ONE write, so a writer killed between them never stores one without the other; each event carries the number of the line it landed on. */
|
|
388
|
+
function appendEvents(id, entries) {
|
|
389
|
+
readConversation(id);
|
|
390
|
+
const text = textAt(eventsPath(id)) ?? "";
|
|
391
|
+
const lines = wholeLines(text);
|
|
392
|
+
const endsWhole = text.length === 0 || text.endsWith("\n");
|
|
393
|
+
const first = lines.length + (endsWhole ? 1 : 2);
|
|
394
|
+
const message = entries.find((entry) => entry.role === "user");
|
|
395
|
+
const trace = message === undefined ? undefined : message.trace ?? randomUUID().slice(0, 8);
|
|
396
|
+
const written = entries.map((entry) => ({ role: entry.role, text: entry.text, ts: new Date().toISOString(), kind: entry.kind, turn: entry.turn, uid: randomUUID(), timing: entry.timing, receivedMs: entry.receivedMs, behind: entry.behind, trace: entry.trace ?? trace ?? traceOfTurn(lines, entry.turn), bnTrace: entry.bnTrace, waitedMs: entry.waitedMs, returnsN: entry.returnsN }));
|
|
397
|
+
// A writer killed mid-append leaves a fragment with no newline: it becomes a line of its own (and is skipped on read) instead of hiding these events behind it.
|
|
398
|
+
appendFileSync(eventsPath(id), `${endsWhole ? "" : "\n"}${written.map((event) => JSON.stringify(event)).join("\n")}\n`);
|
|
399
|
+
storeChanged.emit("change");
|
|
400
|
+
return written.map((event, index) => ({ ...event, n: first + index }));
|
|
401
|
+
}
|
|
402
|
+
/** The number the next appended line carries — a fragment a killed writer left without its newline becomes a line of its own first. */
|
|
403
|
+
function nextEventNumber(id) {
|
|
404
|
+
const before = textAt(eventsPath(id)) ?? "";
|
|
405
|
+
return logLines(id).length + (before.length === 0 || before.endsWith("\n") ? 1 : 2);
|
|
406
|
+
}
|
|
407
|
+
function traceOfTurn(lines, turn) {
|
|
408
|
+
// NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
|
|
409
|
+
return turn === undefined ? undefined : JSON.parse(lines[turn - 1]).trace;
|
|
410
|
+
}
|
|
411
|
+
/** A folder is a project with a board when it holds a BACKLOG.md file: the bullseye-backlog MCP refuses to start anywhere else (#2110). */
|
|
412
|
+
export function hasBoard(folder) {
|
|
413
|
+
const board = join(folder, "BACKLOG.md");
|
|
414
|
+
return existsSync(board) && statSync(board).isFile();
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* #3849 — the projects an agent may run in: every folder on this machine's workspace list (the one list Bullseye Control edits), named by its folder.
|
|
418
|
+
* A list that is not defined or cannot be read is refused with its own reason, never answered as no projects.
|
|
419
|
+
* GATE: NOTIFY_AGENT_PROJECTS (comma list), resolved under NOTIFY_AGENT_WORKSPACE, replaces the list ONLY under NOTIFY_MCP_TEST_ENDPOINTS=1, so a test runs in a tree it owns.
|
|
420
|
+
*/
|
|
421
|
+
function projectsHere() {
|
|
422
|
+
const named = process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" ? process.env.NOTIFY_AGENT_PROJECTS : undefined;
|
|
423
|
+
// NULL-OK: field NOTIFY_AGENT_PROJECTS is OPTIONAL and therefore it is ok to check for NULL
|
|
424
|
+
if (named !== undefined) {
|
|
425
|
+
const stand = process.env.NOTIFY_AGENT_WORKSPACE;
|
|
426
|
+
// NULL-OK: field NOTIFY_AGENT_WORKSPACE is OPTIONAL and therefore it is ok to check for NULL
|
|
427
|
+
if (stand === undefined)
|
|
428
|
+
throw new Error("NOTIFY_AGENT_PROJECTS names test projects but NOTIFY_AGENT_WORKSPACE names no folder of the test's own to resolve them under — a test never runs agents in real folders");
|
|
429
|
+
return named.split(",").map((name) => ({ name, folder: join(stand, name) }));
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
return workspacesHere().map((w) => ({ name: basename(w.root), folder: w.root }));
|
|
433
|
+
}
|
|
434
|
+
catch (err) {
|
|
435
|
+
if (!(err instanceof SyntaxError))
|
|
436
|
+
throw err;
|
|
437
|
+
throw new GatewayError(503, `no agent can be started yet: ${err.message}`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/** The names a project is given by: exactly the folder names on the workspace list, in its order. */
|
|
441
|
+
export function allowedProjects() {
|
|
442
|
+
return projectsHere().map((p) => p.name);
|
|
443
|
+
}
|
|
444
|
+
/** The folder(s) the listed projects sit in, as a reader is told where a name resolves. */
|
|
445
|
+
export function workspaceRoot() {
|
|
446
|
+
return [...new Set(projectsHere().map((p) => dirname(p.folder)))].join(", ");
|
|
447
|
+
}
|
|
448
|
+
/** The refusal every door gives for a project outside the allowed ones. */
|
|
449
|
+
function notAllowedProject() {
|
|
450
|
+
return new GatewayError(400, `project must be exactly one of: ${allowedProjects().join(", ")} — no other name, path or case variant is accepted`);
|
|
451
|
+
}
|
|
452
|
+
/** The folder a project names: exactly one of the listed folder names (exact case); any path, other name or case variant is refused. */
|
|
453
|
+
function projectFolder(project) {
|
|
454
|
+
const listed = projectsHere().find((p) => p.name === project);
|
|
455
|
+
// NULL-OK: field listed is OPTIONAL and therefore it is ok to check for NULL
|
|
456
|
+
if (listed === undefined)
|
|
457
|
+
throw notAllowedProject();
|
|
458
|
+
if (!existsSync(listed.folder) || !statSync(listed.folder).isDirectory())
|
|
459
|
+
throw new GatewayError(400, `project ${project} is not a folder on this machine — it is expected at ${listed.folder}`);
|
|
460
|
+
return listed.folder;
|
|
461
|
+
}
|
|
462
|
+
/** Whether a folder is one of the listed projects' folders. */
|
|
463
|
+
export function isAllowedFolder(folder) {
|
|
464
|
+
return projectsHere().some((p) => sameFolder(p.folder, folder));
|
|
465
|
+
}
|
|
466
|
+
/** The folder an agent is about to run in, proven to be one of the allowed projects' folders: a stored or resolved path outside them is refused. */
|
|
467
|
+
export function allowedFolder(folder) {
|
|
468
|
+
if (!isAllowedFolder(folder))
|
|
469
|
+
throw notAllowedProject();
|
|
470
|
+
return folder;
|
|
471
|
+
}
|
|
472
|
+
/** The header a caller names the workspace it is scoped to in (#4120) — the one name BB, FV and BN callers carry. */
|
|
473
|
+
export const SCOPE_HEADER = "x-bullseye-project";
|
|
474
|
+
/** Whether `child` is `parent` or sits inside it. */
|
|
475
|
+
function within(child, parent) {
|
|
476
|
+
const shape = (folder) => folder.replace(/[\\/]+$/, "").replace(/[\\/]/g, "/");
|
|
477
|
+
const [c, p] = process.platform === "win32" ? [shape(child).toLowerCase(), shape(parent).toLowerCase()] : [shape(child), shape(parent)];
|
|
478
|
+
return c === p || c.startsWith(`${p}/`);
|
|
479
|
+
}
|
|
480
|
+
/** The repository a lane worktree was cut from: its `.git` file names `<repo>/.git/worktrees/<name>`. A folder with no such file is no worktree. */
|
|
481
|
+
function worktreeRepo(folder) {
|
|
482
|
+
const marker = join(folder, ".git");
|
|
483
|
+
// NULL-OK: field .git is OPTIONAL and therefore it is ok to check for NULL
|
|
484
|
+
if (!existsSync(marker) || !statSync(marker).isFile())
|
|
485
|
+
return undefined;
|
|
486
|
+
const named = /^gitdir:\s*(.+)$/m.exec(readFileSync(marker, "utf8"));
|
|
487
|
+
// NULL-OK: field gitdir is OPTIONAL and therefore it is ok to check for NULL
|
|
488
|
+
return named === null ? undefined : resolve(folder, named[1].trim(), "..", "..", "..");
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* #4120 — the listed workspace a header's folder belongs to: the folder itself, a folder inside one, or a lane worktree (under .aw-wt or anywhere) cut from a repository inside one.
|
|
492
|
+
* A folder that belongs to no listed workspace is refused without naming any other workspace's path.
|
|
493
|
+
*/
|
|
494
|
+
export function workspaceOf(named) {
|
|
495
|
+
const listed = projectsHere().map((p) => p.folder);
|
|
496
|
+
const repo = worktreeRepo(named);
|
|
497
|
+
const owner = listed.find((folder) => within(named, folder) || (repo !== undefined && within(repo, folder)));
|
|
498
|
+
// NULL-OK: field owner is OPTIONAL and therefore it is ok to check for NULL
|
|
499
|
+
if (owner === undefined)
|
|
500
|
+
throw new GatewayError(400, `the ${SCOPE_HEADER} header names a folder that belongs to no workspace on this machine's list`);
|
|
501
|
+
return owner;
|
|
502
|
+
}
|
|
503
|
+
/** Whether the conversation an id names is in the viewer's scope: a terminal whose id names no conversation is not. */
|
|
504
|
+
export function conversationInScope(id, viewer) {
|
|
505
|
+
return listConversations().some((c) => c.id === id && inScope(c, viewer));
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* The workspace a request names in its header (#4120), refused when it names none and does not come through the public gateway: only a request that crossed the passkey-signed
|
|
509
|
+
* gateway (`local` is false: it carries a proxy's headers, and the door admits it only on a signed-in session) may name no workspace and keep the whole-machine view; a local caller must name its own.
|
|
510
|
+
*/
|
|
511
|
+
export function namedWorkspace(headers, local) {
|
|
512
|
+
const raw = headers[SCOPE_HEADER];
|
|
513
|
+
const named = (Array.isArray(raw) ? raw[0] : raw)?.trim();
|
|
514
|
+
// NULL-OK: field header x-bullseye-project is OPTIONAL and therefore it is ok to check for NULL
|
|
515
|
+
if (named === undefined || named === "") {
|
|
516
|
+
if (local)
|
|
517
|
+
throw new GatewayError(400, `a local caller names its workspace in the ${SCOPE_HEADER} header; only the passkey-signed public gateway answers for the whole machine`);
|
|
518
|
+
return undefined;
|
|
519
|
+
}
|
|
520
|
+
return workspaceOf(named);
|
|
521
|
+
}
|
|
522
|
+
/** The viewer a REST request is scoped to by its header (#4120), or undefined — the machine view — for a public-gateway caller that names none. A REST caller never creates a conversation outside its workspace, so its creator name matches nothing the MCP door stamps. */
|
|
523
|
+
export function viewerOfHeaders(headers, local) {
|
|
524
|
+
const folder = namedWorkspace(headers, local);
|
|
525
|
+
// NULL-OK: field folder is OPTIONAL and therefore it is ok to check for NULL
|
|
526
|
+
return folder === undefined ? undefined : { folder, creator: `rest:${folder}` };
|
|
527
|
+
}
|
|
528
|
+
/** Whether two folder paths name the same folder: a trailing separator, and on Windows letter case, do not name another folder. */
|
|
529
|
+
function sameFolder(a, b) {
|
|
530
|
+
const shape = (folder) => folder.replace(/[\\/]+$/, "").replace(/[\\/]/g, "/");
|
|
531
|
+
return process.platform === "win32" ? shape(a).toLowerCase() === shape(b).toLowerCase() : shape(a) === shape(b);
|
|
532
|
+
}
|
|
533
|
+
/** #3849 — BN's own home project, where a request that names no project runs: the first folder on the workspace list, in the list's order, which must hold a board — one that holds none is refused loudly, never passed over for the next board. NOTIFY_AGENT_HOME_PROJECT names another listed folder instead. */
|
|
534
|
+
function homeProject(listed, boards) {
|
|
535
|
+
const named = process.env.NOTIFY_AGENT_HOME_PROJECT;
|
|
536
|
+
// NULL-OK: env var NOTIFY_AGENT_HOME_PROJECT is OPTIONAL and therefore it is ok to check for NULL; an empty value counts as unset
|
|
537
|
+
const home = named === undefined || named === "" ? listed[0] : named;
|
|
538
|
+
// NULL-OK: home is undefined exactly when the workspace list names no folder on this machine and NOTIFY_AGENT_HOME_PROJECT is unset
|
|
539
|
+
if (home === undefined)
|
|
540
|
+
throw new GatewayError(400, `the request names no project, and the workspace list (${workspacesFile()}) names no folder on this machine for it to run in — add one on Bullseye Control`);
|
|
541
|
+
if (!boards.includes(home))
|
|
542
|
+
throw new GatewayError(400, `the request names no project, and the home project ${home} (the first folder on the workspace list) holds no BACKLOG.md; name a project (${boards.join(", ")})`);
|
|
543
|
+
return home;
|
|
544
|
+
}
|
|
545
|
+
/** The board-bearing project the request text names, by exact-case folder name as a whole token or path segment; the earliest mention wins, the longer name on a tie. */
|
|
546
|
+
function projectNamedIn(text, names) {
|
|
547
|
+
const hits = names
|
|
548
|
+
.map((name) => ({ name, at: new RegExp("(?<![\\w.-])" + name.replace(/[^\w-]/g, "\\$&") + "(?![\\w-])").exec(text)?.index ?? -1 }))
|
|
549
|
+
.filter((h) => h.at >= 0)
|
|
550
|
+
.sort((x, y) => x.at - y.at || y.name.length - x.name.length);
|
|
551
|
+
return hits[0]?.name;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* The folder a fresh conversation runs in (#2110). The bullseye-backlog MCP resolves the board against the agent's cwd, so the agent
|
|
555
|
+
* must never start in a folder without one: an explicit project must be one of the allowed project names (#2900); otherwise the
|
|
556
|
+
* board-bearing allowed project the request text names; otherwise the home project. When neither holds a board, a refusal that names
|
|
557
|
+
* the home project. A conversation that goes on keeps the folder it started in.
|
|
558
|
+
*/
|
|
559
|
+
export function resolveProject(project, text = "") {
|
|
560
|
+
// NULL-OK: field project is OPTIONAL and therefore it is ok to check for NULL
|
|
561
|
+
if (project !== undefined)
|
|
562
|
+
return projectFolder(project);
|
|
563
|
+
const listed = projectsHere().filter((p) => existsSync(p.folder));
|
|
564
|
+
const boards = listed.filter((p) => hasBoard(p.folder)).map((p) => p.name);
|
|
565
|
+
return projectFolder(projectNamedIn(text, boards) ?? homeProject(listed.map((p) => p.name), boards));
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* The workspace a session is CREATED in, from the name its creation supplied (#3640): exactly one of the allowed project
|
|
569
|
+
* names, resolved to its folder. A creation that names none is refused here by name with what to send — nothing is ever
|
|
570
|
+
* minted on a folder the caller did not choose, and no request's own text stands in for it.
|
|
571
|
+
*/
|
|
572
|
+
export function namedProject(project) {
|
|
573
|
+
if (typeof project !== "string" || project.trim() === "")
|
|
574
|
+
throw new GatewayError(400, `a new session needs the workspace it runs in: send project as exactly one of ${allowedProjects().join(", ")}`);
|
|
575
|
+
return projectFolder(project);
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* The folder a session is CREATED in, proved to be one of the allowed projects' folders: a creation that supplies no
|
|
579
|
+
* folder at all is refused by name, exactly as one that supplies a wrong one is (#3640) — this is the record's own
|
|
580
|
+
* guard, so no door can mint a record on a folder nobody chose.
|
|
581
|
+
*/
|
|
582
|
+
export function createdFolder(project) {
|
|
583
|
+
if (typeof project !== "string" || project.trim() === "")
|
|
584
|
+
throw new GatewayError(400, `a new session needs the workspace it runs in: send project as exactly one of ${allowedProjects().join(", ")}`);
|
|
585
|
+
return allowedFolder(project);
|
|
586
|
+
}
|
|
587
|
+
/** The agent CLI a session is CREATED on, from the name its creation supplied (#3640): nothing is minted on a provider the caller never named. */
|
|
588
|
+
export function namedProvider(provider) {
|
|
589
|
+
if (typeof provider !== "string" || providerFor(provider) === undefined)
|
|
590
|
+
throw new GatewayError(400, `a new session needs the agent CLI it runs: send provider as exactly one of ${PROVIDER_NAMES.join(", ")}`);
|
|
591
|
+
return provider;
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Refuses, in words, a conversation with no CLI of its own to open or stream (#3845, #3916): its record names an agent this gateway does not run.
|
|
595
|
+
*/
|
|
596
|
+
export function requireOwnCli(id) {
|
|
597
|
+
const named = readConversation(id).provider;
|
|
598
|
+
const provider = providerFor(named);
|
|
599
|
+
// NULL-OK: field provider is OPTIONAL and therefore it is ok to check for NULL
|
|
600
|
+
if (provider === undefined)
|
|
601
|
+
throw new GatewayError(409, `This conversation's agent is "${named}", which this gateway does not run, so it has no CLI to open.`);
|
|
602
|
+
}
|
|
603
|
+
/** #3849 — every listed project folder present on this machine, by name, with whether it is a Git repository and holds a board; `list` is the workspace list file they come from. */
|
|
604
|
+
export function listProjects(viewer) {
|
|
605
|
+
const projects = projectsHere()
|
|
606
|
+
.filter((p) => viewer === undefined || sameFolder(p.folder, viewer.folder))
|
|
607
|
+
.filter((p) => existsSync(p.folder) && statSync(p.folder).isDirectory())
|
|
608
|
+
.map((p) => ({ name: p.name, path: p.folder, git: existsSync(join(p.folder, ".git")), board: hasBoard(p.folder) }))
|
|
609
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
610
|
+
return { list: workspacesFile(), projects };
|
|
611
|
+
}
|
|
612
|
+
/** The record every new conversation starts from: one id, one unstarted session of its own, no turn run and nothing spent. Its workspace and its agent CLI are required and are bound HERE, in the one write that mints it (#3640): a record cannot exist without either, so no door can leave one to be filled in later. */
|
|
613
|
+
function newConversation(input) {
|
|
614
|
+
mkdirSync(agentDir(), { recursive: true });
|
|
615
|
+
const now = new Date().toISOString();
|
|
616
|
+
// NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
|
|
617
|
+
const beside = input.chat === undefined ? undefined : openConversationOf(input.chat)?.id;
|
|
618
|
+
const meta = {
|
|
619
|
+
id: randomUUID(), platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project: input.project, provider: input.provider, model: input.model,
|
|
620
|
+
state: input.state, createdAt: now, updatedAt: now, lastMessageAt: now, sessionId: randomUUID(), started: false, consumed: 0, beside,
|
|
621
|
+
};
|
|
622
|
+
writeMeta(meta);
|
|
623
|
+
return meta;
|
|
624
|
+
}
|
|
625
|
+
/** Every door measures its own wait: `receivedMs` is the first half of the turn's `bnMs`, so a door that had none could not name BN's whole time. */
|
|
626
|
+
export function startConversation(input) {
|
|
627
|
+
requireConversationEnabled();
|
|
628
|
+
const project = createdFolder(input.project);
|
|
629
|
+
const provider = namedProvider(input.provider);
|
|
630
|
+
const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, provider, model: input.model, state: "queued" });
|
|
631
|
+
appendEvent(meta.id, { role: "user", text: input.text, receivedMs: input.receivedMs, ...input.arrival });
|
|
632
|
+
return meta;
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Opens a conversation with nothing in it: no message and no agent work (#2723). Nothing is asked, so no user event is
|
|
636
|
+
* stored and no process is started, and opening one costs nothing. Its workspace — the folder, resolved from the name
|
|
637
|
+
* the call supplied — and its agent CLI are named BY THE CALL that opens it (#3640), so it is never an empty
|
|
638
|
+
* conversation waiting for either; it keeps its id and its whole transcript across a later switch of the folder.
|
|
639
|
+
*/
|
|
640
|
+
export function openConversation(input) {
|
|
641
|
+
requireConversationEnabled();
|
|
642
|
+
const project = createdFolder(input.project);
|
|
643
|
+
const provider = namedProvider(input.provider);
|
|
644
|
+
return newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, project, provider, model: input.model, state: "idle" });
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Sets or switches the folder the conversation's agent works in (#2723), reached by every door that offers it: the Web
|
|
648
|
+
* UI's per-row picker and the agent's own `agent_project`. THE AGENT IS NOT REPLACED. A session is resumed by its id from
|
|
649
|
+
* any folder — measured: a session written in one folder resumed from another recalled its earlier turn and worked in the
|
|
650
|
+
* new folder — so the record keeps its session id and the next turn carries the same agent on in the new folder with its
|
|
651
|
+
* whole history. The provider process is not moved either: its folder is fixed at its start, so the driver ends it and
|
|
652
|
+
* opens a new one where the record now points, exactly as it does for a resume after an idle spell.
|
|
653
|
+
*
|
|
654
|
+
* A change is refused while a turn is in flight, because a running process is never moved under itself.
|
|
655
|
+
*/
|
|
656
|
+
export function setConversationProject(id, project) {
|
|
657
|
+
requireConversationEnabled();
|
|
658
|
+
const meta = readConversation(id);
|
|
659
|
+
const log = readEvents(id);
|
|
660
|
+
if (shelfInLog(log) === "deleted")
|
|
661
|
+
throw new GatewayError(404, "no such conversation");
|
|
662
|
+
const turn = turnInFlight(log, meta);
|
|
663
|
+
// NULL-OK: field turn is OPTIONAL and therefore it is ok to check for NULL
|
|
664
|
+
if (turn !== undefined)
|
|
665
|
+
throw new GatewayError(409, `turn ${turn.turn} is ${turn.started ? "running" : "waiting to start"} since ${clockOf(turn.startedAt)}, so the project cannot change until it ends — a running process is never moved under itself`);
|
|
666
|
+
const folder = projectFolder(project);
|
|
667
|
+
// NULL-OK: field project is OPTIONAL and therefore it is ok to check for NULL
|
|
668
|
+
if (meta.project !== undefined && sameFolder(meta.project, folder))
|
|
669
|
+
return meta;
|
|
670
|
+
// The record is written first: the folder the next turn runs in comes from it, so a transcript line may never claim a switch the record does not hold. `providerArchived` is cleared because a later finish must confirm the provider's archive again rather than trust a handshake from before this work.
|
|
671
|
+
const switched = updateConversation(id, { project: folder, providerArchived: undefined });
|
|
672
|
+
appendEvent(id, { role: "system", kind: "status", text: `📁 Project set to ${basename(folder)} — the next turn carries this same agent on in that folder.` });
|
|
673
|
+
return switched;
|
|
674
|
+
}
|
|
675
|
+
/** Appends the message; a stopped conversation is resumed first, so its next turn picks the agent's own session up where it stopped. A message stored while a turn runs gets its place in line at once, so nobody waits behind it in silence. `receivedMs` is the door's own measured wait, as in `startConversation`. */
|
|
676
|
+
export function sendToConversation(id, text, receivedMs, arrival) {
|
|
677
|
+
requireConversationEnabled();
|
|
678
|
+
resumeConversation(id);
|
|
679
|
+
// Read again right here, so a turn that ended while this call was arriving is not named as still running.
|
|
680
|
+
const current = readEvents(id);
|
|
681
|
+
const behind = turnInFlight(current, readConversation(id));
|
|
682
|
+
const n = nextEventNumber(id);
|
|
683
|
+
const entries = [{ role: "user", text, receivedMs, ...arrival }];
|
|
684
|
+
// The place in line is written with the message itself, so a crash can never store a message whose wait went unannounced.
|
|
685
|
+
// NULL-OK: field behind is OPTIONAL and therefore it is ok to check for NULL
|
|
686
|
+
if (behind !== undefined) {
|
|
687
|
+
entries.push({ role: "system", kind: "queued", text: `⏳ queued behind the turn ${behind.started ? "started" : "stored"} at ${clockOf(behind.startedAt)}`, turn: n, behind });
|
|
688
|
+
}
|
|
689
|
+
return appendEvents(id, entries)[0];
|
|
690
|
+
}
|
|
691
|
+
/** The queue notice written for the stored message at position `n`, when it landed behind a running turn — the line a chat is told at once, so it is never left waiting in silence. */
|
|
692
|
+
export function queueNoticeOf(id, n) {
|
|
693
|
+
// `behind` is what tells this line from the driver's own slot line, which carries the same turn and no turn it waits behind.
|
|
694
|
+
return readEvents(id).find((e) => e.kind === "queued" && e.turn === n && e.behind !== undefined);
|
|
695
|
+
}
|
|
696
|
+
/** The one write that takes a record out of `closed`: made only once the log's last stop is followed by a resume. */
|
|
697
|
+
export function reopenConversation(id) {
|
|
698
|
+
writeMeta({ ...readConversation(id), state: "idle", pid: undefined, updatedAt: new Date().toISOString() });
|
|
699
|
+
}
|
|
700
|
+
/** A stopped or archived conversation taken up again — by a message to it, or by its own CLI being opened in the browser (#3845); a deleted one is gone. */
|
|
701
|
+
export function resumeConversation(id) {
|
|
702
|
+
const shelf = shelfInLog(readEvents(id));
|
|
703
|
+
if (shelf === "deleted")
|
|
704
|
+
throw new GatewayError(404, "no such conversation");
|
|
705
|
+
if (shelf === "archived")
|
|
706
|
+
restore(id);
|
|
707
|
+
if (readConversation(id).state !== "closed")
|
|
708
|
+
return;
|
|
709
|
+
appendEvent(id, { role: "system", kind: "resumed", text: "▶ Resumed — the agent picks the conversation up where it stopped." });
|
|
710
|
+
reopenConversation(id);
|
|
711
|
+
}
|
|
712
|
+
/** The kinds that end a turn for its asker: the answer or a failure. */
|
|
713
|
+
const TURN_ENDS = new Set(["answer", "failed"]);
|
|
714
|
+
/**
|
|
715
|
+
* Waits (capped at MAX_WAIT_SECONDS) for the end of the turn user event `turn` started — its answer, its failure, or
|
|
716
|
+
* a stop — and returns every event written past it on the way, with whether the turn ended and which turn that was.
|
|
717
|
+
*/
|
|
718
|
+
export async function waitForTurn(id, turn, waitSeconds) {
|
|
719
|
+
const deadline = Date.now() + Math.min(waitSeconds, MAX_WAIT_SECONDS) * 1000;
|
|
720
|
+
const events = [];
|
|
721
|
+
for (;;) {
|
|
722
|
+
const fresh = await waitForEvents(id, events.at(-1)?.n ?? turn, Math.max(0, deadline - Date.now()) / 1000);
|
|
723
|
+
events.push(...fresh);
|
|
724
|
+
if (events.some((e) => e.turn === turn && TURN_ENDS.has(e.kind)) || stoppedInLog(events))
|
|
725
|
+
return { events, ended: true, turn };
|
|
726
|
+
if (Date.now() >= deadline)
|
|
727
|
+
return { events, ended: false, turn };
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
/** Closes the conversation; the session driver sees it closed and reaps its process tree. */
|
|
731
|
+
export function stopConversation(id) {
|
|
732
|
+
const meta = readConversation(id);
|
|
733
|
+
if (meta.state === "closed")
|
|
734
|
+
return meta;
|
|
735
|
+
appendEvent(id, { role: "system", kind: "stopped", text: "⏹ Stopped." });
|
|
736
|
+
return updateConversation(id, { state: "closed" });
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Stops the conversation and moves it to the Archived shelf; its transcript stays, and a message to it brings it back and resumes it.
|
|
740
|
+
*/
|
|
741
|
+
export function archiveConversation(id) {
|
|
742
|
+
const shelf = shelfInLog(readEvents(id));
|
|
743
|
+
if (shelf === "deleted")
|
|
744
|
+
throw new GatewayError(404, "no such conversation");
|
|
745
|
+
stopConversation(id);
|
|
746
|
+
if (shelf !== "archived")
|
|
747
|
+
appendEvent(id, { role: "system", kind: "archived", text: "🗄 Archived." });
|
|
748
|
+
return updateConversation(id, { shelf: "archived" });
|
|
749
|
+
}
|
|
750
|
+
/** Moves an archived conversation back to the default list, still stopped until its next message. */
|
|
751
|
+
export function unarchiveConversation(id) {
|
|
752
|
+
const shelf = shelfInLog(readEvents(id));
|
|
753
|
+
if (shelf === "deleted")
|
|
754
|
+
throw new GatewayError(404, "no such conversation");
|
|
755
|
+
return shelf === "archived" ? restore(id) : readConversation(id);
|
|
756
|
+
}
|
|
757
|
+
function restore(id) {
|
|
758
|
+
appendEvent(id, { role: "system", kind: "restored", text: "↩ Restored to the list." });
|
|
759
|
+
return updateConversation(id, { shelf: undefined });
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Stops the conversation and marks it deleted; the session driver reaps its process and then removes the record and its transcript.
|
|
763
|
+
*/
|
|
764
|
+
export function deleteConversation(id) {
|
|
765
|
+
stopConversation(id);
|
|
766
|
+
if (shelfInLog(readEvents(id)) !== "deleted")
|
|
767
|
+
appendEvent(id, { role: "system", kind: "deleted", text: "🗑 Deleted." });
|
|
768
|
+
return updateConversation(id, { shelf: "deleted" });
|
|
769
|
+
}
|
|
770
|
+
/** The shelf the log puts the conversation on. The log is append-only, so a mark written beside a racing record write is never lost; a delete is final. */
|
|
771
|
+
export function shelfInLog(events) {
|
|
772
|
+
const marks = events.filter((e) => e.role === "system" && (e.kind === "archived" || e.kind === "restored" || e.kind === "deleted"));
|
|
773
|
+
if (marks.some((e) => e.kind === "deleted"))
|
|
774
|
+
return "deleted";
|
|
775
|
+
return marks.at(-1)?.kind === "archived" ? "archived" : undefined;
|
|
776
|
+
}
|
|
777
|
+
/** Removes the record and its transcript from disk — called only by the session driver once nothing of the session is left running. */
|
|
778
|
+
export function purgeConversation(id) {
|
|
779
|
+
rmSync(eventsPath(id), { force: true });
|
|
780
|
+
rmSync(metaPath(id), { force: true });
|
|
781
|
+
}
|
|
782
|
+
/** Whether the log's last stop stands — no resume after it. The log is append-only, so a stop written beside a racing record write is never lost. */
|
|
783
|
+
export function stoppedInLog(events) {
|
|
784
|
+
return lastStopOrResume(events) === "stopped";
|
|
785
|
+
}
|
|
786
|
+
/** Whether the log's last stop was resumed — a record a racing writer closed after the resume is reopened from it. */
|
|
787
|
+
export function resumedInLog(events) {
|
|
788
|
+
return lastStopOrResume(events) === "resumed";
|
|
789
|
+
}
|
|
790
|
+
function lastStopOrResume(events) {
|
|
791
|
+
return events.filter((e) => e.role === "system" && (e.kind === "stopped" || e.kind === "resumed")).at(-1)?.kind;
|
|
792
|
+
}
|