Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(local-agent): add isolated generic local Agent API

DavidShen27ebb24419c3
diff --git a/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx b/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx
new file mode 100644
index 0000000000..c6bbf7b3d2
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-agent/local-agent-fixture.tsx
@@ -0,0 +1,20 @@
+import { mountPage, subscription } from '../../ui-page/harness';
+import { LocalAgentSection } from '../../../src/renderer/components/settings/LocalAgentSection';
+
+mountPage({
+ host: ctx => ({
+ localAgent: {
+ onConnectionsChanged: subscription('localAgentChanged'),
+ connections: async () => {
+ if (ctx.data.loadFailed) throw new Error('fixture connection read failed');
+ return ctx.data.connections ?? [];
+ },
+ revoke: async (id: string) => {
+ if (id !== ctx.data.connections?.[0]?.id) throw new Error('wrong connection selected');
+ if (ctx.data.revokeFailed) throw new Error('fixture revoke failed');
+ return !ctx.data.cancel;
+ },
+ },
+ }),
+ render: () => <div className="mx-auto w-full max-w-3xl p-5"><LocalAgentSection /></div>,
+});
diff --git a/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs b/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs
new file mode 100644
index 0000000000..d121701fb6
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-agent/ui-page.mjs
@@ -0,0 +1,34 @@
+const connections = [
+ { id: 'grant-notes', name: 'Notes', clientId: 'org.example.notes' },
+ { id: 'grant-board', name: 'Board', clientId: 'org.example.board' },
+];
+
+export default {
+ name: 'local-agent', entry: './local-agent-fixture.tsx', viewport: { width: 900, height: 650 },
+ real: 'LocalAgentSection, standard settings rows and themed Button',
+ notCovered: 'Native consent, IPC authentication and actual grant revocation; these require isolated Desktop and protocol integration checks.',
+ cases: {
+ default: { about: 'Revoke one application and retain the other row', data: { connections } },
+ long: { about: 'Long unverified application names and IDs at phone width', viewport: { width: 390, height: 844 }, data: { connections: [
+ { id: 'grant-long', name: 'Independent application with a long name 独立本机应用程序', clientId: 'org.example.an.independent.application.with.a.long.identifier' }, connections[1],
+ ] } },
+ empty: { about: 'No application is connected', data: { connections: [] } },
+ 'read-failed': { about: 'Connection read error remains visible', data: { loadFailed: true } },
+ cancelled: { about: 'Cancelling native confirmation retains both applications', data: { connections, cancel: true } },
+ 'revoke-failed': { about: 'Failed revocation retains both applications and offers retry', data: { connections, revokeFailed: true } },
+ },
+ async check(page, ui) {
+ const heading = page.getByRole('heading', { name: await ui.t('localAgent.title') });
+ await heading.waitFor();
+ const list = ui.data.connections ?? [];
+ if (!list.length) {
+ await page.getByText(await ui.t(ui.data.loadFailed ? 'localAgent.failed' : 'localAgent.empty'), { exact: true }).waitFor();
+ return;
+ }
+ await page.getByText(list[0].clientId, { exact: false }).waitFor();
+ await page.getByRole('button', { name: await ui.t('localAgent.revokeConnection', { app: list[0].name }), exact: true }).click();
+ if (ui.data.cancel || ui.data.revokeFailed) await page.getByText(list[0].clientId, { exact: false }).waitFor();
+ else await page.getByText(list[0].clientId, { exact: false }).waitFor({ state: 'detached' });
+ await page.getByText(list[1].clientId, { exact: false }).waitFor();
+ },
+};
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3fb364efa2..2c3a9292d0 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -185,6 +185,7 @@ app.commandLine.appendSwitch('enable-features', 'SharedArrayBuffer');
// Windows 上 codex app-server 子进程不会随父死 → 残留孤儿, 持有 binary 文件锁,
// 用户下次启动时撞 EBUSY / 端口占用 (anthropic-compat-proxy 等)。
async function shutdownMaker(): Promise<{ piSessionFailures: number }> {
+ await disposeLocalAgentHost();
stopWorktreeRecycleMaintenance();
// Do not terminate Main while one workspace patch command is settling.
await waitForTurnChangeSetActions();
@@ -416,6 +417,7 @@ import {
isCindyPersonalRuntime,
} from './cindy-make/versionRuntimeIdentity.js';
import { createStorageIpcHandlers } from './cindy-media/storageIpc';
+import { disposeLocalAgentHost, localAgentConnections, revokeLocalAgentConnections } from './local-agent/service.js';
import { clearLocalEntries } from './device-link/remoteMediaCacheStore';
import {
collectDatabaseSizeWarningStatus,
@@ -2028,6 +2030,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// Marked before the await: `shutdownStarted` is set on entry, so the
// singleton is poisoned even if this rejects.
if (maker) shutdownRan = true;
+ await disposeLocalAgentHost();
const shutdownReport = maker
? await maker.shutdown({ reason: 'account-boundary' })
: undefined;
@@ -8551,6 +8554,14 @@ const registerIpcHandlers = () => {
? Promise.resolve({ bytes: 0, fileCount: 0 })
: withActiveChatAttachmentRoot((rootDir) => getFixedDirectoryStats(rootDir)),
});
+ ipcMain.handle('local-agent:connections', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return localAgentConnections(() => assertTrustedAppRendererEvent(event));
+ });
+ ipcMain.handle('local-agent:revoke', (event, connectionId?: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return revokeLocalAgentConnections(connectionId, () => assertTrustedAppRendererEvent(event));
+ });
ipcMain.handle('cindy-media:storage-stats', (event) => {
assertTrustedAppRendererEvent(event);
return storageHandlers.stats();
diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
new file mode 100644
index 0000000000..f289018a8f
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
@@ -0,0 +1,175 @@
+/**
+ * 测试价值:openLocalAgentRuntime 的发送、停止和关闭是授权撤销的最终执行点。
+ * 规则:通用 API 撤销后不能再启动或发送;原投影测试没有跨 await 的生命周期覆盖。
+ * 最小失败输入:setEffort 或重开会话挂起时并发 send / interrupt / close。
+ * tier: integration(只使用系统临时目录与可控原生句柄,无 Electron、模型或账号)。
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+vi.mock('@cindy/maker-core', () => ({ LOCAL_AGENT_CLIENT: Symbol('local-agent-client') }));
+import { openLocalAgentRuntime } from '../runtime.js';
+import type { AgentEvent } from '@cindy/maker-core';
+
+const cleanups: Array<() => Promise<unknown>> = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+function handle(id: string) {
+ const ended = deferred();
+ return {
+ sdkSessionId: id,
+ send: vi.fn(async () => {}),
+ steer: vi.fn(async () => {}),
+ abort: vi.fn(async () => {}),
+ setEffort: vi.fn(async () => {}),
+ setInteractionListener: vi.fn(),
+ onEvent: vi.fn((_listener: (event: AgentEvent) => void) => () => {}),
+ onStatusChange: vi.fn(),
+ beginTurnContinuationWait: vi.fn<() => string | null>(() => null),
+ getObservedCurrentTurnTerminal: vi.fn(() => ({ kind: 'none' })),
+ close: vi.fn(async () => {
+ ended.resolve();
+ }),
+ };
+}
+async function fixture() {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-local-runtime-'));
+ cleanups.push(() => fs.rm(directory, { recursive: true, force: true }));
+ const first = handle('first');
+ const maker = { startLocalAgentSession: vi.fn(async () => first) };
+ const runtime = await openLocalAgentRuntime(
+ maker as any,
+ directory,
+ {
+ isolationKey: 'grant-a',
+ mcpName: 'client',
+ legacyRuntime: false,
+ cwd: directory,
+ model: {
+ id: 'route',
+ label: 'Model',
+ provider: 'provider',
+ model: 'model',
+ engine: 'pi',
+ efforts: ['high'],
+ images: false,
+ isDefault: true,
+ },
+ access: 'none',
+ tools: [],
+ },
+ { url: 'http://127.0.0.1:1/mcp/fixture', token: 'invalid-fixture-token', emit: () => {} },
+ );
+ cleanups.push(() => runtime.close());
+ return { runtime, maker, first };
+}
+const message = { parts: [{ type: 'text', text: 'hello' }], effort: 'high' };
+
+describe('local client runtime lifecycle', () => {
+ it('passes slash-prefixed app text as a literal instead of rejecting paths or running a native command', async () => {
+ const f = await fixture();
+ await f.runtime.call('send', { parts: [{ type: 'text', text: '/workspace/example' }] });
+ expect(f.first.send).toHaveBeenCalledWith({
+ type: 'user',
+ content: [{ type: 'text', text: ' /workspace/example' }],
+ });
+ });
+ it('keeps the app execution busy across a provider continuation until Session observes its final boundary', async () => {
+ const f = await fixture();
+ await f.runtime.call('send', { parts: message.parts });
+ const deliver = f.first.onEvent.mock.calls[0][0];
+ f.first.beginTurnContinuationWait.mockReturnValueOnce('active');
+ deliver({ type: 'done', turnContinuationId: 7, data: { status: 'completed' } });
+ await expect(f.runtime.call('send', { parts: message.parts })).rejects.toMatchObject({
+ code: 'BUSY',
+ });
+ f.first.getObservedCurrentTurnTerminal.mockReturnValue({ kind: 'done' });
+ deliver({ type: 'done', data: { status: 'completed' } });
+ await f.runtime.call('send', { parts: message.parts });
+ expect(f.first.send).toHaveBeenCalledTimes(2);
+ });
+ it('reserves a send before awaiting effort so a concurrent send cannot double-submit', async () => {
+ const f = await fixture(),
+ entered = deferred(),
+ held = deferred();
+ f.first.setEffort.mockImplementation(async () => {
+ entered.resolve();
+ await held.promise;
+ });
+ const sending = f.runtime.call('send', message);
+ await entered.promise;
+ const rejected = expect(f.runtime.call('send', message)).rejects.toMatchObject({
+ code: 'BUSY',
+ });
+ held.resolve();
+ await sending;
+ await rejected;
+ expect(f.first.send).toHaveBeenCalledTimes(1);
+ });
+ it('does not send after an interrupt arrives during effort preparation', async () => {
+ const f = await fixture(),
+ entered = deferred(),
+ held = deferred();
+ f.first.setEffort.mockImplementation(async () => {
+ entered.resolve();
+ await held.promise;
+ });
+ const sending = f.runtime.call('send', message);
+ const rejected = expect(sending).rejects.toMatchObject({ code: 'INTERRUPTED' });
+ await entered.promise;
+ await f.runtime.call('interrupt', {});
+ held.resolve();
+ await rejected;
+ expect(f.first.send).not.toHaveBeenCalled();
+ });
+ it('does not restart an engine after close during an instructions rebuild', async () => {
+ const f = await fixture(),
+ entered = deferred(),
+ held = deferred();
+ f.first.close.mockImplementation(async () => {
+ entered.resolve();
+ await held.promise;
+ });
+ await f.runtime.call('instructions', { instructions: 'new context' });
+ const sending = f.runtime.call('send', message);
+ const rejected = expect(sending).rejects.toMatchObject({ code: 'SESSION_UNAVAILABLE' });
+ await entered.promise;
+ const closing = f.runtime.close();
+ held.resolve();
+ await closing;
+ await rejected;
+ expect(f.maker.startLocalAgentSession).toHaveBeenCalledTimes(1);
+ expect(f.first.send).not.toHaveBeenCalled();
+ });
+ it('closes a late replacement engine instead of sending after its grant was closed', async () => {
+ const f = await fixture(),
+ entered = deferred(),
+ held = deferred(),
+ late = handle('late');
+ cleanups.push(() => late.close());
+ f.maker.startLocalAgentSession.mockImplementationOnce(async () => {
+ entered.resolve();
+ await held.promise;
+ return late;
+ });
+ await f.runtime.call('instructions', { instructions: 'new context' });
+ const sending = f.runtime.call('send', message);
+ const rejected = expect(sending).rejects.toMatchObject({ code: 'SESSION_UNAVAILABLE' });
+ await entered.promise;
+ await f.runtime.close();
+ held.resolve();
+ await rejected;
+ expect(late.close).toHaveBeenCalledTimes(1);
+ expect(late.close).toHaveBeenCalledWith({ reason: 'account-boundary' });
+ expect(late.send).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
new file mode 100644
index 0000000000..e8df049662
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
@@ -0,0 +1,198 @@
+/**
+ * 测试价值:createEventProjection 的文本与工具事件直接决定 HHH 可见记录。
+ * 依据:流式快照不得重复回复、宿主工具不得重复执行;既有 renderer 投影不覆盖本机 API。
+ * 最小失败输入:delta 后 final、宿主 MCP 同时出现原生 tool_result、终态错误后 done。
+ * tier: unit(纯事件、无 Electron);单文件实测 2ms。与 server 分文件以隔离真实 socket tier。
+ */
+import { describe, expect, it, vi } from 'vitest';
+vi.mock('@cindy/maker-core', () => ({ LOCAL_AGENT_CLIENT: Symbol('local-agent-client') }));
+import { createEventProjection } from '../runtime.js';
+import { localAgentModels } from '../catalog.js';
+import type { ProviderView } from '@cindy/model-providers';
+
+describe('whole Cindy catalog projection', () => {
+ const provider = (id: string, patch: Partial<ProviderView> = {}) =>
+ ({
+ id,
+ name: id,
+ source: 'user',
+ connected: true,
+ agents: ['claude-code', 'codex', 'pi'],
+ routing: { 'claude-code': {}, codex: {}, pi: {} },
+ models: { 'claude-code': [], codex: [], pi: [] },
+ ...patch,
+ }) as ProviderView;
+ const model = {
+ id: 'same-model',
+ name: '同名模型',
+ mode: 'chat',
+ efforts: ['low', 'high'],
+ defaultEffort: 'low',
+ modalities: { input: ['text', 'image'], output: ['text'] },
+ };
+ it('includes all available engines and distinguishes supplier/model collisions without leaking routing', () => {
+ const result = localAgentModels(
+ ['A', 'B'].map((id) =>
+ provider(id, {
+ models: { 'claude-code': [model], codex: [model], pi: [model] },
+ routing: { 'claude-code': { apiKey: 'SECRET' }, codex: { endpoint: 'PRIVATE' }, pi: {} },
+ } as never),
+ ),
+ ['claude-code', 'codex', 'pi'],
+ );
+ expect(result).toHaveLength(6);
+ expect(new Set(result.map((m) => m.id)).size).toBe(6);
+ expect(result.every((m) => m.id.length === 64 && m.images)).toBe(true);
+ expect(result.map((m) => m.label)).toContain('B · 同名模型 · pi');
+ expect(result.map((m) => m.providerLabel)).toEqual(['A', 'A', 'A', 'B', 'B', 'B']);
+ expect(JSON.stringify(result)).not.toMatch(/SECRET|PRIVATE|apiKey|endpoint/);
+ expect(
+ localAgentModels(
+ [
+ provider('A', {
+ models: { 'claude-code': [model], codex: [model], pi: [model] },
+ } as never),
+ ],
+ ['pi'],
+ ),
+ ).toHaveLength(1);
+ });
+ it('keeps provider display names separate from stable routing identities', () => {
+ const result = localAgentModels(
+ [provider('source-id', { name: '我的 · 网关', models: { pi: [model] } } as never)],
+ ['pi'],
+ );
+ expect(result[0]).toMatchObject({ provider: 'source-id', providerLabel: '我的 · 网关' });
+ });
+ it('filters disconnected, suspended, disabled, retired and non-chat choices and keeps large catalogs fast', () => {
+ const choices = [
+ model,
+ { ...model, id: 'disabled', disabled: true },
+ { ...model, id: 'retired', status: 'retired' },
+ { ...model, id: 'image-only', mode: 'image' },
+ ];
+ expect(
+ localAgentModels(
+ [
+ provider('A', { models: { pi: choices } } as never),
+ provider('B', { suspended: true }),
+ provider('C', { connected: false }),
+ ],
+ ['pi'],
+ ),
+ ).toHaveLength(1);
+ const large = provider('large', {
+ models: { pi: Array.from({ length: 500 }, (_, i) => ({ ...model, id: `chat-${i}` })) },
+ } as never);
+ const start = performance.now();
+ expect(localAgentModels([large], ['pi'])).toHaveLength(500);
+ expect(performance.now() - start).toBeLessThan(500);
+ });
+});
+
+describe('native event projection', () => {
+ // Actual native done envelopes differ: Codex promptTokens, Pi cacheCreation,
+ // and Claude request deltas alongside a cumulative SDK aggregate.
+ it.each([
+ { usage: { promptTokens: 2, cachedTokens: 3, cacheCreationTokens: 4, completionTokens: 5 } },
+ { usage: { inputTokens: 2, cacheReadTokens: 3, cacheCreationTokens: 4, outputTokens: 5 } },
+ {
+ usage: { input_tokens: 200, output_tokens: 500 },
+ usageSegments: [
+ { inputTokens: 2, cacheReadTokens: 3, cacheCreateTokens: 4, outputTokens: 5 },
+ ],
+ },
+ ])(
+ 'preserves native token buckets without counting a cumulative aggregate twice (%j)',
+ (data) => {
+ const emit = vi.fn(),
+ projection = createEventProjection(emit);
+ projection.begin();
+ projection.accept({ type: 'done', data });
+ expect(emit.mock.calls[0][0]).toEqual({
+ type: 'usage',
+ data: { input: 9, cached: 3, output: 5 },
+ });
+ },
+ );
+ it.each(['client', 'calendar', 'hhh'])(
+ 'does not repeat final snapshots or duplicate tools in namespace %s',
+ (namespace) => {
+ const emit = vi.fn(),
+ p = createEventProjection(emit, namespace);
+ p.begin();
+ for (const event of [
+ { type: 'text', data: { text: 'hello', isFinal: false } },
+ { type: 'text', data: { text: 'hello', isFinal: true } },
+ { type: 'thinking', data: { text: 'think', stage: 'delta' } },
+ { type: 'thinking', data: { text: 'think', stage: 'final' } },
+ {
+ type: 'tool_use',
+ data: { toolUseId: 'host', toolName: `mcp__${namespace}__send`, input: {} },
+ },
+ { type: 'tool_result_full', data: { toolUseId: 'host', fullText: 'done' } },
+ {
+ type: 'tool_use',
+ data: { toolUseId: 'codex-host', toolName: `mcp:${namespace}:list_items`, input: {} },
+ },
+ { type: 'tool_result_full', data: { toolUseId: 'codex-host', fullText: 'done' } },
+ {
+ type: 'done',
+ data: {
+ result: 'hello',
+ status: 'completed',
+ usage: { inputTokens: 10, cacheReadTokens: 5, outputTokens: 2 },
+ },
+ },
+ ])
+ p.accept(event as any);
+ expect(emit.mock.calls.map(([e]) => e.type)).toEqual([
+ 'text',
+ 'thinking',
+ 'usage',
+ 'turn_end',
+ ]);
+ expect(emit.mock.calls[2][0].data).toEqual({ input: 15, cached: 5, output: 2 });
+ },
+ );
+ it('keeps native tool activity and emits one failure per turn', () => {
+ const emit = vi.fn(),
+ p = createEventProjection(emit);
+ p.begin();
+ p.accept({
+ type: 'tool_use',
+ data: { toolUseId: 'native', toolName: 'bash', input: { command: 'pwd' } },
+ });
+ p.accept({ type: 'tool_result_full', data: { toolUseId: 'native', fullText: 'result' } });
+ p.fail('stopped');
+ p.accept({ type: 'done', data: { result: 'late' } });
+ expect(emit.mock.calls.map(([e]) => e.type)).toEqual([
+ 'tool_started',
+ 'tool_finished',
+ 'turn_end',
+ ]);
+ });
+ // Native Pi/Codex Stop uses cancelled; an error can carry paid usage before a paired done.
+ it('preserves cancellation and usage on a failed turn without emitting another terminal', () => {
+ const emit = vi.fn(),
+ p = createEventProjection(emit);
+ p.begin();
+ p.accept({
+ type: 'done',
+ data: { status: 'cancelled', usage: { inputTokens: 3, outputTokens: 1 } },
+ });
+ expect(emit.mock.calls.at(-1)?.[0].data.status).toBe('interrupted');
+ p.begin();
+ emit.mockClear();
+ p.accept({
+ type: 'error',
+ data: { message: 'failed', isTerminal: true, usage: { inputTokens: 7, outputTokens: 2 } },
+ });
+ p.accept({
+ type: 'done',
+ data: { status: 'failed', usage: { inputTokens: 7, outputTokens: 2 } },
+ });
+ expect(emit.mock.calls.map(([event]) => event.type)).toEqual(['usage', 'turn_end']);
+ expect(emit.mock.calls[0][0].data).toEqual({ input: 7, cached: 0, output: 2 });
+ });
+});
diff --git a/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts
new file mode 100644
index 0000000000..7646914001
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts
@@ -0,0 +1,691 @@
+/**
+ * 测试价值:createLocalAgentServer 的真实 loopback 授权、MCP、恢复与撤销协议。
+ * 依据:本机接入必须独立授权、不重放副作用、不跨授权恢复;既有 device-link 测试不经过此接口。
+ * 最小失败输入:无凭据 models、同 id 不同 payload、另一 grant 的 resume、超过批次大小的单事件。
+ * tier: integration(真实临时文件与 socket);单文件实测 136ms。
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { fileURLToPath } from 'node:url';
+import { request } from 'node:http';
+import { once } from 'node:events';
+import { createLocalAgentServer, type LocalAgentServerDeps } from '../server.js';
+import type { LocalAgentModel } from '../catalog.js';
+
+const model: LocalAgentModel = {
+ id: 'source-model-engine',
+ provider: 'custom',
+ engine: 'pi',
+ model: 'same',
+ label: 'Custom · Same · pi',
+ efforts: [],
+ images: false,
+ isDefault: true,
+};
+const cleanups: Array<() => Promise<unknown>> = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+
+async function fixture(overrides: Partial<LocalAgentServerDeps> = {}) {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-local-agent-test-'));
+ cleanups.push(() => fs.rm(directory, { recursive: true, force: true }));
+ const call = vi.fn(async () => ({})),
+ close = vi.fn(async () => {});
+ let bridge: Parameters<LocalAgentServerDeps['open']>[1];
+ const open = vi.fn(async (_input, value) => {
+ bridge = value;
+ return { id: 'native-session', resumed: Boolean(_input.resume), call, close };
+ });
+ const deps: LocalAgentServerDeps = {
+ directory,
+ version: 'test',
+ scope: () => 'owner',
+ models: async () => [model],
+ approve: async () => true,
+ open,
+ warn: () => {},
+ ...overrides,
+ };
+ let server = await createLocalAgentServer(deps);
+ cleanups.push(() => server.close());
+ let sequence = 0;
+ const rpc = async (
+ method: string,
+ params: unknown = {},
+ secret?: string,
+ id = `client123:${++sequence}`,
+ ) => {
+ const response = await fetch(`${server.base}/rpc`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(secret ? { Authorization: `Bearer ${secret}` } : {}),
+ },
+ body: JSON.stringify({ version: 1, id, method, params }),
+ });
+ return response.json() as Promise<any>;
+ };
+ const pair = async (client: unknown = 'HHH') => {
+ const { result } = await rpc('connect/start', { client });
+ if (!result) throw new Error('client pairing rejected');
+ await fetch(result.url);
+ return { result, response: await rpc('connect/poll', { id: result.id, claim: result.claim }) };
+ };
+ const connect = async (client: unknown = 'HHH') =>
+ (await pair(client)).response.result.token as string;
+ const start = (secret: string, sessionId = 'run', extra = {}) =>
+ rpc(
+ 'session/open',
+ {
+ sessionId,
+ cwd: directory,
+ model: model.id,
+ tools: [{ name: 'send', description: '', parameters: { type: 'object' } }],
+ access: 'none',
+ ...extra,
+ },
+ secret,
+ );
+ return {
+ directory,
+ rpc,
+ pair,
+ connect,
+ start,
+ call,
+ close,
+ open,
+ bridge: () => bridge!,
+ server: () => server,
+ async restart() {
+ await server.close();
+ server = await createLocalAgentServer(deps);
+ },
+ };
+}
+
+describe('local application authorization and lifecycle', () => {
+ // Revoking the token is immediate; unconfirmed native shutdown must be reported
+ // and retained for cleanup, rather than claiming that an executor has stopped.
+ it('reports an unconfirmed close and retries cleanup without restoring revoked authority', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ await f.start(secret);
+ f.close.mockRejectedValueOnce(new Error('native process exit unconfirmed'));
+ await expect(f.server().revoke(f.server().connections()[0].id)).rejects.toMatchObject({
+ code: 'RUNTIME_CLOSE_UNCONFIRMED',
+ });
+ expect((await f.rpc('models', {}, secret)).error.code).toBe('UNAUTHORIZED');
+ await f.server().close();
+ expect(f.close).toHaveBeenCalledTimes(2);
+ });
+ it('keeps concurrent opens within the persisted resume limit so the service can restart', async () => {
+ const releases: Array<() => void> = [];
+ const f = await fixture({
+ open: async () => {
+ await new Promise<void>((resolve) => releases.push(resolve));
+ return { id: 'native', resumed: false, call: async () => ({}), close: async () => {} };
+ },
+ });
+ const secret = await f.connect();
+ const file = path.join(f.directory, 'grants.json');
+ const stored = JSON.parse(await fs.readFile(file, 'utf8'));
+ stored.bindings = Object.fromEntries(
+ Array.from({ length: 4095 }, (_, i) => [
+ `resume-${i}`,
+ { owner: stored.grants[0].id, model: model.id, native: 'native' },
+ ]),
+ );
+ await fs.writeFile(file, JSON.stringify(stored));
+ await f.restart();
+ const a = f.start(secret, 'a'),
+ b = f.start(secret, 'b');
+ await vi.waitFor(() => expect(releases).toHaveLength(2));
+ for (const release of releases) release();
+ const results = await Promise.all([a, b]);
+ expect(results.filter((result) => result.result)).toHaveLength(1);
+ expect(results.find((result) => result.error)?.error.code).toBe('RESUME_LIMIT');
+ expect(Object.keys(JSON.parse(await fs.readFile(file, 'utf8')).bindings)).toHaveLength(4096);
+ await f.restart();
+ expect((await f.rpc('models', {}, secret)).result.models).toEqual([model]);
+ });
+ it('does not let a late failed open close the newer run reusing its public session ID', async () => {
+ let release!: () => void, began!: () => void;
+ const started = new Promise<void>((resolve) => {
+ began = resolve;
+ });
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const oldClose = vi.fn(async () => {}),
+ newClose = vi.fn(async () => {});
+ let opens = 0;
+ const f = await fixture({
+ open: async () => {
+ if (++opens === 1) {
+ began();
+ await held;
+ return { id: 'old', resumed: false, call: async () => ({}), close: oldClose };
+ }
+ return { id: 'new', resumed: false, call: async () => ({}), close: newClose };
+ },
+ });
+ const secret = await f.connect();
+ const old = f.start(secret);
+ await started;
+ await f.rpc('session/close', { sessionId: 'run' }, secret);
+ expect((await f.start(secret)).error).toBeUndefined();
+ release();
+ expect((await old).error).toBeDefined();
+ expect(oldClose).toHaveBeenCalledTimes(1);
+ expect(newClose).not.toHaveBeenCalled();
+ expect((await f.rpc('interrupt', { sessionId: 'run' }, secret)).error).toBeUndefined();
+ });
+
+ it('rejects an MCP request whose body completes only after its application is revoked', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ await f.start(secret);
+ const bridge = f.bridge();
+ const connection = f.server().connections()[0];
+ const req = request(bridge.url, {
+ method: 'POST',
+ signal: AbortSignal.timeout(2000),
+ headers: {
+ Authorization: `Bearer ${bridge.token}`,
+ 'Content-Type': 'application/json',
+ Expect: '100-continue',
+ },
+ });
+ const response = new Promise<number>((resolve, reject) => {
+ req.once('response', (res) => {
+ res.resume();
+ resolve(res.statusCode!);
+ });
+ req.once('error', reject);
+ });
+ req.flushHeaders();
+ await once(req, 'continue');
+ await f.server().revoke(connection.id);
+ req.end(
+ JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'send', arguments: {} },
+ }),
+ );
+ expect(await response).toBe(403);
+ });
+
+ it('runs the standalone example in two unrelated Node processes using only discovery and public RPC', async () => {
+ const f = await fixture({
+ open: async (input, bridge) => {
+ let completion = Promise.resolve();
+ return {
+ id: `native-${input.isolationKey}`,
+ resumed: false,
+ async call(method, params) {
+ if (method === 'send')
+ completion = (async () => {
+ const response = await fetch(bridge.url, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${bridge.token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: {
+ name: 'client_echo',
+ arguments: { text: (params.parts as any[])[0].text },
+ },
+ }),
+ });
+ const answer = (await response.json()) as any;
+ bridge.emit({ type: 'text', data: answer.result.content[0].text });
+ bridge.emit({ type: 'turn_end', data: { status: 'completed' } });
+ })();
+ return {};
+ },
+ async close() {
+ await completion;
+ },
+ };
+ },
+ });
+ const example = fileURLToPath(
+ new URL('../../../../../../scripts/examples/local-agent-client.mjs', import.meta.url),
+ );
+ const results = await Promise.all(
+ ['notes', 'board'].map((app) =>
+ promisify(execFile)(
+ process.execPath,
+ [
+ example,
+ '--discovery',
+ f.server().discoveryFile,
+ '--cwd',
+ f.directory,
+ '--client-id',
+ `org.example.${app}`,
+ '--client-name',
+ app,
+ '--prompt',
+ `${app}-only`,
+ ],
+ { timeout: 5000 },
+ ),
+ ),
+ );
+ expect(results[0].stdout).toContain('notes-only');
+ expect(results[0].stdout).not.toContain('board-only');
+ expect(results[1].stdout).toContain('board-only');
+ expect(results[1].stdout).not.toContain('notes-only');
+ expect(f.server().connections()).toEqual([]);
+ });
+
+ it('migrates v1 grant hashes and native resume bindings without changing the credential or overwriting its backup', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ const first = (await f.start(secret)).result;
+ const file = path.join(f.directory, 'grants.json');
+ const current = JSON.parse(await fs.readFile(file, 'utf8'));
+ const original = JSON.stringify({
+ version: 1,
+ grants: current.grants.map(({ id, name, hash, scope }: any) => ({ id, name, hash, scope })),
+ bindings: current.bindings,
+ });
+ await fs.writeFile(file, original);
+ await f.restart();
+ expect((await f.start(secret, 'migrated', { resume: first.id })).result.resumed).toBe(true);
+ expect(f.open.mock.calls.at(-1)?.[0]).toMatchObject({
+ mcpName: 'hhh',
+ legacyRuntime: true,
+ resume: 'native-session',
+ });
+ const saved = JSON.parse(await fs.readFile(file, 'utf8'));
+ expect(saved.version).toBe(2);
+ expect(saved.grants[0].hash).toBe(current.grants[0].hash);
+ expect(await fs.readFile(`${file}.v1.bak`, 'utf8')).toBe(original);
+ await f.connect({ id: 'org.example.notes', name: 'Notes' });
+ expect(await fs.readFile(`${file}.v1.bak`, 'utf8')).toBe(original);
+ await f.restart();
+ expect((await f.start(secret, 'again', { resume: first.id })).result.resumed).toBe(true);
+ expect(
+ f
+ .server()
+ .connections()
+ .map((item) => item.name),
+ ).toEqual(['HHH', 'Notes']);
+ });
+
+ it('rejects invalid client identities and conflicting tool policies without granting or executing anything', async () => {
+ const f = await fixture();
+ for (const client of [
+ { id: '../other', name: 'Notes' },
+ { id: 'notes', name: '\u202eCindy' },
+ { id: 'notes', name: ' ' },
+ ]) {
+ expect((await f.rpc('connect/start', { client })).error).toBeDefined();
+ }
+ expect(f.server().connections()).toEqual([]);
+ const secret = await f.connect({ id: 'notes', name: 'Notes' });
+ expect(
+ (await f.start(secret, 'bad', { toolPolicy: 'native', access: 'none' })).error.code,
+ ).toBe('UNSUPPORTED_ACCESS');
+ expect(
+ (await f.start(secret, 'generic', { toolPolicy: 'client-only', access: undefined })).error,
+ ).toBeUndefined();
+ expect(f.open).toHaveBeenCalledTimes(1);
+ expect(f.open.mock.calls[0][0]).toMatchObject({
+ access: 'none',
+ mcpName: 'client',
+ legacyRuntime: false,
+ });
+ });
+
+ // 通用 API 契约:任意应用独立授权、相同会话/请求编号不串线,名称不是认证身份。
+ // 原覆盖只有 HHH 且会话名不同,无法发现全局 sessionId 冲突;最小输入为两个应用的 run。
+ it('authorizes unrelated clients and namespaces identical session and request IDs by grant', async () => {
+ const approve = vi.fn(async () => true);
+ const f = await fixture({ approve });
+ const alpha = await f.connect({ id: 'org.example.notes', name: 'Notes' });
+ const beta = await f.connect({ id: 'org.example.board', name: 'Board', version: '1.2' });
+ expect(approve.mock.calls.map((args: any[]) => args[1].name)).toEqual(['Notes', 'Board']);
+ expect(
+ f
+ .server()
+ .connections()
+ .map((item) => item.name),
+ ).toEqual(['Notes', 'Board']);
+ expect((await f.start(alpha)).error).toBeUndefined();
+ const alphaBridge = f.bridge();
+ expect((await f.start(beta)).error).toBeUndefined();
+ const betaBridge = f.bridge();
+ expect(betaBridge.url).not.toBe(alphaBridge.url);
+ expect(betaBridge.token).not.toBe(alphaBridge.token);
+ expect(f.open.mock.calls[0][0].isolationKey).not.toBe(f.open.mock.calls[1][0].isolationKey);
+ await f.rpc('interrupt', { sessionId: 'run' }, alpha, 'sameclient:1');
+ await f.rpc('interrupt', { sessionId: 'run' }, beta, 'sameclient:1');
+ expect(f.call).toHaveBeenCalledTimes(2);
+ alphaBridge.emit({ type: 'text', data: 'notes-private' });
+ betaBridge.emit({ type: 'text', data: 'board-private' });
+ expect(
+ (await f.rpc('events', { sessionId: 'run', cursor: 0 }, alpha)).result.events[0].event.data,
+ ).toBe('notes-private');
+ expect(
+ (await f.rpc('events', { sessionId: 'run', cursor: 0 }, beta)).result.events[0].event.data,
+ ).toBe('board-private');
+ await f.server().revokeAll();
+ expect(f.close).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects foreign controls, resume handles, MCP tokens and tool replies without changing the owner run', async () => {
+ const f = await fixture();
+ const alpha = await f.connect({ id: 'org.example.notes', name: 'Same name' });
+ const beta = await f.connect({ id: 'org.example.board', name: 'Same name' });
+ const opened = (await f.start(alpha, 'private')).result;
+ const bridge = f.bridge();
+ await f.start(beta);
+ const betaBridge = f.bridge();
+ for (const method of [
+ 'events',
+ 'send',
+ 'steer',
+ 'interrupt',
+ 'instructions',
+ 'session/close',
+ ]) {
+ expect((await f.rpc(method, { sessionId: 'private', cursor: 0 }, beta)).error.code).toBe(
+ 'SESSION_UNAVAILABLE',
+ );
+ }
+ expect((await f.start(beta, 'foreign', { resume: opened.id })).error.code).toBe(
+ 'RESUME_UNAVAILABLE',
+ );
+ const mcp = (token: string) =>
+ fetch(bridge.url, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'send', arguments: {} },
+ }),
+ });
+ expect((await mcp(betaBridge.token)).status).toBe(403);
+ const pending = mcp(bridge.token).then((response) => response.json());
+ const call = (await f.rpc('events', { sessionId: 'private', cursor: 0 }, alpha)).result
+ .events[0].event.data;
+ expect(
+ (await f.rpc('tool/reply', { sessionId: 'run', callId: call.id, text: 'foreign' }, beta))
+ .error.code,
+ ).toBe('TOOL_UNAVAILABLE');
+ await f.rpc('tool/reply', { sessionId: 'private', callId: call.id, text: 'owner' }, alpha);
+ expect(((await pending) as any).result.content[0].text).toBe('owner');
+ expect(f.call).not.toHaveBeenCalled();
+ });
+
+ it('revokes one application while another keeps its credential, tool call and durable resume binding', async () => {
+ const f = await fixture();
+ const alpha = await f.connect({ id: 'org.example.notes', name: 'Notes' });
+ const beta = await f.connect({ id: 'org.example.board', name: 'Board' });
+ const first = (await f.start(alpha)).result;
+ const alphaBridge = f.bridge();
+ const second = (await f.start(beta)).result;
+ const betaBridge = f.bridge();
+ const callTool = (bridge: typeof alphaBridge) =>
+ fetch(bridge.url, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${bridge.token}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'send', arguments: {} },
+ }),
+ }).then((response) => response.json()) as Promise<any>;
+ const alphaPending = callTool(alphaBridge),
+ betaPending = callTool(betaBridge);
+ const alphaEvents = (await f.rpc('events', { sessionId: 'run', cursor: 0 }, alpha)).result;
+ const betaEvents = (await f.rpc('events', { sessionId: 'run', cursor: 0 }, beta)).result;
+ const waiting = f.rpc('events', { sessionId: 'run', cursor: alphaEvents.cursor }, alpha);
+ const connection = f
+ .server()
+ .connections()
+ .find((item) => item.name === 'Notes')!;
+ await f.server().revoke(connection.id);
+ expect((await waiting).error).toBeDefined();
+ expect((await alphaPending).result.isError).toBe(true);
+ expect((await f.rpc('models', {}, alpha)).error.code).toBe('UNAUTHORIZED');
+ expect((await f.rpc('models', {}, beta)).result.models).toEqual([model]);
+ await f.rpc(
+ 'tool/reply',
+ { sessionId: 'run', callId: betaEvents.events[0].event.data.id, text: 'board survives' },
+ beta,
+ );
+ expect((await betaPending).result.content[0].text).toBe('board survives');
+ expect(
+ f
+ .server()
+ .connections()
+ .map((item) => item.name),
+ ).toEqual(['Board']);
+ await f.restart();
+ expect((await f.start(beta, 'restored', { resume: second.id })).result.resumed).toBe(true);
+ expect((await f.start(beta, 'stolen', { resume: first.id })).error.code).toBe(
+ 'RESUME_UNAVAILABLE',
+ );
+ });
+ it('serves a warm 500-model catalog and control framing within the local bridge budget', async () => {
+ const f = await fixture({
+ models: async () =>
+ Array.from({ length: 500 }, (_, i) => ({
+ ...model,
+ id: i === 0 ? model.id : 'route-' + i,
+ label: 'Supplier ' + i,
+ })),
+ });
+ const secret = await f.connect();
+ expect((await f.start(secret)).error).toBeUndefined();
+ const catalog: number[] = [],
+ control: number[] = [];
+ for (let i = 0; i < 20; i++) {
+ let at = performance.now();
+ const result = await f.rpc('models', {}, secret);
+ catalog.push(performance.now() - at);
+ expect(result.result.models).toHaveLength(500);
+ at = performance.now();
+ const reply = await f.rpc('interrupt', { sessionId: 'run' }, secret);
+ control.push(performance.now() - at);
+ expect(reply.error).toBeUndefined();
+ }
+ const p95 = (values: number[]) => values.sort((a, b) => a - b)[18];
+ expect(f.call).toHaveBeenCalledTimes(20);
+ expect(p95(catalog)).toBeLessThan(2000);
+ expect(p95(control)).toBeLessThan(100);
+ console.log(
+ JSON.stringify({
+ localBridgeMilliseconds: { catalog500P95: p95(catalog), controlP95: p95(control) },
+ samples: 20,
+ nativeEngine: 'scripted; framing overhead only',
+ }),
+ );
+ });
+ it('requires native consent, stores only the grant hash, and rejects browser-origin RPCs', async () => {
+ const f = await fixture();
+ expect((await f.rpc('models')).error.code).toBe('UNAUTHORIZED');
+ const secret = await f.connect();
+ expect((await f.rpc('models', {}, secret)).result.models).toEqual([model]);
+ expect(await fs.readFile(path.join(f.directory, 'grants.json'), 'utf8')).not.toContain(secret);
+ const response = await fetch(`${f.server().base}/rpc`, {
+ method: 'POST',
+ headers: { Origin: 'https://untrusted.invalid', 'Content-Type': 'application/json' },
+ body: '{}',
+ });
+ expect(response.status).toBe(403);
+ await f.server().revokeAll();
+ expect((await f.rpc('models', {}, secret)).error.code).toBe('UNAUTHORIZED');
+ });
+ it('denial and an account switch during consent never mint a usable credential', async () => {
+ const denied = await fixture({ approve: async () => false });
+ expect((await denied.pair()).response.result).toEqual({ state: 'denied' });
+ let scope = 'before';
+ const changed = await fixture({
+ scope: () => scope,
+ approve: async () => {
+ scope = 'after';
+ return true;
+ },
+ });
+ expect((await changed.pair()).response.result.token).toBeUndefined();
+ expect(changed.server().connections()).toEqual([]);
+ });
+ it('cancels the native consent when HHH abandons pairing without creating a grant', async () => {
+ let signal: AbortSignal | undefined;
+ const f = await fixture({
+ approve: async (value) => {
+ signal = value;
+ return new Promise<boolean>((resolve) =>
+ value.addEventListener('abort', () => resolve(false), { once: true }),
+ );
+ },
+ });
+ const pair = (await f.rpc('connect/start', { client: 'HHH' })).result;
+ await f.rpc('connect/cancel', { id: pair.id, claim: pair.claim });
+ expect(signal?.aborted).toBe(true);
+ expect(f.server().connections()).toEqual([]);
+ expect((await f.rpc('connect/poll', { id: pair.id, claim: pair.claim })).error).toBeDefined();
+ });
+ it('deduplicates side effects, rejects changed payloads, and bounds replay history without replaying old operations', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ await f.start(secret);
+ const id = 'replayclient:1';
+ await Promise.all([
+ f.rpc('interrupt', { sessionId: 'run' }, secret, id),
+ f.rpc('interrupt', { sessionId: 'run' }, secret, id),
+ ]);
+ expect(f.call).toHaveBeenCalledTimes(1);
+ expect((await f.rpc('send', { sessionId: 'run' }, secret, id)).error.code).toBe('ID_REUSED');
+ await f.rpc('interrupt', { sessionId: 'run' }, secret, 'replayclient:300');
+ expect((await f.rpc('interrupt', { sessionId: 'run' }, secret, id)).error.code).toBe(
+ 'REQUEST_EXPIRED',
+ );
+ expect(f.call).toHaveBeenCalledTimes(2);
+ });
+ it('round trips actual MCP calls through ordered events and resolves exactly one host answer', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ await f.start(secret);
+ const bridge = f.bridge();
+ const pending = fetch(bridge.url, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${bridge.token}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'send', arguments: { text: 'hello' } },
+ }),
+ }).then((r) => r.json());
+ const events = (await f.rpc('events', { sessionId: 'run', cursor: 0 }, secret)).result.events;
+ expect(events[0].event.type).toBe('host_tool');
+ expect(events[0].event.data.arguments).toEqual({ text: 'hello' });
+ const answer = {
+ sessionId: 'run',
+ callId: events[0].event.data.id,
+ text: 'sent',
+ isError: false,
+ };
+ expect((await f.rpc('tool/reply', { ...answer, text: 42 }, secret)).error.code).toBe(
+ 'INVALID_REQUEST',
+ );
+ expect((await f.rpc('tool/reply', answer, secret)).error).toBeUndefined();
+ expect(((await pending) as any).result).toEqual({
+ content: [{ type: 'text', text: 'sent' }],
+ isError: false,
+ });
+ expect((await f.rpc('tool/reply', answer, secret)).error.code).toBe('TOOL_UNAVAILABLE');
+ });
+ it('persists an opaque owned resume handle across desktop restarts and refuses another grant', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ const opened = (await f.start(secret)).result;
+ expect(opened.id).not.toBe('native-session');
+ await f.restart();
+ const second = await f.start(secret, 'after', { resume: opened.id });
+ expect(second.result.resumed).toBe(true);
+ expect(f.open.mock.calls.at(-1)?.[0].resume).toBe('native-session');
+ const foreign = await f.connect();
+ expect((await f.start(foreign, 'foreign', { resume: opened.id })).error.code).toBe(
+ 'RESUME_UNAVAILABLE',
+ );
+ await f.server().revokeAll();
+ expect(f.close).toHaveBeenCalledTimes(2);
+ });
+ it('starts a new model with an explicit context handoff while keeping the original model resume binding', async () => {
+ const other = { ...model, id: 'other-supplier-model' };
+ const f = await fixture({ models: async () => [model, other] });
+ const secret = await f.connect();
+ const first = (await f.start(secret)).result;
+ const changed = await f.start(secret, 'changed', { model: other.id, resume: first.id });
+ expect(changed.error).toBeUndefined();
+ expect(changed.result.resumed).toBe(false);
+ expect(changed.result.id).not.toBe(first.id);
+ expect(f.open.mock.calls.at(-1)?.[0].resume).toBeUndefined();
+ const original = await f.start(secret, 'original', { resume: first.id });
+ expect(original.result.resumed).toBe(true);
+ expect(f.open.mock.calls.at(-1)?.[0].resume).toBe('native-session');
+ });
+ it('persists a durable engine ID learned only after sending the first message', async () => {
+ let nativeId = 'pending';
+ const f = await fixture({
+ open: async () => ({
+ get id() {
+ return nativeId;
+ },
+ resumed: false,
+ call: async () => {
+ nativeId = 'durable-thread';
+ return {};
+ },
+ close: async () => {},
+ }),
+ });
+ const secret = await f.connect();
+ const opened = (await f.start(secret)).result;
+ await f.rpc('send', { sessionId: 'run', parts: [{ type: 'text', text: 'hello' }] }, secret);
+ await f.restart();
+ const resumed = await f.start(secret, 'again', { resume: opened.id });
+ expect(resumed.error).toBeUndefined();
+ const stored = JSON.parse(await fs.readFile(path.join(f.directory, 'grants.json'), 'utf8'));
+ expect(JSON.stringify(stored)).toContain('durable-thread');
+ expect(JSON.stringify(stored)).not.toContain('pending');
+ });
+ it('delivers a single large event without a cursor gap and wakes a poll on revoke', async () => {
+ const f = await fixture(),
+ secret = await f.connect();
+ await f.start(secret);
+ f.bridge().emit({ type: 'text', data: 'x'.repeat(1100 * 1024) });
+ f.bridge().emit({ type: 'text', data: 'tail' });
+ const first = (await f.rpc('events', { sessionId: 'run', cursor: 0 }, secret)).result;
+ expect(first.cursor).toBe(1);
+ expect(first.events).toHaveLength(1);
+ const second = (await f.rpc('events', { sessionId: 'run', cursor: 1 }, secret)).result;
+ expect(second.cursor).toBe(2);
+ expect(second.events[0].event.data).toBe('tail');
+ const poll = f.rpc('events', { sessionId: 'run', cursor: 2 }, secret);
+ await f.server().revokeAll();
+ expect((await poll).error).toBeDefined();
+ });
+});
diff --git a/apps/desktop/src/main/local-agent/__tests__/service.test.ts b/apps/desktop/src/main/local-agent/__tests__/service.test.ts
new file mode 100644
index 0000000000..277bcba6f5
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/__tests__/service.test.ts
@@ -0,0 +1,203 @@
+/**
+ * 测试价值:Main 原生授权和撤销必须显示申请方、只作用于选中的服务端授权。
+ * 依据:通用应用授权边界;socket 测试不经过 Electron 弹窗或设置 adapter。
+ * 最小失败输入:名称含替换元字符、两个授权只撤销其一、取消、非法或过期编号。
+ * tier: unit(注入 Electron 与服务,不读取 profile、不使用模型或网络)。
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({
+ deps: undefined as any,
+ owner: 'owner-a',
+ generation: 1,
+ startupError: undefined as Error | undefined,
+ dialog: vi.fn(async (..._args: any[]) => ({ response: 1 })),
+ revoke: vi.fn(async (_id: string) => true),
+ revokeAll: vi.fn(async () => {}),
+ close: vi.fn(async () => {}),
+ send: vi.fn(),
+ trusted: true,
+ lockHeld: true,
+}));
+vi.mock('electron', () => ({
+ app: {
+ getVersion: () => 'test',
+ getPath: () => 'unused',
+ getPreferredSystemLanguages: () => ['zh-CN'],
+ },
+ BrowserWindow: {
+ getAllWindows: () => [
+ { isDestroyed: () => false, isVisible: () => true, webContents: { send: mock.send } },
+ ],
+ },
+ dialog: { showMessageBox: mock.dialog },
+}));
+vi.mock('node:fs/promises', () => ({ default: { mkdir: async () => {} } }));
+vi.mock('../../device-link/crossProcessLock.js', () => ({
+ withCrossProcessLock: async (
+ _path: string,
+ _options: unknown,
+ task: (status: unknown) => Promise<unknown>,
+ ) => task({ held: mock.lockHeld, reason: 'busy' }),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ mode: 'local', dataOwnerId: mock.owner }),
+ activeOwnerScopeKey: () => `local:${mock.owner}:${mock.generation}`,
+ isAppSessionBoundaryPending: () => false,
+ ownerScopedUserDataPath: () => 'unused',
+}));
+vi.mock('../../security/trustedAppRenderer.js', () => ({
+ isTrustedAppRendererWindow: () => mock.trusted,
+}));
+vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
+ getDesktopProviderService: vi.fn(),
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+vi.mock('../runtime.js', () => ({ openLocalAgentRuntime: vi.fn() }));
+vi.mock('../server.js', () => ({
+ LocalAgentError: class extends Error {},
+ createLocalAgentServer: async (deps: any) => {
+ mock.deps = deps;
+ if (mock.startupError) throw mock.startupError;
+ return {
+ connections: () => [
+ { id: 'grant-a', name: 'Notes', clientId: 'notes' },
+ { id: 'grant-b', name: 'Board', clientId: 'board' },
+ ],
+ revoke: mock.revoke,
+ revokeAll: mock.revokeAll,
+ close: mock.close,
+ };
+ },
+}));
+import {
+ disposeLocalAgentHost,
+ installLocalAgentHost,
+ localAgentConnections,
+ revokeLocalAgentConnections,
+} from '../service.js';
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mock.owner = 'owner-a';
+ mock.generation = 1;
+ mock.trusted = true;
+ mock.lockHeld = true;
+ mock.startupError = undefined;
+ mock.dialog.mockResolvedValue({ response: 1 });
+ installLocalAgentHost({} as any);
+ await localAgentConnections();
+});
+afterEach(async () => {
+ await disposeLocalAgentHost();
+});
+
+describe('generic local app native authorization', () => {
+ it('shows the unverified client identity literally without expanding replacement metacharacters', async () => {
+ expect(
+ await mock.deps.approve(new AbortController().signal, {
+ id: 'org.example.notes',
+ name: 'Notes $&',
+ version: '1.2',
+ }),
+ ).toBe(true);
+ const options = mock.dialog.mock.calls[0][1];
+ expect(options.message).toContain('Notes $&');
+ expect(options.message).not.toContain('{{app}}');
+ expect(options.detail).toContain('org.example.notes');
+ expect(options.detail).toContain('工作目录不限制访问范围');
+ expect(options.detail).toContain('1.2');
+ expect(options.detail).not.toMatch(/\{\{(?:id|version)\}\}/);
+ });
+ it('revokes only the selected connection through the native confirmation', async () => {
+ expect(await revokeLocalAgentConnections('grant-b')).toBe(true);
+ expect(mock.revoke).toHaveBeenCalledWith('grant-b');
+ expect(mock.revokeAll).not.toHaveBeenCalled();
+ expect(mock.dialog.mock.calls[0][0].message).toContain('Board');
+ });
+ it('keeps connections on cancellation and does not turn invalid IDs into revoke-all', async () => {
+ mock.dialog.mockResolvedValue({ response: 0 });
+ expect(await revokeLocalAgentConnections('grant-a')).toBe(false);
+ expect(await revokeLocalAgentConnections('gone')).toBe(false);
+ await expect(revokeLocalAgentConnections({})).rejects.toThrow('INVALID_PARAMS');
+ expect(mock.revoke).not.toHaveBeenCalled();
+ expect(mock.revokeAll).not.toHaveBeenCalled();
+ });
+ it('rejects native consent if the account changed while the prompt was open', async () => {
+ mock.dialog.mockImplementationOnce(async () => {
+ mock.owner = 'owner-b';
+ return { response: 1 };
+ });
+ expect(
+ await mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' }),
+ ).toBe(false);
+ });
+ it('notifies local settings without sending app identities and suppresses notifications after account changes', () => {
+ mock.deps.changed();
+ expect(mock.send).toHaveBeenCalledWith('local-agent:connections-changed');
+ mock.owner = 'owner-b';
+ mock.deps.changed();
+ expect(mock.send).toHaveBeenCalledTimes(1);
+ });
+ // appSessionState.activeOwnerScopeKey includes generation: A→B→A cannot revive an old approval.
+ it('rejects stale consent after the same owner is recommitted', async () => {
+ mock.dialog.mockImplementationOnce(async () => {
+ mock.generation++;
+ return { response: 1 };
+ });
+ expect(
+ await mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' }),
+ ).toBe(false);
+ });
+ it('rechecks the IPC caller after native confirmation and keeps raw storage errors out of IPC', async () => {
+ const assertCaller = vi.fn();
+ mock.dialog.mockImplementationOnce(async () => {
+ assertCaller.mockImplementation(() => {
+ throw new Error('caller navigated');
+ });
+ return { response: 1 };
+ });
+ await expect(revokeLocalAgentConnections('grant-a', assertCaller)).rejects.toThrow(
+ '[INTERNAL]',
+ );
+ expect(mock.revoke).not.toHaveBeenCalled();
+ mock.revoke.mockRejectedValueOnce(new Error('PRIVATE storage path or credential'));
+ await expect(revokeLocalAgentConnections('grant-a')).rejects.toThrow('[INTERNAL]');
+ });
+ it('uses trusted app windows for native consent and local notifications', async () => {
+ mock.trusted = false;
+ expect(
+ await mock.deps.approve(new AbortController().signal, { id: 'notes', name: 'Notes' }),
+ ).toBe(false);
+ mock.deps.changed();
+ expect(mock.dialog).not.toHaveBeenCalled();
+ expect(mock.send).not.toHaveBeenCalled();
+ });
+ it('does not load another grant snapshot when a shared-profile instance already owns discovery', async () => {
+ await disposeLocalAgentHost();
+ mock.lockHeld = false;
+ mock.deps = undefined;
+ installLocalAgentHost({} as any);
+ await expect(localAgentConnections()).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(mock.deps).toBeUndefined();
+ });
+ it('waits for the previous endpoint to close before replacing Maker on the same profile', async () => {
+ const previous = mock.deps;
+ let finish!: () => void;
+ mock.close.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const stopping = disposeLocalAgentHost();
+ installLocalAgentHost({} as any);
+ const connections = localAgentConnections();
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
+ expect(mock.deps).toBe(previous);
+ finish();
+ await stopping;
+ await connections;
+ expect(mock.deps).not.toBe(previous);
+ });
+});
diff --git a/apps/desktop/src/main/local-agent/catalog.ts b/apps/desktop/src/main/local-agent/catalog.ts
new file mode 100644
index 0000000000..e6a4ed05f6
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/catalog.ts
@@ -0,0 +1,60 @@
+/** Public local-client choices. Routing configuration and credentials never cross this projection. */
+import { createHash } from 'node:crypto';
+import type { AgentKind } from '@cindy/maker-core';
+import type { ProviderView } from '@cindy/model-providers';
+import { isModelSelectableForNewRoute } from '@cindy/model-providers';
+
+export interface LocalAgentModel {
+ id: string;
+ label: string;
+ provider: string;
+ providerLabel?: string;
+ engine: AgentKind;
+ model: string;
+ efforts: string[];
+ defaultEffort?: string;
+ images: boolean;
+ isDefault: boolean;
+}
+
+/** Stable identity includes the source and engine, including same-name custom models. */
+export function localAgentModels(
+ providers: readonly ProviderView[],
+ engines: readonly AgentKind[],
+): LocalAgentModel[] {
+ const result: LocalAgentModel[] = [];
+ const seen = new Set<string>();
+ for (const provider of providers) {
+ if (!provider.connected || provider.suspended || provider.removed) continue;
+ for (const engine of provider.agents) {
+ if (
+ !engines.includes(engine) ||
+ !provider.routing[engine] ||
+ provider.routing[engine]?.disabled
+ )
+ continue;
+ for (const model of provider.models[engine] ?? []) {
+ if (!isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' }))
+ continue;
+ const id = createHash('sha256')
+ .update(JSON.stringify([provider.id, engine, model.id]))
+ .digest('hex');
+ if (seen.has(id)) continue;
+ seen.add(id);
+ result.push({
+ id,
+ label: `${provider.name} · ${model.name} · ${engine}`,
+ provider: provider.id,
+ providerLabel: provider.name,
+ engine,
+ model: model.id,
+ efforts: [...model.efforts],
+ ...(model.defaultEffort ? { defaultEffort: model.defaultEffort } : {}),
+ images: model.modalities?.input.includes('image') ?? false,
+ isDefault: result.length === 0,
+ });
+ }
+ }
+ }
+ return result;
+}
diff --git a/apps/desktop/src/main/local-agent/messages.ts b/apps/desktop/src/main/local-agent/messages.ts
new file mode 100644
index 0000000000..c6dade6408
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/messages.ts
@@ -0,0 +1,84 @@
+import { t } from '../i18n.js';
+
+/** Localize product copy at the host boundary; stable wire codes stay untranslated. */
+export function localAgentMessage(code: string): string {
+ let key: string;
+ switch (code) {
+ case 'HOST_IN_USE':
+ key = 'hostInUse';
+ break;
+ case 'UNAUTHORIZED':
+ case 'FORBIDDEN':
+ key = 'authorizationRequired';
+ break;
+ case 'PAIR_EXPIRED':
+ key = 'pairExpired';
+ break;
+ case 'BUSY':
+ case 'SESSION_STARTING':
+ key = 'busy';
+ break;
+ case 'GRANT_LIMIT':
+ case 'CLIENT_LIMIT':
+ case 'RESUME_LIMIT':
+ key = 'limitReached';
+ break;
+ case 'INVALID_WORKSPACE':
+ key = 'invalidWorkspace';
+ break;
+ case 'SESSION_EXISTS':
+ key = 'sessionExists';
+ break;
+ case 'SESSION_UNAVAILABLE':
+ case 'RESUME_UNAVAILABLE':
+ case 'TOOL_UNAVAILABLE':
+ case 'NOT_RUNNING':
+ key = 'executionUnavailable';
+ break;
+ case 'MODEL_UNAVAILABLE':
+ case 'MODEL_CHANGED':
+ case 'INVALID_EFFORT':
+ key = 'selectionUnavailable';
+ break;
+ case 'INSTANCE_CHANGED':
+ case 'ID_REUSED':
+ case 'REQUEST_EXPIRED':
+ key = 'requestNotReplayed';
+ break;
+ case 'GRANT_STORE_INVALID':
+ case 'DISCOVERY_UNAVAILABLE':
+ key = 'storageUnavailable';
+ break;
+ case 'RUNTIME_CLOSE_UNCONFIRMED':
+ key = 'stopUnconfirmed';
+ break;
+ case 'INTERACTION_UNAVAILABLE':
+ key = 'interactionUnavailable';
+ break;
+ case 'INTERRUPTED':
+ key = 'interrupted';
+ break;
+ case 'TOOL_TIMEOUT':
+ key = 'toolTimeout';
+ break;
+ case 'CONNECT_RESULT':
+ key = 'connectResult';
+ break;
+ case 'INVALID_REQUEST':
+ case 'INVALID_REQUEST_ID':
+ case 'INVALID_CLIENT':
+ case 'INVALID_INPUT':
+ case 'INVALID_IMAGE':
+ case 'INVALID_CURSOR':
+ case 'TOO_LARGE':
+ case 'UNSUPPORTED_ACCESS':
+ case 'UNSUPPORTED_COMMAND':
+ case 'METHOD_UNSUPPORTED':
+ case 'PROTOCOL_UNSUPPORTED':
+ key = 'invalidRequest';
+ break;
+ default:
+ key = 'operationFailed';
+ }
+ return t(`localAgent.${key}`);
+}
diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts
new file mode 100644
index 0000000000..61a115d088
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@ -0,0 +1,396 @@
+/** Adapt existing Maker sessions, without importing a second agent loop or transcript store. */
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import {
+ LOCAL_AGENT_CLIENT,
+ type Maker,
+ type AgentEvent,
+ type Session,
+ type StartSessionOptions,
+ type UserContentBlock,
+ type UserMessage,
+} from '@cindy/maker-core';
+import { LocalAgentError, type LocalAgentOpen, type LocalAgentRuntime } from './server.js';
+
+const object = (v: unknown): Record<string, unknown> =>
+ v && typeof v === 'object' ? (v as Record<string, unknown>) : {};
+const string = (v: unknown) => (typeof v === 'string' ? v : '');
+
+/** Final snapshots must not repeat already-streamed text/thinking. */
+export function createEventProjection(
+ emit: (event: unknown) => void,
+ mcpName = 'client',
+ message = (_code: string, fallback: string) => fallback,
+) {
+ let textSeen = false;
+ let ended = true;
+ let usageReported = false;
+ let usage = { input: 0, cached: 0, output: 0 };
+ const addUsage = (value: unknown) => {
+ if (!value || typeof value !== 'object') return;
+ const u = object(value);
+ const input = Number(u.inputTokens ?? u.promptTokens ?? u.input_tokens ?? 0);
+ const cached = Number(u.cacheReadTokens ?? u.cachedTokens ?? u.cache_read_input_tokens ?? 0);
+ const created = Number(
+ u.cacheCreateTokens ?? u.cacheCreationTokens ?? u.cache_creation_input_tokens ?? 0,
+ );
+ const output = Number(u.outputTokens ?? u.completionTokens ?? u.output_tokens ?? 0);
+ if ([input, cached, created, output].every((n) => Number.isSafeInteger(n) && n >= 0)) {
+ usage.input += input + cached + created;
+ usage.cached += cached;
+ usage.output += output;
+ }
+ };
+ const addEventUsage = (data: Record<string, unknown>) => {
+ // Claude's raw result usage can be cumulative over several turns. Its
+ // translated request segments are already deltas and include cache writes.
+ if (Array.isArray(data.usageSegments)) {
+ for (const segment of data.usageSegments) addUsage(segment);
+ } else addUsage(data.usage);
+ };
+ const reportUsage = () => {
+ if (!usageReported) {
+ usageReported = true;
+ emit({ type: 'usage', data: { ...usage } });
+ }
+ };
+ const ignoredTools = new Set<string>();
+ return {
+ begin() {
+ textSeen = false;
+ ended = false;
+ usageReported = false;
+ usage = { input: 0, cached: 0, output: 0 };
+ ignoredTools.clear();
+ },
+ accept(event: AgentEvent, terminal = true) {
+ const d = object(event.data);
+ // The normal Session owns stale-tail and continuation attribution. Background child
+ // events cannot settle this product turn or become the application's final answer.
+ if (event.turnScope === 'background' || event.agentMeta?.parentUuid) return;
+ if (ended) {
+ if (event.type === 'done' && !usageReported && d.usage) {
+ addEventUsage(d);
+ reportUsage();
+ }
+ return;
+ }
+ if (event.type === 'text') {
+ if (d.isFinal !== true && string(d.text)) {
+ textSeen = true;
+ emit({ type: 'text', data: d.text });
+ }
+ } else if (event.type === 'thinking') {
+ if (d.stage !== 'final' && string(d.text)) emit({ type: 'thinking', data: d.text });
+ } else if (event.type === 'tool_use') {
+ const name = string(d.toolName ?? d.name),
+ id = string(d.toolUseId ?? d.id);
+ if (
+ name.startsWith(`mcp__${mcpName}__`) ||
+ name.startsWith(`mcp:${mcpName}:`) ||
+ ['cindy_mcp_call_tool', 'cindy_mcp_list_tools'].includes(name)
+ )
+ ignoredTools.add(id);
+ else if (id) emit({ type: 'tool_started', data: { id, name, arguments: d.input ?? {} } });
+ } else if (event.type === 'tool_result_full') {
+ const id = string(d.toolUseId ?? d.id);
+ if (id && !ignoredTools.has(id))
+ emit({
+ type: 'tool_finished',
+ data: { id, output: string(d.fullText ?? d.text), isError: d.isError === true },
+ });
+ } else if (
+ event.type === 'error' &&
+ (typeof d.isTerminal === 'boolean' ? d.isTerminal : d.willRetry !== true) &&
+ !ended
+ ) {
+ if (d.usage) {
+ addEventUsage(d);
+ reportUsage();
+ }
+ ended = true;
+ emit({
+ type: 'turn_end',
+ data: {
+ status: 'failed',
+ message: string(d.message) || message('EXECUTION_FAILED', 'Cindy 执行未完成。'),
+ },
+ });
+ } else if (event.type === 'done' && !ended) {
+ if (!textSeen && string(d.result)) emit({ type: 'text', data: d.result });
+ addEventUsage(d);
+ if (!terminal) {
+ textSeen = false;
+ return;
+ }
+ reportUsage();
+ ended = true;
+ emit({
+ type: 'turn_end',
+ data: {
+ status: ['cancelled', 'aborted', 'interrupted'].includes(string(d.status))
+ ? 'interrupted'
+ : d.is_error === true || d.status === 'error' || d.status === 'failed'
+ ? 'failed'
+ : 'completed',
+ message: string(d.error),
+ },
+ });
+ }
+ },
+ fail(message: string) {
+ if (!ended) {
+ ended = true;
+ emit({ type: 'turn_end', data: { status: 'failed', message } });
+ }
+ },
+ };
+}
+
+export async function openLocalAgentRuntime(
+ maker: Pick<Maker, 'startLocalAgentSession'>,
+ directory: string,
+ input: LocalAgentOpen,
+ bridge: { url: string; token: string; emit(event: unknown): void },
+ localize = (_code: string, fallback: string) => fallback,
+): Promise<LocalAgentRuntime> {
+ let instructions = input.instructions;
+ const sessionId = `local-agent-${randomUUID()}`;
+ let handle: Session;
+ let closed = false,
+ busy = false,
+ preparing = false,
+ dirtyInstructions = false,
+ resumed = false;
+ let epoch = 0;
+ const assertCurrent = (expected: number) => {
+ if (closed) throw new LocalAgentError('SESSION_UNAVAILABLE', 'Cindy 会话已关闭。');
+ if (epoch !== expected)
+ throw new LocalAgentError('INTERRUPTED', '本次发送已停止,未继续提交消息。');
+ };
+ const applicationDirectory = path.join(directory, 'clients', input.isolationKey);
+ await fs.mkdir(applicationDirectory, { recursive: true, mode: 0o700 });
+ const temporary = await fs.mkdtemp(path.join(applicationDirectory, 'input-'));
+ const projection = createEventProjection(bridge.emit, input.mcpName, localize);
+ const start = async (resume?: string, expected = epoch) => {
+ assertCurrent(expected);
+ const opts: StartSessionOptions = {
+ sessionId,
+ workingDir: input.cwd,
+ providerId: input.model.provider,
+ model: input.model.model,
+ effort: input.effort as StartSessionOptions['effort'],
+ userPrompt: instructions,
+ makerMemoryEnabled: false,
+ permissionMode: 'bypassPermissions',
+ resumeSessionId: resume,
+ [LOCAL_AGENT_CLIENT]: {
+ url: bridge.url,
+ token: bridge.token,
+ hostToolsOnly: input.access === 'none',
+ mcpName: input.mcpName,
+ ...(input.legacyRuntime
+ ? {}
+ : { storageDirectory: path.join(applicationDirectory, input.model.engine) }),
+ },
+ onInvalidResumeSession: async () => {
+ resumed = false;
+ return false;
+ },
+ };
+ resumed = Boolean(resume);
+ const next = await maker.startLocalAgentSession(input.model.engine, opts);
+ try {
+ assertCurrent(expected);
+ } catch (error) {
+ await next.close({ reason: 'account-boundary' });
+ throw error;
+ }
+ if (resume && !resumed) {
+ await next.close();
+ throw new LocalAgentError(
+ 'RESUME_UNAVAILABLE',
+ 'Cindy 原会话已不存在,请在调用应用中开始新的任务。未重放旧消息。',
+ );
+ }
+ handle = next;
+ next.setInteractionListener(async (request) => {
+ if (request.kind === 'permission') {
+ const hostTool = input.tools.some((tool) =>
+ [`mcp__${input.mcpName}__${tool.name}`, `mcp:${input.mcpName}:${tool.name}`].includes(
+ request.toolName,
+ ),
+ );
+ return {
+ kind: 'permission',
+ behavior: input.access === 'full' || hostTool ? 'allow' : 'deny',
+ reason: 'The authorized client controls this session tool surface.',
+ };
+ }
+ // Native interactive prompts cannot be answered on behalf of the user.
+ projection.fail(
+ localize('INTERACTION_UNAVAILABLE', 'Cindy 引擎需要交互确认,当前应用无法接收。'),
+ );
+ if (request.kind === 'ask_user_question')
+ return { kind: 'ask_user_question', answers: {}, dismissed: true };
+ return {
+ kind: 'plan_review',
+ behavior: 'deny',
+ dismissed: true,
+ reason: 'host_interaction_unavailable',
+ };
+ });
+ const unsubscribe = next.onEvent((event) => {
+ if (handle !== next || closed) return;
+ const claimed =
+ event.type === 'done' && next.beginTurnContinuationWait(event.turnContinuationId) !== null;
+ projection.accept(event, !claimed);
+ if (!preparing && !claimed && next.getObservedCurrentTurnTerminal().kind !== 'none')
+ busy = false;
+ });
+ next.onStatusChange((status) => {
+ if (status === 'closed') unsubscribe();
+ if (!closed && handle === next && !preparing && (status === 'closed' || status === 'error')) {
+ busy = false;
+ projection.fail(localize('SESSION_UNAVAILABLE', 'Cindy 执行连接已结束。'));
+ }
+ });
+ return next;
+ };
+ try {
+ handle = await start(input.resume);
+ } catch (error) {
+ await fs.rm(temporary, { recursive: true, force: true });
+ throw error;
+ }
+ const message = async (params: Record<string, unknown>): Promise<UserMessage> => {
+ if (!Array.isArray(params.parts) || !params.parts.length || params.parts.length > 64)
+ throw new LocalAgentError('INVALID_INPUT', '消息内容无效。');
+ const blocks: UserContentBlock[] = [];
+ for (const raw of params.parts) {
+ const part = object(raw);
+ if (part.type === 'text' && typeof part.text === 'string') {
+ // A tool policy is not an input blacklist: paths and slash-prefixed text
+ // remain usable. Escape the CLI command prefix only for client-only calls.
+ blocks.push({
+ type: 'text',
+ text: input.access === 'none' && part.text.startsWith('/') ? ` ${part.text}` : part.text,
+ });
+ } else if (
+ part.type === 'image' &&
+ input.model.images &&
+ typeof part.data === 'string' &&
+ ['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(string(part.mimeType))
+ ) {
+ const bytes = Buffer.from(part.data, 'base64');
+ if (!bytes.length || bytes.length > 10 * 1024 * 1024)
+ throw new LocalAgentError('INVALID_IMAGE', '图片超过接入限制。');
+ const file = path.join(
+ temporary,
+ randomUUID() +
+ ({
+ 'image/png': '.png',
+ 'image/jpeg': '.jpg',
+ 'image/webp': '.webp',
+ 'image/gif': '.gif',
+ }[string(part.mimeType)] ?? ''),
+ );
+ await fs.writeFile(file, bytes, { mode: 0o600 });
+ blocks.push({
+ type: 'image',
+ path: file,
+ mimeType: string(part.mimeType),
+ pathOrigin: 'desktop-host',
+ });
+ } else throw new LocalAgentError('INVALID_INPUT', '所选 Cindy 模型不支持这类输入。');
+ }
+ return { type: 'user', content: blocks };
+ };
+ return {
+ get id() {
+ return handle.sdkSessionId;
+ },
+ get resumed() {
+ return resumed;
+ },
+ async call(method, params) {
+ if (closed) throw new LocalAgentError('SESSION_UNAVAILABLE', 'Cindy 会话已关闭。');
+ if (method === 'interrupt') {
+ const interrupted = ++epoch;
+ busy = true;
+ try {
+ await handle.abort();
+ } finally {
+ if (epoch === interrupted) {
+ busy = false;
+ preparing = false;
+ }
+ }
+ return {};
+ }
+ if (method === 'instructions') {
+ instructions = typeof params.instructions === 'string' ? params.instructions : undefined;
+ dirtyInstructions = true;
+ return {};
+ }
+ if (method !== 'send' && method !== 'steer')
+ throw new LocalAgentError('METHOD_UNSUPPORTED', '不支持此会话操作。');
+ if (params.model !== undefined && params.model !== input.model.id)
+ throw new LocalAgentError('MODEL_CHANGED', '模型已更改,请在新会话边界重新连接。');
+ if (params.effort !== undefined && !input.model.efforts.includes(string(params.effort)))
+ throw new LocalAgentError('INVALID_EFFORT', '思考力度不可用。');
+ if (method === 'steer') {
+ const current = epoch;
+ if (!busy || preparing)
+ throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');
+ const content = await message(params);
+ assertCurrent(current);
+ if (!busy) throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');
+ await handle.steer(content);
+ return {};
+ }
+ if (busy) throw new LocalAgentError('BUSY', '当前回答尚未结束。');
+ const current = ++epoch;
+ busy = true;
+ preparing = true;
+ try {
+ const content = await message(params);
+ assertCurrent(current);
+ if (dirtyInstructions) {
+ const previous = handle;
+ await previous.close();
+ assertCurrent(current);
+ handle = await start(previous.sdkSessionId, current);
+ dirtyInstructions = false;
+ }
+ if (params.effort !== undefined)
+ await handle.setEffort(params.effort as Parameters<Session['setEffort']>[0]);
+ assertCurrent(current);
+ preparing = false;
+ projection.begin();
+ // Some harnesses await the entire turn; acceptance must not block tool delivery/control RPCs.
+ void handle.send(content).catch(() => {
+ if (!closed && epoch === current) {
+ busy = false;
+ projection.fail(localize('EXECUTION_FAILED', 'Cindy 未能完成本次发送。'));
+ }
+ });
+ return {};
+ } catch (error) {
+ if (epoch === current) {
+ busy = false;
+ preparing = false;
+ }
+ throw error;
+ }
+ },
+ async close() {
+ closed = true;
+ ++epoch;
+ busy = false;
+ await handle.close({ reason: 'account-boundary' });
+ await fs.rm(temporary, { recursive: true, force: true });
+ },
+ };
+}
diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.ts
new file mode 100644
index 0000000000..63a7bab7ac
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/server.ts
@@ -0,0 +1,881 @@
+/**
+ * Same-computer Agent API v1. User consent grants this API its own credential;
+ * supplier credentials remain behind the existing desktop Host boundary.
+ * The transport is injectable so authorization/lifecycle tests never read a real profile.
+ */
+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import type { LocalAgentModel } from './catalog.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+
+const MAX_BODY = 16 * 1024 * 1024;
+const MAX_EVENTS = 8 * 1024 * 1024;
+const MAX_RUNS = 16;
+const PAIR_TTL = 120_000;
+const RUN_IDLE = 3 * 60_000;
+const token = () => randomBytes(32).toString('base64url');
+const hash = (value: string) => createHash('sha256').update(value).digest('hex');
+const equal = (a: string, b: string) =>
+ a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
+
+export class LocalAgentError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+export interface LocalAgentOpen {
+ /** Server-issued grant identity; never taken from session/open parameters. */
+ isolationKey: string;
+ mcpName: string;
+ legacyRuntime: boolean;
+ cwd: string;
+ model: LocalAgentModel;
+ effort?: string;
+ instructions?: string;
+ access: 'none' | 'full';
+ resume?: string;
+ tools: Array<{ name: string; description: string; parameters: Record<string, unknown> }>;
+}
+export interface LocalAgentRuntime {
+ id: string;
+ resumed: boolean;
+ call(method: string, params: Record<string, unknown>): Promise<unknown>;
+ close(): Promise<void>;
+}
+export interface LocalAgentClientIdentity {
+ id: string;
+ name: string;
+ version?: string;
+}
+interface Grant {
+ id: string;
+ name: string;
+ hash: string;
+ scope: string;
+ client: LocalAgentClientIdentity;
+ legacyRuntime: boolean;
+}
+interface Pair {
+ id: string;
+ claim: string;
+ client: LocalAgentClientIdentity;
+ scope: string;
+ expires: number;
+ state: 'waiting' | 'approved' | 'denied';
+ secret?: string;
+ grant?: Grant;
+ approval?: Promise<void>;
+ consent?: AbortController;
+}
+interface Run {
+ owner: string;
+ runtime?: LocalAgentRuntime;
+ touched: number;
+ seq: number;
+ events: Array<{ seq: number; event: unknown; bytes: number }>;
+ bytes: number;
+ waiters: Set<() => void>;
+ closed: boolean;
+ tools: LocalAgentOpen['tools'];
+ mcpToken: string;
+ pending: Map<string, { resolve: (value: unknown) => void; timer: ReturnType<typeof setTimeout> }>;
+ resumeKey?: string;
+ closing?: Promise<void>;
+}
+export interface LocalAgentServerDeps {
+ directory: string;
+ discoveryDirectory?: string;
+ version: string;
+ scope(): string;
+ models(): Promise<LocalAgentModel[]>;
+ approve(signal: AbortSignal, client: LocalAgentClientIdentity): Promise<boolean>;
+ open(
+ input: LocalAgentOpen,
+ bridge: { url: string; token: string; emit(event: unknown): void },
+ ): Promise<LocalAgentRuntime>;
+ warn(code: string): void;
+ changed?(): void;
+ /** Product copy is supplied by the host's current locale; protocol tests remain host-free. */
+ message?(code: string, fallback: string): string;
+}
+function record(value: unknown): Record<string, unknown> {
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
+ throw new LocalAgentError('INVALID_REQUEST', '请求格式不正确。');
+ return value as Record<string, unknown>;
+}
+function text(value: unknown, max = 1024, optional = false): string {
+ if (optional && value === undefined) return '';
+ if (typeof value !== 'string' || (!optional && !value.length) || value.length > max)
+ throw new LocalAgentError('INVALID_REQUEST', '请求字段无效或过长。');
+ return value;
+}
+function displayText(value: unknown, max: number): string {
+ const result = text(value, max).trim();
+ if (!result || /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(result)) {
+ throw new LocalAgentError('INVALID_CLIENT', '应用名称或版本无效。');
+ }
+ return result;
+}
+function clientIdentity(value: unknown): LocalAgentClientIdentity {
+ // v1 accepted a display-name string. Keep that wire shape for any local client.
+ if (typeof value === 'string') {
+ const name = displayText(value, 80);
+ return { id: `legacy.${hash(name)}`, name };
+ }
+ const client = record(value),
+ id = text(client.id, 128);
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(id))
+ throw new LocalAgentError('INVALID_CLIENT', '应用编号无效。');
+ return {
+ id,
+ name: displayText(client.name, 80),
+ ...(client.version !== undefined ? { version: displayText(client.version, 64) } : {}),
+ };
+}
+async function body(req: IncomingMessage): Promise<Record<string, unknown>> {
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ for await (const chunk of req) {
+ bytes += chunk.length;
+ if (bytes > MAX_BODY) throw new LocalAgentError('TOO_LARGE', '请求超过本机接入上限。');
+ chunks.push(Buffer.from(chunk));
+ }
+ try {
+ return record(JSON.parse(Buffer.concat(chunks).toString('utf8')));
+ } catch (error) {
+ if (error instanceof LocalAgentError) throw error;
+ throw new LocalAgentError('INVALID_REQUEST', '请求不是有效 JSON。');
+ }
+}
+function json(res: ServerResponse, status: number, value: unknown): void {
+ if (res.destroyed || res.writableEnded) return;
+ res.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Cache-Control': 'no-store',
+ 'X-Content-Type-Options': 'nosniff',
+ });
+ res.end(JSON.stringify(value));
+}
+
+export async function createLocalAgentServer(deps: LocalAgentServerDeps) {
+ const message = (code: string, fallback: string) => deps.message?.(code, fallback) ?? fallback;
+ await fs.mkdir(deps.directory, { recursive: true, mode: 0o700 });
+ const grantFile = path.join(deps.directory, 'grants.json');
+ let grants: Grant[] = [];
+ let legacyStore: string | undefined;
+ let bindings: Record<string, { owner: string; model: string; native: string }> = {};
+ try {
+ const stat = await fs.stat(grantFile).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ return fs.stat(`${grantFile}.bak`);
+ });
+ if (stat.size > 20 * 1024 * 1024) throw new Error('oversize');
+ const original = readAtomicFileSync(grantFile);
+ if (original === null)
+ throw new LocalAgentError('GRANT_STORE_INVALID', '本机应用授权记录无法读取。');
+ const saved = record(JSON.parse(original));
+ if (
+ ![1, 2].includes(saved.version as number) ||
+ !Array.isArray(saved.grants) ||
+ saved.grants.length > 32
+ )
+ throw new Error('schema');
+ const ids = new Set<string>();
+ grants = saved.grants.map((entry) => {
+ const g = record(entry),
+ id = text(g.id, 128),
+ digest = text(g.hash, 64);
+ if (ids.has(id) || !/^[a-f0-9]{64}$/.test(digest)) throw new Error('grant');
+ ids.add(id);
+ const client = clientIdentity(saved.version === 1 ? g.name : g.client);
+ return {
+ id,
+ name: client.name,
+ hash: digest,
+ scope: text(g.scope),
+ client,
+ legacyRuntime: saved.version === 1 || g.legacyRuntime === true,
+ };
+ });
+ if (saved.bindings !== undefined) {
+ const entries = Object.entries(record(saved.bindings));
+ if (entries.length > 4096) throw new Error('bindings');
+ bindings = Object.fromEntries(
+ entries.map(([id, value]) => {
+ const b = record(value);
+ return [
+ text(id, 128),
+ { owner: text(b.owner), model: text(b.model), native: text(b.native, 4096) },
+ ];
+ }),
+ );
+ }
+ if (saved.version === 1) legacyStore = original;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
+ throw new LocalAgentError('GRANT_STORE_INVALID', '本机应用授权记录无法读取,原文件已保留。');
+ }
+ let persistence = Promise.resolve();
+ const persist = () => {
+ const value = JSON.stringify({ version: 2, grants, bindings });
+ const write = async () => {
+ if (legacyStore !== undefined) {
+ try {
+ await fs.writeFile(`${grantFile}.v1.bak`, legacyStore, { mode: 0o600, flag: 'wx' });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
+ }
+ }
+ atomicWriteFileSync(grantFile, value);
+ legacyStore = undefined;
+ };
+ const result = persistence.then(write, write);
+ persistence = result.catch(() => {});
+ return result;
+ };
+ const pairs = new Map<string, Pair>();
+ const runs = new Map<string, Run>();
+ const dedup = new Map<string, { fingerprint: string; result: Promise<unknown> }>();
+ const clients = new Map<string, number>();
+ let base = '';
+ let closing = false;
+ const closeRun = async (id: string, expected?: Run) => {
+ const run = runs.get(id);
+ if (!run || (expected && expected !== run)) return;
+ if (run.closing) return run.closing;
+ run.closed = true;
+ for (const pending of run.pending.values()) {
+ clearTimeout(pending.timer);
+ pending.resolve({
+ content: [{ type: 'text', text: message('SESSION_UNAVAILABLE', '执行已关闭。') }],
+ isError: true,
+ });
+ }
+ run.pending.clear();
+ for (const wake of run.waiters) wake();
+ run.closing = (async () => {
+ try {
+ await run.runtime?.close();
+ } catch {
+ deps.warn('RUNTIME_CLOSE_UNCONFIRMED');
+ throw new LocalAgentError(
+ 'RUNTIME_CLOSE_UNCONFIRMED',
+ '连接已失效,但尚未确认执行进程停止。',
+ );
+ }
+ if (runs.get(id) === run) runs.delete(id);
+ })();
+ try {
+ await run.closing;
+ } finally {
+ run.closing = undefined;
+ }
+ };
+ const syncBinding = async (run: Run) => {
+ const binding = run.resumeKey && bindings[run.resumeKey];
+ if (binding && run.runtime && binding.native !== run.runtime.id) {
+ binding.native = run.runtime.id;
+ await persist();
+ }
+ };
+ const emit = (id: string, event: unknown) => {
+ const run = runs.get(id);
+ if (!run || run.closed) return;
+ const bytes = Buffer.byteLength(JSON.stringify(event));
+ if (bytes > MAX_BODY || run.bytes + bytes > MAX_EVENTS) {
+ deps.warn('EVENT_BACKPRESSURE');
+ void closeRun(id).catch(() => {});
+ return;
+ }
+ run.events.push({ seq: ++run.seq, event, bytes });
+ run.bytes += bytes;
+ // Claude/Codex can learn the durable native ID only after the first send.
+ if (event && typeof event === 'object' && (event as { type?: unknown }).type === 'turn_end')
+ void syncBinding(run).catch(() => deps.warn('RESUME_PERSIST_FAILED'));
+ for (const wake of run.waiters) wake();
+ };
+ const requireRun = (id: string, owner: string) => {
+ const run = runs.get(id);
+ if (!run || run.owner !== owner || run.closed)
+ throw new LocalAgentError(
+ 'SESSION_UNAVAILABLE',
+ 'Cindy 会话已关闭,请重新发送消息以接续会话。',
+ );
+ run.touched = Date.now();
+ return run;
+ };
+ const authorize = (req: IncomingMessage) => {
+ const authorization = req.headers.authorization;
+ if (!authorization?.startsWith('Bearer '))
+ throw new LocalAgentError('UNAUTHORIZED', '请先在 Cindy 中允许连接。');
+ const digest = hash(authorization.slice(7));
+ const grant = grants.find((g) => g.scope === deps.scope() && equal(g.hash, digest));
+ if (!grant) throw new LocalAgentError('UNAUTHORIZED', 'Cindy 连接授权已失效,请重新连接。');
+ return grant;
+ };
+ const assertGrant = (grant: Grant) => {
+ if (closing || !grants.includes(grant) || grant.scope !== deps.scope())
+ throw new LocalAgentError('UNAUTHORIZED', '连接授权已撤销或账号已更改。');
+ };
+ const runKey = (grant: Grant, id: string) => hash(JSON.stringify([grant.id, id]));
+ const revoke = async (id: string) => {
+ const found = grants.some((grant) => grant.id === id && grant.scope === deps.scope());
+ if (!found) return false;
+ // Remove authority before awaiting disk or runtime cleanup. Other grants stay live.
+ grants = grants.filter((grant) => grant.id !== id);
+ bindings = Object.fromEntries(
+ Object.entries(bindings).filter(([, binding]) => binding.owner !== id),
+ );
+ for (const [key, pair] of pairs)
+ if (pair.grant?.id === id) {
+ pair.consent?.abort();
+ pairs.delete(key);
+ }
+ for (const key of dedup.keys()) if (key.startsWith(`${id}:`)) dedup.delete(key);
+ for (const key of clients.keys()) if (key.startsWith(`${id}:`)) clients.delete(key);
+ const stopped = Promise.all(
+ [...runs].filter(([, run]) => run.owner === id).map(([key]) => closeRun(key)),
+ );
+ try {
+ await Promise.all([persist(), stopped]);
+ } finally {
+ deps.changed?.();
+ }
+ return true;
+ };
+ const operation = async (
+ method: string,
+ p: Record<string, unknown>,
+ grant: Grant,
+ ): Promise<unknown> => {
+ assertGrant(grant);
+ if (method === 'models') {
+ const models = await deps.models();
+ assertGrant(grant);
+ return { models };
+ }
+ if (method === 'connect/revoke') {
+ await revoke(grant.id);
+ return {};
+ }
+ if (method === 'session/open') {
+ if (runs.size >= MAX_RUNS)
+ throw new LocalAgentError('BUSY', 'Cindy 本机接入的会话已满,请先结束不再使用的会话。');
+ const sessionId = text(p.sessionId, 128),
+ id = runKey(grant, sessionId);
+ if (runs.has(id)) throw new LocalAgentError('SESSION_EXISTS', '会话编号已被使用。');
+ const models = await deps.models();
+ const model = models.find((m) => m.id === p.model);
+ if (!model)
+ throw new LocalAgentError(
+ 'MODEL_UNAVAILABLE',
+ '所选模型或供应商已不可用,请在 Cindy 中检查后重新选择。',
+ );
+ const cwd = text(p.cwd, 32768);
+ if (!path.isAbsolute(cwd) || !(await fs.stat(cwd)).isDirectory())
+ throw new LocalAgentError('INVALID_WORKSPACE', '工作目录不存在或不是绝对路径。');
+ const effort = text(p.effort, 64, true) || undefined;
+ if (effort && !model.efforts.includes(effort))
+ throw new LocalAgentError('INVALID_EFFORT', '所选模型不支持这个思考力度。');
+ const access =
+ p.toolPolicy === 'client-only' ? 'none' : p.toolPolicy === 'native' ? 'full' : p.access;
+ if (
+ (p.toolPolicy !== undefined &&
+ !['client-only', 'native'].includes(p.toolPolicy as string)) ||
+ (access !== 'none' && access !== 'full') ||
+ (p.access !== undefined && p.access !== access)
+ ) {
+ throw new LocalAgentError('UNSUPPORTED_ACCESS', '工具策略无效;此接口不声明原生只读保证。');
+ }
+ if (!Array.isArray(p.tools) || p.tools.length > 256)
+ throw new LocalAgentError('INVALID_REQUEST', '宿主工具清单无效。');
+ const names = new Set<string>();
+ const tools = p.tools.map((raw) => {
+ const t = record(raw),
+ name = text(t.name, 64);
+ if (!/^[a-zA-Z0-9_-]+$/.test(name) || names.has(name))
+ throw new LocalAgentError('INVALID_REQUEST', '宿主工具名称无效或重复。');
+ names.add(name);
+ return {
+ name,
+ description: text(t.description, 32768, true),
+ parameters: record(t.parameters),
+ };
+ });
+ const resumeKey = text(p.resume, 128, true) || undefined;
+ const previous = resumeKey ? bindings[resumeKey] : undefined;
+ if (resumeKey && (!previous || previous.owner !== grant.id))
+ throw new LocalAgentError(
+ 'RESUME_UNAVAILABLE',
+ '原 Cindy 会话无法在此授权下恢复,未重新执行消息。',
+ );
+ // A deliberate model/source change starts a fresh engine session. The client sees
+ // resumed:false and supplies its existing context handoff, without replaying
+ // any old tool call or resuming a supplier's thread with another model.
+ const binding = previous?.model === model.id ? previous : undefined;
+ if (Object.keys(bindings).length >= 4096 && !binding)
+ throw new LocalAgentError(
+ 'RESUME_LIMIT',
+ '本机接入的恢复记录已满,请在 Cindy 中撤销连接后重新连接。',
+ );
+ assertGrant(grant);
+ if (runs.has(id)) throw new LocalAgentError('SESSION_EXISTS', '会话编号已被此连接使用。');
+ if (runs.size >= MAX_RUNS) throw new LocalAgentError('BUSY', 'Cindy 本机接入的会话已满。');
+ const run: Run = {
+ owner: grant.id,
+ touched: Date.now(),
+ seq: 0,
+ events: [],
+ bytes: 0,
+ waiters: new Set(),
+ closed: false,
+ tools,
+ mcpToken: token(),
+ pending: new Map(),
+ };
+ runs.set(id, run);
+ try {
+ run.runtime = await deps.open(
+ {
+ isolationKey: hash(grant.id),
+ mcpName: grant.legacyRuntime ? 'hhh' : 'client',
+ legacyRuntime: grant.legacyRuntime,
+ cwd,
+ model,
+ effort,
+ instructions: text(p.instructions, 1024 * 1024, true),
+ access,
+ resume: binding?.native,
+ tools,
+ },
+ {
+ url: `${base}/mcp/${id}`,
+ token: run.mcpToken,
+ emit: (event) => {
+ if (runs.get(id) === run) emit(id, event);
+ },
+ },
+ );
+ if (run.closed || !grants.includes(grant) || grant.scope !== deps.scope()) {
+ await run.runtime.close();
+ throw new LocalAgentError('UNAUTHORIZED', '连接已失效。');
+ }
+ // Another open may have used the last slot while this engine started.
+ if (!binding && Object.keys(bindings).length >= 4096)
+ throw new LocalAgentError(
+ 'RESUME_LIMIT',
+ '本机接入的恢复记录已满,请在 Cindy 中撤销连接后重新连接。',
+ );
+ run.resumeKey = binding && resumeKey ? resumeKey : token();
+ bindings[run.resumeKey] = { owner: grant.id, model: model.id, native: run.runtime.id };
+ await persist();
+ assertGrant(grant);
+ return { id: run.resumeKey, resumed: run.runtime.resumed, sessionId };
+ } catch (error) {
+ await closeRun(id, run);
+ throw error;
+ }
+ }
+ const id = runKey(grant, text(p.sessionId, 128));
+ const run = requireRun(id, grant.id);
+ if (method === 'events') {
+ const cursor = p.cursor;
+ if (!Number.isSafeInteger(cursor) || (cursor as number) < 0 || (cursor as number) > run.seq)
+ throw new LocalAgentError('INVALID_CURSOR', '事件游标无效。');
+ // Acknowledgement allows reclamation; a lost poll response is replayable from its old cursor.
+ while (run.events[0] && run.events[0].seq <= (cursor as number))
+ run.bytes -= run.events.shift()!.bytes;
+ if (!run.events.length && !run.closed)
+ await new Promise<void>((resolve) => {
+ const done = () => {
+ clearTimeout(timer);
+ run.waiters.delete(done);
+ resolve();
+ };
+ const timer = setTimeout(done, 20_000);
+ run.waiters.add(done);
+ });
+ if (run.closed || requireRun(id, grant.id) !== run)
+ throw new LocalAgentError('SESSION_UNAVAILABLE', '原会话已关闭。');
+ if (!grants.includes(grant) || grant.scope !== deps.scope())
+ throw new LocalAgentError('UNAUTHORIZED', '连接授权已撤销。');
+ let bytes = 0;
+ const events: Array<{ seq: number; event: unknown }> = [];
+ for (const entry of run.events) {
+ if (entry.seq <= (cursor as number)) continue;
+ if (bytes && bytes + entry.bytes > 1024 * 1024) break;
+ bytes += entry.bytes;
+ events.push({ seq: entry.seq, event: entry.event });
+ }
+ return { events, cursor: events.at(-1)?.seq ?? cursor };
+ }
+ if (method === 'session/close') {
+ await closeRun(id);
+ return {};
+ }
+ if (method === 'tool/reply') {
+ const callId = text(p.callId, 128);
+ const pending = run.pending.get(callId);
+ if (!pending)
+ throw new LocalAgentError('TOOL_UNAVAILABLE', '该工具请求已结束,结果没有重复执行。');
+ const reply = {
+ content: [{ type: 'text', text: text(p.text, 4 * 1024 * 1024, true) }],
+ isError: p.isError === true,
+ };
+ run.pending.delete(callId);
+ clearTimeout(pending.timer);
+ pending.resolve(reply);
+ return {};
+ }
+ if (!['send', 'steer', 'interrupt', 'instructions'].includes(method))
+ throw new LocalAgentError('METHOD_UNSUPPORTED', '此 Cindy 版本不支持该会话操作。');
+ if (!run.runtime) throw new LocalAgentError('SESSION_STARTING', 'Cindy 会话还在启动。');
+ const result = await run.runtime.call(method, p);
+ await syncBinding(run);
+ return result;
+ };
+ const approvePair = (pair: Pair): Promise<void> => {
+ if (pair.approval) return pair.approval;
+ pair.consent = new AbortController();
+ pair.approval = (async () => {
+ const approved = await deps.approve(pair.consent!.signal, pair.client);
+ if (
+ closing ||
+ pairs.get(pair.id) !== pair ||
+ pair.expires < Date.now() ||
+ pair.scope !== deps.scope()
+ )
+ throw new LocalAgentError('PAIR_EXPIRED', '连接申请已过期或当前账号已更改。');
+ if (approved) {
+ const secret = token();
+ const grant: Grant = {
+ id: token(),
+ name: pair.client.name,
+ client: pair.client,
+ legacyRuntime: false,
+ hash: hash(secret),
+ scope: pair.scope,
+ };
+ if (grants.length >= 32)
+ throw new LocalAgentError('GRANT_LIMIT', '本机应用授权已满,请先撤销不用的连接。');
+ grants.push(grant);
+ try {
+ await persist();
+ if (pairs.get(pair.id) !== pair || pair.scope !== deps.scope()) {
+ grants = grants.filter((g) => g !== grant);
+ await persist();
+ throw new LocalAgentError('PAIR_EXPIRED', '连接申请已取消。');
+ }
+ } catch (error) {
+ grants = grants.filter((g) => g !== grant);
+ throw error;
+ }
+ pair.secret = secret;
+ pair.grant = grant;
+ pair.state = 'approved';
+ deps.changed?.();
+ } else pair.state = 'denied';
+ })();
+ return pair.approval;
+ };
+ const server = createServer(async (req, res) => {
+ try {
+ if (closing) throw new LocalAgentError('SESSION_UNAVAILABLE', '本机应用连接已关闭。');
+ const host = req.headers.host;
+ if (host !== base.slice(7) || req.headers.origin)
+ throw new LocalAgentError('FORBIDDEN', '此接口仅供已授权的本机应用使用。');
+ if (req.method === 'GET' && req.url?.startsWith('/connect/')) {
+ const pair = pairs.get(req.url.slice(9));
+ if (!pair || pair.expires < Date.now())
+ throw new LocalAgentError('PAIR_EXPIRED', '连接申请已过期,请回到申请的应用重新连接。');
+ await approvePair(pair);
+ res.writeHead(200, {
+ 'Content-Type': 'text/html; charset=utf-8',
+ 'Cache-Control': 'no-store',
+ 'Content-Security-Policy': "default-src 'none'",
+ 'X-Frame-Options': 'DENY',
+ 'Referrer-Policy': 'no-referrer',
+ });
+ const copy = message(
+ 'CONNECT_RESULT',
+ '请回到申请的应用查看连接结果。连接授权由 Cindy 中的确认窗口决定。',
+ );
+ res.end(
+ `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Cindy</title><p>${copy.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')}</p>`,
+ );
+ return;
+ }
+ if (req.method === 'POST' && req.url?.startsWith('/mcp/')) {
+ const id = req.url.slice(5);
+ const run = runs.get(id);
+ if (
+ !run ||
+ run.closed ||
+ !equal(req.headers.authorization ?? '', `Bearer ${run.mcpToken}`) ||
+ !grants.some((g) => g.id === run.owner && g.scope === deps.scope())
+ )
+ throw new LocalAgentError('UNAUTHORIZED', '工具连接已失效。');
+ const rpc = await body(req);
+ const method = text(rpc.method);
+ if (
+ run.closed ||
+ runs.get(id) !== run ||
+ !grants.some((g) => g.id === run.owner && g.scope === deps.scope())
+ ) {
+ throw new LocalAgentError('UNAUTHORIZED', '工具连接已失效。');
+ }
+ if (!('id' in rpc)) {
+ res.writeHead(202);
+ res.end();
+ return;
+ }
+ let result: unknown;
+ if (method === 'initialize')
+ result = {
+ protocolVersion: '2025-03-26',
+ capabilities: { tools: {} },
+ serverInfo: { name: 'cindy-client-tools', version: '1' },
+ };
+ else if (method === 'tools/list')
+ result = {
+ tools: run.tools.map((t) => ({
+ name: t.name,
+ description: t.description,
+ inputSchema: t.parameters,
+ })),
+ };
+ else if (method === 'ping') result = {};
+ else if (method === 'tools/call') {
+ const params = record(rpc.params);
+ const name = text(params.name, 64);
+ if (!run.tools.some((t) => t.name === name))
+ throw new LocalAgentError('TOOL_UNAVAILABLE', '未登记此宿主工具。');
+ if (run.pending.size >= 64) throw new LocalAgentError('BUSY', '等待中的宿主工具过多。');
+ const arguments_ = record(params.arguments ?? {});
+ const callId = token();
+ result = await new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ run.pending.delete(callId);
+ resolve({
+ content: [
+ { type: 'text', text: message('TOOL_TIMEOUT', '宿主工具等待超时,未自动重试。') },
+ ],
+ isError: true,
+ });
+ }, 10 * 60_000);
+ run.pending.set(callId, { resolve, timer });
+ emit(id, { type: 'host_tool', data: { id: callId, name, arguments: arguments_ } });
+ });
+ } else throw new LocalAgentError('METHOD_UNSUPPORTED', '不支持此 MCP 操作。');
+ json(res, 200, { jsonrpc: '2.0', id: rpc.id, result });
+ return;
+ }
+ if (
+ req.method !== 'POST' ||
+ req.url !== '/rpc' ||
+ !req.headers['content-type']?.startsWith('application/json')
+ )
+ throw new LocalAgentError('INVALID_REQUEST', '需要有效的本机 RPC 请求。');
+ const rpc = await body(req);
+ const method = text(rpc.method, 64);
+ const params = record(rpc.params ?? {});
+ if (rpc.version !== 1)
+ throw new LocalAgentError(
+ 'PROTOCOL_UNSUPPORTED',
+ '本机 Agent 协议版本不兼容,请更新对应客户端。',
+ );
+ if (rpc.instance !== undefined && rpc.instance !== instanceId)
+ throw new LocalAgentError('INSTANCE_CHANGED', 'Cindy 已重新启动,未重放旧实例中的操作。');
+ if (method === 'capabilities') {
+ json(res, 200, {
+ result: {
+ protocol: 1,
+ version: deps.version,
+ instance: instanceId,
+ features: {
+ clientIdentity: true,
+ isolatedSessions: true,
+ individualRevocation: true,
+ toolPolicy: true,
+ nativeReadOnly: false,
+ },
+ methods: [
+ 'models',
+ 'session/open',
+ 'send',
+ 'steer',
+ 'interrupt',
+ 'instructions',
+ 'events',
+ 'tool/reply',
+ 'session/close',
+ 'connect/revoke',
+ ],
+ },
+ });
+ return;
+ }
+ if (method === 'connect/start') {
+ if (pairs.size >= 8) throw new LocalAgentError('BUSY', '连接申请过多,请稍后再试。');
+ const client = clientIdentity(params.client);
+ const pair: Pair = {
+ id: token(),
+ claim: token(),
+ client,
+ scope: deps.scope(),
+ expires: Date.now() + PAIR_TTL,
+ state: 'waiting',
+ };
+ pairs.set(pair.id, pair);
+ // Native consent is always raised on this computer, including remote viewing.
+ void approvePair(pair).catch(() => {
+ pair.state = 'denied';
+ deps.warn('PAIR_FAILED');
+ });
+ json(res, 200, {
+ result: { id: pair.id, claim: pair.claim, url: `${base}/connect/${pair.id}` },
+ });
+ return;
+ }
+ if (method === 'connect/poll' || method === 'connect/cancel') {
+ const pair = pairs.get(text(params.id, 128));
+ if (!pair || !equal(pair.claim, text(params.claim, 128)) || pair.expires < Date.now())
+ throw new LocalAgentError('PAIR_EXPIRED', '连接申请已过期,请重新连接。');
+ if (method === 'connect/cancel') {
+ pair.consent?.abort();
+ if (pair.grant) await revoke(pair.grant.id);
+ pairs.delete(pair.id);
+ json(res, 200, { result: {} });
+ return;
+ }
+ json(res, 200, {
+ result: { state: pair.state, ...(pair.secret ? { token: pair.secret } : {}) },
+ });
+ return;
+ }
+ const grant = authorize(req);
+ if (method === 'events' || method === 'models') {
+ json(res, 200, { result: await operation(method, params, grant) });
+ return;
+ }
+ const id = text(rpc.id, 128);
+ const key = `${grant.id}:${id}`;
+ const identity = /^([A-Za-z0-9_-]{8,64}):([1-9][0-9]{0,14})$/.exec(id);
+ if (!identity) throw new LocalAgentError('INVALID_REQUEST_ID', '请求编号格式无效。');
+ const client = `${grant.id}:${identity[1]}`,
+ counter = Number(identity[2]);
+ if (!clients.has(client) && clients.size >= 128)
+ throw new LocalAgentError('CLIENT_LIMIT', '本机连接数量已满,请在 Cindy 中重新授权。');
+ const high = clients.get(client) ?? 0;
+ if (counter <= high - 256)
+ throw new LocalAgentError('REQUEST_EXPIRED', '请求记录已过期,未再次执行。');
+ const fingerprint = hash(JSON.stringify([method, params]));
+ const previous = dedup.get(key);
+ if (previous && previous.fingerprint !== fingerprint)
+ throw new LocalAgentError('ID_REUSED', '请求编号已用于不同操作,未再次执行。');
+ if (!previous) {
+ clients.set(client, Math.max(high, counter));
+ for (const old of dedup.keys())
+ if (old.startsWith(`${client}:`) && Number(old.slice(client.length + 1)) <= counter - 256)
+ dedup.delete(old);
+ const result = operation(method, params, grant);
+ result.catch(() => {});
+ dedup.set(key, { fingerprint, result });
+ }
+ json(res, 200, { result: await dedup.get(key)!.result });
+ } catch (error) {
+ const known = error instanceof LocalAgentError;
+ const code = known ? error.code : 'LOCAL_AGENT_FAILED';
+ deps.warn(code);
+ json(res, code === 'UNAUTHORIZED' || code === 'FORBIDDEN' ? 403 : 400, {
+ error: {
+ code,
+ message: message(code, known ? error.message : 'Cindy 本机接入操作未完成。'),
+ },
+ });
+ }
+ });
+ server.requestTimeout = 30_000;
+ server.headersTimeout = 10_000;
+ server.maxConnections = 64;
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', resolve);
+ });
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('local agent address unavailable');
+ base = `http://127.0.0.1:${address.port}`;
+ const instanceId = token();
+ const discoveryDirectory = deps.discoveryDirectory ?? deps.directory;
+ const discoveryFile = path.join(discoveryDirectory, 'discovery.json');
+ try {
+ await fs.mkdir(discoveryDirectory, { recursive: true, mode: 0o700 });
+ await fs.writeFile(
+ discoveryFile,
+ JSON.stringify({ protocol: 1, port: address.port, instance: instanceId }),
+ { mode: 0o600 },
+ );
+ } catch {
+ closing = true;
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ throw new LocalAgentError('DISCOVERY_UNAVAILABLE', '未能保存本机应用连接信息。');
+ }
+ const sweep = setInterval(() => {
+ for (const [id, pair] of pairs)
+ if (pair.expires < Date.now() || pair.scope !== deps.scope()) {
+ pair.consent?.abort();
+ pairs.delete(id);
+ }
+ for (const [id, run] of runs)
+ if (
+ !run.closed &&
+ (run.touched + RUN_IDLE < Date.now() ||
+ !grants.some((g) => g.id === run.owner && g.scope === deps.scope()))
+ )
+ void closeRun(id).catch(() => {});
+ }, 1000).unref();
+ return {
+ base,
+ discoveryFile,
+ connections: () =>
+ grants
+ .filter((g) => g.scope === deps.scope())
+ .map((g) => ({ id: g.id, name: g.name, clientId: g.client.id })),
+ revoke,
+ async revokeAll() {
+ grants = [];
+ bindings = {};
+ for (const pair of pairs.values()) pair.consent?.abort();
+ pairs.clear();
+ dedup.clear();
+ clients.clear();
+ await Promise.all([persist(), ...[...runs.keys()].map((id) => closeRun(id))]);
+ deps.changed?.();
+ },
+ async close() {
+ closing = true;
+ clearInterval(sweep);
+ for (const pair of pairs.values()) pair.consent?.abort();
+ pairs.clear();
+ const stopped = await Promise.allSettled([...runs.keys()].map((id) => closeRun(id)));
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await persistence;
+ try {
+ if (JSON.parse(await fs.readFile(discoveryFile, 'utf8')).instance === instanceId)
+ await fs.rm(discoveryFile, { force: true });
+ } catch {
+ /* profile already closed */
+ }
+ const failed = stopped.find((result) => result.status === 'rejected');
+ if (failed?.status === 'rejected') throw failed.reason;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/local-agent/service.ts b/apps/desktop/src/main/local-agent/service.ts
new file mode 100644
index 0000000000..26c929f066
--- /dev/null
+++ b/apps/desktop/src/main/local-agent/service.ts
@@ -0,0 +1,238 @@
+import { app, BrowserWindow, dialog } from 'electron';
+import { createHash } from 'node:crypto';
+import path from 'node:path';
+import fs from 'node:fs/promises';
+import type { Maker } from '@cindy/maker-core';
+import {
+ activeOwnerScopeKey,
+ getActiveAppSession,
+ isAppSessionBoundaryPending,
+ ownerScopedUserDataPath,
+} from '../appSessionState.js';
+import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
+import { createLogger } from '../logger.js';
+import { t } from '../i18n.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { isIpcError } from '../../shared/ipc-errors.js';
+import type { LocalAgentConnection } from '../../shared/localAgent.js';
+import { isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';
+import { localAgentModels } from './catalog.js';
+import { createLocalAgentServer, LocalAgentError, type LocalAgentServerDeps } from './server.js';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import { openLocalAgentRuntime } from './runtime.js';
+import { localAgentMessage } from './messages.js';
+
+const log = createLogger('local-agent');
+let current: Promise<Awaited<ReturnType<typeof createLocalAgentServer>>> | undefined;
+let startupFailure: unknown;
+let teardown = Promise.resolve();
+
+/** A shared profile has one discovery endpoint and one grant writer. Reuse the
+ * existing process lock so a passive/preview instance cannot resurrect revoked grants. */
+async function startWithProfileLease(deps: LocalAgentServerDeps) {
+ const discovery = deps.discoveryDirectory ?? deps.directory;
+ await fs.mkdir(discovery, { recursive: true, mode: 0o700 });
+ let ready!: (server: Awaited<ReturnType<typeof createLocalAgentServer>>) => void;
+ let failed!: (error: unknown) => void;
+ const started = new Promise<Awaited<ReturnType<typeof createLocalAgentServer>>>(
+ (resolve, reject) => {
+ ready = resolve;
+ failed = reject;
+ },
+ );
+ let release!: () => void;
+ const released = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const lifetime = withCrossProcessLock(
+ path.join(discovery, 'host.lock'),
+ { label: 'local-agent-host', waitMs: 0 },
+ async (status) => {
+ if (!status.held)
+ throw new LocalAgentError(
+ 'HOST_IN_USE',
+ '此 profile 的本机应用连接由另一个 Cindy 实例管理。',
+ );
+ if (!deps.scope()) throw new LocalAgentError('UNAUTHORIZED', '本机应用授权范围已更改。');
+ const server = await createLocalAgentServer(deps);
+ try {
+ ready({
+ ...server,
+ async close() {
+ release();
+ await lifetime;
+ },
+ });
+ await released;
+ } finally {
+ await server.close();
+ }
+ },
+ );
+ void lifetime.catch(failed);
+ return started;
+}
+
+export function installLocalAgentHost(maker: Maker): void {
+ if (current) return;
+ const session = getActiveAppSession();
+ if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;
+ const scope = createHash('sha256').update(`${session.mode}:${session.dataOwnerId}`).digest('hex');
+ const liveOwner = activeOwnerScopeKey();
+ const directory = ownerScopedUserDataPath('local-agent');
+ const scopeNow = () => {
+ const now = getActiveAppSession();
+ return now.dataOwnerId && !isAppSessionBoundaryPending() && activeOwnerScopeKey() === liveOwner
+ ? createHash('sha256').update(`${now.mode}:${now.dataOwnerId}`).digest('hex')
+ : '';
+ };
+ startupFailure = undefined;
+ const pending = teardown.then(() =>
+ startWithProfileLease({
+ directory,
+ discoveryDirectory: path.join(app.getPath('userData'), 'local-agent'),
+ version: app.getVersion(),
+ scope: scopeNow,
+ async models() {
+ if (scopeNow() !== scope)
+ throw new LocalAgentError('UNAUTHORIZED', 'Cindy 当前账号已更改,请重新连接。');
+ const providers = await getDesktopProviderService({
+ allowSideEffects: false,
+ }).listProviders({
+ allowSideEffects: false,
+ });
+ return localAgentModels(providers, maker.listAvailableAgents());
+ },
+ async approve(signal, client) {
+ const parent = BrowserWindow.getAllWindows().find(
+ (window) => isTrustedAppRendererWindow(window) && window.isVisible(),
+ );
+ if (!parent || signal.aborted) return false;
+ const result = await dialog.showMessageBox(parent, {
+ signal,
+ type: 'question',
+ title: t('localAgent.connectTitle'),
+ message: t('localAgent.connectMessage').replaceAll('{{app}}', () => client.name),
+ detail: `${t('localAgent.connectDetail')}\n\n${t('localAgent.clientIdentity')
+ .replaceAll('{{id}}', () => client.id)
+ .replaceAll('{{version}}', () => client.version ?? '—')}`,
+ buttons: [t('localAgent.cancel'), t('localAgent.allow')],
+ defaultId: 0,
+ cancelId: 0,
+ noLink: true,
+ });
+ return (
+ result.response === 1 &&
+ !signal.aborted &&
+ scopeNow() === scope &&
+ isTrustedAppRendererWindow(parent)
+ );
+ },
+ open: (input, bridge) =>
+ openLocalAgentRuntime(maker, directory, input, bridge, localAgentMessage),
+ message: localAgentMessage,
+ warn: (code) => log.warn('local agent request failed', { code }),
+ changed: () => {
+ if (scopeNow() !== scope) return;
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (isTrustedAppRendererWindow(window))
+ window.webContents.send('local-agent:connections-changed');
+ }
+ },
+ }),
+ );
+ current = pending;
+ void pending.catch((error) => {
+ if (current === pending) {
+ current = undefined;
+ startupFailure = error;
+ }
+ log.warn('local agent API startup failed', {
+ code: error instanceof LocalAgentError ? error.code : 'LOCAL_AGENT_FAILED',
+ });
+ });
+}
+
+async function settingsOperation<T>(action: () => Promise<T>): Promise<T> {
+ try {
+ return await action();
+ } catch (error) {
+ if (isIpcError(error)) throw error;
+ log.warn('local agent settings operation failed');
+ if (error instanceof LocalAgentError)
+ throwIpcError('PRECONDITION_FAILED', localAgentMessage(error.code));
+ throwIpcError('INTERNAL', t('localAgent.operationFailed'));
+ }
+}
+
+export async function localAgentConnections(
+ assertCaller = () => {},
+): Promise<LocalAgentConnection[]> {
+ return settingsOperation(async () => {
+ if (!current && startupFailure) throw startupFailure;
+ const server = current ? await current : undefined;
+ assertCaller();
+ return server?.connections() ?? [];
+ });
+}
+
+export async function revokeLocalAgentConnections(
+ connectionId?: unknown,
+ assertCaller = () => {},
+): Promise<boolean> {
+ if (
+ connectionId !== undefined &&
+ (typeof connectionId !== 'string' || !connectionId || connectionId.length > 128)
+ ) {
+ throwIpcError('INVALID_PARAMS', t('localAgent.invalidConnection'));
+ }
+ return settingsOperation(async () => {
+ const owner = activeOwnerScopeKey();
+ const pendingServer = current;
+ const server = pendingServer ? await pendingServer : undefined;
+ assertCaller();
+ if (owner !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) return false;
+ if (!server) return false;
+ const selected =
+ connectionId === undefined
+ ? undefined
+ : server.connections().find((connection) => connection.id === connectionId);
+ if (connectionId !== undefined && !selected) return false;
+ const result = await dialog.showMessageBox({
+ type: 'warning',
+ title: t('localAgent.title'),
+ message: selected
+ ? t('localAgent.revokeOneMessage').replaceAll('{{app}}', () => selected.name)
+ : t('localAgent.revokeMessage'),
+ detail: selected ? t('localAgent.revokeOneDetail') : t('localAgent.revokeDetail'),
+ buttons: [t('localAgent.cancel'), t('localAgent.revoke')],
+ cancelId: 0,
+ defaultId: 0,
+ noLink: true,
+ });
+ assertCaller();
+ if (
+ result.response !== 1 ||
+ owner !== activeOwnerScopeKey() ||
+ isAppSessionBoundaryPending() ||
+ current !== pendingServer
+ )
+ return false;
+ if (selected) return server.revoke(selected.id);
+ await server.revokeAll();
+ return true;
+ });
+}
+
+export async function disposeLocalAgentHost(): Promise<void> {
+ const previous = current;
+ current = undefined;
+ startupFailure = undefined;
+ const stopping = previous
+ ? previous
+ .then((server) => server.close())
+ .catch(() => log.warn('local agent API shutdown failed'))
+ : Promise.resolve();
+ teardown = Promise.all([teardown, stopping]).then(() => {});
+ await teardown;
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index d8a16f5e6c..e9ac4a00ba 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -206,6 +206,7 @@ import { resolveDesktopModelContextProviderId, resolveDesktopModelEfforts } from
import {
prepareCodexCustomContextCatalog,
prepareCodexGuestModelCatalog,
+ readNativeCodexCatalog, findCodexCatalogModel, nativeCodexFallbackModel, patchCodexModelMaxContextWindow,
} from './codex-custom-context-catalog.js';
import { buildPiAgent } from './pi-host.js';
import {
@@ -235,6 +236,7 @@ import {
import { createDeviceAgentStarter } from '../remote-agent/controller/service.js';
import { extractReviewPdfTextInChild } from '../reviewer/reviewPdfProcess.js';
import { disposeRemoteAgentHost, installRemoteAgentHost } from '../remote-agent/host/service.js';
+import { disposeLocalAgentHost, installLocalAgentHost } from '../local-agent/service.js';
import {
getClaudeEndpoint,
setClaudeProxyGatewayKeyReader,
@@ -1781,6 +1783,19 @@ export function getMaker(): Maker {
resolveDesktopModelContextProviderId(getDesktopSelectableCatalog(), 'codex', providerId, modelId), modelId),
resolveCodexContextWindowInfo: (modelId, config, reportedUsableWindow, codexHome) =>
readCodexContextWindowInfo({ codexHome: codexHome ?? getCodexHome(), binaryPath: codexPath, modelId, config, reportedUsableWindow }),
+ prepareCodexHostToolCatalog: async (modelId, contextWindow) => {
+ let catalog = await readNativeCodexCatalog(codexPath, getCodexHome());
+ if (!findCodexCatalogModel(catalog, modelId)) catalog.models.push(nativeCodexFallbackModel(modelId));
+ if (contextWindow !== null) catalog = patchCodexModelMaxContextWindow(catalog, modelId, contextWindow);
+ const restricted = { ...catalog, models: catalog.models.map(model => ({...model, apply_patch_tool_type: null, supports_search_tool: false})) };
+ const directory = ownerScopedUserDataPath('local-agent', 'codex-catalogs');
+ await fs.mkdir(directory, {recursive:true});
+ const target = path.join(directory, `host-tools-only-${createHash('sha256').update(JSON.stringify([modelId, contextWindow])).digest('hex')}.json`);
+ const temporary = target + '.' + randomUUID() + '.tmp';
+ try { await fs.writeFile(temporary, JSON.stringify(restricted), {mode:0o600}); await fs.rename(temporary,target); }
+ finally { await fs.rm(temporary,{force:true}); }
+ return target;
+ },
resolveCodexLocalAuthPolicy: captureCodexLocalAuthPolicy,
resolveCodexThreadContextWindow: (providerId, modelId) => {
const source = resolveDesktopModelContextProviderId(getDesktopSelectableCatalog(), 'codex', providerId, modelId);
@@ -3106,6 +3121,7 @@ export function getMaker(): Maker {
});
// 本机作为「Agent 运行的电脑」:同账号另一台电脑的任务可让 Agent 在这里运行。
installRemoteAgentHost({ getMaker: () => getMaker(), userDataDir: app.getPath('userData') });
+ installLocalAgentHost(_maker);
botRuntimeResourcePreflight = async (opts) => {
const preflightOpts = { ...opts };
return hydrateBotProfileRuntime(preflightOpts, buildBotRuntimeDeps(), {
@@ -3301,6 +3317,7 @@ export function resetMaker(): void {
// Callers keep this Maker when PI teardown is unconfirmed, preserving supervision.
releaseSessionBindingsForOwnerBoundary();
remoteWorkerBridge = null;
+ void disposeLocalAgentHost();
disposeRemoteAgentHost();
_sessionArchiveSync?.stop();
_sessionArchiveSync = null;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 33ecd72e7f..9044734e3c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1076,6 +1076,15 @@ const appearanceSettingsInfo = ipcRenderer.sendSync(
) as AppearanceSettings | null;
contextBridge.exposeInMainWorld('electronAPI', {
+ localAgent: {
+ connections: (): Promise<import('../shared/localAgent').LocalAgentConnection[]> => ipcRenderer.invoke('local-agent:connections'),
+ revoke: (connectionId?: string): Promise<boolean> => ipcRenderer.invoke('local-agent:revoke', connectionId),
+ onConnectionsChanged: (listener: () => void) => {
+ const receive = () => listener();
+ ipcRenderer.on('local-agent:connections-changed', receive);
+ return () => ipcRenderer.removeListener('local-agent:connections-changed', receive);
+ },
+ },
modelFavoritesHost: {
ready: () => ipcRenderer.send(FAVORITE_HOST_READY),
changed: (stamp) => ipcRenderer.send(FAVORITE_HOST_CHANGED, stamp),
diff --git a/apps/desktop/src/renderer/components/settings/LocalAgentSection.settings-search.ts b/apps/desktop/src/renderer/components/settings/LocalAgentSection.settings-search.ts
new file mode 100644
index 0000000000..f57a86fd11
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/LocalAgentSection.settings-search.ts
@@ -0,0 +1,8 @@
+import type { SettingsSearchModule } from './settingsSearchTypes';
+
+export default {
+ id: 'local-agent', order: 2,
+ entries: [{ id: 'localAgent.connections', tab: 'remote-control', targetId: 'settings-search-target-local-agent',
+ titleKey: 'localAgent.title', sectionKey: 'settings.sections.remoteControl',
+ aliases: ['local agent', 'local app', 'revoke connection', '本机应用', '撤销连接'] }],
+} satisfies SettingsSearchModule;
diff --git a/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx b/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx
new file mode 100644
index 0000000000..2ab46e29bc
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx
@@ -0,0 +1,118 @@
+import { Fragment, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
+import type { LocalAgentConnection } from '../../../shared/localAgent';
+import {
+ SETTINGS_CARD_CLASS,
+ SETTINGS_ROW_CLASS,
+ SETTINGS_ROW_DIVIDER_CLASS,
+ SETTINGS_ROW_HINT_CLASS,
+ SETTINGS_ROW_LABEL_CLASS,
+ SETTINGS_SECTION_TITLE_CLASS,
+} from './settingsRowClasses';
+
+export function LocalAgentSection() {
+ const { t } = useTranslation();
+ const [connections, setConnections] = useState<LocalAgentConnection[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [failed, setFailed] = useState(false);
+ const [revoking, setRevoking] = useState<string>();
+ const busy = useRef(false);
+ useEffect(() => {
+ let alive = true,
+ revision = 0;
+ const refresh = () => {
+ const request = ++revision;
+ void window.electronAPI.localAgent
+ .connections()
+ .then((value) => {
+ if (alive && revision === request) {
+ setConnections(value);
+ setFailed(false);
+ }
+ })
+ .catch(() => {
+ if (alive && revision === request) setFailed(true);
+ })
+ .finally(() => {
+ if (alive && revision === request) setLoading(false);
+ });
+ };
+ const unsubscribe = window.electronAPI.localAgent.onConnectionsChanged(refresh);
+ refresh();
+ return () => {
+ alive = false;
+ unsubscribe();
+ };
+ }, []);
+ const revoke = async (id: string) => {
+ if (busy.current) return;
+ busy.current = true;
+ setRevoking(id);
+ try {
+ if (await window.electronAPI.localAgent.revoke(id)) {
+ setConnections((previous) => previous.filter((item) => item.id !== id));
+ setFailed(false);
+ }
+ } catch (error) {
+ toast.error(extractIpcError(error)?.message ?? t('localAgent.revokeFailed'));
+ } finally {
+ busy.current = false;
+ setRevoking(undefined);
+ }
+ };
+ return (
+ <div id="settings-search-target-local-agent" className="mt-6 flex flex-col gap-[14px]">
+ <h2 className={SETTINGS_SECTION_TITLE_CLASS}>{t('localAgent.title')}</h2>
+ <div className={SETTINGS_CARD_CLASS} aria-busy={loading || Boolean(revoking)}>
+ {connections.length ? (
+ connections.map((connection, index) => (
+ <Fragment key={connection.id}>
+ {index > 0 && <div className={SETTINGS_ROW_DIVIDER_CLASS} />}
+ <div className={SETTINGS_ROW_CLASS}>
+ <div className="flex min-w-0 flex-col gap-1">
+ <p className={`${SETTINGS_ROW_LABEL_CLASS} break-words`}>{connection.name}</p>
+ <p className={`${SETTINGS_ROW_HINT_CLASS} break-all`}>
+ {connection.clientId
+ ? t('localAgent.clientId', { id: connection.clientId })
+ : t('localAgent.description')}
+ </p>
+ </div>
+ <Button
+ className="shrink-0"
+ variant="secondary"
+ size="sm"
+ disabled={Boolean(revoking)}
+ aria-label={t('localAgent.revokeConnection', { app: connection.name })}
+ onClick={() => void revoke(connection.id)}
+ >
+ {t(revoking === connection.id ? 'localAgent.revoking' : 'localAgent.revoke')}
+ </Button>
+ </div>
+ </Fragment>
+ ))
+ ) : (
+ <div className={SETTINGS_ROW_CLASS}>
+ <div className="flex min-w-0 flex-col gap-1">
+ <p role={failed ? 'status' : undefined} className={SETTINGS_ROW_LABEL_CLASS}>
+ {t(loading ? 'localAgent.loading' : failed ? 'localAgent.failed' : 'localAgent.empty')}
+ </p>
+ {!loading && !failed && (
+ <p className={SETTINGS_ROW_HINT_CLASS}>
+ {t('localAgent.description')}
+ </p>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ {failed && connections.length > 0 && (
+ <p role="status" className={SETTINGS_ROW_HINT_CLASS}>
+ {t('localAgent.failed')}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
index d678847ab1..69b73d18f8 100644
--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx
+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx
@@ -30,6 +30,7 @@ import { VisionBridgeSection } from './VisionBridgeSection';
import { ProvidersSection } from './ProvidersSection';
import { McpServersSection } from './McpServersSection';
import { RemoteControlSection } from './RemoteControlSection';
+import { LocalAgentSection } from './LocalAgentSection';
import { SharedTaskDialog } from '@/features/device-link/SharedTaskDialog';
import { NotificationSection } from './NotificationSection';
import { WindowBehaviorSection } from './WindowBehaviorSection';
@@ -607,6 +608,7 @@ export function SettingsView() {
>
<section aria-label={t('settings.sections.remoteControl')}>
<RemoteControlSection />
+ <LocalAgentSection />
</section>
</div>
)}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a26ec5ff04..ef56006074 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1,4 +1,5 @@
{
+ "localAgent": {"title":"Local App Connections","empty":"No connected apps","description":"Authorized local apps can use Cindy models and agent capabilities. Cindy keeps supplier credentials.","revoke":"Revoke Connection","failed":"Could not read app connections.","connectTitle":"Connect a Local App","connectMessage":"Allow “{{app}}” to use Cindy?","connectDetail":"This app can list models and providers, create its own executions, and supply tools. Native execution can read and write files and run commands with your system user permissions; the working directory does not restrict access. Provider credentials stay in Cindy. Revoke individual connections in Settings → Remote Connections → Local App Connections.","cancel":"Cancel","allow":"Allow Connection","revokeMessage":"Revoke all local app connections?","revokeDetail":"All local app connections will stop working and their running tasks will stop. Apps can request a new connection when needed.","clientIdentity":"App-reported ID: {{id}}\nVersion: {{version}}\nThe requesting app supplies its name and ID; Cindy has not verified its publisher.","revokeOneMessage":"Revoke this connection for “{{app}}”?","revokeOneDetail":"Tasks running through this connection will stop. Other app connections will keep working. The app can request a new connection when needed.","revokeConnection":"Revoke connection for “{{app}}”","clientId":"App ID: {{id}}","operationFailed":"Could not confirm the local app operation. Check its current state before continuing.","invalidConnection":"The app connection ID is invalid.","revokeFailed":"Could not confirm the revocation. Check the current connection state.","loading":"Loading app connections…","revoking":"Revoking connection…","authorizationRequired":"This operation requires valid local app authorization.","pairExpired":"The connection request expired or was cancelled. Request a new connection from the app.","busy":"A local app execution is still running or the execution limit is reached. End unused executions first.","limitReached":"The local app connection limit is reached. Revoke unused connections in Settings.","invalidWorkspace":"The app must specify an existing absolute working directory on this computer.","sessionExists":"This execution ID is already in use by this app connection.","executionUnavailable":"The requested execution or tool call is unavailable. Messages and tool operations were not replayed.","selectionUnavailable":"The selected model, provider, or reasoning effort is unavailable. Select an available option in the app.","requestNotReplayed":"This request was not repeated. Check the original operation result in the app.","storageUnavailable":"Could not read or save local app connection data. Existing authorization records were retained.","stopUnconfirmed":"Further messages to this execution are blocked, but the process has not been confirmed stopped.","interactionUnavailable":"The engine requires an interaction that this app cannot receive.","interrupted":"This send was interrupted.","toolTimeout":"The app tool timed out. It was not automatically retried.","connectResult":"Return to the requesting app for the connection result. Authorization is decided in the Cindy confirmation window.","invalidRequest":"The app request is invalid or the operation is unsupported.","hostInUse":"Another Cindy instance manages local app connections for this profile. View the connections in that instance."},
"mailReader": {
"markReadFailed": "Could not sync read status. Check mailbox authorization and reopen this email.",
"title": "Mail",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 58218816ac..238b6372da 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1,4 +1,5 @@
{
+ "localAgent": {"title":"ローカルアプリの接続","empty":"接続済みのアプリはありません","description":"承認したローカルアプリが Cindy のモデルと実行機能を利用できます。認証情報は Cindy が管理します。","revoke":"接続を解除","failed":"アプリの接続を読み込めませんでした。","connectTitle":"ローカルアプリを接続","connectMessage":"「{{app}}」に Cindy の利用を許可しますか?","connectDetail":"このアプリはモデルとプロバイダーの一覧を取得し、独自の実行を作成してツールを提供できます。ネイティブ実行では、現在の OS ユーザーの権限でファイルを読み書きし、コマンドを実行できます。作業ディレクトリはアクセス範囲を制限しません。認証情報は Cindy が保持します。設定 → リモート接続 → ローカルアプリの接続で個別に解除できます。","cancel":"キャンセル","allow":"接続を許可","revokeMessage":"すべてのローカルアプリ接続を取り消しますか?","revokeDetail":"すべてのローカルアプリ接続が無効になり、実行中のタスクが停止します。必要に応じて再接続できます。","clientIdentity":"アプリが申告した ID:{{id}}\nバージョン:{{version}}\n名前と ID は申請元の申告であり、Cindy が発行元を確認したことを意味しません。","revokeOneMessage":"「{{app}}」のこの接続を取り消しますか?","revokeOneDetail":"この接続で実行中のタスクが停止します。他のアプリ接続には影響しません。必要に応じて再接続できます。","revokeConnection":"「{{app}}」の接続を取り消す","clientId":"アプリ ID:{{id}}","operationFailed":"ローカルアプリの操作結果を確認できませんでした。現在の状態を確認してから続けてください。","invalidConnection":"アプリ接続の ID が無効です。","revokeFailed":"接続の解除を確認できませんでした。現在の接続状態を確認してください。","loading":"アプリの接続を読み込み中…","revoking":"接続を解除中…","authorizationRequired":"この操作には有効なローカルアプリの承認が必要です。","pairExpired":"接続リクエストの有効期限が切れたか、キャンセルされました。アプリから接続を再申請してください。","busy":"ローカルアプリの実行が続いているか、実行数の上限に達しています。不要な実行を先に終了してください。","limitReached":"ローカルアプリの接続数が上限に達しています。設定で不要な接続を解除してください。","invalidWorkspace":"アプリは、このコンピューター上に存在する作業ディレクトリを絶対パスで指定する必要があります。","sessionExists":"このアプリ接続では、その実行 ID がすでに使われています。","executionUnavailable":"要求された実行またはツール呼び出しは利用できません。メッセージやツール操作は再実行されていません。","selectionUnavailable":"選択したモデル、プロバイダー、または推論強度は利用できません。アプリで利用可能な項目を選択してください。","requestNotReplayed":"このリクエストは再実行されていません。アプリで元の操作結果を確認してください。","storageUnavailable":"ローカルアプリの接続データを読み込めないか、保存できませんでした。既存の承認記録は保持されています。","stopUnconfirmed":"この実行への追加メッセージは停止しましたが、プロセスの終了はまだ確認できていません。","interactionUnavailable":"エンジンが必要とする操作を、このアプリでは受け取れません。","interrupted":"今回の送信は中断されました。","toolTimeout":"アプリのツールがタイムアウトしました。自動で再試行していません。","connectResult":"接続結果は申請元のアプリで確認してください。承認は Cindy の確認ウィンドウで決定します。","invalidRequest":"アプリのリクエストが無効か、この操作はサポートされていません。","hostInUse":"このプロファイルのローカルアプリ接続は、別の Cindy インスタンスが管理しています。そのインスタンスで接続を確認してください。"},
"mailReader": {
"markReadFailed": "既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。",
"title": "メール",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 77519b666b..f68c0f2009 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1,4 +1,5 @@
{
+ "localAgent": {"title":"로컬 앱 연결","empty":"연결된 앱 없음","description":"승인된 로컬 앱이 Cindy 모델과 실행 기능을 사용할 수 있습니다. 제공자 인증 정보는 Cindy가 관리합니다.","revoke":"연결 해제","failed":"앱 연결을 불러오지 못했습니다.","connectTitle":"로컬 앱 연결","connectMessage":"“{{app}}”의 Cindy 사용을 허용할까요?","connectDetail":"이 앱은 모델과 제공자 목록을 확인하고 자체 실행을 만들며 도구를 제공할 수 있습니다. 네이티브 실행은 현재 시스템 사용자 권한으로 파일을 읽고 쓰거나 명령을 실행할 수 있으며, 작업 디렉터리가 접근 범위를 제한하지 않습니다. 제공자 인증 정보는 Cindy가 보관합니다. 설정 → 원격 연결 → 로컬 앱 연결에서 개별 연결을 해제할 수 있습니다.","cancel":"취소","allow":"연결 허용","revokeMessage":"모든 로컬 앱 연결을 해제할까요?","revokeDetail":"모든 로컬 앱 연결이 무효화되고 실행 중인 작업이 중지됩니다. 필요하면 다시 연결할 수 있습니다.","clientIdentity":"앱이 제공한 ID: {{id}}\n버전: {{version}}\n이름과 ID는 요청 앱이 제공하며, Cindy가 게시자를 확인했다는 의미가 아닙니다.","revokeOneMessage":"“{{app}}”의 이 연결을 취소할까요?","revokeOneDetail":"이 연결에서 실행 중인 작업이 중지됩니다. 다른 앱 연결에는 영향을 주지 않습니다. 필요하면 다시 연결할 수 있습니다.","revokeConnection":"“{{app}}” 연결 취소","clientId":"앱 ID: {{id}}","operationFailed":"로컬 앱 작업 결과를 확인하지 못했습니다. 현재 상태를 확인한 후 계속하세요.","invalidConnection":"앱 연결 ID가 유효하지 않습니다.","revokeFailed":"연결 해제 결과를 확인하지 못했습니다. 현재 연결 상태를 확인하세요.","loading":"앱 연결을 불러오는 중…","revoking":"연결 해제 중…","authorizationRequired":"이 작업에는 유효한 로컬 앱 승인이 필요합니다.","pairExpired":"연결 요청이 만료되었거나 취소되었습니다. 앱에서 새 연결을 요청하세요.","busy":"로컬 앱 실행이 진행 중이거나 실행 한도에 도달했습니다. 사용하지 않는 실행을 먼저 종료하세요.","limitReached":"로컬 앱 연결 한도에 도달했습니다. 설정에서 사용하지 않는 연결을 해제하세요.","invalidWorkspace":"앱은 이 컴퓨터에 존재하는 작업 디렉터리의 절대 경로를 지정해야 합니다.","sessionExists":"이 앱 연결에서 해당 실행 ID를 이미 사용하고 있습니다.","executionUnavailable":"요청한 실행 또는 도구 호출을 사용할 수 없습니다. 메시지와 도구 작업은 다시 실행되지 않았습니다.","selectionUnavailable":"선택한 모델, 제공자 또는 추론 강도을 사용할 수 없습니다. 앱에서 사용 가능한 항목을 선택하세요.","requestNotReplayed":"이 요청은 다시 실행되지 않았습니다. 앱에서 원래 작업 결과를 확인하세요.","storageUnavailable":"로컬 앱 연결 데이터를 읽거나 저장하지 못했습니다. 기존 승인 기록은 유지되었습니다.","stopUnconfirmed":"이 실행에 추가 메시지를 보내는 것은 차단되었지만 프로세스가 중지되었는지는 확인되지 않았습니다.","interactionUnavailable":"엔진에 필요한 상호작용을 이 앱이 받을 수 없습니다.","interrupted":"이번 전송이 중단되었습니다.","toolTimeout":"앱 도구 호출 시간이 초과되었습니다. 자동으로 재시도하지 않았습니다.","connectResult":"연결 결과는 요청한 앱에서 확인하세요. 승인은 Cindy 확인 창에서 결정합니다.","invalidRequest":"앱 요청이 유효하지 않거나 지원하지 않는 작업입니다.","hostInUse":"이 프로필의 로컬 앱 연결은 다른 Cindy 인스턴스가 관리합니다. 해당 인스턴스에서 연결을 확인하세요."},
"mailReader": {
"markReadFailed": "읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.",
"title": "메일",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 1245b3579e..7264bb27ef 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1,4 +1,5 @@
{
+ "localAgent": {"title":"本机应用连接","empty":"尚未连接应用","description":"允许已授权的本机应用使用 Cindy 的模型与执行能力。供应商登录仍由 Cindy 管理。","revoke":"撤销连接","failed":"无法读取应用连接。","connectTitle":"连接本机应用","connectMessage":"允许“{{app}}”使用 Cindy?","connectDetail":"此应用可以查看模型与供应商目录、创建自己的执行并提供工具。原生执行可以按当前系统用户的权限读写文件、运行命令;工作目录不限制访问范围。供应商凭证保留在 Cindy。可在设置 → 远程连接 → 本机应用连接中单独撤销连接。","cancel":"取消","allow":"允许连接","revokeMessage":"撤销所有本机应用连接?","revokeDetail":"所有本机应用的连接会失效,正在运行的接入任务会停止。需要使用时可重新申请连接。","clientIdentity":"应用自报编号:{{id}}\n版本:{{version}}\n名称和编号由申请方提供,不代表 Cindy 已验证其发布者。","revokeOneMessage":"撤销“{{app}}”的这条连接?","revokeOneDetail":"这条连接正在运行的任务会停止。其他应用连接不受影响。需要使用时可重新申请连接。","revokeConnection":"撤销“{{app}}”的连接","clientId":"应用编号:{{id}}","operationFailed":"无法确认本机应用操作的结果,请先查看当前状态。","invalidConnection":"应用连接编号无效。","revokeFailed":"无法确认撤销结果,请查看当前连接状态。","loading":"正在读取应用连接…","revoking":"正在撤销连接…","authorizationRequired":"此操作需要有效的本机应用授权。","pairExpired":"连接申请已过期或取消,请从应用重新申请连接。","busy":"本机应用仍有执行正在运行,或已达到执行上限,请先结束不用的执行。","limitReached":"已达到本机应用连接上限,请在设置中撤销不用的连接。","invalidWorkspace":"应用须指定此电脑上已存在的绝对工作目录。","sessionExists":"此应用连接已在使用该执行编号。","executionUnavailable":"所请求的执行或工具调用不可用,消息与工具操作未被重放。","selectionUnavailable":"所选模型、供应商或推理强度不可用,请在应用中重新选择。","requestNotReplayed":"此请求未被重复执行,请在应用中查看原操作结果。","storageUnavailable":"无法读取或保存本机应用连接数据,已保留现有授权记录。","stopUnconfirmed":"已阻止继续向此执行发送消息,但尚未确认进程已停止。","interactionUnavailable":"引擎需要此应用无法接收的交互操作。","interrupted":"本次发送已中断。","toolTimeout":"应用工具调用已超时,未自动重试。","connectResult":"请返回申请连接的应用查看结果,授权由 Cindy 确认窗口决定。","invalidRequest":"应用请求无效,或该操作不受支持。","hostInUse":"此配置的本机应用连接正由另一个 Cindy 实例管理,请在该实例中查看连接。"},
"mailReader": {
"markReadFailed": "未能同步已读状态,请检查邮箱授权后重新打开。",
"title": "邮件",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 4294d688dd..8a0cf78923 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1,4 +1,5 @@
{
+ "localAgent": {"title":"本機應用程式連線","empty":"尚未連接應用程式","description":"允許已授權的本機應用程式使用 Cindy 的模型與執行能力。供應商登入仍由 Cindy 管理。","revoke":"撤銷連線","failed":"無法讀取應用程式連線。","connectTitle":"連接本機應用程式","connectMessage":"允許「{{app}}」使用 Cindy?","connectDetail":"此應用程式可以查看模型與供應商目錄、建立自己的執行並提供工具。原生執行可以依目前系統使用者的權限讀寫檔案、執行命令;工作目錄不限制存取範圍。供應商憑證保留在 Cindy。可在設定 → 遠端連線 → 本機應用程式連線中個別撤銷連線。","cancel":"取消","allow":"允許連接","revokeMessage":"撤銷所有本機應用程式連線?","revokeDetail":"所有本機應用程式連線將失效,正在執行的接入任務會停止。需要時可重新申請連線。","clientIdentity":"應用程式自報編號:{{id}}\n版本:{{version}}\n名稱與編號由申請方提供,不代表 Cindy 已驗證其發行者。","revokeOneMessage":"撤銷「{{app}}」的這條連線?","revokeOneDetail":"透過此連線執行的任務會停止。其他應用程式連線不受影響,需要時可重新申請連線。","revokeConnection":"撤銷「{{app}}」的連線","clientId":"應用程式編號:{{id}}","operationFailed":"無法確認本機應用程式操作的結果,請先查看目前狀態。","invalidConnection":"應用程式連線編號無效。","revokeFailed":"無法確認撤銷結果,請查看目前連線狀態。","loading":"正在讀取應用程式連線…","revoking":"正在撤銷連線…","authorizationRequired":"此操作需要有效的本機應用程式授權。","pairExpired":"連線申請已過期或取消,請從應用程式重新申請連線。","busy":"本機應用程式仍有執行正在運行,或已達執行上限,請先結束不用的執行。","limitReached":"已達本機應用程式連線上限,請在設定中撤銷不用的連線。","invalidWorkspace":"應用程式須指定此電腦上已存在的絕對工作目錄。","sessionExists":"此應用程式連線已在使用該執行編號。","executionUnavailable":"所請求的執行或工具呼叫無法使用,訊息與工具操作未被重播。","selectionUnavailable":"所選模型、供應商或推理強度無法使用,請在應用程式中重新選擇。","requestNotReplayed":"此請求未被重複執行,請在應用程式中查看原操作結果。","storageUnavailable":"無法讀取或儲存本機應用程式連線資料,已保留現有授權紀錄。","stopUnconfirmed":"已阻止繼續向此執行傳送訊息,但尚未確認程序已停止。","interactionUnavailable":"引擎需要此應用程式無法接收的互動操作。","interrupted":"本次傳送已中斷。","toolTimeout":"應用程式工具呼叫已逾時,未自動重試。","connectResult":"請返回申請連線的應用程式查看結果,授權由 Cindy 確認視窗決定。","invalidRequest":"應用程式請求無效,或該操作不受支援。","hostInUse":"此設定檔的本機應用程式連線正由另一個 Cindy 執行個體管理,請在該執行個體中查看連線。"},
"mailReader": {
"markReadFailed": "未能同步已讀狀態,請檢查信箱授權後重新開啟。",
"title": "郵件",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index eb8af15892..ac6e53c1d8 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1145,6 +1145,7 @@ type ElectronLocalDbSessionListUsageOptions = Omit<
};
interface ElectronAPI {
+ localAgent: import('../shared/localAgent').LocalAgentSettingsApi;
botMarket: import('../shared/botMarket').BotMarketApi;
companionImport: import('@cindy/maker-shared/companion-import').CompanionImportApi;
modelFavoritesHost: import('../shared/modelFavoritesSync').ModelFavoritesHostApi;
diff --git a/apps/desktop/src/shared/localAgent.ts b/apps/desktop/src/shared/localAgent.ts
new file mode 100644
index 0000000000..cfa81e67e1
--- /dev/null
+++ b/apps/desktop/src/shared/localAgent.ts
@@ -0,0 +1,12 @@
+/** Local settings projection. This does not expose bearer credentials or native session ids. */
+export interface LocalAgentConnection {
+ id: string;
+ name: string;
+ clientId?: string;
+}
+
+export interface LocalAgentSettingsApi {
+ connections(): Promise<LocalAgentConnection[]>;
+ revoke(connectionId?: string): Promise<boolean>;
+ onConnectionsChanged(listener: () => void): () => void;
+}
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 1d25d708ae..bbcd37cd3f 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -38,7 +38,7 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx, apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginActions, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginDevicePicker, PluginManagementLayout, PluginProjectMenu, RemotePluginConfiguration, RemotePluginPage, RemotePluginReadOnlyDetail, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 28 | 0 | 48 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 137 | 95 | 548 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalAgentSection.settings-search.ts, apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 137 | 95 | 548 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/NewTag.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/TabDragController.tsx, apps/desktop/src/renderer/features/right-sidebar/TabGroupPanel.tsx, apps/desktop/src/renderer/features/right-sidebar/botMenuOwnerContext.ts, apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSideChatTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/useTabCreationMenu.ts, apps/desktop/src/renderer/features/right-sidebar/moveTab.ts, apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/SideChatTabBody.test.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/SideChatTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/state.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx, apps/desktop/src/renderer/features/right-sidebar/tabGroupPanes.ts, apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 147 | 46 | 200 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginDevicePicker, PluginManagementLayout, RemoteSkillsPage, SkillCategoryFilterBar, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/skillhub-home.css | 39 | 0 | 45 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 42 | 0 | 35 |
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 93b9b66d66..52b294ab61 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -198,6 +198,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |
| 浏览器用户配方 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存配方定义及 active/suspended 状态,不保存试跑的 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。试跑凭证与单轮修复预算只在 MCP 会话内存中,暂停状态跨重启保留。 |
+| 本机应用 Agent 授权 | `owners/<owner-key>/local-agent/grants.json`,仅含令牌 SHA-256、自报应用资料、账号范围和按授权归属的原生恢复绑定,不存令牌明文、供应商凭据或消息。复用原子写入与恢复 helper;profile 根 `local-agent/host.lock` 复用跨进程锁,保证一个发现端点和写入者。临时输入与新授权的 Codex 运行历史在同一 owner 下的 `local-agent/clients/<grant-hash>/`;撤权同时关闭执行及工具入口,不允许跨授权恢复。协议与旧版兼容见 [本机应用接入](../local-agent-api.md) |
| 预创建 worktree 的取消标记 | `userData/worktree-cancelled-creations/<sessionId 的 SHA-256>`,空文件原子排他创建;不含路径、草稿或关联密钥。保留以拒绝重启后迟到的创建请求,不按超时删除。只在核实未被任务认领后写入。同路径加 `.lock` 是可释放的跨进程操作锁,复用既有锁协议;同一 profile、同一任务的创建登记与取消回收串行,拿不到锁不得确认回收完成。异步创建完成后、登记前再次核对取消标记 |
| Mobile 已取消创建的草稿 | 复用账号隔离的 durable outbox;持久创建流程先保存草稿、原项目目录和附件,再登记 reservation 和发送远端 worktree 创建;创建回包前暂停发件箱投递。回收确认后,`creation.cancelled` 与原项目目录先持久写入,再忘记回收账本。重建使用新远端 ID,`storageSessionId` 保持原 AsyncStorage 键和附件目录,通过单次记录写入提交;写入失败时原草稿仍可读。编辑页恢复目录时重新探测资格,不沿用旧 worktree 的资格或分支偏好 |
| 可丢弃的临时数据 | `app.getPath('temp')` 或 `os.tmpdir()` 下的任务专属目录 |
diff --git a/docs/dev-rules/repo-map.md b/docs/dev-rules/repo-map.md
index 8296ecd8ed..663936435a 100644
--- a/docs/dev-rules/repo-map.md
+++ b/docs/dev-rules/repo-map.md
@@ -60,6 +60,10 @@
| `project-context` | agent 维护的项目知识层(commit 驱动的 markdown CLI) | desktop(maker-ipc) |
| `voice-input-core` | 语音输入核心:供应商无关的听写状态机与润色守卫 | desktop + mobile |
+## 本机应用 Agent 接入
+
+Desktop 的 `main/local-agent/` 提供经原生授权的通用本机 Agent API,复用 maker-core 的引擎与内存 Session;应用自己的界面、记录、上下文和业务工具留在调用方。协议、存储和兼容边界见 [本机应用接入](../local-agent-api.md),独立客户端示例在 `scripts/examples/`。
+
## 校验下载与工具安装
Desktop 发行资产统一走 `main/downloader/index.ts`;通用工具安装位于
diff --git a/docs/local-agent-api.md b/docs/local-agent-api.md
new file mode 100644
index 0000000000..61c5229bec
--- /dev/null
+++ b/docs/local-agent-api.md
@@ -0,0 +1,126 @@
+# Cindy 本机 Agent API v1
+
+这是供任意本机应用接入的 Agent 会话协议。Cindy 管理供应商、凭据、模型路由和 Claude Code / Codex / Pi 执行;客户端管理自己的界面、记录、上下文、工具实现及业务权限。HHH 是首个客户端,不是协议的应用类型或授权白名单。
+
+实现入口:[`main/local-agent/`](../apps/desktop/src/main/local-agent/)。协议扩展保持 v1,旧客户端可忽略新增能力字段;不要把兼容的本机 API 当成 OpenAI 或 Anthropic 模型 API,也不提供跨机访问。
+
+维护者于 2026-10-22 明确裁决:**保留 Cindy 身份、现有提示词与装配语义**。应用接入的是 Cindy;通用化针对 API、授权和应用隔离。调用方应按公开事件消费 Cindy 现有风格的文本与输出格式,不以移除身份、产品指引或回答呈现规则为集成前提。客户端的 `instructions` 仍通过既有调用方指令位置追加,不替换 Cindy 提示词。
+
+## 独立客户端示例
+
+[`scripts/examples/local-agent-client.mjs`](../scripts/examples/local-agent-client.mjs) 只使用 Node 22+ 标准库、发现文件和 HTTP,没有 Cindy / HHH 源码依赖。先启动本任务或已包含该 API 的 Cindy,再指定**目标 profile** 的发现文件:
+
+```sh
+node scripts/examples/local-agent-client.mjs --discovery "<profile>/local-agent/discovery.json" --list-models
+node scripts/examples/local-agent-client.mjs --discovery "<profile>/local-agent/discovery.json" --provider "<provider-id>" --engine pi --model "<opaque-model-id>" --cwd "<absolute-folder>"
+```
+
+每次在 Cindy 的原生弹窗允许该应用。第二条命令运行一个只做文本回显的 `client_echo` 工具,再接收模型回答。可用 `--client-id org.example.notes --client-name Notes` 和另一组身份同时启动两份示例;两者可使用相同会话编号。`--prompt` 自定输入,`--native-tools` 显式启用原生执行。模型调用会消费所选供应商额度。
+
+示例令牌只在进程内存中,退出时关闭自己的会话并撤销自己的授权,不打印、保存或复用令牌。需要长期连接的产品自行通过 OS 凭据库保存此应用令牌;不得复制供应商登录。命令行参数不接收秘密。`--list-models` 不调用模型生成。
+
+## 发现、封装与能力
+
+目标 profile 根目录的 `local-agent/discovery.json`:
+
+```json
+{"protocol":1,"port":12345,"instance":"<opaque-instance>"}
+```
+
+端口随机分配,只监听 `127.0.0.1`。发现文件不含令牌。正式 profile 与开发沙箱完全独立;示例不扫描或默认借用其他 profile。Windows 正式目录为 `%APPDATA%/CindyGlobal` 或中国大陆版 `%APPDATA%/Cindy`,macOS 在 `~/Library/Application Support/`,Linux 在 `$XDG_CONFIG_HOME`(缺省 `~/.config`);沙箱位置以启动器输出为准。
+
+`POST http://127.0.0.1:<port>/rpc`,`Content-Type: application/json`:
+
+```json
+{"version":1,"instance":"<opaque-instance>","id":"550e8400-e29b-41d4-a716-446655440000:1","method":"capabilities","params":{}}
+```
+
+成功为 `{"result":...}`,失败为 `{"error":{"code":"...","message":"..."}}`;错误的 `code` 用于程序判断,`message` 用于展示。RPC 不使用 JSON-RPC 的 `jsonrpc` 字段。Host 必须为发现的 loopback 地址,任何带 Origin 的请求都拒绝;这是供本机进程使用的接口,不开放浏览器 CORS。
+
+`capabilities` 无需授权,返回 `protocol`、Cindy `version`、`instance`、可用 `methods` 和 `features`。当前通用扩展声明 `clientIdentity`、`isolatedSessions`、`individualRevocation`、`toolPolicy` 为 true,`nativeReadOnly` 为 false。未声明的能力不得假定支持。`instance` 保持可选以兼容早期 v1 客户端,新客户端应始终携带;实例改变后重新发现,不自动重放旧操作。
+
+有副作用的请求编号必须是 `<process-nonce>:<counter>`,nonce 为 8–64 位 `[A-Za-z0-9_-]`,counter 从 1 单调递增、最多 15 位。去重按**授权 + 完整请求编号**计算,同编号不同 payload 拒绝;每个进程保留最近 256 个编号的窗口,已过期请求拒绝执行,不重新提交。重启后用新 nonce,不依赖旧实例的去重记录。网络超时表示结果可能未知;任何消息、工具副作用或控制请求都不能用新编号自动重试。
+
+## 应用授权
+
+1. `connect/start`:`{"client":{"id":"org.example.notes","name":"Notes","version":"1.0"}}`,返回 `{id,claim,url}`。id 最多 128 字符,只含字母、数字、点、下划线、连字符且以字母或数字开头;名称最多 80 字符,version 可省略、最多 64 字符。名称/版本不接受控制或双向覆盖字符。
+2. Cindy 在**本机**显示应用自报名称、编号及能力说明,由用户允许或取消。客户端无需打开返回的兼容网页才能触发弹窗。
+3. `connect/poll`:`{id,claim}`,返回 `{state:"waiting"|"denied"|"approved",token?}`;通过后才有 token。申请两分钟过期。`connect/cancel` 用同一组 id/claim 取消并撤销该申请已经签发的授权。
+4. 后续请求带 `Authorization: Bearer <token>`。`connect/revoke` 无参数,只撤销**当前令牌自己的授权**。
+
+应用名称、id、version 都是申请方自报的展示资料,不能证明安装包或发布者身份。相同 app id / 名称不会得到已有授权或会话;每次经用户允许产生独立、不可猜测的 bearer 凭据。名字不是认证依据,不按品牌自动批准。
+
+设置 → 远程连接 → 本机应用连接逐条显示应用和自报编号,每条可单独撤销。撤销同时失效令牌、恢复绑定、工具桥接与事件轮询,并关闭该授权的执行会话;其他授权保持可用。旧设置调用不带编号的“全部撤销”仍兼容。账号切换和退出会关闭本机 API;数据仍按 Cindy 的账号 owner 隔离。
+
+## 目录和会话操作
+
+| method | params | result / 语义 |
+|---|---|---|
+| `models` | `{}` | `{models:[{id,label,provider,providerLabel?,engine,model,efforts,defaultEffort?,images,isDefault}]}` |
+| `session/open` | `{sessionId,cwd,model,toolPolicy,tools,effort?,instructions?,resume?}` | `{sessionId,id,resumed}`;id 是供恢复使用的不透明句柄,不是原生线程 ID |
+| `send` | `{sessionId,parts,effort?}` | `{}` 表示接收发送请求,轮次结果随后由 events 返回 |
+| `steer` | `{sessionId,parts}` | 向正在运行的轮次插话;未运行返回 `NOT_RUNNING` |
+| `interrupt` | `{sessionId}` | 请求实际引擎停止;最终状态看 events |
+| `instructions` | `{sessionId,instructions}` | 更新追加说明,下一轮按原生恢复边界应用 |
+| `events` | `{sessionId,cursor}` | `{events:[{seq,event}],cursor}`;无新事件最多等待 20 秒 |
+| `tool/reply` | `{sessionId,callId,text,isError?}` | 回传该会话的一次客户端工具结果;重复或过期回传拒绝 |
+| `session/close` | `{sessionId}` | 关闭当前执行会话并释放等待工具,保留属于此授权的恢复绑定 |
+
+`models[].id` 唯一标识供应商 + 引擎 + 模型组合,客户端将其视为不透明值。`provider` 是稳定分组编号,`providerLabel` 是可选显示名,不从 label 解析路由;同名模型的不同来源不合并。目录来自当前已连接且可选的对话来源,不导出路由地址和凭据。空目录正常返回空数组,不悄悄更换来源。
+
+`sessionId` 是客户端自定的非空字符串,最多 128 字符;编号按授权隔离。`cwd` 为当前电脑上的现存绝对目录。`tools` 为至多 256 个 `{name,description,parameters}`,parameters 为 JSON Schema 对象;name 最多 64 字符,只含 `[A-Za-z0-9_-]` 且会话内唯一。新协议使用 `toolPolicy`:
+
+- `client-only`:仅调用该会话登记的客户端工具。它不代表工具本身只读,客户端仍负责业务确认和工具权限。
+- `native`:同时保留所选引擎的原生执行能力,能按当前系统用户权限读写文件、执行命令;**cwd 不是操作系统沙箱**。
+
+旧 v1 的 `access:"none"|"full"` 分别映射上述两种模式,仍可使用;同时传两者时必须一致。原生只读尚未声明,不能用提示词或 `client-only` 推断存在只读文件沙箱。
+
+`parts` 是 1–64 个 `{type:"text",text}` 或 `{type:"image",mimeType,data}`;图片 data 是 base64,只接受模型声明支持的 PNG/JPEG/WebP/GIF,单张解码最多 10 MiB。`client-only` 将以 `/` 开头的文本转义为字面消息,路径等普通内容仍可发送,不执行原生命令;`native` 保留既有引擎命令行为。模型、来源或引擎切换必须重新 open;相同模型可用原句柄恢复,不同模型返回新句柄和 `resumed:false`,客户端自行提供上下文交接,不重放旧工具或付费消息。
+
+## 事件和工具往返
+
+每个会话只安排一个有序事件消费者,初始 cursor 为 0,下一次请求使用已完整处理批次的返回 cursor。发送该 cursor 同时确认其之前事件可回收。事件有严格递增 seq;失去响应时可用**最后已处理**的 cursor 重新读取,不随意推进。不要并行提交相互矛盾的确认游标。
+
+| event.type | event.data |
+|---|---|
+| `text` / `thinking` | 增量字符串,不重复发最终全文快照 |
+| `host_tool` | `{id,name,arguments}`;id 是 callId,客户端执行自己的注册工具后回传 |
+| `tool_started` | `{id,name,arguments}`;引擎自带活动的投影,不要求客户端再执行 |
+| `tool_finished` | `{id,output,isError}` |
+| `usage` | `{input,cached,output}`;input 包括缓存读取和写入,按引擎的当轮用量或请求增量投影,不由客户端猜计费金额 |
+| `turn_end` | `{status:"completed"|"interrupted"|"failed",message?}` |
+
+每个运行会话都有服务端生成的内部 MCP URL 和独立令牌,不由客户端提交,不会通过公共 RPC 返回。三个引擎使用通用 `client` 命名空间,桥接只列出该会话登记的工具;`host_tool` 已代表该调用,不再从原生活动重复执行。其他授权的 MCP token、工具 callId、恢复句柄或 sessionId 都不能取得此会话的调用权。
+
+当前协议不转发原生人机确认:原生提问/计划批准会产生明确失败,不能替用户答应;需要交互的客户端应提供自己的交互工具。
+
+## 执行、存储与兼容
+
+`Maker.startLocalAgentSession` 复用三种引擎及既有内存 `Session`,由同一套发送、原生续段、终态归属、工具循环与关闭生命周期管理执行;不建立第二个 Agent 循环,也不写入 Cindy 的私人任务数据库或装载私人记忆。原生带 continuation claim 的 done 只是 SDK 段落边界,不能提前宣布客户端执行完成或接受下一轮发送。原生 cancelled 投影为 interrupted。
+
+Claude client-only 关闭原生 tools/settings/skills;Pi 仅开启客户端网关;Codex 使用独立模型工具目录、app-server 与原生历史配置,保留所选模型的窗口配置。client-only 不合入 Cindy 的其他 MCP。Cindy 固定身份、回答呈现、host system prompt 及既有动态段装配保持原样;插件花名册仍由原回调按工作目录、启用状态和账号可见性产生,通讯录说明沿用各引擎现有可用性判断。花名册与提示词不是工具授权;连接未注册的私人 MCP 仍不可调用,也不因此取得私人任务、记忆或供应商凭据。静态指引可能提及本连接未开放的能力,调用方须按本连接实际登记的工具与公开事件处理,不能仅凭文字假定能力已获授权。Codex native 排除自动继承的私有 MCP 连接与 Apps 账号连接,同时保留工作目录的原生技能、原生插件与执行能力,不复用 Review 的全量技能禁用策略。native 模式仍可读取工作目录和引擎原生配置;其文件访问受本机系统用户权限支配,API 隔离不是对同一系统用户下恶意程序的 OS 沙箱。
+
+关闭、撤销授权及晚到的启动结果以 account-boundary 原因关闭内存 Session,连同其持有的原生子执行收尾。无法确认进程退出时返回 `RUNTIME_CLOSE_UNCONFIRMED`,保留清理对象供宿主关闭重试;令牌及工具入口仍立即失效,不将不确定的停止报告为已经结束。
+
+持久授权存放在 owner-scoped `local-agent/grants.json`:只含令牌 SHA-256、账号范围、服务端授权 id、自报身份及归属此授权的恢复绑定。它不存令牌明文、供应商凭据或消息正文。写入及异常恢复复用 Main 的 `atomicWriteFileSync` / `readAtomicFileSync`,不另造 Windows 替换协议。profile 根 `local-agent/host.lock` 复用既有跨进程锁:同一 profile 只有一个发现端点和授权快照写入者,共库预览实例不能覆盖撤销结果;Maker 替换等待旧端点释放。账号持久范围与运行期的 owner generation 分开,切走再切回同一账号也不会复活旧的在途确认。
+
+新授权的临时输入和 Codex 运行历史配置位于 `local-agent/clients/<grant-hash>/`;Codex 的可重建模型工具目录仍在 `local-agent/codex-catalogs/`。其他引擎的原生转录由其原有适配器管理,API 只保存自己签发的恢复绑定,不暴露跨应用列举接口。
+
+授权文件由 schema 1 升到 2:校验旧文件后保留令牌哈希、授权 id、账号和绑定;首次写入前以独占创建保留 `grants.json.v1.bak`,新格式经临时文件原子替换。存量 v1 授权保留历史 `hhh` MCP 名称和旧原生存储定位,仅用于已存授权的恢复兼容;所有新连接都使用通用 namespace。旧字符串形式的 `client` 也保持支持,并按通用名称生成自报身份,不再限制品牌。
+
+不认识的版本或损坏文件拒绝加载并保留原文件,不清空重建。schema 1 的旧二进制不能读 schema 2;降级不能直接覆盖现有文件,应使用独立 profile。旧版备份只反映升级时状态,不包含之后新增/撤销的授权;不要将它当成无损降级或在撤销后自动恢复备份。
+
+会话上限 16,授权上限 32,申请上限 8;这些是当前实例的资源预算,不是按品牌分配。请求最大 16 MiB,单会话事件队列最大 8 MiB,事件每批通常不超过 1 MiB(单个大事件可独占一批),空闲会话三分钟回收,单会话最多 64 个待回传工具。超限会返回明确错误或收尾该会话,不转发到另一个供应商。协议不自动重试模型和工具操作。
+
+常见可判断错误:`UNAUTHORIZED`(重新授权)、`INSTANCE_CHANGED`(重新发现)、`MODEL_UNAVAILABLE`(重新选择有效来源)、`RESUME_UNAVAILABLE`(新会话并交接上下文)、`SESSION_UNAVAILABLE`(原会话已关闭或不属于此授权)、`UNSUPPORTED_ACCESS`(策略不支持/矛盾)、`ID_REUSED` / `REQUEST_EXPIRED`(未重复执行)、`GRANT_STORE_INVALID`(保留原文件并检查版本/存储)。
+
+错误 code 保持稳定,展示文案、原生确认及兼容结果页通过 Cindy 当前语言的五语资源提供。设置 IPC 复用受信顶层窗口校验与统一 IPC 错误协议;等待原生确认后再次校验发起窗口及 owner generation,不向 Renderer 返回原始存储异常。
+
+此入口只管理当前电脑的本机应用,不执行 SSH 工作区任务,不加入 device-link 的通用 invoke/push 白名单,也未新增 Mobile 入口。远程管理此类授权需要另行定义目标电脑的原生确认和授权范围,不能把本机 handler 隐式开放给远端。
+
+## 验证入口
+
+- `apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts`:真实 loopback、独立示例进程、同编号并行、越权拒绝、单项撤销、重启恢复及旧存储迁移;模型执行可注入,不能把它说成真实供应商验收。
+- `runtime.test.ts`:目录和事件不重复投影,通用及历史 namespace。
+- `maker-core` 对应适配器:Claude SDK 隔离选项;Pi 真二进制 + 本机模型响应夹具;Codex 真 app-server(需 `CINDY_CODEX_TEST_BINARY`)。
+- `apps/desktop/scripts/fixtures/local-agent/`:真实设置组件,多应用单项撤销、取消、失败、手机宽度、五种语言与深浅主题;宿主接口由场景提供,不替代原生授权与真实 IPC 验收。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index c56072f607..a86e6448f4 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -979,6 +979,9 @@ export interface AgentDeps {
codexHome?: string,
) => Promise<CodexContextWindowInfo | null>;
+ /** Private native catalog with executable edit tools removed for a host-owned conversation. */
+ prepareCodexHostToolCatalog?: (modelId: string, contextWindow: number | null) => Promise<string>;
+
/**
* Resolve verified catalog capacity for a concrete (provider, model) route.
* Return null for unknown, ambiguous, or derived fallback metadata. Do not use
@@ -1856,7 +1859,21 @@ export interface DeviceHostedGuestProvider {
/** 受邀者会话的 Claude Code 请求带上的路由令牌请求头(本机 proxy 据此只走分享的供应商)。 */
export const DEVICE_HOSTED_GUEST_ROUTE_HEADER = 'x-cindy-guest-route';
+/** Main-process capability: symbols cannot cross the renderer/device IPC boundary. */
+export const LOCAL_AGENT_CLIENT = Symbol('local-agent-client');
+
+export interface LocalAgentClient {
+ url: string;
+ token: string;
+ hostToolsOnly: boolean;
+ /** Host-issued namespace; old stored grants may retain their historical name. */
+ mcpName?: string;
+ /** Owner/grant-scoped runtime storage supplied only by Desktop Main. */
+ storageDirectory?: string;
+}
+
export interface StartSessionOptions {
+ [LOCAL_AGENT_CLIENT]?: LocalAgentClient;
/**
* Business 层 session id (host 调用 maker.createSession 时传的 opts.id, 由
* maker.ts 透传到这里)。agent 把它放到 McpProviderContext.sessionId, 让 MCP
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts
index 5301422c84..f6d71cd252 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/bot-own-skills-mount.test.ts
@@ -13,6 +13,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { AgentDeps } from '../../base-agent.js';
+import { LOCAL_AGENT_CLIENT } from '../../base-agent.js';
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -62,7 +63,10 @@ function createDeps(): AgentDeps {
};
return {
auth,
- runtimeConfig: { systemPrompt: 'GLOBAL CINDY HOST PROMPT' },
+ runtimeConfig: {
+ systemPrompt: 'GLOBAL CINDY HOST PROMPT',
+ answerDeliveryPrompt: 'CINDY ANSWER DELIVERY FIXTURE',
+ },
binaryPath: process.execPath,
logger: createNoopLogger(),
getGhostRosterPrompt: vi.fn(() => 'GLOBAL GHOST ROSTER'),
@@ -99,6 +103,7 @@ async function startBotSession(input: {
reviewMode?: boolean;
remote?: boolean;
ordinary?: boolean;
+ localHostOnly?: boolean;
managed?: boolean;
disabled?: boolean;
allowManaged?: boolean;
@@ -130,6 +135,11 @@ async function startBotSession(input: {
sessionId: 'session-bot-skills',
model: 'claude-opus-4-6',
workingDir,
+ ...(input.localHostOnly !== undefined ? {
+ [LOCAL_AGENT_CLIENT]: {url:'http://127.0.0.1:12345/mcp/fixture',token:'fixture-token',hostToolsOnly:input.localHostOnly,mcpName:'notebook'},
+ makerMemoryEnabled: false,
+ makerMemoryIndexSnapshot: 'PRIVATE_MEMORY_INDEX_CANARY',
+ } : {}),
...(input.remote ? { remoteHostId: 'remote-bot-host' } : {}),
permissionMode: 'acceptEdits',
botProfilePrompt: 'BOT SOUL',
@@ -165,6 +175,8 @@ async function startBotSession(input: {
const options = (input.remote ? remoteOptions : sdkMock.query.mock.calls.at(-1)?.[0]?.options) as
| {
plugins?: Array<{ type: string; path: string }>;
+ tools?: string[];
+ mcpServers?: Record<string, {type:string;url:string;headers?:Record<string,string>}>;
settingSources?: string[];
disallowedTools?: string[];
strictMcpConfig?: boolean;
@@ -176,6 +188,33 @@ async function startBotSession(input: {
return options;
}
+// 测试价值:实际 adapter 的 SDK 启动选项是 Claude 工具隔离执行点;普通伙伴挂载用例不覆盖本机接入。
+// 最小输入:一个受管技能与独立客户端 MCP;tier unit,无进程或网络。
+// 2026-10-22 维护者裁决:接入保持 Cindy 提示词装配,权限由实际工具面约束。
+// 普通任务对照锁住完整追加段,不复制提示词常量;禁用记忆仍不得带出已有索引。
+it('local client-only sessions expose their own MCP namespace, while native policy retains engine tools', async () => {
+ const ordinary = await startBotSession({ordinary:true,managed:true});
+ const partner = await startBotSession({ordinary:true,managed:true,localHostOnly:true});
+ expect(partner.tools).toEqual([]);
+ expect(partner.settingSources).toEqual([]);
+ expect(partner.plugins ?? []).toEqual([]);
+ expect(partner.strictMcpConfig).toBe(true);
+ expect(Object.keys(partner.mcpServers ?? {})).toEqual(['notebook']);
+ expect(partner.mcpServers?.notebook.headers?.Authorization).toBe('Bearer fixture-token');
+ const prompt = partner.systemPrompt?.append ?? '';
+ expect(prompt).toContain('GLOBAL CINDY HOST PROMPT');
+ expect(prompt).toContain('CINDY ANSWER DELIVERY FIXTURE');
+ // Existing enabled-but-unregistered Contacts semantics remain unchanged.
+ expect(prompt).not.toContain('Smart Contacts');
+ expect(prompt).toContain('GLOBAL GHOST ROSTER');
+ expect(prompt).toContain('GLOBAL USER PROMPT');
+ expect(prompt).not.toContain('PRIVATE_MEMORY_INDEX_CANARY');
+ expect(prompt).toBe(ordinary.systemPrompt?.append);
+ const delegated = await startBotSession({ordinary:true,localHostOnly:false});
+ expect(delegated.tools).toBeUndefined();
+ expect(delegated.systemPrompt?.append).toBe(prompt);
+});
+
afterEach(async () => {
await Promise.all(liveHandles.splice(0).map((handle) => handle.close()));
// The session owns its plugin staging directories. Wait for asynchronous
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index e8533f5ac1..255c8a87e6 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -60,6 +60,7 @@ import Anthropic, { APIError } from '@anthropic-ai/sdk';
import {
BaseAgent,
+ LOCAL_AGENT_CLIENT,
OneShotError,
AgentNotAuthenticatedError,
AgentStartupStoppedError,
@@ -1892,6 +1893,13 @@ export class ClaudeCodeAgent extends BaseAgent {
if (currentQ === q) nonHarnessMcpServerNames = fallbackNames;
};
const buildMcpServers = (): Record<string, McpServerConfig> | undefined => {
+ const client = opts[LOCAL_AGENT_CLIENT];
+ if (client) {
+ hostMcpServerNames = new Set([client.mcpName ?? 'client']);
+ registeredMcpServerNames = hostMcpServerNames;
+ nonHarnessMcpServerNames = hostMcpServerNames;
+ return { [client.mcpName ?? 'client']: { type: 'http', url: client.url, headers: { Authorization: `Bearer ${client.token}` } } };
+ }
if (hosted) {
// 设备托管:只用经隧道的服务——cindy_exec(文件与命令)+ 任务所在电脑提供的 Cindy 工具。
const headers = { Authorization: `Bearer ${hosted.tunnelToken}` };
@@ -4319,7 +4327,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// Re-read at each Query boundary: plugin uninstall/disable may remove the
// previous projection while the conversation itself remains open.
// 受邀者(另一个账号)的托管会话不带本机安装的托管技能(属于本机用户与其组织)。
- const managedSkills = !reviewMode && !hosted?.guest && this.deps.getManagedSkills
+ const managedSkills = !reviewMode && !hosted?.guest && !opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly && this.deps.getManagedSkills
? await this.deps.getManagedSkills() : [];
const managedDisabledPaths = currentDisabledSkillLaunchPaths(managedDisabledSkillLaunch);
const allowedManagedSkills = resolveAllowedManagedSkills(managedSkills, managedSkillGrants, managedDisabledPaths);
@@ -4446,7 +4454,8 @@ export class ClaudeCodeAgent extends BaseAgent {
canUseTool: sdkCanUseTool,
// Bot MCP selection is explicit; native delegation remains available.
// 设备托管:只用经隧道的 MCP(本机用户 / 项目里的 MCP 启动命令会在本机执行)。
- ...(opts.botRuntimeProfile || hosted ? { strictMcpConfig: true } : {}),
+ ...(opts.botRuntimeProfile || hosted || opts[LOCAL_AGENT_CLIENT] ? { strictMcpConfig: true } : {}),
+ ...(opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly ? { tools: [] } : {}),
// 设备托管:自带文件与命令工具只能操作本机,关掉,由 cindy_exec 顶替;
// 另含 host 路由表关闭的自带工具(见 claudeDisallowedTools)。
...(claudeDisallowedTools.length > 0
@@ -4456,7 +4465,7 @@ export class ClaudeCodeAgent extends BaseAgent {
...(hosted?.guest ? { tools: [...DEVICE_HOSTED_GUEST_CLAUDE_TOOLS] } : {}),
// 设备托管:个人配置(用户级设置、hooks)属于任务所在电脑,不加载本机用户级设置;
// 项目级设置来自同步过来的影子目录(只保留权限规则)。
- settingSources: reviewMode || !!opts.botRuntimeProfile
+ settingSources: reviewMode || !!opts.botRuntimeProfile || opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly
? []
: hosted ? ['project', 'local'] : ['user', 'project', 'local'],
// Settings (SDK "flag settings" 层, 优先级最高 — 覆盖 user/project/local 文件层):
diff --git a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts
index f050c21b80..97243e586f 100644
--- a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts
+++ b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.native.test.ts
@@ -19,6 +19,7 @@ import { describe, expect, it } from 'vitest';
import type { Logger } from '../../../interfaces/logger.js';
import type { DeviceHostedSession } from '../../base-agent.js';
+import { LOCAL_AGENT_CLIENT } from '../../base-agent.js';
import { CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES, listCodexFeatures } from '../device-hosted-guest.js';
import { CodexAgent } from '../index.js';
@@ -47,7 +48,11 @@ async function listFiles(dir: string): Promise<string[]> {
}
describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server', () => {
- it.each([true, false])('keeps this computer\'s Codex home out of the session (guest: %s)', async (guest) => {
+ // 本机应用复用真实 app-server 夹具;历史 hhh namespace 验证 v1 兼容,不读取用户凭据。
+ it.each([true, false, 'local-host-only', 'local-native'] as const)('keeps this computer\'s Codex home out of the session (guest: %s)', async (variant) => {
+ const guest = variant === true;
+ const localHostOnly = variant === 'local-host-only';
+ const localClient = localHostOnly || variant === 'local-native';
const root = realpathSync.native(await mkdtemp(path.join(tmpdir(), 'cindy-codex-guest-native-')));
const hostHome = path.join(root, 'host-codex-home');
const guestHome = path.join(root, 'remote-agent', 'guest-homes', 'c1');
@@ -67,15 +72,29 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
await mkdir(path.join(root, 'remote-agent', '.git'), { recursive: true });
await writeFile(path.join(root, 'remote-agent', 'AGENTS.md'), 'HOST_ANCESTOR_CANARY');
await writeFile(path.join(workingDir, 'AGENTS.md'), 'SHADOW_CANARY');
+ const projectSkill = path.join(workingDir, '.agents', 'skills', 'project-native');
+ await mkdir(projectSkill, { recursive: true });
+ await writeFile(path.join(projectSkill, 'SKILL.md'), '---\nname: project-native\ndescription: PROJECT_NATIVE_SKILL_CANARY\n---\nA project skill for the explicitly selected workspace.');
const bodies: string[] = [];
+ let hostToolCalls = 0;
const server: Server = createServer((req, res) => {
let body = '';
req.on('data', (chunk) => { body += chunk; });
req.on('end', () => {
+ if (req.url?.includes('/mcp')) {
+ if (req.method !== 'POST') { res.writeHead(405).end(); return; }
+ const rpc=JSON.parse(body);
+ if(rpc.id===undefined){res.writeHead(202).end();return;}
+ if (rpc.method === 'tools/call') hostToolCalls++;
+ const result=rpc.method==='initialize'?{protocolVersion:'2025-03-26',capabilities:{tools:{}},serverInfo:{name:'hhh',version:'1'}}:rpc.method==='tools/list'?{tools:[{name:'echo',description:'HHH host echo',inputSchema:{type:'object',properties:{}}}]}:rpc.method==='tools/call'?{content:[{type:'text',text:'HHH_HOST_TOOL_RESULT'}]}:{};
+ res.writeHead(200,{'content-type':'application/json'}).end(JSON.stringify({jsonrpc:'2.0',id:rpc.id,result}));return;
+ }
if (!req.url?.includes('/responses')) { res.writeHead(404).end('{}'); return; }
bodies.push(body);
- const item = { type: 'message', id: 'msg-1', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'DONE', annotations: [] }] };
+ const item = localHostOnly && bodies.length === 1
+ ? { type: 'function_call', id: 'fc-1', call_id: 'call-1', namespace: 'mcp__hhh', name: 'echo', arguments: '{}', status: 'completed' }
+ : { type: 'message', id: 'msg-1', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'DONE', annotations: [] }] };
const events = [
{ type: 'response.created', response: { id: 'r1', status: 'in_progress', output: [] } },
{ type: 'response.output_item.done', output_index: 0, item },
@@ -97,11 +116,21 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
await new Promise((resolve) => setTimeout(resolve, 1_000));
const spawnContexts: Array<{ accountHostKey?: string; runtimeCodexHome?: string; deviceHostedGuestProviderId?: string }> = [];
- const registeredRoutes: Array<{ smartSubagentRoutes?: unknown; subagentRoute?: unknown }> = [];
+ const registeredRoutes: Array<{ threadId: string; text: string; smartSubagentRoutes?: unknown; subagentRoute?: unknown }> = [];
const agent = new CodexAgent({
binaryPath: binaryPath!,
logger,
- runtimeConfig: {},
+ runtimeConfig: {
+ systemPrompt: 'CINDY_HOST_IDENTITY_CANARY',
+ answerDeliveryPrompt: 'CINDY_ANSWER_DELIVERY_CANARY',
+ },
+ getGhostRosterPrompt: () => 'WORKDIR_GHOST_ROSTER_CANARY',
+ getContactsPromptState: () => 'enabled',
+ prepareCodexHostToolCatalog: async modelId => {
+ const target=path.join(root,'host-tool-models.json');
+ await writeFile(target,JSON.stringify({models:[{slug:modelId,display_name:modelId,description:null,supported_reasoning_levels:[],shell_type:'unified_exec',visibility:'none',supported_in_api:true,priority:99,base_instructions:'Use the available host tools.',include_skills_usage_instructions:false,include_plugin_usage_instructions:false,include_apps_usage_instructions:false,supports_reasoning_summary_parameter:true,default_reasoning_summary:'auto',support_verbosity:false,truncation_policy:{mode:'bytes',limit:10000},context_window:272000,max_context_window:272000,effective_context_window_percent:95,experimental_supported_tools:[],apply_patch_tool_type:null,supports_search_tool:false}]}));
+ return target;
+ },
// 供应商配置随 spawn 参数下发(与 Desktop 一样),不依赖 CODEX_HOME 里的 config.toml。
prepareCodexExtraSpawnConfig: async (_providers, ctx) => {
spawnContexts.push(ctx);
@@ -111,16 +140,20 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
'-c', `model_providers.fixture={ name = "Fixture", base_url = "${endpoint}", wire_api = "responses", requires_openai_auth = false, request_max_retries = 0, supports_websockets = false }`,
'-c', 'check_for_update_on_startup=false',
'-c', 'analytics.enabled=false',
+ // A private Cindy MCP must never enter an external client's model request.
+ ...(localClient ? ['-c', `mcp_servers.private_canary={url="${endpoint}/mcp",enabled=true}`] : []),
// 本机用户开了智能子代理调配时 host 会带上的配置;受邀者的 app-server 不接受。
'-c', 'features.multi_agent_v2.expose_spawn_agent_model_overrides=true',
],
extraEnv: {},
- codexProxyActive: true,
+ // Cover both existing delivery paths: client-only registers its prompt
+ // for the host HTTP proxy; native sends developerInstructions inline.
+ codexProxyActive: !localClient || localHostOnly,
smartSubagentRoutes: [{ providerId: 'other-provider', catalogModel: 'other-model' }],
};
},
- registerCodexSystemPromptForThread: ({ smartSubagentRoutes, subagentRoute }) => {
- registeredRoutes.push({ smartSubagentRoutes, subagentRoute });
+ registerCodexSystemPromptForThread: ({ threadId, text, smartSubagentRoutes, subagentRoute }) => {
+ registeredRoutes.push({ threadId, text, smartSubagentRoutes, subagentRoute });
},
auth: {
getState: async () => ({ authenticated: true }),
@@ -157,7 +190,11 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
workingDir,
permissionMode: 'bypassPermissions',
makerMemoryEnabled: false,
- deviceHosted,
+ ...(localClient ? {
+ userPrompt: 'CLIENT_INSTRUCTIONS_CANARY',
+ makerMemoryIndexSnapshot: 'PRIVATE_MEMORY_INDEX_CANARY',
+ } : {}),
+ ...(localClient ? {[LOCAL_AGENT_CLIENT]:{url:`${endpoint}/mcp`,token:'fixture',hostToolsOnly:localHostOnly,mcpName:'hhh',storageDirectory:path.join(sessionRoot,'client-a')}} : {deviceHosted}),
});
const done = (async () => {
for await (const event of handle.events()) {
@@ -177,10 +214,71 @@ describe.skipIf(!binaryPath)('Codex device-hosted guest with a real app-server',
const enabledOutsideAllowlist = threadFeatures
.filter((feature) => feature.enabled && feature.stage !== 'removed' && !CODEX_DEVICE_HOSTED_GUEST_KEPT_FEATURES.has(feature.name))
.map((feature) => feature.name);
- if (guest) expect(enabledOutsideAllowlist).toEqual([]);
+ if (guest || localHostOnly) expect(enabledOutsideAllowlist).toEqual([]);
else expect(enabledOutsideAllowlist.length).toBeGreaterThan(0);
// 两种会话里干活要用的功能都开着(命令、shell 快照、看图、子代理)。
const enabled = new Set(threadFeatures.filter((feature) => feature.enabled).map((feature) => feature.name));
+ if (localClient) {
+ // 2026-10-22 maintainer decision: the app calls Cindy with its existing
+ // prompt assembly. Metadata/instructions do not grant private MCP access.
+ // This fixture does not run the Desktop proxy, so inspect the actual
+ // production registration for that channel, not its uninjected fake upstream.
+ const prompt = localHostOnly
+ ? registeredRoutes.find(entry => entry.threadId === handle.id)?.text ?? ''
+ : bodies[0];
+ for (const segment of [
+ 'CINDY_HOST_IDENTITY_CANARY', 'CINDY_ANSWER_DELIVERY_CANARY',
+ 'CLIENT_INSTRUCTIONS_CANARY', 'WORKDIR_GHOST_ROSTER_CANARY', 'Smart Contacts',
+ ]) expect(prompt).toContain(segment);
+ expect(prompt).not.toContain('PRIVATE_MEMORY_INDEX_CANARY');
+ expect(bodies.join('')).not.toContain('PRIVATE_MEMORY_INDEX_CANARY');
+ expect(bodies.join('')).not.toContain('private_canary');
+ }
+ if (variant === 'local-native') {
+ expect(enabled.has('shell_tool') || enabled.has('unified_exec')).toBe(true);
+ expect(JSON.stringify(JSON.parse(bodies[0]).tools)).toMatch(/\bhhh\b/);
+ expect(bodies.join('')).not.toContain('HOST_GLOBAL_CANARY');
+ expect(bodies.join('')).toContain('PROJECT_NATIVE_SKILL_CANARY');
+ await handle.close();
+ return;
+ }
+ if(localHostOnly){
+ expect(hostToolCalls).toBe(1);
+ expect(bodies.at(-1)).toContain('HHH_HOST_TOOL_RESULT');
+ const request=JSON.parse(bodies.at(-1)!);
+ const names=(request.tools ?? []).flatMap((tool:{name?:string;type?:string;tools?:Array<{name:string}>})=>tool.type==='namespace'?(tool.tools ?? []).map(child=>`${tool.name}__${child.name}`):[tool.name ?? tool.type]);
+ // Native MCP discovery helpers can only inspect this session's HHH
+ // server. Native interactive input is explicitly dismissed by the Host.
+ expect(names).toContain('mcp__hhh__echo');
+ expect(names.filter((name:string)=>!['mcp__hhh__echo','list_mcp_resources','list_mcp_resource_templates','read_mcp_resource','request_user_input'].includes(name))).toEqual([]);
+ expect(['shell_tool','shell_snapshot','view_image','multi_agent'].filter(name=>enabled.has(name))).toEqual([]);
+ expect(bodies.join('')).not.toMatch(/HOST_GLOBAL_CANARY|HOST_ANCESTOR_CANARY|SHADOW_CANARY/);
+ // A second custom model must get a fresh native catalog snapshot. Sharing
+ // the earlier process would silently restore the native fallback tools.
+ const other = await agent.startSession({sessionId:'owner-native',model:'custom-host-fixture',workingDir,
+ permissionMode:'bypassPermissions',makerMemoryEnabled:false,
+ [LOCAL_AGENT_CLIENT]:{url:`${endpoint}/mcp`,token:'fixture',hostToolsOnly:true,mcpName:'hhh',storageDirectory:path.join(sessionRoot,'client-a')}});
+ const finished=(async()=>{for await(const event of other.events()){
+ if(event.type==='error')throw Error(JSON.stringify(event));if(event.type==='done')return;
+ }})();
+ await other.send({type:'user',content:'hello'},{throwOnStartFailure:true});await finished;
+ const second=JSON.parse(bodies.at(-1)!);
+ expect(JSON.stringify(second.tools)).not.toMatch(/apply_patch|exec_command|write_stdin/);
+ expect([...hosts.keys()].filter(key=>key.includes(':host-tools-only:')).length).toBe(2);
+ // An unrelated grant using the same model must not share the app-server or native history.
+ // Retain the historical namespace here to cover v1 grants as well as custom names in Claude/Pi.
+ const unrelated = await agent.startSession({sessionId:'other-client',model:'gpt-5.5',workingDir,
+ permissionMode:'bypassPermissions',makerMemoryEnabled:false,
+ [LOCAL_AGENT_CLIENT]:{url:`${endpoint}/mcp`,token:'fixture',hostToolsOnly:true,mcpName:'hhh',storageDirectory:path.join(sessionRoot,'client-b')}});
+ const unrelatedDone=(async()=>{for await(const event of unrelated.events()){
+ if(event.type==='error')throw Error(JSON.stringify(event));if(event.type==='done')return;
+ }})();
+ await unrelated.send({type:'user',content:'hello'},{throwOnStartFailure:true});await unrelatedDone;
+ expect([...hosts.keys()].filter(key=>key.includes(':host-tools-only:')).length).toBe(3);
+ expect([...hosts.keys()].some(key=>key.includes(path.join(sessionRoot,'client-b','native-history')))).toBe(true);
+ await unrelated.close();
+ await other.close();await handle.close();return;
+ }
expect(['shell_tool', 'unified_exec', 'shell_snapshot', 'view_image', 'multi_agent'].filter((name) => !enabled.has(name))).toEqual([]);
await handle.close();
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index e0e9f19ad4..22e68a0db2 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -46,6 +46,7 @@ import { readAccountRateLimitsWithRefresh } from './app-server/account-rate-limi
import {
BaseAgent,
+ LOCAL_AGENT_CLIENT,
INHERITED_CAPABILITY_SELECTION,
PINNED_SKILL_INVOCATION,
CodexResumePreparationBlockedError,
@@ -2568,6 +2569,7 @@ export class CodexAgent extends BaseAgent {
hostPurpose?: 'control-plane' | 'review' | 'custom-context';
/** Archive-only control host: native storage RPCs, no turns, no MCP bridge. */
nativeStorageOnly?: boolean;
+ localToolCatalog?: string;
customContextModel?: string;
customContextWindow?: number;
sqliteHome?: string;
@@ -2806,6 +2808,7 @@ assertRouteCurrent();
opts.nativeStorageOnly,
opts.deviceHostedGuestSessionId,
opts.deviceHostedGuestModelIds,
+ opts.localToolCatalog,
).finally(() => {
// 成功: this.hosts 已赋值, 后续走快路径; 失败: 清掉 promise 让下次调用能重试
const current = this.hostPromises.get(key);
@@ -3057,6 +3060,7 @@ assertRouteCurrent();
nativeStorageOnly?: boolean,
deviceHostedGuestSessionId?: string,
deviceHostedGuestModelIds?: readonly string[],
+ localToolCatalog?: string,
): Promise<AppServerHost> {
const seq = (this.createHostSeqByKey.get(key) ?? 0) + 1;
this.createHostSeqByKey.set(key, seq);
@@ -3183,7 +3187,7 @@ assertRouteCurrent();
...(!remoteHostId && historyHome ? { runtimeCodexHome: historyHome } : {}),
// 受邀者任务的 app-server 与账号会话一样走按 host 分开的 proxy(鉴权注入方式冻结在这个 host 上),
// 不改写本机用户任务共用的 proxy 状态。
- ...(key.startsWith('local-account:') || key.startsWith(LOCAL_GUEST_HOST_PREFIX) || deviceHostedGuestProviderId
+ ...(key.startsWith('local-account:') || key.startsWith(LOCAL_GUEST_HOST_PREFIX) || deviceHostedGuestProviderId || localToolCatalog
? { accountHostKey: `${key}:${generation}` } : {}),
credentialMode: spawnCredentialMode,
...(localAuthPolicy === 'isolated'
@@ -3296,6 +3300,7 @@ assertRouteCurrent();
break;
}
if (!remoteHostId && sqliteHome) extraArgs.push('-c', `sqlite_home=${JSON.stringify(sqliteHome)}`);
+ if (localToolCatalog) extraArgs.push('-c', `model_catalog_json=${JSON.stringify(localToolCatalog)}`);
let externalAuth: CodexExternalAuth | undefined;
const requireEphemeralAuth = !remoteHostId && (localAuthPolicy === 'isolated'
|| (!!historyHome && path.resolve(historyHome) !== path.resolve(env.CODEX_HOME ?? '')));
@@ -5036,7 +5041,7 @@ assertRouteCurrent();
// Windows Review requires 0.156+ and exposes flat function tools. The legacy
// ordinary provider gate concerns namespace tools, not these scoped reads.
...(reviewMode && process.platform === 'win32' ? REVIEW_READ_TOOLS : []),
- ...(!reviewMode && shouldRegisterAskUserDynamicTool(opts) ? [ASK_USER_DYNAMIC_TOOL] : []),
+ ...(!reviewMode && !opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly && shouldRegisterAskUserDynamicTool(opts) ? [ASK_USER_DYNAMIC_TOOL] : []),
];
const accountProviderId = this.deps.isCodexAccountProvider?.(opts.providerId) ? opts.providerId! : undefined;
const accountSessionHost = !opts.remoteHostId && (accountProviderId !== undefined || this.deps.isolateCodexAccountSessions === true);
@@ -5107,11 +5112,21 @@ assertRouteCurrent();
// 受邀者:CODEX_HOME 换成远程 Agent 运行根下的受邀者目录(本机用户的 AGENTS.md、配置、技能与
// 历史都不在这里)。登录经既有的 token 桥从本机只读取得,受邀者目录用 ephemeral 凭证存储,
// 不复制也不在这里刷新本机的 auth.json;也不按 id 到本机的 Codex 历史里查找线程。
+ const localToolCatalog = opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly
+ ? await this.deps.prepareCodexHostToolCatalog?.(opts.model ?? '', initialCustomContextWindow) : undefined;
+ if (opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly && !localToolCatalog) throw new Error('Host-owned conversations require an isolated native tool catalog.');
+ const localClient = opts[LOCAL_AGENT_CLIENT];
+ const localApplicationHome = localClient?.storageDirectory
+ ? path.join(localClient.storageDirectory, 'native-history')
+ : localToolCatalog ? path.join(path.dirname(localToolCatalog), 'native-history') : undefined;
+ if (localApplicationHome) await fs.mkdir(localApplicationHome, {recursive:true,mode:0o700});
const guestCodexHome = hosted && hostedGuest && hosted.guestHome
? path.join(hosted.guestHome, 'codex')
: undefined;
if (guestCodexHome) await fs.mkdir(guestCodexHome, { recursive: true, mode: 0o700 });
- const sessionStorage = guestCodexHome
+ const sessionStorage = localApplicationHome
+ ? {historyHome:localApplicationHome,sqliteHome:localApplicationHome}
+ : guestCodexHome
? { historyHome: guestCodexHome, sqliteHome: guestCodexHome }
: !opts.remoteHostId && opts.resumeSessionId
? await this.deps.resolveCodexThreadStorage?.(opts.resumeSessionId)
@@ -5124,7 +5139,7 @@ assertRouteCurrent();
reviewMode, customContext: usesCustomContextHost, storage: sessionStorage, policy: localAuthPolicy,
environmentIdentity: companionEnvironment?.identity,
...(guestCodexHome ? { guestSession: true } : {}),
- });
+ }) + (localToolCatalog ? `:host-tools-only:${opts.model ?? ''}` : '');
let currentHostKey = resolveSessionHostKey();
let releaseHostBindingLease: (() => void) | null = null;
const acquireHostBindingLeaseIfNeeded = (): void => {
@@ -5145,6 +5160,7 @@ assertRouteCurrent();
if (!routeSelection.isCurrent()) throw new CodexRouteSelectionChangedError();
acquireHostBindingLeaseIfNeeded();
return await this.getHost(opts.remoteHostId, credentialMode, {
+ ...(localToolCatalog ? {keyOverride:currentHostKey,localToolCatalog} : {}),
...(companionEnvironment ? { keyOverride: currentHostKey } : {}),
...(accountProviderId ? { providerId: accountProviderId } : {}),
...(sessionSqliteHome ? { sqliteHome: sessionSqliteHome } : {}),
@@ -5444,15 +5460,17 @@ assertRouteCurrent();
const buildLocalCapabilityIsolationConfig = async (keep?: {
skill: (skillPath: string, scope?: SkillMetadata['scope']) => boolean;
mcpServer: (serverName: string) => boolean;
+ plugin?: (pluginId: string) => boolean;
+ allSkills?: true;
}): Promise<Record<string, unknown>> => {
- const { skills, errors } = await this.listSkillsForHost(
+ const { skills, errors } = keep?.allSkills ? { skills: [], errors: [] } : await this.listSkillsForHost(
host,
opts.workingDir,
false,
CRITICAL_THREAD_RPC_TIMEOUT_MS,
);
const unscopedSkillError = errors.find((error) => !error.path);
- if (unscopedSkillError) throw new Error(unscopedSkillError.message);
+ if (unscopedSkillError && !keep?.skill('')) throw new Error(unscopedSkillError.message);
const configResponse = await host.request<{ config?: Record<string, unknown> }>(
Method.ConfigRead,
@@ -5531,9 +5549,9 @@ assertRouteCurrent();
] = false;
}
for (const pluginId of pluginIds) {
- isolationConfig[
- `plugins.${quoteReviewConfigSegment(pluginId)}.enabled`
- ] = false;
+ if (!keep?.plugin?.(pluginId)) {
+ isolationConfig[`plugins.${quoteReviewConfigSegment(pluginId)}.enabled`] = false;
+ }
const pluginMcp = asRecord(asRecord(configuredPlugins[pluginId]).mcp_servers);
for (const [serverName, serverConfig] of Object.entries(pluginMcp)) {
if (!hasCodexMcpTransport(serverConfig)) continue;
@@ -5544,20 +5562,25 @@ assertRouteCurrent();
}
return isolationConfig;
};
- if (reviewMode) {
+ if (reviewMode || opts[LOCAL_AGENT_CLIENT]) {
try {
- assertCurrentHost('Review capability isolation');
- const reviewCapabilityConfig = await buildLocalCapabilityIsolationConfig();
+ assertCurrentHost('local capability isolation');
+ // Native execution retains its project Skills and installed native plugins.
+ // Only the automatically inherited credential-bearing MCP connections are excluded.
+ const nativeClient = opts[LOCAL_AGENT_CLIENT] && !opts[LOCAL_AGENT_CLIENT]!.hostToolsOnly;
+ const reviewCapabilityConfig = await buildLocalCapabilityIsolationConfig(nativeClient
+ ? { skill: () => true, plugin: () => true, mcpServer: () => false, allSkills: true }
+ : undefined);
capabilityRoutingConfig = {
...capabilityRoutingConfig,
...reviewCapabilityConfig,
};
- assertCurrentHost('Review capability isolation');
+ assertCurrentHost('local capability isolation');
} catch (error) {
releaseHostBindingLeaseIfNeeded();
if (error instanceof CodexRouteSelectionChangedError) throw error;
throw new Error(
- `Cannot start Codex Review safely because Cindy could not disable local Skills, plugins, and MCP servers: ${error instanceof Error ? error.message : String(error)}`,
+ `Cannot prepare this Codex session's capability scope: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
@@ -5602,6 +5625,13 @@ assertRouteCurrent();
return out;
};
const readSessionMcpConfig = (): Record<string, unknown> => {
+ const client = opts[LOCAL_AGENT_CLIENT];
+ if (client) return {
+ [`mcp_servers.${client.mcpName ?? 'client'}.url`]: client.url,
+ [`mcp_servers.${client.mcpName ?? 'client'}.http_headers`]: { Authorization: `Bearer ${client.token}` },
+ [`mcp_servers.${client.mcpName ?? 'client'}.enabled`]: true,
+ [`mcp_servers.${client.mcpName ?? 'client'}.default_tools_approval_mode`]: 'approve',
+ };
if (hosted) return readHostedMcpConfig();
const config = host.getSessionMcpConfig(opts.sessionInstanceId, { vendorOptions: vo });
if (opts.remoteHostId && opts.botRuntimeProfile?.mcpPolicy
@@ -5610,7 +5640,22 @@ assertRouteCurrent();
}
return config;
};
- let botMcpConfig: Record<string, unknown> = {};
+ let botMcpConfig: Record<string, unknown> = opts[LOCAL_AGENT_CLIENT] ? { 'features.apps': false } : {};
+ if (opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly) {
+ botMcpConfig.model_catalog_json = localToolCatalog;
+ const features = await listCodexFeatures(cursor => host.request(Method.ExperimentalFeatureList, { cursor, limit: 100 }));
+ const infrastructure = new Set(['secret_auth_storage', 'enable_request_compression', 'system_proxy_fallback', 'content_item_kinds', 'compaction_image_budget']);
+ for (const feature of features) {
+ if (infrastructure.has(feature.name) || feature.stage === 'removed' || feature.stage === 'deprecated' && !feature.enabled) continue;
+ botMcpConfig[`features.${feature.name}`] = false;
+ }
+ Object.assign(botMcpConfig, { web_search: 'disabled', include_apply_patch_tool: false, project_doc_max_bytes: 0,
+ 'features.shell_tool': false, 'features.unified_exec': false, 'features.shell_snapshot': false,
+ 'features.view_image': false, 'features.code_mode': false, 'features.code_mode_only': false,
+ 'features.js_repl': false, 'features.browser_use': false, 'features.computer_use': false,
+ 'features.image_generation': false, 'features.multi_agent': false, 'features.multi_agent_v2': false,
+ 'memories.generate_memories': false, 'memories.use_memories': false });
+ }
if (!reviewMode && opts.botRuntimeProfile?.mcpPolicy) {
try {
const response = await host.request<{ config?: Record<string, unknown> }>(
@@ -6416,6 +6461,7 @@ assertRouteCurrent();
cleanup: () => host.unsubscribeThread(detachedThreadId),
});
function currentApprovalConfig(): CodexPermissionConfig {
+ if (opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly) return { approvalPolicy: 'never', sandbox: 'read-only' };
if (reviewMode) {
return { approvalPolicy: 'never', sandbox: 'read-only' };
}
@@ -6584,7 +6630,7 @@ assertRouteCurrent();
// Its host omits Cindy's MCP bridge, so a bare memory override would
// create an invalid transport even though the entry is disabled.
// 设备托管:只停用本机确实配置了的 cindy_memory(没有传输配置的空条目会让 Codex 拒绝配置)。
- ...(!reviewMode && !makerMemoryEnabled && !opts.botRuntimeProfile
+ ...(!reviewMode && !opts[LOCAL_AGENT_CLIENT] && !makerMemoryEnabled && !opts.botRuntimeProfile
&& (!hosted || hostedLocalMcpNames.includes('cindy_memory'))
? { 'mcp_servers.cindy_memory.enabled': false }
: {}),
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts
index 4f69161fd3..7b3268ebe2 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts
@@ -31,6 +31,7 @@ import { createWorkerSpecSchema } from '../../../../../lizi-mcps/src/xdt-helper/
import { PiAgent } from '../index.js';
import type { AgentDeps, AgentSessionHandle, PiExtraSpawnConfig } from '../../base-agent.js';
+import { LOCAL_AGENT_CLIENT } from '../../base-agent.js';
import type { AgentEvent, InteractionRequest, InteractionDecision } from '../../../types/events.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -152,6 +153,15 @@ function latestToolResultContent(request: Record<string, unknown>): string {
function scriptedAnthropicTurn(requestBody: string): string {
const toolResultCount = countToolResults(requestBody);
+ if (requestBody.includes('local host tool isolation')) {
+ const calls = [
+ { name: 'cindy_mcp_list_tools', input: {} },
+ { name: 'cindy_mcp_list_tools', input: { server: 'calendar', tool: 'echo' } },
+ { name: 'cindy_mcp_call_tool', input: { server: 'calendar', tool: 'echo', args: { text: 'hello-pi' } } },
+ ];
+ const call = calls[toolResultCount];
+ return call ? anthropicToolTurn(toolResultCount + 1, call.name, call.input) : anthropicTextTurn(4, 'Client tool complete');
+ }
if (requestBody.includes('exercise task control modes')) {
const calls = [
{ name: 'message_session_task', input: { task_id: 'task-fixture', mode: 'steer', message: 'new direction' } },
@@ -723,7 +733,12 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
logout: async () => {},
getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'k' }),
},
- runtimeConfig: { endpoint: gatewayUrl },
+ runtimeConfig: {
+ endpoint: gatewayUrl,
+ systemPrompt: 'CINDY_HOST_IDENTITY_CANARY',
+ answerDeliveryPrompt: 'CINDY_ANSWER_DELIVERY_CANARY',
+ },
+ getGhostRosterPrompt: () => 'WORKDIR_GHOST_ROSTER_CANARY',
binaryPath: PI_BINARY,
logger,
turnChangeCapture: {
@@ -911,6 +926,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
bridgeMode:
| 'local' | 'orca' | 'local-multi' | 'bot-memory' | 'remote' | 'remote-sse' | 'remote-paginated' = 'local',
prompt = 'call the echo tool',
+ localHostOnly: boolean | 'native' = false,
): Promise<{
events: AgentEvent[];
permissionAsked: boolean;
@@ -929,6 +945,12 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
workingDir: cwd,
model: 'pi-test-model',
permissionMode,
+ ...(localHostOnly ? {
+ [LOCAL_AGENT_CLIENT]: { url: mcpUrl, token: MCP_TOKEN, hostToolsOnly: localHostOnly === true, mcpName: 'calendar' },
+ userPrompt: 'CLIENT_INSTRUCTIONS_CANARY',
+ makerMemoryEnabled: false,
+ makerMemoryIndexSnapshot: 'PRIVATE_MEMORY_INDEX_CANARY',
+ } : {}),
});
handle.setInteractionResolver(async (req) => {
if (req.kind === 'permission') permissionAsked = true;
@@ -977,6 +999,38 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
expect(startupNames).not.toContain('mcp__cindy_orca__create_worker');
});
+ // 测试价值:真实 Pi 的启动工具面与调用链均受本机伙伴权限约束;旧 MCP 测试保留原生工具。
+ // 最小输入:独立客户端的 echo;tier integration,真实二进制与本机 socket,无供应商网络。
+ // 2026-10-22 维护者裁决:两种工具策略均保留 Cindy 装配与原生 preset,仍不装载私人记忆。
+ // 通过实际模型请求验证追加段与多次工具调用的稳定前缀,不读取生产源码或复制提示词常量。
+ it('local client tool isolation exposes only the client gateway and executes its tool', { timeout: 90_000 }, async () => {
+ echoCalls.length = 0;
+ const { requests, events, requestBodies } = await runOneTurn('bypassPermissions', async () => ({kind:'permission',behavior:'allow'}), 'local', 'local host tool isolation', true);
+ const system = JSON.stringify(requests[0].system);
+ for (const segment of ['CINDY_HOST_IDENTITY_CANARY', 'CINDY_ANSWER_DELIVERY_CANARY', 'CLIENT_INSTRUCTIONS_CANARY', 'WORKDIR_GHOST_ROSTER_CANARY'])
+ expect(system).toContain(segment);
+ expect(requests.every(request => JSON.stringify(request.system) === system)).toBe(true);
+ expect(requestBodies.join('')).not.toContain('PRIVATE_MEMORY_INDEX_CANARY');
+ expect((requests[0].tools as Array<{name:string}>).map(t=>t.name).sort()).toEqual(['cindy_mcp_call_tool','cindy_mcp_list_tools']);
+ expect(echoCalls.map(c=>c.text)).toEqual(['hello-pi']);
+ expect(events.some(e=>e.type==='text' && (e.data as {text?:string}).text?.includes('Client tool complete'))).toBe(true);
+ });
+
+ // core-product-principles §3.1 / pi-harness §3.1: explicitly selecting native
+ // execution preserves Pi's tools; application MCP isolation is not a safety downgrade.
+ it('keeps native Pi tools when an application explicitly selects native execution', { timeout: 90_000 }, async () => {
+ echoCalls.length = 0;
+ const { requests, requestBodies } = await runOneTurn('bypassPermissions', async () => ({ kind: 'permission', behavior: 'allow' }), 'local', 'local host tool isolation', 'native');
+ const tools = (requests[0].tools as Array<{ name: string }>).map(tool => tool.name);
+ expect(tools).toContain('bash'); expect(tools).toContain('read');
+ expect(echoCalls.map(call => call.text)).toEqual(['hello-pi']);
+ const system = JSON.stringify(requests[0].system);
+ for (const segment of ['CINDY_HOST_IDENTITY_CANARY', 'CINDY_ANSWER_DELIVERY_CANARY', 'CLIENT_INSTRUCTIONS_CANARY', 'WORKDIR_GHOST_ROSTER_CANARY'])
+ expect(system).toContain(segment);
+ expect(requests.every(request => JSON.stringify(request.system) === system)).toBe(true);
+ expect(requestBodies.join('')).not.toContain('PRIVATE_MEMORY_INDEX_CANARY');
+ });
+
it(
'ask + allow: 模型经桥调 cindy 工具 → 触发权限询问 → 放行 → 工具执行 → 最终 text 含回显',
{ timeout: 90_000 },
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index aebc1eeeae..17d205b059 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -3949,11 +3949,19 @@ function registerCindyHostedTools(
}
export default async function cindyBridge(piApi: any) {
+ const localHostToolsOnly = process.env.CINDY_LOCAL_HOST_TOOLS_ONLY === '1';
// 受邀者:只放行 Cindy 扩展注册的工具(本扩展经下面的 pi 注册的,加上子代理扩展的工具)。
- const guestToolGate = CINDY_HOSTED && CINDY_HOSTED.guest
+ const guestToolGate = (CINDY_HOSTED && CINDY_HOSTED.guest) || process.env.CINDY_LOCAL_HOST_TOOLS_ONLY === '1'
? createCindyGuestToolGate(piApi, [${JSON.stringify(CINDY_SUBAGENT_TOOL_NAME)}])
: null;
const pi = guestToolGate ? guestToolGate.pi : piApi;
+ if (localHostToolsOnly) {
+ const allowed = new Set(['cindy_mcp_list_tools', 'cindy_mcp_call_tool']);
+ const isolate = () => pi.setActiveTools([...allowed]);
+ pi.on('session_start', isolate);
+ pi.on('before_agent_start', isolate);
+ pi.on('tool_call', (event: any) => allowed.has(event.toolName) ? undefined : { block: true, reason: 'This session only exposes the authorized client tools.' });
+ }
if (guestToolGate) {
// 被拦的工具也不交给模型(例如 Pi 自带的 codemode、tool_search)。
pi.on('before_agent_start', () => {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 29c68483dd..9201abd7f3 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -66,6 +66,7 @@ import {
AgentStartupCleanupPendingError,
AgentStartupStoppedError,
BaseAgent,
+ LOCAL_AGENT_CLIENT,
MAIN_OWNED_SEND_CONTEXT,
ASYNC_QUESTION_ANSWER,
PINNED_SKILL_INVOCATION,
@@ -3341,7 +3342,7 @@ export class PiAgent extends BaseAgent {
// directory. Keep the capability absent until the wire protocol owns those
// files remotely end-to-end.
const localSubagentSupported = Boolean(
- !reviewMode
+ !reviewMode && !opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly
&& !remote
// 设备托管:子代理进程继承 CINDY_PI_HOSTED 与同一份 cindy-bridge,文件与命令工具同样经
// 隧道回到任务所在电脑(隧道随任务关闭,任务结束后仍在后台跑的子代理会失去工具)。
@@ -3696,7 +3697,12 @@ export class PiAgent extends BaseAgent {
opts.remoteHostId && this.deps.remotePiSkipMcpBridge?.(opts.remoteHostId));
const mcpReadyStartedAt = Date.now();
let mcpReadyStatus: 'ok' | 'degraded' | 'skipped' = 'skipped';
- if (hosted) {
+ if (opts[LOCAL_AGENT_CLIENT]) {
+ const client = opts[LOCAL_AGENT_CLIENT]!;
+ mcpBridge = { token: client.token, servers: [{ name: client.mcpName ?? 'client', url: client.url }] };
+ registeredMcpServerNames.add(client.mcpName ?? 'client');
+ mcpReadyStatus = 'ok';
+ } else if (hosted) {
// 设备托管:Cindy 工具都在任务所在电脑上,经隧道访问;本机的 MCP 桥不参与。
mcpBridge = deviceHostedPiMcpBridge(hosted);
for (const server of mcpBridge.servers) registeredMcpServerNames.add(server.name);
@@ -3864,7 +3870,7 @@ export class PiAgent extends BaseAgent {
? [] : [...(this.deps.getDisabledSkillPaths?.() ?? [])];
let disabledSkillLaunch = snapshotDisabledSkillLaunch(disabledSkillPaths);
const disabledSkillSnapshot = disabledSkillLaunch.identities;
- const loadProjectResourcesInPlace = !reviewMode && !opts.botRuntimeProfile && !opts.remoteHostId;
+ const loadProjectResourcesInPlace = !reviewMode && !opts.botRuntimeProfile && !opts.remoteHostId && !opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly;
let projectResourceAssembly = unavailablePiProjectResourceAssembly(
reviewMode ? 'review-mode-project-resources-disabled' : 'approval-resolver-unavailable',
);
@@ -3917,7 +3923,7 @@ export class PiAgent extends BaseAgent {
if (!reviewMode && !opts.remoteHostId && !hostedGuest) {
if (this.deps.resolvePiNativePackagePaths) {
try {
- nativePackagePaths = await this.deps.resolvePiNativePackagePaths();
+ nativePackagePaths = opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly ? [] : await this.deps.resolvePiNativePackagePaths();
await this.writePiRuntimeSettings(configHome, {
contextWindow: startupContextWindow,
workingContextWindow: startupWorkingContextWindow,
@@ -4003,7 +4009,7 @@ export class PiAgent extends BaseAgent {
try {
const managedSkillGrants = snapshotManagedSkillGrants(opts.botRuntimeProfile?.skillPolicy);
// 受邀者不带本机安装的托管技能(属于本机用户与其组织)。
- const managedSkills = opts.remoteHostId || reviewMode || hostedGuest ? [] : await this.deps.getManagedSkills?.() ?? [];
+ const managedSkills = opts.remoteHostId || reviewMode || hostedGuest || opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly ? [] : await this.deps.getManagedSkills?.() ?? [];
const managedDisabledPaths = snapshotDisabledSkillLaunch(opts.remoteHostId || reviewMode || hostedGuest ? [] : this.deps.getDisabledSkillPaths?.() ?? []);
const managedSourceIdentities = new Set(managedSkills.flatMap((skill) =>
skill.path ? [canonicalSkillPath(skill.path)] : []));
@@ -4013,7 +4019,7 @@ export class PiAgent extends BaseAgent {
// The catalog path may alias a managed source. Apply the managed grant and
// activation checks once, including paths already selected by the Bot.
const additionalSkillPaths = [...new Map([
- ...(loadProjectResourcesInPlace ? [] : botSkillSelection.explicitSkillPaths.filter((skillPath) =>
+ ...(loadProjectResourcesInPlace || opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly ? [] : botSkillSelection.explicitSkillPaths.filter((skillPath) =>
!managedSourcePaths.has(path.resolve(skillPath)) && !managedSourceIdentities.has(canonicalSkillPath(skillPath)))),
].map((skillPath) => [canonicalSkillPath(skillPath), skillPath])).values()];
@@ -4048,6 +4054,7 @@ export class PiAgent extends BaseAgent {
'--model',
initialWireModel,
...(reviewMode ? ['--tools', 'read,grep,find,ls'] : []),
+ ...(opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly ? ['--no-skills', '--no-context-files', '--no-prompt-templates'] : []),
// Bot sessions must not absorb project/global AGENTS.md or CLAUDE.md from
// the cwd chain — their context is the Bot profile, not the workspace.
...(opts.botRuntimeProfile ? ['--no-context-files'] : []),
@@ -4068,7 +4075,7 @@ export class PiAgent extends BaseAgent {
'--extension',
bridgeExtensionPath,
...(localSubagentSupported ? ['--extension', subagentExtensionPath] : []),
- ...(!reviewMode && planModeExtAvailable ? ['--extension', planModeExtPath] : []),
+ ...(!reviewMode && !opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly && planModeExtAvailable ? ['--extension', planModeExtPath] : []),
...(loadProjectResourcesInPlace
? piProjectResourceCliArgs(projectResourceCli)
: []),
@@ -5580,6 +5587,7 @@ export class PiAgent extends BaseAgent {
// 支持者(如 Anthropic)可避免较长会话在短 TTL 后重新计费。
PI_CACHE_RETENTION: 'long',
...(mcpBridge && mcpBridge.servers.length > 0 ? { [PI_MCP_BRIDGE_ENV]: JSON.stringify(mcpBridge) } : {}),
+ CINDY_LOCAL_HOST_TOOLS_ONLY: opts[LOCAL_AGENT_CLIENT]?.hostToolsOnly ? '1' : '',
};
// 不继承宿主进程里碰巧存在的同名变量;Windows 环境键大小写不敏感,必须先清掉
// 所有 casing 再写入 host 校验并 stage 后的唯一绝对路径。
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index 439e1bfda2..6763b5cc80 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -20,6 +20,7 @@ import {
AgentNotAuthenticatedError,
AgentStartupCleanupPendingError,
AgentStartupStoppedError,
+ LOCAL_AGENT_CLIENT,
TurnPermissionPolicyUnsupportedError,
type AgentSessionHandle,
BaseAgent,
@@ -282,6 +283,49 @@ function createDeferred<T = void>(): {
return { promise, resolve };
}
+describe('application-owned session lifecycle', () => {
+ // Production entry: Maker.startLocalAgentSession. Core rules §1/§2 require the
+ // existing Session lifecycle, without creating or enumerating private task rows.
+ // Existing createSession tests exercise persistent tasks, not this entry (unit).
+ it('uses normal continuation settlement without storing an application transcript in Cindy tasks', async () => {
+ const storage = createStorage(), queue = createAsyncQueue<AgentEvent>();
+ const handle = createHandle({ id: 'native-client' });
+ handle.events = () => queue;
+ handle.close = vi.fn(async () => { queue.end(); });
+ handle.beginTurnContinuationWait = id => id === 7 ? 'active' : null;
+ const maker = new Maker({ agents: { codex: createAgent(async () => handle) }, storage, logger: createLogger() });
+ const session = await maker.startLocalAgentSession('codex', { sessionId: 'client', workingDir: '/repo', model: 'm',
+ [LOCAL_AGENT_CLIENT]: { url: 'http://127.0.0.1:1', token: 'invalid-fixture', hostToolsOnly: false } });
+ const observed: string[] = [];
+ session.onEvent(event => { if (event.type === 'done') observed.push(session.getObservedCurrentTurnTerminal().kind); });
+ await session.send('hello');
+ queue.push({ type: 'done', turnContinuationId: 7, data: { status: 'completed' } });
+ await vi.waitFor(() => expect(observed).toEqual(['none']));
+ queue.push({ type: 'done', data: { status: 'completed' } });
+ await vi.waitFor(() => expect(observed).toEqual(['none', 'done']));
+ expect(session.sdkSessionId).toBe('native-client');
+ expect(await storage.list()).toEqual([]);
+ expect(maker.listActiveSessions()).toEqual([]);
+ await maker.shutdown({ reason: 'account-boundary' });
+ expect(handle.close).toHaveBeenCalledWith({ reason: 'account-boundary' });
+ });
+
+ it('closes an application handle that finishes starting after shutdown instead of publishing it', async () => {
+ const ready = createDeferred<AgentSessionHandle>(), storage = createStorage();
+ const handle = createHandle({ id: 'late-client' });
+ handle.close = vi.fn(async () => {});
+ const maker = new Maker({ agents: { codex: createAgent(() => ready.promise) }, storage, logger: createLogger() });
+ const opening = maker.startLocalAgentSession('codex', { workingDir: '/repo', model: 'm',
+ [LOCAL_AGENT_CLIENT]: { url: 'http://127.0.0.1:1', token: 'invalid-fixture', hostToolsOnly: true } });
+ const rejected = expect(opening).rejects.toThrow('stopped');
+ const stopping = maker.shutdown({ reason: 'account-boundary' });
+ ready.resolve(handle);
+ await stopping; await rejected;
+ expect(handle.close).toHaveBeenCalledWith({ reason: 'account-boundary' });
+ expect(await storage.list()).toEqual([]);
+ });
+});
+
describe('Maker local Pi package generation fence', () => {
it.each(['disable', 'remove', 'update'])(
'closes an in-flight local Pi startup before publish after %s',
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 27d08e94fa..c00cf7d0da 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -49,6 +49,7 @@ import {
AgentNotAuthenticatedError,
AgentStartupCleanupPendingError,
AgentStartupStoppedError,
+ LOCAL_AGENT_CLIENT,
} from './agents/base-agent.js';
import type {
AgentSessionHandle,
@@ -484,6 +485,8 @@ export class Maker {
>();
/** All create paths, including anonymous ids, that may still publish or quarantine a handle. */
private readonly pendingSessionCreations = new Set<Promise<Session>>();
+ /** Application-owned transcripts use the normal in-memory lifecycle without private storage. */
+ private readonly localAgentSessions = new Set<Session>();
/** Once shutdown starts, no new handle may race past its creation barrier. */
private shutdownStarted = false;
/**
@@ -1410,7 +1413,7 @@ export class Maker {
// Snapshot current sessions before the creation barrier. Existing local
// Claude/PI processes must start terminating immediately; a stuck startup
// must not consume the entire host quit window before their detach begins.
- const initialSessionSnapshot = Array.from(this.activeSessions.values());
+ const initialSessionSnapshot = [...this.activeSessions.values(), ...this.localAgentSessions];
const initialSessionIdentities = new Set(initialSessionSnapshot);
const queueSessionDetaches = (
sessions: readonly Session[],
@@ -1461,7 +1464,7 @@ export class Maker {
// Only sessions published while the creation barrier was settling belong
// to the late pass. Identity filtering avoids detaching an initial Session
// twice when it remains in activeSessions until its first detach settles.
- const lateSessionSnapshot = Array.from(this.activeSessions.values())
+ const lateSessionSnapshot = [...this.activeSessions.values(), ...this.localAgentSessions]
.filter((session) => !initialSessionIdentities.has(session));
const lateSessionDetaches = queueSessionDetaches(lateSessionSnapshot, 'late');
const failedHandleCleanupSnapshot = Array.from(this.failedHandleCleanups.entries());
@@ -1540,6 +1543,43 @@ export class Maker {
return this.requireAgent(kind).startSession(opts);
}
+ /** A local application owns the transcript; supplier execution stays in Maker. */
+ async startLocalAgentSession(kind: AgentKind, opts: StartSessionOptions): Promise<Session> {
+ if (this.shutdownStarted) throw new Error('Maker is shutting down');
+ if (!opts[LOCAL_AGENT_CLIENT] || opts.deviceHosted || opts.remoteHostId) {
+ throw new Error('Local application sessions require a Main-process capability');
+ }
+ const agent = this.requireAgent(kind);
+ const creation = (async () => {
+ const handle = await agent.startSession(opts);
+ if (this.shutdownStarted) {
+ await handle.close({ reason: 'account-boundary' });
+ throw new Error('Maker stopped before the local application session started');
+ }
+ const session = new Session({
+ id: opts.sessionId ?? generateSessionId(),
+ agentKind: kind,
+ workDir: opts.workingDir,
+ handle,
+ logger: this.logger,
+ permissionMode: opts.permissionMode,
+ capabilities: capabilitiesForSession(kind, agent.capabilities, undefined, undefined, handle),
+ toolLoopReviewer: this.toolLoopReviewer,
+ });
+ this.localAgentSessions.add(session);
+ session.onStatusChange(status => {
+ if (status === 'closed') this.localAgentSessions.delete(session);
+ });
+ return session;
+ })();
+ this.pendingSessionCreations.add(creation);
+ try {
+ return await creation;
+ } finally {
+ this.pendingSessionCreations.delete(creation);
+ }
+ }
+
/**
* Agent 内置 command (palette 'agent-builtin' 类目) —— 同步硬编码白名单。
* 见 agents/<kind>/commands.ts。
diff --git a/scripts/examples/local-agent-client.mjs b/scripts/examples/local-agent-client.mjs
new file mode 100644
index 0000000000..61a76d71a2
--- /dev/null
+++ b/scripts/examples/local-agent-client.mjs
@@ -0,0 +1,145 @@
+#!/usr/bin/env node
+/** Standalone Node 22+ example. Uses only the published discovery file and HTTP API. */
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { parseArgs } from 'node:util';
+import { pathToFileURL } from 'node:url';
+import { setTimeout as delay } from 'node:timers/promises';
+
+export class LocalAgentApiError extends Error {
+ constructor(code, message) { super(message); this.name = 'LocalAgentApiError'; this.code = code; }
+}
+
+/** Intentionally independent of Cindy/HHH packages; credentials live only in this process. */
+export class LocalAgentClient {
+ #base; #instance; #identity; #token; #prefix = randomUUID(); #sequence = 0;
+ constructor(discovery, identity) {
+ if (discovery.protocol !== 1 || !Number.isInteger(discovery.port) || discovery.port < 1 || discovery.port > 65535
+ || typeof discovery.instance !== 'string' || !discovery.instance) {
+ throw new LocalAgentApiError('DISCOVERY_INVALID', 'Invalid v1 discovery file.');
+ }
+ this.#base = `http://127.0.0.1:${discovery.port}`;
+ this.#instance = discovery.instance;
+ this.#identity = identity;
+ }
+ static async discover(file, identity) {
+ return new LocalAgentClient(JSON.parse(await fs.readFile(file, 'utf8')), identity);
+ }
+ async request(method, params = {}, { signal } = {}) {
+ let response;
+ try {
+ response = await fetch(`${this.#base}/rpc`, {
+ method: 'POST', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),
+ headers: { 'Content-Type': 'application/json', ...(this.#token ? { Authorization: `Bearer ${this.#token}` } : {}) },
+ body: JSON.stringify({ version: 1, instance: this.#instance, id: `${this.#prefix}:${++this.#sequence}`, method, params }),
+ });
+ const reply = await response.json();
+ if (reply.error) throw new LocalAgentApiError(reply.error.code, reply.error.message);
+ if (!response.ok || !Object.hasOwn(reply, 'result')) throw new LocalAgentApiError('INVALID_REPLY', 'Invalid API reply.');
+ return reply.result;
+ } catch (error) {
+ if (error instanceof LocalAgentApiError) throw error;
+ // Never automatically resubmit a possibly accepted send/tool/control request.
+ throw new LocalAgentApiError('RESULT_UNKNOWN', `The ${method} reply was not received. The request may have been accepted; it was not resent.`);
+ }
+ }
+ async connect({ signal } = {}) {
+ const caps = await this.request('capabilities', {}, { signal });
+ if (!caps.features?.clientIdentity || !caps.features?.isolatedSessions) {
+ throw new LocalAgentApiError('CAPABILITY_UNSUPPORTED', 'This example requires the generic local-client API.');
+ }
+ const pair = await this.request('connect/start', { client: this.#identity }, { signal });
+ let claimed = false;
+ try {
+ const expires = Date.now() + 120_000;
+ while (Date.now() < expires) {
+ const reply = await this.request('connect/poll', { id: pair.id, claim: pair.claim }, { signal });
+ if (reply.state === 'approved' && typeof reply.token === 'string') {
+ this.#token = reply.token; claimed = true; return;
+ }
+ if (reply.state === 'denied') throw new LocalAgentApiError('CONNECTION_DENIED', 'Connection was not approved in Cindy.');
+ await delay(200, undefined, { signal });
+ }
+ throw new LocalAgentApiError('PAIR_EXPIRED', 'Approve the connection in Cindy, then run the example again.');
+ } finally {
+ if (!claimed) await this.request('connect/cancel', { id: pair.id, claim: pair.claim }).catch(() => {});
+ }
+ }
+ async disconnect() {
+ if (!this.#token) return;
+ await this.request('connect/revoke');
+ this.#token = undefined;
+ }
+}
+
+export async function main(argv = process.argv.slice(2)) {
+ const { values } = parseArgs({ args: argv, options: {
+ help: { type: 'boolean' }, discovery: { type: 'string' }, model: { type: 'string' }, provider: { type: 'string' },
+ engine: { type: 'string' }, cwd: { type: 'string' }, prompt: { type: 'string' }, 'list-models': { type: 'boolean' },
+ 'native-tools': { type: 'boolean' }, 'client-id': { type: 'string' }, 'client-name': { type: 'string' },
+ } });
+ if (values.help) {
+ console.log('Usage: node scripts/examples/local-agent-client.mjs --discovery <profile>/local-agent/discovery.json [--list-models] [--provider <id>] [--engine pi|codex|claude-code] [--model <opaque-id>] [--prompt <text>] [--cwd <folder>] [--native-tools] [--client-id <id>] [--client-name <name>]');
+ return;
+ }
+ if (!values.discovery) throw new LocalAgentApiError('DISCOVERY_REQUIRED', 'Pass --discovery with the intended Cindy profile. No profiles are scanned.');
+ const client = await LocalAgentClient.discover(values.discovery, {
+ id: values['client-id'] ?? 'org.example.cindy-client', name: values['client-name'] ?? 'Independent API example', version: '1.0',
+ });
+ const controller = new AbortController();
+ const stop = () => controller.abort();
+ process.once('SIGINT', stop);
+ const sessionId = 'example';
+ let opened = false, finished = false;
+ try {
+ console.error('Approve this application in Cindy. The example does not save the connection token.');
+ await client.connect({ signal: controller.signal });
+ const { models } = await client.request('models', {}, { signal: controller.signal });
+ const choices = models.filter(model => (!values.provider || model.provider === values.provider) && (!values.engine || model.engine === values.engine));
+ if (values['list-models']) {
+ for (const model of choices) console.log(JSON.stringify({ id: model.id, provider: model.provider, providerLabel: model.providerLabel, label: model.label, engine: model.engine }));
+ return;
+ }
+ const model = values.model ? choices.find(model => model.id === values.model) : choices[0];
+ if (!model) throw new LocalAgentApiError('MODEL_UNAVAILABLE', 'No model matches the requested source. List models and choose an available ID.');
+ await client.request('session/open', {
+ sessionId, cwd: path.resolve(values.cwd ?? process.cwd()), model: model.id,
+ toolPolicy: values['native-tools'] ? 'native' : 'client-only',
+ instructions: 'You are assisting an independent client. Use client_echo once, then explain its returned text.',
+ tools: [{ name: 'client_echo', description: 'Echo text inside the calling application. No file or network side effects.', parameters: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false } }],
+ }, { signal: controller.signal });
+ opened = true;
+ await client.request('send', { sessionId, parts: [{ type: 'text', text: values.prompt ?? 'Call client_echo with text "Hello from an independent app", then quote its returned text.' }] }, { signal: controller.signal });
+ let cursor = 0;
+ while (!finished) {
+ const batch = await client.request('events', { sessionId, cursor }, { signal: controller.signal });
+ for (const entry of batch.events) {
+ const event = entry.event;
+ if (event.type === 'text') process.stdout.write(event.data);
+ if (event.type === 'host_tool') {
+ const call = event.data;
+ const valid = call.name === 'client_echo' && typeof call.arguments?.text === 'string';
+ await client.request('tool/reply', { sessionId, callId: call.id,
+ text: valid ? JSON.stringify({ text: call.arguments.text }) : 'Unsupported client tool or arguments.', isError: !valid }, { signal: controller.signal });
+ }
+ if (event.type === 'turn_end') {
+ finished = true;
+ if (event.data.status !== 'completed') throw new LocalAgentApiError('TURN_INCOMPLETE', event.data.message || `Turn ${event.data.status}.`);
+ }
+ }
+ cursor = batch.cursor;
+ }
+ process.stdout.write('\n');
+ } finally {
+ process.removeListener('SIGINT', stop);
+ if (opened && !finished) await client.request('interrupt', { sessionId }).catch(() => {});
+ if (opened) await client.request('session/close', { sessionId }).catch(() => {});
+ // A one-shot example must not leave an unused persistent application grant.
+ await client.disconnect();
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main().catch(error => { console.error(`${error.code ?? 'CLIENT_FAILED'}: ${error.message}`); process.exitCode = 1; });
+}
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index 69debda44a..a5d193ea4d 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -363,6 +363,14 @@ export default {
'**/*.bench.ts',
],
},
+ integration: {
+ status: 'manual',
+ reason: 'Local application Agent protocol tests open real loopback sockets and temporary authorization stores.',
+ execution: 'exclusive',
+ coverage: 'allowlist',
+ command: vitestBin('run', '--maxWorkers=2'),
+ include: ['src/main/local-agent/__tests__/*.integration.test.ts'],
+ },
'git-integration': {
status: 'manual',
reason: 'Full real-Git coverage is explicit because it spawns hundreds of local subprocesses and is coordinated across worktrees.',