lark-remote 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.en.md +2 -2
  3. package/README.md +2 -2
  4. package/dist/bridge/inbound-media.d.ts +13 -20
  5. package/dist/bridge/inbound-media.js +107 -93
  6. package/dist/bridge/index.d.ts +6 -6
  7. package/dist/bridge/index.js +6 -12
  8. package/dist/card/approval-render.js +9 -8
  9. package/dist/cli.js +5 -1
  10. package/dist/config/dir.d.ts +9 -0
  11. package/dist/config/dir.js +69 -0
  12. package/dist/config/index.d.ts +22 -3
  13. package/dist/config/index.js +25 -3
  14. package/dist/connector/index.d.ts +22 -1
  15. package/dist/connector/index.js +79 -14
  16. package/dist/inbound/event.d.ts +41 -0
  17. package/dist/inbound/event.js +11 -0
  18. package/dist/inbound/placeholder.d.ts +26 -0
  19. package/dist/inbound/placeholder.js +149 -0
  20. package/dist/inbound/prompt.d.ts +20 -0
  21. package/dist/inbound/prompt.js +47 -0
  22. package/dist/inbound/receipt.d.ts +28 -0
  23. package/dist/inbound/receipt.js +62 -0
  24. package/dist/inbound/turn-assembler.d.ts +63 -0
  25. package/dist/inbound/turn-assembler.js +233 -0
  26. package/dist/inbound/turn.d.ts +48 -0
  27. package/dist/inbound/turn.js +10 -0
  28. package/dist/index.js +96 -71
  29. package/dist/router/card-helpers.d.ts +38 -2
  30. package/dist/router/card-helpers.js +79 -2
  31. package/dist/router/config/opencode.d.ts +1 -1
  32. package/dist/router/config/opencode.js +11 -0
  33. package/dist/router/index.d.ts +56 -6
  34. package/dist/router/index.js +256 -78
  35. package/dist/runner/common/connection-based-runner.js +6 -2
  36. package/dist/runner/dsh/fake-dsh-server.d.ts +6 -0
  37. package/dist/runner/dsh/fake-dsh-server.js +6 -0
  38. package/dist/runner/kimi/acp/runner.d.ts +1 -1
  39. package/dist/runner/kimi/acp/runner.js +1 -1
  40. package/dist/runner/opencode/acp/runner.d.ts +1 -1
  41. package/package.json +1 -1
@@ -52,6 +52,9 @@ export function parseCliArgs(args = process.argv.slice(2)) {
52
52
  else if (arg === '--dev') {
53
53
  result.dev = true;
54
54
  }
55
+ else if (arg === '--advance-help') {
56
+ result.advanceHelp = true;
57
+ }
55
58
  else if (arg === '--update' || arg === 'update') {
56
59
  // 裸子命令等价形式:`lark-remote update` 与 `--update` 同义。
57
60
  // 不识别时它会落到守护进程路径去抢单例锁,被正在运行的实例挡下
@@ -91,9 +94,75 @@ export function printHelp() {
91
94
  ' --settings <path> 指定 Claude 配置文件路径',
92
95
  ' --dev 开发模式:标记从源码 bun src/index.ts 启动(看门狗据此选择拉起方式)',
93
96
  ' --update 升级到最新版本后退出(用于 cron/脚本自动化升级)',
97
+ ' --advance-help 高级配置参考:config.yaml 全部高级字段的语义与改法(面向 coding agent)',
94
98
  ' -h, --help 显示本帮助信息',
95
99
  ' -v, --version 显示版本号',
96
100
  ];
97
101
  process.stdout.write(lines.join('\n') + '\n');
98
102
  }
103
+ /**
104
+ * Print advanced-config reference to stdout (CLI `--advance-help`).
105
+ *
106
+ * 目标读者是 coding agent(用户让 agent 代改 config.yaml):披露所有
107
+ * /config 卡片未暴露的 YAML 字段——名称、默认值、语义、改法。飞书侧
108
+ * 等价命令为 /advancehelp(内容同源,卡片渲染)。
109
+ */
110
+ export function printAdvanceHelp() {
111
+ const configDir = resolveConfigDir(parseCliArgs().configDir);
112
+ const configPath = configDir + '/config.yaml';
113
+ const lines = [
114
+ 'lark-remote 高级配置参考(--advance-help)',
115
+ '',
116
+ '目标读者:coding agent。用户把本输出交给 agent,agent 据此代改配置。',
117
+ '',
118
+ '配置文件:' + configPath,
119
+ '',
120
+ '修改方式(三选一):',
121
+ ' 1. 直接编辑上面的 config.yaml,改完由用户发送 /restart 生效',
122
+ ' 2. 用户发送 /config <key> <value> 文本直写(立盘即生效),',
123
+ ' 如 /config claude.approvalTimeoutMs 300000',
124
+ ' 3. 常用项走 /config 卡片交互(模型/审批档位/超时等已暴露,不在此列)',
125
+ '',
126
+ 'Key 映射规则:pi./codex./opencode./kimi./dsh. 开头自动映射到 agents.<agent>.<字段>;',
127
+ 'claude. 开头在顶层;其余原样。',
128
+ '',
129
+ 'Claude(顶层 claude.*):',
130
+ ' approvalTimeoutMs (默认 300000) 审批请求超时(ms),超时自动 cancel;0=立即过期;勿随意改短',
131
+ ' idleTtlMinutes (默认 30) 会话空闲回收(分钟),turn 间无新消息超窗回收长驻进程;0=不回收',
132
+ ' stopGraceMs (默认 5000) SIGTERM→SIGKILL 宽限(ms),内部实现细节,勿改',
133
+ '',
134
+ 'Codex(agents.codex.appServer.*):',
135
+ ' binary (默认 codex) codex 二进制路径',
136
+ ' requestTimeoutMs (默认 60000) 单次 RPC 请求超时(ms)',
137
+ ' idleTtlMs (默认 1800000) 连接空闲回收(ms)',
138
+ ' turnIdleTimeoutMinutes(默认 30) turn 无输出超时(分钟),0=关闭(卡片也可改)',
139
+ '',
140
+ 'Kimi(agents.kimi.acp.*):',
141
+ ' binary (默认 kimi) kimi 二进制路径',
142
+ ' requestTimeoutMs (默认 60000) 单次请求超时(ms)',
143
+ ' idleTtlMs (默认 1800000) 连接空闲回收(ms)',
144
+ ' turnIdleTimeoutMinutes(默认 30) turn 无输出超时(分钟),0=关闭(卡片也可改)',
145
+ '',
146
+ 'OpenCode(agents.opencode.acp.*):',
147
+ ' binary (默认 opencode) opencode 二进制路径',
148
+ ' requestTimeoutMs (默认 60000) 单次请求超时(ms)',
149
+ ' idleTtlMs (默认 1800000) 连接空闲回收(ms)',
150
+ ' turnIdleTimeoutMinutes(默认 30) turn 无输出超时(分钟),0=关闭(卡片也可改)',
151
+ '',
152
+ 'Pi:',
153
+ ' agents.pi.tools (默认 read,bash,edit,write,grep,find,ls) 逗号分隔工具白名单',
154
+ '',
155
+ '入站媒体(inboundMedia.*):',
156
+ ' enabled (默认 true) 图片/文件落盘开关',
157
+ ' dirName (默认 .lark-remote-temp) 落盘目录名(位于当前 cwd 下)',
158
+ ' maxFileSizeMb (默认 100) 单文件上限(MiB);飞书 >100MB 需分片,实际不可用更大值',
159
+ '',
160
+ '其他:',
161
+ ' checkUpdateOnStartup (默认 false) 启动时检查更新',
162
+ '',
163
+ '字段全集与校验规则见 Zod schema(src/config/index.ts,代码内唯一事实源)。',
164
+ '直接改 YAML 后必须 /restart;/config 文本直写与卡片保存即时生效。',
165
+ ];
166
+ process.stdout.write(lines.join('\n') + '\n');
167
+ }
99
168
  //# sourceMappingURL=dir.js.map
@@ -20,9 +20,16 @@ export declare const PI_THINKING_LEVELS: readonly ["off", "minimal", "low", "med
20
20
  export declare const DEFAULT_STOP_GRACE_MS: 5000;
21
21
  /** Codex app-server turn idle timeout default (minutes). */
22
22
  export declare const DEFAULT_TURN_IDLE_TIMEOUT_MINUTES: 30;
23
- /** 入站媒体默认配置(schema 默认与 connector 兜底共用,避免双源漂移)。 */
23
+ /**
24
+ * 入站媒体默认配置(schema 默认与 connector 兜底共用,避免双源漂移)。
25
+ *
26
+ * 单文件上限默认 100MB:50MB 对视频偏小(2026-09-15 事故就是 mp4 被丢弃)。
27
+ * 注意飞书侧 `type=file` 超过 100MB 必须用 Range 分片下载,而 SDK 的
28
+ * `downloadResourceToFile` 不分片(必报 234037),所以 100 是实际可用上限
29
+ * (inbound-message-matrix.md §4.4)。
30
+ */
24
31
  export declare const DEFAULT_INBOUND_MEDIA_DIR_NAME = ".lark-remote-temp";
25
- export declare const DEFAULT_INBOUND_MEDIA_MAX_SIZE_MB = 50;
32
+ export declare const DEFAULT_INBOUND_MEDIA_MAX_SIZE_MB = 100;
26
33
  /** 模型 ID → alias 映射。 */
27
34
  export declare const MODEL_ID_TO_ALIAS: Record<string, string>;
28
35
  /** alias → model ID 反向映射。 */
@@ -71,7 +78,7 @@ export declare const CodexConfigSchema: z.ZodObject<{
71
78
  turnIdleTimeoutMinutes: z.ZodDefault<z.ZodNumber>;
72
79
  }, z.core.$strip>>;
73
80
  }, z.core.$strip>;
74
- /** OpenCode-specific configuration (run mode: opencode run --format json --auto). */
81
+ /** OpenCode-specific configuration (pure ACP mode: `opencode acp` over stdio). */
75
82
  declare const OpencodeConfigSchema: z.ZodObject<{
76
83
  providerID: z.ZodDefault<z.ZodString>;
77
84
  modelID: z.ZodDefault<z.ZodString>;
@@ -79,6 +86,12 @@ declare const OpencodeConfigSchema: z.ZodObject<{
79
86
  plan: "plan";
80
87
  build: "build";
81
88
  }>>;
89
+ acp: z.ZodOptional<z.ZodObject<{
90
+ binary: z.ZodDefault<z.ZodString>;
91
+ requestTimeoutMs: z.ZodDefault<z.ZodNumber>;
92
+ idleTtlMs: z.ZodDefault<z.ZodNumber>;
93
+ turnIdleTimeoutMinutes: z.ZodDefault<z.ZodNumber>;
94
+ }, z.core.$strip>>;
82
95
  }, z.core.$strip>;
83
96
  /** Pi-specific configuration. pi is a spawn-per-message CLI like Claude. */
84
97
  declare const PiConfigSchema: z.ZodObject<{
@@ -179,6 +192,12 @@ export declare const AppConfigSchema: z.ZodObject<{
179
192
  plan: "plan";
180
193
  build: "build";
181
194
  }>>;
195
+ acp: z.ZodOptional<z.ZodObject<{
196
+ binary: z.ZodDefault<z.ZodString>;
197
+ requestTimeoutMs: z.ZodDefault<z.ZodNumber>;
198
+ idleTtlMs: z.ZodDefault<z.ZodNumber>;
199
+ turnIdleTimeoutMinutes: z.ZodDefault<z.ZodNumber>;
200
+ }, z.core.$strip>>;
182
201
  }, z.core.$strip>>;
183
202
  pi: z.ZodOptional<z.ZodObject<{
184
203
  provider: z.ZodDefault<z.ZodString>;
@@ -48,9 +48,16 @@ const DEFAULTS = {
48
48
  export const DEFAULT_STOP_GRACE_MS = DEFAULTS.STOP_GRACE_MS;
49
49
  /** Codex app-server turn idle timeout default (minutes). */
50
50
  export const DEFAULT_TURN_IDLE_TIMEOUT_MINUTES = DEFAULTS.TURN_IDLE_TIMEOUT_MINUTES;
51
- /** 入站媒体默认配置(schema 默认与 connector 兜底共用,避免双源漂移)。 */
51
+ /**
52
+ * 入站媒体默认配置(schema 默认与 connector 兜底共用,避免双源漂移)。
53
+ *
54
+ * 单文件上限默认 100MB:50MB 对视频偏小(2026-09-15 事故就是 mp4 被丢弃)。
55
+ * 注意飞书侧 `type=file` 超过 100MB 必须用 Range 分片下载,而 SDK 的
56
+ * `downloadResourceToFile` 不分片(必报 234037),所以 100 是实际可用上限
57
+ * (inbound-message-matrix.md §4.4)。
58
+ */
52
59
  export const DEFAULT_INBOUND_MEDIA_DIR_NAME = '.lark-remote-temp';
53
- export const DEFAULT_INBOUND_MEDIA_MAX_SIZE_MB = 50;
60
+ export const DEFAULT_INBOUND_MEDIA_MAX_SIZE_MB = 100;
54
61
  /** 模型 ID → alias 映射。 */
55
62
  export const MODEL_ID_TO_ALIAS = {
56
63
  'claude-opus-4-8': 'opus',
@@ -119,7 +126,7 @@ export const CodexConfigSchema = z.object({
119
126
  /** App-server connection configuration. */
120
127
  appServer: CodexAppServerConfigSchema.optional(),
121
128
  });
122
- /** OpenCode-specific configuration (run mode: opencode run --format json --auto). */
129
+ /** OpenCode-specific configuration (pure ACP mode: `opencode acp` over stdio). */
123
130
  const OpencodeConfigSchema = z.object({
124
131
  /** Provider ID for the LLM backend (e.g. 'anthropic'). */
125
132
  providerID: z.string().default('anthropic'),
@@ -127,6 +134,21 @@ const OpencodeConfigSchema = z.object({
127
134
  modelID: z.string().default('claude-sonnet-4-20250514'),
128
135
  /** Session mode (opencode agent name): 'build' (default) or 'plan'. */
129
136
  mode: z.enum(['build', 'plan']).default('build'),
137
+ /** ACP sub-configuration. Structurally mirrors kimi: the card exposes
138
+ * turnIdleTimeoutMinutes; binary/requestTimeoutMs/idleTtlMs are YAML-only
139
+ * engineering params. */
140
+ acp: z
141
+ .object({
142
+ /** Path to opencode binary for ACP mode. */
143
+ binary: z.string().default('opencode'),
144
+ /** Request timeout in milliseconds. */
145
+ requestTimeoutMs: z.number().int().min(0).default(60000),
146
+ /** Idle TTL for ACP connection in milliseconds. */
147
+ idleTtlMs: z.number().int().min(0).default(1800000),
148
+ /** Turn idle timeout in minutes (0 disables). */
149
+ turnIdleTimeoutMinutes: z.number().int().min(0).default(DEFAULT_TURN_IDLE_TIMEOUT_MINUTES),
150
+ })
151
+ .optional(),
130
152
  });
131
153
  /** Pi-specific configuration. pi is a spawn-per-message CLI like Claude. */
132
154
  const PiConfigSchema = z.object({
@@ -25,6 +25,10 @@ interface FeishuMessage {
25
25
  messageId: string;
26
26
  chatId: string;
27
27
  content: string;
28
+ /** 飞书原始 msg_type(`text` / `image` / `post` / `merge_forward` …)。 */
29
+ rawContentType: string;
30
+ /** 引用消息 id(回复某条消息时存在)。 */
31
+ replyToMessageId?: string;
28
32
  }
29
33
  type MessageHandler = (msg: FeishuMessage) => void;
30
34
  /**
@@ -33,12 +37,19 @@ type MessageHandler = (msg: FeishuMessage) => void;
33
37
  * (bridge 负责把这些失败提示回用户)。
34
38
  */
35
39
  export interface InboundMediaItem {
36
- /** 资源类型:image 消息按 MIME 生成 image_<HHmmss>_<n>.<ext>,file 保留文件名。 */
40
+ /**
41
+ * 下载 type(飞书 `im.v1.messageResource.get` 只认 image/file 两个值,
42
+ * 见 inbound-message-matrix.md §4 —— 不要扩展成 video/audio/sticker)。
43
+ */
37
44
  type: 'image' | 'file';
45
+ /** 资源种类(image/file/video/audio/sticker):命名/展示语义,与下载 type 分离。 */
46
+ kind: InboundResourceKind;
38
47
  /** 原始文件名(file 消息有;image 消息无,由 bridge 按 MIME 生成)。 */
39
48
  fileName?: string;
40
49
  /** 服务端 content-type(参数已剥离;可能缺失,bridge 有兜底)。 */
41
50
  mimeType?: string;
51
+ /** 视频/语音时长(毫秒),透传给 prompt 附件块。 */
52
+ durationMs?: number;
42
53
  /**
43
54
  * 下载内容所在临时文件(流式落盘,避免大文件全量进堆内存)。
44
55
  * 由 bridge 移动到最终位置;任何未移动路径都必须清理该文件。
@@ -46,6 +57,8 @@ export interface InboundMediaItem {
46
57
  tempPath: string;
47
58
  }
48
59
  export interface InboundMediaFailure {
60
+ /** 资源种类(排障/回执分组用)。 */
61
+ kind?: InboundResourceKind;
49
62
  fileName?: string;
50
63
  reason: string;
51
64
  }
@@ -62,16 +75,24 @@ export interface InboundMediaPayload {
62
75
  * 媒体消息到达的轻量描述(未下载):供上层先做 owner/配置闸门,
63
76
  * 通过后再调 downloadInboundMedia —— 下载发生在认证之后(P1 review 修复)。
64
77
  */
78
+ /** SDK 给出的可下载资源种类(`resources[].type`)。 */
79
+ export type InboundResourceKind = 'image' | 'file' | 'audio' | 'video' | 'sticker';
65
80
  export interface InboundMediaMessage {
66
81
  userId: string;
67
82
  chatId: string;
68
83
  messageId: string;
84
+ /** 飞书原始 msg_type(未识别类型时用于 warn,default-deny 而非 default-text)。 */
85
+ rawContentType: string;
69
86
  /** 引用上下文:不同 replyTo 强制拆批。 */
70
87
  replyToMessageId?: string;
71
88
  resources: Array<{
89
+ /** 飞书下载接口 type(只有 image/file 两值)。 */
72
90
  type: 'image' | 'file';
91
+ /** 资源种类(透传 SDK 的 `resources[].type`)。 */
92
+ kind: InboundResourceKind;
73
93
  fileKey: string;
74
94
  fileName?: string;
95
+ durationMs?: number;
75
96
  }>;
76
97
  }
77
98
  type InboundMediaDetectedHandler = (msg: InboundMediaMessage) => void | Promise<void>;
@@ -2,6 +2,7 @@ import { createLarkChannel, } from '@larksuite/channel';
2
2
  import { getLogger } from '../logger/index.js';
3
3
  import { MAX_FILE_UPLOAD_SIZE } from './file-limits.js';
4
4
  import { DEFAULT_INBOUND_MEDIA_MAX_SIZE_MB } from '../config/index.js';
5
+ import { stripPlaceholders } from '../inbound/placeholder.js';
5
6
  import { sleep } from '../common/sleep.js';
6
7
  import { isTransientTransportError } from '../error-classification.js';
7
8
  import axios from 'axios';
@@ -45,8 +46,45 @@ const noKeepAliveAgent = new https.Agent({ keepAlive: false });
45
46
  * 详见 design.md §9.8。原地更新逻辑新增按钮时参考该节去重风险分类。
46
47
  */
47
48
  export const DEDUP_TTL_MS = 300;
49
+ /**
50
+ * SDK converter 注册表支持的 msg_type(@larksuite/channel 0.3.0 实测)。
51
+ * 带资源但类型不在其中 = 未来新增类型:照常下载 + warn(default-deny)。
52
+ */
53
+ const KNOWN_RESOURCE_CONTENT_TYPES = new Set([
54
+ 'text',
55
+ 'post',
56
+ 'image',
57
+ 'file',
58
+ 'audio',
59
+ 'video',
60
+ 'media',
61
+ 'sticker',
62
+ 'interactive',
63
+ 'merge_forward',
64
+ 'share_chat',
65
+ 'share_user',
66
+ 'location',
67
+ 'system',
68
+ 'vote',
69
+ 'todo',
70
+ 'calendar',
71
+ 'general_calendar',
72
+ 'share_calendar_event',
73
+ 'folder',
74
+ 'hongbao',
75
+ 'video_chat',
76
+ ]);
48
77
  /** 单资源下载超时(毫秒):SDK 无内置超时,挂起会导致提示丢失 + 残留临时文件。 */
49
78
  const RESOURCE_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
79
+ /**
80
+ * 合并转发(merge_forward)的聚合资源缺少 `message_id`,飞书要求 key 与 message_id
81
+ * 同属一条消息(234003),且合并转发的资源下载本身被列为不支持(234043)。
82
+ * 自建子消息遍历需要真机验证(inbound-message-matrix.md §5 Step 3),
83
+ * 在验证完成前下载必然失败的场景给用户可执行的替代方案。
84
+ */
85
+ const MERGE_FORWARD_HINT = {
86
+ merge_forward: '(合并转发里的附件暂不支持保存,可逐条转发或直接发送文件)',
87
+ };
50
88
  function withTimeout(promise, ms, label) {
51
89
  return new Promise((resolve, reject) => {
52
90
  const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
@@ -218,21 +256,27 @@ export class FeishuConnector {
218
256
  this.channel.on('message', (msg) => {
219
257
  if (msg.chatType !== 'p2p')
220
258
  return;
221
- // 入站图片/文件:不转发文本内容(图片消息的 content 只是占位文案),
222
- // 而是下载资源后交给 bridge 落盘(runner 零改动)。
223
- if ((msg.rawContentType === 'image' || msg.rawContentType === 'file') &&
224
- msg.resources.length > 0) {
225
- // 只上报"媒体到达",不在此下载:owner/配置闸门在 index.ts 里先执行,
259
+ // 判据是「是否携带可下载资源」(`msg.resources`),不是 `msg_type` 白名单:
260
+ // SDK 只为 image/file/audio/video/media/sticker 五类产出非空 resources,
261
+ // 枚举 msg_type 必然漏(2026-09-15 事故:mp4 被当文本转发给 agent)。
262
+ // 一条消息可以**同时**产出资源事件与文本事件(post 既有文字又有图),
263
+ // 由 B3 的装配器合并成同一个 turn。
264
+ const hasResources = msg.resources.length > 0;
265
+ if (hasResources) {
266
+ // 只上报「媒体到达」,不在此下载:owner/配置闸门在 index.ts 里先执行,
226
267
  // 通过后才调用 downloadInboundMedia(避免未认证大文件下载打爆内存)。
227
268
  void this.handleInboundMediaDetected(msg);
228
- return;
229
269
  }
230
- this.onMessage?.({
231
- userId: msg.senderId,
232
- messageId: msg.messageId,
233
- chatId: msg.chatId,
234
- content: msg.content,
235
- });
270
+ if (!hasResources || stripPlaceholders(msg.content).clean !== '') {
271
+ this.onMessage?.({
272
+ userId: msg.senderId,
273
+ messageId: msg.messageId,
274
+ chatId: msg.chatId,
275
+ content: msg.content,
276
+ rawContentType: msg.rawContentType,
277
+ replyToMessageId: msg.replyToMessageId,
278
+ });
279
+ }
236
280
  });
237
281
  this.channel.on('cardAction', (action) => {
238
282
  // Return the handler's response (toast / in-place card update) so the
@@ -272,16 +316,26 @@ export class FeishuConnector {
272
316
  getLogger().warn('[feishu] inbound media received but no detected handler registered');
273
317
  return;
274
318
  }
319
+ // default-deny 但可见:未识别类型(未来 SDK 新增)照常下载,但必须留痕,
320
+ // 否则会重演「静默降级成占位符」的事故。
321
+ if (!KNOWN_RESOURCE_CONTENT_TYPES.has(msg.rawContentType)) {
322
+ getLogger().warn(`[feishu] inbound media with unrecognized msg_type="${msg.rawContentType}" ` +
323
+ `resources=${msg.resources.length}, downloading anyway`);
324
+ }
275
325
  try {
276
326
  await this.onInboundMediaDetected({
277
327
  userId: msg.senderId,
278
328
  chatId: msg.chatId,
279
329
  messageId: msg.messageId,
330
+ rawContentType: msg.rawContentType,
280
331
  replyToMessageId: msg.replyToMessageId,
281
332
  resources: msg.resources.map((r) => ({
333
+ // 下载 type 只有 image/file 两个合法值(传 video/audio/sticker 会 400)。
282
334
  type: r.type === 'image' ? 'image' : 'file',
335
+ kind: r.type,
283
336
  fileKey: r.fileKey,
284
337
  fileName: r.fileName,
338
+ durationMs: r.durationMs,
285
339
  })),
286
340
  });
287
341
  }
@@ -307,23 +361,34 @@ export class FeishuConnector {
307
361
  const { contentType, bytesWritten } = await withTimeout(this.channel.downloadResourceToFile(msg.messageId, res.fileKey, res.type, tmpPath), timeoutMs, `downloadResource fileKey=${res.fileKey}`);
308
362
  if (bytesWritten > maxBytes) {
309
363
  silentlyUnlink(tmpPath);
364
+ const limitMb = maxBytes / (1024 * 1024);
310
365
  failures.push({
366
+ kind: res.kind,
311
367
  fileName: res.fileName,
312
- reason: `超过 ${maxBytes / (1024 * 1024)}MB 大小限制`,
368
+ // 飞书侧 >100MB 必须 Range 分片(SDK 不分片),到上限就是下不动:
369
+ // 提示写清楚,避免用户以为"再放大上限就能存"(matrix §4.4/§2 #11)。
370
+ reason: `超过 ${limitMb}MB 大小限制` +
371
+ (limitMb >= 100 ? '(飞书 >100MB 的文件需分片下载,暂不支持)' : ''),
313
372
  });
314
373
  continue;
315
374
  }
316
375
  media.push({
317
376
  type: res.type,
377
+ kind: res.kind,
318
378
  fileName: res.fileName,
319
379
  mimeType: contentType,
380
+ durationMs: res.durationMs,
320
381
  tempPath: tmpPath,
321
382
  });
322
383
  }
323
384
  catch (err) {
324
385
  silentlyUnlink(tmpPath);
325
386
  getLogger().warn(`[feishu] downloadResource failed fileKey=${res.fileKey} type=${res.type}:`, err.message);
326
- failures.push({ fileName: res.fileName, reason: `下载失败: ${err.message}` });
387
+ failures.push({
388
+ kind: res.kind,
389
+ fileName: res.fileName,
390
+ reason: `下载失败: ${err.message}${MERGE_FORWARD_HINT[msg.rawContentType] ?? ''}`,
391
+ });
327
392
  }
328
393
  }
329
394
  return {
@@ -0,0 +1,41 @@
1
+ /**
2
+ * 装配器事件(设计依据见 `docs/zh/architecture/inbound-unified-input-design.md`)。
3
+ *
4
+ * 设计文档早期的媒体事件形态是「下载完成后的 attachments/failures」。实际链路里
5
+ * 下载是异步的(`index.ts` 先过 owner/enabled 闸门再下载),若等下载完成才投递事件,
6
+ * 「先图后文」在慢下载下会先提交一个只含文本的 turn(正是要修的症状)。因此媒体事件
7
+ * 携带一个 **outcome promise**:装配器立刻知道「本 turn 还有 in-flight 下载」,
8
+ * 窗口到期后等它落定再 commit(§5.2)。
9
+ */
10
+ import type { PlaceholderKind } from './placeholder.js';
11
+ import type { MediaOutcome } from './turn.js';
12
+ export interface InboundEventBase {
13
+ userId: string;
14
+ chatId: string;
15
+ messageId: string;
16
+ replyToMessageId?: string;
17
+ /** 飞书原始 msg_type(`text` / `image` / `post` / `merge_forward` …)。 */
18
+ rawContentType: string;
19
+ }
20
+ export interface TextInboundEvent extends InboundEventBase {
21
+ kind: 'text';
22
+ /** 已剥离结构占位符的文本(可为空串:整条消息都是占位符)。 */
23
+ text: string;
24
+ /** 本条消息命中的占位符种类,用于「不支持」回执。 */
25
+ placeholders: PlaceholderKind[];
26
+ /** 未知标签(未来 SDK 新增),上层负责 warn。 */
27
+ unknownTags: string[];
28
+ }
29
+ export interface MediaInboundEvent extends InboundEventBase {
30
+ kind: 'media';
31
+ /** 下载 + 落盘结果;装配器在窗口到期后等它落定才 commit。 */
32
+ outcome: Promise<MediaOutcome>;
33
+ }
34
+ export interface RejectedInboundEvent extends InboundEventBase {
35
+ kind: 'rejected';
36
+ /** 面向人的说明(如「入站媒体保存已关闭」)。 */
37
+ reason: string;
38
+ /** 拒绝项的 kind(默认 `unknown`)。 */
39
+ rejectedKind?: string;
40
+ }
41
+ export type InboundEvent = TextInboundEvent | MediaInboundEvent | RejectedInboundEvent;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * 装配器事件(设计依据见 `docs/zh/architecture/inbound-unified-input-design.md`)。
3
+ *
4
+ * 设计文档早期的媒体事件形态是「下载完成后的 attachments/failures」。实际链路里
5
+ * 下载是异步的(`index.ts` 先过 owner/enabled 闸门再下载),若等下载完成才投递事件,
6
+ * 「先图后文」在慢下载下会先提交一个只含文本的 turn(正是要修的症状)。因此媒体事件
7
+ * 携带一个 **outcome promise**:装配器立刻知道「本 turn 还有 in-flight 下载」,
8
+ * 窗口到期后等它落定再 commit(§5.2)。
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=event.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 入站消息结构占位符识别与剥离(纯函数,无 IO,便于表驱动测试)。
3
+ *
4
+ * 背景(P0 事故 2026-09-15):`@larksuite/channel` 把非文本消息渲染成结构占位符,
5
+ * 富文本(`post`)里的图片是 `![image](img_v3_…)` —— 首字符恰好是 `!`,于是被
6
+ * `src/router/index.ts` 的裸前缀判定当成 bash 命令执行了整段消息。
7
+ *
8
+ * 规则来源:`docs/zh/architecture/inbound-message-matrix.md` §1 的 22 种 message_type
9
+ * 实测渲染串。判定顺序**先清洗后判语义**:任何前缀判定都必须发生在剥离之后。
10
+ *
11
+ * 取舍(有意为之):剥离对所有消息生效,所以用户在**纯文本**消息里手打
12
+ * `![image](…)` / `<file key="…"/>` 这类字面量也会被当成占位符剥掉。代价是极少数
13
+ * 「讨论本工具自身语法」的消息会丢片段;换来的是任何入口都不可能把占位符当命令
14
+ * (P0 事故正是 `![image](img_v3_…)` 的首字符 `!` 命中 bash 判定)。
15
+ */
16
+ export type PlaceholderKind = 'image' | 'file' | 'video' | 'audio' | 'sticker' | 'share' | 'location' | 'folder' | 'vote' | 'todo' | 'meeting' | 'calendar' | 'hongbao' | 'forwarded' | 'unsupported' | 'unknown';
17
+ export interface StripResult {
18
+ /** 剥离占位符后的文本(trim 后;forwarded 块只剥标签、保留内部文本)。 */
19
+ clean: string;
20
+ /** 命中的占位符种类(去重、保序),用于 rejected 回执与排障。 */
21
+ kinds: PlaceholderKind[];
22
+ /** 未知标签(未来 SDK 新增)——必须 warn,防止再次静默漏。 */
23
+ unknownTags: string[];
24
+ }
25
+ export declare function isDownloadablePlaceholder(kind: PlaceholderKind): boolean;
26
+ export declare function stripPlaceholders(raw: string): StripResult;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 入站消息结构占位符识别与剥离(纯函数,无 IO,便于表驱动测试)。
3
+ *
4
+ * 背景(P0 事故 2026-09-15):`@larksuite/channel` 把非文本消息渲染成结构占位符,
5
+ * 富文本(`post`)里的图片是 `![image](img_v3_…)` —— 首字符恰好是 `!`,于是被
6
+ * `src/router/index.ts` 的裸前缀判定当成 bash 命令执行了整段消息。
7
+ *
8
+ * 规则来源:`docs/zh/architecture/inbound-message-matrix.md` §1 的 22 种 message_type
9
+ * 实测渲染串。判定顺序**先清洗后判语义**:任何前缀判定都必须发生在剥离之后。
10
+ *
11
+ * 取舍(有意为之):剥离对所有消息生效,所以用户在**纯文本**消息里手打
12
+ * `![image](…)` / `<file key="…"/>` 这类字面量也会被当成占位符剥掉。代价是极少数
13
+ * 「讨论本工具自身语法」的消息会丢片段;换来的是任何入口都不可能把占位符当命令
14
+ * (P0 事故正是 `![image](img_v3_…)` 的首字符 `!` 命中 bash 判定)。
15
+ */
16
+ /**
17
+ * 可下载资源类占位符:这些占位符对应的资源会由媒体通道下载落盘,
18
+ * 因此文本侧不把它们记成「不支持」(否则图文混排会双重报错)。
19
+ */
20
+ const DOWNLOADABLE_KINDS = new Set([
21
+ 'image',
22
+ 'file',
23
+ 'video',
24
+ 'audio',
25
+ 'sticker',
26
+ ]);
27
+ export function isDownloadablePlaceholder(kind) {
28
+ return DOWNLOADABLE_KINDS.has(kind);
29
+ }
30
+ /** 协议块哨兵:`<attachments>` 是本项目自己生成的 prompt 附件块,剥离时必须原样保留。 */
31
+ const ATTACHMENT_BLOCK_RE = /<attachments>[\s\S]*?<\/attachments>/g;
32
+ const SENTINEL_PREFIX = '\u0000lark-inbound-att-';
33
+ const SENTINEL_SUFFIX = '\u0000';
34
+ /** 自闭合标签 → kind(`<file key="…" name="…"/>` 等,属性可缺省)。 */
35
+ const SELF_CLOSING_RULES = [
36
+ [/<file(?:\s[^<>]*)?\/>/g, 'file'],
37
+ [/<video(?:\s[^<>]*)?\/>/g, 'video'],
38
+ [/<audio(?:\s[^<>]*)?\/>/g, 'audio'],
39
+ [/<sticker(?:\s[^<>]*)?\/>/g, 'sticker'],
40
+ [/<group_card(?:\s[^<>]*)?\/>/g, 'share'],
41
+ [/<contact_card(?:\s[^<>]*)?\/>/g, 'share'],
42
+ [/<location(?:\s[^<>]*)?\/>/g, 'location'],
43
+ [/<folder(?:\s[^<>]*)?\/>/g, 'folder'],
44
+ [/<hongbao(?:\s[^<>]*)?\/>/g, 'hongbao'],
45
+ ];
46
+ /** 整块剥离(含内部内容)的容器标签:内容无用户语义,只作噪声。 */
47
+ const BLOCK_RULES = [
48
+ [/<vote>[\s\S]*?<\/vote>/g, 'vote'],
49
+ [/<todo>[\s\S]*?<\/todo>/g, 'todo'],
50
+ [/<meeting>[\s\S]*?<\/meeting>/g, 'meeting'],
51
+ [/<calendar_invite>[\s\S]*?<\/calendar_invite>/g, 'calendar'],
52
+ [/<calendar_share>[\s\S]*?<\/calendar_share>/g, 'calendar'],
53
+ [/<calendar>[\s\S]*?<\/calendar>/g, 'calendar'],
54
+ ];
55
+ /** 图片渲染串:`![image](img_v3_…)` / `![]()`,富文本内嵌图与纯 image 消息同形。 */
56
+ const IMAGE_MD_RE = /!\[(?:image)?\]\([^)]*\)/g;
57
+ /** 合并转发:只剥标签、保留内部文本(子消息文本有语义)。 */
58
+ const FORWARDED_TAG_RE = /<\/?forwarded_messages\s*\/?>/g;
59
+ /** 提及标签:保留内部显示名,不作为占位符上报。 */
60
+ const AT_TAG_RE = /<at(?:\s[^<>]*)?>([\s\S]*?)<\/at>/g;
61
+ /** converter 的降级态(缺 key / 未识别类型 —— 都是纯噪声)。 */
62
+ const BRACKET_FALLBACK_RE = /\[(?:unsupported message|rich text message|interactive card|image|file|video|audio|sticker|system message|folder)\]/g;
63
+ /**
64
+ * 未知标签兜底:只在「有属性」或「成对闭合」时才剥离。
65
+ * 要求有属性可显著降低误伤——用户正文里的 `<3`、`a < b`、`<div>` 不会被吃掉。
66
+ */
67
+ const UNKNOWN_SELF_CLOSING_RE = /<([a-z][a-z0-9_]*)\s[^<>]*\/>/g;
68
+ const UNKNOWN_PAIRED_RE = /<([a-z][a-z0-9_]*)(?:\s[^<>]*)?>[\s\S]*?<\/\1>/g;
69
+ /** 剥离后遗留的连续空行折叠为单空行(属剥离产物,不算对用户文本加工)。 */
70
+ function collapseBlankLines(text) {
71
+ return text.replace(/\n{3,}/g, '\n\n');
72
+ }
73
+ export function stripPlaceholders(raw) {
74
+ const kinds = [];
75
+ const unknownTags = [];
76
+ /** 是否真的剥离过东西:没有命中时不做任何文本加工(保持用户原文)。 */
77
+ let stripped = false;
78
+ // 1. 先把本项目自己的 <attachments> 协议块摘出去,最后原样放回。
79
+ const protectedBlocks = [];
80
+ let working = raw.replace(ATTACHMENT_BLOCK_RE, (match) => {
81
+ const token = `${SENTINEL_PREFIX}${protectedBlocks.length}${SENTINEL_SUFFIX}`;
82
+ protectedBlocks.push(match);
83
+ return token;
84
+ });
85
+ const hit = (kind) => {
86
+ stripped = true;
87
+ if (!kinds.includes(kind))
88
+ kinds.push(kind);
89
+ };
90
+ // 2. 图片渲染串(必须在 forwarded 标签剥离之前,覆盖块内子消息的图)。
91
+ working = working.replace(IMAGE_MD_RE, () => {
92
+ hit('image');
93
+ return '';
94
+ });
95
+ // 3. 已知自闭合标签。
96
+ for (const [re, kind] of SELF_CLOSING_RULES) {
97
+ working = working.replace(re, () => {
98
+ hit(kind);
99
+ return '';
100
+ });
101
+ }
102
+ // 4. 已知容器块(整块剥离)。
103
+ for (const [re, kind] of BLOCK_RULES) {
104
+ working = working.replace(re, () => {
105
+ hit(kind);
106
+ return '';
107
+ });
108
+ }
109
+ // 5. 合并转发:只剥标签。
110
+ working = working.replace(FORWARDED_TAG_RE, () => {
111
+ hit('forwarded');
112
+ return '';
113
+ });
114
+ // 6. 提及标签:保留显示名。
115
+ working = working.replace(AT_TAG_RE, (_match, inner) => {
116
+ stripped = true;
117
+ return inner;
118
+ });
119
+ // 7. converter 降级态。
120
+ working = working.replace(BRACKET_FALLBACK_RE, () => {
121
+ hit('unsupported');
122
+ return '';
123
+ });
124
+ // 8. 未知标签兜底(未来 SDK 新增类型):剥离 + 记录 tag 名。
125
+ working = working.replace(UNKNOWN_SELF_CLOSING_RE, (match, tag) => {
126
+ hit('unknown');
127
+ if (!unknownTags.includes(tag))
128
+ unknownTags.push(tag);
129
+ return '';
130
+ });
131
+ working = working.replace(UNKNOWN_PAIRED_RE, (match, tag) => {
132
+ hit('unknown');
133
+ if (!unknownTags.includes(tag))
134
+ unknownTags.push(tag);
135
+ return '';
136
+ });
137
+ // 9. 放回协议块。
138
+ if (protectedBlocks.length > 0) {
139
+ stripped = true;
140
+ for (let i = 0; i < protectedBlocks.length; i += 1) {
141
+ working = working.split(`${SENTINEL_PREFIX}${i}${SENTINEL_SUFFIX}`).join(protectedBlocks[i]);
142
+ }
143
+ }
144
+ // 未命中任何占位符时**不做文本加工**(保留原文的连续空行等),
145
+ // 确保 router.handle 对纯文本消息的转发与原行为逐字一致。
146
+ const clean = stripped ? collapseBlankLines(working).trim() : working.trim();
147
+ return { clean, kinds, unknownTags };
148
+ }
149
+ //# sourceMappingURL=placeholder.js.map