@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,627 @@
|
|
|
1
|
+
import type { AccountConfig, ChannelConfig, RuleTarget } from "./config.ts";
|
|
2
|
+
import { AdapterProcess, type SendReceipt } from "./adapter.ts";
|
|
3
|
+
import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "./delivery.ts";
|
|
4
|
+
import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
|
|
5
|
+
import { IngestGate, type IngestResult } from "./ingest-gate.ts";
|
|
6
|
+
import { log } from "./log.ts";
|
|
7
|
+
import type { Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
|
|
8
|
+
import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
|
|
9
|
+
import type { ChannelAccountRuntime } from "./stats.ts";
|
|
10
|
+
import { sanitizeAccountError } from "./stats.ts";
|
|
11
|
+
import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
|
|
12
|
+
|
|
13
|
+
export type { IngestResult } from "./ingest-gate.ts";
|
|
14
|
+
|
|
15
|
+
export interface AdapterHandle {
|
|
16
|
+
start(): Promise<void>;
|
|
17
|
+
send(
|
|
18
|
+
deliveryId: string,
|
|
19
|
+
attemptId: string,
|
|
20
|
+
idempotencyKey: string,
|
|
21
|
+
target: Endpoint,
|
|
22
|
+
payload: unknown,
|
|
23
|
+
): Promise<SendReceipt>;
|
|
24
|
+
stop(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SpawnAdapterContext {
|
|
28
|
+
onIngest(event: IngestEvent): Promise<{ duplicate: boolean; eventId?: string }>;
|
|
29
|
+
onExit(code: number | null, signal: NodeJS.Signals | null): void;
|
|
30
|
+
onUnavailable(reason: string): void;
|
|
31
|
+
onStatus(status: { inbound?: string; detail?: string }): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type SpawnAdapter = (account: AccountConfig, context: SpawnAdapterContext) => AdapterHandle;
|
|
35
|
+
|
|
36
|
+
export interface HostDeps {
|
|
37
|
+
stateFactory?: (path: string) => ChannelState;
|
|
38
|
+
spawnAdapter?: SpawnAdapter;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
deliveryIntervalMs?: number;
|
|
41
|
+
onDeliveryResult?: DeliveryResultHandler;
|
|
42
|
+
/**
|
|
43
|
+
* Called once for a newly committed ingest event, never for duplicates or
|
|
44
|
+
* echoes. The host awaits it before reporting success: for an inbound
|
|
45
|
+
* notification, a rejection rolls the event back and becomes an ingest error
|
|
46
|
+
* so the provider retries instead of ACKing a lost message. Duplicate/replay
|
|
47
|
+
* suppression is durable via the event dedup key.
|
|
48
|
+
*/
|
|
49
|
+
onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
|
|
50
|
+
/** Events used as inbound room notifications must not match outbound rules. */
|
|
51
|
+
notificationOnly?: (event: IngestEvent) => boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function defaultSpawnAdapter(account: AccountConfig, context: SpawnAdapterContext): AdapterHandle {
|
|
55
|
+
return new AdapterProcess({ account, ...context });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class ChannelHost {
|
|
59
|
+
readonly #config: ChannelConfig;
|
|
60
|
+
readonly #stateFactory: (path: string) => ChannelState;
|
|
61
|
+
readonly #spawnAdapter: SpawnAdapter;
|
|
62
|
+
readonly #now: () => number;
|
|
63
|
+
readonly #deliveryIntervalMs: number;
|
|
64
|
+
readonly #onDeliveryResult?: DeliveryResultHandler;
|
|
65
|
+
readonly #onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
|
|
66
|
+
readonly #notificationOnly?: (event: IngestEvent) => boolean;
|
|
67
|
+
readonly #adapters = new Map<string, AdapterHandle>();
|
|
68
|
+
readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
69
|
+
readonly #inFlight = new Map<string, Set<string>>();
|
|
70
|
+
readonly #notified = new Set<string>();
|
|
71
|
+
readonly #active = new Set<Promise<void>>();
|
|
72
|
+
readonly #disabled = new Set<string>();
|
|
73
|
+
readonly #accountStates = new Map<string, ChannelAccountRuntime>();
|
|
74
|
+
readonly #gate = new IngestGate((accountId, _event, _error) => {
|
|
75
|
+
this.#disableAccount(accountId, "ingest barrier limit reached");
|
|
76
|
+
});
|
|
77
|
+
#state?: ChannelState;
|
|
78
|
+
#running = false;
|
|
79
|
+
#starting = false;
|
|
80
|
+
#stopReason?: string;
|
|
81
|
+
#idleTimer?: ReturnType<typeof setInterval>;
|
|
82
|
+
#rejectionHandler?: (reason: unknown) => void;
|
|
83
|
+
|
|
84
|
+
constructor(config: ChannelConfig, deps: HostDeps = {}) {
|
|
85
|
+
this.#config = config;
|
|
86
|
+
this.#stateFactory = deps.stateFactory ?? openState;
|
|
87
|
+
this.#spawnAdapter = deps.spawnAdapter ?? defaultSpawnAdapter;
|
|
88
|
+
this.#now = deps.now ?? Date.now;
|
|
89
|
+
this.#deliveryIntervalMs = deps.deliveryIntervalMs ?? 200;
|
|
90
|
+
this.#onDeliveryResult = deps.onDeliveryResult;
|
|
91
|
+
this.#onIngestCommitted = deps.onIngestCommitted;
|
|
92
|
+
this.#notificationOnly = deps.notificationOnly;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Account ids whose adapter failed to start or exited; their queues stay paused. */
|
|
96
|
+
get disabledAccounts(): readonly string[] {
|
|
97
|
+
return [...this.#disabled];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Live per-account state keyed by `platform/account`, including startup failures. */
|
|
101
|
+
get accountRuntimeStates(): ReadonlyMap<string, ChannelAccountRuntime> {
|
|
102
|
+
return new Map(this.#accountStates);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Read-only view for routes: unknown ids or platform mismatches are missing. */
|
|
106
|
+
targetStatus(platform: string, accountId: string): "ready" | "disabled" | "missing" {
|
|
107
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
108
|
+
if (!account || account.platform !== platform) return "missing";
|
|
109
|
+
return this.#disabled.has(accountId) ? "disabled" : "ready";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Latest provider message sent for a logical room message, for native replies. */
|
|
113
|
+
findProviderMessage(endpoint: Endpoint, logicalMessageId: string): MessageRef | undefined {
|
|
114
|
+
const state = this.#state;
|
|
115
|
+
if (!state || !logicalMessageId) return undefined;
|
|
116
|
+
const nativeMessageId = state.findProviderMessage(targetKey(endpoint), logicalMessageId);
|
|
117
|
+
return nativeMessageId ? { endpoint, nativeMessageId } : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async start(): Promise<void> {
|
|
121
|
+
if (this.#running) throw new Error("host is already running");
|
|
122
|
+
validateTargets(this.#config);
|
|
123
|
+
const state = this.#stateFactory(this.#config.stateFile);
|
|
124
|
+
this.#state = state;
|
|
125
|
+
this.#installRejectionGuard();
|
|
126
|
+
const configuredKeys = this.#config.accounts.map((account) => `${account.platform}/${account.id}`);
|
|
127
|
+
const abandoned = state.abandonUnconfiguredDeliveries(configuredKeys);
|
|
128
|
+
if (abandoned.length > 0) {
|
|
129
|
+
log.warn(`abandoned ${abandoned.length} deliveries for unconfigured accounts`);
|
|
130
|
+
for (const row of abandoned) {
|
|
131
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const resumed = state.resumePausedDeliveries();
|
|
135
|
+
if (resumed > 0) log.info(`resumed ${resumed} paused deliveries`);
|
|
136
|
+
const recovered = state.recoverInFlightDeliveries();
|
|
137
|
+
if (recovered > 0) log.warn(`recovered ${recovered} stale in-flight deliveries`);
|
|
138
|
+
|
|
139
|
+
this.#running = true;
|
|
140
|
+
this.#starting = true;
|
|
141
|
+
const started: string[] = [];
|
|
142
|
+
const failures: { id: string; reason: string }[] = [];
|
|
143
|
+
const tasks = this.#config.accounts.map(async (account) => {
|
|
144
|
+
let adapter: AdapterHandle | undefined;
|
|
145
|
+
try {
|
|
146
|
+
adapter = this.#spawnAdapter(account, {
|
|
147
|
+
onIngest: (event) => this.ingest(event),
|
|
148
|
+
onExit: (code, signal) => this.#handleExit(account.id, code, signal),
|
|
149
|
+
onUnavailable: (reason) => this.#disableAccount(account.id, reason),
|
|
150
|
+
onStatus: (status) => this.#handleAdapterStatus(account.id, status),
|
|
151
|
+
});
|
|
152
|
+
this.#adapters.set(account.id, adapter);
|
|
153
|
+
await adapter.start();
|
|
154
|
+
const current = this.#accountStates.get(`${account.platform}/${account.id}`);
|
|
155
|
+
this.#setAccountState(account, "started", current?.lastError);
|
|
156
|
+
this.#schedule(account.id);
|
|
157
|
+
return { id: account.id };
|
|
158
|
+
} catch (error) {
|
|
159
|
+
const reason = startFailureReason(account.id, error);
|
|
160
|
+
this.#setAccountState(account, "failed", reason);
|
|
161
|
+
this.#disabled.add(account.id);
|
|
162
|
+
log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
|
|
163
|
+
if (adapter) {
|
|
164
|
+
try {
|
|
165
|
+
await adapter.stop();
|
|
166
|
+
} catch {
|
|
167
|
+
// The account is already marked disabled.
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return { id: account.id, reason };
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const settled = await Promise.allSettled(tasks);
|
|
175
|
+
this.#starting = false;
|
|
176
|
+
settled.forEach((result, index) => {
|
|
177
|
+
const account = this.#config.accounts[index]!;
|
|
178
|
+
if (result.status === "fulfilled") {
|
|
179
|
+
const { id, reason } = result.value;
|
|
180
|
+
if (reason) failures.push({ id, reason });
|
|
181
|
+
else started.push(id);
|
|
182
|
+
} else {
|
|
183
|
+
const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
|
|
184
|
+
failures.push({ id: account.id, reason });
|
|
185
|
+
this.#setAccountState(account, "failed", reason);
|
|
186
|
+
this.#disabled.add(account.id);
|
|
187
|
+
log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
for (const account of this.#config.accounts) {
|
|
192
|
+
if (this.#disabled.has(account.id)) {
|
|
193
|
+
state.pauseAccountDeliveries(`${account.platform}/${account.id}`, "account disabled until restart");
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const usable = started.filter((accountId) => !this.#disabled.has(accountId));
|
|
198
|
+
if (usable.length === 0) {
|
|
199
|
+
this.#running = false;
|
|
200
|
+
this.#starting = false;
|
|
201
|
+
this.#clearIdle();
|
|
202
|
+
this.#removeRejectionGuard();
|
|
203
|
+
for (const timer of this.#timers.values()) clearTimeout(timer);
|
|
204
|
+
this.#timers.clear();
|
|
205
|
+
await this.#stopAdapters();
|
|
206
|
+
state.close();
|
|
207
|
+
this.#state = undefined;
|
|
208
|
+
this.#disabled.clear();
|
|
209
|
+
this.#accountStates.clear();
|
|
210
|
+
const detail = failures.map((failure) => `${failure.id}: ${failure.reason}`).join("; ");
|
|
211
|
+
throw new Error(`no adapters started${detail ? `: ${detail}` : ""}`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
for (const failure of failures) {
|
|
215
|
+
log.warn(`account ${failure.id} disabled until restart; queued deliveries paused`, {
|
|
216
|
+
account: failure.id,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
log.info(
|
|
220
|
+
`host started: ${usable.length} accounts, ${failures.length} disabled, ${this.#config.rules.length} rules`,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async ingest(event: IngestEvent): Promise<IngestResult> {
|
|
225
|
+
return this.#gate.run(event.source.accountId, event, (item) => this.#processIngest(item));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async #processIngest(event: IngestEvent): Promise<IngestResult> {
|
|
229
|
+
const state = this.#state;
|
|
230
|
+
if (!state) throw new Error("host is not running");
|
|
231
|
+
|
|
232
|
+
if (event.message) {
|
|
233
|
+
const endpoint = targetKey(event.message.endpoint);
|
|
234
|
+
if (state.findEcho(endpoint, event.message.nativeMessageId)) {
|
|
235
|
+
log.info("echo ingest skipped", { event: event.eventId });
|
|
236
|
+
return { duplicate: false, eventId: event.eventId };
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const result = state.commitIngest(event);
|
|
241
|
+
if (result.duplicate) {
|
|
242
|
+
log.info("duplicate ingest skipped", { event: result.existingEventId });
|
|
243
|
+
return { duplicate: true, eventId: result.existingEventId };
|
|
244
|
+
}
|
|
245
|
+
const stored: IngestEvent = { ...event, ingressSeq: result.ingressSeq };
|
|
246
|
+
log.info(`ingested ${stored.kind}`, { event: stored.eventId });
|
|
247
|
+
|
|
248
|
+
if (this.#onIngestCommitted) {
|
|
249
|
+
try {
|
|
250
|
+
await this.#onIngestCommitted(stored);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
253
|
+
// An inbound notification owns the ACK: roll back and fail the ingest so
|
|
254
|
+
// Feishu retries. Other consumer failures stay contained as before.
|
|
255
|
+
if (this.#notificationOnly?.(stored)) {
|
|
256
|
+
state.deleteIngestEvent(stored.eventId);
|
|
257
|
+
log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
log.warn(`onIngestCommitted failed: ${message}`, { event: stored.eventId });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (this.#notificationOnly?.(stored)) {
|
|
265
|
+
log.info("inbound notification only; outbound rules skipped", { event: stored.eventId });
|
|
266
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (stored.kind === "message.forward_requested") {
|
|
270
|
+
const selected = stored.selectedMessage;
|
|
271
|
+
const reason = !selected
|
|
272
|
+
? "selectedMessage is required"
|
|
273
|
+
: !sameEndpoint(selected.endpoint, stored.source)
|
|
274
|
+
? "selectedMessage is outside the source room"
|
|
275
|
+
: undefined;
|
|
276
|
+
if (reason) {
|
|
277
|
+
log.warn(`forward rejected: ${reason}`, { event: stored.eventId });
|
|
278
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const requestedTarget = stored.kind === "message.forward_requested" ? stored.requestedTarget : undefined;
|
|
283
|
+
for (const rule of matchRules(this.#config, stored)) {
|
|
284
|
+
const targets: RuleTarget[] = [];
|
|
285
|
+
const payloads: string[] = [];
|
|
286
|
+
for (const target of rule.to) {
|
|
287
|
+
const endpoint = toEndpoint(this.#config, rule.id, target);
|
|
288
|
+
if (requestedTarget && !sameEndpoint(endpoint, requestedTarget)) continue;
|
|
289
|
+
const plan = planPayload(rule, stored, endpoint);
|
|
290
|
+
if ("dropped" in plan) {
|
|
291
|
+
log.warn(
|
|
292
|
+
`rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`,
|
|
293
|
+
{ event: stored.eventId },
|
|
294
|
+
);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
targets.push(target);
|
|
298
|
+
payloads.push(JSON.stringify(plan.payload));
|
|
299
|
+
}
|
|
300
|
+
if (targets.length === 0) continue;
|
|
301
|
+
const created = state.enqueueDeliveries(stored.eventId, rule, targets, payloads);
|
|
302
|
+
for (const delivery of created) {
|
|
303
|
+
const endpoint = parseTarget(delivery.target);
|
|
304
|
+
if (endpoint && this.#disabled.has(endpoint.accountId)) {
|
|
305
|
+
state.markDelivery(delivery.deliveryId, "paused", {
|
|
306
|
+
lastError: "account disabled until restart",
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
|
|
310
|
+
delivery: delivery.deliveryId,
|
|
311
|
+
event: stored.eventId,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return { duplicate: false, eventId: stored.eventId };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async stop(options: { abortInFlight?: boolean } = {}): Promise<void> {
|
|
319
|
+
if (!this.#running && !this.#state) {
|
|
320
|
+
this.#clearIdle();
|
|
321
|
+
this.#removeRejectionGuard();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
this.#running = false;
|
|
325
|
+
this.#starting = false;
|
|
326
|
+
const stopReason = "relay runtime stopped";
|
|
327
|
+
this.#stopReason = stopReason;
|
|
328
|
+
this.#clearIdle();
|
|
329
|
+
for (const timer of this.#timers.values()) clearTimeout(timer);
|
|
330
|
+
this.#timers.clear();
|
|
331
|
+
if (options.abortInFlight) {
|
|
332
|
+
this.#settleInFlightUnknown(stopReason);
|
|
333
|
+
await this.#stopAdapters();
|
|
334
|
+
}
|
|
335
|
+
await Promise.allSettled([...this.#active]);
|
|
336
|
+
this.#settleInFlightUnknown(stopReason);
|
|
337
|
+
await this.#stopAdapters();
|
|
338
|
+
this.#state?.close();
|
|
339
|
+
this.#state = undefined;
|
|
340
|
+
this.#adapters.clear();
|
|
341
|
+
this.#inFlight.clear();
|
|
342
|
+
this.#notified.clear();
|
|
343
|
+
this.#disabled.clear();
|
|
344
|
+
this.#accountStates.clear();
|
|
345
|
+
this.#removeRejectionGuard();
|
|
346
|
+
log.info("host stopped");
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
#schedule(accountId: string): void {
|
|
350
|
+
if (!this.#running || this.#disabled.has(accountId)) return;
|
|
351
|
+
const timer = setTimeout(() => {
|
|
352
|
+
this.#timers.delete(accountId);
|
|
353
|
+
if (!this.#running) return;
|
|
354
|
+
const task = this.#drainOnce(accountId)
|
|
355
|
+
.catch((error: unknown) => {
|
|
356
|
+
log.error(`delivery loop failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
357
|
+
account: accountId,
|
|
358
|
+
});
|
|
359
|
+
})
|
|
360
|
+
.finally(() => {
|
|
361
|
+
this.#active.delete(task);
|
|
362
|
+
this.#schedule(accountId);
|
|
363
|
+
});
|
|
364
|
+
this.#active.add(task);
|
|
365
|
+
}, this.#deliveryIntervalMs);
|
|
366
|
+
this.#timers.set(accountId, timer);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async #drainOnce(accountId: string): Promise<void> {
|
|
370
|
+
if (!this.#running || this.#disabled.has(accountId)) return;
|
|
371
|
+
const state = this.#state;
|
|
372
|
+
const adapter = this.#adapters.get(accountId);
|
|
373
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
374
|
+
if (!state || !adapter || !account) return;
|
|
375
|
+
const accountKey = `${account.platform}/${account.id}`;
|
|
376
|
+
const row = state.nextPendingDelivery(accountKey, this.#now());
|
|
377
|
+
if (!row) return;
|
|
378
|
+
await this.#deliver(state, adapter, accountId, row);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async #deliver(
|
|
382
|
+
state: ChannelState,
|
|
383
|
+
adapter: AdapterHandle,
|
|
384
|
+
accountId: string,
|
|
385
|
+
row: DeliveryRow,
|
|
386
|
+
): Promise<void> {
|
|
387
|
+
const target = parseTarget(row.target);
|
|
388
|
+
if (!target) {
|
|
389
|
+
state.markDelivery(row.deliveryId, "permanent", { lastError: `invalid target: ${row.target}` });
|
|
390
|
+
state.recordReceipt({
|
|
391
|
+
deliveryId: row.deliveryId,
|
|
392
|
+
attemptId: "invalid-target",
|
|
393
|
+
state: "permanent",
|
|
394
|
+
detail: `invalid target: ${row.target}`,
|
|
395
|
+
});
|
|
396
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId: "invalid-target", notified: this.#notified });
|
|
397
|
+
log.error(`invalid target ${row.target}`, { account: accountId, delivery: row.deliveryId });
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const attempt = row.attemptCount + 1;
|
|
402
|
+
const attemptId = `att-${row.deliveryId}-${attempt}`;
|
|
403
|
+
state.markDelivery(row.deliveryId, "in_flight", { attemptCount: attempt });
|
|
404
|
+
const inFlight = this.#inFlight.get(accountId) ?? new Set<string>();
|
|
405
|
+
this.#inFlight.set(accountId, inFlight);
|
|
406
|
+
inFlight.add(row.deliveryId);
|
|
407
|
+
|
|
408
|
+
// Start the barrier synchronously before send; the finally below releases it
|
|
409
|
+
// only after applyReceipt commits the receipt and echo mapping. Sends are serial per account.
|
|
410
|
+
this.#gate.begin(accountId);
|
|
411
|
+
try {
|
|
412
|
+
let receipt: SendReceipt;
|
|
413
|
+
try {
|
|
414
|
+
receipt = await adapter.send(
|
|
415
|
+
row.deliveryId,
|
|
416
|
+
attemptId,
|
|
417
|
+
row.idempotencyKey,
|
|
418
|
+
target,
|
|
419
|
+
JSON.parse(row.payload) as unknown,
|
|
420
|
+
);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
|
|
423
|
+
} finally {
|
|
424
|
+
inFlight.delete(row.deliveryId);
|
|
425
|
+
}
|
|
426
|
+
// A host stop wins over a late send result: reload must not auto-resend.
|
|
427
|
+
if (this.#stopReason) receipt = { state: "unknown", detail: this.#stopReason };
|
|
428
|
+
applyReceipt(state, row, attemptId, accountId, receipt, this.#now());
|
|
429
|
+
notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId, notified: this.#notified });
|
|
430
|
+
} finally {
|
|
431
|
+
await this.#gate.finish(accountId, (event) => this.#processIngest(event));
|
|
432
|
+
if (this.#disabled.has(accountId)) {
|
|
433
|
+
this.#pauseAccountDeliveries(accountId, "account disabled until restart");
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Stop must never leave rows that the next host would auto-resend. */
|
|
439
|
+
#settleInFlightUnknown(reason: string): void {
|
|
440
|
+
const state = this.#state;
|
|
441
|
+
if (!state) return;
|
|
442
|
+
for (const [accountId, deliveryIds] of this.#inFlight) {
|
|
443
|
+
for (const deliveryId of deliveryIds) {
|
|
444
|
+
try {
|
|
445
|
+
state.markDelivery(deliveryId, "unknown", { lastError: reason });
|
|
446
|
+
notifyDeliveryResult(state, deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
447
|
+
} catch (error) {
|
|
448
|
+
this.#safeWarn(
|
|
449
|
+
`could not mark delivery unknown: ${error instanceof Error ? error.message : String(error)}`,
|
|
450
|
+
accountId,
|
|
451
|
+
deliveryId,
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
this.#inFlight.clear();
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
#pauseAccountDeliveries(accountId: string, reason: string): void {
|
|
460
|
+
const state = this.#state;
|
|
461
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
462
|
+
if (!state || !account) return;
|
|
463
|
+
try {
|
|
464
|
+
const paused = state.pauseAccountDeliveries(`${account.platform}/${account.id}`, reason);
|
|
465
|
+
if (paused > 0) {
|
|
466
|
+
log.info(`paused ${paused} deliveries for disabled account`, { account: accountId });
|
|
467
|
+
}
|
|
468
|
+
} catch (error) {
|
|
469
|
+
this.#safeWarn(
|
|
470
|
+
`could not pause deliveries: ${error instanceof Error ? error.message : String(error)}`,
|
|
471
|
+
accountId,
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Inbound health is advisory: failures must not disable a working outbound account. */
|
|
477
|
+
#handleAdapterStatus(accountId: string, status: { inbound?: string; detail?: string }): void {
|
|
478
|
+
if (this.#disabled.has(accountId)) return;
|
|
479
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
480
|
+
if (!account) return;
|
|
481
|
+
const key = `${account.platform}/${account.id}`;
|
|
482
|
+
if (status.inbound === "failed") {
|
|
483
|
+
const detail = sanitizeAccountError(`inbound failed: ${status.detail ?? "unknown"}`);
|
|
484
|
+
this.#accountStates.set(key, { state: "started", lastError: detail });
|
|
485
|
+
log.warn(detail, { account: accountId });
|
|
486
|
+
} else if (status.inbound === "ready") {
|
|
487
|
+
this.#accountStates.set(key, { state: "started" });
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
#setAccountState(
|
|
492
|
+
account: AccountConfig,
|
|
493
|
+
state: ChannelAccountRuntime["state"],
|
|
494
|
+
lastError?: string,
|
|
495
|
+
): void {
|
|
496
|
+
this.#accountStates.set(
|
|
497
|
+
`${account.platform}/${account.id}`,
|
|
498
|
+
lastError ? { state, lastError } : { state },
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
#disableAccount(accountId: string, reason: string): void {
|
|
503
|
+
if (this.#disabled.has(accountId)) return;
|
|
504
|
+
this.#disabled.add(accountId);
|
|
505
|
+
const account = this.#config.accounts.find((item) => item.id === accountId);
|
|
506
|
+
if (account) this.#setAccountState(account, "disabled", reason);
|
|
507
|
+
|
|
508
|
+
const timer = this.#timers.get(accountId);
|
|
509
|
+
if (timer) {
|
|
510
|
+
clearTimeout(timer);
|
|
511
|
+
this.#timers.delete(accountId);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const state = this.#state;
|
|
515
|
+
const inFlight = this.#inFlight.get(accountId);
|
|
516
|
+
if (state && inFlight && inFlight.size > 0) {
|
|
517
|
+
for (const deliveryId of inFlight) {
|
|
518
|
+
try {
|
|
519
|
+
state.markDelivery(deliveryId, "unknown", { lastError: reason });
|
|
520
|
+
notifyDeliveryResult(state, deliveryId, this.#onDeliveryResult, { notified: this.#notified });
|
|
521
|
+
} catch (error) {
|
|
522
|
+
this.#safeWarn(
|
|
523
|
+
`could not mark delivery unknown: ${error instanceof Error ? error.message : String(error)}`,
|
|
524
|
+
accountId,
|
|
525
|
+
deliveryId,
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
this.#inFlight.delete(accountId);
|
|
530
|
+
this.#safeWarn(`marked ${inFlight.size} in-flight deliveries unknown`, accountId);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
this.#pauseAccountDeliveries(accountId, reason);
|
|
534
|
+
|
|
535
|
+
try {
|
|
536
|
+
log.error(`account ${accountId} disabled: ${reason}`, { account: accountId });
|
|
537
|
+
} catch {
|
|
538
|
+
// Logging must not escape the disable path.
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
try {
|
|
542
|
+
const adapter = this.#adapters.get(accountId);
|
|
543
|
+
if (adapter) {
|
|
544
|
+
void adapter.stop().catch((error: unknown) => {
|
|
545
|
+
this.#safeWarn(
|
|
546
|
+
`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
547
|
+
accountId,
|
|
548
|
+
);
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
} catch (error) {
|
|
552
|
+
this.#safeWarn(
|
|
553
|
+
`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
554
|
+
accountId,
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
this.#maybeIdle();
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
#handleExit(accountId: string, code: number | null, signal: NodeJS.Signals | null): void {
|
|
561
|
+
try {
|
|
562
|
+
this.#disableAccount(accountId, `adapter exited (code=${code} signal=${signal})`);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
this.#safeWarn(
|
|
565
|
+
`disable after adapter exit failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
566
|
+
accountId,
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
#safeWarn(message: string, accountId: string, deliveryId?: string): void {
|
|
572
|
+
try {
|
|
573
|
+
log.warn(message, { account: accountId, delivery: deliveryId });
|
|
574
|
+
} catch {
|
|
575
|
+
// Never throw from a disable/exit path.
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
#maybeIdle(): void {
|
|
580
|
+
try {
|
|
581
|
+
if (!this.#running || this.#starting || this.#idleTimer) return;
|
|
582
|
+
if (!this.#config.accounts.every((account) => this.#disabled.has(account.id))) return;
|
|
583
|
+
log.warn("all accounts disabled; host idle until restart");
|
|
584
|
+
this.#idleTimer = setInterval(() => {}, 60_000);
|
|
585
|
+
} catch {
|
|
586
|
+
// Idle bookkeeping must not throw.
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
#clearIdle(): void {
|
|
591
|
+
if (!this.#idleTimer) return;
|
|
592
|
+
clearInterval(this.#idleTimer);
|
|
593
|
+
this.#idleTimer = undefined;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
#installRejectionGuard(): void {
|
|
597
|
+
if (this.#rejectionHandler) return;
|
|
598
|
+
this.#rejectionHandler = (reason: unknown) => {
|
|
599
|
+
try {
|
|
600
|
+
log.error(`unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
601
|
+
} catch {
|
|
602
|
+
// Last resort: never throw from the process guard.
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
process.on("unhandledRejection", this.#rejectionHandler);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
#removeRejectionGuard(): void {
|
|
609
|
+
const handler = this.#rejectionHandler;
|
|
610
|
+
if (!handler) return;
|
|
611
|
+
this.#rejectionHandler = undefined;
|
|
612
|
+
try {
|
|
613
|
+
process.off("unhandledRejection", handler);
|
|
614
|
+
} catch {
|
|
615
|
+
// Ignore a partially torn-down process.
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async #stopAdapters(): Promise<void> {
|
|
620
|
+
await Promise.allSettled([...this.#adapters.values()].map((adapter) => adapter.stop()));
|
|
621
|
+
this.#adapters.clear();
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
export function createHost(config: ChannelConfig, deps: HostDeps = {}): ChannelHost {
|
|
626
|
+
return new ChannelHost(config, deps);
|
|
627
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ChannelConfig, InboundRoute } from "./config.ts";
|
|
2
|
+
import type { IngestEvent } from "./protocol.ts";
|
|
3
|
+
|
|
4
|
+
const MAX_RELAY_TEXT = 4000;
|
|
5
|
+
|
|
6
|
+
/** Inbound routes that turn one committed external event into a room notification. */
|
|
7
|
+
export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): InboundRoute[] {
|
|
8
|
+
return config.inbound.filter((route) =>
|
|
9
|
+
route.from.platform === event.source.platform
|
|
10
|
+
&& route.from.account === event.source.accountId
|
|
11
|
+
&& route.from.room === event.source.roomId
|
|
12
|
+
&& (route.from.event === undefined || route.from.event === event.kind)
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Room-notification text. The native user id is opaque but stable; the account
|
|
18
|
+
* label shows which Feishu bot and avoids exposing the chat id in room content.
|
|
19
|
+
*/
|
|
20
|
+
export function inboundRoomText(event: IngestEvent, route: InboundRoute): string | undefined {
|
|
21
|
+
const text = event.content?.text?.trim();
|
|
22
|
+
if (!text) return undefined;
|
|
23
|
+
const actor = event.actor.nativeUserId || "unknown";
|
|
24
|
+
const body = text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text;
|
|
25
|
+
return `[Feishu ${route.from.account}] ${actor}: ${body}`;
|
|
26
|
+
}
|