@alexsun-top/opencode-chat-room 0.8.0 → 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 +29 -0
- package/LICENSE +2 -2
- package/README.md +38 -6
- package/README.zh-CN.md +38 -6
- package/cli.ts +27 -1
- package/dist/cli.js +5074 -3212
- package/package.json +23 -3
- package/packages/chat-room-channeld/README.md +98 -25
- package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
- package/packages/chat-room-channeld/src/adapter.ts +36 -2
- 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/feishu-adapter.ts +122 -292
- 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/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +120 -2
- package/packages/chat-room-channeld/src/inbound.ts +26 -0
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -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 +15 -9
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +184 -35
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/index.js +2 -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 +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.js +22 -8
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- 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/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/side-pane.js +1 -2
- package/server/assets/chat/state.js +93 -10
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +55 -32
- package/server/assets/conversation.css +123 -23
- package/server/assets/doc-preview.css +35 -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/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 +50 -11
- package/server/assets/settings.css +73 -1
- 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 +261 -18
- package/server/chat-server.ts +32 -580
- package/server/chat.html +187 -21
- 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 +4 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +2 -10
- 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 +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 -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 +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
|
@@ -1,6 +1,18 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
1
|
import path from "node:path";
|
|
3
2
|
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { cardVersionFromEnv, type CardVersion } from "./feishu-card.ts";
|
|
4
|
+
import { parseInboundEvent } from "./feishu-inbound.ts";
|
|
5
|
+
import { FeishuLiveConnection } from "./feishu-live.ts";
|
|
6
|
+
import {
|
|
7
|
+
ensureToken,
|
|
8
|
+
FeishuApiError,
|
|
9
|
+
sendMessage,
|
|
10
|
+
startupFailureDetail,
|
|
11
|
+
type FeishuConfig,
|
|
12
|
+
type SendParams,
|
|
13
|
+
type SendReceipt,
|
|
14
|
+
type TokenState,
|
|
15
|
+
} from "./feishu-send.ts";
|
|
4
16
|
import { createFrameReader, writeFrame } from "./framing.ts";
|
|
5
17
|
import {
|
|
6
18
|
EVENT_SCHEMA_VERSION,
|
|
@@ -8,91 +20,30 @@ import {
|
|
|
8
20
|
PROTOCOL_VERSION,
|
|
9
21
|
RPC_INTERNAL_ERROR,
|
|
10
22
|
RPC_METHOD_NOT_FOUND,
|
|
23
|
+
adapterRequestId,
|
|
11
24
|
rpcError,
|
|
25
|
+
rpcRequest,
|
|
12
26
|
rpcResult,
|
|
13
|
-
type
|
|
27
|
+
type IngestEvent,
|
|
14
28
|
} from "./protocol.ts";
|
|
15
29
|
|
|
30
|
+
export { deterministicUuid } from "./feishu-send.ts";
|
|
31
|
+
|
|
16
32
|
const DEFAULT_BASE_URL = "https://open.feishu.cn";
|
|
17
33
|
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
34
|
|
|
40
|
-
interface AdapterState {
|
|
41
|
-
accountId: string;
|
|
35
|
+
interface AdapterState extends TokenState {
|
|
42
36
|
config?: FeishuConfig;
|
|
43
|
-
token?: string;
|
|
44
|
-
tokenExpiresAt: number;
|
|
45
37
|
started: boolean;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
}
|
|
38
|
+
inbound?: FeishuLiveConnection;
|
|
39
|
+
pending: Map<string, (result: { duplicate?: boolean; error?: string }) => void>;
|
|
40
|
+
sequence: number;
|
|
81
41
|
}
|
|
82
42
|
|
|
83
43
|
function logLine(accountId: string, message: string): void {
|
|
84
44
|
console.error(`feishu adapter ${accountId}: ${message}`);
|
|
85
45
|
}
|
|
86
46
|
|
|
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
47
|
function configFromEnv(env: NodeJS.ProcessEnv): FeishuConfig | { error: string } {
|
|
97
48
|
const appId = env.FEISHU_APP_ID;
|
|
98
49
|
const appSecret = env.FEISHU_APP_SECRET;
|
|
@@ -105,241 +56,83 @@ function configFromEnv(env: NodeJS.ProcessEnv): FeishuConfig | { error: string }
|
|
|
105
56
|
const timeout = Number(env.FEISHU_HTTP_TIMEOUT_MS);
|
|
106
57
|
const timeoutMs = Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
|
|
107
58
|
const baseUrl = (env.FEISHU_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
108
|
-
|
|
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);
|
|
59
|
+
let cardVersion: CardVersion;
|
|
118
60
|
try {
|
|
119
|
-
|
|
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 };
|
|
61
|
+
cardVersion = cardVersionFromEnv(env.FEISHU_CARD_VERSION);
|
|
130
62
|
} catch (error) {
|
|
131
|
-
|
|
132
|
-
if (timedOut) throw new FeishuTimeoutError();
|
|
133
|
-
throw error;
|
|
134
|
-
} finally {
|
|
135
|
-
clearTimeout(timer);
|
|
63
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
136
64
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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,
|
|
65
|
+
const inbound = env.FEISHU_INBOUND === "1";
|
|
66
|
+
const inboundChats = new Set(
|
|
67
|
+
(env.FEISHU_INBOUND_CHATS ?? "").split(/[,\s]+/).map((item) => item.trim()).filter(Boolean),
|
|
148
68
|
);
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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 };
|
|
69
|
+
if (inbound && inboundChats.size === 0) {
|
|
70
|
+
return {
|
|
71
|
+
error: "FEISHU_INBOUND=1 requires FEISHU_INBOUND_CHATS (comma-separated group chat ids)",
|
|
72
|
+
};
|
|
199
73
|
}
|
|
200
|
-
return
|
|
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;
|
|
74
|
+
return { appId, appSecret, baseUrl, timeoutMs, cardVersion, inbound, inboundChats };
|
|
214
75
|
}
|
|
215
76
|
|
|
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
77
|
|
|
224
|
-
|
|
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
|
-
}
|
|
78
|
+
const INGEST_TIMEOUT_MS = 5000;
|
|
230
79
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
state:
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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}` };
|
|
80
|
+
/** Emit one ingest request and wait for the host commit; false means no ack. */
|
|
81
|
+
function emitIngest(state: AdapterState, event: IngestEvent): Promise<boolean> {
|
|
82
|
+
const id = adapterRequestId(++state.sequence);
|
|
83
|
+
return new Promise((resolve) => {
|
|
84
|
+
const timer = setTimeout(() => {
|
|
85
|
+
state.pending.delete(id);
|
|
86
|
+
logLine(state.accountId, "inbound ingest timed out");
|
|
87
|
+
resolve(false);
|
|
88
|
+
}, INGEST_TIMEOUT_MS);
|
|
89
|
+
state.pending.set(id, (result) => {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
if (result.error) logLine(state.accountId, `inbound ingest failed: ${result.error}`);
|
|
92
|
+
resolve(!result.error);
|
|
93
|
+
});
|
|
94
|
+
void writeFrame(process.stdout, rpcRequest(id, "ingest", event)).catch(() => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
state.pending.delete(id);
|
|
97
|
+
resolve(false);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
263
100
|
}
|
|
264
101
|
|
|
265
|
-
function
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
102
|
+
async function startInbound(config: FeishuConfig, state: AdapterState): Promise<void> {
|
|
103
|
+
const live = new FeishuLiveConnection({
|
|
104
|
+
appId: config.appId,
|
|
105
|
+
appSecret: config.appSecret,
|
|
106
|
+
baseUrl: config.baseUrl,
|
|
107
|
+
timeoutMs: config.timeoutMs,
|
|
108
|
+
log: (message) => logLine(state.accountId, message),
|
|
109
|
+
onEvent: async (payload) => {
|
|
110
|
+
const parsed = parseInboundEvent(payload, {
|
|
111
|
+
accountId: state.accountId,
|
|
112
|
+
appId: config.appId,
|
|
113
|
+
chats: config.inboundChats,
|
|
114
|
+
});
|
|
115
|
+
if (!parsed.event) {
|
|
116
|
+
if (parsed.ignored) logLine(state.accountId, `inbound ignored: ${parsed.ignored}`);
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
return emitIngest(state, parsed.event);
|
|
275
120
|
},
|
|
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
121
|
});
|
|
122
|
+
await live.start();
|
|
123
|
+
state.inbound = live;
|
|
124
|
+
await notifyInbound(state, "ready");
|
|
125
|
+
}
|
|
312
126
|
|
|
313
|
-
|
|
314
|
-
|
|
127
|
+
/** Report inbound health without blocking the adapter's outbound path. */
|
|
128
|
+
async function notifyInbound(state: AdapterState, inbound: "ready" | "failed", detail?: string): Promise<void> {
|
|
129
|
+
const id = adapterRequestId(++state.sequence);
|
|
130
|
+
const params = detail === undefined ? { inbound } : { inbound, detail };
|
|
315
131
|
try {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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
|
-
}
|
|
132
|
+
await writeFrame(process.stdout, rpcRequest(id, "status", params));
|
|
133
|
+
} catch {
|
|
134
|
+
// A status frame must never fail the adapter.
|
|
333
135
|
}
|
|
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
136
|
}
|
|
344
137
|
|
|
345
138
|
async function handleRequest(message: Record<string, unknown>, state: AdapterState): Promise<void> {
|
|
@@ -355,7 +148,16 @@ async function handleRequest(message: Record<string, unknown>, state: AdapterSta
|
|
|
355
148
|
}
|
|
356
149
|
const id = rawId;
|
|
357
150
|
const method = message.method;
|
|
358
|
-
if (typeof method !== "string")
|
|
151
|
+
if (typeof method !== "string") {
|
|
152
|
+
// Response to an adapter-initiated ingest request.
|
|
153
|
+
const resolver = state.pending.get(String(id));
|
|
154
|
+
if (resolver) {
|
|
155
|
+
state.pending.delete(String(id));
|
|
156
|
+
const failure = message.error as { message?: string } | undefined;
|
|
157
|
+
resolver(failure ? { error: failure.message ?? "host ingest failed" } : {});
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
359
161
|
|
|
360
162
|
if (method === "initialize") {
|
|
361
163
|
const config = configFromEnv(process.env);
|
|
@@ -372,7 +174,14 @@ async function handleRequest(message: Record<string, unknown>, state: AdapterSta
|
|
|
372
174
|
maxFrameBytes: MAX_FRAME_BYTES,
|
|
373
175
|
accounts: {
|
|
374
176
|
[state.accountId]: {
|
|
375
|
-
send: {
|
|
177
|
+
send: {
|
|
178
|
+
text: true,
|
|
179
|
+
format: ["text", "markdown"],
|
|
180
|
+
reply: "native",
|
|
181
|
+
idempotency: "persistent_delivery_key",
|
|
182
|
+
card: ["1.0", "2.0"],
|
|
183
|
+
},
|
|
184
|
+
...(config.inbound ? { ingress: "durable_outbox" } : {}),
|
|
376
185
|
},
|
|
377
186
|
},
|
|
378
187
|
}),
|
|
@@ -396,6 +205,19 @@ async function handleRequest(message: Record<string, unknown>, state: AdapterSta
|
|
|
396
205
|
await writeFrame(process.stdout, rpcError(id, RPC_INTERNAL_ERROR, detail));
|
|
397
206
|
return;
|
|
398
207
|
}
|
|
208
|
+
if (state.config.inbound) {
|
|
209
|
+
try {
|
|
210
|
+
await startInbound(state.config, state);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
// Inbound is opt-in but must never take the working outbound path down.
|
|
213
|
+
const detail = error instanceof FeishuApiError
|
|
214
|
+
? startupFailureDetail(error)
|
|
215
|
+
: error instanceof Error ? error.message : String(error);
|
|
216
|
+
const hint = `${detail} (requires long-connection event subscription for im.message.receive_v1 and the bot in an allowlisted group)`;
|
|
217
|
+
logLine(state.accountId, `inbound disabled; outbound stays active: ${hint}`);
|
|
218
|
+
await notifyInbound(state, "failed", detail);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
399
221
|
state.started = true;
|
|
400
222
|
await writeFrame(process.stdout, rpcResult(id, { ready: true }));
|
|
401
223
|
logLine(state.accountId, "ready (tenant token validated)");
|
|
@@ -426,6 +248,7 @@ async function handleRequest(message: Record<string, unknown>, state: AdapterSta
|
|
|
426
248
|
}
|
|
427
249
|
|
|
428
250
|
if (method === "shutdown") {
|
|
251
|
+
await state.inbound?.stop();
|
|
429
252
|
await writeFrame(process.stdout, rpcResult(id, {}));
|
|
430
253
|
process.exit(0);
|
|
431
254
|
}
|
|
@@ -438,6 +261,8 @@ export function runFeishuAdapter(): Promise<void> {
|
|
|
438
261
|
accountId: process.env.CHANNELD_ACCOUNT_ID ?? "feishu",
|
|
439
262
|
tokenExpiresAt: 0,
|
|
440
263
|
started: false,
|
|
264
|
+
pending: new Map(),
|
|
265
|
+
sequence: 0,
|
|
441
266
|
};
|
|
442
267
|
const read = createFrameReader(
|
|
443
268
|
(message) => {
|
|
@@ -449,6 +274,11 @@ export function runFeishuAdapter(): Promise<void> {
|
|
|
449
274
|
);
|
|
450
275
|
process.stdin.on("data", (chunk: Buffer) => read(chunk));
|
|
451
276
|
logLine(state.accountId, "ready on stdio");
|
|
277
|
+
const finish = (): void => {
|
|
278
|
+
void state.inbound?.stop();
|
|
279
|
+
};
|
|
280
|
+
process.stdin.once("end", finish);
|
|
281
|
+
process.stdin.once("close", finish);
|
|
452
282
|
return new Promise((resolve) => {
|
|
453
283
|
process.stdin.once("end", resolve);
|
|
454
284
|
process.stdin.once("close", resolve);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type CardVersion = "1.0" | "2.0";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* FEISHU_CARD_VERSION is opt-in: card 1.0 keeps the 0.8.0 payload because some
|
|
5
|
+
* tenants still render card 2.0 differently. Card 2.0 is required for headings,
|
|
6
|
+
* lists, and fenced code as block Markdown.
|
|
7
|
+
*/
|
|
8
|
+
export function cardVersionFromEnv(value: string | undefined): CardVersion {
|
|
9
|
+
const raw = (value ?? "").trim().toLowerCase();
|
|
10
|
+
if (!raw || raw === "1" || raw === "1.0") return "1.0";
|
|
11
|
+
if (raw === "2" || raw === "2.0") return "2.0";
|
|
12
|
+
throw new Error("FEISHU_CARD_VERSION must be 1.0 or 2.0");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function buildCard(version: CardVersion, text: string): unknown {
|
|
16
|
+
if (version === "2.0") {
|
|
17
|
+
return {
|
|
18
|
+
schema: "2.0",
|
|
19
|
+
config: { update_multi: true },
|
|
20
|
+
body: { elements: [{ tag: "markdown", content: text }] },
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
config: { wide_screen_mode: true },
|
|
25
|
+
elements: [{ tag: "div", text: { tag: "lark_md", content: text } }],
|
|
26
|
+
};
|
|
27
|
+
}
|