Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(ghost): expose model in message hooks (#2178)

天魔e6cb8b6fcc1b
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 7ea61f71e9..98fb20493a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -773,6 +773,7 @@ describe('FORGE_GUIDE', () => {
'notify 槽',
'will-user-message',
'will-assistant-message',
+ '同轮插话(steer)时是当前运行中 turn 的模型 id',
'event-verdict',
'data-ghost-action',
'data-ghost-prompt',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts
index 6859cb223d..8d9a518b1d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts
@@ -18,6 +18,9 @@ import {
isGhostEligibleSessionRow,
normalizeTurnUsage,
readStatusIsRunning,
+ resolveGhostUserHookModel,
+ withGhostAssistantHookModel,
+ withGhostUserHookModel,
type GhostSubscriptionGatewayDeps,
} from '../subscriptionGateway';
import {
@@ -64,6 +67,7 @@ function makeGateway(overrides: Partial<GhostSubscriptionGatewayDeps> = {}) {
},
now: () => 1_000,
newHookId: () => `hook-${++hookSeq}`,
+ resolveMessageHookContext: () => ({}),
...overrides,
};
return { gw: new GhostSubscriptionGateway(deps), sent, running, deps };
@@ -286,15 +290,22 @@ describe('will- 拦截', () => {
});
it('allow 继续问下一个;全 allow 放行', async () => {
- const { gw, sent, running } = makeGateway({ listGhosts: () => HOOK_GHOSTS });
+ const context = { model: 'gpt-5.6' };
+ const { gw, sent, running } = makeGateway({
+ listGhosts: () => HOOK_GHOSTS,
+ resolveMessageHookContext: () => context,
+ });
running.add('h1').add('h2');
const p = gw.screenUserMessage({ sessionId: 's1', text: 'hi' });
+ expect(sent[0]?.payload).toMatchObject({ name: 'will-user-message', data: context });
gw.handleVerdict('h1', {
type: 'event-verdict',
hookId: (sent[0].payload as { hookId: string }).hookId,
action: 'allow',
});
await vi.waitFor(() => expect(sent).toHaveLength(2));
+ const secondData = (sent[1]?.payload as { data: Record<string, unknown> }).data;
+ expect(secondData).toEqual({ sessionId: 's1', text: 'hi', model: 'gpt-5.6' });
gw.handleVerdict('h2', {
type: 'event-verdict',
hookId: (sent[1].payload as { hookId: string }).hookId,
@@ -397,6 +408,38 @@ describe('will- 拦截', () => {
expect(sent).toHaveLength(3);
});
+ it('无匹配钩子时不读取上下文', async () => {
+ const resolveMessageHookContext = vi.fn(() => ({ model: 'gpt-5.6' }));
+ const { gw } = makeGateway({ listGhosts: () => [], resolveMessageHookContext });
+ expect(await gw.screenUserMessage({ sessionId: 's1', text: 'hi' })).toEqual({ action: 'allow' });
+ expect(resolveMessageHookContext).not.toHaveBeenCalled();
+ });
+
+ it('同轮插话使用运行中会话的模型快照', async () => {
+ const resolveMessageHookContext = vi.fn(() => ({ model: 'next-model' }));
+ const { gw, sent, running } = makeGateway({
+ listGhosts: () => [HOOK_GHOSTS[0]],
+ resolveMessageHookContext,
+ });
+ running.add('h1');
+ const p = withGhostUserHookModel('live-model', () =>
+ gw.screenUserMessage({ sessionId: 's1', text: 'steer' }),
+ );
+ expect(sent[0]?.payload).toMatchObject({ data: { model: 'live-model' } });
+ expect(resolveMessageHookContext).not.toHaveBeenCalled();
+ gw.handleVerdict('h1', {
+ type: 'event-verdict',
+ hookId: (sent[0].payload as { hookId: string }).hookId,
+ action: 'allow',
+ });
+ expect(await p).toEqual({ action: 'allow' });
+ });
+
+ it('排队轮次使用入队时捕获的模型', () => {
+ expect(resolveGhostUserHookModel(false, 'new-selection', 'queued-model')).toBe('queued-model');
+ expect(resolveGhostUserHookModel(true, 'live-model', 'queued-model')).toBe('live-model');
+ });
+
it('verdict 归属校验:冒名/未知 hookId 静默丢;迟到 verdict 无副作用', async () => {
const { gw, sent, running } = makeGateway({ listGhosts: () => [HOOK_GHOSTS[0]] });
running.add('h1');
@@ -409,8 +452,8 @@ describe('will- 拦截', () => {
gw.handleVerdict('h1', { type: 'event-verdict', hookId, action: 'block' }); // 迟到
});
- it('wake 挂死(load 永不完成):3s 整体上界照样放行,不卡发送', async () => {
- const { gw } = makeGateway({
+ it('wake 挂死(load 永不完成):超时后终止投递续体,不卡发送', async () => {
+ const { gw, sent } = makeGateway({
listGhosts: () => [HOOK_GHOSTS[0]],
isRunning: () => false,
wake: vi.fn(() => new Promise<never>(() => {})), // 永不 settle
@@ -418,6 +461,50 @@ describe('will- 拦截', () => {
const p = gw.screenUserMessage({ sessionId: 's1', text: 'hi' });
await vi.advanceTimersByTimeAsync(GHOST_HOOK_TIMEOUT_MS + 10);
expect(await p).toEqual({ action: 'allow' });
+ expect(sent).toEqual([]);
+ });
+
+ it('入口钩子的唤醒与裁决共享同一个整体超时', async () => {
+ let finishWake!: () => void;
+ const wake = vi.fn(() => new Promise<void>((resolve) => {
+ finishWake = resolve;
+ }));
+ const { gw, sent } = makeGateway({
+ listGhosts: () => [HOOK_GHOSTS[0]],
+ isRunning: () => false,
+ wake,
+ });
+ const p = gw.screenUserMessage({ sessionId: 's1', text: 'hi' });
+ await vi.advanceTimersByTimeAsync(GHOST_HOOK_TIMEOUT_MS - 100);
+ finishWake();
+ await vi.waitFor(() => expect(sent).toHaveLength(1));
+
+ await vi.advanceTimersByTimeAsync(200);
+ expect(await p).toEqual({ action: 'allow' });
+ gw.handleVerdict('h1', {
+ type: 'event-verdict',
+ hookId: (sent[0].payload as { hookId: string }).hookId,
+ action: 'block',
+ });
+ });
+
+ it('上下文读取挂死:无上下文投递后仍受整体超时约束', async () => {
+ const { gw, sent, running } = makeGateway({
+ listGhosts: () => [HOOK_GHOSTS[0]],
+ resolveMessageHookContext: () => new Promise<never>(() => {}),
+ });
+ running.add('h1');
+ const p = gw.screenUserMessage({ sessionId: 's1', text: 'hi' });
+ await vi.advanceTimersByTimeAsync(GHOST_HOOK_TIMEOUT_MS / 2);
+ expect((sent[0].payload as { data: unknown }).data).toEqual({ sessionId: 's1', text: 'hi' });
+ const hookId = (sent[0].payload as { hookId: string }).hookId;
+ await vi.advanceTimersByTimeAsync(GHOST_HOOK_TIMEOUT_MS / 2 + 1);
+ expect(await p).toEqual({ action: 'allow' });
+ gw.handleVerdict('h1', {
+ type: 'event-verdict',
+ hookId,
+ action: 'block',
+ });
});
it('投递失败计入熔断并放行;成功裁决清零失败计数', async () => {
@@ -458,10 +545,19 @@ describe('will-assistant-message 出口钩子拦截(screenAssistantMessage)', ()
ghost('h2', { hooks: ['will-assistant-message'] }),
];
- it('全 allow → 放行', async () => {
- const { gw, sent, running } = makeGateway({ listGhosts: () => OUT_GHOSTS });
+ it('使用本轮模型快照而不是下一轮选择', async () => {
+ const resolveMessageHookContext = vi.fn(() => ({ model: 'next-model' }));
+ const { gw, sent, running } = makeGateway({
+ listGhosts: () => OUT_GHOSTS,
+ resolveMessageHookContext,
+ });
running.add('h1').add('h2');
- const p = gw.screenAssistantMessage({ sessionId: 's1', text: 'AI 回复' });
+ const p = withGhostAssistantHookModel(Promise.resolve('claude-opus-5'), () =>
+ gw.screenAssistantMessage({ sessionId: 's1', text: 'AI 回复' }),
+ );
+ await vi.waitFor(() => expect(sent).toHaveLength(1));
+ expect(sent[0]?.payload).toMatchObject({ data: { model: 'claude-opus-5' } });
+ expect(resolveMessageHookContext).not.toHaveBeenCalled();
gw.handleVerdict('h1', {
type: 'event-verdict',
hookId: (sent[0].payload as { hookId: string }).hookId,
@@ -478,6 +574,30 @@ describe('will-assistant-message 出口钩子拦截(screenAssistantMessage)', ()
expect((sent[0].payload as { name: string }).name).toBe('will-assistant-message');
});
+ it('出口钩子按自身预算等待较慢的本轮模型快照', async () => {
+ let resolveModel!: (model: string) => void;
+ const model = new Promise<string>((resolve) => {
+ resolveModel = resolve;
+ });
+ const { gw, sent, running } = makeGateway({ listGhosts: () => [OUT_GHOSTS[0]] });
+ running.add('h1');
+ const p = withGhostAssistantHookModel(model, () =>
+ gw.screenAssistantMessage({ sessionId: 's1', text: 'AI 回复' }),
+ );
+
+ await vi.advanceTimersByTimeAsync(GHOST_HOOK_TIMEOUT_MS);
+ expect(sent).toHaveLength(0);
+ resolveModel('claude-opus-5');
+ await vi.waitFor(() => expect(sent).toHaveLength(1));
+ expect(sent[0]?.payload).toMatchObject({ data: { model: 'claude-opus-5' } });
+ gw.handleVerdict('h1', {
+ type: 'event-verdict',
+ hookId: (sent[0].payload as { hookId: string }).hookId,
+ action: 'allow',
+ });
+ expect(await p).toEqual({ action: 'allow' });
+ });
+
it('rewrite 链式叠加:h2 看到 h1 改写后的文本,末个署名', async () => {
const { gw, sent, running } = makeGateway({ listGhosts: () => OUT_GHOSTS });
running.add('h1').add('h2');
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index d3ab6277f8..cb623a56bc 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -2080,7 +2080,9 @@ cindy.onHostMessage(function (msg) {
// 语义 = "主机停下来交给你做,做完继续":你可以在这窗口里做任何事(记账、
// 经 network 槽过合规接口…),然后用三种动作之一收尾:
if (msg.name === 'will-user-message') {
- // msg.data = { sessionId, text };msg.hookId 原样带回。
+ // msg.data = { sessionId, text, model? };新 turn 时 model 是本轮已选模型 id,
+ // 同轮插话(steer)时是当前运行中 turn 的模型 id。
+ // msg.hookId 原样带回。
if (/(内部代号|密钥)/.test(msg.data.text)) {
// ① block:打回,不继续(reason 展示在被拦气泡上)。
cindy.send({ type:'event-verdict', hookId: msg.hookId, action:'block', reason:'疑似包含敏感信息' });
@@ -2136,9 +2138,10 @@ cindy.onHostMessage(function (msg) {
无弹窗**;空改写 / 改写等于原文一律被忽略;
- **UI 全主机画**:红条、气泡都由主机绘制,你只提供 reason / text 文本,伪装不了、
也冒充不了别的意识;
-- **钩子作用于"即将启动新 turn 的用户消息"**:运行中 turn 里的用户插话(steer)v1
- **不经**你的钩子——拦下 = turn 压根不启动,这是钩子点的语义边界,别假设
- 能看到会话里的每一句话;
+- **钩子作用于发给 Agent 的用户消息**:即将启动新 turn 的消息和运行中 turn 里的
+ 用户插话(steer)都经同一道钩子。新 turn 的 \`model\` 是本轮已选模型,steer 的
+ \`model\` 是当前运行中 turn 的模型;拦下新 turn = turn 不启动,拦下 steer = 不注入
+ 当前 turn;
- **没有绕过通道(v1)**:被拦消息用户只能编辑后重发,重发仍会经你再审。即便
如此也别把拦截当硬性管控设计(意识是工具不是管理员):reason 要引导用户怎么
改,而不是单纯说不;
@@ -2163,7 +2166,8 @@ AI 每轮回复完成后,主机把**全文**交给你——这是一个**通用
\`\`\`js
cindy.onHostMessage(async function (msg) {
if (msg.type !== 'event' || msg.name !== 'will-assistant-message') return;
- // msg.data = { sessionId, text = 本轮 AI 回复全文 };msg.hookId 原样带回。
+ // msg.data = { sessionId, text = 本轮 AI 回复全文, model? };
+ // model 是生成本轮回复的模型 id;msg.hookId 原样带回。
const polished = await cindy.fetch({ url: 'https://api.example.com/polish', method: 'POST',
body: JSON.stringify({ text: msg.data.text }) });
// ① rewrite:用改写正文替换回复(静默换文本,≤16000 字符)。
diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
index 0706e4623b..5b7ff343fa 100644
--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts
@@ -18,9 +18,11 @@
* 依赖注入(规则 14):意识清单/运行态/唤醒/投递全经 deps,单测直喂。
*/
+import { AsyncLocalStorage } from 'node:async_hooks';
import { createHash, randomUUID } from 'node:crypto';
import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation';
+import { eq } from 'drizzle-orm';
import {
GHOST_ASSISTANT_HOOK_TIMEOUT_MS,
@@ -36,10 +38,13 @@ import {
type GhostEventThinkingData,
type GhostEventTurnEndData,
type GhostEventTurnStartData,
+ type GhostMessageHookData,
type GhostPipeEventPush,
type GhostSubscribeTopic,
type InstalledGhost,
} from '../../shared/ghost.js';
+import { getDbClient } from '../localDb/client/current.js';
+import * as localDbSchema from '../localDb/schema.js';
/** block 理由展示上限(超长截断,防意识用理由塞小作文)。 */
const BLOCK_REASON_MAX_CHARS = 200;
@@ -53,6 +58,46 @@ type HookVerdict = {
height?: number;
};
+type MessageHookContext = Pick<GhostMessageHookData, 'model'>;
+const userHookContext = new AsyncLocalStorage<MessageHookContext>();
+const assistantHookContext = new AsyncLocalStorage<Promise<MessageHookContext>>();
+
+function boundMessageHookContext(
+ context: Promise<MessageHookContext>,
+ timeoutMs: number,
+): Promise<MessageHookContext> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const fallback = new Promise<MessageHookContext>((resolve) => {
+ timer = setTimeout(() => resolve({}), timeoutMs);
+ timer.unref?.();
+ });
+ return Promise.race([context.catch(() => ({})), fallback]).finally(() => {
+ if (timer) clearTimeout(timer);
+ });
+}
+
+/** Carry the turn-start model through the asynchronous assistant-hook continuation. */
+export function withGhostAssistantHookModel<T>(model: Promise<string>, task: () => T): T {
+ const context = boundMessageHookContext(
+ model.then((value) => (value && value !== 'unknown' ? { model: value } : {})),
+ GHOST_ASSISTANT_HOOK_TIMEOUT_MS / 2,
+ );
+ return assistantHookContext.run(context, task);
+}
+
+export function resolveGhostUserHookModel(
+ turnRunning: boolean,
+ liveModel: string | undefined,
+ queuedModel: string | undefined,
+): string | undefined {
+ return turnRunning ? liveModel : queuedModel;
+}
+
+/** Carry the dispatch model through the user-hook screening continuation. */
+export function withGhostUserHookModel<T>(model: string | undefined, task: () => T): T {
+ return model && model !== 'unknown' ? userHookContext.run({ model }, task) : task();
+}
+
/**
* 用户消息拦截结果(will-user-message,宿主消费):
* - allow:原样派发;
@@ -90,12 +135,26 @@ export interface GhostSubscriptionGatewayDeps {
onHookFused?(ghost: InstalledGhost, ownerStamp?: unknown): void;
/** hookId 生成(测试注入固定序列;缺省 randomUUID)。 */
newHookId?(): string;
+ resolveMessageHookContext?(sessionId: string): MessageHookContext | Promise<MessageHookContext>;
log?: {
info(msg: string, meta?: Record<string, unknown>): void;
warn(msg: string, meta?: Record<string, unknown>): void;
};
}
+async function readMessageHookContext(sessionId: string): Promise<MessageHookContext> {
+ const rows = await getDbClient()
+ .drizzle.select({
+ model: localDbSchema.sessions.model,
+ })
+ .from(localDbSchema.sessions)
+ .where(eq(localDbSchema.sessions.id, sessionId))
+ .limit(1);
+ const row = rows[0];
+ if (!row) return {};
+ return { model: row.model ?? undefined };
+}
+
/** 每意识的订阅运行态。 */
interface SubEntry {
seq: number;
@@ -234,6 +293,8 @@ export class GhostSubscriptionGateway {
input: { sessionId: string; text: string },
ownerStamp?: unknown,
): Promise<GhostScreenResult> {
+ let context: MessageHookContext | Promise<MessageHookContext> | undefined =
+ userHookContext.getStore();
let currentText = input.text;
let rewritten = false;
let lastRewriteGhost: InstalledGhost | null = null;
@@ -243,11 +304,12 @@ export class GhostSubscriptionGateway {
const ghostId = ghost.manifest.id;
const e = this.entry(ghostId);
if (e.hookFused) continue;
+ context ??= this.resolveMessageHookContext(input.sessionId, GHOST_HOOK_TIMEOUT_MS / 2);
const verdict = await this.askOne(ghost, e, 'will-user-message', {
sessionId: input.sessionId,
text: currentText,
- }, ownerStamp);
+ }, context, ownerStamp);
if (verdict?.action === 'block') {
const reason = (verdict.reason ?? '').slice(0, BLOCK_REASON_MAX_CHARS);
this.deps.log?.info('ghost hook blocked user message', { ghostId, sessionId: input.sessionId });
@@ -290,6 +352,8 @@ export class GhostSubscriptionGateway {
input: { sessionId: string; text: string },
ownerStamp?: unknown,
): Promise<GhostAssistantScreenResult> {
+ let context: MessageHookContext | Promise<MessageHookContext> | undefined =
+ assistantHookContext.getStore();
let currentText = input.text;
let lastRewriteGhost: InstalledGhost | null = null;
let renderGhost: InstalledGhost | null = null;
@@ -301,11 +365,15 @@ export class GhostSubscriptionGateway {
const ghostId = ghost.manifest.id;
const e = this.entry(ghostId);
if (e.hookFused) continue;
+ context ??= this.resolveMessageHookContext(
+ input.sessionId,
+ GHOST_ASSISTANT_HOOK_TIMEOUT_MS / 2,
+ );
const verdict = await this.askOne(ghost, e, 'will-assistant-message', {
sessionId: input.sessionId,
text: currentText,
- }, ownerStamp);
+ }, context, ownerStamp);
if (verdict?.action === 'rewrite' && typeof verdict.text === 'string') {
const next = verdict.text.slice(0, GHOST_HOOK_REWRITE_MAX_CHARS).trim();
// 空改写(意识把正文清空)视为无意义,忽略此次 rewrite 保原文。
@@ -347,15 +415,13 @@ export class GhostSubscriptionGateway {
}
/** 问一个意识:唤醒(如需)+ 投递 + 等裁决,整体套一只超时闸。
- * 投递(含 wake)**不在超时闸前阻塞**——fire 后立刻进入等待,wake 挂死
- * (恶意/损坏意识 load 永不完成)照样 3s 放行,这才是真正的整体上界;
- * 迟到的 wake 完成后即便把事件送出去,hookId 已过期,裁决被静默丢。
* 返回 null = 本轮失败(已计入熔断),外层按放行继续。 */
private async askOne(
ghost: InstalledGhost,
e: SubEntry,
hookName: 'will-user-message' | 'will-assistant-message',
- input: { sessionId: string; text: string },
+ input: GhostMessageHookData,
+ context: MessageHookContext | Promise<MessageHookContext>,
ownerStamp?: unknown,
): Promise<HookVerdict | null> {
const ghostId = ghost.manifest.id;
@@ -370,21 +436,41 @@ export class GhostSubscriptionGateway {
resolveVerdict = resolve;
});
this.pendingHooks.set(hookId, { ghostId, resolve: resolveVerdict });
- const timer = setTimeout(() => {
- if (this.pendingHooks.delete(hookId)) resolveVerdict(null); // 超时 = fail-open
- }, timeoutMs);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const armTimeout = () => {
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => {
+ if (this.pendingHooks.delete(hookId)) resolveVerdict(null); // 超时 = fail-open
+ }, timeoutMs);
+ };
+ armTimeout();
let deliverFailure: string | null = null;
void (async () => {
// 常驻意识正常在跑;崩溃恢复窗口内兜底拉一次。
- if (!this.deps.isRunning(ghostId)) await this.deps.wake(ghost);
+ if (!this.deps.isRunning(ghostId)) {
+ const wokeBeforeDeadline = await Promise.race([
+ this.deps.wake(ghost).then(() => true),
+ verdictPromise.then(() => false),
+ ]);
+ if (!wokeBeforeDeadline) return;
+ }
+ const resolvedContext = context instanceof Promise ? await context : context;
+ if (!this.pendingHooks.has(hookId)) return;
+ const data: GhostMessageHookData = {
+ ...input,
+ ...(resolvedContext.model ? { model: resolvedContext.model } : {}),
+ };
this.deps.sendToGhost(ghostId, {
type: 'event',
name: hookName,
hookId,
ts: this.deps.now(),
- data: { sessionId: input.sessionId, text: input.text },
+ data,
});
+ // Assistant hooks run after the turn and may grant a fresh decision
+ // window. User hooks stay inside the original end-to-end send deadline.
+ if (hookName === 'will-assistant-message' && this.pendingHooks.has(hookId)) armTimeout();
})().catch((err) => {
if (this.pendingHooks.delete(hookId)) {
deliverFailure = `deliver: ${err instanceof Error ? err.message : String(err)}`;
@@ -402,6 +488,18 @@ export class GhostSubscriptionGateway {
return verdict;
}
+ private resolveMessageHookContext(
+ sessionId: string,
+ timeoutMs: number,
+ ): MessageHookContext | Promise<MessageHookContext> {
+ try {
+ const context = (this.deps.resolveMessageHookContext ?? readMessageHookContext)(sessionId);
+ return context instanceof Promise ? boundMessageHookContext(context, timeoutMs) : context;
+ } catch {
+ return {};
+ }
+ }
+
private noteHookFailure(
ghost: InstalledGhost,
e: SubEntry,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 8e620917fb..7aa0bfc2d9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -305,8 +305,10 @@ function createHarness(opts?: {
noteSessionClearBoundary,
resolveSessionReferences,
hasPendingCredentialSwitch: () => hasPendingCredentialSwitch?.() === true,
- screenUserMessage: (sessionId, item) =>
- screenUserMessage ? screenUserMessage(sessionId, item) : Promise.resolve({ action: 'allow' }),
+ screenUserMessage: (sessionId, agentFacingText, item) =>
+ screenUserMessage
+ ? screenUserMessage(sessionId, agentFacingText, item)
+ : Promise.resolve({ action: 'allow' }),
onUserMessageBlocked,
onUserMessageRewritten,
emitProjection,
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 6bc2fe0aaf..daea415f77 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -354,6 +354,7 @@ export interface AgentInputCoordinatorDeps {
screenUserMessage?: (
sessionId: string,
agentFacingText: string,
+ item: AgentInputQueuedMessage,
) => Promise<
| { action: 'allow' }
| { action: 'block'; ghostId: string; ghostName: string; reason: string }
@@ -1722,7 +1723,11 @@ export class AgentInputCoordinator {
// marker 已置位,筛查期间并发 steer / drain 被挡;stop / clearSession 竞态
// 由筛查后的 marker 复查兜底。
if (!item.bypassGhostHooks && this.deps.screenUserMessage) {
- const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(item));
+ const verdict = await this.deps.screenUserMessage(
+ sessionId,
+ getAgentFacingText(item),
+ item,
+ );
const cur = this.getState(sessionId);
if (!cur.steeringQueueClientIds.includes(item.clientId)) {
// stop/close/clearSession 赢在筛查期间:steer 事务已被取消,静默放弃。
@@ -3153,7 +3158,11 @@ export class AgentInputCoordinator {
// 留痕署名后照常派发。activeTurn 已置位,并发 drain 被挡住,询问期间
// 不会抢发下一条。
if (!head.bypassGhostHooks && this.deps.screenUserMessage) {
- const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(head));
+ const verdict = await this.deps.screenUserMessage(
+ sessionId,
+ getAgentFacingText(head),
+ head,
+ );
if (!this.isActiveTurnCurrent(sessionId, active)) return;
if (verdict.action === 'block') {
this.getState(sessionId).activeTurn = null;
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ed3e9bc1b9..942494f367 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -778,6 +778,11 @@ import {
writeGhostErrandSessionId,
} from '../cindy-brain/errandPrefsStore.js';
import { isGhostPickedDir } from '../cindy-brain/pickGrantsStore.js';
+import {
+ resolveGhostUserHookModel,
+ withGhostAssistantHookModel,
+ withGhostUserHookModel,
+} from '../cindy-brain/subscriptionGateway.js';
import { createGhostErrandRunner } from './ghostErrandRunner.js';
import {
createGhostErrandSession,
@@ -3928,7 +3933,12 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const doneResult = (event.data as { result?: unknown } | null)?.result;
const replyText = typeof doneResult === 'string' ? doneResult : '';
if (replyText.length > 0 && hasEnabledGhostAssistantHook()) {
- runGhostAssistantReplyHook(session.id, turnAssistantPersistId, replyText);
+ const turnModel =
+ turnModelPromiseBySession.get(session.id) ?? Promise.resolve(session.model || 'unknown');
+ const assistantPersistId = turnAssistantPersistId;
+ withGhostAssistantHookModel(turnModel, () => {
+ runGhostAssistantReplyHook(session.id, assistantPersistId, replyText);
+ });
}
}
// Worker turn 结束后交给 OrcaTeamService 处理 DB status、广播与 auto-bridge。
@@ -10013,8 +10023,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
// 意识拦截钩(订阅槽①):派发/落库前问已装钩子意识;fail-open 由
// screenGhostUserMessage 内部收敛,快路径(无钩子意识)零开销。
- screenUserMessage: (sessionId, agentFacingText) =>
- screenGhostUserMessage(sessionId, agentFacingText),
+ screenUserMessage: (sessionId, agentFacingText, item) => {
+ const session = getStableSessionForTurnBoundary(sessionId);
+ const model = resolveGhostUserHookModel(
+ session?.isTurnRunning() === true,
+ session?.model,
+ item.createOpts.model,
+ );
+ return withGhostUserHookModel(model, () =>
+ screenGhostUserMessage(sessionId, agentFacingText),
+ );
+ },
onUserMessageBlocked: (sessionId, item, verdict) =>
broadcastGhostMessageBlocked({
sessionId,
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 8865618fb7..aef80a4569 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -6183,6 +6183,8 @@ export type GhostDidEventData =
| GhostEventSessionData
| GhostEventActivityData;
+export type GhostMessageHookData = { sessionId: string; text: string; model?: string };
+
/**
* 下行:主机 → 意识的事件推送(经管子 onHostMessage 到达)。
* did- 分支带 topic/seq(每意识单调递增,可自查漏收;dropped = 上一段
@@ -6204,7 +6206,7 @@ export type GhostPipeEventPush =
name: 'will-user-message';
hookId: string;
ts: number;
- data: { sessionId: string; text: string };
+ data: GhostMessageHookData;
}
| {
type: 'event';
@@ -6212,7 +6214,7 @@ export type GhostPipeEventPush =
hookId: string;
ts: number;
/** text = 本轮 AI 回复全文;意识可放行/改写/自绘(见 GhostPipeEventVerdict)。 */
- data: { sessionId: string; text: string };
+ data: GhostMessageHookData;
}
| {
/** 随包 Node 进程发来的 JSON-RPC notification / MCP 进度事件。 */