aai-lark-bridge 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1535 @@
1
+ // src/bridge/agent/claude/adapter.ts
2
+ import { mkdtempSync, rmSync, writeFileSync } from "fs";
3
+ import { tmpdir } from "os";
4
+ import { join as join3 } from "path";
5
+ import { createInterface } from "readline";
6
+
7
+ // src/bridge/core/logger.ts
8
+ import { AsyncLocalStorage } from "async_hooks";
9
+ import { createWriteStream, mkdirSync } from "fs";
10
+ import { open, readdir, rm, stat } from "fs/promises";
11
+ import { join } from "path";
12
+
13
+ // src/bridge/core/telemetry.ts
14
+ var noop = {
15
+ emit() {
16
+ },
17
+ recordError() {
18
+ },
19
+ recordMetric() {
20
+ },
21
+ flush() {
22
+ },
23
+ close() {
24
+ }
25
+ };
26
+ var active = noop;
27
+ function telemetry() {
28
+ return active;
29
+ }
30
+
31
+ // src/bridge/core/logger.ts
32
+ var DEFAULT_RETENTION_DAYS = Math.max(
33
+ 1,
34
+ Number(process.env.LARK_CHANNEL_LOG_DAYS ?? 30) || 30
35
+ );
36
+ var loggerOptions = {
37
+ retentionDays: DEFAULT_RETENTION_DAYS,
38
+ now: () => /* @__PURE__ */ new Date()
39
+ };
40
+ var STDOUT_INFO_ALLOWLIST = /* @__PURE__ */ new Set([
41
+ "ws.connected",
42
+ "ws.reconnecting",
43
+ "ws.reconnected",
44
+ "intake.enter",
45
+ "intake.command",
46
+ "run.started",
47
+ "run.completed",
48
+ "run.failed",
49
+ "cot.created",
50
+ "cot.completed",
51
+ "outbound.sent",
52
+ "outbound.markdown-stream-fallback",
53
+ "card.final"
54
+ ]);
55
+ var als = new AsyncLocalStorage();
56
+ var stream = null;
57
+ var currentDate = "";
58
+ function todayKey() {
59
+ return formatLocalDateKey(loggerOptions.now());
60
+ }
61
+ function logsDir() {
62
+ return loggerOptions.logsDir;
63
+ }
64
+ function logFileName(dateKey) {
65
+ return `bridge-${dateKey}.jsonl`;
66
+ }
67
+ function getStream() {
68
+ const dir = logsDir();
69
+ if (!dir) return null;
70
+ const today = todayKey();
71
+ if (stream && currentDate === today) return stream;
72
+ if (stream) {
73
+ try {
74
+ stream.end();
75
+ } catch {
76
+ }
77
+ }
78
+ try {
79
+ mkdirSync(dir, { recursive: true });
80
+ stream = createWriteStream(join(dir, logFileName(today)), { flags: "a" });
81
+ currentDate = today;
82
+ return stream;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ var RESERVED_KEYS = /* @__PURE__ */ new Set([
88
+ "ts",
89
+ "level",
90
+ "phase",
91
+ "event",
92
+ "traceId",
93
+ "chatId",
94
+ "msgId"
95
+ ]);
96
+ var TELEMETRY_ENVELOPE_KEYS = /* @__PURE__ */ new Set([
97
+ "ts",
98
+ "level",
99
+ "phase",
100
+ "event",
101
+ "traceId",
102
+ "chatId",
103
+ "msgId"
104
+ ]);
105
+ var RAW_PAYLOAD_KEYS = /* @__PURE__ */ new Set([
106
+ "prompt",
107
+ "stdout",
108
+ "stderr",
109
+ "env",
110
+ "environment",
111
+ "proxy"
112
+ ]);
113
+ var RESOURCE_ID_KEYS = /* @__PURE__ */ new Set(["fileKey", "sourceFileKey"]);
114
+ var ID_KEYS = /* @__PURE__ */ new Set([
115
+ "chatId",
116
+ "senderId",
117
+ "sender",
118
+ "openId",
119
+ "operatorId",
120
+ "userId",
121
+ "msgId",
122
+ "messageId",
123
+ "sourceMessageId",
124
+ "sessionId",
125
+ "threadId",
126
+ "docToken",
127
+ "fileToken",
128
+ "fileKey",
129
+ "sourceFileKey",
130
+ "commentId",
131
+ "rootCommentId",
132
+ "replyId",
133
+ "reactionId",
134
+ "scope",
135
+ "appId"
136
+ ]);
137
+ var MAX_LOG_STRING_CHARS = 4096;
138
+ var CREDENTIAL_JSON_FIELD_RE = /("(?:secret|app_secret|appSecret|token|access_token|tenant_access_token|app_access_token|authorization)"\s*:\s*")[^"]*(")/gi;
139
+ var ESCAPED_CREDENTIAL_JSON_FIELD_RE = /(\\\"(?:secret|app_secret|appSecret|token|access_token|tenant_access_token|app_access_token|authorization)\\\"\s*:\s*\\\")[^\\]*(\\\")/gi;
140
+ var RESOURCE_JSON_FIELD_RE = /("(?:fileKey|sourceFileKey|file_key|source_file_key|imageKey|image_key|mediaKey|media_key)"\s*:\s*")[^"]*(")/gi;
141
+ var ESCAPED_RESOURCE_JSON_FIELD_RE = /(\\\"(?:fileKey|sourceFileKey|file_key|source_file_key|imageKey|image_key|mediaKey|media_key)\\\"\s*:\s*\\\")[^\\]*(\\\")/gi;
142
+ var LOCAL_LOG_SANITIZE = { redactIds: false };
143
+ var EXTERNAL_SANITIZE = { redactIds: true };
144
+ function sanitizeLogEntry(entry, options = EXTERNAL_SANITIZE) {
145
+ const out = {};
146
+ for (const [key, value] of Object.entries(entry)) {
147
+ out[key] = sanitizeLogValue(key, value, options);
148
+ }
149
+ return out;
150
+ }
151
+ function sanitizeLogValue(key, value, options = EXTERNAL_SANITIZE) {
152
+ const normalizedKey = key.startsWith("_") ? key.slice(1) : key;
153
+ if (value === void 0) return void 0;
154
+ if (RAW_PAYLOAD_KEYS.has(normalizedKey)) return "[REDACTED]";
155
+ if (/token|secret|authorization/i.test(normalizedKey)) return "[REDACTED]";
156
+ if (/attachment.*path|media.*path|^(cwd|cwdRealpath|path|absPath)$/i.test(normalizedKey)) {
157
+ return "[REDACTED_PATH]";
158
+ }
159
+ if (RESOURCE_ID_KEYS.has(normalizedKey)) return "[REDACTED_RESOURCE]";
160
+ if (options.redactIds && ID_KEYS.has(normalizedKey)) return redactId(value);
161
+ if (Array.isArray(value)) {
162
+ return value.map((item) => sanitizeLogValue(key, item, options));
163
+ }
164
+ if (value && typeof value === "object") {
165
+ const nested = {};
166
+ for (const [nestedKey, nestedValue] of Object.entries(value)) {
167
+ nested[nestedKey] = sanitizeLogValue(nestedKey, nestedValue, options);
168
+ }
169
+ return nested;
170
+ }
171
+ if (typeof value === "string") {
172
+ const redacted = redactDiagnosticText(value);
173
+ if (redacted.length > MAX_LOG_STRING_CHARS) {
174
+ return `${redacted.slice(0, MAX_LOG_STRING_CHARS)}...[truncated]`;
175
+ }
176
+ return redacted;
177
+ }
178
+ return value;
179
+ }
180
+ function redactId(value) {
181
+ if (typeof value !== "string") return value;
182
+ if (value.length <= 6) return value;
183
+ return `...${value.slice(-6)}`;
184
+ }
185
+ function emit(level, phase, event, fields = {}) {
186
+ const ctx = als.getStore() ?? {};
187
+ const entry = sanitizeLogEntry({
188
+ ts: formatLocalTimestamp(loggerOptions.now()),
189
+ level,
190
+ phase,
191
+ event,
192
+ ...ctx
193
+ }, LOCAL_LOG_SANITIZE);
194
+ for (const [k, v] of Object.entries(fields)) {
195
+ if (RESERVED_KEYS.has(k)) {
196
+ entry[`_${k}`] = sanitizeLogValue(`_${k}`, v, LOCAL_LOG_SANITIZE);
197
+ } else {
198
+ entry[k] = sanitizeLogValue(k, v, LOCAL_LOG_SANITIZE);
199
+ }
200
+ }
201
+ const externalEntry = sanitizeLogEntry(entry, EXTERNAL_SANITIZE);
202
+ const telemetrySafe = telemetryPayloadFromEntry(externalEntry);
203
+ const s = getStream();
204
+ if (s) {
205
+ try {
206
+ s.write(`${JSON.stringify(entry)}
207
+ `);
208
+ } catch {
209
+ }
210
+ }
211
+ try {
212
+ telemetry().emit({
213
+ level,
214
+ phase,
215
+ event,
216
+ fields: telemetrySafe.fields,
217
+ ctx: telemetrySafe.ctx,
218
+ ts: String(entry.ts)
219
+ });
220
+ } catch {
221
+ }
222
+ if (level === "error") {
223
+ try {
224
+ telemetry().recordError(telemetrySafe.fields.err ?? `${phase}.${event}`, {
225
+ phase,
226
+ event,
227
+ ...telemetrySafe.ctx,
228
+ ...telemetrySafe.fields
229
+ });
230
+ } catch {
231
+ }
232
+ }
233
+ const showOnStdout = level !== "info" || STDOUT_INFO_ALLOWLIST.has(`${phase}.${event}`);
234
+ if (!showOnStdout) return;
235
+ const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
236
+ fn(formatStdout(level, phase, event, telemetrySafe.ctx, telemetrySafe.fields));
237
+ }
238
+ function telemetryPayloadFromEntry(entry) {
239
+ const ctx = {};
240
+ if (typeof entry.traceId === "string") ctx.traceId = entry.traceId;
241
+ if (typeof entry.chatId === "string") ctx.chatId = entry.chatId;
242
+ if (typeof entry.msgId === "string") ctx.msgId = entry.msgId;
243
+ const fields = {};
244
+ for (const [key, value] of Object.entries(entry)) {
245
+ if (TELEMETRY_ENVELOPE_KEYS.has(key) || value === void 0) continue;
246
+ fields[key] = value;
247
+ }
248
+ return { ctx, fields };
249
+ }
250
+ function formatStdout(level, phase, event, ctx, fields) {
251
+ if (phase === "ws") {
252
+ if (event === "connected") {
253
+ const bot = fields.bot ?? "-";
254
+ const appId = fields.appId ? ` (${fields.appId})` : "";
255
+ const agent = fields.agent ?? "-";
256
+ const proc = fields.procId ? ` \u8FDB\u7A0B: ${fields.procId}` : "";
257
+ return `\u2713 \u5DF2\u8FDE\u63A5 bot: ${bot}${appId} agent: ${agent}${proc}`;
258
+ }
259
+ if (event === "reconnecting") return "\u21BB \u6B63\u5728\u91CD\u8FDE\u2026";
260
+ if (event === "reconnected") return "\u2713 \u5DF2\u91CD\u8FDE";
261
+ if (event === "fail") return `\u2717 WS \u9519\u8BEF: ${fields.err ?? ""}`;
262
+ }
263
+ if (phase === "intake" && event === "enter") {
264
+ const c = ctx.chatId ? ctx.chatId.slice(-6) : "-";
265
+ const mode = fields.chatMode ?? fields.chatType ?? "?";
266
+ const scope = shortId(fields.scope);
267
+ const sender = fields.sender ?? "-";
268
+ const msg = shortId(ctx.msgId ?? fields.msgId ?? fields._msgId);
269
+ const preview = fields.preview ?? "";
270
+ return `\u25B8 ${mode}/${c} scope=${scope} sender=${sender} msg=${msg}: ${preview}`;
271
+ }
272
+ if (phase === "intake" && event === "command") {
273
+ const scope = shortId(fields.scope);
274
+ return ` \u21B3 command scope=${scope} dropped=${fields.droppedPending ?? 0}`;
275
+ }
276
+ if (phase === "run" && event === "started") {
277
+ const scope = shortId(fields.scope);
278
+ return ` \u25B6 run start scope=${scope} run=${shortId(fields.runId)} queue=${fields.queueWaitMs ?? 0}ms`;
279
+ }
280
+ if (phase === "run" && (event === "completed" || event === "failed")) {
281
+ const result = event === "failed" ? "failed" : fields.result ?? "done";
282
+ const mark = event === "failed" ? "\u2717" : result === "interrupted" ? "\u23F9" : "\u2713";
283
+ const scope = shortId(fields.scope);
284
+ const duration = formatDurationMs(fields.durationMs);
285
+ return ` ${mark} run ${result} scope=${scope} run=${shortId(fields.runId)}${duration ? ` duration=${duration}` : ""}`;
286
+ }
287
+ if (phase === "cot" && event === "created") {
288
+ return ` \u25C7 cot created message=${shortId(fields.messageId)} cot=${shortId(fields.cotId)}`;
289
+ }
290
+ if (phase === "cot" && event === "completed") {
291
+ return ` \u25C7 cot completed cot=${shortId(fields.cotId)} reason=${fields.reason ?? "-"}`;
292
+ }
293
+ if (phase === "outbound" && event === "markdown-stream-fallback") {
294
+ return ` \u26A0 markdown stream fallback: ${fields.err ?? ""}`;
295
+ }
296
+ if (phase === "outbound" && event === "sent") {
297
+ const scope = shortId(fields.scope);
298
+ const reply = fields.replyInThread === true ? "thread" : "reply";
299
+ return ` \u2197 sent ${fields.type ?? "message"} scope=${scope} ${reply}=${shortId(fields.replyTo)} msg=${shortId(fields.messageId)}`;
300
+ }
301
+ if (phase === "card" && event === "final") {
302
+ const c = ctx.chatId ? ctx.chatId.slice(-6) : "-";
303
+ const t = fields.terminal;
304
+ const mark = t === "done" ? "\u2713" : t === "interrupted" ? "\u23F9" : "\u2717";
305
+ const scope = fields.scope ? shortId(fields.scope) : c;
306
+ return ` ${mark} ${scope} ${t}`;
307
+ }
308
+ const ctxBits = [];
309
+ if (ctx.traceId) ctxBits.push(`t=${ctx.traceId}`);
310
+ if (ctx.chatId) ctxBits.push(`c=${ctx.chatId.slice(-6)}`);
311
+ const ctxStr = ctxBits.length > 0 ? ` ${ctxBits.join(" ")}` : "";
312
+ const summary = formatFields(fields);
313
+ const tag = level === "error" ? "\u2717" : level === "warn" ? "\u26A0" : "\xB7";
314
+ return `${tag} [${phase}.${event}]${ctxStr}${summary ? ` ${summary}` : ""}`;
315
+ }
316
+ function formatLocalDateKey(date) {
317
+ const y = date.getFullYear();
318
+ const m = String(date.getMonth() + 1).padStart(2, "0");
319
+ const d = String(date.getDate()).padStart(2, "0");
320
+ return `${y}${m}${d}`;
321
+ }
322
+ function formatLocalTimestamp(date) {
323
+ const y = date.getFullYear();
324
+ const m = String(date.getMonth() + 1).padStart(2, "0");
325
+ const d = String(date.getDate()).padStart(2, "0");
326
+ const hh = String(date.getHours()).padStart(2, "0");
327
+ const mm = String(date.getMinutes()).padStart(2, "0");
328
+ const ss = String(date.getSeconds()).padStart(2, "0");
329
+ const ms = String(date.getMilliseconds()).padStart(3, "0");
330
+ const offsetMinutes = -date.getTimezoneOffset();
331
+ const sign = offsetMinutes >= 0 ? "+" : "-";
332
+ const abs = Math.abs(offsetMinutes);
333
+ const oh = String(Math.floor(abs / 60)).padStart(2, "0");
334
+ const om = String(abs % 60).padStart(2, "0");
335
+ return `${y}-${m}-${d}T${hh}:${mm}:${ss}.${ms}${sign}${oh}:${om}`;
336
+ }
337
+ function shortId(value) {
338
+ if (value === void 0 || value === null) return "-";
339
+ const s = String(value);
340
+ const last = s.includes(":") ? s.split(":").at(-1) ?? s : s;
341
+ const bare = last.startsWith("...") ? last.slice(3) : last;
342
+ return bare.length > 6 ? bare.slice(-6) : bare;
343
+ }
344
+ function formatDurationMs(value) {
345
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
346
+ if (value < 1e3) return `${value}ms`;
347
+ const seconds = value / 1e3;
348
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
349
+ const minutes = Math.floor(seconds / 60);
350
+ const rest = Math.round(seconds % 60);
351
+ return rest > 0 ? `${minutes}m${rest}s` : `${minutes}m`;
352
+ }
353
+ function formatFields(fields) {
354
+ const keys = Object.keys(fields);
355
+ if (keys.length === 0) return "";
356
+ const parts = [];
357
+ for (const k of keys) {
358
+ const v = fields[k];
359
+ if (v === void 0 || v === null) continue;
360
+ if (k === "stack") continue;
361
+ if (typeof v === "string") {
362
+ parts.push(`${k}=${v.length > 80 ? `${v.slice(0, 80)}\u2026` : v}`);
363
+ } else if (typeof v === "number" || typeof v === "boolean") {
364
+ parts.push(`${k}=${v}`);
365
+ } else {
366
+ try {
367
+ const s = JSON.stringify(v);
368
+ parts.push(`${k}=${s.length > 80 ? `${s.slice(0, 80)}\u2026` : s}`);
369
+ } catch {
370
+ parts.push(`${k}=?`);
371
+ }
372
+ }
373
+ }
374
+ return parts.join(" ");
375
+ }
376
+ var log = {
377
+ info(phase, event, fields) {
378
+ emit("info", phase, event, fields);
379
+ },
380
+ warn(phase, event, fields) {
381
+ emit("warn", phase, event, fields);
382
+ },
383
+ fail(phase, err, fields) {
384
+ const message = err instanceof Error ? err.message : String(err);
385
+ const stack = err instanceof Error ? err.stack : void 0;
386
+ const apiData = err?.response?.data;
387
+ const apiStatus = err?.response?.status;
388
+ emit("error", phase, "fail", {
389
+ ...fields,
390
+ err: message,
391
+ apiStatus,
392
+ apiData,
393
+ stack
394
+ });
395
+ }
396
+ };
397
+ function redactDiagnosticText(text) {
398
+ let out = redactJsonCredentialText(text);
399
+ out = redactResourceText(out);
400
+ out = out.replace(
401
+ /\b(Authorization\s*[:=]\s*Bearer\s+)[A-Za-z0-9._\-+/=]+/gi,
402
+ "$1[REDACTED]"
403
+ );
404
+ out = out.replace(/\b(Bearer\s+)[A-Za-z0-9._\-+/=]+/g, "$1[REDACTED]");
405
+ out = out.replace(
406
+ /\b(access_token|tenant_access_token|app_access_token|app_secret|appSecret|secret|token|doc_token|file_token|authorization)=([^&\s"',}]+)/gi,
407
+ "$1=[REDACTED]"
408
+ );
409
+ out = out.replace(
410
+ /(^|[\s"'=])((?:\/(?:Users|home|tmp|var|private|Volumes|opt|workspace|workspaces|mnt|app|srv|root|data)\/[^\s"',)]+))/g,
411
+ "$1[REDACTED_PATH]"
412
+ );
413
+ out = out.replace(/(^|[\s"'=])(~\/[^\s"',)]+)/g, "$1[REDACTED_PATH]");
414
+ out = out.replace(/[A-Za-z]:\\[^\s"',)]+/g, "[REDACTED_PATH]");
415
+ return out;
416
+ }
417
+ function redactJsonCredentialText(text) {
418
+ return text.replace(CREDENTIAL_JSON_FIELD_RE, "$1[REDACTED]$2").replace(ESCAPED_CREDENTIAL_JSON_FIELD_RE, "$1[REDACTED]$2");
419
+ }
420
+ function redactResourceText(text) {
421
+ return text.replace(RESOURCE_JSON_FIELD_RE, "$1[REDACTED_RESOURCE]$2").replace(ESCAPED_RESOURCE_JSON_FIELD_RE, "$1[REDACTED_RESOURCE]$2").replace(
422
+ /<\s*(?:file|image|img|audio|video|media|folder)\b[^>]*\bkey\s*=\s*["'][^"']+["'][^>]*>/gi,
423
+ "[REDACTED_RESOURCE]"
424
+ ).replace(/!?\[[^\]]*]\((?:file|img|image|media)_[^)]+\)/gi, "[REDACTED_RESOURCE]").replace(
425
+ /\b(?:file|img|image|media)_(?:v\d+_)?[A-Za-z0-9][A-Za-z0-9._-]{8,}\b/g,
426
+ "[REDACTED_RESOURCE]"
427
+ );
428
+ }
429
+
430
+ // src/bridge/platform/spawn.ts
431
+ import crossSpawn from "cross-spawn";
432
+ function spawnProcess(command, args = [], options = {}) {
433
+ return crossSpawn(command, [...args], options);
434
+ }
435
+ function mergeProcessEnv(base = process.env, overrides = {}) {
436
+ const out = { ...base };
437
+ for (const [key, value] of Object.entries(overrides)) {
438
+ for (const existing of Object.keys(out)) {
439
+ if (existing.toLowerCase() === key.toLowerCase()) {
440
+ delete out[existing];
441
+ }
442
+ }
443
+ if (value !== void 0) out[key] = value;
444
+ }
445
+ return out;
446
+ }
447
+
448
+ // src/bridge/agent/bridge-system-prompt.ts
449
+ var BRIDGE_SYSTEM_PROMPT = `# aai-lark-bridge \u8FD0\u884C\u7EA6\u5B9A
450
+
451
+ \u4F60\u6B63\u5728 aai-lark-bridge \u91CC\u8DD1\uFF1A\u628A\u98DE\u4E66/Lark \u7528\u6237\u6D88\u606F\u6865\u5230\u672C\u5730 agent CLI\u3002
452
+
453
+ ## bridge_context
454
+
455
+ \u6BCF\u6761 user message \u9876\u90E8\u4F1A\u5E26\u4E00\u4E2A \`<bridge_context>\` \u5757\uFF1A
456
+
457
+ \`\`\`
458
+ <bridge_context>
459
+ {"chatId":"oc_xxx","chatType":"p2p","senderId":"ou_xxx","senderName":"...",
460
+ "senderType":"user|bot","botOpenId":"ou_xxx","mentions":[{"openId":"ou_xxx","name":"...","isBot":true}], ...}
461
+ </bridge_context>
462
+ \`\`\`
463
+
464
+ \u91CC\u9762\u662F\u5F53\u524D\u5BF9\u8BDD\u7684 chat_id\u3001chat \u7C7B\u578B\uFF08p2p / group\uFF09\u3001\u53D1\u9001\u8005\u3002\u5173\u952E\u5B57\u6BB5\uFF1A
465
+
466
+ - \`senderType\`\uFF1A\u53D1\u9001\u8005\u662F\u4EBA\uFF08\`user\`\uFF09\u8FD8\u662F\u53E6\u4E00\u4E2A bot\uFF08\`bot\`\uFF09\uFF1B\u7F3A\u7701\u8868\u793A\u672A\u77E5
467
+ - \`botOpenId\`\uFF1A**\u4F60\u81EA\u5DF1**\u7684 open_id
468
+ - \`mentions\`\uFF1A\u8FD9\u6761\u6D88\u606F @ \u5230\u7684\u8D26\u53F7\u5217\u8868\uFF08\u542B open_id \u548C isBot\uFF09\uFF0C\u9700\u8981 @ \u67D0\u4EBA/\u67D0 bot \u65F6\u4ECE\u8FD9\u91CC\u53D6 id
469
+
470
+ \u591A\u6761\u6D88\u606F\u5728\u77ED\u65F6\u95F4\u5185\u5408\u5E76\u9001\u8FBE\u65F6\uFF0C\`user_input\` \u91CC\u6BCF\u6BB5\u4F1A\u5E26 \`[\u540D\u5B57 (user|bot)]:\` \u884C\u9996\u6807\u6CE8\u4EE5\u533A\u5206\u53D1\u9001\u8005\u2014\u2014\u8FD9\u662F bridge \u6CE8\u5165\u7684\u5C55\u793A\u683C\u5F0F\uFF0C**\u4F60\u56DE\u590D\u65F6\u4E0D\u8981\u6A21\u4EFF\u8FD9\u79CD\u6807\u6CE8**\u3002\u8FD9\u4E9B\u90FD\u662F bridge \u6CE8\u5165\u7684\u5143\u6570\u636E\uFF0C**\u4E0D\u8981\u7167\u6284\u3001\u4E0D\u8981\u5728\u4F60\u7684\u56DE\u590D\u91CC\u6E32\u67D3**\u2014\u2014\u5B83\u5BF9\u7528\u6237\u4E0D\u53EF\u89C1\u3002
471
+
472
+ ## \u4E0E\u5176\u4ED6 bot \u534F\u4F5C\uFF08bot-at-bot\uFF09
473
+
474
+ - \u81EA\u6211\u8BC6\u522B\uFF1A\`bridge_context.botOpenId\` \u662F\u4F60\u81EA\u5DF1\u7684 open_id\uFF1B\u6D88\u606F\u5185\u5BB9\u6216 mentions \u91CC\u51FA\u73B0\u8FD9\u4E2A id \u5C31\u662F\u6307\u4F60\u81EA\u5DF1\u3002
475
+ - \u98DE\u4E66\u673A\u5236\uFF1Abot **\u53EA\u6709\u88AB\u771F\u5B9E @\uFF08\u7ED3\u6784\u5316 mention\uFF09\u624D\u80FD\u6536\u5230\u7FA4\u6D88\u606F**\u3002\u7EAF\u6587\u672C\u5199 "@\u540D\u5B57"\u3001\u6216\u4E0D\u5E26 @ \u7684\u666E\u901A\u56DE\u590D\uFF0C\u5176\u4ED6 bot \u4E00\u5F8B\u6536\u4E0D\u5230\u3002\u8FD9\u6761\u9650\u5236\u53EA\u9488\u5BF9 bot\u2014\u2014\u4EBA\u7C7B\u7528\u6237\u80FD\u770B\u5230\u7FA4\u91CC\u6240\u6709\u6D88\u606F\uFF0C\u56DE\u590D\u4EBA\u7C7B\u4E0D\u9700\u8981 @\u3002
476
+ - \u9700\u8981\u67D0\u4E2A bot \u63A5\u7740\u5904\u7406\u65F6\uFF0C\u5FC5\u987B\u771F\u5B9E @ \u5B83\uFF08open_id \u4F18\u5148\u4ECE \`bridge_context.mentions\` \u91CC\u53D6\uFF09\u3002\u9664\u6B64\u4E4B\u5916**\u9ED8\u8BA4\u4E0D\u8981 @ \u5176\u4ED6 bot**\u2014\u2014\u4E92\u76F8 @ \u4F1A\u5F62\u6210\u6B7B\u5FAA\u73AF\uFF1B\u7528\u6237\u660E\u786E\u8981\u6C42\u8F6C\u4EA4/\u901A\u77E5\u67D0\u4E2A bot \u65F6\u6309\u8981\u6C42\u6267\u884C\u3002
477
+ - \u4E0E\u5176\u4ED6 bot \u5BF9\u8BDD\u65F6\uFF0C\u6CA1\u6709\u65B0\u4FE1\u606F\u8981\u8865\u5145\u5C31\u7B80\u77ED\u6536\u5C3E\uFF0C\u4E0D\u8981\u8FFD\u95EE\u3001\u4E0D\u8981\u5BA2\u5957\u5F80\u8FD4\u3002
478
+
479
+ ## quoted_message
480
+
481
+ \u5982\u679C\u7528\u6237\u7528"\u5F15\u7528\u56DE\u590D"\u6307\u5411\u67D0\u6761\u6D88\u606F\uFF0Cbridge \u4F1A\u5728 \`<bridge_context>\` \u540E\u6CE8\u5165\u4E00\u4E2A \`<quoted_message>\` \u5757\uFF1A
482
+
483
+ \`\`\`
484
+ <quoted_message id="om_xxx" sender_id="ou_xxx" sender_name="..." created_at="..." type="text|merge_forward|...">
485
+ \uFF08\u88AB\u5F15\u7528\u6D88\u606F\u7684\u5185\u5BB9\uFF1Bmerge_forward \u7C7B\u578B\u4F1A\u5C55\u5F00\u6210 <forwarded_messages>...</forwarded_messages>\uFF09
486
+ </quoted_message>
487
+ \`\`\`
488
+
489
+ \u8FD9\u662F\u7528\u6237**\u6307\u5411\u7684\u5BF9\u8C61**\u2014\u2014\u7528\u6237\u7684\u5B9E\u9645\u95EE\u9898\u5728\u5B83\u4E4B\u540E\u3002\u56DE\u7B54\u65F6\u56F4\u7ED5\u8FD9\u6BB5\u5185\u5BB9\u5C55\u5F00\uFF1B\u5B83\u4E5F\u662F bridge \u6CE8\u5165\u7684\u5143\u6570\u636E\uFF0C**\u4E0D\u8981\u7167\u6284 XML \u6807\u7B7E**\u5230\u56DE\u590D\u91CC\u3002
490
+
491
+ ## interactive_card
492
+
493
+ \u7528\u6237\u53D1 / \u5F15\u7528\u4EA4\u4E92\u5361\u7247\u65F6,bridge \u4F1A\u628A\u5361\u7684\u771F\u5B9E JSON \u6CE8\u5165\u5230 \`<interactive_card>\` \u5757:
494
+
495
+ \`\`\`
496
+ <interactive_card>
497
+ { "schema": "2.0", "config": { ... }, "body": { ... } }
498
+ </interactive_card>
499
+ \`\`\`
500
+
501
+ \u4E24\u79CD\u6765\u6E90:
502
+
503
+ - **v2 CardKit (schema 2.0)**:\u98DE\u4E66\u5728 raw event \u91CC\u53CC\u53D1\u2014\u2014\`elements\` \u662F v1 \u517C\u5BB9\u964D\u7EA7("\u8BF7\u5347\u7EA7\u81F3\u6700\u65B0\u7248\u672C\u5BA2\u6237\u7AEF"),\`user_dsl\` \u662F\u771F\u6B63\u7684 schema 2.0 DSL\u3002bridge \u4F18\u5148\u53D6 \`user_dsl\`,\u6240\u4EE5\u4F60\u770B\u5230\u7684\u5C31\u662F**\u771F\u5361\u5185\u5BB9**,\u4E0D\u8981\u88AB elements \u7684\u964D\u7EA7\u6587\u6848\u8BEF\u5BFC
504
+ - **\u96F6\u6587\u5B57 v1 \u5361**:\u7EAF\u6309\u94AE / \u56FE\u7247 / \u88C5\u9970\u5361,SDK \u6241\u5E73\u5316\u6293\u4E0D\u5230\u5B57\u65F6,bridge \u628A\u6574\u6BB5 raw JSON \u704C\u8FDB\u6765
505
+
506
+ \u65E0\u8BBA\u54EA\u79CD,\u5757\u91CC\u90FD\u662F\u5361\u7684\u5B8C\u6574 JSON\u3002\u89E3\u6790\u5B83\u6765\u7406\u89E3\u7ED3\u6784(\u6309\u94AE\u3001\u5B57\u6BB5\u3001\u5E03\u5C40)\u3002**\u4E0D\u8981\u7167\u6284 XML \u6807\u7B7E\u5230\u56DE\u590D**\u2014\u2014\u5BF9\u7528\u6237\u4E0D\u53EF\u89C1\u3002
507
+
508
+ ## \u53D1\u4EA4\u4E92\u5361\u7247\uFF08\u6309\u94AE\u3001\u8868\u5355\uFF09\u7684\u56DE\u8C03\u7EA6\u5B9A
509
+
510
+ \u4F60\u60F3\u53D1\u4E00\u5F20\u53EF\u4EA4\u4E92\u7684\u5361\u7247\u8BA9\u7528\u6237\u70B9\u9009\u65F6\uFF1A
511
+
512
+ 1. \u7528 \`lark-cli\` \u628A\u5361\u53D1\u5230 \`bridge_context.chat_id\`\uFF1A
513
+ \`lark-cli im send-card --chat-id <chat_id> --card '<json>'\`
514
+ 2. \u5361\u7247\u7528 CardKit 2.0 schema\uFF08\`schema: "2.0"\`\uFF09\u3002
515
+ 3. **\u5982\u679C\u4F60\u5E0C\u671B\u7528\u6237\u70B9\u6309\u94AE\u540E\u56DE\u8C03\u5230\u4F60\uFF08\u8BA9\u4F60\u5728\u540C\u4E00\u4F1A\u8BDD\u91CC\u7EE7\u7EED\u5904\u7406\uFF09**\uFF1A
516
+ - \u6309\u94AE\u7684 \`value\` \u5BF9\u8C61**\u5FC5\u987B**\u540C\u65F6\u5305\u542B \`__bridge_cb: true\` \u548C \`bridge_token: "<signed token>"\`\u3002
517
+ - \`bridge_token\` \u5FC5\u987B\u7531 bridge-aware \u7684 lark-cli \u56DE\u8C03\u7B7E\u540D\u80FD\u529B\u751F\u6210\uFF1B\u4E0D\u8981\u731C\u6D4B\u3001\u4F2A\u9020\u3001\u590D\u7528\u6216\u624B\u5199 token\u3002
518
+ - \u5982\u679C\u5F53\u524D lark-cli \u4E0D\u80FD\u751F\u6210 \`bridge_token\`\uFF0C\u4E0D\u8981\u53D1\u9001\u56DE\u8C03\u6309\u94AE\u3002\u6539\u6210\u666E\u901A\u5C55\u793A\u5361\uFF0C\u8BA9\u7528\u6237\u7528\u6587\u5B57\u56DE\u590D\u9009\u62E9\u3002
519
+ - \u540C\u65F6\u53EF\u4EE5\u585E\u4EFB\u610F\u5176\u5B83\u5B57\u6BB5\uFF0C\u4F5C\u4E3A\u4F60\u9700\u8981\u5728\u56DE\u8C03\u65F6\u8BB0\u4F4F\u7684\u72B6\u6001\uFF08\u6BD4\u5982 \`choice\`\u3001\`ticket_id\`\uFF09\u3002
520
+ 4. \u7528\u6237\u70B9\u51FB\u540E\uFF0Cbridge \u4F1A\u6821\u9A8C \`bridge_token\`\uFF0C\u7136\u540E\u628A payload\uFF08\u53BB\u6389 \`__bridge_cb\` \u548C \`bridge_token\`\uFF09\u4F5C\u4E3A \`[card-click] {...}\` \u6D88\u606F\u53D1\u56DE\u7ED9\u4F60\uFF1B\u4F60\u7684 session \u81EA\u52A8\u7EED\u4E0A\uFF0C\u80FD\u770B\u5230\u81EA\u5DF1\u4E0A\u8F6E\u53D1\u4E86\u4EC0\u4E48\u5361\u3002
521
+ 5. **\u5982\u679C\u53EA\u662F\u5C55\u793A\u5361\uFF08\u4E0D\u9700\u8981\u56DE\u8C03\uFF09**\uFF0C\u4E0D\u8981\u52A0 \`__bridge_cb\` \u6216 \`bridge_token\`\uFF0C\u5426\u5219\u70B9\u51FB\u4F1A\u88AB\u5F53\u6210\u56DE\u8C03\u5E76\u8981\u6C42\u7B7E\u540D\u3002
522
+
523
+ \u793A\u4F8B button\uFF1A
524
+ \`\`\`json
525
+ {
526
+ "tag": "button",
527
+ "text": { "tag": "plain_text", "content": "\u65B9\u6848 A" },
528
+ "behaviors": [{
529
+ "type": "callback",
530
+ "value": {
531
+ "__bridge_cb": true,
532
+ "bridge_token": "SIGNED_TOKEN_FROM_LARK_CLI",
533
+ "choice": "a"
534
+ }
535
+ }]
536
+ }
537
+ \`\`\`
538
+
539
+ ## lark-cli \u8FD0\u884C\u73AF\u5883
540
+
541
+ bridge \u4F1A\u7ED9\u4F60\u7684\u5B50\u8FDB\u7A0B\u6CE8\u5165\u5F53\u524D\u8FD0\u884C profile \u7684\u73AF\u5883\u53D8\u91CF:
542
+
543
+ - \`LARK_CHANNEL=1\`
544
+ - \`LARK_CHANNEL_HOME\`: \u5F53\u524D bridge \u7684\u914D\u7F6E\u6839\u76EE\u5F55
545
+ - \`LARK_CHANNEL_PROFILE\`: \u5F53\u524D bridge profile
546
+ - \`LARK_CHANNEL_CONFIG\`: \u5F53\u524D profile \u7684 lark-cli source projection
547
+ - \`LARKSUITE_CLI_CONFIG_DIR\`: \u5F53\u524D profile \u7684 lark-cli \u79C1\u6709\u914D\u7F6E\u76EE\u5F55
548
+
549
+ \u56E0\u6B64\u666E\u901A \`lark-cli ...\` \u547D\u4EE4\u4F1A\u81EA\u52A8\u8FDB\u5165\u5F53\u524D lark-channel \u5DE5\u4F5C\u533A,\u8BFB\u53D6\u5F53\u524D profile \u7684\u79C1\u6709 lark-cli \u914D\u7F6E\u3002\u4E0D\u8981 unset \`LARK_CHANNEL\` / \`LARK_CHANNEL_HOME\` / \`LARK_CHANNEL_PROFILE\` / \`LARKSUITE_CLI_CONFIG_DIR\`,\u4E5F\u4E0D\u8981\u7528 \`env -u LARK_CHANNEL\` \u7ED5\u56DE\u672C\u673A\u666E\u901A\u914D\u7F6E\u3002
550
+
551
+ \u5982\u679C \`lark-cli\` \u63D0\u793A \`lark-channel context detected but lark-cli is not bound to it\`,\u4E0D\u8981\u6539\u7528\u666E\u901A profile,\u4E0D\u8981\u76F4\u63A5\u8BFB\u53D6 \`config.json\` \u91CC\u7684\u8D26\u53F7\u6216\u5BC6\u94A5,\u4E5F\u4E0D\u8981\u81EA\u884C\u6267\u884C bind\u3002\u505C\u6B62\u5F53\u524D\u64CD\u4F5C\u5E76\u8BF7\u7528\u6237\u91CD\u542F bridge \u6216\u8FD0\u884C bridge doctor/preflight\u3002
552
+
553
+ \u914D\u7F6E\u6587\u4EF6\u53EF\u80FD\u662F\u591A profile \u7ED3\u6784,\u4E0D\u8981\u5047\u8BBE\u6839\u5C42\u4E00\u5B9A\u6709\u65E7\u7248\u5355 profile \u7684 \`accounts.app\`;\u786E\u5B9E\u9700\u8981\u8BFB\u53D6\u914D\u7F6E\u65F6\u6309\u5F53\u524D profile \u53D6\u503C,\u4E14\u4E0D\u8981\u8F93\u51FA\u5BC6\u94A5\u3002
554
+
555
+ ## \u98DE\u4E66 OAuth \u6388\u6743\uFF08\`lark-cli auth login\`\uFF09
556
+
557
+ \u6388\u6743\u6D41\u7A0B\u8981\u8BA9 \`lark-cli\` \u8FDB\u7A0B\u4E00\u76F4\u6D3B\u5230\u7528\u6237\u5728\u6D4F\u89C8\u5668\u91CC\u70B9\u5B8C\u4E3A\u6B62\u3002bridge \u5728\u4F60\u7684 run \u7ED3\u675F\u4E4B\u540E\u4F1A\u56DE\u6536 agent \u5B50\u8FDB\u7A0B\uFF0C**\u4F60 spawn \u7684\u4EFB\u4F55\u540E\u53F0 bash \u4E5F\u4F1A\u8DDF\u7740\u6B7B**\u2014\u2014\u6240\u4EE5\u6388\u6743\u5FC5\u987B\u7528"\u524D\u53F0\u963B\u585E"\u7684\u65B9\u5F0F\u8DD1\uFF1A
558
+
559
+ 1. **\u4EC5\u5728 p2p \u91CC\u53D1\u8D77\u6388\u6743**\u3002\u4ECE \`bridge_context.chat_type\` \u770B\uFF1A
560
+ - \`chat_type: p2p\` \u2014\u2014 \u6B63\u5E38\u6309\u4E0B\u9762\u6D41\u7A0B\u8D70\u3002
561
+ - \`chat_type: group\`\uFF08\u542B topic \u7FA4\uFF09\u2014\u2014 **\u4E0D\u8981**\u8C03 \`lark-cli auth login\`\u3002device flow \u628A \`verification_url\` \u53D1\u5230\u7FA4\u91CC\uFF0C\u8C01\u5148\u70B9\u8C01\u62FF\u8D70 token\u2014\u2014\u4F1A\u7ED1\u5B9A\u5230\u9519\u7684\u8EAB\u4EFD\u3002\u6B63\u786E\u505A\u6CD5\u662F\u56DE\u590D\u7528\u6237\uFF1A"\u6388\u6743\u8981\u5728\u79C1\u804A\u91CC\u505A\uFF0C\u8BF7\u5355\u72EC\u79C1\u4FE1\u6211\u3002"
562
+ 2. **\u7981\u6B62** \u7528 \`run_in_background: true\` \u8C03 \`lark-cli auth login\`\u2014\u2014\u5B83\u4F1A\u88AB\u4F60 exit \u65F6\u4E00\u8D77\u5E26\u8D70\uFF0C\u7528\u6237\u8FD8\u6CA1\u70B9\u5B8C\u5C31\u4E22\u4E86\u3002
563
+ 3. **\u63A8\u8350\u4E24\u9636\u6BB5\u6D41**\uFF08lark-cli \u5728 \`--no-wait\` \u7684\u8F93\u51FA\u91CC\u4E5F\u4F1A\u544A\u8BC9\u4F60\u8FD9\u5957\uFF09\uFF1A
564
+ - \u5148\u8DD1 \`lark-cli auth login --no-wait --json [--recommend | --domain ... | --scope ...]\`\uFF0C**\u8FD9\u4E00\u6B65\u79D2\u8FD4\u56DE**\uFF0Cstdout \u91CC\u6709 \`verification_url\` \u548C \`device_code\`\u3002
565
+ - \u628A \`verification_url\` **\u539F\u6837**\u7528\u4EE3\u7801\u5757\u53D1\u7ED9\u7528\u6237\uFF08\u4E0D\u8981 Markdown \u94FE\u63A5\u5316\u3001\u4E0D\u8981 URL \u7F16\u7801\uFF09\u3002
566
+ - \u7D27\u63A5\u7740\u540C\u4E00\u8F6E\u91CC\u8DD1 \`lark-cli auth login --device-code <code>\`\uFF0C**\u8FD9\u4E00\u6B65\u524D\u53F0\u963B\u585E**\u76F4\u5230\u7528\u6237\u70B9\u5B8C\u6216 10 \u5206\u949F\u8D85\u65F6\u2014\u2014\u8FD9\u662F\u4F60\u5E94\u8BE5\u7B49\u7684\u5730\u65B9\uFF0C\u4E0D\u8981\u4E22\u5230\u540E\u53F0\u3002
567
+ 4. \`lark-cli auth login --device-code <code>\` \u6210\u529F\u540E,\u7EE7\u7EED\u5728\u540C\u4E00\u4E2A\u5F53\u524D profile \u73AF\u5883\u91CC\u6267\u884C:
568
+ - \`lark-cli config strict-mode off\`
569
+ - \`lark-cli config default-as auto\`
570
+ \u8FD9\u4F1A\u8BA9\u5F53\u524D profile \u540C\u65F6\u53EF\u7528\u5E94\u7528\u8EAB\u4EFD\u548C\u5DF2\u6388\u6743\u7528\u6237\u8EAB\u4EFD\u3002\u4E0D\u8981\u91CD\u65B0 bind,\u4E0D\u8981\u7ED5\u56DE\u672C\u673A\u666E\u901A\u914D\u7F6E\u3002
571
+ \u8FD9\u662F\u5185\u90E8\u987A\u5E8F\u6267\u884C\u8EAB\u4EFD\u7B56\u7565\u6536\u655B,\u4E0D\u8981\u628A strict-mode/default-as \u8FD9\u7C7B\u5185\u90E8\u914D\u7F6E\u547D\u4EE4\u5C55\u793A\u7ED9\u7528\u6237,\u4E5F\u4E0D\u8981\u8BA9\u7528\u6237\u5224\u65AD\u8FD9\u4E9B\u547D\u4EE4\u3002\u9762\u5411\u7528\u6237\u53EA\u8BF4\uFF1A"\u5F53\u524D profile \u8FD8\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u8EAB\u4EFD\u6388\u6743,\u8BF7\u6253\u5F00\u4E0B\u9762\u94FE\u63A5\u5B8C\u6210\u6388\u6743;\u6388\u6743\u5B8C\u6210\u540E\u6211\u4F1A\u7EE7\u7EED\u5904\u7406\u3002"
572
+ 5. \u5982\u679C\u5F53\u524D profile \u5DF2\u7ECF\u6709\u7528\u6237\u6388\u6743,\u4F46 \`--as user\` \u4ECD\u88AB strict-mode/default-as \u62D2\u7EDD,\u4E0D\u8981\u5411\u7528\u6237\u5C55\u793A\u5185\u90E8\u547D\u4EE4;\u5728\u7528\u6237\u660E\u786E\u8981\u6C42\u4F7F\u7528\u7528\u6237\u8EAB\u4EFD\u65F6,\u5185\u90E8\u987A\u5E8F\u6267\u884C\u8EAB\u4EFD\u7B56\u7565\u6536\u655B\u540E\u91CD\u8BD5\u539F\u547D\u4EE4\u3002
573
+ 6. \u4F60\u524D\u53F0\u963B\u585E\u671F\u95F4\uFF0C\u7528\u6237\u53D1\u7684\u65B0\u6D88\u606F bridge \u4F1A\u81EA\u52A8\u6392\u961F\uFF0C**\u4E0D\u4F1A\u6253\u65AD\u4F60**\uFF1B\u7B49\u4F60 tool_result \u4E00\u56DE\u6765\uFF0C\u4E0B\u4E00\u6279\u6D88\u606F\u518D\u8FDB\u6765\u3002\u6240\u4EE5\u653E\u5FC3\u963B\u585E\u3002
574
+ 7. \u5982\u679C\u7528\u6237\u4E2D\u9014\u60F3\u53D6\u6D88\uFF0C\u4ED6\u4EEC\u4F1A\u53D1 \`/stop\`\u2014\u2014\u90A3\u65F6\u88AB kill \u662F\u9884\u671F\u884C\u4E3A\uFF0C\u4E0D\u7528\u515C\u5E95\u3002
575
+ `;
576
+ function buildBridgeSystemPrompt(identity) {
577
+ if (!identity?.openId) return BRIDGE_SYSTEM_PROMPT;
578
+ const nameSuffix = identity.name ? `\uFF0C\u540D\u5B57\u662F\u300C${identity.name}\u300D` : "";
579
+ return `${BRIDGE_SYSTEM_PROMPT}
580
+ ## \u4F60\u7684\u8EAB\u4EFD
581
+
582
+ \u4F60\u7684 open_id \u662F \`${identity.openId}\`${nameSuffix}\u3002\u6D88\u606F\u5185\u5BB9\u6216 mentions \u91CC\u51FA\u73B0\u8FD9\u4E2A open_id \u90FD\u662F\u6307\u4F60\u81EA\u5DF1\u3002
583
+ `;
584
+ }
585
+ function prefixBridgeSystemPrompt(prompt, identity) {
586
+ return `${buildBridgeSystemPrompt(identity)}
587
+
588
+ ## user_message
589
+
590
+ ${prompt}`;
591
+ }
592
+
593
+ // src/bridge/agent/lark-channel-env.ts
594
+ import { join as join2 } from "path";
595
+ function buildLarkChannelEnv(context) {
596
+ const env = {
597
+ LARK_CHANNEL: "1"
598
+ };
599
+ const profile = nonEmpty(context?.profile);
600
+ if (profile) env.LARK_CHANNEL_PROFILE = profile;
601
+ const rootDir = nonEmpty(context?.rootDir);
602
+ if (rootDir) env.LARK_CHANNEL_HOME = rootDir;
603
+ const configPath = nonEmpty(context?.larkCliSourceConfigFile) ?? nonEmpty(context?.configPath) ?? (rootDir ? join2(rootDir, "config.json") : void 0);
604
+ if (configPath) env.LARK_CHANNEL_CONFIG = configPath;
605
+ const larkCliConfigDir = nonEmpty(context?.larkCliConfigDir);
606
+ if (larkCliConfigDir) env.LARKSUITE_CLI_CONFIG_DIR = larkCliConfigDir;
607
+ return env;
608
+ }
609
+ function nonEmpty(value) {
610
+ const trimmed = value?.trim();
611
+ return trimmed ? value : void 0;
612
+ }
613
+
614
+ // src/bridge/agent/preflight.ts
615
+ var AgentPreflightError = class extends Error {
616
+ diagnostic;
617
+ constructor(diagnostic, message) {
618
+ super(message ?? summaryForDiagnostic(diagnostic));
619
+ this.name = "AgentPreflightError";
620
+ this.diagnostic = diagnostic;
621
+ }
622
+ };
623
+ async function checkAgentAvailability(input) {
624
+ try {
625
+ return { ok: true, version: await checkAgentVersion(input) };
626
+ } catch (err) {
627
+ if (err instanceof AgentPreflightError) {
628
+ return { ok: false, error: err, diagnostic: err.diagnostic };
629
+ }
630
+ throw err;
631
+ }
632
+ }
633
+ async function checkAgentVersion(input) {
634
+ const args = input.args ?? ["--version"];
635
+ const timeoutMs = input.timeoutMs ?? 5e3;
636
+ const executable = input.realpath ?? input.binaryPath;
637
+ return new Promise((resolve, reject) => {
638
+ let settled = false;
639
+ let stdout = "";
640
+ let stderr = "";
641
+ let timer;
642
+ const finish = (fn) => {
643
+ if (settled) return;
644
+ settled = true;
645
+ if (timer) clearTimeout(timer);
646
+ fn();
647
+ };
648
+ const base = () => ({
649
+ agentId: input.agentId,
650
+ agentName: input.agentName,
651
+ command: input.command,
652
+ binaryPath: input.binaryPath,
653
+ ...input.realpath ? { realpath: input.realpath } : {},
654
+ args,
655
+ stdoutExcerpt: excerpt(stdout),
656
+ stderrExcerpt: excerpt(stderr)
657
+ });
658
+ const child = (() => {
659
+ try {
660
+ return spawnProcess(executable, [...args], {
661
+ stdio: ["ignore", "pipe", "pipe"]
662
+ });
663
+ } catch (err) {
664
+ finish(
665
+ () => reject(
666
+ new AgentPreflightError({
667
+ ...base(),
668
+ code: codeForSpawnError(err),
669
+ errno: err.code
670
+ })
671
+ )
672
+ );
673
+ return void 0;
674
+ }
675
+ })();
676
+ if (!child) return;
677
+ timer = setTimeout(() => {
678
+ child.kill("SIGTERM");
679
+ finish(
680
+ () => reject(
681
+ new AgentPreflightError({
682
+ ...base(),
683
+ code: "agent-version-check-timeout",
684
+ timeoutMs
685
+ })
686
+ )
687
+ );
688
+ }, timeoutMs);
689
+ child.stdout?.on("data", (chunk) => {
690
+ stdout += chunk.toString("utf8");
691
+ });
692
+ child.stderr?.on("data", (chunk) => {
693
+ stderr += chunk.toString("utf8");
694
+ });
695
+ child.once("error", (err) => {
696
+ finish(
697
+ () => reject(
698
+ new AgentPreflightError({
699
+ ...base(),
700
+ code: codeForSpawnError(err),
701
+ errno: err.code
702
+ })
703
+ )
704
+ );
705
+ });
706
+ child.once("exit", (exitCode, signal) => {
707
+ finish(() => {
708
+ if (signal) {
709
+ reject(
710
+ new AgentPreflightError({
711
+ ...base(),
712
+ code: "agent-version-check-signaled",
713
+ exitCode,
714
+ signal
715
+ })
716
+ );
717
+ return;
718
+ }
719
+ if (exitCode !== 0) {
720
+ reject(
721
+ new AgentPreflightError({
722
+ ...base(),
723
+ code: "agent-version-check-nonzero-exit",
724
+ exitCode,
725
+ signal
726
+ })
727
+ );
728
+ return;
729
+ }
730
+ const version = (stdout.trim() || stderr.trim()).split("\n")[0]?.trim();
731
+ if (!version) {
732
+ reject(
733
+ new AgentPreflightError({
734
+ ...base(),
735
+ code: "agent-version-check-empty-output",
736
+ exitCode,
737
+ signal
738
+ })
739
+ );
740
+ return;
741
+ }
742
+ resolve(version);
743
+ });
744
+ });
745
+ });
746
+ }
747
+ function codeForSpawnError(err) {
748
+ if (err.code === "ENOENT") return "agent-binary-not-found";
749
+ if (err.code === "EACCES" || err.code === "EPERM") return "agent-binary-not-executable";
750
+ return "agent-version-check-spawn-failed";
751
+ }
752
+ function summaryForDiagnostic(diagnostic) {
753
+ return `${diagnostic.agentName} preflight failed: ${diagnostic.code}`;
754
+ }
755
+ function excerpt(value) {
756
+ const trimmed = value.trim();
757
+ return trimmed ? trimmed.slice(0, 500) : void 0;
758
+ }
759
+
760
+ // src/bridge/agent/types.ts
761
+ var CLAUDE_DEFAULT_PERMISSION_MODE = "bypassPermissions";
762
+
763
+ // src/bridge/agent/claude/stream-json.ts
764
+ function* translateEvent(raw) {
765
+ if (!raw || typeof raw !== "object") return;
766
+ const evt = raw;
767
+ if (evt.type === "system" && evt.subtype === "init") {
768
+ yield {
769
+ type: "system",
770
+ sessionId: evt.session_id,
771
+ cwd: evt.cwd,
772
+ model: evt.model
773
+ };
774
+ return;
775
+ }
776
+ if (evt.type === "assistant" && evt.message?.content) {
777
+ for (const block of evt.message.content) {
778
+ if (block.type === "text" && typeof block.text === "string" && block.text) {
779
+ yield { type: "text", delta: block.text };
780
+ } else if (block.type === "thinking" && typeof block.thinking === "string" && block.thinking) {
781
+ yield { type: "thinking", delta: block.thinking };
782
+ } else if (block.type === "tool_use" && block.id && block.name) {
783
+ yield { type: "tool_use", id: block.id, name: block.name, input: block.input };
784
+ }
785
+ }
786
+ return;
787
+ }
788
+ if (evt.type === "user" && evt.message?.content) {
789
+ for (const block of evt.message.content) {
790
+ if (block.type === "tool_result" && block.tool_use_id) {
791
+ const output = typeof block.content === "string" ? block.content : JSON.stringify(block.content);
792
+ yield {
793
+ type: "tool_result",
794
+ id: block.tool_use_id,
795
+ output,
796
+ isError: block.is_error === true
797
+ };
798
+ }
799
+ }
800
+ return;
801
+ }
802
+ if (evt.type === "result") {
803
+ if (evt.usage) {
804
+ yield {
805
+ type: "usage",
806
+ inputTokens: evt.usage.input_tokens,
807
+ outputTokens: evt.usage.output_tokens,
808
+ cachedInputTokens: evt.usage.cache_read_input_tokens,
809
+ costUsd: evt.total_cost_usd
810
+ };
811
+ }
812
+ yield { type: "done", sessionId: evt.session_id, terminationReason: "normal" };
813
+ }
814
+ }
815
+
816
+ // src/bridge/agent/claude/adapter.ts
817
+ var ClaudeAdapter = class {
818
+ id = "claude";
819
+ displayName = "Claude Code";
820
+ binary;
821
+ larkChannel;
822
+ botIdentity;
823
+ constructor(opts = {}) {
824
+ this.binary = opts.binary ?? "claude";
825
+ this.larkChannel = opts.larkChannel;
826
+ }
827
+ setBotIdentity(identity) {
828
+ this.botIdentity = identity;
829
+ }
830
+ async isAvailable() {
831
+ return (await this.checkAvailability()).ok;
832
+ }
833
+ async checkAvailability() {
834
+ return checkAgentAvailability({
835
+ agentId: "claude",
836
+ agentName: "Claude Code",
837
+ command: this.binary,
838
+ binaryPath: this.binary
839
+ });
840
+ }
841
+ run(opts) {
842
+ if (!opts.cwd) {
843
+ throw new Error("cwd is required for ClaudeAdapter.run");
844
+ }
845
+ const systemPromptFile = writeSystemPromptFile(buildBridgeSystemPrompt(this.botIdentity));
846
+ const args = [
847
+ "-p",
848
+ "--output-format",
849
+ "stream-json",
850
+ "--verbose",
851
+ "--permission-mode",
852
+ opts.permissionMode ?? CLAUDE_DEFAULT_PERMISSION_MODE,
853
+ "--append-system-prompt-file",
854
+ systemPromptFile.path
855
+ ];
856
+ if (opts.sessionId) args.push("--resume", opts.sessionId);
857
+ if (opts.model) args.push("--model", opts.model);
858
+ const child = spawnProcess(this.binary, args, {
859
+ cwd: opts.cwd,
860
+ env: mergeProcessEnv(process.env, buildLarkChannelEnv(this.larkChannel)),
861
+ stdio: ["pipe", "pipe", "pipe"]
862
+ });
863
+ log.info("agent", "spawn", {
864
+ pid: child.pid ?? null,
865
+ cwd: opts.cwd ?? process.cwd(),
866
+ hasSession: Boolean(opts.sessionId),
867
+ promptChars: opts.prompt.length,
868
+ model: opts.model
869
+ });
870
+ const stderrChunks = [];
871
+ let runtimeError = null;
872
+ let stderrBuffer = "";
873
+ child.stderr.on("data", (chunk) => {
874
+ stderrChunks.push(chunk);
875
+ stderrBuffer += chunk.toString("utf8");
876
+ let nl = stderrBuffer.indexOf("\n");
877
+ while (nl !== -1) {
878
+ const line = stderrBuffer.slice(0, nl);
879
+ stderrBuffer = stderrBuffer.slice(nl + 1);
880
+ if (line.trim()) log.warn("agent", "stderr", { line });
881
+ if (isWindowsCommandNotFoundLine(line)) {
882
+ runtimeError = new Error(`failed to spawn claude: ${line.trim()}`);
883
+ child.stdout.destroy();
884
+ child.kill();
885
+ }
886
+ nl = stderrBuffer.indexOf("\n");
887
+ }
888
+ });
889
+ child.on("error", (err) => {
890
+ runtimeError = err;
891
+ systemPromptFile.cleanup();
892
+ });
893
+ child.on("exit", (code, signal) => {
894
+ log.info("agent", "exit", { pid: child.pid ?? null, code, signal });
895
+ systemPromptFile.cleanup();
896
+ });
897
+ child.stdin.on("error", (err) => {
898
+ log.warn("agent", "stdin-error", { message: err.message });
899
+ });
900
+ child.stdin.end(opts.prompt, "utf8");
901
+ const stopGraceMs = opts.stopGraceMs ?? 5e3;
902
+ return {
903
+ runId: opts.runId,
904
+ events: createEventStream(child, stderrChunks, () => runtimeError),
905
+ async stop() {
906
+ if (child.exitCode !== null || child.signalCode !== null) return;
907
+ log.info("agent", "stop-sigterm", { pid: child.pid ?? null, graceMs: stopGraceMs });
908
+ child.kill("SIGTERM");
909
+ await new Promise((resolve) => {
910
+ const timer = setTimeout(() => {
911
+ if (child.exitCode === null && child.signalCode === null) {
912
+ log.warn("agent", "stop-sigkill", {
913
+ pid: child.pid ?? null,
914
+ graceMs: stopGraceMs,
915
+ reason: "grace-period-expired"
916
+ });
917
+ child.kill("SIGKILL");
918
+ }
919
+ resolve();
920
+ }, stopGraceMs);
921
+ child.once("exit", () => {
922
+ clearTimeout(timer);
923
+ resolve();
924
+ });
925
+ });
926
+ },
927
+ waitForExit(timeoutMs) {
928
+ if (child.exitCode !== null || child.signalCode !== null) {
929
+ return Promise.resolve(true);
930
+ }
931
+ return new Promise((resolve) => {
932
+ const onExit = () => {
933
+ clearTimeout(timer);
934
+ resolve(true);
935
+ };
936
+ const timer = setTimeout(() => {
937
+ child.removeListener("exit", onExit);
938
+ resolve(false);
939
+ }, timeoutMs);
940
+ child.once("exit", onExit);
941
+ });
942
+ }
943
+ };
944
+ }
945
+ };
946
+ async function* createEventStream(child, stderrChunks, getError) {
947
+ if (!child.pid) {
948
+ const err = getError();
949
+ yield {
950
+ type: "error",
951
+ message: err ? `failed to spawn claude: ${err.message}` : "spawn returned no pid",
952
+ terminationReason: "failed"
953
+ };
954
+ return;
955
+ }
956
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
957
+ let sawStdout = false;
958
+ let silentExitTimer;
959
+ const closeSilentStdout = () => {
960
+ silentExitTimer = setTimeout(() => {
961
+ if (!sawStdout && !child.stdout.readableEnded) child.stdout.destroy();
962
+ }, 50);
963
+ };
964
+ child.once("exit", closeSilentStdout);
965
+ try {
966
+ for await (const line of rl) {
967
+ sawStdout = true;
968
+ const trimmed = line.trim();
969
+ if (!trimmed) continue;
970
+ let parsed;
971
+ try {
972
+ parsed = JSON.parse(trimmed);
973
+ } catch {
974
+ continue;
975
+ }
976
+ yield* translateEvent(parsed);
977
+ }
978
+ } finally {
979
+ if (silentExitTimer) clearTimeout(silentExitTimer);
980
+ child.removeListener("exit", closeSilentStdout);
981
+ rl.close();
982
+ }
983
+ const earlyRuntimeError = getError();
984
+ if (earlyRuntimeError && child.exitCode === null && child.signalCode === null) {
985
+ yield {
986
+ type: "error",
987
+ message: `claude runtime error: ${earlyRuntimeError.message}`,
988
+ terminationReason: "failed"
989
+ };
990
+ return;
991
+ }
992
+ const exitCode = await new Promise((resolve) => {
993
+ if (child.exitCode !== null || child.signalCode !== null) {
994
+ resolve(child.exitCode);
995
+ } else {
996
+ child.once("exit", (code) => resolve(code));
997
+ }
998
+ });
999
+ const runtimeError = getError();
1000
+ if (exitCode !== 0 && exitCode !== null) {
1001
+ const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
1002
+ const detail = stderr ? `: ${stderr.slice(0, 500)}` : "";
1003
+ yield {
1004
+ type: "error",
1005
+ message: `claude exited with code ${exitCode}${detail}`,
1006
+ terminationReason: "failed"
1007
+ };
1008
+ } else if (runtimeError) {
1009
+ yield {
1010
+ type: "error",
1011
+ message: `claude runtime error: ${runtimeError.message}`,
1012
+ terminationReason: "failed"
1013
+ };
1014
+ }
1015
+ }
1016
+ function writeSystemPromptFile(content) {
1017
+ const dir = mkdtempSync(join3(tmpdir(), "lark-claude-"));
1018
+ const path = join3(dir, "append-system-prompt.md");
1019
+ writeFileSync(path, content, "utf8");
1020
+ return {
1021
+ path,
1022
+ cleanup: () => {
1023
+ try {
1024
+ rmSync(dir, { recursive: true, force: true });
1025
+ } catch {
1026
+ }
1027
+ }
1028
+ };
1029
+ }
1030
+ function isWindowsCommandNotFoundLine(line) {
1031
+ return process.platform === "win32" && /is not recognized as an internal or external command|operable program or batch file/i.test(line);
1032
+ }
1033
+
1034
+ // src/bridge/agent/codex/adapter.ts
1035
+ import { createInterface as createInterface2 } from "readline";
1036
+ import { join as join4 } from "path";
1037
+
1038
+ // src/bridge/runtime/errors.ts
1039
+ var SpawnFailed = class extends Error {
1040
+ cause;
1041
+ code;
1042
+ diagnostic;
1043
+ constructor(message, cause, code = "agent-spawn-failed", diagnostic) {
1044
+ super(message);
1045
+ this.name = "SpawnFailed";
1046
+ this.cause = cause;
1047
+ this.code = code;
1048
+ this.diagnostic = diagnostic;
1049
+ }
1050
+ };
1051
+
1052
+ // src/bridge/agent/codex/argv.ts
1053
+ function buildCodexArgs(input) {
1054
+ if (input.sandbox !== "read-only" && input.sandbox !== "workspace-write" && input.sandbox !== "danger-full-access") {
1055
+ throw new Error(`unsafe sandbox mode: ${input.sandbox}`);
1056
+ }
1057
+ const globalFlags = [
1058
+ "--sandbox",
1059
+ input.sandbox,
1060
+ ...input.model ? ["--model", input.model] : [],
1061
+ "-c",
1062
+ 'approval_policy="never"',
1063
+ "-c",
1064
+ 'shell_environment_policy.inherit="all"',
1065
+ ...input.ignoreUserConfig === true ? ["--ignore-user-config"] : [],
1066
+ ...input.ignoreRules === false ? [] : ["--ignore-rules"],
1067
+ "--skip-git-repo-check",
1068
+ "-C",
1069
+ input.cwd
1070
+ ];
1071
+ const imageFlags = (input.images ?? []).flatMap((path) => ["--image", path]);
1072
+ if (input.threadId) {
1073
+ return [
1074
+ "exec",
1075
+ ...globalFlags,
1076
+ "resume",
1077
+ "--json",
1078
+ ...imageFlags,
1079
+ input.threadId,
1080
+ "-"
1081
+ ];
1082
+ }
1083
+ return [
1084
+ "exec",
1085
+ "--json",
1086
+ ...globalFlags,
1087
+ ...imageFlags,
1088
+ ...imageFlags.length > 0 ? ["--"] : [],
1089
+ "-"
1090
+ ];
1091
+ }
1092
+
1093
+ // src/bridge/agent/codex/jsonl.ts
1094
+ var CodexJsonlTranslator = class {
1095
+ threadId;
1096
+ terminal = false;
1097
+ lastNonTerminalError;
1098
+ pendingAgentMessage;
1099
+ startedItems = /* @__PURE__ */ new Set();
1100
+ drift = {
1101
+ unknownEvents: 0,
1102
+ anomalies: 0
1103
+ };
1104
+ translate(raw) {
1105
+ if (this.terminal) return [];
1106
+ if (!isRecord(raw) || typeof raw.type !== "string") {
1107
+ this.drift.anomalies++;
1108
+ return [];
1109
+ }
1110
+ switch (raw.type) {
1111
+ case "thread.started":
1112
+ return this.translateThreadStarted(raw);
1113
+ case "turn.started":
1114
+ return [];
1115
+ case "item.started":
1116
+ return this.prependPendingText(this.translateItemStarted(raw));
1117
+ case "item.completed":
1118
+ return this.translateItemCompleted(raw);
1119
+ case "agent_message":
1120
+ return this.translateAgentMessage(raw);
1121
+ case "turn.completed":
1122
+ return this.translateTurnCompleted(raw);
1123
+ case "turn.failed":
1124
+ return this.prependPendingText(
1125
+ this.translateTerminalError(raw, "codex turn failed")
1126
+ );
1127
+ case "error":
1128
+ return this.translateNonTerminalError(raw, "codex error");
1129
+ default:
1130
+ this.drift.unknownEvents++;
1131
+ log.warn("jsonl", "unknown_event", { eventType: raw.type });
1132
+ return [];
1133
+ }
1134
+ }
1135
+ finish(reason = "failed") {
1136
+ if (this.terminal) return [];
1137
+ this.terminal = true;
1138
+ if (reason === "failed") {
1139
+ const detail = this.lastNonTerminalError ? `: ${this.lastNonTerminalError}` : "";
1140
+ return this.prependPendingText([
1141
+ {
1142
+ type: "error",
1143
+ message: truncate(`codex stream ended before a terminal event${detail}`, 4096),
1144
+ terminationReason: "failed"
1145
+ }
1146
+ ]);
1147
+ }
1148
+ return this.prependPendingText([
1149
+ { type: "done", threadId: this.threadId, terminationReason: reason }
1150
+ ]);
1151
+ }
1152
+ fail(message) {
1153
+ if (this.terminal) return [];
1154
+ this.terminal = true;
1155
+ return this.prependPendingText([
1156
+ { type: "error", message: truncate(message, 4096), terminationReason: "failed" }
1157
+ ]);
1158
+ }
1159
+ protocolDrift() {
1160
+ return { ...this.drift };
1161
+ }
1162
+ terminalEmitted() {
1163
+ return this.terminal;
1164
+ }
1165
+ translateThreadStarted(raw) {
1166
+ const threadId = stringValue(raw.thread_id ?? raw.threadId);
1167
+ if (!threadId) {
1168
+ this.drift.anomalies++;
1169
+ return [];
1170
+ }
1171
+ this.threadId = threadId;
1172
+ return [{ type: "system", threadId }];
1173
+ }
1174
+ translateItemStarted(raw) {
1175
+ const item = recordValue(raw.item);
1176
+ if (!item || item.type !== "command_execution") return [];
1177
+ const id = stringValue(item.id);
1178
+ if (!id) {
1179
+ this.drift.anomalies++;
1180
+ return [];
1181
+ }
1182
+ this.startedItems.add(id);
1183
+ return [
1184
+ {
1185
+ type: "tool_use",
1186
+ id,
1187
+ name: "command_execution",
1188
+ input: {
1189
+ command: stringValue(item.command) ?? ""
1190
+ }
1191
+ }
1192
+ ];
1193
+ }
1194
+ translateItemCompleted(raw) {
1195
+ const item = recordValue(raw.item);
1196
+ if (!item) return [];
1197
+ if (item.type === "agent_message") {
1198
+ const message = stringValue(item.text ?? item.message);
1199
+ return message ? this.queueAgentMessage(message) : [];
1200
+ }
1201
+ if (item.type !== "command_execution") return [];
1202
+ const id = stringValue(item.id);
1203
+ if (!id) {
1204
+ this.drift.anomalies++;
1205
+ return [];
1206
+ }
1207
+ if (!this.startedItems.has(id)) {
1208
+ this.drift.anomalies++;
1209
+ }
1210
+ this.startedItems.delete(id);
1211
+ const exitCode = numberValue(item.exit_code);
1212
+ return this.prependPendingText([
1213
+ {
1214
+ type: "tool_result",
1215
+ id,
1216
+ output: stringValue(item.output ?? item.aggregated_output ?? item.stdout) ?? "",
1217
+ isError: exitCode !== void 0 && exitCode !== 0
1218
+ }
1219
+ ]);
1220
+ }
1221
+ translateAgentMessage(raw) {
1222
+ const message = stringValue(raw.message ?? raw.text);
1223
+ if (!message) return [];
1224
+ return this.queueAgentMessage(message);
1225
+ }
1226
+ translateTurnCompleted(raw) {
1227
+ this.terminal = true;
1228
+ const events = [];
1229
+ if (this.pendingAgentMessage) {
1230
+ events.push({ type: "final_text", content: this.pendingAgentMessage });
1231
+ this.pendingAgentMessage = void 0;
1232
+ }
1233
+ const usage = recordValue(raw.usage);
1234
+ if (usage) {
1235
+ events.push({
1236
+ type: "usage",
1237
+ inputTokens: numberValue(usage.input_tokens ?? usage.inputTokens),
1238
+ outputTokens: numberValue(usage.output_tokens ?? usage.outputTokens),
1239
+ cachedInputTokens: numberValue(usage.cached_input_tokens ?? usage.cachedInputTokens),
1240
+ reasoningOutputTokens: numberValue(
1241
+ usage.reasoning_output_tokens ?? usage.reasoningOutputTokens
1242
+ )
1243
+ });
1244
+ }
1245
+ events.push({ type: "done", threadId: this.threadId, terminationReason: "normal" });
1246
+ return events;
1247
+ }
1248
+ queueAgentMessage(message) {
1249
+ if (message === this.pendingAgentMessage) return [];
1250
+ const events = this.pendingAgentMessage ? [{ type: "text", delta: this.pendingAgentMessage }] : [];
1251
+ this.pendingAgentMessage = message;
1252
+ return events;
1253
+ }
1254
+ prependPendingText(events) {
1255
+ if (events.length === 0 || !this.pendingAgentMessage) return events;
1256
+ const pending = this.pendingAgentMessage;
1257
+ this.pendingAgentMessage = void 0;
1258
+ return [{ type: "text", delta: pending }, ...events];
1259
+ }
1260
+ translateTerminalError(raw, fallback) {
1261
+ this.terminal = true;
1262
+ const message = errorMessage(raw, fallback);
1263
+ return [
1264
+ {
1265
+ type: "error",
1266
+ message: truncate(message, 4096),
1267
+ terminationReason: "failed"
1268
+ }
1269
+ ];
1270
+ }
1271
+ translateNonTerminalError(raw, fallback) {
1272
+ const message = errorMessage(raw, fallback);
1273
+ this.lastNonTerminalError = message;
1274
+ log.warn("jsonl", "error_event", { message: truncate(message, 500) });
1275
+ return [];
1276
+ }
1277
+ };
1278
+ function isRecord(value) {
1279
+ return typeof value === "object" && value !== null;
1280
+ }
1281
+ function recordValue(value) {
1282
+ return isRecord(value) ? value : void 0;
1283
+ }
1284
+ function stringValue(value) {
1285
+ return typeof value === "string" ? value : void 0;
1286
+ }
1287
+ function numberValue(value) {
1288
+ return typeof value === "number" ? value : void 0;
1289
+ }
1290
+ function errorMessage(raw, fallback) {
1291
+ const nested = recordValue(raw.error);
1292
+ return stringValue(raw.message) ?? stringValue(nested?.message) ?? stringValue(raw.error) ?? fallback;
1293
+ }
1294
+ function truncate(value, max) {
1295
+ return value.length > max ? value.slice(0, max) : value;
1296
+ }
1297
+
1298
+ // src/bridge/agent/codex/adapter.ts
1299
+ var CodexAdapter = class {
1300
+ id = "codex";
1301
+ displayName = "Codex CLI";
1302
+ binary;
1303
+ profileStateDir;
1304
+ codexHome;
1305
+ inheritCodexHome;
1306
+ ignoreUserConfig;
1307
+ ignoreRules;
1308
+ sandbox;
1309
+ defaultStopGraceMs;
1310
+ larkChannel;
1311
+ botIdentity;
1312
+ constructor(opts) {
1313
+ this.binary = opts.binary;
1314
+ this.profileStateDir = opts.profileStateDir;
1315
+ this.codexHome = opts.codexHome;
1316
+ this.inheritCodexHome = opts.inheritCodexHome !== false;
1317
+ this.ignoreUserConfig = opts.ignoreUserConfig === true;
1318
+ this.ignoreRules = opts.ignoreRules !== false;
1319
+ this.sandbox = opts.sandbox ?? "danger-full-access";
1320
+ this.defaultStopGraceMs = opts.stopGraceMs ?? 5e3;
1321
+ this.larkChannel = opts.larkChannel;
1322
+ }
1323
+ setBotIdentity(identity) {
1324
+ this.botIdentity = identity;
1325
+ }
1326
+ async isAvailable() {
1327
+ return (await this.checkAvailability()).ok;
1328
+ }
1329
+ async checkAvailability() {
1330
+ return checkAgentAvailability({
1331
+ agentId: "codex",
1332
+ agentName: "Codex CLI",
1333
+ command: this.binary,
1334
+ binaryPath: this.binary
1335
+ });
1336
+ }
1337
+ async prepareRun() {
1338
+ const availability = await this.checkAvailability();
1339
+ if (!availability.ok) {
1340
+ throw new SpawnFailed(
1341
+ "codex binary check failed",
1342
+ availability.error,
1343
+ availability.diagnostic.code,
1344
+ availability.diagnostic
1345
+ );
1346
+ }
1347
+ }
1348
+ run(opts) {
1349
+ if (!opts.cwd) {
1350
+ throw new Error("cwd is required for CodexAdapter.run");
1351
+ }
1352
+ const args = buildCodexArgs({
1353
+ cwd: opts.cwd,
1354
+ sandbox: opts.sandbox ?? this.sandbox,
1355
+ threadId: opts.threadId,
1356
+ images: opts.images,
1357
+ ignoreUserConfig: this.ignoreUserConfig,
1358
+ ignoreRules: this.ignoreRules,
1359
+ model: opts.model
1360
+ });
1361
+ const envOverrides = buildLarkChannelEnv(this.larkChannel);
1362
+ if (this.codexHome) {
1363
+ envOverrides.CODEX_HOME = this.codexHome;
1364
+ } else if (!this.inheritCodexHome) {
1365
+ envOverrides.CODEX_HOME = join4(this.profileStateDir, "codex-home");
1366
+ }
1367
+ const child = spawnProcess(this.binary, args, {
1368
+ cwd: opts.cwd,
1369
+ env: mergeProcessEnv(process.env, envOverrides),
1370
+ stdio: ["pipe", "pipe", "pipe"]
1371
+ });
1372
+ log.info("agent", "spawn", {
1373
+ pid: child.pid ?? null,
1374
+ cwd: opts.cwd,
1375
+ hasThread: Boolean(opts.threadId),
1376
+ promptChars: opts.prompt.length,
1377
+ images: opts.images?.length ?? 0,
1378
+ model: opts.model
1379
+ });
1380
+ const stderrChunks = [];
1381
+ let runtimeError = null;
1382
+ let stderrBuffer = "";
1383
+ child.stderr.on("data", (chunk) => {
1384
+ stderrChunks.push(chunk);
1385
+ stderrBuffer += chunk.toString("utf8");
1386
+ let nl = stderrBuffer.indexOf("\n");
1387
+ while (nl !== -1) {
1388
+ const line = stderrBuffer.slice(0, nl);
1389
+ stderrBuffer = stderrBuffer.slice(nl + 1);
1390
+ if (line.trim()) log.warn("agent", "stderr", { line });
1391
+ if (isWindowsCommandNotFoundLine2(line)) {
1392
+ runtimeError = new Error(`failed to spawn codex: ${line.trim()}`);
1393
+ child.stdout.destroy();
1394
+ child.kill();
1395
+ }
1396
+ nl = stderrBuffer.indexOf("\n");
1397
+ }
1398
+ });
1399
+ let stopReason;
1400
+ child.on("error", (err) => {
1401
+ runtimeError = err;
1402
+ });
1403
+ child.on("exit", (code, signal) => {
1404
+ log.info("agent", "exit", { pid: child.pid ?? null, code, signal });
1405
+ });
1406
+ child.stdin.on("error", (err) => {
1407
+ log.warn("agent", "stdin-error", { message: err.message });
1408
+ });
1409
+ child.stdin.end(prefixBridgeSystemPrompt(opts.prompt, this.botIdentity), "utf8");
1410
+ const stopGraceMs = opts.stopGraceMs ?? this.defaultStopGraceMs;
1411
+ return {
1412
+ runId: opts.runId,
1413
+ events: createEventStream2(child, stderrChunks, () => runtimeError, () => stopReason),
1414
+ async stop() {
1415
+ if (child.exitCode !== null || child.signalCode !== null) return;
1416
+ stopReason = "interrupted";
1417
+ log.info("agent", "stop-sigterm", { pid: child.pid ?? null, graceMs: stopGraceMs });
1418
+ child.kill("SIGTERM");
1419
+ await new Promise((resolve) => {
1420
+ const timer = setTimeout(() => {
1421
+ if (child.exitCode === null && child.signalCode === null) {
1422
+ log.warn("agent", "stop-sigkill", {
1423
+ pid: child.pid ?? null,
1424
+ graceMs: stopGraceMs,
1425
+ reason: "grace-period-expired"
1426
+ });
1427
+ child.kill("SIGKILL");
1428
+ }
1429
+ resolve();
1430
+ }, stopGraceMs);
1431
+ child.once("exit", () => {
1432
+ clearTimeout(timer);
1433
+ resolve();
1434
+ });
1435
+ });
1436
+ },
1437
+ waitForExit(timeoutMs) {
1438
+ if (child.exitCode !== null || child.signalCode !== null) {
1439
+ return Promise.resolve(true);
1440
+ }
1441
+ return new Promise((resolve) => {
1442
+ const onExit = () => {
1443
+ clearTimeout(timer);
1444
+ resolve(true);
1445
+ };
1446
+ const timer = setTimeout(() => {
1447
+ child.removeListener("exit", onExit);
1448
+ resolve(false);
1449
+ }, timeoutMs);
1450
+ child.once("exit", onExit);
1451
+ });
1452
+ }
1453
+ };
1454
+ }
1455
+ };
1456
+ async function* createEventStream2(child, stderrChunks, getError, getStopReason) {
1457
+ const translator = new CodexJsonlTranslator();
1458
+ if (!child.pid) {
1459
+ const err = getError();
1460
+ yield {
1461
+ type: "error",
1462
+ message: err ? `failed to spawn codex: ${err.message}` : "spawn returned no pid",
1463
+ terminationReason: "failed"
1464
+ };
1465
+ return;
1466
+ }
1467
+ const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
1468
+ let sawStdout = false;
1469
+ let silentExitTimer;
1470
+ const closeSilentStdout = () => {
1471
+ silentExitTimer = setTimeout(() => {
1472
+ if (!sawStdout && !child.stdout.readableEnded) child.stdout.destroy();
1473
+ }, 50);
1474
+ };
1475
+ child.once("exit", closeSilentStdout);
1476
+ try {
1477
+ for await (const line of rl) {
1478
+ sawStdout = true;
1479
+ const trimmed = line.trim();
1480
+ if (!trimmed) continue;
1481
+ let parsed;
1482
+ try {
1483
+ parsed = JSON.parse(trimmed);
1484
+ } catch {
1485
+ continue;
1486
+ }
1487
+ yield* translator.translate(parsed);
1488
+ }
1489
+ } finally {
1490
+ if (silentExitTimer) clearTimeout(silentExitTimer);
1491
+ child.removeListener("exit", closeSilentStdout);
1492
+ rl.close();
1493
+ }
1494
+ const earlyRuntimeError = getError();
1495
+ if (earlyRuntimeError && child.exitCode === null && child.signalCode === null) {
1496
+ yield* translator.fail(`codex runtime error: ${earlyRuntimeError.message}`);
1497
+ return;
1498
+ }
1499
+ const exitCode = await waitForExitCode(child);
1500
+ const stopReason = getStopReason();
1501
+ if (stopReason) {
1502
+ yield* translator.finish(stopReason);
1503
+ return;
1504
+ }
1505
+ const runtimeError = getError();
1506
+ if (exitCode !== 0 && exitCode !== null) {
1507
+ if (!translator.terminalEmitted()) {
1508
+ const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
1509
+ const detail = stderr ? `: ${stderr.slice(0, 500)}` : "";
1510
+ yield* translator.fail(`codex exited with code ${exitCode}${detail}`);
1511
+ }
1512
+ return;
1513
+ }
1514
+ if (runtimeError && !translator.terminalEmitted()) {
1515
+ yield* translator.fail(`codex runtime error: ${runtimeError.message}`);
1516
+ return;
1517
+ }
1518
+ yield* translator.finish();
1519
+ }
1520
+ async function waitForExitCode(child) {
1521
+ if (child.exitCode !== null || child.signalCode !== null) {
1522
+ return child.exitCode;
1523
+ }
1524
+ return new Promise((resolve) => {
1525
+ child.once("exit", (code) => resolve(code));
1526
+ });
1527
+ }
1528
+ function isWindowsCommandNotFoundLine2(line) {
1529
+ return process.platform === "win32" && /is not recognized as an internal or external command|operable program or batch file/i.test(line);
1530
+ }
1531
+ export {
1532
+ ClaudeAdapter,
1533
+ CodexAdapter
1534
+ };
1535
+ //# sourceMappingURL=index.js.map