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