Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Windows support for managed agents and the controller (CHOO-3472) (#765)

Louis Amaudruz69c97e686b88
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml
index 3b03b4ba2..06e3c87af 100644
--- a/.github/workflows/pr-ci.yml
+++ b/.github/workflows/pr-ci.yml
@@ -226,6 +226,57 @@ jobs:
- name: Test (vitest)
run: pnpm -r run test
+ # The agent runner and the controller on native Windows (CHOO-3472): process
+ # control, CLI lookup and permissions there take different code paths, and
+ # their tests that start real processes only run on Windows. Scoped to the
+ # packages on that path; the rest of the desktop app's suite assumes POSIX.
+ console-windows:
+ name: Switch Console (Windows)
+ needs: changes
+ if: ${{ needs.changes.outputs.console == 'true' || github.event_name == 'push' || github.event_name == 'workflow_dispatch' }}
+ runs-on: windows-latest
+ defaults:
+ run:
+ shell: bash
+ working-directory: console
+ steps:
+ - name: Checkout
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+
+ - name: Set up pnpm
+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4
+ with:
+ version: 11.5.3
+
+ - name: Set up Node
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version-file: console/.nvmrc
+ cache: pnpm
+ cache-dependency-path: console/pnpm-lock.yaml
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Build workspace packages
+ run: pnpm -r --filter './packages/**' run build
+
+ # Each suite runs whatever the one before it did, so one run shows every failure.
+ - name: Test shared
+ run: pnpm --filter @switch-console/shared run test
+
+ - name: Test agent-providers
+ if: ${{ !cancelled() }}
+ run: pnpm --filter @switch-console/agent-providers run test
+
+ - name: Test agent-controller
+ if: ${{ !cancelled() }}
+ run: pnpm --filter @switch-console/agent-controller run test
+
+ - name: Test Console's embedded controller and Windows launching
+ if: ${{ !cancelled() }}
+ run: pnpm --filter @switch-console/desktop exec vitest run --project node src/main/core/embedded-controller src/main/core/execution-context
+
artifacts:
name: Artifact registry
# Every artifact carries a compiled-in copy of artifacts.yaml, so the copies
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.test.ts
index 99d39da15..ca2df51c8 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.test.ts
@@ -45,7 +45,8 @@ describe('EnrollmentFile', () => {
file.set('server-2', { kind: 'removed', controllerId: 'c-2', at: '2026-01-02T00:00:00Z' }),
]);
expect(Object.keys(await file.all()).sort()).toEqual(['server-1', 'server-2']);
- expect(statSync(join(dir, 'nested', 'state.json')).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32')
+ expect(statSync(join(dir, 'nested', 'state.json')).mode & 0o777).toBe(0o600);
await file.delete('server-1');
expect(await file.get('server-1')).toBeNull();
expect((await file.get('server-2'))?.kind).toBe('removed');
@@ -59,14 +60,14 @@ describe('EnrollmentFile', () => {
describe('controller data directory', () => {
it('is one directory per server, and refuses an id that could leave it', () => {
- expect(controllerDataDir('/base', 'server-1')).toBe('/base/servers/server-1');
+ expect(controllerDataDir('/base', 'server-1')).toBe(join('/base', 'servers', 'server-1'));
expect(() => controllerDataDir('/base', '../escape')).toThrow(/cannot name a directory/);
expect(defaultWorkspacePath('/home/me/.switch/agents', 'pm-agent')).toBe(
- '/home/me/.switch/agents/pm-agent'
+ join('/home/me/.switch/agents', 'pm-agent')
);
expect(defaultWorkspacePath('/home/me/.switch/agents', '../escape')).toBeNull();
expect(serverWorkspacesDir('/home/me', 'http://localhost:8000')).toBe(
- '/home/me/.switch/agents/localhost-8000'
+ join('/home/me', '.switch', 'agents', 'localhost-8000')
);
expect(defaultWorkspacePath('/home/me/.switch/agents', '')).toBeNull();
});
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.ts
index 08a866126..cdfecb31b 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-files.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
-import { mkdir, open, readdir, readFile, rename, rm } from 'node:fs/promises';
+import { mkdir, open, readdir, readFile, rm } from 'node:fs/promises';
import { dirname, join } from 'node:path';
-import { WATCH_FLAGS_FILE, watchFlagsSchema } from '@switch-console/agent-providers';
+import { replaceFile, WATCH_FLAGS_FILE, watchFlagsSchema } from '@switch-console/agent-providers';
import { z } from 'zod';
/**
@@ -89,7 +89,7 @@ async function writeAtomic(path: string, body: string): Promise<void> {
} finally {
await file.close();
}
- await rename(temporary, path);
+ await replaceFile(temporary, path);
}
/** `state.json`, read whole and written whole; every change goes through one queue. */
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.test.ts
index cab10686e..80226eed1 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.test.ts
@@ -1,3 +1,4 @@
+import { STOP_MESSAGE } from '@switch-console/agent-providers';
import { describe, expect, it } from 'vitest';
import type { EmbeddedControllerPhase } from '@shared/core/embedded-controller/embedded-controller';
import {
@@ -5,7 +6,7 @@ import {
type ControllerLogLevel,
ControllerSupervisor,
} from './controller-supervisor';
-import { fakeSpawn, waitFor } from './test-helpers/fake-controller-child';
+import { fakeSpawn, STOP_REQUEST, waitFor } from './test-helpers/fake-controller-child';
const NOW = Date.parse('2026-01-01T00:00:00Z');
@@ -177,11 +178,27 @@ describe('ControllerSupervisor', () => {
const child = calls[0]!.child;
child.exitsOnSigterm = false;
await supervisor.stop(20);
- expect(child.signals).toEqual(['SIGTERM', 'SIGKILL']);
+ expect(child.signals).toEqual([STOP_REQUEST, 'SIGKILL']);
await new Promise((resolve) => setTimeout(resolve, 30));
expect(calls).toHaveLength(1);
});
+ it('asks over IPC on Windows, where SIGTERM would end it on the spot', async () => {
+ const platform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ try {
+ const { supervisor, calls } = harness();
+ supervisor.start();
+ await waitFor(() => calls.length === 1, 'the spawn');
+ const child = calls[0]!.child;
+ await supervisor.stop(1_000);
+ expect(child.sent).toEqual([STOP_MESSAGE]);
+ expect(child.signals).toHaveLength(1);
+ } finally {
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ }
+ });
+
it('waits for a released controller to exit by itself, and says when it does not', async () => {
const { supervisor, calls } = harness();
supervisor.start();
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.ts
index 80eb8f2b9..36acac04a 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller-supervisor.ts
@@ -1,5 +1,6 @@
import { createInterface } from 'node:readline';
import type { Readable, Writable } from 'node:stream';
+import { STOP_MESSAGE } from '@switch-console/agent-providers';
import type { EmbeddedControllerPhase } from '@shared/core/embedded-controller/embedded-controller';
/** The controller's exit codes (see the agent-controller README). */
@@ -22,6 +23,9 @@ export interface ControllerChild {
readonly stdin: Writable | null;
readonly stdout: Readable | null;
readonly stderr: Readable | null;
+ /** Whether its IPC channel is open: how it is asked to stop on Windows. */
+ readonly connected: boolean;
+ send(message: unknown): boolean;
kill(signal?: NodeJS.Signals): boolean;
once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
once(event: 'error', listener: (error: Error) => void): this;
@@ -30,7 +34,7 @@ export interface ControllerChild {
export type SpawnController = (
command: string,
args: string[],
- options: { env: NodeJS.ProcessEnv; stdio: ['pipe', 'pipe', 'pipe'] }
+ options: { env: NodeJS.ProcessEnv; stdio: ['pipe', 'pipe', 'pipe', 'ipc']; windowsHide: true }
) => ControllerChild;
/** How to start the controller this time: read afresh before every start. */
@@ -117,9 +121,11 @@ export class ControllerSupervisor {
}
/**
- * Stops supervising and asks the process to end (SIGTERM). The agents keep
- * running: the controller leaves its watchers up, and they reconnect when a
- * controller comes back. Escalates to SIGKILL after `timeoutMs`.
+ * Stops supervising and asks the process to end: SIGTERM, or on Windows,
+ * where SIGTERM would end it on the spot, a stop message over its IPC
+ * channel. The agents keep running: the controller leaves its watchers up,
+ * and they reconnect when a controller comes back. Escalates to SIGKILL
+ * after `timeoutMs`.
*/
async stop(timeoutMs: number): Promise<void> {
this.stopping = true;
@@ -127,7 +133,8 @@ export class ControllerSupervisor {
const child = this.child;
const exited = this.exited;
if (!child || !exited) return;
- child.kill('SIGTERM');
+ if (process.platform === 'win32' && child.connected) child.send(STOP_MESSAGE);
+ else child.kill('SIGTERM');
if (await within(exited, timeoutMs)) return;
child.kill('SIGKILL');
await within(exited, 2_000);
@@ -161,7 +168,8 @@ export class ControllerSupervisor {
this.recent = [];
const child = this.deps.spawn(launch.executable, launch.args, {
env: launch.env,
- stdio: ['pipe', 'pipe', 'pipe'],
+ stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
+ windowsHide: true,
});
this.child = child;
let resolveExited!: () => void;
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
index c08b14afa..0b61d597d 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
@@ -26,9 +26,14 @@ import {
type EmbeddedControllerDeps,
EmbeddedControllerService,
type ManagementPort,
- WINDOWS_UNSUPPORTED,
+ unsupportedPlatformReason,
} from './embedded-controller-service';
-import { fakeSpawn, type SpawnCall, waitFor } from './test-helpers/fake-controller-child';
+import {
+ fakeSpawn,
+ type SpawnCall,
+ STOP_REQUEST,
+ waitFor,
+} from './test-helpers/fake-controller-child';
const CREDENTIAL = 'swcc_credential-placeholder-value';
const SERVER = 'server-1';
@@ -346,7 +351,7 @@ describe('EmbeddedControllerService', () => {
const running = await enabled();
leaveControllerState();
await running.disable(SERVER);
- expect(calls[0]!.child.signals).toEqual(['SIGTERM']);
+ expect(calls[0]!.child.signals).toEqual([STOP_REQUEST]);
expect(readFileSync(join(dataDir(), 'watchers', 'agent-1', 'watch.json'), 'utf8')).toBe(
'{"enabled":false,"spawn":false}'
);
@@ -442,13 +447,22 @@ describe('EmbeddedControllerService', () => {
expect(calls).toHaveLength(0);
});
- it('refuses on Windows, where the controller cannot run', async () => {
- const windows = service({ platform: 'win32' });
- await expect(windows.enable(SERVER, WORKSPACE)).rejects.toThrow(WINDOWS_UNSUPPORTED);
- expect((await windows.overview(SERVER, WORKSPACE)).unsupportedReason).toBe(WINDOWS_UNSUPPORTED);
+ it('refuses on a platform the controller does not run on', async () => {
+ const reason = unsupportedPlatformReason('freebsd');
+ expect(reason).toContain('freebsd');
+ const other = service({ platform: 'freebsd' });
+ await expect(other.enable(SERVER, WORKSPACE)).rejects.toThrow(reason!);
+ expect((await other.overview(SERVER, WORKSPACE)).unsupportedReason).toBe(reason);
expect(management.enroll).not.toHaveBeenCalled();
});
+ it('runs on Windows', async () => {
+ expect(unsupportedPlatformReason('win32')).toBeNull();
+ expect(
+ (await service({ platform: 'win32' }).overview(SERVER, WORKSPACE)).unsupportedReason
+ ).toBeNull();
+ });
+
it('starts the enrolled controllers at launch, and reports a credential it cannot find', async () => {
await enabled();
const relaunched = service();
@@ -471,7 +485,7 @@ describe('EmbeddedControllerService', () => {
it('stops its controllers at quit with SIGTERM and does not start them again', async () => {
const running = await enabled();
await running.dispose();
- expect(calls[0]!.child.signals).toEqual(['SIGTERM']);
+ expect(calls[0]!.child.signals).toEqual([STOP_REQUEST]);
await new Promise((resolve) => setTimeout(resolve, 50));
expect(calls).toHaveLength(1);
});
@@ -511,7 +525,7 @@ describe('EmbeddedControllerService', () => {
const running = await enabled();
management.revoke.mockRejectedValue(new Error('Not signed in to this Switch server.'));
await running.forgetServer(SERVER);
- expect(calls[0]!.child.signals).toEqual(['SIGTERM']);
+ expect(calls[0]!.child.signals).toEqual([STOP_REQUEST]);
expect(secrets.size).toBe(0);
expect((await running.overview(SERVER, null)).enrollment).toBeNull();
});
@@ -519,7 +533,7 @@ describe('EmbeddedControllerService', () => {
const running = await enabled();
apiUrl = 'https://moved.example.com';
await running.followServerApiUrl(SERVER);
- expect(calls[0]!.child.signals).toEqual(['SIGTERM']);
+ expect(calls[0]!.child.signals).toEqual([STOP_REQUEST]);
await waitFor(() => calls.length === 2, 'the restart at the new URL');
expect(serverArg(calls[1]!)).toBe('https://moved.example.com');
await waitFor(() => calls[1]!.child.received === CREDENTIAL, 'the credential again');
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
index 69c5b7a7f..a1c2af84c 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
@@ -90,8 +90,14 @@ export type EmbeddedControllerDeps = {
movedAgents: (serverId: string) => Promise<string[]>;
};
-export const WINDOWS_UNSUPPORTED =
- 'Managed agents run through the shared host, which needs macOS or Linux. This computer runs Windows.';
+const SUPPORTED_PLATFORMS: readonly NodeJS.Platform[] = ['darwin', 'linux', 'win32'];
+
+/** Why managed agents cannot run on `platform`, or null when they can. */
+export function unsupportedPlatformReason(platform: NodeJS.Platform): string | null {
+ return SUPPORTED_PLATFORMS.includes(platform)
+ ? null
+ : `Managed agents run on macOS, Linux and Windows. This computer runs ${platform}.`;
+}
type Runner = { supervisor: ControllerSupervisor; phase: EmbeddedControllerPhase };
@@ -115,7 +121,7 @@ export class EmbeddedControllerService {
constructor(private readonly deps: EmbeddedControllerDeps) {}
get unsupportedReason(): string | null {
- return this.deps.platform === 'win32' ? WINDOWS_UNSUPPORTED : null;
+ return unsupportedPlatformReason(this.deps.platform);
}
/** Starts the controller of every server this Console is enrolled with. */
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts
index 9498bf913..afa7e199c 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/management-port.test.ts
@@ -67,6 +67,7 @@ describe('placedOn', () => {
revokedAt: null,
providers: [],
workspacesDir: null,
+ os: null,
sealingKey: null,
},
],
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/test-helpers/fake-controller-child.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/test-helpers/fake-controller-child.ts
index f9aeea53f..a0007c1e0 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/test-helpers/fake-controller-child.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/test-helpers/fake-controller-child.ts
@@ -1,14 +1,24 @@
import { EventEmitter } from 'node:events';
import { PassThrough } from 'node:stream';
+import { isStopMessage } from '@switch-console/agent-providers';
import type { ControllerChild, SpawnController } from '../controller-supervisor';
+/**
+ * How a controller is asked to stop, as `signals` records it: SIGTERM, or on
+ * Windows the stop message over its IPC channel.
+ */
+export const STOP_REQUEST = process.platform === 'win32' ? 'stop message' : 'SIGTERM';
+
/** A spawned controller as the tests drive it: stdin collected, exits on demand. */
export class FakeControllerChild extends EventEmitter implements ControllerChild {
readonly pid = 4242;
readonly stdin = new PassThrough();
readonly stdout = new PassThrough();
readonly stderr = new PassThrough();
- readonly signals: NodeJS.Signals[] = [];
+ /** The signals it was sent, and `STOP_REQUEST` for each stop message. */
+ readonly signals: string[] = [];
+ readonly sent: unknown[] = [];
+ connected = true;
received = '';
exitedWith: number | null | undefined = undefined;
/** Whether SIGTERM ends it, as it ends the real controller. */
@@ -19,6 +29,13 @@ export class FakeControllerChild extends EventEmitter implements ControllerChild
this.stdin.on('data', (chunk: Buffer) => (this.received += chunk.toString()));
}
+ send(message: unknown): boolean {
+ this.sent.push(message);
+ if (isStopMessage(message)) this.signals.push(STOP_REQUEST);
+ if (this.exitsOnSigterm && isStopMessage(message)) queueMicrotask(() => this.exit(0));
+ return true;
+ }
+
kill(signal: NodeJS.Signals = 'SIGTERM'): boolean {
this.signals.push(signal);
if (signal === 'SIGKILL' || this.exitsOnSigterm)
diff --git a/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.test.ts b/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.test.ts
index 5ac1f771a..58d674dbe 100644
--- a/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.test.ts
@@ -101,7 +101,7 @@ describe('LocalExecutionContext', () => {
expect(execFileMock).toHaveBeenCalledWith(
'C:\\Windows\\System32\\cmd.exe',
- ['/d', '/s', '/c', 'D:\\tools\\npm.cmd root -g'],
+ ['/d', '/s', '/c', '"D:\\tools\\npm.cmd ^^^"root^^^" ^^^"-g^^^""'],
expect.objectContaining({ windowsVerbatimArguments: true }),
expect.any(Function)
);
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts
index 344fc57d5..9d9216371 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts
@@ -12,6 +12,7 @@ function controller(patch: Partial<ManagementController> & { id: string }): Mana
revokedAt: null,
providers: [],
workspacesDir: null,
+ os: null,
sealingKey: null,
...patch,
};
@@ -53,6 +54,7 @@ describe('ownedMachines', () => {
kind: 'console',
providers: [{ provider: 'claude', installed: true, auth: 'ok' }],
workspacesDir: '/data/workspaces',
+ os: null,
}),
controller({ id: 'box', state: 'unknown' }),
controller({ id: 'cloud-vm', sealingKey: { key: 'a2V5', keyId: 'id' } }),
@@ -68,6 +70,7 @@ describe('ownedMachines', () => {
state: 'online',
providers: [{ provider: 'claude', ready: true, problem: null }],
workspacesDir: '/data/workspaces',
+ os: null,
local: { kind: 'this-computer' },
acceptsLogins: false,
cloud: false,
@@ -79,6 +82,7 @@ describe('ownedMachines', () => {
state: 'unknown',
providers: [],
workspacesDir: null,
+ os: null,
local: { kind: 'ssh-host', sshHost: 'devbox' },
acceptsLogins: false,
cloud: false,
@@ -90,6 +94,7 @@ describe('ownedMachines', () => {
state: 'online',
providers: [],
workspacesDir: null,
+ os: null,
local: null,
acceptsLogins: true,
cloud: false,
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts
index 3b98dde32..163cca3d7 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts
@@ -46,6 +46,7 @@ export function ownedMachines(
acceptsLogins: controller.sealingKey !== null,
cloud: isCloudMachine(controller),
workspacesDir: controller.workspacesDir,
+ os: controller.os,
local:
controller.id === local.thisComputer
? { kind: 'this-computer' }
diff --git a/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts
index 75f4abd9e..0e0aed16d 100644
--- a/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts
@@ -105,6 +105,7 @@ describe('a provider added as a plugin and a runtime', () => {
acceptsLogins: false,
cloud: false,
workspacesDir: null,
+ os: null,
local: null,
});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 4b6ac121e..f0ca1fe2f 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -2905,6 +2905,8 @@ export type ManagementController = {
* last reported; null before it has, or when it or the server predates it.
*/
workspacesDir: string | null;
+ /** Its operating system as it enrolled (`macos`, `linux`, `windows`); null when not known. */
+ os: string | null;
/**
* The key provider logins given to this machine are sealed to; null when
* its controller has none (it keeps no key, or predates sealed logins).
@@ -2968,6 +2970,7 @@ type ManagementControllerJson = {
revoked_at: string | null;
status?: unknown;
workspaces_dir?: string | null;
+ platform?: { os: string } | null;
public_key?: { alg: string; key: string; key_id: string } | null;
};
@@ -3048,6 +3051,7 @@ export async function fetchManagementControllers(
revokedAt: json.revoked_at,
providers: providerReports(json.status),
workspacesDir: json.workspaces_dir ?? null,
+ os: json.platform?.os ?? null,
sealingKey:
json.public_key?.alg === 'X25519'
? { key: json.public_key.key, keyId: json.public_key.key_id }
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
index b0bbe5cf1..bedaed9df 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
@@ -49,6 +49,7 @@ import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-con
import type { CloudMachine } from '@shared/core/cloud-agents/cloud-agents';
import {
describeRemoteDirRefusal,
+ isAbsoluteMachineDir,
isAbsoluteRemoteDir,
} from '@shared/core/remote-hosts/remote-dir';
import type { UiEntryPoint } from '@shared/core/telemetry/reporting';
@@ -94,7 +95,9 @@ const NO_ATTRIBUTES: RepoAgentAttributes = {};
* detection, discovery, and location keying — the flow must not care (CHOO-1440). */
function canonicalDir(dir: string): string {
const trimmed = dir.trim();
- const stripped = trimmed.replace(/\/+$/, '');
+ // A Windows drive root keeps its separator: `C:` alone is a relative path.
+ if (/^[A-Za-z]:[\\/]+$/.test(trimmed)) return `${trimmed.slice(0, 2)}\\`;
+ const stripped = trimmed.replace(/[\\/]+$/, '');
return stripped || (trimmed.startsWith('/') ? '/' : '');
}
@@ -425,7 +428,7 @@ export const NewAgentForm = observer(function NewAgentForm({
// session starts in. Caught here so it greys the button out with a reason.
// On a server machine the directory may be unknown: the machine makes a fresh workspace.
const remoteDirIsAbsolute = isMachineRun
- ? trimmedRemoteDir === '' || isAbsoluteRemoteDir(trimmedRemoteDir)
+ ? trimmedRemoteDir === '' || isAbsoluteMachineDir(trimmedRemoteDir, serverMachine?.os ?? null)
: !isRemoteRun || isAbsoluteRemoteDir(trimmedRemoteDir);
const canSubmit =
@@ -476,7 +479,9 @@ export const NewAgentForm = observer(function NewAgentForm({
? 'Enter the agent’s working directory on the host.'
: 'Choose the agent’s working directory.'
: !remoteDirIsAbsolute
- ? `Give the full path on ${runLocationLabel}, starting with “/”.`
+ ? serverMachine?.os === 'windows'
+ ? `Give the full path on ${runLocationLabel}, starting with a drive, like C:\\.`
+ : `Give the full path on ${runLocationLabel}, starting with “/”.`
: policyHasDeadRule(form.addressingPolicy)
? 'One addressing rule can never match — fix it under Settings.'
: null;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.test.ts
index 4143f89a4..423ebed63 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/server-run-locations.test.ts
@@ -17,6 +17,7 @@ function machine(patch: Partial<OwnedMachine> & { id: string }): OwnedMachine {
providers: [],
local: null,
workspacesDir: null,
+ os: null,
acceptsLogins: false,
cloud: false,
...patch,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-changes.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-changes.test.ts
index 71b8d4356..477ebbaa9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-changes.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-changes.test.ts
@@ -129,6 +129,7 @@ describe('shownDirectory', () => {
cloud: false,
local: null,
workspacesDir: '/srv/workspaces/',
+ os: null,
};
const unset = { ...AGENT, definition: { ...AGENT.definition, directory: null } };
const reported = {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts
index a0869957c..2107eb9bc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts
@@ -85,6 +85,7 @@ const LAPTOP: OwnedMachine = {
acceptsLogins: false,
cloud: false,
workspacesDir: null,
+ os: null,
};
describe('machineWorkspaceFor', () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx
index 04755e352..0304f5da6 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/give-machine-login-vertex.test.tsx
@@ -46,6 +46,7 @@ const MACHINE: OwnedMachine = {
acceptsLogins: true,
cloud: true,
workspacesDir: null,
+ os: null,
local: null,
};
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
index 00ede3215..692ca9251 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
@@ -78,6 +78,7 @@ const LAPTOP: OwnedMachine = {
acceptsLogins: false,
cloud: false,
workspacesDir: '/home/me/workspaces',
+ os: null,
};
let container: HTMLDivElement;
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx
index d2125fd73..6680922c7 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx
@@ -316,6 +316,7 @@ const BOX: OwnedMachine = {
state: 'online',
local: null,
workspacesDir: null,
+ os: null,
providers: [
{ provider: 'claude', ready: true, problem: null },
{ provider: 'codex', ready: false, problem: 'not logged in' },
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
index e80e8b859..e389ea44d 100644
--- a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
@@ -106,6 +106,8 @@ export type OwnedMachine = ManagedMachine & {
* null before it has said.
*/
workspacesDir: string | null;
+ /** Its operating system as it enrolled (`macos`, `linux`, `windows`); null when not known. */
+ os: string | null;
local: MachineLocal;
};
diff --git a/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.test.ts b/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.test.ts
new file mode 100644
index 000000000..dababe834
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+import { isAbsoluteMachineDir } from './remote-dir';
+
+describe('isAbsoluteMachineDir', () => {
+ it('takes a drive or a share as absolute on a Windows machine', () => {
+ expect(isAbsoluteMachineDir('C:\\Users\\me\\work', 'windows')).toBe(true);
+ expect(isAbsoluteMachineDir('d:/work', 'windows')).toBe(true);
+ expect(isAbsoluteMachineDir('\\\\server\\share\\work', 'windows')).toBe(true);
+ expect(isAbsoluteMachineDir('C:work', 'windows')).toBe(false);
+ expect(isAbsoluteMachineDir('work', 'windows')).toBe(false);
+ });
+
+ it('wants a rooted path elsewhere, and where the system is not known', () => {
+ expect(isAbsoluteMachineDir('/home/me/work', 'linux')).toBe(true);
+ expect(isAbsoluteMachineDir('C:\\work', 'macos')).toBe(false);
+ expect(isAbsoluteMachineDir('C:\\work', null)).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.ts b/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.ts
index c455e943f..5fd0397a1 100644
--- a/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.ts
@@ -40,6 +40,16 @@ export function isAbsoluteRemoteDir(dir: string): boolean {
return dir.startsWith('/');
}
+/**
+ * Whether `dir` is an absolute path on a machine running `os`: rooted at `/`,
+ * or on Windows at a drive (`C:\`, `C:/`) or a network share (`\\server\share`).
+ * A machine whose system is not known is taken to be POSIX.
+ */
+export function isAbsoluteMachineDir(dir: string, os: string | null): boolean {
+ if (os === 'windows') return /^[A-Za-z]:[\\/]/.test(dir) || dir.startsWith('\\\\');
+ return isAbsoluteRemoteDir(dir);
+}
+
/**
* The one spelling of an absolute remote path: `.`/`..` resolved, repeated and
* trailing slashes gone. The location row, the gateway's `repo_dir` and the
diff --git a/console/docs/sdk-sessions.md b/console/docs/sdk-sessions.md
index 5c56dd808..444615c22 100644
--- a/console/docs/sdk-sessions.md
+++ b/console/docs/sdk-sessions.md
@@ -195,9 +195,13 @@ are the only session runtime. Lifecycle scripts use noninteractive commands.
Recovery requires the saved provider conversation and host state on the same
execution host. Moving that state between machines is not an automatic recovery
-operation. Process-group fencing and automatic host replacement require POSIX;
-unsupported Windows recovery fails explicitly. The supervisor survives Console
-closure and worker crashes, but it is not an operating-system boot service.
+operation. Fencing after a crash and automatic host replacement use process
+groups on macOS and Linux. Windows has none, so there a crashed owner's
+leftovers are found by parent process and creation time (PowerShell's CIM
+cmdlets), and a host is asked to stop over its IPC channel or a stop file in
+its state root rather than by SIGTERM, which Windows cannot deliver to be
+caught. The supervisor survives Console closure and worker crashes, but it is
+not an operating-system boot service.
A remote host needs Node 20.3 or newer, the selected provider, its own provider authentication,
and network access to Switch and the provider. Local SSH fixture coverage does
diff --git a/console/packages/agent-controller/README.md b/console/packages/agent-controller/README.md
index 6091f002b..137b57454 100644
--- a/console/packages/agent-controller/README.md
+++ b/console/packages/agent-controller/README.md
@@ -32,7 +32,8 @@ relay accepts.
## Requirements
-- macOS or Linux. The shared host needs POSIX process control.
+- macOS, Linux or Windows 10/11. On Windows the controller is meant to run with
+ Switch Console, which starts it; see [On Windows](#on-windows).
- Node 22.13 or later. The store uses the built-in `node:sqlite`.
- Each provider CLI the agents use, installed on `PATH` and signed in as the user
the controller runs as (`claude`, `codex`, `opencode`, `agent`/`cursor-agent`,
@@ -85,7 +86,7 @@ switch-agent-controller install-service [--data-dir <dir>] [--env-file <path>]
switch-agent-controller run [--data-dir <dir>] [--env-file <path>]
switch-agent-controller status [--data-dir <dir>]
switch-agent-controller set-info [--name <name>] [--description <text>] [--data-dir <dir>]
-switch-agent-controller doctor [--data-dir <dir>]
+switch-agent-controller doctor [--data-dir <dir>] [--env-file <path>]
switch-agent-controller update [--check]
```
@@ -123,7 +124,7 @@ switch-agent-controller update [--check]
URL that is not one, or is plain `http` to a host that is not loopback; a
data directory that belongs to another controller identity, or whose store
a newer controller wrote; a shared-host bundle that is missing, not a file
- or unreadable; an unsupported platform (Windows); a data directory that
+ or unreadable; an unsupported platform; a data directory that
holds no identity, or no credential (revoked earlier and wiped, or never
enrolled); `set-info` with nothing to change, or a name or description past
the limits; and with `--credential-stdin`, a credential that does not arrive
@@ -161,7 +162,24 @@ with a hash of its path, so two controllers on one account each get their own.
On Linux without a systemd user manager (some containers and minimal VMs),
`install-service` refuses. Run `run` under your own supervisor instead, with the
-restart rules below.
+restart rules below. It refuses on Windows too.
+
+### On Windows
+
+The controller runs natively on Windows, without WSL. Switch Console starts it
+and stops it, so it is not installed as a service there: `install-service`
+refuses, and a controller started by hand is run with `run`. Its data lives in
+`%LOCALAPPDATA%\Switch\agent-controller` (Console keeps its own under its app
+data), whose access list it sets to the current user and the system alone.
+
+- Provider CLIs are found on `PATH` with `PATHEXT`, so `claude.exe` and an npm
+ install's `codex.cmd` both count.
+- Antigravity has no Windows build, so it is reported as not installed.
+- `--agent-runtime separate-user` is Linux only.
+- An agent's shell setup is refused: it is a POSIX shell snippet.
+- Stopping an agent host asks it over its IPC channel or a stop file in its
+ state root, since Windows has no catchable SIGTERM. Process identity and
+ cleanup after a crash go through PowerShell's CIM cmdlets.
### Environment for the agents
@@ -503,7 +521,6 @@ session hosts it launches with `process.execPath` run as Node too.
- OOM kills are not detected. `oom_kills` is always `0`.
- `restarts_10m` counts the relaunches reconciling made, not the restarts after a
agent host failure.
-- Windows is not supported.
## Where data lives
diff --git a/console/packages/agent-controller/src/detached-runtime.test.ts b/console/packages/agent-controller/src/detached-runtime.test.ts
index cb644dcb8..36dddf1a8 100644
--- a/console/packages/agent-controller/src/detached-runtime.test.ts
+++ b/console/packages/agent-controller/src/detached-runtime.test.ts
@@ -102,7 +102,8 @@ describe('DetachedRuntime', () => {
'--ensure-watch',
'false',
]);
- expect(statSync(join(root, 'template.json')).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32')
+ expect(statSync(join(root, 'template.json')).mode & 0o777).toBe(0o600);
expect(await runtime.observe('agent-1')).toMatchObject({
alive: false,
configured: { provider: 'claude', cwd: '/work/scout' },
diff --git a/console/packages/agent-controller/src/detached-runtime.ts b/console/packages/agent-controller/src/detached-runtime.ts
index c70b70954..2fa39c5e9 100644
--- a/console/packages/agent-controller/src/detached-runtime.ts
+++ b/console/packages/agent-controller/src/detached-runtime.ts
@@ -15,7 +15,6 @@ import type { DataLayout } from './paths';
import {
type AgentObservation,
type AgentRunner,
- assertSupportedPlatform,
type LaunchOptions,
ownsRoot,
OWNER_RECORDS,
@@ -50,9 +49,7 @@ export class DetachedRuntime implements AgentRunner {
/** The `shared-host-daemon.mjs` bundle from agent-providers. */
bundlePath: string;
}
- ) {
- assertSupportedPlatform(process.platform);
- }
+ ) {}
async observe(agentId: string): Promise<AgentObservation> {
const root = this.deps.layout.watcherRoot(agentId);
diff --git a/console/packages/agent-controller/src/doctor.test.ts b/console/packages/agent-controller/src/doctor.test.ts
index 7706caad7..fc5fb3ee6 100644
--- a/console/packages/agent-controller/src/doctor.test.ts
+++ b/console/packages/agent-controller/src/doctor.test.ts
@@ -41,6 +41,23 @@ describe('doctor', () => {
expect(formatChecks(checks)).toContain('ok claude');
});
+ it('passes a ready Windows machine, which Console runs rather than a service', async () => {
+ const checks = await runDoctor(
+ inputs({
+ platform: 'win32',
+ service: async () => {
+ throw new Error('not asked on Windows');
+ },
+ })
+ );
+ expect(checks.filter((check) => check.status !== 'ok')).toEqual([]);
+ expect(checks.find((check) => check.name === 'Service')?.detail).toMatch(/Switch Console/);
+ });
+
+ it('fails a platform the controller does not run on', async () => {
+ expect(status(await runDoctor(inputs({ platform: 'freebsd' })), 'Platform')).toBe('fail');
+ });
+
it('fails an old Node, and a machine with no signed-in provider', async () => {
const checks = await runDoctor(
inputs({
diff --git a/console/packages/agent-controller/src/doctor.ts b/console/packages/agent-controller/src/doctor.ts
index e6c5da0ad..b0868f580 100644
--- a/console/packages/agent-controller/src/doctor.ts
+++ b/console/packages/agent-controller/src/doctor.ts
@@ -150,13 +150,13 @@ async function providerChecks(inputs: DoctorInputs, bundle: string | null): Prom
/** Checks this machine can run the agents Switch places on it, and says what to do where it cannot. */
export async function runDoctor(inputs: DoctorInputs): Promise<Check[]> {
const checks: Check[] = [nodeCheck(inputs.nodeVersion)];
- const supported = inputs.platform === 'darwin' || inputs.platform === 'linux';
+ const supported = ['darwin', 'linux', 'win32'].includes(inputs.platform);
checks.push({
name: 'Platform',
status: supported ? 'ok' : 'fail',
detail: supported
? inputs.platform
- : `${inputs.platform} is not supported; use Linux or macOS.`,
+ : `${inputs.platform} is not supported; use Linux, macOS or Windows.`,
});
checks.push(...(await serverChecks(inputs)));
let bundle: string | null = null;
@@ -173,27 +173,37 @@ export async function runDoctor(inputs: DoctorInputs): Promise<Check[]> {
detail: `Each agent runs as one of ${inputs.separateUsers.agentUsers} users of its own, in ${inputs.separateUsers.agentsDir}; a provider is ready only through what the --env-file gives agents.`,
});
checks.push(...(await providerChecks(inputs, bundle)));
- const service = await inputs.service().catch((error: unknown) => errorMessage(error));
const unit = inputs.separateUsers?.controllerUnit;
+ const service =
+ inputs.platform === 'win32'
+ ? 'console'
+ : await inputs.service().catch((error: unknown) => errorMessage(error));
checks.push(
- service === 'running'
- ? { name: 'Service', status: 'ok', detail: 'Installed and running' }
- : service === 'stopped'
- ? {
- name: 'Service',
- status: 'warn',
- detail: unit
- ? `${unit} is not running: sudo systemctl start ${unit}`
- : 'Installed, but not running',
- }
- : service === 'not-installed'
+ service === 'console'
+ ? {
+ name: 'Service',
+ status: 'ok',
+ detail:
+ 'Not a service on Windows: Switch Console starts and stops this controller (or keep `run` going yourself)',
+ }
+ : service === 'running'
+ ? { name: 'Service', status: 'ok', detail: 'Installed and running' }
+ : service === 'stopped'
? {
name: 'Service',
status: 'warn',
- detail:
- 'Not installed; run: switch-agent-controller install-service (or keep `run` going yourself)',
+ detail: unit
+ ? `${unit} is not running: sudo systemctl start ${unit}`
+ : 'Installed, but not running',
}
- : { name: 'Service', status: 'warn', detail: `Cannot tell: ${service}` }
+ : service === 'not-installed'
+ ? {
+ name: 'Service',
+ status: 'warn',
+ detail:
+ 'Not installed; run: switch-agent-controller install-service (or keep `run` going yourself)',
+ }
+ : { name: 'Service', status: 'warn', detail: `Cannot tell: ${service}` }
);
try {
const latest = await inputs.latest();
diff --git a/console/packages/agent-controller/src/exit-codes.test.ts b/console/packages/agent-controller/src/exit-codes.test.ts
index 440595da9..37263b896 100644
--- a/console/packages/agent-controller/src/exit-codes.test.ts
+++ b/console/packages/agent-controller/src/exit-codes.test.ts
@@ -11,7 +11,6 @@ import {
exitCodeFor,
} from './exit-codes';
import { defaultDataDir } from './paths';
-import { assertSupportedPlatform } from './runtime';
function thrown(run: () => unknown): unknown {
try {
@@ -59,10 +58,7 @@ describe('exitCodeFor', () => {
expect(exitCodeFor(null)).toBe(EXIT_FAILURE);
});
- it('answers an unsupported platform and an unresolvable data directory with 2', () => {
- expect(exitCodeFor(thrown(() => assertSupportedPlatform('win32')))).toBe(EXIT_CONFIGURATION);
- expect(() => assertSupportedPlatform('linux')).not.toThrow();
- expect(() => assertSupportedPlatform('darwin')).not.toThrow();
+ it('answers an unresolvable data directory with 2', () => {
expect(
exitCodeFor(thrown(() => defaultDataDir({ platform: 'win32', env: {}, home: 'C:\\a' })))
).toBe(EXIT_CONFIGURATION);
diff --git a/console/packages/agent-controller/src/handover.test.ts b/console/packages/agent-controller/src/handover.test.ts
index dce25cf45..33f9c897e 100644
--- a/console/packages/agent-controller/src/handover.test.ts
+++ b/console/packages/agent-controller/src/handover.test.ts
@@ -182,7 +182,8 @@ describe('resolveSharedHostBundle', () => {
const directory = join(dir, 'bundle-dir');
mkdirSync(directory);
expect(() => resolveSharedHostBundle(directory, {}, () => '')).toThrow(/is not a file/);
- if (process.getuid?.() === 0) return;
+ // Windows has no mode bits to make a file unreadable with.
+ if (process.getuid?.() === 0 || process.platform === 'win32') return;
const unreadable = join(dir, 'unreadable.mjs');
writeFileSync(unreadable, '');
chmodSync(unreadable, 0o000);
diff --git a/console/packages/agent-controller/src/main.ts b/console/packages/agent-controller/src/main.ts
index ab57458d9..b69f6bc82 100644
--- a/console/packages/agent-controller/src/main.ts
+++ b/console/packages/agent-controller/src/main.ts
@@ -3,7 +3,7 @@ import { realpathSync } from 'node:fs';
import { hostname } from 'node:os';
import { join, resolve } from 'node:path';
import { parseArgs } from 'node:util';
-import { generateSealingKeyPair } from '@switch-console/agent-providers';
+import { generateSealingKeyPair, isStopMessage } from '@switch-console/agent-providers';
import packageJson from '../package.json' with { type: 'json' };
import {
AccessTokens,
@@ -39,13 +39,7 @@ import {
import { createLogger, errorMessage } from './log';
import { dataLayout, ensureDataDir, resolveDataDir, serverWorkspacesDir } from './paths';
import { definitionProblem } from './reconcile';
-import {
- assertSupportedPlatform,
- emptyObservation,
- InProcessRuntime,
- observeOnDisk,
- probeProvider,
-} from './runtime';
+import { emptyObservation, InProcessRuntime, observeOnDisk, probeProvider } from './runtime';
import { AgentRuntimes } from './runtimes';
import { type ControllerInfoChange, PROTOCOL_VERSION } from './schemas';
import {
@@ -133,14 +127,14 @@ Commands:
uninstall-service --separate-users [--user <name>]
As root: stop the controller and its agents, and remove what the setup
made. The agents' directories are kept.
- doctor [--data-dir <dir>] [--shared-host-bundle <path>]
+ doctor [--data-dir <dir>] [--shared-host-bundle <path>] [--env-file <path>]
Check this machine can run agents: Node, enrollment, the credential, the
server, the provider CLIs and their sign-in, the service, and updates.
update [--check] [--data-dir <dir>]
Install the newest release with npm, and restart the service if it runs.
--check only says whether there is one.
-run --env-file and install-service --env-file read NAME=value lines (as for
+run, install-service and doctor --env-file read NAME=value lines (as for
systemd's EnvironmentFile) into the agents' environment: provider API keys, or
Vertex AI and Bedrock settings such as CLAUDE_CODE_USE_VERTEX,
ANTHROPIC_VERTEX_PROJECT_ID and CLOUD_ML_REGION.
@@ -347,7 +341,6 @@ async function runCommand(args: string[]): Promise<number> {
},
strict: true,
});
- assertSupportedPlatform(process.platform);
const agentRuntime = values['agent-runtime'] ?? 'default';
if (agentRuntime !== 'default' && agentRuntime !== 'separate-user')
throw new UsageError('--agent-runtime must be default or separate-user.');
@@ -383,11 +376,18 @@ async function runCommand(args: string[]): Promise<number> {
? fileSecrets
: new MemorySecretStore({ [CONTROLLER_CREDENTIAL]: credential }, 'handed over on stdin');
const stop = new AbortController();
- const onSignal = (signal: NodeJS.Signals) => {
+ const onSignal = (signal: NodeJS.Signals | 'a stop request') => {
log.info(`Received ${signal}; stopping this controller's agents and exiting.`);
stop.abort();
};
for (const signal of SIGNALS) process.once(signal, onSignal);
+ // Windows has no signal a parent can send that is caught here, so Console
+ // asks over the IPC channel it starts this controller with.
+ const onMessage = (message: unknown) => {
+ if (isStopMessage(message)) onSignal('a stop request');
+ };
+ process.on('message', onMessage);
+ process.channel?.unref();
if (Object.keys(fromFile).length)
log.info("Read the agents' environment from a file", {
file: values['env-file'],
@@ -460,6 +460,7 @@ async function runCommand(args: string[]): Promise<number> {
return EXIT_CODE_FOR[exit];
} finally {
for (const signal of SIGNALS) process.off(signal, onSignal);
+ process.off('message', onMessage);
store.close();
}
}
@@ -472,7 +473,7 @@ async function statusCommand(args: string[]): Promise<number> {
});
const { dataDir, layout, store, secrets } = await openState(values['data-dir']);
try {
- const separateUsers = await findSeparateUsersConfig(currentUid(), dataDir);
+ const separateUsers = await separateUsersConfigHere(dataDir);
const separateRuntime = separateUsers
? new SystemdRuntime({
config: separateUsers,
@@ -595,7 +596,6 @@ async function installServiceCommand(args: string[]): Promise<number> {
},
strict: true,
});
- assertSupportedPlatform(process.platform);
if (values['separate-users']) return installSeparateUsersCommand(values);
for (const flag of ['user', 'agents-dir', 'agent-users', 'no-block'] as const)
if (values[flag] !== undefined)
@@ -703,13 +703,21 @@ async function uninstallServiceCommand(args: string[]): Promise<number> {
async function doctorCommand(args: string[]): Promise<number> {
const { values } = parseArgs({
args,
- options: { 'data-dir': { type: 'string' }, 'shared-host-bundle': { type: 'string' } },
+ options: {
+ 'data-dir': { type: 'string' },
+ 'shared-host-bundle': { type: 'string' },
+ 'env-file': { type: 'string' },
+ },
strict: true,
});
+ // The agents' environment, as `run` would have it: a provider signed in by a
+ // key or token there reads as signed in here too.
+ if (values['env-file'])
+ Object.assign(process.env, await readEnvFile(resolve(values['env-file'])));
const { dataDir, store, secrets } = await openState(values['data-dir']);
const locator = new PathProviderLocator(process.env.PATH, join(dataDir, 'version-probe'));
try {
- const separateUsers = await findSeparateUsersConfig(currentUid(), dataDir);
+ const separateUsers = await separateUsersConfigHere(dataDir);
const separateRuntime = separateUsers
? new SystemdRuntime({
config: separateUsers,
@@ -859,6 +867,12 @@ async function unitSummary(config: SeparateUsersConfig, slot: number | null): Pr
return `${unit} is ${state.trim()}`;
}
+/** The separate-users setup this data directory has, or none: Windows has no Linux users. */
+async function separateUsersConfigHere(dataDir: string): Promise<SeparateUsersConfig | null> {
+ if (process.platform === 'win32') return null;
+ return findSeparateUsersConfig(currentUid(), dataDir);
+}
+
function currentUid(): number {
const uid = process.getuid?.();
if (uid === undefined) throw new ConfigurationError('This platform has no user ids.');
diff --git a/console/packages/agent-controller/src/paths.test.ts b/console/packages/agent-controller/src/paths.test.ts
index 68a26b0ac..1c696f84b 100644
--- a/console/packages/agent-controller/src/paths.test.ts
+++ b/console/packages/agent-controller/src/paths.test.ts
@@ -1,3 +1,4 @@
+import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -14,42 +15,65 @@ import {
describe('defaultDataDir', () => {
it('follows each OS’s convention', () => {
expect(defaultDataDir({ platform: 'darwin', env: {}, home: '/Users/a' })).toBe(
- '/Users/a/Library/Application Support/Switch/agent-controller'
+ join('/Users/a', 'Library', 'Application Support', 'Switch', 'agent-controller')
);
expect(defaultDataDir({ platform: 'linux', env: {}, home: '/home/a' })).toBe(
- '/home/a/.local/state/switch/agent-controller'
+ join('/home/a', '.local', 'state', 'switch', 'agent-controller')
);
expect(
defaultDataDir({ platform: 'linux', env: { XDG_STATE_HOME: '/state' }, home: '/home/a' })
- ).toBe('/state/switch/agent-controller');
+ ).toBe(join('/state', 'switch', 'agent-controller'));
expect(
defaultDataDir({ platform: 'linux', env: { XDG_STATE_HOME: 'relative' }, home: '/home/a' })
- ).toBe('/home/a/.local/state/switch/agent-controller');
+ ).toBe(join('/home/a', '.local', 'state', 'switch', 'agent-controller'));
});
});
describe('ensureDataDir', () => {
- it('creates the directory owner-only, and tightens an existing one', async () => {
- const base = mkdtempSync(join(tmpdir(), 'controller-paths-'));
- try {
- const fresh = join(base, 'a', 'b');
- await ensureDataDir(fresh);
- expect(statSync(fresh).mode & 0o777).toBe(0o700);
- const loose = join(base, 'loose');
- mkdirSync(loose, { mode: 0o755 });
- await ensureDataDir(loose);
- expect(statSync(loose).mode & 0o777).toBe(0o700);
- } finally {
- rmSync(base, { recursive: true, force: true });
+ it.skipIf(process.platform === 'win32')(
+ 'creates the directory owner-only, and tightens an existing one',
+ async () => {
+ const base = mkdtempSync(join(tmpdir(), 'controller-paths-'));
+ try {
+ const fresh = join(base, 'a', 'b');
+ await ensureDataDir(fresh);
+ expect(statSync(fresh).mode & 0o777).toBe(0o700);
+ const loose = join(base, 'loose');
+ mkdirSync(loose, { mode: 0o755 });
+ await ensureDataDir(loose);
+ expect(statSync(loose).mode & 0o777).toBe(0o700);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
}
- });
+ );
+
+ it.runIf(process.platform === 'win32')(
+ 'gives the directory to this user and the system alone on Windows',
+ async () => {
+ const base = mkdtempSync(join(tmpdir(), 'controller-paths-'));
+ try {
+ const dir = join(base, 'data');
+ await ensureDataDir(dir);
+ const icacls = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'icacls.exe');
+ const acl = execFileSync(icacls, [dir], { encoding: 'utf8' });
+ expect(acl).toContain('NT AUTHORITY\\SYSTEM:(OI)(CI)(F)');
+ expect(acl).not.toMatch(/BUILTIN\\Users|Everyone|Authenticated Users/);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ },
+ 30_000
+ );
});
describe('dataLayout', () => {
it('keeps server-supplied names to one path segment', () => {
const layout = dataLayout('/data');
- expect(layout.agentCredentials('agent-1')).toBe('/data/agents/agent-1/credentials.json');
- expect(layout.watcherRoot('agent-1')).toBe('/data/watchers/agent-1');
+ expect(layout.agentCredentials('agent-1')).toBe(
+ join('/data', 'agents', 'agent-1', 'credentials.json')
+ );
+ expect(layout.watcherRoot('agent-1')).toBe(join('/data', 'watchers', 'agent-1'));
expect(serverWorkspacesDir('http://localhost:8000')).toBe(
join(homedir(), '.switch', 'agents', 'localhost-8000')
);
@@ -57,7 +81,7 @@ describe('dataLayout', () => {
join(homedir(), '.switch', 'agents', 'switch.example.com')
);
expect(agentWorkspace('/home/me/.switch/agents/localhost-8000', 'scout')).toBe(
- '/home/me/.switch/agents/localhost-8000/scout'
+ join('/home/me/.switch/agents/localhost-8000', 'scout')
);
expect(() => agentWorkspace('/w', '../escape')).toThrow(/cannot be used/);
expect(() => layout.watcherRoot('../x')).toThrow(/cannot be used as a directory name/);
diff --git a/console/packages/agent-controller/src/paths.ts b/console/packages/agent-controller/src/paths.ts
index 07514cbb7..5e6b8295f 100644
--- a/console/packages/agent-controller/src/paths.ts
+++ b/console/packages/agent-controller/src/paths.ts
@@ -1,6 +1,8 @@
+import { execFile } from 'node:child_process';
import { chmod, mkdir, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { isAbsolute, join, resolve } from 'node:path';
+import { promisify } from 'node:util';
import { ConfigurationError } from './errors';
export const DATA_DIR_ENV = 'SWITCH_CONTROLLER_DATA_DIR';
@@ -42,15 +44,59 @@ export function resolveDataDir(flag: string | undefined): string {
/**
* Creates the data directory owner-only (0700), and tightens one that already
* exists with looser permissions: it holds the controller credential and every
- * agent's relay token.
+ * agent's relay token. Windows has no mode bits, so there its access list is
+ * replaced with one that lets in this user and the system alone, inherited by
+ * everything written under it.
*/
export async function ensureDataDir(dir: string): Promise<void> {
await mkdir(dir, { recursive: true, mode: 0o700 });
- if (process.platform === 'win32') return;
+ if (process.platform === 'win32') {
+ await restrictToCurrentUser(dir);
+ return;
+ }
const mode = (await stat(dir)).mode & 0o777;
if (mode !== 0o700) await chmod(dir, 0o700);
}
+/** The well-known SID of the operating system's own account. */
+const LOCAL_SYSTEM_SID = 'S-1-5-18';
+
+/**
+ * A Windows tool by its full path: a PATH with Git for Windows on it has GNU
+ * tools of the same names ahead of the system's.
+ */
+function system32(tool: string): string {
+ return join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', tool);
+}
+
+async function restrictToCurrentUser(dir: string): Promise<void> {
+ const execute = promisify(execFile);
+ try {
+ const { stdout } = await execute(system32('whoami.exe'), ['/user', '/fo', 'csv', '/nh'], {
+ timeout: 15_000,
+ windowsHide: true,
+ });
+ const sid = stdout.trim().split(',').at(-1)?.replaceAll('"', '');
+ if (!sid?.startsWith('S-1-')) throw new Error(`whoami printed no SID: ${stdout.trim()}`);
+ await execute(
+ system32('icacls.exe'),
+ [
+ dir,
+ '/inheritance:r',
+ '/grant:r',
+ `*${sid}:(OI)(CI)F`,
+ '/grant:r',
+ `*${LOCAL_SYSTEM_SID}:(OI)(CI)F`,
+ ],
+ { timeout: 15_000, windowsHide: true }
+ );
+ } catch (error) {
+ throw new ConfigurationError(
+ `Could not make ${dir} readable by this user only, and it holds the controller's credentials: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+}
+
export type DataLayout = {
root: string;
database: string;
diff --git a/console/packages/agent-controller/src/reconcile.ts b/console/packages/agent-controller/src/reconcile.ts
index 5dabc2a1d..b4d951054 100644
--- a/console/packages/agent-controller/src/reconcile.ts
+++ b/console/packages/agent-controller/src/reconcile.ts
@@ -1,4 +1,7 @@
-import { providerLoginEnvironment } from '@switch-console/agent-providers';
+import {
+ providerLoginEnvironment,
+ providerUnsupportedReason,
+} from '@switch-console/agent-providers';
import { ReasonedError } from './errors';
import { errorMessage, type Logger } from './log';
import { isSafeSegment } from './paths';
@@ -242,7 +245,8 @@ export async function startAgent(
if (!binaryPath)
throw new ReasonedError(
'provider_not_installed',
- `The ${provider} CLI was not found on this machine's PATH.`
+ providerUnsupportedReason(provider, process.platform) ??
+ `The ${provider} CLI was not found on this machine's PATH.`
);
const template = buildWatcherTemplate({
agentId,
diff --git a/console/packages/agent-controller/src/runtime.test.ts b/console/packages/agent-controller/src/runtime.test.ts
index c86a65c8a..f9b3dc39a 100644
--- a/console/packages/agent-controller/src/runtime.test.ts
+++ b/console/packages/agent-controller/src/runtime.test.ts
@@ -126,9 +126,11 @@ function template(cwd = '/work/scout', provider: 'claude' | 'codex' = 'claude')
/** A process whose command line names the watcher root, as a detached watcher's does. */
async function fakeWatcher(root: string): Promise<ChildProcess> {
- const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)', root], {
- stdio: 'ignore',
- });
+ // Stops as an agent host does: on SIGTERM, or on Windows when its stop file appears.
+ const script = `const { existsSync } = require('node:fs');
+ const stop = require('node:path').join(process.argv[1], '.stop-' + process.pid);
+ setInterval(() => { if (existsSync(stop)) process.exit(0); }, 100);`;
+ const child = spawn(process.execPath, ['-e', script, root], { stdio: 'ignore' });
children.push(child);
await once(child, 'spawn');
return child;
@@ -139,8 +141,9 @@ describe('InProcessRuntime', () => {
await runtime.writeCredentials('agent-1', RELAY);
const path = runtime.credentialsPath('agent-1');
expect(path).toBe(join(dir, 'data', 'agents', 'agent-1', 'credentials.json'));
- expect(statSync(path).mode & 0o777).toBe(0o600);
- expect(statSync(join(dir, 'data', 'agents', 'agent-1')).mode & 0o777).toBe(0o700);
+ if (process.platform !== 'win32') expect(statSync(path).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32')
+ expect(statSync(join(dir, 'data', 'agents', 'agent-1')).mode & 0o777).toBe(0o700);
expect(await readSharedCredentials(template())).toEqual({
SWITCH_API_ENDPOINT: 'http://127.0.0.1:43210',
SWITCH_API_TOKEN: 'swlr_relay-token-placeholder',
@@ -288,7 +291,7 @@ describe('InProcessRuntime', () => {
CLOUD_ML_REGION: 'global',
GOOGLE_APPLICATION_CREDENTIALS: path,
});
- expect(statSync(path).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32') expect(statSync(path).mode & 0o777).toBe(0o600);
expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual(SERVICE_ACCOUNT_KEY_FIXTURE);
});
diff --git a/console/packages/agent-controller/src/runtime.ts b/console/packages/agent-controller/src/runtime.ts
index 04bdc9e76..5c88bac37 100644
--- a/console/packages/agent-controller/src/runtime.ts
+++ b/console/packages/agent-controller/src/runtime.ts
@@ -1,22 +1,27 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { mkdir, open, readFile, rename, rm, stat, unlink } from 'node:fs/promises';
+import { mkdir, open, readFile, rm, stat, unlink } from 'node:fs/promises';
import { homedir } from 'node:os';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { promisify } from 'node:util';
import {
clearTakenOver,
+ commandLineNames,
ensureSharedProcess,
hostedCredentialSchema,
inProcessSupervision,
+ killProcessTree,
materializeHostedProvider,
type OpenAgentStream,
type ProviderReadiness,
+ processCommandLine,
providerReadinessSchema,
readTakenOver,
readWatchFlags,
recordWatcherHealth,
+ replaceFile,
+ requestStop,
runAgentHost,
SessionLinks,
sharedConfigSchema,
@@ -31,7 +36,7 @@ import {
watcherHealthFileSchema,
watchFlagsSchema,
} from '@switch-console/agent-providers';
-import { ConfigurationError, ReasonedError } from './errors';
+import { ReasonedError } from './errors';
import { errorMessage, type Logger } from './log';
import { agentWorkspace, type DataLayout } from './paths';
import type { Isolation, Provider } from './schemas';
@@ -166,7 +171,7 @@ export async function probeProvider(
const { stdout } = await execute(
process.execPath,
[bundlePath, '--probe', provider, cwd, binaryPath],
- { timeout: PROBE_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024, env }
+ { timeout: PROBE_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024, env, windowsHide: true }
);
const line = stdout.trim().split('\n').at(-1) ?? '';
return providerReadinessSchema.parse(JSON.parse(line));
@@ -224,7 +229,7 @@ export async function writeAtomic(path: string, body: string): Promise<void> {
} finally {
await file.close();
}
- await rename(temporary, path);
+ await replaceFile(temporary, path);
}
export async function readOptional(path: string): Promise<string | null> {
@@ -261,13 +266,8 @@ export function alive(pid: number): boolean {
/** A saved PID counts only while it still names a process started for this root. */
export async function ownsRoot(pid: number, root: string): Promise<boolean> {
if (!alive(pid)) return false;
- try {
- const { stdout } = await execute('ps', ['-p', String(pid), '-o', 'command=']);
- return stdout.includes(root);
- } catch (error) {
- if ((error as { code?: number }).code === 1) return false;
- throw error;
- }
+ const commandLine = await processCommandLine(pid);
+ return commandLine !== null && commandLineNames(commandLine, root);
}
export async function recordedPid(path: string): Promise<number | null> {
@@ -280,14 +280,6 @@ export async function recordedPid(path: string): Promise<number | null> {
/** The owner records an agent host writes under its root: the worker's, then a detached one's supervisor's. */
export const OWNER_RECORDS = ['shared-owner.lock', join('supervisor', 'owner.json')];
-/** The shared host needs POSIX process control: macOS or Linux. */
-export function assertSupportedPlatform(platform: NodeJS.Platform): void {
- if (platform === 'win32')
- throw new ConfigurationError(
- 'The agents controller runs agents through the shared host, which needs a macOS or Linux machine.'
- );
-}
-
/** What is on disk for one agent's agent host, read by a process that does not run it (`status`). */
export async function observeOnDisk(
layout: DataLayout,
@@ -364,9 +356,7 @@ export class InProcessRuntime implements AgentRuntime {
/** How long a failed agent host waits before it is started again. */
crashBackoffMs: number;
}
- ) {
- assertSupportedPlatform(process.platform);
- }
+ ) {}
credentialsPath(agentId: string): string {
return this.deps.layout.agentCredentials(agentId);
@@ -397,7 +387,9 @@ export class InProcessRuntime implements AgentRuntime {
return path;
}
const expanded =
- directory === '~' || directory.startsWith('~/')
+ directory === '~' ||
+ directory.startsWith('~/') ||
+ (process.platform === 'win32' && directory.startsWith('~\\'))
? join(homedir(), directory.slice(1))
: directory;
if (!isAbsolute(expanded))
@@ -586,11 +578,11 @@ export class InProcessRuntime implements AgentRuntime {
root,
pid,
});
- process.kill(pid, 'SIGTERM');
+ await requestStop(root, pid);
const deadline = Date.now() + STOP_TIMEOUT_MS;
while (alive(pid)) {
if (Date.now() > deadline) {
- process.kill(pid, 'SIGKILL');
+ await killProcessTree(pid);
break;
}
await delay(200);
diff --git a/console/packages/agent-controller/src/secrets.test.ts b/console/packages/agent-controller/src/secrets.test.ts
index d15b4c6c8..3e95b5187 100644
--- a/console/packages/agent-controller/src/secrets.test.ts
+++ b/console/packages/agent-controller/src/secrets.test.ts
@@ -29,8 +29,10 @@ describe('FileSecretStore', () => {
expect(await store.get(CONTROLLER_CREDENTIAL)).toBeNull();
await store.set(CONTROLLER_CREDENTIAL, 'credential-placeholder');
expect(await store.get(CONTROLLER_CREDENTIAL)).toBe('credential-placeholder');
- expect(statSync(join(dir, 'secrets', CONTROLLER_CREDENTIAL)).mode & 0o777).toBe(0o600);
- expect(statSync(join(dir, 'secrets')).mode & 0o777).toBe(0o700);
+ if (process.platform !== 'win32')
+ expect(statSync(join(dir, 'secrets', CONTROLLER_CREDENTIAL)).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32')
+ expect(statSync(join(dir, 'secrets')).mode & 0o777).toBe(0o700);
await store.set(CONTROLLER_CREDENTIAL, 'replaced');
expect(await store.get(CONTROLLER_CREDENTIAL)).toBe('replaced');
await store.delete(CONTROLLER_CREDENTIAL);
@@ -38,12 +40,16 @@ describe('FileSecretStore', () => {
expect(await store.get(CONTROLLER_CREDENTIAL)).toBeNull();
});
- it('refuses a secret file other users can read', async () => {
- const store = new FileSecretStore(join(dir, 'secrets'));
- await store.set(CONTROLLER_CREDENTIAL, 'credential-placeholder');
- chmodSync(join(dir, 'secrets', CONTROLLER_CREDENTIAL), 0o644);
- await expect(store.get(CONTROLLER_CREDENTIAL)).rejects.toThrow(/readable by other users/);
- });
+ // Windows has no mode bits; the data directory's access list does this there.
+ it.skipIf(process.platform === 'win32')(
+ 'refuses a secret file other users can read',
+ async () => {
+ const store = new FileSecretStore(join(dir, 'secrets'));
+ await store.set(CONTROLLER_CREDENTIAL, 'credential-placeholder');
+ chmodSync(join(dir, 'secrets', CONTROLLER_CREDENTIAL), 0o644);
+ await expect(store.get(CONTROLLER_CREDENTIAL)).rejects.toThrow(/readable by other users/);
+ }
+ );
it('says at startup that no keychain protects the credential', () => {
expect(new FileSecretStore(join(dir, 'secrets')).startupWarning()).toMatch(/No OS keychain/);
diff --git a/console/packages/agent-controller/src/secrets.ts b/console/packages/agent-controller/src/secrets.ts
index 6f3777f6c..d34980dc7 100644
--- a/console/packages/agent-controller/src/secrets.ts
+++ b/console/packages/agent-controller/src/secrets.ts
@@ -1,7 +1,8 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { chmod, mkdir, open, readFile, rename, stat, unlink } from 'node:fs/promises';
+import { chmod, mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
import { join } from 'node:path';
+import { replaceFile } from '@switch-console/agent-providers';
/** The one secret v1 keeps: the long-lived controller credential (`swcc_…`). */
export const CONTROLLER_CREDENTIAL = 'controller-credential';
@@ -41,7 +42,7 @@ export class FileSecretStore implements SecretStore {
readonly description: string;
constructor(private readonly dir: string) {
- this.description = `plaintext files in ${dir} (mode 0600)`;
+ this.description = `plaintext files in ${dir} (${process.platform === 'win32' ? 'readable by this user only' : 'mode 0600'})`;
}
startupWarning(): string {
@@ -79,7 +80,7 @@ export class FileSecretStore implements SecretStore {
} finally {
await file.close();
}
- await rename(temporary, path);
+ await replaceFile(temporary, path);
}
async delete(name: string): Promise<void> {
diff --git a/console/packages/agent-controller/src/separate-users.test.ts b/console/packages/agent-controller/src/separate-users.test.ts
index fcce906d7..b8068fb24 100644
--- a/console/packages/agent-controller/src/separate-users.test.ts
+++ b/console/packages/agent-controller/src/separate-users.test.ts
@@ -29,7 +29,8 @@ function lines(text: string): string[] {
return text.split('\n');
}
-describe('separate users', () => {
+// Linux only: systemd and Linux users.
+describe.skipIf(process.platform === 'win32')('separate users', () => {
it('names everything after the controller user’s uid', () => {
const names = separateUserNames(1001);
expect(names.group).toBe('switch-agents-1001');
diff --git a/console/packages/agent-controller/src/service.ts b/console/packages/agent-controller/src/service.ts
index 783db42bd..a691d7a09 100644
--- a/console/packages/agent-controller/src/service.ts
+++ b/console/packages/agent-controller/src/service.ts
@@ -228,6 +228,7 @@ export type ServiceState = 'running' | 'stopped' | 'not-installed';
/** Whether the service for this data directory is installed, and running. */
export async function serviceState(dataDir: string, run: CommandRunner): Promise<ServiceState> {
+ if (process.platform === 'win32') return 'not-installed';
const identity = serviceIdentity(dataDir);
const paths = servicePaths(identity, dataDir);
try {
diff --git a/console/packages/agent-controller/src/status.test.ts b/console/packages/agent-controller/src/status.test.ts
index 9d438eea0..1669caa32 100644
--- a/console/packages/agent-controller/src/status.test.ts
+++ b/console/packages/agent-controller/src/status.test.ts
@@ -1,8 +1,8 @@
-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { delimiter, join } from 'node:path';
import { generateSealingKeyPair, sealProviderLogin } from '@switch-console/agent-providers';
-import { vertexCredentialFixture } from '@switch-console/agent-providers/testing';
+import { vertexCredentialFixture, writeNodeCli } from '@switch-console/agent-providers/testing';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { silentLogger } from './log';
import { type AgentObservation, emptyObservation } from './runtime';
@@ -407,6 +407,11 @@ describe('ProviderStatuses with logins given to the machine', () => {
});
});
+/** `path` as a pattern: Windows names a CLI with PATHEXT's casing, `.CMD`. */
+function escape(path: string): string {
+ return path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
describe('PathProviderLocator', () => {
let dir: string;
beforeEach(() => {
@@ -415,13 +420,14 @@ describe('PathProviderLocator', () => {
afterEach(() => rmSync(dir, { recursive: true, force: true }));
it('finds a CLI by the plugin’s binary names, and reads its version', async () => {
- const script = join(dir, 'cursor-agent');
- writeFileSync(script, '#!/bin/sh\necho "2026.01.15-abc"\n');
- chmodSync(script, 0o755);
+ const script = await writeNodeCli(dir, 'cursor-agent', 'console.log("2026.01.15-abc")');
writeFileSync(join(dir, 'claude'), 'not executable');
- const locator = new PathProviderLocator(`/nonexistent:${dir}`, join(dir, 'probe-home'));
+ const locator = new PathProviderLocator(
+ ['/nonexistent', dir].join(delimiter),
+ join(dir, 'probe-home')
+ );
expect(await locator.locate('cursor')).toEqual({
- path: script,
+ path: expect.stringMatching(new RegExp(`^${escape(script)}$`, 'i')),
version: '2026.01.15-abc',
versionProblem: null,
});
@@ -430,19 +436,26 @@ describe('PathProviderLocator', () => {
});
it('reads the version of a CLI that writes in its home first, with a home of its own', async () => {
- const script = join(dir, 'opencode');
- writeFileSync(
- script,
- '#!/bin/sh\nmkdir -p "$XDG_DATA_HOME/opencode" "$HOME/.cache" || exit 1\necho 1.18.35\n'
+ const script = await writeNodeCli(
+ dir,
+ 'opencode',
+ `const { mkdirSync } = require('node:fs');
+ const { join } = require('node:path');
+ mkdirSync(join(process.env.XDG_DATA_HOME, 'opencode'), { recursive: true });
+ mkdirSync(join(process.env.HOME, '.cache'), { recursive: true });
+ console.log('1.18.35');`
);
- chmodSync(script, 0o755);
const previous = process.env.HOME;
process.env.HOME = '/nonexistent';
try {
const located = await new PathProviderLocator(dir, join(dir, 'probe-home')).locate(
'opencode'
);
- expect(located).toEqual({ path: script, version: '1.18.35', versionProblem: null });
+ expect(located).toEqual({
+ path: expect.stringMatching(new RegExp(`^${escape(script)}$`, 'i')),
+ version: '1.18.35',
+ versionProblem: null,
+ });
} finally {
process.env.HOME = previous;
}
@@ -457,12 +470,14 @@ describe('a CLI whose version cannot be read', () => {
afterEach(() => rmSync(dir, { recursive: true, force: true }));
it('says why, so the report can carry it', async () => {
- const script = join(dir, 'opencode');
- writeFileSync(script, '#!/bin/sh\necho "EROFS: read-only file system" >&2\nexit 1\n');
- chmodSync(script, 0o755);
+ const script = await writeNodeCli(
+ dir,
+ 'opencode',
+ 'console.error("EROFS: read-only file system"); process.exit(1);'
+ );
const located = await new PathProviderLocator(dir, join(dir, 'probe-home')).locate('opencode');
expect(located).toEqual({
- path: script,
+ path: expect.stringMatching(new RegExp(`^${escape(script)}$`, 'i')),
version: null,
versionProblem: 'exited 1: EROFS: read-only file system',
});
diff --git a/console/packages/agent-controller/src/status.ts b/console/packages/agent-controller/src/status.ts
index d7beba8b8..737e2c869 100644
--- a/console/packages/agent-controller/src/status.ts
+++ b/console/packages/agent-controller/src/status.ts
@@ -1,10 +1,12 @@
-import { execFile } from 'node:child_process';
-import { constants } from 'node:fs';
-import { access, mkdir, statfs } from 'node:fs/promises';
+import { mkdir, statfs } from 'node:fs/promises';
import { arch, freemem, platform, release, totalmem } from 'node:os';
-import { delimiter, join } from 'node:path';
-import { promisify } from 'node:util';
-import type { ProviderReadiness } from '@switch-console/agent-providers';
+import { join } from 'node:path';
+import {
+ execProvider,
+ findOnPath,
+ type ProviderReadiness,
+ providerUnsupportedReason,
+} from '@switch-console/agent-providers';
import { pluginRegistry } from '@switch-console/plugins/agents';
import { errorMessage, type Logger } from './log';
import type { AgentObservation, AgentRuntime } from './runtime';
@@ -72,26 +74,17 @@ export class PathProviderLocator implements ProviderLocator {
const plugin = pluginRegistry.get(provider);
if (!plugin) throw new Error(`No provider plugin is registered for '${provider}'.`);
const dependency = plugin.capabilities.hostDependency;
- const directories = (this.path ?? '').split(delimiter).filter(Boolean);
- for (const name of dependency.binaryNames)
- for (const directory of directories) {
- const candidate = join(directory, name);
- try {
- await access(candidate, constants.X_OK);
- } catch {
- continue;
- }
- if (dependency.skipVersionProbe)
- return { path: candidate, version: null, versionProblem: null };
- return {
- path: candidate,
- ...(await readVersion(
- candidate,
- dependency.versionArgs ?? ['--version'],
- this.probeHome
- )),
- };
- }
+ if (providerUnsupportedReason(provider, process.platform) !== null) return null;
+ for (const name of dependency.binaryNames) {
+ const candidate = await findOnPath(name, this.path);
+ if (candidate === null) continue;
+ if (dependency.skipVersionProbe)
+ return { path: candidate, version: null, versionProblem: null };
+ return {
+ path: candidate,
+ ...(await readVersion(candidate, dependency.versionArgs ?? ['--version'], this.probeHome)),
+ };
+ }
return null;
}
}
@@ -104,7 +97,7 @@ async function readVersion(
): Promise<{ version: string | null; versionProblem: string | null }> {
try {
await mkdir(home, { recursive: true, mode: 0o700 });
- const { stdout, stderr } = await promisify(execFile)(binary, args, {
+ const { stdout, stderr } = await execProvider(binary, args, {
timeout: VERSION_TIMEOUT_MS,
env: {
...process.env,
diff --git a/console/packages/agent-controller/src/systemd-runtime.test.ts b/console/packages/agent-controller/src/systemd-runtime.test.ts
index 9ea179a6f..59d58bfd6 100644
--- a/console/packages/agent-controller/src/systemd-runtime.test.ts
+++ b/console/packages/agent-controller/src/systemd-runtime.test.ts
@@ -128,7 +128,8 @@ afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
-describe('SystemdRuntime', () => {
+// Linux only: systemd and Linux users.
+describe.skipIf(process.platform === 'win32')('SystemdRuntime', () => {
it('runs an agent as the first free agent user, from files the unit loads', async () => {
const cwd = await start('agent-1');
const root = join(config.agentsDir, '01');
@@ -297,7 +298,8 @@ describe('SystemdRuntime', () => {
});
});
-describe('environmentLine', () => {
+// Linux only: systemd and Linux users.
+describe.skipIf(process.platform === 'win32')('environmentLine', () => {
it('quotes a value so systemd reads it back as is', () => {
expect(environmentLine('KEY', 'a b$c"d')).toBe(`KEY='a b$c"d'`);
expect(environmentLine('KEY', `it's $x "y" \\z`)).toBe(`KEY="it's \\$x \\"y\\" \\\\z"`);
diff --git a/console/packages/agent-providers/src/acp/acp-adapter.test.ts b/console/packages/agent-providers/src/acp/acp-adapter.test.ts
index 5416a0df6..ce82e2e1d 100644
--- a/console/packages/agent-providers/src/acp/acp-adapter.test.ts
+++ b/console/packages/agent-providers/src/acp/acp-adapter.test.ts
@@ -1,4 +1,5 @@
import type * as fs from 'node:fs/promises';
+import { pathToFileURL } from 'node:url';
import { beforeEach, expect, it, vi } from 'vitest';
import { ProviderConversationUnavailableError } from '../adapter';
import { FakeAppServer } from '../codex/fake-app-server';
@@ -154,7 +155,7 @@ it('sends attachments as the agent advertises it can take them, else as resource
]);
expect(prompt[2]).toEqual({
type: 'resource_link',
- uri: 'file:///work/notes.txt',
+ uri: pathToFileURL('/work/notes.txt').href,
name: 'notes.txt',
mimeType: 'text/plain',
});
@@ -174,7 +175,11 @@ it('embeds file contents when the agent takes embedded context', async () => {
>;
expect(prompt[1]).toEqual({
type: 'resource',
- resource: { uri: 'file:///work/notes.txt', mimeType: 'text/plain', text: 'file text' },
+ resource: {
+ uri: pathToFileURL('/work/notes.txt').href,
+ mimeType: 'text/plain',
+ text: 'file text',
+ },
});
});
diff --git a/console/packages/agent-providers/src/acp/hooks.ts b/console/packages/agent-providers/src/acp/hooks.ts
index 0465a11ae..3256334fc 100644
--- a/console/packages/agent-providers/src/acp/hooks.ts
+++ b/console/packages/agent-providers/src/acp/hooks.ts
@@ -102,6 +102,8 @@ export interface AcpProviderHooks {
* common vendor keys are already passed through for every provider.
*/
inheritEnv?: readonly string[];
+ /** The platforms the agent cannot run on, each with the reason a person is told. */
+ unsupportedPlatforms?: Partial<Record<NodeJS.Platform, string>>;
/**
* Whether the CLI is signed in, answered without signing it in: a check
* must never be what changes its answer. `handshake` runs the agent and
diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts
index 5a2c40378..04c0f6bdd 100644
--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts
+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts
@@ -22,6 +22,9 @@ export const antigravityAcp: AcpProviderHooks = {
},
launch: antigravityLaunch,
loginCommand: 'antigravity-acp --login',
+ unsupportedPlatforms: {
+ win32: 'Antigravity ACP has no Windows build, so it cannot run on Windows.',
+ },
// `authMethods` is the agent's own answer: the sign-ins it still wants.
// Calling `authenticate` here would not test the sign-in but perform it,
// opening a browser.
diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.ts
index 827830ada..f9fa3a5b3 100644
--- a/console/packages/agent-providers/src/claude/claude-adapter.ts
+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { accessSync, constants } from 'node:fs';
+import { accessSync, constants, existsSync } from 'node:fs';
import { access, readdir, readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { delimiter, join } from 'node:path';
@@ -15,8 +15,14 @@ import type {
SDKMessage,
SDKResultMessage,
SDKUserMessage,
+ SpawnedProcess,
+ SpawnOptions,
} from '@anthropic-ai/claude-agent-sdk';
import type { ModelChoice } from '@switch-console/shared/session-v1';
+import {
+ getWindowsEnvValue,
+ resolveWindowsCommandPath,
+} from '@switch-console/shared/windows-spawn';
import type {
ModelSelection,
ProviderAdapter,
@@ -42,6 +48,7 @@ import type {
UserInputAnswers,
UserInputQuestion,
} from '../events';
+import { spawnProvider, stopProvider } from '../provider-process';
import { CumulativeUsage, mergeUsage } from '../usage';
import {
approvalContent,
@@ -285,6 +292,14 @@ export function resolveClaudeExecutable(
env: Record<string, string>
): string | undefined {
if (configured !== undefined) return configured;
+ if (process.platform === 'win32') {
+ const onPath = resolveWindowsCommandPath({ command: 'claude', env, fileExists: existsSync });
+ if (onPath) return onPath;
+ // Where Claude Code's own installer puts it on Windows.
+ const profile = getWindowsEnvValue(env, 'USERPROFILE');
+ const installed = profile ? join(profile, '.local', 'bin', 'claude.exe') : null;
+ return installed && existsSync(installed) ? installed : undefined;
+ }
const candidates: string[] = [];
for (const dir of (env.PATH ?? '').split(delimiter)) {
if (dir.length > 0) candidates.push(join(dir, 'claude'));
@@ -301,6 +316,26 @@ export function resolveClaudeExecutable(
return undefined;
}
+/**
+ * Starts Claude Code for the SDK on Windows through `spawnProvider`, which can
+ * start the `claude.cmd` an npm install leaves. The SDK aborts `signal` once
+ * its own graceful close (stdin closed, then a grace period) has run; the
+ * CLI's whole tree goes then, `cmd.exe` and all.
+ */
+function spawnClaudeOnWindows(
+ options: SpawnOptions,
+ onStderr: (data: string) => void
+): SpawnedProcess {
+ const child = spawnProvider(options.command, options.args, {
+ cwd: options.cwd,
+ env: options.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ child.stderr?.on('data', (chunk: Buffer) => onStderr(chunk.toString('utf8')));
+ options.signal.addEventListener('abort', () => stopProvider(child, 'SIGTERM'), { once: true });
+ return child as SpawnedProcess;
+}
+
function effortFrom(model: ModelSelection | undefined): EffortLevel | undefined {
const raw = model?.options?.effort;
return EFFORT_LEVELS.find((level) => level === raw);
@@ -424,6 +459,15 @@ export class ClaudeAdapter implements ProviderAdapter {
canUseTool: this.makeCanUseTool(input.sessionId),
...(permissionMode === 'bypassPermissions' ? { allowDangerouslySkipPermissions: true } : {}),
...(executable ? { pathToClaudeCodeExecutable: executable } : {}),
+ // An npm install is `claude.cmd` on Windows, which the SDK cannot start itself.
+ ...(process.platform === 'win32'
+ ? {
+ spawnClaudeCodeProcess: (spawnOptions: SpawnOptions) =>
+ spawnClaudeOnWindows(spawnOptions, (data) =>
+ this.logger?.debug('claude stderr', { sessionId: input.sessionId, data })
+ ),
+ }
+ : {}),
...(input.agentName ? { agent: input.agentName } : {}),
...(input.agentName && input.agentDefinition
? { agents: { [input.agentName]: input.agentDefinition } }
diff --git a/console/packages/agent-providers/src/claude/sign-in.ts b/console/packages/agent-providers/src/claude/sign-in.ts
index 9536c9c2f..5789ad41b 100644
--- a/console/packages/agent-providers/src/claude/sign-in.ts
+++ b/console/packages/agent-providers/src/claude/sign-in.ts
@@ -1,6 +1,5 @@
-import { execFile } from 'node:child_process';
-import { promisify } from 'node:util';
import { z } from 'zod';
+import { execProvider } from '../provider-process';
import {
commandOutput,
readiness,
@@ -27,7 +26,7 @@ export async function checkClaudeSignIn(input: SignInCheckInput): Promise<Provid
let output: string;
try {
output = (
- await promisify(execFile)(input.binaryPath, ['auth', 'status'], {
+ await execProvider(input.binaryPath, ['auth', 'status'], {
cwd: input.cwd,
env: input.env,
timeout: 15000,
diff --git a/console/packages/agent-providers/src/codex/home.ts b/console/packages/agent-providers/src/codex/home.ts
index 0d2da09c4..8d51c80cb 100644
--- a/console/packages/agent-providers/src/codex/home.ts
+++ b/console/packages/agent-providers/src/codex/home.ts
@@ -1,8 +1,9 @@
import { createHash, randomUUID } from 'node:crypto';
-import { chmod, copyFile, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import { chmod, copyFile, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { parse, stringify } from 'smol-toml';
import { linkHomeAsset, linkSkills, optionalText } from '../host/provider-home';
+import { replaceFile } from '../host/replace-file';
/**
* A managed agent's Codex configuration with the sandbox its sessions run
@@ -71,7 +72,7 @@ async function replacePrivateFile(path: string, value: string): Promise<void> {
const temporary = `${path}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, value, { mode: 0o600, flag: 'wx' });
- await rename(temporary, path);
+ await replaceFile(temporary, path);
} finally {
await rm(temporary, { force: true });
}
diff --git a/console/packages/agent-providers/src/cursor/cursor-adapter.ts b/console/packages/agent-providers/src/cursor/cursor-adapter.ts
index edf319fc5..31338c949 100644
--- a/console/packages/agent-providers/src/cursor/cursor-adapter.ts
+++ b/console/packages/agent-providers/src/cursor/cursor-adapter.ts
@@ -1,9 +1,8 @@
-import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { promisify } from 'node:util';
import { createAcpAdapter, type AcpAdapter } from '../acp/acp-adapter';
import type { AcpAdapterOptions, AcpProviderHooks, AcpSessionContext } from '../acp/hooks';
import type { ItemType } from '../events';
+import { execProvider } from '../provider-process';
import { commandOutput, readiness, signInWith, type ProviderReadiness } from '../readiness';
const CURSOR_LOGIN = 'agent login';
@@ -117,7 +116,7 @@ export const cursorAcp: AcpProviderHooks = {
let output: string;
try {
output = (
- await promisify(execFile)(binaryPath, ['about'], {
+ await execProvider(binaryPath, ['about'], {
cwd,
env,
timeout: 15000,
diff --git a/console/packages/agent-providers/src/host/agent-env.ts b/console/packages/agent-providers/src/host/agent-env.ts
index 9bdccf411..fb4a2a003 100644
--- a/console/packages/agent-providers/src/host/agent-env.ts
+++ b/console/packages/agent-providers/src/host/agent-env.ts
@@ -64,10 +64,40 @@ export const AGENT_ENV_VARS = [
'XAI_API_KEY',
] as const;
+/**
+ * What Windows itself, Node and the provider CLIs need there to find the
+ * user's profile, the system and a temporary directory. None is set on macOS
+ * or Linux.
+ */
+const WINDOWS_ENV = [
+ 'APPDATA',
+ 'COMSPEC',
+ 'COMMONPROGRAMFILES',
+ 'HOMEDRIVE',
+ 'HOMEPATH',
+ 'LOCALAPPDATA',
+ 'NUMBER_OF_PROCESSORS',
+ 'OS',
+ 'PATHEXT',
+ 'PROCESSOR_ARCHITECTURE',
+ 'PROGRAMDATA',
+ 'PROGRAMFILES',
+ 'PROGRAMFILES(X86)',
+ 'SYSTEMDRIVE',
+ 'SYSTEMROOT',
+ 'TEMP',
+ 'TMP',
+ 'USERDOMAIN',
+ 'USERNAME',
+ 'USERPROFILE',
+ 'WINDIR',
+];
+
/**
* What a session host's `execution.inheritEnv` names: the provider variables
* above, those each registered provider's runtime asks for, and the basics a
- * CLI needs to find itself, its home and its terminal.
+ * CLI needs to find itself, its home and its terminal. Matched without regard
+ * to case on Windows, where `Path` and `PATH` are one variable.
* Console and the headless agents controller both launch hosts with it.
*/
export const EXECUTION_INHERIT_ENV: readonly string[] = [
@@ -80,4 +110,5 @@ export const EXECUTION_INHERIT_ENV: readonly string[] = [
'LANG',
'TERM',
'SSH_AUTH_SOCK',
+ ...WINDOWS_ENV,
];
diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.ts
index 6cfd9edd8..fcf987904 100644
--- a/console/packages/agent-providers/src/host/agent-host.ts
+++ b/console/packages/agent-providers/src/host/agent-host.ts
@@ -1341,11 +1341,20 @@ export async function runAgentHost(
}
}
};
+ // A turn ending while the definition is being applied is not lost: the
+ // pass is run again once the one under way is done.
+ let again = false;
const redefine = () => {
- if (redefining) return;
+ if (redefining) {
+ again = true;
+ return;
+ }
redefining = true;
pending = pending.then(applyDefinition).finally(() => {
redefining = false;
+ if (!again) return;
+ again = false;
+ redefine();
});
void pending.catch((error: Error) => fail(error));
};
diff --git a/console/packages/agent-providers/src/host/attachments.ts b/console/packages/agent-providers/src/host/attachments.ts
index 54b706ba4..f2332e396 100644
--- a/console/packages/agent-providers/src/host/attachments.ts
+++ b/console/packages/agent-providers/src/host/attachments.ts
@@ -1,9 +1,10 @@
import { createHash, randomUUID } from 'node:crypto';
-import { mkdir, readFile, rename, open, realpath, unlink, lstat } from 'node:fs/promises';
+import { mkdir, readFile, open, realpath, unlink, lstat } from 'node:fs/promises';
import { basename, join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import type { Attachment } from '@switch-console/shared/session-v1';
import type { TurnAttachment } from '../adapter';
+import { replaceFile } from './replace-file';
export const ATTACHMENT_MIME_TYPES = [
'image/png',
@@ -95,16 +96,19 @@ export async function stageAttachment(
await file.close();
}
try {
- await rename(temporary, path);
+ await replaceFile(temporary, path);
} catch (error) {
await unlink(temporary);
throw error;
}
- const parent = await open(directory, 'r');
- try {
- await parent.sync();
- } finally {
- await parent.close();
+ // Windows cannot open a directory to flush it, and records the rename itself.
+ if (process.platform !== 'win32') {
+ const parent = await open(directory, 'r');
+ try {
+ await parent.sync();
+ } finally {
+ await parent.close();
+ }
}
}
return { path, mimeType: attachment.mimeType };
diff --git a/console/packages/agent-providers/src/host/control.ts b/console/packages/agent-providers/src/host/control.ts
index b84a51629..c0e20e6e7 100644
--- a/console/packages/agent-providers/src/host/control.ts
+++ b/console/packages/agent-providers/src/host/control.ts
@@ -1,5 +1,5 @@
import { randomBytes } from 'node:crypto';
-import { rename, rm, writeFile } from 'node:fs/promises';
+import { rm, writeFile } from 'node:fs/promises';
import { createServer, type Socket } from 'node:net';
import { join } from 'node:path';
import type { Duplex } from 'node:stream';
@@ -12,6 +12,7 @@ import {
} from './attachment-transfers';
import { readJournalSnapshot } from './journal-snapshot';
import { ensureSharedProcess, liveSupervisor, sharedSessionRoot, type Supervision } from './launch';
+import { replaceFile } from './replace-file';
import {
SessionHostFailedError,
sessionRequestSchema,
@@ -296,7 +297,7 @@ export async function serveControl(
const path = join(root, CONTROL_FILE);
const temporary = `${path}.${token.slice(0, 8)}.tmp`;
await writeFile(temporary, JSON.stringify({ port: address.port, token }), { mode: 0o600 });
- await rename(temporary, path);
+ await replaceFile(temporary, path);
try {
await new Promise<void>((resolve) => {
if (signal.aborted) resolve();
diff --git a/console/packages/agent-providers/src/host/hosted-provider.test.ts b/console/packages/agent-providers/src/host/hosted-provider.test.ts
index ad85dff52..213689cbe 100644
--- a/console/packages/agent-providers/src/host/hosted-provider.test.ts
+++ b/console/packages/agent-providers/src/host/hosted-provider.test.ts
@@ -36,7 +36,7 @@ it('preserves a native token refresh until the owner replaces the source credent
'fixture-cli'
);
const path = join(env.CODEX_HOME!, 'auth.json');
- expect((await stat(path)).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32') expect((await stat(path)).mode & 0o777).toBe(0o600);
await writeFile(path, '{"tokens":{"access_token":"fixture-refreshed"}}');
await materializeHostedProvider(
root,
@@ -132,8 +132,9 @@ it('writes a Vertex AI login’s Google credential under the root, and signs Cla
CLOUD_ML_REGION: 'global',
GOOGLE_APPLICATION_CREDENTIALS: path,
});
- expect((await stat(path)).mode & 0o777).toBe(0o600);
- expect((await stat(join(root, 'provider-home'))).mode & 0o777).toBe(0o700);
+ if (process.platform !== 'win32') expect((await stat(path)).mode & 0o777).toBe(0o600);
+ if (process.platform !== 'win32')
+ expect((await stat(join(root, 'provider-home'))).mode & 0o777).toBe(0o700);
expect(JSON.parse(await readFile(path, 'utf8'))).toEqual(SERVICE_ACCOUNT_KEY_FIXTURE);
await materializeHostedProvider(root, env, vertex(AUTHORIZED_USER_FIXTURE), 'fixture-cli');
diff --git a/console/packages/agent-providers/src/host/hosted-provider.ts b/console/packages/agent-providers/src/host/hosted-provider.ts
index 0d98d00e8..2c287c582 100644
--- a/console/packages/agent-providers/src/host/hosted-provider.ts
+++ b/console/packages/agent-providers/src/host/hosted-provider.ts
@@ -1,11 +1,12 @@
import { createHash } from 'node:crypto';
import { constants } from 'node:fs';
-import { lstat, mkdir, open, readFile, rename } from 'node:fs/promises';
+import { lstat, mkdir, open, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { refreshCodexAuthentication } from '../codex/home';
import { parseVertexLogin, VERTEX_CREDENTIALS_FILE } from '../vertex-login';
import { importOpenCodeConsole } from './opencode-console';
import type { HostedCredential } from './provider-login';
+import { replaceFile } from './replace-file';
export type { HostedCredential } from './provider-login';
@@ -93,7 +94,7 @@ async function writeAuthentication(root: string, relative: string, content: stri
} finally {
await file.close();
}
- await rename(temporary, path);
+ await replaceFile(temporary, path);
const record = await open(
marker,
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
diff --git a/console/packages/agent-providers/src/host/launch.test.ts b/console/packages/agent-providers/src/host/launch.test.ts
index f2555e4bc..4fd99a6a1 100644
--- a/console/packages/agent-providers/src/host/launch.test.ts
+++ b/console/packages/agent-providers/src/host/launch.test.ts
@@ -5,10 +5,37 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, expect, it, vi } from 'vitest';
import { detachedSupervision, ensureSharedProcess, inProcessSupervision } from './launch';
+import { killProcessTree } from './process-fence';
import { SessionLinks } from './session-channel';
import { owedSessionStart, type HostStartSource } from './session-start';
import type { SharedHostConfig } from './shared-config';
+if (process.platform === 'win32') vi.setConfig({ testTimeout: 60_000 });
+
+/**
+ * Script for a stand-in host that runs `then` when asked to stop, as a real
+ * one does: on SIGTERM, or on Windows when its stop file appears in `root`.
+ */
+function onStop(root: string, then: string): string {
+ return `{
+ const stop = () => { ${then} };
+ process.on('SIGTERM', stop);
+ const file = require('node:path').join(${JSON.stringify(root)}, '.stop-' + process.pid);
+ const poll = setInterval(() => {
+ if (require('node:fs').existsSync(file)) { clearInterval(poll); stop(); }
+ }, 50);
+ }`;
+}
+
+/** Ends what a test started, the process and what it started. */
+async function cleanUp(pid: number | undefined): Promise<void> {
+ if (!pid) return;
+ try {
+ if (process.platform === 'win32') await killProcessTree(pid);
+ else process.kill(-pid, 'SIGKILL');
+ } catch {}
+}
+
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
@@ -63,40 +90,37 @@ async function fixture() {
it('refuses to replace missing conversation state with a fresh session', async () => {
await expect(ensureSharedProcess(await fixture())).rejects.toThrow('no saved SDK conversation');
});
-it.skipIf(process.platform === 'win32')(
- 'waits for the old owner to exit before starting its replacement',
- async () => {
- const input = await fixture();
- await writeFile(join(input.root, 'config.json'), JSON.stringify(input.config));
- await writeFile(
- input.entrypoint,
- `const fs=require('node:fs');fs.appendFileSync(process.argv[2]+'/trace','new\\n');`
- );
- const old = spawn(
- process.execPath,
- [
- '-e',
- `const fs=require('node:fs');const root=process.argv[1];fs.writeFileSync(root+'/shared-owner.lock',JSON.stringify({pid:process.pid}));process.on('SIGTERM',()=>{setTimeout(()=>{fs.appendFileSync(root+'/trace','old-stopped\\n');process.exit(0)},200)});console.log('ready');setInterval(()=>{},1000);`,
- input.root,
- ],
- { stdio: ['ignore', 'pipe', 'pipe'] }
+it('waits for the old owner to exit before starting its replacement', async () => {
+ const input = await fixture();
+ await writeFile(join(input.root, 'config.json'), JSON.stringify(input.config));
+ await writeFile(
+ input.entrypoint,
+ `const fs=require('node:fs');fs.appendFileSync(process.argv[2]+'/trace','new\\n');`
+ );
+ const old = spawn(
+ process.execPath,
+ [
+ '-e',
+ `const fs=require('node:fs');const root=process.argv[1];fs.writeFileSync(root+'/shared-owner.lock',JSON.stringify({pid:process.pid}));${onStop(input.root, "setTimeout(()=>{fs.appendFileSync(root+'/trace','old-stopped\\n');process.exit(0)},200)")};console.log('ready');setInterval(()=>{},1000);`,
+ input.root,
+ ],
+ { stdio: ['ignore', 'pipe', 'pipe'] }
+ );
+ try {
+ await once(old.stdout!, 'data');
+ const exit = once(old, 'exit');
+ await ensureSharedProcess(input);
+ await exit;
+ await expect
+ .poll(async () => readFile(join(input.root, 'trace'), 'utf8'))
+ .toBe('old-stopped\nnew\n');
+ expect(JSON.parse(await readFile(join(input.root, 'config.json'), 'utf8')).session).toEqual(
+ input.config.session
);
- try {
- await once(old.stdout!, 'data');
- const exit = once(old, 'exit');
- await ensureSharedProcess(input);
- await exit;
- await expect
- .poll(async () => readFile(join(input.root, 'trace'), 'utf8'))
- .toBe('old-stopped\nnew\n');
- expect(JSON.parse(await readFile(join(input.root, 'config.json'), 'utf8')).session).toEqual(
- input.config.session
- );
- } finally {
- if (old.exitCode === null) old.kill('SIGKILL');
- }
+ } finally {
+ if (old.exitCode === null) old.kill('SIGKILL');
}
-);
+});
it('refreshes renamed agent configuration without changing the saved session', async () => {
const input = await fixture();
@@ -138,79 +162,78 @@ it('gives a controller the connection it was asked for rather than the one on di
expect(saved.roomConnection).toEqual({ connectionId: 'derived-from-the-agent' });
});
-it.skipIf(process.platform === 'win32')(
- 'replaces a supervisor an earlier deployment left running',
- async () => {
- const input = await fixture();
- input.restart = false;
- await writeFile(join(input.root, 'config.json'), JSON.stringify(input.config));
+it('replaces a supervisor an earlier deployment left running', async () => {
+ const input = await fixture();
+ input.restart = false;
+ await writeFile(join(input.root, 'config.json'), JSON.stringify(input.config));
+ await writeFile(
+ input.entrypoint,
+ `const fs=require('node:fs');fs.appendFileSync(process.argv[2]+'/trace','new\\n');`
+ );
+ await mkdir(join(input.root, 'supervisor'));
+ const old = spawn(
+ process.execPath,
+ [
+ '-e',
+ `${onStop(input.root, 'process.exit(0)')};console.log('ready');setInterval(()=>{},1000);`,
+ input.root,
+ ],
+ { stdio: ['ignore', 'pipe', 'pipe'] }
+ );
+ try {
+ await once(old.stdout!, 'data');
await writeFile(
- input.entrypoint,
- `const fs=require('node:fs');fs.appendFileSync(process.argv[2]+'/trace','new\\n');`
- );
- await mkdir(join(input.root, 'supervisor'));
- const old = spawn(
- process.execPath,
- ['-e', `console.log('ready');setInterval(()=>{},1000);`, input.root],
- { stdio: ['ignore', 'pipe', 'pipe'] }
+ join(input.root, 'supervisor', 'owner.json'),
+ JSON.stringify({
+ pid: old.pid,
+ build: join(input.root, 'superseded.cjs'),
+ })
);
- try {
- await once(old.stdout!, 'data');
- await writeFile(
- join(input.root, 'supervisor', 'owner.json'),
- JSON.stringify({
- pid: old.pid,
- build: join(input.root, 'superseded.cjs'),
- })
- );
- const exit = once(old, 'exit');
- expect(await ensureSharedProcess(input)).toEqual({ created: false });
- await exit;
- await expect.poll(async () => readFile(join(input.root, 'trace'), 'utf8')).toBe('new\n');
- } finally {
- if (old.exitCode === null) old.kill('SIGKILL');
- }
+ const exit = once(old, 'exit');
+ expect(await ensureSharedProcess(input)).toEqual({ created: false });
+ await exit;
+ await expect.poll(async () => readFile(join(input.root, 'trace'), 'utf8')).toBe('new\n');
+ } finally {
+ if (old.exitCode === null) old.kill('SIGKILL');
}
-);
+});
-it.skipIf(process.platform === 'win32')(
- 'leaves a supervisor running the deployed build alone',
- async () => {
- const input = await fixture();
- input.restart = false;
- await writeFile(join(input.root, 'config.json'), JSON.stringify(input.config));
+it('leaves a supervisor running the deployed build alone', async () => {
+ const input = await fixture();
+ input.restart = false;
+ await writeFile(join(input.root, 'config.json'), JSON.stringify(input.config));
+ await writeFile(
+ input.entrypoint,
+ `const fs=require('node:fs');fs.appendFileSync(process.argv[2]+'/trace','new\\n');`
+ );
+ await mkdir(join(input.root, 'supervisor'));
+ const running = spawn(
+ process.execPath,
+ ['-e', `console.log('ready');setInterval(()=>{},1000);`, input.root],
+ { stdio: ['ignore', 'pipe', 'pipe'] }
+ );
+ try {
+ await once(running.stdout!, 'data');
await writeFile(
- input.entrypoint,
- `const fs=require('node:fs');fs.appendFileSync(process.argv[2]+'/trace','new\\n');`
- );
- await mkdir(join(input.root, 'supervisor'));
- const running = spawn(
- process.execPath,
- ['-e', `console.log('ready');setInterval(()=>{},1000);`, input.root],
- { stdio: ['ignore', 'pipe', 'pipe'] }
+ join(input.root, 'supervisor', 'owner.json'),
+ JSON.stringify({ pid: running.pid, build: input.supervision.build })
);
- try {
- await once(running.stdout!, 'data');
- await writeFile(
- join(input.root, 'supervisor', 'owner.json'),
- JSON.stringify({ pid: running.pid, build: input.supervision.build })
- );
- expect(await ensureSharedProcess(input)).toEqual({ created: false });
- expect(running.exitCode).toBeNull();
- await expect(readFile(join(input.root, 'trace'))).rejects.toMatchObject({
- code: 'ENOENT',
- });
- } finally {
- if (running.exitCode === null) running.kill('SIGKILL');
- }
+ expect(await ensureSharedProcess(input)).toEqual({ created: false });
+ expect(running.exitCode).toBeNull();
+ await expect(readFile(join(input.root, 'trace'))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ } finally {
+ if (running.exitCode === null) running.kill('SIGKILL');
}
-);
+});
it('stops the hosts it supervises in-process when closed, and starts no more', async () => {
const { root, entrypoint } = await fixture();
await writeFile(
entrypoint,
`require('node:fs').writeFileSync(process.argv[2] + '/pid', String(process.pid));
+ process.on('message', (m) => { if (m && m.kind === 'switch-stop') process.exit(0); });
setInterval(() => {}, 1000);`
);
const supervision = inProcessSupervision(entrypoint, new SessionLinks());
@@ -307,47 +330,41 @@ it('starts the session anyway when its start cannot be recorded', async () => {
warn.mockRestore();
});
-it.skipIf(process.platform === 'win32')(
- 'kills a host that will not stop for its replacement, with the session hosts under it',
- async () => {
- // The case that blocked an update: an old watcher waiting forever on a
- // session host that had hung up, so SIGTERM never finished and every
- // replacement gave up with "has not stopped".
- const root = await mkdtemp(join(tmpdir(), 'stop-owned-'));
- const grandchildPid = join(root, 'grandchild.pid');
- const stubborn = spawn(
- process.execPath,
- [
- '-e',
- `process.on('SIGTERM', () => {});
+it('kills a host that will not stop for its replacement, with the session hosts under it', async () => {
+ // The case that blocked an update: an old watcher waiting forever on a
+ // session host that had hung up, so SIGTERM never finished and every
+ // replacement gave up with "has not stopped".
+ const root = await mkdtemp(join(tmpdir(), 'stop-owned-'));
+ const grandchildPid = join(root, 'grandchild.pid');
+ const stubborn = spawn(
+ process.execPath,
+ [
+ '-e',
+ `process.on('SIGTERM', () => {});
const child = require('node:child_process').spawn(process.execPath,
['-e', 'process.on("SIGTERM", () => {}); setInterval(() => {}, 1000)'],
{ detached: true, stdio: 'ignore' });
require('node:fs').writeFileSync(process.argv[1] + '/grandchild.pid', String(child.pid));
setInterval(() => {}, 1000);`,
- // On its command line, which is how the stop confirms the pid is still its host.
- root,
- ],
- { detached: true, stdio: 'ignore' }
- );
- try {
- let pid = 0;
- for (let attempt = 0; attempt < 100 && !pid; attempt++) {
- pid = Number(await readFile(grandchildPid, 'utf8').catch(() => '0'));
- if (!pid) await new Promise((resolve) => setTimeout(resolve, 50));
- }
- await writeFile(join(root, 'shared-owner.lock'), JSON.stringify({ pid: stubborn.pid }));
+ // On its command line, which is how the stop confirms the pid is still its host.
+ root,
+ ],
+ { detached: true, stdio: 'ignore' }
+ );
+ try {
+ let pid = 0;
+ for (let attempt = 0; attempt < 100 && !pid; attempt++) {
+ pid = Number(await readFile(grandchildPid, 'utf8').catch(() => '0'));
+ if (!pid) await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ await writeFile(join(root, 'shared-owner.lock'), JSON.stringify({ pid: stubborn.pid }));
- await detachedSupervision('bundle.mjs').stop(root);
+ await detachedSupervision('bundle.mjs').stop(root);
- expect(() => process.kill(stubborn.pid!, 0)).toThrow();
- expect(() => process.kill(pid, 0)).toThrow();
- } finally {
- try {
- process.kill(-stubborn.pid!, 'SIGKILL');
- } catch {}
- await rm(root, { recursive: true, force: true });
- }
- },
- 40_000
-);
+ expect(() => process.kill(stubborn.pid!, 0)).toThrow();
+ expect(() => process.kill(pid, 0)).toThrow();
+ } finally {
+ await cleanUp(stubborn.pid);
+ await rm(root, { recursive: true, force: true });
+ }
+}, 60_000);
diff --git a/console/packages/agent-providers/src/host/launch.ts b/console/packages/agent-providers/src/host/launch.ts
index d39bed82a..62babca05 100644
--- a/console/packages/agent-providers/src/host/launch.ts
+++ b/console/packages/agent-providers/src/host/launch.ts
@@ -1,15 +1,15 @@
-import { execFile, spawn } from 'node:child_process';
+import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { link, mkdir, open, readFile, unlink } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
-import { promisify } from 'node:util';
import { replaceOwner, withOwnershipLock } from './ownership-lock';
-import { killProcessTree } from './process-fence';
+import { commandLineNames, killProcessTree, processCommandLine } from './process-fence';
import type { SessionLinks } from './session-channel';
import { recordSessionStart, type HostStartSource } from './session-start';
import { sharedConfigSchema, type SharedHostConfig } from './shared-config';
+import { requestStop } from './stop-request';
import { superviseSharedHost } from './supervisor';
export function sharedSessionsBase(): string {
@@ -71,6 +71,7 @@ export function detachedSupervision(entrypoint: string): Supervision {
[entrypoint, root, configPath, watcher ? '--watch-supervise' : '--supervise'],
{
detached: true,
+ windowsHide: true,
stdio: ['ignore', log.fd, log.fd],
env: process.env,
}
@@ -264,16 +265,13 @@ async function stopOwnedProcess(root: string, ownerPath: string): Promise<void>
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code ?? '')) return;
throw error;
}
- if (process.platform === 'win32')
- throw new Error(
- 'Automatic host restart requires process fencing, which is not available on Windows.'
- );
- const { stdout } = await promisify(execFile)('ps', ['-p', String(pid), '-o', 'command=']);
- if (!stdout.includes(root))
+ const commandLine = await processCommandLine(pid);
+ if (commandLine === null) return;
+ if (!commandLineNames(commandLine, root))
throw new Error(
'The saved PID no longer identifies this SDK host. Refusing to stop another process.'
);
- process.kill(pid, 'SIGTERM');
+ await requestStop(root, pid);
if (await exitsWithin(pid, STOP_GRACE_MS)) return;
// Asked, and still here: most likely waiting on a child that will never
// finish, such as a session host that hung up and stayed alive. Waiting
diff --git a/console/packages/agent-providers/src/host/opencode-console.test.ts b/console/packages/agent-providers/src/host/opencode-console.test.ts
index dc3be4587..f92760677 100644
--- a/console/packages/agent-providers/src/host/opencode-console.test.ts
+++ b/console/packages/agent-providers/src/host/opencode-console.test.ts
@@ -1,8 +1,9 @@
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it } from 'vitest';
+import { writeNodeCli } from '../testing/node-cli';
import { exportOpenCodeConsole, importOpenCodeConsole } from './opencode-console';
const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite');
@@ -24,15 +25,13 @@ const value = {
};
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'opencode-console-'));
- cli = join(root, 'fixture-cli');
- await writeFile(
- cli,
- `#!${process.execPath}
-const { DatabaseSync } = require('node:sqlite');
+ cli = await writeNodeCli(
+ root,
+ 'fixture-cli',
+ `const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(require('node:path').join(process.env.XDG_DATA_HOME, 'opencode/opencode.db'));
db.exec('CREATE TABLE IF NOT EXISTS account (id TEXT PRIMARY KEY,email TEXT,url TEXT,access_token TEXT,refresh_token TEXT,token_expiry INTEGER,time_created INTEGER,time_updated INTEGER); CREATE TABLE IF NOT EXISTS account_state (id INTEGER PRIMARY KEY,active_account_id TEXT,active_org_id TEXT)');
-db.close();`,
- { mode: 0o700 }
+db.close();`
);
});
afterEach(async () => {
diff --git a/console/packages/agent-providers/src/host/opencode-console.ts b/console/packages/agent-providers/src/host/opencode-console.ts
index b295656c0..19b28f8f9 100644
--- a/console/packages/agent-providers/src/host/opencode-console.ts
+++ b/console/packages/agent-providers/src/host/opencode-console.ts
@@ -1,12 +1,10 @@
-import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import { chmod, lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { join } from 'node:path';
-import { promisify } from 'node:util';
import { openCodeConsoleCredentialSchema } from '../opencode/console-credential';
+import { execProvider } from '../provider-process';
-const exec = promisify(execFile);
interface Database {
prepare(sql: string): {
run(...values: unknown[]): unknown;
@@ -48,7 +46,7 @@ export async function importOpenCodeConsole(
}
await mkdir(directory, { recursive: true, mode: 0o700 });
try {
- await exec(binaryPath, ['db', 'SELECT 1', '--format', 'json'], {
+ await execProvider(binaryPath, ['db', 'SELECT 1', '--format', 'json'], {
env,
timeout: 60000,
maxBuffer: 1024 * 1024,
diff --git a/console/packages/agent-providers/src/host/ownership-lock.test.ts b/console/packages/agent-providers/src/host/ownership-lock.test.ts
index 2d949e373..30f940f97 100644
--- a/console/packages/agent-providers/src/host/ownership-lock.test.ts
+++ b/console/packages/agent-providers/src/host/ownership-lock.test.ts
@@ -12,6 +12,8 @@ import {
withOwnershipLockOutlasting,
} from './ownership-lock';
+if (process.platform === 'win32') vi.setConfig({ testTimeout: 60_000 });
+
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
@@ -51,12 +53,15 @@ async function child(root: string, stage: string): Promise<number | null> {
});
`;
const processHandle = spawn(process.execPath, ['--input-type=module', '-e', script], {
- stdio: 'ignore',
+ stdio: ['ignore', 'ignore', 'inherit'],
});
const [code] = await once(processHandle, 'exit');
return code;
}
+/** How `child` reports a process that killed itself: by signal, or on Windows with exit code 1. */
+const KILLED = process.platform === 'win32' ? 1 : null;
+
it.each([
'before-link',
'after-link',
@@ -67,7 +72,7 @@ it.each([
'after-owner',
])('recovers after a process crash at %s', async (stage) => {
const root = await rootDirectory();
- expect(await child(root, stage)).toBeNull();
+ expect(await child(root, stage)).toBe(KILLED);
await withOwnershipLock(root, () =>
replaceOwner(join(root, 'shared-owner.lock'), { pid: process.pid, group: null })
);
diff --git a/console/packages/agent-providers/src/host/ownership-lock.ts b/console/packages/agent-providers/src/host/ownership-lock.ts
index 3e05e4d94..b70896d11 100644
--- a/console/packages/agent-providers/src/host/ownership-lock.ts
+++ b/console/packages/agent-providers/src/host/ownership-lock.ts
@@ -28,6 +28,25 @@ function recordMode(): number {
return process.env.SWITCH_HOST_SHARED_GROUP === '1' ? 0o640 : 0o600;
}
+/**
+ * `replaceFile` from `replace-file`, for any operation: on Windows a rename
+ * or link onto a record another contender has open is refused while it stays
+ * open, so it is tried again for a few seconds.
+ */
+async function waitingOutSharing(operation: () => Promise<void>): Promise<void> {
+ const deadline = Date.now() + 5_000;
+ for (let wait = 10; ; wait = Math.min(wait * 2, 200)) {
+ try {
+ return await operation();
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code ?? '';
+ if (process.platform !== 'win32' || !['EPERM', 'EACCES', 'EBUSY'].includes(code)) throw error;
+ if (Date.now() > deadline) throw error;
+ }
+ await delay(wait);
+ }
+}
+
async function save(path: string, value: unknown, replace: boolean): Promise<void> {
const temporary = `${path}.${randomUUID()}.tmp`;
const file = await open(temporary, 'wx', recordMode());
@@ -38,8 +57,7 @@ async function save(path: string, value: unknown, replace: boolean): Promise<voi
await file.close();
}
try {
- if (replace) await rename(temporary, path);
- else await link(temporary, path);
+ await waitingOutSharing(() => (replace ? rename(temporary, path) : link(temporary, path)));
} finally {
await unlink(temporary).catch((error) => {
if (error.code !== 'ENOENT') throw error;
diff --git a/console/packages/agent-providers/src/host/placements.ts b/console/packages/agent-providers/src/host/placements.ts
index c0c07ae6b..03b9eeadc 100644
--- a/console/packages/agent-providers/src/host/placements.ts
+++ b/console/packages/agent-providers/src/host/placements.ts
@@ -1,7 +1,8 @@
import { randomUUID } from 'node:crypto';
-import { open, readFile, rename, unlink } from 'node:fs/promises';
+import { open, readFile, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import { z } from 'zod';
+import { replaceFile } from './replace-file';
export const PLACEMENTS_FILE = 'placements.json';
@@ -169,7 +170,7 @@ export class SessionPlacements {
await file.close();
}
try {
- await rename(temporary, this.path);
+ await replaceFile(temporary, this.path);
} catch (error) {
await unlink(temporary).catch(() => {});
throw error;
diff --git a/console/packages/agent-providers/src/host/process-fence.test.ts b/console/packages/agent-providers/src/host/process-fence.test.ts
index 5fcfee755..fdfebad32 100644
--- a/console/packages/agent-providers/src/host/process-fence.test.ts
+++ b/console/packages/agent-providers/src/host/process-fence.test.ts
@@ -31,11 +31,11 @@ it.skipIf(process.platform === 'win32')(
let fenced = false;
try {
await once(owner.stdout!, 'data');
- await expect(fenceDeadOwner(pid, pid)).rejects.toThrow('still alive');
+ await expect(fenceDeadOwner(pid, pid, null)).rejects.toThrow('still alive');
const exited = once(owner, 'exit');
owner.kill('SIGKILL');
await exited;
- await fenceDeadOwner(pid, pid);
+ await fenceDeadOwner(pid, pid, null);
fenced = true;
expect(() => process.kill(-pid, 0)).toThrow();
} finally {
@@ -58,7 +58,7 @@ it.skipIf(process.platform === 'win32')(
throw gone;
});
try {
- await expect(fenceDeadOwner(12345, 12345)).resolves.toBeUndefined();
+ await expect(fenceDeadOwner(12345, 12345, null)).resolves.toBeUndefined();
expect(kill).toHaveBeenLastCalledWith(-12345, 'SIGKILL');
} finally {
kill.mockRestore();
@@ -66,29 +66,32 @@ it.skipIf(process.platform === 'win32')(
}
);
-it('waits for confirmed exit after a transient permission error during group teardown', async () => {
- const gone = Object.assign(new Error('Process exited'), { code: 'ESRCH' });
- const denied = Object.assign(new Error('Permission denied'), { code: 'EPERM' });
- const kill = vi
- .spyOn(process, 'kill')
- .mockImplementationOnce(() => {
- throw gone;
- })
- .mockReturnValueOnce(true)
- .mockReturnValueOnce(true)
- .mockImplementationOnce(() => {
- throw denied;
- })
- .mockImplementationOnce(() => {
- throw gone;
- });
- try {
- await expect(fenceDeadOwner(12345, 12345)).resolves.toBeUndefined();
- expect(kill).toHaveBeenCalledTimes(5);
- } finally {
- kill.mockRestore();
+it.skipIf(process.platform === 'win32')(
+ 'waits for confirmed exit after a transient permission error during group teardown',
+ async () => {
+ const gone = Object.assign(new Error('Process exited'), { code: 'ESRCH' });
+ const denied = Object.assign(new Error('Permission denied'), { code: 'EPERM' });
+ const kill = vi
+ .spyOn(process, 'kill')
+ .mockImplementationOnce(() => {
+ throw gone;
+ })
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(true)
+ .mockImplementationOnce(() => {
+ throw denied;
+ })
+ .mockImplementationOnce(() => {
+ throw gone;
+ });
+ try {
+ await expect(fenceDeadOwner(12345, 12345, null)).resolves.toBeUndefined();
+ expect(kill).toHaveBeenCalledTimes(5);
+ } finally {
+ kill.mockRestore();
+ }
}
-});
+);
const throws = (code: string) => () => {
throw Object.assign(new Error(code), { code });
@@ -96,7 +99,7 @@ const throws = (code: string) => () => {
// macOS answers EPERM for a group left with only unreaped members, as it can
// be the moment a host exits.
-it.each([
+it.skipIf(process.platform === 'win32').each([
['checking it', [throws('EPERM')]],
['killing it', [(): true => true, throws('EPERM')]],
])('waits out a group that answers EPERM when %s', async (_when, answers) => {
@@ -104,30 +107,34 @@ it.each([
for (const answer of [throws('ESRCH'), ...answers, throws('ESRCH')])
kill.mockImplementationOnce(answer);
try {
- await expect(fenceDeadOwner(12345, 12345)).resolves.toBeUndefined();
+ await expect(fenceDeadOwner(12345, 12345, null)).resolves.toBeUndefined();
expect(kill).toHaveBeenLastCalledWith(-12345, 0);
} finally {
kill.mockRestore();
}
});
-it('does not assume a group is gone when permission stays denied', async () => {
- const gone = Object.assign(new Error('Process exited'), { code: 'ESRCH' });
- const denied = Object.assign(new Error('Permission denied'), { code: 'EPERM' });
- const kill = vi
- .spyOn(process, 'kill')
- .mockImplementationOnce(() => {
- throw gone;
- })
- .mockReturnValueOnce(true)
- .mockReturnValueOnce(true)
- .mockImplementation(() => {
- throw denied;
- });
- try {
- const result = expect(fenceDeadOwner(12345, 12345)).rejects.toThrow('has not exited');
- await result;
- } finally {
- kill.mockRestore();
- }
-}, 10000);
+it.skipIf(process.platform === 'win32')(
+ 'does not assume a group is gone when permission stays denied',
+ async () => {
+ const gone = Object.assign(new Error('Process exited'), { code: 'ESRCH' });
+ const denied = Object.assign(new Error('Permission denied'), { code: 'EPERM' });
+ const kill = vi
+ .spyOn(process, 'kill')
+ .mockImplementationOnce(() => {
+ throw gone;
+ })
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(true)
+ .mockImplementation(() => {
+ throw denied;
+ });
+ try {
+ const result = expect(fenceDeadOwner(12345, 12345, null)).rejects.toThrow('has not exited');
+ await result;
+ } finally {
+ kill.mockRestore();
+ }
+ },
+ 10000
+);
diff --git a/console/packages/agent-providers/src/host/process-fence.ts b/console/packages/agent-providers/src/host/process-fence.ts
index 8bc9fa4f8..15ca90b27 100644
--- a/console/packages/agent-providers/src/host/process-fence.ts
+++ b/console/packages/agent-providers/src/host/process-fence.ts
@@ -1,8 +1,15 @@
-import { execFile } from 'node:child_process';
+import { execFile, type ExecFileOptions } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
import { promisify } from 'node:util';
+import { descendants, listWindowsProcesses, reused, windowsProcess } from './windows-processes';
-const execute = promisify(execFile);
+/** Bound when called, so a test that mocks `node:child_process` without it can still import this. */
+function execute(file: string, args: string[], options: ExecFileOptions = {}) {
+ return promisify(execFile)(file, args, { ...options, encoding: 'utf8' }) as Promise<{
+ stdout: string;
+ stderr: string;
+ }>;
+}
export async function ownProcessGroup(): Promise<number | null> {
if (process.platform === 'win32') return null;
@@ -20,11 +27,28 @@ function exists(pid: number): boolean {
}
}
-/** Only a dead group leader can be reclaimed; a live owner is never displaced. */
-export async function fenceDeadOwner(pid: number, group: number | null): Promise<void> {
+/**
+ * When this process started, as an owner record keeps it on Windows, where
+ * ids are reused soon and a process's children are found by creation time
+ * rather than by group. Null elsewhere: groups do that job.
+ */
+export function ownStartTime(): number | null {
+ return process.platform === 'win32' ? Math.floor(performance.timeOrigin) : null;
+}
+
+/**
+ * Only a dead group leader can be reclaimed; a live owner is never displaced.
+ * `startedAt` is when the owner started, where its record says (Windows).
+ */
+export async function fenceDeadOwner(
+ pid: number,
+ group: number | null,
+ startedAt: number | null
+): Promise<void> {
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Invalid shared host owner PID.');
+ if (process.platform === 'win32') return fenceDeadWindowsOwner(pid, startedAt);
if (exists(pid)) throw new Error('FENCING_REQUIRED: the shared host owner is still alive.');
- if (group !== pid || process.platform === 'win32')
+ if (group !== pid)
throw new Error('FENCING_REQUIRED: the previous host did not isolate its provider processes.');
try {
if (!exists(-group)) return;
@@ -47,6 +71,70 @@ export async function fenceDeadOwner(pid: number, group: number | null): Promise
throw new Error('FENCING_REQUIRED: the previous provider process group has not exited.');
}
+/**
+ * Windows has no process groups, so what a dead owner left behind is what
+ * still names it as a parent, created after it started, and theirs in turn.
+ * An owner whose id now belongs to a newer process is dead; one whose start
+ * is not recorded cannot be told from such a process, so is taken as alive.
+ */
+async function fenceDeadWindowsOwner(pid: number, startedAt: number | null): Promise<void> {
+ const processes = await listWindowsProcesses();
+ const holder = processes.find((entry) => entry.pid === pid);
+ if (holder && (startedAt === null || !reused(holder, startedAt)))
+ throw new Error('FENCING_REQUIRED: the shared host owner is still alive.');
+ const left = descendants(processes, pid, startedAt);
+ if (left.length === 0) return;
+ for (const entry of left) terminate(entry.pid);
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const now = await listWindowsProcesses();
+ const remaining = left.filter((entry) =>
+ now.some((next) => next.pid === entry.pid && !reused(next, entry.createdAt))
+ );
+ if (remaining.length === 0) return;
+ await delay(250);
+ }
+ throw new Error('FENCING_REQUIRED: the processes the previous host started have not exited.');
+}
+
+function terminate(pid: number): void {
+ try {
+ process.kill(pid, 'SIGKILL');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
+ }
+}
+
+/**
+ * The command line a live process was started with, or null when no process
+ * has `pid`: what an owner record's PID is checked against before it is
+ * stopped, so a reused id never stops someone else's process.
+ */
+export async function processCommandLine(pid: number): Promise<string | null> {
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error(`Invalid process id ${pid}.`);
+ if (process.platform === 'win32') {
+ const entry = await windowsProcess(pid);
+ // A process of another user reports no command line to this one.
+ return entry ? (entry.commandLine ?? '') : null;
+ }
+ try {
+ const { stdout } = await execute('ps', ['-p', String(pid), '-o', 'command=']);
+ return stdout;
+ } catch (error) {
+ if ((error as { code?: number }).code === 1) return null;
+ throw error;
+ }
+}
+
+/**
+ * Whether `commandLine` names the state root `root`. Windows paths compare
+ * without regard to case or slash direction.
+ */
+export function commandLineNames(commandLine: string, root: string): boolean {
+ if (process.platform !== 'win32') return commandLine.includes(root);
+ const normal = (value: string) => value.replaceAll('/', '\\').toLowerCase();
+ return normal(commandLine).includes(normal(root));
+}
+
/**
* Kill a process and every process descended from it, whatever group each is
* in.
@@ -61,11 +149,9 @@ export async function fenceDeadOwner(pid: number, group: number | null): Promise
export async function killProcessTree(pid: number): Promise<void> {
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Invalid process to kill.');
if (process.platform === 'win32') {
- try {
- process.kill(pid, 'SIGKILL');
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
- }
+ const processes = await listWindowsProcesses();
+ const doomed = [pid, ...descendants(processes, pid, null).map((entry) => entry.pid)];
+ for (const target of doomed) terminate(target);
return;
}
const { stdout } = await execute('ps', ['-A', '-o', 'pid=,ppid=']);
diff --git a/console/packages/agent-providers/src/host/provider-home.ts b/console/packages/agent-providers/src/host/provider-home.ts
index 02baf7f0a..ea65aaead 100644
--- a/console/packages/agent-providers/src/host/provider-home.ts
+++ b/console/packages/agent-providers/src/host/provider-home.ts
@@ -1,4 +1,4 @@
-import { lstat, mkdir, readFile, readdir, symlink } from 'node:fs/promises';
+import { copyFile, link, lstat, mkdir, readFile, readdir, symlink } from 'node:fs/promises';
import { join } from 'node:path';
export async function optionalText(path: string): Promise<string | null> {
@@ -24,7 +24,35 @@ export async function linkHomeAsset(source: string, destination: string): Promis
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
throw error;
}
- await symlink(source, destination, (await lstat(source)).isDirectory() ? 'junction' : 'file');
+ const directory = (await lstat(source)).isDirectory();
+ try {
+ await symlink(source, destination, directory ? 'junction' : 'file');
+ } catch (error) {
+ if (
+ process.platform !== 'win32' ||
+ directory ||
+ (error as NodeJS.ErrnoException).code !== 'EPERM'
+ )
+ throw error;
+ await linkFileWithoutSymlink(source, destination);
+ }
+}
+
+/**
+ * Windows lets an account make a file symlink only with Developer Mode on or
+ * as an administrator. A hard link stands in for it on the same volume; on
+ * another, the file is copied, and the copy does not follow later edits.
+ */
+async function linkFileWithoutSymlink(source: string, destination: string): Promise<void> {
+ try {
+ await link(source, destination);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;
+ await copyFile(source, destination);
+ console.warn(
+ `Copied ${source} to ${destination}: Windows refused a symlink, and a hard link cannot cross volumes. Edits to ${source} reach the agent only after ${destination} is deleted.`
+ );
+ }
}
/**
diff --git a/console/packages/agent-providers/src/host/provider-login.test.ts b/console/packages/agent-providers/src/host/provider-login.test.ts
index 46d1eaa6c..64fba1620 100644
--- a/console/packages/agent-providers/src/host/provider-login.test.ts
+++ b/console/packages/agent-providers/src/host/provider-login.test.ts
@@ -55,10 +55,10 @@ describe('provider logins handed to an agent host', () => {
});
expect(
providerLoginEnvironment('/root', { ...login, provider: 'codex', kind: 'auth-json' })
- ).toEqual({ CODEX_HOME: '/root/provider-home' });
+ ).toEqual({ CODEX_HOME: join('/root', 'provider-home') });
expect(
providerLoginEnvironment('/root', { ...login, provider: 'opencode', kind: 'auth-json' })
- ).toEqual({ XDG_DATA_HOME: '/root/provider-data' });
+ ).toEqual({ XDG_DATA_HOME: join('/root', 'provider-data') });
});
it('signs Claude in through Vertex AI with the credential file under the root', () => {
@@ -67,7 +67,7 @@ describe('provider logins handed to an agent host', () => {
CLAUDE_CODE_USE_VERTEX: '1',
ANTHROPIC_VERTEX_PROJECT_ID: 'cg-vertexai',
CLOUD_ML_REGION: 'global',
- GOOGLE_APPLICATION_CREDENTIALS: '/root/provider-home/google-credentials.json',
+ GOOGLE_APPLICATION_CREDENTIALS: join('/root', 'provider-home', 'google-credentials.json'),
ANTHROPIC_API_KEY: '',
CLAUDE_CODE_OAUTH_TOKEN: '',
});
diff --git a/console/packages/agent-providers/src/host/replace-file.ts b/console/packages/agent-providers/src/host/replace-file.ts
new file mode 100644
index 000000000..0b1e60251
--- /dev/null
+++ b/console/packages/agent-providers/src/host/replace-file.ts
@@ -0,0 +1,26 @@
+import { rename } from 'node:fs/promises';
+import { setTimeout as delay } from 'node:timers/promises';
+
+/** What Windows answers while another process has the file open. */
+const SHARING_VIOLATIONS = new Set(['EPERM', 'EACCES', 'EBUSY']);
+const SHARING_WAIT_MS = 5_000;
+
+/**
+ * Renames `from` over `to`. On Windows a rename onto a file another process
+ * has open — a reader of the same record, an antivirus scan — is refused for
+ * as long as it stays open, so it is tried again for a few seconds before
+ * the refusal is passed on.
+ */
+export async function replaceFile(from: string, to: string): Promise<void> {
+ if (process.platform !== 'win32') return rename(from, to);
+ const deadline = Date.now() + SHARING_WAIT_MS;
+ for (let wait = 10; ; wait = Math.min(wait * 2, 200)) {
+ try {
+ return await rename(from, to);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code ?? '';
+ if (!SHARING_VIOLATIONS.has(code) || Date.now() > deadline) throw error;
+ }
+ await delay(wait);
+ }
+}
diff --git a/console/packages/agent-providers/src/host/server.ts b/console/packages/agent-providers/src/host/server.ts
index a2f835296..b9168aab5 100644
--- a/console/packages/agent-providers/src/host/server.ts
+++ b/console/packages/agent-providers/src/host/server.ts
@@ -1,5 +1,5 @@
import { randomUUID, timingSafeEqual, createHash } from 'node:crypto';
-import { mkdir, readFile, readdir, writeFile, rename, unlink } from 'node:fs/promises';
+import { mkdir, readFile, readdir, writeFile, unlink } from 'node:fs/promises';
import { createServer, type IncomingMessage } from 'node:http';
import { join } from 'node:path';
import { commandSchema } from '@switch-console/shared/session-v1';
@@ -7,6 +7,7 @@ import type { Command, Session } from '@switch-console/shared/session-v1';
import { z } from 'zod';
import type { AgentLaunchDefinition, ProviderAdapter, ProviderSessionStartInput } from '../adapter';
import { isProviderRuntime, providerRuntime, providerRuntimeIds } from '../providers/registry';
+import { replaceFile } from './replace-file';
import { HostedSession } from './session-host';
const id = z.string().min(1).max(200);
@@ -232,7 +233,7 @@ export async function startHostServer(
};
const temp = join(root, 'endpoint.tmp');
await writeFile(temp, JSON.stringify(endpoint), { mode: 0o600 });
- await rename(temp, join(root, 'endpoint.json'));
+ await replaceFile(temp, join(root, 'endpoint.json'));
const directories = await readdir(join(root, 'sessions'), { withFileTypes: true }).catch(
(error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return [];
diff --git a/console/packages/agent-providers/src/host/session-channel.test.ts b/console/packages/agent-providers/src/host/session-channel.test.ts
index dc8b502f1..2ea02d5c4 100644
--- a/console/packages/agent-providers/src/host/session-channel.test.ts
+++ b/console/packages/agent-providers/src/host/session-channel.test.ts
@@ -318,24 +318,28 @@ it('stops sending to a host that hung up, and waits for the next one', async ()
expect(await next).toBe('fresh');
});
-it('kills a host that hung up and stays alive, with what it started', async () => {
- vi.useFakeTimers();
- try {
- const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
- const links = new SessionLinks();
- const hung = fakeChild();
- links.attach('root', hung as unknown as ChildProcess);
- hung.emit('disconnect');
-
- await vi.advanceTimersByTimeAsync(HOST_HUNG_UP_MS - 1);
- expect(kill).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(1);
- // Its group: the provider it started is in it.
- expect(kill).toHaveBeenCalledWith(-4242, 'SIGKILL');
- } finally {
- vi.useRealTimers();
+// Windows has no process groups; the tree kill it does instead is tested in windows-processes.
+it.skipIf(process.platform === 'win32')(
+ 'kills a host that hung up and stays alive, with what it started',
+ async () => {
+ vi.useFakeTimers();
+ try {
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const links = new SessionLinks();
+ const hung = fakeChild();
+ links.attach('root', hung as unknown as ChildProcess);
+ hung.emit('disconnect');
+
+ await vi.advanceTimersByTimeAsync(HOST_HUNG_UP_MS - 1);
+ expect(kill).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ // Its group: the provider it started is in it.
+ expect(kill).toHaveBeenCalledWith(-4242, 'SIGKILL');
+ } finally {
+ vi.useRealTimers();
+ }
}
-});
+);
it('leaves a host that hung up and then exited on its own', async () => {
vi.useFakeTimers();
diff --git a/console/packages/agent-providers/src/host/session-channel.ts b/console/packages/agent-providers/src/host/session-channel.ts
index cbb483ffa..7c2f2708f 100644
--- a/console/packages/agent-providers/src/host/session-channel.ts
+++ b/console/packages/agent-providers/src/host/session-channel.ts
@@ -3,6 +3,8 @@ import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { serverEventSchema, type ServerEvent } from '@switch-console/shared/session-v1';
import { z } from 'zod';
+import { killProcessTree } from './process-fence';
+import { isStopMessage } from './stop-request';
/**
* How long a session host that has finished may take to exit once it has
@@ -552,13 +554,19 @@ export class SessionLinks {
/**
* Kill a session host and every process in its group. A host is started
* detached, so it leads its own group, and the provider processes it starts
- * are in it too.
+ * are in it too. Windows has no groups: the host's process tree goes instead.
*/
function killHostGroup(child: ChildProcess): void {
if (!child.pid) return;
+ if (process.platform === 'win32') {
+ const root = child.pid;
+ killProcessTree(root).catch((error: unknown) =>
+ console.error(`Could not stop the session host (pid ${root}): ${String(error)}`)
+ );
+ return;
+ }
try {
- if (process.platform === 'win32') child.kill('SIGKILL');
- else process.kill(-child.pid, 'SIGKILL');
+ process.kill(-child.pid, 'SIGKILL');
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
}
@@ -631,6 +639,8 @@ export function connectParent(port: ParentPort): ParentChannel {
}
>();
const onMessage = (raw: unknown) => {
+ // Heard by the process's stop listener, not by the session channel.
+ if (isStopMessage(raw)) return;
const parsed = toChildSchema.safeParse(raw);
if (!parsed.success) {
console.warn('Ignoring an unreadable message from the parent process.');
diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.ts
index 5e9505736..84b31ade3 100644
--- a/console/packages/agent-providers/src/host/session-host.test.ts
+++ b/console/packages/agent-providers/src/host/session-host.test.ts
@@ -8,6 +8,14 @@ import { ProviderConversationUnavailableError, type ProviderAdapter } from '../a
import type { ProviderRuntimeEvent } from '../events';
import { HostedSession, lastAssistantText, type RoomReply, unpostedReply } from './session-host';
+/**
+ * `vi.waitFor` with room for a slow disk: every step here is a journal write
+ * flushed to disk, and Windows runners take well over the default second.
+ */
+function waitFor<T>(check: () => T | Promise<T>): Promise<T> {
+ return vi.waitFor(check, { timeout: 10_000 });
+}
+
const roots: string[] = [];
const hosts: HostedSession[] = [];
afterEach(async () => {
@@ -111,7 +119,7 @@ async function start(provider: Session['provider']) {
const fixture = setup(provider);
const host = await HostedSession.start(root, fixture.config, fixture.adapter);
hosts.push(host);
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
return { ...fixture, root, host };
}
it.each(['claude', 'codex', 'opencode', 'antigravity', 'cursor'] as const)(
@@ -122,7 +130,7 @@ it.each(['claude', 'codex', 'opencode', 'antigravity', 'cursor'] as const)(
expect((await host.command(command)).status).toBe('applied');
await host.command(structuredClone(command));
await host.command(message('second'));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(1));
await expect(
host.command({ ...command, body: { ...command.body, text: 'Changed' } } as Command)
).rejects.toThrow('IDEMPOTENCY_CONFLICT');
@@ -143,7 +151,7 @@ it.each(['claude', 'codex', 'opencode', 'antigravity', 'cursor'] as const)(
it('keeps an explicitly stopped session stopped across restart', async () => {
const { root, host } = await start('claude');
await host.command({ ...message('stop'), body: { type: 'session.stop' } });
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));
await host.shutdown();
const fixture = setup('claude');
const recovered = await HostedSession.start(root, fixture.config, fixture.adapter);
@@ -162,7 +170,7 @@ it('keeps a failed callback outcome unknown and never retries the answer', async
title: 'Write file',
options: [{ decision: 'accept', label: 'Allow once' }],
});
- await vi.waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
+ await waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
vi.mocked(adapter.respondToRequest).mockRejectedValueOnce(new Error('Provider exited'));
const answer: Command = {
...message('answer'),
@@ -201,9 +209,9 @@ it('settles unanswered questions when the provider exits', async () => {
},
],
});
- await vi.waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
+ await waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
emit({ type: 'session.exited', reason: 'Disconnected' });
- await vi.waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('closed'));
+ await waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('closed'));
expect(host.snapshot().session.pendingRequestIds).toEqual([]);
});
it('rejects oversized input before persisting or dispatching a turn', async () => {
@@ -230,7 +238,7 @@ it.each(['accept', 'decline', 'cancel'] as const)(
title: 'Write file',
options: [{ decision, label: decision }],
});
- await vi.waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
+ await waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
const answer: Command = {
...message('answer'),
body: {
@@ -280,7 +288,7 @@ it('rejects host publication claims before dispatching a command', async () => {
it('records uncertain interrupt delivery and never sends it twice', async () => {
const { host, adapter } = await start('codex');
await host.command(message('turn'));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
vi.mocked(adapter.interruptTurn).mockRejectedValue(new Error('Connection lost after send'));
const interrupt: Command = {
...message('interrupt'),
@@ -324,7 +332,7 @@ it('stops active and queued turns without dispatching the queue during cleanup',
const { host, adapter, emit } = await start('codex');
await host.command(message('active'));
await host.command(message('queued'));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
vi.mocked(adapter.stopSession).mockImplementationOnce(async () => {
emit({ type: 'turn.completed', turnId: 'active', outcome: 'interrupted', usage: [] });
emit({ type: 'session.exited', reason: 'Stopped' });
@@ -332,7 +340,7 @@ it('stops active and queued turns without dispatching the queue during cleanup',
expect((await host.command({ ...message('stop'), body: { type: 'session.stop' } })).status).toBe(
'applied'
);
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));
expect(host.snapshot().turns.map((turn) => turn.status)).toEqual(['interrupted', 'interrupted']);
expect(adapter.sendTurn).toHaveBeenCalledOnce();
});
@@ -343,14 +351,14 @@ it('knows what a turn spent from the moment it reads as ended, and after a resta
{ model: 'big', inputTokens: 10, outputTokens: 2, cacheReadTokens: 300, cacheWriteTokens: 0 },
];
await host.command(message('spender'));
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
const seenWhenEnded: unknown[] = [];
host.onPublished((event) => {
if (event.body.type === 'turn.upsert' && event.body.status === 'completed')
seenWhenEnded.push(host.usageOf(event.body.turnId));
});
emit({ type: 'turn.completed', turnId: 'spender', outcome: 'completed', usage: spent });
- await vi.waitFor(() => expect(seenWhenEnded).toEqual([spent]));
+ await waitFor(() => expect(seenWhenEnded).toEqual([spent]));
await host.shutdown();
const next = setup('claude');
const recovered = await HostedSession.start(root, next.config, next.adapter);
@@ -362,15 +370,15 @@ it('knows what a turn spent from the moment it reads as ended, and after a resta
it('resets into a new epoch and native conversation while retaining history', async () => {
const { host, adapter, emit, root } = await start('claude');
await host.command(message('old-turn'));
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
// Completed only after the provider reported the turn started, or its late
// start would put the turn back to running.
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
emit({ type: 'turn.completed', turnId: 'old-turn', outcome: 'completed', usage: [] });
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
// The turn reads completed a moment before the session reads ready again,
// and a reset is refused until it does.
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
vi.mocked(adapter.startSession).mockImplementationOnce(async () => {
emit({ type: 'session.state.changed', status: 'ready' });
return { provider: 'claude', sessionId: 'session', nativeSessionId: 'fresh-native' };
@@ -405,7 +413,7 @@ it('rejects reset with queued work or a pending native request', async () => {
title: 'Run command',
options: [{ decision: 'accept', label: 'Allow' }],
});
- await vi.waitFor(() => expect(host.snapshot().requests).toHaveLength(1));
+ await waitFor(() => expect(host.snapshot().requests).toHaveLength(1));
await expect(
host.command({ ...message('reset'), body: { type: 'session.reset' } })
).rejects.toThrow('SESSION_BUSY');
@@ -486,7 +494,7 @@ it('starts a fresh conversation when the user decides an uncertain reset', async
expect(adapter.stopSession).not.toHaveBeenCalled();
expect(adapter.startSession).toHaveBeenCalledOnce();
expect(vi.mocked(adapter.startSession).mock.calls[0][0].resume).toBeUndefined();
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
expect(host.resetDecisionPending).toBe(false);
expect(host.snapshot().session.capabilities.attachmentMimeTypes.length).toBeGreaterThan(0);
expect(host.status('interrupted-reset')).toMatchObject({
@@ -527,7 +535,7 @@ it('resumes an ordinary interrupted session without a reset decision', async ()
expect.objectContaining({ resume: { nativeSessionId: 'native' } })
);
expect(resumed.resetDecisionPending).toBe(false);
- await vi.waitFor(() => expect(resumed.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(resumed.snapshot().session.status).toBe('ready'));
});
it('starts a new conversation on its own when the saved one is gone and never answered', async () => {
@@ -542,7 +550,7 @@ it('starts a new conversation on its own when the saved one is gone and never an
expect(restarted.resetDecisionPending).toBe(false);
expect(next.adapter.startSession).toHaveBeenCalledTimes(2);
expect(vi.mocked(next.adapter.startSession).mock.calls[1][0].resume).toBeUndefined();
- await vi.waitFor(() =>
+ await waitFor(() =>
expect(restarted.replay(0).events.map((e) => e.body)).toContainEqual(
expect.objectContaining({ code: 'CONVERSATION_STARTED_FRESH' })
)
@@ -559,7 +567,7 @@ it('validates native model choices and persists a confirmed choice across restar
fixture.adapter.setModel = vi.fn(async () => {});
const host = await HostedSession.start(root, fixture.config, fixture.adapter);
hosts.push(host);
- await vi.waitFor(() => expect(host.snapshot().session.models?.length).toBeGreaterThan(0));
+ await waitFor(() => expect(host.snapshot().session.models?.length).toBeGreaterThan(0));
expect(host.snapshot().session.capabilities.modelChange).toBe(true);
const command: Command = {
...message('model'),
@@ -604,7 +612,7 @@ it('leaves a lost model acknowledgement unknown and does not retry it', async ()
});
const host = await HostedSession.start(root, fixture.config, fixture.adapter);
hosts.push(host);
- await vi.waitFor(() => expect(host.snapshot().session.models?.length).toBeGreaterThan(0));
+ await waitFor(() => expect(host.snapshot().session.models?.length).toBeGreaterThan(0));
const command: Command = {
...message('model'),
body: { type: 'session.model.set', modelId: 'model-a', options: {} },
@@ -628,10 +636,10 @@ it('waits for native compaction and keeps history without sending a summarizatio
);
const host = await HostedSession.start(root, fixture.config, fixture.adapter);
hosts.push(host);
- await vi.waitFor(() => expect(host.snapshot().session.capabilities.compact).toBe(true));
+ await waitFor(() => expect(host.snapshot().session.capabilities.compact).toBe(true));
const command: Command = { ...message('compact'), body: { type: 'session.compact' } };
const applied = host.command(command);
- await vi.waitFor(() => expect(fixture.adapter.compactSession).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(fixture.adapter.compactSession).toHaveBeenCalledTimes(1));
expect(host.status('compact').status).toBe('accepted');
expect(host.snapshot().session.status).toBe('running');
expect(
@@ -662,7 +670,7 @@ it('stages attachments before dispatch and never executes after shutdown during
roots.push(root);
const stageAttachments = vi.fn(() => transfer.promise);
const host = await HostedSession.start(root, { ...config, stageAttachments }, adapter);
- await vi.waitFor(() =>
+ await waitFor(() =>
expect(host.snapshot().session.capabilities.attachmentMimeTypes).toContain('text/plain')
);
const command = message('with-file');
@@ -688,7 +696,7 @@ it('delivers staged execution paths once and keeps durable attachment metadata',
const staged = [{ path: '/execution-host/note.txt', mimeType: 'text/plain' }];
const stageAttachments = vi.fn(async () => staged);
const host = await HostedSession.start(root, { ...config, stageAttachments }, adapter);
- await vi.waitFor(() =>
+ await waitFor(() =>
expect(host.snapshot().session.capabilities.attachmentMimeTypes).toContain('text/plain')
);
hosts.push(host);
@@ -726,7 +734,7 @@ it('updates attachment support after a confirmed native model change', async ()
adapter
);
hosts.push(host);
- await vi.waitFor(() => expect(host.snapshot().session.capabilities.modelChange).toBe(true));
+ await waitFor(() => expect(host.snapshot().session.capabilities.modelChange).toBe(true));
expect(host.snapshot().session.capabilities.attachmentMimeTypes).not.toContain('image/png');
const image = message('image');
if (image.body.type !== 'message.send') throw new Error('Expected message');
@@ -761,13 +769,13 @@ it('requires an explicit fresh reset when the provider cannot resume the saved c
const { host, adapter, emit, root } = await start('codex');
// The provider has answered, so the lost conversation held something.
await host.command(message('answered'));
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
// Completed only after the provider reported the turn started, or its late
// start would put the turn back to running.
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
emit({ type: 'turn.completed', turnId: 'answered', outcome: 'completed', usage: [] });
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
await host.shutdown();
const next = setup('codex');
vi.mocked(next.adapter.startSession).mockRejectedValueOnce(
@@ -887,7 +895,7 @@ it('overlaps authentication with startup but waits for authentication before ret
hosts.push(host);
return host;
});
- await vi.waitFor(() => expect(fixture.adapter.startSession).toHaveBeenCalledOnce());
+ await waitFor(() => expect(fixture.adapter.startSession).toHaveBeenCalledOnce());
expect(authenticate).toHaveBeenCalledOnce();
expect(returned).toBe(false);
authenticated();
@@ -923,7 +931,7 @@ it('reports model discovery failures without losing the usable session', async (
});
const host = await HostedSession.start(root, fixture.config, fixture.adapter);
hosts.push(host);
- await vi.waitFor(() =>
+ await waitFor(() =>
expect(
host
.replay(0)
@@ -990,7 +998,7 @@ async function openApproval(
{ decision: 'decline', label: 'Deny' },
],
});
- await vi.waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
+ await waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
}
it('applies an answer Switch recorded for an approval, once', async () => {
@@ -1102,7 +1110,7 @@ async function openQuestions(
},
],
});
- await vi.waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
+ await waitFor(() => expect(host.snapshot().requests[0]?.state).toBe('open'));
}
it('answers questions with what Switch recorded for them', async () => {
@@ -1208,7 +1216,7 @@ it('starts a conversation on recovery when the first start never opened one', as
expect(recovered.adapter.startSession).toHaveBeenCalledWith(
expect.not.objectContaining({ resume: expect.anything() })
);
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
});
function roomMessage(commandId: string, threadId: string | null): Command {
@@ -1238,7 +1246,7 @@ async function startReplying(
fixture.adapter
);
hosts.push(host);
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
return { ...fixture, root: dir, host };
}
@@ -1267,11 +1275,11 @@ it('posts the last words of a room turn that ended without posting, once, in its
const reply = vi.fn(async (_reply: RoomReply) => {});
const { host, emit, root, adapter } = await startReplying(reply);
await host.command(roomMessage('turn', 'thread'));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
said(emit, 'turn', 'first', 'Let me look.');
said(emit, 'turn', 'last', ' Upgrade your plan to continue ');
emit({ type: 'turn.completed', turnId: 'turn', outcome: 'completed', usage: [] });
- await vi.waitFor(() =>
+ await waitFor(() =>
expect(host.snapshot().notices.map((notice) => notice.code)).toContain('ROOM_REPLY_POSTED')
);
expect(reply).toHaveBeenCalledExactlyOnceWith({
@@ -1293,16 +1301,16 @@ it('leaves a room turn alone when the agent posted to the room during it', async
const reply = vi.fn(async (_reply: RoomReply) => {});
const { host, emit, adapter } = await startReplying(reply);
await host.command(roomMessage('posted', null));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
host.agentPostedToRoom();
said(emit, 'posted', 'done', 'Posted the answer.');
emit({ type: 'turn.completed', turnId: 'posted', outcome: 'completed', usage: [] });
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
// A post counts for the turn it was made in, not the next one.
await host.command(roomMessage('silent', null));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));
emit({ type: 'turn.completed', turnId: 'silent', outcome: 'completed', usage: [] });
- await vi.waitFor(() => expect(reply).toHaveBeenCalledOnce());
+ await waitFor(() => expect(reply).toHaveBeenCalledOnce());
expect(reply).toHaveBeenCalledWith({
roomId: 'room',
threadId: null,
@@ -1314,7 +1322,7 @@ it('tells the room a failed turn with nothing to show failed, and why', async ()
const reply = vi.fn(async (_reply: RoomReply) => {});
const { host, emit, adapter } = await startReplying(reply);
await host.command(roomMessage('failed', 'thread'));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
emit({
type: 'turn.completed',
turnId: 'failed',
@@ -1322,7 +1330,7 @@ it('tells the room a failed turn with nothing to show failed, and why', async ()
message: 'Not signed in.',
usage: [],
});
- await vi.waitFor(() => expect(reply).toHaveBeenCalledOnce());
+ await waitFor(() => expect(reply).toHaveBeenCalledOnce());
expect(reply).toHaveBeenCalledWith({
roomId: 'room',
threadId: 'thread',
@@ -1335,7 +1343,7 @@ it('tells the room a turn that never reached the provider failed', async () => {
const { host, adapter } = await startReplying(reply);
vi.mocked(adapter.sendTurn).mockRejectedValueOnce(new Error('quota exhausted'));
await host.command(roomMessage('unsent', null));
- await vi.waitFor(() => expect(reply).toHaveBeenCalledOnce());
+ await waitFor(() => expect(reply).toHaveBeenCalledOnce());
expect(reply.mock.calls[0]![0].body).toBe(
'I finished without replying. The turn failed: Error: quota exhausted'
);
@@ -1345,10 +1353,10 @@ it('posts nothing for a turn no room message started', async () => {
const reply = vi.fn(async (_reply: RoomReply) => {});
const { host, emit, adapter } = await startReplying(reply);
await host.command(message('console'));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
said(emit, 'console', 'answer', 'Here you go.');
emit({ type: 'turn.completed', turnId: 'console', outcome: 'completed', usage: [] });
- await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
+ await waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
await host.barrier();
expect(reply).not.toHaveBeenCalled();
});
@@ -1357,13 +1365,13 @@ it('posts nothing for a room turn the host stopped', async () => {
const reply = vi.fn(async (_reply: RoomReply) => {});
const { host, emit, adapter } = await startReplying(reply);
await host.command(roomMessage('cut', null));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
vi.mocked(adapter.stopSession).mockImplementationOnce(async () => {
emit({ type: 'turn.completed', turnId: 'cut', outcome: 'interrupted', usage: [] });
emit({ type: 'session.exited', reason: 'Stopped' });
});
await host.command({ ...message('stop'), body: { type: 'session.stop' } });
- await vi.waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));
+ await waitFor(() => expect(host.snapshot().session.status).toBe('stopped'));
expect(reply).not.toHaveBeenCalled();
});
@@ -1374,16 +1382,16 @@ it('keeps the session working when the room reply cannot be posted', async () =>
});
const { host, emit, adapter } = await startReplying(reply);
await host.command(roomMessage('first', null));
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
emit({ type: 'turn.completed', turnId: 'first', outcome: 'completed', usage: [] });
- await vi.waitFor(() =>
+ await waitFor(() =>
expect(host.snapshot().notices.map((notice) => notice.code)).toContain('ROOM_REPLY_FAILED')
);
expect(
warn.mock.calls.some(([line]) => String(line).includes('Switch refused post_message'))
).toBe(true);
expect((await host.command(message('second'))).status).toBe('applied');
- await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledTimes(2));
expect(host.snapshot().session.status).toBe('ready');
warn.mockRestore();
});
diff --git a/console/packages/agent-providers/src/host/session-start.ts b/console/packages/agent-providers/src/host/session-start.ts
index e4f7168e7..abb18c1d1 100644
--- a/console/packages/agent-providers/src/host/session-start.ts
+++ b/console/packages/agent-providers/src/host/session-start.ts
@@ -1,7 +1,8 @@
import { randomUUID } from 'node:crypto';
-import { open, readFile, rename, unlink } from 'node:fs/promises';
+import { open, readFile, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import { z } from 'zod';
+import { replaceFile } from './replace-file';
/**
* How a session came to start, as whatever launched it knows: a person in
@@ -49,7 +50,7 @@ export async function recordSessionStart(
await file.close();
}
try {
- await rename(temporary, path);
+ await replaceFile(temporary, path);
} catch (error) {
await unlink(temporary).catch(() => {});
throw error;
diff --git a/console/packages/agent-providers/src/host/shared-config.test.ts b/console/packages/agent-providers/src/host/shared-config.test.ts
index 7b4636a9f..b8ac42904 100644
--- a/console/packages/agent-providers/src/host/shared-config.test.ts
+++ b/console/packages/agent-providers/src/host/shared-config.test.ts
@@ -6,26 +6,51 @@ import { executionEnvironment, prepareSharedConfig, sharedConfigSchema } from '.
afterEach(() => vi.unstubAllEnvs());
-it('preserves host and configured environment, including shell setup output', async () => {
- vi.stubEnv('SDK_CUSTOM_HOST_VALUE', 'from-host');
- vi.stubEnv('SDK_UNLISTED_VALUE', 'must-not-inherit');
- vi.stubEnv('SWITCH_API_TOKEN', 'discard-inherited-identity');
- const env = await executionEnvironment(
- process.cwd(),
- { SDK_CONFIGURED: 'configured' },
- 'echo setup-output; export SDK_CUSTOM_SETUP="$SDK_CONFIGURED-from-setup"',
- ['SDK_CUSTOM_HOST_VALUE', 'PATH', 'HOME', 'SHELL']
- );
- expect(env.SDK_UNLISTED_VALUE).toBeUndefined();
- expect(env.SDK_CUSTOM_HOST_VALUE).toBe('from-host');
- expect(env.SDK_CUSTOM_SETUP).toBe('configured-from-setup');
- expect(env.SWITCH_API_TOKEN).toBeUndefined();
-});
+it.skipIf(process.platform === 'win32')(
+ 'preserves host and configured environment, including shell setup output',
+ async () => {
+ vi.stubEnv('SDK_CUSTOM_HOST_VALUE', 'from-host');
+ vi.stubEnv('SDK_UNLISTED_VALUE', 'must-not-inherit');
+ vi.stubEnv('SWITCH_API_TOKEN', 'discard-inherited-identity');
+ const env = await executionEnvironment(
+ process.cwd(),
+ { SDK_CONFIGURED: 'configured' },
+ 'echo setup-output; export SDK_CUSTOM_SETUP="$SDK_CONFIGURED-from-setup"',
+ ['SDK_CUSTOM_HOST_VALUE', 'PATH', 'HOME', 'SHELL']
+ );
+ expect(env.SDK_UNLISTED_VALUE).toBeUndefined();
+ expect(env.SDK_CUSTOM_HOST_VALUE).toBe('from-host');
+ expect(env.SDK_CUSTOM_SETUP).toBe('configured-from-setup');
+ expect(env.SWITCH_API_TOKEN).toBeUndefined();
+ }
+);
it('fails before provider startup if shell setup fails', async () => {
await expect(executionEnvironment(process.cwd(), {}, 'false', [])).rejects.toThrow();
});
+it.runIf(process.platform === 'win32')('refuses shell setup on Windows, saying why', async () => {
+ await expect(executionEnvironment(process.cwd(), {}, 'echo hi', [])).rejects.toThrow(
+ /POSIX shell snippet/
+ );
+});
+
+it('inherits Path whatever its case on Windows', async () => {
+ const platform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
+ vi.stubEnv('Path', 'C:\\Windows\\System32');
+ try {
+ const env = await executionEnvironment(process.cwd(), {}, undefined, ['PATH']);
+ // Windows has one variable whatever its case; the key is the case it was first set in.
+ const key = Object.keys(env).find(
+ (name) => name.toUpperCase() === 'PATH' && env[name] === 'C:\\Windows\\System32'
+ );
+ expect(key).toBeDefined();
+ } finally {
+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });
+ }
+});
+
it('gives the provider the host’s own MCP server and no Switch identity', async () => {
const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));
try {
diff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.ts
index 9de330304..21fb7656c 100644
--- a/console/packages/agent-providers/src/host/shared-config.ts
+++ b/console/packages/agent-providers/src/host/shared-config.ts
@@ -153,10 +153,14 @@ export async function executionEnvironment(
inheritEnv: string[]
): Promise<Record<string, string>> {
const env: Record<string, string> = {};
+ const inherited =
+ process.platform === 'win32'
+ ? new Set(inheritEnv.map((key) => key.toUpperCase()))
+ : new Set(inheritEnv);
for (const [key, value] of Object.entries(process.env))
if (
value !== undefined &&
- inheritEnv.includes(key) &&
+ inherited.has(process.platform === 'win32' ? key.toUpperCase() : key) &&
!key.startsWith('SWITCH_') &&
!key.startsWith('ELECTRON_')
)
@@ -164,7 +168,9 @@ export async function executionEnvironment(
Object.assign(env, configured);
if (!setup) return env;
if (process.platform === 'win32')
- throw new Error('SDK shell setup requires a POSIX execution host.');
+ throw new Error(
+ "The agent's shell setup is a POSIX shell snippet, which Windows cannot run; remove it from the agent."
+ );
const marker = randomUUID();
const { stdout } = await promisify(execFile)(
env.SHELL || '/bin/sh',
diff --git a/console/packages/agent-providers/src/host/shared-daemon.ts b/console/packages/agent-providers/src/host/shared-daemon.ts
index e82b45e41..cfdd0076f 100644
--- a/console/packages/agent-providers/src/host/shared-daemon.ts
+++ b/console/packages/agent-providers/src/host/shared-daemon.ts
@@ -16,6 +16,7 @@ import { adapterFor } from './server';
import { HOST_EXIT_GRACE_MS, SessionLinks } from './session-channel';
import { readProviderLogin, readSharedCredentials, sharedConfigSchema } from './shared-config';
import { hostSessionProcess } from './shared-host';
+import { onStopRequest } from './stop-request';
import { superviseSharedHost } from './supervisor';
import { recordWatcherHealth } from './watcher-health-file';
import { WatcherControl } from './watcher-tools';
@@ -98,8 +99,7 @@ async function main(): Promise<void> {
);
} else if (mode === '--supervise' || mode === '--watch-supervise') {
const stop = new AbortController();
- process.on('SIGTERM', () => stop.abort());
- process.on('SIGINT', () => stop.abort());
+ onStopRequest(() => stop.abort(), resolve(root));
await superviseSharedHost({
root: resolve(root),
executable: process.execPath,
@@ -116,8 +116,7 @@ async function main(): Promise<void> {
});
} else if (mode === '--watch-worker') {
const stop = new AbortController();
- process.on('SIGTERM', () => stop.abort());
- process.on('SIGINT', () => stop.abort());
+ onStopRequest(() => stop.abort(), resolve(root));
// The sidecar is the parent of the sessions it runs: it talks to each over
// IPC, and Console reaches them through its control port.
const links = new SessionLinks();
@@ -176,6 +175,7 @@ async function main(): Promise<void> {
} else if (process.platform !== 'win32' && (await ownProcessGroup()) === null) {
const child = spawn(process.execPath, process.argv.slice(1), {
detached: true,
+ windowsHide: true,
stdio: 'inherit',
env: process.env,
});
@@ -193,8 +193,7 @@ async function main(): Promise<void> {
'A session host is started by Console or the agent sidecar, which answer its Switch tools; run on its own it has nothing to answer them.'
);
const stop = new AbortController();
- process.on('SIGTERM', () => stop.abort());
- process.on('SIGINT', () => stop.abort());
+ onStopRequest(() => stop.abort(), resolve(root));
// Started by a parent that talks to it: it goes when the parent goes.
process.on('disconnect', () => stop.abort());
try {
diff --git a/console/packages/agent-providers/src/host/shared-state.ts b/console/packages/agent-providers/src/host/shared-state.ts
index f8d4a954b..7b398f3a4 100644
--- a/console/packages/agent-providers/src/host/shared-state.ts
+++ b/console/packages/agent-providers/src/host/shared-state.ts
@@ -5,7 +5,7 @@ import { sessionSchema, snapshotSchema } from '@switch-console/shared/session-v1
import { z } from 'zod';
import { Journal } from './journal';
import { releaseOwner, replaceOwner, withOwnershipLock } from './ownership-lock';
-import { fenceDeadOwner, ownProcessGroup } from './process-fence';
+import { fenceDeadOwner, ownProcessGroup, ownStartTime } from './process-fence';
import type { SharedHostOptions } from './shared-host';
export const sharedStateRecordSchema = z.discriminatedUnion('type', [
@@ -78,13 +78,19 @@ export class SharedState {
readonly journal: Journal<Record>,
private readonly lock: string,
private readonly root: string,
- private readonly owner: { pid: number; group: number | null; token: string }
+ private readonly owner: { pid: number; group: number | null; token: string; started?: number }
) {}
static async open(options: SharedHostOptions): Promise<SharedState> {
await mkdir(options.root, { recursive: true, mode: 0o700 });
const lock = join(options.root, 'shared-owner.lock');
- const owner = { pid: process.pid, group: await ownProcessGroup(), token: randomUUID() };
+ const started = ownStartTime();
+ const owner = {
+ pid: process.pid,
+ group: await ownProcessGroup(),
+ token: randomUUID(),
+ ...(started === null ? {} : { started }),
+ };
await withOwnershipLock(options.root, async () => {
try {
const owner = z
@@ -92,9 +98,10 @@ export class SharedState {
token: z.string().optional(),
pid: z.number().int().positive(),
group: z.number().int().positive().nullable(),
+ started: z.number().int().positive().optional(),
})
.parse(JSON.parse(await readFile(lock, 'utf8')));
- await fenceDeadOwner(owner.pid, owner.group);
+ await fenceDeadOwner(owner.pid, owner.group, owner.started ?? null);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
diff --git a/console/packages/agent-providers/src/host/stop-request.test.ts b/console/packages/agent-providers/src/host/stop-request.test.ts
new file mode 100644
index 000000000..2bef5735c
--- /dev/null
+++ b/console/packages/agent-providers/src/host/stop-request.test.ts
@@ -0,0 +1,106 @@
+import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ isStopMessage,
+ onStopRequest,
+ requestChildStop,
+ requestStop,
+ STOP_MESSAGE,
+ stopFile,
+} from './stop-request';
+
+const platform = process.platform;
+function pretend(value: NodeJS.Platform): void {
+ Object.defineProperty(process, 'platform', { value, configurable: true });
+}
+
+let root: string;
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'stop-request-'));
+});
+afterEach(async () => {
+ pretend(platform);
+ await rm(root, { recursive: true, force: true });
+});
+
+function fakeChild(connected: boolean) {
+ return { connected, pid: 4242, send: vi.fn(() => true), kill: vi.fn(() => true) };
+}
+
+describe('requestChildStop', () => {
+ it('sends SIGTERM on macOS and Linux', async () => {
+ pretend('linux');
+ const child = fakeChild(true);
+ await requestChildStop(child, root);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(child.send).not.toHaveBeenCalled();
+ });
+
+ it('sends the stop message over IPC on Windows', async () => {
+ pretend('win32');
+ const child = fakeChild(true);
+ await requestChildStop(child, root);
+ expect(child.send).toHaveBeenCalledWith(STOP_MESSAGE);
+ expect(child.kill).not.toHaveBeenCalled();
+ });
+
+ it('writes the stop file for a child with no IPC channel on Windows', async () => {
+ pretend('win32');
+ const child = fakeChild(false);
+ await requestChildStop(child, root);
+ expect(child.kill).not.toHaveBeenCalled();
+ expect(await readdir(root)).toEqual(['.stop-4242']);
+ });
+});
+
+describe('onStopRequest', () => {
+ it('stops once on the stop message', () => {
+ const stop = vi.fn();
+ const dispose = onStopRequest(stop, null);
+ try {
+ process.emit('message', { kind: 'other' }, undefined);
+ expect(stop).not.toHaveBeenCalled();
+ process.emit('message', STOP_MESSAGE, undefined);
+ process.emit('message', STOP_MESSAGE, undefined);
+ expect(stop).toHaveBeenCalledTimes(1);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('stops when its stop file is written on Windows', async () => {
+ pretend('win32');
+ const stop = vi.fn();
+ const dispose = onStopRequest(stop, root);
+ try {
+ await requestStop(root, process.pid);
+ for (let waited = 0; waited < 3000 && !stop.mock.calls.length; waited += 50) await delay(50);
+ expect(stop).toHaveBeenCalledTimes(1);
+ expect(await readdir(root)).toEqual([]);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('ignores a stop file left for an earlier process with the same id', async () => {
+ pretend('win32');
+ await writeFile(stopFile(root, process.pid), JSON.stringify({ pid: process.pid, at: 1 }));
+ const stop = vi.fn();
+ const dispose = onStopRequest(stop, root);
+ try {
+ await delay(600);
+ expect(stop).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+ });
+});
+
+it('tells the stop message apart from session traffic', () => {
+ expect(isStopMessage(STOP_MESSAGE)).toBe(true);
+ expect(isStopMessage({ kind: 'answer', id: 1 })).toBe(false);
+ expect(isStopMessage(null)).toBe(false);
+});
diff --git a/console/packages/agent-providers/src/host/stop-request.ts b/console/packages/agent-providers/src/host/stop-request.ts
new file mode 100644
index 000000000..e48744cec
--- /dev/null
+++ b/console/packages/agent-providers/src/host/stop-request.ts
@@ -0,0 +1,111 @@
+import type { ChildProcess } from 'node:child_process';
+import { readFile, unlink, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+
+/**
+ * Asking a process to stop and letting it finish what it was doing.
+ *
+ * On macOS and Linux that is SIGTERM. Windows has no signal one process can
+ * send another and have it caught: `kill('SIGTERM')` there ends the process
+ * on the spot, mid-write. So on Windows a child with an IPC channel is sent
+ * `STOP_MESSAGE`, and a process known only by its id is asked through a file
+ * in the state root it runs for, `stopFile(root, pid)`, which it watches.
+ */
+export const STOP_MESSAGE = { kind: 'switch-stop' } as const;
+
+export function isStopMessage(raw: unknown): boolean {
+ return (
+ typeof raw === 'object' &&
+ raw !== null &&
+ (raw as { kind?: unknown }).kind === STOP_MESSAGE.kind
+ );
+}
+
+/** Where the process `pid`, running for the state root `root`, is asked to stop on Windows. */
+export function stopFile(root: string, pid: number): string {
+ return join(root, `.stop-${pid}`);
+}
+
+const STOP_FILE_POLL_MS = 250;
+
+/**
+ * Ask `child`, running for the state root `root`, to stop: SIGTERM, or on
+ * Windows `STOP_MESSAGE` over its IPC channel, or its stop file without one.
+ */
+export async function requestChildStop(
+ child: Pick<ChildProcess, 'connected' | 'send' | 'kill' | 'pid'>,
+ root: string
+): Promise<void> {
+ if (process.platform !== 'win32') {
+ child.kill('SIGTERM');
+ return;
+ }
+ if (child.connected) {
+ child.send(STOP_MESSAGE);
+ return;
+ }
+ if (child.pid) await requestStop(root, child.pid);
+}
+
+/** Ask the process `pid`, running for `root`, to stop: SIGTERM, or its stop file on Windows. */
+export async function requestStop(root: string, pid: number): Promise<void> {
+ if (process.platform !== 'win32') {
+ process.kill(pid, 'SIGTERM');
+ return;
+ }
+ await writeFile(stopFile(root, pid), JSON.stringify({ pid, at: Date.now() }), { mode: 0o600 });
+}
+
+/**
+ * Calls `stop` once when this process is asked to stop: SIGTERM or SIGINT,
+ * `STOP_MESSAGE` from its parent, or — on Windows, with a `root` — its stop
+ * file appearing there. Returns what removes the listeners.
+ */
+export function onStopRequest(stop: () => void, root: string | null): () => void {
+ let stopped = false;
+ const once = () => {
+ if (stopped) return;
+ stopped = true;
+ stop();
+ };
+ const onMessage = (raw: unknown) => {
+ if (isStopMessage(raw)) once();
+ };
+ process.on('SIGTERM', once);
+ process.on('SIGINT', once);
+ process.on('message', onMessage);
+ let timer: ReturnType<typeof setInterval> | null = null;
+ if (process.platform === 'win32' && root !== null) {
+ const path = stopFile(root, process.pid);
+ const started = performance.timeOrigin;
+ let checking = false;
+ timer = setInterval(() => {
+ if (checking) return;
+ checking = true;
+ readFile(path, 'utf8')
+ .then(async (text) => {
+ const request = JSON.parse(text) as { pid?: unknown; at?: unknown };
+ await unlink(path).catch(ignoreMissing);
+ // One left for an earlier process that had this id is not for this one.
+ if (request.pid !== process.pid || typeof request.at !== 'number' || request.at < started)
+ return;
+ once();
+ }, ignoreMissing)
+ .catch((error: unknown) => console.warn(`Could not read ${path}: ${String(error)}`))
+ .finally(() => {
+ checking = false;
+ });
+ }, STOP_FILE_POLL_MS);
+ timer.unref();
+ }
+ return () => {
+ process.off('SIGTERM', once);
+ process.off('SIGINT', once);
+ process.off('message', onMessage);
+ if (timer) clearInterval(timer);
+ };
+}
+
+function ignoreMissing(error: unknown): void {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+}
diff --git a/console/packages/agent-providers/src/host/supervisor.test.ts b/console/packages/agent-providers/src/host/supervisor.test.ts
index 097d443b6..b302ad715 100644
--- a/console/packages/agent-providers/src/host/supervisor.test.ts
+++ b/console/packages/agent-providers/src/host/supervisor.test.ts
@@ -1,9 +1,12 @@
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { afterEach, expect, it } from 'vitest';
+import { afterEach, expect, it, vi } from 'vitest';
import { CHILD_STOP_GRACE_MS, superviseSharedHost } from './supervisor';
+// Each worker exit is fenced on Windows through PowerShell, which takes seconds to start.
+if (process.platform === 'win32') vi.setConfig({ testTimeout: 60_000 });
+
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
@@ -23,6 +26,8 @@ it('restarts a crashed isolated worker and exits after a clean stop', async () =
if (!fs.existsSync(marker)) {
fs.writeFileSync(marker, '1');
fs.writeFileSync(root + '/shared-owner.lock', JSON.stringify({pid: process.pid}));
+ // A crash: a signal, or on Windows an exception's NTSTATUS exit code.
+ if (process.platform === 'win32') process.exit(0xc0000005);
process.kill(process.pid, 'SIGKILL');
}
fs.writeFileSync(marker, '2');
diff --git a/console/packages/agent-providers/src/host/supervisor.ts b/console/packages/agent-providers/src/host/supervisor.ts
index ea2072aa1..083bb8d28 100644
--- a/console/packages/agent-providers/src/host/supervisor.ts
+++ b/console/packages/agent-providers/src/host/supervisor.ts
@@ -8,6 +8,7 @@ import { z } from 'zod';
import { releaseOwner, replaceOwner, withOwnershipLock } from './ownership-lock';
import { fenceDeadOwner, killProcessTree } from './process-fence';
import type { SessionLinks } from './session-channel';
+import { requestChildStop } from './stop-request';
function alive(pid: number): boolean {
try {
@@ -31,6 +32,16 @@ async function ownerPid(path: string): Promise<number | null> {
}
}
+/**
+ * A Windows process that died of an exception — an access violation, a stack
+ * overflow, a fatal error — exits with its NTSTATUS code, 0xC0000000 and up:
+ * what a signal is elsewhere, so it is recovered rather than taken as the
+ * host refusing to run.
+ */
+function crashedOnWindows(code: number): boolean {
+ return process.platform === 'win32' && code >>> 0 >= 0xc0000000;
+}
+
/**
* How long a supervised host asked to stop is given before it and what it
* started are killed. Shorter than the launcher's `STOP_GRACE_MS`, so a chain
@@ -73,8 +84,10 @@ export async function superviseSharedHost(input: {
continue;
}
const log = await open(join(directory, 'worker.log'), 'a', 0o600);
+ const spawnedAt = Date.now();
const child = spawn(input.executable, input.args, {
detached: true,
+ windowsHide: true,
env: input.env,
stdio: input.links ? ['ignore', log.fd, log.fd, 'ipc'] : ['ignore', log.fd, log.fd],
});
@@ -87,7 +100,9 @@ export async function superviseSharedHost(input: {
// so that stopping this supervisor cannot hang on it.
let escalation: ReturnType<typeof setTimeout> | null = null;
const stop = () => {
- child.kill('SIGTERM');
+ requestChildStop(child, input.root).catch((error: unknown) =>
+ console.error(`Could not ask the shared host at ${input.root} to stop: ${String(error)}`)
+ );
escalation ??= setTimeout(() => {
if (child.exitCode !== null || child.signalCode !== null || !child.pid) return;
console.warn(
@@ -110,7 +125,7 @@ export async function superviseSharedHost(input: {
if (escalation) clearTimeout(escalation);
}
if (child.pid) {
- await fenceDeadOwner(child.pid, child.pid);
+ await fenceDeadOwner(child.pid, child.pid, spawnedAt);
const workerPath = join(input.root, 'shared-owner.lock');
try {
const owner = JSON.parse(await readFile(workerPath, 'utf8'));
@@ -121,7 +136,7 @@ export async function superviseSharedHost(input: {
}
if (input.signal.aborted) return;
if (code === 0) return;
- if (code !== null) {
+ if (code !== null && !crashedOnWindows(code)) {
try {
await readFile(join(directory, 'failure.json'));
} catch (error) {
@@ -132,7 +147,9 @@ export async function superviseSharedHost(input: {
}
throw new Error(`Shared SDK host failed with exit code ${code}.`);
}
- console.warn(`Shared SDK host exited on ${signal}; recovering its saved state.`);
+ console.warn(
+ `Shared SDK host exited on ${signal ?? `exception 0x${((code ?? 0) >>> 0).toString(16)}`}; recovering its saved state.`
+ );
await delay(1000, undefined, { signal: input.signal });
}
} catch (error) {
diff --git a/console/packages/agent-providers/src/host/taken-over.ts b/console/packages/agent-providers/src/host/taken-over.ts
index 20c38d422..7af76baf0 100644
--- a/console/packages/agent-providers/src/host/taken-over.ts
+++ b/console/packages/agent-providers/src/host/taken-over.ts
@@ -1,8 +1,9 @@
import { randomUUID } from 'node:crypto';
-import { open, readFile, rename, unlink } from 'node:fs/promises';
+import { open, readFile, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import { z } from 'zod';
import { fileMode } from './host-permissions';
+import { replaceFile } from './replace-file';
/**
* The record a watcher leaves behind when something else took its connection.
@@ -39,7 +40,7 @@ export async function recordTakenOver(root: string, info: TakenOver): Promise<vo
await file.close();
}
try {
- await rename(temporary, path);
+ await replaceFile(temporary, path);
} finally {
await unlink(temporary).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
diff --git a/console/packages/agent-providers/src/host/watch-flags.test.ts b/console/packages/agent-providers/src/host/watch-flags.test.ts
index d3d3c6acf..3b6a56860 100644
--- a/console/packages/agent-providers/src/host/watch-flags.test.ts
+++ b/console/packages/agent-providers/src/host/watch-flags.test.ts
@@ -1,9 +1,10 @@
import type * as NodeFs from 'node:fs';
import type { FSWatcher } from 'node:fs';
-import { mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, expect, it, vi } from 'vitest';
+import { replaceFile } from './replace-file';
import { awaitWatchChange, readWatchFlags, type WatchFlags } from './watch-flags';
const platform = vi.hoisted(() => ({ canWatch: true, watchers: [] as FSWatcher[] }));
@@ -40,7 +41,7 @@ async function watcherRoot(flags: WatchFlags) {
async function write(root: string, flags: WatchFlags) {
const temporary = join(root, 'watch.json.tmp');
await writeFile(temporary, JSON.stringify(flags));
- await rename(temporary, join(root, 'watch.json'));
+ await replaceFile(temporary, join(root, 'watch.json'));
}
it('reads both flags back', async () => {
diff --git a/console/packages/agent-providers/src/host/watcher-health-file.ts b/console/packages/agent-providers/src/host/watcher-health-file.ts
index 55a37dce4..0d1bcb8cd 100644
--- a/console/packages/agent-providers/src/host/watcher-health-file.ts
+++ b/console/packages/agent-providers/src/host/watcher-health-file.ts
@@ -1,8 +1,9 @@
import { randomUUID } from 'node:crypto';
-import { rename, writeFile } from 'node:fs/promises';
+import { writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { z } from 'zod';
import { fileMode } from './host-permissions';
+import { replaceFile } from './replace-file';
import { type WatcherControl, watcherHealthSchema } from './watcher-tools';
/**
@@ -48,7 +49,7 @@ export function recordWatcherHealth(root: string, control: WatcherControl): () =
.then(async () => {
const temporary = `${path}.${randomUUID()}`;
await writeFile(temporary, JSON.stringify(body), { mode: fileMode(0o600) });
- await rename(temporary, path);
+ await replaceFile(temporary, path);
})
.catch((error: unknown) => {
console.error(`Could not record the room watcher's health in ${path}: ${String(error)}`);
diff --git a/console/packages/agent-providers/src/host/windows-processes.test.ts b/console/packages/agent-providers/src/host/windows-processes.test.ts
new file mode 100644
index 000000000..cb1f79ebc
--- /dev/null
+++ b/console/packages/agent-providers/src/host/windows-processes.test.ts
@@ -0,0 +1,111 @@
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { describe, expect, it } from 'vitest';
+import { fenceDeadOwner, killProcessTree, processCommandLine } from './process-fence';
+import { descendants, listWindowsProcesses, type WindowsProcess } from './windows-processes';
+
+const at = (seconds: number) => Date.UTC(2026, 0, 1) + seconds * 1000;
+const proc = (pid: number, ppid: number, created: number): WindowsProcess => ({
+ pid,
+ ppid,
+ createdAt: at(created),
+ commandLine: null,
+});
+
+describe('descendants', () => {
+ it('walks children and grandchildren of a live root', () => {
+ const processes = [proc(10, 1, 0), proc(11, 10, 5), proc(12, 11, 6), proc(20, 1, 3)];
+ expect(descendants(processes, 10, null).map((entry) => entry.pid)).toEqual([11, 12]);
+ });
+
+ it('finds orphans that still name a root that has exited', () => {
+ const processes = [proc(11, 10, 5), proc(12, 11, 6)];
+ expect(descendants(processes, 10, at(0)).map((entry) => entry.pid)).toEqual([11, 12]);
+ });
+
+ it('skips a process created before its supposed parent: its parent id was reused', () => {
+ const processes = [proc(10, 1, 100), proc(11, 10, 5)];
+ expect(descendants(processes, 10, null)).toEqual([]);
+ });
+
+ it('leaves alone what a newer process holding the id started', () => {
+ // The owner started at 0 and died; pid 10 now belongs to a process from 50.
+ const processes = [proc(10, 1, 50), proc(11, 10, 5), proc(12, 10, 60)];
+ expect(descendants(processes, 10, at(0)).map((entry) => entry.pid)).toEqual([11]);
+ });
+
+ it('survives a parent cycle', () => {
+ const processes = [proc(11, 12, 5), proc(12, 11, 6)];
+ expect(descendants(processes, 11, at(0)).map((entry) => entry.pid)).toEqual([12]);
+ });
+});
+
+/** A process that starts a child which outlives it, printing the child's pid. */
+const PARENT_OF_A_SURVIVOR = `
+ const { spawn } = require('node:child_process');
+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore', detached: true, windowsHide: true });
+ console.log(child.pid);
+ setInterval(() => {}, 1000);
+`;
+
+function exists(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+describe.runIf(process.platform === 'win32')('on Windows', () => {
+ it('lists this process with its command line', async () => {
+ const processes = await listWindowsProcesses();
+ const self = processes.find((entry) => entry.pid === process.pid);
+ expect(self?.ppid).toBe(process.ppid);
+ expect(await processCommandLine(process.pid)).toContain('node');
+ }, 60_000);
+
+ it('answers null for a process that is gone', async () => {
+ const child = spawn(process.execPath, ['-e', ''], { windowsHide: true });
+ await once(child, 'exit');
+ expect(await processCommandLine(child.pid!)).toBeNull();
+ }, 60_000);
+
+ it('fences what a crashed owner left running', async () => {
+ const startedAt = Date.now();
+ const owner = spawn(process.execPath, ['-e', PARENT_OF_A_SURVIVOR], {
+ stdio: ['ignore', 'pipe', 'ignore'],
+ windowsHide: true,
+ });
+ const [line] = await once(owner.stdout!, 'data');
+ const survivor = Number(String(line).trim());
+ try {
+ await expect(fenceDeadOwner(owner.pid!, null, startedAt)).rejects.toThrow('still alive');
+ const exited = once(owner, 'exit');
+ owner.kill();
+ await exited;
+ expect(exists(survivor)).toBe(true);
+ await fenceDeadOwner(owner.pid!, null, startedAt);
+ expect(exists(survivor)).toBe(false);
+ } finally {
+ if (exists(survivor)) process.kill(survivor);
+ }
+ }, 120_000);
+
+ it('kills a whole tree', async () => {
+ const owner = spawn(process.execPath, ['-e', PARENT_OF_A_SURVIVOR], {
+ stdio: ['ignore', 'pipe', 'ignore'],
+ windowsHide: true,
+ });
+ const [line] = await once(owner.stdout!, 'data');
+ const survivor = Number(String(line).trim());
+ try {
+ const exited = once(owner, 'exit');
+ await killProcessTree(owner.pid!);
+ await exited;
+ expect(exists(survivor)).toBe(false);
+ } finally {
+ if (exists(survivor)) process.kill(survivor);
+ }
+ }, 120_000);
+});
diff --git a/console/packages/agent-providers/src/host/windows-processes.ts b/console/packages/agent-providers/src/host/windows-processes.ts
new file mode 100644
index 000000000..4a667514b
--- /dev/null
+++ b/console/packages/agent-providers/src/host/windows-processes.ts
@@ -0,0 +1,129 @@
+import { execFile, type ExecFileOptions } from 'node:child_process';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import { z } from 'zod';
+
+/** Bound when called, so a test that mocks `node:child_process` without it can still import this. */
+function execute(file: string, args: string[], options: ExecFileOptions = {}) {
+ return promisify(execFile)(file, args, { ...options, encoding: 'utf8' }) as Promise<{
+ stdout: string;
+ stderr: string;
+ }>;
+}
+
+/** One process as Windows reports it. `createdAt` is epoch milliseconds. */
+export type WindowsProcess = {
+ pid: number;
+ ppid: number;
+ createdAt: number;
+ commandLine: string | null;
+};
+
+const rowSchema = z.object({
+ p: z.number().int(),
+ pp: z.number().int(),
+ c: z.string().nullable(),
+ l: z.string().nullable(),
+});
+
+/**
+ * How far a process's recorded start may sit from the creation time Windows
+ * reports for it: Node takes its time origin a little after the process is
+ * created, and a supervisor records a spawn just before.
+ */
+export const START_TOLERANCE_MS = 5_000;
+
+const PROCESS_QUERY_TIMEOUT_MS = 30_000;
+
+function powershell(): string {
+ const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? 'C:\\Windows';
+ return join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+}
+
+/**
+ * The processes Windows reports, through PowerShell's CIM cmdlets: every
+ * Windows 10 and 11 has them, where `wmic` is gone from current builds and
+ * `tasklist` reports neither parents nor command lines. `filter` is a WQL
+ * condition; omitted, every process is listed.
+ */
+export async function listWindowsProcesses(filter?: string): Promise<WindowsProcess[]> {
+ const query = filter
+ ? `Get-CimInstance Win32_Process -Filter '${filter}'`
+ : 'Get-CimInstance Win32_Process';
+ const script = [
+ "$ErrorActionPreference = 'Stop'",
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
+ `$rows = @(${query} | ForEach-Object { [pscustomobject]@{ p = [int]$_.ProcessId; pp = [int]$_.ParentProcessId; c = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }); l = $_.CommandLine } })`,
+ 'ConvertTo-Json -InputObject $rows -Compress',
+ ].join('; ');
+ const { stdout } = await execute(
+ powershell(),
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
+ { timeout: PROCESS_QUERY_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, windowsHide: true }
+ );
+ const text = stdout.trim();
+ if (!text) return [];
+ return z
+ .array(rowSchema)
+ .parse(JSON.parse(text))
+ .map((row) => ({
+ pid: row.p,
+ ppid: row.pp,
+ createdAt: row.c === null ? 0 : Date.parse(row.c),
+ commandLine: row.l,
+ }));
+}
+
+/** One process by id, or null when none has it. */
+export async function windowsProcess(pid: number): Promise<WindowsProcess | null> {
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error(`Invalid process id ${pid}.`);
+ return (await listWindowsProcesses(`ProcessId = ${pid}`))[0] ?? null;
+}
+
+/**
+ * The processes descended from `root`, parents before children, `root`
+ * excluded.
+ *
+ * Windows keeps a process's parent id after the parent exits, so an orphan
+ * still names it, and it reuses ids. A process counts as a child only when it
+ * was created after its parent was: `rootStartedAt` stands in for a root that
+ * is gone, and when its id has since gone to a newer process, what that
+ * newer process started is left alone.
+ */
+export function descendants(
+ processes: readonly WindowsProcess[],
+ root: number,
+ rootStartedAt: number | null
+): WindowsProcess[] {
+ const byParent = new Map<number, WindowsProcess[]>();
+ for (const entry of processes) {
+ if (entry.pid === entry.ppid) continue;
+ byParent.set(entry.ppid, [...(byParent.get(entry.ppid) ?? []), entry]);
+ }
+ const current = processes.find((entry) => entry.pid === root) ?? null;
+ const rootStart =
+ current && (rootStartedAt === null || !reused(current, rootStartedAt))
+ ? current.createdAt
+ : rootStartedAt;
+ const successor =
+ current && rootStartedAt !== null && reused(current, rootStartedAt) ? current : null;
+ const found: WindowsProcess[] = [];
+ const seen = new Set<number>([root]);
+ const visit = (parent: number, parentStart: number | null, before: number | null) => {
+ for (const child of byParent.get(parent) ?? []) {
+ if (seen.has(child.pid)) continue;
+ if (parentStart !== null && child.createdAt < parentStart - START_TOLERANCE_MS) continue;
+ if (before !== null && child.createdAt >= before) continue;
+ seen.add(child.pid);
+ found.push(child);
+ visit(child.pid, child.createdAt, null);
+ }
+ };
+ visit(root, rootStart, successor ? successor.createdAt : null);
+ return found;
+}
+
+/** `entry` holds the id now, but is not the process recorded as starting at `startedAt`. */
+export function reused(entry: WindowsProcess, startedAt: number): boolean {
+ return Math.abs(entry.createdAt - startedAt) > START_TOLERANCE_MS;
+}
diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.ts
index 19e9bafd3..ab47b7b94 100644
--- a/console/packages/agent-providers/src/index.ts
+++ b/console/packages/agent-providers/src/index.ts
@@ -66,6 +66,16 @@ export {
sharedSessionRoot,
} from './host/launch';
export type { Supervision } from './host/launch';
+export { commandLineNames, killProcessTree, processCommandLine } from './host/process-fence';
+export { execProvider, findOnPath, spawnProvider, stopProvider } from './provider-process';
+export { replaceFile } from './host/replace-file';
+export {
+ isStopMessage,
+ onStopRequest,
+ requestChildStop,
+ requestStop,
+ STOP_MESSAGE,
+} from './host/stop-request';
export { hostStartSources, type HostStartSource } from './host/session-start';
export {
type AgentEventStream,
@@ -153,6 +163,7 @@ export {
PROVIDER_RUNTIMES,
providerRuntime,
providerRuntimeIds,
+ providerUnsupportedReason,
} from './providers/registry';
export type { ProviderRuntime, ProviderRuntimeOptions } from './providers/registry';
export { CONTROL_FILE, ControlClient, SidecarConnectionClosedError } from './host/control';
diff --git a/console/packages/agent-providers/src/opencode/server.ts b/console/packages/agent-providers/src/opencode/server.ts
index fad5be94c..b19a98ba9 100644
--- a/console/packages/agent-providers/src/opencode/server.ts
+++ b/console/packages/agent-providers/src/opencode/server.ts
@@ -1,8 +1,9 @@
-import { type ChildProcess, spawn } from 'node:child_process';
+import type { ChildProcess } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { rm } from 'node:fs/promises';
import { createServer } from 'node:net';
import { ProviderUnavailableError } from '../adapter';
+import { spawnProvider, stopProvider } from '../provider-process';
import type { OpencodeConfigFile } from './config';
import { prepareOpencodeHome } from './home';
@@ -60,15 +61,19 @@ export async function startOpencodeServer(input: StartServerInput): Promise<Open
const port = await findFreePort();
const configHome = await prepareOpencodeHome(input.config, input.skills, input.env);
- const child = spawn(input.binaryPath, ['serve', '--hostname=127.0.0.1', `--port=${port}`], {
- cwd: input.cwd,
- env: {
- ...input.env,
- XDG_CONFIG_HOME: configHome,
- OPENCODE_SERVER_PASSWORD: password,
- },
- stdio: ['ignore', 'pipe', 'pipe'],
- });
+ const child = spawnProvider(
+ input.binaryPath,
+ ['serve', '--hostname=127.0.0.1', `--port=${port}`],
+ {
+ cwd: input.cwd,
+ env: {
+ ...input.env,
+ XDG_CONFIG_HOME: configHome,
+ OPENCODE_SERVER_PASSWORD: password,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }
+ );
try {
const url = await new Promise<string>((resolve, reject) => {
@@ -82,7 +87,7 @@ export async function startOpencodeServer(input: StartServerInput): Promise<Open
};
const timer = setTimeout(() => {
finish(() => {
- child.kill('SIGKILL');
+ stopProvider(child, 'SIGKILL');
reject(
new ProviderUnavailableError(
'opencode',
@@ -137,7 +142,7 @@ export async function stopOpencodeServer(
const child = server.process;
if (child.pid && child.exitCode === null && child.signalCode === null) {
await new Promise<void>((resolve, reject) => {
- const kill = setTimeout(() => child.kill('SIGKILL'), 2000);
+ const kill = setTimeout(() => stopProvider(child, 'SIGKILL'), 2000);
const timeout = setTimeout(() => {
cleanup();
reject(new Error('OpenCode process did not exit after termination.'));
@@ -152,7 +157,7 @@ export async function stopOpencodeServer(
resolve();
};
child.once('exit', exited);
- child.kill('SIGTERM');
+ stopProvider(child, 'SIGTERM');
});
}
await rm(server.configHome, { recursive: true, force: true });
diff --git a/console/packages/agent-providers/src/provider-process.test.ts b/console/packages/agent-providers/src/provider-process.test.ts
new file mode 100644
index 000000000..9681d76dd
--- /dev/null
+++ b/console/packages/agent-providers/src/provider-process.test.ts
@@ -0,0 +1,83 @@
+import { once } from 'node:events';
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, join } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { execProvider, findOnPath, spawnProvider, stopProvider } from './provider-process';
+
+let dir: string;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'provider-process-'));
+});
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+describe.skipIf(process.platform === 'win32')('on macOS and Linux', () => {
+ it('finds the first executable on PATH', async () => {
+ const empty = join(dir, 'empty');
+ const bin = join(dir, 'bin');
+ for (const [path, mode] of [
+ [join(dir, 'tool'), 0o644],
+ [join(dir, 'bin-tool'), 0o755],
+ ] as const) {
+ writeFileSync(path, '#!/bin/sh\n');
+ chmodSync(path, mode);
+ }
+ expect(await findOnPath('tool', [empty, dir].join(delimiter))).toBeNull();
+ expect(await findOnPath('bin-tool', [empty, bin, dir].join(delimiter))).toBe(
+ join(dir, 'bin-tool')
+ );
+ });
+});
+
+/** A `.cmd` CLI like npm's shims: it runs node on a script beside it with its arguments. */
+function writeCmdCli(name: string, script: string): string {
+ writeFileSync(join(dir, `${name}.js`), script);
+ writeFileSync(
+ join(dir, `${name}.cmd`),
+ `@ECHO off\r\n"${process.execPath}" "%~dp0\\${name}.js" %*\r\n`
+ );
+ return join(dir, `${name}.cmd`);
+}
+
+describe.runIf(process.platform === 'win32')('on Windows', () => {
+ it('finds a .cmd CLI by its bare name, and not npm’s extensionless shell script', async () => {
+ writeFileSync(join(dir, 'tool'), '#!/bin/sh\n');
+ writeCmdCli('tool', '');
+ expect((await findOnPath('tool', dir))?.toLowerCase()).toBe(
+ join(dir, 'tool.cmd').toLowerCase()
+ );
+ });
+
+ it('runs a .cmd CLI with its arguments intact', async () => {
+ const cli = writeCmdCli('echo-args', 'console.log(JSON.stringify(process.argv.slice(2)))');
+ const args = ['plain', 'with space', 'quote"inside', '100%', 'a&b'];
+ const { stdout } = await execProvider(cli, args, { timeout: 30_000 });
+ expect(JSON.parse(stdout)).toEqual(args);
+ }, 60_000);
+
+ it('stops a .cmd CLI and the process it runs, not just cmd.exe', async () => {
+ const cli = writeCmdCli(
+ 'long-running',
+ 'console.log(process.pid); setInterval(() => {}, 1000)'
+ );
+ const child = spawnProvider(cli, [], { stdio: ['ignore', 'pipe', 'ignore'] });
+ const [line] = await once(child.stdout!, 'data');
+ const node = Number(String(line).trim());
+ const exited = once(child, 'exit');
+ stopProvider(child, 'SIGTERM');
+ await exited;
+ for (let waited = 0; waited < 10_000; waited += 200) {
+ try {
+ process.kill(node, 0);
+ } catch {
+ return;
+ }
+ await delay(200);
+ }
+ process.kill(node);
+ throw new Error('The CLI behind cmd.exe was left running.');
+ }, 60_000);
+});
diff --git a/console/packages/agent-providers/src/provider-process.ts b/console/packages/agent-providers/src/provider-process.ts
new file mode 100644
index 000000000..7e26124af
--- /dev/null
+++ b/console/packages/agent-providers/src/provider-process.ts
@@ -0,0 +1,104 @@
+import {
+ type ChildProcess,
+ execFile,
+ type ExecFileOptions,
+ spawn,
+ type SpawnOptions,
+} from 'node:child_process';
+import { constants, existsSync } from 'node:fs';
+import { access } from 'node:fs/promises';
+import { delimiter, join } from 'node:path';
+import { promisify } from 'node:util';
+import {
+ resolveExecFileSpawn,
+ resolveWindowsCommandPath,
+} from '@switch-console/shared/windows-spawn';
+import { killProcessTree } from './host/process-fence';
+
+/**
+ * Starting a provider's CLI, wherever it was installed from.
+ *
+ * On Windows a CLI installed with npm is a `.cmd` file, which Node refuses to
+ * start without a shell; it goes through `cmd.exe /d /s /c` with its command
+ * line quoted by hand instead (`resolveExecFileSpawn`), never `shell: true`.
+ * A bare name is looked up on PATH with PATHEXT, as cmd.exe would. Elsewhere,
+ * and for a plain `.exe`, nothing changes.
+ */
+function resolved(command: string, args: readonly string[], env: NodeJS.ProcessEnv | undefined) {
+ return resolveExecFileSpawn({
+ command,
+ args: [...args],
+ platform: process.platform,
+ env: env ?? process.env,
+ fileExists: existsSync,
+ });
+}
+
+export function spawnProvider(
+ command: string,
+ args: readonly string[],
+ options: SpawnOptions
+): ChildProcess {
+ const target = resolved(command, args, options.env);
+ return spawn(target.command, target.args, {
+ ...options,
+ windowsHide: true,
+ windowsVerbatimArguments: target.windowsVerbatimArguments,
+ });
+}
+
+export function execProvider(
+ command: string,
+ args: readonly string[],
+ options: ExecFileOptions
+): Promise<{ stdout: string; stderr: string }> {
+ const target = resolved(command, args, options.env);
+ return promisify(execFile)(target.command, target.args, {
+ ...options,
+ encoding: 'utf8',
+ windowsHide: true,
+ windowsVerbatimArguments: target.windowsVerbatimArguments,
+ }) as Promise<{ stdout: string; stderr: string }>;
+}
+
+/**
+ * The file `name` runs from, looked up in the directories of `path`: the first
+ * executable one, or on Windows the first with an extension from PATHEXT, as
+ * cmd.exe finds it (npm's extensionless shell script beside `claude.cmd` is
+ * not one Windows can run).
+ */
+export async function findOnPath(name: string, path: string | undefined): Promise<string | null> {
+ if (process.platform === 'win32')
+ return resolveWindowsCommandPath({
+ command: name,
+ env: { PATH: path ?? '', PATHEXT: process.env.PATHEXT },
+ fileExists: existsSync,
+ });
+ for (const directory of (path ?? '').split(delimiter).filter(Boolean)) {
+ const candidate = join(directory, name);
+ try {
+ await access(candidate, constants.X_OK);
+ return candidate;
+ } catch {
+ continue;
+ }
+ }
+ return null;
+}
+
+/**
+ * Ends a provider process. On Windows the child may be the `cmd.exe` a
+ * `.cmd` CLI runs under, and killing it alone would leave the CLI running,
+ * so the whole tree goes; there is no gentler signal to send there.
+ */
+export function stopProvider(child: ChildProcess, signal: NodeJS.Signals): void {
+ if (process.platform !== 'win32' || !child.pid) {
+ child.kill(signal);
+ return;
+ }
+ const pid = child.pid;
+ killProcessTree(pid).catch((error: unknown) => {
+ console.error(`Could not stop the provider process (pid ${pid}): ${String(error)}`);
+ child.kill(signal);
+ });
+}
diff --git a/console/packages/agent-providers/src/providers/registry.ts b/console/packages/agent-providers/src/providers/registry.ts
index f4061b82f..4f68eb0aa 100644
--- a/console/packages/agent-providers/src/providers/registry.ts
+++ b/console/packages/agent-providers/src/providers/registry.ts
@@ -34,6 +34,8 @@ export interface ProviderRuntime {
* session host passes through from the machine's environment.
*/
inheritEnv: readonly string[];
+ /** The platforms the CLI cannot run on, each with the reason a person is told. */
+ unsupportedPlatforms: Partial<Record<NodeJS.Platform, string>>;
createAdapter(options: ProviderRuntimeOptions): ProviderAdapter;
/** Whether the CLI is signed in, answered without signing it in. */
checkSignIn(input: SignInCheckInput): Promise<ProviderReadiness>;
@@ -45,6 +47,7 @@ export function acpProviderRuntime(hooks: AcpProviderHooks): ProviderRuntime {
id: hooks.provider,
loginCommand: hooks.loginCommand,
inheritEnv: hooks.inheritEnv ?? [],
+ unsupportedPlatforms: hooks.unsupportedPlatforms ?? {},
createAdapter: ({ binaryPath, logger }) => createAcpAdapter(hooks, { binaryPath, logger }),
checkSignIn: (input) => checkAcpSignIn(hooks, input),
};
@@ -61,6 +64,7 @@ export const PROVIDER_RUNTIMES: readonly ProviderRuntime[] = [
id: 'claude',
loginCommand: CLAUDE_LOGIN,
inheritEnv: [],
+ unsupportedPlatforms: {},
createAdapter: ({ binaryPath, logger }) =>
createClaudeAdapter({ claudeExecutablePath: binaryPath, ...(logger ? { logger } : {}) }),
checkSignIn: checkClaudeSignIn,
@@ -69,6 +73,7 @@ export const PROVIDER_RUNTIMES: readonly ProviderRuntime[] = [
id: 'codex',
loginCommand: CODEX_LOGIN,
inheritEnv: [],
+ unsupportedPlatforms: {},
createAdapter: ({ binaryPath, logger }) =>
createCodexAdapter({ binaryPath, ...(logger ? { logger } : {}) }),
checkSignIn: checkCodexSignIn,
@@ -77,6 +82,7 @@ export const PROVIDER_RUNTIMES: readonly ProviderRuntime[] = [
id: 'opencode',
loginCommand: OPENCODE_LOGIN,
inheritEnv: [],
+ unsupportedPlatforms: {},
createAdapter: ({ binaryPath, logger, skill }) =>
createOpencodeAdapter({
binaryPath,
@@ -99,6 +105,11 @@ export function isProviderRuntime(id: string): boolean {
return RUNTIMES.has(id);
}
+/** Why the provider cannot run on `platform`, or null when it can. */
+export function providerUnsupportedReason(id: string, platform: NodeJS.Platform): string | null {
+ return RUNTIMES.get(id)?.unsupportedPlatforms[platform] ?? null;
+}
+
export function providerRuntime(id: string): ProviderRuntime {
const runtime = RUNTIMES.get(id);
if (!runtime) throw new Error(`Unsupported execution provider: ${id}`);
diff --git a/console/packages/agent-providers/src/testing/index.ts b/console/packages/agent-providers/src/testing/index.ts
index 91e829b17..24ff65fe5 100644
--- a/console/packages/agent-providers/src/testing/index.ts
+++ b/console/packages/agent-providers/src/testing/index.ts
@@ -1,4 +1,5 @@
export { EventRecorder } from './event-recorder';
+export { writeNodeCli } from './node-cli';
export type { ConformanceOptions, ConformanceScenario } from './conformance';
export { conformanceScenarios, describeConformance } from './conformance';
export { echoMcpServerSpec } from './fixtures/index';
diff --git a/console/packages/agent-providers/src/testing/node-cli.ts b/console/packages/agent-providers/src/testing/node-cli.ts
new file mode 100644
index 000000000..7f093a266
--- /dev/null
+++ b/console/packages/agent-providers/src/testing/node-cli.ts
@@ -0,0 +1,19 @@
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+
+/**
+ * Writes a CLI for a test that runs `script` with this Node, and returns the
+ * path to start it by: an executable script with a shebang on macOS and Linux,
+ * or a `.cmd` beside the script on Windows, the way npm installs one there.
+ */
+export async function writeNodeCli(dir: string, name: string, script: string): Promise<string> {
+ if (process.platform !== 'win32') {
+ const path = join(dir, name);
+ await writeFile(path, `#!${process.execPath}\n${script}`, { mode: 0o700 });
+ return path;
+ }
+ await writeFile(join(dir, `${name}.js`), script);
+ const path = join(dir, `${name}.cmd`);
+ await writeFile(path, `@ECHO off\r\n"${process.execPath}" "%~dp0\\${name}.js" %*\r\n`);
+ return path;
+}
diff --git a/console/packages/agent-providers/src/transport/stdio-json-rpc.ts b/console/packages/agent-providers/src/transport/stdio-json-rpc.ts
index c47038bf0..acfef01f2 100644
--- a/console/packages/agent-providers/src/transport/stdio-json-rpc.ts
+++ b/console/packages/agent-providers/src/transport/stdio-json-rpc.ts
@@ -1,6 +1,7 @@
-import { type ChildProcess, spawn } from 'node:child_process';
+import type { ChildProcess } from 'node:child_process';
import { createInterface } from 'node:readline';
import { Transform } from 'node:stream';
+import { spawnProvider, stopProvider } from '../provider-process';
export interface ProviderLogger {
debug(message: string, context?: Record<string, unknown>): void;
@@ -77,7 +78,7 @@ export class StdioJsonRpcClient {
constructor(options: StdioJsonRpcClientOptions) {
this.logger = options.logger;
this.onExit = options.onExit;
- this.child = spawn(options.command, options.args, {
+ this.child = spawnProvider(options.command, options.args, {
cwd: options.cwd,
env: options.env,
stdio: ['pipe', 'pipe', 'pipe'],
@@ -103,7 +104,7 @@ export class StdioJsonRpcClient {
},
});
bounded.on('error', (error) => {
- this.child.kill('SIGKILL');
+ stopProvider(this.child, 'SIGKILL');
this.handleExit(error.message);
});
stdout.pipe(bounded);
@@ -112,7 +113,7 @@ export class StdioJsonRpcClient {
const error = options.rejectOutputLine?.(line);
if (error) {
this.handleExit(error);
- this.child.kill('SIGTERM');
+ stopProvider(this.child, 'SIGTERM');
} else this.handleLine(line);
})
.on('error', (error) => this.handleExit(error.message));
@@ -122,7 +123,7 @@ export class StdioJsonRpcClient {
if (error) {
this.stderrTail = error;
this.handleExit(error);
- this.child.kill('SIGTERM');
+ stopProvider(this.child, 'SIGTERM');
}
});
@@ -196,7 +197,7 @@ export class StdioJsonRpcClient {
async dispose(): Promise<void> {
if (this.processExited) return;
await new Promise<void>((resolve, reject) => {
- const kill = setTimeout(() => this.child.kill('SIGKILL'), 2000);
+ const kill = setTimeout(() => stopProvider(this.child, 'SIGKILL'), 2000);
const timeout = setTimeout(() => {
cleanup();
reject(new Error('Provider process did not exit after termination.'));
@@ -212,7 +213,9 @@ export class StdioJsonRpcClient {
};
this.child.once('exit', exited);
this.child.stdin?.end();
- this.child.kill('SIGTERM');
+ // On Windows any kill is immediate: the closed stdin is the request to
+ // stop, and the kill above is what follows it.
+ if (process.platform !== 'win32') this.child.kill('SIGTERM');
});
}
diff --git a/console/packages/core/src/exec/index.ts b/console/packages/core/src/exec/index.ts
index 8bd4582e1..7a6da0d89 100644
--- a/console/packages/core/src/exec/index.ts
+++ b/console/packages/core/src/exec/index.ts
@@ -7,13 +7,13 @@ export {
getWindowsPathDirs,
getWindowsPathExts,
getWindowsShellExecutable,
- quoteForCmdExe,
+ escapeCmdExeArgument,
+ escapeCmdExeCommand,
resolveExecFileSpawn,
resolveWindowsCommandPath,
- wrapCmdExeCommandLine,
type ExecFileSpawn,
type FileExists,
-} from './windows-spawn';
+} from '@switch-console/shared/windows-spawn';
export {
ExecError,
type BoundExec,
diff --git a/console/packages/shared/package.json b/console/packages/shared/package.json
index 70f472322..c6ac8eec6 100644
--- a/console/packages/shared/package.json
+++ b/console/packages/shared/package.json
@@ -20,6 +20,10 @@
"./session-v1": {
"types": "./dist/session-v1.d.mts",
"default": "./dist/session-v1.mjs"
+ },
+ "./windows-spawn": {
+ "types": "./dist/windows-spawn.d.mts",
+ "default": "./dist/windows-spawn.mjs"
}
},
"scripts": {
diff --git a/console/packages/core/src/exec/windows-spawn.test.ts b/console/packages/shared/src/windows-spawn.test.ts
similarity index 78%
rename from console/packages/core/src/exec/windows-spawn.test.ts
rename to console/packages/shared/src/windows-spawn.test.ts
index 83f7fc62a..c79bde7f3 100644
--- a/console/packages/core/src/exec/windows-spawn.test.ts
+++ b/console/packages/shared/src/windows-spawn.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'vitest';
import {
getWindowsEnvValue,
- quoteForCmdExe,
+ escapeCmdExeArgument,
+ escapeCmdExeCommand,
resolveExecFileSpawn,
resolveWindowsCommandPath,
} from './windows-spawn';
@@ -27,15 +28,23 @@ describe('getWindowsEnvValue', () => {
});
});
-describe('quoteForCmdExe', () => {
- it('quotes a path containing a space', () => {
- expect(quoteForCmdExe('C:\\Program Files\\nodejs\\npm.cmd')).toBe(
- '"C:\\Program Files\\nodejs\\npm.cmd"'
+describe('escapeCmdExeCommand', () => {
+ it('caret-escapes a space and other metacharacters in a program path', () => {
+ expect(escapeCmdExeCommand('C:\\Program Files (x86)\\npm.cmd')).toBe(
+ 'C:\\Program^ Files^ ^(x86^)\\npm.cmd'
);
});
+});
+
+describe('escapeCmdExeArgument', () => {
+ it('quotes, then caret-escapes twice for the batch file’s own pass', () => {
+ expect(escapeCmdExeArgument('a&b')).toBe('^^^"a^^^&b^^^"');
+ expect(escapeCmdExeArgument('100%')).toBe('^^^"100^^^%^^^"');
+ });
- it('escapes cmd.exe metacharacters', () => {
- expect(quoteForCmdExe('a&b')).toBe('"a^&b"');
+ it('escapes an embedded quote and the backslashes before it for the C runtime', () => {
+ expect(escapeCmdExeArgument('say "hi"')).toBe('^^^"say^^^ \\^^^"hi\\^^^"^^^"');
+ expect(escapeCmdExeArgument('C:\\dir\\')).toBe('^^^"C:\\dir\\\\^^^"');
});
});
@@ -95,12 +104,11 @@ describe('resolveExecFileSpawn', () => {
});
expect(spawn.command).toBe('C:\\Windows\\System32\\cmd.exe');
- // The whole line is wrapped once more because it starts with a quote.
expect(spawn.args).toEqual([
'/d',
'/s',
'/c',
- '""C:\\Program Files\\nodejs\\npm.CMD" root -g"',
+ '"C:\\Program^ Files\\nodejs\\npm.CMD ^^^"root^^^" ^^^"-g^^^""',
]);
expect(spawn.windowsVerbatimArguments).toBe(true);
});
@@ -131,6 +139,6 @@ describe('resolveExecFileSpawn', () => {
});
expect(spawn.command).toBe('C:\\Windows\\System32\\cmd.exe');
- expect(spawn.args[3]).toBe('D:\\tools\\claude.cmd --version');
+ expect(spawn.args[3]).toBe('"D:\\tools\\claude.cmd ^^^"--version^^^""');
});
});
diff --git a/console/packages/core/src/exec/windows-spawn.ts b/console/packages/shared/src/windows-spawn.ts
similarity index 82%
rename from console/packages/core/src/exec/windows-spawn.ts
rename to console/packages/shared/src/windows-spawn.ts
index c2c3714b9..af1c065cf 100644
--- a/console/packages/core/src/exec/windows-spawn.ts
+++ b/console/packages/shared/src/windows-spawn.ts
@@ -58,24 +58,24 @@ export function getWindowsPathExts(
});
}
-export function quoteForCmdExe(input: string): string {
- if (input.length === 0) return '""';
- if (!/[\s"^&|<>()%!]/.test(input)) return input;
- return `"${input
- .replace(/%/g, '%%')
- .replace(/!/g, '^!')
- .replace(/(["^&|<>()])/g, '^$1')}"`;
+/** What cmd.exe treats specially on a command line. */
+const CMD_EXE_META = /([()\][%!^"`<>&|;, *?])/g;
+
+/** A program path for a cmd.exe command line: each metacharacter caret-escaped. */
+export function escapeCmdExeCommand(command: string): string {
+ return command.replace(CMD_EXE_META, '^$1');
}
/**
- * cmd.exe + /S /C has a quirk: if the command string starts with a quote, the
- * outer quotes are taken as part of the executable name (printed back as
- * `'"C:\Program Files\..."' is not recognized`). The documented workaround is
- * to wrap the entire command line in an extra pair of outer quotes so cmd.exe
- * strips one layer and runs the still-quoted path.
+ * One argument for a cmd.exe command line that runs a batch file: quoted for
+ * the C runtime parser of the program the batch file starts (backslashes
+ * before a quote doubled, the quote escaped), then caret-escaped for cmd.exe —
+ * twice, since the batch file's `%*` is parsed by cmd.exe a second time. This
+ * is cross-spawn's algorithm, after https://qntm.org/cmd.
*/
-export function wrapCmdExeCommandLine(commandLine: string): string {
- return commandLine.startsWith('"') ? `"${commandLine}"` : commandLine;
+export function escapeCmdExeArgument(argument: string): string {
+ const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1')}"`;
+ return quoted.replace(CMD_EXE_META, '^$1').replace(CMD_EXE_META, '^$1');
}
function hasWindowsPathSeparator(command: string): boolean {
@@ -180,10 +180,10 @@ export function resolveExecFileSpawn({
return { command: resolved, args, windowsVerbatimArguments: false };
}
- const commandLine = [resolved, ...args].map(quoteForCmdExe).join(' ');
+ const commandLine = [escapeCmdExeCommand(resolved), ...args.map(escapeCmdExeArgument)].join(' ');
return {
command: getWindowsShellExecutable(env),
- args: ['/d', '/s', '/c', wrapCmdExeCommandLine(commandLine)],
+ args: ['/d', '/s', '/c', `"${commandLine}"`],
windowsVerbatimArguments: true,
};
}
diff --git a/console/packages/shared/tsdown.config.ts b/console/packages/shared/tsdown.config.ts
index 68c60a480..4ac9336fd 100644
--- a/console/packages/shared/tsdown.config.ts
+++ b/console/packages/shared/tsdown.config.ts
@@ -1,7 +1,11 @@
import { defineConfig } from 'tsdown';
export default defineConfig({
- entry: { index: 'src/index.ts', 'session-v1': 'src/session-v1/index.ts' },
+ entry: {
+ index: 'src/index.ts',
+ 'session-v1': 'src/session-v1/index.ts',
+ 'windows-spawn': 'src/windows-spawn.ts',
+ },
format: ['esm'],
dts: true,
deps: {},