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(desktop): agent Bash 命令全局并发闸门(资源治理 1/3,默认不限) (#1049)

Chris Zhangb43581aead59
diff --git a/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts b/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
new file mode 100644
index 0000000000..92adcc5bf6
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/agentProcessPriority.test.ts
@@ -0,0 +1,326 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn(() => ''),
+ isPackaged: false,
+ },
+}));
+
+vi.mock('../logger', () => ({
+ createLogger: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ debug: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+vi.mock('../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ },
+}));
+
+const osMock = vi.hoisted(() => ({
+ setPriority: vi.fn(),
+}));
+vi.mock('node:os', () => {
+ const constants = { priority: { PRIORITY_BELOW_NORMAL: 10, PRIORITY_LOW: 19, PRIORITY_NORMAL: 0 } };
+ return {
+ default: { setPriority: osMock.setPriority, constants },
+ setPriority: osMock.setPriority,
+ constants,
+ };
+});
+
+import { allUserDataDirNames } from '@cindy/maker-shared/brand-identity';
+
+import {
+ __testing,
+ classifyAgentCommandLine,
+ createAgentProcessPriorityWatcher,
+ parsePosixAgentProcesses,
+ registerUserDataMarkers,
+ type AgentProcessRow,
+ type ApplyPriorityResult,
+} from '../agent-process-priority';
+import type { AgentProcessPriority } from '../maker-host/agent-resource-settings-store';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+
+const fakeLog = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
+
+function makeWatcher(opts: {
+ priority: () => AgentProcessPriority;
+ rows: () => AgentProcessRow[];
+ applyResult?: (pid: number) => ApplyPriorityResult;
+}) {
+ const scan = vi.fn(async () => opts.rows());
+ const apply = vi.fn(
+ async (
+ pid: number,
+ _tier: AgentProcessPriority,
+ _prev: AgentProcessPriority | undefined,
+ ): Promise<ApplyPriorityResult> => (opts.applyResult ? opts.applyResult(pid) : 'applied'),
+ );
+ const watcher = createAgentProcessPriorityWatcher({
+ readPriority: opts.priority,
+ scanAgentProcesses: scan,
+ applyPriority: apply,
+ log: fakeLog,
+ });
+ return { watcher, scan, apply };
+}
+
+describe('agent process priority watcher', () => {
+ it('does not even scan when priority is normal and nothing was touched', async () => {
+ const { watcher, scan, apply } = makeWatcher({
+ priority: () => 'normal',
+ rows: () => [{ pid: 1, kind: 'claude' }],
+ });
+ await watcher.tickOnce();
+ expect(scan).not.toHaveBeenCalled();
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('lowers discovered agent processes once and does not re-apply the same tier', async () => {
+ const { watcher, apply } = makeWatcher({
+ priority: () => 'low',
+ rows: () => [
+ { pid: 11, kind: 'claude' },
+ { pid: 22, kind: 'codex' },
+ ],
+ });
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenCalledTimes(2);
+ expect(apply).toHaveBeenCalledWith(11, 'low', undefined);
+ expect(apply).toHaveBeenCalledWith(22, 'low', undefined);
+
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenCalledTimes(2); // 已在目标档,不重复调
+ });
+
+ it('re-applies when the tier changes and passes the previous tier through', async () => {
+ let tier: AgentProcessPriority = 'lowest';
+ const { watcher, apply } = makeWatcher({
+ priority: () => tier,
+ rows: () => [{ pid: 11, kind: 'claude' }],
+ });
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenLastCalledWith(11, 'lowest', undefined);
+
+ tier = 'low';
+ await watcher.tickOnce();
+ // prevTier='lowest' 让实现知道要清 macOS taskpolicy 背景钳制
+ expect(apply).toHaveBeenLastCalledWith(11, 'low', 'lowest');
+ });
+
+ it('restores only processes it previously touched when switching back to normal', async () => {
+ let tier: AgentProcessPriority = 'low';
+ let rows: AgentProcessRow[] = [{ pid: 11, kind: 'claude' }];
+ const { watcher, apply, scan } = makeWatcher({ priority: () => tier, rows: () => rows });
+ await watcher.tickOnce();
+
+ tier = 'normal';
+ rows = [
+ { pid: 11, kind: 'claude' },
+ { pid: 33, kind: 'claude' }, // 从未被动过的进程,normal 下绝不碰
+ ];
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenCalledTimes(2);
+ expect(apply).toHaveBeenLastCalledWith(11, 'normal', 'low');
+
+ // 恢复完成后账本清空 → 回到零成本快路径
+ const scanCallsSoFar = scan.mock.calls.length;
+ await watcher.tickOnce();
+ expect(scan.mock.calls.length).toBe(scanCallsSoFar);
+ });
+
+ it('drops processes that disappeared and ones apply reports as gone', async () => {
+ let rows: AgentProcessRow[] = [
+ { pid: 11, kind: 'claude' },
+ { pid: 22, kind: 'codex' },
+ ];
+ const { watcher, apply } = makeWatcher({
+ priority: () => 'low',
+ rows: () => rows,
+ applyResult: (pid) => (pid === 22 ? 'process-gone' : 'applied'), // 22 在 apply 时已退出
+ });
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenCalledTimes(2);
+
+ // 22 未入账 → 再次出现会重试;11 已入账不重试
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenCalledTimes(3);
+ expect(apply).toHaveBeenLastCalledWith(22, 'low', undefined);
+
+ // 11 退出后从账本移除;若再回来(pid 复用)会重新降档
+ rows = [];
+ await watcher.tickOnce();
+ rows = [{ pid: 11, kind: 'claude' }];
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenLastCalledWith(11, 'low', undefined);
+ });
+
+ it('records nice-stuck raises truthfully and does not retry them every tick', async () => {
+ // lowest → low 是 POSIX 升档:nice 卡在 19,只有钳制被调整
+ let tier: AgentProcessPriority = 'lowest';
+ const { watcher, apply } = makeWatcher({
+ priority: () => tier,
+ rows: () => [{ pid: 11, kind: 'claude' }],
+ applyResult: () => (tier === 'low' ? 'nice-raise-refused' : 'applied'),
+ });
+ await watcher.tickOnce();
+ expect(fakeLog.info).toHaveBeenCalledWith(
+ 'agent process priority lowered',
+ expect.objectContaining({ pid: 11, tier: 'lowest' }),
+ );
+
+ tier = 'low';
+ fakeLog.info.mockClear();
+ await watcher.tickOnce();
+ // 不写"lowered"假成功日志,改记 warn 说明 nice 卡档
+ expect(fakeLog.info).not.toHaveBeenCalledWith(
+ 'agent process priority lowered',
+ expect.anything(),
+ );
+ expect(fakeLog.warn).toHaveBeenCalledWith(
+ expect.stringContaining('nice stuck'),
+ expect.objectContaining({ pid: 11, requestedTier: 'low', stuckAtTier: 'lowest' }),
+ );
+
+ // 已按目标档入账:下一 tick 不再空转重试
+ const applyCalls = apply.mock.calls.length;
+ await watcher.tickOnce();
+ expect(apply.mock.calls.length).toBe(applyCalls);
+ });
+
+ it('survives a throwing scan without breaking later ticks', async () => {
+ let shouldThrow = true;
+ const apply = vi.fn(async (): Promise<ApplyPriorityResult> => 'applied');
+ const watcher = createAgentProcessPriorityWatcher({
+ readPriority: () => 'low',
+ scanAgentProcesses: async () => {
+ if (shouldThrow) throw new Error('ps blew up');
+ return [{ pid: 11, kind: 'claude' as const }];
+ },
+ applyPriority: apply,
+ log: fakeLog,
+ });
+ await watcher.tickOnce();
+ expect(fakeLog.warn).toHaveBeenCalled();
+ shouldThrow = false;
+ await watcher.tickOnce();
+ expect(apply).toHaveBeenCalledWith(11, 'low', undefined);
+ });
+});
+
+describe('agent process discovery', () => {
+ // userData 目录名按当前构建区域取(测试环境默认 global → CindyGlobal),不写死区域
+ const userDataDir = allUserDataDirNames(CURRENT_CINDY_REGION)[0].toLowerCase();
+ const claudeCmd = `/users/me/library/application support/${userDataDir}/claude-code/2.1.219/claude --setting-sources user`;
+ const codexCmd = `/users/me/library/application support/${userDataDir}/codex/0.145.0/codex app-server`;
+ const devClaudeCmd = '/repo/apps/claude-code-bin/darwin-arm64/claude';
+ const externalClaudeCmd = '/usr/local/bin/claude';
+
+ it('classifies bundled claude/codex command lines and rejects external installs', () => {
+ expect(classifyAgentCommandLine(claudeCmd)).toBe('claude');
+ expect(classifyAgentCommandLine(codexCmd)).toBe('codex');
+ expect(classifyAgentCommandLine(devClaudeCmd)).toBe('claude');
+ expect(classifyAgentCommandLine(externalClaudeCmd)).toBeNull();
+ expect(classifyAgentCommandLine('/usr/bin/node some-script.js')).toBeNull();
+ });
+
+ it('classifies packaged Linux layouts (legacy managed + agent-runtime fallback)', () => {
+ // Linux userData 在 ~/.config/<dir>/;linux-runtime-fallback 的 privateBinaryPath
+ // 布局是 <userData>/agent-runtime/<kind>/bin/<cmd>
+ expect(
+ classifyAgentCommandLine(`/home/u/.config/${userDataDir}/agent-runtime/claude-code/bin/claude`),
+ ).toBe('claude');
+ expect(
+ classifyAgentCommandLine(`/home/u/.config/${userDataDir}/agent-runtime/codex/bin/codex`),
+ ).toBe('codex');
+ expect(
+ classifyAgentCommandLine(`/home/u/.config/${userDataDir}/claude-code/2.1.219/claude`),
+ ).toBe('claude');
+ expect(
+ classifyAgentCommandLine(`/home/u/.config/${userDataDir}/codex/0.145.0/codex app-server`),
+ ).toBe('codex');
+ // 外部安装(不带 userData 目录)仍不认领
+ expect(classifyAgentCommandLine('/home/u/.local/bin/claude')).toBeNull();
+ });
+
+ it('classifies redirected userData layouts after registerUserDataMarkers (XDG/--user-data-dir)', () => {
+ // XDG_CONFIG_HOME 重定向后 userData 不在 ~/.config 下,静态品牌 marker 失配
+ const redirected = '/mnt/data/xdg-alt/CindyCustom';
+ expect(
+ classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/claude-code/bin/claude`),
+ ).toBeNull(); // 注册前:不认识
+ registerUserDataMarkers(redirected);
+ expect(
+ classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/claude-code/bin/claude`),
+ ).toBe('claude');
+ expect(
+ classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/codex/bin/codex`),
+ ).toBe('codex');
+ expect(
+ classifyAgentCommandLine(`${redirected.toLowerCase()}/claude-code/2.1.219/claude`),
+ ).toBe('claude');
+ // 重复注册整组替换(幂等):旧路径不残留
+ registerUserDataMarkers('/somewhere/else/Cindy2');
+ expect(
+ classifyAgentCommandLine(`${redirected.toLowerCase()}/agent-runtime/claude-code/bin/claude`),
+ ).toBeNull();
+ });
+
+ it('maps setPriority errno to apply results (default implementation)', async () => {
+ const applyPriority = __testing.makeDefaultApplyPriority(fakeLog);
+ const errWith = (code: string) => Object.assign(new Error(code), { code });
+ // Node 真实形态:libuv 失败被包成 SystemError,顶层 code 恒为 ERR_SYSTEM_ERROR,
+ // 真 errno 在 info.code
+ const systemErrWith = (code: string) =>
+ Object.assign(new Error(`A system error occurred: uv_os_setpriority returned ${code}`), {
+ code: 'ERR_SYSTEM_ERROR',
+ info: { code, errno: -1, syscall: 'uv_os_setpriority' },
+ });
+
+ for (const make of [errWith, systemErrWith]) {
+ osMock.setPriority.mockImplementationOnce(() => {
+ throw make('ESRCH');
+ });
+ await expect(applyPriority(11, 'low', undefined)).resolves.toBe('process-gone');
+
+ osMock.setPriority.mockImplementationOnce(() => {
+ throw make('EPERM');
+ });
+ await expect(applyPriority(11, 'low', undefined)).resolves.toBe('nice-raise-refused');
+
+ osMock.setPriority.mockImplementationOnce(() => {
+ throw make('EACCES');
+ });
+ await expect(applyPriority(11, 'low', undefined)).resolves.toBe('nice-raise-refused');
+ }
+
+ osMock.setPriority.mockImplementationOnce(() => {});
+ await expect(applyPriority(11, 'low', undefined)).resolves.toBe('applied');
+ });
+
+ it('parses ps output and keeps only direct children of this process', () => {
+ const selfPid = 4242;
+ const psOutput = [
+ ` 100 ${selfPid} ${claudeCmd}`,
+ ` 101 ${selfPid} ${codexCmd}`,
+ ` 102 9999 ${claudeCmd}`, // 别的进程的孩子(如另一个 Cindy 实例)
+ ` 103 ${selfPid} ${externalClaudeCmd}`,
+ ` 104 ${selfPid} /applications/cindy.app/contents/macos/cindy helper`,
+ 'garbage line',
+ ].join('\n');
+ expect(parsePosixAgentProcesses(psOutput, selfPid)).toEqual([
+ { pid: 100, kind: 'claude' },
+ { pid: 101, kind: 'codex' },
+ ]);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts b/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts
new file mode 100644
index 0000000000..8c899d6a20
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/agentResourceSettingsStore.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn(() => ''),
+ },
+}));
+
+vi.mock('../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ },
+}));
+
+import { __testing } from '../maker-host/agent-resource-settings-store';
+
+describe('agent resource settings store', () => {
+ it('defaults to unlimited concurrency (0)', () => {
+ expect(__testing.normalize(undefined).maxConcurrentCommands).toBe(0);
+ expect(__testing.normalize({}).maxConcurrentCommands).toBe(0);
+ expect(__testing.normalize(null).maxConcurrentCommands).toBe(0);
+ });
+
+ it('preserves zero as the unlimited value', () => {
+ expect(__testing.normalize({ maxConcurrentCommands: 0 }).maxConcurrentCommands).toBe(0);
+ });
+
+ it('floors and clamps the concurrency limit', () => {
+ expect(__testing.normalize({ maxConcurrentCommands: 4.9 }).maxConcurrentCommands).toBe(4);
+ expect(__testing.normalize({ maxConcurrentCommands: -3 }).maxConcurrentCommands).toBe(0);
+ expect(__testing.normalize({ maxConcurrentCommands: 9999 }).maxConcurrentCommands).toBe(64);
+ });
+
+ it('falls back to default on non-numeric values', () => {
+ expect(__testing.normalize({ maxConcurrentCommands: '5' }).maxConcurrentCommands).toBe(0);
+ expect(__testing.normalize({ maxConcurrentCommands: Number.NaN }).maxConcurrentCommands).toBe(0);
+ expect(
+ __testing.normalize({ maxConcurrentCommands: Number.POSITIVE_INFINITY }).maxConcurrentCommands,
+ ).toBe(0);
+ });
+
+ it('defaults process priority to normal and only accepts known tiers', () => {
+ expect(__testing.normalize({}).processPriority).toBe('normal');
+ expect(__testing.normalize({ processPriority: 'low' }).processPriority).toBe('low');
+ expect(__testing.normalize({ processPriority: 'lowest' }).processPriority).toBe('lowest');
+ expect(__testing.normalize({ processPriority: 'turbo' }).processPriority).toBe('normal');
+ expect(__testing.normalize({ processPriority: 19 }).processPriority).toBe('normal');
+ });
+
+ it('defaults toolchain thread cap to off and only accepts literal true', () => {
+ expect(__testing.normalize({}).capToolchainThreads).toBe(false);
+ expect(__testing.normalize({ capToolchainThreads: true }).capToolchainThreads).toBe(true);
+ expect(__testing.normalize({ capToolchainThreads: 'yes' }).capToolchainThreads).toBe(false);
+ expect(__testing.normalize({ capToolchainThreads: 1 }).capToolchainThreads).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/agent-process-priority.ts b/apps/desktop/src/main/agent-process-priority.ts
new file mode 100644
index 0000000000..c3f5f21583
--- /dev/null
+++ b/apps/desktop/src/main/agent-process-priority.ts
@@ -0,0 +1,424 @@
+/**
+ * agent-process-priority —— agent 进程优先级降档 watcher(资源占用治理第三层)。
+ *
+ * 动机: 并发闸门与工具链限核都管不住"任意重命令抢占前台"——优先级是内核层的,
+ * 对 agent 进程树里的一切子进程(bash / 测试 / 构建)都生效:降档后 agent 照常
+ * 用满空闲核,但用户前台应用永远优先,机器不再卡顿。
+ *
+ * 实现方式: claude 子进程由 Claude SDK 内部 spawn(host 拿不到 pid),codex 由
+ * maker-core spawn —— 统一用周期扫描:找到"当前主进程直接子进程 + 命中本产品
+ * agent 二进制路径 marker"的进程,按设置档位调 os.setPriority;后续 spawn 的
+ * 子进程(bash / 测试 worker)自动继承。发现窗口 ≤ intervalMs,即会话最初几秒
+ * 启动的命令可能仍以原优先级跑完 —— 可接受,重负载通常出现在会话中后期。
+ *
+ * 档位映射:
+ * - 'low' → PRIORITY_BELOW_NORMAL(nice 10 / Windows BELOW_NORMAL)
+ * - 'lowest' → PRIORITY_LOW(nice 19 / Windows IDLE);macOS 额外 taskpolicy -b
+ * (Darwin 背景 QoS,压到能效核)
+ * - 'normal' → 只对**曾被本 watcher 降档**的进程尝试恢复;POSIX 非特权进程
+ * 无法调回已升高的 nice(EPERM 静默接受,新进程自然是 normal),
+ * macOS 的 taskpolicy -B 钳制清除是例外、可恢复。
+ *
+ * 安全边界: 只匹配 ppid == 本进程 且命令行带产品二进制 marker 的进程,绝不触碰
+ * 外部安装的 claude/codex 或另一个 Cindy 实例的进程(与 claude-orphan-reaper
+ * 同一套 marker 策略)。所有失败 best-effort,永不影响 agent 功能。
+ */
+
+import { execFile } from 'node:child_process';
+import os from 'node:os';
+import { promisify } from 'node:util';
+
+import { app } from 'electron';
+
+import { allUserDataDirNames } from '@cindy/maker-shared/brand-identity';
+
+import { CURRENT_CINDY_REGION } from '../shared/brandRegion.js';
+import { buildClaudePathMarkers } from './claude-orphan-reaper.js';
+import { createLogger } from './logger';
+import {
+ readAgentResourceSettings,
+ type AgentProcessPriority,
+} from './maker-host/agent-resource-settings-store.js';
+
+const execFileAsync = promisify(execFile);
+
+const DEFAULT_INTERVAL_MS = 15_000;
+
+export interface AgentProcessRow {
+ pid: number;
+ kind: 'claude' | 'codex';
+}
+
+/**
+ * 单进程调档结果:
+ * - 'applied' : 目标档已生效(或至少 setPriority 成功)
+ * - 'process-gone' : 进程已退出(ESRCH),从账上移除
+ * - 'nice-raise-refused' : POSIX 拒绝调高优先级(EPERM/EACCES)——nice 停留在
+ * 原档;darwin 的 taskpolicy 钳制部分仍按目标档调整过
+ */
+export type ApplyPriorityResult = 'applied' | 'process-gone' | 'nice-raise-refused';
+
+interface WatcherLogger {
+ info(message: string, meta?: Record<string, unknown>): void;
+ warn(message: string, meta?: Record<string, unknown>): void;
+ debug(message: string, meta?: Record<string, unknown>): void;
+}
+
+export interface AgentProcessPriorityWatcherDeps {
+ readPriority: () => AgentProcessPriority;
+ scanAgentProcesses: () => Promise<AgentProcessRow[]>;
+ /** 对单个进程应用档位;结果语义见 ApplyPriorityResult。 */
+ applyPriority: (
+ pid: number,
+ tier: AgentProcessPriority,
+ prevTier: AgentProcessPriority | undefined,
+ ) => Promise<ApplyPriorityResult>;
+ log: WatcherLogger;
+ intervalMs?: number;
+}
+
+export interface AgentProcessPriorityWatcher {
+ start(): void;
+ stop(): void;
+ /** 单次 tick(测试用;生产由内部 interval 驱动)。 */
+ tickOnce(): Promise<void>;
+}
+
+/**
+ * codex 二进制路径 marker(与 buildClaudePathMarkers 同构):
+ * <userData>/codex/<ver>/ 及 dev checkout 的 apps/codex-bin/。
+ */
+export function buildCodexPathMarkers(dirNames: readonly string[]): string[] {
+ return dirNames.flatMap((dirName) => {
+ const dir = dirName.toLowerCase();
+ return [
+ `appdata\\roaming\\${dir}\\codex\\`,
+ `appdata/roaming/${dir}/codex/`,
+ `/library/application support/${dir}/codex/`,
+ ];
+ });
+}
+
+/**
+ * Linux 布局 marker:userData 在 ~/.config/<dir>/ 下。覆盖两种托管形态——
+ * legacy `<userData>/<kind>/<version>/` 与 linux-runtime-fallback 的
+ * `<userData>/agent-runtime/<kind>/bin/`(见 agent-binaries/linux-runtime-fallback.ts
+ * privateBinaryPath;打包 Linux 走这条,不加就整平台失明,bot review P1)。
+ * agent-runtime 布局当前仅 Linux 使用,mac/win 无需对应新增。
+ */
+export function buildLinuxPathMarkers(
+ dirNames: readonly string[],
+ kind: 'claude-code' | 'codex',
+): string[] {
+ return dirNames.flatMap((dirName) => {
+ const dir = dirName.toLowerCase();
+ return [
+ `/.config/${dir}/${kind}/`,
+ `/.config/${dir}/agent-runtime/${kind}/`,
+ ];
+ });
+}
+
+const CLAUDE_MARKERS = [
+ ...buildClaudePathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION)),
+ ...buildLinuxPathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION), 'claude-code'),
+ 'apps\\claude-code-bin\\',
+ 'apps/claude-code-bin/',
+];
+
+const CODEX_MARKERS = [
+ ...buildCodexPathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION)),
+ ...buildLinuxPathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION), 'codex'),
+ 'apps\\codex-bin\\',
+ 'apps/codex-bin/',
+];
+
+/**
+ * 运行时 userData 派生 marker:Linux 的 userData 可被 XDG_CONFIG_HOME /
+ * --user-data-dir 重定向,静态 ~/.config/<brand>/ 形态的 marker 会整体失配,
+ * watcher 静默失明(bot review fresh evidence)。以 app.getPath('userData') 的
+ * 实际解析值补一组 marker;静态品牌 marker 仍保留(覆盖历史目录名与另一实例
+ * 的标准布局)。start 入口注册,重复调用整组替换(幂等)。
+ */
+const runtimeUserDataMarkers: { claude: string[]; codex: string[] } = { claude: [], codex: [] };
+
+export function registerUserDataMarkers(userDataPath: string): void {
+ const markersFor = (kind: 'claude-code' | 'codex'): string[] => {
+ const lower = userDataPath.toLowerCase();
+ // 命令行里的分隔符形态可能与 app.getPath 返回值不同(Windows 下 / 与 \ 混用),
+ // 两种形态都登记;非本平台形态的变体永不命中,无害。
+ const variants = new Set([lower.replace(/\\/g, '/'), lower.replace(/\//g, '\\')]);
+ const out: string[] = [];
+ for (const v of variants) {
+ const sep = v.includes('\\') ? '\\' : '/';
+ out.push(`${v}${sep}${kind}${sep}`);
+ out.push(`${v}${sep}agent-runtime${sep}${kind}${sep}`);
+ }
+ return out;
+ };
+ runtimeUserDataMarkers.claude = markersFor('claude-code');
+ runtimeUserDataMarkers.codex = markersFor('codex');
+}
+
+/** 命令行(已小写)→ agent 种类;不命中任何 marker = 不是我们的 agent 进程。 */
+export function classifyAgentCommandLine(cmdLineLower: string): 'claude' | 'codex' | null {
+ if (
+ CLAUDE_MARKERS.some((m) => cmdLineLower.includes(m)) ||
+ runtimeUserDataMarkers.claude.some((m) => cmdLineLower.includes(m))
+ ) {
+ return 'claude';
+ }
+ if (
+ CODEX_MARKERS.some((m) => cmdLineLower.includes(m)) ||
+ runtimeUserDataMarkers.codex.some((m) => cmdLineLower.includes(m))
+ ) {
+ return 'codex';
+ }
+ return null;
+}
+
+const POSIX_PS_ROW_RE = /^(\d+)\s+(\d+)\s+(.+)$/;
+
+/** POSIX: 一次 ps 全表,过滤"本进程直接子进程 + 命中 marker"。 */
+export function parsePosixAgentProcesses(
+ psOutput: string,
+ selfPid: number,
+): AgentProcessRow[] {
+ const rows: AgentProcessRow[] = [];
+ for (const raw of psOutput.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line) continue;
+ const match = line.match(POSIX_PS_ROW_RE);
+ if (!match) continue;
+ const pid = Number.parseInt(match[1], 10);
+ const ppid = Number.parseInt(match[2], 10);
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid) || ppid !== selfPid) continue;
+ const kind = classifyAgentCommandLine(match[3].toLowerCase());
+ if (kind) rows.push({ pid, kind });
+ }
+ return rows;
+}
+
+async function scanPosix(): Promise<AgentProcessRow[]> {
+ // -ww: macOS ps 默认按显示宽度截断 command 列,长路径(长用户名/重定向
+ // userData)会把 /claude-code/ marker 截掉导致扫描静默漏认;重复 -w 取消截断。
+ const { stdout } = await execFileAsync('ps', ['-Aww', '-o', 'pid=,ppid=,command='], {
+ encoding: 'utf8',
+ timeout: 5_000,
+ maxBuffer: 8 * 1024 * 1024,
+ });
+ return parsePosixAgentProcesses(stdout, process.pid);
+}
+
+async function scanWindows(): Promise<AgentProcessRow[]> {
+ // 与 claude-orphan-reaper 的 Windows 扫描同一套写法(含行尾管道符的坑,见其注释)。
+ const script = [
+ 'Get-CimInstance Win32_Process -Filter "Name=\'claude.exe\' OR Name=\'codex.exe\'" |',
+ 'ForEach-Object {',
+ ' $cmd = ([string]$_.CommandLine) -replace "`r|`n", " "',
+ ' Write-Output ("{0}|{1}|{2}" -f $_.ProcessId, $_.ParentProcessId, $cmd)',
+ '}',
+ ].join('\n');
+ const { stdout } = await execFileAsync(
+ 'powershell.exe',
+ ['-NoProfile', '-NonInteractive', '-Command', script],
+ { encoding: 'utf8', timeout: 10_000, windowsHide: true },
+ );
+ const rows: AgentProcessRow[] = [];
+ for (const raw of stdout.split(/\r?\n/)) {
+ const parts = raw.trim().split('|');
+ if (parts.length < 3) continue;
+ const pid = Number.parseInt(parts[0]?.trim() ?? '', 10);
+ const ppid = Number.parseInt(parts[1]?.trim() ?? '', 10);
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid) || ppid !== process.pid) continue;
+ const kind = classifyAgentCommandLine(parts.slice(2).join('|').toLowerCase());
+ if (kind) rows.push({ pid, kind });
+ }
+ return rows;
+}
+
+function defaultScanAgentProcesses(): Promise<AgentProcessRow[]> {
+ return process.platform === 'win32' ? scanWindows() : scanPosix();
+}
+
+function priorityValue(tier: AgentProcessPriority): number {
+ switch (tier) {
+ case 'low':
+ return os.constants.priority.PRIORITY_BELOW_NORMAL;
+ case 'lowest':
+ return os.constants.priority.PRIORITY_LOW;
+ default:
+ return os.constants.priority.PRIORITY_NORMAL;
+ }
+}
+
+/** macOS taskpolicy(背景 QoS 钳制)best-effort;非 darwin no-op。 */
+async function taskpolicy(args: string[], log: WatcherLogger): Promise<void> {
+ if (process.platform !== 'darwin') return;
+ try {
+ await execFileAsync('/usr/sbin/taskpolicy', args, { timeout: 5_000 });
+ } catch (err) {
+ log.debug('taskpolicy failed (best-effort, ignored)', {
+ args,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+}
+
+/**
+ * 提取 os.setPriority 失败的真实 errno。Node 把 libuv 失败包成 SystemError:
+ * 顶层 code 是 'ERR_SYSTEM_ERROR',可判定的 errno 在 err.info.code(bot review
+ * fresh evidence);plain ErrnoException 形态与 message 内的 uv 错误名做兜底。
+ */
+export function systemErrnoCode(err: unknown): string | undefined {
+ const e = err as NodeJS.ErrnoException & { info?: { code?: string } };
+ if (typeof e?.info?.code === 'string') return e.info.code;
+ if (typeof e?.code === 'string' && e.code !== 'ERR_SYSTEM_ERROR') return e.code;
+ const match = /\b(EACCES|EPERM|ESRCH)\b/.exec(String(e?.message ?? ''));
+ return match?.[1];
+}
+
+function makeDefaultApplyPriority(log: WatcherLogger) {
+ return async (
+ pid: number,
+ tier: AgentProcessPriority,
+ prevTier: AgentProcessPriority | undefined,
+ ): Promise<ApplyPriorityResult> => {
+ let result: ApplyPriorityResult = 'applied';
+ try {
+ os.setPriority(pid, priorityValue(tier));
+ } catch (err) {
+ const code = systemErrnoCode(err);
+ if (code === 'ESRCH') return 'process-gone';
+ if (code === 'EPERM' || code === 'EACCES') {
+ // POSIX 非特权进程不能调高优先级(normal←low←lowest 方向都算 raise):
+ // nice 停在原档。如实上报给调用方,不装成功(bot review P1)。
+ result = 'nice-raise-refused';
+ } else {
+ log.debug('setPriority failed', { pid, tier, code, error: String(err) });
+ }
+ }
+ // taskpolicy 钳制与 nice 独立:即使 nice 调不回,darwin 上仍按目标档调整钳制
+ // (lowest→low 清掉 -b 后,实际效果介于两档之间,是无特权下能达到的最优近似)。
+ if (tier === 'lowest') {
+ await taskpolicy(['-b', '-p', String(pid)], log);
+ } else if (prevTier === 'lowest') {
+ await taskpolicy(['-B', '-p', String(pid)], log);
+ }
+ return result;
+ };
+}
+
+export function createAgentProcessPriorityWatcher(
+ deps: AgentProcessPriorityWatcherDeps,
+): AgentProcessPriorityWatcher {
+ const { readPriority, scanAgentProcesses, applyPriority, log } = deps;
+ const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;
+ /**
+ * 已被本 watcher 处理过的进程账本。只记非 normal 档;恢复/退出即移除。
+ * tier 记的是**目标档**;niceStuck = POSIX 拒绝了本次 raise,nice 实际停在
+ * 更低优先级的旧档(darwin 钳制已按目标档调整)。仍按目标档入账是有意的:
+ * 无特权下重试永远失败,每 tick 重试只会空转 + 反复 spawn taskpolicy;
+ * 账本的职责是"别重复动它",真实状态由日志如实记录。
+ */
+ const applied = new Map<number, { tier: AgentProcessPriority; niceStuck: boolean }>();
+ let timer: ReturnType<typeof setInterval> | null = null;
+ let ticking = false;
+
+ async function tickOnce(): Promise<void> {
+ if (ticking) return; // 扫描慢于 interval 时跳过本 tick,不排队叠加
+ ticking = true;
+ try {
+ const desired = readPriority();
+ // 空闲快路径:设置为 normal 且没有欠恢复的进程 → 完全不扫进程表。
+ if (desired === 'normal' && applied.size === 0) return;
+ const rows = await scanAgentProcesses();
+ const alive = new Set(rows.map((r) => r.pid));
+ for (const pid of [...applied.keys()]) {
+ if (!alive.has(pid)) applied.delete(pid);
+ }
+ for (const row of rows) {
+ const prev = applied.get(row.pid);
+ if (desired === 'normal') {
+ if (prev === undefined) continue; // 没动过的进程绝不碰
+ const result = await applyPriority(row.pid, 'normal', prev.tier);
+ applied.delete(row.pid); // POSIX 恢复注定被拒,重试无意义(见账本注释)
+ log.info('agent process priority restore attempted', {
+ pid: row.pid,
+ kind: row.kind,
+ // nice-raise-refused = nice 停在降档值直到进程退出,新进程不受影响
+ niceRestored: result === 'applied',
+ });
+ } else if (prev?.tier !== desired) {
+ const result = await applyPriority(row.pid, desired, prev?.tier);
+ if (result === 'process-gone') {
+ applied.delete(row.pid);
+ } else if (result === 'nice-raise-refused') {
+ // lowest→low 这类升档:nice 卡在旧档,只有 darwin 钳制按目标档调整了。
+ // 入账目标档防空转重试,日志如实说明(不写"lowered")。
+ applied.set(row.pid, { tier: desired, niceStuck: true });
+ log.warn('agent process priority partially applied: nice stuck at previous tier', {
+ pid: row.pid,
+ kind: row.kind,
+ requestedTier: desired,
+ stuckAtTier: prev?.tier ?? 'unknown',
+ });
+ } else {
+ applied.set(row.pid, { tier: desired, niceStuck: false });
+ log.info('agent process priority lowered', {
+ pid: row.pid,
+ kind: row.kind,
+ tier: desired,
+ });
+ }
+ }
+ }
+ } catch (err) {
+ log.warn('agent process priority tick failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ ticking = false;
+ }
+ }
+
+ return {
+ start() {
+ if (timer) return;
+ timer = setInterval(() => {
+ void tickOnce();
+ }, intervalMs);
+ timer.unref?.();
+ },
+ stop() {
+ if (timer) {
+ clearInterval(timer);
+ timer = null;
+ }
+ },
+ tickOnce,
+ };
+}
+
+export const __testing = { makeDefaultApplyPriority };
+
+/** 生产入口:默认依赖(设置 store + 平台扫描 + os.setPriority/taskpolicy)组装并启动。 */
+export function startAgentProcessPriorityWatcher(): AgentProcessPriorityWatcher {
+ const log = createLogger('agent-process-priority');
+ try {
+ // userData 实际值派生 marker(XDG_CONFIG_HOME / --user-data-dir 重定向场景)。
+ registerUserDataMarkers(app.getPath('userData'));
+ } catch (err) {
+ log.warn('userData marker registration failed; static brand markers only', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ const watcher = createAgentProcessPriorityWatcher({
+ readPriority: () => readAgentResourceSettings().processPriority,
+ scanAgentProcesses: defaultScanAgentProcesses,
+ applyPriority: makeDefaultApplyPriority(log),
+ log,
+ });
+ watcher.start();
+ return watcher;
+}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index ad17459abc..3fe42f27a3 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -260,6 +260,7 @@ import {
installVoiceInputPowerRelease,
} from './voice-input/powerReleaseNotifier';
import { reapClaudeOrphansSync } from './claude-orphan-reaper';
+import { startAgentProcessPriorityWatcher } from './agent-process-priority';
import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService';
import { initNotificationService } from './notificationService';
import { getAgentIslandService, initAgentIslandService } from './agent-island/service.js';
@@ -972,6 +973,15 @@ try {
createLogger('claude-orphan-reaper').warn('initial reap threw', { error: String(err) });
}
+// ── agent 进程优先级降档 watcher(agent 资源占用治理)─────────────────────
+// 设置(processPriority)为 normal 且无欠恢复进程时,每 tick 零成本(不扫进程表);
+// interval 已 unref,进程退出不被它拖住。所有失败 best-effort,不影响启动。
+try {
+ startAgentProcessPriorityWatcher();
+} catch (err) {
+ createLogger('agent-process-priority').warn('watcher start threw', { error: String(err) });
+}
+
// ── 启动诊断 (issue #758) ────────────────────────────────────────────────
// 上次异常退出尸检 (run marker) + Crashpad 本地 minidump + crash dump 扫描。
// 必须在 app ready 前 (crashReporter.start 约束)、userData 定型后 (index.ts 的
diff --git a/apps/desktop/src/main/maker-host/__tests__/bashConcurrencyHook.test.ts b/apps/desktop/src/main/maker-host/__tests__/bashConcurrencyHook.test.ts
new file mode 100644
index 0000000000..4fa44714a0
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/bashConcurrencyHook.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { Logger } from '@cindy/maker-core';
+
+import {
+ createBashConcurrencyHooks,
+ mergeClaudeHooks,
+} from '../claude-hooks/bash-concurrency-hook';
+import type { CommandConcurrencyGate } from '../command-concurrency-gate';
+
+const fakeLogger = {
+ child: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ debug: vi.fn(),
+ error: vi.fn(),
+ child: vi.fn(),
+ }),
+} as unknown as Logger;
+
+function makeGate(): CommandConcurrencyGate & {
+ acquire: ReturnType<typeof vi.fn>;
+ release: ReturnType<typeof vi.fn>;
+ releaseSession: ReturnType<typeof vi.fn>;
+} {
+ return {
+ acquire: vi.fn().mockResolvedValue('immediate'),
+ release: vi.fn(),
+ releaseSession: vi.fn(),
+ snapshot: vi.fn(() => ({ running: 0, queued: 0 })),
+ };
+}
+
+const hookOptions = { signal: new AbortController().signal };
+
+const baseInput = {
+ session_id: 'session-1',
+ transcript_path: '/tmp/t',
+ cwd: '/tmp',
+};
+
+function preToolUseInput(toolName: string): never {
+ return {
+ ...baseInput,
+ hook_event_name: 'PreToolUse',
+ tool_name: toolName,
+ tool_input: { command: 'pnpm test' },
+ } as never;
+}
+
+describe('bash concurrency hooks', () => {
+ it('acquires a slot for Bash PreToolUse and always continues', async () => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const pre = hooks.PreToolUse![0];
+ expect(pre.matcher).toBe('Bash');
+
+ const result = await pre.hooks[0](preToolUseInput('Bash'), 'tool-1', hookOptions);
+ expect(result).toEqual({ continue: true });
+ expect(gate.acquire).toHaveBeenCalledWith({
+ toolUseId: 'tool-1',
+ sessionId: 'session-1',
+ signal: hookOptions.signal,
+ });
+ });
+
+ it('ignores non-Bash tools that the regex matcher can still hit (BashOutput)', async () => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const result = await hooks.PreToolUse![0].hooks[0](
+ preToolUseInput('BashOutput'),
+ 'tool-1',
+ hookOptions,
+ );
+ expect(result).toEqual({ continue: true });
+ expect(gate.acquire).not.toHaveBeenCalled();
+ });
+
+ it('skips gating when toolUseID is missing (no way to pair the release)', async () => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const result = await hooks.PreToolUse![0].hooks[0](
+ preToolUseInput('Bash'),
+ undefined,
+ hookOptions,
+ );
+ expect(result).toEqual({ continue: true });
+ expect(gate.acquire).not.toHaveBeenCalled();
+ });
+
+ it('fails open when gate.acquire throws', async () => {
+ const gate = makeGate();
+ gate.acquire.mockRejectedValueOnce(new Error('boom'));
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const result = await hooks.PreToolUse![0].hooks[0](
+ preToolUseInput('Bash'),
+ 'tool-1',
+ hookOptions,
+ );
+ expect(result).toEqual({ continue: true });
+ });
+
+ it.each([
+ ['PostToolUse' as const],
+ ['PostToolUseFailure' as const],
+ ['PermissionDenied' as const],
+ ])('releases the slot on %s', async (eventName) => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const matcher = hooks[eventName]![0];
+ expect(matcher.matcher).toBe('Bash');
+
+ const input = {
+ ...baseInput,
+ hook_event_name: eventName,
+ tool_name: 'Bash',
+ tool_input: {},
+ tool_use_id: 'tool-9',
+ } as never;
+ const result = await matcher.hooks[0](input, 'tool-9', hookOptions);
+ expect(result).toEqual({ continue: true });
+ expect(gate.release).toHaveBeenCalledWith('tool-9', expect.any(String));
+ });
+
+ it('does not release for non-Bash tool events', async () => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const input = {
+ ...baseInput,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'BashOutput',
+ tool_input: {},
+ tool_use_id: 'tool-9',
+ } as never;
+ await hooks.PostToolUse![0].hooks[0](input, 'tool-9', hookOptions);
+ expect(gate.release).not.toHaveBeenCalled();
+ });
+
+ it('cleans up the whole session on SessionEnd', async () => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ const input = {
+ ...baseInput,
+ hook_event_name: 'SessionEnd',
+ reason: 'other',
+ } as never;
+ const result = await hooks.SessionEnd![0].hooks[0](input, undefined, hookOptions);
+ expect(result).toEqual({ continue: true });
+ expect(gate.releaseSession).toHaveBeenCalledWith('session-1', 'session-end');
+ });
+
+ it('sets a PreToolUse matcher timeout comfortably above the queue wait ceiling', () => {
+ const gate = makeGate();
+ const hooks = createBashConcurrencyHooks(gate, fakeLogger);
+ // gate 默认排队上限 120s;matcher timeout 必须显著大于它,否则 SDK 会先掐 hook
+ expect(hooks.PreToolUse![0].timeout).toBeGreaterThanOrEqual(300);
+ });
+});
+
+describe('mergeClaudeHooks', () => {
+ it('concatenates matchers of the same event and keeps distinct events', () => {
+ const a = {
+ PreToolUse: [{ matcher: 'Read', hooks: [vi.fn()] }],
+ };
+ const b = {
+ PreToolUse: [{ matcher: 'Bash', hooks: [vi.fn()] }],
+ SessionEnd: [{ hooks: [vi.fn()] }],
+ };
+ const merged = mergeClaudeHooks(a, b);
+ expect(merged.PreToolUse?.map((m) => m.matcher)).toEqual(['Read', 'Bash']);
+ expect(merged.SessionEnd).toHaveLength(1);
+ });
+
+ it('skips empty matcher arrays', () => {
+ const merged = mergeClaudeHooks({ PreToolUse: [] }, {});
+ expect(merged.PreToolUse).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/commandConcurrencyGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/commandConcurrencyGate.test.ts
new file mode 100644
index 0000000000..a5bd962456
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/commandConcurrencyGate.test.ts
@@ -0,0 +1,261 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createCommandConcurrencyGate,
+ type CommandConcurrencyGate,
+} from '../command-concurrency-gate';
+
+const silentLog = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
+
+function makeGate(opts?: {
+ limit?: () => number;
+ queueWaitMaxMs?: number;
+ runningTtlMs?: number;
+}): { gate: CommandConcurrencyGate; setLimit: (n: number) => void } {
+ let limit = 2;
+ const gate = createCommandConcurrencyGate({
+ readMaxConcurrent: opts?.limit ?? (() => limit),
+ log: silentLog,
+ queueWaitMaxMs: opts?.queueWaitMaxMs,
+ runningTtlMs: opts?.runningTtlMs,
+ });
+ return { gate, setLimit: (n) => (limit = n) };
+}
+
+/** 让已 resolve 的 promise 回调有机会跑完(fake timers 下 microtask 仍即时)。 */
+async function settled(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('command concurrency gate', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it('admits immediately while under the limit', async () => {
+ const { gate } = makeGate();
+ await expect(gate.acquire({ toolUseId: 'a', sessionId: 's1' })).resolves.toBe('immediate');
+ await expect(gate.acquire({ toolUseId: 'b', sessionId: 's1' })).resolves.toBe('immediate');
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 0 });
+ });
+
+ it('admits everything without queueing when limit is 0 (unlimited)', async () => {
+ const { gate, setLimit } = makeGate();
+ setLimit(0);
+ for (let i = 0; i < 10; i += 1) {
+ await expect(gate.acquire({ toolUseId: `t${i}`, sessionId: 's1' })).resolves.toBe(
+ 'immediate',
+ );
+ }
+ expect(gate.snapshot()).toEqual({ running: 10, queued: 0 });
+ });
+
+ it('queues over-limit commands and admits them FIFO on release', async () => {
+ const { gate } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+
+ const admissions: string[] = [];
+ const c = gate.acquire({ toolUseId: 'c', sessionId: 's2' }).then((r) => {
+ admissions.push(`c:${r}`);
+ return r;
+ });
+ const d = gate.acquire({ toolUseId: 'd', sessionId: 's2' }).then((r) => {
+ admissions.push(`d:${r}`);
+ return r;
+ });
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 2 });
+
+ gate.release('a', 'test');
+ await settled();
+ expect(admissions).toEqual(['c:queued']);
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 1 });
+
+ gate.release('b', 'test');
+ await settled();
+ expect(admissions).toEqual(['c:queued', 'd:queued']);
+ await expect(c).resolves.toBe('queued');
+ await expect(d).resolves.toBe('queued');
+ });
+
+ it('does not let a new command jump a non-empty queue after the limit is raised', async () => {
+ const { gate, setLimit } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ const waiting = gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+ expect(gate.snapshot().queued).toBe(1);
+
+ // limit 热更调高:下一个 acquire 先 pump,老等待者 c 先占新槽,新命令 d 排它后面
+ setLimit(3);
+ const next = gate.acquire({ toolUseId: 'd', sessionId: 's1' });
+ await settled();
+ await expect(waiting).resolves.toBe('queued');
+ // d 进来时 c 已被 pump 放行,槽位 3/3 满,d 排队
+ expect(gate.snapshot()).toEqual({ running: 3, queued: 1 });
+ gate.release('a', 'test');
+ await expect(next).resolves.toBe('queued');
+ });
+
+ it('repumps queued waiters within one poll interval after the limit is raised (no acquire/release needed)', async () => {
+ const { gate, setLimit } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ const c = gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+ const d = gate.acquire({ toolUseId: 'd', sessionId: 's1' });
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 2 });
+
+ // limit 热更调高:没有任何 acquire/release 事件,repump 轮询必须自己唤醒队列
+ setLimit(4);
+ vi.advanceTimersByTime(1000);
+ await expect(c).resolves.toBe('queued');
+ await expect(d).resolves.toBe('queued');
+ expect(gate.snapshot()).toEqual({ running: 4, queued: 0 });
+ });
+
+ it('repumps everything when the limit is switched to unlimited mid-wait', async () => {
+ const { gate, setLimit } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ const waiting = gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+
+ setLimit(0);
+ vi.advanceTimersByTime(1000);
+ await expect(waiting).resolves.toBe('queued');
+ // 队列清空后 repump 轮询自停:继续推进时间不应产生任何状态变化
+ vi.advanceTimersByTime(10_000);
+ expect(gate.snapshot()).toEqual({ running: 3, queued: 0 });
+ });
+
+ it('fails open with wait-timeout after queueWaitMaxMs', async () => {
+ const { gate } = makeGate({ queueWaitMaxMs: 1000 });
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ const waiting = gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+
+ vi.advanceTimersByTime(1001);
+ await expect(waiting).resolves.toBe('wait-timeout');
+ // 超时放行仍登记 running,如实反映超载
+ expect(gate.snapshot()).toEqual({ running: 3, queued: 0 });
+ expect(silentLog.warn).toHaveBeenCalledWith(
+ expect.stringContaining('timed out'),
+ expect.objectContaining({ toolUseId: 'c' }),
+ );
+ });
+
+ it('resolves aborted when the signal fires while queued, without taking a slot', async () => {
+ const { gate } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ const controller = new AbortController();
+ const waiting = gate.acquire({
+ toolUseId: 'c',
+ sessionId: 's1',
+ signal: controller.signal,
+ });
+ controller.abort();
+ await expect(waiting).resolves.toBe('aborted');
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 0 });
+ // 之后到达的 release(c) 不应误伤任何在途槽位
+ gate.release('c', 'test');
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 0 });
+ });
+
+ it('resolves aborted immediately when the signal is already aborted', async () => {
+ const { gate } = makeGate();
+ const controller = new AbortController();
+ controller.abort();
+ await expect(
+ gate.acquire({ toolUseId: 'a', sessionId: 's1', signal: controller.signal }),
+ ).resolves.toBe('aborted');
+ expect(gate.snapshot()).toEqual({ running: 0, queued: 0 });
+ });
+
+ it('release is idempotent and unknown ids are no-ops', async () => {
+ const { gate } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ gate.release('a', 'test');
+ gate.release('a', 'test');
+ gate.release('never-acquired', 'test');
+ expect(gate.snapshot()).toEqual({ running: 0, queued: 0 });
+ });
+
+ it('releasing a queued id (e.g. PermissionDenied while waiting) cancels the wait', async () => {
+ const { gate } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ const waiting = gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+ gate.release('c', 'permission-denied');
+ await expect(waiting).resolves.toBe('aborted');
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 0 });
+ });
+
+ it('releaseSession clears running slots and cancels queued waiters of that session', async () => {
+ const { gate } = makeGate();
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's2' });
+ const s1Waiter = gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+ const s2Waiter = gate.acquire({ toolUseId: 'd', sessionId: 's2' });
+
+ gate.releaseSession('s1', 'session-end');
+ await settled();
+ await expect(s1Waiter).resolves.toBe('aborted');
+ // s1 释放了一个槽,s2 的等待者顶上
+ await expect(s2Waiter).resolves.toBe('queued');
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 0 });
+ });
+
+ it('reclaims stale running slots after the TTL (lost release events)', async () => {
+ const { gate } = makeGate({ runningTtlMs: 60_000 });
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+
+ vi.advanceTimersByTime(61_000);
+ // 下一次 acquire 触发 sweep:两个僵尸槽被回收,新命令直接放行
+ await expect(gate.acquire({ toolUseId: 'c', sessionId: 's1' })).resolves.toBe('immediate');
+ expect(gate.snapshot()).toEqual({ running: 1, queued: 0 });
+ expect(silentLog.warn).toHaveBeenCalledWith(
+ expect.stringContaining('stale slot'),
+ expect.objectContaining({ toolUseId: 'a' }),
+ );
+ });
+
+ it('treats a throwing limit reader as unlimited (fail-open)', async () => {
+ const { gate } = makeGate({
+ limit: () => {
+ throw new Error('boom');
+ },
+ });
+ for (let i = 0; i < 5; i += 1) {
+ await expect(gate.acquire({ toolUseId: `t${i}`, sessionId: 's1' })).resolves.toBe(
+ 'immediate',
+ );
+ }
+ expect(gate.snapshot()).toEqual({ running: 5, queued: 0 });
+ });
+
+ it('lowering the limit mid-flight blocks new admissions until running drains below it', async () => {
+ const { gate, setLimit } = makeGate();
+ setLimit(3);
+ await gate.acquire({ toolUseId: 'a', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'b', sessionId: 's1' });
+ await gate.acquire({ toolUseId: 'c', sessionId: 's1' });
+
+ setLimit(1);
+ const waiting = gate.acquire({ toolUseId: 'd', sessionId: 's1' });
+ expect(gate.snapshot()).toEqual({ running: 3, queued: 1 });
+ gate.release('a', 'test');
+ // 3 → 2,仍在 limit=1 之上,d 继续等
+ expect(gate.snapshot()).toEqual({ running: 2, queued: 1 });
+ gate.release('b', 'test');
+ // 2 → 1,仍不低于 limit=1,d 继续等
+ expect(gate.snapshot()).toEqual({ running: 1, queued: 1 });
+ gate.release('c', 'test');
+ await expect(waiting).resolves.toBe('queued');
+ expect(gate.snapshot()).toEqual({ running: 1, queued: 0 });
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/toolchainThreadCap.test.ts b/apps/desktop/src/main/maker-host/__tests__/toolchainThreadCap.test.ts
new file mode 100644
index 0000000000..9fc0624e32
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/toolchainThreadCap.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn(() => ''),
+ },
+}));
+
+vi.mock('../logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ },
+}));
+
+import {
+ computeToolchainThreadCapEnv,
+ recommendedToolchainThreads,
+} from '../toolchain-thread-cap';
+
+describe('recommendedToolchainThreads', () => {
+ it('gives half the cores for normal/low and a quarter for lowest', () => {
+ expect(recommendedToolchainThreads('normal', 10)).toBe(5);
+ expect(recommendedToolchainThreads('low', 10)).toBe(5);
+ expect(recommendedToolchainThreads('lowest', 10)).toBe(3);
+ });
+
+ it('never goes below 1', () => {
+ expect(recommendedToolchainThreads('lowest', 1)).toBe(1);
+ expect(recommendedToolchainThreads('low', 1)).toBe(1);
+ });
+});
+
+describe('computeToolchainThreadCapEnv', () => {
+ it('returns an empty object when the cap is disabled', () => {
+ expect(
+ computeToolchainThreadCapEnv(
+ { capToolchainThreads: false, processPriority: 'lowest' },
+ {},
+ 10,
+ ),
+ ).toEqual({});
+ });
+
+ it('injects the full variable set when enabled (POSIX)', () => {
+ expect(
+ computeToolchainThreadCapEnv(
+ { capToolchainThreads: true, processPriority: 'normal' },
+ {},
+ 8,
+ 'darwin',
+ ),
+ ).toEqual({
+ VITEST_MAX_FORKS: '4',
+ VITEST_MAX_THREADS: '4',
+ MAKEFLAGS: '-j4',
+ CARGO_BUILD_JOBS: '4',
+ });
+ });
+
+ it('skips MAKEFLAGS on Windows (nmake rejects GNU -j syntax)', () => {
+ const out = computeToolchainThreadCapEnv(
+ { capToolchainThreads: true, processPriority: 'normal' },
+ {},
+ 8,
+ 'win32',
+ );
+ expect(out.MAKEFLAGS).toBeUndefined();
+ expect(out.VITEST_MAX_FORKS).toBe('4');
+ expect(out.CARGO_BUILD_JOBS).toBe('4');
+ });
+
+ it('never overrides variables the user already has in the base env', () => {
+ const out = computeToolchainThreadCapEnv(
+ { capToolchainThreads: true, processPriority: 'normal' },
+ { MAKEFLAGS: '-j16', VITEST_MAX_FORKS: '9' },
+ 8,
+ 'darwin',
+ );
+ expect(out).toEqual({
+ VITEST_MAX_THREADS: '4',
+ CARGO_BUILD_JOBS: '4',
+ });
+ });
+
+ it('uses the lowest-tier divisor when priority is lowest', () => {
+ const out = computeToolchainThreadCapEnv(
+ { capToolchainThreads: true, processPriority: 'lowest' },
+ {},
+ 8,
+ 'darwin',
+ );
+ expect(out.VITEST_MAX_FORKS).toBe('2');
+ expect(out.MAKEFLAGS).toBe('-j2');
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts b/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts
new file mode 100644
index 0000000000..52380dca7a
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/agent-resource-settings-store.ts
@@ -0,0 +1,120 @@
+/**
+ * agent-resource-settings-store —— agent 命令行资源占用治理的 main 端持久化设置。
+ *
+ * 文件: <userData>/agent-resource-settings.json
+ *
+ * 默认值为「不干预」,与本设置引入前的行为完全一致:
+ * - maxConcurrentCommands: 0 (不限制 agent Bash 命令的全局并发)
+ * - processPriority: 'normal' (不降 agent 进程优先级)
+ * - capToolchainThreads: false (不注入工具链限核 env)
+ *
+ * 配置层级:当前为隐藏配置(无 Settings UI,直接改 JSON 文件或由 agent 代改)。
+ * 读取入口调 invalidateIfChanged(),文件被进程外修改后下次读取即生效,不需要重启;
+ * 后续 Settings UI 接入(IPC 写路径)复用同一 store。
+ */
+
+import { app } from 'electron';
+import path from 'node:path';
+
+import { desktopMakerLogger } from './logger-adapter.js';
+import {
+ createOverrideSettingsFile,
+ type OverrideSettingsState,
+} from './override-settings-file.js';
+
+const log = desktopMakerLogger.child('agent-resource-settings-store');
+
+/**
+ * agent 进程的 OS 调度优先级档位:
+ * - 'normal': 不干预(默认)。
+ * - 'low' : nice/BELOW_NORMAL —— agent 照常用满空闲核,但前台应用永远优先。
+ * - 'lowest': nice 最低档 + macOS 上额外 taskpolicy -b(压到能效核,风扇安静),
+ * 代价是 agent 任务明显变慢,agent 起的 dev server 也会变慢。
+ *
+ * POSIX 限制:非特权进程无法把已调低的优先级调回来——从 low/lowest 切回
+ * normal 只对**新启动**的 agent 进程生效,在跑的进程保持原档直到退出
+ * (macOS 的 taskpolicy 背景钳制是例外,可以清除)。
+ */
+export type AgentProcessPriority = 'normal' | 'low' | 'lowest';
+
+export interface AgentResourceSettings {
+ /**
+ * 所有本地 Claude 会话(含 Orca worker、subagent)同时在跑的 Bash 命令数上限;
+ * 超出的命令在启动前排队等待。0 = 不限(默认,历史行为)。
+ */
+ maxConcurrentCommands: number;
+ /** agent 进程(claude / codex 及其子进程)的调度优先级档位。 */
+ processPriority: AgentProcessPriority;
+ /**
+ * 是否向 agent 进程注入工具链限核 env(VITEST_MAX_FORKS / MAKEFLAGS 等),
+ * 防止单条测试/构建命令自己 fork 满全部核。只对新启动的 agent 进程生效;
+ * 用户 env 里已有的同名变量不覆盖。
+ */
+ capToolchainThreads: boolean;
+}
+
+const DEFAULTS: AgentResourceSettings = {
+ maxConcurrentCommands: 0,
+ processPriority: 'normal',
+ capToolchainThreads: false,
+};
+
+/** 上限的上限:超过这个值的并发治理已无意义,防手滑写进天文数字。IPC 写路径复用同一常量。 */
+export const MAX_CONCURRENT_COMMANDS_CAP = 64;
+
+function settingsFilePath(): string {
+ return path.join(app.getPath('userData'), 'agent-resource-settings.json');
+}
+
+function normalize(raw: unknown): AgentResourceSettings {
+ if (!raw || typeof raw !== 'object') return { ...DEFAULTS };
+ const r = raw as Record<string, unknown>;
+ return {
+ maxConcurrentCommands:
+ typeof r.maxConcurrentCommands === 'number' && Number.isFinite(r.maxConcurrentCommands)
+ ? clampInt(r.maxConcurrentCommands, 0, MAX_CONCURRENT_COMMANDS_CAP)
+ : DEFAULTS.maxConcurrentCommands,
+ processPriority:
+ r.processPriority === 'low' || r.processPriority === 'lowest'
+ ? r.processPriority
+ : DEFAULTS.processPriority,
+ capToolchainThreads: r.capToolchainThreads === true,
+ };
+}
+
+function clampInt(v: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, Math.floor(v)));
+}
+
+const store = createOverrideSettingsFile<AgentResourceSettings>({
+ filePath: settingsFilePath,
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'agent-resource',
+});
+
+export function readAgentResourceSettings(): AgentResourceSettings {
+ // 隐藏配置约定:直接改文件也是正式入口,读取前按 mtime 失效缓存。
+ store.invalidateIfChanged();
+ return store.read();
+}
+
+export function readAgentResourceSettingsState(): OverrideSettingsState<AgentResourceSettings> {
+ store.invalidateIfChanged();
+ return store.readState();
+}
+
+export function writeAgentResourceSetting<K extends keyof AgentResourceSettings>(
+ key: K,
+ value: AgentResourceSettings[K],
+): void {
+ store.writePatch({ [key]: value } as Partial<AgentResourceSettings>);
+ log.info('agent resource setting written', { key, value });
+}
+
+export function resetAgentResourceSettings(): AgentResourceSettings {
+ return store.reset();
+}
+
+export const __testing = { normalize };
diff --git a/apps/desktop/src/main/maker-host/claude-hooks/bash-concurrency-hook.ts b/apps/desktop/src/main/maker-host/claude-hooks/bash-concurrency-hook.ts
new file mode 100644
index 0000000000..cd7173d314
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/claude-hooks/bash-concurrency-hook.ts
@@ -0,0 +1,150 @@
+/**
+ * Bash 命令并发闸门 hooks —— 把 command-concurrency-gate 接到 Claude SDK 的
+ * in-process hook 事件上。
+ *
+ * 事件分工:
+ * - PreToolUse('Bash') : acquire —— 满员时在这里挂起排队,命令启动被推迟
+ * - PostToolUse('Bash') : release —— 命令正常结束
+ * - PostToolUseFailure('Bash') : release —— 命令失败/被打断
+ * - PermissionDenied('Bash') : release —— 审批被拒,命令没跑
+ * - SessionEnd : releaseSession —— 会话收尾清扫(防漏)
+ * 进程被杀等所有事件都收不到的情况,由 gate 内部 TTL 兜底回收。
+ *
+ * 关键保证:
+ * - **只挂起,不决策**: PreToolUse 永远不返回 permissionDecision,排队结束后
+ * 照常进入原 permission 流程(canUseTool / 审批 UI / auto 分类器),不打穿
+ * Orca / 协同模式那套审批链路。
+ * - **fail-open**: gate 异常、toolUseID 缺失、等待被中止(hook 超时 / 用户打断)
+ * 一律放行;本 hook 永远不能成为命令被卡死的原因。
+ * - matcher 是正则语义,'Bash' 也会命中 BashOutput 等工具名,hook 内一律做
+ * tool_name 严格等值判断(与 read-image-hook 同模式)。
+ *
+ * 已知边界(有意为之,v1 不处理):
+ * - run_in_background 的命令在 spawn 后立即返回 PostToolUse,槽位随即释放,
+ * 后台常驻进程不受并发上限约束(否则 dev server 会永久占槽)。
+ * - ask 档下等待用户审批期间槽位不释放;被它挤住的其它命令最多等
+ * queueWaitMaxMs 后 fail-open 放行。目标场景(auto / Full access 并行跑测试)
+ * 无此问题。
+ *
+ * 位置说明: 本文件在 host 层 (apps/desktop/src/main/maker-host/claude-hooks/),
+ * maker-core 不感知具体业务 hook —— 只暴露 AgentDeps.claudeHooks 注入点。
+ */
+
+import type {
+ HookCallback,
+ HookCallbackMatcher,
+ HookEvent,
+ PreToolUseHookInput,
+} from '@anthropic-ai/claude-agent-sdk';
+import type { Logger } from '@cindy/maker-core';
+
+import type { CommandConcurrencyGate } from '../command-concurrency-gate.js';
+
+const BASH_TOOL_NAME = 'Bash';
+
+/**
+ * PreToolUse matcher 超时(秒)。必须显著大于 gate 的排队上限(默认 120s),
+ * 否则 SDK 会先于 fail-open 把 hook 掐掉;留 3 倍余量。
+ */
+const PRE_TOOL_USE_TIMEOUT_SEC = 360;
+
+/** 释放类 hook 输入的公共字段(PostToolUse / PostToolUseFailure / PermissionDenied)。 */
+interface ReleaseHookFields {
+ tool_name?: string;
+ tool_use_id?: string;
+}
+
+/**
+ * 工厂函数: 绑定 gate + logger,返回可直接并入 AgentDeps.claudeHooks 的事件表。
+ * 注册侧用 mergeClaudeHooks 与其它 hook(如 read-image-hook)合并。
+ */
+export function createBashConcurrencyHooks(
+ gate: CommandConcurrencyGate,
+ logger: Logger,
+): Partial<Record<HookEvent, HookCallbackMatcher[]>> {
+ const log = logger.child('hook/bash-concurrency');
+
+ const preToolUse: HookCallback = async (input, toolUseID, options) => {
+ if (input.hook_event_name !== 'PreToolUse') {
+ return { continue: true };
+ }
+ const pre = input as PreToolUseHookInput;
+ if (pre.tool_name !== BASH_TOOL_NAME) {
+ return { continue: true };
+ }
+ if (!toolUseID) {
+ // 没有 id 就无法配对释放,宁可放行也不能占一个永远还不掉的槽。
+ log.debug('bash gate skipped: missing toolUseID', { sessionId: pre.session_id });
+ return { continue: true };
+ }
+ try {
+ const admission = await gate.acquire({
+ toolUseId: toolUseID,
+ sessionId: pre.session_id,
+ signal: options.signal,
+ });
+ if (admission === 'queued' || admission === 'wait-timeout') {
+ log.info('bash command admitted after queueing', {
+ toolUseId: toolUseID,
+ sessionId: pre.session_id,
+ admission,
+ });
+ }
+ } catch (err) {
+ // gate.acquire 设计上不 reject,这里是兜底防御:任何异常都放行。
+ log.warn('bash gate acquire threw, fail-open', {
+ toolUseId: toolUseID,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ return { continue: true };
+ };
+
+ const releaseFor = (reason: string): HookCallback => {
+ return async (input) => {
+ const fields = input as unknown as ReleaseHookFields;
+ if (fields.tool_name === BASH_TOOL_NAME && typeof fields.tool_use_id === 'string') {
+ gate.release(fields.tool_use_id, reason);
+ }
+ return { continue: true };
+ };
+ };
+
+ const sessionEnd: HookCallback = async (input) => {
+ gate.releaseSession(input.session_id, 'session-end');
+ return { continue: true };
+ };
+
+ return {
+ PreToolUse: [
+ {
+ matcher: BASH_TOOL_NAME,
+ hooks: [preToolUse],
+ timeout: PRE_TOOL_USE_TIMEOUT_SEC,
+ },
+ ],
+ PostToolUse: [{ matcher: BASH_TOOL_NAME, hooks: [releaseFor('post-tool-use')] }],
+ PostToolUseFailure: [{ matcher: BASH_TOOL_NAME, hooks: [releaseFor('post-tool-use-failure')] }],
+ PermissionDenied: [{ matcher: BASH_TOOL_NAME, hooks: [releaseFor('permission-denied')] }],
+ SessionEnd: [{ hooks: [sessionEnd] }],
+ };
+}
+
+/**
+ * 合并多份 claudeHooks 事件表:同事件的 matcher 数组按序拼接。
+ * SDK 对同事件多 matcher 逐个匹配执行,拼接不改变各自语义。
+ */
+export function mergeClaudeHooks(
+ ...tables: Array<Partial<Record<HookEvent, HookCallbackMatcher[]>>>
+): Partial<Record<HookEvent, HookCallbackMatcher[]>> {
+ const merged: Partial<Record<HookEvent, HookCallbackMatcher[]>> = {};
+ for (const table of tables) {
+ for (const [event, matchers] of Object.entries(table) as Array<
+ [HookEvent, HookCallbackMatcher[] | undefined]
+ >) {
+ if (!matchers || matchers.length === 0) continue;
+ merged[event] = [...(merged[event] ?? []), ...matchers];
+ }
+ }
+ return merged;
+}
diff --git a/apps/desktop/src/main/maker-host/command-concurrency-gate.ts b/apps/desktop/src/main/maker-host/command-concurrency-gate.ts
new file mode 100644
index 0000000000..41d6292761
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/command-concurrency-gate.ts
@@ -0,0 +1,294 @@
+/**
+ * command-concurrency-gate —— agent Bash 命令的全局并发闸门(跨 session 共享)。
+ *
+ * 背景: Claude 会话是每 session 一个独立子进程,命令由 agent 自己 spawn,Cindy
+ * 不接管执行——所以"并发上限"只能做成启动前的放行闸:PreToolUse hook 在这里
+ * acquire,满员则挂起排队;命令结束(成功/失败/被拒)后 release 唤醒队首。
+ *
+ * 设计不变量 —— fail-open 是唯一的失败方向,任何路径都不允许把命令永久卡死:
+ * - 排队超时 → 超额放行(over-admit)并记 warn 日志;
+ * - acquire 时 signal 已中止 / 等待中被中止(用户打断 turn)→ 立即返回、不占槽;
+ * - 释放事件丢失(进程被杀、hook 没触发)→ TTL 兜底回收 + SessionEnd 清扫;
+ * - limit 每次准入判断现读,设置热更即刻生效;limit <= 0 = 不限,但在途命令
+ * 仍登记 running,保证中途调低 limit 时计数不失真;
+ * - 队列非空期间跑一个轻量 repump 轮询(默认 1s,队列清空即停):设置 store 没有
+ * 变更事件,limit 被调高(或改为不限)后等待者最迟一个轮询周期内被唤醒,
+ * 不必干等下一次 acquire/release 或 120s fail-open。
+ *
+ * 释放语义: release 按 toolUseId 幂等,多事件重复释放(PostToolUse 与
+ * PermissionDenied 先后到达等)只生效一次。
+ */
+
+export interface CommandGateLogger {
+ info(message: string, meta?: Record<string, unknown>): void;
+ warn(message: string, meta?: Record<string, unknown>): void;
+ debug?(message: string, meta?: Record<string, unknown>): void;
+}
+
+export type CommandGateAdmission =
+ /** 有空槽,直接放行 */
+ | 'immediate'
+ /** 排过队,等到空槽后放行 */
+ | 'queued'
+ /** 排队超时,fail-open 超额放行 */
+ | 'wait-timeout'
+ /** 等待期间被中止(用户打断/hook 超时),未占槽,调用方直接放行 */
+ | 'aborted';
+
+export interface CommandConcurrencyGate {
+ /** 申请一个执行槽;resolve 即代表"可以开始执行"。永不 reject。 */
+ acquire(args: {
+ toolUseId: string;
+ sessionId: string;
+ signal?: AbortSignal;
+ }): Promise<CommandGateAdmission>;
+ /** 释放 toolUseId 对应的槽(幂等);也会移除同 id 的排队等待。 */
+ release(toolUseId: string, reason: string): void;
+ /** 会话结束时清扫其全部在途槽位与排队项。 */
+ releaseSession(sessionId: string, reason: string): void;
+ /** 观测用快照。 */
+ snapshot(): { running: number; queued: number };
+}
+
+export interface CommandConcurrencyGateOptions {
+ /** 每次准入判断现读的并发上限;<= 0 = 不限。 */
+ readMaxConcurrent: () => number;
+ log: CommandGateLogger;
+ /** 排队最长等待,超时 fail-open 放行。默认 120s。 */
+ queueWaitMaxMs?: number;
+ /** running 记录的 TTL,兜底回收释放事件丢失的槽。默认 30min。 */
+ runningTtlMs?: number;
+ /** 队列非空期间的 repump 轮询间隔(响应 limit 热更调高)。默认 1s。 */
+ repumpIntervalMs?: number;
+ now?: () => number;
+}
+
+const DEFAULT_QUEUE_WAIT_MAX_MS = 120_000;
+const DEFAULT_RUNNING_TTL_MS = 30 * 60_000;
+const DEFAULT_REPUMP_INTERVAL_MS = 1_000;
+
+interface RunningEntry {
+ sessionId: string;
+ admittedAt: number;
+}
+
+interface Waiter {
+ toolUseId: string;
+ sessionId: string;
+ resolve: (admission: CommandGateAdmission) => void;
+ timer: ReturnType<typeof setTimeout>;
+ signal?: AbortSignal;
+ onAbort?: () => void;
+}
+
+export function createCommandConcurrencyGate(
+ options: CommandConcurrencyGateOptions,
+): CommandConcurrencyGate {
+ const log = options.log;
+ const now = options.now ?? Date.now;
+ const queueWaitMaxMs = options.queueWaitMaxMs ?? DEFAULT_QUEUE_WAIT_MAX_MS;
+ const runningTtlMs = options.runningTtlMs ?? DEFAULT_RUNNING_TTL_MS;
+ const repumpIntervalMs = options.repumpIntervalMs ?? DEFAULT_REPUMP_INTERVAL_MS;
+
+ const running = new Map<string, RunningEntry>();
+ const queue: Waiter[] = [];
+ /**
+ * 队列非空期间的 repump 轮询:设置 store 没有变更事件,limit 被调高后必须有人
+ * 主动再跑 pump,否则等待者只能干等下一次 acquire/release 或 fail-open 超时
+ * (bot review P1)。队列清空即自停,空闲零成本。
+ */
+ let repumpTimer: ReturnType<typeof setInterval> | null = null;
+
+ function ensureRepumpTimer(): void {
+ if (repumpTimer !== null || queue.length === 0) return;
+ repumpTimer = setInterval(() => {
+ pump();
+ if (queue.length === 0 && repumpTimer !== null) {
+ clearInterval(repumpTimer);
+ repumpTimer = null;
+ }
+ }, repumpIntervalMs);
+ (repumpTimer as { unref?: () => void }).unref?.();
+ }
+
+ function readLimit(): number {
+ try {
+ const limit = options.readMaxConcurrent();
+ return Number.isFinite(limit) ? limit : 0;
+ } catch (err) {
+ // 设置读取失败不属于安全拦截,fail-open 到"不限"。
+ log.warn('command gate limit read failed, treating as unlimited', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return 0;
+ }
+ }
+
+ function hasFreeSlot(limit: number): boolean {
+ return limit <= 0 || running.size < limit;
+ }
+
+ /** 兜底回收:释放事件丢失(进程被杀等)的 running 记录超过 TTL 后强制清除。 */
+ function sweepStaleRunning(): void {
+ if (running.size === 0) return;
+ const deadline = now() - runningTtlMs;
+ for (const [id, entry] of running) {
+ if (entry.admittedAt <= deadline) {
+ running.delete(id);
+ log.warn('command gate reclaimed stale slot (release event lost?)', {
+ toolUseId: id,
+ sessionId: entry.sessionId,
+ heldMs: now() - entry.admittedAt,
+ });
+ }
+ }
+ }
+
+ function admit(toolUseId: string, sessionId: string): void {
+ running.set(toolUseId, { sessionId, admittedAt: now() });
+ }
+
+ function settleWaiter(waiter: Waiter, admission: CommandGateAdmission): void {
+ clearTimeout(waiter.timer);
+ if (waiter.signal && waiter.onAbort) {
+ waiter.signal.removeEventListener('abort', waiter.onAbort);
+ }
+ waiter.resolve(admission);
+ }
+
+ function removeWaiter(waiter: Waiter): boolean {
+ const idx = queue.indexOf(waiter);
+ if (idx < 0) return false;
+ queue.splice(idx, 1);
+ return true;
+ }
+
+ function pump(): void {
+ sweepStaleRunning();
+ while (queue.length > 0) {
+ const limit = readLimit();
+ if (!hasFreeSlot(limit)) return;
+ const waiter = queue.shift()!;
+ admit(waiter.toolUseId, waiter.sessionId);
+ settleWaiter(waiter, 'queued');
+ }
+ }
+
+ function acquire(args: {
+ toolUseId: string;
+ sessionId: string;
+ signal?: AbortSignal;
+ }): Promise<CommandGateAdmission> {
+ const { toolUseId, sessionId, signal } = args;
+ if (signal?.aborted) {
+ return Promise.resolve('aborted');
+ }
+ // 先清队列(内含 TTL sweep):limit 热更调高后,新空槽必须先给先来的等待者,
+ // 新命令不许越过非空队列插队(严格 FIFO)。
+ pump();
+ // 同 id 重复 acquire(理论上不发生):刷新登记时间即可,不重复占槽。
+ if (running.has(toolUseId)) {
+ admit(toolUseId, sessionId);
+ return Promise.resolve('immediate');
+ }
+ const limit = readLimit();
+ if (queue.length === 0 && hasFreeSlot(limit)) {
+ admit(toolUseId, sessionId);
+ return Promise.resolve('immediate');
+ }
+
+ return new Promise<CommandGateAdmission>((resolve) => {
+ const waiter: Waiter = {
+ toolUseId,
+ sessionId,
+ resolve,
+ signal,
+ timer: setTimeout(() => {
+ if (!removeWaiter(waiter)) return;
+ // 排队超时:fail-open 超额放行。仍登记 running,让计数如实反映超载。
+ admit(toolUseId, sessionId);
+ log.warn('command gate queue wait timed out, admitting over limit', {
+ toolUseId,
+ sessionId,
+ waitedMs: queueWaitMaxMs,
+ running: running.size,
+ limit: readLimit(),
+ });
+ settleWaiter(waiter, 'wait-timeout');
+ }, queueWaitMaxMs),
+ };
+ // Electron main 常驻,unref 防测试/退出被空转 timer 拖住(node timer 才有)。
+ (waiter.timer as { unref?: () => void }).unref?.();
+ if (signal) {
+ const onAbort = () => {
+ if (!removeWaiter(waiter)) return;
+ settleWaiter(waiter, 'aborted');
+ };
+ waiter.onAbort = onAbort;
+ signal.addEventListener('abort', onAbort, { once: true });
+ }
+ queue.push(waiter);
+ ensureRepumpTimer();
+ log.debug?.('command gate queued', {
+ toolUseId,
+ sessionId,
+ running: running.size,
+ queued: queue.length,
+ limit,
+ });
+ });
+ }
+
+ function release(toolUseId: string, reason: string): void {
+ const entry = running.get(toolUseId);
+ if (entry) {
+ running.delete(toolUseId);
+ log.debug?.('command gate released', {
+ toolUseId,
+ reason,
+ heldMs: now() - entry.admittedAt,
+ running: running.size,
+ queued: queue.length,
+ });
+ pump();
+ return;
+ }
+ // 等待中的同 id 被释放(如 PermissionDenied 先到):撤出队列,按 aborted 放行。
+ const waiter = queue.find((w) => w.toolUseId === toolUseId);
+ if (waiter && removeWaiter(waiter)) {
+ settleWaiter(waiter, 'aborted');
+ }
+ }
+
+ function releaseSession(sessionId: string, reason: string): void {
+ let removed = 0;
+ for (const [id, entry] of running) {
+ if (entry.sessionId === sessionId) {
+ running.delete(id);
+ removed += 1;
+ }
+ }
+ const waiters = queue.filter((w) => w.sessionId === sessionId);
+ for (const waiter of waiters) {
+ if (removeWaiter(waiter)) {
+ settleWaiter(waiter, 'aborted');
+ }
+ }
+ if (removed > 0 || waiters.length > 0) {
+ log.info('command gate session cleanup', {
+ sessionId,
+ reason,
+ releasedRunning: removed,
+ cancelledQueued: waiters.length,
+ });
+ pump();
+ }
+ }
+
+ return {
+ acquire,
+ release,
+ releaseSession,
+ snapshot: () => ({ running: running.size, queued: queue.length }),
+ };
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 1fa80a0b2c..0f5f6df8b7 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -68,7 +68,13 @@ import {
} from '../remote-ssh/agent-proxy.js';
import { openCcManagerSession } from './cc-manager-client.js';
import { getRemoteClaudeBinaryPath } from '../remote-ssh/cc-manager-install.js';
+import {
+ createBashConcurrencyHooks,
+ mergeClaudeHooks,
+} from './claude-hooks/bash-concurrency-hook.js';
import { createReadImageHook } from './claude-hooks/read-image-hook.js';
+import { readAgentResourceSettings } from './agent-resource-settings-store.js';
+import { createCommandConcurrencyGate } from './command-concurrency-gate.js';
import { deriveAvailableModels, refreshCatalogDerivedModels } from './catalog-to-descriptors.js';
import { clearChatgptBridgeCredentialCache } from './anthropic-responses-bridge-host.js';
import {
@@ -657,6 +663,12 @@ export function getMaker(): Maker {
...createDesktopMcpProviders(makerMemoryProviderDeps),
orcaWorkerBridgeProvider,
];
+ // agent Bash 命令的全局并发闸门(跨所有本地 cc session / worker / subagent 共享)。
+ // 上限每次准入判断现读设置文件,热更即刻生效;默认 0 = 不限 = 不排队。
+ const commandConcurrencyGate = createCommandConcurrencyGate({
+ readMaxConcurrent: () => readAgentResourceSettings().maxConcurrentCommands,
+ log: desktopMakerLogger.child('command-gate'),
+ });
const claudeAgent = new ClaudeCodeAgent({
auth: desktopClaudeAuthAdapter,
runtimeConfig: buildDesktopClaudeRuntimeConfig(getClaudeEndpoint),
@@ -696,17 +708,23 @@ export function getMaker(): Maker {
// WebP 副本, 把 Read 的 file_path 改写到副本路径再交给 SDK (原图不动).
// 解决 agent 自主 Read 大图把 vision context 撑爆的问题 (用户附图那条路本来
// 就走压缩, 但 agent 自己调 Read 绕过了).
+ // - bash-concurrency-hooks: agent Bash 命令的全局并发闸门(跨 session)。
+ // PreToolUse 满员挂起排队, Post/Failure/Denied/SessionEnd 释放;
+ // maxConcurrentCommands 默认 0 = 不限 = 行为与无此 hook 时一致。
// (slack-empty-cursor-hook 已随 slack-official MCP 集成退役 2026-07-15:
// 它只认老集成的 mcp__slack__* 工具名;空 cursor 清洗移入 cindy-slack
// 意识的 slack_call_tool。)
- claudeHooks: {
- PreToolUse: [
- {
- matcher: 'Read',
- hooks: [createReadImageHook(desktopMakerLogger)],
- },
- ],
- },
+ claudeHooks: mergeClaudeHooks(
+ {
+ PreToolUse: [
+ {
+ matcher: 'Read',
+ hooks: [createReadImageHook(desktopMakerLogger)],
+ },
+ ],
+ },
+ createBashConcurrencyHooks(commandConcurrencyGate, desktopMakerLogger),
+ ),
registerClaudeSubagentTask: (task) => claudeSubagentUsageBridge.registerTask(task),
getClaudeSubagentTaskUsage: (taskId) => claudeSubagentUsageBridge.getTaskUsage(taskId),
// 远端 Claude 会话的路由 materialization:把该会话真实上游 + 鉴权 + 定制头解析成 cc
diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.ts
index bbe781c914..d52bf2b8e1 100644
--- a/apps/desktop/src/main/maker-host/runtime-configs.ts
+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts
@@ -22,6 +22,7 @@ import hostSystemPrompt from './host-system-prompt.md?raw';
import { readCompactionPct } from './compaction-settings-store.js';
import { readMemorySettings } from './memory-settings-store.js';
import { readSubagentModelSettings } from './subagent-model-settings-store.js';
+import { toolchainThreadCapEnv } from './toolchain-thread-cap.js';
// host 层 system prompt 拼接:先 host 共用段 (host-system-prompt.md),再 agent 专属段
// (claude-system-prompt.md / codex-system-prompt.md)。空段被过滤,避免出现孤零零的 \n\n。
@@ -128,11 +129,15 @@ export function buildDesktopClaudeRuntimeConfig(endpointFn: () => string): Agent
// 调用 —— gateway-key spawn(显式 XD source / SSH remote)保持禁归因且不读钥匙串,
// 其余形态按**当时**的 Claude.ai 订阅连接态决定(判据与 proxy 同源)。会话中途
// 连/断订阅只影响新 spawn —— 与 cc 子进程凭证冻结语义一致。
- behaviorFlags: (ctx) =>
- claudeBehaviorFlagsForSpawn({
+ behaviorFlags: (ctx) => ({
+ ...claudeBehaviorFlagsForSpawn({
credentialMode: ctx.credentialMode,
oauthConnected: hasClaudeAiOAuth,
}),
+ // 工具链限核 env(agent 资源占用治理):只对本机 spawn 注入 —— 值按本机
+ // 核数算,远端机器的资源不归本设置管。设置关闭时为空对象,零影响。
+ ...(ctx.spawnMode === 'remote' ? {} : toolchainThreadCapEnv()),
+ }),
// xdt-maker 产品级 system prompt 注入:host 共用段 (host-system-prompt.md)
// + Claude 专属段 (claude-system-prompt.md),按顺序拼接后给 maker-core append。
systemPrompt: composeHostPrompt(claudeSystemPrompt),
@@ -222,11 +227,16 @@ function resolveSubagentModelForRoute(
}
/**
- * Codex 运行时配置:当前没有 proxy URL 覆盖,也没有业务 flag。
+ * Codex 运行时配置:当前没有 proxy URL 覆盖。
* systemPrompt 已接通 —— codex agent 在 thread/start 时跟 engine append 拼成
* developerInstructions 注入 codex 子进程 (见 codex/index.ts)。
*/
export const desktopCodexRuntimeConfig: AgentRuntimeConfig = {
+ // 工具链限核 env(agent 资源占用治理)。注意:远端 codex spawn 也会执行
+ // buildCodexEnv(其产物随后被远端 transport 整体丢弃,见 codex/index.ts:1917
+ // 附近注释),所以这里仍按 spawnMode 分流让代码自证,不依赖"远端不走本函数"
+ // 这种会过期的假设(对抗式预审发现)。
+ behaviorFlags: (ctx) => (ctx.spawnMode === 'remote' ? {} : toolchainThreadCapEnv()),
// host 共用段 (host-system-prompt.md) + Codex 专属段 (codex-system-prompt.md)。
systemPrompt: composeHostPrompt(codexSystemPrompt),
pathPrepends: [bundledRipgrepDir()],
diff --git a/apps/desktop/src/main/maker-host/toolchain-thread-cap.ts b/apps/desktop/src/main/maker-host/toolchain-thread-cap.ts
new file mode 100644
index 0000000000..9f6c234c60
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/toolchain-thread-cap.ts
@@ -0,0 +1,77 @@
+/**
+ * toolchain-thread-cap —— 工具链限核 env 注入(agent 资源占用治理第二层)。
+ *
+ * 动机: 并发闸门(command-concurrency-gate)只管"几条命令同时跑",管不住单条
+ * 重命令自己 fork 满全部核(vitest/jest 默认按核数起 worker,一条 `pnpm test`
+ * 就能把 10 核吃满)。对认环境变量的主流工具链,在 agent 进程 env 里注入
+ * 上限值,其 spawn 的所有子命令自动继承。
+ *
+ * 边界(有意为之):
+ * - 只注入「构建/测试并行度」类变量;不碰 GOMAXPROCS / UV_THREADPOOL_SIZE 这类
+ * 会改变被测程序运行时语义的变量(会掩盖/制造并发 bug,agent 测试结论失真)。
+ * - 用户 env 已有的同名变量一律不覆盖(用户显式设置优先)。
+ * - jest 等只认 CLI 参数的工具管不住 —— 那部分由进程优先级降档兜底。
+ * - env 是 spawn 期快照:改设置只影响新启动的 agent 会话进程。
+ * - 只对本机 spawn 注入;远端(SSH)机器的核数与资源不归本设置管。
+ */
+
+import os from 'node:os';
+
+import type {
+ AgentProcessPriority,
+ AgentResourceSettings,
+} from './agent-resource-settings-store.js';
+import { readAgentResourceSettings } from './agent-resource-settings-store.js';
+
+/**
+ * 推荐并行度: low/normal 档给一半核,lowest 档给四分之一,至少 1。
+ * 目标是"agent 干活但留出交互余量",不追求精确公平。
+ */
+export function recommendedToolchainThreads(
+ priority: AgentProcessPriority,
+ cores: number = os.availableParallelism(),
+): number {
+ const divisor = priority === 'lowest' ? 4 : 2;
+ return Math.max(1, Math.ceil(cores / divisor));
+}
+
+/**
+ * 纯函数形态(可测):按给定设置/基础 env/核数计算应注入的 env 增量。
+ * baseEnv 已有的键被跳过 —— 返回值只含"确实要新增"的变量。
+ */
+export function computeToolchainThreadCapEnv(
+ settings: Pick<AgentResourceSettings, 'capToolchainThreads' | 'processPriority'>,
+ baseEnv: NodeJS.ProcessEnv,
+ cores?: number,
+ platform: NodeJS.Platform = process.platform,
+): Record<string, string> {
+ if (!settings.capToolchainThreads) return {};
+ const threads = recommendedToolchainThreads(settings.processPriority, cores);
+ const desired: Record<string, string> = {
+ // vitest: forks 池(默认)与 threads 池各有独立上限变量,都设
+ VITEST_MAX_FORKS: String(threads),
+ VITEST_MAX_THREADS: String(threads),
+ // cargo build 并行度
+ CARGO_BUILD_JOBS: String(threads),
+ };
+ if (platform !== 'win32') {
+ // make 系(node-gyp / 原生依赖构建等)。Windows 跳过:MSVC 工具链下 cmake/qmake
+ // 可能生成 NMake Makefiles,nmake 不认 GNU Make 的 -j 语法,继承到会直接报错
+ // 中止构建,而不是静默忽略(对抗式预审发现)。
+ desired.MAKEFLAGS = `-j${threads}`;
+ }
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(desired)) {
+ if (baseEnv[key] === undefined) out[key] = value;
+ }
+ return out;
+}
+
+/**
+ * 生产入口: 读当前设置,返回应合入 agent spawn env 的增量。
+ * 设置关闭时返回空对象(零行为变化)。供 runtime-configs 的 behaviorFlags 消费,
+ * Claude 与 Codex 共用;调用方负责"远端 spawn 不注入"的分流。
+ */
+export function toolchainThreadCapEnv(): Record<string, string> {
+ return computeToolchainThreadCapEnv(readAgentResourceSettings(), process.env);
+}
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts
index 31cf91e2de..f15f240486 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/env-builder.test.ts
@@ -73,7 +73,7 @@ describe('buildClaudeEnv', () => {
expect(env.ANTHROPIC_API_KEY).toBe('key');
});
- it('evaluates function-form behaviorFlags with the spawn credentialMode', async () => {
+ it('evaluates function-form behaviorFlags with the spawn credentialMode and spawnMode', async () => {
const behaviorFlags = vi.fn(() => ({ CLAUDE_CODE_ATTRIBUTION_HEADER: '0' }));
const env = await buildClaudeEnv(
@@ -82,10 +82,28 @@ describe('buildClaudeEnv', () => {
{ credentialMode: 'gateway-key' },
);
- expect(behaviorFlags).toHaveBeenCalledWith({ credentialMode: 'gateway-key' });
+ expect(behaviorFlags).toHaveBeenCalledWith({
+ credentialMode: 'gateway-key',
+ spawnMode: 'local',
+ });
expect(env.CLAUDE_CODE_ATTRIBUTION_HEADER).toBe('0');
});
+ it('marks remote spawns so hosts can skip local-only behavior flags', async () => {
+ const behaviorFlags = vi.fn(() => ({}));
+
+ await buildClaudeEnv(
+ createAuthAdapter(),
+ { behaviorFlags },
+ { credentialMode: 'gateway-key', mode: 'remote' },
+ );
+
+ expect(behaviorFlags).toHaveBeenCalledWith({
+ credentialMode: 'gateway-key',
+ spawnMode: 'remote',
+ });
+ });
+
it('lets behaviorFlags override an inherited CLAUDE_CODE_ATTRIBUTION_HEADER from the host env', async () => {
// local spawn 继承宿主 process.env:宿主 shell export 过 =0 时,flags 缺席压不住
// 继承值 —— 保留归因必须显式 '1'(desktop issue #758 的环境继承回归面)。
diff --git a/packages/maker-core/src/agents/claude-code/env-builder.ts b/packages/maker-core/src/agents/claude-code/env-builder.ts
index 82c32898da..99f0a2f5af 100644
--- a/packages/maker-core/src/agents/claude-code/env-builder.ts
+++ b/packages/maker-core/src/agents/claude-code/env-builder.ts
@@ -285,10 +285,11 @@ export async function buildClaudeEnv(
const cleanEnv = mode === 'remote' ? {} : cleanProcessEnv();
const env: Record<string, string> = { ...cleanEnv };
- // 函数形态按本次 spawn 的凭证形态求值(如 attribution 归因块只对 gateway-key 禁用)。
+ // 函数形态按本次 spawn 的凭证形态求值(如 attribution 归因块只对 gateway-key 禁用);
+ // spawnMode 让 host 区分本机/远端(只对本机有意义的 flag 不注到远端)。
const behaviorFlags =
typeof runtimeConfig.behaviorFlags === 'function'
- ? runtimeConfig.behaviorFlags({ credentialMode: options.credentialMode })
+ ? runtimeConfig.behaviorFlags({ credentialMode: options.credentialMode, spawnMode: mode })
: runtimeConfig.behaviorFlags;
if (behaviorFlags) {
Object.assign(env, behaviorFlags);
diff --git a/packages/maker-core/src/agents/codex/env-builder.ts b/packages/maker-core/src/agents/codex/env-builder.ts
index 623b415ea2..db7a81fdbe 100644
--- a/packages/maker-core/src/agents/codex/env-builder.ts
+++ b/packages/maker-core/src/agents/codex/env-builder.ts
@@ -44,10 +44,13 @@ export async function buildCodexEnv(
if (typeof v === 'string') env[k] = v;
}
- // 函数形态按 spawn 凭证形态求值(与 claude-code/env-builder 同语义;Codex 当前无业务 flag)。
+ // 函数形态按 spawn 凭证形态求值(与 claude-code/env-builder 同语义)。
+ // spawnMode 恒传 'local':本函数产出的 env 只被**本地** transport 消费——远端
+ // spawn 虽也会执行到这里,但产物随后被远端 daemon transport 整体丢弃(见
+ // codex/index.ts 远端路径注释),真正落到子进程的只有本地分支。
const behaviorFlags =
typeof runtimeConfig.behaviorFlags === 'function'
- ? runtimeConfig.behaviorFlags({ credentialMode: options.credentialMode })
+ ? runtimeConfig.behaviorFlags({ credentialMode: options.credentialMode, spawnMode: 'local' })
: runtimeConfig.behaviorFlags;
if (behaviorFlags) {
Object.assign(env, behaviorFlags);
diff --git a/packages/maker-core/src/interfaces/runtime-config.ts b/packages/maker-core/src/interfaces/runtime-config.ts
index 5ea2b565d0..54f11987e4 100644
--- a/packages/maker-core/src/interfaces/runtime-config.ts
+++ b/packages/maker-core/src/interfaces/runtime-config.ts
@@ -13,6 +13,13 @@ import type { AgentCredentialMode } from './auth-adapter.js';
/** 函数形态 behaviorFlags 的入参:本次 spawn 的凭证形态(undefined = 未显式指定,走 adapter fallback)。 */
export interface BehaviorFlagsContext {
credentialMode?: AgentCredentialMode;
+ /**
+ * 本次 spawn 落在哪台机器:'local' = 本机子进程,'remote' = 远端 daemon。
+ * host 据此决定"只对本机有意义"的 flag(如按本机核数算的工具链限核 env)
+ * 要不要注入 —— 本机核数注到远端机器纯属错误值。undefined 视同 'local'
+ * (未接入该字段的调用方保持旧行为)。
+ */
+ spawnMode?: 'local' | 'remote';
}
export interface AgentRuntimeConfig {