@alexsun-top/opencode-chat-room 0.8.0 → 0.8.2
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 +52 -0
- package/LICENSE +2 -2
- package/README.md +40 -8
- package/README.zh-CN.md +40 -8
- package/cli.ts +27 -1
- package/dist/cli.js +5406 -3088
- package/package.json +25 -5
- package/packages/chat-room-channeld/README.md +111 -33
- package/packages/chat-room-channeld/src/adapter.ts +179 -7
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +142 -9
- package/packages/chat-room-channeld/src/inbound.ts +35 -0
- package/packages/chat-room-channeld/src/protocol.ts +52 -1
- package/packages/chat-room-channeld/src/rules.ts +7 -2
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/plugin.ts +1 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +21 -9
- package/server/assets/chat/admin.js +0 -2
- package/server/assets/chat/announcements.js +69 -8
- package/server/assets/chat/chat-background.js +177 -0
- package/server/assets/chat/confirm-dialog.js +0 -1
- package/server/assets/chat/create-room-dialog.js +0 -1
- package/server/assets/chat/diagram-viewer.js +7 -1
- package/server/assets/chat/doc-preview.js +251 -46
- package/server/assets/chat/events.js +16 -5
- package/server/assets/chat/files.js +53 -7
- package/server/assets/chat/image-zoom.js +8 -1
- package/server/assets/chat/index.js +6 -2
- package/server/assets/chat/integration-account-schema.js +99 -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 +648 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown-footnotes.js +1 -1
- package/server/assets/chat/markdown.js +45 -8
- package/server/assets/chat/messages.js +6 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/palette.js +6 -1
- package/server/assets/chat/panels.js +56 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +17 -6
- package/server/assets/chat/reminders.js +68 -9
- package/server/assets/chat/replies.js +0 -6
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/rooms.js +1 -6
- package/server/assets/chat/settings.js +98 -4
- package/server/assets/chat/shortcuts.js +0 -3
- package/server/assets/chat/side-pane.js +34 -10
- package/server/assets/chat/state.js +125 -12
- package/server/assets/chat/system-events.js +58 -0
- package/server/assets/chat/system-messages.js +32 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +119 -37
- package/server/assets/chat/window-controls.js +37 -0
- package/server/assets/code-highlight.css +71 -32
- package/server/assets/conversation.css +174 -31
- package/server/assets/doc-preview.css +40 -3
- package/server/assets/files.css +8 -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 +1605 -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/office/licenses/zrender-LICENSE.txt +29 -0
- 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 +80 -11
- package/server/assets/settings.css +185 -9
- package/server/assets/tasks.css +57 -7
- package/server/assets/window-controls.css +36 -0
- package/server/channel-attachments.ts +133 -0
- package/server/channel-integration.ts +572 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +274 -21
- package/server/chat-server.ts +32 -580
- package/server/chat.html +234 -34
- package/server/http-server.ts +3 -182
- package/server/manifest.webmanifest +1 -0
- 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 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +3 -11
- package/src/config/file-config.ts +7 -54
- 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/watch.ts +1 -1
- 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 +133 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +130 -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 +194 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +34 -0
- package/src/state/sqlite-state.ts +15 -897
- 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 +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- 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 +573 -0
- package/src/web/integration-rules.ts +26 -0
- package/src/web/integration-schema.ts +229 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -499
- package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -473
- package/server/assets/chat/forward.js +0 -69
|
@@ -1,473 +0,0 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { pathToFileURL } from "node:url";
|
|
4
|
-
import { createFrameReader, writeFrame } from "./framing.ts";
|
|
5
|
-
import {
|
|
6
|
-
EVENT_SCHEMA_VERSION,
|
|
7
|
-
MAX_FRAME_BYTES,
|
|
8
|
-
PROTOCOL_VERSION,
|
|
9
|
-
RPC_INTERNAL_ERROR,
|
|
10
|
-
RPC_METHOD_NOT_FOUND,
|
|
11
|
-
rpcError,
|
|
12
|
-
rpcResult,
|
|
13
|
-
type Endpoint,
|
|
14
|
-
} from "./protocol.ts";
|
|
15
|
-
|
|
16
|
-
const DEFAULT_BASE_URL = "https://open.feishu.cn";
|
|
17
|
-
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
18
|
-
const DEFAULT_RATE_LIMIT_MS = 1000;
|
|
19
|
-
const TOKEN_REFRESH_MARGIN_MS = 30 * 60_000;
|
|
20
|
-
const FALLBACK_TOKEN_TTL_SECONDS = 7200;
|
|
21
|
-
const TOKEN_INVALID_CODE = 99991663;
|
|
22
|
-
const RATE_LIMIT_CODES = new Set([230020, 99991400]);
|
|
23
|
-
|
|
24
|
-
type SendState = "sent" | "retryable" | "rate_limited" | "permanent" | "unsupported" | "unknown";
|
|
25
|
-
|
|
26
|
-
interface SendReceipt {
|
|
27
|
-
state: SendState;
|
|
28
|
-
providerMessage?: { endpoint: Endpoint; nativeMessageId: string };
|
|
29
|
-
retryAfterMs?: number;
|
|
30
|
-
detail?: string;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
interface FeishuConfig {
|
|
34
|
-
appId: string;
|
|
35
|
-
appSecret: string;
|
|
36
|
-
baseUrl: string;
|
|
37
|
-
timeoutMs: number;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
interface AdapterState {
|
|
41
|
-
accountId: string;
|
|
42
|
-
config?: FeishuConfig;
|
|
43
|
-
token?: string;
|
|
44
|
-
tokenExpiresAt: number;
|
|
45
|
-
started: boolean;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
interface SendTarget {
|
|
49
|
-
roomId?: unknown;
|
|
50
|
-
room?: unknown;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
interface SendParams {
|
|
54
|
-
idempotencyKey?: unknown;
|
|
55
|
-
target?: SendTarget;
|
|
56
|
-
payload?: unknown;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
interface RawResponse {
|
|
60
|
-
status: number;
|
|
61
|
-
headers: Headers;
|
|
62
|
-
body?: unknown;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
class FeishuTimeoutError extends Error {
|
|
66
|
-
constructor() {
|
|
67
|
-
super("feishu request timed out");
|
|
68
|
-
this.name = "FeishuTimeoutError";
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
class FeishuApiError extends Error {
|
|
73
|
-
constructor(
|
|
74
|
-
readonly code: number,
|
|
75
|
-
readonly msg: string,
|
|
76
|
-
readonly scope: "token" | "send",
|
|
77
|
-
) {
|
|
78
|
-
super(`feishu ${scope} code ${code}: ${msg}`);
|
|
79
|
-
this.name = "FeishuApiError";
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function logLine(accountId: string, message: string): void {
|
|
84
|
-
console.error(`feishu adapter ${accountId}: ${message}`);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** Stable 32-hex SHA-256 prefix used as the Feishu idempotent message uuid. */
|
|
88
|
-
export function deterministicUuid(idempotencyKey: string): string {
|
|
89
|
-
return createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 32);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
93
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function configFromEnv(env: NodeJS.ProcessEnv): FeishuConfig | { error: string } {
|
|
97
|
-
const appId = env.FEISHU_APP_ID;
|
|
98
|
-
const appSecret = env.FEISHU_APP_SECRET;
|
|
99
|
-
const missing: string[] = [];
|
|
100
|
-
if (!appId) missing.push("FEISHU_APP_ID");
|
|
101
|
-
if (!appSecret) missing.push("FEISHU_APP_SECRET");
|
|
102
|
-
if (!appId || !appSecret) {
|
|
103
|
-
return { error: `feishu adapter requires ${missing.join(" and ")}` };
|
|
104
|
-
}
|
|
105
|
-
const timeout = Number(env.FEISHU_HTTP_TIMEOUT_MS);
|
|
106
|
-
const timeoutMs = Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
|
|
107
|
-
const baseUrl = (env.FEISHU_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
108
|
-
return { appId, appSecret, baseUrl, timeoutMs };
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
async function fetchJson(url: string, init: RequestInit, timeoutMs: number): Promise<RawResponse> {
|
|
112
|
-
const controller = new AbortController();
|
|
113
|
-
let timedOut = false;
|
|
114
|
-
const timer = setTimeout(() => {
|
|
115
|
-
timedOut = true;
|
|
116
|
-
controller.abort();
|
|
117
|
-
}, timeoutMs);
|
|
118
|
-
try {
|
|
119
|
-
const response = await fetch(url, { ...init, signal: controller.signal });
|
|
120
|
-
const text = await response.text();
|
|
121
|
-
let body: unknown;
|
|
122
|
-
if (text.trim()) {
|
|
123
|
-
try {
|
|
124
|
-
body = JSON.parse(text);
|
|
125
|
-
} catch {
|
|
126
|
-
body = undefined;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return { status: response.status, headers: response.headers, body };
|
|
130
|
-
} catch (error) {
|
|
131
|
-
// A timeout means the request may already be in Feishu's hands.
|
|
132
|
-
if (timedOut) throw new FeishuTimeoutError();
|
|
133
|
-
throw error;
|
|
134
|
-
} finally {
|
|
135
|
-
clearTimeout(timer);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
async function requestToken(config: FeishuConfig): Promise<{ token: string; expiresAt: number }> {
|
|
140
|
-
const raw = await fetchJson(
|
|
141
|
-
`${config.baseUrl}/open-apis/auth/v3/tenant_access_token/internal`,
|
|
142
|
-
{
|
|
143
|
-
method: "POST",
|
|
144
|
-
headers: { "Content-Type": "application/json; charset=utf-8" },
|
|
145
|
-
body: JSON.stringify({ app_id: config.appId, app_secret: config.appSecret }),
|
|
146
|
-
},
|
|
147
|
-
config.timeoutMs,
|
|
148
|
-
);
|
|
149
|
-
const body = raw.body;
|
|
150
|
-
if (!isRecord(body) || typeof body.code !== "number") {
|
|
151
|
-
throw new Error("feishu token response was malformed");
|
|
152
|
-
}
|
|
153
|
-
if (body.code !== 0) {
|
|
154
|
-
throw new FeishuApiError(body.code, typeof body.msg === "string" ? body.msg : "", "token");
|
|
155
|
-
}
|
|
156
|
-
if (typeof body.tenant_access_token !== "string" || body.tenant_access_token.length === 0) {
|
|
157
|
-
throw new Error("feishu token response was malformed");
|
|
158
|
-
}
|
|
159
|
-
const expire =
|
|
160
|
-
typeof body.expire === "number" && body.expire > 0 ? body.expire : FALLBACK_TOKEN_TTL_SECONDS;
|
|
161
|
-
return { token: body.tenant_access_token, expiresAt: Date.now() + expire * 1000 };
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
async function ensureToken(config: FeishuConfig, state: AdapterState, force = false): Promise<string> {
|
|
165
|
-
if (!force && state.token && state.tokenExpiresAt - Date.now() > TOKEN_REFRESH_MARGIN_MS) {
|
|
166
|
-
return state.token;
|
|
167
|
-
}
|
|
168
|
-
const fresh = await requestToken(config);
|
|
169
|
-
state.token = fresh.token;
|
|
170
|
-
state.tokenExpiresAt = fresh.expiresAt;
|
|
171
|
-
logLine(state.accountId, "tenant token acquired");
|
|
172
|
-
return fresh.token;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
function errorCode(error: unknown): string | undefined {
|
|
176
|
-
const direct = (error as { code?: unknown } | null)?.code;
|
|
177
|
-
if (typeof direct === "string") return direct;
|
|
178
|
-
const cause = (error as { cause?: { code?: unknown } } | null)?.cause?.code;
|
|
179
|
-
return typeof cause === "string" ? cause : undefined;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
function networkFailure(error: unknown): SendReceipt {
|
|
183
|
-
const code = errorCode(error);
|
|
184
|
-
return { state: "retryable", detail: code ? `feishu network error (${code})` : "feishu network error" };
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function failureReceipt(error: unknown): SendReceipt {
|
|
188
|
-
if (error instanceof FeishuTimeoutError) {
|
|
189
|
-
return { state: "unknown", detail: error.message };
|
|
190
|
-
}
|
|
191
|
-
if (error instanceof FeishuApiError) {
|
|
192
|
-
if (RATE_LIMIT_CODES.has(error.code)) {
|
|
193
|
-
return { state: "rate_limited", retryAfterMs: DEFAULT_RATE_LIMIT_MS, detail: `feishu code ${error.code}` };
|
|
194
|
-
}
|
|
195
|
-
return { state: "permanent", detail: error.message };
|
|
196
|
-
}
|
|
197
|
-
if (error instanceof Error && error.message === "feishu token response was malformed") {
|
|
198
|
-
return { state: "permanent", detail: error.message };
|
|
199
|
-
}
|
|
200
|
-
return networkFailure(error);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
function parseRetryAfter(value: string | null): number {
|
|
204
|
-
if (!value) return DEFAULT_RATE_LIMIT_MS;
|
|
205
|
-
const seconds = Number(value.trim());
|
|
206
|
-
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
|
|
207
|
-
const date = Date.parse(value);
|
|
208
|
-
if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
|
|
209
|
-
return DEFAULT_RATE_LIMIT_MS;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function apiCode(raw: RawResponse): number | undefined {
|
|
213
|
-
return isRecord(raw.body) && typeof raw.body.code === "number" ? raw.body.code : undefined;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/** A Feishu business error, as opposed to an HTTP transport failure. */
|
|
217
|
-
function isApiFailure(raw: RawResponse): boolean {
|
|
218
|
-
const code = apiCode(raw);
|
|
219
|
-
return raw.status !== 429 && raw.status < 500 && code !== undefined && code !== 0;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
const CLIENT_ERROR_STATUSES = new Set([400, 401, 403, 404]);
|
|
223
|
-
|
|
224
|
-
function apiResponseDetail(body: unknown, status: number): string {
|
|
225
|
-
const code = isRecord(body) && typeof body.code === "number" ? body.code : undefined;
|
|
226
|
-
const msg = isRecord(body) && typeof body.msg === "string" ? body.msg : "";
|
|
227
|
-
if (code !== undefined && code !== 0) return msg ? `feishu code ${code}: ${msg}` : `feishu code ${code}`;
|
|
228
|
-
return `feishu http ${status}`;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
function mapSendResponse(raw: RawResponse, endpoint: Endpoint): SendReceipt {
|
|
232
|
-
if (raw.status === 429) {
|
|
233
|
-
return { state: "rate_limited", retryAfterMs: parseRetryAfter(raw.headers.get("retry-after")) };
|
|
234
|
-
}
|
|
235
|
-
if (raw.status >= 500) {
|
|
236
|
-
return { state: "retryable", detail: `feishu http ${raw.status}` };
|
|
237
|
-
}
|
|
238
|
-
const body = raw.body;
|
|
239
|
-
const code = apiCode(raw);
|
|
240
|
-
if (code !== undefined && RATE_LIMIT_CODES.has(code)) {
|
|
241
|
-
return {
|
|
242
|
-
state: "rate_limited",
|
|
243
|
-
retryAfterMs: parseRetryAfter(raw.headers.get("retry-after")),
|
|
244
|
-
detail: `feishu code ${code}`,
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
if (CLIENT_ERROR_STATUSES.has(raw.status)) {
|
|
248
|
-
return { state: "permanent", detail: apiResponseDetail(body, raw.status) };
|
|
249
|
-
}
|
|
250
|
-
if (!isRecord(body) || typeof body.code !== "number") {
|
|
251
|
-
return { state: "unknown", detail: "feishu response was malformed" };
|
|
252
|
-
}
|
|
253
|
-
if (body.code === 0) {
|
|
254
|
-
const data = isRecord(body.data) ? body.data : undefined;
|
|
255
|
-
const messageId = data && typeof data.message_id === "string" ? data.message_id : undefined;
|
|
256
|
-
if (raw.status >= 200 && raw.status < 300 && messageId) {
|
|
257
|
-
return { state: "sent", providerMessage: { endpoint, nativeMessageId: messageId } };
|
|
258
|
-
}
|
|
259
|
-
return { state: "unknown", detail: "feishu response was malformed" };
|
|
260
|
-
}
|
|
261
|
-
const msg = typeof body.msg === "string" ? body.msg : "";
|
|
262
|
-
return { state: "permanent", detail: msg ? `feishu code ${body.code}: ${msg}` : `feishu code ${body.code}` };
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
function postMessage(config: FeishuConfig, token: string, body: string): Promise<RawResponse> {
|
|
266
|
-
return fetchJson(
|
|
267
|
-
`${config.baseUrl}/open-apis/im/v1/messages?receive_id_type=chat_id`,
|
|
268
|
-
{
|
|
269
|
-
method: "POST",
|
|
270
|
-
headers: {
|
|
271
|
-
Authorization: `Bearer ${token}`,
|
|
272
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
273
|
-
},
|
|
274
|
-
body,
|
|
275
|
-
},
|
|
276
|
-
config.timeoutMs,
|
|
277
|
-
);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
async function sendMessage(
|
|
281
|
-
config: FeishuConfig,
|
|
282
|
-
state: AdapterState,
|
|
283
|
-
params: SendParams,
|
|
284
|
-
): Promise<SendReceipt> {
|
|
285
|
-
const target = params.target;
|
|
286
|
-
const chatId = target && typeof target.roomId === "string" && target.roomId
|
|
287
|
-
? target.roomId
|
|
288
|
-
: target && typeof target.room === "string"
|
|
289
|
-
? target.room
|
|
290
|
-
: undefined;
|
|
291
|
-
if (!chatId) return { state: "permanent", detail: "send target requires a room" };
|
|
292
|
-
const text = isRecord(params.payload) && typeof params.payload.text === "string"
|
|
293
|
-
? params.payload.text
|
|
294
|
-
: undefined;
|
|
295
|
-
if (text === undefined) return { state: "permanent", detail: "send payload.text must be a string" };
|
|
296
|
-
if (typeof params.idempotencyKey !== "string" || params.idempotencyKey.length === 0) {
|
|
297
|
-
return { state: "permanent", detail: "send requires an idempotency key" };
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
const endpoint = target as unknown as Endpoint;
|
|
301
|
-
// A Feishu interactive card renders Markdown; msg_type "text" would show it literally.
|
|
302
|
-
const card = {
|
|
303
|
-
config: { wide_screen_mode: true },
|
|
304
|
-
elements: [{ tag: "div", text: { tag: "lark_md", content: text } }],
|
|
305
|
-
};
|
|
306
|
-
const body = JSON.stringify({
|
|
307
|
-
receive_id: chatId,
|
|
308
|
-
msg_type: "interactive",
|
|
309
|
-
content: JSON.stringify(card),
|
|
310
|
-
uuid: deterministicUuid(params.idempotencyKey),
|
|
311
|
-
});
|
|
312
|
-
|
|
313
|
-
let token: string;
|
|
314
|
-
let raw: RawResponse;
|
|
315
|
-
try {
|
|
316
|
-
token = await ensureToken(config, state);
|
|
317
|
-
raw = await postMessage(config, token, body);
|
|
318
|
-
} catch (error) {
|
|
319
|
-
return failureReceipt(error);
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
if (raw.status !== 429 && raw.status < 500 && apiCode(raw) === TOKEN_INVALID_CODE) {
|
|
323
|
-
try {
|
|
324
|
-
token = await ensureToken(config, state, true);
|
|
325
|
-
raw = await postMessage(config, token, body);
|
|
326
|
-
} catch (error) {
|
|
327
|
-
return failureReceipt(error);
|
|
328
|
-
}
|
|
329
|
-
// A token that is still rejected after a forced refresh will not fix itself.
|
|
330
|
-
if (isApiFailure(raw) && apiCode(raw) === TOKEN_INVALID_CODE) {
|
|
331
|
-
return { state: "permanent", detail: `feishu code ${TOKEN_INVALID_CODE}` };
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
return mapSendResponse(raw, endpoint);
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
function startupFailureDetail(error: unknown): string {
|
|
338
|
-
if (error instanceof FeishuTimeoutError) return error.message;
|
|
339
|
-
if (error instanceof FeishuApiError) return error.message;
|
|
340
|
-
if (error instanceof Error && error.message === "feishu token response was malformed") return error.message;
|
|
341
|
-
const code = errorCode(error);
|
|
342
|
-
return code ? `feishu token request failed (${code})` : "feishu token request failed";
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
async function handleRequest(message: Record<string, unknown>, state: AdapterState): Promise<void> {
|
|
346
|
-
const rawId = message.id;
|
|
347
|
-
if (rawId === undefined) {
|
|
348
|
-
const failure = message.error as { message?: string } | undefined;
|
|
349
|
-
if (failure) logLine(state.accountId, `request failed: ${failure.message ?? "error"}`);
|
|
350
|
-
return;
|
|
351
|
-
}
|
|
352
|
-
if (typeof rawId !== "string" && typeof rawId !== "number") {
|
|
353
|
-
logLine(state.accountId, "request id must be a string or number");
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
const id = rawId;
|
|
357
|
-
const method = message.method;
|
|
358
|
-
if (typeof method !== "string") return;
|
|
359
|
-
|
|
360
|
-
if (method === "initialize") {
|
|
361
|
-
const config = configFromEnv(process.env);
|
|
362
|
-
if ("error" in config) {
|
|
363
|
-
await writeFrame(process.stdout, rpcError(id, RPC_INTERNAL_ERROR, config.error));
|
|
364
|
-
return;
|
|
365
|
-
}
|
|
366
|
-
state.config = config;
|
|
367
|
-
await writeFrame(
|
|
368
|
-
process.stdout,
|
|
369
|
-
rpcResult(id, {
|
|
370
|
-
version: PROTOCOL_VERSION,
|
|
371
|
-
eventSchema: EVENT_SCHEMA_VERSION,
|
|
372
|
-
maxFrameBytes: MAX_FRAME_BYTES,
|
|
373
|
-
accounts: {
|
|
374
|
-
[state.accountId]: {
|
|
375
|
-
send: { text: true, format: ["text", "markdown"], reply: "none", idempotency: "persistent_delivery_key" },
|
|
376
|
-
},
|
|
377
|
-
},
|
|
378
|
-
}),
|
|
379
|
-
);
|
|
380
|
-
return;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
if (method === "start") {
|
|
384
|
-
if (!state.config) {
|
|
385
|
-
await writeFrame(
|
|
386
|
-
process.stdout,
|
|
387
|
-
rpcError(id, RPC_INTERNAL_ERROR, "feishu adapter requires FEISHU_APP_ID and FEISHU_APP_SECRET"),
|
|
388
|
-
);
|
|
389
|
-
return;
|
|
390
|
-
}
|
|
391
|
-
try {
|
|
392
|
-
await ensureToken(state.config, state);
|
|
393
|
-
} catch (error) {
|
|
394
|
-
const detail = startupFailureDetail(error);
|
|
395
|
-
logLine(state.accountId, `token validation failed: ${detail}`);
|
|
396
|
-
await writeFrame(process.stdout, rpcError(id, RPC_INTERNAL_ERROR, detail));
|
|
397
|
-
return;
|
|
398
|
-
}
|
|
399
|
-
state.started = true;
|
|
400
|
-
await writeFrame(process.stdout, rpcResult(id, { ready: true }));
|
|
401
|
-
logLine(state.accountId, "ready (tenant token validated)");
|
|
402
|
-
return;
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
if (method === "send") {
|
|
406
|
-
if (!state.started || !state.config) {
|
|
407
|
-
await writeFrame(
|
|
408
|
-
process.stdout,
|
|
409
|
-
rpcResult(id, { state: "unknown", detail: "adapter is not started" } satisfies SendReceipt),
|
|
410
|
-
);
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
const receipt = await sendMessage(state.config, state, (message.params ?? {}) as SendParams);
|
|
414
|
-
if (receipt.state === "sent" && receipt.providerMessage) {
|
|
415
|
-
logLine(state.accountId, `send succeeded native=${receipt.providerMessage.nativeMessageId}`);
|
|
416
|
-
} else {
|
|
417
|
-
logLine(state.accountId, `send ${receipt.state}${receipt.detail ? `: ${receipt.detail}` : ""}`);
|
|
418
|
-
}
|
|
419
|
-
await writeFrame(process.stdout, rpcResult(id, receipt));
|
|
420
|
-
return;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
if (method === "ping") {
|
|
424
|
-
await writeFrame(process.stdout, rpcResult(id, { pong: true }));
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
if (method === "shutdown") {
|
|
429
|
-
await writeFrame(process.stdout, rpcResult(id, {}));
|
|
430
|
-
process.exit(0);
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
await writeFrame(process.stdout, rpcError(id, RPC_METHOD_NOT_FOUND, `method not found: ${method}`));
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
export function runFeishuAdapter(): Promise<void> {
|
|
437
|
-
const state: AdapterState = {
|
|
438
|
-
accountId: process.env.CHANNELD_ACCOUNT_ID ?? "feishu",
|
|
439
|
-
tokenExpiresAt: 0,
|
|
440
|
-
started: false,
|
|
441
|
-
};
|
|
442
|
-
const read = createFrameReader(
|
|
443
|
-
(message) => {
|
|
444
|
-
void handleRequest(message, state).catch((error: unknown) => {
|
|
445
|
-
logLine(state.accountId, `handler failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
446
|
-
});
|
|
447
|
-
},
|
|
448
|
-
(error) => logLine(state.accountId, `frame error: ${error.message}`),
|
|
449
|
-
);
|
|
450
|
-
process.stdin.on("data", (chunk: Buffer) => read(chunk));
|
|
451
|
-
logLine(state.accountId, "ready on stdio");
|
|
452
|
-
return new Promise((resolve) => {
|
|
453
|
-
process.stdin.once("end", resolve);
|
|
454
|
-
process.stdin.once("close", resolve);
|
|
455
|
-
});
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
function isDirectRun(): boolean {
|
|
459
|
-
const entry = process.argv[1];
|
|
460
|
-
if (!entry) return false;
|
|
461
|
-
try {
|
|
462
|
-
return pathToFileURL(path.resolve(entry)).href === import.meta.url;
|
|
463
|
-
} catch {
|
|
464
|
-
return false;
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
if (isDirectRun()) {
|
|
469
|
-
runFeishuAdapter().catch((error: unknown) => {
|
|
470
|
-
console.error(`feishu adapter failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
471
|
-
process.exit(1);
|
|
472
|
-
});
|
|
473
|
-
}
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
// Forwarding UI: the server lists configured targets, and a terminal system
|
|
2
|
-
// message reports the outcome. The dialog posts an explicit message ID and
|
|
3
|
-
// target; it never infers either from message text.
|
|
4
|
-
import { LS } from "./state.js";
|
|
5
|
-
|
|
6
|
-
const label = (target) => [target.platform, target.account, target.room].join(" / ");
|
|
7
|
-
|
|
8
|
-
export function initForward(app) {
|
|
9
|
-
const dialog = app.$("#forwardDialog"), list = app.$("#forwardTargets"), status = app.$("#forwardStatus");
|
|
10
|
-
const close = () => { if (dialog.open) dialog.close(); };
|
|
11
|
-
app.$("#btnCloseForward").addEventListener("click", close);
|
|
12
|
-
app.$("#btnCancelForward").addEventListener("click", close);
|
|
13
|
-
dialog.addEventListener("click", (event) => { if (event.target === dialog) close(); });
|
|
14
|
-
dialog.addEventListener("close", () => { status.textContent = ""; list.replaceChildren(); });
|
|
15
|
-
|
|
16
|
-
async function send(roomId, messageId, target) {
|
|
17
|
-
try {
|
|
18
|
-
await app.api(`/rooms/${encodeURIComponent(roomId)}/forward`, {
|
|
19
|
-
method: "POST",
|
|
20
|
-
body: JSON.stringify({
|
|
21
|
-
sessionID: LS.sessionID,
|
|
22
|
-
messageId,
|
|
23
|
-
target: { platform: target.platform, account: target.account, room: target.room },
|
|
24
|
-
}),
|
|
25
|
-
});
|
|
26
|
-
return true;
|
|
27
|
-
} catch (error) {
|
|
28
|
-
status.textContent = app.t("forwardFailed", { message: error?.message || "" });
|
|
29
|
-
return false;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function open(message, roomId) {
|
|
34
|
-
let targets = [];
|
|
35
|
-
try {
|
|
36
|
-
const data = await app.api(`/rooms/${encodeURIComponent(roomId)}/forward-targets?sessionID=${encodeURIComponent(LS.sessionID)}`);
|
|
37
|
-
targets = Array.isArray(data.targets) ? data.targets : [];
|
|
38
|
-
} catch (error) {
|
|
39
|
-
status.textContent = app.t(error?.status === 404 ? "forwardUnavailable" : "forwardLoadFailed");
|
|
40
|
-
if (!dialog.open) dialog.showModal();
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
if (targets.length === 0) {
|
|
44
|
-
status.textContent = app.t("forwardNoTargets");
|
|
45
|
-
if (!dialog.open) dialog.showModal();
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
if (targets.length === 1) {
|
|
49
|
-
if (!await app.confirmAction(app.t("forwardConfirm", { target: label(targets[0]) }))) return;
|
|
50
|
-
if (!await send(roomId, message.id, targets[0])) dialog.showModal();
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
for (const target of targets) {
|
|
54
|
-
const button = document.createElement("button");
|
|
55
|
-
button.type = "button"; button.className = "btn ghost small"; button.textContent = label(target);
|
|
56
|
-
button.addEventListener("click", () => { void send(roomId, message.id, target).then((ok) => { if (ok) close(); }); });
|
|
57
|
-
list.append(button);
|
|
58
|
-
}
|
|
59
|
-
dialog.showModal();
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
app.$("#msgList").addEventListener("click", (event) => {
|
|
63
|
-
const button = event.target.closest?.("[data-forward-message]");
|
|
64
|
-
const room = app.state.room;
|
|
65
|
-
if (!button || !room) return;
|
|
66
|
-
const message = room.messages.find((item) => item.id === button.dataset.forwardMessage);
|
|
67
|
-
if (message) void open(message, room.id);
|
|
68
|
-
});
|
|
69
|
-
}
|