@alexsun-top/opencode-chat-room 0.8.5 → 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -2
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/cli.ts +19 -0
- package/dist/cli.js +3747 -1443
- package/package.json +6 -1
- package/packages/chat-room-channeld/README.md +13 -8
- package/packages/chat-room-channeld/src/delivery.ts +0 -4
- package/packages/chat-room-channeld/src/host.ts +48 -37
- package/packages/chat-room-channeld/src/pg/database.ts +141 -49
- package/packages/chat-room-channeld/src/pg/worker.mjs +46 -5
- package/packages/chat-room-channeld/src/pg/worker.mts +41 -6
- package/packages/chat-room-channeld/src/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/plugin.ts +20 -4
- package/server/app.ts +9 -0
- package/server/assets/base.css +22 -2
- package/server/assets/chat/admin.js +13 -0
- package/server/assets/chat/announcements.js +76 -34
- package/server/assets/chat/confirm-dialog.js +3 -0
- package/server/assets/chat/create-room-dialog.js +7 -0
- package/server/assets/chat/diagram-viewer.js +4 -8
- package/server/assets/chat/doc-preview.js +70 -30
- package/server/assets/chat/editor.js +38 -3
- package/server/assets/chat/events.js +6 -1
- package/server/assets/chat/files.js +28 -26
- package/server/assets/chat/history-loader.js +31 -15
- package/server/assets/chat/integration-editor.js +25 -1
- package/server/assets/chat/integrations.js +107 -15
- package/server/assets/chat/join-requests.js +39 -1
- package/server/assets/chat/locales/de.js +5 -3
- package/server/assets/chat/locales/es.js +5 -3
- package/server/assets/chat/locales/fr.js +5 -3
- package/server/assets/chat/locales/it.js +5 -3
- package/server/assets/chat/locales/ja.js +5 -3
- package/server/assets/chat/locales/ko.js +5 -3
- package/server/assets/chat/markdown-footnotes.js +19 -8
- package/server/assets/chat/markdown.js +0 -7
- package/server/assets/chat/members.js +31 -19
- package/server/assets/chat/message-cache.js +8 -2
- package/server/assets/chat/message-polling.js +8 -2
- package/server/assets/chat/message-window.js +57 -0
- package/server/assets/chat/messages.js +79 -40
- package/server/assets/chat/operator.js +624 -0
- package/server/assets/chat/palette.js +2 -7
- package/server/assets/chat/panels.js +31 -8
- package/server/assets/chat/questions.js +72 -56
- package/server/assets/chat/recall.js +14 -5
- package/server/assets/chat/receipts.js +63 -7
- package/server/assets/chat/refresh-timing.js +6 -0
- package/server/assets/chat/reminders.js +44 -13
- package/server/assets/chat/replies.js +33 -22
- package/server/assets/chat/resource-format.js +4 -1
- package/server/assets/chat/room-list.js +202 -3
- package/server/assets/chat/room-watcher.js +3 -1
- package/server/assets/chat/rooms.js +22 -3
- package/server/assets/chat/settings.js +33 -3
- package/server/assets/chat/state.js +21 -7
- package/server/assets/chat/tasks.js +33 -11
- package/server/assets/chat/window-controls.js +25 -16
- package/server/assets/code-highlight.css +0 -13
- package/server/assets/conversation.css +31 -3
- package/server/assets/doc-preview.css +3 -0
- package/server/assets/files.css +4 -0
- package/server/assets/monaco/integration-rules.js +1 -1
- package/server/assets/responsive.css +12 -2
- package/server/assets/settings.css +3 -1
- package/server/assets/tasks.css +6 -1
- package/server/assets/window-controls.css +3 -1
- package/server/channels.ts +3 -2
- package/server/chat.html +7 -2
- package/server/inbox.ts +3 -1
- package/server/join-requests.ts +8 -1
- package/server/member-routes.ts +16 -2
- package/server/newrooms.ts +2 -13
- package/server/operator-auth.ts +21 -0
- package/server/operator-routes.ts +150 -0
- package/server/operator-state.ts +64 -0
- package/server/operator.css +139 -0
- package/server/room-owner.ts +17 -0
- package/server/routes/inbox.ts +15 -5
- package/server/routes/pages.ts +12 -2
- package/server/routes/room-actions.ts +4 -3
- package/server/system.html +109 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +3 -3
- package/src/acp/client.ts +254 -0
- package/src/acp/protocol.ts +300 -0
- package/src/acp/watch.ts +498 -0
- package/src/agent/agent-receipts.ts +87 -5
- package/src/center/center-client.ts +5 -0
- package/src/center/center-inbox.ts +54 -7
- package/src/center/center-wake.ts +57 -3
- package/src/center/forward-client.ts +48 -0
- package/src/center/mentions.ts +16 -3
- package/src/center/notification-delay.ts +139 -0
- package/src/center/queue.ts +3 -0
- package/src/config/file-config.ts +25 -0
- package/src/mcp/server.ts +389 -0
- package/src/protocol/config.ts +7 -0
- package/src/runtime/plugin-notifications.ts +43 -9
- package/src/runtime/v2-plugin.ts +14 -3
- package/src/runtime/v2-receiver.ts +10 -2
- package/src/runtime/watch.ts +5 -1
- package/src/state/pg-database.ts +133 -49
- package/src/state/pg-worker.mjs +46 -5
- package/src/state/pg-worker.mts +41 -6
- package/src/state/receiver-state.ts +47 -0
- package/src/state/sqlite-database.ts +6 -2
- package/src/state/sqlite-members.ts +48 -4
- package/src/state/sqlite-messages.ts +25 -12
- package/src/state/sqlite-schema.ts +4 -1
- package/src/state/sqlite-state.ts +1 -1
- package/src/state/store.ts +10 -4
- package/src/tui/app.mjs +57 -10
- package/src/tui/app.mts +54 -11
- package/src/tui/room-settings-app.mjs +27 -9
- package/src/tui/room-settings-app.mts +26 -9
- package/src/web/integration-rules-editor.ts +25 -2
|
@@ -40,6 +40,7 @@ let port: MessagePort | undefined;
|
|
|
40
40
|
let readyFlag: Int32Array | undefined;
|
|
41
41
|
let statementTimeout = 4_500;
|
|
42
42
|
let connected = false;
|
|
43
|
+
let lost: Error | undefined;
|
|
43
44
|
let draining = false;
|
|
44
45
|
let closing = false;
|
|
45
46
|
const queue: Request[] = [];
|
|
@@ -73,16 +74,42 @@ function signalReady(): void {
|
|
|
73
74
|
}
|
|
74
75
|
|
|
75
76
|
function reply(request: Request, payload: Record<string, unknown>): void {
|
|
76
|
-
port?.postMessage({ id: request.id, ...payload });
|
|
77
|
+
try { port?.postMessage({ id: request.id, ...payload }); } catch { /* port already retired */ }
|
|
77
78
|
const flag = new Int32Array(request.signal);
|
|
78
79
|
Atomics.store(flag, 0, 1);
|
|
79
80
|
Atomics.notify(flag, 0);
|
|
80
81
|
}
|
|
81
82
|
|
|
83
|
+
function markLost(error: unknown): Error {
|
|
84
|
+
if (!lost) lost = error instanceof Error ? error : new Error(String(error));
|
|
85
|
+
connected = false;
|
|
86
|
+
return lost;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Session-level failures (backend termination, server shutdown, socket error)
|
|
90
|
+
// leave the client unusable. Ordinary statement errors such as 57014 keep it.
|
|
91
|
+
function unusable(error: unknown): boolean {
|
|
92
|
+
if (lost) return true;
|
|
93
|
+
const source = (error ?? {}) as { severity?: unknown; code?: unknown };
|
|
94
|
+
if (source.severity === "FATAL" || source.severity === "PANIC") return true;
|
|
95
|
+
// SQLSTATE class 08 is a connection exception, not a statement failure.
|
|
96
|
+
return typeof source.code === "string" && source.code.startsWith("08");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// pg emits "error" on the client when the socket dies without an active query
|
|
100
|
+
// (idle connection). Without this listener the event is uncaught and the worker
|
|
101
|
+
// dies, which used to take the whole server process with it.
|
|
102
|
+
function clientLost(error: unknown): void {
|
|
103
|
+
if (closing) return;
|
|
104
|
+
markLost(error);
|
|
105
|
+
if (queue.length && !draining) void drain();
|
|
106
|
+
}
|
|
107
|
+
|
|
82
108
|
async function handle(request: Request): Promise<void> {
|
|
83
109
|
const db = client;
|
|
84
|
-
if (!db) {
|
|
85
|
-
|
|
110
|
+
if (!db || lost) {
|
|
111
|
+
const error = lost ?? new Error("PostgreSQL worker is not connected");
|
|
112
|
+
return reply(request, { ok: false, error: serialize(error), broken: true });
|
|
86
113
|
}
|
|
87
114
|
try {
|
|
88
115
|
const text = translate(request.sql);
|
|
@@ -100,7 +127,9 @@ async function handle(request: Request): Promise<void> {
|
|
|
100
127
|
// keep the API shape without pretending to know an insert id.
|
|
101
128
|
return reply(request, { ok: true, changes: last?.rowCount ?? 0, lastInsertRowid: 0 });
|
|
102
129
|
} catch (error) {
|
|
103
|
-
return reply(request, { ok: false, error: serialize(error) });
|
|
130
|
+
if (!unusable(error)) return reply(request, { ok: false, error: serialize(error) });
|
|
131
|
+
markLost(error);
|
|
132
|
+
return reply(request, { ok: false, error: serialize(error), broken: true });
|
|
104
133
|
}
|
|
105
134
|
}
|
|
106
135
|
|
|
@@ -130,7 +159,9 @@ function handlePortMessage(message: PortMessage): void {
|
|
|
130
159
|
return;
|
|
131
160
|
}
|
|
132
161
|
queue.push(message);
|
|
133
|
-
|
|
162
|
+
// After a loss the queue is still served, but every reply is marked broken so
|
|
163
|
+
// the main thread reopens immediately instead of waiting for its timeout.
|
|
164
|
+
if (!draining && (connected || lost)) void drain();
|
|
134
165
|
}
|
|
135
166
|
|
|
136
167
|
async function startup(connectionString: string, ready: SharedArrayBuffer, timeout: number): Promise<void> {
|
|
@@ -142,6 +173,10 @@ async function startup(connectionString: string, ready: SharedArrayBuffer, timeo
|
|
|
142
173
|
application_name: "chat-room-channeld",
|
|
143
174
|
statement_timeout: statementTimeout,
|
|
144
175
|
});
|
|
176
|
+
db.on("error", clientLost);
|
|
177
|
+
// pg normally emits "error" before "end"; "end" alone still means the
|
|
178
|
+
// connection is gone, and the first failure keeps its message.
|
|
179
|
+
db.on("end", () => clientLost(new Error("PostgreSQL connection ended")));
|
|
145
180
|
client = db;
|
|
146
181
|
await db.connect();
|
|
147
182
|
connected = true;
|
|
@@ -163,4 +198,4 @@ if (parent) {
|
|
|
163
198
|
parent.close();
|
|
164
199
|
void startup(message.connectionString, message.ready, message.statementTimeout ?? 4_500);
|
|
165
200
|
});
|
|
166
|
-
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Row shapes and mappers shared by the Channel D state store.
|
|
2
|
+
|
|
3
|
+
export const DELIVERY_STATES = [
|
|
4
|
+
"pending",
|
|
5
|
+
"in_flight",
|
|
6
|
+
"sent",
|
|
7
|
+
"retryable",
|
|
8
|
+
"rate_limited",
|
|
9
|
+
"permanent",
|
|
10
|
+
"unsupported",
|
|
11
|
+
"unknown",
|
|
12
|
+
"exhausted",
|
|
13
|
+
"paused",
|
|
14
|
+
] as const;
|
|
15
|
+
|
|
16
|
+
export type DeliveryState = (typeof DELIVERY_STATES)[number];
|
|
17
|
+
|
|
18
|
+
export const TERMINAL_DELIVERY_STATES: readonly DeliveryState[] = [
|
|
19
|
+
"sent",
|
|
20
|
+
"permanent",
|
|
21
|
+
"unsupported",
|
|
22
|
+
"exhausted",
|
|
23
|
+
"unknown",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
export function isTerminalDeliveryState(state: DeliveryState): boolean {
|
|
27
|
+
return TERMINAL_DELIVERY_STATES.includes(state);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface DeliveryPatch {
|
|
31
|
+
attemptCount?: number;
|
|
32
|
+
nextAttemptAt?: number | null;
|
|
33
|
+
lastError?: string | null;
|
|
34
|
+
providerMessage?: string | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface DeliveryRow {
|
|
38
|
+
deliveryId: string;
|
|
39
|
+
eventId: string;
|
|
40
|
+
ruleId: string;
|
|
41
|
+
ruleVersion: number;
|
|
42
|
+
target: string;
|
|
43
|
+
idempotencyKey: string;
|
|
44
|
+
payload: string;
|
|
45
|
+
state: DeliveryState;
|
|
46
|
+
attemptCount: number;
|
|
47
|
+
nextAttemptAt: number | null;
|
|
48
|
+
lastError: string | null;
|
|
49
|
+
providerMessage: string | null;
|
|
50
|
+
createdAt: number;
|
|
51
|
+
updatedAt: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ReceiptRow {
|
|
55
|
+
receiptId: string;
|
|
56
|
+
deliveryId: string;
|
|
57
|
+
attemptId: string;
|
|
58
|
+
state: string;
|
|
59
|
+
providerMessage: string | null;
|
|
60
|
+
detail: string | null;
|
|
61
|
+
observedAt: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface SentRecordInput {
|
|
65
|
+
deliveryId: string;
|
|
66
|
+
attemptId: string;
|
|
67
|
+
providerMessage: string | null;
|
|
68
|
+
detail?: string | null;
|
|
69
|
+
observedAt?: number;
|
|
70
|
+
echo?: { endpoint: string; nativeMessageId: string; logicalMessageId: string };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface ReceiptInput {
|
|
74
|
+
deliveryId: string;
|
|
75
|
+
attemptId: string;
|
|
76
|
+
state: string;
|
|
77
|
+
providerMessage?: string | null;
|
|
78
|
+
detail?: string | null;
|
|
79
|
+
observedAt?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type CommitResult =
|
|
83
|
+
| { duplicate: true; existingEventId: string }
|
|
84
|
+
| { duplicate: false; eventId: string; ingressSeq: number };
|
|
85
|
+
|
|
86
|
+
/** One authorized outbound delivery, frozen before the ingest transaction. */
|
|
87
|
+
export interface PlannedDelivery {
|
|
88
|
+
ruleId: string;
|
|
89
|
+
ruleVersion: number;
|
|
90
|
+
target: string;
|
|
91
|
+
payload: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface CreatedDelivery {
|
|
95
|
+
deliveryId: string;
|
|
96
|
+
target: string;
|
|
97
|
+
ruleId: string;
|
|
98
|
+
ruleVersion: number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type RawRow = Record<string, unknown>;
|
|
102
|
+
|
|
103
|
+
export function toDelivery(row: RawRow): DeliveryRow {
|
|
104
|
+
return {
|
|
105
|
+
deliveryId: String(row.delivery_id),
|
|
106
|
+
eventId: String(row.event_id),
|
|
107
|
+
ruleId: String(row.rule_id),
|
|
108
|
+
ruleVersion: Number(row.rule_version),
|
|
109
|
+
target: String(row.target),
|
|
110
|
+
idempotencyKey: String(row.idempotency_key),
|
|
111
|
+
payload: String(row.payload),
|
|
112
|
+
state: String(row.state) as DeliveryState,
|
|
113
|
+
attemptCount: Number(row.attempt_count),
|
|
114
|
+
nextAttemptAt: row.next_attempt_at === null ? null : Number(row.next_attempt_at),
|
|
115
|
+
lastError: row.last_error === null ? null : String(row.last_error),
|
|
116
|
+
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
117
|
+
createdAt: Number(row.created_at),
|
|
118
|
+
updatedAt: Number(row.updated_at),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function toReceipt(row: RawRow): ReceiptRow {
|
|
123
|
+
return {
|
|
124
|
+
receiptId: String(row.receipt_id),
|
|
125
|
+
deliveryId: String(row.delivery_id),
|
|
126
|
+
attemptId: String(row.attempt_id),
|
|
127
|
+
state: String(row.state),
|
|
128
|
+
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
129
|
+
detail: row.detail === null ? null : String(row.detail),
|
|
130
|
+
observedAt: Number(row.observed_at),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -6,6 +6,23 @@ import { Database, type StateDatabase } from "./pg/sqlite.ts";
|
|
|
6
6
|
import type { IngestEvent } from "./protocol.ts";
|
|
7
7
|
import { buildPublishedResult, PUBLISHED_RESULT_PREFIX, type PublishedResultEvent } from "./published.ts";
|
|
8
8
|
import { accountKey } from "./stats.ts";
|
|
9
|
+
import {
|
|
10
|
+
DELIVERY_STATES,
|
|
11
|
+
TERMINAL_DELIVERY_STATES,
|
|
12
|
+
isTerminalDeliveryState,
|
|
13
|
+
toDelivery,
|
|
14
|
+
toReceipt,
|
|
15
|
+
type CommitResult,
|
|
16
|
+
type CreatedDelivery,
|
|
17
|
+
type DeliveryPatch,
|
|
18
|
+
type DeliveryRow,
|
|
19
|
+
type DeliveryState,
|
|
20
|
+
type PlannedDelivery,
|
|
21
|
+
type RawRow,
|
|
22
|
+
type ReceiptInput,
|
|
23
|
+
type ReceiptRow,
|
|
24
|
+
type SentRecordInput,
|
|
25
|
+
} from "./state-rows.ts";
|
|
9
26
|
|
|
10
27
|
export {
|
|
11
28
|
readChannelStats,
|
|
@@ -14,92 +31,34 @@ export {
|
|
|
14
31
|
type ChannelStats,
|
|
15
32
|
} from "./stats.ts";
|
|
16
33
|
export type { PublishedResultEvent } from "./published.ts";
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
export const TERMINAL_DELIVERY_STATES: readonly DeliveryState[] = [
|
|
34
|
-
"sent",
|
|
35
|
-
"permanent",
|
|
36
|
-
"unsupported",
|
|
37
|
-
"exhausted",
|
|
38
|
-
"unknown",
|
|
39
|
-
];
|
|
40
|
-
|
|
41
|
-
export function isTerminalDeliveryState(state: DeliveryState): boolean {
|
|
42
|
-
return TERMINAL_DELIVERY_STATES.includes(state);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface DeliveryPatch {
|
|
46
|
-
attemptCount?: number;
|
|
47
|
-
nextAttemptAt?: number | null;
|
|
48
|
-
lastError?: string | null;
|
|
49
|
-
providerMessage?: string | null;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export interface DeliveryRow {
|
|
53
|
-
deliveryId: string;
|
|
54
|
-
eventId: string;
|
|
55
|
-
ruleId: string;
|
|
56
|
-
ruleVersion: number;
|
|
57
|
-
target: string;
|
|
58
|
-
idempotencyKey: string;
|
|
59
|
-
payload: string;
|
|
60
|
-
state: DeliveryState;
|
|
61
|
-
attemptCount: number;
|
|
62
|
-
nextAttemptAt: number | null;
|
|
63
|
-
lastError: string | null;
|
|
64
|
-
providerMessage: string | null;
|
|
65
|
-
createdAt: number;
|
|
66
|
-
updatedAt: number;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export interface ReceiptRow {
|
|
70
|
-
receiptId: string;
|
|
71
|
-
deliveryId: string;
|
|
72
|
-
attemptId: string;
|
|
73
|
-
state: string;
|
|
74
|
-
providerMessage: string | null;
|
|
75
|
-
detail: string | null;
|
|
76
|
-
observedAt: number;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export interface SentRecordInput {
|
|
80
|
-
deliveryId: string;
|
|
81
|
-
attemptId: string;
|
|
82
|
-
providerMessage: string | null;
|
|
83
|
-
detail?: string | null;
|
|
84
|
-
observedAt?: number;
|
|
85
|
-
echo?: { endpoint: string; nativeMessageId: string; logicalMessageId: string };
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
export interface ReceiptInput {
|
|
89
|
-
deliveryId: string;
|
|
90
|
-
attemptId: string;
|
|
91
|
-
state: string;
|
|
92
|
-
providerMessage?: string | null;
|
|
93
|
-
detail?: string | null;
|
|
94
|
-
observedAt?: number;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export type CommitResult =
|
|
98
|
-
| { duplicate: true; existingEventId: string }
|
|
99
|
-
| { duplicate: false; eventId: string; ingressSeq: number };
|
|
34
|
+
export {
|
|
35
|
+
DELIVERY_STATES,
|
|
36
|
+
TERMINAL_DELIVERY_STATES,
|
|
37
|
+
isTerminalDeliveryState,
|
|
38
|
+
};
|
|
39
|
+
export type {
|
|
40
|
+
CommitResult,
|
|
41
|
+
CreatedDelivery,
|
|
42
|
+
DeliveryPatch,
|
|
43
|
+
DeliveryRow,
|
|
44
|
+
DeliveryState,
|
|
45
|
+
PlannedDelivery,
|
|
46
|
+
ReceiptInput,
|
|
47
|
+
ReceiptRow,
|
|
48
|
+
SentRecordInput,
|
|
49
|
+
};
|
|
100
50
|
|
|
101
51
|
export interface ChannelState {
|
|
102
52
|
commitIngest(event: IngestEvent): CommitResult;
|
|
53
|
+
/**
|
|
54
|
+
* Commit the event and its outbound plan in one transaction. The plan callback
|
|
55
|
+
* runs only for a new event and receives the stored event with its ingressSeq,
|
|
56
|
+
* so a duplicate never re-plans against changed config.
|
|
57
|
+
*/
|
|
58
|
+
commitIngestWithPlan(
|
|
59
|
+
event: IngestEvent,
|
|
60
|
+
plan: (stored: IngestEvent) => PlannedDelivery[],
|
|
61
|
+
): { result: CommitResult; created: CreatedDelivery[] };
|
|
103
62
|
/** Remove a freshly committed event when a downstream consumer failed. */
|
|
104
63
|
deleteIngestEvent(eventId: string): void;
|
|
105
64
|
enqueueDeliveries(
|
|
@@ -107,7 +66,7 @@ export interface ChannelState {
|
|
|
107
66
|
rule: RuleConfig,
|
|
108
67
|
targets: RuleTarget[],
|
|
109
68
|
payloads: string[],
|
|
110
|
-
):
|
|
69
|
+
): CreatedDelivery[];
|
|
111
70
|
nextPendingDelivery(accountKey: string, now: number): DeliveryRow | undefined;
|
|
112
71
|
markDelivery(deliveryId: string, state: DeliveryState, patch?: DeliveryPatch): void;
|
|
113
72
|
recordSent(input: SentRecordInput): string;
|
|
@@ -130,8 +89,6 @@ export interface ChannelState {
|
|
|
130
89
|
close(): void;
|
|
131
90
|
}
|
|
132
91
|
|
|
133
|
-
type RawRow = Record<string, unknown>;
|
|
134
|
-
|
|
135
92
|
function transaction<T>(db: StateDatabase, fn: () => T): T {
|
|
136
93
|
return db.transaction(fn).immediate();
|
|
137
94
|
}
|
|
@@ -141,37 +98,6 @@ function likePrefix(value: string): string {
|
|
|
141
98
|
return `${value.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
|
|
142
99
|
}
|
|
143
100
|
|
|
144
|
-
function toDelivery(row: RawRow): DeliveryRow {
|
|
145
|
-
return {
|
|
146
|
-
deliveryId: String(row.delivery_id),
|
|
147
|
-
eventId: String(row.event_id),
|
|
148
|
-
ruleId: String(row.rule_id),
|
|
149
|
-
ruleVersion: Number(row.rule_version),
|
|
150
|
-
target: String(row.target),
|
|
151
|
-
idempotencyKey: String(row.idempotency_key),
|
|
152
|
-
payload: String(row.payload),
|
|
153
|
-
state: String(row.state) as DeliveryState,
|
|
154
|
-
attemptCount: Number(row.attempt_count),
|
|
155
|
-
nextAttemptAt: row.next_attempt_at === null ? null : Number(row.next_attempt_at),
|
|
156
|
-
lastError: row.last_error === null ? null : String(row.last_error),
|
|
157
|
-
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
158
|
-
createdAt: Number(row.created_at),
|
|
159
|
-
updatedAt: Number(row.updated_at),
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function toReceipt(row: RawRow): ReceiptRow {
|
|
164
|
-
return {
|
|
165
|
-
receiptId: String(row.receipt_id),
|
|
166
|
-
deliveryId: String(row.delivery_id),
|
|
167
|
-
attemptId: String(row.attempt_id),
|
|
168
|
-
state: String(row.state),
|
|
169
|
-
providerMessage: row.provider_message === null ? null : String(row.provider_message),
|
|
170
|
-
detail: row.detail === null ? null : String(row.detail),
|
|
171
|
-
observedAt: Number(row.observed_at),
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
|
|
175
101
|
export function openState(path: string): ChannelState {
|
|
176
102
|
const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
|
|
177
103
|
return createChannelState(url ? new PgDatabase(url) : new Database(path));
|
|
@@ -189,24 +115,78 @@ export function createChannelState(db: StateDatabase): ChannelState {
|
|
|
189
115
|
return row ? toDelivery(row) : undefined;
|
|
190
116
|
}
|
|
191
117
|
|
|
118
|
+
function insertDeliveries(
|
|
119
|
+
triggerEventId: string,
|
|
120
|
+
entries: PlannedDelivery[],
|
|
121
|
+
now: number,
|
|
122
|
+
): CreatedDelivery[] {
|
|
123
|
+
const created: CreatedDelivery[] = [];
|
|
124
|
+
const insert = db.prepare(
|
|
125
|
+
`INSERT OR IGNORE INTO channel_deliveries
|
|
126
|
+
(delivery_id, event_id, rule_id, rule_version, target, idempotency_key, payload, state, created_at, updated_at)
|
|
127
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
|
|
128
|
+
);
|
|
129
|
+
for (const entry of entries) {
|
|
130
|
+
const idempotencyKey = `${triggerEventId}:${entry.ruleId}:${entry.ruleVersion}:0:${entry.target}`;
|
|
131
|
+
const deliveryId = `dlv-${randomUUID()}`;
|
|
132
|
+
const result = insert.run(
|
|
133
|
+
deliveryId,
|
|
134
|
+
triggerEventId,
|
|
135
|
+
entry.ruleId,
|
|
136
|
+
entry.ruleVersion,
|
|
137
|
+
entry.target,
|
|
138
|
+
idempotencyKey,
|
|
139
|
+
entry.payload,
|
|
140
|
+
now,
|
|
141
|
+
now,
|
|
142
|
+
);
|
|
143
|
+
if (Number(result.changes) > 0) {
|
|
144
|
+
created.push({
|
|
145
|
+
deliveryId,
|
|
146
|
+
target: entry.target,
|
|
147
|
+
ruleId: entry.ruleId,
|
|
148
|
+
ruleVersion: entry.ruleVersion,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return created;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function commitWithPlan(
|
|
156
|
+
event: IngestEvent,
|
|
157
|
+
plan: (stored: IngestEvent) => PlannedDelivery[],
|
|
158
|
+
): { result: CommitResult; created: CreatedDelivery[] } {
|
|
159
|
+
return transaction(db, () => {
|
|
160
|
+
const existing = db.prepare("SELECT event_id FROM channel_events WHERE dedup_key = ?").get(
|
|
161
|
+
event.sourceDedupKey,
|
|
162
|
+
) as RawRow | undefined;
|
|
163
|
+
if (existing) {
|
|
164
|
+
return {
|
|
165
|
+
result: { duplicate: true, existingEventId: String(existing.event_id) } as CommitResult,
|
|
166
|
+
created: [] as CreatedDelivery[],
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const max = db.prepare("SELECT COALESCE(MAX(ingress_seq), 0) AS seq FROM channel_events").get() as RawRow;
|
|
170
|
+
const ingressSeq = event.ingressSeq ?? Number(max.seq) + 1;
|
|
171
|
+
const stored = { ...event, ingressSeq };
|
|
172
|
+
db.prepare(
|
|
173
|
+
`INSERT INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
|
|
174
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
175
|
+
).run(event.eventId, event.sourceDedupKey, JSON.stringify(stored), ingressSeq, Date.now());
|
|
176
|
+
return {
|
|
177
|
+
result: { duplicate: false, eventId: event.eventId, ingressSeq } as CommitResult,
|
|
178
|
+
created: insertDeliveries(event.eventId, plan(stored), Date.now()),
|
|
179
|
+
};
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
192
183
|
return {
|
|
193
184
|
commitIngest(event: IngestEvent): CommitResult {
|
|
194
|
-
return
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
return { duplicate: true, existingEventId: String(existing.event_id) };
|
|
200
|
-
}
|
|
201
|
-
const max = db.prepare("SELECT COALESCE(MAX(ingress_seq), 0) AS seq FROM channel_events").get() as RawRow;
|
|
202
|
-
const ingressSeq = event.ingressSeq ?? Number(max.seq) + 1;
|
|
203
|
-
const stored = { ...event, ingressSeq };
|
|
204
|
-
db.prepare(
|
|
205
|
-
`INSERT INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
|
|
206
|
-
VALUES (?, ?, ?, ?, ?)`,
|
|
207
|
-
).run(event.eventId, event.sourceDedupKey, JSON.stringify(stored), ingressSeq, Date.now());
|
|
208
|
-
return { duplicate: false, eventId: event.eventId, ingressSeq };
|
|
209
|
-
});
|
|
185
|
+
return commitWithPlan(event, () => []).result;
|
|
186
|
+
},
|
|
187
|
+
|
|
188
|
+
commitIngestWithPlan(event, plan) {
|
|
189
|
+
return commitWithPlan(event, plan);
|
|
210
190
|
},
|
|
211
191
|
|
|
212
192
|
deleteIngestEvent(eventId) {
|
|
@@ -217,31 +197,15 @@ export function createChannelState(db: StateDatabase): ChannelState {
|
|
|
217
197
|
if (targets.length !== payloads.length) {
|
|
218
198
|
throw new Error("enqueueDeliveries: targets and payloads must have the same length");
|
|
219
199
|
}
|
|
220
|
-
const
|
|
221
|
-
|
|
200
|
+
const entries: PlannedDelivery[] = targets.map((target, index) => ({
|
|
201
|
+
ruleId: rule.id,
|
|
202
|
+
ruleVersion: rule.version,
|
|
203
|
+
target: `${target.platform}/${target.account}/${target.room}`,
|
|
204
|
+
payload: payloads[index] ?? "",
|
|
205
|
+
}));
|
|
206
|
+
let created: CreatedDelivery[] = [];
|
|
222
207
|
transaction(db, () => {
|
|
223
|
-
|
|
224
|
-
`INSERT OR IGNORE INTO channel_deliveries
|
|
225
|
-
(delivery_id, event_id, rule_id, rule_version, target, idempotency_key, payload, state, created_at, updated_at)
|
|
226
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
|
|
227
|
-
);
|
|
228
|
-
targets.forEach((target, index) => {
|
|
229
|
-
const key = `${target.platform}/${target.account}/${target.room}`;
|
|
230
|
-
const idempotencyKey = `${triggerEventId}:${rule.id}:${rule.version}:0:${key}`;
|
|
231
|
-
const deliveryId = `dlv-${randomUUID()}`;
|
|
232
|
-
const result = insert.run(
|
|
233
|
-
deliveryId,
|
|
234
|
-
triggerEventId,
|
|
235
|
-
rule.id,
|
|
236
|
-
rule.version,
|
|
237
|
-
key,
|
|
238
|
-
idempotencyKey,
|
|
239
|
-
payloads[index] ?? "",
|
|
240
|
-
now,
|
|
241
|
-
now,
|
|
242
|
-
);
|
|
243
|
-
if (Number(result.changes) > 0) created.push({ deliveryId, target: key });
|
|
244
|
-
});
|
|
208
|
+
created = insertDeliveries(triggerEventId, entries, Date.now());
|
|
245
209
|
});
|
|
246
210
|
return created;
|
|
247
211
|
},
|
|
@@ -286,6 +250,14 @@ export function createChannelState(db: StateDatabase): ChannelState {
|
|
|
286
250
|
const receiptId = `rcp-${randomUUID()}`;
|
|
287
251
|
const observedAt = input.observedAt ?? Date.now();
|
|
288
252
|
transaction(db, () => {
|
|
253
|
+
// The provider already accepted: mark sent, receipt and echo in one
|
|
254
|
+
// transaction. A DB failure leaves the row in_flight, never re-sent here.
|
|
255
|
+
const updated = db.prepare(
|
|
256
|
+
`UPDATE channel_deliveries
|
|
257
|
+
SET state = 'sent', next_attempt_at = NULL, last_error = NULL, provider_message = ?, updated_at = ?
|
|
258
|
+
WHERE delivery_id = ?`,
|
|
259
|
+
).run(input.providerMessage, observedAt, input.deliveryId);
|
|
260
|
+
if (Number(updated.changes) === 0) throw new Error(`delivery not found: ${input.deliveryId}`);
|
|
289
261
|
db.prepare(
|
|
290
262
|
`INSERT INTO channel_receipts
|
|
291
263
|
(receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
|
package/plugin.ts
CHANGED
|
@@ -36,10 +36,12 @@ import { readAgentResource, resourceReadFailure } from "./src/rooms/resource-rea
|
|
|
36
36
|
import { adminTool, adminToolDescription, adminToolSchema } from "./src/agent/admin-client.ts";
|
|
37
37
|
import { runReminderTool } from "./src/center/reminder-client.ts";
|
|
38
38
|
import { loadRoomConfig, resolveClientSettings } from "./src/config/file-config.ts";
|
|
39
|
+
import { configureNotificationDelay } from "./src/center/notification-delay.ts";
|
|
39
40
|
// ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
|
|
40
41
|
// central server); unset = standalone local-file mode. A chatroom.json(c)/yaml
|
|
41
42
|
// file is the shared fallback; environment variables still override it.
|
|
42
43
|
const connection = resolveClientSettings(loadRoomConfig());
|
|
44
|
+
configureNotificationDelay(connection);
|
|
43
45
|
const centerUrl = connection.url;
|
|
44
46
|
const centerToken = connection.token;
|
|
45
47
|
// A configured OpenCode serve URL is required to wake exited sessions.
|
|
@@ -271,10 +273,15 @@ function actionableError(error: unknown): string {
|
|
|
271
273
|
}
|
|
272
274
|
|
|
273
275
|
export const roomArgs = z.object({
|
|
274
|
-
action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "get_message", "catch_up", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
|
|
276
|
+
action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "get_message", "catch_up", "members", "forward_targets", "forward", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
|
|
275
277
|
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."),
|
|
276
278
|
roomId: z.string().optional().describe("Room UUID, not the room name. Required for resource actions and every room-scoped action."),
|
|
277
|
-
messageId: z.string().optional().describe("For recall and
|
|
279
|
+
messageId: z.string().optional().describe("For recall, get_message and forward: the full message ID returned by send, poll, or catch_up."),
|
|
280
|
+
target: z.object({
|
|
281
|
+
platform: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target platform identifier from forward_targets."),
|
|
282
|
+
account: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target account identifier from forward_targets."),
|
|
283
|
+
room: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/).describe("Target room identifier from forward_targets."),
|
|
284
|
+
}).optional().describe("For forward: one exact ready target from forward_targets; tool arguments cannot choose credentials."),
|
|
278
285
|
resourceId: z.string().optional().describe("Resource UUID returned by upload_resource. read_resource and delete_resource also require roomId."),
|
|
279
286
|
filePath: z.string().optional().describe("Absolute path to a regular local file to upload; central mode only; requires host read permission."),
|
|
280
287
|
text: z.string().max(5000).optional().describe("Message text, at most 5000 characters; required for send."),
|
|
@@ -303,6 +310,12 @@ export const roomArgs = z.object({
|
|
|
303
310
|
if (args.action === "join" && !args.name?.trim()) {
|
|
304
311
|
ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room; pass your participant display name" });
|
|
305
312
|
}
|
|
313
|
+
if (args.action === "forward" && !args.messageId) {
|
|
314
|
+
ctx.addIssue({ code: "custom", path: ["messageId"], message: "messageId is required to forward; send the reply first" });
|
|
315
|
+
}
|
|
316
|
+
if (args.action === "forward" && !args.target) {
|
|
317
|
+
ctx.addIssue({ code: "custom", path: ["target"], message: "target is required for forward; run forward_targets first" });
|
|
318
|
+
}
|
|
306
319
|
});
|
|
307
320
|
type RoomArguments = z.infer<typeof roomArgs>;
|
|
308
321
|
|
|
@@ -334,7 +347,7 @@ const roomExecute = async (
|
|
|
334
347
|
// (skipped for poll: poll itself pulls the inbox, so racing the
|
|
335
348
|
// fire-and-forget check would read the position it just advanced;
|
|
336
349
|
// get_message and catch_up stay read-only: no delivery, ack or wake)
|
|
337
|
-
if (args.action !== "poll" && args.action !== "get_message" && args.action !== "catch_up") {
|
|
350
|
+
if (args.action !== "poll" && args.action !== "get_message" && args.action !== "catch_up" && args.action !== "forward_targets") {
|
|
338
351
|
void checkCenterInbox(runtime.center, context.sessionID, runtime.transport);
|
|
339
352
|
}
|
|
340
353
|
return await centerAction(runtime.center, {
|
|
@@ -361,6 +374,9 @@ const roomExecute = async (
|
|
|
361
374
|
if (announcementResult !== undefined) return announcementResult;
|
|
362
375
|
const taskResult = await runTaskTool(args, context.sessionID);
|
|
363
376
|
if (taskResult !== undefined) return taskResult;
|
|
377
|
+
if (args.action === "forward_targets" || args.action === "forward") {
|
|
378
|
+
return `error: ${args.action} requires central server mode (CHAT_ROOM_SERVER_URL)`;
|
|
379
|
+
}
|
|
364
380
|
// ponytail: act as the identity this session registered with on join
|
|
365
381
|
let selfName = identity();
|
|
366
382
|
let joinPrevName: string | undefined;
|
|
@@ -554,7 +570,7 @@ const roomExecute = async (
|
|
|
554
570
|
}
|
|
555
571
|
};
|
|
556
572
|
const room = tool({
|
|
557
|
-
description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake). Send accepts parentMessageId to reply to a message. List members, announcements and tasks; create, update and delete room tasks; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). 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. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. 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. Room joinPolicy \"approval\" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.",
|
|
573
|
+
description: "Chat room operations: create, join, leave and list rooms; send, poll and recall messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake). Send accepts parentMessageId to reply to a message. forward_targets lists the exact ready relay targets for this room; forward queues one already-sent reply to one listed target and reports queued, never delivered. List members, announcements and tasks; create, update and delete room tasks; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). 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. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. 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. Room joinPolicy \"approval\" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.",
|
|
558
574
|
args: roomArgs.shape,
|
|
559
575
|
execute: roomExecute,
|
|
560
576
|
});
|
package/server/app.ts
CHANGED
|
@@ -8,6 +8,8 @@ import { joinRequestRoutes } from "./join-requests.ts";
|
|
|
8
8
|
import { memberRoutes } from "./member-routes.ts";
|
|
9
9
|
import { messageRecallRoutes } from "./message-recall-routes.ts";
|
|
10
10
|
import { roomManagement } from "./newrooms.ts";
|
|
11
|
+
import { operatorRoutes } from "./operator-routes.ts";
|
|
12
|
+
import { resolveOperatorToken } from "./operator-auth.ts";
|
|
11
13
|
import { resourceRoutes } from "./resource-routes.ts";
|
|
12
14
|
import { roomReminderRoutes } from "./room-reminders.ts";
|
|
13
15
|
import { inboxRoutes } from "./routes/inbox.ts";
|
|
@@ -19,6 +21,7 @@ import { roomCreateRoute, roomDetailRoutes, roomListRoutes } from "./routes/room
|
|
|
19
21
|
export type AppOptions = {
|
|
20
22
|
here: string;
|
|
21
23
|
token?: string;
|
|
24
|
+
operatorToken?: string;
|
|
22
25
|
serveWakeUrl: string;
|
|
23
26
|
channeld: () => ChannelController | undefined;
|
|
24
27
|
};
|
|
@@ -30,10 +33,16 @@ const json = (body: unknown, status = 200) =>
|
|
|
30
33
|
});
|
|
31
34
|
|
|
32
35
|
export function createApp(options: AppOptions): (req: Request) => Promise<Response> {
|
|
36
|
+
// Resolve the opt-in operator token once; identity can change here only.
|
|
37
|
+
const operatorToken = resolveOperatorToken(options.operatorToken, options.token);
|
|
33
38
|
// Database callbacks finish synchronously before any HTTP or long-poll wait.
|
|
34
39
|
return async function handle(req: Request): Promise<Response> {
|
|
35
40
|
const url = new URL(req.url);
|
|
36
41
|
const p = url.pathname;
|
|
42
|
+
// The operator panel owns /system before any page, asset or shared-token path.
|
|
43
|
+
if (p === "/system" || p.startsWith("/system/")) {
|
|
44
|
+
return operatorRoutes(req, url, { here: options.here, token: operatorToken });
|
|
45
|
+
}
|
|
37
46
|
const page = await pageRoutes(req, url, options.here, options.channeld()?.enabled ?? false);
|
|
38
47
|
if (page) return page;
|
|
39
48
|
// ponytail: F1 — reject non-JSON POSTs; a text/plain simple request from a
|