Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(local-agent): 回收空闲进程 nonce 并按授权限额
david10dede018d4e
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.tsindex fc7ec5b495..cf789d84b7 100644--- a/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts+++ b/apps/desktop/src/main/local-agent/__tests__/server.integration.test.ts@@ -783,6 +783,25 @@ describe('local application authorization and lifecycle', () => {);expect(f.call).toHaveBeenCalledTimes(2);});+ it('reclaims quiet process nonces per grant and refuses their late requests instead of replaying', async () => {+ const f = await fixture(),+ secret = await f.connect();+ await f.start(secret);+ vi.useFakeTimers({ toFake: ['Date'] });+ try {+ const interrupt = (nonce: string) =>+ f.rpc('interrupt', { sessionId: 'run' }, secret, `${nonce}:1`);+ // session/open above already holds one of the grant's 32 process slots.+ for (let i = 0; i < 31; i++) await interrupt(`process${String(i).padStart(3, '0')}`);+ expect((await interrupt('restarted')).error.code).toBe('CLIENT_LIMIT');+ vi.setSystemTime(Date.now() + 10 * 60_000);+ expect((await interrupt('restarted')).error).toBeUndefined();+ expect((await interrupt('process000')).error.code).toBe('REQUEST_EXPIRED');+ expect(f.call).toHaveBeenCalledTimes(32);+ } finally {+ vi.useRealTimers();+ }+ });it('round trips actual MCP calls through ordered events and resolves exactly one host answer', async () => {const f = await fixture(),secret = await f.connect();diff --git a/apps/desktop/src/main/local-agent/server.ts b/apps/desktop/src/main/local-agent/server.tsindex 739a4f4759..13ac6cf2f4 100644--- a/apps/desktop/src/main/local-agent/server.ts+++ b/apps/desktop/src/main/local-agent/server.ts@@ -16,6 +16,10 @@ const MAX_EVENTS = 8 * 1024 * 1024;const MAX_RUNS = 16;const PAIR_TTL = 120_000;const RUN_IDLE = 3 * 60_000;+const MAX_CLIENTS = 128;+const MAX_GRANT_CLIENTS = 32;+const MAX_RETIRED_CLIENTS = 4096;+const CLIENT_IDLE_MS = 10 * 60_000;const token = () => randomBytes(32).toString('base64url');const hash = (value: string) => createHash('sha256').update(value).digest('hex');const equal = (a: string, b: string) =>@@ -251,7 +255,27 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {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>();+ const clients = new Map<string, { high: number; seen: number }>();+ // Reclaimed process nonces are refused rather than forgotten: a late retry under one+ // of them must not re-run a side effect whose dedup record was dropped.+ const retired = new Set<string>();+ const retire = (client: string) => {+ clients.delete(client);+ for (const key of dedup.keys()) if (key.startsWith(`${client}:`)) dedup.delete(key);+ retired.add(client);+ if (retired.size > MAX_RETIRED_CLIENTS) retired.delete(retired.values().next().value!);+ };+ const admitClient = (client: string, owner: string) => {+ if (retired.has(client))+ throw new LocalAgentError('REQUEST_EXPIRED', '该进程的请求记录已回收,请使用新的进程编号。');+ const owned = () => [...clients.keys()].filter((key) => key.startsWith(`${owner}:`)).length;+ if (clients.size < MAX_CLIENTS && owned() < MAX_GRANT_CLIENTS) return;+ // Restarted processes use new nonces; reclaim the ones that have gone quiet.+ const idle = Date.now() - CLIENT_IDLE_MS;+ for (const [key, state] of clients) if (state.seen <= idle) retire(key);+ if (clients.size >= MAX_CLIENTS || owned() >= MAX_GRANT_CLIENTS)+ throw new LocalAgentError('CLIENT_LIMIT', '本机连接数量已满,请稍后重试或在 Cindy 中重新授权。');+ };let base = '';let closing = false;/** Closes of engines that were still starting when their run was closed, by grant. */@@ -376,6 +400,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {}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);+ for (const key of retired) if (key.startsWith(`${id}:`)) retired.delete(key);const stopped = Promise.all([...runs].filter(([, run]) => run.owner === id).map(([key]) => closeRun(key)),).then(() => lateClosed(id));@@ -809,9 +834,10 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {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 (!clients.has(client)) admitClient(client, grant.id);+ const state = clients.get(client) ?? { high: 0, seen: 0 };+ state.seen = Date.now();+ const high = state.high;if (counter <= high - 256)throw new LocalAgentError('REQUEST_EXPIRED', '请求记录已过期,未再次执行。');const fingerprint = hash(JSON.stringify([method, params]));@@ -819,7 +845,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {if (previous && previous.fingerprint !== fingerprint)throw new LocalAgentError('ID_REUSED', '请求编号已用于不同操作,未再次执行。');if (!previous) {- clients.set(client, Math.max(high, counter));+ clients.set(client, { high: Math.max(high, counter), seen: state.seen });for (const old of dedup.keys())if (old.startsWith(`${client}:`) && Number(old.slice(client.length + 1)) <= counter - 256)dedup.delete(old);@@ -899,6 +925,7 @@ export async function createLocalAgentServer(deps: LocalAgentServerDeps) {pairs.clear();dedup.clear();clients.clear();+ retired.clear();await Promise.all([persist(),Promise.all([...runs.keys()].map((id) => closeRun(id))).then(() => lateClosed()),diff --git a/docs/local-agent-api.md b/docs/local-agent-api.mdindex e637371dea..98d406b9d6 100644--- a/docs/local-agent-api.md+++ b/docs/local-agent-api.md@@ -61,7 +61,7 @@ node scripts/examples/local-agent-client.mjs --connection-code "cindy-local:v1:<`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,不依赖旧实例的去重记录。网络超时表示结果可能未知;任何消息、工具副作用或控制请求都不能用新编号自动重试。+有副作用的请求编号必须是 `<process-nonce>:<counter>`,nonce 为 8–64 位 `[A-Za-z0-9_-]`,counter 从 1 单调递增、最多 15 位。去重按**授权 + 完整请求编号**计算,同编号不同 payload 拒绝;每个进程保留最近 256 个编号的窗口,已过期请求拒绝执行,不重新提交。重启后用新 nonce,不依赖旧实例的去重记录。每个授权最多同时保留 32 个进程 nonce(全部授权合计 128 个);名额用满时,空闲超过 10 分钟的 nonce 会被回收,之后再用该 nonce 的请求返回 `REQUEST_EXPIRED` 且不执行,仍无可回收名额时返回 `CLIENT_LIMIT`。网络超时表示结果可能未知;任何消息、工具副作用或控制请求都不能用新编号自动重试。## 应用授权@@ -136,7 +136,7 @@ Claude client-only 关闭原生 tools/settings/skills;Pi 仅开启客户端网会话上限 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`(保留原文件并检查版本/存储)。+常见可判断错误:`UNAUTHORIZED`(重新授权)、`INSTANCE_CHANGED`(重新发现)、`MODEL_UNAVAILABLE`(重新选择有效来源)、`RESUME_UNAVAILABLE`(新会话并交接上下文)、`SESSION_UNAVAILABLE`(原会话已关闭或不属于此授权)、`UNSUPPORTED_ACCESS`(策略不支持/矛盾)、`ID_REUSED` / `REQUEST_EXPIRED`(未重复执行)、`CLIENT_LIMIT`(同时运行的客户端进程过多,稍后重试)、`GRANT_STORE_INVALID`(保留原文件并检查版本/存储)。错误 code 保持稳定,展示文案、Cindy 确认及兼容结果页通过 Cindy 当前语言的五语资源提供。设置 IPC 复用受信顶层窗口校验与统一 IPC 错误协议;等待 Cindy 确认后再次校验发起窗口及 owner generation,不向 Renderer 返回原始存储异常。