@alexsun-top/opencode-chat-room 0.7.8 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/LICENSE +21 -0
  3. package/README.md +77 -36
  4. package/README.zh-CN.md +82 -41
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +6905 -2764
  7. package/package.json +33 -3
  8. package/packages/chat-room-channeld/README.md +315 -0
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
  10. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  11. package/packages/chat-room-channeld/src/adapter.ts +509 -0
  12. package/packages/chat-room-channeld/src/cli.ts +124 -0
  13. package/packages/chat-room-channeld/src/config.ts +269 -0
  14. package/packages/chat-room-channeld/src/delivery.ts +163 -0
  15. package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
  16. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  17. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  18. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  19. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  20. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  21. package/packages/chat-room-channeld/src/framing.ts +128 -0
  22. package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
  23. package/packages/chat-room-channeld/src/host.ts +627 -0
  24. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  25. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  26. package/packages/chat-room-channeld/src/log.ts +26 -0
  27. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  28. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  29. package/packages/chat-room-channeld/src/published.ts +37 -0
  30. package/packages/chat-room-channeld/src/rules.ts +127 -0
  31. package/packages/chat-room-channeld/src/state.ts +502 -0
  32. package/packages/chat-room-channeld/src/stats.ts +209 -0
  33. package/plugin.ts +22 -5
  34. package/server/addressing-routes.ts +130 -0
  35. package/server/admin-state.ts +13 -13
  36. package/server/app.ts +95 -0
  37. package/server/assets/NOTICE.txt +3 -2
  38. package/server/assets/SHIKI-LICENSE +22 -0
  39. package/server/assets/base.css +24 -10
  40. package/server/assets/chat/announcements.js +70 -7
  41. package/server/assets/chat/doc-preview.js +187 -39
  42. package/server/assets/chat/events.js +3 -0
  43. package/server/assets/chat/files.js +46 -4
  44. package/server/assets/chat/forward.js +69 -0
  45. package/server/assets/chat/index.js +4 -0
  46. package/server/assets/chat/integration-editor.js +163 -0
  47. package/server/assets/chat/integration-values.js +124 -0
  48. package/server/assets/chat/integrations.js +498 -0
  49. package/server/assets/chat/locales/de.js +45 -4
  50. package/server/assets/chat/locales/es.js +45 -4
  51. package/server/assets/chat/locales/fr.js +45 -4
  52. package/server/assets/chat/locales/it.js +45 -4
  53. package/server/assets/chat/locales/ja.js +45 -4
  54. package/server/assets/chat/locales/ko.js +45 -4
  55. package/server/assets/chat/markdown-footnotes.js +115 -0
  56. package/server/assets/chat/markdown.js +46 -43
  57. package/server/assets/chat/messages.js +5 -5
  58. package/server/assets/chat/office-preview.js +69 -0
  59. package/server/assets/chat/palette.js +1 -1
  60. package/server/assets/chat/panels.js +36 -0
  61. package/server/assets/chat/recall.js +58 -7
  62. package/server/assets/chat/receipts.js +15 -3
  63. package/server/assets/chat/reminders.js +69 -8
  64. package/server/assets/chat/replies.js +7 -1
  65. package/server/assets/chat/resource-format.js +11 -0
  66. package/server/assets/chat/settings.js +30 -2
  67. package/server/assets/chat/shiki.js +87 -0
  68. package/server/assets/chat/side-pane.js +9 -3
  69. package/server/assets/chat/state.js +107 -11
  70. package/server/assets/chat/system-events.js +32 -0
  71. package/server/assets/chat/system-messages.js +23 -12
  72. package/server/assets/chat/task-row.js +0 -6
  73. package/server/assets/chat/tasks.js +121 -33
  74. package/server/assets/code-highlight.css +74 -62
  75. package/server/assets/conversation.css +126 -25
  76. package/server/assets/doc-preview.css +36 -3
  77. package/server/assets/files.css +5 -0
  78. package/server/assets/fluent-icons.svg +2 -0
  79. package/server/assets/monaco/LICENSE +21 -0
  80. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  81. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  82. package/server/assets/monaco/editor.worker.js +45 -0
  83. package/server/assets/monaco/integration-rules.css +1 -0
  84. package/server/assets/monaco/integration-rules.js +1297 -0
  85. package/server/assets/monaco/json.worker.js +77 -0
  86. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  87. package/server/assets/office/docx.bundle.js +33 -0
  88. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  89. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  90. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  91. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  92. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  93. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  94. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  95. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  96. package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
  97. package/server/assets/office/pptx.bundle.js +104 -0
  98. package/server/assets/office/xlsx.bundle.js +141 -0
  99. package/server/assets/recall.css +5 -4
  100. package/server/assets/responsive.css +52 -8
  101. package/server/assets/settings.css +73 -1
  102. package/server/assets/shiki.bundle.js +152 -0
  103. package/server/assets/tasks.css +57 -7
  104. package/server/channel-integration.ts +519 -0
  105. package/server/channel-settings.ts +77 -0
  106. package/server/channels.ts +557 -0
  107. package/server/chat-server.ts +33 -558
  108. package/server/chat.html +195 -22
  109. package/server/http-server.ts +3 -182
  110. package/server/resource-routes.ts +16 -16
  111. package/server/routes/inbox.ts +100 -0
  112. package/server/routes/pages.ts +83 -0
  113. package/server/routes/questions.ts +39 -0
  114. package/server/routes/room-actions.ts +162 -0
  115. package/server/routes/rooms.ts +160 -0
  116. package/server/startup.ts +84 -0
  117. package/server/sw.js +5 -2
  118. package/server/task-routes.ts +1 -1
  119. package/skills/chatroom/SKILL.md +1 -1
  120. package/src/center/center-client.ts +71 -1
  121. package/src/config/file-config.ts +29 -42
  122. package/src/platform/http-server.ts +182 -0
  123. package/src/protocol/addressing.ts +21 -0
  124. package/src/protocol/config.ts +58 -0
  125. package/src/protocol/room.ts +51 -0
  126. package/src/rooms/resources.ts +26 -16
  127. package/src/rooms/room-service.ts +2 -48
  128. package/src/rooms/storage.ts +329 -0
  129. package/src/rooms/tasks.ts +21 -5
  130. package/src/runtime/v2-plugin.ts +8 -2
  131. package/src/runtime/watch.ts +4 -3
  132. package/src/state/pg-database.ts +183 -0
  133. package/src/state/pg-migrate.ts +175 -0
  134. package/src/state/pg-sql.mjs +175 -0
  135. package/src/state/pg-worker.mjs +148 -0
  136. package/src/state/sqlite-announcements.ts +25 -0
  137. package/src/state/sqlite-database.ts +121 -0
  138. package/src/state/sqlite-legacy.ts +90 -0
  139. package/src/state/sqlite-members.ts +155 -0
  140. package/src/state/sqlite-messages.ts +288 -0
  141. package/src/state/sqlite-resources.ts +39 -0
  142. package/src/state/sqlite-rooms.ts +87 -0
  143. package/src/state/sqlite-schema.ts +80 -0
  144. package/src/state/sqlite-state-store.ts +33 -0
  145. package/src/state/sqlite-state.ts +15 -866
  146. package/src/state/sqlite-tasks.ts +65 -0
  147. package/src/state/sqlite-transaction.ts +13 -0
  148. package/src/state/sqlite.ts +21 -1
  149. package/src/state/store.ts +13 -3
  150. package/src/tui/app.mjs +32 -19
  151. package/src/tui/config.mjs +12 -4
  152. package/src/tui/http.mjs +16 -2
  153. package/src/tui/i18n.mjs +38 -0
  154. package/src/tui/info-app.mjs +50 -51
  155. package/src/tui/info-content.mjs +79 -44
  156. package/src/tui/join-app.mjs +9 -9
  157. package/src/tui/locales/en.mjs +349 -0
  158. package/src/tui/locales/zh-CN.mjs +349 -0
  159. package/src/tui/main.mjs +85 -37
  160. package/src/tui/markdown.mjs +3 -2
  161. package/src/tui/mentions.mjs +3 -1
  162. package/src/tui/message-app.mjs +22 -21
  163. package/src/tui/message-view.mjs +2 -1
  164. package/src/tui/palette-app.mjs +9 -8
  165. package/src/tui/palette.mjs +30 -24
  166. package/src/tui/prefs.mjs +92 -0
  167. package/src/tui/reminder-app.mjs +18 -17
  168. package/src/tui/room-settings-app.mjs +30 -28
  169. package/src/tui/settings-app.mjs +153 -0
  170. package/src/tui/ui-content.mjs +65 -86
  171. package/src/tui/ui-help.mjs +73 -0
  172. package/src/tui/ui-overlay-view.mjs +23 -7
  173. package/src/tui/ui-suggest.mjs +6 -5
  174. package/src/tui/ui-theme.mjs +37 -33
  175. package/src/tui/ui-view.mjs +22 -7
  176. package/src/tui/ui.mjs +15 -3
  177. package/src/web/editor.worker.ts +1 -0
  178. package/src/web/integration-rules-editor.ts +439 -0
  179. package/src/web/integration-rules.ts +22 -0
  180. package/src/web/integration-schema.ts +228 -0
  181. package/src/web/json.worker.ts +1 -0
  182. package/src/web/office-viewer.ts +221 -0
  183. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,502 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import type { RuleConfig, RuleTarget } from "./config.ts";
4
+ import type { IngestEvent } from "./protocol.ts";
5
+ import { buildPublishedResult, PUBLISHED_RESULT_PREFIX, type PublishedResultEvent } from "./published.ts";
6
+
7
+ export { readChannelStats, type ChannelAccountStats, type ChannelStats } from "./stats.ts";
8
+ export type { PublishedResultEvent } from "./published.ts";
9
+
10
+ export const DELIVERY_STATES = [
11
+ "pending",
12
+ "in_flight",
13
+ "sent",
14
+ "retryable",
15
+ "rate_limited",
16
+ "permanent",
17
+ "unsupported",
18
+ "unknown",
19
+ "exhausted",
20
+ "paused",
21
+ ] as const;
22
+
23
+ export type DeliveryState = (typeof DELIVERY_STATES)[number];
24
+
25
+ export const TERMINAL_DELIVERY_STATES: readonly DeliveryState[] = [
26
+ "sent",
27
+ "permanent",
28
+ "unsupported",
29
+ "exhausted",
30
+ "unknown",
31
+ ];
32
+
33
+ export function isTerminalDeliveryState(state: DeliveryState): boolean {
34
+ return TERMINAL_DELIVERY_STATES.includes(state);
35
+ }
36
+
37
+ export interface DeliveryPatch {
38
+ attemptCount?: number;
39
+ nextAttemptAt?: number | null;
40
+ lastError?: string | null;
41
+ providerMessage?: string | null;
42
+ }
43
+
44
+ export interface DeliveryRow {
45
+ deliveryId: string;
46
+ eventId: string;
47
+ ruleId: string;
48
+ ruleVersion: number;
49
+ target: string;
50
+ idempotencyKey: string;
51
+ payload: string;
52
+ state: DeliveryState;
53
+ attemptCount: number;
54
+ nextAttemptAt: number | null;
55
+ lastError: string | null;
56
+ providerMessage: string | null;
57
+ createdAt: number;
58
+ updatedAt: number;
59
+ }
60
+
61
+ export interface ReceiptRow {
62
+ receiptId: string;
63
+ deliveryId: string;
64
+ attemptId: string;
65
+ state: string;
66
+ providerMessage: string | null;
67
+ detail: string | null;
68
+ observedAt: number;
69
+ }
70
+
71
+ export interface SentRecordInput {
72
+ deliveryId: string;
73
+ attemptId: string;
74
+ providerMessage: string | null;
75
+ detail?: string | null;
76
+ observedAt?: number;
77
+ echo?: { endpoint: string; nativeMessageId: string; logicalMessageId: string };
78
+ }
79
+
80
+ export interface ReceiptInput {
81
+ deliveryId: string;
82
+ attemptId: string;
83
+ state: string;
84
+ providerMessage?: string | null;
85
+ detail?: string | null;
86
+ observedAt?: number;
87
+ }
88
+
89
+ export type CommitResult =
90
+ | { duplicate: true; existingEventId: string }
91
+ | { duplicate: false; eventId: string; ingressSeq: number };
92
+
93
+ export interface ChannelState {
94
+ commitIngest(event: IngestEvent): CommitResult;
95
+ /** Remove a freshly committed event when a downstream consumer failed. */
96
+ deleteIngestEvent(eventId: string): void;
97
+ enqueueDeliveries(
98
+ triggerEventId: string,
99
+ rule: RuleConfig,
100
+ targets: RuleTarget[],
101
+ payloads: string[],
102
+ ): { deliveryId: string; target: string }[];
103
+ nextPendingDelivery(accountKey: string, now: number): DeliveryRow | undefined;
104
+ markDelivery(deliveryId: string, state: DeliveryState, patch?: DeliveryPatch): void;
105
+ recordSent(input: SentRecordInput): string;
106
+ pauseAccountDeliveries(accountKey: string, reason: string): number;
107
+ abandonUnconfiguredDeliveries(configuredAccountKeys: string[]): DeliveryRow[];
108
+ resumePausedDeliveries(): number;
109
+ recoverInFlightDeliveries(): number;
110
+ recordReceipt(input: ReceiptInput): string;
111
+ recordPublishedResult(delivery: DeliveryRow, receipt?: ReceiptRow): void;
112
+ getPublishedResult(deliveryId: string): PublishedResultEvent | undefined;
113
+ recordEcho(endpoint: string, nativeMessageId: string, logicalMessageId: string, deliveryId?: string): void;
114
+ findEcho(endpoint: string, nativeMessageId: string): string | undefined;
115
+ /** Latest sent provider message for one logical message at one endpoint. */
116
+ findProviderMessage(endpoint: string, logicalMessageId: string): string | undefined;
117
+ getDelivery(deliveryId: string): DeliveryRow | undefined;
118
+ getEvent(eventId: string): IngestEvent | undefined;
119
+ listDeliveries(): DeliveryRow[];
120
+ countEvents(): number;
121
+ listReceipts(deliveryId: string): ReceiptRow[];
122
+ close(): void;
123
+ }
124
+
125
+ type RawRow = Record<string, unknown>;
126
+
127
+ const SCHEMA = `
128
+ CREATE TABLE IF NOT EXISTS channel_events (
129
+ event_id TEXT PRIMARY KEY,
130
+ dedup_key TEXT NOT NULL UNIQUE,
131
+ payload TEXT NOT NULL,
132
+ ingress_seq INTEGER,
133
+ committed_at INTEGER NOT NULL
134
+ );
135
+ CREATE TABLE IF NOT EXISTS channel_deliveries (
136
+ delivery_id TEXT PRIMARY KEY,
137
+ event_id TEXT NOT NULL,
138
+ rule_id TEXT NOT NULL,
139
+ rule_version INTEGER NOT NULL,
140
+ target TEXT NOT NULL,
141
+ idempotency_key TEXT NOT NULL UNIQUE,
142
+ payload TEXT NOT NULL,
143
+ state TEXT NOT NULL,
144
+ attempt_count INTEGER NOT NULL DEFAULT 0,
145
+ next_attempt_at INTEGER,
146
+ last_error TEXT,
147
+ provider_message TEXT,
148
+ created_at INTEGER NOT NULL,
149
+ updated_at INTEGER NOT NULL
150
+ );
151
+ CREATE TABLE IF NOT EXISTS channel_receipts (
152
+ receipt_id TEXT PRIMARY KEY,
153
+ delivery_id TEXT NOT NULL,
154
+ attempt_id TEXT NOT NULL,
155
+ state TEXT NOT NULL,
156
+ provider_message TEXT,
157
+ detail TEXT,
158
+ observed_at INTEGER NOT NULL
159
+ );
160
+ CREATE TABLE IF NOT EXISTS channel_echoes (
161
+ endpoint TEXT NOT NULL,
162
+ native_message_id TEXT NOT NULL,
163
+ logical_message_id TEXT NOT NULL,
164
+ delivery_id TEXT,
165
+ PRIMARY KEY (endpoint, native_message_id)
166
+ );
167
+ `;
168
+
169
+ function transaction<T>(db: DatabaseSync, fn: () => T): T {
170
+ db.exec("BEGIN IMMEDIATE");
171
+ try {
172
+ const value = fn();
173
+ db.exec("COMMIT");
174
+ return value;
175
+ } catch (error) {
176
+ try {
177
+ db.exec("ROLLBACK");
178
+ } catch {
179
+ // Keep the original failure.
180
+ }
181
+ throw error;
182
+ }
183
+ }
184
+
185
+ function toDelivery(row: RawRow): DeliveryRow {
186
+ return {
187
+ deliveryId: String(row.delivery_id),
188
+ eventId: String(row.event_id),
189
+ ruleId: String(row.rule_id),
190
+ ruleVersion: Number(row.rule_version),
191
+ target: String(row.target),
192
+ idempotencyKey: String(row.idempotency_key),
193
+ payload: String(row.payload),
194
+ state: String(row.state) as DeliveryState,
195
+ attemptCount: Number(row.attempt_count),
196
+ nextAttemptAt: row.next_attempt_at === null ? null : Number(row.next_attempt_at),
197
+ lastError: row.last_error === null ? null : String(row.last_error),
198
+ providerMessage: row.provider_message === null ? null : String(row.provider_message),
199
+ createdAt: Number(row.created_at),
200
+ updatedAt: Number(row.updated_at),
201
+ };
202
+ }
203
+
204
+ function toReceipt(row: RawRow): ReceiptRow {
205
+ return {
206
+ receiptId: String(row.receipt_id),
207
+ deliveryId: String(row.delivery_id),
208
+ attemptId: String(row.attempt_id),
209
+ state: String(row.state),
210
+ providerMessage: row.provider_message === null ? null : String(row.provider_message),
211
+ detail: row.detail === null ? null : String(row.detail),
212
+ observedAt: Number(row.observed_at),
213
+ };
214
+ }
215
+
216
+ export function openState(path: string): ChannelState {
217
+ const db = new DatabaseSync(path);
218
+ db.exec(SCHEMA);
219
+ let closed = false;
220
+
221
+ function getDelivery(deliveryId: string): DeliveryRow | undefined {
222
+ const row = db.prepare("SELECT * FROM channel_deliveries WHERE delivery_id = ?").get(deliveryId) as
223
+ | RawRow
224
+ | undefined;
225
+ return row ? toDelivery(row) : undefined;
226
+ }
227
+
228
+ return {
229
+ commitIngest(event: IngestEvent): CommitResult {
230
+ return transaction(db, () => {
231
+ const existing = db.prepare("SELECT event_id FROM channel_events WHERE dedup_key = ?").get(
232
+ event.sourceDedupKey,
233
+ ) as RawRow | undefined;
234
+ if (existing) {
235
+ return { duplicate: true, existingEventId: String(existing.event_id) };
236
+ }
237
+ const max = db.prepare("SELECT COALESCE(MAX(ingress_seq), 0) AS seq FROM channel_events").get() as RawRow;
238
+ const ingressSeq = event.ingressSeq ?? Number(max.seq) + 1;
239
+ const stored = { ...event, ingressSeq };
240
+ db.prepare(
241
+ `INSERT INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
242
+ VALUES (?, ?, ?, ?, ?)`,
243
+ ).run(event.eventId, event.sourceDedupKey, JSON.stringify(stored), ingressSeq, Date.now());
244
+ return { duplicate: false, eventId: event.eventId, ingressSeq };
245
+ });
246
+ },
247
+
248
+ deleteIngestEvent(eventId) {
249
+ db.prepare("DELETE FROM channel_events WHERE event_id = ?").run(eventId);
250
+ },
251
+
252
+ enqueueDeliveries(triggerEventId, rule, targets, payloads) {
253
+ if (targets.length !== payloads.length) {
254
+ throw new Error("enqueueDeliveries: targets and payloads must have the same length");
255
+ }
256
+ const now = Date.now();
257
+ const created: { deliveryId: string; target: string }[] = [];
258
+ transaction(db, () => {
259
+ const insert = db.prepare(
260
+ `INSERT OR IGNORE INTO channel_deliveries
261
+ (delivery_id, event_id, rule_id, rule_version, target, idempotency_key, payload, state, created_at, updated_at)
262
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
263
+ );
264
+ targets.forEach((target, index) => {
265
+ const key = `${target.platform}/${target.account}/${target.room}`;
266
+ const idempotencyKey = `${triggerEventId}:${rule.id}:${rule.version}:0:${key}`;
267
+ const deliveryId = `dlv-${randomUUID()}`;
268
+ const result = insert.run(
269
+ deliveryId,
270
+ triggerEventId,
271
+ rule.id,
272
+ rule.version,
273
+ key,
274
+ idempotencyKey,
275
+ payloads[index] ?? "",
276
+ now,
277
+ now,
278
+ );
279
+ if (Number(result.changes) > 0) created.push({ deliveryId, target: key });
280
+ });
281
+ });
282
+ return created;
283
+ },
284
+
285
+ nextPendingDelivery(accountKey, now) {
286
+ const prefix = `${accountKey.replace(/\/+$/, "")}/`;
287
+ const row = db.prepare(
288
+ `SELECT * FROM channel_deliveries
289
+ WHERE substr(target, 1, length(?)) = ?
290
+ AND state IN ('pending', 'retryable', 'rate_limited')
291
+ AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
292
+ ORDER BY created_at ASC, delivery_id ASC
293
+ LIMIT 1`,
294
+ ).get(prefix, prefix, now) as RawRow | undefined;
295
+ return row ? toDelivery(row) : undefined;
296
+ },
297
+
298
+ markDelivery(deliveryId, state, patch = {}) {
299
+ if (!DELIVERY_STATES.includes(state)) throw new Error(`unknown delivery state: ${state}`);
300
+ const current = getDelivery(deliveryId);
301
+ if (!current) throw new Error(`delivery not found: ${deliveryId}`);
302
+ const terminal = isTerminalDeliveryState(state);
303
+ const nextAttemptAt = patch.nextAttemptAt !== undefined
304
+ ? patch.nextAttemptAt
305
+ : terminal ? null : current.nextAttemptAt;
306
+ db.prepare(
307
+ `UPDATE channel_deliveries
308
+ SET state = ?, attempt_count = ?, next_attempt_at = ?, last_error = ?, provider_message = ?, updated_at = ?
309
+ WHERE delivery_id = ?`,
310
+ ).run(
311
+ state,
312
+ patch.attemptCount ?? current.attemptCount,
313
+ nextAttemptAt,
314
+ patch.lastError !== undefined ? patch.lastError : current.lastError,
315
+ patch.providerMessage !== undefined ? patch.providerMessage : current.providerMessage,
316
+ Date.now(),
317
+ deliveryId,
318
+ );
319
+ },
320
+
321
+ recordSent(input) {
322
+ const receiptId = `rcp-${randomUUID()}`;
323
+ transaction(db, () => {
324
+ db.prepare(
325
+ `INSERT INTO channel_receipts
326
+ (receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
327
+ VALUES (?, ?, ?, 'sent', ?, ?, ?)`,
328
+ ).run(
329
+ receiptId,
330
+ input.deliveryId,
331
+ input.attemptId,
332
+ input.providerMessage,
333
+ input.detail ?? null,
334
+ input.observedAt ?? Date.now(),
335
+ );
336
+ if (input.echo) {
337
+ db.prepare(
338
+ `INSERT OR IGNORE INTO channel_echoes
339
+ (endpoint, native_message_id, logical_message_id, delivery_id)
340
+ VALUES (?, ?, ?, ?)`,
341
+ ).run(
342
+ input.echo.endpoint,
343
+ input.echo.nativeMessageId,
344
+ input.echo.logicalMessageId,
345
+ input.deliveryId,
346
+ );
347
+ }
348
+ });
349
+ return receiptId;
350
+ },
351
+
352
+ pauseAccountDeliveries(accountKey, reason) {
353
+ const prefix = `${accountKey.replace(/\/+$/, "")}/`;
354
+ const result = db.prepare(
355
+ `UPDATE channel_deliveries
356
+ SET state = 'paused', next_attempt_at = NULL, last_error = ?, updated_at = ?
357
+ WHERE substr(target, 1, length(?)) = ?
358
+ AND state IN ('pending', 'retryable', 'rate_limited')`,
359
+ ).run(reason, Date.now(), prefix, prefix);
360
+ return Number(result.changes);
361
+ },
362
+
363
+ abandonUnconfiguredDeliveries(configuredAccountKeys) {
364
+ const configured = [...new Set(configuredAccountKeys)];
365
+ const accountKeySql = `CASE WHEN instr(target, '/') > 0
366
+ AND instr(substr(target, instr(target, '/') + 1), '/') > 0
367
+ THEN substr(target, 1, instr(target, '/') + instr(substr(target, instr(target, '/') + 1), '/') - 1)
368
+ ELSE target END`;
369
+ const filter = configured.length > 0
370
+ ? `AND (${accountKeySql}) NOT IN (${configured.map(() => "?").join(", ")})`
371
+ : "";
372
+ const rows = db.prepare(
373
+ `SELECT * FROM channel_deliveries
374
+ WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
375
+ ${filter}
376
+ ORDER BY created_at ASC, delivery_id ASC`,
377
+ ).all(...configured) as RawRow[];
378
+ if (rows.length === 0) return [];
379
+ transaction(db, () =>
380
+ db.prepare(
381
+ `UPDATE channel_deliveries
382
+ SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
383
+ WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
384
+ ${filter}`,
385
+ ).run("account is not configured; add it back to retry", Date.now(), ...configured)
386
+ );
387
+ return rows.map((row) => ({ ...toDelivery(row), state: "unknown" as const }));
388
+ },
389
+
390
+ resumePausedDeliveries() {
391
+ const result = db.prepare(
392
+ `UPDATE channel_deliveries
393
+ SET state = 'pending', next_attempt_at = NULL, updated_at = ?
394
+ WHERE state = 'paused'`,
395
+ ).run(Date.now());
396
+ return Number(result.changes);
397
+ },
398
+
399
+ recoverInFlightDeliveries() {
400
+ const result = db.prepare(
401
+ `UPDATE channel_deliveries
402
+ SET state = 'pending', next_attempt_at = NULL,
403
+ last_error = 'recovered stale in_flight after restart', updated_at = ?
404
+ WHERE state = 'in_flight'`,
405
+ ).run(Date.now());
406
+ return Number(result.changes);
407
+ },
408
+
409
+ recordReceipt(input) {
410
+ const receiptId = `rcp-${randomUUID()}`;
411
+ db.prepare(
412
+ `INSERT INTO channel_receipts
413
+ (receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
414
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
415
+ ).run(
416
+ receiptId,
417
+ input.deliveryId,
418
+ input.attemptId,
419
+ input.state,
420
+ input.providerMessage ?? null,
421
+ input.detail ?? null,
422
+ input.observedAt ?? Date.now(),
423
+ );
424
+ return receiptId;
425
+ },
426
+
427
+ recordPublishedResult(delivery, receipt) {
428
+ const now = Date.now();
429
+ const event = buildPublishedResult(delivery, receipt, now);
430
+ db.prepare(
431
+ `INSERT OR IGNORE INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
432
+ VALUES (?, ?, ?, NULL, ?)`,
433
+ ).run(event.eventId, event.sourceDedupKey, JSON.stringify(event), now);
434
+ },
435
+
436
+ getPublishedResult(deliveryId) {
437
+ const row = db.prepare("SELECT payload FROM channel_events WHERE dedup_key = ?").get(
438
+ `${PUBLISHED_RESULT_PREFIX}${deliveryId}`,
439
+ ) as RawRow | undefined;
440
+ return row ? (JSON.parse(String(row.payload)) as PublishedResultEvent) : undefined;
441
+ },
442
+
443
+ recordEcho(endpoint, nativeMessageId, logicalMessageId, deliveryId) {
444
+ db.prepare(
445
+ `INSERT OR IGNORE INTO channel_echoes
446
+ (endpoint, native_message_id, logical_message_id, delivery_id)
447
+ VALUES (?, ?, ?, ?)`,
448
+ ).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null);
449
+ },
450
+
451
+ findEcho(endpoint, nativeMessageId) {
452
+ const row = db.prepare(
453
+ "SELECT logical_message_id FROM channel_echoes WHERE endpoint = ? AND native_message_id = ?",
454
+ ).get(endpoint, nativeMessageId) as RawRow | undefined;
455
+ return row ? String(row.logical_message_id) : undefined;
456
+ },
457
+
458
+ findProviderMessage(endpoint, logicalMessageId) {
459
+ const row = db.prepare(
460
+ `SELECT native_message_id FROM channel_echoes
461
+ WHERE endpoint = ? AND logical_message_id = ? AND delivery_id IS NOT NULL
462
+ ORDER BY rowid DESC LIMIT 1`,
463
+ ).get(endpoint, logicalMessageId) as RawRow | undefined;
464
+ return row ? String(row.native_message_id) : undefined;
465
+ },
466
+
467
+ getDelivery,
468
+
469
+ getEvent(eventId) {
470
+ const row = db.prepare("SELECT payload FROM channel_events WHERE event_id = ?").get(eventId) as
471
+ | RawRow
472
+ | undefined;
473
+ return row ? (JSON.parse(String(row.payload)) as IngestEvent) : undefined;
474
+ },
475
+
476
+ listDeliveries() {
477
+ return (db.prepare(
478
+ "SELECT * FROM channel_deliveries ORDER BY created_at ASC, delivery_id ASC",
479
+ ).all() as RawRow[]).map(toDelivery);
480
+ },
481
+
482
+ listReceipts(deliveryId) {
483
+ return (db.prepare(
484
+ "SELECT * FROM channel_receipts WHERE delivery_id = ? ORDER BY observed_at ASC, receipt_id ASC",
485
+ ).all(deliveryId) as RawRow[]).map(toReceipt);
486
+ },
487
+
488
+ countEvents() {
489
+ // Ingest events only; published results are reported by readChannelStats.
490
+ const row = db.prepare(
491
+ "SELECT COUNT(*) AS count FROM channel_events WHERE dedup_key NOT LIKE ?",
492
+ ).get(`${PUBLISHED_RESULT_PREFIX}%`) as RawRow;
493
+ return Number(row.count);
494
+ },
495
+
496
+ close() {
497
+ if (closed) return;
498
+ closed = true;
499
+ db.close();
500
+ },
501
+ };
502
+ }
@@ -0,0 +1,209 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+
3
+ export type ChannelAccountState = "started" | "failed" | "disabled" | "unknown";
4
+
5
+ /** Live state supplied by a running host; stats itself only reads SQLite. */
6
+ export interface ChannelAccountRuntime {
7
+ state: ChannelAccountState;
8
+ lastError?: string;
9
+ }
10
+
11
+ export interface ChannelAccountStats {
12
+ account: string;
13
+ state: ChannelAccountState;
14
+ lastError?: string;
15
+ queueDepth: number;
16
+ oldestBacklogAt: number | null;
17
+ unknown: number;
18
+ retryable: number;
19
+ rateLimited: number;
20
+ }
21
+
22
+ export interface ChannelStats {
23
+ generatedAt: number;
24
+ events: number;
25
+ publishedResults: number;
26
+ eventsWithoutDeliveries: number;
27
+ deliveriesWithoutEvent: number;
28
+ receiptsWithoutDelivery: number;
29
+ deliveries: {
30
+ total: number;
31
+ pending: number;
32
+ inFlight: number;
33
+ retryable: number;
34
+ rateLimited: number;
35
+ paused: number;
36
+ unknown: number;
37
+ sent: number;
38
+ failed: number;
39
+ };
40
+ queueDepth: number;
41
+ oldestBacklogAt: number | null;
42
+ oldestBacklogAgeMs: number | null;
43
+ accounts: ChannelAccountStats[];
44
+ }
45
+
46
+ const REQUIRED_TABLES = ["channel_events", "channel_deliveries", "channel_receipts"];
47
+ const QUEUE_STATES = new Set(["pending", "retryable", "rate_limited"]);
48
+ const MAX_LAST_ERROR = 200;
49
+
50
+ type Row = Record<string, unknown>;
51
+
52
+ /** Keep status details short and free of credential-shaped fragments. */
53
+ export function sanitizeAccountError(value: string): string {
54
+ const redacted = value
55
+ .replace(/\bBearer\s+\S+/gi, "Bearer [redacted]")
56
+ .replace(/\b(secret|token|password|passwd|authorization|api[_-]?key)\b\s*[:=]\s*\S+/gi, "$1=[redacted]");
57
+ return redacted.replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, MAX_LAST_ERROR);
58
+ }
59
+
60
+ function count(db: DatabaseSync, sql: string): number {
61
+ const row = db.prepare(sql).get() as Row;
62
+ return Number(row.count);
63
+ }
64
+
65
+ function accountKey(target: string): string {
66
+ const first = target.indexOf("/");
67
+ if (first < 0) return target;
68
+ const second = target.indexOf("/", first + 1);
69
+ return second === -1 ? target : target.slice(0, second);
70
+ }
71
+
72
+ /**
73
+ * Read queue and integrity counts without touching message content.
74
+ * The database is opened read-only, so a missing state file is never created.
75
+ */
76
+ export function readChannelStats(
77
+ path: string,
78
+ now = Date.now(),
79
+ runtime: ReadonlyMap<string, ChannelAccountRuntime> = new Map(),
80
+ ): ChannelStats {
81
+ let db: DatabaseSync | undefined;
82
+ try {
83
+ db = new DatabaseSync(path, { readOnly: true });
84
+ db.exec("PRAGMA busy_timeout = 2000");
85
+
86
+ const names = new Set(
87
+ (db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Row[]).map((row) =>
88
+ String(row.name)
89
+ ),
90
+ );
91
+ if (REQUIRED_TABLES.some((table) => !names.has(table))) {
92
+ throw new Error(`channel state not found: ${path}`);
93
+ }
94
+
95
+ const stateCounts: Record<string, number> = {};
96
+ const accounts = new Map<string, ChannelAccountStats>();
97
+ let oldestBacklogAt: number | null = null;
98
+ const rows = db.prepare("SELECT target, state, created_at FROM channel_deliveries").all() as Row[];
99
+
100
+ for (const row of rows) {
101
+ const state = String(row.state);
102
+ stateCounts[state] = (stateCounts[state] ?? 0) + 1;
103
+
104
+ const key = accountKey(String(row.target));
105
+ let account = accounts.get(key);
106
+ if (!account) {
107
+ account = {
108
+ account: key,
109
+ state: "unknown",
110
+ queueDepth: 0,
111
+ oldestBacklogAt: null,
112
+ unknown: 0,
113
+ retryable: 0,
114
+ rateLimited: 0,
115
+ };
116
+ accounts.set(key, account);
117
+ }
118
+ if (state === "unknown") account.unknown += 1;
119
+ if (state === "retryable") account.retryable += 1;
120
+ if (state === "rate_limited") account.rateLimited += 1;
121
+ if (QUEUE_STATES.has(state)) {
122
+ const createdAt = Number(row.created_at);
123
+ account.queueDepth += 1;
124
+ if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
125
+ account.oldestBacklogAt = createdAt;
126
+ }
127
+ if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
128
+ oldestBacklogAt = createdAt;
129
+ }
130
+ }
131
+ }
132
+
133
+ // Runtime entries add configured accounts without deliveries and override
134
+ // the SQLite-only default of "unknown" for a running host.
135
+ for (const [key, live] of runtime) {
136
+ const account = accounts.get(key) ?? {
137
+ account: key,
138
+ state: "unknown" as const,
139
+ queueDepth: 0,
140
+ oldestBacklogAt: null,
141
+ unknown: 0,
142
+ retryable: 0,
143
+ rateLimited: 0,
144
+ };
145
+ account.state = live.state;
146
+ const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
147
+ if (lastError) account.lastError = lastError;
148
+ accounts.set(key, account);
149
+ }
150
+
151
+ const pending = stateCounts.pending ?? 0;
152
+ const retryable = stateCounts.retryable ?? 0;
153
+ const rateLimited = stateCounts.rate_limited ?? 0;
154
+ const failed = (stateCounts.permanent ?? 0)
155
+ + (stateCounts.unsupported ?? 0)
156
+ + (stateCounts.exhausted ?? 0);
157
+
158
+ return {
159
+ generatedAt: now,
160
+ events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
161
+ publishedResults: count(
162
+ db,
163
+ "SELECT COUNT(*) AS count FROM channel_events WHERE json_extract(payload, '$.kind') = 'result.published'",
164
+ ),
165
+ eventsWithoutDeliveries: count(
166
+ db,
167
+ `SELECT COUNT(*) AS count FROM channel_events e
168
+ WHERE json_extract(e.payload, '$.kind') IS NOT 'result.published'
169
+ AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`,
170
+ ),
171
+ deliveriesWithoutEvent: count(
172
+ db,
173
+ `SELECT COUNT(*) AS count FROM channel_deliveries d
174
+ WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`,
175
+ ),
176
+ receiptsWithoutDelivery: count(
177
+ db,
178
+ `SELECT COUNT(*) AS count FROM channel_receipts r
179
+ WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`,
180
+ ),
181
+ deliveries: {
182
+ total: rows.length,
183
+ pending,
184
+ inFlight: stateCounts.in_flight ?? 0,
185
+ retryable,
186
+ rateLimited,
187
+ paused: stateCounts.paused ?? 0,
188
+ unknown: stateCounts.unknown ?? 0,
189
+ sent: stateCounts.sent ?? 0,
190
+ failed,
191
+ },
192
+ queueDepth: pending + retryable + rateLimited,
193
+ oldestBacklogAt,
194
+ oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
195
+ accounts: [...accounts.values()].sort((left, right) =>
196
+ left.account < right.account ? -1 : left.account > right.account ? 1 : 0
197
+ ),
198
+ };
199
+ } catch (error) {
200
+ if (error instanceof Error && error.message.startsWith("channel state not found:")) throw error;
201
+ throw new Error(`channel state not found: ${path}`);
202
+ } finally {
203
+ try {
204
+ db?.close();
205
+ } catch {
206
+ // Keep the original result or error.
207
+ }
208
+ }
209
+ }