Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugin): 订阅槽新增 activity topic,向插件暴露思考/审批/等待输入边界 (#1283)
zhanghengxd264a35b119c6
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 69e0a72ea5..d5661491c6 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -32,10 +32,14 @@ describe('maker:event hot path ordering', () => {'registration.disposers.push(session.onStatusChange((status) => {',);// #1286:拆线(实例替换 / 会话关闭)必须给插件补 did-turn-end,否则订阅方的- // 「AI 在忙」外层状态永久卡在 working,除重启没有自愈手段。- expect(wireSessionSource).toContain(- 'registration.disposers.push(() => ghostSessionTap.dispose());',- );+ // 「AI 在忙」外层状态永久卡在 working,除重启没有自愈手段。同一个 disposer 里+ // 摘 interaction observer(#1283),不摘会让 activity 的审批边界发给已拆线的 tap。+ const tapDisposerIndex = wireSessionSource.indexOf('ghostSessionTap.dispose();');+ expect(tapDisposerIndex).toBeGreaterThanOrEqual(0);+ expect(+ wireSessionSource.lastIndexOf('registration.disposers.push(', tapDisposerIndex),+ ).toBeGreaterThanOrEqual(0);+ expect(wireSessionSource).toContain('installInteractionLifecycleObserver(session, null);');});it('broadcasts EVENT before usage/context/island/idle side effects', () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex b1e4e1b5f6..cd3dff6ebd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -570,6 +570,11 @@ describe('FORGE_GUIDE', () => {'cindy.confirm','只代表问到了,答案看','全局同时只有一个确认框',+ '"turn", "session", "activity"',+ 'did-thinking-{start,end}',+ 'did-approval-{start,end}',+ 'did-user-input-{start,end}',+ '不会给 reasoning、工具',]) {expect(FORGE_GUIDE).toContain(marker);}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.tsindex be72317e11..e8896fc18c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts@@ -2,17 +2,22 @@* subscriptionGateway.test.ts — 订阅槽网关单测(纯 DI,假时钟,无 Electron)。* 覆盖:did- 扇出(topic 白名单/停用忽略)、熄灯缓冲+唤醒补投+溢出丢最旧* 带 dropped、seq 单调;will- 串行短路、超时 fail-open、熔断降级、verdict- * 归属校验、reason 截断;turn 翻译器状态机与 usage 归一化。+ * 归属校验、reason 截断;turn 翻译器状态机与 usage 归一化;activity 边界配对与轮次来源过滤。*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {GhostSubscriptionGateway,+ GhostActivityTracker,+ GhostTapPendingQueue,+ GhostTurnOriginTracker,GhostTurnTranslator,createGhostSessionFocusTracker,+ ghostActivityId,isGhostEligibleSessionRow,normalizeTurnUsage,+ readStatusIsRunning,type GhostSubscriptionGatewayDeps,} from '../subscriptionGateway';import {@@ -80,10 +85,30 @@ describe('did- 旁听扇出', () => {running.add('b');gw.publish('turn', 'did-turn-start', TURN_DATA);gw.publish('turn', 'did-turn-end', { ...TURN_DATA, durationMs: 5, endReason: 'completed' });+ gw.publish('activity', 'did-thinking-start', { sessionId: 's1', blockId: 'ignored' });expect(sent.map((s) => s.ghostId)).toEqual(['a', 'a']);expect(sent.map((s) => (s.payload as { seq: number }).seq)).toEqual([1, 2]);});+ it('activity topic 复用同一扇出/seq/buffer/wake 管道', async () => {+ const { gw, sent, running, deps } = makeGateway({+ listGhosts: () => [ghost('a', { topics: ['activity'] })],+ });+ gw.publish('activity', 'did-thinking-start', { sessionId: 's1', blockId: 'b1' });+ expect(sent).toHaveLength(0);+ await vi.waitFor(() => expect(sent).toHaveLength(1));+ expect(deps.wake).toHaveBeenCalledOnce();+ expect(sent[0]?.payload).toMatchObject({+ topic: 'activity',+ name: 'did-thinking-start',+ seq: 1,+ data: { sessionId: 's1', blockId: 'b1' },+ });+ running.add('a');+ gw.publish('activity', 'did-thinking-end', { sessionId: 's1', blockId: 'b1' });+ expect(sent[1]?.payload).toMatchObject({ topic: 'activity', seq: 2 });+ });+it('熄灯缓冲:事件触发唤醒,醒后按序补投', async () => {const { gw, sent, deps } = makeGateway();gw.publish('turn', 'did-turn-start', TURN_DATA);@@ -118,6 +143,117 @@ describe('did- 旁听扇出', () => {});});+describe('GhostActivityTracker', () => {+ /** 出网关的标识都是投影值(见 ghostActivityId);断言用同一个投影算,不写死哈希。 */+ const aid = (upstreamId: string) => ghostActivityId('s1', upstreamId);++ it('按 thinking blockId 边界只发元数据,不发正文', () => {+ const events: Array<{ name: string; data: unknown }> = [];+ const tracker = new GhostActivityTracker({+ sessionId: 's1',+ sink: { activity: (name, data) => events.push({ name, data }) },+ });+ tracker.beginTurn();+ tracker.handleEvent({ type: 'thinking', data: { stage: 'start', blockId: 'b1' } });+ tracker.handleEvent({ type: 'thinking', data: { stage: 'delta', blockId: 'b1', text: 'secret reasoning' } });+ tracker.handleEvent({ type: 'thinking', data: { stage: 'final', blockId: 'b1', text: 'secret reasoning' } });+ tracker.handleEvent({ type: 'thinking', data: { stage: 'final', blockId: 'b1', text: 'duplicate' } });+ expect(events).toEqual([+ { name: 'did-thinking-start', data: { sessionId: 's1', blockId: aid('b1') } },+ { name: 'did-thinking-end', data: { sessionId: 's1', blockId: aid('b1') } },+ ]);+ expect(events.some((event) => JSON.stringify(event).includes('secret reasoning'))).toBe(false);+ // 上游原值不外泄:投影后与 'b1' 不同(sessionId 保持明文,它是跨 topic 关联键)。+ expect(events.some((event) => JSON.stringify(event).includes('"b1"'))).toBe(false);+ });++ it('approval 与 user-input 生命周期分别映射, finishAll 给所有在场请求兜底结束', () => {+ const names: string[] = [];+ const tracker = new GhostActivityTracker({+ sessionId: 's1',+ sink: { activity: (name) => names.push(name) },+ });+ tracker.beginTurn();+ tracker.startInteraction('permission', 'p1');+ tracker.startInteraction('plan_review', 'p2');+ tracker.startInteraction('ask_user_question', 'q1');+ // 三个请求同时在场:开始阶段只有 start,谁都不被提前收口。+ expect(names).toEqual([+ 'did-approval-start',+ 'did-approval-start',+ 'did-user-input-start',+ ]);+ // 回合收口不碰审批(用户可能还在批),只有会话级 finishAll 才兜底。+ tracker.finishTurn();+ expect(names).toHaveLength(3);+ tracker.finishAll();+ expect(names.slice(3)).toEqual([+ 'did-approval-end',+ 'did-approval-end',+ 'did-user-input-end',+ ]);+ });++ it('codex 计划审批在回合终态之后开始也能完整配对', () => {+ const events: Array<{ name: string; requestId: unknown }> = [];+ const tracker = new GhostActivityTracker({+ sessionId: 's1',+ sink: {+ activity: (name, data) =>+ events.push({ name, requestId: (data as { requestId?: unknown }).requestId }),+ },+ });+ // codex 计划模式真实时序:计划 turn 的 done 先入队被消费(turn 收口),+ // runPlanReviewFlow 之后才发起 plan_review。+ tracker.beginTurn();+ tracker.finishTurn();+ tracker.startInteraction('plan_review', 'plan-1');+ // 回合已收口也必须发 start:否则插件根本不知道用户正在批计划。+ expect(events).toEqual([{ name: 'did-approval-start', requestId: aid('plan-1') }]);+ // 期间新回合开始也不能把仍在等的审批抹掉(修订 turn 由审批结果触发)。+ tracker.beginTurn();+ expect(events).toHaveLength(1);+ tracker.endInteraction('plan_review', 'plan-1');+ expect(events).toEqual([+ { name: 'did-approval-start', requestId: aid('plan-1') },+ { name: 'did-approval-end', requestId: aid('plan-1') },+ ]);+ });++ it('并发审批按 requestId 各自配对:先结束的不抹掉仍在等的', () => {+ const events: Array<{ name: string; requestId: unknown }> = [];+ const tracker = new GhostActivityTracker({+ sessionId: 's1',+ sink: {+ activity: (name, data) =>+ events.push({ name, requestId: (data as { requestId?: unknown }).requestId }),+ },+ });+ tracker.beginTurn();+ tracker.startInteraction('permission', 'a');+ tracker.startInteraction('permission', 'b');+ tracker.startInteraction('permission', 'b'); // 同 id 重复进入不重发 start+ tracker.endInteraction('permission', 'b');+ // b 已收口而 a 仍在等:此刻绝不能出现 a 的 end。+ expect(events).toEqual([+ { name: 'did-approval-start', requestId: aid('a') },+ { name: 'did-approval-start', requestId: aid('b') },+ { name: 'did-approval-end', requestId: aid('b') },+ ]);+ tracker.endInteraction('permission', 'b'); // 已收口不重发 end+ tracker.endInteraction('permission', 'a');+ expect(events).toEqual([+ { name: 'did-approval-start', requestId: aid('a') },+ { name: 'did-approval-start', requestId: aid('b') },+ { name: 'did-approval-end', requestId: aid('b') },+ { name: 'did-approval-end', requestId: aid('a') },+ ]);+ // 全部收口后 finishTurn 不再补发。+ tracker.finishTurn();+ expect(events).toHaveLength(4);+ });+});+describe('will- 拦截', () => {beforeEach(() => {vi.useFakeTimers();@@ -665,3 +801,160 @@ describe('GhostTurnTranslator(status/done/error → did-turn-*)', () => {expect(normalizeTurnUsage('x')).toBeUndefined();});});++describe('readStatusIsRunning', () => {+ it('只认 status 事件,data 形状不对按 false', () => {+ expect(readStatusIsRunning({ type: 'status', data: { isRunning: true } })).toBe(true);+ expect(readStatusIsRunning({ type: 'status', data: { isRunning: false } })).toBe(false);+ // 非布尔真值不认(避免 'true' / 1 之类被当成在跑)+ expect(readStatusIsRunning({ type: 'status', data: { isRunning: 'true' } })).toBe(false);+ expect(readStatusIsRunning({ type: 'status', data: undefined })).toBe(false);+ expect(readStatusIsRunning({ type: 'status', data: null })).toBe(false);+ // null 表示"不是轮次起点判断的对象",与 false 语义不同+ expect(readStatusIsRunning({ type: 'done', data: {} })).toBeNull();+ expect(readStatusIsRunning({ type: 'thinking', data: {} })).toBeNull();+ });+});++describe('ghostActivityId(标识对外投影)', () => {+ it('确定性:同会话同上游 id 恒定同值 —— start / end 才能配上', () => {+ expect(ghostActivityId('s1', 'req-1')).toBe(ghostActivityId('s1', 'req-1'));+ });++ it('不透传上游原值,也不含其中任何语义片段', () => {+ // codex MCP elicitation 的真实形态(codex/index.ts:4699)——serverName 拼在里头+ const upstream = 'mcp-elicitation:cindy-github:turn-7:3';+ const projected = ghostActivityId('s1', upstream);+ expect(projected).not.toBe(upstream);+ expect(projected).not.toContain('cindy-github');+ expect(projected).not.toContain('mcp-elicitation');+ // codex 计划审批前缀同样不外泄("这是计划审批"本身也是信息)+ expect(ghostActivityId('s1', 'codex-plan-review:turn-7:1')).not.toContain('plan-review');+ expect(projected).toMatch(/^[0-9a-f]{16}$/);+ });++ it('掺 sessionId:同一个上游 id 在不同会话得到不同值,不给跨会话关联留口', () => {+ expect(ghostActivityId('s1', 'req-1')).not.toBe(ghostActivityId('s2', 'req-1'));+ });++ it('不同上游 id 在同会话内不同值', () => {+ expect(ghostActivityId('s1', 'req-1')).not.toBe(ghostActivityId('s1', 'req-2'));+ });++ it('带长度前缀拼接:边界组合不撞车', () => {+ // 若直接用分隔符拼接,('s1:x','y') 与 ('s1','x:y') 之类可能拼出同一个串+ expect(ghostActivityId('s1:x', 'y')).not.toBe(ghostActivityId('s1', 'x:y'));+ });+});++describe('GhostTapPendingQueue', () => {+ const ev = (n: number) => ({ type: 'event' as const, event: { type: `e${n}` } });+ const act = (phase: 'start' | 'end', requestId: string) => ({+ type: 'activity' as const,+ phase,+ request: { kind: 'permission' as const, requestId },+ });++ it('封顶前照收,drain 取快照并清空', () => {+ const q = new GhostTapPendingQueue(3);+ q.push(ev(1));+ q.push(ev(2));+ expect(q.size).toBe(2);+ expect(q.drain().map((i) => (i.type === 'event' ? i.event.type : ''))).toEqual(['e1', 'e2']);+ expect(q.size).toBe(0);+ expect(q.dropped).toBe(0);+ });++ it('溢出丢最旧,首次溢出只回调一次', () => {+ const onFirstOverflow = vi.fn();+ const q = new GhostTapPendingQueue(2, onFirstOverflow);+ q.push(ev(1));+ q.push(ev(2));+ q.push(ev(3));+ q.push(ev(4));+ expect(q.size).toBe(2);+ expect(q.dropped).toBe(2);+ expect(onFirstOverflow).toHaveBeenCalledOnce();+ expect(q.drain().map((i) => (i.type === 'event' ? i.event.type : ''))).toEqual(['e3', 'e4']);+ });++ it('丢最旧不留孤儿 start:留下的一定是到达序的后缀', () => {+ const q = new GhostTapPendingQueue(3);+ q.push(act('start', 'p1'));+ q.push(ev(1));+ q.push(ev(2));+ // 满了:挤掉队首的 start,end 照常入队 —— 落单的 end 在下游是 no-op。+ q.push(act('end', 'p1'));+ expect(q.dropped).toBe(1);+ const items = q.drain();+ expect(items.map((i) => (i.type === 'event' ? i.event.type : i.phase))).toEqual([+ 'e1',+ 'e2',+ 'end',+ ]);+ });++ it('普通 event 与 activity 同规则:收口事件永远留在队尾,不必按类型配对压缩', () => {+ const q = new GhostTapPendingQueue(2);+ q.push(ev(1)); // thinking start+ q.push(ev(2)); // delta…+ q.push(act('start', 'p1'));+ q.push(ev(3)); // status(false) / done 这类终态+ expect(q.dropped).toBe(2);+ expect(q.drain().map((i) => (i.type === 'event' ? i.event.type : i.phase))).toEqual([+ 'start',+ 'e3',+ ]);+ });+});++describe('GhostTurnOriginTracker', () => {+ it('缺省放行用户 Desktop:首个轮次起点到达前也认', () => {+ const origin = new GhostTurnOriginTracker();+ expect(origin.acceptsInteraction(undefined)).toBe(true);+ expect(origin.acceptsInteraction({ origin: { kind: 'desktop' } })).toBe(true);+ });++ it('非 desktop route 直接挡掉(IM / hook 的 channel-card / headless 面)', () => {+ const origin = new GhostTurnOriginTracker();+ expect(origin.acceptsInteraction({ origin: { kind: 'im' } })).toBe(false);+ expect(origin.acceptsInteraction({ origin: { kind: 'hook' } })).toBe(false);+ expect(origin.acceptsInteraction({ origin: { kind: 'scheduler' } })).toBe(false);+ });++ it('goal / scheduler 直发(无 route)靠事件流上的轮次来源挡掉', () => {+ const origin = new GhostTurnOriginTracker();+ // goal 续跑:GoalController 直发 session.send,router 侧没有 route+ origin.noteEvent({ type: 'status', data: { isRunning: true }, turnOrigin: { kind: 'goal' } });+ expect(origin.acceptsInteraction(undefined)).toBe(false);+ // 轮次终态之后 origin 会被 Session 清空,但不能因此放行(codex 计划审批就在终态后)+ origin.noteEvent({ type: 'status', data: { isRunning: false } });+ origin.noteEvent({ type: 'done', data: {} });+ expect(origin.acceptsInteraction(undefined)).toBe(false);++ origin.noteEvent({+ type: 'status',+ data: { isRunning: true },+ turnOrigin: { kind: 'scheduler' },+ });+ expect(origin.acceptsInteraction(undefined)).toBe(false);+ });++ it('自动化轮次之后的用户轮次要恢复放行(不带 turnOrigin = Desktop 直发)', () => {+ const origin = new GhostTurnOriginTracker();+ origin.noteEvent({ type: 'status', data: { isRunning: true }, turnOrigin: { kind: 'goal' } });+ expect(origin.acceptsInteraction(undefined)).toBe(false);+ // Desktop 的 send 不传 origin,Session 就不会给事件打 turnOrigin+ origin.noteEvent({ type: 'status', data: { isRunning: true } });+ expect(origin.acceptsInteraction(undefined)).toBe(true);+ });++ it('只有轮次起点更新来源:轮次中途的事件不会把 goal 抹回 user', () => {+ const origin = new GhostTurnOriginTracker();+ origin.noteEvent({ type: 'status', data: { isRunning: true }, turnOrigin: { kind: 'goal' } });+ // 中途事件在 Session 清空 origin 后不带 turnOrigin,逐事件更新就会误判+ origin.noteEvent({ type: 'thinking', data: { stage: 'start', blockId: 'b1' } });+ origin.noteEvent({ type: 'assistant', data: {} });+ expect(origin.acceptsInteraction(undefined)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 8d6b09cc21..494de3b43a 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1552,7 +1552,7 @@ cindy.onHostMessage(async function (msg) {\`\`\`json"slots": [..., "subscribe"],"subscribe": {- "topics": ["turn", "session"], // did- 旁听(元数据,不含消息内容)+ "topics": ["turn", "session", "activity"], // did- 旁听(元数据,不含消息内容)"hooks": ["will-user-message", "will-assistant-message"] // will- 拦截(声明任一必须 launch:"resident")},"launch": "resident" // 拦截要求常驻在场(否则每条消息都等你冷启动)@@ -1573,6 +1573,26 @@ cindy.onHostMessage(function (msg) {return;}// did-turn-start / did-session-created / did-session-archived 同理(见 topics)。+ // activity topic 只提供内层活动边界元数据:+ // did-thinking-{start,end}: { sessionId, blockId }(不含 reasoning 正文);+ // did-approval-{start,end}: { sessionId, requestId };+ // did-user-input-{start,end}: { sessionId, requestId }。+ // approval = permission / plan_review; user-input = ask_user_question。+ // **blockId / requestId 都是主机生成的不透明配对键**,不是 agent 或 provider 侧的+ // 原始 id:只保证同一段思考 / 同一个请求的 start 与 end 拿到同一个值,同一个上游+ // 请求在不同会话里也是不同值。它们不承载任何语义(看不出是哪个工具、哪个 MCP+ // 服务、是不是计划审批),也**关联不到**主机或 provider 的任何其他标识 —— 别拿它+ // 去和你从别处拿到的 id 对齐,只用来配对。+ // **按 requestId 配对,不是全局开关**:一轮里并行工具调用可能同时挂着多个审批,+ // 每个 requestId 各发自己的 start / end。要判断"是否仍在等审批",用 requestId+ // 集合(收到 start 加入、end 移除),集合非空即仍在等;别用单个布尔位,否则先结束+ // 的那个请求会把还在等的抹掉。+ // **审批可能跨过 did-turn-end**:codex 计划模式的 plan_review 就是在计划轮次+ // 收尾之后才发起的,你会先收到 did-turn-end、再收到 did-approval-start。所以+ // 别拿 did-turn-end 去清空审批状态——只认对应 requestId 的 did-approval-end。+ // thinking 不同:它只在轮次内,did-turn-end 前主机必定先补发未收口的+ // did-thinking-end。审批 / 等待输入则由主机在真实决策落地(批准、拒绝、回答、+ // 超时、取消)时收口,会话被关闭 / 重建时也会给所有在场 requestId 各补一条 end。if (msg.name === 'did-session-switched') {// 用户把某个会话切到台前(切换会话 / 从非会话页切回都算)。// msg.data = { sessionId, workdir? }。连续停留同一会话不重发。@@ -1604,12 +1624,26 @@ cindy.onHostMessage(function (msg) {硬规则(主机代码强制):- **旁听 topic**:\`turn\`(轮次开始/结束,带 agent / 模型 / 耗时 / token 用量)、\`session\`(会话创建 / 归档 / 切换——切换 = 用户把哪个会话切到台前,连续停留- 同一会话不重发)。**只有元数据,永远不含消息内容**(v1 不开正文旁听)。- 没声明的 topic 主机不投;-- **只覆盖你自己的主会话**:orca worker、后台自动化会话不投(与你无关的噪音);+ 同一会话不重发)、\`activity\`(思考 / 审批 / 等待用户输入的开始结束边界)。+ activity 只带 \`sessionId\` + \`blockId\` 或 \`requestId\`;**不会给 reasoning、工具+ input、命令、文件内容、计划正文、问题内容或答案**。旧插件不声明 activity 时行为+ 完全不变;没声明的 topic 主机不投;+- **只覆盖你自己的主会话**:orca worker、后台自动化会话不投(与你无关的噪音)。+ 粒度到**轮次**:主会话里由 \`/goal\` 自动续跑、定时任务、hook 渠道发起的轮次不投,+ **连它们触发的审批与提问也不投**。+ 已知例外:飞书 / Slack 等渠道**接管**(attached)现有主会话代发的轮次,其+ \`did-turn-*\` 与 thinking 边界仍会投给你(该轮次在主机侧没打来源标记,这是+ \`turn\` topic 的既有行为,不是 activity 引入的);它触发的审批与提问**不会**投+ (走渠道卡的确认面,主机按面拦掉)。所以:\`did-approval-*\` /+ \`did-user-input-*\` 一定是用户本人在 Desktop 上被问到,不会出现没有对应轮次的+ 孤儿审批;但 \`did-turn-*\` / \`did-thinking-*\` 偶尔可能来自渠道代发的轮次,别把+ "有 thinking"直接等同于"用户本人正在用 Desktop";- **旁听是 fire-and-forget**:主机投完即走,你崩了/慢了不影响任何会话;熄灯期事件进队列(上限 100,溢出丢最旧,下一条带 \`dropped\` 计数),事件到达会把你按需- 拉起补投——但订阅型意识**建议 \`launch:"resident"\`**(要秒收就得在场);+ 拉起补投——但订阅型意识**建议 \`launch:"resident"\`**(要秒收就得在场)。+ **\`dropped\` 非零就必须重置你本地派生的状态**:被丢的可能正是某条+ \`did-turn-end\` 或 \`did-*-end\`,你要是继续拿旧状态往下推,就会永久停在+ "在忙 / 在等审批"。收到 \`dropped\` 时把状态清空、以此后到达的事件为准;- **钩子超时 = 放行**:\`will-\` 裁决必须 3 秒内回,超时主机按 allow 放行(聊天绝不因你卡死);连续 3 次超时/崩溃,主机**熔断**你的钩子能力(降级为只旁听 + 提示用户),旁听不受影响。要过外部合规接口就在窗口内 \`await cindy.fetch\`(networkdiff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 45f29c806a..a6af95afb4 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -164,9 +164,13 @@ import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';import { getDirDepositVault, getSaveDepositVault, isPathInsideDir } from './dirDeposit.js';import {GhostSubscriptionGateway,+ GhostActivityTracker,GhostTurnTranslator,createGhostSessionFocusTracker,+ GhostTapPendingQueue,+ GhostTurnOriginTracker,isGhostEligibleSessionRow,+ type GhostInteractionActivityKind,type GhostScreenResult,type MinimalAgentEvent,} from './subscriptionGateway.js';@@ -1186,35 +1190,75 @@ async function isGhostEligibleSession(}}+type PendingActivityRequest = {+ kind: GhostInteractionActivityKind;+ requestId: string;+};+/*** 会话事件 tap 工厂(register.ts wireSessionToIpc 对每个新会话叠加一个* onEvent 监听):把 AgentEvent 折叠成 did-turn-* 发进网关。* - 只投用户主会话(desktop、非 orca;资格 DB 现查,判定期事件小缓冲回放);- * - 自动化轮次(turnOrigin 非 user)不投——hook-control 后台会话由此天然滤除。+ * - 自动化轮次(turnOrigin 非 user)不投——hook-control 后台会话由此天然滤除;+ * - interaction 侧同样只投用户 Desktop 面(见 GhostTurnOriginTracker):非 desktop+ * route 直接挡掉,route 缺省时按事件流上记下的轮次来源挡掉 goal / scheduler。** 拆线必须调 `dispose()`:register.ts 的 disposer 一跑,事件源就没了,turn 在场时* 只有这里能给插件补上缺失的 did-turn-end(见 GhostTurnTranslator.dispose)。*/export function createGhostSessionTap(sessionId: string): {handleEvent(ev: MinimalAgentEvent & { turnOrigin?: { kind?: string } }): void;+ interactionObserver: {+ onStart(+ request: PendingActivityRequest,+ route?: { origin?: { kind?: string } },+ ): void;+ onEnd(+ request: PendingActivityRequest,+ route?: { origin?: { kind?: string } },+ ): void;+ };dispose(): void;} {let translator: GhostTurnTranslator | null = null;+ let activity: GhostActivityTracker | null = null;/** 拆线不可逆:资格判定是异步的,回调必须知道自己已经没有归属会话了。 */let disposed = false;// 资格判定**惰性化 + 可重试**:接线发生在启动重连期,DbClient 可能还没// 就绪——判定挪到第一个事件到达时(用户已在交互,DB 必然可用);暂时性// 失败(retry)不定性,下个事件再试,封顶后放弃(防怪会话反复打 DB)。let state: 'unknown' | 'resolving' | 'eligible' | 'ineligible' = 'unknown';+ // 轮次来源:interaction 侧只靠 route 判断不住 goal / scheduler(它们没 route),+ // 得从事件流上记。语义与理由见 GhostTurnOriginTracker。资格无关,恒记。+ const origin = new GhostTurnOriginTracker();let attempts = 0;const MAX_ATTEMPTS = 5;- const pending: MinimalAgentEvent[] = [];+ const MAX_PENDING = 32;+ // 有界缓冲,溢出丢最旧(留下的是到达序后缀,不留孤儿 start),语义见 GhostTapPendingQueue。+ const pending = new GhostTapPendingQueue(MAX_PENDING, () => {+ log.warn('ghost session tap pending overflow while resolving eligibility', {+ sessionId,+ cap: MAX_PENDING,+ });+ });++ const applyActivity = (+ phase: 'start' | 'end',+ request: PendingActivityRequest,+ ): void => {+ if (!activity) {+ pending.push({ type: 'activity', phase, request });+ return;+ }+ if (phase === 'start') activity.startInteraction(request.kind, request.requestId);+ else activity.endInteraction(request.kind, request.requestId);+ };const kickResolve = (): void => {if (state !== 'unknown') return;if (attempts >= MAX_ATTEMPTS) {state = 'ineligible';- pending.length = 0;+ pending.clear();return;}state = 'resolving';@@ -1229,54 +1273,109 @@ export function createGhostSessionTap(sessionId: string): {}if (info.outcome === 'ineligible') {state = 'ineligible';- pending.length = 0;+ pending.clear();return;}const gw = getGhostSubscriptionGateway();+ activity = new GhostActivityTracker({+ sessionId,+ sink: { activity: (name, data) => gw.publish('activity', name, data) },+ });translator = new GhostTurnTranslator({sessionId,agent: info.agentKind ?? 'unknown',now: () => Date.now(),sink: {- turnStart: (d) => gw.publish('turn', 'did-turn-start', d),- turnEnd: (d) => gw.publish('turn', 'did-turn-end', d),+ turnStart: (d) => {+ gw.publish('turn', 'did-turn-start', d);+ activity?.beginTurn();+ },+ turnEnd: (d) => {+ activity?.finishTurn();+ gw.publish('turn', 'did-turn-end', d);+ },},});state = 'eligible';- log.debug('ghost session tap eligible', { sessionId, replay: pending.length });- for (const ev of pending) translator.handleEvent(ev);- pending.length = 0;+ // 先取快照再回放:applyActivity 在 activity 已就绪后直投,不会再回队。+ const replay = pending.drain();+ log.debug('ghost session tap eligible', {+ sessionId,+ replay: replay.length,+ ...(pending.dropped > 0 ? { droppedPending: pending.dropped } : {}),+ });+ for (const item of replay) {+ if (item.type === 'event') {+ activity.handleEvent(item.event);+ translator.handleEvent(item.event);+ } else {+ applyActivity(item.phase, item.request);+ }+ }});};return {handleEvent(ev) {if (disposed) return;+ // 记来源要在过滤**之前**:自动化轮次的事件正是"当前轮次不是用户发起"的唯一线索。+ origin.noteEvent(ev);if (ev.turnOrigin?.kind && ev.turnOrigin.kind !== 'user') return;if (state === 'eligible') {+ activity?.handleEvent(ev);translator?.handleEvent(ev);return;}if (state === 'ineligible') return;- if (pending.length < 32) pending.push({ type: ev.type, data: ev.data, source: ev.source });+ pending.push({+ type: 'event',+ event: { type: ev.type, data: ev.data, source: ev.source },+ });kickResolve();},+ interactionObserver: {+ onStart(request, route) {+ if (state === 'ineligible') return;+ if (!origin.acceptsInteraction(route)) return;+ applyActivity('start', request);+ if (state !== 'eligible') kickResolve();+ },+ onEnd(request, route) {+ if (state === 'ineligible') return;+ void route; // 见 acceptsInteraction 注释:end 只按 requestId 配对,不过滤来源+ applyActivity('end', request);+ if (state !== 'eligible') kickResolve();+ },+ },dispose() {if (disposed) return; // 两条 disposer 路径都可能跑到,补发只做一次disposed = true;- // 补发 end 会走插件分发链路,它的异常不能打断 register.ts 的 disposer 队列- // ——实例替换路径是裸调用,后面还排着 onEvent 退订。- try {- translator?.dispose();- } catch (err) {- log.warn('ghost session tap dispose failed', {- sessionId,- error: err instanceof Error ? err.message : String(err),- });- }+ // 补发都会走插件分发链路,它们的异常不能打断 register.ts 的 disposer 队列+ // (实例替换路径是裸调用,后面还排着 onEvent 退订),也不能让 activity 侧的+ // 失败吃掉 turn 侧的补发,所以两段各自兜住。+ const guard = (stage: string, fn: () => void): void => {+ try {+ fn();+ } catch (err) {+ log.warn('ghost session tap dispose failed', {+ sessionId,+ stage,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ };+ // 先收口 activity 再收口 turn:会话关闭 / Session 实例替换时,router 里可能还有+ // interaction 等在 finally 前,而 observer 马上就会被摘掉——不补发 end 插件就会+ // 永久停在"等待审批 / 等待用户输入"。顺序也是契约:未收口的 thinking end 必须+ // 排在 did-turn-end 之前(回合边界只收口 thinking——审批可以跨回合终态,+ // 见 GhostActivityTracker)。+ guard('activity', () => activity?.finishAll());+ guard('turn', () => translator?.dispose());+ activity?.reset();translator = null;+ activity = null;+ pending.clear();state = 'ineligible';- pending.length = 0;},};}diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.tsindex 853171bf62..1e3b4f46c1 100644--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts@@ -18,7 +18,7 @@* 依赖注入(规则 14):意识清单/运行态/唤醒/投递全经 deps,单测直喂。*/-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import {GHOST_ASSISTANT_HOOK_TIMEOUT_MS,@@ -26,8 +26,12 @@ import {GHOST_HOOK_REWRITE_MAX_CHARS,GHOST_HOOK_TIMEOUT_MS,GHOST_SUB_QUEUE_MAX,+ type GhostActivityEventName,+ type GhostDidEventData,type GhostDidEventName,- type GhostEventSessionData,+ type GhostEventActivityData,+ type GhostEventInteractionActivityData,+ type GhostEventThinkingData,type GhostEventTurnEndData,type GhostEventTurnStartData,type GhostPipeEventPush,@@ -124,7 +128,7 @@ export class GhostSubscriptionGateway {publish(topic: GhostSubscribeTopic,name: GhostDidEventName,- data: GhostEventTurnStartData | GhostEventTurnEndData | GhostEventSessionData,+ data: GhostDidEventData,): void {for (const ghost of this.deps.listGhosts()) {if (!ghost.enabled) continue;@@ -147,7 +151,7 @@ export class GhostSubscriptionGateway {ghost: InstalledGhost,topic: GhostSubscribeTopic,name: GhostDidEventName,- data: GhostEventTurnStartData | GhostEventTurnEndData | GhostEventSessionData,+ data: GhostDidEventData,): void {const ghostId = ghost.manifest.id;const e = this.entry(ghostId);@@ -491,6 +495,317 @@ export interface TurnEventSink {turnEnd(data: GhostEventTurnEndData): void;}+/**+ * 读 status 事件的 isRunning。非 status 事件返回 null(供"这是不是轮次起点"判断);+ * status 但 data 形状不对按 false —— 拿不准就不算在跑。+ */+export function readStatusIsRunning(ev: MinimalAgentEvent): boolean | null {+ if (ev.type !== 'status') return null;+ if (typeof ev.data !== 'object' || ev.data === null) return false;+ return (ev.data as { isRunning?: unknown }).isRunning === true;+}++export type GhostTapPendingItem =+ | { type: 'event'; event: MinimalAgentEvent }+ | {+ type: 'activity';+ phase: 'start' | 'end';+ request: { kind: GhostInteractionActivityKind; requestId: string };+ };++/**+ * 资格判定期的有界缓冲。DB 未就绪时判定要重试,这段时间的事件先攒着,判定通过后+ * 按序回放;封顶防怪会话把内存吃干。+ *+ * 溢出策略:**丢最旧**(与网关缓冲一致)。要护住的不变量是"回放出去的流里不留孤儿+ * start" —— 没有 end 的 start 会让插件永久停在"在忙 / 在等审批",要等会话销毁才被+ * finishAll 兜底。丢最旧天然满足它:留下的永远是到达序的一个**后缀**,某个 start 还在+ * 队里就意味着它之后的一切都还在,它的 end 也在。+ *+ * 反过来落单的 end 无害 —— 三个下游状态机对它一律 no-op:translator 在 idle 收到+ * done/error 直接 return、非 running 收到 status(false) 不动;endThinking 认 blockId、+ * endInteraction 认在场 requestId。极端情况下连 status(true) 一起被挤掉,turnActive+ * 压根不置起,那一轮连 thinking 都整体静默 —— 是"少一段情节",不是"半段情节"。+ *+ * 所以这里不需要按事件类型做配对压缩:丢最新才需要(收口事件本就排在最后,首当其冲),+ * 而那要求队列认识 thinking / turn / interaction 各自的语义。+ */+export class GhostTapPendingQueue {+ private readonly items: GhostTapPendingItem[] = [];+ private droppedCount = 0;++ constructor(+ private readonly cap: number,+ /** 首次溢出回调(只回一次,避免怪会话刷爆日志)。 */+ private readonly onFirstOverflow?: () => void,+ ) {}++ get size(): number {+ return this.items.length;+ }++ get dropped(): number {+ return this.droppedCount;+ }++ push(item: GhostTapPendingItem): void {+ if (this.items.length >= this.cap) {+ this.items.shift();+ this.noteDropped(1);+ }+ this.items.push(item);+ }++ /** 取快照并清空(回放用:先清再放,回放中新到的事件不会被本轮吞掉)。 */+ drain(): GhostTapPendingItem[] {+ return this.items.splice(0, this.items.length);+ }++ clear(): void {+ this.items.length = 0;+ }++ private noteDropped(count: number): void {+ const wasEmpty = this.droppedCount === 0;+ this.droppedCount += count;+ if (wasEmpty) this.onFirstOverflow?.();+ }+}++/**+ * activity 标识的对外投影:把上游 id 换成**主机域内的不透明配对键**。+ *+ * 为什么必须投影 —— provider 侧的 id 不保证语义中立。codex 的 MCP elicitation 会把+ * 服务名拼进 requestId(`mcp-elicitation:<serverName>:…`,`codex/index.ts:4699`),+ * 计划审批带 `codex-plan-review:` 前缀(`:3838`);原样转发就等于告诉插件"正在请求+ * 哪个 MCP 服务 / 这是计划审批",与权限确认框宣称的"只知道时机、看不到待批准的操作"+ * 不符。thinking 的 blockId 今天是时间戳 / 随机 / provider item id,并不泄露,但一起+ * 投影才能让这个协议**结构上**不透传任何 provider 值 —— 上游以后往 id 里塞东西也伤+ * 不到我们,而不是依赖"我们审计过今天的形态"。+ *+ * 为什么是确定性哈希而不是分配式 ID —— 同一个上游 id 恒定映射到同一个 token,所以+ * start/end 的配对契约逐字不变,不需要映射表、不需要清理、不新增任何状态。+ * 掺 sessionId 是为了让同一个上游 id 在不同会话里得到不同 token(不给跨会话关联留口)。+ * 截 16 位十六进制 = 64 bit:单会话内标识量级 ≤ 10³,碰撞概率约 10⁻¹⁴,可忽略。+ *+ * 注意 `sessionId` 本身不投影 —— 它是 turn / session / activity 三个 topic 共用的关联键,+ * 换掉会断掉插件"把 activity 关联回哪个会话"的能力,而它本来就在 turn / session 里明文投。+ */+export function ghostActivityId(sessionId: string, upstreamId: string): string {+ // 带长度前缀拼接:两段都可能含任意分隔符,前缀保证拼接无歧义+ // (不同的 (sessionId, upstreamId) 组合不可能拼出同一个串)。+ return createHash('sha256')+ .update(`${sessionId.length}:${sessionId}:${upstreamId}`)+ .digest('hex')+ .slice(0, 16);+}++/**+ * 轮次来源跟踪:回答"这条 interaction 该不该投给插件"。+ *+ * 为什么需要它 —— interaction router 给 observer 的 `route.origin` 是另一套取值+ * (TurnPermissionOrigin: desktop / im / scheduler / hook),而且只有 hook-control 与+ * IM turnRunner 会 beginInteractionRoute。goal 续跑与 scheduler 定时任务都是直发+ * session.send,压根没有 route,光看 route 会把它们的审批 / 提问放行;而事件侧+ * (turnOrigin 非 user)又把它们的轮次事件滤掉了,插件就会收到"没有对应轮次的审批",+ * 违反作者手册"不投后台自动化"的契约。所以来源要从事件流上自己记。+ */+export class GhostTurnOriginTracker {+ /** 缺省 user:接线发生在任何轮次之前,首个轮次起点到达前按用户会话处理。 */+ private kind = 'user';++ /**+ * 只在轮次起点(status isRunning:true)更新:Session 越过 dispatch 边界后才装+ * currentTurnOrigin,provider 的 status(true) 必然带上本轮 origin;而轮次终态之后+ * origin 会被清空,逐事件更新会被 undefined 抹回 user。+ *+ * 也**不在轮次结束时复位** —— codex 计划审批就发生在轮次终态之后,复位会把它+ * 误判成用户轮次。下一个轮次起点自然会覆盖。+ */+ noteEvent(ev: MinimalAgentEvent & { turnOrigin?: { kind?: string } }): void {+ if (readStatusIsRunning(ev) === true) this.kind = ev.turnOrigin?.kind ?? 'user';+ }++ /**+ * 两道独立的门:route 存在时必须是 desktop 面(IM / hook 注册的是 channel-card /+ * headless);route 缺省即 Desktop 面,此时再看当前轮次来源挡掉 goal / scheduler。+ *+ * **只该用在 start 侧**:end 由 GhostActivityTracker 按 requestId 配对,没登记过的+ * requestId 本就是 no-op。若 end 也过滤,一旦来源在等待期间翻转(理论上被 Session+ * busy 守卫挡住,但不该依赖它),start 就会永远等不到 end。+ */+ acceptsInteraction(route?: { origin?: { kind?: string } }): boolean {+ if (route?.origin?.kind && route.origin.kind !== 'desktop') return false;+ return this.kind === 'user';+ }+}++export type GhostInteractionActivityKind =+ | 'permission'+ | 'plan_review'+ | 'ask_user_question';++export interface ActivityEventSink {+ activity(+ name: GhostActivityEventName,+ data: GhostEventActivityData,+ ): void;+}++/** interaction kind → 对插件暴露的活动类型(等待用户回答 vs 等待用户批准)。 */+function activityTypeOf(kind: GhostInteractionActivityKind): 'approval' | 'user-input' {+ return kind === 'ask_user_question' ? 'user-input' : 'approval';+}++/**+ * activity 边界状态机:同步、O(1)、不读取正文。两类活动的生命周期主人不同:+ *+ * - **thinking 归回合**:是单活跃 block 模型(vendor 的 reasoning block 串行产出,+ * 新 block 开始即代表上一个已收口),只在回合内有意义,turn 收口时强制结束。+ * - **approval / user-input 归 router,可跨回合终态**:codex 计划模式里+ * runPlanReviewFlow 是在计划 turn 把 status(false) 与 done **入队之后**才发起+ * plan_review(见 agents/codex/index.ts 的 "放在 done 之后 (AsyncQueue FIFO)"),+ * 即 done 必然先被消费。若拿 turnActive 当门控,这个审批的 start 会被直接丢掉,+ * 插件根本不知道用户正在批计划;若靠 turn 收口去补 end,又会在用户还在审批时+ * 谎报"审批结束"。所以这两类只认 SessionInteractionRouter 的 dispatch/finally+ * ——finally 保证每个 requestId 一定收口,回合边界不插手。+ *+ * 两类都按 id 集合跟踪:同一轮的并行工具调用会让多个 permission 同时等在 router+ * 里(见 SessionInteractionRouter.pending),用单值覆盖会在第二个请求开始时提前给+ * 第一个发 end。每个 id 各配一对 start/end,插件按集合非空判断是否仍在等待。+ */+export class GhostActivityTracker {+ private turnActive = false;+ private thinkingBlockId: string | null = null;+ private lastEndedThinkingBlockId: string | null = null;+ private readonly interactionRequestIds: Record<'approval' | 'user-input', Set<string>> = {+ approval: new Set(),+ 'user-input': new Set(),+ };++ constructor(private readonly opts: { sessionId: string; sink: ActivityEventSink }) {}++ beginTurn(): void {+ if (this.turnActive) this.finishTurn();+ this.turnActive = true;+ this.lastEndedThinkingBlockId = null;+ }++ handleEvent(ev: MinimalAgentEvent): void {+ if (!this.turnActive) return;+ if (ev.type !== 'thinking' || typeof ev.data !== 'object' || ev.data === null) return;+ const data = ev.data as { stage?: unknown; blockId?: unknown };+ if (typeof data.blockId !== 'string' || data.blockId.length === 0) return;+ if (+ data.stage !== 'start' &&+ data.stage !== 'delta' &&+ data.stage !== 'final' &&+ data.stage !== 'redacted'+ ) return;+ if (data.stage === 'start' || data.stage === 'delta') {+ this.startThinking(data.blockId);+ return;+ }+ if (this.thinkingBlockId !== data.blockId) {+ if (this.lastEndedThinkingBlockId === data.blockId) return;+ this.startThinking(data.blockId);+ }+ this.endThinking(data.blockId);+ }++ /** 不看 turnActive:审批可以在回合终态之后才开始(codex 计划模式),见类注释。 */+ startInteraction(kind: GhostInteractionActivityKind, requestId: string): void {+ if (!requestId) return;+ const type = activityTypeOf(kind);+ // 同一 requestId 重复进入(路由重投)不重复发 start。+ if (this.interactionRequestIds[type].has(requestId)) return;+ this.interactionRequestIds[type].add(requestId);+ this.emitInteraction(type, 'start', requestId);+ }++ endInteraction(kind: GhostInteractionActivityKind, requestId: string): void {+ const type = activityTypeOf(kind);+ // delete 返回 false = 这个 requestId 没在场(已收口或从未开始),不重复发 end。+ if (!this.interactionRequestIds[type].delete(requestId)) return;+ this.emitInteraction(type, 'end', requestId);+ }++ /** 回合收口:只结束 thinking。在场的审批交给 router 的 finally,不在这里谎报结束。 */+ finishTurn(): void {+ if (!this.turnActive) return;+ if (this.thinkingBlockId) this.endThinking(this.thinkingBlockId);+ this.lastEndedThinkingBlockId = null;+ this.turnActive = false;+ }++ /**+ * 会话级收口(tap dispose):observer 即将被摘掉,router 的 finally 再也到不了+ * 这里,所以此刻必须把仍在场的审批 / 等待输入逐个补 end,否则插件永久停在等待态。+ */+ finishAll(): void {+ this.finishTurn();+ this.finishInteraction('approval');+ this.finishInteraction('user-input');+ }++ reset(): void {+ this.turnActive = false;+ this.thinkingBlockId = null;+ this.lastEndedThinkingBlockId = null;+ this.interactionRequestIds.approval.clear();+ this.interactionRequestIds['user-input'].clear();+ }++ private startThinking(blockId: string): void {+ if (this.thinkingBlockId === blockId) return;+ if (this.thinkingBlockId) this.endThinking(this.thinkingBlockId);+ this.thinkingBlockId = blockId;+ this.lastEndedThinkingBlockId = null;+ this.opts.sink.activity('did-thinking-start', this.thinkingData(blockId));+ }++ private endThinking(blockId: string): void {+ if (this.thinkingBlockId !== blockId) return;+ this.opts.sink.activity('did-thinking-end', this.thinkingData(blockId));+ this.thinkingBlockId = null;+ this.lastEndedThinkingBlockId = blockId;+ }++ /** 给所有仍在场的 requestId 各补一条 end(仅会话级收口调用,见 finishAll)。 */+ private finishInteraction(type: 'approval' | 'user-input'): void {+ const ids = this.interactionRequestIds[type];+ if (ids.size === 0) return;+ // 先取快照再清:emit 是同步回调,清空后再遍历可避免被回调内的再入改动影响。+ const pending = [...ids];+ ids.clear();+ for (const requestId of pending) this.emitInteraction(type, 'end', requestId);+ }++ /** 内部状态一律用上游原值配对,只在**出网关那一刻**投影(见 ghostActivityId)。 */+ private thinkingData(blockId: string): GhostEventThinkingData {+ return {+ sessionId: this.opts.sessionId,+ blockId: ghostActivityId(this.opts.sessionId, blockId),+ };+ }++ private emitInteraction(+ type: 'approval' | 'user-input',+ edge: 'start' | 'end',+ requestId: string,+ ): void {+ const data: GhostEventInteractionActivityData = {+ sessionId: this.opts.sessionId,+ requestId: ghostActivityId(this.opts.sessionId, requestId),+ };+ if (type === 'approval') {+ this.opts.sink.activity(edge === 'start' ? 'did-approval-start' : 'did-approval-end', data);+ } else {+ this.opts.sink.activity(edge === 'start' ? 'did-user-input-start' : 'did-user-input-end', data);+ }+ }+}+/** 从 done 事件的 usage 里尽力抽 token 数。三种真实形态都认:* cc snake_case(input_tokens/cache_read_input_tokens…)、通用 camelCase、* codex translator 形态(promptTokens/completionTokens/cachedTokens);@@ -562,10 +877,7 @@ export class GhostTurnTranslator {};if (ev.type === 'status') {- const isRunning =- typeof ev.data === 'object' && ev.data !== null- ? (ev.data as { isRunning?: unknown }).isRunning === true- : false;+ const isRunning = readStatusIsRunning(ev) === true;if (isRunning) {// closing 期间就开新 turn:上一轮确实没等到定性事件,按中断收口。if (this.state === 'closing') this.finish(base, 'interrupted', undefined);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.tsindex 983cdcb605..2f69512a87 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts@@ -4,6 +4,7 @@ import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core'import {beginInteractionRoute,installDesktopInteractionHandler,+ installInteractionLifecycleObserver,type InteractionHandler,} from '../interactionRouter';@@ -194,6 +195,60 @@ describe('session interaction router', () => {keepPending();});+ it('notifies lifecycle observer on resolve, timeout, release, and handler throw', async () => {+ vi.useFakeTimers();+ try {+ const harness = makeSession();+ const starts: string[] = [];+ const ends: string[] = [];+ installInteractionLifecycleObserver(harness.session, {+ onStart: (request) => starts.push(request.requestId),+ onEnd: (request) => ends.push(request.requestId),+ });+ installDesktopInteractionHandler(harness.session, async (request) => {+ if (request.requestId === 'throw') throw new Error('boom');+ if (request.requestId === 'release' || request.requestId === 'timeout') {+ return new Promise<InteractionDecision>(() => {});+ }+ return { kind: 'permission', behavior: 'allow' };+ });++ await expect(harness.dispatch(permission('resolve'))).resolves.toMatchObject({ behavior: 'allow' });+ await expect(harness.dispatch(permission('throw'))).resolves.toMatchObject({+ reason: 'interaction_handler_failed',+ });+ const timeoutLease = beginInteractionRoute(harness.session, {+ route: {+ sessionId: 'session-1',+ turnId: 'timeout-observer',+ origin: { kind: 'im', channel: 'wechat' },+ interactionSurface: 'desktop',+ timeoutMs: 50,+ },+ });+ const timeoutPromise = harness.dispatch(permission('timeout'));+ await vi.advanceTimersByTimeAsync(50);+ await expect(timeoutPromise).resolves.toMatchObject({ reason: 'interaction_timeout' });+ timeoutLease.release();+ const releaseLease = beginInteractionRoute(harness.session, {+ route: {+ sessionId: 'session-1',+ turnId: 'release-observer',+ origin: { kind: 'im', channel: 'wechat' },+ interactionSurface: 'desktop',+ },+ });+ const releasePromise = harness.dispatch(permission('release'));+ await vi.waitFor(() => expect(starts).toContain('release'));+ releaseLease.release('turn_terminal');+ await expect(releasePromise).resolves.toMatchObject({ reason: 'turn_terminal' });+ expect(starts).toEqual(['resolve', 'throw', 'timeout', 'release']);+ expect(ends).toEqual(['resolve', 'throw', 'timeout', 'release']);+ } finally {+ vi.useRealTimers();+ }+ });+it('rejects overlapping routes before provider dispatch', () => {const harness = makeSession();const handle = vi.fn(async (): Promise<InteractionDecision> => ({diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.tsindex b379300783..e2adca763d 100644--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts@@ -29,6 +29,11 @@ export interface InteractionRoute {export type InteractionHandler = (request: InteractionRequest) => Promise<InteractionDecision>;+export interface InteractionLifecycleObserver {+ onStart(request: InteractionRequest, route?: InteractionRoute): void;+ onEnd(request: InteractionRequest, route?: InteractionRoute): void;+}+export interface InteractionSession {readonly id: string;setInteractionListener(listener: InteractionHandler | null): void;@@ -63,6 +68,14 @@ export interface InteractionRouteLease {release(reason?: string): void;}+function callSafely<T>(callback: () => T): T | undefined {+ try {+ return callback();+ } catch {+ return undefined;+ }+}+function safeDecision(request: InteractionRequest,reason: string,@@ -83,6 +96,7 @@ function safeDecision(class SessionInteractionRouter {private desktopHandler: InteractionHandler | null = null;+ private lifecycleObserver: InteractionLifecycleObserver | null = null;private activeRoute: ActiveRoute | null = null;private readonly pending = new Map<string, PendingRequest>();@@ -94,6 +108,22 @@ class SessionInteractionRouter {this.desktopHandler = handler;}+ setLifecycleObserver(observer: InteractionLifecycleObserver | null): void {+ this.lifecycleObserver = observer;+ }++ private notifyState(route: InteractionRoute | undefined, state: InteractionRouteState): void {+ callSafely(() => route?.onStateChange?.(state));+ }++ private notifyLifecycle(+ phase: keyof InteractionLifecycleObserver,+ request: InteractionRequest,+ route?: InteractionRoute,+ ): void {+ callSafely(() => this.lifecycleObserver?.[phase](request, route));+ }+begin(registration: RouteRegistration): InteractionRouteLease {if (registration.route.sessionId !== this.session.id) {throw new Error(@@ -121,7 +151,9 @@ class SessionInteractionRouter {for (const [requestId, pending] of this.pending) {if (pending.routeToken !== active.token) continue;const decision = safeDecision(pending.request, reason);- const handledBySurface = active.onCancel?.(requestId, decision) === true;+ const handledBySurface = callSafely(+ () => active.onCancel?.(requestId, decision) === true,+ ) === true;if (!handledBySurface) pending.cancel(decision);}},@@ -153,32 +185,36 @@ class SessionInteractionRouter {request,cancel,});- active?.route.onStateChange?.('waiting');+ this.notifyLifecycle('onStart', request, active?.route);+ this.notifyState(active?.route, 'waiting');const timeoutMs = active?.route.timeoutMs;const timeout =timeoutMs && timeoutMs > 0? setTimeout(() => {const decision = safeDecision(request, 'interaction_timeout');- const handledBySurface =- active?.onCancel?.(request.requestId, decision) === true;+ const handledBySurface = callSafely(+ () => active?.onCancel?.(request.requestId, decision) === true,+ ) === true;if (!handledBySurface) cancel(decision);}, timeoutMs): null;try {const decision = await Promise.race([handler(request), cancelled]);- active?.route.onStateChange?.(+ this.notifyState(+ active?.route,!cancelledByRouter && this.activeRoute?.token === active?.token? 'resolved': 'cancelled',);return decision;} catch {- active?.route.onStateChange?.('cancelled');+ this.notifyState(active?.route, 'cancelled');return safeDecision(request, 'interaction_handler_failed');} finally {if (timeout) clearTimeout(timeout);this.pending.delete(request.requestId);+ this.notifyLifecycle('onEnd', request, active?.route);}}}@@ -203,6 +239,13 @@ export function installDesktopInteractionHandler(routerFor(session).setDesktopHandler(handler);}+export function installInteractionLifecycleObserver(+ session: InteractionSession,+ observer: InteractionLifecycleObserver | null,+): void {+ routerFor(session).setLifecycleObserver(observer);+}+/*** Activate a non-Desktop route after Session's busy guard has admitted the* turn. A second live route is rejected so the provider cannot start with andiff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 29b7b4008f..5bafcee693 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -364,7 +364,10 @@ import {readOrcaWorkerOutputReadOnly,} from './orcaDiagnostics.js';import { createMakerSendTransaction } from './makerSendTransaction.js';-import { installDesktopInteractionHandler } from './interactionRouter.js';+import {+ installDesktopInteractionHandler,+ installInteractionLifecycleObserver,+} from './interactionRouter.js';import { registerMakerMessageDeleteHandler } from './messageDeleteHandler.js';import { normalizeUserMessage, materializeQueuedOssAttachments } from './normalizeAttachments.js';import { AGENT_ISLAND_DISPLAY_CONFIG } from '../agent-island/displayConfig.js';@@ -2729,9 +2732,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// did-turn-*。资格(用户主会话)与自动化轮次过滤都在 tap 内部,这里零逻辑。const ghostSessionTap = createGhostSessionTap(session.id);// 拆线收口:实例替换(上面的 existing.disposers)与会话关闭(下面 closed 的- // finally)两条路径都要给插件补上缺失的 did-turn-end,否则订阅方的「AI 在忙」- // 外层状态永久卡在 working。- registration.disposers.push(() => ghostSessionTap.dispose());+ // finally)两条路径都要给插件补上缺失的 did-turn-end 与在场审批的 end,否则订阅方+ // 的「AI 在忙 / 在等审批」外层状态永久卡住。observer 也在这里摘掉。+ registration.disposers.push(() => {+ ghostSessionTap.dispose();+ installInteractionLifecycleObserver(session, null);+ });registration.disposers.push(session.onEvent((event: AgentEvent) => {ghostSessionTap.handleEvent(event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },@@ -3802,6 +3808,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 注入 interaction listener (permission/ask/plan 三合一,renderer 按 kind 弹不同 UI)installDesktopInteractionListener(session);+ installInteractionLifecycleObserver(session, ghostSessionTap.interactionObserver);}/**diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 61b51fff62..0d28e05c9a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3186,6 +3186,8 @@"resident": "Always-on (starts when enabled, keeps a background process even when idle)","residentDetail": "Uses a small amount of memory while idle; the process stops immediately when it is disabled or uninstalled.","subscribeTopics": "Observes your session activity (turn and session events, no message content)",+ "subscribeActivity": "Observes when the AI is thinking and when it is waiting on you",+ "subscribeActivityDetail": "Sees only the timing: when thinking starts and ends, and when the AI is waiting for your approval or your answer. It never sees the reasoning text, the action awaiting approval, the command or file involved, the plan, the question, or your answer — and it cannot approve anything on your behalf.","subscribeHooks": "Can read, block, or rewrite the messages you send","subscribeHooksDetail": "Reviews each message before sending: it may block it or rewrite the text before it goes out; blocked messages can be edited and resent.","subscribeAssistantReply": "Can read and rewrite the AI's replies",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 94789bc3cd..930f02882a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3185,6 +3185,8 @@"resident": "常駐実行(有効化すると起動し、呼び出されなくてもバックグラウンドプロセスを維持)","residentDetail": "待機中も少量のメモリを使用します。無効化またはアンインストールすると、プロセスは直ちに終了します。","subscribeTopics": "セッションの動きを傍受(ターン・セッションイベント、メッセージ内容は含まない)",+ "subscribeActivity": "AI が思考中のタイミングと、あなたの操作を待っているタイミングを傍受",+ "subscribeActivityDetail": "分かるのはタイミングのみです。思考の開始と終了、そして AI があなたの承認や回答を待っている時点だけを把握します。思考の内容、承認待ちの操作、関係するコマンドやファイル、計画の本文、質問、あなたの回答は一切見えず、あなたの代わりに承認することもできません。","subscribeHooks": "送信するメッセージの読み取り・ブロック・書き換えが可能","subscribeHooksDetail": "送信前に各メッセージを審査します。ブロックしたり、本文を書き換えてから送信することがあります。ブロックされたメッセージは編集して再送信できます。","subscribeAssistantReply": "AI の返信を読み取り・書き換え可能",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex aa471f7604..92b931fe21 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3185,6 +3185,8 @@"resident": "상주 실행(활성화하면 시작되며 호출이 없어도 백그라운드 프로세스 유지)","residentDetail": "대기 중에도 소량의 메모리를 사용합니다. 비활성화하거나 제거하면 프로세스가 즉시 종료됩니다.","subscribeTopics": "세션 활동을 수신(턴 및 세션 이벤트, 메시지 내용 제외)",+ "subscribeActivity": "AI가 언제 생각하고 언제 사용자를 기다리는지 수신",+ "subscribeActivityDetail": "시점만 알 수 있습니다. 생각이 언제 시작되고 끝나는지, 그리고 AI가 언제 사용자의 승인이나 답변을 기다리는지만 파악합니다. 생각의 내용, 승인 대기 중인 작업, 관련된 명령과 파일, 계획 본문, 질문, 사용자의 답변은 전혀 볼 수 없으며 사용자를 대신해 승인할 수도 없습니다.","subscribeHooks": "보내는 메시지를 읽고 차단하거나 고쳐 쓸 수 있음","subscribeHooksDetail": "전송 전에 각 메시지를 검토합니다. 차단하거나 본문을 고쳐 쓴 뒤 전송할 수 있으며, 차단된 메시지는 수정 후 다시 보낼 수 있습니다.","subscribeAssistantReply": "AI의 답변을 읽고 다시 쓸 수 있음",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ec5768745d..bc21baf679 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3185,6 +3185,8 @@"resident": "常驻运行(生效后即启动,不调用也保持后台进程)","residentDetail": "空闲时也占用少量内存;停用或卸载后进程立即关闭。","subscribeTopics": "旁听你的任务动态(每轮往来与任务事件,不含消息内容)",+ "subscribeActivity": "旁听 AI 何时在思考、何时在等你",+ "subscribeActivityDetail": "只知道时机:思考何时开始与结束,以及 AI 何时在等你批准或等你回答。看不到思考内容、待批准的操作、涉及的命令与文件、计划正文、问题与你的答案,也无法代你批准。","subscribeHooks": "可读取、拦截或改写你发出的消息","subscribeHooksDetail": "发送前先经它审阅:可拦下消息,也可能改写正文后再发出;被拦的消息可编辑后重发。","subscribeAssistantReply": "可读取并重写 AI 的回复",diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 9a88fe5390..9d83b92a81 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -1339,9 +1339,9 @@ describe('ghost · subscribe 订阅详单校验(卡槽①,2026-07-12)', () => {});it('topics 合法值放行并归一化进清单', () => {- const r = validateGhostManifest(withSub({ topics: ['turn', 'session'] }));+ const r = validateGhostManifest(withSub({ topics: ['turn', 'session', 'activity'] }));expect(r.ok).toBe(true);- if (r.ok) expect(r.manifest.subscribe).toEqual({ topics: ['turn', 'session'] });+ if (r.ok) expect(r.manifest.subscribe).toEqual({ topics: ['turn', 'session', 'activity'] });});it('hooks 必须搭配 launch:"resident",否则拒装', () => {@@ -1389,6 +1389,57 @@ describe('ghost · subscribe 订阅详单校验(卡槽①,2026-07-12)', () => {}});+ it('activity 单列一项权限,从 turn 加订阅 activity 计入扩张;turn/session 清单逐字不变', () => {+ const turnOnly = validateGhostManifest(withSub({ topics: ['turn'] }));+ const withActivity = validateGhostManifest(withSub({ topics: ['turn', 'activity'] }));+ const turnAndSession = validateGhostManifest(withSub({ topics: ['turn', 'session'] }));+ expect(turnOnly.ok && withActivity.ok && turnAndSession.ok).toBe(true);+ if (!turnOnly.ok || !withActivity.ok || !turnAndSession.ok) return;++ // activity 是独立一项(带自己的 label/detail),不并进固定的 subscribe:topics。+ expect(ghostPermissionItems(withActivity.manifest).map((i) => i.key)).toContain(+ 'subscribe:topics:activity',+ );+ expect(+ ghostPermissionItems(withActivity.manifest).find((i) => i.key === 'subscribe:topics:activity'),+ ).toMatchObject({ labelKey: 'subscribeActivity', detailKey: 'subscribeActivityDetail' });++ // 存量插件更新时新增 activity 必须被权限扩张检测抓到(plugin-market 要求复核)。+ const added = diffGhostPermissionItems(turnOnly.manifest, withActivity.manifest).added;+ expect(added.map((i) => i.key)).toEqual(['subscribe:topics:activity']);++ // 只动 turn / session 的存量插件权限清单不 churn(批准状态不受影响)。+ expect(diffGhostPermissionItems(turnOnly.manifest, turnAndSession.manifest).added).toEqual([]);+ expect(ghostPermissionItems(turnAndSession.manifest).filter((i) => i.kind === 'subscribe')).toEqual(+ ghostPermissionItems(turnOnly.manifest).filter((i) => i.kind === 'subscribe'),+ );++ // 取消订阅 activity 应报为 removed。+ expect(+ diffGhostPermissionItems(withActivity.manifest, turnOnly.manifest).removed.map((i) => i.key),+ ).toEqual(['subscribe:topics:activity']);+ });++ it('纯 activity 订阅不显示 turn/session 那行:确认框不凭空多报能力', () => {+ const activityOnly = validateGhostManifest(withSub({ topics: ['activity'] }));+ expect(activityOnly.ok).toBe(true);+ if (!activityOnly.ok) return;+ const keys = ghostPermissionItems(activityOnly.manifest)+ .filter((i) => i.kind === 'subscribe')+ .map((i) => i.key);+ // 网关不会给它投 turn / session,所以固定的 subscribe:topics 一行不该出现。+ expect(keys).toEqual(['subscribe:topics:activity']);+ });++ it('订阅 session 或 turn 任一都产出旧 subscribe:topics(存量批准状态不 churn)', () => {+ for (const topics of [['turn'], ['session'], ['turn', 'session'], ['session', 'activity']]) {+ const v = validateGhostManifest(withSub({ topics }));+ expect(v.ok).toBe(true);+ if (!v.ok) return;+ expect(ghostPermissionItems(v.manifest).map((i) => i.key)).toContain('subscribe:topics');+ }+ });+it('will-assistant-message:出口钩子合法(继承 resident 要求),单列一档权限行', () => {const noResident = validateGhostManifest(withSub({ hooks: ['will-assistant-message'] }));expect(noResident.ok).toBe(false); // resident 要求 key 在 hooks 非空,自动覆盖新钩子diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 13b31ba8b1..8034bfaa04 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -439,11 +439,12 @@ export interface GhostCindyNeeds {/*** 订阅槽 did- 旁听主题(卡槽①,2026-07-12 开闸)。v1 全部是**元数据级**:* turn = 轮次开始/结束(agent/模型/耗时/用量,不含消息内容);+ * activity = 轮次内思考/审批/等待用户输入的开始结束边界(只含 id 元数据);* session = 会话创建/归档/切换(切换 = 用户把哪个会话切到台前,2026-07-13 增)。* 正文级主题(消息内容旁听)刻意不开——隐私最重,等真实场景再议,权限文案* 也要另分一档。*/-export const GHOST_SUBSCRIBE_TOPICS = ['turn', 'session'] as const;+export const GHOST_SUBSCRIBE_TOPICS = ['turn', 'session', 'activity'] as const;export type GhostSubscribeTopic = (typeof GHOST_SUBSCRIBE_TOPICS)[number];/**@@ -1704,8 +1705,30 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItif (slot === 'subscribe') {// 订阅两档分列:旁听(元数据)常规位;拦截是全部槽里权限最重的一档,// unshift 排到清单最顶(敏感项排最上)。- if (manifest.subscribe?.topics?.length) {- items.push({ key: 'subscribe:topics', kind: 'subscribe', labelKey: 'subscribeTopics' });+ const topics = manifest.subscribe?.topics;+ if (topics?.length) {+ // 旧 key 只在真订了 turn / session 时产出:纯 activity 插件不该在确认框里+ // 多出一行"旁听轮次与会话事件"——网关根本不给它投 turn / session,那行是凭空+ // 多报的能力,用户可能据此误拒。存量已批准插件必然含 turn 或 session(activity+ // 是本版新增),所以旧 key 对它们照旧产出,批准状态不 churn。+ if (topics.includes('turn') || topics.includes('session')) {+ items.push({ key: 'subscribe:topics', kind: 'subscribe', labelKey: 'subscribeTopics' });+ }+ // activity 单列一项(不并进 subscribe:topics):它暴露的是"用户此刻正被要求+ // 批准某个操作 / 正被问问题"的行为时序,比 turn / session 的统计元数据敏感+ // 一档,文案也要另讲。更要紧的是权限扩张检测——diffGhostPermissionItems 按+ // key + detail 比对,若 activity 并进固定的 subscribe:topics,已装插件从+ // topics:["turn"] 更新到 ["turn","activity"] 时 added 为空,plugin-market+ // 的复核就不会拦,用户会在毫不知情的情况下多给出审批时序。旧 key 保持原样,+ // 只声明 turn / session 的存量插件权限清单逐字不变(批准状态不 churn)。+ if (topics.includes('activity')) {+ items.push({+ key: 'subscribe:topics:activity',+ kind: 'subscribe',+ labelKey: 'subscribeActivity',+ detailKey: 'subscribeActivityDetail',+ });+ }}if (manifest.subscribe?.hooks?.length) {// 拦截钩按点分列(入口=改用户消息、出口=读并重渲 AI 回复,后者更敏感);@@ -5353,13 +5376,23 @@ export const GHOST_HOOK_FUSE_THRESHOLD = 3;* 撑爆消息;提示词优化产物通常远小于此。 */export const GHOST_HOOK_REWRITE_MAX_CHARS = 16_000;-/** did- 旁听事件名(topic 归属:turn / session)。 */+/** activity topic 的旁听事件名。 */+export type GhostActivityEventName =+ | 'did-thinking-start'+ | 'did-thinking-end'+ | 'did-approval-start'+ | 'did-approval-end'+ | 'did-user-input-start'+ | 'did-user-input-end';++/** did- 旁听事件名(topic 归属:turn / session / activity)。 */export type GhostDidEventName =| 'did-turn-start'| 'did-turn-end'| 'did-session-created'| 'did-session-archived'- | 'did-session-switched';+ | 'did-session-switched'+ | GhostActivityEventName;/** did-turn-start 载荷(全元数据,无消息内容)。 */export interface GhostEventTurnStartData {@@ -5388,6 +5421,41 @@ export interface GhostEventSessionData {workdir?: string;}+/**+ * thinking 活动边界;只暴露 blockId,不暴露 reasoning 正文。+ *+ * `blockId` 是**主机生成的不透明配对键**(见 `ghostActivityId`),不是 provider 侧原值:+ * 只保证同一段 thinking 的 start / end 拿到同一个值、不同会话不同值,不承载任何语义,+ * 也不能用来关联主机或 provider 的任何其他标识。+ */+export interface GhostEventThinkingData {+ sessionId: string;+ blockId: string;+}++/**+ * 审批/用户输入活动边界;只暴露 requestId,不暴露请求或回答内容。+ *+ * `requestId` 同样是**主机生成的不透明配对键**(见 `ghostActivityId`),不是 provider 侧+ * 原值——provider 的 id 不保证语义中立(codex 的 MCP elicitation 会把服务名拼进去),+ * 原样转发会越过"只知道时机"的隐私边界。只保证 start / end 配对。+ */+export interface GhostEventInteractionActivityData {+ sessionId: string;+ requestId: string;+}++export type GhostEventActivityData =+ | GhostEventThinkingData+ | GhostEventInteractionActivityData;++/** 所有 did- 旁听事件共享的安全元数据载荷。 */+export type GhostDidEventData =+ | GhostEventTurnStartData+ | GhostEventTurnEndData+ | GhostEventSessionData+ | GhostEventActivityData;+/*** 下行:主机 → 意识的事件推送(经管子 onHostMessage 到达)。* did- 分支带 topic/seq(每意识单调递增,可自查漏收;dropped = 上一段@@ -5402,7 +5470,7 @@ export type GhostPipeEventPush =seq: number;ts: number;dropped?: number;- data: GhostEventTurnStartData | GhostEventTurnEndData | GhostEventSessionData;+ data: GhostDidEventData;}| {type: 'event';diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 9fd26a2e8d..049af2996b 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -204,6 +204,17 @@权限原样不扩权、来源记日志),本地包要有"不必重新提供原始包、但仍逐条确认"的恢复路径,格式 bump 走"按旧编码核对 → 原地升级"而不是 fail closed。不得再把一次内部机制升级变成全体用户重新确认。+- **manifest 枚举扩展在客户端降级方向不兼容(#1283 披露)。** `validateGhostManifest()`+ 对 `slots` / `subscribe.topics` 的未知枚举值、以及 `schemaVersion` 不等于 2,都是整份+ 判无效(`return { ok: false }`);而 `GhostManager.list()` 每次调用都重新校验已装目录,+ 无效即 `continue` 跳过。所以用户把客户端**降级**到某个枚举值引入之前的版本后,声明了该值+ 的插件会从已装列表**整个消失**(不是能力降级)——界面上看不到、无从修复,已存凭证与偏好+ 变成孤儿。这不是某次扩展的疏漏:校验器只在**字段**级向前兼容(「宽进严出:忽略未知字段」),+ 不在**取值**级向前兼容,历史上每次新增卡槽都有同样特征。已发布的旧版无法追改,唯一可行+ 方向是让**新版**把未知枚举值降级为「忽略 + warn」而非整份拒绝,使此后的扩展天然降级安全+ (救不了「从引入版降到引入前」那一段,任何方案都救不了)。改动方向本身要过第 5 节红线+ 评估:放宽校验等于让主机接受读不全的权限声明,不能顺手做。**触及 `validateGhostManifest()`+ 的枚举白名单、或 `GhostManager.list()` 的跳过逻辑时必须一并考虑。**- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机