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(pi): distinguish protected antimalware from unreadable runtimes

Chris9b02f14011e1
diff --git a/docs/research/pi-subagent-delegation.md b/docs/research/pi-subagent-delegation.md
index 77964a1563..e6914b438c 100644
--- a/docs/research/pi-subagent-delegation.md
+++ b/docs/research/pi-subagent-delegation.md
@@ -24,8 +24,13 @@ parentSessionId、runDir 和全部 child/session/agent 身份,并确认所有
包括 runner 已退出但子进程仍存活的情况。清单查询失败、超时、截断,或无法确认本账号
进程可见性时保留未知;Windows 使用系统的当前用户过滤取得 PID 集合,再逐项核验 CIM
命令行;若进程在两次查询之间消失或命令行不可读,必须再由 OS 独立确认该 PID 已退出。
-仍存活但不可读或存活查询失败都不放行,不把其他账号的受保护系统进程混入当前账号证明。
-仅排除本次启动的 `tasklist` 查询进程自身 PID,避免它正常退出后使清单永久不完整。
+仍存活但不可读或存活查询失败通常不放行。唯一系统角色例外是通过只读
+`GetProcessInformation(ProcessProtectionLevelInfo)` 确认的 `ANTIMALWARE_LIGHT` 进程:
+其代码完整性由 Windows 强制约束,不是 Cindy 启动的普通 Node/Electron/Pi 进程。
+不按 `DefenderSessionHelper.exe` 等文件名豁免;无保护、第三方 `PPL_APP`、未知级别或查询失败仍拒绝。
+该判据遵循 [Windows 保护进程合同](https://learn.microsoft.com/en-us/windows/win32/services/protecting-anti-malware-services-);
+查询只申请 `PROCESS_QUERY_LIMITED_INFORMATION`,随后关闭句柄。
+另排除本次启动的 `tasklist` 查询进程自身 PID,避免它正常退出后使清单永久不完整。
查询是只读核验,不向清单里的 PID 发信号。先读取本轮所有 parent-session root 的候选回执,
再共享一次清单查询,避免历史 root 逐个查询耗尽总回收预算;下次扫描或升级终止阶段重新读取。
续跑使用新 run UUID;复用 native session ID 的活跃子进程仍保守视为未结束。
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
index 50e50f6bb9..821665fe3e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
@@ -8,43 +8,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { CINDY_SUBAGENT_RUNNER_SOURCE } from '../cindy-subagent-runner-source.js';
-// Keep the Windows integration query real. A false boundary result alone hid
-// the reason for #6733's Windows failure; retain only counts, image names and
-// PowerShell error identifiers, never process command lines or tasklist rows.
-const inventoryEvidence = vi.hoisted(() => ({ runId: '', probes: [] as unknown[] }));
-vi.mock('node:child_process', async (importOriginal) => {
- const actual = await importOriginal<typeof import('node:child_process')>();
- const { promisify } = await import('node:util');
- const execute = promisify(actual.execFile);
- const execFile = Object.assign(actual.execFile.bind(actual), {
- [promisify.custom]: async (file: string, args: readonly string[], options: import('node:child_process').ExecFileOptionsWithStringEncoding) => {
- const script = args.at(-1) ?? '';
- if (file !== 'powershell.exe' || !script.includes('$processIds = @{}')) return execute(file, args, options);
- const diagnosticScript = 'trap { [Console]::Error.WriteLine("InventoryProbeError:" + $_.FullyQualifiedErrorId + ":line=" + $_.InvocationInfo.ScriptLineNumber); exit 1 }\n'
- + script.replace('@{ complete = $complete;', '@{ unreadableNames = @($items | Where-Object { $processIds.ContainsKey([int]$_.ProcessId) } | ForEach-Object { $_.Name }); complete = $complete;');
- try {
- const result = await execute(file, [...args.slice(0, -1), diagnosticScript], options);
- try {
- const value = JSON.parse(result.stdout);
- inventoryEvidence.probes.push({
- complete: value.complete, count: value.count,
- commandCount: value.commands?.length,
- matchingCommands: value.commands?.filter((command: string) => command.includes(inventoryEvidence.runId)).length,
- unreadableNames: value.unreadableNames,
- });
- } catch { inventoryEvidence.probes.push({ invalidJson: true, bytes: result.stdout.length }); }
- return result;
- } catch (error) {
- const failure = error as { code?: string | number; killed?: boolean; stderr?: string };
- inventoryEvidence.probes.push({ code: failure.code, killed: failure.killed,
- reason: failure.stderr?.match(/InventoryProbeError:[^\r\n]*/)?.[0] });
- throw error;
- }
- },
- });
- return { ...actual, execFile };
-});
-
/**
* Every case here spawns a real runner process (and that runner spawns a fake
* pi per child). Vitest's 5s default is a Linux-shaped budget: on the Windows
@@ -660,14 +623,11 @@ describe('Cindy durable PI Subagent runner', () => {
// that the independent artifact has the identity required by recovery.
it('recovers account teardown from a real terminal receipt after status corruption', async () => {
const fixture = await makeFixture();
- inventoryEvidence.runId = path.basename(fixture.runDir);
- inventoryEvidence.probes.length = 0;
await waitForClose(fixture.child, fixture.stderr);
const files = ['result.json', 'transcript.jsonl', 'config.json'];
const before = await Promise.all(files.map(file => readFile(path.join(fixture.runDir, file))));
await writeFile(path.join(fixture.runDir, 'status.json'), Buffer.alloc(72_506));
- const recovered = await stopForAccountBoundary(fixture.root, { timeoutMs: 0 });
- expect(recovered, JSON.stringify(inventoryEvidence.probes)).toBe(true);
+ await expect(stopForAccountBoundary(fixture.root, { timeoutMs: 0 })).resolves.toBe(true);
expect(await Promise.all(files.map(file => readFile(path.join(fixture.runDir, file)))))
.toEqual(before);
});
diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
index e29541f483..976fd4c7ef 100644
--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
@@ -3139,8 +3139,9 @@ async function terminalResultProcessIdentities(
* omit command lines for protected processes in other accounts. Use the OS
* user filter first (tasklist /FI USERNAME, like POSIX ps -u), then require a
* readable command line or independent exit confirmation for every selected
- * PID. An inaccessible live process keeps recovery closed; PID discovery never
- * authorizes a kill.
+ * PID, except OS-confirmed antimalware PPL processes (which cannot be our
+ * ordinary Node/Electron/Pi runtimes). Other inaccessible live processes keep
+ * recovery closed; PID discovery never authorizes a kill.
*/
async function readRecoveryProcessInventory(deadline: number): Promise<string[] | null> {
try {
@@ -3184,14 +3185,42 @@ async function readRecoveryProcessInventory(deadline: number): Promise<string[]
' $commands.Add($item.CommandLine)',
' $processIds.Remove($number)',
'}',
+ // DefenderSessionHelper can belong to this user but hide its command
+ // line. Never exempt an image name: query the OS protection level with
+ // minimum read-only rights. Only ANTIMALWARE_LIGHT is excluded; NONE,
+ // third-party PPL_APP, unknown levels and query failures remain unknown.
+ // https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocessinformation
+ 'if ($processIds.Count -gt 0) {',
+ "Add-Type -TypeDefinition @'",
+ 'using System;',
+ 'using System.Runtime.InteropServices;',
+ 'public static class CindyRecoveryProcessProtection {',
+ ' [DllImport("kernel32.dll", SetLastError = true)]',
+ ' private static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);',
+ ' [DllImport("kernel32.dll", SetLastError = true)]',
+ ' private static extern bool GetProcessInformation(IntPtr handle, int kind, out uint level, uint size);',
+ ' [DllImport("kernel32.dll")]',
+ ' private static extern bool CloseHandle(IntPtr handle);',
+ ' public static bool IsAntimalware(uint pid) {',
+ ' IntPtr handle = OpenProcess(0x1000, false, pid); // PROCESS_QUERY_LIMITED_INFORMATION',
+ ' if (handle == IntPtr.Zero) return false;',
+ ' try {',
+ ' uint level;',
+ ' return GetProcessInformation(handle, 7, out level, 4) && level == 3; // ProcessProtectionLevelInfo / ANTIMALWARE_LIGHT',
+ ' } finally { CloseHandle(handle); }',
+ ' }',
+ '}',
+ "'@",
+ '}',
// Other short-lived processes can exit between tasklist and CIM too.
// Missing command lines alone are not exit evidence; independently
- // check each remaining PID. Only an exited process can leave the count.
+ // check each remaining PID. Retire only confirmed exits or the OS
+ // antimalware role above, never an arbitrary unreadable live process.
'foreach ($number in @($processIds.Keys)) {',
' $unreadable = $null',
' try {',
' $unreadable = [System.Diagnostics.Process]::GetProcessById($number)',
- ' if ($unreadable.HasExited) { $count-- } else { $complete = $false }',
+ ' if ($unreadable.HasExited -or [CindyRecoveryProcessProtection]::IsAntimalware($number)) { $count-- } else { $complete = $false }',
' } catch [System.ArgumentException] {',
' $count--',
' } finally {',