@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.
- package/CHANGELOG.md +43 -1
- package/LICENSE +21 -0
- package/README.md +77 -36
- package/README.zh-CN.md +82 -41
- package/cli.ts +27 -1
- package/dist/cli.js +6905 -2764
- package/package.json +33 -3
- package/packages/chat-room-channeld/README.md +315 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
- package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
- package/packages/chat-room-channeld/src/adapter.ts +509 -0
- package/packages/chat-room-channeld/src/cli.ts +124 -0
- package/packages/chat-room-channeld/src/config.ts +269 -0
- package/packages/chat-room-channeld/src/delivery.ts +163 -0
- package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
- package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
- package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
- package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
- package/packages/chat-room-channeld/src/framing.ts +128 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
- package/packages/chat-room-channeld/src/host.ts +627 -0
- package/packages/chat-room-channeld/src/inbound.ts +26 -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 +502 -0
- package/packages/chat-room-channeld/src/stats.ts +209 -0
- package/plugin.ts +22 -5
- package/server/addressing-routes.ts +130 -0
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +3 -2
- package/server/assets/SHIKI-LICENSE +22 -0
- package/server/assets/base.css +24 -10
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +187 -39
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/forward.js +69 -0
- package/server/assets/chat/index.js +4 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +498 -0
- package/server/assets/chat/locales/de.js +45 -4
- package/server/assets/chat/locales/es.js +45 -4
- package/server/assets/chat/locales/fr.js +45 -4
- package/server/assets/chat/locales/it.js +45 -4
- package/server/assets/chat/locales/ja.js +45 -4
- package/server/assets/chat/locales/ko.js +45 -4
- package/server/assets/chat/markdown-footnotes.js +115 -0
- package/server/assets/chat/markdown.js +46 -43
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/palette.js +1 -1
- package/server/assets/chat/panels.js +36 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +15 -3
- package/server/assets/chat/reminders.js +69 -8
- package/server/assets/chat/replies.js +7 -1
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/shiki.js +87 -0
- package/server/assets/chat/side-pane.js +9 -3
- package/server/assets/chat/state.js +107 -11
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -12
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +74 -62
- package/server/assets/conversation.css +126 -25
- package/server/assets/doc-preview.css +36 -3
- package/server/assets/files.css +5 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1297 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +52 -8
- package/server/assets/settings.css +73 -1
- package/server/assets/shiki.bundle.js +152 -0
- package/server/assets/tasks.css +57 -7
- package/server/channel-integration.ts +519 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +557 -0
- package/server/chat-server.ts +33 -558
- package/server/chat.html +195 -22
- package/server/http-server.ts +3 -182
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +5 -2
- package/server/task-routes.ts +1 -1
- package/skills/chatroom/SKILL.md +1 -1
- package/src/center/center-client.ts +71 -1
- package/src/config/file-config.ts +29 -42
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/v2-plugin.ts +8 -2
- package/src/runtime/watch.ts +4 -3
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +148 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +121 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +87 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +33 -0
- package/src/state/sqlite-state.ts +15 -866
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +13 -3
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/http.mjs +16 -2
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +439 -0
- package/src/web/integration-rules.ts +22 -0
- package/src/web/integration-schema.ts +228 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
- package/server/assets/highlight-10.7.3.min.js +0 -1358
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { log } from "./log.ts";
|
|
2
|
+
import type { IngestEvent } from "./protocol.ts";
|
|
3
|
+
|
|
4
|
+
export interface IngestResult {
|
|
5
|
+
duplicate: boolean;
|
|
6
|
+
eventId?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type IngestProcessor = (event: IngestEvent) => Promise<IngestResult>;
|
|
10
|
+
export type OverflowHandler = (accountId: string, event: IngestEvent, error: Error) => void;
|
|
11
|
+
|
|
12
|
+
interface BufferedIngest {
|
|
13
|
+
event: IngestEvent;
|
|
14
|
+
resolve(result: IngestResult): void;
|
|
15
|
+
reject(error: Error): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface GateState {
|
|
19
|
+
sends: number;
|
|
20
|
+
draining: boolean;
|
|
21
|
+
queue: BufferedIngest[];
|
|
22
|
+
overflow?: Error;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const MAX_BUFFERED_INGESTS = 100;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Serializes inbound ingest handling behind in-flight sends per account. A
|
|
29
|
+
* counter, not a boolean, keeps buffered events parked until every started send
|
|
30
|
+
* has settled. Overflow is reported to the owner, which disables the account.
|
|
31
|
+
*/
|
|
32
|
+
export class IngestGate {
|
|
33
|
+
readonly #onOverflow: OverflowHandler;
|
|
34
|
+
readonly #gates = new Map<string, GateState>();
|
|
35
|
+
|
|
36
|
+
constructor(onOverflow: OverflowHandler) {
|
|
37
|
+
this.#onOverflow = onOverflow;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
begin(accountId: string): void {
|
|
41
|
+
const gate = this.#gate(accountId);
|
|
42
|
+
gate.sends += 1;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async finish(accountId: string, process: IngestProcessor): Promise<void> {
|
|
46
|
+
const gate = this.#gates.get(accountId);
|
|
47
|
+
if (!gate) return;
|
|
48
|
+
gate.sends = Math.max(0, gate.sends - 1);
|
|
49
|
+
if (gate.sends > 0 || gate.draining) return;
|
|
50
|
+
|
|
51
|
+
gate.draining = true;
|
|
52
|
+
try {
|
|
53
|
+
while (gate.queue.length > 0) {
|
|
54
|
+
const item = gate.queue.shift()!;
|
|
55
|
+
try {
|
|
56
|
+
item.resolve(await process(item.event));
|
|
57
|
+
} catch (error) {
|
|
58
|
+
item.reject(error instanceof Error ? error : new Error(String(error)));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} finally {
|
|
62
|
+
gate.draining = false;
|
|
63
|
+
if (gate.sends === 0 && gate.queue.length === 0) this.#gates.delete(accountId);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async run(accountId: string, event: IngestEvent, process: IngestProcessor): Promise<IngestResult> {
|
|
68
|
+
const gate = this.#gates.get(accountId);
|
|
69
|
+
if (!gate || (!gate.draining && gate.sends === 0)) return process(event);
|
|
70
|
+
if (gate.overflow) throw gate.overflow;
|
|
71
|
+
if (gate.queue.length >= MAX_BUFFERED_INGESTS) {
|
|
72
|
+
const error = new Error(
|
|
73
|
+
`ingest buffer overflow for account ${accountId}; limit ${MAX_BUFFERED_INGESTS}; event ${event.eventId} dropped`,
|
|
74
|
+
) as Error & { code?: string };
|
|
75
|
+
error.code = "ingest_buffer_overflow";
|
|
76
|
+
gate.overflow = error;
|
|
77
|
+
try {
|
|
78
|
+
log.error(error.message, { account: accountId, event: event.eventId });
|
|
79
|
+
} catch {
|
|
80
|
+
// Logging must not break the overflow path.
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
this.#onOverflow(accountId, event, error);
|
|
84
|
+
} catch (callbackError) {
|
|
85
|
+
try {
|
|
86
|
+
log.error(
|
|
87
|
+
`overflow handler failed: ${callbackError instanceof Error ? callbackError.message : String(callbackError)}`,
|
|
88
|
+
{ account: accountId },
|
|
89
|
+
);
|
|
90
|
+
} catch {
|
|
91
|
+
// Keep the overflow rejection.
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
return new Promise<IngestResult>((resolve, reject) => {
|
|
97
|
+
gate.queue.push({ event, resolve, reject });
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
#gate(accountId: string): GateState {
|
|
102
|
+
const existing = this.#gates.get(accountId);
|
|
103
|
+
if (existing) return existing;
|
|
104
|
+
const gate: GateState = { sends: 0, draining: false, queue: [] };
|
|
105
|
+
this.#gates.set(accountId, gate);
|
|
106
|
+
return gate;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface LogFields {
|
|
2
|
+
account?: string;
|
|
3
|
+
delivery?: string;
|
|
4
|
+
event?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function write(level: "INFO" | "WARN" | "ERROR", message: string, fields: LogFields = {}): void {
|
|
8
|
+
const parts = [new Date().toISOString(), level, message];
|
|
9
|
+
if (fields.account) parts.push(`account=${fields.account}`);
|
|
10
|
+
if (fields.delivery) parts.push(`delivery=${fields.delivery}`);
|
|
11
|
+
if (fields.event) parts.push(`event=${fields.event}`);
|
|
12
|
+
process.stderr.write(`${parts.join(" ")}\n`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Logger for protocol hosts: stderr only, one line per event. */
|
|
16
|
+
export const log = {
|
|
17
|
+
info(message: string, fields?: LogFields): void {
|
|
18
|
+
write("INFO", message, fields);
|
|
19
|
+
},
|
|
20
|
+
warn(message: string, fields?: LogFields): void {
|
|
21
|
+
write("WARN", message, fields);
|
|
22
|
+
},
|
|
23
|
+
error(message: string, fields?: LogFields): void {
|
|
24
|
+
write("ERROR", message, fields);
|
|
25
|
+
},
|
|
26
|
+
};
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { createFrameReader, writeFrame } from "./framing.ts";
|
|
4
|
+
import {
|
|
5
|
+
EVENT_SCHEMA_VERSION,
|
|
6
|
+
MAX_FRAME_BYTES,
|
|
7
|
+
PROTOCOL_VERSION,
|
|
8
|
+
RPC_METHOD_NOT_FOUND,
|
|
9
|
+
adapterRequestId,
|
|
10
|
+
rpcError,
|
|
11
|
+
rpcRequest,
|
|
12
|
+
rpcResult,
|
|
13
|
+
type Endpoint,
|
|
14
|
+
type IngestEvent,
|
|
15
|
+
} from "./protocol.ts";
|
|
16
|
+
|
|
17
|
+
interface SendParams {
|
|
18
|
+
attemptId: string;
|
|
19
|
+
target: Endpoint;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface MockOptions {
|
|
23
|
+
accountId: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function handleRequest(
|
|
27
|
+
message: Record<string, unknown>,
|
|
28
|
+
options: MockOptions,
|
|
29
|
+
state: { started: boolean; emitted: boolean; sequence: number },
|
|
30
|
+
): Promise<void> {
|
|
31
|
+
const rawId = message.id;
|
|
32
|
+
if (rawId === undefined) {
|
|
33
|
+
const failure = message.error as { message?: string } | undefined;
|
|
34
|
+
if (failure) console.error(`mock adapter ${options.accountId}: request failed: ${failure.message ?? "error"}`);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (typeof rawId !== "string" && typeof rawId !== "number") {
|
|
38
|
+
console.error(`mock adapter ${options.accountId}: request id must be a string or number`);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const id = rawId;
|
|
42
|
+
const method = message.method;
|
|
43
|
+
if (typeof method !== "string") return;
|
|
44
|
+
|
|
45
|
+
if (method === "initialize") {
|
|
46
|
+
const accounts = {
|
|
47
|
+
[options.accountId]: {
|
|
48
|
+
ingress: "durable_outbox",
|
|
49
|
+
ack: "after_host_commit",
|
|
50
|
+
send: { text: true, reply: "none", idempotency: "persistent_delivery_key" },
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
await writeFrame(
|
|
54
|
+
process.stdout,
|
|
55
|
+
rpcResult(id, {
|
|
56
|
+
version: PROTOCOL_VERSION,
|
|
57
|
+
eventSchema: EVENT_SCHEMA_VERSION,
|
|
58
|
+
maxFrameBytes: MAX_FRAME_BYTES,
|
|
59
|
+
accounts,
|
|
60
|
+
}),
|
|
61
|
+
);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (method === "start") {
|
|
66
|
+
state.started = true;
|
|
67
|
+
await writeFrame(process.stdout, rpcResult(id, { ready: true }));
|
|
68
|
+
if (process.env.CHANNELD_MOCK_EMIT === "1" && !state.emitted) {
|
|
69
|
+
state.emitted = true;
|
|
70
|
+
setTimeout(() => {
|
|
71
|
+
void emitIngest(options, state);
|
|
72
|
+
}, 50);
|
|
73
|
+
}
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (method === "send") {
|
|
78
|
+
const params = (message.params ?? {}) as SendParams;
|
|
79
|
+
const target = params.target;
|
|
80
|
+
const nativeMessageId = `mock-${params.attemptId}`;
|
|
81
|
+
console.error(
|
|
82
|
+
`mock adapter ${options.accountId}: send attempt=${params.attemptId} target=${target?.platform}/${target?.roomId}`,
|
|
83
|
+
);
|
|
84
|
+
const result = rpcResult(id, {
|
|
85
|
+
state: "sent",
|
|
86
|
+
providerMessage: { endpoint: target, nativeMessageId },
|
|
87
|
+
});
|
|
88
|
+
if (process.env.CHANNELD_MOCK_ECHO !== "1" || !target) {
|
|
89
|
+
await writeFrame(process.stdout, result);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const echo = rpcRequest(adapterRequestId(++state.sequence), "ingest", {
|
|
93
|
+
schemaVersion: EVENT_SCHEMA_VERSION,
|
|
94
|
+
eventId: `mock-echo-${nativeMessageId}`,
|
|
95
|
+
kind: "message.created",
|
|
96
|
+
source: {
|
|
97
|
+
platform: target.platform,
|
|
98
|
+
accountId: target.accountId,
|
|
99
|
+
roomId: target.roomId,
|
|
100
|
+
},
|
|
101
|
+
actor: { platform: target.platform, identityNamespace: "mock", nativeUserId: "mock-user" },
|
|
102
|
+
providerEventId: nativeMessageId,
|
|
103
|
+
sourceDedupKey: `mock-echo:${target.platform}/${target.accountId}/${target.roomId}:${nativeMessageId}`,
|
|
104
|
+
message: { endpoint: target, nativeMessageId },
|
|
105
|
+
receivedAt: new Date().toISOString(),
|
|
106
|
+
content: { text: "mock echo" },
|
|
107
|
+
} satisfies IngestEvent);
|
|
108
|
+
const delay = Number(process.env.CHANNELD_MOCK_ECHO_DELAY_MS ?? 0);
|
|
109
|
+
if (delay > 0) {
|
|
110
|
+
await writeFrame(process.stdout, echo);
|
|
111
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
112
|
+
await writeFrame(process.stdout, result);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
await writeLines([result, echo]);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (method === "ping") {
|
|
120
|
+
await writeFrame(process.stdout, rpcResult(id, { pong: true }));
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (method === "shutdown") {
|
|
125
|
+
await writeFrame(process.stdout, rpcResult(id, {}));
|
|
126
|
+
process.exit(0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
await writeFrame(process.stdout, rpcError(id, RPC_METHOD_NOT_FOUND, `method not found: ${method}`));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function writeLines(values: unknown[]): Promise<void> {
|
|
133
|
+
const text = `${values.map((value) => JSON.stringify(value)).join("\n")}\n`;
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
process.stdout.write(text, (error?: Error | null) => {
|
|
136
|
+
if (error) reject(error);
|
|
137
|
+
else resolve();
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function emitIngest(
|
|
143
|
+
options: MockOptions,
|
|
144
|
+
state: { started: boolean; sequence: number },
|
|
145
|
+
): Promise<void> {
|
|
146
|
+
if (!state.started) return;
|
|
147
|
+
const source: Endpoint = { platform: "mock", accountId: options.accountId, roomId: "in" };
|
|
148
|
+
const event: IngestEvent = {
|
|
149
|
+
schemaVersion: EVENT_SCHEMA_VERSION,
|
|
150
|
+
eventId: `mock-event-${options.accountId}`,
|
|
151
|
+
kind: "message.created",
|
|
152
|
+
source,
|
|
153
|
+
actor: { platform: "mock", identityNamespace: "mock", nativeUserId: "mock-user" },
|
|
154
|
+
providerEventId: `mock-provider-${options.accountId}`,
|
|
155
|
+
sourceDedupKey: `mock:${options.accountId}:hello-from-mock`,
|
|
156
|
+
message: { endpoint: source, nativeMessageId: `mock-native-${options.accountId}` },
|
|
157
|
+
receivedAt: new Date().toISOString(),
|
|
158
|
+
content: { text: "hello from mock" },
|
|
159
|
+
};
|
|
160
|
+
try {
|
|
161
|
+
await writeFrame(process.stdout, rpcRequest(adapterRequestId(++state.sequence), "ingest", event));
|
|
162
|
+
console.error(`mock adapter ${options.accountId}: ingest emitted`);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
console.error(
|
|
165
|
+
`mock adapter ${options.accountId}: ingest failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function runMockAdapter(): Promise<void> {
|
|
171
|
+
const options: MockOptions = { accountId: process.env.CHANNELD_ACCOUNT_ID ?? "mock" };
|
|
172
|
+
const state = { started: false, emitted: false, sequence: 0 };
|
|
173
|
+
const read = createFrameReader(
|
|
174
|
+
(message) => {
|
|
175
|
+
void handleRequest(message, options, state).catch((error: unknown) => {
|
|
176
|
+
console.error(
|
|
177
|
+
`mock adapter ${options.accountId}: handler failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
178
|
+
);
|
|
179
|
+
});
|
|
180
|
+
},
|
|
181
|
+
(error) => console.error(`mock adapter ${options.accountId}: frame error: ${error.message}`),
|
|
182
|
+
);
|
|
183
|
+
process.stdin.on("data", (chunk: Buffer) => read(chunk));
|
|
184
|
+
console.error(`mock adapter ${options.accountId}: ready on stdio`);
|
|
185
|
+
return new Promise((resolve) => {
|
|
186
|
+
process.stdin.once("end", resolve);
|
|
187
|
+
process.stdin.once("close", resolve);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function isDirectRun(): boolean {
|
|
192
|
+
const entry = process.argv[1];
|
|
193
|
+
if (!entry) return false;
|
|
194
|
+
try {
|
|
195
|
+
return pathToFileURL(path.resolve(entry)).href === import.meta.url;
|
|
196
|
+
} catch {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (isDirectRun()) {
|
|
202
|
+
runMockAdapter().catch((error: unknown) => {
|
|
203
|
+
console.error(`mock adapter failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
204
|
+
process.exit(1);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export const PROTOCOL_VERSION = 1;
|
|
2
|
+
export const EVENT_SCHEMA_VERSION = 1;
|
|
3
|
+
export const MAX_FRAME_BYTES = 1_048_576;
|
|
4
|
+
|
|
5
|
+
export type Endpoint = { platform: string; accountId: string; roomId: string };
|
|
6
|
+
|
|
7
|
+
export type MessageRef = {
|
|
8
|
+
endpoint: Endpoint;
|
|
9
|
+
nativeMessageId: string;
|
|
10
|
+
/** Optional preview text supplied by the adapter for quote transforms. */
|
|
11
|
+
text?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type ActorKey = { platform: string; identityNamespace: string; nativeUserId: string };
|
|
15
|
+
|
|
16
|
+
export interface IngestEvent {
|
|
17
|
+
schemaVersion: number;
|
|
18
|
+
eventId: string;
|
|
19
|
+
kind: string;
|
|
20
|
+
source: Endpoint;
|
|
21
|
+
actor: ActorKey;
|
|
22
|
+
providerEventId?: string;
|
|
23
|
+
sourceDedupKey: string;
|
|
24
|
+
message?: MessageRef;
|
|
25
|
+
parent?: MessageRef;
|
|
26
|
+
occurredAt?: string;
|
|
27
|
+
receivedAt: string;
|
|
28
|
+
content?: { text?: string; attachmentRefs?: string[] };
|
|
29
|
+
selectedMessage?: MessageRef;
|
|
30
|
+
requestedTarget?: Endpoint;
|
|
31
|
+
cause?: { rootEventId: string; visitedEndpoints: Endpoint[]; hopCount: number };
|
|
32
|
+
ingressSeq?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type JsonRpcId = string | number;
|
|
36
|
+
|
|
37
|
+
export type JsonRpcRequest = { jsonrpc: "2.0"; id: JsonRpcId; method: string; params?: unknown };
|
|
38
|
+
export type JsonRpcSuccess = { jsonrpc: "2.0"; id: JsonRpcId; result: unknown };
|
|
39
|
+
export type JsonRpcFailure = {
|
|
40
|
+
jsonrpc: "2.0";
|
|
41
|
+
id: JsonRpcId;
|
|
42
|
+
error: { code: number; message: string; data?: unknown };
|
|
43
|
+
};
|
|
44
|
+
export type JsonRpcMessage = JsonRpcRequest | JsonRpcSuccess | JsonRpcFailure;
|
|
45
|
+
|
|
46
|
+
export const HOST_ID_PREFIX = "host-";
|
|
47
|
+
export const ADAPTER_ID_PREFIX = "adapter-";
|
|
48
|
+
|
|
49
|
+
export const RPC_PARSE_ERROR = -32700;
|
|
50
|
+
export const RPC_INVALID_REQUEST = -32600;
|
|
51
|
+
export const RPC_METHOD_NOT_FOUND = -32601;
|
|
52
|
+
export const RPC_INTERNAL_ERROR = -32603;
|
|
53
|
+
|
|
54
|
+
export function hostRequestId(sequence: number): string {
|
|
55
|
+
return `${HOST_ID_PREFIX}${sequence}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function adapterRequestId(sequence: number): string {
|
|
59
|
+
return `${ADAPTER_ID_PREFIX}${sequence}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function rpcRequest(id: JsonRpcId, method: string, params?: unknown): JsonRpcRequest {
|
|
63
|
+
return params === undefined
|
|
64
|
+
? { jsonrpc: "2.0", id, method }
|
|
65
|
+
: { jsonrpc: "2.0", id, method, params };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function rpcResult(id: JsonRpcId, result: unknown): JsonRpcSuccess {
|
|
69
|
+
return { jsonrpc: "2.0", id, result };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function rpcError(id: JsonRpcId, code: number, message: string, data?: unknown): JsonRpcFailure {
|
|
73
|
+
const error = data === undefined ? { code, message } : { code, message, data };
|
|
74
|
+
return { jsonrpc: "2.0", id, error };
|
|
75
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { EVENT_SCHEMA_VERSION, type IngestEvent } from "./protocol.ts";
|
|
2
|
+
import type { DeliveryRow, DeliveryState, ReceiptRow } from "./state.ts";
|
|
3
|
+
|
|
4
|
+
export const PUBLISHED_RESULT_PREFIX = "result.published:";
|
|
5
|
+
|
|
6
|
+
export interface PublishedResultEvent extends IngestEvent {
|
|
7
|
+
forwardEventId: string;
|
|
8
|
+
deliveryId: string;
|
|
9
|
+
receiptId: string | null;
|
|
10
|
+
state: DeliveryState;
|
|
11
|
+
target: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Build the ids/state-only terminal result event. Never include message content or error detail. */
|
|
15
|
+
export function buildPublishedResult(
|
|
16
|
+
delivery: DeliveryRow,
|
|
17
|
+
receipt: ReceiptRow | undefined,
|
|
18
|
+
now: number,
|
|
19
|
+
): PublishedResultEvent {
|
|
20
|
+
const occurredAt = new Date(now).toISOString();
|
|
21
|
+
return {
|
|
22
|
+
schemaVersion: EVENT_SCHEMA_VERSION,
|
|
23
|
+
eventId: `result-${delivery.deliveryId}`,
|
|
24
|
+
kind: "result.published",
|
|
25
|
+
source: { platform: "channeld", accountId: "host", roomId: delivery.deliveryId },
|
|
26
|
+
actor: { platform: "channeld", identityNamespace: "system", nativeUserId: "channeld" },
|
|
27
|
+
sourceDedupKey: `${PUBLISHED_RESULT_PREFIX}${delivery.deliveryId}`,
|
|
28
|
+
cause: { rootEventId: delivery.eventId, visitedEndpoints: [], hopCount: 1 },
|
|
29
|
+
occurredAt,
|
|
30
|
+
receivedAt: occurredAt,
|
|
31
|
+
forwardEventId: delivery.eventId,
|
|
32
|
+
deliveryId: delivery.deliveryId,
|
|
33
|
+
receiptId: receipt?.receiptId ?? null,
|
|
34
|
+
state: delivery.state,
|
|
35
|
+
target: delivery.target,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { ConfigError, type ChannelConfig, type RuleConfig, type RuleTarget } from "./config.ts";
|
|
2
|
+
import type { Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
|
|
3
|
+
|
|
4
|
+
const QUOTE_PREVIEW_LIMIT = 280;
|
|
5
|
+
export const UNSUPPORTED_NOTICE = "attachment/format unsupported";
|
|
6
|
+
|
|
7
|
+
export type RenderResult = { text: string; degraded?: "empty" };
|
|
8
|
+
|
|
9
|
+
export type DeliveryPayload = {
|
|
10
|
+
text: string;
|
|
11
|
+
degraded?: "empty" | "unthreaded";
|
|
12
|
+
parent?: MessageRef;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export type PayloadPlan = { payload: DeliveryPayload } | { dropped: string };
|
|
16
|
+
|
|
17
|
+
export function targetKey(endpoint: Endpoint): string {
|
|
18
|
+
const parts = [endpoint.platform, endpoint.accountId, endpoint.roomId];
|
|
19
|
+
if (parts.some((part) => !part || part.includes("/"))) {
|
|
20
|
+
throw new ConfigError('config: platform, account and room must be non-empty and must not contain "/"');
|
|
21
|
+
}
|
|
22
|
+
return parts.join("/");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function sameEndpoint(left: Endpoint, right: Endpoint): boolean {
|
|
26
|
+
return left.platform === right.platform
|
|
27
|
+
&& left.accountId === right.accountId
|
|
28
|
+
&& left.roomId === right.roomId;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Match rules for an event. Only the highest configured version of each rule
|
|
33
|
+
* id is active; an explicit newer version replaces the older definition.
|
|
34
|
+
*/
|
|
35
|
+
export function matchRules(config: ChannelConfig, event: IngestEvent): RuleConfig[] {
|
|
36
|
+
if (event.kind === "result.published") return [];
|
|
37
|
+
const latest = new Map<string, RuleConfig>();
|
|
38
|
+
for (const rule of config.rules) {
|
|
39
|
+
const current = latest.get(rule.id);
|
|
40
|
+
if (!current || rule.version > current.version) latest.set(rule.id, rule);
|
|
41
|
+
}
|
|
42
|
+
return [...latest.values()]
|
|
43
|
+
.filter((rule) => {
|
|
44
|
+
const { from } = rule;
|
|
45
|
+
return from.platform === event.source.platform
|
|
46
|
+
&& from.account === event.source.accountId
|
|
47
|
+
&& from.room === event.source.roomId
|
|
48
|
+
&& (from.event === undefined || from.event === event.kind);
|
|
49
|
+
})
|
|
50
|
+
.sort((left, right) =>
|
|
51
|
+
left.id === right.id
|
|
52
|
+
? left.version - right.version
|
|
53
|
+
: left.id < right.id ? -1 : left.id > right.id ? 1 : 0,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Render the event text for one target. Transforms run in config order.
|
|
59
|
+
*/
|
|
60
|
+
export function renderForTarget(
|
|
61
|
+
rule: RuleConfig,
|
|
62
|
+
event: IngestEvent,
|
|
63
|
+
target: RuleTarget,
|
|
64
|
+
): RenderResult {
|
|
65
|
+
void target;
|
|
66
|
+
let text = event.content?.text ?? "";
|
|
67
|
+
if (!text) return { text: "", degraded: "empty" };
|
|
68
|
+
|
|
69
|
+
for (const transform of rule.transforms) {
|
|
70
|
+
switch (transform.op) {
|
|
71
|
+
case "prefix-source":
|
|
72
|
+
text = `[${event.source.platform}/${event.source.roomId}] ${text}`;
|
|
73
|
+
break;
|
|
74
|
+
case "trim":
|
|
75
|
+
text = text.trim();
|
|
76
|
+
break;
|
|
77
|
+
case "truncate":
|
|
78
|
+
if (text.length > transform.max) text = `${text.slice(0, transform.max)}…`;
|
|
79
|
+
break;
|
|
80
|
+
case "quote-preview": {
|
|
81
|
+
const quote = event.selectedMessage?.text?.trim();
|
|
82
|
+
if (quote) {
|
|
83
|
+
const short = quote.length > QUOTE_PREVIEW_LIMIT
|
|
84
|
+
? `${quote.slice(0, QUOTE_PREVIEW_LIMIT)}…`
|
|
85
|
+
: quote;
|
|
86
|
+
text = `${text}\n> ${short}`;
|
|
87
|
+
}
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (!text) return { text: "", degraded: "empty" };
|
|
94
|
+
return { text };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Build the frozen payload for one target. Unsupported content follows
|
|
99
|
+
* onUnsupported; replies whose parent endpoint is not the target endpoint
|
|
100
|
+
* follow onMissingParent.
|
|
101
|
+
*/
|
|
102
|
+
export function planPayload(rule: RuleConfig, event: IngestEvent, target: Endpoint): PayloadPlan {
|
|
103
|
+
const rendered = renderForTarget(rule, event, {
|
|
104
|
+
platform: target.platform,
|
|
105
|
+
account: target.accountId,
|
|
106
|
+
room: target.roomId,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
let payload: DeliveryPayload;
|
|
110
|
+
if (rendered.degraded === "empty") {
|
|
111
|
+
if (rule.onUnsupported === "drop") return { dropped: "rendered text is empty" };
|
|
112
|
+
payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
|
|
113
|
+
} else {
|
|
114
|
+
payload = { text: rendered.text };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (event.parent) {
|
|
118
|
+
if (sameEndpoint(event.parent.endpoint, target)) {
|
|
119
|
+
payload.parent = event.parent;
|
|
120
|
+
} else if (rule.onMissingParent === "drop") {
|
|
121
|
+
return { dropped: "parent message mapping is unavailable" };
|
|
122
|
+
} else {
|
|
123
|
+
payload.degraded = "unthreaded";
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { payload };
|
|
127
|
+
}
|