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): 让 Windows 回执恢复清点在预算内完成

xuzini-xzna99e909a4e14
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 7f34618782..944cdf4af1 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -144,6 +144,9 @@ const noopLogger: Logger = {
// Durable approval assertions allow 3s for the 500ms poll and asynchronous delivery.
// The default 1s wait races the second poll on loaded CI runners; permission assertions stay exact.
// The same durable store feeds streaming foreground discovery and detached lease inspection.
+// The default 5s test timeout can abort that 3s wait on a loaded Windows runner
+// before Vitest reports the assertion (observed 5157ms, no assertion).
+if (process.platform === 'win32') vi.setConfig({ testTimeout: 20_000, hookTimeout: 20_000 });
function mockRunDiscovery() {
const list = vi.spyOn(piSubagentRuns, 'listPiSubagentRuns');
vi.spyOn(piSubagentRuns, 'scanPiSubagentRuns').mockImplementation(async function* (root) {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
index 4149db1dfd..de25fbe4d3 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
@@ -1514,6 +1514,23 @@ describe('PI durable subagent run store', () => {
await expect(stopAllPiSubagentRunsForExit(agentHome, 0)).resolves.toBe(true);
});
+ it('treats a finished Windows inventory with no command lines as absence', async () => {
+ usePlatform('win32');
+ const { root } = await terminalReceiptHome(async () => {});
+ // Empty stdout is still an unknown probe. A completed report with zero
+ // readable processes is the case where every user process has exited.
+ childProcess.spawnSync.mockImplementation(() => ({
+ status: 0,
+ stdout: JSON.stringify({ complete: true, count: 0, commands: [] }),
+ }));
+ await expect(stopPiSubagentRunsForAccountBoundary(root, { timeoutMs: 0 })).resolves.toBe(true);
+ childProcess.spawnSync.mockImplementation(() => ({
+ status: 0,
+ stdout: JSON.stringify({ complete: false, count: 0, commands: [] }),
+ }));
+ await expect(stopPiSubagentRunsForAccountBoundary(root, { timeoutMs: 0 })).resolves.toBe(false);
+ });
+
it.each([
...cases,
['contains zero bytes', async (dir: string) => writeFile(path.join(dir, 'status.json'), Buffer.alloc(72_506))],
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 976fd4c7ef..ce5be58bc6 100644
--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
@@ -3135,13 +3135,20 @@ async function terminalResultProcessIdentities(
/**
* Inventory only for receipt recovery; never a source of PIDs to signal.
- * Empty/failed/truncated probes are unknown, not proof of absence. Windows can
- * 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, 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.
+ * Empty stdout, a failed probe, or `complete: false` are unknown, not proof of
+ * absence. A finished Windows probe may return no command lines: that means
+ * the current user had no process left to read, which is absence.
+ * Windows can 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, 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.
+ *
+ * The Windows probe has to finish inside the kill budget. Enumerating every
+ * Win32_Process property, plus compiling a protection helper before checking
+ * which PIDs are still alive, exceeded that budget on hosted runners (8238ms
+ * against an 8000ms cap) and failed a dead child closed.
*/
async function readRecoveryProcessInventory(deadline: number): Promise<string[] | null> {
try {
@@ -3155,42 +3162,82 @@ async function readRecoveryProcessInventory(deadline: number): Promise<string[]
// own probe PID so that its expected exit cannot block every recovery.
'$probe = [System.Diagnostics.Process]::new()',
'$probe.StartInfo.FileName = "$env:SystemRoot\\System32\\tasklist.exe"',
- '$probe.StartInfo.Arguments = \'/V /FO CSV /NH /FI "USERNAME eq \' + $user + \'"\'',
+ // /V adds a window title per process and is not needed for the user
+ // filter. PID and image name are the only columns this probe reads.
+ '$probe.StartInfo.Arguments = \'/FO CSV /NH /FI "USERNAME eq \' + $user + \'"\'',
'$probe.StartInfo.UseShellExecute = $false',
'$probe.StartInfo.CreateNoWindow = $true',
'$probe.StartInfo.RedirectStandardOutput = $true',
+ '$probe.StartInfo.RedirectStandardError = $true',
'if (-not $probe.Start()) { throw "tasklist did not start" }',
'$probeId = $probe.Id',
+ // Drain both pipes before WaitForExit. Reading only stdout while stderr
+ // fills its pipe deadlocks until the outer timeout kills the probe.
'$csv = $probe.StandardOutput.ReadToEnd()',
+ '$null = $probe.StandardError.ReadToEnd()',
'$probe.WaitForExit()',
'$probeExitCode = $probe.ExitCode',
'$probe.Dispose()',
'if ($probeExitCode -ne 0) { throw "tasklist failed" }',
- '$owned = @($csv | ConvertFrom-Csv -Header Name,ProcessId,SessionName,SessionNumber,Memory,Status,UserName,CPUTime,WindowTitle)',
+ // Without /V the columns are Image Name, PID, Session Name, Session#, Mem Usage.
+ '$owned = @($csv | ConvertFrom-Csv -Header Name,ProcessId,SessionName,SessionNumber,Memory)',
'$processIds = @{}',
+ '$names = @{}',
'foreach ($row in $owned) {',
' $number = 0',
' if (-not [int]::TryParse($row.ProcessId, [ref]$number) -or $number -le 0) { throw "invalid process inventory" }',
' if ($number -eq $probeId) { continue }',
' $processIds[$number] = $true',
+ ' $name = [string]$row.Name',
+ ' if (-not [string]::IsNullOrWhiteSpace($name)) { $names[$name] = $true }',
'}',
'$count = $processIds.Count',
'$commands = [System.Collections.Generic.List[string]]::new()',
'$complete = $true',
- '$items = @(Get-CimInstance Win32_Process -ErrorAction Stop)',
- 'foreach ($item in $items) {',
- ' $number = [int]$item.ProcessId',
- ' if (-not $processIds.ContainsKey($number)) { continue }',
- ' if ([string]::IsNullOrWhiteSpace($item.CommandLine)) { continue }',
- ' $commands.Add($item.CommandLine)',
- ' $processIds.Remove($number)',
+ 'if ($names.Count -gt 0) {',
+ // A short name filter uses the indexed Name column. A long OR list can
+ // be rejected by WQL; fall back to the same two fields without a filter
+ // rather than failing the whole probe closed.
+ ' $items = $null',
+ ' if ($names.Count -le 32) {',
+ ' try {',
+ ' $clauses = @(foreach ($name in @($names.Keys)) { "Name=\'" + ($name -replace "\'", "\'\'" ) + "\'" })',
+ ' $filter = $clauses -join \' OR \'',
+ ' $items = @(Get-CimInstance -ClassName Win32_Process -Property ProcessId,CommandLine -Filter $filter -ErrorAction Stop)',
+ ' } catch { $items = $null }',
+ ' }',
+ ' if ($null -eq $items) {',
+ ' $items = @(Get-CimInstance -ClassName Win32_Process -Property ProcessId,CommandLine -ErrorAction Stop)',
+ ' }',
+ ' foreach ($item in $items) {',
+ ' $number = [int]$item.ProcessId',
+ ' if (-not $processIds.ContainsKey($number)) { continue }',
+ ' if ([string]::IsNullOrWhiteSpace($item.CommandLine)) { continue }',
+ ' $commands.Add($item.CommandLine)',
+ ' $processIds.Remove($number)',
+ ' }',
+ '}',
+ // Confirm exits before compiling the protection helper. csc.exe is
+ // another multi-second startup, and PIDs that have already vanished
+ // do not need it.
+ '$stillLive = New-Object System.Collections.Generic.List[int]',
+ 'foreach ($number in @($processIds.Keys)) {',
+ ' $unreadable = $null',
+ ' try {',
+ ' $unreadable = [System.Diagnostics.Process]::GetProcessById($number)',
+ ' if ($unreadable.HasExited) { $count-- } else { [void]$stillLive.Add($number) }',
+ ' } catch [System.ArgumentException] {',
+ ' $count--',
+ ' } finally {',
+ ' if ($null -ne $unreadable) { $unreadable.Dispose() }',
+ ' }',
'}',
// 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) {',
+ 'if ($stillLive.Count -gt 0) {',
"Add-Type -TypeDefinition @'",
'using System;',
'using System.Runtime.InteropServices;',
@@ -3211,32 +3258,30 @@ async function readRecoveryProcessInventory(deadline: number): Promise<string[]
' }',
'}',
"'@",
- '}',
- // Other short-lived processes can exit between tasklist and CIM too.
- // Missing command lines alone are not exit evidence; independently
- // 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 -or [CindyRecoveryProcessProtection]::IsAntimalware($number)) { $count-- } else { $complete = $false }',
- ' } catch [System.ArgumentException] {',
- ' $count--',
- ' } finally {',
- ' if ($null -ne $unreadable) { $unreadable.Dispose() }',
+ // Exits were already retired above. Only a still-live PID remains, and
+ // only OS-confirmed antimalware may be dropped without a command line.
+ ' foreach ($number in $stillLive) {',
+ ' if ([CindyRecoveryProcessProtection]::IsAntimalware([uint32]$number)) { $count-- } else { $complete = $false }',
' }',
'}',
- '@{ complete = $complete; commands = @($commands.ToArray()); count = $count } | ConvertTo-Json -Compress',
+ // ConvertTo-Json unwraps a one-element array and can emit null for an
+ // empty one. Build the array explicitly so a finished probe stays JSON.
+ '$encoded = @(foreach ($command in $commands) { ConvertTo-Json -InputObject $command -Compress })',
+ '$commandJson = \'[\' + ($encoded -join \',\') + \']\'',
+ '$completeJson = if ($complete) { \'true\' } else { \'false\' }',
+ '\'{"complete":\' + $completeJson + \',"count":\' + $count + \',"commands":\' + $commandJson + \'}\'',
].join('\n');
const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
encoding: 'utf8', timeout: Math.min(DEFAULT_KILL_BUDGET_MS, remaining), maxBuffer: 4 * 1024 * 1024, windowsHide: true,
});
const value = JSON.parse(stdout);
- if (value?.complete !== true || !Number.isSafeInteger(value.count) || value.count <= 0
- || !Array.isArray(value.commands) || value.commands.length !== value.count
- || value.commands.some((command: unknown) => typeof command !== 'string' || !command.trim())) return null;
- return value.commands;
+ const commands = Array.isArray(value?.commands)
+ ? value.commands
+ : value?.count === 0 && value?.commands == null ? [] : null;
+ if (value?.complete !== true || !Number.isSafeInteger(value.count) || value.count < 0
+ || !Array.isArray(commands) || commands.length !== value.count
+ || commands.some((command: unknown) => typeof command !== 'string' || !command.trim())) return null;
+ return commands;
}
const uid = process.geteuid?.();
if (!Number.isSafeInteger(uid)) return null;