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。

fix(ios-simulator): restore external workflow fallback

JiangJiahaofa418f900560
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts
index b5081c06a3..9ba00e2dd5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts
@@ -1,10 +1,7 @@
import { describe, expect, it } from 'vitest';
import type { InstalledGhost } from '../../../shared/ghost.js';
-import {
- resolveIOSSimulatorPluginAccess,
- shouldEnforceIOSSimulatorShellPolicy,
-} from '../iosSimulatorPluginGate.js';
+import { resolveIOSSimulatorPluginAccess } from '../iosSimulatorPluginGate.js';
function ghost(id: string, enabled: boolean, slots: string[] = ['ios-simulator']): InstalledGhost {
return {
@@ -70,36 +67,3 @@ describe('iOS Simulator plugin Host gate', () => {
});
});
});
-
-describe('embedded Simulator shell guard scope', () => {
- it('applies while the plugin grants access', () => {
- expect(
- shouldEnforceIOSSimulatorShellPolicy({
- pluginAccessAllowed: true,
- hostRuntimeActive: false,
- }),
- ).toBe(true);
- });
-
- it('stops blocking the user own Xcode tooling once the capability is gated off', () => {
- // Without the plugin there is no embedded simulator to protect, and the
- // denial would point at a cindy_ios_simulator tool the gate has removed.
- expect(
- shouldEnforceIOSSimulatorShellPolicy({
- pluginAccessAllowed: false,
- hostRuntimeActive: false,
- }),
- ).toBe(false);
- });
-
- it('keeps protecting a runtime this process already installed', () => {
- // An instance booted while the plugin was enabled stays Cindy-owned after a
- // disable, so a shell shutdown would race Cindy's own cleanup.
- expect(
- shouldEnforceIOSSimulatorShellPolicy({
- pluginAccessAllowed: false,
- hostRuntimeActive: true,
- }),
- ).toBe(true);
- });
-});
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 57671db981..bf9ad78820 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3402,12 +3402,14 @@ const opened = await cindy.iosSimulator.request({
在 Host 面板里选择设备;连续请求会限速;
- panel.html 保持零桥。面板要使用本槽时,按 §5 先 \`/wake\`,再用同源
BroadcastChannel 把请求交给 main.js,由 main.js 调 \`cindy.iosSimulator.request\`;
-- Agent 构建、安装、启动与 UI 操作继续调用 Host 注册的 \`cindy_ios_simulator\` MCP。
- 插件 Skill 可以编排这套工作流,但不要用 shell 打开外部 Simulator.app,也不要重复
- 打包一份 WDA/Sidecar;
+- 插件 Skill 选择内嵌路线后,Agent 构建、安装、启动与 UI 操作调用 Host 注册的
+ \`cindy_ios_simulator\` MCP,不要重复打包一份 WDA/Sidecar。内嵌能力不存在或不可用时,
+ Skill 可以按用户目标与普通权限规则改走外部 Xcode、Simulator.app、\`simctl\` 或
+ Computer Use;Host 不会把这些外部操作自动转换为内嵌调用;
- 本能力仅存在于带该槽的 Cindy Desktop。当前 Host 遇到未来 schema 或未知 capability
slot 时会把包识别为“需要更新 Cindy”,而不是误报插件非法。已发布的旧 Host 无法追改;
- Skill 在 MCP 不存在时仍必须引导用户升级 Cindy,不要降级成 shell 或 Node 替代实现。
+ Skill 在 MCP 不存在时必须说明内嵌路线不可用;如果用户目标不依赖 Cindy viewer,
+ 可以继续使用正常的外部工具链,否则再引导用户升级 Cindy。
## 5. 面板(panel.html/css/js)
diff --git a/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts b/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts
index f3a2d99876..d8d3b78d94 100644
--- a/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts
+++ b/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts
@@ -23,30 +23,6 @@ function pluginActionData(
};
}
-/**
- * Whether the shell guard that blocks external `simctl` / `Simulator.app` use
- * should still apply.
- *
- * That guard exists to protect the ownership, admission, viewer and cleanup
- * contracts of Cindy's *embedded* simulator. With no plugin there is no embedded
- * simulator to protect, and blocking the user's own Xcode tooling — while
- * pointing them at a `cindy_ios_simulator` tool that this gate has just removed
- * — is a dead end rather than a boundary.
- *
- * The runtime condition is the safety half: a simulator instance booted while
- * the plugin was enabled stays Cindy-owned after it is disabled, and a shell
- * `simctl shutdown` would then race Cindy's own cleanup. `hostRuntimeActive` is
- * deliberately coarser than "an instance is live" because the Host exposes no
- * synchronous instance snapshot, and erring toward keeping the guard on is the
- * safe direction.
- */
-export function shouldEnforceIOSSimulatorShellPolicy(state: {
- pluginAccessAllowed: boolean;
- hostRuntimeActive: boolean;
-}): boolean {
- return state.pluginAccessAllowed || state.hostRuntimeActive;
-}
-
/**
* Resolve the live product gate for Cindy's Host-owned iOS Simulator.
*
@@ -65,7 +41,7 @@ export function resolveIOSSimulatorPluginAccess(
allowed: false,
errorCode: 'IOS_SIMULATOR_PLUGIN_REQUIRED',
message:
- "Cindy's embedded iOS Simulator requires the iOS Simulator plugin. Ask the user to open Plugins → Marketplace, install “iOS Simulator”, and enable it. Do not retry until the plugin is installed.",
+ "Cindy's embedded iOS Simulator requires the iOS Simulator plugin. The embedded route is unavailable until the user installs and enables “iOS Simulator” from Plugins → Marketplace; other iOS workflows are unaffected.",
data: pluginActionData('not-installed', 'install-plugin'),
};
}
@@ -85,7 +61,7 @@ export function resolveIOSSimulatorPluginAccess(
allowed: false,
errorCode: 'IOS_SIMULATOR_DISABLED',
message:
- 'The iOS Simulator plugin is disabled for the current project. Ask the user to enable it for this working directory before retrying.',
+ 'The embedded iOS Simulator plugin is disabled for the current project. Enable it for this working directory before retrying the embedded tool; other iOS workflows are unaffected.',
data: pluginActionData('disabled-in-workdir', 'enable-plugin', workdirDisabled),
};
}
@@ -96,7 +72,7 @@ export function resolveIOSSimulatorPluginAccess(
allowed: false,
errorCode: 'IOS_SIMULATOR_PLUGIN_DISABLED',
message:
- 'The iOS Simulator plugin is installed but disabled. Ask the user to enable it on the Plugins page before retrying.',
+ 'The embedded iOS Simulator plugin is installed but disabled. Enable it on the Plugins page before retrying the embedded tool; other iOS workflows are unaffected.',
data: pluginActionData('disabled', 'enable-plugin', disabled),
};
}
@@ -105,7 +81,7 @@ export function resolveIOSSimulatorPluginAccess(
allowed: false,
errorCode: 'IOS_SIMULATOR_PLUGIN_DISABLED',
message:
- 'The installed iOS Simulator plugin is unavailable in the current Cindy session. Ask the user to open the Plugins page and make the plugin available before retrying.',
+ 'The installed embedded iOS Simulator plugin is unavailable in the current Cindy session. Make it available from the Plugins page before retrying the embedded tool; other iOS workflows are unaffected.',
data: pluginActionData('session-unavailable', 'enable-plugin', candidates[0]),
};
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/iosSimulatorShellHook.test.ts b/apps/desktop/src/main/maker-host/__tests__/iosSimulatorShellHook.test.ts
deleted file mode 100644
index 9d7a595d1c..0000000000
--- a/apps/desktop/src/main/maker-host/__tests__/iosSimulatorShellHook.test.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import type { Logger } from '@cindy/maker-core';
-
-import { createIOSSimulatorShellGuardHook } from '../claude-hooks/ios-simulator-shell-hook.js';
-
-const describeMac = process.platform === 'darwin' ? describe : describe.skip;
-
-function createLoggerSpy(): { logger: Logger; warn: ReturnType<typeof vi.fn> } {
- const warn = vi.fn();
- const logger = {
- trace: vi.fn(),
- debug: vi.fn(),
- info: vi.fn(),
- warn,
- error: vi.fn(),
- fatal: vi.fn(),
- child: () => logger,
- } as unknown as Logger;
- return { logger, warn };
-}
-
-describeMac('iOS Simulator shell guard hook', () => {
- it('denies bypass commands without persisting command text in logs', async () => {
- const { logger, warn } = createLoggerSpy();
- const hook = createIOSSimulatorShellGuardHook(logger);
- const command = 'API_TOKEN=super-secret xcrun simctl boot DEVICE';
-
- const result = await hook(
- {
- session_id: 'session-1',
- transcript_path: '/tmp/transcript',
- cwd: '/tmp',
- hook_event_name: 'PreToolUse',
- tool_name: 'Bash',
- tool_input: { command },
- } as never,
- 'tool-secret',
- { signal: new AbortController().signal },
- );
-
- expect(result).toMatchObject({
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: 'deny',
- },
- });
- expect(warn).toHaveBeenCalledWith(
- 'shell command denied by embedded iOS Simulator policy',
- expect.objectContaining({
- toolUseId: 'tool-secret',
- toolName: 'Bash',
- reason: expect.any(String),
- }),
- );
- const persistedLog = JSON.stringify(warn.mock.calls);
- expect(persistedLog).not.toContain(command);
- expect(persistedLog).not.toContain('super-secret');
- });
-
- it('lets the command through when the capability is gated off', async () => {
- const { logger, warn } = createLoggerSpy();
- const shouldEnforce = vi.fn(() => false);
- const hook = createIOSSimulatorShellGuardHook(logger, shouldEnforce);
-
- const result = await hook(
- {
- session_id: 'session-1',
- transcript_path: '/tmp/transcript',
- cwd: '/repo',
- hook_event_name: 'PreToolUse',
- tool_name: 'Bash',
- tool_input: { command: 'xcrun simctl boot DEVICE' },
- } as never,
- 'tool-1',
- { signal: new AbortController().signal },
- );
-
- // The user's own Xcode tooling must run when there is no embedded simulator
- // to protect; denying here would point at a tool the gate has removed.
- expect(result).toEqual({ continue: true });
- expect(shouldEnforce).toHaveBeenCalledWith('/repo');
- expect(warn).not.toHaveBeenCalled();
- });
-
- it('still denies while the capability is available', async () => {
- const { logger } = createLoggerSpy();
- const shouldEnforce = vi.fn(() => true);
- const hook = createIOSSimulatorShellGuardHook(logger, shouldEnforce);
-
- const result = await hook(
- {
- session_id: 'session-1',
- transcript_path: '/tmp/transcript',
- cwd: ' ',
- hook_event_name: 'PreToolUse',
- tool_name: 'Bash',
- tool_input: { command: 'open -a Simulator' },
- } as never,
- 'tool-2',
- { signal: new AbortController().signal },
- );
-
- expect(result).toMatchObject({
- hookSpecificOutput: { permissionDecision: 'deny' },
- });
- // A blank cwd is unknown, not the repository root.
- expect(shouldEnforce).toHaveBeenCalledWith(null);
- });
-});
diff --git a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
deleted file mode 100644
index 8609d65373..0000000000
--- a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
+++ /dev/null
@@ -1,738 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { getDesktopShellCommandPolicy } from '../shell-command-policy.js';
-
-const describeMac = process.platform === 'darwin' ? describe : describe.skip;
-
-describeMac('embedded iOS Simulator shell policy', () => {
- it.each([
- 'open -a Simulator',
- 'open -n -a "Simulator.app"',
- 'open -na Simulator',
- 'open -b com.apple.iphonesimulator',
- 'open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app',
- '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
- ])('denies an external Simulator launch: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
- });
-
- it('denies a multiline legacy simulator workflow before it can execute', () => {
- const command = [
- 'SIM_UUID=1A9D41E0-E031-4AD0-A8B5-847480802E8E',
- 'xcrun simctl boot "$SIM_UUID"',
- 'open -a Simulator',
- 'xcrun simctl install "$SIM_UUID" /tmp/FiloApp.app',
- ].join('\n');
- expect(getDesktopShellCommandPolicy(command)).toMatchObject({
- decision: 'deny',
- reason: expect.stringContaining('cindy_ios_simulator'),
- });
- });
-
- it.each([
- 'xcrun simctl boot DEVICE',
- 'xcrun simctl bootstatus DEVICE -b',
- 'xcrun simctl install DEVICE /tmp/App.app',
- 'xcrun simctl launch DEVICE com.example.app',
- 'xcrun simctl shutdown DEVICE',
- '/usr/bin/xcrun simctl io DEVICE screenshot /tmp/frame.png',
- ])('denies direct Simulator mutation: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
- });
-
- // Documentation puts these prefixes in front of a recipe, so the recipe is
- // still spelled out and still reachable by reading the command word.
- it.each([
- 'exec /usr/bin/xcrun simctl shutdown DEVICE',
- 'command xcrun simctl boot DEVICE',
- 'builtin exec xcrun simctl install DEVICE /tmp/App.app',
- 'nohup -- xcrun simctl launch DEVICE com.example.app',
- 'env FOO=1 /usr/bin/xcrun simctl shutdown DEVICE',
- 'FOO=1 exec env BAR=2 xcrun simctl boot DEVICE',
- "bash -lc 'xcrun simctl shutdown DEVICE'",
- "/bin/csh -c 'xcrun simctl shutdown DEVICE'",
- "/bin/tcsh -c 'xcrun simctl shutdown DEVICE'",
- "/bin/ksh -c 'xcrun simctl shutdown DEVICE'",
- "fish -c 'xcrun simctl shutdown DEVICE'",
- "eval 'xcrun simctl erase DEVICE'",
- 'echo "$(xcrun simctl shutdown DEVICE)"',
- 'echo >(xcrun simctl shutdown DEVICE)',
- 'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; eval "$CMD"',
- 'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; sh -c "$CMD"',
- 'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; $CMD',
- 'time xcrun simctl shutdown DEVICE',
- `function f () ( printf '%s' "$(date)"; /usr/bin/open -a Simulator ); f`,
- '/usr/bin/xcrun \\\n simctl shutdown DEVICE',
- '/usr/bin/nice /usr/bin/xcrun simctl erase DEVICE',
- '/usr/bin/arch /usr/bin/xcrun simctl boot DEVICE',
- '/usr/bin/caffeinate /usr/bin/xcrun simctl shutdown DEVICE',
- 'xargs /usr/bin/xcrun simctl shutdown DEVICE',
- 'timeout 30 xcrun simctl boot DEVICE',
- 'timeout 1.5s gtimeout 2m xcrun simctl erase DEVICE',
- // A shell option that takes a value must not be read as the script operand.
- // Unlike a prefix, a shell's `-c` scan can only ever miss when it reads an
- // option wrongly, so the two value-taking options stay modelled here.
- "bash -o pipefail -c 'xcrun simctl shutdown DEVICE'",
- "bash -O extglob -c 'xcrun simctl shutdown DEVICE'",
- "bash +O extglob -c 'xcrun simctl boot DEVICE'",
- "zsh -o extendedglob -c 'xcrun simctl shutdown DEVICE'",
- // A stored recipe counts once something runs the variable that holds it.
- `CMD='xcrun simctl shutdown DEVICE'; eval "\${CMD}"`,
- `CMD='xcrun simctl boot DEVICE'; bash -lc "$CMD"`,
- `CMD='xcrun simctl boot DEVICE'; echo start; eval "$CMD"`,
- // An assignment builtin stores a recipe just like a bare `NAME=value`.
- `export CMD='xcrun simctl shutdown DEVICE'; eval "$CMD"`,
- `readonly CMD='xcrun simctl boot DEVICE'; eval "$CMD"`,
- `declare CMD='open -a Simulator'; eval "$CMD"`,
- `typeset CMD='xcrun simctl erase DEVICE'; eval "$CMD"`,
- `export -p CMD='xcrun simctl boot DEVICE'; eval "$CMD"`,
- // Heredoc reduction must not let a fake marker in a comment swallow a real
- // following command, and CRLF delimiters must end the data region correctly.
- `echo hi # <<'EOF'\nxcrun simctl shutdown DEVICE`,
- `cat <<'EOF'\r\ntext\r\nEOF\r\nxcrun simctl shutdown DEVICE`,
- `cat <<$'EOF' >/dev/null\ntext\nEOF\nxcrun simctl shutdown DEVICE`,
- `cat <<$"EOF" >/dev/null\ntext\nEOF\nxcrun simctl shutdown DEVICE`,
- // Arithmetic left-shift uses the same `<<` spelling as a heredoc opener;
- // it must not make the following command look like a body for delimiter 2.
- `echo $((1 << 2))\nxcrun simctl shutdown DEVICE`,
- `(( 1 << 2 ))\nxcrun simctl shutdown DEVICE`,
- `echo $[1 << 2]\nxcrun simctl shutdown DEVICE`,
- ])('denies a literal recipe behind a documentation-style prefix: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
- });
-
- // ── An option on the prefix ends the peel ──────────────────────────────────
- //
- // Each command below was denied while the policy carried a per-prefix table of
- // which options consume the following token. Maintaining that table meant
- // encoding two things about every CLI: its option arity, and whether the
- // operands are executed at all. Getting either wrong denies ordinary work, and
- // both kept being wrong — `bash -O`, then `command -v`, then `sudo -l`, one per
- // review round. Stopping at the first option can only miss, so the table is
- // gone and these forms are missed on purpose.
- //
- // Documentation spells a recipe as `sudo xcrun simctl boot …`, not
- // `sudo -u me xcrun simctl boot …`; the plain spelling of every prefix above is
- // still covered. All of these were also allowed before the embedded simulator
- // existed, so this restores that behaviour rather than loosening past it.
- it.each([
- 'command -p xcrun simctl boot DEVICE',
- 'time -p xcrun simctl boot DEVICE',
- 'env -u FOO xcrun simctl shutdown DEVICE',
- 'env --unset=FOO xcrun simctl shutdown DEVICE',
- 'env -C /tmp xcrun simctl shutdown DEVICE',
- 'sudo -u me xcrun simctl shutdown DEVICE',
- 'sudo --user=me xcrun simctl boot DEVICE',
- 'sudo -g staff xcrun simctl shutdown DEVICE',
- 'nice -n 5 xcrun simctl shutdown DEVICE',
- 'timeout -k 5 30 xcrun simctl shutdown DEVICE',
- 'xargs -n 1 xcrun simctl shutdown DEVICE',
- 'xargs -I{} xcrun simctl boot {}',
- 'arch -arch arm64 xcrun simctl shutdown DEVICE',
- '/usr/bin/arch -arm64 /usr/bin/xcrun simctl boot DEVICE',
- 'caffeinate -t 60 xcrun simctl shutdown DEVICE',
- '/usr/bin/caffeinate -i /usr/bin/xcrun simctl shutdown DEVICE',
- 'exec -a label xcrun simctl shutdown DEVICE',
- 'exec -a label /usr/bin/xcrun simctl boot DEVICE',
- 'exec -cl -a label xcrun simctl erase DEVICE',
- ])('no longer denies a recipe behind an option-bearing prefix: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- // A stored recipe is only a recipe once something runs it. Classifying every
- // assignment denied commands that print or write the string and execute
- // nothing — and printing a command is exactly what a script does while
- // explaining itself.
- it.each([
- `CMD='xcrun simctl shutdown DEVICE'; printf '%s\\n' "$CMD"`,
- `CMD='xcrun simctl boot DEVICE'; echo "$CMD"`,
- `CMD='open -a Simulator'; echo "$CMD" > /tmp/note.txt`,
- `export CMD='xcrun simctl erase DEVICE'; echo "$CMD"`,
- `CMD='xcrun simctl boot DEVICE'; echo done`,
- `CMD='xcrun simctl boot DEVICE'`,
- `readonly DOC='run xcrun simctl boot DEVICE to start'; printf '%s' "$DOC"`,
- // A different name reaches the execution site, so this value never runs.
- `CMD='xcrun simctl boot DEVICE'; eval "$OTHER"`,
- // The execution point sees the latest value, not the complete assignment
- // history. The stored recipe was replaced before anything ran it.
- `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe'; eval "$CMD" 2>&1`,
- `CMD='xcrun simctl shutdown DEVICE'; echo if; CMD='echo safe'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE' && true; CMD='echo safe'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'
-CMD='echo safe'
-eval "$CMD"`,
- // A lone background separator is complete before the newline, so the next
- // assignment is unconditional in the parent shell and replaces the value.
- `CMD='xcrun simctl shutdown DEVICE'; false &\nCMD='echo safe'; eval "$CMD"`,
- // A command-scoped assignment shadows the exported parent value only for
- // that child command.
- `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' sh -c '$CMD'`,
- ])('allows a stored recipe that nothing executes: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- it.each([
- `CMD='xcrun simctl shutdown DEVICE'; eval "$CMD"; CMD='echo safe'`,
- `CMD='echo safe'; CMD='xcrun simctl shutdown DEVICE'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; OTHER='echo safe'; eval "$CMD"`,
- // An assignment attached to another command only changes that command's
- // environment; it must not replace the shell-scoped value used by eval.
- `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' /usr/bin/true; eval "$CMD"`,
- `CMD='echo safe'; CMD='xcrun simctl shutdown DEVICE' sh -c '$CMD'`,
- // The later text is not a guaranteed replacement when control flow can skip
- // it or keep it inside a child scope, so the earlier value stays possible.
- `CMD='xcrun simctl shutdown DEVICE'; false && CMD='echo safe'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; false &&\nCMD='echo safe'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; true ||\nCMD='echo safe'; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; printf ignored |\nCMD='echo safe'; eval "$CMD"`,
- // A comment's separators and assignments are not shell syntax. Quoted
- // hashes remain ordinary data and must not disable comment scanning.
- `CMD='xcrun simctl shutdown DEVICE'; # note; CMD='echo safe'\neval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; echo "# not a comment"; eval "$CMD"`,
- // Assignments in a pipeline or background segment run in a child shell;
- // they cannot replace the parent value consumed by the later eval.
- `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' & eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; CMD='echo safe' | /usr/bin/cat; eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; (CMD='echo safe'); eval "$CMD"`,
- `CMD='xcrun simctl shutdown DEVICE'; if false; then CMD='echo safe'; fi; eval "$CMD"`,
- // `local` fails outside a function, and function bodies are intentionally
- // outside this literal-recipe parser. It cannot prove a top-level override.
- `CMD='xcrun simctl shutdown DEVICE'; local CMD='echo safe'; eval "$CMD"`,
- ])('denies the current stored recipe at its execution point: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
- });
-
- // A recipe pasted into an interpreter one-liner is still literal text.
- it.each([
- `python3 -c 'import subprocess; subprocess.run(["/usr/bin/xcrun", "simctl", "shutdown", "DEVICE"])'`,
- `node -e 'require("node:child_process").execFileSync("xcrun", ["simctl", "erase", "DEVICE"])'`,
- `ruby -e 'system("xcrun simctl boot DEVICE")'`,
- `perl -e 'system("simctl shutdown DEVICE")'`,
- `env FOO=1 python3.12 -c 'import os; os.system("xcrun simctl install DEVICE /tmp/App.app")'`,
- `/usr/bin/python3 -c 'import os; os.system("simctl shutdown DEVICE")'`,
- `awk 'BEGIN { system("xcrun simctl erase DEVICE") }'`,
- `osascript -e 'do shell script "/usr/bin/xcrun simctl shutdown DEVICE"'`,
- `osascript -e 'do shell script "open -a Simulator"'`,
- `osascript -e 'set cmd to "/usr/bin/xcrun simctl shutdown DEVICE"' -e 'do shell script cmd'`,
- `osascript -l JavaScript -e 'ObjC.import("Foundation"); const task = $.NSTask.alloc.init; task.launchPath = "/usr/bin/xcrun"; task.arguments = ["simctl", "shutdown", "DEVICE"]; task.launch'`,
- `python3 -c 'import subprocess; subprocess.run(["/usr/bin/open","-a","Simulator"])'`,
- `node -e 'require("child_process").spawnSync("/usr/bin/open",["-na","Simulator"])'`,
- `ruby -e 'system("/usr/bin/open", "-a", "Simulator")'`,
- `/usr/bin/expect -c 'spawn /usr/bin/xcrun simctl shutdown DEVICE; expect eof'`,
- // The consumer can also follow the marker, so the heredoc's own pipeline —
- // not just the text before `<<` — decides whether the body is executable.
- `cat <<'SH' | sh
-xcrun simctl boot DEVICE
-SH`,
- `cat <<'SH' |
-echo safe
-SH
-xcrun simctl shutdown DEVICE`,
- `cat <<'SH' | bash -s
-xcrun simctl shutdown DEVICE
-SH`,
- `cat <<'SH' | env FOO=1 bash
-xcrun simctl erase DEVICE
-SH`,
- `cat <<'SH' | bash | cat
-open -a Simulator
-SH`,
- `bash 2>/dev/null <<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `bash>/dev/null <<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `bash &>/dev/null <<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `bash {log}>/dev/null <<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `bash 0<<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `cat <<'SH' | bash 2>/dev/null
-open -a Simulator
-SH`,
- // Multiple stdin heredocs on one consumer: only the last body reaches bash.
- `bash <<'DATA' <<'CODE'
-echo safe
-DATA
-xcrun simctl shutdown DEVICE
-CODE`,
- `cat <<'DATA' | bash <<'CODE'
-echo safe
-DATA
-xcrun simctl shutdown DEVICE
-CODE`,
- `printf '<<SH'; cat <<SH | bash
-xcrun simctl shutdown DEVICE
-SH`,
- // A non-zero fd redirection leaves stdin connected to the pipeline, so the
- // downstream shell still executes the producer's body.
- `cat <<'DATA' | bash 2<err
-xcrun simctl shutdown DEVICE
-DATA`,
- `cat <<'DATA' | bash {fd}<err
-xcrun simctl shutdown DEVICE
-DATA`,
- `cat <<'SH' | bash -s $((1 << 2))
-xcrun simctl shutdown DEVICE
-SH`,
- `cat <<'SH' | bash -s $[1 << 2]
-xcrun simctl shutdown DEVICE
-SH`,
- `cat <<'SH' | bash -o pipefail
-xcrun simctl shutdown DEVICE
-SH`,
- `cat <<'SH' | bash -O extglob
-xcrun simctl shutdown DEVICE
-SH`,
- `cat <<'DATA' | bash -s $(printf foo < /tmp/x)
-xcrun simctl shutdown DEVICE
-DATA`,
- // An unquoted delimiter still expands, so the body's substitutions run.
- `cat <<MSG
-$(xcrun simctl boot DEVICE)
-MSG`,
- `cat <<MSG
-\`xcrun simctl shutdown DEVICE\`
-MSG`,
- // Quote removal happens during tokenization exactly as a shell performs it,
- // so an interrupted spelling is still a literal recipe.
- `bash <<'SH'
-xcr"un" sim"ctl" shutdown DEVICE
-SH`,
- // Only the executor is assembled here; `simctl shutdown DEVICE` is spelled out.
- `python3 -c "import os; os.system(''.join(['xc','run']) + ' simctl shutdown DEVICE')"`,
- ])('denies a literal recipe inside an interpreter payload: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
- });
-
-
- it.each([
- 'xcrun simctl list devices',
- 'xcrun simctl listapps DEVICE',
- 'xcrun simctl list "$DEVICE"',
- 'xcrun simctl getenv "$DEVICE" HOME',
- 'xcrun --sdk iphonesimulator simctl list devices',
- 'xcrun swift --version',
- 'exec xcrun simctl list devices',
- 'command -p xcrun simctl listapps DEVICE',
- "bash -lc 'xcrun simctl list devices'",
- 'f(){ xcrun simctl list devices;}; f',
- 'f() ( xcrun simctl list devices ); f',
- 'echo "f() ( xcrun simctl shutdown DEVICE )"',
- 'command -v xcrun',
- 'xcodebuild -scheme FiloApp -sdk iphonesimulator build',
- 'open -a Xcode',
- 'echo "open -a Simulator"',
- 'osascript -e \'tell application "Simulator" to quit\'',
- `python3 -c 'print("ordinary project build")'`,
- `python3 -c 'print("Simulator")'`,
- `node -e 'console.log("ordinary project build")'`,
- 'swift test --filter IOSSimulatorTests',
- 'swift build --product IOSSimulatorRuntime',
- 'find . -maxdepth 1 -name simctl',
- 'git grep simctl',
- 'git log --grep=simctl',
- `sed -n '/simctl/p' README.md`,
- `jq '.simctl' config.json`,
- 'diff simctl-before.txt simctl-after.txt',
- 'cp simctl-notes.txt backup.txt',
- 'git grep simctl && python3 scripts/check.py',
- 'git grep simctl | python3 formatter.py',
- `git grep simctl | awk '{print $1}'`,
- `python3 -c 'print("ordinary")'; git grep simctl`,
- 'git grep simctl || python3',
- 'alias',
- 'alias sim',
- "alias ll='ls -la'; ll",
- 'echo "alias sim=\'xcrun simctl\'"',
- 'echo "$UNTRUSTED_EXECUTABLE"',
- '# ordinary shell comment',
- '#!/bin/sh\necho ordinary',
- 'command -v "$UNTRUSTED_EXECUTABLE"',
- '[ -n "$UNTRUSTED_EXECUTABLE" ]',
- '[[ -n "$UNTRUSTED_EXECUTABLE" ]]',
- '(( 1 + 2 > 0 ))',
- 'if (( 3 > 0 )); then echo ready; fi',
- 'sudo ls "$ORDINARY_PATH"',
- 'sudo -u "$ORDINARY_USER" /bin/echo ok',
- 'sudo FOO=bar /bin/echo "$ORDINARY_VALUE"',
- 'sudo >/dev/null /bin/echo "$ORDINARY_VALUE"',
- 'xargs echo "$ORDINARY_VALUE"',
- 'xargs -n "$ORDINARY_COUNT" /bin/echo ok',
- `sandbox-exec -p '(version 1) (allow default)' /bin/echo "$ORDINARY_VALUE"`,
- 'sandbox-exec -p "$ORDINARY_PROFILE" /bin/echo ok',
- 'launchctl submit -l "$ORDINARY_LABEL" -- /bin/echo ok',
- 'launchctl asuser "$ORDINARY_UID" /bin/echo ok',
- 'launchctl bsexec "$ORDINARY_PID" /bin/echo "$ORDINARY_VALUE"',
- 'watch -d /bin/echo "$ORDINARY_VALUE"',
- 'time -l /bin/echo "$ORDINARY_VALUE"',
- 'script -q /tmp/typescript /bin/echo "$ORDINARY_VALUE"',
- ])('allows a non-bypass command: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- // A heredoc body, an inline interpreter program and an arithmetic expression
- // are not shell argv. Classifying their contents as command words denied
- // ordinary work with no Simulator executor anywhere in the command.
- it.each([
- // Ordinary HTTPS read through a Python heredoc (issue #2404).
- `python3 - <<'PY'
-import urllib.request
-data = urllib.request.urlopen("https://example.com").read()
-print(len(data))
-PY`,
- `python3 - <<'PY'
-print(1)
-PY`,
- `python3 - <<'PY'
-def main():
- print("hi")
-main()
-PY`,
- `node <<'JS'
-console.log(1)
-JS`,
- `sqlite3 /tmp/app.db <<'SQL'
-SELECT count(*) FROM items;
-SQL`,
- `jq . <<'JSON'
-{"a": 1}
-JSON`,
- `cat > /tmp/notes.txt <<'EOF'
-hello (world)
-EOF`,
- `cat > README.md <<'EOF'
-xcrun simctl shutdown DEVICE
-open -a Simulator
-EOF`,
- `cat > README.md <<EOF
-xcrun simctl shutdown DEVICE
-open -a Simulator
-EOF`,
- // A trailing pipe does not make the next physical line a consumer: it is
- // still heredoc body data. The command after the delimiter is separate.
- `cat <<'SH' |
-xcrun simctl shutdown DEVICE
-SH
-bash`,
- `cat <<'DATA' |
-xcrun simctl shutdown DEVICE
-DATA`,
- `cat <<$'EOF' >/dev/null
-xcrun simctl shutdown DEVICE
-EOF`,
- // A commit message written through a heredoc is stdin data, never argv. A
- // line starting with a Markdown backtick span used to read as an executable
- // position filled by an unresolvable expansion, which denied the commit and
- // interrupted the turn — with no Simulator executor anywhere in the command.
- `git commit -s -F - <<'MSG'
-fix(scope): 收窄判据
-
-验证:\`pnpm --filter desktop typecheck\` 通过,\`@cindy/ios-simulator-runtime\` 36 文件
-\`pnpm test:unit\` 全绿
-MSG`,
- `git commit -F - <<'MSG'
-\`ls\`
-MSG`,
- `git commit -F - <<'MSG'
-xcrun simctl shutdown DEVICE
-MSG`,
- `git commit -F - <<MSG
-xcrun simctl shutdown DEVICE
-MSG`,
- `git commit 2>/dev/null -F - <<'MSG'
-xcrun simctl shutdown DEVICE
-MSG`,
- `bash '2>/dev/null' <<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `bash '&>/dev/null' <<'SH'
-xcrun simctl shutdown DEVICE
-SH`,
- `git commit &>/dev/null -F - <<'MSG'
-xcrun simctl shutdown DEVICE
-MSG`,
- // A quoted delimiter suppresses expansion in every spelling, and `<<-`
- // strips leading tabs from the body and the closing delimiter.
- `git commit -F - <<"MSG"
-\`ls\`
-MSG`,
- `git commit -F - <<\\MSG
-\`ls\`
-MSG`,
- `git commit -F - <<-'MSG'
-\t\`ls\`
-\tMSG`,
- // An unquoted delimiter expands, but running `ls` to build the body is not a
- // Simulator bypass; only the substitution's own command is classified.
- `git commit -F - <<MSG
-\`ls\` 通过
-MSG`,
- `cat <<'A' > /tmp/a && cat <<'B' > /tmp/b
-\`ls\`
-A
-\`pwd\`
-B`,
- // An unterminated body must not fall back to argv classification either.
- `git commit -F - <<'MSG'
-\`ls\``,
- `git commit -F - <<'MSG'
-说明:不要直接用 simctl,走 cindy_ios_simulator
-MSG`,
- `node -e "
-function check() {
- console.log(1);
-}
-check();
-"`,
- `python3 -c "
-def check():
- print(1)
-check()
-"`,
- ])('allows an ordinary interpreter heredoc or inline program: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- it.each([
- 'n=3; (( n > 1 )) && echo yes',
- 'i=0; (( i++ )); echo "$i"',
- '(( $# > 0 )) && echo has-args',
- '(( $? == 0 )) && echo ok',
- 'echo $((1 << 2))',
- 'echo $[1 << 2]',
- '(( 1 << 2 ))',
- 'i=0; while (( i < 3 )); do echo "$i"; i=$((i+1)); done',
- 'if (( count > 0 )); then echo ready; fi',
- ])('allows shell arithmetic with no Simulator evidence: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- it.each([
- 'echo start\n*.ts\necho done',
- // A redirected group leaves `}` in command position, which is a shell
- // control token, not a glob-expanded executable name.
- '{ echo a; echo b; } > /tmp/out.log 2>&1',
- '{ pnpm build; pnpm test; } 2>&1 | tee /tmp/build.log',
- '( cd /tmp && ls ) > /tmp/out.txt',
- 'expected=200; actual=$(curl -s -o /dev/null -w \'%{http_code}\' https://example.com); if [ "$expected" != "$actual" ]; then echo bad; fi',
- 'rg -n "Rejected\\((.*)\\)" apps',
- "rg -n foo --glob '*.{ts,tsx}' apps",
- 'grep -rEn "(foo|bar)" apps',
- "awk '{print $1}' /tmp/app.log",
- 'ls /tmp/[abc]*.log',
- 'cp file.{ts,ts.bak}',
- // Options after the script operand belong to the script, not to the shell.
- // Reading them as a shell program denied ordinary work and interrupted it.
- "bash ./print-args.sh -c 'xcrun simctl shutdown DEVICE'",
- 'sh ./run.sh -c "xcrun simctl boot DEVICE"',
- "zsh tools/x.zsh -c 'open -a Simulator'",
- 'bash ./build.sh --release',
- // Some prefixes only report on the command they name. `command -v` prints
- // where it lives and `sudo -l` asks whether it would be permitted; neither
- // runs it. Ending the peel at the option covers them without the policy
- // having to know which prefixes behave this way.
- 'command -v simctl shutdown',
- 'command -V simctl',
- 'command -v xcrun simctl',
- 'command -pv simctl boot',
- 'sudo -l xcrun simctl boot DEVICE',
- 'sudo --list xcrun simctl shutdown DEVICE',
- // The same rule keeps ordinary option-bearing work out of the guard.
- 'sudo -u postgres psql -c "select 1"',
- 'env -u NODE_OPTIONS pnpm test',
- 'timeout -k 5 30 pnpm build',
- 'nice -n 10 make -j8',
- 'export PATH=/usr/bin:$PATH; echo ok',
- ])('allows an ordinary command whose shape is not an executable: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- // ── Reclassified by the stale-recipe threat model ──────────────────────────
- //
- // Every command below was denied before. Each one disguises the executor:
- // assembling it from variables or string fragments, completing it with a glob
- // or a substitution, forwarding it through eval, or storing it for an opaque
- // wrapper to run. A recipe copied from documentation never looks like this, so
- // none of them are in the threat model this policy defends.
- //
- // They are listed rather than deleted because the change is a deliberate
- // reduction in what the guard claims to stop, and a reviewer should be able to
- // see exactly what moved. Detecting these forms is not achievable from command
- // text anyway — `bash script.sh` carries the executor outside the command
- // entirely — and the machinery that attempted it is what denied ordinary work
- // such as a heredoc body, shell arithmetic and a redirected group.
- it.each([
- "env -S 'xcrun simctl shutdown DEVICE'",
- 'printf "xcrun simctl shutdown DEVICE\\n" | sh',
- 'f(){ xcrun simctl shutdown DEVICE;}; f',
- 'f() ( xcrun simctl shutdown DEVICE ); f',
- `/bin/sh -c '"$0" "$@"' /usr/bin/xcrun simctl shutdown DEVICE`,
- `/bin/sh -c '/usr/bin/open -a "$1"' ignored Simulator`,
- '$(/usr/bin/xcrun --find simctl) shutdown DEVICE',
- '/usr/bin/xc[r]un simctl shutdown DEVICE',
- 'TOOL=simctl; /usr/bin/xcrun "$TOOL" shutdown DEVICE',
- 'A=sim; B=ctl; xcrun "$A$B" shutdown DEVICE',
- 'A=sim; B=ctl; xcrun --sdk iphonesimulator "${A}${B}" erase DEVICE',
- 'xcrun s{imc,foo}tl shutdown DEVICE',
- 'A="default simctl"; xcrun --toolchain ${=A} shutdown DEVICE',
- `bash -lc 'A="default simctl"; xcrun --toolchain $A shutdown DEVICE'`,
- 'A=(default simctl); xcrun --toolchain "${(@)A}" shutdown DEVICE',
- 'A="default simctl"; xcrun --toolchain "$=A" shutdown DEVICE',
- 'A=(default simctl); xcrun --toolchain "$A[@]" shutdown DEVICE',
- `bash -O extglob -lc 'xcrun @(simctl) shutdown DEVICE'`,
- `zsh -o extendedglob -c 'xcrun ^foo shutdown DEVICE'`,
- 'xcrun --sdk "$SDK" simctl list devices',
- 'A=default; xcrun --toolchain "$A" swift --version',
- "find . -maxdepth 0 -exec /usr/bin/xcrun simctl shutdown DEVICE ';'",
- `printf 'simctl shutdown DEVICE' | xargs /usr/bin/xcrun`,
- 'xcrun "$(printf simctl)" shutdown DEVICE',
- 'xcrun $(printf simctl) shutdown DEVICE',
- 'xcrun $(echo simctl) shutdown DEVICE',
- 'TOOL=$(printf simctl); xcrun "$TOOL" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=simctl; env "$A$B" "$C" shutdown DEVICE',
- 'A=x; B=crun; C=sim; D=ctl; command "${A}${B}" "${C}${D}" shutdown DEVICE',
- '$(printf xcr)$(printf un) simctl shutdown DEVICE',
- 'x{cr,foo}un simctl shutdown DEVICE',
- 'RUNNER="$UNTRUSTED_EXECUTABLE"; exec "$RUNNER" --version',
- 'env -S "$UNTRUSTED_EXECUTABLE"',
- 'A=xcr; B=un; C=sim; D=ctl; CMD="$A$B $C$D shutdown DEVICE"; env -S "$CMD"',
- 'time -l "$UNTRUSTED_EXECUTABLE"',
- 'xargs "$UNTRUSTED_EXECUTABLE"',
- "find . -maxdepth 0 -exec \"$UNTRUSTED_EXECUTABLE\" '{}' '+'",
- `sandbox-exec -p '(version 1) (allow default)' "$UNTRUSTED_EXECUTABLE"`,
- 'A=xcr; B=un; sh -c \'"$0" simctl shutdown DEVICE\' "$A$B"',
- 'A=xcr; B=un; C=sim; D=ctl; >/tmp/cindy-shell.log "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; 2>/dev/null "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; < /dev/null "$A$B" "$C$D" shutdown DEVICE',
- "A=xcr; B=un; C=sim; D=ctl; COUNT='arr[$($A$B $C$D shutdown DEVICE)]'; (( COUNT ))",
- "A=xcr; B=un; C=sim; D=ctl; PAYLOAD='arr[$($A$B $C$D shutdown DEVICE)]'; COUNT=PAYLOAD; (( COUNT ))",
- "A=xcr; B=un; C=sim; D=ctl; printf -v COUNT 'arr[$($A$B $C$D shutdown DEVICE)]'; (( COUNT ))",
- "A=xcr B=un C=sim D=ctl COUNT='arr[$($A$B $C$D shutdown DEVICE)]' bash -c '(( COUNT ))'",
- 'xargs -0 /Applications/Xcode.app/Contents/Developer/usr/bin/simct? shutdown DEVICE',
- 'sudo -n /Applications/Xcode.app/Contents/Developer/usr/bin/simct[l] shutdown DEVICE',
- 'gtimeout -v 5 /Applications/Xcode.app/Contents/Developer/usr/bin/simct? shutdown DEVICE',
- `zsh -o extendedglob -c '/Applications/Xcode.app/Contents/Developer/usr/bin/simct^foo shutdown DEVICE'`,
- `zsh -o extendedglob -c '/Applications/Xcode.app/Contents/Developer/usr/bin/simctl~foo shutdown DEVICE'`,
- `zsh -o extendedglob -c '/Applications/Xcode.app/Contents/Developer/usr/bin/simctl# shutdown DEVICE'`,
- 'A=xcr; B=un; C=sim; D=ctl; launchctl asuser 501 "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; launchctl bsexec 123 "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; noglob "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; nocorrect "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; coproc "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; repeat 1 "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; sudo >/dev/null "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; xargs 2>/dev/null "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; launchctl submit -l test >/dev/null -- "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; sudo FOO=bar "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; xargs env FOO=bar "$A$B" "$C$D" shutdown DEVICE',
- 'A=xcr; B=un; C=sim; D=ctl; find . -maxdepth 0 -exec env FOO=bar "$A$B" "$C$D" shutdown DEVICE \';\'',
- 'A=xcr; B=un; C=sim; D=ctl; sudo command "$A$B" "$C$D" shutdown DEVICE',
- 'launchctl submit -l cindy-test -- /usr/bin/xcrun simctl shutdown DEVICE',
- `sandbox-exec -p '(version 1) (allow default)' /usr/bin/xcrun simctl shutdown DEVICE`,
- "shopt -s expand_aliases\nalias sim='xcrun simctl'\nsim shutdown DEVICE",
- "alias sim=xcrun\\ simctl; eval 'sim erase DEVICE'",
- "builtin alias sim='/usr/bin/xcrun simctl'; eval 'sim shutdown DEVICE'",
- "command -- alias sim='open -a Simulator'; eval sim",
- "alias safe='ls -la' sim='xcrun simctl'; eval 'sim boot DEVICE'",
- "alias sc='simctl'; eval 'sc shutdown DEVICE'",
- '(( $COUNT > 0 ))',
- '(( COUNT[$idx]++ ))',
- 'if (( $COUNT > 0 )); then echo ready; fi',
- `printf '%s' 'import os; os.system("xcrun simctl shutdown DEVICE")' | python3`,
- `python3 <<'PY'
-import os
-os.system("xcrun simctl shutdown DEVICE")
-PY`,
- `printf '%s' 'exec /usr/bin/xcrun simctl shutdown DEVICE' | /usr/bin/tclsh`,
- `printf '%s' 'import os; os.system("xcrun simctl shutdown DEVICE")' |& python3`,
- `bash <<< 'xcrun simctl shutdown DEVICE'`,
- `zsh <<< 'open -a Simulator'`,
- `bash -c 'source /dev/stdin' <<< 'xcrun simctl shutdown DEVICE'`,
- `bash -c 'eval "$(cat)"' <<< 'xcrun simctl shutdown DEVICE'`,
- `printf 'xcrun simctl shutdown DEVICE' | bash -c 'eval "$(cat)"'`,
- `python3 -c 'import os; os.system("xcr" + "un" + " sim" + "ctl shutdown DEVICE")'`,
- `node -e 'require("child_process").execSync("xcr" + "un" + " sim" + "ctl shutdown DEVICE")'`,
- `python3 - <<'PY'
-import os
-os.system("xcr" + "un" + " sim" + "ctl shutdown DEVICE")
-PY`,
- // The downstream heredoc replaces the pipe as bash's stdin, so DATA is
- // ordinary cat input even though it looks like a Simulator recipe.
- `cat <<'DATA' | bash <<'CODE'
-xcrun simctl shutdown DEVICE
-DATA
-echo safe
-CODE`,
- `bash <<'DATA' <<'CODE'
-xcrun simctl shutdown DEVICE
-DATA
-echo safe
-CODE`,
- `bash 3<<'DATA'
-xcrun simctl shutdown DEVICE
-DATA`,
- `bash {fd}<<'DATA'
-xcrun simctl shutdown DEVICE
-DATA`,
- `awk 'BEGIN { system("xcr" "un" " sim" "ctl shutdown DEVICE") }'`,
- 'xcr$TAIL boot DEVICE',
- 'sim$TAIL shutdown DEVICE',
- 'xc$TAIL boot DEVICE',
- '${DIR}crun boot DEVICE',
- 'simct$TAIL shutdown DEVICE',
- 'sim* shutdown DEVICE',
- '$DIR/build/$NAME --version',
- '"$PWD/build/$NAME" --version',
- '$DIR/simctl/$SUB shutdown DEVICE',
- // A substitution can supply characters in the middle of the name, and the
- // tokenizer splits on the whitespace inside it, so the command word arrives
- // as an unterminated remnant. Contiguity is not a safe test here.
- 'si$(printf m)ctl shutdown DEVICE',
- 'sim$(printf c)tl shutdown DEVICE',
- 'x$(printf c)run simctl shutdown DEVICE',
- 'sim`printf c`tl shutdown DEVICE',
- // A character class or brace list holds mutually exclusive candidates, so
- // merging their contents into the core would invent a literal that matches
- // nothing and hide the name the shell can expand to.
- '/usr/bin/[sx]crun s[ai]mctl shutdown DEVICE',
- '/Applications/Xcode.app/Contents/Developer/usr/bin/[sx]imctl shutdown DEVICE',
- '[sx]crun boot DEVICE',
- 's[ai]mctl shutdown DEVICE',
- 'x{cr,foo}un boot DEVICE',
- 's{imc,foo}tl shutdown DEVICE',
- `python3 - <<'PY'
-import os
-os.system(''.join(('xc','run')) + ' ' + ''.join(('sim','ctl')) + ' shutdown DEVICE')
-PY`,
- ])('no longer denies a disguised executor: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- // The deliberate boundary of the narrowing: the executable name is knowable
- // and is not a Simulator executor, so denying it would be a guess about the
- // expansion rather than a product rule. Documented in the PR description.
- it.each([
- '$DIR/build/tool --version',
- 'tool$SUFFIX --version',
- 'build$SUFFIX --version',
- ])('allows a resolvable non-Simulator executable name: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-
- // Adjacent string literals are data, not a join. Folding them used to fabricate
- // an executor name out of ordinary interpreter code.
- it.each([
- `python3 -c 'print("xcr", "un")'`,
- `node -e 'console.log(["sim", "ctl"])'`,
- `python3 -c 'print(["sim","ctl"])'`,
- ])('allows adjacent string literals that merely look like fragments: %s', (command) => {
- expect(getDesktopShellCommandPolicy(command)).toBeUndefined();
- });
-});
diff --git a/apps/desktop/src/main/maker-host/agent-shell-guards.ts b/apps/desktop/src/main/maker-host/agent-shell-guards.ts
deleted file mode 100644
index 2cfa9fe326..0000000000
--- a/apps/desktop/src/main/maker-host/agent-shell-guards.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * Executable shims placed first in the local Codex child PATH.
- *
- * Codex Full access can run trusted commands without sending an approval
- * request. A command-approval callback therefore cannot be the only boundary:
- * these shims stop the common bare `open` / `xcrun` skill recipes before the
- * real macOS binaries are reached. Absolute paths are covered by the item-start
- * fallback and the Claude PreToolUse hook.
- */
-
-import fs from 'node:fs';
-import path from 'node:path';
-import { app } from 'electron';
-
-const OPEN_SHIM = `#!/bin/sh
-joined="$*"
-if printf '%s' "$joined" | /usr/bin/grep -Eiq '(^|[[:space:]])-a[[:space:]]+Simulator(\\.app)?($|[[:space:]])|(^|[[:space:]])-b[[:space:]]+com\\.apple\\.iphonesimulator($|[[:space:]])|Simulator\\.app(/Contents/MacOS/Simulator)?($|[[:space:]])'; then
- echo 'Cindy: use cindy_ios_simulator instead of launching the external Simulator.app.' >&2
- exit 86
-fi
-exec /usr/bin/open "$@"
-`;
-
-const XCRUN_SHIM = `#!/bin/sh
-if [ "$1" = "simctl" ]; then
- case "$2" in
- help|list|listapps|getenv|get_app_container|diagnose) ;;
- *)
- echo 'Cindy: use cindy_ios_simulator instead of mutating an iOS Simulator with simctl.' >&2
- exit 86
- ;;
- esac
-fi
-exec /usr/bin/xcrun "$@"
-`;
-
-/** Returns a stable per-user guard directory, or null outside macOS. */
-export function ensureAgentShellGuards(): string | null {
- if (process.platform !== 'darwin') return null;
- const dir = path.join(app.getPath('userData'), 'agent-shell-guards');
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
- const files: Array<[string, string]> = [
- ['open', OPEN_SHIM],
- ['xcrun', XCRUN_SHIM],
- ];
- for (const [name, contents] of files) {
- const filePath = path.join(dir, name);
- if (!fs.existsSync(filePath) || fs.readFileSync(filePath, 'utf8') !== contents) {
- fs.writeFileSync(filePath, contents, { mode: 0o700 });
- } else {
- fs.chmodSync(filePath, 0o700);
- }
- }
- return dir;
-}
diff --git a/apps/desktop/src/main/maker-host/claude-hooks/ios-simulator-shell-hook.ts b/apps/desktop/src/main/maker-host/claude-hooks/ios-simulator-shell-hook.ts
deleted file mode 100644
index 2b6c2bc82a..0000000000
--- a/apps/desktop/src/main/maker-host/claude-hooks/ios-simulator-shell-hook.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/** Claude PreToolUse guard for legacy shell-based iOS Simulator workflows. */
-
-import type { HookCallback, PreToolUseHookInput } from '@anthropic-ai/claude-agent-sdk';
-import type { Logger } from '@cindy/maker-core';
-import { getDesktopShellCommandPolicy } from '../shell-command-policy.js';
-
-export function createIOSSimulatorShellGuardHook(
- logger: Logger,
- /**
- * Whether the embedded Simulator boundary applies to this working directory.
- * Omitted in tests that only exercise the policy itself; production wiring
- * always supplies it so an absent plugin does not block the user's own Xcode
- * tooling.
- */
- shouldEnforce?: (workingDir: string | null) => boolean,
-): HookCallback {
- const log = logger.child('hook/ios-simulator-shell-guard');
- return async (input, toolUseId) => {
- if (input.hook_event_name !== 'PreToolUse') return { continue: true };
- const pre = input as PreToolUseHookInput;
- if (pre.tool_name !== 'Bash' && pre.tool_name !== 'PowerShell') return { continue: true };
- const toolInput = pre.tool_input as Record<string, unknown> | null | undefined;
- const command = toolInput?.command;
- if (typeof command !== 'string') return { continue: true };
- const workingDir = typeof pre.cwd === 'string' && pre.cwd.trim() ? pre.cwd : null;
- if (shouldEnforce && !shouldEnforce(workingDir)) return { continue: true };
-
- const policy = getDesktopShellCommandPolicy(command);
- if (!policy) return { continue: true };
-
- log.warn('shell command denied by embedded iOS Simulator policy', {
- toolUseId: toolUseId ?? null,
- toolName: pre.tool_name,
- reason: policy.reason,
- });
- return {
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: 'deny',
- permissionDecisionReason: policy.reason,
- additionalContext: policy.reason,
- },
- };
- };
-}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 85049f47c5..10fa5185ff 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -50,7 +50,6 @@ import { WorktreePool } from '../worktree/index.js';
import { getReadyBinaryPath, getCachedBinaryStatus } from '../agent-binaries/index.js';
import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { getIOSSimulatorPluginAccessDecision } from '../cindy-brain/index.js';
-import { shouldEnforceIOSSimulatorShellPolicy } from '../cindy-brain/iosSimulatorPluginGate.js';
import {
desktopClaudeAuthAdapter,
desktopCodexAuthAdapter,
@@ -76,9 +75,6 @@ import {
mergeClaudeHooks,
} from './claude-hooks/bash-concurrency-hook.js';
import { createReadImageHook } from './claude-hooks/read-image-hook.js';
-import { createIOSSimulatorShellGuardHook } from './claude-hooks/ios-simulator-shell-hook.js';
-import { getDesktopShellCommandPolicy } from './shell-command-policy.js';
-import { ensureAgentShellGuards } from './agent-shell-guards.js';
import { readAgentResourceSettings } from './agent-resource-settings-store.js';
import { createCommandConcurrencyGate } from './command-concurrency-gate.js';
import {
@@ -136,10 +132,7 @@ import {
} from './codex-proxy-host.js';
import { createDesktopMcpProviders } from '../mcp-integrations/mcp-providers.js';
import { getGhostRosterPrompt } from '../mcp-integrations/ghost.js';
-import {
- getIOSSimulatorMcpDeps,
- isIOSSimulatorHostRuntimeActive,
-} from '../mcp-integrations/ios-simulator.js';
+import { getIOSSimulatorMcpDeps } from '../mcp-integrations/ios-simulator.js';
import { readContactsSettings } from './contacts-settings-store.js';
import { createIOSSimulatorCodexDynamicToolProvider } from './ios-simulator-codex-dynamic-tools.js';
import { captureKnownFileBefore, noteOpaqueTurnChange } from '../turn-change-set/store.js';
@@ -696,7 +689,7 @@ export function getMaker(): Maker {
allowed: false as const,
errorCode: 'IOS_SIMULATOR_DISABLED' as const,
message:
- 'The iOS Simulator capability is disabled for the current project. Ask the user to enable it in the project plugin settings before retrying.',
+ 'The embedded iOS Simulator capability is disabled for the current project. Enable it in the project plugin settings before retrying the embedded tool; other iOS workflows are unaffected.',
data: {
reason: 'disabled-in-workdir',
action: 'enable-plugin',
@@ -708,19 +701,6 @@ export function getMaker(): Maker {
return { allowed: true as const };
};
- // The shell guard protects the embedded simulator's ownership/admission/
- // viewer/cleanup contracts. With the plugin gated off there is nothing to
- // protect, so blocking the user's own `simctl` / Simulator.app work — and
- // pointing them at a cindy_ios_simulator tool the gate just removed — would
- // be a dead end. A runtime this process already installed keeps its
- // protection either way.
- const shouldEnforceSimulatorShellGuard = (workingDir: string | null): boolean =>
- shouldEnforceIOSSimulatorShellPolicy({
- pluginAccessAllowed: resolveIOSSimulatorAccess({ workingDir: workingDir ?? undefined })
- .allowed,
- hostRuntimeActive: isIOSSimulatorHostRuntimeActive(),
- });
-
const makerMemoryProviderDeps = {
getMakerMemoryManager: () => makerMemoryManager,
lspPool: getLspPool(),
@@ -913,15 +893,6 @@ export function getMaker(): Maker {
claudeHooks: mergeClaudeHooks(
{
PreToolUse: [
- {
- matcher: 'Bash|PowerShell',
- hooks: [
- createIOSSimulatorShellGuardHook(
- desktopMakerLogger,
- shouldEnforceSimulatorShellGuard,
- ),
- ],
- },
{
matcher: 'Read',
hooks: [createReadImageHook(desktopMakerLogger)],
@@ -1192,10 +1163,6 @@ export function getMaker(): Maker {
codexHostDynamicToolProvider: createIOSSimulatorCodexDynamicToolProvider({
deps: getIOSSimulatorMcpDeps({ resolveAccess: resolveIOSSimulatorAccess }),
}),
- getShellCommandPolicy: ({ command, cwd }) =>
- shouldEnforceSimulatorShellGuard(cwd?.trim() || null)
- ? getDesktopShellCommandPolicy(command)
- : undefined,
// 通讯录 prompt 段有效状态(codex 版): 在 claude 的判定链之上再与「实际应用
// 到 running app-server 的 spawn 快照」对齐 —— 开关切换后失效失败(busy,
// contacts-ipc 折成 codexMcpRefreshed:false)时 stale 桥里没有新工具面,
@@ -1296,12 +1263,6 @@ export function getMaker(): Maker {
codexAppliedContactsEnabled = false;
}
}
- const shellGuardDir = ensureAgentShellGuards();
- if (shellGuardDir) {
- mcpExtraEnv.PATH = [shellGuardDir, mcpExtraEnv.PATH ?? process.env.PATH]
- .filter((value): value is string => Boolean(value))
- .join(path.delimiter);
- }
const browserCompanion = usesIsolatedProxy
? null
: await prepareCodexBrowserCompanion({ codexHome: getCodexHome() });
diff --git a/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts b/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts
index b300e60917..a3f992da23 100644
--- a/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts
+++ b/apps/desktop/src/main/maker-host/ios-simulator-codex-dynamic-tools.ts
@@ -18,7 +18,7 @@ const TOOLS = [
type: 'function',
name: LIST_TOOLS_NAME,
description:
- "Discover Cindy's embedded iOS Simulator tools. Use this deterministic Host gateway for iOS app work instead of probing MCP resources or opening macOS Simulator.app. Every tool behind it acts on a simulated Apple device: never use it to browse the web, fetch HTTP data, or automate this Mac. Start with check_environment.",
+ "Discover Cindy's embedded iOS Simulator tools. Use this deterministic Host gateway when the embedded route is selected for iOS app work. Every tool behind it acts on a simulated Apple device: never use it to browse the web, fetch HTTP data, or automate this Mac. Start with check_environment.",
inputSchema: {
type: 'object',
additionalProperties: false,
diff --git a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
index 9b65a5ece6..2e4963abac 100644
--- a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
+++ b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
@@ -30,7 +30,7 @@ interface BuiltinPluginMeta {
*/
const BUILTIN_META: BuiltinPluginMeta[] = [
{ id: 'android', name: 'Android Automation', description: 'Android adb automation — screenshots, UI dump, taps, swipes, text input, and app launch on connected devices' },
- { id: 'ios-simulator', name: 'iOS Simulator', description: 'Cindy embedded iOS Simulator — create or attach a session-owned device, boot it in the embedded viewer, build/install/launch apps, inspect screens, and debug interactions. Prefer this for requests to open, run, test, or debug an iOS app; do not launch macOS Simulator.app unless the user explicitly asks for an external system window.' },
+ { id: 'ios-simulator', name: 'iOS Simulator', description: 'Cindy embedded iOS Simulator — create or attach a session-owned device, boot it in the embedded viewer, build/install/launch apps, inspect screens, and debug interactions.' },
{ id: 'browser', name: 'Browser', description: 'Browser automation — isolated browsing, snapshots, screenshots, and page actions' },
{ id: 'computer', name: 'Computer Use', description: 'Local desktop automation — apps, windows, UI inspection, clicks, and typing via an installed driver' },
{ id: 'feishu_bot', name: 'Feishu Bot', description: 'Send files and notifications to Feishu users via bot messages' },
diff --git a/apps/desktop/src/main/maker-host/shell-command-policy.ts b/apps/desktop/src/main/maker-host/shell-command-policy.ts
deleted file mode 100644
index a7ae5ab571..0000000000
--- a/apps/desktop/src/main/maker-host/shell-command-policy.ts
+++ /dev/null
@@ -1,1155 +0,0 @@
-/**
- * Product-owned shell command policy for the embedded iOS Simulator.
- *
- * **Threat model: a stale recipe.** A Skill, a README or the model's own memory
- * still carries a pre-Cindy incantation (`xcrun simctl boot …`,
- * `open -a Simulator`) and the Agent copies it verbatim. Such recipes are
- * literal by construction — they come from documentation, so they never disguise
- * themselves — and a literal matcher catches all of them. Cindy's own main
- * process reaches simctl through the runtime adapter and is unaffected, and the
- * capability gate means this policy only applies where an embedded simulator
- * actually exists to protect.
- *
- * **Deliberately outside the threat model: writing around this policy.** Command
- * text cannot decide that case at all — `bash script.sh` moves the executor out
- * of the command entirely, and no amount of parsing recovers it. Trying anyway is
- * what made this module deny ordinary work: it had to fail closed on every shape
- * it could not resolve, and in shell that is most shapes, so `print(len(data))`
- * in a heredoc, `(( n > 1 ))`, a glob-leading line, `{ …; } > file` and a commit
- * message containing a Markdown backtick were all rejected with no Simulator
- * executor anywhere in the command. This matcher denies only what it can read
- * directly and lets everything else reach the normal shell permission flow.
- * "Directly" means that the executor occupies a command-word position this
- * policy already understands: a direct segment, one of the plain documentation
- * prefixes below, or a supported shell/interpreter payload. It does not scan
- * arbitrary argv for a command another program might execute. Opaque wrappers
- * such as `launchctl`, `sandbox-exec`, `doas`, `script`, `watch`, `parallel`,
- * `coproc` and `repeat` remain outside this boundary even when their argv holds
- * a complete literal recipe, because locating the executed operand requires a
- * per-wrapper execution contract rather than shell syntax.
- *
- * Heredocs need one narrow boundary: their bodies are stdin data unless the
- * receiving command executes stdin as a program. Data bodies are omitted from
- * command classification (while substitutions in an unquoted body still run),
- * so a commit message may quote a stale recipe without being mistaken for one.
- */
-
-export interface ShellCommandPolicyDenial {
- decision: 'deny';
- reason: string;
-}
-
-const SAFE_SIMCTL_COMMANDS = new Set([
- 'help',
- 'list',
- 'listapps',
- 'getenv',
- 'get_app_container',
- 'diagnose',
-]);
-
-const IOS_SIMULATOR_SHELL_DENIAL =
- 'Cindy blocked a shell command that would bypass the embedded iOS Simulator. ' +
- 'Use cindy_ios_simulator for device lifecycle, app install/launch, interaction, screenshots, and diagnostics.';
-
-const MAX_RECURSION_DEPTH = 8;
-
-interface ShellSegment {
- command: string;
- /** The operator that ran before this command; null for the first segment. */
- precedingOperator: ';' | '&&' | '||' | '|' | '&' | null;
- /** The operator that separates this command from the next segment, if any. */
- followingOperator: ';' | '&&' | '||' | '|' | '&' | null;
-}
-
-/** Split command lists without treating separators inside quotes as boundaries. */
-function shellSegments(command: string): ShellSegment[] {
- const segments: ShellSegment[] = [];
- let current = '';
- let quote: "'" | '"' | null = null;
- let escaped = false;
- let atWordStart = true;
- let precedingOperator: ShellSegment['precedingOperator'] = null;
-
- const flush = (nextOperator: Exclude<ShellSegment['precedingOperator'], null>): void => {
- if (current.trim()) {
- segments.push({
- command: current.trim(),
- precedingOperator,
- followingOperator: nextOperator,
- });
- }
- current = '';
- precedingOperator = nextOperator;
- };
-
- for (let index = 0; index < command.length; index += 1) {
- const char = command[index]!;
- if (escaped) {
- current += char;
- escaped = false;
- atWordStart = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- current += char;
- escaped = true;
- atWordStart = false;
- continue;
- }
- if (quote) {
- current += char;
- if (char === quote) quote = null;
- continue;
- }
- if (char === "'" || char === '"') {
- current += char;
- quote = char;
- atWordStart = false;
- continue;
- }
- if (char === '#' && atWordStart) {
- // A comment consumes the rest of the current physical line. Keep the
- // newline for the normal separator handling so assignments before the
- // comment retain their real shell scope.
- const newline = command.indexOf('\n', index);
- if (newline < 0) break;
- index = newline - 1;
- continue;
- }
- if (char === '\n' || char === ';') {
- // A newline immediately after `&&`, `||` or `|` continues that operator's
- // command. There is no empty command for the newline to run, so keep the
- // pending edge instead of turning it into an unconditional list separator.
- // A lone `&` is already a complete separator, so the next line is
- // unconditional in the parent shell.
- if (char === ';' || current.trim() || precedingOperator === '&') flush(';');
- atWordStart = true;
- continue;
- }
- if (
- (char === '&' && (command[index - 1] === '>' || command[index - 1] === '<')) ||
- (char === '&' && command[index + 1] === '>') ||
- (char === '|' && command[index - 1] === '>')
- ) {
- current += char;
- atWordStart = false;
- continue;
- }
- if (char === '|' || char === '&') {
- if (char === '|' && command[index + 1] === '&') {
- flush('|');
- index += 1;
- continue;
- }
- const doubled = command[index + 1] === char;
- flush(doubled ? (char === '|' ? '||' : '&&') : char);
- if (doubled) index += 1;
- atWordStart = true;
- continue;
- }
- current += char;
- atWordStart = /\s/.test(char);
- }
- if (current.trim())
- segments.push({ command: current.trim(), precedingOperator, followingOperator: null });
- return segments;
-}
-
-/** Whether a segment's assignments definitely replace values in the current scope. */
-function assignmentDefinitelyRunsInCurrentScope(segment: ShellSegment): boolean {
- if (segment.precedingOperator !== null && segment.precedingOperator !== ';') return false;
- // Assignments in a pipeline or background segment execute in a child shell.
- // They must not be treated as replacing the value in the parent scope that a
- // later command (for example `eval "$CMD"`) will read.
- if (segment.followingOperator === '|' || segment.followingOperator === '&') return false;
- let quote: "'" | '"' | null = null;
- let escaped = false;
- let unquoted = '';
- for (const char of segment.command) {
- if (escaped) {
- unquoted += ' ';
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- unquoted += ' ';
- escaped = true;
- continue;
- }
- if (quote) {
- unquoted += ' ';
- if (char === quote) quote = null;
- continue;
- }
- if (char === "'" || char === '"') {
- unquoted += ' ';
- quote = char;
- continue;
- }
- if (char === '(' || char === ')' || char === '`') return false;
- unquoted += char;
- }
- const start = unquoted.trimStart();
- return !/^(?:(?:\{|!)\s*|(?:then|do|else|elif|if|while|until|for|select|case|function)\b)/.test(
- start,
- );
-}
-
-/** Lightweight argv tokenizer. Quotes group tokens but are not retained. */
-function tokenizeShellSegment(segment: string): string[] {
- const tokens: string[] = [];
- let token = '';
- let started = false;
- let quote: "'" | '"' | null = null;
- const flush = (): void => {
- if (!started) return;
- tokens.push(token);
- token = '';
- started = false;
- };
- for (let index = 0; index < segment.length; index += 1) {
- const char = segment[index]!;
- if (char === '\\' && quote !== "'" && index + 1 < segment.length) {
- token += segment[index + 1]!;
- started = true;
- index += 1;
- continue;
- }
- if (quote) {
- if (char === quote) quote = null;
- else token += char;
- started = true;
- continue;
- }
- if (char === "'" || char === '"') {
- quote = char;
- started = true;
- } else if (/\s/.test(char)) {
- flush();
- } else {
- token += char;
- started = true;
- }
- }
- flush();
- return tokens;
-}
-
-function executableName(token: string | undefined): string {
- return (token ?? '')
- .replace(/\\/g, '/')
- .split('/')
- .at(-1)!
- .replace(/\.exe$/i, '')
- .toLowerCase();
-}
-
-/** Drop compound-command keywords and braces so the next token is the command word. */
-function stripShellControlTokens(tokens: string[]): string[] {
- const out = [...tokens];
- while (out.length > 0 && /^(?:\{|\(|!|then|do|else|elif|if|while|until)$/.test(out[0]!)) {
- out.shift();
- }
- if (out[0]) out[0] = out[0].replace(/^[({]+/, '');
- while (out[0] === '') out.shift();
- const last = out.length - 1;
- if (last >= 0) {
- // A trailing `)` may close a substitution rather than a subshell. Stripping
- // it there would truncate `CMD='echo $(xcrun simctl boot X)'` into an
- // unterminated substitution that the recursive scan can no longer read.
- const closesSubstitution = /\$\(|<\(|>\(/.test(out[last]!);
- if (!closesSubstitution) {
- out[last] = out[last]!.replace(/[)}]+$/, '');
- if (out[last] === '') out.pop();
- }
- }
- return out;
-}
-
-function shellRedirectionSuffix(token: string): string | null {
- const match = /^(?:\d+)?(?:<<<|<<-?|<>|<|>>?|>&|<&|>\|)(.*)$/s.exec(token);
- return match ? (match[1] ?? '') : null;
-}
-
-function redirectionAt(segment: string, index: number): string | null {
- if (
- (segment[index] === '<' || segment[index] === '>')
- && segment[index + 1] === '('
- ) return null;
- const wordStart = index === 0 || /\s/.test(segment[index - 1]!);
- const prefix = wordStart ? '(?:(?:\\d+|\\{[A-Za-z_][A-Za-z0-9_]*\\}))?' : '';
- return new RegExp(`^${prefix}(?:&>>?|<<<|<<-|<<|<>|>>|>&|<&|>\\||<|>)`).exec(
- segment.slice(index),
- )?.[0] ?? null;
-}
-
-/** Remove unquoted redirections before deciding whether stdin is the program. */
-function tokenizeHeredocConsumer(segment: string): string[] {
- let command = '';
- let quote: "'" | '"' | null = null;
- let escaped = false;
- for (let index = 0; index < segment.length; index += 1) {
- const char = segment[index]!;
- if (escaped) {
- command += char;
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- command += char;
- escaped = true;
- continue;
- }
- if (char === "'" || char === '"') {
- command += char;
- if (quote === char) quote = null;
- else if (quote === null) quote = char;
- continue;
- }
- const redirection = quote === null ? redirectionAt(segment, index) : null;
- if (redirection === null) {
- command += char;
- continue;
- }
- index += redirection.length;
- while (/\s/.test(segment[index] ?? '')) index += 1;
- let targetQuote: "'" | '"' | null = null;
- let targetEscaped = false;
- for (; index < segment.length; index += 1) {
- const target = segment[index]!;
- if (targetEscaped) {
- targetEscaped = false;
- continue;
- }
- if (target === '\\' && targetQuote !== "'") {
- targetEscaped = true;
- continue;
- }
- if (target === "'" || target === '"') {
- if (targetQuote === target) targetQuote = null;
- else if (targetQuote === null) targetQuote = target;
- continue;
- }
- if (targetQuote === null && (/\s/.test(target) || redirectionAt(segment, index))) break;
- }
- command += ' ';
- index -= 1;
- }
- return tokenizeShellSegment(command);
-}
-
-/** A `NAME=value` assignment, whose value may hold a whole recipe. */
-interface ShellAssignment {
- name: string;
- value: string;
-}
-
-const SHELL_ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/;
-
-interface Preamble {
- tokens: string[];
- assignments: ShellAssignment[];
-}
-
-/** Remove leading assignments and redirections so the next token is the command word. */
-function stripLeadingShellPreamble(input: string[]): Preamble {
- const tokens = [...input];
- const assignments: ShellAssignment[] = [];
- while (tokens.length > 0) {
- const token = tokens[0]!;
- const assignment = SHELL_ASSIGNMENT.exec(token);
- if (assignment) {
- assignments.push({ name: assignment[1] ?? '', value: assignment[2] ?? '' });
- tokens.shift();
- continue;
- }
- const redirectionSuffix = shellRedirectionSuffix(token);
- if (redirectionSuffix === null) break;
- tokens.shift();
- if (redirectionSuffix === '' && tokens.length > 0) tokens.shift();
- }
- return { tokens, assignments };
-}
-
-const SHELL_EXECUTABLES = new Set(['bash', 'csh', 'dash', 'fish', 'ksh', 'sh', 'tcsh', 'zsh']);
-const PROGRAMMABLE_INTERPRETER =
- /^(?:python(?:\d+(?:\.\d+)*)?|pypy(?:\d+(?:\.\d+)*)?|node|nodejs|bun|deno|ruby(?:\d+(?:\.\d+)*)?|perl(?:\d+(?:\.\d+)*)?|php(?:\d+(?:\.\d+)*)?|lua(?:\d+(?:\.\d+)*)?|luajit|swift|expect(?:\d+(?:\.\d+)*)?|tclsh(?:\d+(?:\.\d+)*)?|wish(?:\d+(?:\.\d+)*)?|(?:g|m|n)?awk|osascript)$/;
-
-/**
- * Prefixes documentation puts in front of a recipe, in the plain spelling it
- * actually uses: `sudo xcrun simctl …`, `env FOO=1 xcrun simctl …`,
- * `timeout 30 xcrun simctl …`.
- *
- * **An option on the prefix ends the peel.** Reading past one means knowing that
- * CLI's option arity *and* whether its operands are executed at all — `sudo -l`
- * and `command -v` merely report on the command they name. Both kinds of
- * knowledge were a standing source of defects here, in the direction that
- * matters: getting either wrong denies ordinary work. Stopping can only miss,
- * and a recipe copied out of documentation does not arrive decorated with
- * options.
- */
-const LITERAL_COMMAND_PREFIXES = new Set([
- 'arch',
- 'builtin',
- 'caffeinate',
- 'command',
- 'env',
- 'exec',
- 'gtimeout',
- 'nice',
- 'nocorrect',
- 'noglob',
- 'nohup',
- 'sudo',
- 'time',
- 'timeout',
- 'xargs',
-]);
-
-interface UnwrappedCommand {
- tokens: string[];
- /** A literal program string handed to a shell via `-c`, classified recursively. */
- nestedShell: string | null;
- assignments: ShellAssignment[];
-}
-
-/** Builtins that declare `NAME=value`, an equally standard way to store a recipe. */
-const SHELL_ASSIGNMENT_BUILTINS = new Set([
- 'declare',
- 'export',
- 'readonly',
- 'typeset',
-]);
-
-/** Peel documentation-style prefixes to reach the command word. */
-function unwrapCommand(input: string[]): UnwrappedCommand {
- const first = stripLeadingShellPreamble(stripShellControlTokens(input));
- let tokens = first.tokens;
- const assignments = [...first.assignments];
- for (let depth = 0; depth < MAX_RECURSION_DEPTH; depth += 1) {
- const peeled = stripLeadingShellPreamble(tokens);
- tokens = peeled.tokens;
- assignments.push(...peeled.assignments);
- if (tokens.length === 0) return { tokens, nestedShell: null, assignments };
- const head = executableName(tokens[0]);
-
- if (SHELL_ASSIGNMENT_BUILTINS.has(head)) {
- // `export CMD='xcrun simctl …'` stores the recipe just like a bare
- // assignment, so its operands feed the same stored-value path.
- for (const token of tokens.slice(1)) {
- const assignment = SHELL_ASSIGNMENT.exec(token);
- if (assignment) {
- assignments.push({ name: assignment[1] ?? '', value: assignment[2] ?? '' });
- }
- }
- return { tokens: [], nestedShell: null, assignments };
- }
-
- if (SHELL_EXECUTABLES.has(head)) {
- // Only leading options belong to the shell. `bash ./run.sh -c 'x'` passes
- // `-c` to the script as `$1`, so scanning the whole argv would classify an
- // ordinary script argument as an executed shell program.
- let index = 1;
- while (index < tokens.length) {
- const token = tokens[index]!;
- if (token === '--') break;
- if (!token.startsWith('-') && !token.startsWith('+')) break;
- if (/^-[A-Za-z]*c[A-Za-z]*$/.test(token)) {
- return { tokens: [], nestedShell: tokens[index + 1] ?? '', assignments };
- }
- // `-o name` and `-O shopt_option` take a value; skipping one token would
- // read the option's value as the script operand and end the scan early.
- index += /^[-+][oO]$/.test(token) ? 2 : 1;
- }
- return { tokens, nestedShell: null, assignments };
- }
- if (head === 'eval') {
- return { tokens: [], nestedShell: tokens.slice(1).join(' '), assignments };
- }
- if (!LITERAL_COMMAND_PREFIXES.has(head)) return { tokens, nestedShell: null, assignments };
-
- let index = 1;
- if (tokens[index] === '--') {
- // The only option-like token whose meaning needs no per-CLI knowledge.
- index += 1;
- } else if (tokens[index]?.startsWith('-')) {
- return { tokens, nestedShell: null, assignments };
- }
- // timeout takes a duration operand before the command it runs.
- if ((head === 'timeout' || head === 'gtimeout') && /^[\d.]+[smhd]?$/.test(tokens[index] ?? '')) {
- index += 1;
- }
- const next = tokens.slice(index);
- if (next.length === 0 || next.length === tokens.length) {
- return { tokens: next, nestedShell: null, assignments };
- }
- tokens = next;
- }
- return { tokens, nestedShell: null, assignments };
-}
-
-/** `open -a Simulator` and the Simulator binary, in their documented spellings. */
-function isExternalSimulatorLaunch(tokens: string[]): boolean {
- const head = executableName(tokens[0]);
- if (head === 'open') {
- for (let index = 1; index < tokens.length; index += 1) {
- const token = tokens[index]!;
- const next = tokens[index + 1];
- if (/^-[^-]*a[^-]*$/i.test(token) && /^Simulator(?:\.app)?$/i.test(next ?? '')) return true;
- if (/^-aSimulator(?:\.app)?$/i.test(token)) return true;
- if (/^-[^-]*b[^-]*$/i.test(token) && /^com\.apple\.iphonesimulator$/i.test(next ?? '')) {
- return true;
- }
- if (/^-bcom\.apple\.iphonesimulator$/i.test(token)) return true;
- if (/\/Simulator\.app(?:\/Contents\/MacOS\/Simulator)?$/i.test(token)) return true;
- }
- }
- return (
- head === 'simulator' && /Simulator\.app\/Contents\/MacOS\/Simulator$/i.test(tokens[0] ?? '')
- );
-}
-
-/** The simctl subcommand of a literal `[xcrun] simctl …` invocation, or null. */
-function simctlSubcommand(tokens: string[]): string | null {
- let index = 0;
- if (executableName(tokens[index]) === 'xcrun') {
- index += 1;
- while (index < tokens.length && tokens[index]!.startsWith('-')) {
- const option = tokens[index]!;
- const takesValue =
- option === '--sdk' ||
- option === '-sdk' ||
- option === '--toolchain' ||
- option === '-toolchain';
- index += takesValue ? 2 : 1;
- }
- }
- if (executableName(tokens[index]) !== 'simctl') return null;
- index += 1;
- if (tokens[index] === '--set') index += 2;
- return tokens[index]?.toLowerCase() ?? null;
-}
-
-function isSimulatorMutation(tokens: string[]): boolean {
- const subcommand = simctlSubcommand(tokens);
- return subcommand !== null && !SAFE_SIMCTL_COMMANDS.has(subcommand);
-}
-
-function isSimulatorRecipeArgv(tokens: string[]): boolean {
- return isExternalSimulatorLaunch(tokens) || isSimulatorMutation(tokens);
-}
-
-/** A Simulator command spelled out in free text, used for interpreter payloads. */
-function containsLiteralSimulatorExecutor(value: string): boolean {
- const argvLike = value.replace(/[^A-Za-z0-9_./-]+/g, ' ').trim();
- return (
- /\bxcrun\b[\s\S]*\bsimctl\b/i.test(value) ||
- /(?:^|[^\w./-])simctl\s+\S/i.test(argvLike) ||
- /\bSimulator\.app\b/i.test(value) ||
- /\bcom\.apple\.iphonesimulator\b/i.test(value) ||
- /(?:^|\s)(?:\S*\/)?open(?:\s+-[A-Za-z]+)*\s+Simulator(?:\.app)?(?:\s|$)/i.test(argvLike)
- );
-}
-
-/**
- * A recipe pasted into an interpreter one-liner (`python3 -c 'os.system("xcrun
- * simctl boot X")'`) is still literal, so the payload is scanned as text. Only a
- * spelled-out command counts; assembling one from fragments is outside the threat
- * model.
- */
-function containsInterpreterSimulatorPayload(tokens: string[]): boolean {
- if (!PROGRAMMABLE_INTERPRETER.test(executableName(tokens[0]))) return false;
- return containsLiteralSimulatorExecutor(tokens.slice(1).join('\n'));
-}
-
-/** Command and process substitutions execute, so their contents are classified too. */
-function shellSubcommands(command: string): string[] {
- const subcommands: string[] = [];
- let quote: "'" | '"' | null = null;
- let escaped = false;
- for (let index = 0; index < command.length; index += 1) {
- const char = command[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- escaped = true;
- continue;
- }
- if (char === "'") {
- if (quote === "'") quote = null;
- else if (quote === null) quote = "'";
- continue;
- }
- if (char === '"') {
- if (quote === '"') quote = null;
- else if (quote === null) quote = '"';
- continue;
- }
- if (quote === "'") continue;
- if (char === '`') {
- let end = index + 1;
- for (; end < command.length; end += 1) {
- if (command[end] === '\\') end += 1;
- else if (command[end] === '`') break;
- }
- if (end < command.length) {
- subcommands.push(command.slice(index + 1, end));
- index = end;
- }
- continue;
- }
- if ((char === '$' || char === '<' || char === '>') && command[index + 1] === '(') {
- let depth = 1;
- let innerQuote: "'" | '"' | null = null;
- let end = index + 2;
- for (; end < command.length && depth > 0; end += 1) {
- const inner = command[end]!;
- if (inner === '\\' && innerQuote !== "'") {
- end += 1;
- continue;
- }
- if (inner === "'" || inner === '"') {
- if (innerQuote === inner) innerQuote = null;
- else if (innerQuote === null) innerQuote = inner;
- continue;
- }
- if (innerQuote) continue;
- if (inner === '(') depth += 1;
- else if (inner === ')') depth -= 1;
- }
- if (depth === 0) {
- subcommands.push(command.slice(index + 2, end - 1));
- index = end - 1;
- }
- }
- }
- return subcommands;
-}
-
-function nestedShellConsumesStdinAsProgram(command: string): boolean {
- return (
- /(?:^|[;&|]\s*)(?:source|\.)\s+(?:\/dev\/stdin|\/dev\/fd\/0|-)(?:\s|$)/i.test(command) ||
- /\beval\b[\s\S]*\$\(\s*cat(?:\s+(?:-|\/dev\/stdin|\/dev\/fd\/0))?\s*\)/i.test(command)
- );
-}
-
-/** Leading shell options removed before deciding whether a script operand exists. */
-function shellPositionalArgs(args: string[]): string[] {
- let index = 0;
- while (index < args.length) {
- const token = args[index]!;
- if (token === '--') return args.slice(index + 1);
- if (!token.startsWith('-') && !token.startsWith('+')) break;
- // Bash/zsh `-o name` and Bash `-O shopt_name` consume the next token; that
- // operand is not a script filename and does not displace heredoc stdin.
- index += /^[-+][oO]$/.test(token) ? 2 : 1;
- }
- return args.slice(index);
-}
-
-/** Whether this literal command executes its stdin as source code. */
-function consumesStdinAsProgram(tokens: string[]): boolean {
- const unwrapped = unwrapCommand(tokens);
- if (unwrapped.nestedShell !== null) {
- return nestedShellConsumesStdinAsProgram(unwrapped.nestedShell);
- }
- const executable = executableName(unwrapped.tokens[0]);
- const args = unwrapped.tokens.slice(1);
- if (SHELL_EXECUTABLES.has(executable)) {
- if (args.some((arg) => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg))) return false;
- if (args.some((arg) => /^-[A-Za-z]*s[A-Za-z]*$/.test(arg))) return true;
- } else if (executable === 'osascript') {
- if (args.some((arg) => arg === '-e' || arg.startsWith('-e'))) return false;
- } else if (PROGRAMMABLE_INTERPRETER.test(executable)) {
- if (/^(?:(?:g|m|n)?awk)$/.test(executable)) return false;
- if (args.some((arg) => /^(?:-c|-e|-p|-m|--eval|--print|--input-type|--module)$/.test(arg))) {
- return false;
- }
- } else {
- return false;
- }
- const positional = SHELL_EXECUTABLES.has(executable)
- ? shellPositionalArgs(args)[0]
- : args.find((arg) => !arg.startsWith('-'));
- return positional === undefined || positional === '-';
-}
-
-interface HeredocRedirection {
- start: number;
- marker: string;
- delimiter: string;
- expands: boolean;
- stripsTabs: boolean;
-}
-
-function heredocDescriptorBefore(
- segment: string,
- start: number,
-): { value: string; start: number } | null {
- const beforeOperator = segment.slice(0, start);
- const match = /(?:^|[\s;&|()])(\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/.exec(beforeOperator);
- const value = match?.[1];
- return value === undefined ? null : { value, start: start - value.length };
-}
-
-/** Whether a heredoc redirection feeds the command's stdin rather than another fd. */
-function heredocIsStdinRedirection(segment: string, start: number): boolean {
- const descriptor = heredocDescriptorBefore(segment, start);
- return descriptor === null || descriptor.value === '0';
-}
-
-/**
- * Skip a shell arithmetic expression while looking for heredoc operators.
- *
- * `<<` is also the arithmetic left-shift operator. Treating it as a heredoc
- * opener makes the following physical lines look like the body for a marker
- * named `2`, so a real command after the arithmetic expression can disappear
- * from classification. Both `$(( ... ))` expansions and `(( ... ))` commands
- * use the same balanced-parenthesis shape here.
- */
-function skipArithmeticExpression(line: string, start: number): number {
- let depth = 1;
- let quote: "'" | '"' | null = null;
- let escaped = false;
- const expressionStart = line[start] === '$' ? start + 3 : start + 2;
- for (let index = expressionStart; index < line.length; index += 1) {
- const char = line[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- escaped = true;
- continue;
- }
- if (char === "'" || char === '"') {
- if (quote === char) quote = null;
- else if (quote === null) quote = char;
- continue;
- }
- if (quote) continue;
- if (char === '(') {
- depth += 1;
- continue;
- }
- if (char !== ')') continue;
- if (depth === 1 && line[index + 1] === ')') return index + 2;
- depth -= 1;
- }
- return line.length;
-}
-
-/** Skip Bash's legacy `$[ ... ]` arithmetic expansion. */
-function skipLegacyArithmeticExpression(line: string, start: number): number {
- let depth = 1;
- let quote: "'" | '"' | null = null;
- let escaped = false;
- for (let index = start + 2; index < line.length; index += 1) {
- const char = line[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- escaped = true;
- continue;
- }
- if (char === "'" || char === '"') {
- if (quote === char) quote = null;
- else if (quote === null) quote = char;
- continue;
- }
- if (quote) continue;
- if (char === '[') {
- depth += 1;
- continue;
- }
- if (char === ']' && --depth === 0) return index + 1;
- }
- return line.length;
-}
-
-/** Heredoc markers on one shell line, excluding quoted text, comments and `<<<`. */
-function heredocRedirections(line: string): HeredocRedirection[] {
- const redirections: HeredocRedirection[] = [];
- let quote: "'" | '"' | null = null;
- let escaped = false;
- for (let index = 0; index < line.length; index += 1) {
- const char = line[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- escaped = true;
- continue;
- }
- if (char === "'" || char === '"') {
- if (quote === char) quote = null;
- else if (quote === null) quote = char;
- continue;
- }
- if (quote) continue;
- // `<<` inside arithmetic syntax is left shift, not a shell heredoc. Skip
- // both current `$(( ... ))` / `(( ... ))` and Bash's legacy `$[ ... ]`.
- if (
- (char === '$' && line[index + 1] === '(' && line[index + 2] === '(') ||
- (char === '(' && line[index + 1] === '(')
- ) {
- index = skipArithmeticExpression(line, index) - 1;
- continue;
- }
- if (char === '$' && line[index + 1] === '[') {
- index = skipLegacyArithmeticExpression(line, index) - 1;
- continue;
- }
- // In shell grammar `#` starts a comment when it begins a word. A marker in
- // that comment must not consume later commands as a fake heredoc body.
- if (char === '#' && (index === 0 || /[\s;&|()]/.test(line[index - 1]!))) break;
- if (char !== '<' || line[index + 1] !== '<' || line[index + 2] === '<') continue;
- let cursor = index + 2;
- const stripsTabs = line[cursor] === '-';
- if (stripsTabs) cursor += 1;
- while (line[cursor] === ' ' || line[cursor] === '\t') cursor += 1;
- let delimiter = '';
- let expands = true;
- while (cursor < line.length) {
- const delimiterChar = line[cursor]!;
- if (
- delimiterChar === '$'
- && (line[cursor + 1] === "'" || line[cursor + 1] === '"')
- ) {
- // Bash's ANSI-C and locale quote prefixes are removed along with the
- // surrounding quotes for a simple literal delimiter (`$'EOF'`). Do not
- // grow this boundary into decoding ANSI-C escape sequences.
- expands = false;
- cursor += 1;
- continue;
- }
- if (delimiterChar === "'" || delimiterChar === '"') {
- expands = false;
- const closing = line.indexOf(delimiterChar, cursor + 1);
- if (closing < 0) {
- delimiter += line.slice(cursor + 1);
- cursor = line.length;
- break;
- }
- delimiter += line.slice(cursor + 1, closing);
- cursor = closing + 1;
- continue;
- }
- if (delimiterChar === '\\') {
- expands = false;
- cursor += 1;
- if (cursor < line.length) {
- delimiter += line[cursor]!;
- cursor += 1;
- }
- continue;
- }
- if (/[\s;&|<>()]/.test(delimiterChar)) break;
- delimiter += delimiterChar;
- cursor += 1;
- }
- if (delimiter !== '') {
- redirections.push({
- start: index,
- marker: line.slice(index, cursor),
- delimiter,
- expands,
- stripsTabs,
- });
- }
- index = cursor - 1;
- }
- return redirections;
-}
-
-/** Remove heredoc operators before tokenizing the command that consumes them. */
-function removeHeredocRedirections(command: string): string {
- const redirections = heredocRedirections(command);
- let result = command;
- for (let index = redirections.length - 1; index >= 0; index -= 1) {
- const redirection = redirections[index]!;
- const descriptor = heredocDescriptorBefore(command, redirection.start);
- const removalStart = descriptor?.start ?? redirection.start;
- result =
- result.slice(0, removalStart)
- + result.slice(redirection.start + redirection.marker.length);
- }
- return result;
-}
-
-/** Find the closing parenthesis for a shell `$(...)`, `<(...)` or `>(...)`. */
-function skipShellSubstitution(input: string, start: number): number {
- let depth = 1;
- let quote: "'" | '"' | null = null;
- let escaped = false;
- for (let index = start + 2; index < input.length; index += 1) {
- const char = input[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- escaped = true;
- continue;
- }
- if (char === "'" || char === '"') {
- if (quote === char) quote = null;
- else if (quote === null) quote = char;
- continue;
- }
- if (quote !== null) continue;
- if (char === '(') depth += 1;
- else if (char === ')' && --depth === 0) return index;
- }
- return input.length - 1;
-}
-
-/** Find the closing backtick for an old-style shell command substitution. */
-function skipBacktickSubstitution(input: string, start: number): number {
- let escaped = false;
- for (let index = start + 1; index < input.length; index += 1) {
- const char = input[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\') {
- escaped = true;
- continue;
- }
- if (char === '`') return index;
- }
- return input.length - 1;
-}
-
-/** Whether a pipeline segment explicitly replaces its stdin source. */
-function hasUnquotedStdinRedirection(segment: string): boolean {
- let quote: "'" | '"' | null = null;
- let escaped = false;
- for (let index = 0; index < segment.length; index += 1) {
- const char = segment[index]!;
- if (escaped) {
- escaped = false;
- continue;
- }
- if (char === '\\' && quote !== "'") {
- escaped = true;
- continue;
- }
- if (quote) {
- if (char === quote) quote = null;
- continue;
- }
- if (char === "'" || char === '"') {
- quote = char;
- continue;
- }
- if (
- (char === '$' && segment[index + 1] === '(' && segment[index + 2] === '(') ||
- (char === '(' && segment[index + 1] === '(')
- ) {
- index = skipArithmeticExpression(segment, index) - 1;
- continue;
- }
- if (char === '$' && segment[index + 1] === '[') {
- index = skipLegacyArithmeticExpression(segment, index) - 1;
- continue;
- }
- if (
- (char === '$' || char === '<' || char === '>')
- && segment[index + 1] === '('
- ) {
- index = skipShellSubstitution(segment, index);
- continue;
- }
- if (char === '`') {
- index = skipBacktickSubstitution(segment, index);
- continue;
- }
- if (char !== '<') continue;
- const redirection = redirectionAt(segment, index);
- if (redirection === null) continue;
- // A descriptor other than 0 redirects a separate input channel and does
- // not replace the pipeline's stdin. Cover both `2<file` and Bash's
- // allocated-fd spelling `{fd}<file`.
- const beforeOperator = segment.slice(0, index);
- const explicitDescriptor =
- /(?:^|[\s;&|()])(\d+)$/.exec(beforeOperator)?.[1]
- ?? /(?:^|[\s;&|()])(\{[A-Za-z_][A-Za-z0-9_]*\})$/.exec(beforeOperator)?.[1]
- ?? null;
- if (explicitDescriptor !== null && explicitDescriptor !== '0') {
- index += redirection.length - 1;
- continue;
- }
- return true;
- }
- return false;
-}
-
-/** Whether the heredoc's own clause hands its body to a code-reading consumer. */
-function heredocBodyIsProgram(line: string, markerStart: number): boolean {
- const segments = shellSegments(line);
- let searchCursor = 0;
- let openingSegmentStart = -1;
- const openingIndex = segments.findIndex((segment) => {
- const segmentStart = line.indexOf(segment.command, searchCursor);
- if (segmentStart < 0) return false;
- searchCursor = segmentStart + segment.command.length;
- if (markerStart < segmentStart || markerStart >= searchCursor) return false;
- openingSegmentStart = segmentStart;
- return true;
- });
- if (openingIndex < 0) return false;
- const openingSegment = segments[openingIndex]!;
- const localMarkerStart = markerStart - openingSegmentStart;
- const openingRedirections = heredocRedirections(openingSegment.command);
- const openingRedirection = openingRedirections.find(
- (redirection) => redirection.start === localMarkerStart,
- );
- if (
- !openingRedirection
- || !heredocIsStdinRedirection(openingSegment.command, openingRedirection.start)
- ) return false;
- // Bash applies multiple stdin heredocs on one consumer from left to right;
- // only the final stdin redirection supplies the process's input. A previous
- // body is data even when the later body is the program we should inspect.
- if (
- openingRedirections.some(
- (redirection) =>
- redirection.start > openingRedirection.start
- && heredocIsStdinRedirection(openingSegment.command, redirection.start),
- )
- ) return false;
- for (let index = openingIndex; index < segments.length; index += 1) {
- const segment = segments[index]!;
- if (index > openingIndex && segment.precedingOperator !== '|') break;
- // A downstream stdin redirection takes precedence over the pipe, so the
- // current heredoc body cannot become that command's input program.
- if (index > openingIndex && hasUnquotedStdinRedirection(segment.command)) break;
- if (
- consumesStdinAsProgram(
- tokenizeHeredocConsumer(removeHeredocRedirections(segment.command)),
- )
- ) return true;
- }
- return false;
-}
-
-/**
- * Remove stdin-only heredoc prose before classifying command words.
- *
- * Bodies executed by a shell/interpreter remain visible. Data bodies disappear,
- * except that an unquoted delimiter still executes command/process substitutions.
- */
-function stripHeredocBodies(command: string): string {
- if (!command.includes('<<')) return command;
- const lines = command.split(/\r?\n/);
- const executable: string[] = [];
- for (let index = 0; index < lines.length; index += 1) {
- const line = lines[index]!;
- executable.push(line);
- for (const heredoc of heredocRedirections(line)) {
- const body: string[] = [];
- index += 1;
- for (; index < lines.length; index += 1) {
- const candidate = lines[index]!;
- const unindented = heredoc.stripsTabs ? candidate.replace(/^\t+/, '') : candidate;
- if (unindented === heredoc.delimiter) break;
- body.push(candidate);
- }
- if (heredocBodyIsProgram(line, heredoc.start)) executable.push(...body);
- else if (heredoc.expands) executable.push(...shellSubcommands(body.join('\n')));
- if (index >= lines.length) break;
- }
- }
- return executable.join('\n');
-}
-
-function containsSimulatorRecipe(command: string, depth = 0): boolean {
- if (depth > MAX_RECURSION_DEPTH) return false;
- const executableCommand = stripHeredocBodies(command);
- for (const nested of shellSubcommands(executableCommand)) {
- if (containsSimulatorRecipe(nested, depth + 1)) return true;
- }
- const assignments = new Map<string, string[]>();
- const referencedAssignmentContainsRecipe = (
- reference: string,
- visibleAssignments: Map<string, string[]> = assignments,
- ): boolean => {
- for (const [name, values] of visibleAssignments) {
- // The name matched `[A-Za-z_][A-Za-z0-9_]*`, so it carries no regex syntax.
- if (!new RegExp(`\\$\\{?${name}\\b`).test(reference)) continue;
- if (values.some((value) => containsSimulatorRecipe(value, depth + 1))) return true;
- }
- return false;
- };
- for (const segment of shellSegments(executableCommand)) {
- const unwrapped = unwrapCommand(tokenizeShellSegment(segment.command));
- const commandScopedAssignments = new Map<string, string[]>();
- // Shell assignments replace the previous value before the command in this
- // segment runs. A `;`/newline-separated assignment therefore supersedes the
- // previous value, while a conditional, pipeline or background edge can skip
- // it or isolate its scope, so both values remain possible there.
- for (const assignment of unwrapped.assignments) {
- if (assignment.name === '') continue;
- const persistentAssignment =
- assignmentDefinitelyRunsInCurrentScope(segment)
- && unwrapped.tokens.length === 0
- && unwrapped.nestedShell === null;
- if (persistentAssignment) {
- assignments.set(assignment.name, [assignment.value]);
- } else if (unwrapped.tokens.length > 0 || unwrapped.nestedShell !== null) {
- // A leading assignment shadows the exported value only for this
- // command. Use its last value while classifying the child, then leave
- // the parent-shell possibilities unchanged for later segments.
- commandScopedAssignments.set(assignment.name, [assignment.value]);
- } else {
- const possibleValues = assignments.get(assignment.name) ?? [];
- possibleValues.push(assignment.value);
- assignments.set(assignment.name, possibleValues);
- }
- }
- const visibleAssignments = new Map(assignments);
- for (const [name, values] of commandScopedAssignments) {
- visibleAssignments.set(name, values);
- }
- if (unwrapped.nestedShell !== null) {
- // `eval "$CMD"` and `sh -c "$CMD"` run a variable this scan cannot resolve.
- if (referencedAssignmentContainsRecipe(unwrapped.nestedShell, visibleAssignments)) {
- return true;
- }
- if (containsSimulatorRecipe(unwrapped.nestedShell, depth + 1)) return true;
- continue;
- }
- // A variable in the command word position is run as the command itself.
- const commandWord = unwrapped.tokens[0];
- if (
- commandWord?.includes('$')
- && referencedAssignmentContainsRecipe(commandWord, visibleAssignments)
- ) return true;
- if (isSimulatorRecipeArgv(unwrapped.tokens)) return true;
- if (containsInterpreterSimulatorPayload(unwrapped.tokens)) return true;
- }
- return false;
-}
-
-/** Undefined means the normal shell permission flow remains unchanged. */
-export function getDesktopShellCommandPolicy(
- command: string,
-): ShellCommandPolicyDenial | undefined {
- if (process.platform !== 'darwin') return undefined;
- // POSIX shells remove an unquoted backslash-newline before tokenization.
- const expandedCommand = command.replace(/\\\r?\n/g, '');
- if (containsSimulatorRecipe(expandedCommand)) {
- return { decision: 'deny', reason: IOS_SIMULATOR_SHELL_DENIAL };
- }
- return undefined;
-}
-
-export const iosSimulatorShellDenialReason = IOS_SIMULATOR_SHELL_DENIAL;
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
index cdbebb9c9e..97f237ce30 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/computer.test.ts
@@ -2466,54 +2466,6 @@ describe('computer mcp integration', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
- it('resolves Computer Use target PID provenance for package-level routing guards', async () => {
- const deps = getComputerMcpDeps();
- mockProcessSnapshotSpawn([{
- pid: 686,
- parentPid: 1,
- name: 'Xcode',
- command: '/Applications/Xcode.app/Contents/MacOS/Xcode',
- executable: '/Applications/Xcode.app/Contents/MacOS/Xcode',
- }]);
-
- await expect(deps.resolveProcessIdentity?.(686)).resolves.toMatchObject({
- pid: 686,
- name: 'Xcode',
- command: '/Applications/Xcode.app/Contents/MacOS/Xcode',
- });
- expect(spawnMock).toHaveBeenCalledTimes(1);
- });
-
- it('bypasses the process snapshot cache when a routing guard requests fresh provenance', async () => {
- const deps = getComputerMcpDeps();
- mockProcessSnapshotSpawn([{
- pid: 687,
- parentPid: 1,
- name: 'Code',
- command: '/Applications/Visual Studio Code.app/Contents/MacOS/Electron',
- }]);
- mockProcessSnapshotSpawn([{
- pid: 687,
- parentPid: 1,
- name: 'Simulator',
- command:
- '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
- }]);
-
- await expect(deps.resolveProcessIdentity?.(687)).resolves.toMatchObject({
- pid: 687,
- command: '/Applications/Visual Studio Code.app/Contents/MacOS/Electron',
- });
- await expect(
- deps.resolveProcessIdentity?.(687, { forceFresh: true }),
- ).resolves.toMatchObject({
- pid: 687,
- command:
- '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
- });
- expect(spawnMock).toHaveBeenCalledTimes(2);
- });
-
it('closes active MCP sessions and blocks tool dispatch while permission onboarding is paused', async () => {
setPlatform('darwin');
mcpCallToolMock
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index 6e4c65586e..6bfcddeb7d 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -3501,22 +3501,6 @@ export function getComputerMcpDeps(options: ComputerMcpDepsOptions = {}): Comput
await ensureRuntime();
return getComputerDriverStatus();
},
- resolveProcessIdentity: async (pid, resolveOptions) => {
- const forceFresh = resolveOptions?.forceFresh === true;
- let processSnapshot = await readProcessSnapshotResult({ forceFresh });
- let processInfo = processSnapshot.processes.get(pid);
- if (!processInfo && !forceFresh) {
- processSnapshot = await readProcessSnapshotResult({ forceFresh: true });
- processInfo = processSnapshot.processes.get(pid);
- }
- if (!processInfo) return null;
- return {
- pid: processInfo.pid,
- name: processInfo.name,
- command: processInfo.command,
- executable: processInfo.executable,
- };
- },
callTool: async (name, args, context) => {
if (options.isComputerUseEnabled && !options.isComputerUseEnabled(context)) {
throw new ComputerDriverError('Computer Use is disabled in Settings.');
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 7f361ab95e..7dfdbf9615 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -6536,19 +6536,6 @@ function currentIOSSimulatorHost(): IOSSimulatorHost | null {
return defaultIOSSimulatorRuntime?.host ?? null;
}
-/**
- * Whether this process installed the Host Simulator runtime, which means Cindy
- * may hold simulator ownership right now.
- *
- * Synchronous and side-effect free by contract: it must never initialize the
- * Host, because the plugin gate's whole point is that an absent plugin leaves
- * the runtime untouched. A shutting-down runtime still counts as active so
- * in-flight cleanup keeps its protection.
- */
-export function isIOSSimulatorHostRuntimeActive(): boolean {
- return currentIOSSimulatorHost() !== null || defaultIOSSimulatorRuntimeClosing;
-}
-
export function getIOSSimulatorSessionStatus(
sessionId: string,
): Promise<IOSSimulatorSessionStatus> {
diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.md
index 6917404663..9facbbef97 100644
--- a/docs/ios-simulator-integration-plan.md
+++ b/docs/ios-simulator-integration-plan.md
@@ -8,7 +8,7 @@
>
> 适用平台:macOS
>
-> 更新时间:2026-08-05
+> 更新时间:2026-08-13
## 0. 当前实施状态
@@ -17,8 +17,8 @@
- 新增 host-neutral `@cindy/ios-simulator-runtime`,通过 argv 方式调用 Apple 工具并解析 `simctl list -j`,不执行 shell。
- Desktop main 以真实 Session 记录为准,local macOS 会话可发现环境;缺失、已删除、SSH/remote Session 均 fail-closed。
- 新增默认启用、允许用户或项目显式关闭的 `cindy_ios_simulator` Agent provider,已经覆盖环境/设备/实例生命周期、screen map、基础输入、App build/install/launch/terminate/open URL、截图录屏和诊断工具。这样 iOS 请求可直接进入内嵌流程,而无需用户先为每个项目手动开启插件。
-- 新增宿主级 shell hard gate:对 Agent 发出的 `open -a Simulator`、Simulator.app 直接可执行路径和会改变设备状态的 `xcrun simctl` 命令确定性拒绝,并将请求引导回 `cindy_ios_simulator`;只读 `simctl list/listapps`、Xcode build 和关闭外部 Simulator 不受影响。不同 Agent runtime 分别通过 PATH shim、command approval deny、item-start interrupt 或 pre-tool hook 覆盖 Full access 免审批命令与绝对路径兜底,避免旧 skill 或恢复会话绕过内嵌路由。
-- 新增 Computer MCP 外部 iOS 工作流硬闸:`launch_app(Xcode/Simulator)` 直接返回 `EMBEDDED_IOS_SIMULATOR_PREFERRED`;对 PID 定向的 click/hotkey/type 等修改操作先由 Desktop 使用 OS 进程快照解析真实 provenance,命中 Xcode 或 Simulator.app 时同样引导到 `cindy_ios_simulator`,无法验证 provenance 时 fail closed。只读窗口检查和其它已验证身份的应用操作保持可用;在 Cindy 建立 host-issued、按任务绑定的显式授权流之前,不向模型暴露外部 iOS 修改操作的 override 参数。
+- 内嵌与外部模拟器的路线选择由插件 Skill/Agent 负责:内嵌能力可用且适合任务时优先使用 `cindy_ios_simulator`,不可用或用户需要系统窗口时可以走普通 shell、Xcode、Simulator.app、`simctl` 或 Computer Use。Desktop 不再注入 iOS 专用 shell policy、Claude hook 或 Codex PATH shim;外部命令继续服从 Agent 原有权限与审批机制。
+- Computer MCP 不再对 Xcode/Simulator.app 设置 iOS 专用路由硬闸;启动、点击、快捷键和轨迹回放均走普通桌面驱动。工作目录路径边界、窗口快照代际、轨迹不可变预检、取消与执行预算等通用安全保护保持不变。内嵌 Host 的 session ownership、generation、lease、设备准入、跨任务隔离与 cleanup 仍由 Host 强制执行,不依赖 Skill 自觉。
- 新增非 singleton 的 `ios-simulator` right-sidebar plugin;用户可手动打开、attach、启动/停止/解绑设备、管理 Agent 设备授权,并查看 main 内存中的实时 JPEG stream 与 FPS/连接状态。
- manual pane 与 Agent tool gate 分离:关闭实验性 Agent tool 不影响用户查看本机设备状态。
- 已覆盖 runtime parser、MCP envelope/session context、main host/IPC、远程会话拒绝、renderer 状态展示和 plugin provider 映射测试。
diff --git a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
index 1f47265f19..59fb657226 100644
--- a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
@@ -39,16 +39,8 @@ function textPayload(result: unknown): unknown {
async function makeHarness(
deps: ComputerMcpDeps,
options?: Parameters<typeof createComputerMcpServer>[1],
- testOptions: { injectDefaultProcessResolver?: boolean } = {},
) {
- const resolvedDeps =
- testOptions.injectDefaultProcessResolver === false || deps.resolveProcessIdentity
- ? deps
- : {
- ...deps,
- resolveProcessIdentity: vi.fn(async (pid: number) => ({ pid, name: 'Code' })),
- };
- const server = createComputerMcpServer(resolvedDeps, options);
+ const server = createComputerMcpServer(deps, options);
const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'computer-test-client', version: '0.0.0' });
await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
@@ -92,8 +84,7 @@ describe('createComputerMcpServer', () => {
expect(listWindows?.inputSchema?.properties).toHaveProperty('process_name');
expect(payload.workflow).toContain('query/workspace_root/process_name');
expect(listWindows?.description).toContain('{"process_name":"Simulator"}');
- expect(payload.workflow).toContain('cindy_ios_simulator first');
- expect(listWindows?.description).toContain('external desktop UI work');
+ expect(payload.workflow).toContain('{"process_name":"Simulator"}');
expect(payload.tools.find((tool) => tool.name === 'get_window_state')?.description)
.toContain('{"capture_mode":"vision"}');
expect(payload.tools.find((tool) => tool.name === 'click')?.description)
@@ -474,44 +465,36 @@ describe('createComputerMcpServer', () => {
await h.cleanup();
});
- it('routes standalone Simulator.app launches to the embedded simulator by default', async () => {
+ it('dispatches standalone Simulator.app launches through the normal desktop driver', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- callTool: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
};
const h = await makeHarness(deps);
- const result = await h.client.callTool({
+ const payload = textPayload(await h.client.callTool({
name: 'call_tool',
arguments: {
name: 'launch_app',
args: { name: 'Simulator' },
},
- });
- const payload = textPayload(result) as {
- ok: boolean;
- errorCode: string;
- data: { next_tool?: string };
- };
+ })) as { ok: boolean };
- expect(payload).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: { next_tool: 'cindy_ios_simulator' },
+ expect(payload.ok).toBe(true);
+ expect(deps.callTool).toHaveBeenCalledWith('launch_app', {
+ name: 'Simulator',
});
- expect(result.isError).toBe(true);
- expect(deps.callTool).not.toHaveBeenCalled();
await h.cleanup();
});
- it('routes Xcode launches to the embedded simulator workflow by default', async () => {
+ it('dispatches Xcode launches through the normal desktop driver', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- callTool: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
};
const h = await makeHarness(deps);
- const result = await h.client.callTool({
+ const payload = textPayload(await h.client.callTool({
name: 'call_tool',
arguments: {
name: 'launch_app',
@@ -521,218 +504,47 @@ describe('createComputerMcpServer', () => {
urls: ['file:///repo/App.xcworkspace'],
},
},
- });
- const payload = textPayload(result) as {
- ok: boolean;
- errorCode: string;
- data: { next_tool?: string; blocked_target?: string };
- };
+ })) as { ok: boolean };
- expect(payload).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: {
- next_tool: 'cindy_ios_simulator',
- blocked_target: 'Xcode',
- },
+ expect(payload.ok).toBe(true);
+ expect(deps.callTool).toHaveBeenCalledWith('launch_app', {
+ name: 'Xcode',
+ bundle_id: 'com.apple.dt.Xcode',
+ urls: ['file:///repo/App.xcworkspace'],
});
- expect(result.isError).toBe(true);
- expect(deps.callTool).not.toHaveBeenCalled();
await h.cleanup();
});
- it.each(['/Applications/Xcode-beta.app', '/Applications/Xcode_26.app'])(
- 'routes renamed Xcode bundle %s to the embedded simulator workflow',
- async (name) => {
+ it.each([
+ ['Xcode hotkey', 'hotkey', { pid: 686, window_id: 282, keys: ['cmd', 'r'] }],
+ ['Simulator click', 'click', { pid: 44412, window_id: 29131, x: 20, y: 20 }],
+ ])(
+ 'dispatches %s without requiring process provenance',
+ async (_label, name, args) => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- callTool: vi.fn(),
+ callTool: vi.fn(async () => ({ ok: true })),
};
- const h = await makeHarness(deps);
+ const h = await makeHarness(deps, { sessionId: 'agent-session-1' });
- const result = await h.client.callTool({
+ const payload = textPayload(await h.client.callTool({
name: 'call_tool',
arguments: {
- name: 'launch_app',
- args: { name },
+ name,
+ args,
},
- });
- expect(textPayload(result)).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: { blocked_target: 'Xcode' },
- });
- expect(result.isError).toBe(true);
- expect(deps.callTool).not.toHaveBeenCalled();
+ })) as { ok: boolean };
+
+ expect(payload.ok).toBe(true);
+ expect(deps.callTool).toHaveBeenCalledWith(
+ name,
+ { ...args, session: 'agent-session-1' },
+ { sessionId: 'agent-session-1' },
+ );
await h.cleanup();
},
);
- it('blocks Xcode hotkeys using host-resolved PID provenance', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) => ({
- pid,
- name: 'Xcode',
- executable: '/Applications/Xcode.app/Contents/MacOS/Xcode',
- })),
- callTool: vi.fn(),
- };
- const h = await makeHarness(deps, { sessionId: 'agent-session-1' });
-
- const result = await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'hotkey',
- args: { pid: 686, window_id: 282, keys: ['cmd', 'r'] },
- },
- });
- const payload = textPayload(result) as {
- ok: boolean;
- errorCode: string;
- data: { next_tool?: string; blocked_target?: string };
- };
-
- expect(payload).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: {
- next_tool: 'cindy_ios_simulator',
- blocked_target: 'Xcode',
- },
- });
- expect(deps.resolveProcessIdentity).toHaveBeenCalledWith(686);
- expect(deps.callTool).not.toHaveBeenCalled();
- await h.cleanup();
- });
-
- it('blocks mutating Simulator.app actions using host-resolved PID provenance', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) => ({
- pid,
- command: '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
- })),
- callTool: vi.fn(),
- };
- const h = await makeHarness(deps);
-
- const result = await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'click',
- args: { pid: 44412, window_id: 29131, x: 20, y: 20 },
- },
- });
- const payload = textPayload(result) as {
- ok: boolean;
- errorCode: string;
- data: { blocked_target?: string };
- };
-
- expect(payload).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: { blocked_target: 'Simulator.app' },
- });
- expect(deps.callTool).not.toHaveBeenCalled();
- await h.cleanup();
- });
-
- it('keeps Xcode read-only inspection available', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Xcode' })),
- callTool: vi.fn(async () => ({ elements: [] })),
- };
- const h = await makeHarness(deps, { sessionId: 'agent-session-1' });
-
- const payload = textPayload(await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'get_window_state',
- args: { pid: 686, window_id: 282, capture_mode: 'ax' },
- },
- })) as { ok: boolean };
-
- expect(payload.ok).toBe(true);
- expect(deps.resolveProcessIdentity).not.toHaveBeenCalled();
- expect(deps.callTool).toHaveBeenCalledWith('get_window_state', {
- pid: 686,
- window_id: 282,
- capture_mode: 'ax',
- session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
- await h.cleanup();
- });
-
- it('does not block the same hotkey in a non-iOS desktop app', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) => ({
- pid,
- name: 'Code',
- executable: '/Applications/Visual Studio Code.app/Contents/MacOS/Electron',
- })),
- callTool: vi.fn(async () => ({ ok: true })),
- };
- const h = await makeHarness(deps, { sessionId: 'agent-session-1' });
-
- const payload = textPayload(await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'hotkey',
- args: { pid: 123, window_id: 7, keys: ['cmd', 'r'] },
- },
- })) as { ok: boolean };
-
- expect(payload.ok).toBe(true);
- expect(deps.callTool).toHaveBeenCalledWith('hotkey', {
- pid: 123,
- window_id: 7,
- keys: ['cmd', 'r'],
- session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
- await h.cleanup();
- });
-
- it.each([
- ['missing resolver', undefined],
- ['resolver failure', vi.fn(async () => { throw new Error('process snapshot unavailable'); })],
- ['missing process', vi.fn(async () => null)],
- ['empty identity', vi.fn(async (pid: number) => ({ pid }))],
- ['mismatched pid', vi.fn(async () => ({ pid: 999, name: 'Code' }))],
- ])('fails closed for mutating actions with %s', async (_label, resolveProcessIdentity) => {
- const callTool = vi.fn();
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- ...(resolveProcessIdentity ? { resolveProcessIdentity } : {}),
- callTool,
- };
- const h = await makeHarness(
- deps,
- undefined,
- { injectDefaultProcessResolver: false },
- );
-
- const result = await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'click',
- args: { pid: 123, window_id: 7, x: 10, y: 20 },
- },
- });
- const payload = textPayload(result) as { ok: boolean; errorCode: string };
-
- expect(payload).toMatchObject({
- ok: false,
- errorCode: 'TARGET_PROVENANCE_UNAVAILABLE',
- });
- expect(result.isError).toBe(true);
- expect(callTool).not.toHaveBeenCalled();
- await h.cleanup();
- });
-
it('rejects model-supplied external iOS override fields before dispatch', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
@@ -1202,212 +1014,65 @@ describe('createComputerMcpServer', () => {
},
);
- it('preflights every turn before replay and blocks a later Simulator action', async () => {
+ it('replays external iOS desktop actions through the normal driver path', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) =>
- pid === 202
- ? {
- pid,
- command:
- '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
- }
- : { pid, name: 'Code' },
- ),
callTool: vi.fn(async () => ({ ok: true })),
};
const root = await makeWorkingDir();
await writeTrajectory(root, [
- { tool: 'click', arguments: { pid: 101, window_id: 1, x: 10, y: 20 } },
+ { tool: 'launch_app', arguments: { name: 'Simulator' } },
{ tool: 'click', arguments: { pid: 202, window_id: 2, x: 30, y: 40 } },
]);
const h = await makeHarness(deps, {
getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
});
- const result = await h.client.callTool({
+ const payload = textPayload(await h.client.callTool({
name: 'call_tool',
arguments: {
name: 'replay_trajectory',
args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
},
- });
+ })) as { ok: boolean; data: { attempted: number; succeeded: number } };
- expect(textPayload(result)).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: { blocked_target: 'Simulator.app' },
+ expect(payload).toMatchObject({
+ ok: true,
+ data: { attempted: 2, succeeded: 2 },
});
- expect(result.isError).toBe(true);
- expect(deps.callTool).not.toHaveBeenCalled();
- await h.cleanup();
- await fs.rm(root, { recursive: true, force: true });
- });
-
- it.each([
- [
- 'Xcode hotkey',
- { tool: 'hotkey', arguments: { pid: 303, keys: ['cmd', 'r'] } },
- { pid: 303, name: 'Xcode' },
- 'Xcode',
- ],
- [
- 'Simulator launch',
- { tool: 'launch_app', arguments: { name: 'Simulator' } },
- { pid: 404, name: 'Code' },
- 'Simulator.app',
- ],
- ])(
- 'blocks %s embedded in a manually authored trajectory',
- async (_label, action, identity, target) => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async () => identity),
- callTool: vi.fn(),
- };
- const root = await makeWorkingDir();
- await writeTrajectory(root, [action]);
- const h = await makeHarness(deps, {
- getSessionContext: () => ({
- agentKind: 'claude-code',
- workingDir: root,
- }),
- });
-
- const result = await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'replay_trajectory',
- args: { dir: 'rec', delay_ms: 0 },
- },
- });
-
- expect(textPayload(result)).toMatchObject({
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: { blocked_target: target },
- });
- expect(deps.callTool).not.toHaveBeenCalled();
- await h.cleanup();
- await fs.rm(root, { recursive: true, force: true });
- },
- );
-
- it('does not classify trajectory paths or typed text as an external Simulator target', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Code' })),
- callTool: vi.fn(async () => ({ ok: true })),
- };
- const root = await makeWorkingDir();
- await writeTrajectory(
- root,
- [
- {
- tool: 'type_text',
- arguments: { pid: 505, text: 'Simulator.app is text only' },
- },
- ],
- 'Simulator-recording',
+ expect(deps.callTool).toHaveBeenNthCalledWith(
+ 1,
+ 'launch_app',
+ { name: 'Simulator' },
+ { agentKind: 'claude-code' },
);
- const h = await makeHarness(deps, {
- getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
- });
-
- const payload = textPayload(
- await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'replay_trajectory',
- args: { dir: 'Simulator-recording', delay_ms: 0 },
- },
- }),
- ) as { ok: boolean; data: { succeeded: number } };
-
- expect(payload).toMatchObject({ ok: true, data: { succeeded: 1 } });
- expect(deps.callTool).toHaveBeenCalledWith(
- 'type_text',
- {
- pid: 505,
- text: 'Simulator.app is text only',
- },
+ expect(deps.callTool).toHaveBeenNthCalledWith(
+ 2,
+ 'click',
+ { pid: 202, window_id: 2, x: 30, y: 40 },
{ agentKind: 'claude-code' },
);
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
});
- it('re-resolves process identity immediately before each recorded action', async () => {
- const resolveProcessIdentity = vi
- .fn()
- .mockResolvedValueOnce({ pid: 606, name: 'Code' })
- .mockResolvedValueOnce({
- pid: 606,
- bundleId: 'com.apple.iphonesimulator',
- });
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- resolveProcessIdentity,
- callTool: vi.fn(async () => ({ ok: true })),
- };
- const root = await makeWorkingDir();
- await writeTrajectory(root, [
- { tool: 'click', arguments: { pid: 606, window_id: 6, x: 10, y: 20 } },
- ]);
- const h = await makeHarness(deps, {
- getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
- });
-
- const payload = textPayload(
- await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'replay_trajectory',
- args: { dir: 'rec', delay_ms: 0 },
- },
- }),
- ) as {
- ok: boolean;
- data: {
- attempted: number;
- failed: number;
- first_failure?: { error?: string };
- };
- };
-
- expect(payload).toMatchObject({
- ok: true,
- data: { attempted: 1, failed: 1 },
- });
- expect(payload.data.first_failure?.error).toContain('EMBEDDED_IOS_SIMULATOR_PREFERRED');
- expect(resolveProcessIdentity).toHaveBeenCalledTimes(2);
- expect(resolveProcessIdentity).toHaveBeenNthCalledWith(1, 606);
- expect(resolveProcessIdentity).toHaveBeenNthCalledWith(2, 606, { forceFresh: true });
- expect(deps.callTool).not.toHaveBeenCalled();
- await h.cleanup();
- await fs.rm(root, { recursive: true, force: true });
- });
-
it('executes the immutable preflight snapshot when the action file changes later', async () => {
const root = await makeWorkingDir();
const trajectory = await writeTrajectory(root, [
{ tool: 'type_text', arguments: { pid: 616, text: 'original text' } },
]);
const actionPath = path.join(trajectory, 'turn-00001', 'action.json');
- const resolveProcessIdentity = vi.fn(async (pid: number) => {
- if (resolveProcessIdentity.mock.calls.length === 1) {
- await fs.writeFile(
- actionPath,
- JSON.stringify({ tool: 'launch_app', arguments: { name: 'Simulator' } }),
- 'utf8',
- );
- }
- return { pid, name: 'Code' };
+ const callTool = vi.fn(async () => {
+ await fs.writeFile(
+ actionPath,
+ JSON.stringify({ tool: 'launch_app', arguments: { name: 'Simulator' } }),
+ 'utf8',
+ );
+ return { ok: true };
});
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- resolveProcessIdentity,
- callTool: vi.fn(async () => ({ ok: true })),
+ callTool,
};
const h = await makeHarness(deps, {
getSessionContext: () => ({ agentKind: 'claude-code', workingDir: root }),
@@ -1422,50 +1087,12 @@ describe('createComputerMcpServer', () => {
})) as { ok: boolean; data: { succeeded: number } };
expect(payload).toMatchObject({ ok: true, data: { succeeded: 1 } });
- expect(deps.callTool).toHaveBeenCalledWith(
+ expect(callTool).toHaveBeenCalledWith(
'type_text',
{ pid: 616, text: 'original text' },
{ agentKind: 'claude-code' },
);
- expect(deps.callTool).not.toHaveBeenCalledWith('launch_app', expect.anything());
- await h.cleanup();
- await fs.rm(root, { recursive: true, force: true });
- });
-
- it('fails replay closed when host process provenance is unavailable', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- callTool: vi.fn(async () => ({ ok: true })),
- };
- const root = await makeWorkingDir();
- await writeTrajectory(root, [
- { tool: 'click', arguments: { pid: 707, window_id: 7, x: 10, y: 20 } },
- ]);
- const h = await makeHarness(
- deps,
- {
- getSessionContext: () => ({
- agentKind: 'claude-code',
- workingDir: root,
- }),
- },
- { injectDefaultProcessResolver: false },
- );
-
- const result = await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'replay_trajectory',
- args: { dir: 'rec', delay_ms: 0, stop_on_error: false },
- },
- });
-
- expect(textPayload(result)).toMatchObject({
- ok: false,
- errorCode: 'TARGET_PROVENANCE_UNAVAILABLE',
- });
- expect(result.isError).toBe(true);
- expect(deps.callTool).not.toHaveBeenCalled();
+ expect(callTool).not.toHaveBeenCalledWith('launch_app', expect.anything());
await h.cleanup();
await fs.rm(root, { recursive: true, force: true });
});
@@ -1555,7 +1182,6 @@ describe('createComputerMcpServer', () => {
it('rejects trajectories whose aggregate action files exceed the memory budget', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Code' })),
callTool: vi.fn(async () => ({ ok: true })),
};
const root = await makeWorkingDir();
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index e490e80246..b6952a8045 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -26,7 +26,6 @@ export interface ComputerMcpServerOptions {
const DESCRIPTION_LIST =
'Discover local desktop computer-use tools. These tools operate on the user desktop through the installed driver. ' +
- "For iOS work, cindy_ios_simulator is the default embedded-simulator route; use this server for macOS Simulator.app only after the user explicitly requests an external window. " +
'Use read-only status/get_accessibility_tree/list_apps/list_windows/get_window_state before click/type_text/press_key/hotkey.';
const DESCRIPTION_CALL =
@@ -89,19 +88,6 @@ const ELEMENT_INDEX_ACTION_TOOLS = new Set<ComputerMcpToolName>([
'scroll',
]);
-/** Actions that can change a target app after resolving its model-supplied PID. */
-const TARGETED_MUTATING_TOOLS = new Set<ComputerMcpToolName>([
- 'click',
- 'double_click',
- 'right_click',
- 'drag',
- 'type_text',
- 'set_value',
- 'press_key',
- 'hotkey',
- 'scroll',
-]);
-
const MAX_REPLAY_TURNS = 1_000;
const MAX_REPLAY_DIRECTORY_ENTRIES = 10_000;
const MAX_REPLAY_ACTION_BYTES = 256 * 1024;
@@ -123,7 +109,6 @@ interface ReplayTrajectoryAction {
}
interface ComputerDispatchOptions {
- forceFreshProcessIdentity?: boolean;
pathWorkingDirOverride?: string;
}
@@ -305,7 +290,7 @@ export function createComputerMcpServer(
inputSchema: z.toJSONSchema(z.object(tool.inputShape).strict()),
})),
workflow:
- 'Start with status and check_permissions. For iOS work, use cindy_ios_simulator first; this server may inspect the external Xcode/Simulator desktop UI read-only, but mutating external iOS workflows are not available until Cindy has a host-issued authorization flow. Otherwise use get_accessibility_tree/list_windows, optionally narrow list_windows with query/workspace_root/process_name (for example, {"process_name":"Simulator"}), inspect a target with get_window_state, perform one action, and call get_window_state again to verify. Targeted actions such as click/type_text require pid; include window_id whenever the target window is known, and always for coordinates. Use get_window_state with {"capture_mode":"vision"} for screenshots and normally omit screenshot_out_file. Element indices are only valid for the latest snapshot of the same pid/window_id: pass the snapshot_id from get_window_state along with element_index, and re-observe when an action is rejected with STALE_SNAPSHOT. Use start_recording/stop_recording/replay_trajectory only when the user explicitly asks for recording or replay.',
+ 'Start with status and check_permissions. Use get_accessibility_tree/list_windows, optionally narrow list_windows with query/workspace_root/process_name (for example, {"process_name":"Simulator"}), inspect a target with get_window_state, perform one action, and call get_window_state again to verify. Targeted actions such as click/type_text require pid; include window_id whenever the target window is known, and always for coordinates. Use get_window_state with {"capture_mode":"vision"} for screenshots and normally omit screenshot_out_file. Element indices are only valid for the latest snapshot of the same pid/window_id: pass the snapshot_id from get_window_state along with element_index, and re-observe when an action is rejected with STALE_SNAPSHOT. Use start_recording/stop_recording/replay_trajectory only when the user explicitly asks for recording or replay.',
}),
);
@@ -370,13 +355,6 @@ export function createComputerMcpServer(
return replayTrajectoryWithGuards(parsedData, signal);
}
- const externalIosGuard = await guardExternalIosDesktopWorkflow(
- name as ComputerMcpToolName,
- parsedData,
- dispatchOptions?.forceFreshProcessIdentity === true,
- );
- if (externalIosGuard) return externalIosGuard;
-
// 快照代际护栏:element_index 指向"某次 get_window_state 的第几项",观察和
// 动作之间 UI 树变化时会静默作用到错误元素。带 snapshot_id 的动作在此校验
// 它是否仍是目标窗口最新观察;不带的放行(过渡兼容)但打遥测日志。
@@ -417,75 +395,6 @@ export function createComputerMcpServer(
}
}
- /**
- * Cindy's embedded simulator is the default iOS route. This guard uses
- * host-resolved PID provenance so the model cannot relabel Xcode/Simulator
- * and then drive Run/click/hotkey through generic desktop automation.
- */
- async function guardExternalIosDesktopWorkflow(
- name: ComputerMcpToolName,
- parsedData: Record<string, unknown>,
- forceFreshProcessIdentity = false,
- ) {
- if (name === 'launch_app') {
- const target = classifyExternalIosTarget({
- name: parsedData.name,
- bundleId: parsedData.bundle_id,
- executable: parsedData.name,
- });
- if (target === 'simulator') {
- return embeddedIosSimulatorPreferredResult('Simulator.app');
- }
- if (target === 'xcode') {
- return embeddedIosSimulatorPreferredResult('Xcode');
- }
- return null;
- }
-
- if (
- !TARGETED_MUTATING_TOOLS.has(name) ||
- typeof parsedData.pid !== 'number'
- ) {
- return null;
- }
- return guardMutatingProcessTarget(parsedData.pid, name, forceFreshProcessIdentity);
- }
-
- async function guardMutatingProcessTarget(
- pid: number,
- tool: ComputerMcpToolName,
- forceFreshProcessIdentity = false,
- ) {
- if (!deps.resolveProcessIdentity) return targetProvenanceUnavailableResult();
-
- let identity;
- try {
- identity = forceFreshProcessIdentity
- ? await deps.resolveProcessIdentity(pid, { forceFresh: true })
- : await deps.resolveProcessIdentity(pid);
- } catch (err) {
- deps.logger?.warn('failed to resolve Computer Use target process for iOS routing guard', {
- pid,
- tool,
- error: err instanceof Error ? err.message : String(err),
- });
- return targetProvenanceUnavailableResult();
- }
- if (
- !identity ||
- identity.pid !== pid ||
- ![identity.name, identity.command, identity.executable, identity.bundleId].some(
- (value) => typeof value === 'string' && value.trim().length > 0,
- )
- ) {
- return targetProvenanceUnavailableResult();
- }
- const target = classifyExternalIosTarget(identity);
- if (!target) return null;
-
- return embeddedIosSimulatorPreferredResult(target === 'xcode' ? 'Xcode' : 'Simulator.app');
- }
-
function trajectoryValidationFailedResult(message: string, turn?: string) {
return textResult(
{
@@ -756,8 +665,6 @@ export function createComputerMcpServer(
const args = parsed.data as Record<string, unknown>;
const nestedPathError = await guardPathArgs(toolName, args, workingRoot);
if (nestedPathError) return { error: nestedPathError };
- const externalIosGuard = await guardExternalIosDesktopWorkflow(toolName, args);
- if (externalIosGuard) return { error: externalIosGuard };
actions.push({ turn, tool: toolName, args });
} catch (error) {
if (signal?.aborted) return { error: replayCancelledResult() };
@@ -871,7 +778,6 @@ export function createComputerMcpServer(
// This closes both PID-reuse and mutable-action-file races that a single
// preflight followed by the driver's nested replay would leave open.
const result = await handleCallTool(action.tool, action.args, signal, {
- forceFreshProcessIdentity: true,
// Preflight normalized nested path arguments against this canonical
// root. Reuse it so a symlink spelling of the session workingDir does
// not make those immutable absolute paths look lexically out of scope.
@@ -926,65 +832,6 @@ export function createComputerMcpServer(
});
}
- function classifyExternalIosTarget(input: {
- name?: unknown;
- bundleId?: unknown;
- command?: unknown;
- executable?: unknown;
- }): 'xcode' | 'simulator' | null {
- const name = typeof input.name === 'string' ? input.name.trim().toLowerCase() : '';
- const bundleId = typeof input.bundleId === 'string' ? input.bundleId.trim().toLowerCase() : '';
- const command = typeof input.command === 'string' ? input.command.trim().toLowerCase() : '';
- const executable = typeof input.executable === 'string' ? input.executable.trim().toLowerCase() : '';
- const provenance = [name, command, executable].filter(Boolean).join(' ');
- const nameBasename = name.replace(/\\/g, '/').split('/').at(-1) ?? '';
-
- if (
- bundleId === 'com.apple.iphonesimulator' ||
- /(^|[\s/])simulator(?:\.app)?(?:[\s/]|$)/.test(provenance)
- ) {
- return 'simulator';
- }
- if (
- bundleId === 'com.apple.dt.xcode' ||
- /^xcode(?:[-_.][a-z0-9][a-z0-9._-]*)?(?:\.app)?$/i.test(nameBasename) ||
- /(^|[\s/])xcode(?:\.app)?(?:[\s/]|$)/.test(provenance)
- ) {
- return 'xcode';
- }
- return null;
- }
-
- function embeddedIosSimulatorPreferredResult(target: 'Xcode' | 'Simulator.app') {
- return textResult(
- {
- ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
- data: {
- message:
- `Use cindy_ios_simulator for Cindy's embedded viewer. External ${target} automation is unavailable until Cindy can issue an explicit host authorization.`,
- next_tool: 'cindy_ios_simulator',
- blocked_target: target,
- },
- },
- true,
- );
- }
-
- function targetProvenanceUnavailableResult() {
- return textResult(
- {
- ok: false,
- errorCode: 'TARGET_PROVENANCE_UNAVAILABLE',
- data: {
- message:
- 'Cindy could not verify the target process identity, so this mutating desktop action was blocked. Refresh the target window and try again.',
- },
- },
- true,
- );
- }
-
/**
* 把工具入参里的本地文件路径约束到 session workingDir。返回 null 放行(路径
* 已被替换为约束后的绝对路径),返回结果对象表示以 PATH_NOT_ALLOWED 拒绝。
diff --git a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
index f8e04b4678..e9daac651e 100644
--- a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
+++ b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
@@ -23,14 +23,7 @@ function makeLogger(): LiziMcpLogger & { warn: ReturnType<typeof vi.fn> } {
}
async function makeHarness(deps: ComputerMcpDeps, options?: Parameters<typeof createComputerMcpServer>[1]) {
- const server = createComputerMcpServer(
- {
- ...deps,
- resolveProcessIdentity:
- deps.resolveProcessIdentity ?? (async (pid) => ({ pid, name: 'Code' })),
- },
- options,
- );
+ const server = createComputerMcpServer(deps, options);
const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'snapshot-test-client', version: '0.0.0' });
await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
diff --git a/packages/lizi-mcps/src/computer/tools.ts b/packages/lizi-mcps/src/computer/tools.ts
index a0a03883ce..40ebfbe605 100644
--- a/packages/lizi-mcps/src/computer/tools.ts
+++ b/packages/lizi-mcps/src/computer/tools.ts
@@ -46,7 +46,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
{
name: 'launch_app',
description:
- 'Launch or locate a desktop application without stealing focus. Prefer this over shell open/Start-Process for GUI apps. For iOS work, use cindy_ios_simulator for Cindy\'s embedded viewer; launching Xcode or macOS Simulator.app is unavailable until Cindy can issue an explicit host authorization. Use list_windows with {"process_name":"Simulator"} for read-only external Simulator window discovery.',
+ 'Launch or locate an application without stealing focus. Prefer this over shell open/Start-Process for GUI apps. If an already-running app such as Simulator is not discoverable here, use list_windows with {"process_name":"Simulator"}.',
inputShape: {
name: z.string().optional(),
bundle_id: z.string().optional(),
@@ -66,7 +66,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
{
name: 'list_windows',
description:
- 'List known top-level desktop windows. Use only for external desktop UI work; Cindy iOS app work should use cindy_ios_simulator and its embedded viewer. For an explicitly requested external Simulator.app window, filter with {"process_name":"Simulator"}. Hosts may enrich results with process provenance and generic identity hints.',
+ 'List known top-level windows. Use before choosing a target window; for example, {"process_name":"Simulator"}. Hosts may enrich results with process provenance and generic identity hints.',
readOnly: true,
inputShape: {
on_screen_only: z.boolean().optional(),
diff --git a/packages/lizi-mcps/src/ios-simulator/server.ts b/packages/lizi-mcps/src/ios-simulator/server.ts
index daa9b68b7c..8196af0c50 100644
--- a/packages/lizi-mcps/src/ios-simulator/server.ts
+++ b/packages/lizi-mcps/src/ios-simulator/server.ts
@@ -56,7 +56,7 @@ export function createIOSSimulatorMcpServer(
server.tool(
"list_tools",
- "Discover Cindy's embedded iOS Simulator tools. This is the preferred entry point for opening, running, testing, or debugging an iOS app in Cindy. Everything behind it acts on a simulated Apple device: never use it to browse the web, fetch HTTP data, or automate this Mac — use the browser, fetch, or computer tools for those. Do not use cindy_computer to launch macOS Simulator.app unless the user explicitly requests an external system window. Start with check_environment before selecting a device.",
+ "Discover Cindy's embedded iOS Simulator tools. Use this entry point when the embedded route is selected for opening, running, testing, or debugging an iOS app in Cindy. Everything behind it acts on a simulated Apple device: never use it to browse the web, fetch HTTP data, or automate this Mac — use the browser, fetch, or computer tools for those. Start with check_environment before selecting a device.",
{ category: z.enum(["ios_simulator"]).optional() },
async () => {
const availability = await deps.describeTools?.(readContext(options));
diff --git a/packages/lizi-mcps/src/ios-simulator/tools.ts b/packages/lizi-mcps/src/ios-simulator/tools.ts
index c0165d1120..6b95064fe3 100644
--- a/packages/lizi-mcps/src/ios-simulator/tools.ts
+++ b/packages/lizi-mcps/src/ios-simulator/tools.ts
@@ -207,7 +207,7 @@ export function registerIOSSimulatorTools(
register({
name: "attach_device",
description:
- "Attach one exact simulator UDID to the current Cindy embedded-simulator session. Resource admission is enforced by the host; do not open Simulator.app.",
+ "Attach one exact simulator UDID to the current Cindy embedded-simulator session. Resource admission is enforced by the host; this operation does not open Simulator.app.",
inputShape: { udid: z.string().uuid() },
handler: async (args) =>
callHost(deps, "attach_device", args, getContext?.()),
@@ -247,7 +247,7 @@ export function registerIOSSimulatorTools(
register({
name: "start_instance",
description:
- "Boot the exact simulator attached to this Cindy embedded-simulator session and invalidate stale generations. Keep the device in Cindy's viewer rather than opening Simulator.app.",
+ "Boot the exact simulator attached to this Cindy embedded-simulator session, invalidate stale generations, and display it in Cindy's viewer without opening Simulator.app.",
inputShape: routeShape,
handler: async (args) =>
callHost(deps, "start_instance", args, getContext?.()),
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index bad4a95135..24b85aa9a1 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -596,26 +596,8 @@ export interface ComputerMcpCallContext {
agentKind?: string;
}
-export interface ComputerProcessIdentity {
- pid: number;
- name?: string;
- command?: string;
- executable?: string;
- bundleId?: string;
-}
-
-export interface ComputerProcessIdentityResolveOptions {
- /** Bypass any host-side process snapshot cache before a side effect. */
- forceFresh?: boolean;
-}
-
export interface ComputerMcpDeps {
getStatus(): Promise<ComputerDriverStatus>;
- /** Resolve process provenance without trusting model-supplied app labels. */
- resolveProcessIdentity?(
- pid: number,
- options?: ComputerProcessIdentityResolveOptions,
- ): Promise<ComputerProcessIdentity | null>;
callTool(
name: ComputerMcpToolName,
args: Record<string, unknown>,