-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathbridge.mjs
More file actions
1629 lines (1406 loc) · 56.2 KB
/
bridge.mjs
File metadata and controls
1629 lines (1406 loc) · 56.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Feishu ↔ Clawdbot Bridge
*
* Receives messages from Feishu via WebSocket (long connection),
* forwards them to Clawdbot Gateway, and sends the AI reply back.
*
* Design goals:
* - Robust: never silently drop messages just because parsing failed.
* - Long-term: tolerate Feishu rich-text (post/md/list) structure variations.
* - Practical: handle images from (1) real Feishu image messages, (2) post embeds,
* (3) local markdown image paths produced by local automation (restricted allowlist).
* - Optional: support "MEDIA:" outputs from the agent to send files back to Feishu
* with correct upload/send type mapping (avoids 230055).
*/
import * as Lark from '@larksuiteoapi/node-sdk';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import * as http from 'node:http';
import * as https from 'node:https';
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
import { fileURLToPath } from 'node:url';
import WebSocket from 'ws';
// Load .env automatically (so users don't need to export env vars manually).
// - Does NOT override existing process.env values.
// - Keeps this bridge dependency-free (no dotenv package).
loadDotEnvIfPresent();
function loadDotEnvIfPresent() {
const candidates = [
// cwd
path.resolve(process.cwd(), '.env'),
// script dir
path.resolve(path.dirname(fileURLToPath(import.meta.url)), '.env'),
];
for (const p of candidates) {
try {
if (!fs.existsSync(p)) continue;
const raw = fs.readFileSync(p, 'utf8');
for (const line of raw.split(/\r?\n/)) {
const s = line.trim();
if (!s || s.startsWith('#')) continue;
const i = s.indexOf('=');
if (i <= 0) continue;
const k = s.slice(0, i).trim();
const v = s.slice(i + 1).trim();
if (!k) continue;
if (process.env[k] == null) process.env[k] = v;
}
return;
} catch {
// ignore
}
}
}
// ─── Config ──────────────────────────────────────────────────────
const APP_ID = process.env.FEISHU_APP_ID;
const APP_SECRET_PATH = resolvePath(process.env.FEISHU_APP_SECRET_PATH || '~/.clawdbot/secrets/feishu_app_secret');
const CLAWDBOT_CONFIG_PATH = resolvePath(process.env.CLAWDBOT_CONFIG_PATH || '~/.clawdbot/clawdbot.json');
const CLAWDBOT_AGENT_ID = process.env.CLAWDBOT_AGENT_ID || 'main';
const THINKING_THRESHOLD_MS = Number(process.env.FEISHU_THINKING_THRESHOLD_MS ?? 2500);
// Local markdown media support (issue #3): allow reading ONLY under these dirs.
// Default supports the common local automation path: ~/.clawdbot/media
const ALLOWED_LOCAL_MEDIA_DIRS = (process.env.FEISHU_BRIDGE_ALLOWED_LOCAL_MEDIA_DIRS || '~/.clawdbot/media')
.split(',')
.map((s) => resolvePath(s.trim()))
.filter(Boolean);
// Outbound media (agent → Feishu): allow sending files ONLY from these dirs.
// Default includes /tmp so tool-generated images can be sent.
const ALLOWED_OUTBOUND_MEDIA_DIRS = (
process.env.FEISHU_BRIDGE_ALLOWED_OUTBOUND_MEDIA_DIRS || `~/.clawdbot/media,${os.tmpdir()},/tmp`
)
.split(',')
.map((s) => resolvePath(s.trim()))
.filter(Boolean);
const MAX_LOCAL_FILE_MB = Number(process.env.FEISHU_BRIDGE_MAX_LOCAL_FILE_MB ?? 15);
const MAX_INBOUND_IMAGE_MB = Number(process.env.FEISHU_BRIDGE_MAX_INBOUND_IMAGE_MB ?? 12);
const MAX_INBOUND_FILE_MB = Number(process.env.FEISHU_BRIDGE_MAX_INBOUND_FILE_MB ?? 40);
const INBOUND_FILE_TTL_MIN = Number(process.env.FEISHU_BRIDGE_INBOUND_FILE_TTL_MIN ?? 60);
const MAX_ATTACHMENTS = Number(process.env.FEISHU_BRIDGE_MAX_ATTACHMENTS ?? 4);
const SELFTEST = process.argv.includes('--selftest') || process.env.FEISHU_BRIDGE_SELFTEST === '1';
const DEBUG = process.env.FEISHU_BRIDGE_DEBUG === '1';
const BRIDGE_VERSION = readBridgeVersion();
const DEVICE_IDENTITY_PATH = resolveDeviceIdentityPath(process.env.FEISHU_BRIDGE_DEVICE_IDENTITY_PATH);
const ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
let DEVICE_IDENTITY = null;
// ─── Helpers ─────────────────────────────────────────────────────
function resolvePath(p) {
return String(p || '').replace(/^~/, os.homedir());
}
function toBase64Url(buffer) {
return Buffer.from(buffer).toString('base64url');
}
function fromBase64Url(str) {
return Buffer.from(str, 'base64url');
}
function readBridgeVersion() {
try {
const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
return String(pkg?.version || '0.0.0');
} catch {
return '0.0.0';
}
}
function resolveDeviceIdentityPath(explicitPath) {
if (explicitPath) return resolvePath(explicitPath);
const openclawDir = resolvePath('~/.openclaw');
if (fs.existsSync(openclawDir)) {
return path.join(openclawDir, 'feishu-bridge-device.json');
}
return resolvePath('~/.clawdbot/feishu-bridge-device.json');
}
function buildEd25519PublicKey(rawPublicKey) {
if (!Buffer.isBuffer(rawPublicKey) || rawPublicKey.length !== 32) {
throw new Error('Invalid Ed25519 public key length');
}
const der = Buffer.concat([ED25519_SPKI_PREFIX, rawPublicKey]);
return crypto.createPublicKey({ key: der, format: 'der', type: 'spki' });
}
function buildEd25519PrivateKey(rawPrivateKey) {
if (!Buffer.isBuffer(rawPrivateKey) || rawPrivateKey.length !== 32) {
throw new Error('Invalid Ed25519 private key length');
}
const der = Buffer.concat([ED25519_PKCS8_PREFIX, rawPrivateKey]);
return crypto.createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
}
function writeDeviceIdentityFile(filePath, record) {
const resolved = resolvePath(filePath);
fs.mkdirSync(path.dirname(resolved), { recursive: true });
fs.writeFileSync(resolved, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
try {
fs.chmodSync(resolved, 0o600);
} catch {
// ignore permission errors on non-POSIX fs
}
}
function validateAndHydrateDeviceIdentity(record, filePath) {
if (!record || typeof record !== 'object') throw new Error('Device identity must be an object');
const deviceId = String(record.deviceId || '').trim();
const publicKey = String(record.publicKey || '').trim();
const privateKey = String(record.privateKey || '').trim();
const createdAtMs = Number(record.createdAtMs || 0);
if (record.version !== 1) throw new Error('Unsupported device identity version');
if (!/^[a-f0-9]{64}$/i.test(deviceId)) throw new Error('Invalid deviceId');
const pubRaw = fromBase64Url(publicKey);
const privRaw = fromBase64Url(privateKey);
if (pubRaw.length !== 32) throw new Error('Invalid public key bytes');
if (privRaw.length !== 32) throw new Error('Invalid private key bytes');
const derivedDeviceId = crypto.createHash('sha256').update(pubRaw).digest('hex');
if (derivedDeviceId !== deviceId.toLowerCase()) throw new Error('deviceId mismatch');
return {
version: 1,
deviceId: derivedDeviceId,
publicKey,
privateKey,
createdAtMs: Number.isFinite(createdAtMs) && createdAtMs > 0 ? createdAtMs : Date.now(),
deviceToken: typeof record.deviceToken === 'string' ? record.deviceToken : undefined,
filePath: resolvePath(filePath),
publicKeyObject: buildEd25519PublicKey(pubRaw),
privateKeyObject: buildEd25519PrivateKey(privRaw),
};
}
function createDeviceIdentityRecord() {
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
const pubRaw = publicKey.export({ type: 'spki', format: 'der' }).subarray(-32);
const privRaw = privateKey.export({ type: 'pkcs8', format: 'der' }).subarray(-32);
const deviceId = crypto.createHash('sha256').update(pubRaw).digest('hex');
return {
version: 1,
deviceId,
publicKey: toBase64Url(pubRaw),
privateKey: toBase64Url(privRaw),
createdAtMs: Date.now(),
};
}
async function loadOrCreateDeviceIdentity(filePath = DEVICE_IDENTITY_PATH) {
const resolved = resolvePath(filePath);
if (fs.existsSync(resolved)) {
try {
const raw = fs.readFileSync(resolved, 'utf8');
const parsed = JSON.parse(raw);
const identity = validateAndHydrateDeviceIdentity(parsed, resolved);
try {
fs.chmodSync(resolved, 0o600);
} catch {
// ignore
}
return identity;
} catch (e) {
console.error(`[WARN] Device identity file invalid, regenerating: ${e?.message || String(e)}`);
}
}
const record = createDeviceIdentityRecord();
writeDeviceIdentityFile(resolved, record);
return validateAndHydrateDeviceIdentity(record, resolved);
}
function persistDeviceToken(identity, deviceToken) {
const token = String(deviceToken || '').trim();
if (!token || !identity) return identity;
if (identity.deviceToken === token) return identity;
const record = {
version: 1,
deviceId: identity.deviceId,
publicKey: identity.publicKey,
privateKey: identity.privateKey,
createdAtMs: identity.createdAtMs,
deviceToken: token,
};
writeDeviceIdentityFile(identity.filePath, record);
return { ...identity, deviceToken: token };
}
/**
* Build the device auth payload string that the Gateway expects.
* Format: version|deviceId|clientId|clientMode|role|scopes|signedAtMs|token[|nonce]
*/
function buildDeviceAuthPayload({ deviceId, clientId, clientMode, role, scopes, signedAtMs, token, nonce }) {
const version = nonce ? 'v2' : 'v1';
const base = [version, deviceId, clientId, clientMode, role, scopes.join(','), String(signedAtMs), token || ''];
if (version === 'v2') base.push(nonce || '');
return base.join('|');
}
function signDevicePayload(identity, payload) {
const signature = crypto.sign(null, Buffer.from(payload, 'utf8'), identity.privateKeyObject);
return toBase64Url(signature);
}
function mustRead(filePath, label) {
const resolved = resolvePath(filePath);
if (!fs.existsSync(resolved)) {
console.error(`[FATAL] ${label} not found: ${resolved}`);
process.exit(1);
}
const val = fs.readFileSync(resolved, 'utf8').trim();
if (!val) {
console.error(`[FATAL] ${label} is empty: ${resolved}`);
process.exit(1);
}
return val;
}
const uuid = () => crypto.randomUUID();
function toNodeReadableStream(maybeStream) {
if (!maybeStream) return null;
if (typeof maybeStream.pipe === 'function') return maybeStream; // Node stream
// Web stream
if (typeof maybeStream.getReader === 'function' && typeof Readable.fromWeb === 'function') {
return Readable.fromWeb(maybeStream);
}
return null;
}
function truncate(s, max = 2000) {
const str = String(s ?? '');
if (str.length <= max) return str;
return str.slice(0, max) + `…(truncated, ${str.length} chars)`;
}
function decodeHtmlEntities(s) {
return String(s ?? '')
.replace(/ /gi, ' ')
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/&/gi, '&')
.replace(/"/gi, '"')
.replace(/'/g, "'");
}
/**
* Normalize Feishu "text" payloads.
* Some clients may send HTML-ish strings like <p>- 1</p><p>- 2</p>.
*/
function normalizeFeishuText(raw) {
let t = String(raw ?? '');
// Convert common HTML blocks to newlines
t = t.replace(/<\s*br\s*\/?>/gi, '\n');
t = t.replace(/<\s*\/p\s*>\s*<\s*p\s*>/gi, '\n');
t = t.replace(/<\s*p\s*>/gi, '');
t = t.replace(/<\s*\/p\s*>/gi, '');
// Strip remaining tags
t = t.replace(/<[^>]+>/g, '');
t = decodeHtmlEntities(t);
// Normalize newlines
t = t.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
t = t.replace(/\n{3,}/g, '\n\n');
// Fix Feishu list quirk: sometimes list marker and content are split into two lines.
// "-\n1" -> "- 1"
// "•\nfoo" -> "• foo"
t = t.replace(/(^|\n)([-*•])\n(?=\S)/g, '$1$2 ');
t = t.replace(/(^|\n)(\d+[\.|\)])\n(?=\S)/g, '$1$2 ');
return t.trim();
}
function extLower(p) {
return path.extname(p || '').toLowerCase().replace(/^\./, '');
}
function guessMimeByExt(p) {
const e = extLower(p);
if (e === 'png') return 'image/png';
if (e === 'jpg' || e === 'jpeg') return 'image/jpeg';
if (e === 'gif') return 'image/gif';
if (e === 'webp') return 'image/webp';
if (e === 'mp4') return 'video/mp4';
if (e === 'mov') return 'video/quicktime';
if (e === 'mp3') return 'audio/mpeg';
if (e === 'wav') return 'audio/wav';
if (e === 'm4a') return 'audio/mp4';
if (e === 'opus') return 'audio/opus';
return 'application/octet-stream';
}
function isPathInside(child, parent) {
const rel = path.relative(parent, child);
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function isAllowedLocalPath(filePath) {
const p = path.resolve(filePath);
return ALLOWED_LOCAL_MEDIA_DIRS.some((dir) => isPathInside(p, dir) || p === dir);
}
function isAllowedOutboundPath(filePath) {
const p = path.resolve(filePath);
return ALLOWED_OUTBOUND_MEDIA_DIRS.some((dir) => isPathInside(p, dir) || p === dir);
}
function scheduleCleanup(filePath, minutes = INBOUND_FILE_TTL_MIN) {
const ms = Math.max(1, Number(minutes || 0)) * 60 * 1000;
const t = setTimeout(() => {
try { fs.unlinkSync(filePath); } catch {}
}, ms);
// Let Node exit even if the timer is pending.
if (typeof t.unref === 'function') t.unref();
}
function looksLikeMediaRef(s) {
const v = String(s || '').trim();
if (!v) return false;
if (/^data:[^;]+;base64,/i.test(v)) return true;
if (/^https?:\/\//i.test(v)) return true;
if (/^file:\/\//i.test(v)) return true;
if (v.startsWith('/') && /\.(png|jpe?g|gif|webp|bmp|mp4|mov|mp3|wav|m4a|opus)$/i.test(v)) return true;
if (/^MEDIA:\s*\S+/i.test(v)) return true;
return false;
}
function extractMediaRefsDeep(value, limit = 8) {
const out = [];
const seen = new Set();
const walk = (x, depth) => {
if (out.length >= limit) return;
if (depth > 4) return;
if (typeof x === 'string') {
if (looksLikeMediaRef(x)) {
const m = /^MEDIA:\s*(\S+)/i.exec(x.trim());
const ref = m ? m[1] : x.trim();
if (!seen.has(ref)) {
seen.add(ref);
out.push(ref);
}
}
return;
}
if (!x) return;
if (Array.isArray(x)) {
for (const it of x) walk(it, depth + 1);
return;
}
if (typeof x === 'object') {
for (const v of Object.values(x)) walk(v, depth + 1);
}
};
walk(value, 0);
return out;
}
function safeFileSizeOk(filePath) {
try {
const st = fs.statSync(filePath);
if (!st.isFile()) return { ok: false, reason: 'not a file' };
const maxBytes = MAX_LOCAL_FILE_MB * 1024 * 1024;
if (st.size > maxBytes) return { ok: false, reason: `too large (${st.size} bytes)` };
return { ok: true, size: st.size };
} catch (e) {
return { ok: false, reason: e?.message || String(e) };
}
}
function fileToDataUrl(filePath, mimeType) {
const buf = fs.readFileSync(filePath);
const b64 = buf.toString('base64');
return `data:${mimeType};base64,${b64}`;
}
function isProbablyImagePath(p) {
return /\.(png|jpg|jpeg|gif|webp|bmp)$/i.test(p);
}
function isProbablyVideoPath(p) {
return /\.(mp4|mov|avi|mkv|webm)$/i.test(p);
}
function isProbablyAudioPath(p) {
return /\.(opus|mp3|wav|m4a|aac|ogg)$/i.test(p);
}
function extractMarkdownLocalMediaPaths(text) {
const t = String(text ?? '');
const out = [];
// Markdown image syntax: 
// Note: we only care about absolute local paths or file:// URLs.
const mdImageRe = /!\[[^\]]*\]\(([^)]+)\)/g;
let m;
while ((m = mdImageRe.exec(t))) {
const raw = (m[1] || '').trim().replace(/^</, '').replace(/>$/, '');
if (!raw) continue;
if (raw.startsWith('file://')) out.push(raw.replace('file://', ''));
else if (raw.startsWith('/')) out.push(raw);
else if (raw.startsWith('~')) out.push(resolvePath(raw));
}
// Also support bare local paths (rare): /Users/.../.clawdbot/media/xxx.png or /tmp/xxx.png
const barePathRe = /\/(Users|home|tmp)\/[^\s)]+\.(png|jpg|jpeg|gif|webp|bmp)/gi;
while ((m = barePathRe.exec(t))) {
out.push(m[0]);
}
// Dedup
return [...new Set(out)];
}
function stripMarkdownLocalMediaRefs(text) {
const t = String(text ?? '');
// Remove markdown image refs and bare paths; keep text readable.
return t
.replace(/!\[[^\]]*\]\(([^)]+)\)/g, '[图片]')
.replace(/\/(Users|home)\/[^\s)]+\.(png|jpg|jpeg|gif|webp|bmp)/gi, '[图片]')
.trim();
}
function parseMediaLines(replyText) {
const text = String(replyText ?? '');
const lines = text.split(/\r?\n/);
const media = [];
const kept = [];
const pushMedia = (raw) => {
let u = String(raw || '').trim();
if (!u) return;
// Strip angle brackets and trailing punctuation.
u = u.replace(/^</, '').replace(/>$/, '').replace(/[),.;,。;]+$/, '').trim();
if (!u) return;
media.push(u);
};
for (const line of lines) {
// 1) Dedicated MEDIA line
const m = line.match(/^\s*MEDIA\s*[::]\s*(.+?)\s*$/i);
if (m) {
pushMedia(m[1]);
continue;
}
// 2) Inline MEDIA tokens (some agents print "... MEDIA: /path.png" in the same line)
const inlineRe = /MEDIA\s*[::]\s*(\S+)/gi;
let mm;
let foundInline = false;
while ((mm = inlineRe.exec(line))) {
foundInline = true;
pushMedia(mm[1]);
}
if (foundInline) {
// keep the line but remove the MEDIA token chunk to avoid clutter
kept.push(line.replace(inlineRe, '').trim());
continue;
}
kept.push(line);
}
return { text: kept.join('\n').trim(), mediaUrls: [...new Set(media)] };
}
async function downloadUrlToTempFile(url) {
const u = String(url);
const ext = extLower(u) || 'bin';
const tmp = path.join(os.tmpdir(), `feishu_bridge_${Date.now()}_${Math.random().toString(16).slice(2)}.${ext}`);
const proto = u.startsWith('https') ? https : http;
await new Promise((resolve, reject) => {
const req = proto.get(u, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
const loc = res.headers.location;
res.resume();
if (!loc) return reject(new Error('Redirect without location header'));
downloadUrlToTempFile(loc).then(resolve).catch(reject);
return;
}
if (res.statusCode !== 200) {
res.resume();
return reject(new Error(`HTTP ${res.statusCode}`));
}
const out = fs.createWriteStream(tmp);
pipeline(res, out).then(resolve).catch(reject);
});
req.on('error', reject);
});
return tmp;
}
function cleanupTempFile(filePath) {
try {
if (filePath && filePath.startsWith(os.tmpdir())) fs.unlinkSync(filePath);
} catch {
// ignore
}
}
// ─── Load secrets & config ───────────────────────────────────────
if (SELFTEST) {
await runSelfTest();
process.exit(0);
}
if (!APP_ID) {
console.error('[FATAL] FEISHU_APP_ID environment variable is required');
process.exit(1);
}
const APP_SECRET = mustRead(APP_SECRET_PATH, 'Feishu App Secret');
const clawdConfig = JSON.parse(mustRead(CLAWDBOT_CONFIG_PATH, 'Clawdbot config'));
const GATEWAY_PORT = clawdConfig?.gateway?.port || 18789;
const GATEWAY_TOKEN = clawdConfig?.gateway?.auth?.token;
if (!GATEWAY_TOKEN) {
console.error('[FATAL] gateway.auth.token missing in Clawdbot config');
process.exit(1);
}
DEVICE_IDENTITY = await loadOrCreateDeviceIdentity(DEVICE_IDENTITY_PATH);
console.log(`[OK] Device identity: ${DEVICE_IDENTITY.deviceId.slice(0, 8)}...`);
// ─── Feishu SDK setup ────────────────────────────────────────────
const sdkConfig = {
appId: APP_ID,
appSecret: APP_SECRET,
domain: Lark.Domain.Feishu,
appType: Lark.AppType.SelfBuild,
};
const client = new Lark.Client(sdkConfig);
const wsClient = new Lark.WSClient({ ...sdkConfig, loggerLevel: Lark.LoggerLevel.info });
// ─── Dedup (Feishu may deliver the same event more than once) ────
const seen = new Map();
const SEEN_TTL_MS = 10 * 60 * 1000;
function isDuplicate(messageId) {
const now = Date.now();
for (const [k, ts] of seen) {
if (now - ts > SEEN_TTL_MS) seen.delete(k);
}
if (!messageId) return false;
if (seen.has(messageId)) return true;
seen.set(messageId, now);
return false;
}
// ─── Talk to Clawdbot Gateway ────────────────────────────────────
async function askClawdbot({ text, sessionKey, attachments = [] }) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${GATEWAY_PORT}`);
let runId = null;
let buf = '';
let mediaUrls = [];
let connectSent = false;
let connectFallbackTimer = null;
const close = () => {
try {
ws.close();
} catch {}
};
const sendConnect = (challengeNonce = null) => {
if (connectSent) return;
connectSent = true;
if (connectFallbackTimer) {
clearTimeout(connectFallbackTimer);
connectFallbackTimer = null;
}
const params = {
minProtocol: 3,
maxProtocol: 3,
client: { id: 'gateway-client', version: BRIDGE_VERSION, platform: 'macos', mode: 'backend' },
role: 'operator',
scopes: ['operator.read', 'operator.write'],
auth: { token: GATEWAY_TOKEN },
locale: 'zh-CN',
userAgent: 'feishu-openclaw-bridge',
};
if (DEVICE_IDENTITY) {
try {
const signedAt = Date.now();
const payload = buildDeviceAuthPayload({
deviceId: DEVICE_IDENTITY.deviceId,
clientId: params.client.id,
clientMode: params.client.mode,
role: params.role,
scopes: params.scopes,
signedAtMs: signedAt,
token: GATEWAY_TOKEN,
nonce: challengeNonce || undefined,
});
const signature = signDevicePayload(DEVICE_IDENTITY, payload);
params.device = {
id: DEVICE_IDENTITY.deviceId,
publicKey: DEVICE_IDENTITY.publicKey,
signature,
signedAt,
...(challengeNonce ? { nonce: challengeNonce } : {}),
};
} catch (e) {
console.error(`[WARN] Device auth sign failed, falling back without device block: ${e?.message || String(e)}`);
}
}
ws.send(
JSON.stringify({
type: 'req',
id: 'connect',
method: 'connect',
params,
}),
);
};
ws.on('open', () => {
// Backward compatibility: older gateways may not send connect.challenge.
connectFallbackTimer = setTimeout(() => sendConnect(null), 300);
if (typeof connectFallbackTimer.unref === 'function') connectFallbackTimer.unref();
});
ws.on('close', () => {
if (connectFallbackTimer) {
clearTimeout(connectFallbackTimer);
connectFallbackTimer = null;
}
});
ws.on('error', (e) => {
close();
reject(e);
});
ws.on('message', (raw) => {
let msg;
try {
msg = JSON.parse(raw.toString());
} catch {
return;
}
if (msg.type === 'event' && msg.event === 'connect.challenge') {
const nonce = msg.payload?.nonce;
sendConnect(typeof nonce === 'string' ? nonce : null);
return;
}
if (msg.type === 'res' && msg.id === 'connect') {
if (!msg.ok) {
close();
reject(new Error(msg.error?.message || 'connect failed'));
return;
}
const deviceToken = msg.payload?.auth?.deviceToken;
if (typeof deviceToken === 'string' && deviceToken.trim()) {
try {
DEVICE_IDENTITY = persistDeviceToken(DEVICE_IDENTITY, deviceToken);
} catch (e) {
console.error(`[WARN] Failed to persist device token: ${e?.message || String(e)}`);
}
}
const params = {
message: text,
agentId: CLAWDBOT_AGENT_ID,
sessionKey,
deliver: false,
// Help the agent return media in a way the bridge can forward.
extraSystemPrompt:
'When you generate images/files, always include one or more standalone lines like:\nMEDIA: <absolute_file_path_or_url>\nIf you cannot generate or attach media, say so explicitly.',
idempotencyKey: uuid(),
};
if (Array.isArray(attachments) && attachments.length > 0) {
params.attachments = attachments;
}
ws.send(
JSON.stringify({
type: 'req',
id: 'agent',
method: 'agent',
params,
}),
);
return;
}
if (msg.type === 'res' && msg.id === 'agent') {
if (!msg.ok) {
close();
reject(new Error(msg.error?.message || 'agent error'));
return;
}
if (msg.payload?.runId) runId = msg.payload.runId;
return;
}
if (msg.type === 'event' && msg.event === 'agent') {
const p = msg.payload;
if (!p || (runId && p.runId !== runId)) return;
// Capture media outputs from ANY stream (assistant/tool/etc).
// Some tools return media URLs without printing "MEDIA:" lines.
{
const d = p.data || {};
if (typeof d.mediaUrl === 'string' && d.mediaUrl.trim()) {
mediaUrls.push(d.mediaUrl.trim());
}
if (Array.isArray(d.mediaUrls)) {
for (const u of d.mediaUrls) {
if (typeof u === 'string' && u.trim()) mediaUrls.push(u.trim());
}
}
// Ultra-defensive: some tools embed media refs deeply.
const deep = extractMediaRefsDeep(d, 8);
if (deep.length > 0) mediaUrls.push(...deep);
if (DEBUG) {
const hasDirect = Boolean(d.mediaUrl || (Array.isArray(d.mediaUrls) && d.mediaUrls.length));
const hasDeep = deep.length > 0;
if (hasDirect || hasDeep) {
console.log(`[DEBUG] agent event media: stream=${p.stream} direct=${hasDirect} deep=${JSON.stringify(deep)}`);
}
}
}
if (p.stream === 'assistant') {
const d = p.data || {};
// text stream
if (typeof d.text === 'string') buf = d.text;
else if (typeof d.delta === 'string') buf += d.delta;
return;
}
if (p.stream === 'lifecycle') {
if (p.data?.phase === 'end') {
close();
mediaUrls = [...new Set(mediaUrls)];
if (DEBUG) {
console.log(`[DEBUG] agent run end: runId=${runId || '-'} textLen=${(buf || '').length} mediaCount=${mediaUrls.length}`);
if (mediaUrls.length) console.log(`[DEBUG] agent mediaUrls: ${mediaUrls.slice(0, 6).join(' | ')}`);
}
resolve({ text: (buf || '').trim(), mediaUrls });
}
if (p.data?.phase === 'error') {
close();
reject(new Error(p.data?.message || 'agent error'));
}
}
}
});
});
}
// ─── Feishu message parsing ─────────────────────────────────────
function shouldRespondInGroup(text, mentions) {
if (mentions.length > 0) return true;
const t = text.toLowerCase();
if (/[??]$/.test(text)) return true;
if (/\b(why|how|what|when|where|who|help)\b/.test(t)) return true;
const verbs = ['帮', '麻烦', '请', '能否', '可以', '解释', '看看', '排查', '分析', '总结', '写', '改', '修', '查', '对比', '翻译'];
if (verbs.some((k) => text.includes(k))) return true;
if (/^(alen|clawdbot|bot|助手|智能体)[\s,:,:]/i.test(text)) return true;
return false;
}
function extractFromPostJson(postJson) {
const lines = [];
const imageKeys = [];
const pushLine = (s) => {
const v = String(s ?? '').trimEnd();
if (v.trim()) lines.push(v);
};
const inline = (node) => {
if (!node) return '';
if (Array.isArray(node)) return node.map(inline).join('');
if (typeof node !== 'object') return '';
const tag = node.tag;
if (typeof tag === 'string') {
if (tag === 'text') return String(node.text ?? '');
if (tag === 'a') return String(node.text ?? node.href ?? '');
if (tag === 'at') return node.user_name ? `@${node.user_name}` : '@';
if (tag === 'md') return String(node.text ?? '');
if (tag === 'img') {
if (node.image_key) imageKeys.push(String(node.image_key));
return '[图片]';
}
if (tag === 'file') return '[文件]';
if (tag === 'media') return '[视频]';
if (tag === 'hr') return '\n';
if (tag === 'code_block') {
const lang = String(node.language || '').trim();
const code = String(node.text || '');
return `\n\n\
\`\`\`${lang ? ` ${lang}` : ''}\n${code}\n\`\`\`\n\n`;
}
}
// Fallback: traverse children to avoid dropping content when Feishu changes structure.
let acc = '';
for (const v of Object.values(node)) {
if (v && (typeof v === 'object' || Array.isArray(v))) acc += inline(v);
}
return acc;
};
if (postJson?.title) pushLine(normalizeFeishuText(postJson.title));
const content = postJson?.content;
if (Array.isArray(content)) {
for (const paragraph of content) {
// In Feishu post, each paragraph is usually an array of inline nodes.
if (Array.isArray(paragraph)) {
const joined = paragraph.map(inline).join('');
const normalized = normalizeFeishuText(joined);
if (normalized) pushLine(normalized);
} else {
const normalized = normalizeFeishuText(inline(paragraph));
if (normalized) pushLine(normalized);
}
}
} else if (content) {
const normalized = normalizeFeishuText(inline(content));
if (normalized) pushLine(normalized);
}
const text = lines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
return { text, imageKeys: [...new Set(imageKeys)] };
}
async function downloadFeishuImageAsDataUrl(messageId, imageKey) {
const tmp = path.join(os.tmpdir(), `feishu_recv_${Date.now()}_${Math.random().toString(16).slice(2)}.png`);
try {
if (DEBUG) console.log(`[DEBUG] Downloading image: messageId=${messageId}, imageKey=${imageKey}`);
const response = await client.im.messageResource.get({
path: { message_id: messageId, file_key: imageKey },
params: { type: 'image' },
});
// Debug: log response structure
const responseType = typeof response;
const responseKeys = response && typeof response === 'object' ? Object.keys(response) : [];
if (DEBUG) console.log(`[DEBUG] Image response: type=${responseType}, keys=${responseKeys.join(',')}`);
if (response && response.data) {
const dataType = typeof response.data;
const dataKeys = response.data && typeof response.data === 'object' ? Object.keys(response.data) : [];
if (DEBUG) console.log(`[DEBUG] response.data: type=${dataType}, keys=${dataKeys.join(',')}`);
}
// SDK may return stream/buffer or wrap it inside { data: ... }
const data = response;
const payload = (data && typeof data === 'object' && 'data' in data) ? data.data : data;
// Newer SDK versions return a "response-like" object with helpers.
if (payload && typeof payload.writeFile === 'function') {
await payload.writeFile(tmp);
} else if (payload && typeof payload.getReadableStream === 'function') {
const rs = payload.getReadableStream();
const nodeRs = toNodeReadableStream(rs);
if (!nodeRs) throw new Error('getReadableStream() returned non-stream');
const out = fs.createWriteStream(tmp);
await pipeline(nodeRs, out);
} else if (payload && typeof payload.pipe === 'function') {
const out = fs.createWriteStream(tmp);
await pipeline(payload, out);
} else if (data && data.data && typeof data.data === 'object' && typeof data.data.pipe === 'function') {
// Some SDK versions nest the stream deeper
const out = fs.createWriteStream(tmp);
await pipeline(data.data, out);
} else if (Buffer.isBuffer(payload)) {
fs.writeFileSync(tmp, payload);
} else if (payload instanceof ArrayBuffer) {
fs.writeFileSync(tmp, Buffer.from(payload));
} else if (ArrayBuffer.isView(payload)) {
fs.writeFileSync(tmp, Buffer.from(payload.buffer));
} else {
const k = data && typeof data === 'object' ? Object.keys(data).join(',') : '';
throw new Error(`Unexpected response type: ${typeof data}${k ? ` (keys: ${k})` : ''}`);
}
// Size guard: base64 data URLs explode in size; avoid choking the gateway.
const st = fs.statSync(tmp);
if (DEBUG) console.log(`[DEBUG] Image downloaded: ${st.size} bytes -> ${tmp}`);
const maxBytes = MAX_INBOUND_IMAGE_MB * 1024 * 1024;
if (st.size > maxBytes) {
throw new Error(`Image too large (${st.size} bytes > ${maxBytes})`);
}
return fileToDataUrl(tmp, 'image/png');
} finally {
cleanupTempFile(tmp);
}
}
async function downloadFeishuFileToPath(messageId, fileKey, fileName = 'file.bin', type = 'file') {
const ext = path.extname(fileName || '') || '.bin';
const tmp = path.join(
os.tmpdir(),
`feishu_recv_${Date.now()}_${Math.random().toString(16).slice(2)}${ext}`,
);
const response = await client.im.messageResource.get({
path: { message_id: messageId, file_key: fileKey },
params: { type },
});