@alexsun-top/opencode-chat-room 0.8.5 → 0.8.6
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/CHANGELOG.md +12 -2
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/cli.ts +19 -0
- package/dist/cli.js +3747 -1443
- package/package.json +6 -1
- package/packages/chat-room-channeld/README.md +13 -8
- package/packages/chat-room-channeld/src/delivery.ts +0 -4
- package/packages/chat-room-channeld/src/host.ts +48 -37
- package/packages/chat-room-channeld/src/pg/database.ts +141 -49
- package/packages/chat-room-channeld/src/pg/worker.mjs +46 -5
- package/packages/chat-room-channeld/src/pg/worker.mts +41 -6
- package/packages/chat-room-channeld/src/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/plugin.ts +20 -4
- package/server/app.ts +9 -0
- package/server/assets/base.css +22 -2
- package/server/assets/chat/admin.js +13 -0
- package/server/assets/chat/announcements.js +76 -34
- package/server/assets/chat/confirm-dialog.js +3 -0
- package/server/assets/chat/create-room-dialog.js +7 -0
- package/server/assets/chat/diagram-viewer.js +4 -8
- package/server/assets/chat/doc-preview.js +70 -30
- package/server/assets/chat/editor.js +38 -3
- package/server/assets/chat/events.js +6 -1
- package/server/assets/chat/files.js +28 -26
- package/server/assets/chat/history-loader.js +31 -15
- package/server/assets/chat/integration-editor.js +25 -1
- package/server/assets/chat/integrations.js +107 -15
- package/server/assets/chat/join-requests.js +39 -1
- package/server/assets/chat/locales/de.js +5 -3
- package/server/assets/chat/locales/es.js +5 -3
- package/server/assets/chat/locales/fr.js +5 -3
- package/server/assets/chat/locales/it.js +5 -3
- package/server/assets/chat/locales/ja.js +5 -3
- package/server/assets/chat/locales/ko.js +5 -3
- package/server/assets/chat/markdown-footnotes.js +19 -8
- package/server/assets/chat/markdown.js +0 -7
- package/server/assets/chat/members.js +31 -19
- package/server/assets/chat/message-cache.js +8 -2
- package/server/assets/chat/message-polling.js +8 -2
- package/server/assets/chat/message-window.js +57 -0
- package/server/assets/chat/messages.js +79 -40
- package/server/assets/chat/operator.js +624 -0
- package/server/assets/chat/palette.js +2 -7
- package/server/assets/chat/panels.js +31 -8
- package/server/assets/chat/questions.js +72 -56
- package/server/assets/chat/recall.js +14 -5
- package/server/assets/chat/receipts.js +63 -7
- package/server/assets/chat/refresh-timing.js +6 -0
- package/server/assets/chat/reminders.js +44 -13
- package/server/assets/chat/replies.js +33 -22
- package/server/assets/chat/resource-format.js +4 -1
- package/server/assets/chat/room-list.js +202 -3
- package/server/assets/chat/room-watcher.js +3 -1
- package/server/assets/chat/rooms.js +22 -3
- package/server/assets/chat/settings.js +33 -3
- package/server/assets/chat/state.js +21 -7
- package/server/assets/chat/tasks.js +33 -11
- package/server/assets/chat/window-controls.js +25 -16
- package/server/assets/code-highlight.css +0 -13
- package/server/assets/conversation.css +31 -3
- package/server/assets/doc-preview.css +3 -0
- package/server/assets/files.css +4 -0
- package/server/assets/monaco/integration-rules.js +1 -1
- package/server/assets/responsive.css +12 -2
- package/server/assets/settings.css +3 -1
- package/server/assets/tasks.css +6 -1
- package/server/assets/window-controls.css +3 -1
- package/server/channels.ts +3 -2
- package/server/chat.html +7 -2
- package/server/inbox.ts +3 -1
- package/server/join-requests.ts +8 -1
- package/server/member-routes.ts +16 -2
- package/server/newrooms.ts +2 -13
- package/server/operator-auth.ts +21 -0
- package/server/operator-routes.ts +150 -0
- package/server/operator-state.ts +64 -0
- package/server/operator.css +139 -0
- package/server/room-owner.ts +17 -0
- package/server/routes/inbox.ts +15 -5
- package/server/routes/pages.ts +12 -2
- package/server/routes/room-actions.ts +4 -3
- package/server/system.html +109 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +3 -3
- package/src/acp/client.ts +254 -0
- package/src/acp/protocol.ts +300 -0
- package/src/acp/watch.ts +498 -0
- package/src/agent/agent-receipts.ts +87 -5
- package/src/center/center-client.ts +5 -0
- package/src/center/center-inbox.ts +54 -7
- package/src/center/center-wake.ts +57 -3
- package/src/center/forward-client.ts +48 -0
- package/src/center/mentions.ts +16 -3
- package/src/center/notification-delay.ts +139 -0
- package/src/center/queue.ts +3 -0
- package/src/config/file-config.ts +25 -0
- package/src/mcp/server.ts +389 -0
- package/src/protocol/config.ts +7 -0
- package/src/runtime/plugin-notifications.ts +43 -9
- package/src/runtime/v2-plugin.ts +14 -3
- package/src/runtime/v2-receiver.ts +10 -2
- package/src/runtime/watch.ts +5 -1
- package/src/state/pg-database.ts +133 -49
- package/src/state/pg-worker.mjs +46 -5
- package/src/state/pg-worker.mts +41 -6
- package/src/state/receiver-state.ts +47 -0
- package/src/state/sqlite-database.ts +6 -2
- package/src/state/sqlite-members.ts +48 -4
- package/src/state/sqlite-messages.ts +25 -12
- package/src/state/sqlite-schema.ts +4 -1
- package/src/state/sqlite-state.ts +1 -1
- package/src/state/store.ts +10 -4
- package/src/tui/app.mjs +57 -10
- package/src/tui/app.mts +54 -11
- package/src/tui/room-settings-app.mjs +27 -9
- package/src/tui/room-settings-app.mts +26 -9
- package/src/web/integration-rules-editor.ts +25 -2
package/src/acp/watch.ts
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
// Opt-in ACP room watch: one trusted local ACP v1 session, one explicit room,
|
|
2
|
+
// one prompt per delivered notification. It never joins, reads receipts, or
|
|
3
|
+
// spawns a worker per message.
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { statSync } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
import { request, type CenterOpts } from "../center/center-client.ts";
|
|
9
|
+
import { withMessageIds } from "../center/message-ids.ts";
|
|
10
|
+
import {
|
|
11
|
+
claimBackgroundAttempt,
|
|
12
|
+
hasAcpWatchCompletion,
|
|
13
|
+
saveAcpWatchCompletion,
|
|
14
|
+
} from "../state/receiver-state.ts";
|
|
15
|
+
import { formatNotificationLines } from "../state/store.ts";
|
|
16
|
+
import { mcpServer, resolveAcpCenter, safeAgentText } from "./client.ts";
|
|
17
|
+
import { AcpConnection, AcpTimeoutError } from "./protocol.ts";
|
|
18
|
+
|
|
19
|
+
const SETUP_TIMEOUT_MS = 30_000;
|
|
20
|
+
const DEFAULT_TURN_TIMEOUT_MS = 600_000;
|
|
21
|
+
const MIN_TIMEOUT_MS = 500;
|
|
22
|
+
const MAX_TIMEOUT_MS = 3_600_000;
|
|
23
|
+
const POLL_TIMEOUT_MS = 5_000;
|
|
24
|
+
const RETRY_MS = 1_000;
|
|
25
|
+
const MAX_IDLE_ERRORS = 30;
|
|
26
|
+
const STOP_REASONS = new Set([
|
|
27
|
+
"end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled",
|
|
28
|
+
]);
|
|
29
|
+
const TERMINAL_STOP_REASONS = new Set(["end_turn", "max_tokens", "max_turn_requests", "refusal"]);
|
|
30
|
+
const ACK_RETRY_DELAYS_MS = [0, 100, 250, 500, 1_000];
|
|
31
|
+
|
|
32
|
+
type InboxItem = {
|
|
33
|
+
id: string;
|
|
34
|
+
roomId: string;
|
|
35
|
+
roomName: string;
|
|
36
|
+
roomKind?: "group" | "direct";
|
|
37
|
+
senderId: string;
|
|
38
|
+
text: string;
|
|
39
|
+
createdAt: number;
|
|
40
|
+
answerQuestionExcerpt?: string;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type InboxResult = {
|
|
44
|
+
member?: boolean;
|
|
45
|
+
membershipID?: string;
|
|
46
|
+
items?: InboxItem[];
|
|
47
|
+
queuedTs?: Record<string, number>;
|
|
48
|
+
hasMore?: boolean;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
type WatchOptions = {
|
|
52
|
+
sessionId: string;
|
|
53
|
+
roomId: string;
|
|
54
|
+
prompt?: string;
|
|
55
|
+
cwd: string;
|
|
56
|
+
command: string;
|
|
57
|
+
args: string[];
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function isDirectory(directory: string): boolean {
|
|
61
|
+
try {
|
|
62
|
+
return statSync(directory).isDirectory();
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isFile(file: string): boolean {
|
|
69
|
+
try {
|
|
70
|
+
return statSync(file).isFile();
|
|
71
|
+
} catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function turnTimeout(): number {
|
|
77
|
+
const raw = process.env.CHAT_ROOM_ACP_TURN_TIMEOUT_MS;
|
|
78
|
+
if (raw && /^\d+$/.test(raw)) {
|
|
79
|
+
const value = Number(raw);
|
|
80
|
+
if (value >= MIN_TIMEOUT_MS && value <= MAX_TIMEOUT_MS) return value;
|
|
81
|
+
}
|
|
82
|
+
return DEFAULT_TURN_TIMEOUT_MS;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function parseWatchArgs(args: readonly string[]): WatchOptions | string {
|
|
86
|
+
if (args.some((arg) => typeof arg !== "string")) return "arguments must be strings";
|
|
87
|
+
let sessionId = "";
|
|
88
|
+
let roomId = "";
|
|
89
|
+
let prompt: string | undefined;
|
|
90
|
+
let cwd = process.cwd();
|
|
91
|
+
let command: string[] | undefined;
|
|
92
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
93
|
+
const arg = args[index]!;
|
|
94
|
+
if (arg === "--") {
|
|
95
|
+
command = args.slice(index + 1);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
if (arg === "--session-id" || arg === "--room-id" || arg === "--prompt" || arg === "--cwd") {
|
|
99
|
+
const value = args[index + 1];
|
|
100
|
+
index += 1;
|
|
101
|
+
if (value === undefined || value === "") return `missing value for ${arg}`;
|
|
102
|
+
if (arg === "--session-id") sessionId = value;
|
|
103
|
+
else if (arg === "--room-id") roomId = value;
|
|
104
|
+
else if (arg === "--prompt") prompt = value;
|
|
105
|
+
else cwd = path.resolve(value);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
return `unknown option: ${arg}`;
|
|
109
|
+
}
|
|
110
|
+
if (!command || command.length === 0) return "usage: acp watch ... -- <command> [args...]";
|
|
111
|
+
if (!/^\S{1,200}$/.test(sessionId)) return "--session-id must be 1-200 characters without spaces";
|
|
112
|
+
if (!/^\S{1,200}$/.test(roomId)) return "--room-id must be 1-200 characters without spaces";
|
|
113
|
+
if (prompt !== undefined && prompt.length > 1_000_000) return "--prompt must be at most 1000000 characters";
|
|
114
|
+
if (!isDirectory(cwd)) return "--cwd must be an existing directory";
|
|
115
|
+
return { sessionId, roomId, prompt, cwd, command: command[0]!, args: command.slice(1) };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function writeOut(text: string): void {
|
|
119
|
+
if (text) process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function diagnostic(text: string): void {
|
|
123
|
+
process.stderr.write(`acp watch: ${text}\n`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function sleep(ms: number): Promise<void> {
|
|
127
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
131
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
132
|
+
? value as Record<string, unknown>
|
|
133
|
+
: undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function runAcpWatch(args: readonly string[], cliEntry: string): Promise<number> {
|
|
137
|
+
const options = parseWatchArgs(args);
|
|
138
|
+
if (typeof options === "string") {
|
|
139
|
+
diagnostic(options);
|
|
140
|
+
return 2;
|
|
141
|
+
}
|
|
142
|
+
if (!path.isAbsolute(cliEntry) || !isFile(cliEntry)) {
|
|
143
|
+
diagnostic("CLI entry must be an absolute file path");
|
|
144
|
+
return 1;
|
|
145
|
+
}
|
|
146
|
+
let center;
|
|
147
|
+
try {
|
|
148
|
+
center = resolveAcpCenter();
|
|
149
|
+
} catch (error) {
|
|
150
|
+
diagnostic(error instanceof Error ? error.message : "cannot resolve center");
|
|
151
|
+
return 1;
|
|
152
|
+
}
|
|
153
|
+
const opts: CenterOpts = { center: center.center, token: center.token };
|
|
154
|
+
const child = spawn(options.command, options.args, {
|
|
155
|
+
cwd: options.cwd,
|
|
156
|
+
env: process.env,
|
|
157
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
158
|
+
shell: false,
|
|
159
|
+
windowsHide: true,
|
|
160
|
+
});
|
|
161
|
+
const connection = new AcpConnection(child);
|
|
162
|
+
const shutdown = new AbortController();
|
|
163
|
+
let stopping = false;
|
|
164
|
+
const onSignal = () => {
|
|
165
|
+
if (stopping) return;
|
|
166
|
+
stopping = true;
|
|
167
|
+
shutdown.abort();
|
|
168
|
+
void connection.shutdown();
|
|
169
|
+
};
|
|
170
|
+
process.on("SIGINT", onSignal);
|
|
171
|
+
process.on("SIGTERM", onSignal);
|
|
172
|
+
try {
|
|
173
|
+
connection.armTimeout(SETUP_TIMEOUT_MS);
|
|
174
|
+
const initialize = record(await connection.request("initialize", {
|
|
175
|
+
protocolVersion: 1,
|
|
176
|
+
clientCapabilities: {
|
|
177
|
+
fs: { readTextFile: false, writeTextFile: false },
|
|
178
|
+
terminal: false,
|
|
179
|
+
auth: { terminal: false },
|
|
180
|
+
},
|
|
181
|
+
clientInfo: { name: "opencode-chat-room", version: "1" },
|
|
182
|
+
}));
|
|
183
|
+
if (initialize?.protocolVersion !== 1) throw new Error("agent does not support ACP protocol version 1");
|
|
184
|
+
const created = record(await connection.request("session/new", {
|
|
185
|
+
cwd: options.cwd,
|
|
186
|
+
mcpServers: [mcpServer(options.sessionId, cliEntry, center.env)],
|
|
187
|
+
}));
|
|
188
|
+
const acpSessionId = created?.sessionId;
|
|
189
|
+
if (typeof acpSessionId !== "string" || !acpSessionId) throw new Error("agent returned no session id");
|
|
190
|
+
connection.setSessionId(acpSessionId);
|
|
191
|
+
connection.disarmTimeout();
|
|
192
|
+
if (options.prompt) {
|
|
193
|
+
const turn = await promptTurn(connection, acpSessionId, options.prompt, turnTimeout());
|
|
194
|
+
writeOut(turn.text);
|
|
195
|
+
connection.resetOutput();
|
|
196
|
+
if (turn.stopReason !== "end_turn") {
|
|
197
|
+
diagnostic(`initial prompt stopped: ${turn.stopReason}`);
|
|
198
|
+
return exitForStop(turn.stopReason);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return await watchLoop(connection, acpSessionId, options, opts, () => stopping, shutdown.signal);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (stopping) return 0;
|
|
204
|
+
diagnostic(error instanceof Error ? error.message : "ACP watch failed");
|
|
205
|
+
return error instanceof AcpTimeoutError ? 3 : 1;
|
|
206
|
+
} finally {
|
|
207
|
+
process.off("SIGINT", onSignal);
|
|
208
|
+
process.off("SIGTERM", onSignal);
|
|
209
|
+
connection.disarmTimeout();
|
|
210
|
+
await connection.shutdown();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function promptTurn(
|
|
215
|
+
connection: AcpConnection,
|
|
216
|
+
acpSessionId: string,
|
|
217
|
+
text: string,
|
|
218
|
+
timeoutMs: number,
|
|
219
|
+
): Promise<{ stopReason: string; text: string }> {
|
|
220
|
+
connection.resetOutput();
|
|
221
|
+
connection.markPromptActive();
|
|
222
|
+
connection.armTimeout(timeoutMs);
|
|
223
|
+
try {
|
|
224
|
+
const result = record(await connection.request("session/prompt", {
|
|
225
|
+
sessionId: acpSessionId,
|
|
226
|
+
prompt: [{ type: "text", text }],
|
|
227
|
+
}));
|
|
228
|
+
const stopReason = result?.stopReason;
|
|
229
|
+
if (typeof stopReason !== "string" || !STOP_REASONS.has(stopReason)) {
|
|
230
|
+
throw new Error("agent returned an invalid stop reason");
|
|
231
|
+
}
|
|
232
|
+
return { stopReason, text: safeAgentText(connection.output) };
|
|
233
|
+
} finally {
|
|
234
|
+
connection.disarmTimeout();
|
|
235
|
+
connection.markPromptDone();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function exitForStop(stopReason: string): number {
|
|
240
|
+
return stopReason === "cancelled" ? 3 : stopReason === "end_turn" ? 0 : 1;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
type AckOutcome = "ok" | "stopped" | "stale" | "failed";
|
|
244
|
+
|
|
245
|
+
async function postAck(opts: CenterOpts, body: unknown, signal: AbortSignal): Promise<void> {
|
|
246
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
247
|
+
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
|
|
248
|
+
const response = await fetch(`${opts.center}/queued/member`, {
|
|
249
|
+
method: "POST",
|
|
250
|
+
headers,
|
|
251
|
+
body: JSON.stringify(body),
|
|
252
|
+
redirect: "manual",
|
|
253
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]),
|
|
254
|
+
});
|
|
255
|
+
if (response.status >= 300 && response.status < 400) {
|
|
256
|
+
throw Object.assign(new Error("ack redirect refused"), { status: response.status, permanent: true });
|
|
257
|
+
}
|
|
258
|
+
if (!response.ok) throw Object.assign(new Error("ack failed"), { status: response.status });
|
|
259
|
+
const data = await response.json().catch(() => null);
|
|
260
|
+
if (record(data)?.ok !== true) {
|
|
261
|
+
throw Object.assign(new Error("ack response is not confirmed"), { permanent: true });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function acknowledgeCompletion(
|
|
266
|
+
opts: CenterOpts,
|
|
267
|
+
sessionID: string,
|
|
268
|
+
roomID: string,
|
|
269
|
+
membershipID: string,
|
|
270
|
+
throughTs: number,
|
|
271
|
+
stopping: () => boolean,
|
|
272
|
+
signal: AbortSignal,
|
|
273
|
+
): Promise<AckOutcome> {
|
|
274
|
+
for (let attempt = 0; attempt < ACK_RETRY_DELAYS_MS.length; attempt += 1) {
|
|
275
|
+
if (stopping()) return "stopped";
|
|
276
|
+
try {
|
|
277
|
+
await postAck(opts, { roomId: roomID, sessionID, membershipID, ts: throughTs }, signal);
|
|
278
|
+
return "ok";
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (stopping()) return "stopped";
|
|
281
|
+
const details = record(error);
|
|
282
|
+
if (details?.permanent) return "failed";
|
|
283
|
+
const status = details?.status;
|
|
284
|
+
if (status === 409) return "stale";
|
|
285
|
+
const transient = status === undefined || status === 408 || status === 425 || status === 429 ||
|
|
286
|
+
(typeof status === "number" && status >= 500);
|
|
287
|
+
if (!transient || attempt === ACK_RETRY_DELAYS_MS.length - 1) return "failed";
|
|
288
|
+
await sleep(ACK_RETRY_DELAYS_MS[attempt + 1]!);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return "failed";
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// One ACK path for recovered completion and fresh terminal result.
|
|
295
|
+
async function finishDelivery(
|
|
296
|
+
connection: AcpConnection, opts: CenterOpts, options: WatchOptions, membershipID: string,
|
|
297
|
+
throughTs: number, stopping: () => boolean, signal: AbortSignal,
|
|
298
|
+
): Promise<number | null> {
|
|
299
|
+
const ack = await acknowledgeCompletion(
|
|
300
|
+
opts, options.sessionId, options.roomId, membershipID, throughTs, stopping, signal,
|
|
301
|
+
);
|
|
302
|
+
if (ack === "ok") {
|
|
303
|
+
connection.resetOutput();
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
if (ack === "stopped") return 0;
|
|
307
|
+
diagnostic(ack === "stale" ? "membership changed; not acknowledging" : "queue acknowledgement failed");
|
|
308
|
+
return 1;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function readRoomInbox(opts: CenterOpts, chatSessionId: string, roomId: string): Promise<unknown> {
|
|
312
|
+
const query = new URLSearchParams({
|
|
313
|
+
sessionID: chatSessionId,
|
|
314
|
+
roomId,
|
|
315
|
+
excludeSelf: "1",
|
|
316
|
+
timeout: String(POLL_TIMEOUT_MS),
|
|
317
|
+
});
|
|
318
|
+
return await request(opts, `/inbox?${query.toString()}`, "GET");
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function renderNotification(items: InboxItem[]): { text: string; omitted: boolean } {
|
|
322
|
+
const { lines, visibleIndices } = formatNotificationLines(withMessageIds(items));
|
|
323
|
+
const first = items[0]!;
|
|
324
|
+
const context = first.roomKind === "direct"
|
|
325
|
+
? `Direct conversation in room ${first.roomName} (${first.roomId})`
|
|
326
|
+
: `New messages in room ${first.roomName} (${first.roomId})`;
|
|
327
|
+
return {
|
|
328
|
+
text: `<notification>\n${context}:\n${lines.join("\n")}\n</notification>`,
|
|
329
|
+
omitted: visibleIndices.length !== items.length,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function parseInbox(value: unknown): InboxResult | string {
|
|
334
|
+
const input = record(value);
|
|
335
|
+
if (!input || typeof input.member !== "boolean") return "inbox response invalid";
|
|
336
|
+
if (input.member && (typeof input.membershipID !== "string" || !input.membershipID)) {
|
|
337
|
+
return "center does not provide membershipID; upgrade the center";
|
|
338
|
+
}
|
|
339
|
+
if (input.hasMore !== undefined && typeof input.hasMore !== "boolean") return "inbox response invalid";
|
|
340
|
+
const items = input.items === undefined ? [] : input.items;
|
|
341
|
+
if (!Array.isArray(items)) return "inbox response invalid";
|
|
342
|
+
const parsed: InboxItem[] = [];
|
|
343
|
+
for (const entry of items) {
|
|
344
|
+
const item = record(entry);
|
|
345
|
+
if (!item || typeof item.id !== "string" || !item.id ||
|
|
346
|
+
typeof item.roomId !== "string" || typeof item.roomName !== "string" ||
|
|
347
|
+
typeof item.senderId !== "string" || typeof item.text !== "string" ||
|
|
348
|
+
!Number.isSafeInteger(item.createdAt) || (item.createdAt as number) <= 0 ||
|
|
349
|
+
(item.roomKind !== undefined && item.roomKind !== "group" && item.roomKind !== "direct") ||
|
|
350
|
+
(item.answerQuestionExcerpt !== undefined && typeof item.answerQuestionExcerpt !== "string")) {
|
|
351
|
+
return "inbox response invalid";
|
|
352
|
+
}
|
|
353
|
+
parsed.push(item as unknown as InboxItem);
|
|
354
|
+
}
|
|
355
|
+
const queuedInput = input.queuedTs === undefined ? {} : record(input.queuedTs);
|
|
356
|
+
if (!queuedInput) return "inbox response invalid";
|
|
357
|
+
const queuedTs: Record<string, number> = {};
|
|
358
|
+
for (const [key, value] of Object.entries(queuedInput)) {
|
|
359
|
+
if (!Number.isSafeInteger(value) || (value as number) < 0) return "inbox response invalid";
|
|
360
|
+
queuedTs[key] = value as number;
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
member: input.member,
|
|
364
|
+
membershipID: typeof input.membershipID === "string" ? input.membershipID : undefined,
|
|
365
|
+
items: parsed,
|
|
366
|
+
queuedTs,
|
|
367
|
+
hasMore: input.hasMore === true,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function watchLoop(
|
|
372
|
+
connection: AcpConnection,
|
|
373
|
+
acpSessionId: string,
|
|
374
|
+
options: WatchOptions,
|
|
375
|
+
opts: CenterOpts,
|
|
376
|
+
stopping: () => boolean,
|
|
377
|
+
signal: AbortSignal,
|
|
378
|
+
): Promise<number> {
|
|
379
|
+
let waiting: "waiting" | "member" | undefined;
|
|
380
|
+
let idleErrors = 0;
|
|
381
|
+
while (!connection.isClosed) {
|
|
382
|
+
let raw: unknown;
|
|
383
|
+
try {
|
|
384
|
+
raw = await readRoomInbox(opts, options.sessionId, options.roomId);
|
|
385
|
+
} catch {
|
|
386
|
+
if (connection.isClosed) return stopping() ? 0 : 1;
|
|
387
|
+
idleErrors += 1;
|
|
388
|
+
if (idleErrors > MAX_IDLE_ERRORS) {
|
|
389
|
+
diagnostic("inbox reads kept failing");
|
|
390
|
+
return 1;
|
|
391
|
+
}
|
|
392
|
+
diagnostic("inbox read failed; retrying");
|
|
393
|
+
await sleep(RETRY_MS);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
if (connection.isClosed) return stopping() ? 0 : 1;
|
|
397
|
+
const parsed = parseInbox(raw);
|
|
398
|
+
if (typeof parsed === "string") {
|
|
399
|
+
if (parsed.includes("membershipID")) {
|
|
400
|
+
diagnostic(parsed);
|
|
401
|
+
return 1;
|
|
402
|
+
}
|
|
403
|
+
idleErrors += 1;
|
|
404
|
+
if (idleErrors > MAX_IDLE_ERRORS) {
|
|
405
|
+
diagnostic("inbox responses kept failing validation");
|
|
406
|
+
return 1;
|
|
407
|
+
}
|
|
408
|
+
diagnostic("inbox response invalid; retrying");
|
|
409
|
+
await sleep(RETRY_MS);
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
idleErrors = 0;
|
|
413
|
+
const inbox = parsed;
|
|
414
|
+
if (inbox.member !== true) {
|
|
415
|
+
if (waiting !== "waiting") diagnostic(`waiting: not a member of room ${options.roomId}`);
|
|
416
|
+
waiting = "waiting";
|
|
417
|
+
await sleep(RETRY_MS);
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
waiting = "member";
|
|
421
|
+
const membershipID = inbox.membershipID;
|
|
422
|
+
if (!membershipID) {
|
|
423
|
+
diagnostic("center does not provide membershipID; upgrade the center");
|
|
424
|
+
return 1;
|
|
425
|
+
}
|
|
426
|
+
const items = (inbox.items ?? []).filter((item) => item.roomId === options.roomId);
|
|
427
|
+
if (!items.length) continue;
|
|
428
|
+
const oldest = items.reduce((min, item) => Math.min(min, item.createdAt), items[0]!.createdAt);
|
|
429
|
+
const last = items[items.length - 1]!;
|
|
430
|
+
if (inbox.hasMore && last.createdAt === oldest) {
|
|
431
|
+
diagnostic("oldest notification spans a paginated inbox page; not prompting");
|
|
432
|
+
return 1;
|
|
433
|
+
}
|
|
434
|
+
const cutoff = inbox.queuedTs?.[options.roomId] ?? 0;
|
|
435
|
+
const batch = items.filter((item) => item.createdAt === oldest && item.createdAt > cutoff);
|
|
436
|
+
if (!batch.length) continue;
|
|
437
|
+
const rendered = renderNotification(batch);
|
|
438
|
+
if (rendered.omitted) {
|
|
439
|
+
diagnostic("notification formatter omitted message IDs; not prompting");
|
|
440
|
+
return 1;
|
|
441
|
+
}
|
|
442
|
+
const throughTs = batch.reduce((max, item) => Math.max(max, item.createdAt), oldest);
|
|
443
|
+
const service = JSON.stringify(["acp-watch", opts.center, options.sessionId, options.roomId, membershipID]);
|
|
444
|
+
let completed: boolean;
|
|
445
|
+
try {
|
|
446
|
+
completed = hasAcpWatchCompletion(options.sessionId, options.roomId, service, throughTs);
|
|
447
|
+
} catch {
|
|
448
|
+
diagnostic("completion marker unavailable; stopping");
|
|
449
|
+
return 1;
|
|
450
|
+
}
|
|
451
|
+
if (completed) {
|
|
452
|
+
const exit = await finishDelivery(connection, opts, options, membershipID, throughTs, stopping, signal);
|
|
453
|
+
if (exit !== null) return exit;
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
if (connection.isClosed) return stopping() ? 0 : 1;
|
|
457
|
+
let claimed: boolean;
|
|
458
|
+
try {
|
|
459
|
+
claimed = claimBackgroundAttempt(options.sessionId, options.roomId, service, throughTs);
|
|
460
|
+
} catch {
|
|
461
|
+
diagnostic("attempt fence unavailable; stopping");
|
|
462
|
+
return 1;
|
|
463
|
+
}
|
|
464
|
+
if (!claimed) {
|
|
465
|
+
diagnostic("an earlier attempt for this message is unresolved; not replaying");
|
|
466
|
+
return 1;
|
|
467
|
+
}
|
|
468
|
+
if (connection.isClosed) return stopping() ? 0 : 1;
|
|
469
|
+
let turn: { stopReason: string; text: string };
|
|
470
|
+
try {
|
|
471
|
+
turn = await promptTurn(connection, acpSessionId, rendered.text, turnTimeout());
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (stopping()) return 0;
|
|
474
|
+
diagnostic(error instanceof AcpTimeoutError ? "turn timed out; not replaying" : "ACP turn ended without a result; not replaying");
|
|
475
|
+
return error instanceof AcpTimeoutError ? 3 : 1;
|
|
476
|
+
}
|
|
477
|
+
if (!TERMINAL_STOP_REASONS.has(turn.stopReason)) {
|
|
478
|
+
writeOut(turn.text);
|
|
479
|
+
connection.resetOutput();
|
|
480
|
+
diagnostic(`turn stopped: ${turn.stopReason}; not acknowledging`);
|
|
481
|
+
return exitForStop(turn.stopReason);
|
|
482
|
+
}
|
|
483
|
+
try {
|
|
484
|
+
saveAcpWatchCompletion(options.sessionId, options.roomId, service, throughTs);
|
|
485
|
+
} catch {
|
|
486
|
+
writeOut(turn.text);
|
|
487
|
+
connection.resetOutput();
|
|
488
|
+
diagnostic("completion marker unavailable; not acknowledging");
|
|
489
|
+
return 1;
|
|
490
|
+
}
|
|
491
|
+
writeOut(turn.text);
|
|
492
|
+
connection.resetOutput();
|
|
493
|
+
const exit = await finishDelivery(connection, opts, options, membershipID, throughTs, stopping, signal);
|
|
494
|
+
if (exit !== null) return exit;
|
|
495
|
+
}
|
|
496
|
+
if (!stopping()) diagnostic("agent exited");
|
|
497
|
+
return stopping() ? 0 : 1;
|
|
498
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { databasePath, formatNotificationLines, notificationMessageLine, recordMessageReceipts } from "../state/store.ts";
|
|
4
|
-
import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "../state/receiver-state.ts";
|
|
3
|
+
import { databasePath, formatNotificationLines, notificationMessageLine, recordMessageDeliveries, recordMessageReceipts } from "../state/store.ts";
|
|
4
|
+
import { acquireDeliveryLease, deleteReceiptCandidate, deleteReceiptDelivery, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, readyReceiptDeliveries, releaseDeliveryLease, rescheduleReceiptDelivery, saveReceiptCandidate, saveReceiptDelivery, type ReceiptDelivery } from "../state/receiver-state.ts";
|
|
5
5
|
|
|
6
6
|
// shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
|
|
7
7
|
const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
|
|
@@ -12,6 +12,9 @@ export type ReceiptCandidate = {
|
|
|
12
12
|
receiverOwnerID: string; destination: string; messageIDs: string[]; textHash: string; createdAt: number;
|
|
13
13
|
};
|
|
14
14
|
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
|
|
15
|
+
function receiptCandidateKey(candidate: ReceiptCandidate): string {
|
|
16
|
+
return hash(JSON.stringify([candidate.sessionID, candidate.admissionID, candidate.roomID, candidate.destination, candidate.receiverOwnerID, candidate.membershipID]));
|
|
17
|
+
}
|
|
15
18
|
function hasCappedMetadata(item: Item): item is CappedItem {
|
|
16
19
|
return typeof item.senderId === "string" && typeof item.createdAt === "number" && Number.isSafeInteger(item.createdAt) &&
|
|
17
20
|
!/[\r\n]/.test(item.senderId) && !/[\r\n]/.test(item.text);
|
|
@@ -60,7 +63,7 @@ export function prepareReceiptCandidate(input: {
|
|
|
60
63
|
destination: input.destination, messageIDs: evidenceItems.map((item) => item.id!),
|
|
61
64
|
textHash: hash(input.prompt), createdAt: Date.now(),
|
|
62
65
|
};
|
|
63
|
-
const key =
|
|
66
|
+
const key = receiptCandidateKey(candidate);
|
|
64
67
|
try { saveReceiptCandidate(key, candidate, candidate.createdAt + UNOBSERVED_TTL); }
|
|
65
68
|
catch { return undefined; }
|
|
66
69
|
return candidate;
|
|
@@ -89,13 +92,90 @@ export function observeReceiptContext(sessionID: string, messages: readonly unkn
|
|
|
89
92
|
if (!context) continue;
|
|
90
93
|
for (const candidate of receiptCandidates<ReceiptCandidate>(sessionID, context.id, destination, ownerID, Date.now())) {
|
|
91
94
|
if (!matchesReceiptText(context.text, candidate.textHash)) continue;
|
|
92
|
-
const key =
|
|
95
|
+
const key = receiptCandidateKey(candidate);
|
|
93
96
|
if (markReceiptCandidateReady(key)) observed++;
|
|
94
97
|
}
|
|
95
98
|
}
|
|
96
99
|
return observed;
|
|
97
100
|
}
|
|
98
101
|
|
|
102
|
+
export function markReceiptDelivered(candidate: ReceiptCandidate | undefined): void {
|
|
103
|
+
if (!candidate) return;
|
|
104
|
+
const now = Date.now();
|
|
105
|
+
try {
|
|
106
|
+
saveReceiptDelivery(receiptCandidateKey(candidate), {
|
|
107
|
+
sessionID: candidate.sessionID, roomID: candidate.roomID, destination: candidate.destination,
|
|
108
|
+
receiverOwnerID: candidate.receiverOwnerID, membershipID: candidate.membershipID,
|
|
109
|
+
messageIDs: candidate.messageIDs,
|
|
110
|
+
}, now, now + UNOBSERVED_TTL);
|
|
111
|
+
} catch { /* Best effort: the host ack is already spent and never replayed, so a store failure loses this confirmation. */ }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const DELIVERY_FLUSH_LIMIT = 8;
|
|
115
|
+
const DELIVERY_FLUSH_LEASE_MS = 30_000;
|
|
116
|
+
const DELIVERY_MAX_ATTEMPTS = 8;
|
|
117
|
+
const deliveryFlushes = new Map<string, Promise<void>>();
|
|
118
|
+
|
|
119
|
+
export function flushReceiptDeliveries(input: {
|
|
120
|
+
destination: string; receiverOwnerID?: string; center?: string; token?: string;
|
|
121
|
+
}): Promise<void> {
|
|
122
|
+
const key = JSON.stringify([input.destination, input.receiverOwnerID ?? ""]);
|
|
123
|
+
const running = deliveryFlushes.get(key);
|
|
124
|
+
if (running) return running;
|
|
125
|
+
const task = flushOneReceiptDelivery(input, key).finally(() => deliveryFlushes.delete(key));
|
|
126
|
+
deliveryFlushes.set(key, task);
|
|
127
|
+
return task;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function flushOneReceiptDelivery(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }, cursorKey: string): Promise<void> {
|
|
131
|
+
const leaseKey = `delivery-flush:${hash(cursorKey)}`;
|
|
132
|
+
const holder = randomUUID(), now = Date.now();
|
|
133
|
+
if (!acquireDeliveryLease(leaseKey, holder, now, now + DELIVERY_FLUSH_LEASE_MS)) return;
|
|
134
|
+
const owned = () => ownsDeliveryLease(leaseKey, holder, Date.now());
|
|
135
|
+
try {
|
|
136
|
+
let deliveries: Array<{ id: string; value: ReceiptDelivery; attempts: number }>;
|
|
137
|
+
try { deliveries = readyReceiptDeliveries(input.destination, input.receiverOwnerID, Date.now(), DELIVERY_FLUSH_LIMIT); }
|
|
138
|
+
catch { return; }
|
|
139
|
+
const retry = (id: string, attempts: number) => {
|
|
140
|
+
if (!owned()) return;
|
|
141
|
+
const next = attempts + 1;
|
|
142
|
+
if (next >= DELIVERY_MAX_ATTEMPTS) { deleteReceiptDelivery(id); return; }
|
|
143
|
+
rescheduleReceiptDelivery(id, next, Date.now() + Math.min(60_000 * 2 ** next, 3_600_000));
|
|
144
|
+
};
|
|
145
|
+
for (const { id, value, attempts } of deliveries) {
|
|
146
|
+
if (!owned()) break;
|
|
147
|
+
try {
|
|
148
|
+
if (input.center) {
|
|
149
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
150
|
+
if (input.token) headers.Authorization = `Bearer ${input.token}`;
|
|
151
|
+
const response = await fetch(`${input.center.replace(/\/+$/, "")}/rooms/${encodeURIComponent(value.roomID)}/deliveries`, {
|
|
152
|
+
method: "POST", headers, body: JSON.stringify({ sessionID: value.sessionID, membershipID: value.membershipID,
|
|
153
|
+
receiverOwnerID: value.receiverOwnerID, messageIDs: value.messageIDs }),
|
|
154
|
+
signal: AbortSignal.timeout(3000),
|
|
155
|
+
});
|
|
156
|
+
if (!owned()) break;
|
|
157
|
+
if (response.ok) {
|
|
158
|
+
const body = await response.json() as { acceptedIDs?: unknown };
|
|
159
|
+
const accepted = new Set(Array.isArray(body.acceptedIDs) ? body.acceptedIDs.filter((item): item is string => typeof item === "string") : []);
|
|
160
|
+
if (!owned()) break;
|
|
161
|
+
if (value.messageIDs.every((messageID) => accepted.has(messageID))) deleteReceiptDelivery(id);
|
|
162
|
+
else retry(id, attempts);
|
|
163
|
+
} else if (response.status === 400 || response.status === 404 || response.status === 409) deleteReceiptDelivery(id);
|
|
164
|
+
else retry(id, attempts);
|
|
165
|
+
} else {
|
|
166
|
+
const result = await recordMessageDeliveries(value.roomID, value.sessionID, value.messageIDs, {
|
|
167
|
+
membershipID: value.membershipID, receiverOwnerID: value.receiverOwnerID,
|
|
168
|
+
});
|
|
169
|
+
if (!owned()) break;
|
|
170
|
+
if (result.status === "ok" && value.messageIDs.every((messageID) => result.acceptedIDs.includes(messageID))) deleteReceiptDelivery(id);
|
|
171
|
+
else if (result.status === "membership" || result.status === "messageIDs") deleteReceiptDelivery(id);
|
|
172
|
+
else retry(id, attempts);
|
|
173
|
+
}
|
|
174
|
+
} catch { retry(id, attempts); }
|
|
175
|
+
}
|
|
176
|
+
} finally { releaseDeliveryLease(leaseKey, holder); }
|
|
177
|
+
}
|
|
178
|
+
|
|
99
179
|
const receiptFlushes = new Map<string, Promise<void>>();
|
|
100
180
|
// shortcut: cursor resets on process restart; persist it if restart storms delay backlog progress.
|
|
101
181
|
const receiptFlushCursors = new Map<string, string>();
|
|
@@ -107,7 +187,9 @@ export function flushReceiptCandidates(input: {
|
|
|
107
187
|
const key = JSON.stringify([input.destination, input.receiverOwnerID ?? ""]);
|
|
108
188
|
const running = receiptFlushes.get(key);
|
|
109
189
|
if (running) return running;
|
|
110
|
-
const task = flushOneReceiptCandidate(input, key)
|
|
190
|
+
const task = flushOneReceiptCandidate(input, key)
|
|
191
|
+
.catch(() => {})
|
|
192
|
+
.finally(() => receiptFlushes.delete(key));
|
|
111
193
|
receiptFlushes.set(key, task);
|
|
112
194
|
return task;
|
|
113
195
|
}
|
|
@@ -18,6 +18,7 @@ import type { InboxItem } from "./center-inbox.ts";
|
|
|
18
18
|
import { assertDeliveryLease } from "./session-delivery.ts";
|
|
19
19
|
import { formatTasks, taskFields, validateTaskFields, type Task } from "../agent/task-tool.ts";
|
|
20
20
|
import type { CatchUpOptions, CatchUpPage } from "../protocol/addressing.ts";
|
|
21
|
+
import { runForwardAction } from "./forward-client.ts";
|
|
21
22
|
export { queueAdmissionId } from "./queue.ts";
|
|
22
23
|
export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport.ts";
|
|
23
24
|
export type { QueueTransport, PushResult } from "./queue-transport.ts";
|
|
@@ -220,6 +221,7 @@ export async function centerAction(
|
|
|
220
221
|
receiverOwnerID?: string;
|
|
221
222
|
protocol?: "v1" | "v2";
|
|
222
223
|
joinPolicy?: "open" | "approval";
|
|
224
|
+
target?: unknown;
|
|
223
225
|
},
|
|
224
226
|
sessionID: string,
|
|
225
227
|
): Promise<string> {
|
|
@@ -396,6 +398,9 @@ export async function centerAction(
|
|
|
396
398
|
});
|
|
397
399
|
return JSON.stringify(page);
|
|
398
400
|
}
|
|
401
|
+
case "forward_targets":
|
|
402
|
+
case "forward":
|
|
403
|
+
return runForwardAction(opts, args, sessionID);
|
|
399
404
|
case "send": {
|
|
400
405
|
if (!args.roomId) {
|
|
401
406
|
return "error: roomId is required; use a room UUID from the room list, not the room name";
|