@alexsun-top/opencode-chat-room 0.7.2 → 0.7.4
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 +21 -0
- package/README.md +11 -4
- package/README.zh-CN.md +11 -4
- package/cli.ts +26 -6
- package/dist/cli.js +7804 -0
- package/package.json +19 -6
- package/plugin.ts +7 -4
- package/server/admin-auth.ts +1 -1
- package/server/admin-routes.ts +2 -2
- package/server/admin-state.ts +2 -1
- package/server/assets/chat/admin.js +43 -3
- package/server/assets/chat/announcements.js +5 -3
- package/server/assets/chat/confirm-dialog.js +12 -2
- package/server/assets/chat/create-room-dialog.js +5 -3
- package/server/assets/chat/events.js +32 -7
- package/server/assets/chat/files.js +368 -0
- package/server/assets/chat/index.js +6 -0
- package/server/assets/chat/locales/de.js +17 -1
- package/server/assets/chat/locales/es.js +17 -1
- package/server/assets/chat/locales/fr.js +17 -1
- package/server/assets/chat/locales/it.js +17 -1
- package/server/assets/chat/locales/ja.js +17 -1
- package/server/assets/chat/locales/ko.js +17 -1
- package/server/assets/chat/markdown.js +10 -3
- package/server/assets/chat/message-polling.js +61 -6
- package/server/assets/chat/message-window.js +28 -0
- package/server/assets/chat/messages.js +29 -4
- package/server/assets/chat/palette.js +384 -0
- package/server/assets/chat/rooms.js +8 -3
- package/server/assets/chat/search.js +137 -0
- package/server/assets/chat/settings.js +11 -5
- package/server/assets/chat/state.js +34 -2
- package/server/assets/code-highlight.css +2 -5
- package/server/assets/edit-room.css +77 -0
- package/server/assets/files.css +237 -0
- package/server/assets/palette.css +277 -0
- package/server/assets/responsive.css +3 -2
- package/server/assets/room-create.css +42 -43
- package/server/assets/settings.css +6 -3
- package/server/chat-server.ts +46 -29
- package/server/chat.html +129 -33
- package/server/http-server.ts +182 -0
- package/server/join-requests.ts +5 -4
- package/server/manifest.webmanifest +1 -1
- package/server/member-routes.ts +3 -3
- package/server/message-recall-routes.ts +1 -1
- package/server/newrooms.ts +4 -4
- package/server/resource-routes.ts +19 -4
- package/server/room-join.ts +8 -3
- package/server/room-payload.ts +1 -1
- package/server/sw.js +3 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +1 -1
- package/src/README.md +4 -2
- package/src/config/file-config.ts +294 -0
- package/src/rooms/resource-read.ts +2 -1
- package/src/rooms/resource-upload.ts +6 -3
- package/src/rooms/resources.ts +7 -2
- package/src/runtime/v2-plugin.ts +2 -2
- package/src/runtime/watch.ts +13 -8
- package/src/state/receiver-state.ts +3 -5
- package/src/state/sqlite-state.ts +11 -7
- package/src/state/sqlite.ts +80 -0
- package/src/state/store.ts +1 -0
- package/src/tui/app.mjs +417 -0
- package/src/tui/config.mjs +194 -0
- package/src/tui/http.mjs +103 -0
- package/src/tui/main.mjs +176 -0
- package/src/tui/messages.mjs +67 -0
- package/src/tui/palette-app.mjs +265 -0
- package/src/tui/palette.mjs +101 -0
- package/src/tui/session.mjs +40 -0
- package/src/tui/ui-content.mjs +426 -0
- package/src/tui/ui-theme.mjs +60 -0
- package/src/tui/ui-view.mjs +452 -0
- package/src/tui/ui.mjs +262 -0
- package/src/tests/announcement-board.ts +0 -186
package/skills/chatroom/SKILL.md
CHANGED
|
@@ -56,7 +56,7 @@ Discuss shared questions in the room rather than opening private dialogs. Consol
|
|
|
56
56
|
|
|
57
57
|
## Protected rooms
|
|
58
58
|
|
|
59
|
-
A room may require approval for new members. Create one with `joinPolicy: "approval"` only when the user asks to restrict a room; central mode is required. Do not create a protected room yourself unless the request explicitly assigns a human owner: only a person can own a room, so an Agent-created protected room has no human administrator to approve joins. Prefer asking a human to create it in the web UI. In such a room, `join` returns a pending request instead of membership. While pending you have no membership or inbox delivery, the web client cannot open the room, and you cannot send or poll. Never describe yourself as a member
|
|
59
|
+
A room may require approval for new members. Create one with `joinPolicy: "approval"` only when the user asks to restrict a room; central mode is required. Do not create a protected room yourself unless the request explicitly assigns a human owner: only a person can own a room, so an Agent-created protected room has no human administrator to approve joins. Prefer asking a human to create it in the web UI. In such a room, `join` returns a pending request instead of membership. While pending you have no membership or inbox delivery, the web client cannot open the room, and you cannot send or poll. Never describe yourself as a member and do not retry repeatedly; a human administrator must approve you. Once approved, the join event is unread for your session and a client with background delivery receives it in the original session context. If you are unsure or your client has no background delivery, call `join_status`; silence before approval is not rejection.
|
|
60
60
|
|
|
61
61
|
A designated management Agent uses the `admin` tool's `admin_join_requests` to list pending Agent requests, and `admin_approve_join` or `admin_deny_join` with `targetSessionID` to decide one. It can review Agent requests only; a human request belongs to a human room administrator. Do not ask the management Agent to bypass that boundary.
|
|
62
62
|
|
package/src/README.md
CHANGED
|
@@ -5,12 +5,14 @@ takes through the plugin.
|
|
|
5
5
|
|
|
6
6
|
| Folder | What lives there | Read it when |
|
|
7
7
|
| --- | --- | --- |
|
|
8
|
-
| `state/` | Persistence and the data model: `store.ts` (the room store), `sqlite-state.ts` (SQLite tables, join requests and pages), `member-state.ts`, `receiver-state.ts`, `receiver-owner.ts` | A value must survive a restart, or a query must be paged |
|
|
8
|
+
| `state/` | Persistence and the data model: `store.ts` (the room store), `sqlite-state.ts` (SQLite tables, join requests and pages), `sqlite.ts` (the `node:sqlite` adapter), `member-state.ts`, `receiver-state.ts`, `receiver-owner.ts` | A value must survive a restart, or a query must be paged |
|
|
9
9
|
| `rooms/` | The room domain: `room-service.ts` (rooms, messages, participants, join policy), `announcements.ts`, `resources.ts` (+ upload/read helpers) | You need to change what a room is or what it holds |
|
|
10
10
|
| `center/` | Talking to a remote center: `center-client.ts`, `center-inbox.ts`, `center-wake.ts`, the delivery `queue*`, `session-delivery.ts`, `reminder-client.ts`, `mentions.ts` | A message must leave this process, or a reply must come back |
|
|
11
11
|
| `agent/` | The agent-facing side: presence and receipts, the admin client and credentials, the room skill text, and the announcement tool | You are changing what an agent can do or what it is told |
|
|
12
|
+
| `config/` | The shared `chatroom.json` / JSONC / YAML loader and environment precedence used by the server and every client | You are adding a configuration field or changing its precedence |
|
|
12
13
|
| `runtime/` | Entry points and the running loop: `v1-plugin.ts`, `v2-plugin.ts`, `v2-receiver.ts`, `watch.ts`, `background.ts`, `plugin-notifications.ts` | You are changing startup, the poll loop, or host hooks |
|
|
13
|
-
| `
|
|
14
|
+
| `tui/` | The OpenTUI terminal client: `app.mjs` (headless state), `ui*.mjs` (renderables), `config.mjs`, `http.mjs`, `session.mjs`, `palette*.mjs` | You are changing the `opencode-chat-room cli` experience |
|
|
15
|
+
| `tests/` | Every `*.test.ts` under `src/`. Run one with `bun test src/tests/<name>.test.ts`; TUI tests run with `bun test src/tui/test` | You changed behaviour and need the proof |
|
|
14
16
|
|
|
15
17
|
The entry points that the host and the CLI load stay at the repository root:
|
|
16
18
|
`plugin.ts`, `cli.ts`, `index.ts`, with the HTTP server in `server/`. Join
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { parse as parseYaml } from "yaml";
|
|
5
|
+
|
|
6
|
+
// A shared, human-editable configuration file. Environment variables still
|
|
7
|
+
// win over the file so a deployment can override one value without editing it.
|
|
8
|
+
export type RoomFileConfig = {
|
|
9
|
+
url?: string;
|
|
10
|
+
token?: string;
|
|
11
|
+
server?: {
|
|
12
|
+
host?: string;
|
|
13
|
+
port?: number;
|
|
14
|
+
token?: string;
|
|
15
|
+
stateDir?: string;
|
|
16
|
+
wakeServeUrl?: string;
|
|
17
|
+
maxFileSizeMb?: number;
|
|
18
|
+
};
|
|
19
|
+
client?: {
|
|
20
|
+
url?: string;
|
|
21
|
+
token?: string;
|
|
22
|
+
participant?: string;
|
|
23
|
+
wakeServeUrl?: string;
|
|
24
|
+
delivery?: boolean;
|
|
25
|
+
deliveryIntervalMs?: number;
|
|
26
|
+
requestTimeoutMs?: number;
|
|
27
|
+
codexBin?: string;
|
|
28
|
+
};
|
|
29
|
+
p2p?: {
|
|
30
|
+
enabled?: boolean;
|
|
31
|
+
peers?: Record<string, { url: string; token?: string }>;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type ServerSettings = {
|
|
36
|
+
host: string;
|
|
37
|
+
port: string;
|
|
38
|
+
token?: string;
|
|
39
|
+
stateDir?: string;
|
|
40
|
+
wakeServeUrl: string;
|
|
41
|
+
maxFileSizeMb?: number;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type ClientSettings = {
|
|
45
|
+
url: string;
|
|
46
|
+
token: string;
|
|
47
|
+
wakeServeUrl: string;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const FILE_NAMES = ["chatroom.json", "chatroom.jsonc", "chatroom.yaml", "chatroom.yml"] as const;
|
|
51
|
+
const PEER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
|
|
52
|
+
|
|
53
|
+
function asRecord(value: unknown, where: string): Record<string, unknown> | undefined {
|
|
54
|
+
if (value === undefined) return undefined;
|
|
55
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
56
|
+
throw new Error(`chatroom config: ${where} must be an object`);
|
|
57
|
+
}
|
|
58
|
+
return value as Record<string, unknown>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function optionalString(value: unknown, where: string): string | undefined {
|
|
62
|
+
if (value === undefined) return undefined;
|
|
63
|
+
if (typeof value !== "string") throw new Error(`chatroom config: ${where} must be a string`);
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function optionalNumber(value: unknown, where: string): number | undefined {
|
|
68
|
+
if (value === undefined) return undefined;
|
|
69
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
70
|
+
throw new Error(`chatroom config: ${where} must be a finite number`);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function optionalBoolean(value: unknown, where: string): boolean | undefined {
|
|
76
|
+
if (value === undefined) return undefined;
|
|
77
|
+
if (typeof value !== "boolean") throw new Error(`chatroom config: ${where} must be true or false`);
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseServer(value: unknown): RoomFileConfig["server"] {
|
|
82
|
+
const raw = asRecord(value, "server");
|
|
83
|
+
if (!raw) return undefined;
|
|
84
|
+
const port = optionalNumber(raw.port, "server.port");
|
|
85
|
+
if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
|
|
86
|
+
throw new Error("chatroom config: server.port must be an integer from 1 to 65535");
|
|
87
|
+
}
|
|
88
|
+
const maxFileSizeMb = optionalNumber(raw.maxFileSizeMb, "server.maxFileSizeMb");
|
|
89
|
+
if (maxFileSizeMb !== undefined && maxFileSizeMb <= 0) {
|
|
90
|
+
throw new Error("chatroom config: server.maxFileSizeMb must be greater than zero");
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
host: optionalString(raw.host, "server.host"),
|
|
94
|
+
port,
|
|
95
|
+
token: optionalString(raw.token, "server.token"),
|
|
96
|
+
stateDir: optionalString(raw.stateDir, "server.stateDir"),
|
|
97
|
+
wakeServeUrl: optionalString(raw.wakeServeUrl, "server.wakeServeUrl"),
|
|
98
|
+
maxFileSizeMb,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function parseClient(value: unknown): RoomFileConfig["client"] {
|
|
103
|
+
const raw = asRecord(value, "client");
|
|
104
|
+
if (!raw) return undefined;
|
|
105
|
+
const deliveryIntervalMs = optionalNumber(raw.deliveryIntervalMs, "client.deliveryIntervalMs");
|
|
106
|
+
if (deliveryIntervalMs !== undefined && deliveryIntervalMs < 1000) {
|
|
107
|
+
throw new Error("chatroom config: client.deliveryIntervalMs must be at least 1000");
|
|
108
|
+
}
|
|
109
|
+
const requestTimeoutMs = optionalNumber(raw.requestTimeoutMs, "client.requestTimeoutMs");
|
|
110
|
+
if (requestTimeoutMs !== undefined && requestTimeoutMs < 1000) {
|
|
111
|
+
throw new Error("chatroom config: client.requestTimeoutMs must be at least 1000");
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
url: optionalString(raw.url, "client.url"),
|
|
115
|
+
token: optionalString(raw.token, "client.token"),
|
|
116
|
+
participant: optionalString(raw.participant, "client.participant"),
|
|
117
|
+
wakeServeUrl: optionalString(raw.wakeServeUrl, "client.wakeServeUrl"),
|
|
118
|
+
delivery: optionalBoolean(raw.delivery, "client.delivery"),
|
|
119
|
+
deliveryIntervalMs,
|
|
120
|
+
requestTimeoutMs,
|
|
121
|
+
codexBin: optionalString(raw.codexBin, "client.codexBin"),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function parsePeers(value: unknown): RoomFileConfig["p2p"] {
|
|
126
|
+
const raw = asRecord(value, "p2p");
|
|
127
|
+
if (!raw) return undefined;
|
|
128
|
+
const enabled = optionalBoolean(raw.enabled, "p2p.enabled");
|
|
129
|
+
const peersRaw = asRecord(raw.peers, "p2p.peers");
|
|
130
|
+
const peers: Record<string, { url: string; token?: string }> = {};
|
|
131
|
+
for (const [name, entry] of Object.entries(peersRaw ?? {})) {
|
|
132
|
+
if (!PEER_NAME.test(name)) {
|
|
133
|
+
throw new Error(`chatroom config: p2p.peers.${name} is not a valid peer name`);
|
|
134
|
+
}
|
|
135
|
+
const peer = asRecord(entry, `p2p.peers.${name}`);
|
|
136
|
+
const url = optionalString(peer?.url, `p2p.peers.${name}.url`);
|
|
137
|
+
if (!url || !/^https?:\/\/[^/]+/.test(url)) {
|
|
138
|
+
throw new Error(`chatroom config: p2p.peers.${name}.url must be an http(s) origin`);
|
|
139
|
+
}
|
|
140
|
+
peers[name] = { url: url.replace(/\/+$/, ""), token: optionalString(peer?.token, `p2p.peers.${name}.token`) };
|
|
141
|
+
}
|
|
142
|
+
return { enabled, peers };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function parseRoomConfig(value: unknown): RoomFileConfig {
|
|
146
|
+
const raw = asRecord(value, "root");
|
|
147
|
+
if (!raw) return {};
|
|
148
|
+
return {
|
|
149
|
+
url: optionalString(raw.url, "url"),
|
|
150
|
+
token: optionalString(raw.token, "token"),
|
|
151
|
+
server: parseServer(raw.server),
|
|
152
|
+
client: parseClient(raw.client),
|
|
153
|
+
p2p: parsePeers(raw.p2p),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Remove comments and trailing commas without touching quoted strings. */
|
|
158
|
+
function stripJsonc(source: string): string {
|
|
159
|
+
let out = "";
|
|
160
|
+
let quote = "";
|
|
161
|
+
let escaped = false;
|
|
162
|
+
let comma = -1;
|
|
163
|
+
for (let i = 0; i < source.length; i++) {
|
|
164
|
+
const char = source[i]!;
|
|
165
|
+
const next = source[i + 1];
|
|
166
|
+
if (quote) {
|
|
167
|
+
out += char;
|
|
168
|
+
if (escaped) escaped = false;
|
|
169
|
+
else if (char === "\\") escaped = true;
|
|
170
|
+
else if (char === quote) quote = "";
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (char === '"') {
|
|
174
|
+
quote = char;
|
|
175
|
+
comma = -1;
|
|
176
|
+
out += char;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (char === "/" && next === "/") {
|
|
180
|
+
while (i < source.length && source[i] !== "\n") i++;
|
|
181
|
+
out += "\n";
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (char === "/" && next === "*") {
|
|
185
|
+
i += 2;
|
|
186
|
+
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i++;
|
|
187
|
+
i++;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (char === ",") {
|
|
191
|
+
comma = out.length;
|
|
192
|
+
out += char;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (char === "}" || char === "]") {
|
|
196
|
+
if (comma >= 0) {
|
|
197
|
+
out = out.slice(0, comma) + out.slice(comma + 1);
|
|
198
|
+
comma = -1;
|
|
199
|
+
}
|
|
200
|
+
out += char;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (!/\s/.test(char)) comma = -1;
|
|
204
|
+
out += char;
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function parseFile(file: string): RoomFileConfig {
|
|
210
|
+
let text: string;
|
|
211
|
+
try {
|
|
212
|
+
text = readFileSync(file, "utf8");
|
|
213
|
+
} catch {
|
|
214
|
+
throw new Error(`chatroom config: cannot read ${file}`);
|
|
215
|
+
}
|
|
216
|
+
const extension = path.extname(file).toLowerCase();
|
|
217
|
+
try {
|
|
218
|
+
if (extension === ".yaml" || extension === ".yml") return parseRoomConfig(parseYaml(text));
|
|
219
|
+
if (extension === ".jsonc") return parseRoomConfig(JSON.parse(stripJsonc(text)));
|
|
220
|
+
if (extension === ".json") return parseRoomConfig(JSON.parse(text));
|
|
221
|
+
try {
|
|
222
|
+
return parseRoomConfig(JSON.parse(text));
|
|
223
|
+
} catch {
|
|
224
|
+
return parseRoomConfig(parseYaml(text));
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (error instanceof SyntaxError || (error as Error)?.name === "YAMLParseError") {
|
|
228
|
+
// Never include parser source text: a malformed file may contain a token.
|
|
229
|
+
throw new Error(`chatroom config: ${file} is not valid JSON/YAML`);
|
|
230
|
+
}
|
|
231
|
+
throw error;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function candidateDirs(env: NodeJS.ProcessEnv, cwd: string): string[] {
|
|
236
|
+
const home = env.HOME || os.homedir();
|
|
237
|
+
const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
|
|
238
|
+
return [...new Set([cwd, path.join(configHome, "chatroom")])];
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Resolve the config path; explicit CHAT_ROOM_CONFIG must exist. */
|
|
242
|
+
export function findRoomConfigFile(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): string | null {
|
|
243
|
+
const explicit = env.CHAT_ROOM_CONFIG?.trim();
|
|
244
|
+
if (explicit) {
|
|
245
|
+
const file = explicit.startsWith("~/") ? path.join(env.HOME || os.homedir(), explicit.slice(2)) : path.resolve(cwd, explicit);
|
|
246
|
+
if (!existsSync(file)) throw new Error(`chatroom config: CHAT_ROOM_CONFIG file does not exist: ${file}`);
|
|
247
|
+
return file;
|
|
248
|
+
}
|
|
249
|
+
for (const dir of candidateDirs(env, cwd)) {
|
|
250
|
+
for (const name of FILE_NAMES) {
|
|
251
|
+
const file = path.join(dir, name);
|
|
252
|
+
if (existsSync(file)) return file;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Read the first found chatroom.json(c)/yaml/yml, or null when absent. */
|
|
259
|
+
export function loadRoomConfig(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): RoomFileConfig | null {
|
|
260
|
+
const file = findRoomConfigFile(env, cwd);
|
|
261
|
+
return file ? parseFile(file) : null;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function envValue(env: NodeJS.ProcessEnv, key: string): string | undefined {
|
|
265
|
+
const value = env[key];
|
|
266
|
+
return value === undefined || value === "" ? undefined : value;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Environment overrides the file; server.token/client.token are not logged. */
|
|
270
|
+
export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.ProcessEnv = process.env): ServerSettings {
|
|
271
|
+
const port = envValue(env, "CHAT_ROOM_SERVER_PORT") ?? envValue(env, "PORT") ?? String(file?.server?.port ?? 4399);
|
|
272
|
+
const maxRaw = envValue(env, "CHAT_ROOM_MAX_FILE_SIZE_MB");
|
|
273
|
+
const maxFileSizeMb = maxRaw === undefined ? file?.server?.maxFileSizeMb : Number(maxRaw);
|
|
274
|
+
if (maxFileSizeMb !== undefined && (!Number.isFinite(maxFileSizeMb) || maxFileSizeMb <= 0)) {
|
|
275
|
+
throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
host: envValue(env, "CHAT_ROOM_SERVER_HOST") ?? envValue(env, "HOST") ?? file?.server?.host ?? "0.0.0.0",
|
|
279
|
+
port,
|
|
280
|
+
token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.server?.token ?? file?.token,
|
|
281
|
+
stateDir: envValue(env, "CHAT_ROOM_STATE_DIR") ?? file?.server?.stateDir,
|
|
282
|
+
wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.server?.wakeServeUrl ?? "",
|
|
283
|
+
maxFileSizeMb,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Environment overrides the file; client.url/token fall back to top-level. */
|
|
288
|
+
export function resolveClientSettings(file: RoomFileConfig | null, env: NodeJS.ProcessEnv = process.env): ClientSettings {
|
|
289
|
+
return {
|
|
290
|
+
url: envValue(env, "CHAT_ROOM_SERVER_URL") ?? file?.client?.url ?? file?.url ?? "",
|
|
291
|
+
token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.client?.token ?? file?.token ?? "",
|
|
292
|
+
wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.client?.wakeServeUrl ?? file?.server?.wakeServeUrl ?? "",
|
|
293
|
+
};
|
|
294
|
+
}
|
|
@@ -9,7 +9,8 @@ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
|
|
|
9
9
|
const limit = 512 * 1024 * 1024;
|
|
10
10
|
|
|
11
11
|
export class ResourceReadError extends Error {
|
|
12
|
-
|
|
12
|
+
readonly code: "invalid" | "permission_denied" | "size_limit" | "not_found" | "aborted" | "network" | "save_failed";
|
|
13
|
+
constructor(code: "invalid" | "permission_denied" | "size_limit" | "not_found" | "aborted" | "network" | "save_failed", message: string) { super(message); this.code = code; }
|
|
13
14
|
}
|
|
14
15
|
export function resourceReadFailure(error: unknown): string {
|
|
15
16
|
return error instanceof ResourceReadError ? error.message : "resource read failed; verify roomId and resourceId, check the server connection, then retry";
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
1
2
|
import { realpath, stat } from "node:fs/promises";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import { Readable } from "node:stream";
|
|
3
5
|
import type { Resource } from "./resources.ts";
|
|
4
6
|
|
|
5
7
|
type PermissionContext = { directory: string; worktree?: string; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> };
|
|
@@ -32,13 +34,14 @@ export async function uploadAgentResource(opts: UploadOptions, roomID: string, f
|
|
|
32
34
|
};
|
|
33
35
|
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
|
|
34
36
|
const response = await fetch(`${opts.center}/rooms/${encodeURIComponent(roomID)}/resources`, {
|
|
35
|
-
method: "POST", headers,
|
|
37
|
+
method: "POST", headers,
|
|
38
|
+
body: Readable.toWeb(createReadStream(actual)) as unknown as BodyInit,
|
|
36
39
|
redirect: "error",
|
|
37
40
|
// Large transfers need more than the JSON client's ten-second deadline.
|
|
38
41
|
signal: AbortSignal.timeout(30 * 60_000),
|
|
39
|
-
//
|
|
42
|
+
// Streaming request bodies require half-duplex framing in fetch.
|
|
40
43
|
duplex: "half",
|
|
41
|
-
});
|
|
44
|
+
} as RequestInit & { duplex: "half" });
|
|
42
45
|
const data = await response.json().catch(() => ({})) as { resource?: Resource; error?: string };
|
|
43
46
|
if (!response.ok || !data.resource) throw new Error(data.error ?? `upload failed (${response.status})`);
|
|
44
47
|
return `${JSON.stringify(data.resource)}\n[[resource:${data.resource.id}]]\nThe upload alone is invisible. To display this attachment, include the marker above unchanged in a send message, outside backticks or code blocks.`;
|
package/src/rooms/resources.ts
CHANGED
|
@@ -2,11 +2,12 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { promises as fs } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { databasePath, readState } from "../state/store.ts";
|
|
5
|
-
import { getResource, putResource, removeResource, type StoredResource } from "../state/sqlite-state.ts";
|
|
5
|
+
import { getResource, listResources, putResource, removeResource, type StoredResource } from "../state/sqlite-state.ts";
|
|
6
6
|
|
|
7
7
|
export type Resource = StoredResource;
|
|
8
8
|
export class ResourceError extends Error {
|
|
9
|
-
|
|
9
|
+
readonly status: number;
|
|
10
|
+
constructor(status: number, message: string) { super(message); this.status = status; }
|
|
10
11
|
}
|
|
11
12
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
12
13
|
const storageDir = () => path.join(path.dirname(databasePath()), "resources");
|
|
@@ -133,6 +134,10 @@ export function resourcePath(resource: Pick<Resource, "id" | "roomID">): string
|
|
|
133
134
|
if (!uuid.test(resource.roomID) || !uuid.test(resource.id)) throw new ResourceError(404, "resource not found");
|
|
134
135
|
return path.join(roomDirectory(resource.roomID), resource.id);
|
|
135
136
|
}
|
|
137
|
+
export async function listRoomResources(roomID: string, limit = 500, offset = 0): Promise<{ items: Resource[]; total: number }> {
|
|
138
|
+
if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
|
|
139
|
+
return listResources(databasePath(), roomID, limit, offset);
|
|
140
|
+
}
|
|
136
141
|
export async function findResource(roomID: string, id: string): Promise<Resource | undefined> {
|
|
137
142
|
if (!uuid.test(id)) return undefined;
|
|
138
143
|
return getResource(databasePath(), roomID, id);
|
package/src/runtime/v2-plugin.ts
CHANGED
|
@@ -81,7 +81,7 @@ export function createV2Setup(deps: {
|
|
|
81
81
|
});
|
|
82
82
|
toolRegistration = await context.tool.transform((editor) => editor.add({
|
|
83
83
|
name: "room",
|
|
84
|
-
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
|
|
84
|
+
description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; list members and announcements; manage reminders. In an approval room join returns pending: you are not a member yet; call join_status to check whether an administrator approved you. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
|
|
85
85
|
options: { codemode: false },
|
|
86
86
|
input: roomSchema(),
|
|
87
87
|
execute: async (args, toolContext) => {
|
|
@@ -169,7 +169,7 @@ export function createV2Setup(deps: {
|
|
|
169
169
|
|
|
170
170
|
export function roomSchema() {
|
|
171
171
|
return z.object({
|
|
172
|
-
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
|
|
172
|
+
action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
|
|
173
173
|
name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
|
|
174
174
|
roomId: z.string().optional(),
|
|
175
175
|
resourceId: z.string().optional(),
|
package/src/runtime/watch.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
1
2
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
3
|
import { realpathSync } from "node:fs";
|
|
3
4
|
import { appendFile, chmod, link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
@@ -10,12 +11,14 @@ import { receiverOwnerID } from "../state/receiver-owner.ts";
|
|
|
10
11
|
import { claimWatcher, closeReceiverState, releaseWatcherClaim, receiverStateDirectory, watcherProcessMayExist } from "../state/receiver-state.ts";
|
|
11
12
|
import { databasePath, loadRegistry } from "../state/store.ts";
|
|
12
13
|
import { request, type CenterOpts } from "../center/center-client.ts";
|
|
14
|
+
import { loadRoomConfig, resolveClientSettings } from "../config/file-config.ts";
|
|
13
15
|
import { assertDeliveryLease } from "../center/session-delivery.ts";
|
|
14
16
|
import type { QueueTransport } from "../center/queue-transport.ts";
|
|
15
17
|
import { pollOwnedSessions } from "./v2-receiver.ts";
|
|
16
|
-
import { pollKnownSessions } from "../../plugin";
|
|
18
|
+
import { pollKnownSessions } from "../../plugin.ts";
|
|
17
19
|
import { locallyOwnedSessions, reportAgentPresence } from "../agent/agent-presence.ts";
|
|
18
20
|
import { flushReceiptCandidates, receiptDestination } from "../agent/agent-receipts.ts";
|
|
21
|
+
import { startServer } from "../../server/http-server.ts";
|
|
19
22
|
|
|
20
23
|
type WatchRecord = { phase: "starting" | "running"; token: string; nonce: string; instanceID: string; pid: number; port?: number; createdAt?: number };
|
|
21
24
|
function canonicalPath(value: string): string {
|
|
@@ -33,8 +36,9 @@ function canonicalPath(value: string): string {
|
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
38
|
}
|
|
39
|
+
const clientSettings = () => resolveClientSettings(loadRoomConfig());
|
|
36
40
|
const profile = () => {
|
|
37
|
-
const center =
|
|
41
|
+
const center = clientSettings().url;
|
|
38
42
|
const home = process.env.HOME || os.homedir();
|
|
39
43
|
let target = `standalone:${canonicalPath(databasePath())}`;
|
|
40
44
|
if (center) { try { const url = new URL(center); target = `${url.origin}${url.pathname}`; } catch { target = "invalid-center"; } }
|
|
@@ -136,9 +140,10 @@ export async function watcherSweep(deps: WatchSweepDeps = defaultSweepDeps()): P
|
|
|
136
140
|
}
|
|
137
141
|
|
|
138
142
|
function defaultSweepDeps(): WatchSweepDeps {
|
|
143
|
+
const settings = clientSettings();
|
|
139
144
|
const center: CenterOpts = {
|
|
140
|
-
center:
|
|
141
|
-
token:
|
|
145
|
+
center: settings.url,
|
|
146
|
+
token: settings.token,
|
|
142
147
|
};
|
|
143
148
|
return {
|
|
144
149
|
discover: discoverCompatibleRegisteredHost,
|
|
@@ -308,7 +313,7 @@ export async function runWatcher(): Promise<void> {
|
|
|
308
313
|
let shuttingDown = false;
|
|
309
314
|
let interval: ReturnType<typeof setInterval> | undefined;
|
|
310
315
|
let activeSweep: Promise<unknown> | undefined;
|
|
311
|
-
let server: ReturnType<typeof
|
|
316
|
+
let server: Awaited<ReturnType<typeof startServer>> | undefined;
|
|
312
317
|
let finish!: () => void;
|
|
313
318
|
const done = new Promise<void>((resolve) => { finish = resolve; });
|
|
314
319
|
const stop = async () => {
|
|
@@ -319,14 +324,14 @@ export async function runWatcher(): Promise<void> {
|
|
|
319
324
|
process.off("SIGTERM", onSignal);
|
|
320
325
|
await activeSweep?.catch(() => {});
|
|
321
326
|
await logEvent("stopped");
|
|
322
|
-
server?.
|
|
327
|
+
await server?.close();
|
|
323
328
|
await removeRecord(token!, nonce!);
|
|
324
329
|
try { releaseWatcherClaim(profile(), instanceID!); } catch { /* Dead process detection reclaims the row next time. */ }
|
|
325
330
|
closeReceiverState();
|
|
326
331
|
finish();
|
|
327
332
|
};
|
|
328
333
|
const onSignal = () => { void stop(); };
|
|
329
|
-
const controlServer =
|
|
334
|
+
const controlServer = await startServer({
|
|
330
335
|
hostname: "127.0.0.1", port: 0,
|
|
331
336
|
fetch(request) {
|
|
332
337
|
const url = new URL(request.url);
|
|
@@ -349,7 +354,7 @@ export async function runWatcher(): Promise<void> {
|
|
|
349
354
|
try {
|
|
350
355
|
await saveRecord({ phase: "running", token, nonce, instanceID: instanceID!, pid: process.pid, port: controlServer.port, createdAt });
|
|
351
356
|
} catch (error) {
|
|
352
|
-
controlServer.
|
|
357
|
+
await controlServer.close();
|
|
353
358
|
await removeRecord(token, nonce);
|
|
354
359
|
releaseWatcherClaim(profile(), instanceID!);
|
|
355
360
|
throw error;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Database } from "bun:sqlite";
|
|
2
1
|
import { chmodSync, mkdirSync } from "node:fs";
|
|
3
2
|
import os from "node:os";
|
|
4
3
|
import path from "node:path";
|
|
4
|
+
import { Database, isBusyError } from "./sqlite.ts";
|
|
5
5
|
|
|
6
6
|
const databases = new Map<string, Database>();
|
|
7
7
|
const pause = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
@@ -14,8 +14,7 @@ function initialize(db: Database): void {
|
|
|
14
14
|
return;
|
|
15
15
|
} catch (error) {
|
|
16
16
|
try { db.exec("ROLLBACK"); } catch { /* No transaction remained open. */ }
|
|
17
|
-
|
|
18
|
-
if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
|
|
17
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
19
18
|
pause(Math.min(20 * 2 ** attempt, 250));
|
|
20
19
|
}
|
|
21
20
|
}
|
|
@@ -78,8 +77,7 @@ function immediate<T>(fn: (db: Database) => T): T {
|
|
|
78
77
|
for (let attempt = 0; ; attempt++) {
|
|
79
78
|
try { return db.transaction(() => fn(db)).immediate(); }
|
|
80
79
|
catch (error) {
|
|
81
|
-
|
|
82
|
-
if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
|
|
80
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
83
81
|
pause(Math.min(20 * 2 ** attempt, 250));
|
|
84
82
|
}
|
|
85
83
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Database } from "bun:sqlite";
|
|
2
1
|
import { randomUUID } from "node:crypto";
|
|
3
2
|
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
3
|
import path from "node:path";
|
|
@@ -6,6 +5,7 @@ import RoomService, { type Message, type Room, type Participant } from "../rooms
|
|
|
6
5
|
import type { MessageReceipt, PresenceReport, ReceiptEvidence, ReceiptIdentity, ReceiptWriteResult, Registry, RegistryEntry } from "./store.ts";
|
|
7
6
|
import { presenceOwnerMatches, receiptOwnerMatches } from "./member-state.ts";
|
|
8
7
|
import { isRoomAdmin } from "./roles.ts";
|
|
8
|
+
import { Database, isBusyError } from "./sqlite.ts";
|
|
9
9
|
|
|
10
10
|
type State = { rooms: Room[]; registry: Registry };
|
|
11
11
|
type Page<T> = { items: T[]; hasMore: boolean };
|
|
@@ -91,7 +91,7 @@ async function initialize(file: string): Promise<Database> {
|
|
|
91
91
|
db.exec("PRAGMA busy_timeout=50;");
|
|
92
92
|
return db;
|
|
93
93
|
} catch (error) {
|
|
94
|
-
if (!
|
|
94
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
95
95
|
await pause(Math.min(20 * 2 ** attempt, 250));
|
|
96
96
|
}
|
|
97
97
|
}
|
|
@@ -131,6 +131,14 @@ export async function putResource(file: string, resource: StoredResource): Promi
|
|
|
131
131
|
return true;
|
|
132
132
|
});
|
|
133
133
|
}
|
|
134
|
+
export async function listResources(file: string, roomID: string, limit = 500, offset = 0): Promise<{ items: StoredResource[]; total: number }> {
|
|
135
|
+
const db = await initialize(file);
|
|
136
|
+
const items = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?")
|
|
137
|
+
.all(roomID, limit, offset) as StoredResource[];
|
|
138
|
+
const total = Number((db.query("SELECT COUNT(*) AS count FROM resources WHERE room_id=?").get(roomID) as { count: number } | null)?.count ?? 0);
|
|
139
|
+
return { items, total };
|
|
140
|
+
}
|
|
141
|
+
|
|
134
142
|
export async function getResource(file: string, roomID: string, id: string): Promise<StoredResource | undefined> {
|
|
135
143
|
const db = await openStateDatabase(file);
|
|
136
144
|
const row = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? AND id=?")
|
|
@@ -203,16 +211,12 @@ function readLegacy(file: string): unknown | undefined {
|
|
|
203
211
|
}
|
|
204
212
|
|
|
205
213
|
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
206
|
-
function isBusy(error: unknown): boolean {
|
|
207
|
-
const err = error as { code?: string; message?: string };
|
|
208
|
-
return err.code === "SQLITE_BUSY" || err.code === "SQLITE_LOCKED" || /database is locked/i.test(err.message ?? "");
|
|
209
|
-
}
|
|
210
214
|
|
|
211
215
|
async function immediate<T>(db: Database, fn: () => T): Promise<T> {
|
|
212
216
|
for (let attempt = 0; ; attempt++) {
|
|
213
217
|
try { return db.transaction(fn).immediate(); }
|
|
214
218
|
catch (error) {
|
|
215
|
-
if (!
|
|
219
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
216
220
|
await pause(Math.min(20 * 2 ** attempt, 250));
|
|
217
221
|
}
|
|
218
222
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { DatabaseSync, type StatementSync } from "node:sqlite";
|
|
2
|
+
|
|
3
|
+
// The subset of bun:sqlite that this codebase uses, backed by node:sqlite so the
|
|
4
|
+
// same synchronous driver runs on Node, Bun and Deno.
|
|
5
|
+
export type SQLQueryBindings = null | number | bigint | string | boolean | Uint8Array | undefined;
|
|
6
|
+
export type RunResult = { changes: number; lastInsertRowid: number };
|
|
7
|
+
type RawBindings = Array<null | number | bigint | string | Uint8Array>;
|
|
8
|
+
|
|
9
|
+
// bun:sqlite binds booleans as 1/0 and undefined as NULL; node:sqlite rejects both.
|
|
10
|
+
function bindings(params: SQLQueryBindings[]): RawBindings {
|
|
11
|
+
let values: SQLQueryBindings[] | undefined;
|
|
12
|
+
for (let index = 0; index < params.length; index++) {
|
|
13
|
+
const value = params[index];
|
|
14
|
+
if (value === undefined || typeof value === "boolean") {
|
|
15
|
+
values ??= params.slice();
|
|
16
|
+
values[index] = value === undefined ? null : value ? 1 : 0;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return (values ?? params) as RawBindings;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class Statement {
|
|
23
|
+
readonly #statement: StatementSync;
|
|
24
|
+
constructor(statement: StatementSync) { this.#statement = statement; }
|
|
25
|
+
all(...params: SQLQueryBindings[]): unknown[] {
|
|
26
|
+
return this.#statement.all(...bindings(params));
|
|
27
|
+
}
|
|
28
|
+
// bun:sqlite returns null for a missing row, node:sqlite returns undefined.
|
|
29
|
+
get(...params: SQLQueryBindings[]): unknown {
|
|
30
|
+
return this.#statement.get(...bindings(params)) ?? null;
|
|
31
|
+
}
|
|
32
|
+
run(...params: SQLQueryBindings[]): RunResult {
|
|
33
|
+
const result = this.#statement.run(...bindings(params));
|
|
34
|
+
return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type Transaction<T> = (() => T) & { deferred(): T; immediate(): T };
|
|
39
|
+
|
|
40
|
+
export class Database {
|
|
41
|
+
readonly #db: DatabaseSync;
|
|
42
|
+
#savepoints = 0;
|
|
43
|
+
|
|
44
|
+
// node:sqlite always creates a missing file, matching the default Bun options.
|
|
45
|
+
constructor(file: string, _options?: { create?: boolean }) {
|
|
46
|
+
this.#db = new DatabaseSync(file);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
query(sql: string): Statement { return new Statement(this.#db.prepare(sql)); }
|
|
50
|
+
exec(sql: string): void { this.#db.exec(sql); }
|
|
51
|
+
|
|
52
|
+
transaction<T>(fn: () => T): Transaction<T> {
|
|
53
|
+
const run = (begin: string) => this.#run(begin, fn);
|
|
54
|
+
return Object.assign(() => run("BEGIN"), { deferred: () => run("BEGIN"), immediate: () => run("BEGIN IMMEDIATE") });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
close(): void { this.#db.close(); }
|
|
58
|
+
|
|
59
|
+
#run<T>(begin: string, fn: () => T): T {
|
|
60
|
+
// Nested calls become savepoints, like bun:sqlite transactions.
|
|
61
|
+
const nested = this.#db.isTransaction;
|
|
62
|
+
const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
|
|
63
|
+
this.#db.exec(nested ? `SAVEPOINT ${savepoint}` : begin);
|
|
64
|
+
try {
|
|
65
|
+
const result = fn();
|
|
66
|
+
this.#db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
|
|
67
|
+
return result;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
try { this.#db.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK"); } catch { /* keep the original error */ }
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function isBusyError(error: unknown): boolean {
|
|
76
|
+
const err = error as { code?: string; errcode?: number; message?: string } | null;
|
|
77
|
+
if (!err) return false;
|
|
78
|
+
if (typeof err.errcode === "number" && ((err.errcode & 0xff) === 5 || (err.errcode & 0xff) === 6)) return true;
|
|
79
|
+
return /SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || /database (?:is|table is) locked/i.test(err.message ?? "");
|
|
80
|
+
}
|