lark-remote 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 入站回执文案(设计依据见 `docs/zh/architecture/inbound-unified-input-design.md`)。
3
+ *
4
+ * 两类回执合并成一条:
5
+ * 1. 无文本纯附件(决策 2):不自动起 turn,只回已保存路径 + 引导语;
6
+ * 2. 拿不到的东西(不支持类型 / 超限 / 下载失败 / 媒体保存已关闭):明确告知,
7
+ * 而不是把占位符塞给 agent。
8
+ *
9
+ * 用户可见文案指代本程序时只能写 `lark-remote`(AGENTS.md 命名纪律)。
10
+ */
11
+ import path from 'node:path';
12
+ /** 单条回执最多列出的文件数;超出折叠为 "… 等 N 个文件"(沿用旧提示口径)。 */
13
+ export const MAX_PATHS_IN_RECEIPT = 10;
14
+ /** 占位符种类 → 面向人的名称。 */
15
+ const PLACEHOLDER_LABELS = {
16
+ image: '图片',
17
+ file: '文件',
18
+ video: '视频',
19
+ audio: '语音',
20
+ sticker: '表情',
21
+ share: '名片/群分享',
22
+ location: '位置',
23
+ folder: '文件夹',
24
+ vote: '投票',
25
+ todo: '待办',
26
+ meeting: '视频会议',
27
+ calendar: '日程',
28
+ hongbao: '红包',
29
+ forwarded: '合并转发',
30
+ unsupported: '此类',
31
+ unknown: '未知类型',
32
+ };
33
+ /** 「不支持」回执句式(§5.7 表:不支持类型统一「暂不支持 X」)。 */
34
+ export function unsupportedReason(kind) {
35
+ return `暂不支持${PLACEHOLDER_LABELS[kind]}消息`;
36
+ }
37
+ /**
38
+ * 生成回执文案;没有任何需要告知的内容时返回 undefined(调用方不发消息)。
39
+ */
40
+ export function buildReceipt(input) {
41
+ const parts = [];
42
+ if (input.saved.length > 0) {
43
+ const lines = input.saved.slice(0, MAX_PATHS_IN_RECEIPT).map((p) => `- ${p}`);
44
+ const overflow = input.saved.length > MAX_PATHS_IN_RECEIPT ? `\n… 等 ${input.saved.length} 个文件` : '';
45
+ parts.push(`📎 已保存 ${input.saved.length} 个文件:\n${lines.join('\n')}${overflow}`);
46
+ }
47
+ if (input.rejected.length > 0) {
48
+ parts.push(`⚠️ ${input.rejected.map((r) => r.reason).join(';')}`);
49
+ }
50
+ if (input.startWorkHint && input.saved.length > 0) {
51
+ // 保存目录去重(跨分钟时可能落在两个目录,此时全部列出)。
52
+ const dirs = [...new Set(input.saved.map((p) => path.dirname(p)))];
53
+ const example = dirs.length === 1
54
+ ? `请处理 ${dirs[0]} 下的文件`
55
+ : `请处理以下目录下的文件:${dirs.join('、')}`;
56
+ parts.push(`💡 说一句话我就开始处理,例如:${example}`);
57
+ }
58
+ if (parts.length === 0)
59
+ return undefined;
60
+ return parts.join('\n');
61
+ }
62
+ //# sourceMappingURL=receipt.js.map
@@ -0,0 +1,63 @@
1
+ /**
2
+ * InboundTurnAssembler:统一静默期窗口 + 合并 + 下载等待 + commit。
3
+ *
4
+ * 设计依据:`docs/zh/architecture/inbound-unified-input-design.md` §4/§5.2。
5
+ *
6
+ * 规则:
7
+ * - 任何事件到达 → **重置** 700ms 定时器(按 `userId:chatId` 分桶),保证图/文任意顺序等价;
8
+ * - 定时器到点 → 若本 turn 仍有 in-flight 下载 → 等待,落定后再 commit;
9
+ * - 下载失败/超时 → 该项进 `rejected`,然后照常 commit;
10
+ * - commit → 构造 prompt(`prompt.ts`)→ `onCommit`;
11
+ * - **无文本且只有附件 → 不 commit**(决策 2),只发 `onReceipt` 回执;
12
+ * - 命令消息由调用方 `flush()` 强制提交,不等窗口。
13
+ */
14
+ import type { InboundEvent } from './event.js';
15
+ import { type CommitReason, type InboundTurn } from './turn.js';
16
+ /** 统一静默期窗口(ms)——决策 1:不做「纯文本零延迟」快路径。 */
17
+ export declare const DEFAULT_TURN_WINDOW_MS = 700;
18
+ export interface AssemblerContext {
19
+ userId: string;
20
+ chatId: string;
21
+ messageId: string;
22
+ }
23
+ export interface AssemblerDeps {
24
+ /** 静默期窗口(毫秒),默认 700。 */
25
+ windowMs?: number;
26
+ /** 定时器注入(便于 vitest fake timers / 单元测试确定性)。 */
27
+ setTimer?: (fn: () => void, ms: number) => unknown;
28
+ clearTimer?: (handle: unknown) => void;
29
+ /** commit 回调:组装完成的 turn + prompt 交给上层(进 agent)。 */
30
+ onCommit: (turn: InboundTurn, prompt: string) => void | Promise<void>;
31
+ /** 回执回调:面向用户的提示(无文本纯附件 / 有 rejected 项)。 */
32
+ onReceipt?: (ctx: AssemblerContext, text: string) => void | Promise<void>;
33
+ }
34
+ export declare class InboundTurnAssembler {
35
+ private readonly deps;
36
+ private readonly buckets;
37
+ private readonly windowMs;
38
+ private readonly setTimer;
39
+ private readonly clearTimer;
40
+ private disposed;
41
+ constructor(deps: AssemblerDeps);
42
+ /** 投递一个入站事件(文本 / 媒体[in-flight] / 拒绝)。 */
43
+ ingest(event: InboundEvent): void;
44
+ /**
45
+ * 强制提交窗口内已装配的内容(命令到达、退出前冲刷)。
46
+ * 仍有 in-flight 下载时先等它落定(避免丢掉附件路径)。
47
+ */
48
+ flush(userId: string, chatId: string, reason?: CommitReason): Promise<void>;
49
+ /** 冲刷全部窗口(/exit、/restart 干净退出前调用)。 */
50
+ flushAll(reason?: CommitReason): Promise<void>;
51
+ /** 进程退出:丢弃定时器,避免悬挂。 */
52
+ dispose(): void;
53
+ private ensureBucket;
54
+ private pushRejected;
55
+ private armTimer;
56
+ /**
57
+ * 登记一次 in-flight 媒体下载:落定后合并结果,并在窗口已到期时触发 commit。
58
+ * 下载异常(含超时)记入 rejected,不阻断本 turn 的其它内容。
59
+ */
60
+ private trackMediaOutcome;
61
+ private tryCommit;
62
+ private commit;
63
+ }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * InboundTurnAssembler:统一静默期窗口 + 合并 + 下载等待 + commit。
3
+ *
4
+ * 设计依据:`docs/zh/architecture/inbound-unified-input-design.md` §4/§5.2。
5
+ *
6
+ * 规则:
7
+ * - 任何事件到达 → **重置** 700ms 定时器(按 `userId:chatId` 分桶),保证图/文任意顺序等价;
8
+ * - 定时器到点 → 若本 turn 仍有 in-flight 下载 → 等待,落定后再 commit;
9
+ * - 下载失败/超时 → 该项进 `rejected`,然后照常 commit;
10
+ * - commit → 构造 prompt(`prompt.ts`)→ `onCommit`;
11
+ * - **无文本且只有附件 → 不 commit**(决策 2),只发 `onReceipt` 回执;
12
+ * - 命令消息由调用方 `flush()` 强制提交,不等窗口。
13
+ */
14
+ import { getLogger } from '../logger/index.js';
15
+ import { isDownloadablePlaceholder } from './placeholder.js';
16
+ import { buildPrompt } from './prompt.js';
17
+ import { buildReceipt, unsupportedReason } from './receipt.js';
18
+ import { bucketKey, } from './turn.js';
19
+ /** 统一静默期窗口(ms)——决策 1:不做「纯文本零延迟」快路径。 */
20
+ export const DEFAULT_TURN_WINDOW_MS = 700;
21
+ export class InboundTurnAssembler {
22
+ deps;
23
+ buckets = new Map();
24
+ windowMs;
25
+ setTimer;
26
+ clearTimer;
27
+ disposed = false;
28
+ constructor(deps) {
29
+ this.deps = deps;
30
+ this.windowMs = deps.windowMs ?? DEFAULT_TURN_WINDOW_MS;
31
+ this.setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
32
+ this.clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
33
+ }
34
+ /** 投递一个入站事件(文本 / 媒体[in-flight] / 拒绝)。 */
35
+ ingest(event) {
36
+ if (this.disposed) {
37
+ // 已 dispose(进程收尾):不再装配,但必须吞掉 in-flight promise 的 rejection,
38
+ // 否则它会以 unhandledRejection 形式打死进程。
39
+ if (event.kind === 'media')
40
+ void event.outcome.catch(() => { });
41
+ return;
42
+ }
43
+ const key = bucketKey(event.userId, event.chatId);
44
+ const bucket = this.ensureBucket(key, event);
45
+ if (!bucket.messageIds.includes(event.messageId))
46
+ bucket.messageIds.push(event.messageId);
47
+ if (bucket.replyToMessageId === undefined && event.replyToMessageId !== undefined) {
48
+ bucket.replyToMessageId = event.replyToMessageId;
49
+ }
50
+ switch (event.kind) {
51
+ case 'text': {
52
+ if (event.text !== '')
53
+ bucket.texts.push(event.text);
54
+ // 可下载占位符(图/文件/视频/语音/表情)由媒体通道处理,不在此记 rejected;
55
+ // 其余(位置/名片/投票/合并转发/降级态/未知)拿不到,明确回执。
56
+ for (const kind of event.placeholders) {
57
+ if (isDownloadablePlaceholder(kind))
58
+ continue;
59
+ // 合并转发的子消息文本已被 SDK 渲染(text 非空)→ 只保留文本;
60
+ // 附件能不能拿到由媒体通道的 outcome 决定,不在这里重复报「不支持」。
61
+ if (kind === 'forwarded' && event.text !== '')
62
+ continue;
63
+ this.pushRejected(bucket, {
64
+ kind,
65
+ reason: unsupportedReason(kind),
66
+ sourceMsgId: event.messageId,
67
+ });
68
+ }
69
+ break;
70
+ }
71
+ case 'media': {
72
+ this.trackMediaOutcome(bucket, key, event.messageId, event.outcome);
73
+ break;
74
+ }
75
+ case 'rejected': {
76
+ this.pushRejected(bucket, {
77
+ kind: event.rejectedKind ?? 'unknown',
78
+ reason: event.reason,
79
+ sourceMsgId: event.messageId,
80
+ });
81
+ break;
82
+ }
83
+ }
84
+ this.armTimer(key, bucket);
85
+ }
86
+ /**
87
+ * 强制提交窗口内已装配的内容(命令到达、退出前冲刷)。
88
+ * 仍有 in-flight 下载时先等它落定(避免丢掉附件路径)。
89
+ */
90
+ async flush(userId, chatId, reason = 'flush') {
91
+ const key = bucketKey(userId, chatId);
92
+ const bucket = this.buckets.get(key);
93
+ if (!bucket)
94
+ return;
95
+ bucket.windowElapsed = true;
96
+ bucket.forcedReason = reason;
97
+ if (bucket.pendingOutcomes.size > 0) {
98
+ await Promise.all([...bucket.pendingOutcomes]);
99
+ }
100
+ await (bucket.commitPromise ?? this.tryCommit(key, reason));
101
+ }
102
+ /** 冲刷全部窗口(/exit、/restart 干净退出前调用)。 */
103
+ async flushAll(reason = 'flush') {
104
+ const buckets = [...this.buckets.values()];
105
+ await Promise.all(buckets.map((b) => this.flush(b.userId, b.chatId, reason)));
106
+ }
107
+ /** 进程退出:丢弃定时器,避免悬挂。 */
108
+ dispose() {
109
+ this.disposed = true;
110
+ for (const bucket of this.buckets.values()) {
111
+ if (bucket.timer !== undefined)
112
+ this.clearTimer(bucket.timer);
113
+ }
114
+ this.buckets.clear();
115
+ }
116
+ ensureBucket(key, event) {
117
+ const existing = this.buckets.get(key);
118
+ if (existing)
119
+ return existing;
120
+ const bucket = {
121
+ userId: event.userId,
122
+ chatId: event.chatId,
123
+ texts: [],
124
+ attachments: [],
125
+ rejected: [],
126
+ messageIds: [],
127
+ pendingOutcomes: new Set(),
128
+ windowElapsed: false,
129
+ committed: false,
130
+ };
131
+ this.buckets.set(key, bucket);
132
+ return bucket;
133
+ }
134
+ pushRejected(bucket, item) {
135
+ const dup = bucket.rejected.some((r) => r.sourceMsgId === item.sourceMsgId && r.reason === item.reason);
136
+ if (!dup)
137
+ bucket.rejected.push(item);
138
+ }
139
+ armTimer(key, bucket) {
140
+ if (bucket.timer !== undefined)
141
+ this.clearTimer(bucket.timer);
142
+ bucket.windowElapsed = false;
143
+ bucket.timer = this.setTimer(() => {
144
+ bucket.timer = undefined;
145
+ bucket.windowElapsed = true;
146
+ if (bucket.pendingOutcomes.size > 0)
147
+ return; // 等 in-flight 下载落定
148
+ void this.tryCommit(key, bucket.forcedReason ?? 'idle');
149
+ }, this.windowMs);
150
+ }
151
+ /**
152
+ * 登记一次 in-flight 媒体下载:落定后合并结果,并在窗口已到期时触发 commit。
153
+ * 下载异常(含超时)记入 rejected,不阻断本 turn 的其它内容。
154
+ */
155
+ trackMediaOutcome(bucket, key, messageId, outcome) {
156
+ const tracked = Promise.resolve(outcome)
157
+ .then((result) => {
158
+ bucket.attachments.push(...result.attachments);
159
+ for (const item of result.rejected)
160
+ this.pushRejected(bucket, item);
161
+ }, (err) => {
162
+ this.pushRejected(bucket, {
163
+ kind: 'file',
164
+ reason: `下载失败: ${err?.message ?? String(err)}`,
165
+ sourceMsgId: messageId,
166
+ });
167
+ })
168
+ .then(() => {
169
+ bucket.pendingOutcomes.delete(tracked);
170
+ if (bucket.windowElapsed && bucket.pendingOutcomes.size === 0 && !bucket.committed) {
171
+ void this.tryCommit(key, bucket.forcedReason ?? 'idle');
172
+ }
173
+ });
174
+ bucket.pendingOutcomes.add(tracked);
175
+ }
176
+ tryCommit(key, reason) {
177
+ const bucket = this.buckets.get(key);
178
+ if (!bucket || bucket.committed)
179
+ return Promise.resolve();
180
+ if (bucket.pendingOutcomes.size > 0)
181
+ return Promise.resolve();
182
+ bucket.committed = true;
183
+ this.buckets.delete(key);
184
+ if (bucket.timer !== undefined) {
185
+ this.clearTimer(bucket.timer);
186
+ bucket.timer = undefined;
187
+ }
188
+ const promise = this.commit(bucket, reason);
189
+ bucket.commitPromise = promise;
190
+ return promise;
191
+ }
192
+ async commit(bucket, reason) {
193
+ const noText = bucket.texts.length === 0;
194
+ const turn = {
195
+ userId: bucket.userId,
196
+ chatId: bucket.chatId,
197
+ replyToMessageId: bucket.replyToMessageId,
198
+ texts: bucket.texts,
199
+ attachments: bucket.attachments,
200
+ rejected: bucket.rejected,
201
+ messageIds: bucket.messageIds,
202
+ commitReason: noText ? 'no-text' : reason,
203
+ };
204
+ const ctx = {
205
+ userId: bucket.userId,
206
+ chatId: bucket.chatId,
207
+ messageId: bucket.messageIds[bucket.messageIds.length - 1] ?? '',
208
+ };
209
+ try {
210
+ if (noText) {
211
+ // 决策 2:纯附件不自动起 turn,只回执并引导用户说一句话。
212
+ const text = buildReceipt({
213
+ saved: bucket.attachments.map((a) => a.path),
214
+ rejected: bucket.rejected,
215
+ startWorkHint: true,
216
+ });
217
+ if (text)
218
+ await this.deps.onReceipt?.(ctx, text);
219
+ return;
220
+ }
221
+ await this.deps.onCommit(turn, buildPrompt(turn));
222
+ if (bucket.rejected.length > 0) {
223
+ const text = buildReceipt({ saved: [], rejected: bucket.rejected, startWorkHint: false });
224
+ if (text)
225
+ await this.deps.onReceipt?.(ctx, text);
226
+ }
227
+ }
228
+ catch (err) {
229
+ getLogger().error('[inbound] turn commit failed:', err?.message ?? String(err));
230
+ }
231
+ }
232
+ }
233
+ //# sourceMappingURL=turn-assembler.js.map
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 统一入站回合(InboundTurn)模型。
3
+ *
4
+ * 设计依据:`docs/zh/architecture/inbound-unified-input-design.md` §4。
5
+ * 核心不变量:**一个用户意图 = 一个 turn**,且任何进 agent 的内容都必须已落到本地路径。
6
+ */
7
+ /** 附件种类(命名/展示语义)。与下载语义 `InboundMediaItem.type` 分离(§5.3)。 */
8
+ export type AttachmentKind = 'image' | 'file' | 'video' | 'audio' | 'sticker';
9
+ export interface InboundAttachment {
10
+ /** 绝对路径(落盘后位置)。 */
11
+ path: string;
12
+ kind: AttachmentKind;
13
+ /** 来源飞书 messageId:下载凭据的一部分,也是排障锚点。 */
14
+ sourceMsgId: string;
15
+ /** 原始文件名(有则保留,用于 prompt 标注与排障)。 */
16
+ originalName?: string;
17
+ /** 视频/语音时长(毫秒)。 */
18
+ durationMs?: number;
19
+ }
20
+ /** 拿不到、不支持、超限、失败的项 —— 需要回执给人(不进 agent)。 */
21
+ export interface RejectedItem {
22
+ /** 原 msg_type / 占位符种类 / 资源种类。 */
23
+ kind: string;
24
+ /** 面向人的说明。 */
25
+ reason: string;
26
+ sourceMsgId: string;
27
+ }
28
+ /** 提交原因,用于观测与测试断言。 */
29
+ export type CommitReason = 'idle' | 'timeout' | 'flush' | 'no-text';
30
+ export interface InboundTurn {
31
+ userId: string;
32
+ chatId: string;
33
+ replyToMessageId?: string;
34
+ /** 用户文本片段,按到达顺序;已剥离结构占位符。 */
35
+ texts: string[];
36
+ /** 已落盘的附件(绝对路径),按到达顺序。 */
37
+ attachments: InboundAttachment[];
38
+ rejected: RejectedItem[];
39
+ /** 本 turn 覆盖的飞书 messageId(回执、去重、排障)。 */
40
+ messageIds: string[];
41
+ commitReason: CommitReason;
42
+ }
43
+ /** 媒体下载 + 落盘的结果(装配器等待它落定后才 commit)。 */
44
+ export interface MediaOutcome {
45
+ attachments: InboundAttachment[];
46
+ rejected: RejectedItem[];
47
+ }
48
+ export declare function bucketKey(userId: string, chatId: string): string;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * 统一入站回合(InboundTurn)模型。
3
+ *
4
+ * 设计依据:`docs/zh/architecture/inbound-unified-input-design.md` §4。
5
+ * 核心不变量:**一个用户意图 = 一个 turn**,且任何进 agent 的内容都必须已落到本地路径。
6
+ */
7
+ export function bucketKey(userId, chatId) {
8
+ return `${userId}:${chatId}`;
9
+ }
10
+ //# sourceMappingURL=turn.js.map
package/dist/index.js CHANGED
@@ -24,6 +24,8 @@ import { startSleepBlocker } from './platform/sleep-blocker.js';
24
24
  import { checkLatestVersion, isNewer, runInstallLatest, formatUpdateHint } from './update/index.js';
25
25
  import { classifyRejection } from './error-classification.js';
26
26
  import { WorkspaceStore } from './workspace/index.js';
27
+ import { InboundTurnAssembler } from './inbound/turn-assembler.js';
28
+ import { stripPlaceholders } from './inbound/placeholder.js';
27
29
  import { buildSessionHistoryCard } from './router/card-helpers.js';
28
30
  import { newSessionButton, resumeCompactButton, agentDisplayName } from './card/card-shared.js';
29
31
  import path from 'node:path';
@@ -197,6 +199,12 @@ function initializeRunner(config, configDir, cliArgs) {
197
199
  model,
198
200
  sessionReader: opencodeSessionReader,
199
201
  mode: ocConfig?.mode ?? 'build',
202
+ binary: ocConfig?.acp?.binary,
203
+ requestTimeoutMs: ocConfig?.acp?.requestTimeoutMs,
204
+ idleTtlMs: ocConfig?.acp?.idleTtlMs,
205
+ turnIdleTimeoutMs: ocConfig?.acp?.turnIdleTimeoutMinutes != null
206
+ ? ocConfig.acp.turnIdleTimeoutMinutes * 60_000
207
+ : undefined,
200
208
  });
201
209
  });
202
210
  sessionReaderRegistry.register('opencode', opencodeSessionReader);
@@ -292,9 +300,48 @@ function initializeRunner(config, configDir, cliArgs) {
292
300
  }
293
301
  /** Setup message and card action handlers. */
294
302
  function setupMessageHandlers(connector, router, bridge, sessionStore, workspaceStore, binder, logger, config, cloneSession) {
295
- // 入站媒体(图片/文件):先认证后下载(P1 review 修复)。
303
+ // 入站统一装配器(2026-09-15):图/文任意顺序 → 同一个 turn、同一个 prompt,
304
+ // 附件路径统一注入 prompt;无文本纯附件只回执(决策 2)。
305
+ const assembler = new InboundTurnAssembler({
306
+ onCommit: (turn, prompt) => {
307
+ // 入队时刻(T0)快照 workspace + agent/session 绑定,语义与旧路径一致
308
+ // (排队期间 /cd、/config 不再导致语义漂移)。
309
+ const messageId = turn.messageIds[turn.messageIds.length - 1] ?? '';
310
+ const ctx = { userId: turn.userId, chatId: turn.chatId, messageId };
311
+ let workspace = sessionStore.getCwd(turn.userId) ?? '';
312
+ if (!workspace && workspaceStore) {
313
+ const workspaces = workspaceStore.list();
314
+ if (workspaces.length > 0)
315
+ workspace = workspaces[0].path;
316
+ }
317
+ const binding = bridge.currentBinding(turn.userId);
318
+ bridge.enqueue(workspace, async () => {
319
+ // allowCommandPrefix: false —— prompt 已剥离占位符,绝不再做命令分发。
320
+ await router.handle(prompt, ctx, {
321
+ cwdOverride: workspace,
322
+ binding,
323
+ allowCommandPrefix: false,
324
+ });
325
+ }, {
326
+ taskMeta: {
327
+ userId: turn.userId,
328
+ chatId: turn.chatId,
329
+ messageId,
330
+ messagePreview: prompt.slice(0, 3000),
331
+ binding,
332
+ },
333
+ });
334
+ },
335
+ onReceipt: async (ctx, text) => {
336
+ await bridge.sendResult({ text }, ctx);
337
+ },
338
+ });
339
+ router.setInboundFlusher(() => assembler.flushAll('flush'));
340
+ // 入站媒体(图片/文件/视频/语音/表情):先认证后下载(P1 review 修复)。
296
341
  // connector 只上报"媒体到达",这里先过 owner + enabled 闸门,通过后才
297
342
  // 下载——未认证/关闭配置时不会发生任何网络下载或内存/磁盘占用。
343
+ // 下载是异步的:立刻把在途 promise 交给装配器(`kind: 'media'`),
344
+ // 保证「先图后文」不会先提交一个只含文本的 turn。
298
345
  connector.setInboundMediaDetectedHandler((msg) => {
299
346
  if (!binder.isOwner(msg.userId)) {
300
347
  logger.warn(`[media] rejected inbound media from non-owner ${msg.userId}`);
@@ -304,35 +351,45 @@ function setupMessageHandlers(connector, router, bridge, sessionStore, workspace
304
351
  // 启动时捕获的 config 参数会过期(P2 review 修复)。
305
352
  if (!router.config.inboundMedia.enabled) {
306
353
  // 不静默(P3 review):关闭时给 owner 明确反馈,避免发图后无任何反应。
307
- // 不下载、不落盘,只回一条说明。
308
- void bridge
309
- .sendResult({
310
- text: '⚠️ 入站媒体保存已关闭(inboundMedia.enabled: false),未保存文件。' +
311
- '如需自动保存图片/文件,请开启后重试',
312
- }, {
354
+ // 不下载、不落盘,只进 rejected(随 turn 回执一起发出)。
355
+ assembler.ingest({
356
+ kind: 'rejected',
313
357
  userId: msg.userId,
314
358
  chatId: msg.chatId,
315
359
  messageId: msg.messageId,
316
- })
317
- .catch((err) => logger.error('[media] disabled feedback send failed:', err));
360
+ replyToMessageId: msg.replyToMessageId,
361
+ rawContentType: msg.rawContentType,
362
+ rejectedKind: 'file',
363
+ reason: '入站媒体保存已关闭(inboundMedia.enabled: false),未保存文件。' +
364
+ '如需自动保存图片/文件,请开启后重试',
365
+ });
318
366
  return;
319
367
  }
320
- void (async () => {
368
+ const outcome = (async () => {
321
369
  const payload = await connector.downloadInboundMedia(msg, {
322
370
  maxFileSizeMb: router.config.inboundMedia.maxFileSizeMb,
323
371
  });
324
372
  try {
325
- await bridge.onInboundMedia(payload);
373
+ return await bridge.saveInboundMedia(payload);
326
374
  }
327
375
  catch (err) {
328
- // handle() 的正常路径会清理临时文件;这里兜底 handle 进入 mkdir
376
+ // save() 的正常路径会清理临时文件;这里兜底 save 进入 mkdir
329
377
  // try 之前意外抛错的情况,避免 os.tmpdir 残留。
330
378
  for (const item of payload.media) {
331
379
  silentlyUnlink(item.tempPath);
332
380
  }
333
381
  throw err;
334
382
  }
335
- })().catch((err) => logger.error('[media] inbound media download/save failed:', err));
383
+ })();
384
+ assembler.ingest({
385
+ kind: 'media',
386
+ userId: msg.userId,
387
+ chatId: msg.chatId,
388
+ messageId: msg.messageId,
389
+ replyToMessageId: msg.replyToMessageId,
390
+ rawContentType: msg.rawContentType,
391
+ outcome,
392
+ });
336
393
  });
337
394
  connector.setMessageHandler((msg) => {
338
395
  // 绑定/授权闸门:仅 owner 放行;非 owner 静默丢弃;未绑定时首条消息(任意内容)认领
@@ -387,10 +444,7 @@ function setupMessageHandlers(connector, router, bridge, sessionStore, workspace
387
444
  return;
388
445
  }
389
446
  // decision.kind === 'owner':正常处理(不再每条覆盖 startup-contact)
390
- logger.info(`message from ${msg.userId}: ${msg.content.slice(0, 100)}`);
391
- // 文本到达先冲刷待合批的媒体保存提示(先图后文字时文字到达
392
- // 先冲刷批次,避免合批提示被后续消息淹没/丢图)。
393
- bridge.flushMediaNotifications(msg.userId, msg.chatId);
447
+ logger.info(`message from ${msg.userId} (${msg.rawContentType}): ${msg.content.slice(0, 100)}`);
394
448
  // Add Typing reaction to indicate "still alive"
395
449
  void connector.addReaction(msg.messageId, 'Typing');
396
450
  // 复制分身流程活跃期:一切消息先经 clone 状态机(stop 命令除外,保留其
@@ -425,67 +479,38 @@ function setupMessageHandlers(connector, router, bridge, sessionStore, workspace
425
479
  })().catch((err) => logger.error('[control] /stop failed:', err));
426
480
  return;
427
481
  }
428
- if (content.trim().startsWith('/')) {
429
- void router
430
- .handle(content, {
431
- userId: msg.userId,
432
- chatId: msg.chatId,
433
- messageId: msg.messageId,
434
- })
435
- .catch((err) => logger.error('[control] slash command failed:', err));
436
- return;
482
+ // 先清洗,后判语义(§5.6):结构占位符永远不能触发命令分发。
483
+ // `![image](img_v3_…)` 的首字符恰好是 `!` —— 2026-09-15 事故就是这么进 shell 的。
484
+ const stripped = stripPlaceholders(content);
485
+ if (stripped.unknownTags.length > 0) {
486
+ logger.warn(`[inbound] unknown placeholder tags stripped: ${stripped.unknownTags.join(', ')} ` +
487
+ `(msg_type=${msg.rawContentType})`);
437
488
  }
438
- // `!` bash commands bypass the serial queue: they don't start claude and
439
- // don't touch session state, so they must run in parallel with claude runs
440
- // in the same workspace (design.md §9.6: the queue exists to prevent
441
- // concurrent claude runs, not to serialize bash). router.handle dispatches
442
- // `!` to bridge.executeBash, which tracks the run independently.
443
- if (content.trim().startsWith('!')) {
489
+ const commandEligible = msg.rawContentType === 'text' && stripped.kinds.length === 0 && stripped.clean !== '';
490
+ // 命令消息旁路装配窗口:其它 /命令 立即执行,窗口内已装配的内容
491
+ // 作为独立提交冲刷(/stop 已在上面处理,立即生效不等待)。
492
+ if (commandEligible && (stripped.clean.startsWith('/') || stripped.clean.startsWith('!'))) {
493
+ void assembler.flush(msg.userId, msg.chatId, 'flush');
444
494
  void router
445
- .handle(content, {
495
+ .handle(stripped.clean, {
446
496
  userId: msg.userId,
447
497
  chatId: msg.chatId,
448
498
  messageId: msg.messageId,
449
- })
450
- .catch((err) => logger.error('[control] bang command failed:', err));
499
+ }, { allowCommandPrefix: true })
500
+ .catch((err) => logger.error('[control] command failed:', err));
451
501
  return;
452
502
  }
453
- // Compute workspace with same fallback logic as executeBash:
454
- // 1. sessionStore cwd → 2. first saved workspace
455
- let workspace = sessionStore.getCwd(msg.userId) ?? '';
456
- if (!workspace && workspaceStore) {
457
- const workspaces = workspaceStore.list();
458
- if (workspaces.length > 0) {
459
- // NOTE: fallback uses insertion order, not sort preference — by design
460
- // (cwd fallback stays insertion-order for now)
461
- workspace = workspaces[0].path;
462
- }
463
- }
464
- // Step4/D4: 入队时刻(T0)快照 agent+session,随任务闭包带到 T1 执行时刻,
465
- // 避免排队期间 /new、/config 改写 live 状态导致语义漂移(方案 D4)。唯一
466
- // 捕获点 Bridge.currentBinding。
467
- const binding = bridge.currentBinding(msg.userId);
468
- bridge.enqueue(workspace, async () => {
469
- await router.handle(content, {
470
- userId: msg.userId,
471
- chatId: msg.chatId,
472
- messageId: msg.messageId,
473
- },
474
- // P1-14: lane 与执行 cwd 同源 —— 入队时捕获的 workspace 显式传给
475
- // forwardToClaude,排队期间 /cd 不再导致旧 lane 消息被 busy-drop。
476
- // D4/Step4: binding 同源 —— 入队时快照的 agent+session 一并透传,
477
- // 排队期间 /new、/config 不再导致旧 lane 消息语义漂移。
478
- { cwdOverride: workspace, binding });
479
- }, {
480
- taskMeta: {
481
- userId: msg.userId,
482
- chatId: msg.chatId,
483
- messageId: msg.messageId,
484
- messagePreview: content.slice(0, 3000),
485
- // D3/Step4: binding 随 taskMeta 存进 QueuedTask,供替换闭包
486
- // (queue.edit/queue.immediate)复用,不重新快照。
487
- binding,
488
- },
503
+ // 普通消息:进装配器,等静默期窗口到期(下载落定)后合并成一个 turn。
504
+ assembler.ingest({
505
+ kind: 'text',
506
+ userId: msg.userId,
507
+ chatId: msg.chatId,
508
+ messageId: msg.messageId,
509
+ replyToMessageId: msg.replyToMessageId,
510
+ rawContentType: msg.rawContentType,
511
+ text: stripped.clean,
512
+ placeholders: stripped.kinds,
513
+ unknownTags: stripped.unknownTags,
489
514
  });
490
515
  });
491
516
  connector.setCardActionHandler(async (action) => {
@@ -2,7 +2,7 @@
2
2
  * OpenCode config builder — builds fields and handles field changes for OpenCode agent.
3
3
  */
4
4
  import type { AgentConfigCardBuilder, ConfigField } from './types.js';
5
- import type { AppConfig } from '../../config/index.js';
5
+ import { type AppConfig } from '../../config/index.js';
6
6
  export declare class OpencodeConfigBuilder implements AgentConfigCardBuilder {
7
7
  buildFields(displayConfig: AppConfig): ConfigField[];
8
8
  handleFieldChange(key: string, value: unknown, config: AppConfig): Array<{