Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 插件新增 AI 代办双通道——快问快答(cindy.text.oneshot)与派活取件(agent.errand)
Lizi35b64a3f8b2e
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.tsindex dad702e153..a4e31266bb 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts@@ -21,7 +21,7 @@ function fakeGhost(overrides: {enabled?: boolean;slots?: string[];- model?: { image?: string[]; video?: string[]; media?: string[] } | null;+ model?: { image?: string[]; video?: string[]; media?: string[]; text?: string[] } | null;} = {},): InstalledGhost {return {@@ -1170,3 +1170,140 @@ describe('寄存(deposit_media / release_media)', () => {expect(releaseDeposit).not.toHaveBeenCalled();});});++describe('快问快答(oneshot_text)', () => {+ const ONESHOT = { type: 'cindy-request', kind: 'oneshot_text', prompt: '总结一下' };+ const withText = (deps: Partial<CindySlotDeps> = {}) =>+ makeSlot({+ getGhost: () =>+ fakeGhost({ model: { image: ['generate'], text: ['oneshot'] } }),+ oneshotText: vi.fn(async () => ({ ok: true as const, text: '好的', model: 'chain/mini' })),+ ...deps,+ });++ it('未声明 text.oneshot → PERMISSION_DENIED,不触发链路', async () => {+ const oneshotText = vi.fn();+ const { slot } = makeSlot({ oneshotText });+ const r = await slot.handleModelRequest('art', ONESHOT);+ expect(r).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(oneshotText).not.toHaveBeenCalled();+ });++ it('载荷校验:空 prompt / 超长 prompt / 非法 maxTokens / 非法 expectJson → INVALID_PARAMS', async () => {+ const { slot } = withText();+ expect(+ await slot.handleModelRequest('art', { ...ONESHOT, prompt: ' ' }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });+ expect(+ await slot.handleModelRequest('art', { ...ONESHOT, prompt: 'x'.repeat(32_769) }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });+ expect(+ await slot.handleModelRequest('art', { ...ONESHOT, maxTokens: 0 }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });+ expect(+ await slot.handleModelRequest('art', { ...ONESHOT, maxTokens: 99999 }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });+ expect(+ await slot.handleModelRequest('art', { ...ONESHOT, expectJson: 'yes' }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_PARAMS' });+ });++ it('能力未接线(deps 缺 oneshotText)→ 结构化拒绝,fail closed', async () => {+ const { slot } = makeSlot({+ getGhost: () => fakeGhost({ model: { text: ['oneshot'] } }),+ oneshotText: undefined,+ });+ expect(await slot.handleModelRequest('art', ONESHOT)).toMatchObject({+ ok: false,+ errorCode: 'INTERNAL',+ });+ });++ it('happy path:文字随返回递回,带实际选型;缺省 maxTokens=1024', async () => {+ const oneshotText = vi.fn(async () => ({ ok: true as const, text: '答案', model: 'chain/mini' }));+ const { slot } = withText({ oneshotText });+ const r = await slot.handleModelRequest('art', ONESHOT);+ expect(r).toMatchObject({ ok: true, text: '答案', model: 'chain/mini' });+ expect(oneshotText).toHaveBeenCalledWith({+ prompt: '总结一下',+ maxTokens: 1024,+ timeoutMs: 60_000,+ });+ });++ it('链路失败三档映射:no_candidate → NO_CANDIDATE,timeout → TIMEOUT,failed → INTERNAL', async () => {+ for (const [reason, errorCode] of [+ ['no_candidate', 'NO_CANDIDATE'],+ ['timeout', 'TIMEOUT'],+ ['failed', 'INTERNAL'],+ ] as const) {+ const { slot } = withText({+ oneshotText: vi.fn(async () => ({ ok: false as const, reason, message: '不行' })),+ });+ expect(await slot.handleModelRequest('art', ONESHOT)).toMatchObject({+ ok: false,+ errorCode,+ message: '不行',+ });+ }+ });++ it('expectJson:剥围栏后可解析 → 返回清洗后的 JSON 文本;不可解析 → BAD_MODEL_OUTPUT', async () => {+ const good = withText({+ oneshotText: vi.fn(async () => ({+ ok: true as const,+ text: '```json\n{"a":1}\n```',+ })),+ });+ expect(await good.slot.handleModelRequest('art', { ...ONESHOT, expectJson: true })).toMatchObject(+ { ok: true, text: '{"a":1}' },+ );+ const bad = withText({+ oneshotText: vi.fn(async () => ({ ok: true as const, text: '这不是 JSON' })),+ });+ expect(await bad.slot.handleModelRequest('art', { ...ONESHOT, expectJson: true })).toMatchObject(+ { ok: false, errorCode: 'BAD_MODEL_OUTPUT' },+ );+ });++ it('expectJson 时提示里追加 JSON 要求(确定性拼接,不甩给链路)', async () => {+ const oneshotText = vi.fn(async (_params: { prompt: string; maxTokens: number; timeoutMs: number }) => ({+ ok: true as const,+ text: '{}',+ }));+ const { slot } = withText({ oneshotText });+ await slot.handleModelRequest('art', { ...ONESHOT, expectJson: true });+ expect(oneshotText.mock.calls[0]?.[0]?.prompt).toContain('只输出 JSON');+ });++ it('在途并发闸与媒体代办共用:达到上限即 RATE_LIMITED', async () => {+ let release: (() => void) | null = null;+ const oneshotText = vi.fn(+ () =>+ new Promise<{ ok: true; text: string }>((resolve) => {+ release = () => resolve({ ok: true, text: 'ok' });+ }),+ );+ const { slot } = withText({ oneshotText, getInflightLimit: () => 1 });+ const first = slot.handleModelRequest('art', ONESHOT);+ await Promise.resolve();+ expect(await slot.handleModelRequest('art', ONESHOT)).toMatchObject({+ ok: false,+ errorCode: 'RATE_LIMITED',+ });+ release!();+ expect(await first).toMatchObject({ ok: true });+ });++ it('注入实现抛错 → 折叠为 INTERNAL,不向沙箱穿透异常', async () => {+ const { slot } = withText({+ oneshotText: vi.fn(async () => {+ throw new Error('boom');+ }),+ });+ expect(await slot.handleModelRequest('art', ONESHOT)).toMatchObject({+ ok: false,+ errorCode: 'INTERNAL',+ });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.tsnew file mode 100644index 0000000000..07e3941daa--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts@@ -0,0 +1,87 @@+/**+ * errandPrefsStore.test.ts — 派活配置存储的 normalize 单测。+ * 存储真身经 createOverrideSettingsFile 落 userData,依赖 electron;这里+ * 只测纯函数(坏形态清洗与权限档白名单),读写链路由 IPC 层与 runner 测试覆盖。+ */++import { describe, it, expect, vi } from 'vitest';++vi.mock('electron', () => ({ app: { getPath: () => '/tmp/never-used-here' } }));+vi.mock('../../maker-host/logger-adapter.js', () => ({+ desktopMakerLogger: { child: () => ({ info: () => {}, warn: () => {}, error: () => {} }) },+}));++const { __testing } = await import('../errandPrefsStore');++describe('normalizeConfig(单插件配置清洗)', () => {+ it('合法字段保留,非法值逐字段丢弃(= 回到跟随默认)', () => {+ expect(+ __testing.normalizeConfig({+ agentKind: 'codex',+ model: 'gpt-x',+ effort: 'high',+ fastMode: true,+ providerId: 'openai',+ permissionMode: 'acceptEdits',+ workingDir: '/proj/demo',+ }),+ ).toEqual({+ agentKind: 'codex',+ model: 'gpt-x',+ effort: 'high',+ fastMode: true,+ providerId: 'openai',+ permissionMode: 'acceptEdits',+ workingDir: '/proj/demo',+ });+ expect(+ __testing.normalizeConfig({+ agentKind: 'claude',+ model: '',+ effort: 'minimal',+ fastMode: 'yes',+ permissionMode: 'bypassPermissions',+ workingDir: 42,+ }),+ ).toEqual({});+ });++ it('permissionMode 白名单:bypassPermissions / ask 等一律清掉', () => {+ expect(__testing.normalizeConfig({ permissionMode: 'plan' })).toEqual({+ permissionMode: 'plan',+ });+ expect(__testing.normalizeConfig({ permissionMode: 'auto' })).toEqual({+ permissionMode: 'auto',+ });+ expect(__testing.normalizeConfig({ permissionMode: 'bypassPermissions' })).toEqual({});+ expect(__testing.normalizeConfig({ permissionMode: 'ask' })).toEqual({});+ });++ it('非对象入参 → 空配置', () => {+ expect(__testing.normalizeConfig(null)).toEqual({});+ expect(__testing.normalizeConfig('x')).toEqual({});+ });+});++describe('normalize(整文件清洗)', () => {+ it('errand 与 sessions 两区各自清洗;空配置条目剔除', () => {+ expect(+ __testing.normalize({+ errand: {+ helper: { agentKind: 'cc' },+ junk: { agentKind: 'nope' },+ broken: 'not-an-object',+ },+ sessions: { helper: 'sess-1', bad: 42, empty: '' },+ }),+ ).toEqual({+ errand: { helper: { agentKind: 'cc' } },+ sessions: { helper: 'sess-1' },+ });+ });++ it('非对象/缺区 → 全空', () => {+ expect(__testing.normalize(null)).toEqual({ errand: {}, sessions: {} });+ expect(__testing.normalize({})).toEqual({ errand: {}, sessions: {} });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.tsnew file mode 100644index 0000000000..0e8d12f9e3--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts@@ -0,0 +1,339 @@+/**+ * errandSlot.test.ts — 派活取件守门层单测(纯 DI,无 Electron)。+ * 覆盖:资格审(agent 槽 + errand 详单)、载荷校验、频控(最小间隔 + 单在途)、+ * 异步受理/查询生命周期、wait 同步、结果截断、归属校验话术、TTL 清理、+ * runner 异常折叠、clearGhost。+ */++import { describe, it, expect, vi } from 'vitest';++import {+ clampErrandResultText,+ GhostErrandSlot,+ type GhostErrandRunner,+ type GhostErrandSlotDeps,+} from '../errandSlot';+import {+ GHOST_ERRAND_JOB_TTL_MS,+ GHOST_ERRAND_MAX_RESULT_CHARS,+ GHOST_ERRAND_MIN_INTERVAL_MS,+ type InstalledGhost,+} from '../../../shared/ghost';++function fakeGhost(+ overrides: { enabled?: boolean; slots?: string[]; agent?: Record<string, unknown> | null } = {},+): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: 'helper',+ name: '帮手',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: overrides.slots ?? ['tool', 'agent'],+ ...(overrides.agent === null ? {} : { agent: overrides.agent ?? { errand: true } }),+ },+ dir: '/fake/brain/helper',+ enabled: overrides.enabled ?? true,+ } as InstalledGhost;+}++function makeSlot(overrides: Partial<GhostErrandSlotDeps> = {}): {+ slot: GhostErrandSlot;+ runner: ReturnType<typeof vi.fn>;+ clock: { now: number };+} {+ const clock = { now: 1_000_000 };+ const runner = vi.fn(async () => ({+ ok: true as const,+ sessionId: 'sess-1',+ text: '干完了',+ agentKind: 'cc',+ model: 'claude-x',+ }));+ const slot = new GhostErrandSlot({+ getGhost: () => fakeGhost(),+ runner: runner as unknown as GhostErrandRunner,+ now: () => clock.now,+ createJobId: (() => {+ let n = 0;+ return () => `job-${++n}`;+ })(),+ ...overrides,+ });+ return { slot, runner, clock };+}++const RUN = { type: 'agent-errand-request', kind: 'run', task: '总结 README' };++describe('资格审', () => {+ it('未声明 agent 槽 / 未声明 errand / 未启用 → PERMISSION_DENIED', async () => {+ for (const ghost of [+ fakeGhost({ slots: ['tool'] }),+ fakeGhost({ agent: null }),+ fakeGhost({ agent: { background: true } }),+ fakeGhost({ enabled: false }),+ ]) {+ const { slot, runner } = makeSlot({ getGhost: () => ghost });+ expect(await slot.handleRequest('helper', RUN)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ expect(runner).not.toHaveBeenCalled();+ }+ });+});++describe('载荷校验', () => {+ it('空 task / 超长 task / 非法 title / 非法 mode / 非法 callId → INVALID_REQUEST', async () => {+ const { slot } = makeSlot();+ const cases = [+ { ...RUN, task: ' ' },+ { ...RUN, task: 'x'.repeat(32_769) },+ { ...RUN, title: '' },+ { ...RUN, title: 'x'.repeat(101) },+ { ...RUN, mode: 'submit' },+ { ...RUN, callId: '' },+ ];+ for (const payload of cases) {+ expect(await slot.handleRequest('helper', payload)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ }+ });++ it('context 不可 JSON 化 / JSON 超长 → INVALID_REQUEST', async () => {+ const { slot } = makeSlot();+ const cyclic: Record<string, unknown> = {};+ cyclic.self = cyclic;+ expect(await slot.handleRequest('helper', { ...RUN, context: cyclic })).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(+ await slot.handleRequest('helper', { ...RUN, context: 'x'.repeat(65_600) }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ });++ it('context 以固定标记附在任务消息尾部(确定性组装)', async () => {+ const { slot, runner } = makeSlot();+ await slot.handleRequest('helper', { ...RUN, context: { a: 1 } });+ const req = runner.mock.calls[0][0] as { message: string };+ expect(req.message).toBe('总结 README\n\n[结构化上下文 JSON]\n{"a":1}');+ });+});++describe('频控', () => {+ it('相邻提交小于最小间隔 → RATE_LIMITED;runner 失败也不退间隔', async () => {+ const { slot, runner, clock } = makeSlot({+ runner: vi.fn(async () => ({+ ok: false as const,+ errorCode: 'INTERNAL' as const,+ message: '炸了',+ })) as unknown as GhostErrandRunner,+ });+ void runner;+ await slot.handleRequest('helper', RUN);+ clock.now += GHOST_ERRAND_MIN_INTERVAL_MS - 1;+ expect(await slot.handleRequest('helper', RUN)).toMatchObject({+ ok: false,+ errorCode: 'RATE_LIMITED',+ });+ });++ it('单在途:上一单未完成时再提交 → BUSY', async () => {+ let release: (() => void) | null = null;+ const runner = vi.fn(+ () =>+ new Promise((resolve) => {+ release = () =>+ resolve({ ok: true, sessionId: 's', text: 'done' });+ }),+ );+ const { slot, clock } = makeSlot({ runner: runner as unknown as GhostErrandRunner });+ const first = await slot.handleRequest('helper', RUN);+ expect(first).toMatchObject({ ok: true, status: 'running' });+ clock.now += GHOST_ERRAND_MIN_INTERVAL_MS + 1;+ expect(await slot.handleRequest('helper', RUN)).toMatchObject({+ ok: false,+ errorCode: 'BUSY',+ });+ release!();+ });++ it('runner 未注入 → HOST_NOT_READY', async () => {+ const { slot } = makeSlot({ runner: null });+ expect(await slot.handleRequest('helper', RUN)).toMatchObject({+ ok: false,+ errorCode: 'HOST_NOT_READY',+ });+ });+});++describe('异步受理 + 查询生命周期', () => {+ it('受理即返 jobId;进行中可见 sessionId(onSession 回填)与耗时;完成后取件', async () => {+ let finish: (() => void) | null = null;+ let hooks: { onSession?: (sid: string) => void } | undefined;+ const runner = vi.fn((_req: unknown, h?: { onSession?: (sid: string) => void }) => {+ hooks = h;+ return new Promise((resolve) => {+ finish = () =>+ resolve({ ok: true, sessionId: 'sess-9', text: '结果文字', agentKind: 'cc', model: 'm1' });+ });+ });+ const { slot, clock } = makeSlot({ runner: runner as unknown as GhostErrandRunner });+ const accepted = await slot.handleRequest('helper', RUN);+ expect(accepted).toMatchObject({ ok: true, jobId: 'job-1', status: 'running' });++ hooks?.onSession?.('sess-9');+ clock.now += 5000;+ expect(+ await slot.handleRequest('helper', { type: 'agent-errand-request', kind: 'query', jobId: 'job-1' }),+ ).toMatchObject({ ok: true, status: 'running', sessionId: 'sess-9', elapsedSeconds: 5 });++ finish!();+ await new Promise((r) => setTimeout(r, 0));+ expect(+ await slot.handleRequest('helper', { type: 'agent-errand-request', kind: 'query', jobId: 'job-1' }),+ ).toMatchObject({+ ok: true,+ status: 'done',+ sessionId: 'sess-9',+ text: '结果文字',+ agentKind: 'cc',+ model: 'm1',+ });+ });++ it('runner 失败 → 查询返回结构化失败;runner 抛错 → INTERNAL', async () => {+ const failed = makeSlot({+ runner: vi.fn(async () => ({+ ok: false as const,+ errorCode: 'TIMEOUT' as const,+ message: '超时了',+ })) as unknown as GhostErrandRunner,+ });+ const a = await failed.slot.handleRequest('helper', RUN);+ await new Promise((r) => setTimeout(r, 0));+ expect(+ await failed.slot.handleRequest('helper', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: (a as { jobId: string }).jobId,+ }),+ ).toMatchObject({ ok: false, errorCode: 'TIMEOUT', message: '超时了' });++ const thrown = makeSlot({+ runner: vi.fn(async () => {+ throw new Error('爆炸');+ }) as unknown as GhostErrandRunner,+ });+ const b = await thrown.slot.handleRequest('helper', RUN);+ await new Promise((r) => setTimeout(r, 0));+ expect(+ await thrown.slot.handleRequest('helper', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: (b as { jobId: string }).jobId,+ }),+ ).toMatchObject({ ok: false, errorCode: 'INTERNAL' });+ });++ it('查无此单与他人单同一话术(JOB_NOT_FOUND,不泄露归属差异)', async () => {+ const { slot } = makeSlot();+ await slot.handleRequest('helper', RUN);+ await new Promise((r) => setTimeout(r, 0));+ const foreign = await slot.handleRequest('other', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: 'job-1',+ });+ // other 未声明 errand → 先被资格审拦;换一个声明了的插件查别人的单:+ expect(foreign).toMatchObject({ ok: false });+ const otherGhost = fakeGhost();+ (otherGhost.manifest as { id: string }).id = 'other';+ const slot2 = makeSlot({+ getGhost: (id) => (id === 'other' ? otherGhost : fakeGhost()),+ });+ await slot2.slot.handleRequest('helper', RUN);+ await new Promise((r) => setTimeout(r, 0));+ expect(+ await slot2.slot.handleRequest('other', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: 'job-1',+ }),+ ).toMatchObject({ ok: false, errorCode: 'JOB_NOT_FOUND' });+ expect(+ await slot2.slot.handleRequest('helper', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: 'job-none',+ }),+ ).toMatchObject({ ok: false, errorCode: 'JOB_NOT_FOUND' });+ });++ it('完成态过 TTL 被惰性清理 → 查无此单', async () => {+ const { slot, clock } = makeSlot();+ const a = await slot.handleRequest('helper', RUN);+ await new Promise((r) => setTimeout(r, 0));+ clock.now += GHOST_ERRAND_JOB_TTL_MS + 1;+ expect(+ await slot.handleRequest('helper', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: (a as { jobId: string }).jobId,+ }),+ ).toMatchObject({ ok: false, errorCode: 'JOB_NOT_FOUND' });+ });+});++describe('wait 同步模式', () => {+ it('直接返回完成态;署名单在途 hold/release 管子', async () => {+ const holdPipeCall = vi.fn();+ const releasePipeCall = vi.fn();+ const { slot } = makeSlot({ holdPipeCall, releasePipeCall });+ const r = await slot.handleRequest('helper', { ...RUN, mode: 'wait', callId: 'call-1' });+ expect(r).toMatchObject({ ok: true, status: 'done', text: '干完了', sessionId: 'sess-1' });+ expect(holdPipeCall).toHaveBeenCalledWith('helper', 'call-1', expect.any(Number));+ expect(releasePipeCall).toHaveBeenCalledWith('helper', 'call-1');+ });++ it('未署名(无 callId)不 hold', async () => {+ const holdPipeCall = vi.fn();+ const { slot } = makeSlot({ holdPipeCall });+ await slot.handleRequest('helper', { ...RUN, mode: 'wait' });+ expect(holdPipeCall).not.toHaveBeenCalled();+ });+});++describe('结果截断', () => {+ it('超过上限从头保留并带明示标记', () => {+ const text = 'x'.repeat(GHOST_ERRAND_MAX_RESULT_CHARS + 10);+ const clamped = clampErrandResultText(text);+ expect(clamped.length).toBeLessThan(text.length + 30);+ expect(clamped).toContain('已截断');+ expect(clampErrandResultText('短')).toBe('短');+ });+});++describe('clearGhost', () => {+ it('清除任务记录与节流状态', async () => {+ const { slot, clock } = makeSlot();+ const a = await slot.handleRequest('helper', RUN);+ await new Promise((r) => setTimeout(r, 0));+ slot.clearGhost('helper');+ expect(+ await slot.handleRequest('helper', {+ type: 'agent-errand-request',+ kind: 'query',+ jobId: (a as { jobId: string }).jobId,+ }),+ ).toMatchObject({ ok: false, errorCode: 'JOB_NOT_FOUND' });+ // 节流状态一并清:立刻可再次提交(不受最小间隔限制)。+ void clock;+ expect(await slot.handleRequest('helper', RUN)).toMatchObject({ ok: true, status: 'running' });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex d754e6f5d0..8dbf740c5c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -410,6 +410,14 @@ describe('FORGE_GUIDE', () => {'userActionToken',"mode:'continue'","trigger: 'background'",+ // 2026-07-31 快问快答(cindy.text.oneshot)与派活取件(agent.errand)。+ 'oneshot_text',+ 'NO_CANDIDATE',+ 'expectJson',+ '4.11.1',+ 'cindy.agent.errand',+ 'queryErrand',+ '"errand": true','node 槽','cindy.node.request','json-rpc-stdio',diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.tsindex 8be7a37c26..51a7957cab 100644--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts@@ -49,6 +49,10 @@ import {GHOST_CINDY_MAX_ASYNC_JOBS,GHOST_IMAGE_ASPECT_RATIOS,GHOST_MODEL_TIERS,+ GHOST_ONESHOT_TEXT_DEFAULT_MAX_TOKENS,+ GHOST_ONESHOT_TEXT_MAX_PROMPT_CHARS,+ GHOST_ONESHOT_TEXT_MAX_TOKENS,+ GHOST_ONESHOT_TEXT_TIMEOUT_MS,GHOST_VIDEO_MAX_DURATION_SECONDS,GHOST_VIDEO_MAX_FPS,GHOST_VIDEO_RATIOS,@@ -183,6 +187,17 @@ export interface CindySlotDeps {depositUsageBytes?(ghostId: string): Promise<number>;/** 撤回该意识对某指纹的寄存引用;返回是否真的删掉了行(false = 本就没有)。 */releaseDeposit?(params: { ghostId: string; hash: string }): Promise<boolean>;+ /**+ * 快问快答(text.oneshot,2026-07-31):把 prompt 交给主机的轻量任务+ * 模型链直答一次。注入实现包装 utility-model/oneShotCandidates 的+ * requestUtilityText(动态 import,保持本模块纯 node 可测)。可选依赖:+ * 不注入 = 能力在运行期不可用,资格审通过也回结构化拒绝(未接线的+ * 宿主/测试环境天然 fail closed)。+ */+ oneshotText?(params: { prompt: string; maxTokens: number; timeoutMs: number }): Promise<+ | { ok: true; text: string; model?: string }+ | { ok: false; reason: 'no_candidate' | 'timeout' | 'failed'; message: string }+ >;/*** 管子续命挂钩(pipeDispatcher.holdCall/releaseCall 接线):tool-call* 触发的同步视频代办开始时 hold(budgetMs = 这单的轮询预算),结束时@@ -329,6 +344,16 @@ function describeUnsupportedVideoParams(return null;}+/**+ * 剥掉模型习惯性包裹的 ``` 围栏(仅整体包裹的情况;正文中途出现的围栏+ * 不动)。expectJson 校验前的确定性清洗,导出供单测直测(规则 14)。+ */+export function stripJsonFences(text: string): string {+ const trimmed = text.trim();+ const m = /^```[a-zA-Z]*\r?\n([\s\S]*?)\r?\n?```$/.exec(trimmed);+ return m ? m[1].trim() : trimmed;+}+export class GhostCindySlot {private readonly inflight = new Map<string, number>();/** 异步代办任务表(jobId → 记录;惰性 sweep,过期即清)。 */@@ -388,13 +413,27 @@ export class GhostCindySlot {return { ok: false, message: `${verb}失败:${message}` };}}+ // 快问快答(text.oneshot):不经媒体生成链、不选型、秒级同步——单独+ // 分支,自带兜底 catch("永不 reject"同纪律)。+ if (p?.kind === 'oneshot_text') {+ try {+ return await this.handleOneshotText(ghostId, payload);+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ this.deps.log?.warn('ghost cindy-request oneshot_text unexpected failure', {+ ghostId,+ error: message,+ });+ return { ok: false, message: `快问快答失败:${message}`, errorCode: 'INTERNAL' };+ }+ }const info = typeof p?.kind === 'string' ? KIND_INFO[p.kind] : undefined;if (!info) {return {ok: false,message:`未知的代办类型(当前支持 ${Object.keys(KIND_INFO).join(' / ')} / ` +- 'deposit_media / release_media / query_job)',+ 'deposit_media / release_media / oneshot_text / query_job)',};}const kind = p.kind as string;@@ -797,6 +836,136 @@ export class GhostCindySlot {return null;}+ /**+ * oneshot_text:快问快答(2026-07-31 开闸)。轻量任务模型链直答一次,+ * 文字随本次 invoke 递回;不选型(链由用户在主机侧配置)、不产媒体、+ * 不进任何会话。失败面全部结构化(errorCode 稳定契约,见 shared 类型注释)。+ * 在途并发闸与媒体代办共用同一计数与用户上限——它们花的都是用户的额度。+ */+ private async handleOneshotText(+ ghostId: string,+ payload: unknown,+ ): Promise<GhostPipeModelResult> {+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost || !ghost.enabled) {+ return { ok: false, message: '意识不在可用状态', errorCode: 'PERMISSION_DENIED' };+ }+ if (!ghost.manifest.slots?.includes('cindy')) {+ return {+ ok: false,+ message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办',+ errorCode: 'PERMISSION_DENIED',+ };+ }+ const declared: readonly string[] = ghost.manifest.cindy?.text ?? [];+ if (!declared.includes('oneshot')) {+ return {+ ok: false,+ message:+ '本意识未声明文本「快问快答」能力(身份卡 cindy.text 缺 "oneshot"),请意识作者更新声明',+ errorCode: 'PERMISSION_DENIED',+ };+ }+ const p = payload as {+ prompt?: unknown;+ expectJson?: unknown;+ maxTokens?: unknown;+ callId?: unknown;+ };+ if (typeof p.prompt !== 'string' || p.prompt.trim().length === 0) {+ return { ok: false, message: 'prompt 不能为空', errorCode: 'INVALID_PARAMS' };+ }+ if (p.prompt.length > GHOST_ONESHOT_TEXT_MAX_PROMPT_CHARS) {+ return {+ ok: false,+ message: `prompt 过长(上限 ${GHOST_ONESHOT_TEXT_MAX_PROMPT_CHARS} 字符)`,+ errorCode: 'INVALID_PARAMS',+ };+ }+ if (p.expectJson !== undefined && typeof p.expectJson !== 'boolean') {+ return { ok: false, message: 'expectJson 必须是布尔值(或不传)', errorCode: 'INVALID_PARAMS' };+ }+ if (p.maxTokens !== undefined && !isPositiveIntWithin(p.maxTokens, GHOST_ONESHOT_TEXT_MAX_TOKENS)) {+ return {+ ok: false,+ message: `maxTokens 不合法(1–${GHOST_ONESHOT_TEXT_MAX_TOKENS} 的整数,或不传)`,+ errorCode: 'INVALID_PARAMS',+ };+ }+ if (+ p.callId !== undefined &&+ (typeof p.callId !== 'string' || p.callId.length === 0 || p.callId.length > MAX_CALL_ID_LEN)+ ) {+ return { ok: false, message: 'callId 不合法(1–128 字符的字符串,或不传)', errorCode: 'INVALID_PARAMS' };+ }+ const callId = (p.callId as string | undefined) ?? 'unattributed';+ const oneshot = this.deps.oneshotText;+ if (!oneshot) {+ return { ok: false, message: '主机当前不支持快问快答(能力未接线)', errorCode: 'INTERNAL' };+ }++ const inflight = this.inflight.get(ghostId) ?? 0;+ const inflightLimit = this.deps.getInflightLimit?.(ghostId) ?? null;+ if (inflightLimit !== null && inflight >= inflightLimit) {+ return {+ ok: false,+ message: `同时进行的代办已达上限(${inflightLimit} 单),请稍后再试`,+ errorCode: 'RATE_LIMITED',+ };+ }+ this.inflight.set(ghostId, inflight + 1);+ try {+ this.deps.log?.info('ghost cindy-request oneshot_text start', { ghostId, callId });+ const expectJson = p.expectJson === true;+ // JSON 期望用确定性代码拼进 prompt(不甩给链路侧自由发挥),校验也在+ // 本层做——链只负责"问一句答一句"。+ const prompt = expectJson+ ? `${p.prompt}\n\n(只输出 JSON 本体,不要任何解释、前后缀或代码围栏)`+ : p.prompt;+ const outcome = await oneshot({+ prompt,+ maxTokens: (p.maxTokens as number | undefined) ?? GHOST_ONESHOT_TEXT_DEFAULT_MAX_TOKENS,+ timeoutMs: GHOST_ONESHOT_TEXT_TIMEOUT_MS,+ });+ if (!outcome.ok) {+ const errorCode =+ outcome.reason === 'no_candidate'+ ? 'NO_CANDIDATE'+ : outcome.reason === 'timeout'+ ? 'TIMEOUT'+ : 'INTERNAL';+ this.deps.log?.warn('ghost cindy-request oneshot_text failed', {+ ghostId,+ callId,+ reason: outcome.reason,+ });+ return { ok: false, message: outcome.message, errorCode };+ }+ let text = outcome.text;+ if (expectJson) {+ const cleaned = stripJsonFences(text);+ try {+ JSON.parse(cleaned);+ text = cleaned;+ } catch {+ return {+ ok: false,+ errorCode: 'BAD_MODEL_OUTPUT',+ message: `模型未按 JSON 输出(原始输出开头:${text.slice(0, 200)})`,+ };+ }+ }+ this.deps.log?.info('ghost cindy-request oneshot_text done', {+ ghostId,+ callId,+ chars: text.length,+ });+ return { ok: true, text, ...(outcome.model !== undefined ? { model: outcome.model } : {}) };+ } finally {+ this.releaseInflight(ghostId);+ }+ }+/*** 寄存频控令牌桶:取一枚令牌,取不到返回 false。* 桶满时把结算时刻推到当下(不积累无限额度);未满时只推进已兑现的整数diff --git a/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts b/apps/desktop/src/main/cindy-brain/errandPrefsStore.tsnew file mode 100644index 0000000000..ecaf530046--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts@@ -0,0 +1,163 @@+/**+ * errandPrefsStore —— agent 槽「派活取件(errand)」的每插件用户配置持久化。+ *+ * File: <userData>/ghost-errand-prefs.json+ *+ * 形态:{ errand: { <ghostId>: { agentKind?, model?, effort?, fastMode?,+ * providerId?, permissionMode?, workingDir? } } }+ * - 全部字段缺省 = 跟随默认:agent/模型/effort/fast/供应商跟随「新建草稿」+ * 偏好快照(与 Orca worker 同源,见 newMakerDefaultsCache),permissionMode+ * 缺省 'plan'(只读,2026-07-31 定案),workingDir 缺省专属对话目录;+ * - permissionMode 只收 GHOST_ERRAND_PERMISSION_MODES(plan/acceptEdits/auto),+ * **bypassPermissions 在协议层就不存在**,存储层照单执法;+ * - 抽离插件**不**清配置——与 cindy 槽覆盖同语义,重装回来钉的配置还在;+ * - 模型/供应商的白名单校验由消费方(errand 服务)按当下目录做,存储层+ * 不感知清单(过期值静默落回默认并留日志,同 cindySlot override 契约)。+ */++import {+ GHOST_ERRAND_PERMISSION_MODES,+ type GhostErrandPermissionMode,+} from '../../shared/ghost.js';+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';+import { ownerScopedUserDataPath } from '../appSessionState.js';++const log = desktopMakerLogger.child('errand-prefs-store');++/** errand 会话可选的 agent 种类(与 sessions.agent_kind 同词汇表)。 */+export const GHOST_ERRAND_AGENT_KINDS = ['cc', 'codex'] as const;+export type GhostErrandAgentKind = (typeof GHOST_ERRAND_AGENT_KINDS)[number];++/** errand 会话可选的思考强度(与 worker 同集合;minimal 刻意不收)。 */+export const GHOST_ERRAND_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;+export type GhostErrandEffort = (typeof GHOST_ERRAND_EFFORTS)[number];++/** 单插件的 errand 配置(全部可缺省;缺省语义见文件头)。 */+export interface GhostErrandConfig {+ agentKind?: GhostErrandAgentKind;+ model?: string;+ effort?: GhostErrandEffort;+ fastMode?: boolean;+ providerId?: string;+ permissionMode?: GhostErrandPermissionMode;+ /** 绝对路径(用户亲选的项目目录);缺省 = 专属对话目录。 */+ workingDir?: string;+}++interface GhostErrandPrefs {+ errand: Record<string, GhostErrandConfig>;+ /**+ * ghostId → 专属 errand 会话 id(runner 复用映射)。放在偏好文件里而非+ * DB:这是"哪间是它的干活间"的宿主侧记忆,丢了(手删/损坏)的后果只是+ * 下一单重建一间,不值得动 sessions schema(migration 风险不对等)。+ */+ sessions: Record<string, string>;+}++const DEFAULTS: GhostErrandPrefs = { errand: {}, sessions: {} };++/** 单字段清洗:类型/值域不合法一律丢弃(= 回到跟随默认),不迁就脏数据。 */+function normalizeConfig(raw: unknown): GhostErrandConfig {+ if (!raw || typeof raw !== 'object') return {};+ const r = raw as Record<string, unknown>;+ const cfg: GhostErrandConfig = {};+ if (+ typeof r.agentKind === 'string' &&+ (GHOST_ERRAND_AGENT_KINDS as readonly string[]).includes(r.agentKind)+ ) {+ cfg.agentKind = r.agentKind as GhostErrandAgentKind;+ }+ if (typeof r.model === 'string' && r.model.length > 0 && r.model.length <= 128) {+ cfg.model = r.model;+ }+ if (+ typeof r.effort === 'string' &&+ (GHOST_ERRAND_EFFORTS as readonly string[]).includes(r.effort)+ ) {+ cfg.effort = r.effort as GhostErrandEffort;+ }+ if (typeof r.fastMode === 'boolean') cfg.fastMode = r.fastMode;+ if (typeof r.providerId === 'string' && r.providerId.length > 0 && r.providerId.length <= 128) {+ cfg.providerId = r.providerId;+ }+ if (+ typeof r.permissionMode === 'string' &&+ (GHOST_ERRAND_PERMISSION_MODES as readonly string[]).includes(r.permissionMode)+ ) {+ cfg.permissionMode = r.permissionMode as GhostErrandPermissionMode;+ }+ if (typeof r.workingDir === 'string' && r.workingDir.length > 0 && r.workingDir.length <= 1024) {+ cfg.workingDir = r.workingDir;+ }+ return cfg;+}++function normalize(raw: unknown): GhostErrandPrefs {+ if (!raw || typeof raw !== 'object') return { errand: {}, sessions: {} };+ const errandRaw = (raw as { errand?: unknown }).errand;+ const errand: GhostErrandPrefs['errand'] = {};+ if (errandRaw && typeof errandRaw === 'object') {+ for (const [ghostId, cfgRaw] of Object.entries(errandRaw as Record<string, unknown>)) {+ const cfg = normalizeConfig(cfgRaw);+ if (Object.keys(cfg).length > 0) errand[ghostId] = cfg;+ }+ }+ const sessionsRaw = (raw as { sessions?: unknown }).sessions;+ const sessions: GhostErrandPrefs['sessions'] = {};+ if (sessionsRaw && typeof sessionsRaw === 'object') {+ for (const [ghostId, v] of Object.entries(sessionsRaw as Record<string, unknown>)) {+ if (typeof v === 'string' && v.length > 0 && v.length <= 128) sessions[ghostId] = v;+ }+ }+ return { errand, sessions };+}++const store = createOverrideSettingsFile<GhostErrandPrefs>({+ filePath: () => ownerScopedUserDataPath('ghost-errand-prefs.json'),+ defaults: DEFAULTS,+ normalize,+ log,+ label: 'ghost-errand-prefs',+});++/** 读某插件的 errand 配置(缺省空对象 = 全跟随默认)。 */+export function readGhostErrandConfig(ghostId: string): GhostErrandConfig {+ // mtime 守卫现读:直接改文件也算配置入口(与 cindy prefs 同契约)。+ store.invalidateIfChanged();+ return store.read().errand[ghostId] ?? {};+}++/**+ * 整份替换某插件的 errand 配置(设置卡整卡提交);传 null / 清洗后为空+ * 即删除条目(恢复全跟随默认,规则 20 语义)。入参收 unknown:IPC 层只做+ * 形状粗筛,逐字段值域清洗统一在这里(单一执法点)。返回清洗后的落盘值。+ */+export function writeGhostErrandConfig(ghostId: string, config: unknown): GhostErrandConfig {+ store.invalidateIfChanged();+ const errand = { ...store.read().errand };+ const cfg = config === null ? {} : normalizeConfig(config);+ if (Object.keys(cfg).length === 0) delete errand[ghostId];+ else errand[ghostId] = cfg;+ store.writePatch({ errand });+ log.info('ghost errand config written', { ghostId, keys: Object.keys(cfg) });+ return cfg;+}++/** 读某插件的专属 errand 会话 id;null = 还没建过(或映射被清)。 */+export function readGhostErrandSessionId(ghostId: string): string | null {+ store.invalidateIfChanged();+ return store.read().sessions[ghostId] ?? null;+}++/** 写/清某插件的专属 errand 会话映射(null 即清除;会话失效重建时更新)。 */+export function writeGhostErrandSessionId(ghostId: string, sessionId: string | null): void {+ store.invalidateIfChanged();+ const sessions = { ...store.read().sessions };+ if (sessionId === null) delete sessions[ghostId];+ else sessions[ghostId] = sessionId;+ store.writePatch({ sessions });+ log.info('ghost errand session mapping written', { ghostId, sessionId });+}++export const __testing = { normalize, normalizeConfig };diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.tsnew file mode 100644index 0000000000..18e0f257c2--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts@@ -0,0 +1,370 @@+/**+ * errandSlot — agent 槽「派活取件(errand)」的主机守门层(2026-07-31 开闸)。+ *+ * 与 agentSlot(把回合发进用户会话,结果给用户看)相对:errand 把任务交给+ * 插件**专属 errand 会话**里的 agent 跑一轮,把最终回复文字取回给插件。+ *+ * 安全边界(全部由本层与注入 runner 的主机代码强制,prompt 不构成边界):+ * - 插件必须声明 `agent` 槽 + `agent.errand: true`(装入确认高风险单列);+ * - 任务文本只进普通 user 消息,绝不进 system prompt;+ * - errand 会话的 agent/模型/权限档/工作目录由用户配置(runner 侧解析;+ * 权限档默认 plan 只读,协议层就没有 bypassPermissions);+ * - 每插件同时最多 1 单在途 + 相邻提交最小间隔(防刷);+ * - 任务表在内存:主进程重启即丢,query 对丢失单统一回「查无此任务」,+ * 插件按可重新提交处理(与 cindy 槽异步代办同语义)。+ *+ * 真正的会话创建/投递/收口经 runner 注入(maker-ipc 侧实现),本模块不+ * 反向依赖 maker-ipc,规则可单测(规则 14)。+ */++import { randomUUID } from 'node:crypto';++import {+ GHOST_ERRAND_JOB_TTL_MS,+ GHOST_ERRAND_MAX_CONTEXT_JSON_CHARS,+ GHOST_ERRAND_MAX_RESULT_CHARS,+ GHOST_ERRAND_MAX_TASK_CHARS,+ GHOST_ERRAND_MIN_INTERVAL_MS,+ GHOST_PIPE_CALL_MAX_TOTAL_MS,+ type GhostAgentErrandErrorCode,+ type GhostPipeAgentErrandResult,+ type InstalledGhost,+} from '../../shared/ghost.js';++/** 归因号长度上限(与 cindySlot 同口径)。 */+const MAX_CALL_ID_LEN = 128;+/** 任务号长度上限(主机铸 UUID 量级)。 */+const MAX_JOB_ID_LEN = 64;+/** 每插件完成态任务记录保留上限(同 cindySlot 的第二道闸)。 */+const MAX_SETTLED_JOBS_PER_GHOST = 16;++export interface GhostErrandRunRequest {+ ghostId: string;+ ghostVersion: string;+ /** 已组装的最终任务消息(task + 结构化上下文;本层组装,runner 原样投递)。 */+ message: string;+ /** 首次创建 errand 会话时的标题提示。 */+ title?: string;+}++export interface GhostErrandRunHooks {+ /** errand 会话 id 一旦确定即回报(异步单据此让 query 尽早可见 sessionId)。 */+ onSession?(sessionId: string): void;+}++export type GhostErrandRunOutcome =+ | { ok: true; sessionId: string; text: string; agentKind?: string; model?: string }+ | {+ ok: false;+ errorCode: 'HOST_NOT_READY' | 'BUSY' | 'SESSION_UNAVAILABLE' | 'TURN_FAILED' | 'TIMEOUT' | 'INTERNAL';+ message: string;+ };++export type GhostErrandRunner = (+ request: GhostErrandRunRequest,+ hooks?: GhostErrandRunHooks,+) => Promise<GhostErrandRunOutcome>;++export interface GhostErrandSlotDeps {+ getGhost(id: string): InstalledGhost | null;+ runner?: GhostErrandRunner | null;+ /** 管子续命挂钩(同 cindySlot 契约;wait 模式的署名单在途期间续命)。 */+ holdPipeCall?(ghostId: string, callId: string, budgetMs: number): void;+ releasePipeCall?(ghostId: string, callId: string): void;+ now?: () => number;+ createJobId?: () => string;+ log?: {+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ };+}++/** 在途/完成的派活任务记录(内存表;语义同 cindySlot 的 CindyAsyncJob)。 */+interface ErrandJob {+ ghostId: string;+ startedAt: number;+ status: 'running' | 'done' | 'failed';+ /** runner 一旦确定 errand 会话即回填(running 期即可见)。 */+ sessionId?: string;+ result?: { sessionId: string; text: string; agentKind?: string; model?: string };+ errorCode?: GhostAgentErrandErrorCode;+ error?: string;+ doneAt?: number;+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function fail(+ errorCode: GhostAgentErrandErrorCode,+ message: string,+): GhostPipeAgentErrandResult {+ return { ok: false, errorCode, message };+}++/** 结果截断(超长从头保留,尾部带明示标记——静默截断会让插件误判拿到了全文)。 */+export function clampErrandResultText(text: string): string {+ if (text.length <= GHOST_ERRAND_MAX_RESULT_CHARS) return text;+ return `${text.slice(0, GHOST_ERRAND_MAX_RESULT_CHARS)}\n…[结果超长,已截断]`;+}++export class GhostErrandSlot {+ private readonly jobs = new Map<string, ErrandJob>();+ private readonly inFlightGhosts = new Set<string>();+ private readonly lastRunAt = new Map<string, number>();+ private runner: GhostErrandRunner | null;++ constructor(private readonly deps: GhostErrandSlotDeps) {+ this.runner = deps.runner ?? null;+ }++ /** maker-ipc 初始化完成后注入真实 runner;传 null 用于退出清理。 */+ setRunner(runner: GhostErrandRunner | null): void {+ this.runner = runner;+ }++ /** 插件停用/卸载时清除节流状态与任务记录,防止权限/信息残留。 */+ clearGhost(ghostId: string): void {+ this.lastRunAt.delete(ghostId);+ for (const [jobId, job] of [...this.jobs]) {+ if (job.ghostId === ghostId) this.jobs.delete(jobId);+ }+ }++ /** 处理一条 agent-errand-request;所有失败折叠成结构化返回,永不 reject。 */+ async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeAgentErrandResult> {+ this.sweepJobs();+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost?.enabled || !ghost.manifest.slots.includes('agent') || ghost.manifest.agent?.errand !== true) {+ return fail('PERMISSION_DENIED', '插件未申请「派活取件」权限(身份卡 agent.errand),或当前未启用');+ }+ if (!isPlainObject(payload) || payload.type !== 'agent-errand-request') {+ return fail('INVALID_REQUEST', 'agent-errand-request 载荷必须是对象');+ }+ if (payload.kind === 'query') {+ return this.handleQuery(ghostId, payload);+ }+ if (payload.kind !== 'run') {+ return fail('INVALID_REQUEST', "kind 必须是 'run' 或 'query'");+ }++ if (+ typeof payload.task !== 'string' ||+ payload.task.trim().length === 0 ||+ payload.task.length > GHOST_ERRAND_MAX_TASK_CHARS+ ) {+ return fail('INVALID_REQUEST', `task 必须是 1–${GHOST_ERRAND_MAX_TASK_CHARS} 字符的非空字符串`);+ }+ if (+ payload.title !== undefined &&+ (typeof payload.title !== 'string' || payload.title.trim().length === 0 || payload.title.length > 100)+ ) {+ return fail('INVALID_REQUEST', 'title 必须是 1–100 字符的字符串');+ }+ if (payload.mode !== undefined && payload.mode !== 'wait') {+ return fail('INVALID_REQUEST', "mode 只支持 'wait'(同步等待)或不传(异步受理 + query 轮询)");+ }+ if (+ payload.callId !== undefined &&+ (typeof payload.callId !== 'string' || payload.callId.length === 0 || payload.callId.length > MAX_CALL_ID_LEN)+ ) {+ return fail('INVALID_REQUEST', 'callId 不合法(1–128 字符的字符串,或不传)');+ }+ const callId = (payload.callId as string | undefined) ?? 'unattributed';++ // 结构化上下文:JSON 化由主机做(确定性代码),超限明拒。+ let contextJson: string | null = null;+ if (payload.context !== undefined) {+ try {+ contextJson = JSON.stringify(payload.context);+ } catch {+ return fail('INVALID_REQUEST', 'context 必须可以转换成 JSON');+ }+ if (contextJson.length > GHOST_ERRAND_MAX_CONTEXT_JSON_CHARS) {+ return fail('INVALID_REQUEST', `context 转成 JSON 后不能超过 ${GHOST_ERRAND_MAX_CONTEXT_JSON_CHARS} 字符`);+ }+ }++ // 频控两道:相邻提交最小间隔 + 每插件单在途。间隔在一切校验通过后才+ // 记账(runner 失败也不退,防重试放大,与 agentSlot 票据同纪律)。+ const now = this.now();+ const last = this.lastRunAt.get(ghostId) ?? 0;+ if (now - last < GHOST_ERRAND_MIN_INTERVAL_MS) {+ return fail('RATE_LIMITED', '派活太频繁,请稍后再试');+ }+ if (this.inFlightGhosts.has(ghostId)) {+ return fail('BUSY', '这个插件已有一单派活在途,先取回或等它完成');+ }+ if (!this.runner) {+ return fail('HOST_NOT_READY', '派活服务尚未准备好');+ }++ this.lastRunAt.set(ghostId, now);+ this.evictSettledJobs(ghostId);+ const jobId = (this.deps.createJobId ?? randomUUID)();+ const job: ErrandJob = { ghostId, startedAt: now, status: 'running' };+ this.jobs.set(jobId, job);+ this.inFlightGhosts.add(ghostId);++ // 任务消息组装是确定性代码:上下文以固定标记附尾,格式契约写进手册。+ const message =+ contextJson !== null+ ? `${payload.task}\n\n[结构化上下文 JSON]\n${contextJson}`+ : (payload.task as string);++ this.deps.log?.info('ghost errand run start', {+ ghostId,+ jobId,+ callId,+ mode: payload.mode === 'wait' ? 'wait' : 'submit',+ });++ const execute = async (): Promise<void> => {+ try {+ const outcome = await this.runner!(+ {+ ghostId,+ ghostVersion: ghost.manifest.version,+ message,+ ...(typeof payload.title === 'string' ? { title: payload.title.trim() } : {}),+ },+ {+ onSession: (sessionId) => {+ job.sessionId = sessionId;+ },+ },+ );+ if (outcome.ok) {+ job.status = 'done';+ job.sessionId = outcome.sessionId;+ job.result = {+ sessionId: outcome.sessionId,+ text: clampErrandResultText(outcome.text),+ ...(outcome.agentKind !== undefined ? { agentKind: outcome.agentKind } : {}),+ ...(outcome.model !== undefined ? { model: outcome.model } : {}),+ };+ } else {+ job.status = 'failed';+ job.errorCode = outcome.errorCode;+ job.error = outcome.message;+ }+ } catch (err) {+ job.status = 'failed';+ job.errorCode = 'INTERNAL';+ job.error = err instanceof Error ? err.message : String(err);+ } finally {+ job.doneAt = this.now();+ this.inFlightGhosts.delete(ghostId);+ if (job.status === 'failed') {+ this.deps.log?.warn('ghost errand run failed', {+ ghostId,+ jobId,+ errorCode: job.errorCode,+ error: job.error,+ });+ } else {+ this.deps.log?.info('ghost errand run done', {+ ghostId,+ jobId,+ sessionId: job.sessionId,+ chars: job.result?.text.length ?? 0,+ });+ }+ }+ };++ if (payload.mode === 'wait') {+ // 同步等待:署名单在途期间替管子那头的 tool-call 续命(预算直接给到+ // 天花板,extendDeadline 会按 GHOST_PIPE_CALL_MAX_TOTAL_MS 钳制)。+ const shouldHold = callId !== 'unattributed';+ if (shouldHold) this.deps.holdPipeCall?.(ghostId, callId, GHOST_PIPE_CALL_MAX_TOTAL_MS);+ try {+ await execute();+ } finally {+ if (shouldHold) this.deps.releasePipeCall?.(ghostId, callId);+ }+ return this.jobResult(jobId, job);+ }++ void execute();+ return {+ ok: true,+ jobId,+ status: 'running',+ ...(job.sessionId !== undefined ? { sessionId: job.sessionId } : {}),+ };+ }++ private handleQuery(+ ghostId: string,+ payload: Record<string, unknown>,+ ): GhostPipeAgentErrandResult {+ if (+ typeof payload.jobId !== 'string' ||+ payload.jobId.length === 0 ||+ payload.jobId.length > MAX_JOB_ID_LEN+ ) {+ return fail('INVALID_REQUEST', 'jobId 不合法');+ }+ const job = this.jobs.get(payload.jobId);+ // 归属校验与查无此单同一句话术:不给沙箱探测别人 jobId 的空间。+ if (!job || job.ghostId !== ghostId) {+ return fail('JOB_NOT_FOUND', '查无此任务(可能已过期或主机重启过),请重新提交');+ }+ return this.jobResult(payload.jobId, job);+ }++ /** 把任务记录折叠成协议返回(run wait 收口与 query 共用)。 */+ private jobResult(jobId: string, job: ErrandJob): GhostPipeAgentErrandResult {+ if (job.status === 'running') {+ return {+ ok: true,+ jobId,+ status: 'running',+ ...(job.sessionId !== undefined ? { sessionId: job.sessionId } : {}),+ elapsedSeconds: Math.max(0, Math.round((this.now() - job.startedAt) / 1000)),+ };+ }+ if (job.status === 'done' && job.result) {+ return {+ ok: true,+ jobId,+ status: 'done',+ sessionId: job.result.sessionId,+ text: job.result.text,+ ...(job.result.agentKind !== undefined ? { agentKind: job.result.agentKind } : {}),+ ...(job.result.model !== undefined ? { model: job.result.model } : {}),+ };+ }+ return fail(job.errorCode ?? 'TURN_FAILED', job.error ?? '派活失败');+ }++ private now(): number {+ return this.deps.now?.() ?? Date.now();+ }++ /** 惰性清理:完成态超过 TTL 出表(running 永不清,同 cindySlot)。 */+ private sweepJobs(): void {+ if (this.jobs.size === 0) return;+ const now = this.now();+ for (const [jobId, job] of [...this.jobs]) {+ if (job.status !== 'running' && now - (job.doneAt ?? 0) > GHOST_ERRAND_JOB_TTL_MS) {+ this.jobs.delete(jobId);+ }+ }+ }++ /** 新 job 入表前按插件淘汰最旧完成记录(条数上限,同 cindySlot 契约)。 */+ private evictSettledJobs(ghostId: string): void {+ const entries = [...this.jobs.entries()].filter(([, j]) => j.ghostId === ghostId);+ const running = entries.filter(([, j]) => j.status === 'running').length;+ const settled = entries+ .filter(([, j]) => j.status !== 'running')+ .sort((a, b) => (a[1].doneAt ?? 0) - (b[1].doneAt ?? 0));+ const excess = settled.length - (MAX_SETTLED_JOBS_PER_GHOST - running - 1);+ for (let i = 0; i < excess; i++) {+ this.jobs.delete(settled[i][0]);+ }+ }+}diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex bdb8155019..8936bccfb1 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -882,8 +882,9 @@ key、未知字段、原清单没有的条目、类型或长度不合格、文node secretBindings key、setup kv key——都不能使用 \`__proto__\`、\`constructor\` 或\`prototype\`;这些名称是宿主保留键,打包时会直接拒绝。-十五个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图)、\`agent\`(让-当前 Agent 开始一个普通用户回合,见 §4.11)、\`panel\`(常驻+十五个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图/快问快答,+见 §4 与 §4.0.2)、\`agent\`(让+当前 Agent 开始一个普通用户回合,或派活取回结果,见 §4.11 / §4.11.1)、\`panel\`(常驻面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话事件 + 拦截用户消息,见 §4.6)、\`network\`(访问自带服务的域名白名单 HTTP,主机代发,见 §4.7)、\`notify\`(弹系统轻提示,主机画壳带你的身份头,见 §4.9)、\`fs\`(请主机@@ -899,6 +900,9 @@ Claude Code 与 Codex 都能发现,见 §4.16)、\`workspace\`(请主机为项聊天卡片后发起一次 Agent 回合;这一档不写配套字段。若确实需要没有当次点击也能自动发起,额外写 \`"agent": { "background": true }\`。后台档会在装入确认框单独显示为更高风险权限,而且仍只能使用用户曾通过点击卡片与你建立关联的会话。+要把任务交给 Agent 干并**取回结果**(而不是发进用户的会话),另写+\`"agent": { "errand": true }\`(可与 background 并存),见 §4.11.1;同样是装入+确认框单列的高风险档。**node 工作进程详单**(声明 node 槽时必写,详见 §4.12):@@ -1272,6 +1276,39 @@ await cindy.send({ type: 'cindy-request', kind: 'release_media', hash: r.hash })媒体库」并写明上限——这是唯一一条"不花钱就能写用户媒体库"的能力,所以要用户单独点头。别为了省事把它当默认能力申请:不做面板素材加工的插件不要声明。+### 4.0.2 快问快答:向 Cindy 的快速通道要一段文字(oneshot_text)++需要"问一句、拿一段文字答案"(总结、分类、改写、抽取)而不需要 Agent 动用+任何工具时,不要发起 Agent 回合——用快问快答,几秒到几十秒出结果,便宜得多:++\`\`\`js+// 需声明:"slots": [..., "cindy"], "cindy": { "text": ["oneshot"] }+const r = await cindy.send({+ type: 'cindy-request',+ kind: 'oneshot_text',+ prompt: '把下面的反馈按情绪分成 正面/负面/中性,只回类别词:\\n' + feedback,+ // expectJson: true, // 可选:要求只输出 JSON,主机校验可解析+ // maxTokens: 256, // 可选:回答预算(1–4096,缺省 1024)+ callId: msg.callId, // tool-call 触发时务必带上(归因)+});+// 成功:{ ok:true, text:'…', model:'…' }(model = 实际应答的通道/型号,仅诊断)+// 失败:{ ok:false, message, errorCode }+\`\`\`++规矩与边界:++- 它走主机的**轻量任务模型链**(用户在设置里配置的快速通道,与会话自动起+ 标题同一条),不拉起 Agent、没有工具、碰不到用户文件、不进任何会话——+ 要"干活"(读文件、查资料、多步操作)请用派活(§4.11.1);+- 选型不在你手里,也没有 tier/model 参数:链由用户配置,主机逐候选兜底;+- \`errorCode:'NO_CANDIDATE'\` = 用户当前没有可用的快速通道(未配置或凭证+ 不可用)。**这是正常失败面**:如实提示用户,不要重试轰炸;+- \`expectJson: true\` 时主机会剥掉代码围栏并校验 JSON.parse,解析失败返回+ \`errorCode:'BAD_MODEL_OUTPUT'\`(message 带原始输出开头供排查)。字段结构+ 在 prompt 里自己描述,主机不做逐字段 schema 校验;+- prompt ≤32768 字符;同步返回,没有异步单;每插件在途上限与媒体代办共用+ (用户可配);装入确认框会单列一行「可向 Cindy 的快速通道提问」。+## 4.1 宿主公开上下文(request,无需卡槽)电子脑需要按宿主构建身份或当前语言选择公开配置/界面文案时,走只读 request。当前只暴露@@ -2127,6 +2164,45 @@ await cindy.agent.run({一条 Agent 请求,后台请求之间至少间隔 10 秒。这个能力可能自动产生模型费用,只在产品确实需要时申请,不要把 \`sessionId\` 当作任意跨会话控制口。+### 4.11.1 派活取件:让 Agent 替你干活并取回结果(errand)++\`agent.run\` 把回合发进**用户的会话**,结果是给用户看的;派活(errand)相反:+任务在**你的专属 errand 会话**里跑,Agent 的最终回复文字交回**你**手里继续用。+需声明 \`"slots": [..., "agent"]\` + \`"agent": { "errand": true }\`(装入确认高风险单列)。++\`\`\`js+// 提交(默认异步:先拿单号,再轮询取件——Agent 干活是分钟级的):+const r = await cindy.agent.errand({+ task: '阅读工作目录下的 README 并总结要点(200 字以内)',+ // context: { anything: '结构化上下文,主机 JSON 化后附在任务消息尾部' },+ // title: '我的插件 · 代办', // 仅首次创建 errand 会话时用作标题+ // mode: 'wait', // 同步等到完成(30 分钟顶);默认不传 = 异步+ callId: msg.callId,+});+// 受理:{ ok:true, jobId, status:'running', sessionId }+// 轮询取件(建议间隔 ≥5s;做成"提交 + 查询"两个工具让 AI 自己掌握节奏):+const q = await cindy.agent.queryErrand({ jobId: r.jobId });+// 进行中:{ ok:true, jobId, status:'running', sessionId, elapsedSeconds }+// 完成: { ok:true, jobId, status:'done', sessionId, text, agentKind, model }+// 失败: { ok:false, errorCode, message }+\`\`\`++主机强制的边界(都不是建议):++- **任务只进普通 user 消息**,绝不进 system prompt;+- errand 会话在**侧边栏可见**,用户可随时旁观、叫停——没有隐身会话;+- 用哪个 agent/模型/思考强度、多大动手权限、在哪个目录干活,全部由**用户**在+ 你的插件详情页「AI 代办」卡里配置;缺省跟随用户新建草稿的选择,权限档缺省+ **只读**(不能改任何文件),目录缺省是插件专属文件夹。别假设你能写文件——+ 只读档下让 Agent"分析/回答"没问题,"修改"类任务要在文案里引导用户先放开+ 权限档;+- 每插件同时 1 单在途、相邻提交至少隔 10 秒;结果超过 64K 字符会截断(尾部带+ 标记);完成结果保留 30 分钟,应用重启后查无此单(按可重新提交处理);+- \`errorCode:'BUSY'\` = 你已有一单在途,或用户恰好正在 errand 会话里说话;+ \`'NO_CANDIDATE'\` 不存在于此——但会话创建/派发失败有 \`'SESSION_UNAVAILABLE'\`,+ 超时有 \`'TIMEOUT'\`(任务可能仍在会话里继续,提示用户打开会话查看)。+- 这个能力必然产生模型费用且耗时分钟级:能用快问快答(§4.0.2)解决的,不要派活。+## 4.12 随包 Node 工作进程与 stdio MCP(node 槽)\`main.js\` 永远还是浏览器沙箱代码。声明 node 槽后,主机额外为**这一段意识**按需@@ -2652,7 +2728,7 @@ const ensured = await cindy.workspace({- panel.systemButtons 格式错(不是对象、未知键、值非布尔,或 position:"tab" 时声明——页签形态没有标准头)- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 2- cindy 详单格式错(未知类目/动作、空数组、有详单但 slots 没有 "cindy")-- agent 详单格式错(有详单但 slots 没有 "agent",或 background 不是 true;只需点击触发时应省略 agent 字段)+- agent 详单格式错(有详单但 slots 没有 "agent",或 background / errand 都不是 true;只需点击触发时应省略 agent 字段)- node 详单格式错(槽/详单不成对、entry 不是包内 CommonJS .js/.cjs、protocol 不在 json-rpc-stdio / mcp-stdio、写了 command/args/shell/env、resident 又写 idleTimeoutSeconds)- id 用了 \`cindy-\` / \`filo-\` / \`xd-\` 前缀(官方保留,正式版用户通道拒装;给自己的意识换个前缀)diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 8a314e67dd..8bf6053cb6 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -138,6 +138,8 @@ import {type CindyVideoParams,} from './cindySlot.js';import { GhostAgentSlot, type GhostAgentTurnRunner } from './agentSlot.js';+import { GhostErrandSlot, type GhostErrandRunner } from './errandSlot.js';+import { readGhostErrandConfig, writeGhostErrandConfig } from './errandPrefsStore.js';import { GhostNodeRuntimeBroker } from './nodeRuntimeBroker.js';import { GhostPickSlot } from './pickSlot.js';import { GhostPreviewSlot } from './previewSlot.js';@@ -727,6 +729,7 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {getGhostRuntime().stop(id);getGhostNodeRuntimeBroker().stop(id);getGhostAgentSlot().clearGhost(id);+ getGhostErrandSlot().clearGhost(id);},onApplyStart: () => {tipShown = true;@@ -919,6 +922,33 @@ export function setGhostAgentTurnRunner(runner: GhostAgentTurnRunner | null): vogetGhostAgentSlot().setRunner(runner);}+let errandSlotSingleton: GhostErrandSlot | null = null;++/** 派活取件槽单例(agent 槽 errand 加档):资格审/频控/任务表的统一守门点。 */+export function getGhostErrandSlot(): GhostErrandSlot {+ if (!errandSlotSingleton) {+ errandSlotSingleton = new GhostErrandSlot({+ getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,+ // wait 模式的署名单在途期间替管子那头的 tool-call 续命(同 cindy 槽契约)。+ holdPipeCall: (ghostId, callId, budgetMs) =>+ getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),+ releasePipeCall: (ghostId, callId) => getGhostPipeDispatcher().releaseCall(ghostId, callId),+ log,+ });+ }+ return errandSlotSingleton;+}++/** maker-ipc 完成初始化后注入真实派活 runner;传 null 用于退出清理。 */+export function setGhostErrandRunner(runner: GhostErrandRunner | null): void {+ getGhostErrandSlot().setRunner(runner);+}++/** 插件展示名(errand 会话默认标题等宿主侧使用;未装返回 null)。 */+export function getInstalledGhostName(id: string): string | null {+ return getGhostManager().list().find((g) => g.manifest.id === id)?.manifest.name ?? null;+}+let nodeRuntimeBrokerSingleton: GhostNodeRuntimeBroker | null = null;/** 随包 Node 工作进程单例:每个活跃插件一个进程,main.js 经主机中继调用。 */@@ -2007,6 +2037,36 @@ export function getGhostCindySlot(): GhostCindySlot {// 在途并发上限:用户级隐藏配置(ghost-cindy-prefs.json 的 inflightLimits),// 缺省 null = 不限并发;每单现读,改配置即生效。getInflightLimit: (ghostId) => readGhostCindyInflightLimit(ghostId),+ // 快问快答(text.oneshot):走轻量任务模型链(与会话起标题/任务摘要+ // 同一条,用户在设置里配置)。动态 import:utility-model 的传递依赖在+ // 模块顶层读 electron app 路径,静态引入会把这条链拽进所有 import 本+ // 模块的单测(hook-script-generator 同款做法)。失败面折叠成 slot 层+ // 的三档 reason;attempts 细节只进日志,不给沙箱探测面。+ oneshotText: async ({ prompt, maxTokens, timeoutMs }) => {+ const [{ requestUtilityText }, { getMaker }] = await Promise.all([+ import('../utility-model/oneShotCandidates.js'),+ import('../maker-host/index.js'),+ ]);+ const r = await requestUtilityText(getMaker(), prompt, { maxTokens, timeoutMs });+ if (r.ok) {+ return { ok: true, text: r.text, model: `${r.providerId}/${r.model}` };+ }+ log.warn('ghost oneshot_text utility chain failed', {+ reason: r.reason,+ attempts: r.attempts.map((a) => `${a.providerId}/${a.model}:${a.reason}`),+ });+ if (r.reason === 'no_candidate') {+ return {+ ok: false,+ reason: 'no_candidate',+ message: '当前没有可用的快速通道模型(用户未配置或凭证不可用),请如实告知用户并优雅降级',+ };+ }+ if (r.reason === 'timeout') {+ return { ok: false, reason: 'timeout', message: '快问快答超时,请稍后再试' };+ }+ return { ok: false, reason: 'failed', message: '快速通道各候选均失败,请稍后再试' };+ },// 管子续命挂钩:同步视频代办(署名单)在途期间替 tool-call 续命,// 免得分钟级生成被管子 330s 基础窗口掐掉(任务后台继续烧钱、结果作废)。// ghostId 由派发器配对验身:冒用他人在途 callId 不能续命/收短别人的卷。@@ -2647,6 +2707,7 @@ export async function installOrUpdateMarketGhostPackage(runtime.stop(expected.ghostId);getGhostNodeRuntimeBroker().stop(expected.ghostId);getGhostAgentSlot().clearGhost(expected.ghostId);+ getGhostErrandSlot().clearGhost(expected.ghostId);let result: Awaited<ReturnType<typeof manager.update>>;try {result = await manager.update(cindyFilePath);@@ -2714,6 +2775,7 @@ export async function uninstallGhostAndCleanup(runtime.stop(id);getGhostNodeRuntimeBroker().stop(id);getGhostAgentSlot().clearGhost(id);+ getGhostErrandSlot().clearGhost(id);getGhostSubscriptionGateway().dropGhost(id);const result = await manager.uninstall(id, { notify: false });if ('rejection' in result) throwUninstallError(result.rejection);@@ -3257,7 +3319,8 @@ export function registerGhostIpc(): void {// 代办,返回值即结果)/ card-update(卡槽③供片,cardService 校验链)/// notify(系统提示,notifySlot 资格审+限速)/ fs-request(fs 槽代写文件,// fsSlot 三档守门)/ agent-request(Agent 新回合,一次性用户票或后台权限- // 守门)/ node-request(随包 Node JSON-RPC/MCP stdio 中继)/ pick-request+ // 守门)/ agent-errand-request(派活取件,agent.errand 加档 + 频控守门)/+ // node-request(随包 Node JSON-RPC/MCP stdio 中继)/ pick-request// (系统级选文件夹,用户亲选即授权)/ preview-request(右侧栏开预览标签,// preview.hosts 白名单守门)/ workspace-request(工作区会话入口,亲选或// 确认卡授权,判重/创建在 workspaceSlot)。其它类型一律拒。@@ -3310,6 +3373,13 @@ export function registerGhostIpc(): void {if (type === 'agent-request') {return getGhostAgentSlot().handleRequest(id, payload);}+ // agent-errand-request = 派活取件(agent 槽 errand 加档):任务进插件+ // 专属 errand 会话跑一轮,最终回复文字取回给插件;任务文本同样只进+ // 普通 user 消息。资格审/频控/任务表在 errandSlot,会话与收口在注入+ // 的 runner(maker-ipc)。+ if (type === 'agent-errand-request') {+ return getGhostErrandSlot().handleRequest(id, payload);+ }// node-request 只在 main.js → contextBridge → 主机方向开放。子进程反向// JSON-RPC 请求恒被 broker 拒绝,因此 Node 不能绕过 main.js 控制 Cindy。if (type === 'node-request') {@@ -3609,6 +3679,28 @@ export function registerGhostIpc(): void {return { overrides };});+ // ── agent 槽派活(errand)每插件配置(插件详情页「AI 代办」卡)──+ // 读走 sendSync(与 cindy-prefs 同理:详情页首帧同帧渲染);写走 invoke,+ // 整卡替换,值域清洗在存储层(errandPrefsStore.normalizeConfig 白名单,+ // permissionMode 只认 plan/acceptEdits/auto——bypassPermissions 协议上不存在)。+ // model/providerId 不在此处对目录校验:与 sessions:create 同一信任面+ // (可信 renderer 配置面),过期值由 errand runner 建会话时按 mapper 兜底。+ ipcMain.on('ghosts:errand-prefs', (event, ghostId: unknown) => {+ event.returnValue = {+ config: typeof ghostId === 'string' ? readGhostErrandConfig(ghostId) : {},+ };+ });+ ipcMain.handle('ghosts:errand-prefs:set', (_event, ghostId: unknown, config: unknown) => {+ if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {+ throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');+ }+ if (config !== null && (typeof config !== 'object' || Array.isArray(config))) {+ throwIpcError('INVALID_PARAMS', 'config must be an object or null');+ }+ const saved = writeGhostErrandConfig(ghostId, config as Record<string, unknown> | null);+ return { config: saved };+ });+ipcMain.handle('ghosts:install', async (event, lizFilePath: unknown, opts: unknown) => {assertTrustedAppRendererEvent(event);if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {@@ -3668,6 +3760,7 @@ export function registerGhostIpc(): void {runtime.stop(inspected.manifest.id);getGhostNodeRuntimeBroker().stop(inspected.manifest.id);getGhostAgentSlot().clearGhost(inspected.manifest.id);+ getGhostErrandSlot().clearGhost(inspected.manifest.id);let result: Awaited<ReturnType<typeof manager.update>>;try {result = await manager.update(lizFilePath, { expectedPackageSha256 });diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.tsindex a360f87eba..4cbedb31f5 100644--- a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts@@ -26,6 +26,7 @@ import { and, eq, isNull, isNotNull, ne, or } from 'drizzle-orm';import { getDbClient } from '../client/current';import { sessions } from '../schema';import { sessionCreateToRow } from '../mapper';+import { ensureDialogueWorkspaceDir } from '../dialogueWorkspace';import { ensureProjectGitInitialized } from '../../git-snapshot/projectGitBootstrap';import { readGitSafetySettings } from '../../maker-host/git-safety-settings-store';import { upsertRecentWorkdir } from './recentWorkdirs';@@ -146,3 +147,87 @@ export async function createPluginDraftSession(params: {});return id;}++/**+ * 创建 agent 槽「派活取件(errand)」的专属会话行(不拉起 agent 进程)。+ *+ * 与 createPluginDraftSession 的分工:workspace 槽建的是用户项目里的普通+ * draft;errand 会话是插件的干活间——缺省落在专属 dialogue 目录(不碰用户+ * 项目),只有用户在插件详情页亲手选了项目目录才落 project。权限档由调用方+ * (errand runner)按用户配置传入,缺省档 plan(只读,2026-07-31 定案)在+ * runner 侧兜底,这里照传入值落库。source='plugin' 语义同上;Orca 字段+ * 显式排除——errand 会话在侧边栏可见、可旁观,不做隐藏会话。+ */+export async function createGhostErrandSession(params: {+ ghostId: string;+ title: string | null;+ agentKind?: 'cc' | 'codex';+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId?: string | null;+ permissionMode: 'plan' | 'acceptEdits' | 'auto';+ /** 用户亲选的项目目录(绝对路径);缺省 = 专属 dialogue 目录。 */+ workingDir?: string;+ notifySessionCreated?: (info: { sessionId: string; workdir?: string }) => void;+}): Promise<string> {+ const db = getDbClient().drizzle;+ const now = Date.now();+ const id = randomUUID();+ const projectDir = params.workingDir+ ? (normalizeWorkingDirForStorage(params.workingDir) ?? undefined)+ : undefined;+ const workspaceKind = projectDir ? ('project' as const) : ('dialogue' as const);+ const workingDir = projectDir ?? ensureDialogueWorkspaceDir(id, now);+ const insertRow = {+ ...sessionCreateToRow(+ id,+ {+ workingDir,+ workspaceKind,+ permissionMode: params.permissionMode,+ ...(params.agentKind ? { agentKind: params.agentKind } : {}),+ ...(params.model ? { model: params.model } : {}),+ ...(params.effort ? { effort: params.effort } : {}),+ ...(params.fastMode !== undefined ? { fastMode: params.fastMode } : {}),+ ...(params.providerId !== undefined ? { providerId: params.providerId } : {}),+ },+ now,+ ),+ source: 'plugin' as const,+ ...(params.title ? { title: params.title } : {}),+ };+ // 与既有 create 同流程;dialogue 目录由 projectGitBootstrap 自带守卫跳过。+ await ensureProjectGitInitialized({+ workingDir: insertRow.workingDir,+ workspaceKind: insertRow.workspaceKind,+ remoteHostId: insertRow.remoteHostId,+ sessionId: id,+ autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,+ source: 'plugin-errand-session',+ });+ await db.insert(sessions).values(insertRow);+ if (projectDir && insertRow.workingDir) {+ // 项目目录是用户在插件详情页亲手选的,进"最近项目"合理;dialogue 目录+ // 是 app 管理的临时间,不进。失败仅日志,不阻断创建。+ void upsertRecentWorkdir(insertRow.workingDir, now);+ }+ try {+ params.notifySessionCreated?.({+ sessionId: id,+ ...(insertRow.workingDir ? { workdir: insertRow.workingDir } : {}),+ });+ } catch (error) {+ log.warn('[plugin-errand] notifySessionCreated failed', {+ sessionId: id,+ err: error instanceof Error ? error.message : String(error),+ });+ }+ log.info('[plugin-errand] errand session created', {+ sessionId: id,+ ghostId: params.ghostId,+ workspaceKind,+ workingDir: insertRow.workingDir,+ });+ return id;+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.tsnew file mode 100644index 0000000000..b6293569a4--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts@@ -0,0 +1,240 @@+/**+ * ghostErrandRunner.test.ts — 派活执行器单测(纯 DI,无 Electron)。+ * 覆盖:配置解析与权限档钳制、专属会话建/复用/关键配置变更重建、忙检、+ * 投递失败映射、queued 竞态如实报 BUSY、turn 收口取文、DB 兜底取文、超时。+ */++import { describe, it, expect, vi } from 'vitest';++import {+ clampErrandPermissionMode,+ createGhostErrandRunner,+ type GhostErrandRunnerDeps,+ type GhostErrandSessionRow,+} from '../ghostErrandRunner';+import type { AgentEvent } from '@cindy/maker-core';++/** 最小可观察会话替身:测试手动放事件。 */+function fakeSession(id: string): {+ session: { id: string; onEvent(listener: (ev: AgentEvent) => void): () => void };+ emit: (ev: AgentEvent) => void;+} {+ const listeners = new Set<(ev: AgentEvent) => void>();+ return {+ session: {+ id,+ onEvent(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ emit: (ev) => listeners.forEach((l) => l(ev)),+ };+}++const textEvent = (text: string): AgentEvent =>+ ({ type: 'text', source: 'codex', data: { text, isFinal: true } }) as unknown as AgentEvent;+const doneEvent = (): AgentEvent => ({ type: 'done', data: {} }) as unknown as AgentEvent;++const ACTIVE_ROW: GhostErrandSessionRow = {+ status: 'active',+ agentKind: 'cc',+ model: 'claude-x',+ permissionMode: 'plan',+ workingDir: '/dialogues/x',+ workspaceKind: 'dialogue',+};++function makeDeps(overrides: Partial<GhostErrandRunnerDeps> = {}): {+ deps: GhostErrandRunnerDeps;+ emitters: Map<string, ReturnType<typeof fakeSession>>;+ writes: Array<[string, string | null]>;+} {+ const emitters = new Map<string, ReturnType<typeof fakeSession>>();+ const writes: Array<[string, string | null]> = [];+ const ensureEmitter = (id: string) => {+ let e = emitters.get(id);+ if (!e) {+ e = fakeSession(id);+ emitters.set(id, e);+ }+ return e;+ };+ const deps: GhostErrandRunnerDeps = {+ readConfig: () => ({}),+ readSessionId: () => null,+ writeSessionId: (ghostId, sessionId) => {+ writes.push([ghostId, sessionId]);+ },+ getSessionRow: async () => ACTIVE_ROW,+ createSession: vi.fn(async () => 'sess-new'),+ getGhostName: () => '帮手',+ getDraftDefaults: () => ({}),+ normalizeWorkingDir: (dir) => dir.replace(/\/+$/, ''),+ isSessionBusy: () => false,+ dispatch: vi.fn(async () => ({ ok: true as const, wakeKind: 'resumed' as const })),+ getObservableSession: (id) => ensureEmitter(id).session,+ onSilentStopSettled: () => () => undefined,+ readLatestAssistantText: async () => null,+ log: { info: () => undefined, warn: () => undefined },+ sleep: async () => undefined,+ ...overrides,+ };+ return { deps, emitters, writes };+}++const REQUEST = { ghostId: 'helper', ghostVersion: '1.0.0', message: '干活' };++describe('权限档钳制', () => {+ it('白名单外/缺省一律收敛到 plan;bypassPermissions 不存在', () => {+ expect(clampErrandPermissionMode(undefined)).toBe('plan');+ expect(clampErrandPermissionMode('bypassPermissions')).toBe('plan');+ expect(clampErrandPermissionMode('ask')).toBe('plan');+ expect(clampErrandPermissionMode('acceptEdits')).toBe('acceptEdits');+ expect(clampErrandPermissionMode('auto')).toBe('auto');+ });+});++describe('专属会话建/复用', () => {+ it('无映射时创建会话并写映射,onSession 尽早回报', async () => {+ const { deps, emitters, writes } = makeDeps();+ const runner = createGhostErrandRunner(deps);+ const seen: string[] = [];+ const p = runner(REQUEST, { onSession: (sid) => seen.push(sid) });+ await vi.waitFor(() => {+ expect(emitters.has('sess-new')).toBe(true);+ });+ const e = emitters.get('sess-new')!;+ e.emit(textEvent('答案'));+ e.emit(doneEvent());+ const r = await p;+ expect(r).toMatchObject({ ok: true, sessionId: 'sess-new', text: '答案', agentKind: 'cc' });+ expect(seen).toEqual(['sess-new']);+ expect(writes).toContainEqual(['helper', 'sess-new']);+ });++ it('映射有效且配置匹配时复用,不再创建', async () => {+ const createSession = vi.fn(async () => 'should-not-happen');+ const { deps, emitters } = makeDeps({+ readSessionId: () => 'sess-old',+ createSession,+ });+ const runner = createGhostErrandRunner(deps);+ const p = runner(REQUEST);+ await vi.waitFor(() => expect(emitters.has('sess-old')).toBe(true));+ const e = emitters.get('sess-old')!;+ e.emit(textEvent('ok'));+ e.emit(doneEvent());+ expect(await p).toMatchObject({ ok: true, sessionId: 'sess-old' });+ expect(createSession).not.toHaveBeenCalled();+ });++ it('关键配置变了(权限档不匹配)→ 解除映射并重建', async () => {+ const { deps, emitters, writes } = makeDeps({+ readConfig: () => ({ permissionMode: 'auto' }),+ readSessionId: () => 'sess-old',+ getSessionRow: async (id) => (id === 'sess-old' ? ACTIVE_ROW : ACTIVE_ROW),+ });+ const runner = createGhostErrandRunner(deps);+ const p = runner(REQUEST);+ await vi.waitFor(() => expect(emitters.has('sess-new')).toBe(true));+ const e = emitters.get('sess-new')!;+ e.emit(doneEvent());+ await p;+ expect(writes[0]).toEqual(['helper', null]);+ expect(writes).toContainEqual(['helper', 'sess-new']);+ });++ it('配置目录经规范化再比对(尾斜杠不导致重建)', async () => {+ const createSession = vi.fn(async () => 'should-not-happen');+ const { deps, emitters } = makeDeps({+ readConfig: () => ({ workingDir: '/proj/demo/' }),+ readSessionId: () => 'sess-proj',+ getSessionRow: async () => ({+ ...ACTIVE_ROW,+ workspaceKind: 'project',+ workingDir: '/proj/demo',+ }),+ createSession,+ });+ const runner = createGhostErrandRunner(deps);+ const p = runner(REQUEST);+ await vi.waitFor(() => expect(emitters.has('sess-proj')).toBe(true));+ emitters.get('sess-proj')!.emit(doneEvent());+ await p;+ expect(createSession).not.toHaveBeenCalled();+ });+});++describe('忙检与投递', () => {+ it('会话正忙 → BUSY,不投递', async () => {+ const dispatch = vi.fn();+ const { deps } = makeDeps({+ readSessionId: () => 'sess-1',+ isSessionBusy: () => true,+ dispatch: dispatch as unknown as GhostErrandRunnerDeps['dispatch'],+ });+ expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({+ ok: false,+ errorCode: 'BUSY',+ });+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('投递返回 queued(竞态窗口)→ 如实报 BUSY', async () => {+ const { deps } = makeDeps({+ readSessionId: () => 'sess-1',+ dispatch: async () => ({ ok: true as const, wakeKind: 'queued' as const }),+ });+ expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({+ ok: false,+ errorCode: 'BUSY',+ });+ });++ it('投递失败映射:NOT_FOUND/ARCHIVED → SESSION_UNAVAILABLE 并解除映射', async () => {+ const { deps, writes } = makeDeps({+ readSessionId: () => 'sess-1',+ dispatch: async () => ({ ok: false as const, errorCode: 'ARCHIVED', message: '归档了' }),+ });+ expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({+ ok: false,+ errorCode: 'SESSION_UNAVAILABLE',+ });+ expect(writes).toContainEqual(['helper', null]);+ });+});++describe('收口与取文', () => {+ it('观察器无文本时回落 DB 最新 assistant 消息', async () => {+ const { deps, emitters } = makeDeps({+ readSessionId: () => 'sess-1',+ readLatestAssistantText: async () => 'DB 里的答案',+ });+ const runner = createGhostErrandRunner(deps);+ const p = runner(REQUEST);+ await vi.waitFor(() => expect(emitters.has('sess-1')).toBe(true));+ emitters.get('sess-1')!.emit(doneEvent());+ expect(await p).toMatchObject({ ok: true, text: 'DB 里的答案' });+ });++ it('终态错误 → TURN_FAILED', async () => {+ const { deps, emitters } = makeDeps({ readSessionId: () => 'sess-1' });+ const runner = createGhostErrandRunner(deps);+ const p = runner(REQUEST);+ await vi.waitFor(() => expect(emitters.has('sess-1')).toBe(true));+ // isTerminal: true 是 maker-core isTerminalAgentErrorEvent 的显式终态判据。+ emitters.get('sess-1')!.emit(+ { type: 'error', data: { message: '模型炸了', isTerminal: true } } as unknown as AgentEvent,+ );+ expect(await p).toMatchObject({ ok: false, errorCode: 'TURN_FAILED' });+ });++ it('超时 → TIMEOUT', async () => {+ const { deps, emitters } = makeDeps({ readSessionId: () => 'sess-1' });+ const runner = createGhostErrandRunner({ ...deps, turnTimeoutMs: 20 });+ const p = runner(REQUEST);+ await vi.waitFor(() => expect(emitters.has('sess-1')).toBe(true));+ expect(await p).toMatchObject({ ok: false, errorCode: 'TIMEOUT' });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.tsnew file mode 100644index 0000000000..abe6d3806e--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts@@ -0,0 +1,284 @@+/**+ * ghostErrandRunner —— 插件「派活取件(errand)」的主机执行器(maker-ipc 侧)。+ *+ * errandSlot(cindy-brain)只负责资格审/频控/任务表;真正的干活链在这里:+ *+ * 解析用户配置(errandPrefsStore,缺省跟随 New Maker 草稿偏好)+ * → 确保专属 errand 会话(映射存 prefs;失效/配置关键项变更则重建)+ * → 忙检(errand 会话正被占用即 BUSY,不排队——排队会让结果对不上单)+ * → sendToSessionInternal 统一通路投递(消息落库/进程拉起与用户亲发一致)+ * → observeHookTurn 收口(与飞书 bot / scheduler 同一套 turn 观察语义)+ * → 取最终回复文字(观察器累积为主,DB 最新 assistant 消息兜底)+ *+ * 安全不变量(与 errandSlot 头注释同一契约):任务文本只进普通 user 消息;+ * 权限档只认 plan/acceptEdits/auto(存储层与本层双重钳制,bypassPermissions+ * 在协议上不存在);errand 会话侧边栏可见,用户可旁观可随时停。+ *+ * 全部依赖注入(规则 14):register.ts 只做接线,本模块可单测。+ */++import {+ GHOST_ERRAND_PERMISSION_MODES,+ type GhostErrandPermissionMode,+} from '../../shared/ghost.js';+import type {+ GhostErrandRunner,+ GhostErrandRunOutcome,+} from '../cindy-brain/errandSlot.js';+import type { GhostErrandConfig } from '../cindy-brain/errandPrefsStore.js';+import { observeHookTurn, type ObservableSession } from '../hook-control/turnObserver.js';++/** turn 收口的兜底超时(25 分钟:低于管子 30 分钟天花板,给交卷留余量)。 */+const DEFAULT_TURN_TIMEOUT_MS = 25 * 60_000;++/** 收口后读 DB 兜底文本的重试(消息落库与 done 事件之间可能有毫秒级间隙)。 */+const DB_TEXT_RETRIES = 3;+const DB_TEXT_RETRY_DELAY_MS = 400;++/** errand 会话行的关键面(复用判定与结果归因用)。 */+export interface GhostErrandSessionRow {+ status: string;+ agentKind: string;+ model: string;+ permissionMode: string;+ workingDir: string | null;+ workspaceKind: string;+}++export interface GhostErrandRunnerDeps {+ readConfig(ghostId: string): GhostErrandConfig;+ readSessionId(ghostId: string): string | null;+ writeSessionId(ghostId: string, sessionId: string | null): void;+ getSessionRow(sessionId: string): Promise<GhostErrandSessionRow | null>;+ /** 建 errand 会话 DB 行(不拉 agent);config 已由本层解析合并完毕。 */+ createSession(params: {+ ghostId: string;+ title: string | null;+ agentKind?: 'cc' | 'codex';+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId?: string | null;+ permissionMode: GhostErrandPermissionMode;+ workingDir?: string;+ }): Promise<string>;+ /** 该插件的展示名(errand 会话默认标题用)。 */+ getGhostName(ghostId: string): string | null;+ /** 缺省选型来源:New Maker 草稿偏好快照(与 Orca worker 同源)。 */+ getDraftDefaults(vendor: 'claude-code' | 'codex'): {+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId?: string | null;+ };+ /**+ * 目录规范化(与 sessions 落库同一实现):配置目录必须先规范化再与 DB 行+ * 比对,否则"带尾斜杠 vs 不带"会让复用判定永远失败、每单都建新会话。+ */+ normalizeWorkingDir(dir: string): string | null;+ isSessionBusy(sessionId: string): boolean;+ /** 统一投递通路(sendToSessionInternal 的窄化面)。 */+ dispatch(params: { targetSessionId: string; message: string }): Promise<+ | { ok: true; wakeKind: 'resumed' | 'already-active' | 'created' | 'queued' }+ | { ok: false; errorCode: string; message: string }+ >;+ getObservableSession(sessionId: string): ObservableSession | null;+ onSilentStopSettled(+ sessionId: string,+ cb: (sessionId: string, reason: string) => void,+ ): () => void;+ /** 收口后读该会话 sinceMs 之后最新一条 assistant 正文(兜底;查无 → null)。 */+ readLatestAssistantText(sessionId: string, sinceMs: number): Promise<string | null>;+ log: {+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ };+ now?: () => number;+ turnTimeoutMs?: number;+ sleep?: (ms: number) => Promise<void>;+}++function failure(+ errorCode: Extract<GhostErrandRunOutcome, { ok: false }>['errorCode'],+ message: string,+): GhostErrandRunOutcome {+ return { ok: false, errorCode, message };+}++/** 权限档钳制:任何来路的值都收敛进白名单,缺省 plan(只读)。 */+export function clampErrandPermissionMode(value: unknown): GhostErrandPermissionMode {+ return typeof value === 'string' &&+ (GHOST_ERRAND_PERMISSION_MODES as readonly string[]).includes(value)+ ? (value as GhostErrandPermissionMode)+ : 'plan';+}++export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErrandRunner {+ const now = deps.now ?? (() => Date.now());+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));++ /** 既有会话还能不能当这单的干活间:关键配置(agent/权限档/目录)变了就换新间。 */+ const sessionMatchesConfig = (+ row: GhostErrandSessionRow,+ cfg: GhostErrandConfig,+ permissionMode: GhostErrandPermissionMode,+ configuredDir: string | undefined,+ ): boolean => {+ if (row.status !== 'active') return false;+ if (cfg.agentKind && row.agentKind !== cfg.agentKind) return false;+ if (row.permissionMode !== permissionMode) return false;+ // 用户配置了项目目录:目录不同(或旧间还是 dialogue)就换新间;+ // 用户清掉目录配置:旧的 project 间不再复用,回到专属 dialogue 间。+ if (configuredDir) {+ if (row.workspaceKind !== 'project' || row.workingDir !== configuredDir) return false;+ } else if (row.workspaceKind !== 'dialogue') {+ return false;+ }+ return true;+ };++ return async (request, hooks) => {+ const cfg = deps.readConfig(request.ghostId);+ const permissionMode = clampErrandPermissionMode(cfg.permissionMode);+ // 与落库同一套规范化再参与比对/创建;规范化失败视为没配(回专属间)。+ const configuredDir = cfg.workingDir+ ? (deps.normalizeWorkingDir(cfg.workingDir) ?? undefined)+ : undefined;++ // ── 确保专属 errand 会话 ─────────────────────────────────────────────+ let sessionId = deps.readSessionId(request.ghostId);+ if (sessionId) {+ const row = await deps.getSessionRow(sessionId);+ if (!row || !sessionMatchesConfig(row, cfg, permissionMode, configuredDir)) {+ // 旧间不可用/配置已变:解除映射换新间(旧会话留在侧边栏,历史可查)。+ deps.writeSessionId(request.ghostId, null);+ sessionId = null;+ }+ }+ if (!sessionId) {+ // 缺省选型跟随 New Maker 草稿偏好(与 Orca worker / workspace 槽同源);+ // 配置项逐字段覆盖。model/effort 缺省最终由 mapper 兜底,这里不硬编码。+ const vendor = cfg.agentKind === 'codex' ? 'codex' : 'claude-code';+ const draft = deps.getDraftDefaults(vendor);+ const ghostName = deps.getGhostName(request.ghostId);+ try {+ sessionId = await deps.createSession({+ ghostId: request.ghostId,+ title: request.title ?? (ghostName ? `${ghostName} · 代办` : null),+ ...(cfg.agentKind ? { agentKind: cfg.agentKind } : {}),+ ...(cfg.model ?? draft.model ? { model: cfg.model ?? draft.model } : {}),+ ...(cfg.effort ?? draft.effort ? { effort: cfg.effort ?? draft.effort } : {}),+ ...((cfg.fastMode ?? draft.fastMode) !== undefined+ ? { fastMode: cfg.fastMode ?? draft.fastMode }+ : {}),+ ...((cfg.providerId ?? draft.providerId) !== undefined+ ? { providerId: cfg.providerId ?? draft.providerId }+ : {}),+ permissionMode,+ ...(configuredDir ? { workingDir: configuredDir } : {}),+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ deps.log.warn('ghost errand session create failed', { ghostId: request.ghostId, error: message });+ return failure('SESSION_UNAVAILABLE', `errand 会话创建失败:${message}`);+ }+ deps.writeSessionId(request.ghostId, sessionId);+ }+ hooks?.onSession?.(sessionId);++ // ── 忙检 + 投递 ──────────────────────────────────────────────────────+ // 不排队:排队会让"这单的结果"对不上"正在跑的那轮"。errandSlot 已保证+ // 同插件单在途,这里挡的是用户恰好正在这间会话里亲自聊天的情况。+ if (deps.isSessionBusy(sessionId)) {+ return failure('BUSY', 'errand 会话正被占用(可能正被用户使用),请稍后再试');+ }+ const dispatchedAt = now();+ const dispatched = await deps.dispatch({ targetSessionId: sessionId, message: request.message });+ if (!dispatched.ok) {+ if (dispatched.errorCode === 'BUSY') return failure('BUSY', dispatched.message);+ if (+ dispatched.errorCode === 'NOT_FOUND' ||+ dispatched.errorCode === 'ARCHIVED' ||+ dispatched.errorCode === 'DELETED'+ ) {+ // 会话在忙检与投递之间被删/归档:解除映射,让下一单重建。+ deps.writeSessionId(request.ghostId, null);+ return failure('SESSION_UNAVAILABLE', dispatched.message);+ }+ return failure('INTERNAL', dispatched.message);+ }+ if (dispatched.wakeKind === 'queued') {+ // 忙检后的窄竞态窗口:消息已进队(会在当前轮后执行,但结果不取回)。+ // 如实告知并留日志——这是已知边界,不装作没发生。+ deps.log.warn('ghost errand message queued behind a foreign turn', {+ ghostId: request.ghostId,+ sessionId,+ });+ return failure(+ 'BUSY',+ 'errand 会话恰好正忙,本单任务已排队进该会话但结果不再取回;请稍后查看会话或重新提交',+ );+ }++ // ── 收口:观察这一轮直到 done / 终态错误 / 超时 ─────────────────────+ const session = deps.getObservableSession(sessionId);+ if (!session) {+ return failure('SESSION_UNAVAILABLE', 'errand 会话进程不可用,请稍后再试');+ }+ const observer = observeHookTurn(session, {+ answerOnlyProgress: true,+ onSilentStopSettled: deps.onSilentStopSettled,+ log: { warn: (msg) => deps.log.warn(msg) },+ });+ const timeoutMs = deps.turnTimeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;+ let timer: NodeJS.Timeout | undefined;+ let timedOut = false;+ try {+ await Promise.race([+ observer.finished,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ timedOut = true;+ reject(new Error('errand turn timeout'));+ }, timeoutMs);+ timer.unref?.();+ }),+ ]);+ } catch (err) {+ observer.stop();+ if (timedOut) {+ return failure('TIMEOUT', '派活超时(任务可能仍在会话里继续,可打开 errand 会话查看)');+ }+ const message = err instanceof Error ? err.message : String(err);+ return failure('TURN_FAILED', `派活这一轮失败:${message}`);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }++ // ── 取结果文字:观察器累积为主,DB 最新 assistant 消息兜底 ──────────+ // (create/resumed 分支里观察器晚于 turn 启动挂上,可能漏掉最早的文本+ // 事件;DB 是落库后的权威内容,带 sinceMs 防捞到上一轮的旧答案。)+ let text = observer.text().trim();+ if (!text) {+ for (let i = 0; i < DB_TEXT_RETRIES && !text; i++) {+ if (i > 0) await sleep(DB_TEXT_RETRY_DELAY_MS);+ text = ((await deps.readLatestAssistantText(sessionId, dispatchedAt)) ?? '').trim();+ }+ }+ if (!text) text = '(本轮没有可取回的文字回复)';+ const row = await deps.getSessionRow(sessionId);+ deps.log.info('ghost errand turn finished', {+ ghostId: request.ghostId,+ sessionId,+ chars: text.length,+ elapsedMs: now() - dispatchedAt,+ });+ return {+ ok: true,+ sessionId,+ text,+ ...(row?.agentKind ? { agentKind: row.agentKind } : {}),+ ...(row?.model ? { model: row.model } : {}),+ };+ };+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 97eb9864c0..5efd668d95 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -31,7 +31,7 @@ import { createId } from '@paralleldrive/cuid2';import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';import { DL_SESSION_REFERENCE_CAPABILITY_CHANNEL } from '@cindy/device-link';-import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';+import { and, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';import { BrowserWindow, ipcMain, type IpcMainInvokeEvent } from 'electron';import { getActiveAppSession } from '../appSessionState.js';import type { AgentMeta } from '../../renderer/lib/ccAgent.types';@@ -555,13 +555,23 @@ import {hasEnabledUserMessageHookGhost,screenGhostUserMessage,setGhostAgentTurnRunner,+ setGhostErrandRunner,setGhostWorkspaceSessionService,notifyGhostSessionEvent,+ getInstalledGhostName,} from '../cindy-brain/index.js';import {+ readGhostErrandConfig,+ readGhostErrandSessionId,+ writeGhostErrandSessionId,+} from '../cindy-brain/errandPrefsStore.js';+import { createGhostErrandRunner } from './ghostErrandRunner.js';+import {+ createGhostErrandSession,createPluginDraftSession,findActiveSessionByWorkdir,} from '../localDb/ipc/pluginWorkspaceSessions.js';+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';import { openMainWindowSession } from '../deepLink.js';const log = createLogger('maker-ipc');@@ -5811,6 +5821,76 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};});+ // Ghost 的派活取件(agent 槽 errand 加档):守门在 cindy-brain/errandSlot,+ // 这里注入真实执行链——专属会话确保/统一投递/turn 收口。投递仍走+ // sendToSessionInternal 这一条主机通路(消息落库、进程拉起与用户亲发一致);+ // 收口复用 hook-control 的 observeHookTurn(与飞书 bot 同一套 turn 观察语义)。+ setGhostErrandRunner(+ createGhostErrandRunner({+ readConfig: readGhostErrandConfig,+ readSessionId: readGhostErrandSessionId,+ writeSessionId: writeGhostErrandSessionId,+ getSessionRow: async (sessionId) => {+ const [row] = await getDbClient().drizzle+ .select({+ status: sessions.status,+ agentKind: sessions.agentKind,+ model: sessions.model,+ permissionMode: sessions.permissionMode,+ workingDir: sessions.workingDir,+ workspaceKind: sessions.workspaceKind,+ })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ return row ?? null;+ },+ createSession: async (params) => {+ const sessionId = await createGhostErrandSession({+ ...params,+ notifySessionCreated: (info) => notifyGhostSessionEvent('created', info),+ });+ // errand 会话在侧边栏可见(与 workspace 槽同通道刷新)——透明是这个+ // 能力的安全边界之一,不做隐藏会话。+ broadcastSessionCreated(sessionId);+ return sessionId;+ },+ getGhostName: getInstalledGhostName,+ getDraftDefaults: getWorkerDefaultsFromNewMaker,+ normalizeWorkingDir: (dir) => normalizeWorkingDirForStorage(dir),+ isSessionBusy: isSessionInTurn,+ dispatch: async ({ targetSessionId, message }) => {+ const r = await sendToSessionInternal({ targetSessionId, message });+ if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };+ return { ok: true, wakeKind: r.wakeKind };+ },+ getObservableSession: (sessionId) => maker.getSession(sessionId) ?? null,+ onSilentStopSettled,+ readLatestAssistantText: async (sessionId, sinceMs) => {+ const [row] = await getDbClient().drizzle+ .select({ content: messages.content })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ gte(messages.createdAt, sinceMs),+ ),+ )+ .orderBy(desc(messages.createdAt), desc(messages.id))+ .limit(1);+ if (!row) return null;+ const text = visibleMessageTextForConversationSearch('assistant', row.content ?? '');+ return text.length > 0 ? text : null;+ },+ log: {+ info: (message, meta) => log.info(message, meta),+ warn: (message, meta) => log.warn(message, meta),+ },+ }),+ );+// Ghost 的 workspace 槽:判重/创建走 localDb 服务,创建后广播与 scheduler// 同一条 `local-db:sessions:created` 通道让侧边栏刷新;focus 复用 deep link// 的会话聚焦通道。注入方式与 setGhostAgentTurnRunner 同款倒置,避免diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex 3ba1e46238..81bb09a7f3 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -19,6 +19,8 @@ import { contextBridge, ipcRenderer } from 'electron';* …req}) 的语法糖,零新通道零新权限(白名单/凭证注入全在主机侧守门)。* - fs(req):fs 槽代写文件的便捷口——send({type:'fs-request', …req}) 的* 语法糖,同样零新通道零新权限(三档守门全在主机侧 fsSlot)。+ * - agent.errand(req) / agent.queryErrand(req):派活取件便捷口——+ * send({type:'agent-errand-request', kind:'run'/'query', …req}) 的语法糖;* - agent.run(req):Agent 新回合的便捷口——send({type:'agent-request',* …req}) 的语法糖;一次性用户票、后台权限和会话归属由主机校验。* - node.request(req):随包 Node / stdio MCP 的便捷口。Node 只能经本管子与@@ -53,6 +55,13 @@ contextBridge.exposeInMainWorld('cindy', {agent: {run: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-request' }),+ // 派活取件(agent.errand 加档)的便捷口:errand = 提交(kind:'run'),+ // queryErrand = 取件(kind:'query')。都是 send({type:'agent-errand-request'})+ // 的语法糖,资格审与频控在主机 errandSlot。+ errand: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-errand-request', kind: 'run' }),+ queryErrand: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'agent-errand-request', kind: 'query' }),},node: {request: (req: Record<string, unknown>): Promise<unknown> =>diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 35940149bc..eef097e285 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -867,6 +867,14 @@ contextBridge.exposeInMainWorld('electronAPI', {} => ipcRenderer.sendSync('ghosts:cindy-prefs', id),setCindyPref: (id: string, capability: string, model: string | null): Promise<{ overrides: Record<string, string> }> =>ipcRenderer.invoke('ghosts:cindy-prefs:set', id, capability, model),+ /** 派活(errand)每插件配置(插件详情页「AI 代办」卡;sendSync 首帧同帧渲染)。 */+ errandPrefsSync: (id: string): { config: Record<string, unknown> } =>+ ipcRenderer.sendSync('ghosts:errand-prefs', id),+ setErrandConfig: (+ id: string,+ config: Record<string, unknown> | null,+ ): Promise<{ config: Record<string, unknown> }> =>+ ipcRenderer.invoke('ghosts:errand-prefs:set', id, config),pickFile: (): Promise<{ canceled: true } | { filePath: string }> =>ipcRenderer.invoke('ghosts:pick-file'),inspect: (lizFilePath: string): Promise<{diff --git a/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx b/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsxnew file mode 100644index 0000000000..b5cbce5c29--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx@@ -0,0 +1,304 @@+/**+ * Host-rendered errand (派活取件) preferences for a Plugin that declares+ * `agent.errand`. Settings 详情与 Plugin 详情共用(同 CindyCapabilityPrefs)。+ *+ * 配置语义(与 main 侧 errandPrefsStore 同一契约):+ * - 全部字段缺省 = 跟随「新建草稿」偏好;agent 跟随默认时,模型/强度/Fast+ * 一并跟随(锁定不可单独配),先选定 agent 才谈得上给它挑模型;+ * - 权限档只有 只读(默认)/可改文件/自动 三档——「完全不设防」在协议上+ * 就不存在(2026-07-31 定案),这里画不出来也传不上去;+ * - 工作目录缺省是插件专属文件夹,选真实项目目录必须经系统选文件夹窗口+ * (用户亲手选中即授权,与 pick 槽同一哲学)。+ */++import { useCallback, useState, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';+import { Bot, FolderOpen, X } from 'lucide-react';++import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';+import { useAgentCapabilities, type AgentKind } from '@/hooks/useAgentCapabilities';++/** 跟随默认在 select 里的哨兵值(配置里"没有这项"= 跟随默认)。 */+const FOLLOW_DEFAULT_VALUE = '__default__';++const PERMISSION_MODES = ['plan', 'acceptEdits', 'auto'] as const;+type ErrandPermissionMode = (typeof PERMISSION_MODES)[number];++/** errand 只收 worker 同集合的思考档(minimal 不收,与 main 侧存储层一致)。 */+const ERRAND_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max', 'ultra']);++interface ErrandConfig {+ agentKind?: 'cc' | 'codex';+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId?: string;+ permissionMode?: ErrandPermissionMode;+ workingDir?: string;+}++function vendorOf(config: ErrandConfig): AgentKind | null {+ if (config.agentKind === 'cc') return 'claude-code';+ if (config.agentKind === 'codex') return 'codex';+ return null;+}++export function GhostErrandPrefs({+ ghostId,+ appearance = 'settings',+}: {+ ghostId: string;+ /** Plugin detail aligns the card with the shared Plugin surface. */+ appearance?: 'settings' | 'plugin';+}) {+ const { t } = useTranslation();+ const [config, setConfig] = useState<ErrandConfig>(+ () => (window.electronAPI.ghosts.errandPrefsSync(ghostId).config ?? {}) as ErrandConfig,+ );+ const vendor = vendorOf(config);+ // agent 跟随默认时不拉能力表(hook 收 null 即挂起),模型/强度/Fast 行锁定。+ const { capabilities } = useAgentCapabilities(vendor);++ const save = useCallback(+ async (next: ErrandConfig) => {+ const prev = config;+ setConfig(next);+ try {+ const result = await window.electronAPI.ghosts.setErrandConfig(+ ghostId,+ next as Record<string, unknown>,+ );+ setConfig((result.config ?? {}) as ErrandConfig);+ } catch {+ setConfig(prev);+ toast.error(t('settings.ghosts.errors.generic'));+ }+ },+ [config, ghostId, t],+ );++ const labelCls = cn(+ 'min-w-0 text-[var(--text-secondary)]',+ appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',+ );+ const selectCls = cn(+ 'h-8 w-[300px] max-w-[60%] min-w-0 shrink appearance-none rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] py-0 pl-3 pr-8 text-[var(--settings-input-text)] outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)] disabled:opacity-50',+ appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',+ );++ // agent 显式选定后才有可配的模型清单;模型选定后强度跟着该模型的支持集走。+ const models = (capabilities?.availableModels ?? []).filter((m) => m.defaultEnabled !== false);+ const selectedModel = config.model ? models.find((m) => m.id === config.model) : undefined;+ const effortOptions = (+ selectedModel ? selectedModel.efforts : (capabilities?.effortLevels ?? []).map((e) => e.id)+ ).filter((e) => ERRAND_EFFORTS.has(e));+ const fastSupported =+ vendor !== null &&+ (capabilities?.hasFastMode ?? false) &&+ (selectedModel ? selectedModel.supportsFastMode !== false : true);++ const pickWorkingDir = async (): Promise<void> => {+ const result = await window.electronAPI.showOpenDirectoryDialog();+ if (!result.canceled && result.path) {+ await save({ ...config, workingDir: result.path });+ }+ };++ const row = (key: string, control: ReactNode): ReactNode => (+ <div className="flex min-w-0 items-center justify-between gap-4">+ <span className={labelCls}>{t(`settings.ghosts.detail.errandPrefs.${key}`)}</span>+ {control}+ </div>+ );++ return (+ <div+ className={cn(+ 'ghost-errand-prefs min-w-0 max-w-full flex flex-col gap-3 rounded-xl border px-5 py-4',+ appearance === 'plugin'+ ? 'border-[color-mix(in_srgb,var(--border-default)_72%,transparent)] bg-[color-mix(in_srgb,var(--surface-elevated)_82%,var(--surface))]'+ : 'border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',+ )}+ >+ <div className="flex items-center gap-2">+ <Bot size={14} className="text-[var(--text-tertiary)]" />+ <p+ className={cn(+ 'font-medium text-[var(--text-primary)]',+ appearance === 'plugin' ? 'text-14 leading-[22px]' : 'text-13',+ )}+ >+ {t('settings.ghosts.detail.errandPrefs.title')}+ </p>+ </div>+ <p+ className={cn(+ 'text-[var(--text-tertiary)]',+ appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',+ )}+ >+ {t('settings.ghosts.detail.errandPrefs.desc')}+ </p>++ {row(+ 'agent',+ <select+ value={config.agentKind ?? FOLLOW_DEFAULT_VALUE}+ onChange={(event) => {+ const v = event.target.value;+ // 换 agent 连带清掉模型/强度/Fast(跨 agent 的模型 id 互不通用)。+ void save({+ ...config,+ agentKind: v === FOLLOW_DEFAULT_VALUE ? undefined : (v as 'cc' | 'codex'),+ model: undefined,+ effort: undefined,+ fastMode: undefined,+ });+ }}+ aria-label={t('settings.ghosts.detail.errandPrefs.agent')}+ className={selectCls}+ >+ <option value={FOLLOW_DEFAULT_VALUE}>+ {t('settings.ghosts.detail.errandPrefs.followDefault')}+ </option>+ <option value="cc">Claude Code</option>+ <option value="codex">Codex</option>+ </select>,+ )}++ {row(+ 'model',+ <select+ value={config.model ?? FOLLOW_DEFAULT_VALUE}+ disabled={vendor === null || models.length === 0}+ onChange={(event) => {+ const v = event.target.value;+ void save({+ ...config,+ model: v === FOLLOW_DEFAULT_VALUE ? undefined : v,+ // 模型换了,旧强度可能不在新模型支持集里,一并回跟随。+ effort: undefined,+ });+ }}+ aria-label={t('settings.ghosts.detail.errandPrefs.model')}+ className={selectCls}+ >+ <option value={FOLLOW_DEFAULT_VALUE}>+ {t('settings.ghosts.detail.errandPrefs.followDefault')}+ </option>+ {models.map((m) => (+ <option key={m.id} value={m.id}>+ {m.displayName}+ </option>+ ))}+ </select>,+ )}++ {row(+ 'effort',+ <select+ value={config.effort ?? FOLLOW_DEFAULT_VALUE}+ disabled={vendor === null || effortOptions.length === 0}+ onChange={(event) => {+ const v = event.target.value;+ void save({ ...config, effort: v === FOLLOW_DEFAULT_VALUE ? undefined : v });+ }}+ aria-label={t('settings.ghosts.detail.errandPrefs.effort')}+ className={selectCls}+ >+ <option value={FOLLOW_DEFAULT_VALUE}>+ {t('settings.ghosts.detail.errandPrefs.followDefault')}+ </option>+ {effortOptions.map((effort) => (+ <option key={effort} value={effort}>+ {capabilities?.effortLevels.find((e) => e.id === effort)?.displayName ?? effort}+ </option>+ ))}+ </select>,+ )}++ {fastSupported+ ? row(+ 'fast',+ <select+ value={+ config.fastMode === undefined ? FOLLOW_DEFAULT_VALUE : config.fastMode ? 'on' : 'off'+ }+ onChange={(event) => {+ const v = event.target.value;+ void save({+ ...config,+ fastMode: v === FOLLOW_DEFAULT_VALUE ? undefined : v === 'on',+ });+ }}+ aria-label={t('settings.ghosts.detail.errandPrefs.fast')}+ className={selectCls}+ >+ <option value={FOLLOW_DEFAULT_VALUE}>+ {t('settings.ghosts.detail.errandPrefs.followDefault')}+ </option>+ <option value="on">{t('settings.ghosts.detail.errandPrefs.fastOn')}</option>+ <option value="off">{t('settings.ghosts.detail.errandPrefs.fastOff')}</option>+ </select>,+ )+ : null}++ {row(+ 'permission',+ <select+ value={config.permissionMode ?? 'plan'}+ onChange={(event) => {+ const v = event.target.value as ErrandPermissionMode;+ // 'plan' 是缺省档:选回它就清掉显式配置(规则 20:覆盖与默认分开记)。+ void save({ ...config, permissionMode: v === 'plan' ? undefined : v });+ }}+ aria-label={t('settings.ghosts.detail.errandPrefs.permission')}+ className={selectCls}+ >+ {PERMISSION_MODES.map((mode) => (+ <option key={mode} value={mode}>+ {t(`settings.ghosts.detail.errandPrefs.permissionMode.${mode}`)}+ </option>+ ))}+ </select>,+ )}++ {row(+ 'workdir',+ <div className="flex min-w-0 max-w-[60%] items-center gap-2">+ <span+ className={cn(+ 'min-w-0 flex-1 truncate text-right text-[var(--text-tertiary)]',+ appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',+ )}+ title={config.workingDir}+ >+ {config.workingDir ?? t('settings.ghosts.detail.errandPrefs.workdirDefault')}+ </span>+ {config.workingDir ? (+ <button+ type="button"+ onClick={() => void save({ ...config, workingDir: undefined })}+ aria-label={t('settings.ghosts.detail.errandPrefs.workdirClear')}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)]"+ >+ <X size={13} />+ </button>+ ) : null}+ <button+ type="button"+ onClick={() => void pickWorkingDir()}+ className={cn(+ 'flex h-8 shrink-0 items-center gap-1.5 rounded-full border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] px-3 text-[var(--settings-input-text)] hover:bg-[var(--surface-hover)]',+ appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',+ )}+ >+ <FolderOpen size={13} />+ {t('settings.ghosts.detail.errandPrefs.workdirPick')}+ </button>+ </div>,+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 1e41072555..9f37371329 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -39,6 +39,7 @@ import {import { useTranslation } from 'react-i18next';import { CindyCapabilityPrefs } from '@/cindy-brain/CindyCapabilityPrefs';+import { GhostErrandPrefs } from '@/cindy-brain/GhostErrandPrefs';import { GhostSettingsWebview } from '@/cindy-brain/GhostSettingsWebview';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import {@@ -142,7 +143,8 @@ export function GhostPluginDetailView({const enabled = enabledOverride ?? detail.enabled;const canUse = enabled && detail.canUse;const cindyCapabilities = detail.cindyCapabilities;- const hasConfiguration = detail.hasSettingsUi || cindyCapabilities.length > 0;+ const hasConfiguration =+ detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;const summary = ghostPluginSummary(detail.description, detail.id);useLayoutEffect(() => {@@ -364,6 +366,9 @@ export function GhostPluginDetailView({appearance="plugin"/>) : null}+ {detail.hasErrand ? (+ <GhostErrandPrefs ghostId={detail.id} appearance="plugin" />+ ) : null}</div></section>) : null}diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex 9caf4ab337..f86783eb6e 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -105,6 +105,7 @@ const detail: GhostPluginDetail = {tools: [],hasSettingsUi: false,cindyCapabilities: [],+ hasErrand: false,panelMinWidth: 320,installDir: '/tmp/cindy-brain/builtin.example',trust: {diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex 9d2e0703e7..73b423e589 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -34,6 +34,8 @@ export interface GhostPluginDetail extends GhostPluginListItem {tools: readonly GhostToolDecl[];hasSettingsUi: boolean;cindyCapabilities: readonly string[];+ /** 申请了派活取件(agent.errand)——详情页据此渲染宿主统一的「AI 代办」配置卡。 */+ hasErrand: boolean;panelMinWidth: number | null;installDir: string | null;}@@ -195,6 +197,7 @@ export function toGhostPluginDetail(...(manifest.cindy?.image ?? []).map((action) => `image.${action}`),...(manifest.cindy?.video ?? []).map((action) => `video.${action}`),],+ hasErrand: manifest.agent?.errand === true,panelMinWidth: manifest.panel ? (manifest.panel.minWidth ?? 280) : null,installDir: ghost.dir,};diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 86bd4977bb..a7f2f8009b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2884,10 +2884,14 @@"cindyVideoEdit": "Image-to-video (delegated to Cindy, reference images from its own media only)","cindyMediaDeposit": "Can save images, video or audio it holds into your media library","cindyMediaDepositDetail": "This lets AI work on material you paste or drop into the plugin. Saved items are recorded under this plugin, use at most {{quota}}, and are cleaned up when you uninstall it.",+ "cindyTextOneshot": "Can ask Cindy's fast lane a question and receive a text answer",+ "cindyTextOneshotDetail": "Uses the system's lightweight utility model chain (the same lane as auto titles). No Agent involved and no file access. Model charges may apply.","agentUserAction": "Can start a new Agent turn after you click a plugin card","agentUserActionDetail": "Each click permits one turn only, and only in the session that owns the card.","agentBackground": "Can automatically start new Agent turns in the background","agentBackgroundDetail": "Does not require a click each time, but can only use sessions you previously connected to this plugin. Model charges may apply.",+ "agentErrand": "Can hand tasks to the Cindy Agent and collect the result",+ "agentErrandDetail": "Tasks run in this plugin's dedicated session, always visible in the sidebar and stoppable at any time. Read-only by default; raising the level requires your change in the plugin settings. Model charges may apply.","nodeRuntime": "Can run a bundled Node program on this computer","nodeMcp": "Can run a bundled stdio MCP on this computer","nodeRuntimeDetail": "High risk: it has the same local access as your user account, including files, network, and starting other programs. Cindy cannot contain it in the browser sandbox.",@@ -2996,6 +3000,27 @@"defaultOption": "{{model}} (default)","noModels": "No models available"},+ "errandPrefs": {+ "title": "AI errands",+ "desc": "How this plugin's tasks run when it hands work to the Cindy Agent. Unset fields follow your new-draft preferences; the helper is read-only by default and works in a dedicated folder.",+ "agent": "Agent",+ "model": "Model",+ "effort": "Reasoning effort",+ "fast": "Fast mode",+ "fastOn": "On",+ "fastOff": "Off",+ "permission": "Write access",+ "permissionMode": {+ "plan": "Read-only (default): can look and think, cannot change anything",+ "acceptEdits": "Can edit files: may modify files in the working folder",+ "auto": "Auto: routine actions in the working folder no longer ask each time"+ },+ "workdir": "Working folder",+ "workdirDefault": "Plugin's dedicated folder (default)",+ "workdirPick": "Choose…",+ "workdirClear": "Reset to default folder",+ "followDefault": "Follow default"+ },"toolsTitle": "Tools","permissionsTitle": "Permissions","infoDescription": "Description",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 507d9cfd96..430d25fb95 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2883,10 +2883,14 @@"cindyVideoEdit": "画像から動画(Cindy に代行依頼、参照画像は自身名義のもののみ)","cindyMediaDeposit": "保有している画像・動画・音声をあなたのメディアライブラリに保存できます","cindyMediaDepositDetail": "プラグイン内で貼り付け・ドロップした素材も AI で加工できるようにするための権限です。保存内容はこのプラグイン名義で記録され、最大 {{quota}} まで使用し、アンインストール時に併せて削除されます。",+ "cindyTextOneshot": "Cindy のクイックチャンネルに質問してテキスト回答を受け取れます",+ "cindyTextOneshotDetail": "システムの軽量タスクモデルチェーン(自動タイトルと同じ経路)を使用します。Agent は使わず、ファイルにもアクセスしません。モデル料金が発生する場合があります。","agentUserAction": "プラグインカードをクリックした後、Agent の新しいターンを開始できます","agentUserActionDetail": "1 回のクリックにつき 1 回だけ開始でき、そのカードが属するセッションでのみ使用できます。","agentBackground": "バックグラウンドで Agent の新しいターンを自動的に開始できます","agentBackgroundDetail": "毎回のクリックは不要ですが、以前このプラグインに関連付けたセッションでのみ使用できます。モデル料金が発生する場合があります。",+ "agentErrand": "Cindy Agent にタスクを任せて結果を受け取れます",+ "agentErrandDetail": "タスクはこのプラグイン専用のセッションで実行され、サイドバーから常に確認・停止できます。既定では読み取り専用で、権限の引き上げはプラグイン設定であなた自身が行う必要があります。モデル料金が発生する場合があります。","nodeRuntime": "同梱された Node プログラムをこのコンピューターで実行できます","nodeMcp": "同梱された stdio MCP をこのコンピューターで実行できます","nodeRuntimeDetail": "高リスク:あなたのユーザーアカウントと同じ権限で、ローカルファイルの読み書き、ネットワークアクセス、他のプログラムの起動ができます。Cindy のブラウザーサンドボックスでは隔離できません。",@@ -2995,6 +2999,27 @@"defaultOption": "{{model}}(既定)","noModels": "利用可能なモデルなし"},+ "errandPrefs": {+ "title": "AI 代行",+ "desc": "このプラグインが Cindy Agent にタスクを任せるときの実行設定です。未設定の項目は新規ドラフトの選択に従います。既定では読み取り専用で、専用フォルダー内で作業します。",+ "agent": "Agent",+ "model": "モデル",+ "effort": "推論強度",+ "fast": "Fast モード",+ "fastOn": "オン",+ "fastOff": "オフ",+ "permission": "書き込み権限",+ "permissionMode": {+ "plan": "読み取り専用(既定):閲覧と思考のみで、変更はできません",+ "acceptEdits": "ファイル編集可:作業フォルダー内のファイルを変更できます",+ "auto": "自動:作業フォルダー内の通常操作は毎回確認しません"+ },+ "workdir": "作業フォルダー",+ "workdirDefault": "プラグイン専用フォルダー(既定)",+ "workdirPick": "選択…",+ "workdirClear": "既定のフォルダーに戻す",+ "followDefault": "既定に従う"+ },"toolsTitle": "Tools","permissionsTitle": "権限","infoDescription": "説明",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7c761f403f..ae9c4812bc 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2883,10 +2883,14 @@"cindyVideoEdit": "이미지로 영상 만들기(Cindy에게 대행 요청, 참조 이미지는 자신 소유만)","cindyMediaDeposit": "보유한 이미지·영상·오디오를 내 미디어 라이브러리에 저장할 수 있음","cindyMediaDepositDetail": "플러그인에 붙여넣거나 끌어다 놓은 소재도 AI가 편집할 수 있게 하는 권한입니다. 저장된 항목은 이 플러그인 이름으로 기록되며 최대 {{quota}}까지 사용하고, 플러그인을 삭제하면 함께 정리됩니다.",+ "cindyTextOneshot": "Cindy의 빠른 채널에 질문하고 텍스트 답변을 받을 수 있음",+ "cindyTextOneshotDetail": "시스템의 경량 작업 모델 체인(자동 제목과 같은 경로)을 사용합니다. Agent를 사용하지 않고 파일에도 접근하지 않습니다. 모델 비용이 발생할 수 있습니다.","agentUserAction": "플러그인 카드를 클릭한 뒤 Agent의 새 작업을 시작할 수 있음","agentUserActionDetail": "클릭 한 번마다 한 번만 시작할 수 있으며, 해당 카드가 속한 세션에서만 사용할 수 있습니다.","agentBackground": "백그라운드에서 Agent의 새 작업을 자동으로 시작할 수 있음","agentBackgroundDetail": "매번 클릭할 필요는 없지만, 이전에 이 플러그인과 연결한 세션에서만 사용할 수 있습니다. 모델 비용이 발생할 수 있습니다.",+ "agentErrand": "Cindy Agent에게 작업을 맡기고 결과를 받아올 수 있음",+ "agentErrandDetail": "작업은 이 플러그인 전용 세션에서 실행되며, 사이드바에서 언제든 확인하고 중단할 수 있습니다. 기본은 읽기 전용이며, 권한 상향은 플러그인 설정에서 직접 해야 합니다. 모델 비용이 발생할 수 있습니다.","nodeRuntime": "함께 제공된 Node 프로그램을 이 컴퓨터에서 실행할 수 있음","nodeMcp": "함께 제공된 stdio MCP를 이 컴퓨터에서 실행할 수 있음","nodeRuntimeDetail": "고위험:사용자 계정과 같은 권한으로 로컬 파일을 읽거나 수정하고, 네트워크에 접근하며, 다른 프로그램을 시작할 수 있습니다. Cindy의 브라우저 샌드박스로 격리할 수 없습니다.",@@ -2995,6 +2999,27 @@"defaultOption": "{{model}} (기본값)","noModels": "사용 가능한 모델 없음"},+ "errandPrefs": {+ "title": "AI 대행",+ "desc": "이 플러그인이 Cindy Agent에게 작업을 맡길 때 사용하는 실행 설정입니다. 설정하지 않은 항목은 새 초안 선택을 따르며, 기본은 읽기 전용이고 전용 폴더에서 작업합니다.",+ "agent": "Agent",+ "model": "모델",+ "effort": "추론 강도",+ "fast": "Fast 모드",+ "fastOn": "켬",+ "fastOff": "끔",+ "permission": "쓰기 권한",+ "permissionMode": {+ "plan": "읽기 전용(기본): 보고 생각만 할 수 있고 변경은 불가",+ "acceptEdits": "파일 수정 가능: 작업 폴더 안의 파일을 수정할 수 있음",+ "auto": "자동: 작업 폴더 안의 일반 작업은 매번 묻지 않음"+ },+ "workdir": "작업 폴더",+ "workdirDefault": "플러그인 전용 폴더(기본)",+ "workdirPick": "선택…",+ "workdirClear": "기본 폴더로 되돌리기",+ "followDefault": "기본값 따르기"+ },"toolsTitle": "Tools","permissionsTitle": "권한","infoDescription": "설명",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4c10df564a..dfc6470cdf 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2883,10 +2883,14 @@"cindyVideoEdit": "图生视频(请 Cindy 代办,参考图仅限它名下的图)","cindyMediaDeposit": "可将它手中的图片、视频或音频存入你的媒体库","cindyMediaDepositDetail": "用于让你在插件里粘贴或拖入的素材也能被 AI 加工。存入的内容记在这个插件名下,最多占用 {{quota}},卸载插件时一并清理。",+ "cindyTextOneshot": "可向 Cindy 的快速通道提问并获得文字回答",+ "cindyTextOneshotDetail": "走系统的轻量任务模型链(与自动起标题同一条通道),不动用 Agent、碰不到你的文件,可能产生模型费用。","agentUserAction": "用户点击插件卡片后,可让 Agent 开始新一轮工作","agentUserActionDetail": "每次点击只允许启动一次,并且只能使用这张卡所属的对话。","agentBackground": "可在后台自动让 Agent 开始新一轮工作","agentBackgroundDetail": "不需要当次点击,但只能使用你曾为这个插件建立过关联的对话,可能产生模型费用。",+ "agentErrand": "可把任务交给 Cindy Agent 代办并取回结果",+ "agentErrandDetail": "任务在这个插件的专属对话里进行,你随时可以在侧边栏看到并叫停;默认只能读不能改,要放开需你在插件配置里亲手调整,可能产生模型费用。","nodeRuntime": "可在本机运行随插件附带的 Node 程序","nodeMcp": "可在本机运行随插件附带的 stdio MCP","nodeRuntimeDetail": "高风险:它和你本人一样,可以读取或修改你账号能访问的本机文件、访问网络并启动其它程序。Cindy 不能用浏览器沙箱限制它。",@@ -2995,6 +2999,27 @@"defaultOption": "{{model}}(默认)","noModels": "暂无可用模型"},+ "errandPrefs": {+ "title": "AI 代办",+ "desc": "这个插件把任务交给 Cindy Agent 时用哪套配置干活。不配就跟随你新建草稿时的选择;帮工默认只能看不能改,工作目录默认是插件专属文件夹。",+ "agent": "Agent",+ "model": "模型",+ "effort": "推理强度",+ "fast": "Fast 模式",+ "fastOn": "开",+ "fastOff": "关",+ "permission": "动手权限",+ "permissionMode": {+ "plan": "只读(默认):只能看和想,不能改东西",+ "acceptEdits": "可改文件:允许修改工作目录里的文件",+ "auto": "自动:工作目录内的常规操作不再逐次询问"+ },+ "workdir": "工作目录",+ "workdirDefault": "插件专属文件夹(默认)",+ "workdirPick": "选择…",+ "workdirClear": "恢复默认目录",+ "followDefault": "跟随默认"+ },"toolsTitle": "Tools","permissionsTitle": "权限","infoDescription": "描述",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8c4138d758..68927ef598 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1124,6 +1124,13 @@ interface ElectronAPI {capability: string,model: string | null,) => Promise<{ overrides: Record<string, string> }>;+ /** 派活(errand)每插件配置:首帧同步读(规则 7);config 缺项 = 跟随默认。 */+ errandPrefsSync: (id: string) => { config: Record<string, unknown> };+ /** 整卡替换派活配置(null / 空对象 = 全恢复跟随默认);返回清洗后的落盘值。 */+ setErrandConfig: (+ id: string,+ config: Record<string, unknown> | null,+ ) => Promise<{ config: Record<string, unknown> }>;/** 系统文件选择框(.cindy 过滤),只选不装;取消返回 { canceled: true }。 */pickFile: () => Promise<{ canceled: true } | { filePath: string }>;/** 只验不装:读出清单、签名信任等级与 icon data URL,供确认弹窗展示。 */diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex b46200aead..9a88fe5390 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -709,7 +709,7 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(diff.removed).toHaveLength(0);});- it('agent 详单必须与槽成对,且目前只接受 background: true', () => {+ it('agent 详单必须与槽成对,且只接受 background / errand 两项加档', () => {expect(validateGhostManifest({...goodChipManifest(),@@ -739,6 +739,56 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {).toBe(false);});+ it('agent.errand 派活加档:单列高风险权限,可与 background 并存(2026-07-31)', () => {+ const errand = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { errand: true },+ });+ expect(errand.ok).toBe(true);+ if (!errand.ok) return;+ expect(errand.manifest.agent).toEqual({ errand: true });+ expect(ghostPermissionItems(errand.manifest)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ key: 'agent:errand',+ kind: 'agent',+ labelKey: 'agentErrand',+ detailKey: 'agentErrandDetail',+ }),+ ]),+ );++ const both = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { background: true, errand: true },+ });+ expect(both.ok).toBe(true);+ if (!both.ok) return;+ expect(both.manifest.agent).toEqual({ background: true, errand: true });+ expect(ghostPermissionItems(both.manifest).map((item) => item.key)).toEqual(+ expect.arrayContaining(['agent:user-action', 'agent:background', 'agent:errand']),+ );++ // errand: false 与 background 双双非 true = 详单没意义,拒(应省略字段)。+ expect(+ validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { errand: false },+ }).ok,+ ).toBe(false);+ // errand 非布尔 → 拒。+ expect(+ validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'agent'],+ agent: { errand: 'yes' },+ }).ok,+ ).toBe(false);+ });+it('node 槽只允许包内入口与固定 stdio 协议,并如实生成高风险权限项', () => {const raw = {...goodChipManifest(),@@ -1215,6 +1265,42 @@ describe('ghost · cindy 能力详单校验(字段旧名 model 别名兼容)', (media: ['deposit'],});});++ // 2026-07-31 快问快答:text 类目独立落位(同 #784 的落位纪律),权限清单+ // 单独成行(cindy:text.oneshot,带固定说明)。+ it('text 类目落进 cindy.text,并生成 cindy:text.oneshot 权限行', () => {+ const v = validateGhostManifest(chipWithModel({ text: ['oneshot'] }));+ expect(v.ok, JSON.stringify(v)).toBe(true);+ if (!v.ok) return;+ expect(v.manifest.cindy).toEqual({ text: ['oneshot'] });+ expect(v.manifest.cindy?.image).toBeUndefined();+ expect(v.manifest.cindy?.video).toBeUndefined();+ expect(ghostPermissionItems(v.manifest)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ key: 'cindy:text.oneshot',+ kind: 'cindy',+ labelKey: 'cindyTextOneshot',+ detailKey: 'cindyTextOneshotDetail',+ }),+ ]),+ );+ });++ it('text 类目未知动作 / 空数组 → 拒;四类目可同时声明', () => {+ expect(validateGhostManifest(chipWithModel({ text: ['complete'] })).ok).toBe(false);+ expect(validateGhostManifest(chipWithModel({ text: [] })).ok).toBe(false);+ const v = validateGhostManifest(+ chipWithModel({ image: ['generate'], video: ['edit'], media: ['deposit'], text: ['oneshot'] }),+ );+ expect(v.ok, JSON.stringify(v)).toBe(true);+ expect(v.ok && v.manifest.cindy).toEqual({+ image: ['generate'],+ video: ['edit'],+ media: ['deposit'],+ text: ['oneshot'],+ });+ });});describe('ghost · model → cindy 旧名兼容(2026-07-11 更名)', () => {diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 87f57cd1f9..490174c55d 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -131,9 +131,21 @@ export interface GhostCardNeeds {* 申请 `agent` 槽默认只允许消费宿主在真实用户点击插件卡片时签发的* 一次性通行票。`background: true` 额外允许插件在没有当次点击票据时,* 对已经由用户建立过关联的会话发起回合;这是更高一档权限,安装时单列。+ *+ * `errand: true` = 派活取件(2026-07-31 开闸):允许插件把任务交给 Cindy+ * agent 在**插件专属 errand 会话**里跑一轮,并把最终回复文字取回。与+ * background 同为高风险加档,安装时单列。安全边界(全部主机代码强制):+ * - 任务文本只进普通 user 消息,绝不进 system prompt(与 agent-request 同纪律);+ * - errand 会话默认跑在专属对话目录、权限档默认 plan(只读);用户可在+ * 设置里按插件放开到 acceptEdits/auto,**永不提供 bypassPermissions**+ * (2026-07-31 Lizi 定案);+ * - errand 会话在侧边栏可见、可旁观、可随时停,不存在隐身会话;+ * - 每插件同时最多 1 单在途,任务表在内存(重启即丢,查询按"查无此单、+ * 可重新提交"处理)。*/export interface GhostAgentNeeds {background?: boolean;+ errand?: boolean;}/** 插件随包本地 Node 工作进程使用的 stdio 协议。 */@@ -386,6 +398,18 @@ export type GhostModelVideoAction = (typeof GHOST_MODEL_VIDEO_ACTIONS)[number];export const GHOST_CINDY_MEDIA_ACTIONS = ['deposit'] as const;export type GhostCindyMediaAction = (typeof GHOST_CINDY_MEDIA_ACTIONS)[number];+/**+ * cindy 槽·文本类可申请的动作(2026-07-31 开闸)。+ *+ * `oneshot` = 快问快答:意识递一段文字,主机经**轻量任务模型链**(与会话+ * 起标题、任务一句话总结同一条通道,见 utility-model/oneShotCandidates.ts)+ * 直答一次并把文字原样递回。不拉起 agent、无工具、无用户权限、不进任何+ * 会话——它与 agent 派活(agent 槽 errand)是两条信任面完全不同的路:+ * 这条只花模型额度,拿不到任何宿主能力。+ */+export const GHOST_CINDY_TEXT_ACTIONS = ['oneshot'] as const;+export type GhostCindyTextAction = (typeof GHOST_CINDY_TEXT_ACTIONS)[number];+/*** cindy 槽能力详单(卡槽⑤配套,原名模型槽,2026-07-11 设计定案):声明"这个意识被允许* 向主机点哪几类代办"——只有类目与动作,**不含任何具体模型/供应商信息**@@ -399,6 +423,8 @@ export interface GhostCindyNeeds {video?: GhostModelVideoAction[];/** 媒体类:deposit=寄存自己手里的媒体字节入总仓(换指纹,兼授权 release_media)。 */media?: GhostCindyMediaAction[];+ /** 文本类:oneshot=快问快答(轻量任务模型链直答一次,无 agent 无工具)。 */+ text?: GhostCindyTextAction[];}/**@@ -1401,6 +1427,7 @@ const GHOST_CINDY_PERM_LABEL: Record<string, string> = {'video.generate': 'cindyVideoGenerate','video.edit': 'cindyVideoEdit','media.deposit': 'cindyMediaDeposit',+ 'text.oneshot': 'cindyTextOneshot',};/**@@ -1410,6 +1437,7 @@ const GHOST_CINDY_PERM_LABEL: Record<string, string> = {*/const GHOST_CINDY_PERM_DETAIL: Record<string, string> = {'media.deposit': 'cindyMediaDepositDetail',+ 'text.oneshot': 'cindyTextOneshotDetail',};/**@@ -1481,6 +1509,16 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetailKey: 'agentBackgroundDetail',});}+ // 派活取件与 background 同级高风险,unshift 到清单上部单列——"能让+ // agent 替它干活并拿走结果"必须在装入前看得清清楚楚。+ if (manifest.agent?.errand === true) {+ items.unshift({+ key: 'agent:errand',+ kind: 'agent',+ labelKey: 'agentErrand',+ detailKey: 'agentErrandDetail',+ });+ }}// Node 是本机用户级执行权,不与浏览器沙箱的 `code` 混称。基础执行与// 常驻分别列出,用户能看懂“能运行”与“会一直运行”是两件事。@@ -2718,6 +2756,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {image: GHOST_MODEL_IMAGE_ACTIONS,video: GHOST_MODEL_VIDEO_ACTIONS,media: GHOST_CINDY_MEDIA_ACTIONS,+ text: GHOST_CINDY_TEXT_ACTIONS,};for (const [category, actionsRaw] of Object.entries(cindyRaw)) {const allowed = actionTable[category];@@ -2748,9 +2787,15 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (category === 'image') cindy.image = actions as GhostModelImageAction[];else if (category === 'video') cindy.video = actions as GhostModelVideoAction[];else if (category === 'media') cindy.media = actions as GhostCindyMediaAction[];+ else if (category === 'text') cindy.text = actions as GhostCindyTextAction[];else return { ok: false, reason: `cindy 能力类目 ${JSON.stringify(category)} 尚未接线(主机缺陷)` };}- if (cindy.image === undefined && cindy.video === undefined && cindy.media === undefined) {+ if (+ cindy.image === undefined &&+ cindy.video === undefined &&+ cindy.media === undefined &&+ cindy.text === undefined+ ) {return { ok: false, reason: 'cindy 能力详单不能是空对象' };}}@@ -2766,7 +2811,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: '声明了 agent 能力详单但 slots 未包含 "agent"' };}const agentRaw = raw.agent as Record<string, unknown>;- const unknownAgentField = Object.keys(agentRaw).find((key) => key !== 'background');+ const unknownAgentField = Object.keys(agentRaw).find(+ (key) => key !== 'background' && key !== 'errand',+ );if (unknownAgentField) {return {ok: false,@@ -2776,13 +2823,20 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (agentRaw.background !== undefined && typeof agentRaw.background !== 'boolean') {return { ok: false, reason: 'agent.background 必须是布尔值' };}- if (agentRaw.background !== true) {+ if (agentRaw.errand !== undefined && typeof agentRaw.errand !== 'boolean') {+ return { ok: false, reason: 'agent.errand 必须是布尔值' };+ }+ if (agentRaw.background !== true && agentRaw.errand !== true) {return {ok: false,- reason: 'agent 能力详单目前只有 background: true 这一项;仅需用户点击触发时请省略 agent 字段',+ reason:+ 'agent 能力详单只有 background: true / errand: true 两项加档;仅需用户点击触发时请省略 agent 字段',};}- agent = { background: true };+ agent = {+ ...(agentRaw.background === true ? { background: true } : {}),+ ...(agentRaw.errand === true ? { errand: true } : {}),+ };}// node 槽详单:只收包内入口 + 固定 stdio 协议 + 生命周期。这里刻意采用@@ -4176,6 +4230,99 @@ export type GhostPipeAgentResult =message: string;};+/* ── agent 槽·派活取件(errand,2026-07-31 开闸)──────────────────────────+ * 与 agent-request(把回合发进用户会话,结果给用户看)相对:errand 把任务+ * 交给插件**专属 errand 会话**里的 agent 跑一轮,最终回复文字取回给插件。+ * 须声明 'agent' 卡槽 + `agent.errand: true`(装入确认高风险单列)。+ * agent/模型/effort/fast/供应商/权限档/工作目录由用户在插件详情页配置+ * (缺省跟随新建草稿偏好;权限档默认 plan 只读,永不提供 bypassPermissions,+ * 2026-07-31 Lizi 定案);任务文本只进普通 user 消息,绝不进 system prompt。 */++/** 任务描述上限(与 agent-request 的最终消息同量级)。 */+export const GHOST_ERRAND_MAX_TASK_CHARS = 32_768;+/** 结构化上下文 JSON 化后的上限(与 agent-request 的 event 同量级)。 */+export const GHOST_ERRAND_MAX_CONTEXT_JSON_CHARS = 65_536;+/** 取回结果的截断上限(超长从头保留;截断时结果尾部带明示标记)。 */+export const GHOST_ERRAND_MAX_RESULT_CHARS = 65_536;+/** 完成结果保留时长(毫秒;同 cindy 异步代办:过期即清,查询按查无此单)。 */+export const GHOST_ERRAND_JOB_TTL_MS = 30 * 60_000;+/** 每插件相邻两次提交的最小间隔(毫秒;与 agent-request 后台档同口径)。+ * 同步等待(mode:'wait')的绝对上限直接复用 GHOST_PIPE_CALL_MAX_TOTAL_MS。 */+export const GHOST_ERRAND_MIN_INTERVAL_MS = 10_000;++/**+ * errand 会话允许的权限档。plan = 只读默认档;acceptEdits / auto 由用户在+ * 插件详情页显式放开。**bypassPermissions 刻意不在此列**(2026-07-31 定案:+ * 被骗的插件配上不设防会话 = 无人看守的用户全权,风险不可接受)。+ */+export const GHOST_ERRAND_PERMISSION_MODES = ['plan', 'acceptEdits', 'auto'] as const;+export type GhostErrandPermissionMode = (typeof GHOST_ERRAND_PERMISSION_MODES)[number];++/** 上行:派活提交与取件查询。 */+export type GhostPipeAgentErrandRequest =+ | {+ type: 'agent-errand-request';+ kind: 'run';+ /** 任务描述(1–32768 字符;进 errand 会话的普通 user 消息)。 */+ task: string;+ /** 可选结构化上下文:主机 JSON.stringify 后附在任务消息尾部(≤64KB)。 */+ context?: unknown;+ /** errand 会话标题提示(仅首次创建该插件的 errand 会话时采用;1–100 字符)。 */+ title?: string;+ /**+ * 'wait' = 同步吊着等完成(管子自动续命,30 分钟天花板);缺省异步:+ * 受理后立即返回 jobId,用 kind:'query' 轮询取件。agent 干活是分钟级+ * 的,推荐缺省异步 + 插件自己掌握轮询节奏。+ */+ mode?: 'wait';+ /** 归因号(tool-call 触发时把 callId 原样带上;同 cindy-request 语义)。 */+ callId?: string;+ }+ | {+ type: 'agent-errand-request';+ kind: 'query';+ /** 提交受理时返回的任务号(仅本插件自己的任务可查)。 */+ jobId: string;+ };++/** errand 结构化错误码(稳定契约,新增值不改旧值语义)。 */+export type GhostAgentErrandErrorCode =+ | 'INVALID_REQUEST'+ | 'PERMISSION_DENIED'+ | 'BUSY'+ | 'RATE_LIMITED'+ | 'HOST_NOT_READY'+ | 'JOB_NOT_FOUND'+ | 'SESSION_UNAVAILABLE'+ | 'TURN_FAILED'+ | 'TIMEOUT'+ | 'INTERNAL';++/** 下行(invoke 返回值):受理/进行中、完成、失败三态。 */+export type GhostPipeAgentErrandResult =+ | {+ /** 受理(kind:'run' 异步)与查询进行中(kind:'query')共用本分支。 */+ ok: true;+ jobId: string;+ status: 'running';+ /** errand 会话 id(用户可在侧边栏找到它旁观)。 */+ sessionId?: string;+ /** 已耗时(秒;仅查询返回)。 */+ elapsedSeconds?: number;+ }+ | {+ /** 完成态:text 即 agent 本轮的最终回复(超长按上限截断并带标记)。 */+ ok: true;+ jobId: string;+ status: 'done';+ sessionId: string;+ text: string;+ /** 实际干活的 agent 与模型(用户配置的解析结果;诊断展示用)。 */+ agentKind?: string;+ model?: string;+ }+ | { ok: false; errorCode: GhostAgentErrandErrorCode; message: string };+/*** node-request 长任务绝对上限(毫秒,15 分钟):声明 maxTotalMs 后请求最长* 可以吊多久的天花板——盖住旧 Bridge 约 12 分钟的构建时长,又不给真死掉的@@ -4720,6 +4867,18 @@ export const GHOST_CINDY_DEPOSIT_QUOTA_BYTES = 1024 * 1024 * 1024;export const GHOST_CINDY_DEPOSIT_BURST = 8;export const GHOST_CINDY_DEPOSIT_REFILL_MS = 1000;+/**+ * ── oneshot_text 政策参数(2026-07-31 开闸)────────────────────────────+ * 快问快答走轻量任务模型链,秒级到几十秒,只有同步形态(没有 submit 档:+ * 一单等不起的文本问答本身就是用错了通道)。上限对齐 agent-request 的+ * 消息量级;回答预算钳在小额度——这是"快问快答",不是长文生成通道。+ */+export const GHOST_ONESHOT_TEXT_MAX_PROMPT_CHARS = 32_768;+export const GHOST_ONESHOT_TEXT_MAX_TOKENS = 4096;+export const GHOST_ONESHOT_TEXT_DEFAULT_MAX_TOKENS = 1024;+/** 单次快问快答的等待上限(毫秒;超时按结构化失败收单,不吊管子)。 */+export const GHOST_ONESHOT_TEXT_TIMEOUT_MS = 60_000;+/*** 上行:cindy 槽代办请求(请 Cindy 本体出图 / 改图)。协议 type 为* 'cindy-request'(2026-07-11 由 'model-request' 更名,主机对旧名保持@@ -4864,6 +5023,33 @@ export type GhostPipeCindyRequest =kind: 'release_media';/** 要撤回的寄存指纹(sha256)。 */hash: string;+ }+ | {+ /**+ * 快问快答(2026-07-31 开闸):把 prompt 交给主机的轻量任务模型链+ * 直答一次,答案文字随本次 invoke 的返回值递回。不拉起 agent、无+ * 工具、无用户权限、不进任何会话。须声明 'cindy' 卡槽 ++ * `cindy.text: ["oneshot"]`。+ *+ * 选型不在意识手里:走主机的轻量任务模型链(用户在设置里配置的+ * 快速通道,与会话起标题同一条),链上无可用候选时收到+ * errorCode:'NO_CANDIDATE' 的结构化失败——意识必须把它当正常失败面+ * 处理(典型场景:用户只登了订阅、没配可用的快速通道凭证)。+ */+ type: 'cindy-request';+ kind: 'oneshot_text';+ /** 要问的内容(1–32768 字符)。 */+ prompt: string;+ /**+ * 期望模型只输出 JSON:主机在提示里注明并校验返回可解析,解析失败+ * 按 errorCode:'BAD_MODEL_OUTPUT' 收单(text 里带原始输出,便于排查)。+ * 具体字段结构写进 prompt 里描述;主机不做 schema 逐字段校验。+ */+ expectJson?: boolean;+ /** 回答长度预算(token;1–4096,缺省 1024)。 */+ maxTokens?: number;+ /** 归因号(同 gen_image 分支)。 */+ callId?: string;};/**@@ -4958,7 +5144,27 @@ export type GhostPipeModelResult =quotaUsedBytes: number;quotaLimitBytes: number;}- | { ok: false; message: string };+ | {+ /**+ * oneshot_text 成功(独立成员:有 `text`、无 `url`/`status`,可与+ * 其它成功分支可靠判别)。+ */+ ok: true;+ text: string;+ /** 实际应答的供应商/模型标识(轻量链解析结果;仅诊断展示用)。 */+ model?: string;+ }+ | {+ ok: false;+ message: string;+ /**+ * 结构化错误码(2026-07-31 起 oneshot_text 填写;媒体代办暂只有+ * message)。稳定值:'NO_CANDIDATE'(快速通道无可用模型/凭证)、+ * 'BAD_MODEL_OUTPUT'(expectJson 下输出不可解析)、'RATE_LIMITED'、+ * 'TIMEOUT'、'PERMISSION_DENIED'、'INVALID_PARAMS'、'INTERNAL'。+ */+ errorCode?: string;+ };/* ── 订阅槽①:事件协议(2026-07-12 定案:一种事件模型,两个类型)──────* did- 旁听:fire-and-forget,主机投完即走,意识崩/慢不影响任何会话;diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex a45f57606e..c0edf8387f 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -28,7 +28,7 @@| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) || 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` || 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |-| 能力 slot(网络/通知/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts` |+| 能力 slot(网络/通知/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) || 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 || 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` || 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |@@ -90,7 +90,15 @@- `network.secrets[].url` 可由 Host 作为 Setup 字段旁的辅助获取入口展示。该地址必须继续满足 manifest 安装期的 `https`、无内嵌凭证校验;它不是 Agent 文案或 plan的一部分,插件也不能通过 `settings.js` 动态替换 Setup 卡地址。-- 模型调用一律走 Cindy 统一通道,不允许插件自建绕过通道的推理请求。+- 模型调用一律走 Cindy 统一通道,不允许插件自建绕过通道的推理请求。两条 AI 代办+ 通道的固定边界(2026-07-31 定案,主机代码强制):+ - 快问快答(`cindy.text.oneshot`)只走主机轻量任务模型链,无 agent、无工具、+ 不进会话;选型不在插件手里,链上无候选时返回结构化 `NO_CANDIDATE`。+ - 派活取件(`agent.errand`)的任务文本**只进普通 user 消息、绝不进 system+ prompt**;errand 会话侧边栏可见、可旁观可叫停;agent/模型/权限档/工作+ 目录全部由用户在插件详情页配置,权限档只有 `plan`(默认)/`acceptEdits`/+ `auto` 三档,**`bypassPermissions` 在协议层就不存在**,不得以任何形式放开;+ 工作目录缺省为插件专属对话目录,指向真实项目必须由用户亲手选择。- 附件、媒体、目录和保存路径通过归属校验后的 grant/deposit/ledger 交接,**禁止把宿主绝对路径或不必要的字节暴露给沙箱**。媒体字节须走[`media-storage-and-protocols.md`](media-storage-and-protocols.md) 的统一入库。