@alexsun-top/opencode-chat-room 0.7.7 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/LICENSE +21 -0
- package/README.md +45 -36
- package/README.zh-CN.md +50 -41
- package/dist/cli.js +2696 -365
- package/package.json +14 -4
- package/packages/chat-room-channeld/README.md +242 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
- package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
- package/packages/chat-room-channeld/src/adapter.ts +475 -0
- package/packages/chat-room-channeld/src/cli.ts +124 -0
- package/packages/chat-room-channeld/src/config.ts +207 -0
- package/packages/chat-room-channeld/src/delivery.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
- package/packages/chat-room-channeld/src/framing.ts +128 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
- package/packages/chat-room-channeld/src/host.ts +509 -0
- package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
- package/packages/chat-room-channeld/src/log.ts +26 -0
- package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
- package/packages/chat-room-channeld/src/protocol.ts +75 -0
- package/packages/chat-room-channeld/src/published.ts +37 -0
- package/packages/chat-room-channeld/src/rules.ts +127 -0
- package/packages/chat-room-channeld/src/state.ts +485 -0
- package/packages/chat-room-channeld/src/stats.ts +167 -0
- package/plugin.ts +22 -5
- package/server/addressing-routes.ts +130 -0
- package/server/assets/NOTICE.txt +2 -2
- package/server/assets/SHIKI-LICENSE +22 -0
- package/server/assets/base.css +9 -1
- package/server/assets/chat/announcements.js +5 -2
- package/server/assets/chat/clipboard.js +30 -0
- package/server/assets/chat/copy-action.js +48 -0
- package/server/assets/chat/diagram-viewer.js +253 -0
- package/server/assets/chat/doc-preview.js +149 -12
- package/server/assets/chat/events.js +25 -4
- package/server/assets/chat/files.js +26 -5
- package/server/assets/chat/forward.js +69 -0
- package/server/assets/chat/history-loader.js +3 -1
- package/server/assets/chat/index.js +11 -1
- package/server/assets/chat/join-requests.js +6 -3
- package/server/assets/chat/locales/de.js +7 -2
- package/server/assets/chat/locales/es.js +7 -2
- package/server/assets/chat/locales/fr.js +7 -2
- package/server/assets/chat/locales/it.js +7 -2
- package/server/assets/chat/locales/ja.js +7 -2
- package/server/assets/chat/locales/ko.js +7 -2
- package/server/assets/chat/markdown-footnotes.js +115 -0
- package/server/assets/chat/markdown.js +65 -113
- package/server/assets/chat/messages.js +6 -3
- package/server/assets/chat/palette.js +33 -16
- package/server/assets/chat/pwa.js +2 -0
- package/server/assets/chat/questions.js +5 -0
- package/server/assets/chat/replies.js +7 -1
- package/server/assets/chat/resource-format.js +74 -0
- package/server/assets/chat/rooms.js +3 -0
- package/server/assets/chat/shiki.js +87 -0
- package/server/assets/chat/side-pane.js +143 -0
- package/server/assets/chat/state.js +63 -9
- package/server/assets/chat/system-messages.js +2 -0
- package/server/assets/chat/task-row.js +2 -1
- package/server/assets/chat/tasks.js +29 -2
- package/server/assets/chat/viewport.js +5 -0
- package/server/assets/code-highlight.css +20 -31
- package/server/assets/conversation.css +27 -2
- package/server/assets/diagram-viewer.css +141 -0
- package/server/assets/doc-preview.css +26 -6
- package/server/assets/responsive.css +87 -13
- package/server/assets/shiki.bundle.js +152 -0
- package/server/assets/tasks.css +1 -4
- package/server/channels.ts +314 -0
- package/server/chat-server.ts +36 -8
- package/server/chat.html +33 -5
- package/server/resource-routes.ts +3 -1
- package/server/sw.js +236 -4
- package/skills/chatroom/SKILL.md +1 -1
- package/src/agent/chatroom-skill.ts +8 -2
- package/src/center/center-client.ts +79 -1
- package/src/config/file-config.ts +34 -0
- package/src/rooms/resources.ts +2 -2
- package/src/runtime/v2-plugin.ts +8 -2
- package/src/runtime/watch.ts +41 -7
- package/src/state/sqlite-state.ts +67 -18
- package/src/state/store.ts +11 -5
- package/src/tui/app.mjs +10 -2
- package/src/tui/http.mjs +16 -2
- package/src/tui/info-app.mjs +24 -15
- package/src/tui/join-app.mjs +3 -3
- package/src/tui/main.mjs +1 -1
- package/src/tui/markdown.mjs +5 -3
- package/src/tui/mentions.mjs +3 -3
- package/src/tui/message-app.mjs +14 -11
- package/src/tui/palette-app.mjs +10 -7
- package/src/tui/reminder-app.mjs +14 -10
- package/src/tui/ui-content.mjs +3 -1
- package/server/assets/HIGHLIGHT-LICENSE +0 -29
- package/server/assets/highlight-10.7.3.min.js +0 -1358
|
@@ -0,0 +1,473 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { StringDecoder } from "node:string_decoder";
|
|
2
|
+
import { MAX_FRAME_BYTES } from "./protocol.ts";
|
|
3
|
+
|
|
4
|
+
export type FrameMessage = Record<string, unknown>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parse one newline-delimited JSON frame. Frames must be JSON objects; a
|
|
8
|
+
* scalar or array is a protocol violation.
|
|
9
|
+
*/
|
|
10
|
+
export function parseFrame(line: string): FrameMessage {
|
|
11
|
+
const text = line.trim();
|
|
12
|
+
if (!text) throw new Error("empty frame");
|
|
13
|
+
let value: unknown;
|
|
14
|
+
try {
|
|
15
|
+
value = JSON.parse(text);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
throw new Error(`invalid JSON frame: ${error instanceof Error ? error.message : String(error)}`);
|
|
18
|
+
}
|
|
19
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
20
|
+
throw new Error("frame must be a JSON object");
|
|
21
|
+
}
|
|
22
|
+
return value as FrameMessage;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Feed Buffer chunks into the returned function. Complete lines are handed to
|
|
27
|
+
* onMessage; parse failures and oversize frames go to onError. An oversize
|
|
28
|
+
* frame is dropped up to its newline and never partially emitted.
|
|
29
|
+
*
|
|
30
|
+
* Byte length is checked on the raw chunk segments, before UTF-8 decoding, so
|
|
31
|
+
* a frame of multi-byte characters is measured in bytes rather than UTF-16
|
|
32
|
+
* code units.
|
|
33
|
+
*/
|
|
34
|
+
export function createFrameReader(
|
|
35
|
+
onMessage: (message: FrameMessage) => void,
|
|
36
|
+
onError: (error: Error) => void,
|
|
37
|
+
): (chunk: Buffer) => void {
|
|
38
|
+
const decoder = new StringDecoder("utf8");
|
|
39
|
+
let parts: string[] = [];
|
|
40
|
+
let bytes = 0;
|
|
41
|
+
let discarding = false;
|
|
42
|
+
|
|
43
|
+
const dispatch = (): void => {
|
|
44
|
+
const text = discarding ? "" : parts.join("");
|
|
45
|
+
const wasDiscarding = discarding;
|
|
46
|
+
parts = [];
|
|
47
|
+
bytes = 0;
|
|
48
|
+
discarding = false;
|
|
49
|
+
if (wasDiscarding || !text.trim()) return;
|
|
50
|
+
try {
|
|
51
|
+
onMessage(parseFrame(text));
|
|
52
|
+
} catch (error) {
|
|
53
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const consume = (segment: Buffer): void => {
|
|
58
|
+
const decoded = decoder.write(segment);
|
|
59
|
+
if (discarding) return;
|
|
60
|
+
if (bytes + segment.length > MAX_FRAME_BYTES) {
|
|
61
|
+
parts = [];
|
|
62
|
+
bytes = 0;
|
|
63
|
+
discarding = true;
|
|
64
|
+
onError(new Error(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
bytes += segment.length;
|
|
68
|
+
parts.push(decoded);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
return (chunk: Buffer): void => {
|
|
72
|
+
let start = 0;
|
|
73
|
+
while (start <= chunk.length) {
|
|
74
|
+
const newline = chunk.indexOf(0x0a, start);
|
|
75
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
76
|
+
consume(chunk.subarray(start, end));
|
|
77
|
+
if (newline === -1) return;
|
|
78
|
+
dispatch();
|
|
79
|
+
start = newline + 1;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class AdapterGoneError extends Error {
|
|
85
|
+
readonly code = "ADAPTER_GONE";
|
|
86
|
+
|
|
87
|
+
constructor(message: string) {
|
|
88
|
+
super(message);
|
|
89
|
+
this.name = "AdapterGoneError";
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const GONE_CODES = new Set(["EPIPE", "ERR_STREAM_DESTROYED", "ERR_STREAM_WRITE_AFTER_END"]);
|
|
94
|
+
|
|
95
|
+
function writeError(error: unknown): Error {
|
|
96
|
+
const code = (error as { code?: string } | null)?.code;
|
|
97
|
+
if (code && GONE_CODES.has(code)) return new AdapterGoneError(`adapter stream is gone (${code})`);
|
|
98
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Write one JSON line. Protocol streams only carry JSON objects. */
|
|
102
|
+
export function writeFrame(stream: NodeJS.WritableStream, value: unknown): Promise<void> {
|
|
103
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
104
|
+
throw new TypeError("frame must be a JSON object");
|
|
105
|
+
}
|
|
106
|
+
const writable = stream as NodeJS.WritableStream & {
|
|
107
|
+
destroyed?: boolean;
|
|
108
|
+
writableEnded?: boolean;
|
|
109
|
+
};
|
|
110
|
+
if (writable.destroyed || writable.writableEnded) {
|
|
111
|
+
throw new AdapterGoneError("adapter stream is closed");
|
|
112
|
+
}
|
|
113
|
+
const line = `${JSON.stringify(value)}\n`;
|
|
114
|
+
if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
|
|
115
|
+
throw new RangeError(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`);
|
|
116
|
+
}
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
const fail = (error: unknown): void => reject(writeError(error));
|
|
119
|
+
try {
|
|
120
|
+
stream.write(line, (error?: Error | null) => {
|
|
121
|
+
if (error) fail(error);
|
|
122
|
+
else resolve();
|
|
123
|
+
});
|
|
124
|
+
} catch (error) {
|
|
125
|
+
fail(error);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ChannelConfig, RuleTarget } from "./config.ts";
|
|
2
|
+
import type { Endpoint } from "./protocol.ts";
|
|
3
|
+
|
|
4
|
+
export function parseTarget(value: string): Endpoint | undefined {
|
|
5
|
+
const parts = value.split("/");
|
|
6
|
+
if (parts.length !== 3) return undefined;
|
|
7
|
+
const [platform, accountId, roomId] = parts;
|
|
8
|
+
if (!platform || !accountId || !roomId) return undefined;
|
|
9
|
+
return { platform, accountId, roomId };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function startFailureReason(accountId: string, error: unknown): string {
|
|
13
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
14
|
+
const prefix = `adapter ${accountId} failed to start: `;
|
|
15
|
+
return message.startsWith(prefix) ? message.slice(prefix.length) : message;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function validateTargets(config: ChannelConfig): void {
|
|
19
|
+
const accounts = new Map(config.accounts.map((account) => [account.id, account]));
|
|
20
|
+
for (const rule of config.rules) {
|
|
21
|
+
for (const target of rule.to) {
|
|
22
|
+
const account = accounts.get(target.account);
|
|
23
|
+
if (!account) {
|
|
24
|
+
throw new Error(`config: rule "${rule.id}" targets unknown account "${target.account}"`);
|
|
25
|
+
}
|
|
26
|
+
if (account.platform !== target.platform) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
`config: rule "${rule.id}" targets platform "${target.platform}" but account "${target.account}" is "${account.platform}"`,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function toEndpoint(config: ChannelConfig, ruleId: string, target: RuleTarget): Endpoint {
|
|
36
|
+
const account = config.accounts.find((item) => item.id === target.account);
|
|
37
|
+
if (!account) {
|
|
38
|
+
throw new Error(`config: rule "${ruleId}" targets unknown account "${target.account}"`);
|
|
39
|
+
}
|
|
40
|
+
return { platform: target.platform, accountId: account.id, roomId: target.room };
|
|
41
|
+
}
|