Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(console): make the Windows paths work (#207)
Louis Amaudruz0ca1127bd8f4
diff --git a/artifacts.yaml b/artifacts.yamlindex ee49547bb..5ae232066 100644--- a/artifacts.yaml+++ b/artifacts.yaml@@ -90,7 +90,7 @@ artifacts:The remote runtime Switch Console deploys to an agent host. Deployed ratherthan published, so nothing else declares its version — this file is itsonly source and the constant is generated from it.- version: 1.9.0+ version: 1.9.1# ── Published under the switch-core release ────────────────────────────────# No version of their own: `helm package` and the image build stamp them withdiff --git a/console/AGENTS.md b/console/AGENTS.mdindex 5cab70f0d..a8cf74ad6 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -556,6 +556,33 @@ pnpm run test`SWITCHDASH_DB_FILE`, `SWITCHDASH_DISABLE_NATIVE_DB`,`SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`, and`SWITCHDASH_FAKE_UPDATE`.+- **A hook command is built for the machine the session runs on, not for the one+ building it.** `writeHooks(fs, hooks, { platform })` takes the target+ platform: `process.platform` locally and in the sidecar, the VM's `uname -s`+ in `SshAgentRuntime.installRemoteHooks`. A `makeStdinHookCommand(...)` returns+ a builder, not a string, so nothing can freeze the wrong shell at import time.+ Getting this wrong is silent — the POSIX form ends in `|| true` and agents+ ignore hook exit codes, so the only symptom is a remote session whose provider+ session id is never captured and whose room never stops saying "working on it".+- **A Windows hook command carries no quotes of its own.** It is a bare+ `powershell.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand <base64>`,+ never a `cmd.exe /d /c "…"` wrapper. Hosts wrap a `command` hook in a shell+ before running it, and Claude Code's wrapping did not reliably survive the+ inner double quotes: when they were lost, cmd.exe ignored its `/c` argument,+ opened an interactive prompt and exited 0 — a hook that reported success+ having never run. Because the marker then exists only inside the base64,+ `isManagedHookEntry` decodes it; matching on the raw string would stop+ recognising managed entries and append a duplicate on every launch.+- The Codex Windows install list leads with the ChatGPT `install.ps1`, and npm's+ option is stripped of the `recommended` flag `npmDependency` adds for every+ platform — both `pickInstallOption` and the settings UI take the *first*+ recommended option, so leaving it on npm steers Windows users there whatever+ the order. The script ships no uninstaller, so the descriptor removes exactly+ the two directories it creates (`%LOCALAPPDATA%\Programs\OpenAI\Codex` and+ `%USERPROFILE%\.codex\packages\standalone`) and leaves the rest of+ `~/.codex` — config, auth, sessions — alone. It is written without `$` or `%`+ because the install runner's shell may be either PowerShell or cmd.exe, and+ each would expand one of them before `powershell -c` ran.- An auto-approving Codex session launches with `-c approval_policy="never"` andnothing else. The sandbox is deliberately **not** overridden: "Bypasspermissions" promises unattended approvals, not unattended filesystem anddiff --git a/console/apps/switch-console-desktop/package.json b/console/apps/switch-console-desktop/package.jsonindex 385d8b935..e8ec2b021 100644--- a/console/apps/switch-console-desktop/package.json+++ b/console/apps/switch-console-desktop/package.json@@ -40,7 +40,7 @@"package:linux:arm64": "pnpm run build && electron-builder --linux --arm64 --publish never --config electron-builder.config.ts","package:win": "pnpm run build && electron-builder --win --publish never --config electron-builder.config.ts","postinstall": "node --experimental-strip-types scripts/postinstall.ts",- "rebuild": "electron-rebuild -f -v 40.7.0 --only=better-sqlite3,node-pty",+ "rebuild": "electron-rebuild -f --only=better-sqlite3,node-pty","deeplink:reset": "node --experimental-strip-types scripts/reset-deeplink-handler.ts","clean": "rm -rf node_modules dist","reset": "pnpm run clean && pnpm install",diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/hook-config-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/hook-config-service.tsindex db8f1ac0d..a9cf1464c 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/hook-config-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/hook-config-service.ts@@ -64,7 +64,9 @@ export async function ensureHooksInstalled({const scope = hooksDescriptor.scope;const root = scope === 'global' ? homedir() : sessionPath;const fs = createPluginFs(root);- const paths = await plugin.behavior.hooks.writeHooks(fs, []);+ const paths = await plugin.behavior.hooks.writeHooks(fs, [], {+ platform: process.platform,+ });// For global-scope hooks the paths are relative to homedir; don't add// them to the workspace .gitignore (they live in the user's home).writtenPaths = scope === 'global' ? [] : paths;diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-node-platform.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-node-platform.tsnew file mode 100644index 000000000..a660001e2--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-node-platform.ts@@ -0,0 +1,44 @@+import type { IExecutionContext } from '@main/core/execution-context/types';+import { log } from '@main/lib/logger';++/**+ * The remote host's platform, in Node's `process.platform` vocabulary.+ *+ * Anything Switch Console generates for a session to *run* — hook commands above all —+ * has to be built for the machine the session runs on, not for the machine+ * building it. A Windows console driving a Linux VM would otherwise SFTP+ * `cmd.exe /d /c "... powershell.exe ..."` into the VM's agent config, where+ * every hook fails silently.+ *+ * Cached per connection: the answer cannot change for the life of an SSH+ * connection, and hook installs run on every session spawn.+ */+const probes = new Map<string, Promise<NodeJS.Platform>>();++async function probeRemotePlatform(ctx: IExecutionContext): Promise<NodeJS.Platform> {+ const { stdout } = await ctx.exec('uname', ['-s']);+ const kernel = stdout.trim().toLowerCase();+ if (kernel.includes('darwin')) return 'darwin';+ if (kernel.includes('linux')) return 'linux';+ throw new Error(`unrecognised remote kernel '${stdout.trim()}'`);+}++export function remoteNodePlatform(+ connectionId: string,+ ctx: IExecutionContext+): Promise<NodeJS.Platform> {+ const cached = probes.get(connectionId);+ if (cached) return cached;+ const probe = probeRemotePlatform(ctx).catch((error) => {+ probes.delete(connectionId);+ // Every remote host Switch Console supports is POSIX, so this is the useful guess —+ // but say so, because a wrong one costs the session all of its hooks.+ log.warn('remoteNodePlatform: uname failed, assuming linux', {+ connectionId,+ error: String((error as Error)?.message ?? error),+ });+ return 'linux' as NodeJS.Platform;+ });+ probes.set(connectionId, probe);+ return probe;+}diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex 12213de20..45a39caf3 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@ -153,10 +153,16 @@ function makeProxy(overrides: Partial<SshClientProxy> = {}): SshClientProxy {} as unknown as SshClientProxy;}-/** A remote host with an empty home: the home-rooted read probe answers `0`- * ("no such file") and every other command exits quietly. */+/** A remote host with an empty home: `uname -s` reports the Linux VM every+ * remote host is, the home-rooted read probe answers `0` ("no such file"),+ * and every other command exits quietly. */function makeCtx(): ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'] {- return { exec: vi.fn(async () => ({ stdout: '0', stderr: '' })) } as never;+ return {+ exec: vi.fn(async (command: string) => ({+ stdout: command === 'uname' ? 'Linux' : '0',+ stderr: '',+ })),+ } as never;}/** A remote filesystem holding `files` (keyed by repo-relative path); anything@@ -425,6 +431,45 @@ describe('SshAgentRuntime', () => {]);});+ // The hook command runs on the VM, so it is the VM's shell that has to+ // understand it. A Windows console that writes its own `cmd.exe /d /c+ // "... powershell.exe ..."` into a Linux VM's hooks.json loses every event on+ // that host, and the `|| true` on the POSIX form means nobody ever sees why.+ it('writes POSIX hook commands onto a Linux VM even from a Windows console', async () => {+ const realPlatform = process.platform;+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });+ const ctx = makeCtx();+ vi.mocked(getPlugin).mockImplementation(+ (id: string) =>+ ({+ metadata: { id },+ capabilities: {+ hostDependency: { binaryNames: [id] },+ hooks: { kind: 'config', scope: 'global', supportedEvents: ['stop'] },+ },+ behavior: {+ prompt: { buildCommand: buildCommandMock },+ hooks: pluginRegistry.get('codex')!.behavior.hooks,+ },+ }) as never+ );+ mockSpawn([]);++ try {+ await sshProvider({ ctx, tmux: true }).start(session());+ } finally {+ Object.defineProperty(process, 'platform', { value: realPlatform, configurable: true });+ }++ const written = (vi.mocked(ctx.exec).mock.calls as unknown[][])+ .map((call) => (call[1] as string[]) ?? [])+ .find((args) => args.includes('.codex/hooks.json') && args[1]?.includes('base64 -d'));+ const contents = Buffer.from(written!.at(-1)!, 'base64').toString('utf8');++ expect(contents).toContain('curl -sf -X POST');+ expect(contents).not.toContain('cmd.exe');+ });+// Neither root fits a scope nobody has taught the remote path about, and the// session would come up with no hooks at all — which looks fine until someone// notices resume has been starting fresh conversations for a month.diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex b764321ae..2df0b626e 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -37,6 +37,7 @@ import { SIDECAR_VERSION } from '../../../../sidecar/sidecar-version';import { ensureAgentSidecar, probeAgentSidecar } from './ensure-agent-sidecar';import { scheduleInitialPromptInjection } from './keystroke-injection';import { createRemoteHomePluginFs } from './remote-home-plugin-fs';+import { remoteNodePlatform } from './remote-node-platform';import { createRemotePluginFs } from './remote-plugin-fs';import type { SidecarEndpoint, SidecarHost } from './remote-sidecar-launcher';import { resolveAgentExecutable } from './resolve-agent-executable';@@ -281,7 +282,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime/*** Install the provider's agent hooks onto the VM, mirroring what- * `ensureHooksInstalled` does for local sessions. The remote agent is spawned+ * `ensureHooksInstalled` does for local sessions — built for the VM's+ * platform, not the console's. The remote agent is spawned* with the `SWITCHDASH_HOOK_*` env vars, but those only matter if its config* actually registers the hook commands — otherwise the agent posts no* lifecycle events to the sidecar, so its provider session id is never@@ -305,6 +307,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime}const writeHooks = plugin.behavior.hooks.writeHooks;const fs = this.remoteHookFs(hooks.scope);+ const platform = await remoteNodePlatform(this.connectionId, this.ctx);// A global-scope write targets the VM's home, so it is shared by every dir// on the host; keying it on the dir would let one write per dir through.const scopeKey = hooks.scope === 'global' ? '~' : this.sessionPath;@@ -312,11 +315,12 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimeawait dedupeInFlight(remoteHookInstallsInFlight,`${this.connectionId}::${scopeKey}::${providerId}`,- () => writeHooks(fs, [])+ () => writeHooks(fs, [], { platform }));log.info('SshAgentRuntime: installed remote agent hooks', {providerId,scope: hooks.scope,+ platform,});} catch (error) {log.error('SshAgentRuntime: failed to install remote agent hooks', {diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.tsnew file mode 100644index 000000000..e95e91efd--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.test.ts@@ -0,0 +1,22 @@+import { pickInstallOption } from '@switch-console/core/deps/runtime';+import { describe, expect, it } from 'vitest';+import { CORE_DEPENDENCIES } from './core-dependencies';++function descriptor(id: string) {+ const found = CORE_DEPENDENCIES.find((d) => d.id === id);+ if (!found) throw new Error(`no core dependency ${id}`);+ return found;+}++describe('CORE_DEPENDENCIES on Windows', () => {+ it.each([+ ['git', 'winget install --id Git.Git'],+ ['node', 'winget install --id OpenJS.NodeJS.LTS'],+ ])('offers a winget install for %s', (id, command) => {+ expect(pickInstallOption(descriptor(id), 'windows')?.command).toBe(command);+ });++ it('has no Windows option for tmux, which does not run there', () => {+ expect(pickInstallOption(descriptor('tmux'), 'windows')).toBeUndefined();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.tsindex 3818a2399..6b5cc5f55 100644--- a/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/core-dependencies.ts@@ -53,6 +53,7 @@ export const CORE_DEPENDENCIES: DependencyDescriptor[] = [recommended: true,},],+ windows: [{ method: 'winget', command: 'winget install --id Git.Git', recommended: true }],},},{@@ -99,6 +100,13 @@ export const CORE_DEPENDENCIES: DependencyDescriptor[] = [recommended: true,},],+ windows: [+ {+ method: 'winget',+ command: 'winget install --id OpenJS.NodeJS.LTS',+ recommended: true,+ },+ ],},},];diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.test.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.test.tsindex 26ca7b5ae..944d660c5 100644--- a/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.test.ts@@ -63,6 +63,17 @@ const pwshProfile: ResolvedShellProfile = {commandArgs: ['-NoLogo', '-Command'],};+const posixProfile: ResolvedShellProfile = {+ id: 'zsh',+ resolvedShellId: 'zsh',+ resolvedFromSystem: true,+ executable: '/bin/zsh',+ available: true,+ family: 'posix',+ interactiveArgs: ['-il'],+ commandArgs: ['-c'],+};+beforeEach(() => {mocks.spawnLocalPty.mockReturnValue(createSuccessfulPty());});@@ -140,6 +151,46 @@ describe('runLocalInstallCommand', () => {);});+ it('keeps an argv spec as argv, so a spaced Windows shim path is not split', async () => {+ setPlatform('win32');+ delete process.env.SHELL;+ process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe';++ const result = await runLocalInstallCommand(+ { command: 'C:\\Program Files\\nodejs\\npm.cmd', args: ['uninstall', '-g', '@openai/codex'] },+ cmdProfile+ );++ expect(result.success).toBe(true);+ expect(mocks.spawnLocalPty).toHaveBeenCalledWith(+ expect.objectContaining({+ command: 'C:\\Windows\\System32\\cmd.exe',+ args: [+ '/d',+ '/s',+ '/c',+ '""C:\\Program Files\\nodejs\\npm.cmd" uninstall -g @openai/codex"',+ ],+ } satisfies Partial<LocalSpawnOptions>)+ );+ });++ it('quotes an argv spec for the POSIX shell', async () => {+ setPlatform('darwin');++ const result = await runLocalInstallCommand(+ { command: '/usr/local/bin/claude', args: ['custom-remove', '--force'] },+ posixProfile+ );++ expect(result.success).toBe(true);+ expect(mocks.spawnLocalPty).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['-c', '/usr/local/bin/claude custom-remove --force'],+ } satisfies Partial<LocalSpawnOptions>)+ );+ });+it('resolves the local install shell outside the low-level runner', async () => {setPlatform('win32');const resolveShellProfile = vi.fn(async () => pwshProfile);diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.tsindex 00b74cded..bcdd69fdb 100644--- a/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.ts+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/install-runner.ts@@ -1,17 +1,31 @@import os from 'node:os';-import type { InstallCommandError } from '@switch-console/core/deps/runtime';+import type { InstallCommandError, InstallCommandSpec } from '@switch-console/core/deps/runtime';import { err, ok, type Result } from '@switch-console/shared';import { spawnLocalPty } from '@main/core/pty/local-pty';import type { Pty } from '@main/core/pty/pty';-import { logLocalPtySpawnWarnings, resolveLocalPtySpawn } from '@main/core/pty/pty-spawn-platform';+import {+ logLocalPtySpawnWarnings,+ resolveLocalPtySpawn,+ type PtyCommandSpec,+} from '@main/core/pty/pty-spawn-platform';import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';import { log } from '@main/lib/logger';import { ensureUserBinDirsInPath } from '@main/utils/userEnv';export type InstallCommandRunner<TData = void, TError = InstallCommandError> = (- command: string+ command: InstallCommandSpec) => Promise<Result<TData, TError>>;+/**+ * An argv spec stays argv all the way into the PTY layer, which quotes it for+ * the target shell. Only a descriptor's own shell line is passed through as one.+ */+function toPtyCommand(command: InstallCommandSpec): PtyCommandSpec {+ return typeof command === 'string'+ ? { kind: 'shell-line', commandLine: command }+ : { kind: 'argv', command: command.command, args: command.args };+}+type ShellProfileResolver = () => Promise<ResolvedShellProfile>;const ANSI_RE = /\u001b\[[0-?]*[ -/]*[@-~]/g;@@ -60,7 +74,7 @@ function waitForInstallPty(pty: Pty): Promise<Result<void, InstallCommandError>>}export async function runLocalInstallCommand(- command: string,+ command: InstallCommandSpec,shellProfile: ResolvedShellProfile): Promise<Result<void, InstallCommandError>> {const installId = `install:${crypto.randomUUID()}`;@@ -70,7 +84,7 @@ export async function runLocalInstallCommand(intent: {kind: 'run-command',cwd: os.homedir(),- command: { kind: 'shell-line', commandLine: command },+ command: toPtyCommand(command),shellProfile,},});diff --git a/console/apps/switch-console-desktop/src/main/core/dependencies/ssh-install-runner.ts b/console/apps/switch-console-desktop/src/main/core/dependencies/ssh-install-runner.tsindex c2b268222..bb73b8d5f 100644--- a/console/apps/switch-console-desktop/src/main/core/dependencies/ssh-install-runner.ts+++ b/console/apps/switch-console-desktop/src/main/core/dependencies/ssh-install-runner.ts@@ -1,11 +1,18 @@-import type { InstallCommandError } from '@switch-console/core/deps/runtime';+import type { InstallCommandError, InstallCommandSpec } from '@switch-console/core/deps/runtime';import { err, ok, type Result } from '@switch-console/shared';import { openSsh2Pty } from '@main/core/pty/ssh2-pty';import { buildRemoteShellCommand } from '@main/core/ssh/lifecycle/remote-shell-profile';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';import { log } from '@main/lib/logger';+import { quoteShellArg } from '@main/utils/shellEscape';import { classifyInstallCommandFailure, type InstallCommandRunner } from './install-runner';+/** Remote hosts are POSIX-only today, so an argv spec is quoted for `sh`. */+function toRemoteCommandLine(command: InstallCommandSpec): string {+ if (typeof command === 'string') return command;+ return [command.command, ...command.args].map(quoteShellArg).join(' ');+}+/*** Runs an install/update command string on a remote host over SSH.*@@ -37,8 +44,9 @@ export function createSshInstallCommandRunner(onOutput: (chunk: string) => void): InstallCommandRunner {return async (command) => {+ const commandLine = toRemoteCommandLine(command);const profile = await proxy.getRemoteShellProfile();- const remoteCommand = buildRemoteShellCommand(profile, command);+ const remoteCommand = buildRemoteShellCommand(profile, commandLine);const installId = `ssh-install:${crypto.randomUUID()}`;const opened = await openSsh2Pty(proxy, {@@ -73,7 +81,7 @@ export function createSshInstallCommandRunner(stallTimer = setTimeout(() => {const output = chunks.join('').trim();log.error('[SshDependencyManager] Remote install produced no output; abandoning', {- command,+ command: commandLine,output,});// Kill it rather than leaving it: a stopped install holds the packagediff --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.tsindex 0390bb318..5ac1f771a 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@@ -85,6 +85,28 @@ describe('LocalExecutionContext', () => {);});+ it('routes a Windows .cmd shim through cmd.exe instead of failing with EINVAL', async () => {+ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });+ process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe';+ execFileMock.mockImplementation((_command, _args, _options, callback) => {+ callback(null, { stdout: '', stderr: '' });+ });++ try {+ await new LocalExecutionContext().exec('D:\\tools\\npm.cmd', ['root', '-g']);+ } finally {+ if (originalPlatform) Object.defineProperty(process, 'platform', originalPlatform);+ }++ expect(execFileMock).toHaveBeenCalledWith(+ 'C:\\Windows\\System32\\cmd.exe',+ ['/d', '/s', '/c', 'D:\\tools\\npm.cmd root -g'],+ expect.objectContaining({ windowsVerbatimArguments: true }),+ expect.any(Function)+ );+ });+it('explains when git is missing during streaming local execution', async () => {const child = new FakeChildProcess();spawnMock.mockReturnValue(child);diff --git a/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.ts b/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.tsindex 11e2af295..35df1b44a 100644--- a/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.ts+++ b/console/apps/switch-console-desktop/src/main/core/execution-context/local-execution-context.ts@@ -1,7 +1,9 @@import { execFile, spawn } from 'node:child_process';+import { existsSync } from 'node:fs';import { promisify } from 'node:util';+import { resolveExecFileSpawn } from '@switch-console/core/exec';import {- GIT_EXECUTABLE,+ getGitExecutable,isMissingGitExecutableError,missingGitExecutableError,} from '@main/core/utils/exec';@@ -34,17 +36,33 @@ export class LocalExecutionContext implements IExecutionContext {}private resolveCommand(command: string): string {- return command === 'git' ? GIT_EXECUTABLE : command;+ return command === 'git' ? getGitExecutable() : command;+ }++ /**+ * Rewrites the argv so a Windows `.cmd`/`.bat` shim — how every npm-global CLI+ * installs there — runs through cmd.exe instead of failing with EINVAL.+ */+ private resolveSpawn(command: string, args: string[]) {+ return resolveExecFileSpawn({+ command: this.resolveCommand(command),+ args,+ platform: process.platform,+ env: process.env,+ fileExists: existsSync,+ });}exec(command: string, args: string[] = [], opts: ExecOptions = {}): Promise<ExecResult> {const { timeout, maxBuffer } = opts;- return execFileAsync(this.resolveCommand(command), args, {+ const spawnSpec = this.resolveSpawn(command, args);+ return execFileAsync(spawnSpec.command, spawnSpec.args, {cwd: this.root || undefined,env: command === 'git' ? buildNonInteractiveGitEnv() : undefined,timeout,maxBuffer,signal: this._signal(opts.signal),+ windowsVerbatimArguments: spawnSpec.windowsVerbatimArguments,}).catch((error) => {if (command === 'git' && isMissingGitExecutableError(error)) {throw missingGitExecutableError();@@ -67,9 +85,11 @@ export class LocalExecutionContext implements IExecutionContext {return;}- const child = spawn(this.resolveCommand(command), args, {+ const spawnSpec = this.resolveSpawn(command, args);+ const child = spawn(spawnSpec.command, spawnSpec.args, {cwd: this.root || undefined,env: command === 'git' ? buildNonInteractiveGitEnv() : undefined,+ windowsVerbatimArguments: spawnSpec.windowsVerbatimArguments,});let settled = false;diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.test.tsindex 3f5b6725f..0816e76c1 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.test.ts@@ -1,5 +1,6 @@+import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';-import { classifyDockerError } from './docker';+import { classifyDockerError, resolveDockerBin } from './docker';describe('classifyDockerError', () => {it('maps a missing binary (ENOENT) to not-installed', () => {@@ -14,6 +15,28 @@ describe('classifyDockerError', () => {expect(classifyDockerError(err).reason).toBe('daemon-down');});+ it('maps the Windows named-pipe connect failure to daemon-down', () => {+ const err = new Error(+ 'error during connect: Get "http://%2F%2F.%2Fpipe%2FdockerDesktopLinuxEngine/v1.51/version": ' ++ 'open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified.'+ );+ const result = classifyDockerError(err);+ expect(result.reason).toBe('daemon-down');+ expect(result.detail).toContain('Start Docker Desktop');+ });++ it('maps the legacy docker_engine pipe failure to daemon-down', () => {+ const err = new Error(+ 'open //./pipe/docker_engine: The system cannot find the file specified.'+ );+ expect(classifyDockerError(err).reason).toBe('daemon-down');+ });++ it('maps EINVAL from a .cmd shim to not-installed rather than a dead daemon', () => {+ const err = Object.assign(new Error('spawn docker EINVAL'), { code: 'EINVAL' });+ expect(classifyDockerError(err).reason).toBe('not-installed');+ });+it('falls back to daemon-down with the raw message for unknown failures', () => {const err = new Error('some other failure');const result = classifyDockerError(err);@@ -21,3 +44,16 @@ describe('classifyDockerError', () => {expect(result.detail).toContain('some other failure');});});++describe('resolveDockerBin', () => {+ it('honours DOCKER_PATH when it points at a real file', () => {+ const thisFile = fileURLToPath(import.meta.url);+ expect(resolveDockerBin({ DOCKER_PATH: thisFile })).toBe(thisFile);+ });++ it('ignores a DOCKER_PATH that does not exist', () => {+ expect(resolveDockerBin({ DOCKER_PATH: '/definitely/not/a/docker' })).not.toBe(+ '/definitely/not/a/docker'+ );+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.tsindex 39b1f44f5..2a9b8d8e3 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/docker.ts@@ -1,29 +1,66 @@import { execFile } from 'node:child_process';-import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';import { promisify } from 'node:util';+import { resolveExecutable, windowsInstallPath } from '@main/core/utils/resolve-executable';import { log } from '@main/lib/logger';import type { DockerAvailability } from '@shared/core/managed-switch-server/managed-switch-server';const execFileAsync = promisify(execFile);-function resolveDockerBin(): string {- const candidates = [- (process.env.DOCKER_PATH || '').trim(),+function dockerCandidates(env: NodeJS.ProcessEnv): string[] {+ return ['/opt/homebrew/bin/docker','/usr/local/bin/docker','/usr/bin/docker','/Applications/Docker.app/Contents/Resources/bin/docker',- ].filter(Boolean) as string[];- for (const p of candidates) {- try {- if (fs.existsSync(p)) return p;- } catch {}- }- return 'docker';+ path.join(os.homedir(), '.rd', 'bin', 'docker'),+ windowsInstallPath(env, 'ProgramFiles', 'Docker', 'Docker', 'resources', 'bin', 'docker.exe'),+ windowsInstallPath(+ env,+ 'LOCALAPPDATA',+ 'Programs',+ 'Docker',+ 'Docker',+ 'resources',+ 'bin',+ 'docker.exe'+ ),+ windowsInstallPath(+ env,+ 'LOCALAPPDATA',+ 'Programs',+ 'Rancher Desktop',+ 'resources',+ 'resources',+ 'win32',+ 'bin',+ 'docker.exe'+ ),+ ].filter((candidate): candidate is string => candidate !== null);+}++export function resolveDockerBin(env: NodeJS.ProcessEnv = process.env): string {+ return resolveExecutable('docker', {+ overridePath: env.DOCKER_PATH,+ candidates: dockerCandidates(env),+ env,+ });}-/** Resolved path to the Docker CLI. */-export const DOCKER_EXECUTABLE = resolveDockerBin();+let resolvedDockerExecutable: string | null = null;++/**+ * Path to the Docker CLI, memoized only once a real binary is found. A run that+ * had to fall back to the bare name is not cached, so installing Docker while+ * the app is open is picked up on the next call instead of after a restart.+ */+export function dockerExecutable(): string {+ if (resolvedDockerExecutable !== null) return resolvedDockerExecutable;+ const resolved = resolveDockerBin();+ if (resolved !== 'docker') resolvedDockerExecutable = resolved;+ return resolved;+}/*** Classify a failed `docker version` invocation into the DockerAvailability@@ -37,10 +74,16 @@ export function classifyDockerError(error: unknown): {} {const code = (error as NodeJS.ErrnoException | undefined)?.code;const message = error instanceof Error ? error.message : String(error);- if (code === 'ENOENT') {+ // EINVAL is what a shell-less spawn of a Windows .cmd/.bat shim raises, and+ // ENOTDIR what a stale directory component raises: neither is a live daemon.+ if (code === 'ENOENT' || code === 'EINVAL' || code === 'ENOTDIR') {return { reason: 'not-installed', detail: 'The Docker CLI was not found on this system.' };}- if (/cannot connect to the docker daemon|is the docker daemon running/i.test(message)) {+ if (+ /cannot connect to the docker daemon|is the docker daemon running|error during connect|open \/\/\.\/pipe\/|pipe[\\/]docker_engine|the system cannot find the file specified/i.test(+ message+ )+ ) {return {reason: 'daemon-down',detail: 'Docker is installed but the daemon is not running. Start Docker Desktop and retry.',@@ -58,7 +101,7 @@ export function classifyDockerError(error: unknown): {export async function detectDocker(): Promise<DockerAvailability> {try {const { stdout } = await execFileAsync(- DOCKER_EXECUTABLE,+ dockerExecutable(),['version', '--format', '{{.Server.Version}}'],{ timeout: 15_000 });diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.tsindex 8078980cd..a92bb09db 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts@@ -75,8 +75,14 @@ describe('buildEnvFile', () => {// "Open in Switch Console" redirect was silently disabled on every managed// stack) while asserting vars compose never interpolates. A list cannot// notice a variable being added to the contract; this can.+ // Comments are stripped first: they document the interpolation syntax, and+ // an example in prose is not a variable the stack needs set.+ const composeBody = composeYaml+ .split('\n')+ .filter((line) => !line.trimStart().startsWith('#'))+ .join('\n');const interpolated = new Set(- [...composeYaml.matchAll(/\$\{([A-Z_][A-Z0-9_]*)/g)].map((m) => m[1])+ [...composeBody.matchAll(/\$\{([A-Z_][A-Z0-9_]*)/g)].map((m) => m[1]));// Nothing is exempt today. An entry here must say why the stack is correct// without it — leaving a var unset is a decision, not a default.diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.tsindex 625b42c1f..a7a144c39 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.ts@@ -1,15 +1,49 @@-import { spawn } from 'node:child_process';+import { execFile, spawn } from 'node:child_process';import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';import { dirname, join } from 'node:path';+import { promisify } from 'node:util';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import type { IExecutionContext } from '@main/core/execution-context/types';+import { log } from '@main/lib/logger';import type { DockerAvailability } from '@shared/core/managed-switch-server/managed-switch-server';import { LOCAL_SERVER_PROJECT_NAME } from '../constants';-import { DOCKER_EXECUTABLE, detectDocker } from '../docker';+import { detectDocker, dockerExecutable } from '../docker';import { type LocalServerPorts, pickFreePorts } from '../free-port';import { localServerDir } from '../paths';import type { ServerHost } from './types';+const execFileAsync = promisify(execFile);++/**+ * Windows has no mode bits: `chmod(path, 0o600)` only toggles the read-only+ * flag, so on its own it would leave the managed server's Postgres and gateway+ * credentials readable by every account on the machine while looking protected.+ * Replace the inherited ACL with one that grants the current user alone.+ *+ * A failure is logged rather than thrown: the caller has already written the+ * file, and losing the stack over a hardening step nobody asked for is worse+ * than a degraded mode that says so out loud.+ */+async function restrictWindowsFileToOwner(path: string): Promise<void> {+ const account = process.env.USERNAME;+ if (!account) {+ log.warn('local-switch-server: USERNAME unset; file left with inherited permissions', {+ path,+ });+ return;+ }+ try {+ await execFileAsync('icacls', [path, '/inheritance:r', '/grant:r', `${account}:F`], {+ timeout: 15_000,+ });+ } catch (error) {+ log.warn('local-switch-server: could not restrict file permissions; it stays world-readable', {+ path,+ error: String((error as Error)?.message ?? error),+ });+ }+}+/*** The managed stack running on this machine's Docker daemon — the CHOO-1428* behaviour, now expressed through {@link ServerHost}. Commands run via a local@@ -18,7 +52,9 @@ import type { ServerHost } from './types';*/export class LocalServerHost implements ServerHost {readonly kind = 'local' as const;- readonly dockerBin = DOCKER_EXECUTABLE;+ get dockerBin(): string {+ return dockerExecutable();+ }readonly composeProjectName = LOCAL_SERVER_PROJECT_NAME;readonly workingDir = localServerDir();readonly stateDir = localServerDir();@@ -30,8 +66,10 @@ export class LocalServerHost implements ServerHost {const path = join(this.workingDir, relPath);await mkdir(dirname(path), { recursive: true });await writeFile(path, content, mode !== undefined ? { encoding: 'utf8', mode } : 'utf8');+ if (mode === undefined) return;// writeFile only applies `mode` when creating; enforce it on rewrite too.- if (mode !== undefined) await chmod(path, mode);+ await chmod(path, mode);+ if (process.platform === 'win32') await restrictWindowsFileToOwner(path);}async readFile(relPath: string): Promise<string | null> {diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex b071b9ad7..19278c58b 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -33,6 +33,14 @@# recently been published — a different switch-core on every `up`, with nothing# to say so. Compose now refuses to start rather than pick a version nobody# asked for (CHOO-1865). `.env.example` sets it, and Switch Console writes it.+#+# The `:?` messages below read "required, set it in .env" rather than+# "required - set it in .env" on purpose. Some Compose builds (observed on+# v2.6.0) mis-tokenize a `${VAR:?msg}` whose msg contains " - " when it follows+# other `${...}` substitutions in the same value: part of the message is+# spliced into the image reference instead of the required-variable check+# firing, and the daemon then rejects the mangled tag. A comma keeps the+# wording without the trigger.# What this compose artifact speaks on the `stack-compose` contract, which is# what Switch Console's local-server mode pins against (CHOO-1865). The version this@@ -145,7 +153,7 @@ services:condition: service_completed_successfullyswitch:- image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/switch-core:${SWITCH_VERSION:?required - set it in .env, there is no default}+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/switch-core:${SWITCH_VERSION:?required, set it in .env, there is no default}ports:- "${SWITCH_BIND_ADDR:-127.0.0.1}:${API_HOST_PORT:-8000}:8000"environment:@@ -172,7 +180,7 @@ services:condition: service_startedgateway:- image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/gateway:${SWITCH_VERSION:?required - set it in .env, there is no default}+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/gateway:${SWITCH_VERSION:?required, set it in .env, there is no default}profiles: ["gateway"]ports:- "${SWITCH_BIND_ADDR:-127.0.0.1}:${GATEWAY_HOST_PORT:-3000}:3000"@@ -180,7 +188,7 @@ services:- switchsetup:- image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/setup:${SWITCH_VERSION:?required - set it in .env, there is no default}+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/setup:${SWITCH_VERSION:?required, set it in .env, there is no default}profiles: ["collab"]restart: on-failureenvironment:diff --git a/console/apps/switch-console-desktop/src/main/core/pty/pty-env.ts b/console/apps/switch-console-desktop/src/main/core/pty/pty-env.tsindex 07358e1a6..21356a505 100644--- a/console/apps/switch-console-desktop/src/main/core/pty/pty-env.ts+++ b/console/apps/switch-console-desktop/src/main/core/pty/pty-env.ts@@ -1,7 +1,7 @@import os from 'node:os';+import { getWindowsEnvValue } from '@switch-console/core/exec';import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';import { detectSshAuthSock } from '@main/utils/shellEnv';-import { getWindowsEnvValue } from '@main/utils/windows-env';import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';export const AGENT_ENV_VARS = [diff --git a/console/apps/switch-console-desktop/src/main/core/pty/pty-spawn-platform.ts b/console/apps/switch-console-desktop/src/main/core/pty/pty-spawn-platform.tsindex 803a08011..ae2deac8b 100644--- a/console/apps/switch-console-desktop/src/main/core/pty/pty-spawn-platform.ts+++ b/console/apps/switch-console-desktop/src/main/core/pty/pty-spawn-platform.ts@@ -1,9 +1,15 @@import { existsSync } from 'node:fs';import path from 'node:path';+import {+ getWindowsShellExecutable,+ quoteForCmdExe,+ resolveWindowsCommandPath,+ wrapCmdExeCommandLine,+ type FileExists,+} from '@switch-console/core/exec';import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';import { log } from '@main/lib/logger';import { quoteCshArg } from '@main/utils/shellEscape';-import { getWindowsEnvValue } from '@main/utils/windows-env';import { buildTmuxShellLine } from './tmux-session-name';export type PtyCommandSpec =@@ -48,16 +54,10 @@ export type ResolvedLocalPtySpawn = {warnings: LocalPtySpawnWarning[];};-type FileExists = (candidate: string) => boolean;-function getPosixShell(env: NodeJS.ProcessEnv): string {return env.SHELL || '/bin/sh';}-function getWindowsShell(env: NodeJS.ProcessEnv): string {- return env.ComSpec || 'C:\\Windows\\System32\\cmd.exe';-}-function getResolvedShell(intent: PtySpawnIntent, env: NodeJS.ProcessEnv): string {return intent.shellProfile?.executable ?? getPosixShell(env);}@@ -101,106 +101,12 @@ function argvToPosixShellLine(intent: PtySpawnIntent, command: string, args: strreturn [command, ...args].map(shellArgQuoter(intent)).join(' ');}-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')}"`;-}-function quoteForPowerShell(input: string): string {if (input.length === 0) return "''";if (!/[\s'`"$;&|<>(){}[\],]/.test(input)) return input;return `'${input.replace(/'/g, "''")}'`;}-/**- * 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.- */-function wrapCmdExeCommandLine(commandLine: string): string {- return commandLine.startsWith('"') ? `"${commandLine}"` : commandLine;-}--function getWindowsPathDirs(env: NodeJS.ProcessEnv): string[] {- const rawPath = getWindowsEnvValue(env, 'PATH') ?? '';- return rawPath.split(path.win32.delimiter).filter(Boolean);-}--function getWindowsPathExts(- env: NodeJS.ProcessEnv,- options: { powershell?: boolean } = {}-): string[] {- const rawPathExt =- getWindowsEnvValue(env, 'PATHEXT') ?? '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC';- const exts = rawPathExt- .split(';')- .map((ext) => ext.trim())- .filter(Boolean)- .map((ext) => (ext.startsWith('.') ? ext : `.${ext}`));- if (!options.powershell) return exts;-- const normalized = new Set(exts.map((ext) => ext.toUpperCase()));- if (!normalized.has('.PS1')) exts.push('.PS1');-- const priority = new Map([- ['.COM', 0],- ['.EXE', 1],- ['.PS1', 2],- ['.CMD', 3],- ['.BAT', 4],- ]);- return [...exts].sort((a, b) => {- const aRank = priority.get(a.toUpperCase()) ?? 5;- const bRank = priority.get(b.toUpperCase()) ?? 5;- return aRank - bRank;- });-}--function hasWindowsPathSeparator(command: string): boolean {- return command.includes('\\') || command.includes('/');-}--function resolveWindowsCommandPath({- command,- cwd,- env,- fileExists,- powershell = false,-}: {- command: string;- cwd: string;- env: NodeJS.ProcessEnv;- fileExists: FileExists;- powershell?: boolean;-}): string | null {- if (path.win32.extname(command)) {- return null;- }-- const baseCandidates =- hasWindowsPathSeparator(command) || path.win32.isAbsolute(command)- ? [path.win32.isAbsolute(command) ? command : path.win32.join(cwd, command)]- : [- path.win32.join(cwd, command),- ...getWindowsPathDirs(env).map((dir) => path.win32.join(dir, command)),- ];-- for (const base of baseCandidates) {- for (const ext of getWindowsPathExts(env, { powershell })) {- const candidate = `${base}${ext}`;- if (fileExists(candidate)) return candidate;- }- }-- return null;-}-function windowsWarnings(intent: PtySpawnIntent): LocalPtySpawnWarning[] {const warnings: LocalPtySpawnWarning[] = [];if (intent.shellSetup) warnings.push('shell_setup_ignored_on_windows');@@ -221,7 +127,7 @@ function windowsShellLineSpawn({shellProfile: PtySpawnIntent['shellProfile'];warnings: LocalPtySpawnWarning[];}): ResolvedLocalPtySpawn {- const shell = shellProfile?.executable ?? getWindowsShell(env);+ const shell = shellProfile?.executable ?? getWindowsShellExecutable(env);const commandArgs = shellProfile?.commandArgs ?? ['/d', '/s', '/c'];return {command: shell,@@ -246,7 +152,7 @@ function cmdShellLineSpawn({warnings: LocalPtySpawnWarning[];}): ResolvedLocalPtySpawn {return {- command: getWindowsShell(env),+ command: getWindowsShellExecutable(env),args: ['/d', '/s', '/c', wrapCmdExeCommandLine(commandLine)],cwd,warnings,@@ -263,7 +169,7 @@ function resolveWindowsSpawn(fileExists: FileExists): ResolvedLocalPtySpawn {const warnings = windowsWarnings(intent);- const shell = intent.shellProfile?.executable ?? getWindowsShell(env);+ const shell = intent.shellProfile?.executable ?? getWindowsShellExecutable(env);if (intent.kind === 'interactive-shell') {return {diff --git a/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.test.ts b/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.test.tsindex cc80919e8..7613b908e 100644--- a/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.test.ts@@ -1,9 +1,36 @@-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { IExecutionContext } from '@main/core/execution-context/types';import {makeAgentTmuxSessionName as makeSidecarAgentTmuxSessionName,parseAgentTmuxSessionName,} from '../../../sidecar/vm-tmux';-import { buildTmuxShellLine, makeAgentTmuxSessionName } from './tmux-session-name';+import { buildTmuxShellLine, killTmuxSession, makeAgentTmuxSessionName } from './tmux-session-name';++const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');++afterEach(() => {+ if (originalPlatform) Object.defineProperty(process, 'platform', originalPlatform);+});++function setPlatform(platform: NodeJS.Platform): void {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+}++describe('killTmuxSession', () => {+ it('does not shell out to tmux on Windows, which never started one', async () => {+ setPlatform('win32');+ const exec = vi.fn();+ await killTmuxSession({ exec } as unknown as IExecutionContext, 'switchdash-abc');+ expect(exec).not.toHaveBeenCalled();+ });++ it('kills the exact session elsewhere', async () => {+ setPlatform('darwin');+ const exec = vi.fn(async () => ({ stdout: '', stderr: '' }));+ await killTmuxSession({ exec } as unknown as IExecutionContext, 'switchdash-abc');+ expect(exec).toHaveBeenCalledWith('tmux', ['kill-session', '-t', '=switchdash-abc']);+ });+});describe('buildTmuxShellLine', () => {it('enables tmux mouse scrolling and deep history before attach', () => {diff --git a/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.ts b/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.tsindex be0244b69..b15701a17 100644--- a/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.ts+++ b/console/apps/switch-console-desktop/src/main/core/pty/tmux-session-name.ts@@ -78,6 +78,9 @@ export function makeAgentTmuxSessionName(sessionId: string): string {}export async function killTmuxSession(ctx: IExecutionContext, sessionName: string): Promise<void> {+ // Windows never starts a tmux session (resolveLocalPtySpawn warns and ignores+ // the request), so the teardown would only ever produce a phantom ENOENT.+ if (process.platform === 'win32') return;try {await ctx.exec('tmux', ['kill-session', '-t', exactTmuxTarget(sessionName)]);} catch (err) {diff --git a/console/apps/switch-console-desktop/src/main/core/utils/exec.test.ts b/console/apps/switch-console-desktop/src/main/core/utils/exec.test.tsnew file mode 100644index 000000000..933de7847--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/utils/exec.test.ts@@ -0,0 +1,84 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { GIT_EXECUTABLE, getGitExecutable, resolveGitBin, setGitExecutableOverride } from './exec';++const originalPlatform = process.platform;+let tempDir: string;++beforeEach(() => {+ setGitExecutableOverride(null);+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'switch-console-git-bin-'));+});++afterEach(() => {+ setGitExecutableOverride(null);+ Object.defineProperty(process, 'platform', { value: originalPlatform });+ fs.rmSync(tempDir, { recursive: true, force: true });+});++function setPlatform(platform: NodeJS.Platform): void {+ Object.defineProperty(process, 'platform', { value: platform });+}++function executableGit(directory: string, filename = 'git'): string {+ fs.mkdirSync(directory, { recursive: true });+ const gitPath = path.join(directory, filename);+ fs.writeFileSync(gitPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ return gitPath;+}++describe('resolveGitBin', () => {+ it('prefers explicit GIT_PATH over PATH git', () => {+ const pathGit = executableGit(path.join(tempDir, 'path-bin'));+ const explicitGit = executableGit(path.join(tempDir, 'explicit-bin'));++ expect(resolveGitBin({ GIT_PATH: explicitGit, PATH: path.dirname(pathGit) })).toBe(explicitGit);+ });++ it('prefers PATH git before the hardcoded install locations', () => {+ const pathGit = executableGit(path.join(tempDir, 'path-bin'));++ expect(resolveGitBin({ PATH: path.dirname(pathGit) })).toBe(pathGit);+ });++ it('skips an invalid GIT_PATH and falls back to PATH git', () => {+ const pathGit = executableGit(path.join(tempDir, 'path-bin'));++ expect(resolveGitBin({ GIT_PATH: '/does/not/exist', PATH: path.dirname(pathGit) })).toBe(+ pathGit+ );+ });++ it('walks PATHEXT on Windows so a PATH entry resolves to git.exe', () => {+ setPlatform('win32');+ const pathGit = executableGit(path.join(tempDir, 'path-bin'), 'git.exe');++ expect(resolveGitBin({ PATH: path.dirname(pathGit), PATHEXT: '.exe' })).toBe(pathGit);+ });+});++describe('getGitExecutable', () => {+ it('uses the local host dependency override when present', () => {+ setGitExecutableOverride('/opt/homebrew/bin/git');++ expect(getGitExecutable()).toBe('/opt/homebrew/bin/git');++ setGitExecutableOverride(null);+ expect(getGitExecutable()).toBe(GIT_EXECUTABLE);+ });++ it('keeps remote overrides scoped by connection', () => {+ setGitExecutableOverride('/remote-a/bin/git', 'ssh-a');+ setGitExecutableOverride('/remote-b/bin/git', 'ssh-b');++ expect(getGitExecutable('ssh-a')).toBe('/remote-a/bin/git');+ expect(getGitExecutable('ssh-b')).toBe('/remote-b/bin/git');+ expect(getGitExecutable('ssh-c')).toBe('git');++ setGitExecutableOverride(null, 'ssh-a');+ setGitExecutableOverride(null, 'ssh-b');+ expect(getGitExecutable('ssh-a')).toBe('git');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/utils/exec.ts b/console/apps/switch-console-desktop/src/main/core/utils/exec.tsindex e01cd7763..af61e5231 100644--- a/console/apps/switch-console-desktop/src/main/core/utils/exec.ts+++ b/console/apps/switch-console-desktop/src/main/core/utils/exec.ts@@ -1,26 +1,52 @@-import fs from 'node:fs';+import { resolveExecutable, windowsInstallPath } from './resolve-executable';-function resolveGitBin(): string {- const candidates = [- (process.env.GIT_PATH || '').trim(),+function gitCandidates(env: NodeJS.ProcessEnv): string[] {+ return ['/opt/homebrew/bin/git','/usr/local/bin/git','/usr/bin/git',- ].filter(Boolean) as string[];- for (const p of candidates) {- try {- if (fs.existsSync(p)) return p;- } catch {}- }- return 'git';+ 'C:\\Program Files\\Git\\cmd\\git.exe',+ 'C:\\Program Files (x86)\\Git\\cmd\\git.exe',+ windowsInstallPath(env, 'LOCALAPPDATA', 'Programs', 'Git', 'cmd', 'git.exe'),+ ].filter((candidate): candidate is string => candidate !== null);+}++export function resolveGitBin(env: NodeJS.ProcessEnv = process.env): string {+ return resolveExecutable('git', {+ overridePath: env.GIT_PATH,+ candidates: gitCandidates(env),+ env,+ });}-/** Resolved path to the `git` binary — use for all git exec calls. */+/** Initial fallback path for Git before the host dependency probe completes. */export const GIT_EXECUTABLE = resolveGitBin();+let localGitExecutableOverride: string | null = null;+const remoteGitExecutableOverrides = new Map<string, string>();++export function setGitExecutableOverride(executable: string | null, connectionId?: string): void {+ if (connectionId) {+ if (executable) remoteGitExecutableOverrides.set(connectionId, executable);+ else remoteGitExecutableOverrides.delete(connectionId);+ return;+ }++ localGitExecutableOverride = executable;+}++/** Current Git executable selected by the host dependency system, with startup fallback. */+export function getGitExecutable(connectionId?: string): string {+ if (connectionId) return remoteGitExecutableOverrides.get(connectionId) ?? 'git';+ return localGitExecutableOverride ?? GIT_EXECUTABLE;+}+export function isMissingGitExecutableError(error: unknown): boolean {const err = error as NodeJS.ErrnoException | undefined;- return err?.code === 'ENOENT' && (err.path === 'git' || err.path === GIT_EXECUTABLE);+ return (+ err?.code === 'ENOENT' &&+ (err.path === 'git' || err.path === GIT_EXECUTABLE || err.path === localGitExecutableOverride)+ );}export function missingGitExecutableError(): Error {diff --git a/console/apps/switch-console-desktop/src/main/core/utils/resolve-executable.test.ts b/console/apps/switch-console-desktop/src/main/core/utils/resolve-executable.test.tsnew file mode 100644index 000000000..7fe7ef514--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/utils/resolve-executable.test.ts@@ -0,0 +1,80 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { findExecutableOnPath, resolveExecutable, windowsInstallPath } from './resolve-executable';++let tempDir: string;++beforeEach(() => {+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'switch-console-resolve-exe-'));+});++afterEach(() => {+ fs.rmSync(tempDir, { recursive: true, force: true });+});++function makeExecutable(directory: string, filename: string): string {+ fs.mkdirSync(directory, { recursive: true });+ const filePath = path.join(directory, filename);+ fs.writeFileSync(filePath, '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ return filePath;+}++describe('findExecutableOnPath', () => {+ it('reads PATH case-insensitively', () => {+ const tool = makeExecutable(path.join(tempDir, 'bin'), 'sometool');++ expect(findExecutableOnPath('sometool', { Path: path.dirname(tool) })).toBe(tool);+ });++ it('returns null when PATH is unset', () => {+ expect(findExecutableOnPath('sometool', {})).toBeNull();+ });+});++describe('resolveExecutable', () => {+ it('prefers the override, then PATH, then the candidate list', () => {+ const onPath = makeExecutable(path.join(tempDir, 'bin'), 'sometool');+ const candidate = makeExecutable(path.join(tempDir, 'opt'), 'sometool');+ const override = makeExecutable(path.join(tempDir, 'override'), 'sometool');+ const env = { PATH: path.dirname(onPath) };++ expect(+ resolveExecutable('sometool', { overridePath: override, candidates: [candidate], env })+ ).toBe(override);+ expect(resolveExecutable('sometool', { candidates: [candidate], env })).toBe(onPath);+ expect(+ resolveExecutable('sometool', {+ candidates: [candidate],+ env: { PATH: path.join(tempDir, 'empty') },+ })+ ).toBe(candidate);+ });++ it('falls back to the bare name so the OS loader gets the last word', () => {+ expect(+ resolveExecutable('sometool', { candidates: [], env: { PATH: path.join(tempDir, 'empty') } })+ ).toBe('sometool');+ });+});++describe('windowsInstallPath', () => {+ it('expands a Windows install root', () => {+ expect(+ windowsInstallPath(+ { ProgramFiles: 'C:\\Program Files' },+ 'ProgramFiles',+ 'Docker',+ 'Docker',+ 'resources',+ 'bin',+ 'docker.exe'+ )+ ).toBe('C:\\Program Files\\Docker\\Docker\\resources\\bin\\docker.exe');+ });++ it('returns null when the root variable is unset', () => {+ expect(windowsInstallPath({}, 'LOCALAPPDATA', 'Programs')).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/utils/resolve-executable.ts b/console/apps/switch-console-desktop/src/main/core/utils/resolve-executable.tsnew file mode 100644index 000000000..bd682e93d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/utils/resolve-executable.ts@@ -0,0 +1,68 @@+import fs from 'node:fs';+import path from 'node:path';+import { getWindowsEnvValue, getWindowsPathExts } from '@switch-console/core/exec';++/**+ * Locates `name` on PATH the way the OS loader would, including the PATHEXT+ * extension walk Windows needs (`git` -> `git.exe`). Returns null when nothing+ * executable matches.+ */+export function findExecutableOnPath(+ name: string,+ env: NodeJS.ProcessEnv = process.env+): string | null {+ const pathValue = getWindowsEnvValue(env, 'PATH');+ if (!pathValue) return null;++ const extensions =+ process.platform === 'win32' && !path.extname(name) ? ['', ...getWindowsPathExts(env)] : [''];++ for (const directory of pathValue.split(path.delimiter)) {+ if (!directory) continue;++ for (const extension of extensions) {+ const candidate = path.join(directory, `${name}${extension}`);+ try {+ fs.accessSync(candidate, fs.constants.X_OK);+ return candidate;+ } catch {}+ }+ }++ return null;+}++/**+ * Resolves a tool to an absolute path, in order: an explicit env override, the+ * PATH entry, then the well-known install locations for the platforms we ship+ * on. Falls back to the bare name so the OS loader gets the last word.+ */+export function resolveExecutable(+ name: string,+ options: { overridePath?: string; candidates: string[]; env?: NodeJS.ProcessEnv }+): string {+ const env = options.env ?? process.env;+ const ordered = [+ (options.overridePath ?? '').trim(),+ findExecutableOnPath(name, env) ?? '',+ ...options.candidates,+ ].filter(Boolean);++ for (const candidate of ordered) {+ try {+ if (fs.existsSync(candidate)) return candidate;+ } catch {}+ }++ return name;+}++/** Expands a Windows install root from the environment, or null when unset. */+export function windowsInstallPath(+ env: NodeJS.ProcessEnv,+ rootVar: string,+ ...segments: string[]+): string | null {+ const root = getWindowsEnvValue(env, rootVar);+ return root ? path.win32.join(root, ...segments) : null;+}diff --git a/console/apps/switch-console-desktop/src/main/utils/shellEnv.test.ts b/console/apps/switch-console-desktop/src/main/utils/shellEnv.test.tsnew file mode 100644index 000000000..f51be86b0--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/utils/shellEnv.test.ts@@ -0,0 +1,54 @@+import type * as FsModule from 'fs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { detectSshAuthSock } from './shellEnv';++const mocks = vi.hoisted(() => ({+ existsSync: vi.fn<(p: string) => boolean>(),+ statSync: vi.fn(),+}));++vi.mock('fs', async (importOriginal) => {+ const actual = await importOriginal<typeof FsModule>();+ return { ...actual, existsSync: mocks.existsSync, statSync: mocks.statSync };+});++const WINDOWS_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent';+const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');+const originalEnv = { ...process.env };++afterEach(() => {+ if (originalPlatform) Object.defineProperty(process, 'platform', originalPlatform);+ process.env = { ...originalEnv };+ vi.clearAllMocks();+});++function setPlatform(platform: NodeJS.Platform): void {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+}++describe('detectSshAuthSock on Windows', () => {+ it('returns the OpenSSH named pipe, which is not a socket to statSync', () => {+ setPlatform('win32');+ delete process.env.SSH_AUTH_SOCK;+ mocks.existsSync.mockImplementation((p) => p === WINDOWS_AGENT_PIPE);++ expect(detectSshAuthSock()).toBe(WINDOWS_AGENT_PIPE);+ });++ it('returns undefined when the agent pipe is absent, without globbing POSIX paths', () => {+ setPlatform('win32');+ delete process.env.SSH_AUTH_SOCK;+ mocks.existsSync.mockReturnValue(false);++ expect(detectSshAuthSock()).toBeUndefined();+ expect(mocks.statSync).not.toHaveBeenCalled();+ });++ it('still prefers an inherited SSH_AUTH_SOCK', () => {+ setPlatform('win32');+ process.env.SSH_AUTH_SOCK = '\\\\.\\pipe\\custom-agent';++ expect(detectSshAuthSock()).toBe('\\\\.\\pipe\\custom-agent');+ expect(mocks.existsSync).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/utils/shellEnv.ts b/console/apps/switch-console-desktop/src/main/utils/shellEnv.tsindex 77a795cfc..968dee7f2 100644--- a/console/apps/switch-console-desktop/src/main/utils/shellEnv.ts+++ b/console/apps/switch-console-desktop/src/main/utils/shellEnv.ts@@ -8,6 +8,13 @@ import * as fs from 'fs';import * as os from 'os';import * as path from 'path';+/**+ * Windows' OpenSSH agent listens on a named pipe, not a Unix socket, so+ * `statSync().isSocket()` is false for it and the glob fallbacks below (which+ * split on '/') cannot describe it either.+ */+const WINDOWS_OPENSSH_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent';+/*** Common SSH agent socket locations to check as fallback*/@@ -103,6 +110,10 @@ export function detectSshAuthSock(): string | undefined {return process.env.SSH_AUTH_SOCK;}+ if (process.platform === 'win32') {+ return fs.existsSync(WINDOWS_OPENSSH_AGENT_PIPE) ? WINDOWS_OPENSSH_AGENT_PIPE : undefined;+ }+// macOS launchd (fast, no shell spawn)if (process.platform === 'darwin') {try {diff --git a/console/apps/switch-console-desktop/src/main/utils/userEnv.ts b/console/apps/switch-console-desktop/src/main/utils/userEnv.tsindex 274272b2a..416ed7ec0 100644--- a/console/apps/switch-console-desktop/src/main/utils/userEnv.ts+++ b/console/apps/switch-console-desktop/src/main/utils/userEnv.ts@@ -2,9 +2,10 @@ import { spawnSync } from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import { getWindowsEnvValue } from '@switch-console/core/exec';import { log } from '@main/lib/logger';import { buildExternalToolEnv } from './childProcessEnv';-import { getWindowsEnvValue, prependWindowsPathEntry } from './windows-env';+import { prependWindowsPathEntry } from './windows-env';/*** Keys that must never be overwritten from the shell env capture.diff --git a/console/apps/switch-console-desktop/src/main/utils/windows-env.ts b/console/apps/switch-console-desktop/src/main/utils/windows-env.tsindex 76e2165a0..499042aa6 100644--- a/console/apps/switch-console-desktop/src/main/utils/windows-env.ts+++ b/console/apps/switch-console-desktop/src/main/utils/windows-env.ts@@ -1,16 +1,5 @@import path from 'node:path';--export function getWindowsEnvKey(env: NodeJS.ProcessEnv, key: string): string | undefined {- if (env[key] !== undefined) return key;-- const lowerKey = key.toLowerCase();- return Object.keys(env).find((candidate) => candidate.toLowerCase() === lowerKey);-}--export function getWindowsEnvValue(env: NodeJS.ProcessEnv, key: string): string | undefined {- const envKey = getWindowsEnvKey(env, key);- return envKey ? env[envKey] : undefined;-}+import { getWindowsEnvKey } from '@switch-console/core/exec';export function getWindowsPathEnvKey(env: NodeJS.ProcessEnv): string {return getWindowsEnvKey(env, 'PATH') ?? 'PATH';diff --git a/console/apps/switch-console-desktop/src/renderer/index.css b/console/apps/switch-console-desktop/src/renderer/index.cssindex 9c840a902..19d1d533f 100644--- a/console/apps/switch-console-desktop/src/renderer/index.css+++ b/console/apps/switch-console-desktop/src/renderer/index.css@@ -176,6 +176,13 @@}@layer base {+ /* `:root` carries the light values as well as `.emlight` so the tokens+ resolve before ThemeProvider's layout effect puts a theme class on+ <html>. Without it `cssVar()` returns '' during that first paint, and a+ terminal created in it comes up with an empty theme. `.emdark` matches the+ same element at equal specificity and is declared later, so it still wins+ in dark mode. */+ :root,.emlight {/* ── Color palette (Radix P3) ──────────────────────────────── */@@ -421,6 +428,33 @@--xterm-selection-bg: color(display-p3 0.004 0.502 0.984 / 0.212);--xterm-selection-fg: var(--blue-12);+ /* The 16 ANSI colors xterm resolves SGR 30-37 / 90-97 against. Without+ them xterm falls back to its built-in Tango palette, which is tuned for+ a black background: on white, its bright tones are unreadable as text+ and its black is a near-black block.++ Solarized Light (Ethan Schoonover's published 16-color terminal+ palette). Colors 7 and 15 are its base2/base3 background tones by+ design, so an agent that paints body text as bright-white — a+ dark-terminal assumption — still reads faintly; that is a property of+ the agent, not of the palette. */+ --xterm-ansi-black: #073642;+ --xterm-ansi-red: #dc322f;+ --xterm-ansi-green: #859900;+ --xterm-ansi-yellow: #b58900;+ --xterm-ansi-blue: #268bd2;+ --xterm-ansi-magenta: #d33682;+ --xterm-ansi-cyan: #2aa198;+ --xterm-ansi-white: #eee8d5;+ --xterm-ansi-bright-black: #002b36;+ --xterm-ansi-bright-red: #cb4b16;+ --xterm-ansi-bright-green: #586e75;+ --xterm-ansi-bright-yellow: #657b83;+ --xterm-ansi-bright-blue: #839496;+ --xterm-ansi-bright-magenta: #6c71c4;+ --xterm-ansi-bright-cyan: #93a1a1;+ --xterm-ansi-bright-white: #fdf6e3;+--foreground-diff-added: var(--green-9);--foreground-diff-modified: var(--amber-9);--foreground-diff-deleted: var(--red-9);@@ -700,6 +734,25 @@--xterm-selection-bg: color(display-p3 0.224 0.557 1 / 0.475);--xterm-selection-fg: var(--blue-11);+ /* xterm's own default palette (Tango), spelled out rather than left to the+ fallback so both themes resolve the same tokens. */+ --xterm-ansi-black: #2e3436;+ --xterm-ansi-red: #cc0000;+ --xterm-ansi-green: #4e9a06;+ --xterm-ansi-yellow: #c4a000;+ --xterm-ansi-blue: #3465a4;+ --xterm-ansi-magenta: #75507b;+ --xterm-ansi-cyan: #06989a;+ --xterm-ansi-white: #d3d7cf;+ --xterm-ansi-bright-black: #555753;+ --xterm-ansi-bright-red: #ef2929;+ --xterm-ansi-bright-green: #8ae234;+ --xterm-ansi-bright-yellow: #fce94f;+ --xterm-ansi-bright-blue: #729fcf;+ --xterm-ansi-bright-magenta: #ad7fa8;+ --xterm-ansi-bright-cyan: #34e2e2;+ --xterm-ansi-bright-white: #eeeeec;+--foreground-diff-added: var(--green-10);--foreground-diff-modified: var(--amber-9);--foreground-diff-deleted: var(--red-9);diff --git a/console/apps/switch-console-desktop/src/renderer/lib/providers/theme-provider.tsx b/console/apps/switch-console-desktop/src/renderer/lib/providers/theme-provider.tsxindex 1451d6a56..9470c04b4 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/providers/theme-provider.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/providers/theme-provider.tsx@@ -59,10 +59,14 @@ export function ThemeProvider({ children }: { children: ReactNode }) {setCachedTheme(theme);}, [theme, isLoading, setCachedTheme]);- // Re-apply xterm theme after CSS classes have been updated by the layout effect above.+ // Re-apply xterm theme after CSS classes have been updated by the layout+ // effect above. `isLoading` is a dependency, not just a guard: a persisted+ // theme that matches the system one leaves `effectiveTheme` unchanged across+ // the load, so this would otherwise never run against the applied classes.useEffect(() => {+ if (isLoading) return;applyThemeToAll();- }, [effectiveTheme]);+ }, [effectiveTheme, isLoading]);const setTheme = (newTheme: Theme) => {update(newTheme);diff --git a/console/apps/switch-console-desktop/src/renderer/lib/pty/pty.ts b/console/apps/switch-console-desktop/src/renderer/lib/pty/pty.tsindex 63c00cbdf..f74a59840 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/pty/pty.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/pty/pty.ts@@ -18,6 +18,15 @@ export interface SessionTheme {override?: ITerminalOptions['theme'];}+/**+ * Read the terminal theme, including the 16 ANSI colors.+ *+ * The palette is not optional: xterm falls back to its built-in Tango colors+ * when a theme omits them, and those are chosen for a black background. Against+ * the light theme's white `--xterm-bg` that puts near-white text on white and+ * near-black fills on white, which is most of what makes light mode unreadable+ * inside a session.+ */export function readXtermCssVars(): ITerminalOptions['theme'] {const color = (name: string) => cssColorToHex(cssVar(name));return {@@ -27,6 +36,22 @@ export function readXtermCssVars(): ITerminalOptions['theme'] {cursorAccent: color('--xterm-cursor-accent'),selectionBackground: color('--xterm-selection-bg'),selectionForeground: color('--xterm-selection-fg'),+ black: color('--xterm-ansi-black'),+ red: color('--xterm-ansi-red'),+ green: color('--xterm-ansi-green'),+ yellow: color('--xterm-ansi-yellow'),+ blue: color('--xterm-ansi-blue'),+ magenta: color('--xterm-ansi-magenta'),+ cyan: color('--xterm-ansi-cyan'),+ white: color('--xterm-ansi-white'),+ brightBlack: color('--xterm-ansi-bright-black'),+ brightRed: color('--xterm-ansi-bright-red'),+ brightGreen: color('--xterm-ansi-bright-green'),+ brightYellow: color('--xterm-ansi-bright-yellow'),+ brightBlue: color('--xterm-ansi-bright-blue'),+ brightMagenta: color('--xterm-ansi-bright-magenta'),+ brightCyan: color('--xterm-ansi-bright-cyan'),+ brightWhite: color('--xterm-ansi-bright-white'),};}diff --git a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts b/console/apps/switch-console-desktop/src/sidecar/session-spawner.tsindex db5c086ae..de3302f6b 100644--- a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts+++ b/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts@@ -237,7 +237,11 @@ export class InProcessSessionSpawner implements SessionSpawner {);}const root = hooks.scope === 'global' ? homedir() : this.spec.cwd;- await plugin.behavior.hooks.writeHooks(createPluginFs(root), []);+ // The sidecar runs on the machine the session runs on, so its own platform+ // is the target platform.+ await plugin.behavior.hooks.writeHooks(createPluginFs(root), [], {+ platform: process.platform,+ });this.deps.log.info('InProcessSessionSpawner: installed agent hooks', {providerId,scope: hooks.scope,diff --git a/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts b/console/packages/core/src/agents/plugins/capabilities/hooks-types.tsindex b2732fb3e..d6694f23d 100644--- a/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts+++ b/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts@@ -17,6 +17,24 @@ export type HookRegistration = {command: string;};+/**+ * The machine the hook command will run on.+ *+ * This is the *session's* host, not Switch Console's: a remote session's hooks are+ * written into a config file on the SSH host and run there, so a Windows+ * console installing hooks on a Linux VM must still emit the POSIX command.+ */+export type HookCommandOptions = {+ platform: NodeJS.Platform;+};++/**+ * A hook command that is only a string once the platform it will run on is+ * known. Deferring it is what keeps the target platform, rather than the+ * platform that happened to import the module, from deciding the shell.+ */+export type HookCommand = (opts: HookCommandOptions) => string;+export type NotificationType =| 'permission_prompt'| 'idle_prompt'diff --git a/console/packages/core/src/agents/plugins/capabilities/hooks.ts b/console/packages/core/src/agents/plugins/capabilities/hooks.tsindex 8d30e8030..2d8c42305 100644--- a/console/packages/core/src/agents/plugins/capabilities/hooks.ts+++ b/console/packages/core/src/agents/plugins/capabilities/hooks.ts@@ -1,16 +1,26 @@import z from 'zod';import { definePluginCapability } from '../../../lib/plugins/capability';import type { PluginFs } from '../../runtime/fs';-import type { CanonicalHookEvent, HookRegistration } from './hooks-types';+import type { CanonicalHookEvent, HookCommandOptions, HookRegistration } from './hooks-types';export type { HookRegistration };-export type { CanonicalHookEvent, HookEvent, NotificationType } from './hooks-types';+export type {+ CanonicalHookEvent,+ HookCommand,+ HookCommandOptions,+ HookEvent,+ NotificationType,+} from './hooks-types';export { HOOK_EVENTS } from './hooks-types';export type IHooksBehavior = {readHooks(fs: PluginFs): Promise<HookRegistration[]>;- /** Write hooks and return the root-relative paths written. */- writeHooks(fs: PluginFs, hooks: HookRegistration[]): Promise<string[]>;+ /**+ * Write hooks for a session that will run on `opts.platform`, and return the+ * root-relative paths written. The platform is the target host's, which is+ * not Switch Console's whenever the session is remote.+ */+ writeHooks(fs: PluginFs, hooks: HookRegistration[], opts: HookCommandOptions): Promise<string[]>;deleteHooks(fs: PluginFs): Promise<void>;getHooksInstalled(fs: PluginFs): Promise<boolean>;/**diff --git a/console/packages/core/src/agents/plugins/helpers/hook-config.ts b/console/packages/core/src/agents/plugins/helpers/hook-config.tsindex 100430246..8d37d7758 100644--- a/console/packages/core/src/agents/plugins/helpers/hook-config.ts+++ b/console/packages/core/src/agents/plugins/helpers/hook-config.ts@@ -1,9 +1,11 @@import * as toml from 'smol-toml';import type { PluginFs } from '../../runtime/fs';-import type { HookRegistration } from '../capabilities/hooks';-import { SWITCHDASH_MARKER, filterUserHooks } from './hooks';--export type { HookCommandOptions } from './hooks';+import type {+ HookCommand,+ HookCommandOptions,+ HookRegistration,+} from '../capabilities/hooks-types';+import { SWITCHDASH_MARKER, filterUserHooks, isManagedHookEntry } from './hooks';// ── JSON config helpers ────────────────────────────────────────────────────@@ -115,7 +117,7 @@ export function mergeMinimalEntries(existing: unknown[], command: string): unkno// ── Generic hook config builders ────────────────────────────────────────────-type HookSpec = { hookKey: string; command: string; matcher?: string };+type HookSpec = { hookKey: string; command: HookCommand; matcher?: string };type FlatTomlHookConfigOptions = {beforeWrite?: (fs: PluginFs) => Promise<void>;afterWrite?: (fs: PluginFs) => Promise<string[]>;@@ -129,14 +131,14 @@ type FlatTomlHookConfigOptions = {*/export function buildFlatTomlHookConfig(configPath: string,- entries: Record<string, unknown>[],+ entries: (opts: HookCommandOptions) => Record<string, unknown>[],options: FlatTomlHookConfigOptions = {}) {const stringifyEntry = options.stringifyEntry ?? JSON.stringify;const getHookEntries = (config: Record<string, unknown>) =>Array.isArray(config.hooks) ? (config.hooks as Record<string, unknown>[]) : [];const hasSwitchConsoleHook = (config: Record<string, unknown>) =>- getHookEntries(config).some((entry) => stringifyEntry(entry).includes(SWITCHDASH_MARKER));+ getHookEntries(config).some((entry) => isManagedHookEntry(stringifyEntry(entry)));return {async readHooks(fs: PluginFs): Promise<HookRegistration[]> {@@ -145,11 +147,18 @@ export function buildFlatTomlHookConfig(? [{ event: 'switchdash', command: SWITCHDASH_MARKER }]: [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {const config = await readTomlConfig(fs, configPath);await options.beforeWrite?.(fs);const userHooks = filterUserHooks(getHookEntries(config), stringifyEntry);- await writeTomlConfig(fs, configPath, { ...config, hooks: [...userHooks, ...entries] });+ await writeTomlConfig(fs, configPath, {+ ...config,+ hooks: [...userHooks, ...entries(opts)],+ });const extraPaths = (await options.afterWrite?.(fs)) ?? [];return [configPath, ...extraPaths];},@@ -173,7 +182,8 @@ export function buildFlatTomlHookConfig(* the nested format:* `{ hooks: { <Event>: [{ hooks: [{ type: 'command', command }] }] } }`*- * Pass pre-built command strings (from `makeStdinHookCommand`, etc.) in `hookSpecs`.+ * Pass command builders (from `makeStdinHookCommand`, etc.) in `hookSpecs`; each+ * is resolved against the platform the session will run on at write time.*/export function buildNestedJsonHookConfig(configPath: string, hookSpecs: HookSpec[]) {return {@@ -182,11 +192,15 @@ export function buildNestedJsonHookConfig(configPath: string, hookSpecs: HookSpeconst hooks = (config.hooks ?? {}) as Record<string, unknown[]>;const installed = hookSpecs.some(({ hookKey }) => {const entries = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));+ return entries.some((e) => isManagedHookEntry(JSON.stringify(e)));});return installed ? [{ event: 'switchdash', command: SWITCHDASH_MARKER }] : [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {const config = await readJsonConfigForUpdate(fs, configPath);const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;// Strip previously-installed Switch Console entries once per touched key, THEN@@ -198,7 +212,10 @@ export function buildNestedJsonHookConfig(configPath: string, hookSpecs: HookSpehooks[hookKey] = filterUserHooks(existing as Record<string, unknown>[]);}for (const { hookKey, command, matcher } of hookSpecs) {- hooks[hookKey] = [...(hooks[hookKey] as unknown[]), buildNestedEntry(command, matcher)];+ hooks[hookKey] = [+ ...(hooks[hookKey] as unknown[]),+ buildNestedEntry(command(opts), matcher),+ ];}await writeJsonConfig(fs, configPath, { ...config, hooks });return [configPath];@@ -216,7 +233,7 @@ export function buildNestedJsonHookConfig(configPath: string, hookSpecs: HookSpeconst hooks = (config.hooks ?? {}) as Record<string, unknown[]>;return hookSpecs.some(({ hookKey }) => {const entries = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));+ return entries.some((e) => isManagedHookEntry(JSON.stringify(e)));});},};@@ -239,16 +256,20 @@ export function buildFlatJsonHookConfig(const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;const installed = hookSpecs.some(({ hookKey }) => {const entries = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));+ return entries.some((e) => isManagedHookEntry(JSON.stringify(e)));});return installed ? [{ event: 'switchdash', command: SWITCHDASH_MARKER }] : [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {const config = await readJsonConfigForUpdate(fs, configPath);const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;for (const { hookKey, command } of hookSpecs) {const existing = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- hooks[hookKey] = mergeFlatEntries(existing, command);+ hooks[hookKey] = mergeFlatEntries(existing, command(opts));}await writeJsonConfig(fs, configPath, { ...config, ...extraRoot, hooks });return [configPath];@@ -266,7 +287,7 @@ export function buildFlatJsonHookConfig(const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;return hookSpecs.some(({ hookKey }) => {const entries = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));+ return entries.some((e) => isManagedHookEntry(JSON.stringify(e)));});},};@@ -287,16 +308,20 @@ export function buildMinimalJsonHookConfig(const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;const installed = hookSpecs.some(({ hookKey }) => {const entries = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));+ return entries.some((e) => isManagedHookEntry(JSON.stringify(e)));});return installed ? [{ event: 'switchdash', command: SWITCHDASH_MARKER }] : [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {const config = await readJsonConfigForUpdate(fs, configPath);const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;for (const { hookKey, command } of hookSpecs) {const existing = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- hooks[hookKey] = mergeMinimalEntries(existing, command);+ hooks[hookKey] = mergeMinimalEntries(existing, command(opts));}await writeJsonConfig(fs, configPath, { ...config, ...extraRoot, hooks });return [configPath];@@ -314,7 +339,7 @@ export function buildMinimalJsonHookConfig(const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;return hookSpecs.some(({ hookKey }) => {const entries = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));+ return entries.some((e) => isManagedHookEntry(JSON.stringify(e)));});},};diff --git a/console/packages/core/src/agents/plugins/helpers/hooks.test.ts b/console/packages/core/src/agents/plugins/helpers/hooks.test.tsindex 2b10f958c..3edc4d3d9 100644--- a/console/packages/core/src/agents/plugins/helpers/hooks.test.ts+++ b/console/packages/core/src/agents/plugins/helpers/hooks.test.ts@@ -69,7 +69,7 @@ export async function runHookCommand(async function resolveEndpoint(env: Record<string, string>): Promise<{ url: string; token: string }> {- return runHookCommand(makeStdinHookCommand('notification', { platform: 'linux' }), { env });+ return runHookCommand(makeStdinHookCommand('notification')({ platform: 'linux' }), { env });}describe('makeStdinHookCommand endpoint resolution', () => {@@ -144,7 +144,7 @@ describe('makeStdinHookCommand endpoint resolution', () => {// one or both — curl's `|| true` swallows the resulting failure.const payload = '{"tool_response":{"room_id":"r1","agent_id":"a1"}}';const { url, body } = await runHookCommand(- makeStdinHookCommand('switch_room_connect', { platform: 'linux' }),+ makeStdinHookCommand('switch_room_connect')({ platform: 'linux' }),{env: {SWITCHDASH_HOOK_PORT: '5001',@@ -160,7 +160,7 @@ describe('makeStdinHookCommand endpoint resolution', () => {});it('stays recognisable to filterUserHooks so managed entries are replaced, not duplicated', () => {- const command = makeStdinHookCommand('notification', { platform: 'linux' });+ const command = makeStdinHookCommand('notification')({ platform: 'linux' });expect(command).toContain(SWITCHDASH_MARKER);expect(filterUserHooks([{ command }, { command: 'user-own-hook' }])).toEqual([@@ -168,3 +168,66 @@ describe('makeStdinHookCommand endpoint resolution', () => {]);});});++/** The PowerShell body a Windows hook command carries, base64 in the file. */+function decodeWindowsHookScript(command: string): string {+ const encoded = /-EncodedCommand ([A-Za-z0-9+/=]+)/.exec(command)?.[1] ?? '';+ return Buffer.from(encoded, 'base64').toString('utf16le');+}++describe('makeStdinHookCommand target platform', () => {+ // The console's platform is irrelevant: a Windows console installs hooks on a+ // Linux VM over SFTP, and a `cmd.exe` command there fails on every event —+ // silently, because agents ignore hook exit codes.+ it('builds for the platform it is given, not the one it is running on', () => {+ const build = makeStdinHookCommand('stop');++ expect(build({ platform: 'linux' })).toContain('curl -sf -X POST');+ expect(build({ platform: 'darwin' })).toContain('curl -sf -X POST');+ expect(build({ platform: 'win32' })).toContain('powershell.exe -NoProfile');+ });++ // A host wraps a `command` hook in a shell of its own before running it. When+ // this carried a `cmd.exe /d /c "…"` layer, that wrapping could eat the double+ // quotes, leaving cmd.exe to ignore its `/c` argument, open an interactive+ // prompt and exit 0 — a hook that reported success without running.+ it('invokes PowerShell directly, with no shell wrapper and nothing quoted', () => {+ const command = makeStdinHookCommand('stop')({ platform: 'win32' });++ expect(command).not.toContain('cmd.exe');+ expect(command).not.toContain('"');+ expect(command.startsWith('powershell.exe ')).toBe(true);+ });++ it('stays recognisable on Windows, where the marker only exists inside the base64', () => {+ const command = makeStdinHookCommand('stop')({ platform: 'win32' });++ expect(command).not.toContain(SWITCHDASH_MARKER);+ expect(decodeWindowsHookScript(command)).toContain(SWITCHDASH_MARKER);+ expect(filterUserHooks([{ command }, { command: 'user-own-hook' }])).toEqual([+ { command: 'user-own-hook' },+ ]);+ });++ // Without this a Windows session goes permanently silent the first time its+ // sidecar restarts or rotates its token — the POSIX branch has always+ // followed the endpoint file, and the two must agree.+ it('resolves the endpoint file on Windows too, not just the baked-in env', () => {+ const script = decodeWindowsHookScript(makeStdinHookCommand('stop')({ platform: 'win32' }));++ expect(script).toContain('$env:SWITCHDASH_HOOK_ENDPOINT_FILE');+ expect(script).toContain('Get-Content -LiteralPath $env:SWITCHDASH_HOOK_ENDPOINT_FILE');+ expect(script).toContain('-TotalCount 2');+ // The request must use the resolved values, not the environment directly.+ expect(script).toContain("-Uri ('http://127.0.0.1:' + $sdPort + '/hook')");+ expect(script).toContain("'X-Switchdash-Token' = $sdToken");+ });++ it('still gives up quietly when neither the env nor a file yields an endpoint', () => {+ const script = decodeWindowsHookScript(makeStdinHookCommand('stop')({ platform: 'win32' }));++ expect(script).toContain(+ 'if (-not $sdPort -or -not $sdToken -or -not $env:SWITCHDASH_PTY_ID) { exit 0 }'+ );+ });+});diff --git a/console/packages/core/src/agents/plugins/helpers/hooks.ts b/console/packages/core/src/agents/plugins/helpers/hooks.tsindex 540a10411..be2160337 100644--- a/console/packages/core/src/agents/plugins/helpers/hooks.ts+++ b/console/packages/core/src/agents/plugins/helpers/hooks.ts@@ -1,15 +1,35 @@import { Buffer } from 'node:buffer';--export type HookCommandOptions = {- platform?: NodeJS.Platform;-};+import type { HookCommand, HookCommandOptions } from '../capabilities/hooks-types';export const SWITCHDASH_MARKER = 'SWITCHDASH_HOOK_PORT';+const ENCODED_COMMAND_RE = /-EncodedCommand\s+([A-Za-z0-9+/=]+)/;++/**+ * Whether a hook entry is one Switch Console wrote.+ *+ * POSIX commands name the marker outright. The Windows command is a single+ * `powershell.exe -EncodedCommand <base64>` invocation with nothing quoted+ * around it, so the marker only exists inside the encoded script and has to be+ * decoded back out. Getting this wrong is not cosmetic: an unrecognised managed+ * entry is treated as the user's, so it is never replaced and a second copy is+ * appended on every launch.+ */+export function isManagedHookEntry(text: string): boolean {+ if (text.includes(SWITCHDASH_MARKER)) return true;+ const encoded = ENCODED_COMMAND_RE.exec(text)?.[1];+ if (!encoded) return false;+ try {+ return Buffer.from(encoded, 'base64').toString('utf16le').includes(SWITCHDASH_MARKER);+ } catch {+ return false;+ }+}+/** Filter out Switch Console-managed entries from a hook array. */export function filterUserHooks<T>(entries: T[], stringify?: (entry: T) => string): T[] {const toStr = stringify ?? JSON.stringify;- return entries.filter((entry) => !toStr(entry).includes(SWITCHDASH_MARKER));+ return entries.filter((entry) => !isManagedHookEntry(toStr(entry)));}// ── Internal helpers ────────────────────────────────────────────────────────@@ -34,6 +54,10 @@ type HookPostPayload = 'stdin' | { json: Record<string, string> };* repo dir, and `.`-ing it would make anything that can write there able to run* arbitrary code in every hook. Falls back to the environment, which is how* local sessions (and any pane spawned before this existed) keep working.+ *+ * {@link POWERSHELL_ENDPOINT_PREAMBLE} is the same resolution for the Windows+ * branch; the two must stay in step or one platform's sessions go silent the+ * first time their sidecar rebinds.*/const POSIX_ENDPOINT_PREAMBLE ='_sd_p="$SWITCHDASH_HOOK_PORT"; _sd_t="$SWITCHDASH_HOOK_TOKEN"; ' +@@ -58,6 +82,17 @@ function makePosixHookPostCommand(eventType: string, payload: HookPostPayload):);}+/** The PowerShell counterpart to {@link POSIX_ENDPOINT_PREAMBLE}. */+const POWERSHELL_ENDPOINT_PREAMBLE = [+ '$sdPort = $env:SWITCHDASH_HOOK_PORT',+ '$sdToken = $env:SWITCHDASH_HOOK_TOKEN',+ 'if ($env:SWITCHDASH_HOOK_ENDPOINT_FILE -and ' ++ '(Test-Path -LiteralPath $env:SWITCHDASH_HOOK_ENDPOINT_FILE -PathType Leaf)) { ' ++ '$sdLines = @(Get-Content -LiteralPath $env:SWITCHDASH_HOOK_ENDPOINT_FILE -TotalCount 2); ' ++ 'if ($sdLines.Count -ge 1 -and $sdLines[0].Trim()) { $sdPort = $sdLines[0].Trim() }; ' ++ 'if ($sdLines.Count -ge 2 -and $sdLines[1].Trim()) { $sdToken = $sdLines[1].Trim() } }',+];+function makeWindowsHookPostCommand(eventType: string, payload: HookPostPayload): string {const bodyLine =payload === 'stdin'@@ -65,30 +100,36 @@ function makeWindowsHookPostCommand(eventType: string, payload: HookPostPayload): `$payload = ${quotePowerShellString(JSON.stringify((payload as { json: Record<string, string> }).json))}`;const script = ["$ErrorActionPreference = 'SilentlyContinue'",- 'if (-not $env:SWITCHDASH_HOOK_PORT -or -not $env:SWITCHDASH_HOOK_TOKEN -or -not $env:SWITCHDASH_PTY_ID) { exit 0 }',+ ...POWERSHELL_ENDPOINT_PREAMBLE,+ 'if (-not $sdPort -or -not $sdToken -or -not $env:SWITCHDASH_PTY_ID) { exit 0 }',bodyLine,'try { Invoke-WebRequest -UseBasicParsing -Method POST ' +- "-Uri ('http://127.0.0.1:' + $env:SWITCHDASH_HOOK_PORT + '/hook') " ++ "-Uri ('http://127.0.0.1:' + $sdPort + '/hook') " +'-Headers @{ ' +"'Content-Type' = 'application/json'; " +- "'X-Switchdash-Token' = $env:SWITCHDASH_HOOK_TOKEN; " ++ "'X-Switchdash-Token' = $sdToken; " +"'X-Switchdash-Pty-Id' = $env:SWITCHDASH_PTY_ID; " +`'X-Switchdash-Event-Type' = '${eventType}' ` +'} -Body $payload | Out-Null } catch { exit 0 }',].join('; ');const encoded = Buffer.from(script, 'utf16le').toString('base64');- return `cmd.exe /d /c "echo SWITCHDASH_HOOK_PORT >NUL & powershell.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand ${encoded}"`;+ // Deliberately a bare invocation with no quoting of its own. Hosts wrap a+ // `command` hook in a shell of their own on Windows, and Claude Code's+ // wrapping did not reliably survive the double quotes this used to carry+ // around a `cmd.exe /d /c "…"` layer: when they were lost, cmd.exe ignored+ // the `/c` argument, opened an interactive prompt, and exited 0 — so the hook+ // reported success having never run the script at all, and the room's+ // "working on it…" never cleared. One layer, no quotes, nothing to mis-escape.+ // {@link isManagedHookEntry} decodes the payload to recognise this again.+ return `powershell.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand ${encoded}`;}-/** Post an event with an arbitrary payload, platform-aware. */-export function makeHookPostCommand(- eventType: string,- payload: HookPostPayload,- opts: HookCommandOptions-): string {- return (opts.platform ?? process.platform) === 'win32'- ? makeWindowsHookPostCommand(eventType, payload)- : makePosixHookPostCommand(eventType, payload);+/** Post an event with an arbitrary payload, resolved against the target platform. */+export function makeHookPostCommand(eventType: string, payload: HookPostPayload): HookCommand {+ return (opts: HookCommandOptions) =>+ opts.platform === 'win32'+ ? makeWindowsHookPostCommand(eventType, payload)+ : makePosixHookPostCommand(eventType, payload);}// ── Public command builders ─────────────────────────────────────────────────@@ -97,8 +138,8 @@ export function makeHookPostCommand(* Standard stdin-piped hook command.* The agent pipes the event JSON body through stdin.*/-export function makeStdinHookCommand(eventType: string, opts: HookCommandOptions = {}): string {- return makeHookPostCommand(eventType, 'stdin', opts);+export function makeStdinHookCommand(eventType: string): HookCommand {+ return makeHookPostCommand(eventType, 'stdin');}/**@@ -106,12 +147,7 @@ export function makeStdinHookCommand(eventType: string, opts: HookCommandOptions* Sends a JSON body with a `notification_type` key (used by Codex-style events).*/export function makeNotificationHookCommand(- notificationType: 'idle_prompt' | 'permission_prompt',- opts: HookCommandOptions = {}-): string {- return makeHookPostCommand(- 'notification',- { json: { notification_type: notificationType } },- opts- );+ notificationType: 'idle_prompt' | 'permission_prompt'+): HookCommand {+ return makeHookPostCommand('notification', { json: { notification_type: notificationType } });}diff --git a/console/packages/core/src/agents/plugins/index.ts b/console/packages/core/src/agents/plugins/index.tsindex 10ffc5db0..92b0fc321 100644--- a/console/packages/core/src/agents/plugins/index.ts+++ b/console/packages/core/src/agents/plugins/index.ts@@ -60,6 +60,8 @@ export type { AgentIconAsset, AgentIconVariant } from './assets/icon';export type { AgentCommand, CommandContext } from './capabilities/prompt';export type {CanonicalHookEvent,+ HookCommand,+ HookCommandOptions,HookEvent,HookRegistration,NotificationType,diff --git a/console/packages/core/src/exec/index.ts b/console/packages/core/src/exec/index.tsindex 8c1fc9562..8bd4582e1 100644--- a/console/packages/core/src/exec/index.ts+++ b/console/packages/core/src/exec/index.ts@@ -1,6 +1,19 @@export { createBoundExec, type CreateBoundExecOptions } from './bound-exec';export { type ExecContextOptions, type IExecutionContext } from './execution-context';export { isTransportFailure, TransportError } from './transport-error';+export {+ getWindowsEnvKey,+ getWindowsEnvValue,+ getWindowsPathDirs,+ getWindowsPathExts,+ getWindowsShellExecutable,+ quoteForCmdExe,+ resolveExecFileSpawn,+ resolveWindowsCommandPath,+ wrapCmdExeCommandLine,+ type ExecFileSpawn,+ type FileExists,+} from './windows-spawn';export {ExecError,type BoundExec,diff --git a/console/packages/core/src/exec/windows-spawn.test.ts b/console/packages/core/src/exec/windows-spawn.test.tsnew file mode 100644index 000000000..83f7fc62a--- /dev/null+++ b/console/packages/core/src/exec/windows-spawn.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest';+import {+ getWindowsEnvValue,+ quoteForCmdExe,+ resolveExecFileSpawn,+ resolveWindowsCommandPath,+} from './windows-spawn';++const WINDOWS_ENV: NodeJS.ProcessEnv = {+ Path: 'C:\\Program Files\\nodejs;C:\\Windows\\System32',+ PATHEXT: '.COM;.EXE;.BAT;.CMD',+ ComSpec: 'C:\\Windows\\System32\\cmd.exe',+};++function existsIn(paths: string[]) {+ const set = new Set(paths.map((p) => p.toLowerCase()));+ return (candidate: string) => set.has(candidate.toLowerCase());+}++describe('getWindowsEnvValue', () => {+ it('finds a key whose casing differs from the request', () => {+ expect(getWindowsEnvValue(WINDOWS_ENV, 'PATH')).toBe(WINDOWS_ENV.Path);+ });++ it('returns undefined when nothing matches', () => {+ expect(getWindowsEnvValue(WINDOWS_ENV, 'NOPE')).toBeUndefined();+ });+});++describe('quoteForCmdExe', () => {+ it('quotes a path containing a space', () => {+ expect(quoteForCmdExe('C:\\Program Files\\nodejs\\npm.cmd')).toBe(+ '"C:\\Program Files\\nodejs\\npm.cmd"'+ );+ });++ it('escapes cmd.exe metacharacters', () => {+ expect(quoteForCmdExe('a&b')).toBe('"a^&b"');+ });+});++describe('resolveWindowsCommandPath', () => {+ it('walks PATHEXT over the PATH directories', () => {+ const resolved = resolveWindowsCommandPath({+ command: 'npm',+ env: WINDOWS_ENV,+ fileExists: existsIn(['C:\\Program Files\\nodejs\\npm.cmd']),+ });+ // The resolved name carries the PATHEXT casing, which cmd.exe accepts.+ expect(resolved).toBe('C:\\Program Files\\nodejs\\npm.CMD');+ });++ it('does not search the working directory unless one is given', () => {+ const fileExists = existsIn(['C:\\repo\\npm.cmd']);+ expect(resolveWindowsCommandPath({ command: 'npm', env: WINDOWS_ENV, fileExists })).toBeNull();+ expect(+ resolveWindowsCommandPath({ command: 'npm', cwd: 'C:\\repo', env: WINDOWS_ENV, fileExists })+ ).toBe('C:\\repo\\npm.CMD');+ });++ it('returns null when the command already has an extension', () => {+ expect(+ resolveWindowsCommandPath({+ command: 'npm.cmd',+ env: WINDOWS_ENV,+ fileExists: () => true,+ })+ ).toBeNull();+ });+});++describe('resolveExecFileSpawn', () => {+ it('passes argv through untouched off Windows', () => {+ const spawn = resolveExecFileSpawn({+ command: 'npm',+ args: ['root', '-g'],+ platform: 'darwin',+ env: {},+ fileExists: () => true,+ });+ expect(spawn).toEqual({+ command: 'npm',+ args: ['root', '-g'],+ windowsVerbatimArguments: false,+ });+ });++ it('routes a .cmd shim through cmd.exe with a quoted command line', () => {+ const spawn = resolveExecFileSpawn({+ command: 'npm',+ args: ['root', '-g'],+ platform: 'win32',+ env: WINDOWS_ENV,+ fileExists: existsIn(['C:\\Program Files\\nodejs\\npm.cmd']),+ });++ 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"',+ ]);+ expect(spawn.windowsVerbatimArguments).toBe(true);+ });++ it('spawns a resolved .exe directly', () => {+ const spawn = resolveExecFileSpawn({+ command: 'where',+ args: ['git'],+ platform: 'win32',+ env: WINDOWS_ENV,+ fileExists: existsIn(['C:\\Windows\\System32\\where.exe']),+ });++ expect(spawn).toEqual({+ command: 'C:\\Windows\\System32\\where.EXE',+ args: ['git'],+ windowsVerbatimArguments: false,+ });+ });++ it('honours an explicit .cmd path that was never on PATH', () => {+ const spawn = resolveExecFileSpawn({+ command: 'D:\\tools\\claude.cmd',+ args: ['--version'],+ platform: 'win32',+ env: WINDOWS_ENV,+ fileExists: () => false,+ });++ expect(spawn.command).toBe('C:\\Windows\\System32\\cmd.exe');+ expect(spawn.args[3]).toBe('D:\\tools\\claude.cmd --version');+ });+});diff --git a/console/packages/core/src/exec/windows-spawn.ts b/console/packages/core/src/exec/windows-spawn.tsnew file mode 100644index 000000000..c2c3714b9--- /dev/null+++ b/console/packages/core/src/exec/windows-spawn.ts@@ -0,0 +1,189 @@+import path from 'node:path';++export type FileExists = (candidate: string) => boolean;++/**+ * Windows environment variables are case-insensitive; Node preserves whatever+ * casing the parent process used, so `env.PATH` misses a `Path` inherited from+ * Explorer. Look the key up case-insensitively before reading it.+ */+export function getWindowsEnvKey(env: NodeJS.ProcessEnv, key: string): string | undefined {+ if (env[key] !== undefined) return key;++ const lowerKey = key.toLowerCase();+ return Object.keys(env).find((candidate) => candidate.toLowerCase() === lowerKey);+}++export function getWindowsEnvValue(env: NodeJS.ProcessEnv, key: string): string | undefined {+ const envKey = getWindowsEnvKey(env, key);+ return envKey ? env[envKey] : undefined;+}++export function getWindowsShellExecutable(env: NodeJS.ProcessEnv): string {+ return getWindowsEnvValue(env, 'ComSpec') || 'C:\\Windows\\System32\\cmd.exe';+}++export function getWindowsPathDirs(env: NodeJS.ProcessEnv): string[] {+ const rawPath = getWindowsEnvValue(env, 'PATH') ?? '';+ return rawPath.split(path.win32.delimiter).filter(Boolean);+}++export function getWindowsPathExts(+ env: NodeJS.ProcessEnv,+ options: { powershell?: boolean } = {}+): string[] {+ const rawPathExt =+ getWindowsEnvValue(env, 'PATHEXT') ?? '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC';+ const exts = rawPathExt+ .split(';')+ .map((ext) => ext.trim())+ .filter(Boolean)+ .map((ext) => (ext.startsWith('.') ? ext : `.${ext}`));+ if (!options.powershell) return exts;++ const normalized = new Set(exts.map((ext) => ext.toUpperCase()));+ if (!normalized.has('.PS1')) exts.push('.PS1');++ const priority = new Map([+ ['.COM', 0],+ ['.EXE', 1],+ ['.PS1', 2],+ ['.CMD', 3],+ ['.BAT', 4],+ ]);+ return [...exts].sort((a, b) => {+ const aRank = priority.get(a.toUpperCase()) ?? 5;+ const bRank = priority.get(b.toUpperCase()) ?? 5;+ return aRank - bRank;+ });+}++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')}"`;+}++/**+ * 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.+ */+export function wrapCmdExeCommandLine(commandLine: string): string {+ return commandLine.startsWith('"') ? `"${commandLine}"` : commandLine;+}++function hasWindowsPathSeparator(command: string): boolean {+ return command.includes('\\') || command.includes('/');+}++/**+ * Resolves a bare command name to a concrete file by walking PATHEXT, the way+ * cmd.exe would. Returns null when the command already carries an extension or+ * no candidate exists.+ *+ * `cwd` is only searched when supplied — cmd.exe searches the current directory+ * first, but an exec call resolving a bare name must not pick up a binary+ * sitting in the user's repository.+ */+export function resolveWindowsCommandPath({+ command,+ cwd,+ env,+ fileExists,+ powershell = false,+}: {+ command: string;+ cwd?: string;+ env: NodeJS.ProcessEnv;+ fileExists: FileExists;+ powershell?: boolean;+}): string | null {+ if (path.win32.extname(command)) {+ return null;+ }++ let baseCandidates: string[];+ if (path.win32.isAbsolute(command)) {+ baseCandidates = [command];+ } else if (hasWindowsPathSeparator(command)) {+ baseCandidates = cwd === undefined ? [] : [path.win32.join(cwd, command)];+ } else {+ baseCandidates = [+ ...(cwd === undefined ? [] : [path.win32.join(cwd, command)]),+ ...getWindowsPathDirs(env).map((dir) => path.win32.join(dir, command)),+ ];+ }++ for (const base of baseCandidates) {+ for (const ext of getWindowsPathExts(env, { powershell })) {+ const candidate = `${base}${ext}`;+ if (fileExists(candidate)) return candidate;+ }+ }++ return null;+}++export type ExecFileSpawn = {+ command: string;+ args: string[];+ /**+ * True when `args` is a pre-quoted cmd.exe command line that Node must pass+ * through untouched. Feed straight into the `windowsVerbatimArguments`+ * option of child_process.+ */+ windowsVerbatimArguments: boolean;+};++/**+ * Rewrites an argv pair so `child_process.execFile`/`spawn` can run it without+ * a shell on Windows.+ *+ * npm-global CLIs install as `.cmd`/`.bat` shims, and since Node's+ * CVE-2024-27980 hardening a shell-less spawn of one fails with EINVAL. The+ * shim has to go through cmd.exe — but via an explicit `ComSpec /d /s /c` with+ * a hand-quoted command line, not `shell: true`, which is the argument+ * injection hole that hardening closed.+ *+ * Everything else (including plain `.exe`s and every non-Windows platform) is+ * returned unchanged.+ */+export function resolveExecFileSpawn({+ command,+ args,+ platform,+ env,+ cwd,+ fileExists,+}: {+ command: string;+ args: string[];+ platform: NodeJS.Platform;+ env: NodeJS.ProcessEnv;+ cwd?: string;+ fileExists: FileExists;+}): ExecFileSpawn {+ if (platform !== 'win32') {+ return { command, args, windowsVerbatimArguments: false };+ }++ const resolved = resolveWindowsCommandPath({ command, cwd, env, fileExists }) ?? command;+ const ext = path.win32.extname(resolved).toLowerCase();++ if (ext !== '.cmd' && ext !== '.bat') {+ return { command: resolved, args, windowsVerbatimArguments: false };+ }++ const commandLine = [resolved, ...args].map(quoteForCmdExe).join(' ');+ return {+ command: getWindowsShellExecutable(env),+ args: ['/d', '/s', '/c', wrapCmdExeCommandLine(commandLine)],+ windowsVerbatimArguments: true,+ };+}diff --git a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.tsindex abfc9a345..1434d4a7f 100644--- a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts+++ b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts@@ -529,7 +529,10 @@ describe('HostDependencyManager update', () => {await manager.update('claude');- expect(runInstallCommand).toHaveBeenCalledWith(expect.stringContaining('update'));+ expect(runInstallCommand).toHaveBeenCalledWith({+ command: expect.any(String),+ args: expect.arrayContaining(['update']),+ });});});@@ -706,7 +709,10 @@ describe('HostDependencyManager uninstall', () => {await manager.uninstall('claude-cli-uninstall');- expect(runInstallCommand).toHaveBeenCalledWith(expect.stringContaining('uninstall'));+ expect(runInstallCommand).toHaveBeenCalledWith({+ command: expect.any(String),+ args: expect.arrayContaining(['uninstall']),+ });});it('uses buildUninstallCommand hook when provided', async () => {@@ -731,7 +737,10 @@ describe('HostDependencyManager uninstall', () => {await manager.uninstall('claude-hook-uninstall');- expect(runInstallCommand).toHaveBeenCalledWith('/usr/local/bin/claude custom-remove --force');+ expect(runInstallCommand).toHaveBeenCalledWith({+ command: '/usr/local/bin/claude',+ args: ['custom-remove', '--force'],+ });});});diff --git a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.tsindex 19c28f267..5c93a70a4 100644--- a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts+++ b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts@@ -25,6 +25,7 @@ import type {HostDependency,HostDependencySelection,InstallCommandError,+ InstallCommandSpec,Installation,ProbeResult,Provenance,@@ -33,12 +34,14 @@ import type {import { resolveActiveInstallation, resolveSelectedSource } from './types';/**- * Runs an install or update command string (e.g. "brew install claude") through the- * host's shell. Deliberately not part of IExecutionContext: install commands are full- * shell lines run through the user's shell profile (typically in a PTY), with failures+ * Runs an install or update command (e.g. "brew install claude") through the+ * host's shell. Deliberately not part of IExecutionContext: install commands are run+ * through the user's shell profile (typically in a PTY), with failures* classified into InstallCommandError instead of thrown.*/-export type InstallCommandRunner = (command: string) => Promise<Result<void, InstallCommandError>>;+export type InstallCommandRunner = (+ command: InstallCommandSpec+) => Promise<Result<void, InstallCommandError>>;const VERSION_RE = /(\d+\.\d+[\d.]*)/;@@ -766,8 +769,7 @@ export class HostDependencyManager {args = plan.args;}- const commandLine = [command, ...args].join(' ');- const runResult = await this.runInstallCommand(commandLine);+ const runResult = await this.runInstallCommand({ command, args });if (!runResult.success) return err(runResult.error);} else {return err({ type: 'no-update-strategy', id });@@ -848,8 +850,7 @@ export class HostDependencyManager {args = plan.args;}- const commandLine = [command, ...args].join(' ');- const runResult = await this.runInstallCommand(commandLine);+ const runResult = await this.runInstallCommand({ command, args });if (!runResult.success) return err(runResult.error);} else {return err({ type: 'no-uninstall-command', id });diff --git a/console/packages/core/src/host-dependencies/runtime/index.ts b/console/packages/core/src/host-dependencies/runtime/index.tsindex 268ef946b..e35dbf54c 100644--- a/console/packages/core/src/host-dependencies/runtime/index.ts+++ b/console/packages/core/src/host-dependencies/runtime/index.ts@@ -26,6 +26,7 @@ export {type HostDependency,type HostDependencySelection,type InstallCommandError,+ type InstallCommandSpec,type InstallOverride,type Installation,type Provenance,diff --git a/console/packages/core/src/host-dependencies/runtime/method-detection.test.ts b/console/packages/core/src/host-dependencies/runtime/method-detection.test.tsindex 042dbafb8..45518865d 100644--- a/console/packages/core/src/host-dependencies/runtime/method-detection.test.ts+++ b/console/packages/core/src/host-dependencies/runtime/method-detection.test.ts@@ -111,6 +111,16 @@ describe('createInstallMethodDetector', () => {expect(result.confidence).toBe('confirmed');});+ it('matches a Windows npm root despite backslashes and a trailing separator', async () => {+ const ctx = makeRootCtx(null, 'C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\');+ const detector = createInstallMethodDetector(ctx, 'windows');+ const result = await detector.detect(+ 'C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\@openai\\codex\\bin\\codex.js'+ );+ expect(result.kind).toBe('npm');+ expect(result.confidence).toBe('confirmed');+ });+it('returns npm for npm global on brew-managed node (path under brew prefix but not Cellar)', async () => {const ctx = makeRootCtx('/opt/homebrew/Cellar', '/opt/homebrew/lib/node_modules');const detector = createInstallMethodDetector(ctx, 'macos');diff --git a/console/packages/core/src/host-dependencies/runtime/method-detection.ts b/console/packages/core/src/host-dependencies/runtime/method-detection.tsindex 06a6afd8c..4c521ad58 100644--- a/console/packages/core/src/host-dependencies/runtime/method-detection.ts+++ b/console/packages/core/src/host-dependencies/runtime/method-detection.ts@@ -103,33 +103,40 @@ export function createInstallMethodDetector(return npmRootCache;}- function normalizeDir(dir: string): string {- return dir.toLowerCase().replace(/\/+$/, '');+ /**+ * Case- and separator-insensitive form of a path, without trailing+ * separators. `npm root -g` on Windows answers with backslashes+ * (`C:\Users\x\AppData\Roaming\npm\node_modules`), so comparing raw strings+ * against a '/'-only prefix never matches and npm provenance degrades to a+ * guess.+ */+ function normalizePath(p: string): string {+ return p.replace(/\\/g, '/').toLowerCase().replace(/\/+$/, '');}- function pathStartsWith(lower: string, dir: string): boolean {- const norm = normalizeDir(dir);- return lower.startsWith(norm + '/') || lower === norm;+ function pathStartsWith(candidate: string, dir: string): boolean {+ const norm = normalizePath(dir);+ const target = normalizePath(candidate);+ return target === norm || target.startsWith(norm + '/');}/** Extract a segment of a path that follows a known prefix directory. */function extractSegmentAfterPrefix(realPath: string, prefix: string): string | undefined {- const norm = normalizeDir(prefix);- const lower = realPath.toLowerCase();- if (!pathStartsWith(lower, norm)) return undefined;+ if (!pathStartsWith(realPath, prefix)) return undefined;+ const norm = normalizePath(prefix);// Get the actual casing from the original realPath- const rest = realPath.slice(norm.length).replace(/^\/+/, '');+ const rest = realPath.slice(norm.length).replace(/^[\\/]+/, '');// First path segment = formula/cask name- return rest.split('/')[0] ?? undefined;+ return rest.split(/[\\/]/)[0] || undefined;}return {async detect(realPath: string): Promise<Provenance> {- const lower = realPath.toLowerCase();+ const lower = normalizePath(realPath);// 1. Homebrew Cellar (formulas)const cellar = await brewCellar();- if (cellar && pathStartsWith(lower, cellar)) {+ if (cellar && pathStartsWith(realPath, cellar)) {const managerRef = extractSegmentAfterPrefix(realPath, cellar);return { kind: 'homebrew', confidence: 'confirmed', managerRef };}@@ -138,12 +145,12 @@ export function createInstallMethodDetector(const prefix = await brewPrefix();if (prefix) {const caskroom = prefix + '/Caskroom';- if (pathStartsWith(lower, caskroom)) {+ if (pathStartsWith(realPath, caskroom)) {const managerRef = extractSegmentAfterPrefix(realPath, caskroom);return { kind: 'homebrew', confidence: 'confirmed', managerRef };}const opt = prefix + '/opt';- if (pathStartsWith(lower, opt)) {+ if (pathStartsWith(realPath, opt)) {const managerRef = extractSegmentAfterPrefix(realPath, opt);return { kind: 'homebrew', confidence: 'confirmed', managerRef };}@@ -151,7 +158,7 @@ export function createInstallMethodDetector(// 3. npm global rootconst root = await npmRoot();- if (root && pathStartsWith(lower, root)) {+ if (root && pathStartsWith(realPath, root)) {// managerRef: parent dir of node_modules is the package root; use descriptor laterreturn { kind: 'npm', confidence: 'confirmed' };}diff --git a/console/packages/core/src/host-dependencies/runtime/types.ts b/console/packages/core/src/host-dependencies/runtime/types.tsindex c0379c797..c5e6e6b93 100644--- a/console/packages/core/src/host-dependencies/runtime/types.ts+++ b/console/packages/core/src/host-dependencies/runtime/types.ts@@ -29,6 +29,17 @@ export interface DependencyState {export type DependencyStatusMap = Record<string, DependencyState>;+/**+ * What to run for an install / update / uninstall.+ *+ * A plain string is a shell line straight from a descriptor's installCommands+ * (`brew install claude`) and must stay one, since it may contain pipes and+ * `&&`. An argv pair is a command Switch Console assembled itself from a resolved+ * binary path; keeping it as argv is what stops `C:\Program Files\nodejs\npm.cmd`+ * from being split at the space.+ */+export type InstallCommandSpec = string | { command: string; args: string[] };+export type InstallCommandError =| { type: 'permission-denied'; message: string; output: string; exitCode?: number }| { type: 'command-failed'; message: string; output: string; exitCode?: number }diff --git a/console/packages/plugins/src/agents/impl/claude/hooks.test.ts b/console/packages/plugins/src/agents/impl/claude/hooks.test.tsindex e908baac8..aee873ca9 100644--- a/console/packages/plugins/src/agents/impl/claude/hooks.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/hooks.test.ts@@ -28,7 +28,7 @@ type NestedHookEntry = { matcher?: string; hooks: { type: string; command: strindescribe('buildClaudeHookConfig', () => {it('installs the scoped connect_to_room and general activity hooks', async () => {const fs = createMemoryFs();- await buildClaudeHookConfig().writeHooks(fs, []);+ await buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' });const settings = JSON.parse((await fs.read(CLAUDE_SETTINGS_PATH))!) as {hooks: Record<string, NestedHookEntry[]>;@@ -62,7 +62,7 @@ describe('buildClaudeHookConfig', () => {permissions: { allow: ['Bash'] },});const fs = createMemoryFs({ [CLAUDE_SETTINGS_PATH]: existing });- await buildClaudeHookConfig().writeHooks(fs, []);+ await buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' });const settings = JSON.parse((await fs.read(CLAUDE_SETTINGS_PATH))!) as Record<string, unknown>;expect(settings.env).toEqual({ SWITCH_API_TOKEN: 'secret', SWITCH_AGENT_ID: 'agent-1' });@@ -72,7 +72,9 @@ describe('buildClaudeHookConfig', () => {it('refuses to install hooks over an unparseable settings file', async () => {const fs = createMemoryFs({ [CLAUDE_SETTINGS_PATH]: 'not json {' });- await expect(buildClaudeHookConfig().writeHooks(fs, [])).rejects.toThrow(/not valid JSON/);+ await expect(buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' })).rejects.toThrow(+ /not valid JSON/+ );expect(await fs.read(CLAUDE_SETTINGS_PATH)).toBe('not json {');});@@ -81,7 +83,7 @@ describe('buildClaudeHookConfig', () => {fs.read = async () => {throw new Error('SSH connection is not available');};- await expect(buildClaudeHookConfig().writeHooks(fs, [])).rejects.toThrow(+ await expect(buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' })).rejects.toThrow(/SSH connection is not available/);expect(await fs.exists(CLAUDE_SETTINGS_PATH)).toBe(false);@@ -164,7 +166,7 @@ describe('buildClaudeHookConfig', () => {it('leaves matcher-less hooks (Stop) without a matcher field', async () => {const fs = createMemoryFs();- await buildClaudeHookConfig().writeHooks(fs, []);+ await buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' });const settings = JSON.parse((await fs.read(CLAUDE_SETTINGS_PATH))!) as {hooks: Record<string, NestedHookEntry[]>;diff --git a/console/packages/plugins/src/agents/impl/codex/hooks.test.ts b/console/packages/plugins/src/agents/impl/codex/hooks.test.tsindex 404b09ac3..9b040b6cc 100644--- a/console/packages/plugins/src/agents/impl/codex/hooks.test.ts+++ b/console/packages/plugins/src/agents/impl/codex/hooks.test.ts@@ -70,7 +70,7 @@ async function runHookCommand(/** The `command` strings Switch Console writes into Codex's `hooks.json`, by event. */async function installedCommands(): Promise<Record<string, string>> {const fs = createMemoryFs();- await buildCodexHookConfig().writeHooks(fs, []);+ await buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' });const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>>;};@@ -220,7 +220,7 @@ describe('buildCodexHookConfig.parseHookEvent', () => {describe('buildCodexHookConfig install/read/delete', () => {it('installs Stop / PermissionRequest / SessionStart hooks and reports the written path', async () => {const fs = createMemoryFs();- const paths = await buildCodexHookConfig().writeHooks(fs, []);+ const paths = await buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' });expect(paths).toEqual([CODEX_HOOKS_PATH]);const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {@@ -239,7 +239,7 @@ describe('buildCodexHookConfig install/read/delete', () => {// Switch Console opens and hands it as SWITCH_CONNECTION_ID, so the server// reports the room back and the old `connect_to_room` scrape is gone.const fs = createMemoryFs();- await buildCodexHookConfig().writeHooks(fs, []);+ await buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' });const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {hooks: Record<string, { matcher?: string }[]>;};@@ -268,7 +268,7 @@ describe('buildCodexHookConfig install/read/delete', () => {};const fs = createMemoryFs();- await buildCodexHookConfig().writeHooks(fs, []);+ await buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' });const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {hooks: Record<string, unknown>;};@@ -291,7 +291,7 @@ describe('buildCodexHookConfig install/read/delete', () => {expect(await cfg.getHooksInstalled(fs)).toBe(false);expect(await cfg.readHooks(fs)).toEqual([]);- await cfg.writeHooks(fs, []);+ await cfg.writeHooks(fs, [], { platform: 'linux' });expect(await cfg.getHooksInstalled(fs)).toBe(true);expect(await cfg.readHooks(fs)).toEqual([@@ -306,7 +306,7 @@ describe('buildCodexHookConfig install/read/delete', () => {});const cfg = buildCodexHookConfig();- await cfg.writeHooks(fs, []);+ await cfg.writeHooks(fs, [], { platform: 'linux' });let config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {hooks: Record<string, unknown[]>;};@@ -327,7 +327,7 @@ describe('buildCodexHookConfig install/read/delete', () => {].join('\n');const fs = createMemoryFs({ [CODEX_CONFIG_PATH]: configToml });- await buildCodexHookConfig().writeHooks(fs, []);+ await buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' });const rewritten = (await fs.read(CODEX_CONFIG_PATH))!;expect(rewritten).not.toContain('notify');@@ -340,7 +340,9 @@ describe('buildCodexHookConfig install/read/delete', () => {// configured, so a file we cannot parse must stop the install.const fs = createMemoryFs({ [CODEX_HOOKS_PATH]: '{ not json' });- await expect(buildCodexHookConfig().writeHooks(fs, [])).rejects.toThrow(/not valid JSON/);+ await expect(buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' })).rejects.toThrow(+ /not valid JSON/+ );expect(await fs.read(CODEX_HOOKS_PATH)).toBe('{ not json');});@@ -357,7 +359,9 @@ describe('buildCodexHookConfig install/read/delete', () => {throw new Error('transport failure');};- await expect(buildCodexHookConfig().writeHooks(fs, [])).rejects.toThrow('transport failure');+ await expect(buildCodexHookConfig().writeHooks(fs, [], { platform: 'linux' })).rejects.toThrow(+ 'transport failure'+ );});});diff --git a/console/packages/plugins/src/agents/impl/codex/hooks.ts b/console/packages/plugins/src/agents/impl/codex/hooks.tsindex 6ad2279f2..937b21623 100644--- a/console/packages/plugins/src/agents/impl/codex/hooks.ts+++ b/console/packages/plugins/src/agents/impl/codex/hooks.ts@@ -1,5 +1,9 @@import type { PluginFs } from '@switch-console/core/agents/plugins';-import type { CanonicalHookEvent, HookRegistration } from '@switch-console/core/agents/plugins';+import type {+ CanonicalHookEvent,+ HookCommandOptions,+ HookRegistration,+} from '@switch-console/core/agents/plugins';import {baseName,buildNestedJsonHookConfig,@@ -175,8 +179,12 @@ export function buildCodexHookConfig() {return {...base,- async writeHooks(fs: PluginFs, hooks: HookRegistration[]): Promise<string[]> {- const paths = await base.writeHooks(fs, hooks);+ async writeHooks(+ fs: PluginFs,+ hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {+ const paths = await base.writeHooks(fs, hooks, opts);await removeLegacyCodexNotify(fs);return paths;},diff --git a/console/packages/plugins/src/agents/impl/codex/host-dependency.test.ts b/console/packages/plugins/src/agents/impl/codex/host-dependency.test.tsnew file mode 100644index 000000000..82f172d27--- /dev/null+++ b/console/packages/plugins/src/agents/impl/codex/host-dependency.test.ts@@ -0,0 +1,49 @@+import type { DependencyDescriptor } from '@switch-console/core/deps/runtime';+import { pickInstallOption } from '@switch-console/core/deps/runtime';+import { describe, expect, it } from 'vitest';+import { plugin } from './index';++const hostDependency = plugin.capabilities.hostDependency;+// `pickInstallOption` reads only `installCommands`; the registry fills the rest.+const descriptor: DependencyDescriptor = {+ ...hostDependency,+ name: 'Codex',+ category: 'agent',+ commands: hostDependency.binaryNames,+};++describe('codex hostDependency', () => {+ it('recommends the ChatGPT installer on Windows, not global npm', () => {+ const picked = pickInstallOption(descriptor, 'windows');+ expect(picked?.method).toBe('powershell');+ expect(picked?.command).toContain('chatgpt.com/codex/install.ps1');+ });++ it('leaves npm available on Windows but unflagged', () => {+ const windows = hostDependency.installCommands.windows ?? [];+ expect(windows.filter((option) => option.recommended)).toHaveLength(1);+ const npm = windows.find((option) => option.method === 'npm');+ expect(npm?.recommended).toBeUndefined();+ });++ it('keeps npm recommended on macOS and Linux', () => {+ expect(pickInstallOption(descriptor, 'macos')?.method).toBe('npm');+ expect(pickInstallOption(descriptor, 'linux')?.method).toBe('npm');+ });++ it('gives every install option an uninstallCommand, since uninstall is package-manager', () => {+ expect(hostDependency.uninstall).toEqual({ kind: 'package-manager' });+ for (const [platform, options] of Object.entries(hostDependency.installCommands)) {+ for (const option of options) {+ expect(option.uninstallCommand, `${platform}/${option.method}`).toBeTruthy();+ }+ }+ });++ it('removes only what install.ps1 created, and interpolates in neither shell', () => {+ const uninstall = pickInstallOption(descriptor, 'windows')?.uninstallCommand ?? '';+ expect(uninstall).toContain("'Programs\\OpenAI\\Codex'");+ expect(uninstall).toContain("'.codex\\packages\\standalone'");+ expect(uninstall).not.toMatch(/[$%]/);+ });+});diff --git a/console/packages/plugins/src/agents/impl/codex/index.ts b/console/packages/plugins/src/agents/impl/codex/index.tsindex 3fa3fa431..7e066878b 100644--- a/console/packages/plugins/src/agents/impl/codex/index.ts+++ b/console/packages/plugins/src/agents/impl/codex/index.ts@@ -5,11 +5,73 @@ import {homebrewOption,npmDependency,} from '@switch-console/core/agents/plugins/helpers';+import type { HostDependencyDescriptor, InstallOption } from '@switch-console/core/deps';import { SWITCH_MARKETPLACE_SOURCE } from '../../../distribution';import { buildCodexHookConfig, CODEX_HOOK_TRUST_FLAG } from './hooks';import { icon } from './icon';import { codexLaunchProfile, codexProfilePaths } from './profile';+const CODEX_WINDOWS_INSTALL_SCRIPT =+ 'powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"';++/**+ * Undo what `install.ps1` created, and nothing else.+ *+ * The script has no uninstaller and Codex has no `uninstall` subcommand, but+ * its footprint is exactly two directories: the standalone releases under+ * `%USERPROFILE%\.codex\packages\standalone`, and a junction to the current one+ * under `%LOCALAPPDATA%\Programs\OpenAI\Codex`. The rest of `~/.codex` — config,+ * auth, sessions, hooks — is the user's and is deliberately left alone, as is+ * the PATH entry, which points at a directory that no longer exists.+ *+ * Written without `$` or `%` so it survives both shells a Windows user can have+ * resolved for install commands: PowerShell would interpolate `$env:...` before+ * `powershell -c` ever saw it, and cmd.exe would expand `%LOCALAPPDATA%`.+ */+const CODEX_WINDOWS_UNINSTALL_SCRIPT =+ 'powershell -ExecutionPolicy ByPass -c "' ++ "Remove-Item -LiteralPath (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'Programs\\OpenAI\\Codex') -Recurse -Force -ErrorAction SilentlyContinue; " ++ "Remove-Item -LiteralPath (Join-Path ([Environment]::GetFolderPath('UserProfile')) '.codex\\packages\\standalone') -Recurse -Force -ErrorAction SilentlyContinue" ++ '"';++/**+ * The official Windows install path is the ChatGPT script, not a global npm+ * package, so it leads and carries the Recommended badge.+ *+ * `npmDependency` flags its own option as recommended for every platform, and+ * both consumers — `pickInstallOption` and the settings UI's `seedSource` —+ * take the *first* recommended option. Leaving the flag on npm would keep+ * steering Windows users there however this list is ordered, so it is dropped+ * on this platform only.+ */+function codexHostDependency(): HostDependencyDescriptor {+ const descriptor = npmDependency({+ id: 'codex',+ package: '@openai/codex',+ extraOptions: {+ macos: [homebrewOption({ formula: 'codex', cask: true })],+ linux: [homebrewOption({ formula: 'codex', cask: true })],+ },+ });+ const windowsNative: InstallOption = {+ method: 'powershell',+ command: CODEX_WINDOWS_INSTALL_SCRIPT,+ updateCommand: CODEX_WINDOWS_INSTALL_SCRIPT,+ uninstallCommand: CODEX_WINDOWS_UNINSTALL_SCRIPT,+ recommended: true,+ };+ const windowsNpm = (descriptor.installCommands.windows ?? []).map(+ ({ recommended: _recommended, ...option }) => option+ );+ return {+ ...descriptor,+ installCommands: {+ ...descriptor.installCommands,+ windows: [windowsNative, ...windowsNpm],+ },+ };+}+export const plugin = definePlugin({id: 'codex',@@ -30,23 +92,7 @@ export const plugin = definePlugin(scope: 'global',supportedEvents: ['notification', 'stop', 'session', 'tool-use', 'tool-done'],},- hostDependency: npmDependency({- id: 'codex',- package: '@openai/codex',- extraOptions: {- macos: [homebrewOption({ formula: 'codex', cask: true })],- linux: [homebrewOption({ formula: 'codex', cask: true })],- windows: [- {- method: 'powershell',- command:- 'powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"',- updateCommand:- 'powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"',- },- ],- },- }),+ hostDependency: codexHostDependency(),mcp: {kind: 'supported',scope: 'global',diff --git a/console/packages/plugins/src/agents/impl/copilot/hooks.ts b/console/packages/plugins/src/agents/impl/copilot/hooks.tsindex 6f447fbef..227a7367d 100644--- a/console/packages/plugins/src/agents/impl/copilot/hooks.ts+++ b/console/packages/plugins/src/agents/impl/copilot/hooks.ts@@ -1,4 +1,4 @@-import type { PluginFs } from '@switch-console/core/agents/plugins';+import type { HookCommandOptions, PluginFs } from '@switch-console/core/agents/plugins';import type { HookRegistration } from '@switch-console/core/agents/plugins';import {SWITCHDASH_MARKER,@@ -27,24 +27,28 @@ export function buildCopilotHookConfig() {});return installed ? [{ event: 'switchdash', command: SWITCHDASH_MARKER }] : [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {const config = await readJsonConfig(fs, COPILOT_HOOKS_PATH);const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;const stopExisting = Array.isArray(hooks.agentStop) ? hooks.agentStop : [];hooks.agentStop = [...filterUserHooks(stopExisting as Record<string, unknown>[]),- buildFlatEntry(stopCmd),+ buildFlatEntry(stopCmd(opts)),];const sessionExisting = Array.isArray(hooks.sessionStart) ? hooks.sessionStart : [];hooks.sessionStart = [...filterUserHooks(sessionExisting as Record<string, unknown>[]),- buildFlatEntry(sessionCmd),+ buildFlatEntry(sessionCmd(opts)),];const permExisting = Array.isArray(hooks.permissionRequest) ? hooks.permissionRequest : [];hooks.permissionRequest = [...filterUserHooks(permExisting as Record<string, unknown>[]),- buildFlatEntry(permCmd),+ buildFlatEntry(permCmd(opts)),];if (Array.isArray(hooks.notification)) {hooks.notification = filterUserHooks(hooks.notification as Record<string, unknown>[]);diff --git a/console/packages/plugins/src/agents/impl/grok/hooks.ts b/console/packages/plugins/src/agents/impl/grok/hooks.tsindex 6ff2bf128..f8b63f283 100644--- a/console/packages/plugins/src/agents/impl/grok/hooks.ts+++ b/console/packages/plugins/src/agents/impl/grok/hooks.ts@@ -1,6 +1,10 @@import { Buffer } from 'node:buffer';-import type { PluginFs } from '@switch-console/core/agents/plugins';-import type { CanonicalHookEvent, HookRegistration } from '@switch-console/core/agents/plugins';+import type { HookCommandOptions, PluginFs } from '@switch-console/core/agents/plugins';+import type {+ CanonicalHookEvent,+ HookCommand,+ HookRegistration,+} from '@switch-console/core/agents/plugins';import {SWITCHDASH_MARKER,buildNestedEntry,@@ -13,24 +17,33 @@ import {export const GROK_HOOKS_PATH = '.grok/hooks/switchdash.json';-function makeGrokSessionStartCommand(): string {- if (process.platform === 'win32') {- const script = [- "$ErrorActionPreference = 'SilentlyContinue'",- 'if (-not $env:SWITCHDASH_HOOK_PORT -or -not $env:SWITCHDASH_HOOK_TOKEN -or -not $env:SWITCHDASH_PTY_ID) { exit 0 }',- '$payload = @{ session_id = $env:GROK_SESSION_ID } | ConvertTo-Json -Compress',- 'try { Invoke-WebRequest -UseBasicParsing -Method POST ' +- "-Uri ('http://127.0.0.1:' + $env:SWITCHDASH_HOOK_PORT + '/hook') " +- '-Headers @{ ' +- "'Content-Type' = 'application/json'; " +- "'X-Switchdash-Token' = $env:SWITCHDASH_HOOK_TOKEN; " +- "'X-Switchdash-Pty-Id' = $env:SWITCHDASH_PTY_ID; " +- "'X-Switchdash-Event-Type' = 'session' " +- '} -Body $payload | Out-Null } catch { exit 0 }',- ].join('; ');- const encoded = Buffer.from(script, 'utf16le').toString('base64');- return `cmd.exe /d /c "echo SWITCHDASH_HOOK_PORT >NUL & powershell.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand ${encoded}"`;- }+function makeGrokSessionStartCommand(): HookCommand {+ return (opts: HookCommandOptions) =>+ opts.platform === 'win32' ? grokWindowsSessionStart() : grokPosixSessionStart();+}++function grokWindowsSessionStart(): string {+ const script = [+ "$ErrorActionPreference = 'SilentlyContinue'",+ 'if (-not $env:SWITCHDASH_HOOK_PORT -or -not $env:SWITCHDASH_HOOK_TOKEN -or -not $env:SWITCHDASH_PTY_ID) { exit 0 }',+ '$payload = @{ session_id = $env:GROK_SESSION_ID } | ConvertTo-Json -Compress',+ 'try { Invoke-WebRequest -UseBasicParsing -Method POST ' ++ "-Uri ('http://127.0.0.1:' + $env:SWITCHDASH_HOOK_PORT + '/hook') " ++ '-Headers @{ ' ++ "'Content-Type' = 'application/json'; " ++ "'X-Switchdash-Token' = $env:SWITCHDASH_HOOK_TOKEN; " ++ "'X-Switchdash-Pty-Id' = $env:SWITCHDASH_PTY_ID; " ++ "'X-Switchdash-Event-Type' = 'session' " ++ '} -Body $payload | Out-Null } catch { exit 0 }',+ ].join('; ');+ const encoded = Buffer.from(script, 'utf16le').toString('base64');+ // No `cmd.exe /d /c "…"` wrapper, for the reason given on+ // makeWindowsHookPostCommand: a host's own shell wrapping can strip the+ // quotes, leaving cmd.exe to exit 0 without ever running the script.+ return `powershell.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand ${encoded}`;+}++function grokPosixSessionStart(): string {return ('curl -sf -X POST ' +'-H "Content-Type: application/json" ' +@@ -83,14 +96,18 @@ export function buildGrokHookConfig() {});return installed ? [{ event: 'switchdash', command: SWITCHDASH_MARKER }] : [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {const config = await readJsonConfig(fs, GROK_HOOKS_PATH);const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;for (const { hookKey, command } of specs) {const existing = Array.isArray(hooks[hookKey]) ? hooks[hookKey] : [];hooks[hookKey] = [...filterUserHooks(existing as Record<string, unknown>[]),- buildNestedEntry(command),+ buildNestedEntry(command(opts)),];}await writeJsonConfig(fs, GROK_HOOKS_PATH, { ...config, hooks });diff --git a/console/packages/plugins/src/agents/impl/kimi/hooks.ts b/console/packages/plugins/src/agents/impl/kimi/hooks.tsindex 916835678..b02b8c492 100644--- a/console/packages/plugins/src/agents/impl/kimi/hooks.ts+++ b/console/packages/plugins/src/agents/impl/kimi/hooks.ts@@ -1,4 +1,4 @@-import type { PluginFs } from '@switch-console/core/agents/plugins';+import type { HookCommandOptions, PluginFs } from '@switch-console/core/agents/plugins';import type { HookRegistration } from '@switch-console/core/agents/plugins';import {SWITCHDASH_MARKER,@@ -21,11 +21,11 @@ const KIMI_HOOK_SPECS = [{ hookKey: 'SessionEnd', command: makeStdinHookCommand('stop') },];-function buildKimiHookEntries(existing: unknown[]): unknown[] {+function buildKimiHookEntries(existing: unknown[], opts: HookCommandOptions): unknown[] {const userEntries = filterUserHooks(existing as Record<string, unknown>[]);const switchConsoleEntries = KIMI_HOOK_SPECS.map(({ hookKey, command }) => ({event: hookKey,- command,+ command: command(opts),}));return [...userEntries, ...switchConsoleEntries];}@@ -34,11 +34,11 @@ function buildKimiHookEntries(existing: unknown[]): unknown[] {* Inject kimi hooks into an inline --config JSON/TOML text string.* Used by the kimi buildCommand to patch the --config= flag value on the fly.*/-export function addKimiHooksToConfigText(content: string): string {+export function addKimiHooksToConfigText(content: string, opts: HookCommandOptions): string {try {const config = JSON.parse(content) as Record<string, unknown>;const hooks = Array.isArray(config.hooks) ? config.hooks : [];- config.hooks = buildKimiHookEntries(hooks);+ config.hooks = buildKimiHookEntries(hooks, opts);return JSON.stringify(config);} catch {/* fall through to TOML */@@ -46,14 +46,18 @@ export function addKimiHooksToConfigText(content: string): string {try {const config = parseTOML(content) as Record<string, unknown>;const hooks = Array.isArray(config.hooks) ? config.hooks : [];- config.hooks = buildKimiHookEntries(hooks);+ config.hooks = buildKimiHookEntries(hooks, opts);return stringifyTOML(config);} catch {return content;}}-async function writeKimiHookPath(fs: PluginFs, path: string): Promise<boolean> {+async function writeKimiHookPath(+ fs: PluginFs,+ path: string,+ opts: HookCommandOptions+): Promise<boolean> {const content = await fs.read(path);let config: Record<string, unknown> = {};if (content) {@@ -64,7 +68,7 @@ async function writeKimiHookPath(fs: PluginFs, path: string): Promise<boolean> {}}const hooks = Array.isArray(config.hooks) ? config.hooks : [];- config.hooks = buildKimiHookEntries(hooks);+ config.hooks = buildKimiHookEntries(hooks, opts);await fs.write(path, stringifyTOML(config));return true;}@@ -87,9 +91,13 @@ export function buildKimiHookConfig() {}return [];},- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {- await writeKimiHookPath(fs, KIMI_CONFIG_PATH);- await writeKimiHookPath(fs, KIMI_LEGACY_CONFIG_PATH);+ async writeHooks(+ fs: PluginFs,+ _hooks: HookRegistration[],+ opts: HookCommandOptions+ ): Promise<string[]> {+ await writeKimiHookPath(fs, KIMI_CONFIG_PATH, opts);+ await writeKimiHookPath(fs, KIMI_LEGACY_CONFIG_PATH, opts);return [KIMI_CONFIG_PATH, KIMI_LEGACY_CONFIG_PATH];},async deleteHooks(fs: PluginFs): Promise<void> {diff --git a/console/packages/plugins/src/agents/impl/kimi/index.ts b/console/packages/plugins/src/agents/impl/kimi/index.tsindex 0eb3b471e..b33f95c50 100644--- a/console/packages/plugins/src/agents/impl/kimi/index.ts+++ b/console/packages/plugins/src/agents/impl/kimi/index.ts@@ -3,12 +3,20 @@ import type { AgentCommand, CommandContext } from '@switch-console/core/agents/pimport { buildStandardCommand } from '@switch-console/core/agents/plugins/helpers';import { addKimiHooksToConfigText, buildKimiHookConfig } from './hooks';+/**+ * The inline `--config` value is built from argv, and `CommandContext` does not+ * say which host the argv will run on, so this path can only assume the+ * console's platform. A remote Kimi session therefore still gets the console's+ * hook dialect; the config-file path (`writeHooks`) is the one that knows the+ * target platform.+ */function injectKimiHooksIntoInlineConfig(args: string[]): string[] {+ const opts = { platform: process.platform };return args.map((arg, index) => {if (arg === '--config' && args[index + 1] !== undefined) return arg;- if (index > 0 && args[index - 1] === '--config') return addKimiHooksToConfigText(arg);+ if (index > 0 && args[index - 1] === '--config') return addKimiHooksToConfigText(arg, opts);if (arg.startsWith('--config='))- return `--config=${addKimiHooksToConfigText(arg.slice('--config='.length))}`;+ return `--config=${addKimiHooksToConfigText(arg.slice('--config='.length), opts)}`;return arg;});}diff --git a/console/packages/plugins/src/agents/impl/mistral/hooks.test.ts b/console/packages/plugins/src/agents/impl/mistral/hooks.test.tsindex 16a3bf2ce..0bf4ea992 100644--- a/console/packages/plugins/src/agents/impl/mistral/hooks.test.ts+++ b/console/packages/plugins/src/agents/impl/mistral/hooks.test.ts@@ -45,7 +45,7 @@ command = "curl http://127.0.0.1:$SWITCHDASH_HOOK_PORT/hook"const fs = createMemoryFs({ [MISTRAL_CONFIG_PATH]: 'invalid = [' });const hooks = buildMistralHookConfig();- await expect(hooks.writeHooks(fs, [])).rejects.toThrow(+ await expect(hooks.writeHooks(fs, [], { platform: 'linux' })).rejects.toThrow(`Failed to parse ${MISTRAL_CONFIG_PATH}`);await expect(fs.exists(MISTRAL_HOOKS_PATH)).resolves.toBe(false);diff --git a/console/packages/plugins/src/agents/impl/mistral/hooks.ts b/console/packages/plugins/src/agents/impl/mistral/hooks.tsindex f606491e5..c50d3300c 100644--- a/console/packages/plugins/src/agents/impl/mistral/hooks.ts+++ b/console/packages/plugins/src/agents/impl/mistral/hooks.ts@@ -1,4 +1,4 @@-import type { PluginFs } from '@switch-console/core/agents/plugins';+import type { HookCommandOptions, PluginFs } from '@switch-console/core/agents/plugins';import {buildFlatTomlHookConfig,makeNotificationHookCommand,@@ -10,11 +10,11 @@ import {export const MISTRAL_HOOKS_PATH = '.vibe/hooks.toml';export const MISTRAL_CONFIG_PATH = '.vibe/config.toml';-const MISTRAL_HOOK_ENTRIES = [+const MISTRAL_HOOK_ENTRIES = (opts: HookCommandOptions) => [{name: 'switchdash-post-agent-turn',type: 'post_agent_turn',- command: makeStdinHookCommand('stop'),+ command: makeStdinHookCommand('stop')(opts),timeout: 10,strict: false,description: 'Notify Switch Console when Mistral Vibe finishes an agent turn.',@@ -23,7 +23,7 @@ const MISTRAL_HOOK_ENTRIES = [name: 'switchdash-ask-user-question',type: 'before_tool',match: 'ask_user_question',- command: makeNotificationHookCommand('permission_prompt'),+ command: makeNotificationHookCommand('permission_prompt')(opts),timeout: 10,strict: false,description: 'Notify Switch Console when Mistral Vibe asks for user input.',diff --git a/console/packages/shared/src/artifacts.ts b/console/packages/shared/src/artifacts.tsindex c60c07b2d..67b7e84cb 100644--- a/console/packages/shared/src/artifacts.ts+++ b/console/packages/shared/src/artifacts.ts@@ -23,7 +23,7 @@ export const ARTIFACT_VERSIONS = {'switch-core': '0.13.1','switch-console': '0.22.0','agent-runtime': '0.3.0',- sidecar: '1.9.0',+ sidecar: '1.9.1',gateway: '0.13.1',setup: '0.13.1','helm-chart': '0.13.1',diff --git a/console/packages/switch-agent-runtime/src/artifacts.ts b/console/packages/switch-agent-runtime/src/artifacts.tsindex c60c07b2d..67b7e84cb 100644--- a/console/packages/switch-agent-runtime/src/artifacts.ts+++ b/console/packages/switch-agent-runtime/src/artifacts.ts@@ -23,7 +23,7 @@ export const ARTIFACT_VERSIONS = {'switch-core': '0.13.1','switch-console': '0.22.0','agent-runtime': '0.3.0',- sidecar: '1.9.0',+ sidecar: '1.9.1',gateway: '0.13.1',setup: '0.13.1','helm-chart': '0.13.1',diff --git a/core/switch_core/artifacts.py b/core/switch_core/artifacts.pyindex b0e6ff1dd..9125bda2a 100644--- a/core/switch_core/artifacts.py+++ b/core/switch_core/artifacts.py@@ -23,7 +23,7 @@ ARTIFACT_VERSIONS: Final[dict[str, str]] = {"switch-core": "0.13.1","switch-console": "0.22.0","agent-runtime": "0.3.0",- "sidecar": "1.9.0",+ "sidecar": "1.9.1","gateway": "0.13.1","setup": "0.13.1","helm-chart": "0.13.1",diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 7c166576c..49d2c9f6e 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -26,6 +26,14 @@# recently been published — a different switch-core on every `up`, with nothing# to say so. Compose now refuses to start rather than pick a version nobody# asked for (CHOO-1865). `.env.example` sets it, and Switch Console writes it.+#+# The `:?` messages below read "required, set it in .env" rather than+# "required - set it in .env" on purpose. Some Compose builds (observed on+# v2.6.0) mis-tokenize a `${VAR:?msg}` whose msg contains " - " when it follows+# other `${...}` substitutions in the same value: part of the message is+# spliced into the image reference instead of the required-variable check+# firing, and the daemon then rejects the mangled tag. A comma keeps the+# wording without the trigger.# What this compose artifact speaks on the `stack-compose` contract, which is# what Switch Console's local-server mode pins against (CHOO-1865). The version this@@ -138,7 +146,7 @@ services:condition: service_completed_successfullyswitch:- image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/switch-core:${SWITCH_VERSION:?required - set it in .env, there is no default}+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/switch-core:${SWITCH_VERSION:?required, set it in .env, there is no default}ports:- "${SWITCH_BIND_ADDR:-127.0.0.1}:${API_HOST_PORT:-8000}:8000"environment:@@ -165,7 +173,7 @@ services:condition: service_startedgateway:- image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/gateway:${SWITCH_VERSION:?required - set it in .env, there is no default}+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/gateway:${SWITCH_VERSION:?required, set it in .env, there is no default}profiles: ["gateway"]ports:- "${SWITCH_BIND_ADDR:-127.0.0.1}:${GATEWAY_HOST_PORT:-3000}:3000"@@ -173,7 +181,7 @@ services:- switchsetup:- image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/setup:${SWITCH_VERSION:?required - set it in .env, there is no default}+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/setup:${SWITCH_VERSION:?required, set it in .env, there is no default}profiles: ["collab"]restart: on-failureenvironment: