The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Windows guests: setup, sharing, and the guest's own terminal host (#3248)
lingrd6fe6272a573c
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex c30e83606..98f82915e 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -173,7 +173,8 @@ export const LAUNCH_ERROR_CODES = ['stop_unconfirmed',// A guest on a machine shared with it (core/guestPolicy.ts, core/agents/guestCreate.ts, services/guestLaunches.ts).'guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required',- 'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',+ 'guest_engine_unsupported', 'guest_engine_check_failed', 'guest_engine_install_failed', 'guest_host_unavailable',+ 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing','guest_helper_not_authorized', 'guest_helper_failed',// The `setup` kind's own codes, named for a delete or restart refusal (cli/src/lib/productUsageSignals.ts).'tmux_unavailable', 'pty_host_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',diff --git a/cli/src/core/agents/guestCreate.spec.ts b/cli/src/core/agents/guestCreate.spec.tsindex f5ddd406c..fcd233f35 100644--- a/cli/src/core/agents/guestCreate.spec.ts+++ b/cli/src/core/agents/guestCreate.spec.ts@@ -3,6 +3,7 @@ import type { GuestLaunch } from '../api.js'import type { RegisteredSession } from '../../lib/registry.js'import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'import { createGuestCreate, type GuestCreateDeps } from './guestCreate.js'+import { WindowsBatchLaunchRefused } from '../../lib/windows/launch.js'// A guest's New Harness: the launch shared machines builds, opened as a pane and recorded as the guest's// (docs/plans/2026-10-19-guest-machine-sharing-plan.md). The pane is a fake tmux's; nothing runs.@@ -18,6 +19,8 @@ function setup(over: Partial<GuestCreateDeps> & { answer?: GuestLaunch; spawn?:const deps: GuestCreateDeps = {launch: vi.fn(async () => over.answer ?? launched),tmuxBackend: () => tmux as never,+ ensureEngine: vi.fn(async () => ({ ok: true as const })),+ resolveEngine: vi.fn((_engine: string, argv: readonly string[]) => [...argv]),registry: { openPendingAgent: vi.fn(() => over.register === false ? null : session) },announceSession: vi.fn(),watchNewPane: vi.fn(async () => {}) as never,@@ -73,6 +76,58 @@ describe('a guest\'s New Harness', () => {expect((await create({ engine: 'claude', dsh: null, agent: '' }, '[email protected]')).ok).toBe(true)})+ it('makes a launch that names the guest\'s own host there, never the owner\'s pane', async () => {+ said()+ // Windows: the guest's panes come from its own host, whose processes already run as that account.+ const windows: GuestLaunch = { ok: true, workspace: 'C:\\Users\\hg_0123456789ab\\work', argv: ['claude'], env: {},+ guestHostUser: 'hg_0123456789ab' }+ const runtime = { backend: 'ptyhost', instance: 'p3', paneId: '%1' } as const+ const host = { create: vi.fn(async () => ({ state: 'succeeded' as const, runtime })), kill: vi.fn(async () => {}) }+ const guestBackend = vi.fn(() => host as never)+ const run = setup({ answer: windows, guestBackend })+ expect(await run.create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: true, session: run.session })+ expect(guestBackend).toHaveBeenCalledWith('hg_0123456789ab')+ expect(run.tmux.create).not.toHaveBeenCalled()+ // The pane is made on the guest's host, starts in its workspace, and becomes the guest's shell when the engine goes.+ expect(host.create).toHaveBeenCalledWith(expect.objectContaining({ cwd: windows.workspace, command: ['claude'], afterExit: expect.any(Object) }))+ expect(run.deps.registry.openPendingAgent).toHaveBeenCalledWith(expect.objectContaining({ runtimes: [runtime], guest: '[email protected]' }))+ // A host that is gone is said as such: the owner's pane is never a fallback (it would run as the owner).+ const missing = setup({ answer: windows, guestBackend: () => null })+ expect(await missing.create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'GUEST_HOST_UNAVAILABLE', detail: expect.any(String) })+ expect(missing.tmux.create).not.toHaveBeenCalled()+ })++ it('installs the guest\'s engine before its pane, once even for two launches at once, and reports a failed install', async () => {+ said()+ const windows: GuestLaunch = { ok: true, workspace: 'C:\\Users\\hg_0123456789ab\\work', argv: ['claude'], env: {},+ guestHostUser: 'hg_0123456789ab' }+ const host = { create: vi.fn(async () => ({ state: 'succeeded' as const, runtime })), kill: vi.fn(async () => {}) }+ let open: () => void = () => {}+ const ensureEngine = vi.fn(async () => { await new Promise<void>((resolve) => { open = resolve }); return { ok: true as const } })+ const run = setup({ answer: windows, guestBackend: vi.fn(() => host as never), ensureEngine })+ const first = run.create({ engine: 'claude' }, '[email protected]')+ const second = run.create({ engine: 'claude' }, '[email protected]')+ await vi.waitFor(() => expect(ensureEngine).toHaveBeenCalledTimes(1))+ open()+ await Promise.all([first, second])+ // One install for both: the second pane waits for the first rather than running npm beside it.+ expect(ensureEngine).toHaveBeenCalledWith(host, { user: 'hg_0123456789ab', engine: 'claude', cwd: windows.workspace, prefix: 'C:\\ProgramData\\HarnessGuests\\hosts\\hg_0123456789ab\\engines' })+ expect(host.create).toHaveBeenCalledTimes(2)+ // A failed install is the person's answer: no pane, no registration, and npm's own words.+ const refused = setup({ answer: windows, guestBackend: () => host as never,+ ensureEngine: vi.fn(async () => ({ ok: false as const, error: 'GUEST_ENGINE_INSTALL_FAILED' as const, detail: 'npm said no' })) })+ expect(await refused.create({ engine: 'claude' }, '[email protected]'))+ .toEqual({ ok: false, error: 'GUEST_ENGINE_INSTALL_FAILED', detail: 'npm said no' })+ expect(refused.deps.registry.openPendingAgent).not.toHaveBeenCalled()+ expect(refused.tmux.create).not.toHaveBeenCalled()+ // A launch Windows refuses (a batch engine whose arguments cmd.exe would read) is the person's answer.+ const unsafe = setup({ answer: windows, guestBackend: () => host as never,+ resolveEngine: () => { throw new WindowsBatchLaunchRefused('claude', 'C:\\tools\\claude.cmd') } })+ expect(await unsafe.create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'ENGINE_LAUNCH_REFUSED',+ detail: expect.stringContaining('claude.cmd is a batch file') })+ expect(unsafe.deps.registry.openPendingAgent).not.toHaveBeenCalled()+ })+it('starts on the guest\'s first message, bounded as the owner\'s are', async () => {said()const { create, deps } = setup()@@ -80,15 +135,38 @@ describe('a guest\'s New Harness', () => {await create({ engine: 'claude', prompt: ' ' }, '[email protected]')await create({ engine: 'claude', prompt: null }, '[email protected]')expect(vi.mocked(deps.launch).mock.calls.map(([input]) => input.prompt)).toEqual(['Fix the tests', undefined, undefined])- // A folder to start in goes to shared machines, which starts there only when the owner shares it.+ // A folder to start in goes to shared machines, which starts there only when the owner shares it: this side passes+ // what it was given, because only shared machines knows this machine's own absolute form (`/…`, `C:\…`).await create({ engine: 'claude', cwd: '/Users/dee/docs' }, '[email protected]')await create({ engine: 'claude', cwd: 'docs' }, '[email protected]')- expect(vi.mocked(deps.launch).mock.calls.slice(3).map(([input]) => input.cwd)).toEqual(['/Users/dee/docs', undefined])+ expect(vi.mocked(deps.launch).mock.calls.slice(3).map(([input]) => input.cwd)).toEqual(['/Users/dee/docs', 'docs'])expect(await create({ engine: 'claude', prompt: 7 }, '[email protected]')).toEqual({ ok: false, error: 'INVALID_PROMPT', detail: 'prompt must be a string' })expect(await create({ engine: 'claude', prompt: 'x'.repeat(2001) }, '[email protected]')).toEqual({ ok: false, error: 'PROMPT_TOO_LONG', detail: expect.stringMatching(/2000/) })expect(deps.launch).toHaveBeenCalledTimes(5)})+ it('installs through the guest host when no one hands in an installer', async () => {+ said()+ const windows: GuestLaunch = { ok: true, workspace: 'C:\\Users\\hg_0123456789ab\\work', argv: ['claude'], env: {},+ guestHostUser: 'hg_0123456789ab' }+ let checked = false+ const host = {+ create: vi.fn(async (_request: { command?: string[]; label?: string }) => ({ state: 'succeeded' as const, dispatch: 'executed' as const, runtime: { backend: 'ptyhost', instance: 'p3-0.5.55-gu0123456789ab', paneId: '%1' } })),+ kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })),+ // Missing first, then the install succeeds.+ paneState: vi.fn(async () => { const status = checked ? 0 : 1; checked = true; return { dead: true, exitStatus: status, command: 'cmd.exe', engineExit: null } }),+ capture: vi.fn(async () => ({ state: 'succeeded' as const, value: 'installed' })),+ }+ const run = setup({ answer: windows, guestBackend: vi.fn(() => host as never), ensureEngine: undefined, resolveEngine: undefined })+ expect(await run.create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: true, session: run.session })+ // The check, the install, then the harness's own pane; npm ran from the staged Node, as the guest.+ expect(host.create).toHaveBeenCalledTimes(3)+ expect(host.create.mock.calls[0]![0]).toMatchObject({ command: ['cmd.exe', '/d', '/s', '/c', 'where claude'] })+ expect(host.create.mock.calls[1]![0]).toMatchObject({ label: 'guest-engine-install-claude',+ command: expect.arrayContaining([expect.stringContaining('\\bin\\node-'), expect.stringMatching(/engines$/)]) })+ expect(run.deps.registry.openPendingAgent).toHaveBeenCalledTimes(1)+ })+it('says what stopped it: no tmux, a launch refused, a pane that would not open or register', async () => {expect(await setup({ tmuxBackend: () => null }).create({ engine: 'claude' }, '[email protected]')).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })expect(await setup({ answer: { ok: false, error: 'GUEST_HELPER_REQUIRED', detail: 'Turn it on.' } }).create({ engine: 'claude' }, '[email protected]'))diff --git a/cli/src/core/agents/guestCreate.ts b/cli/src/core/agents/guestCreate.tsindex 01a686964..6850153c7 100644--- a/cli/src/core/agents/guestCreate.ts+++ b/cli/src/core/agents/guestCreate.ts@@ -17,6 +17,10 @@ import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags } fimport { DEFAULT_HARNESS_PERMISSION } from '../../lib/harnessDefaults.js'import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'import type { RegisteredSession } from '../../lib/registry.js'+import { windowsAfterExit } from '../../lib/windows/engineStart.js'+import { ensureGuestEngine, guestNodeDir, type GuestEngineBackend, type GuestEngineResult } from '../../lib/windows/guestEngine.js'+import { guestHostHome, WINDOWS_GUEST_SETUP_VERSION } from '../../lib/windows/guestRequests.js'+import { windowsEngineArgv, windowsLaunchRefusal } from '../../lib/windows/launch.js'import type { createPaneWatcher } from './newPane.js'export type GuestCreateResult =@@ -27,6 +31,17 @@ export interface GuestCreateDeps {launch: (input: GuestLaunchInput) => Promise<GuestLaunch>/** The tmux backend; null where the configuration lists no tmux. */tmuxBackend: () => CreateAgentPaneDeps['tmuxBackend'] | null+ /** The pane backend of a guest's own host, for a launch that must not be made by this account (Windows: the+ * guest's `harness-pty` host, lib/windows/guestHostBackend.ts); absent where the platform has no such host.+ * Resolves null when that host cannot be reached: the owner's backend is never a fallback. */+ guestBackend?: (user: string) => Promise<(CreateAgentPaneDeps['tmuxBackend'] & GuestEngineBackend) | null>+ | (CreateAgentPaneDeps['tmuxBackend'] & GuestEngineBackend) | null+ /** Makes sure the guest's engine is installed for its account first (Windows: lib/windows/guestEngine.ts); a seam+ * for tests. Only called for a launch on a guest's own host. */+ ensureEngine?: (backend: GuestEngineBackend, options: { user: string; engine: string; cwd: string; prefix: string }) => Promise<GuestEngineResult>+ /** The engine's argv as this machine runs it, from the guest's own engines folder (Windows resolves the npm shim+ * there, lib/windows/launch.ts); a seam for tests. */+ resolveEngine?: (engine: string, argv: readonly string[], prefix: string) => string[]registry: CreateAgentPaneDeps['registry']announceSession: (session: RegisteredSession) => voidwatchNewPane: ReturnType<typeof createPaneWatcher>@@ -40,13 +55,26 @@ const NOT_FOR_GUESTS: ReadonlyArray<readonly [string, string]> = []export function createGuestCreate(deps: GuestCreateDeps) {+ /** One install per guest and engine at a time: two panes running npm at once fight over the same prefix. */+ const installing = new Map<string, Promise<GuestEngineResult>>()+ const installOnce = (key: string, run: () => Promise<GuestEngineResult>): Promise<GuestEngineResult> => {+ const at = installing.get(key)+ if (at) return at+ const pending = run().finally(() => { installing.delete(key) })+ installing.set(key, pending)+ return pending+ }+ const ensureEngine = deps.ensureEngine ?? ((backend, options) => ensureGuestEngine(backend, {+ ...options, setupVersion: WINDOWS_GUEST_SETUP_VERSION, log: (line) => console.log(`[guest] ${line}`),+ }))+ const resolveEngine = deps.resolveEngine ?? ((engine, argv, prefix) => windowsEngineArgv(engine, argv, {+ environment: { PATH: `${prefix};${guestNodeDir(WINDOWS_GUEST_SETUP_VERSION)}` },+ }))return async (payload: Record<string, unknown>, guest: string): Promise<GuestCreateResult> => {for (const [key, detail] of NOT_FOR_GUESTS) {const value = payload[key]if (value !== undefined && value !== null && value !== '') return { ok: false, error: 'GUEST_UNSUPPORTED', detail }}- const tmuxBackend = deps.tmuxBackend()- if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }const engine = typeof payload.engine === 'string' ? payload.engine : ''// The mode the guest chose, with the engine's own flags for it, as an owner's launch has (Auto-approve is the// engine's auto mode, never Skip all checks). A client that predates the choice sends only `bypassPermission`.@@ -63,23 +91,59 @@ export function createGuestCreate(deps: GuestCreateDeps) {if (prompt.length > MAX_FIRST_PROMPT_CHARS) {return { ok: false, error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` }}- // A folder the owner shares, to start in (shared machines checks it is shared; the helper, that it may be).- const cwd = typeof payload.cwd === 'string' && payload.cwd.startsWith('/') ? payload.cwd : null+ // A folder the owner shares, to start in (shared machines checks it is shared; the helper, that it may be). Both+ // platforms' absolute forms: `/Users/...` and `C:\Users\...`.+ const cwd = typeof payload.cwd === 'string' && payload.cwd.trim() ? payload.cwd : nullconst launch = await deps.launch({ email: guest, engine, bypassPermission, permissionFlags: [...permissionFlags],...(prompt ? { prompt } : {}), ...(cwd ? { cwd } : {}) })if (!launch.ok) return { ok: false, error: launch.error, ...(launch.detail ? { detail: launch.detail } : {}) }+ // Where the pane must be made by the guest's own host (Windows), never by this account: the owner's tmux or+ // pty host has no pane there, and a fallback to it would run the guest's harness as the owner.+ let backend: CreateAgentPaneDeps['tmuxBackend'] | null+ // The engine's argv as the pane runs it. On Windows it is resolved after the install, from the guest's own+ // engines folder, exactly as the owner's is from its PATH (lib/windows/launch.ts `windowsEngineArgv`):+ // an npm shim becomes its program or node script, so no argument is ever read by cmd.exe.+ let argv = launch.argv+ const hostUser = launch.guestHostUser+ if (hostUser) {+ const host = await deps.guestBackend?.(hostUser) ?? null+ if (!host) {+ return { ok: false, error: 'GUEST_HOST_UNAVAILABLE',+ detail: 'The guest\'s own terminal host is not running on this computer. Turn sharing on again for it.' }+ }+ const prefix = `${guestHostHome(hostUser)}\\engines`+ // The engine must be installed for that account, as the guest: a new Windows account has neither, and its+ // profile is not the owner's (lib/windows/guestEngine.ts, the macOS helper's `install` on this platform).+ const ready = await installOnce(`${hostUser}:${engine}`,+ () => ensureEngine(host, { user: hostUser, engine, cwd: launch.workspace, prefix }))+ if (!ready.ok) return { ok: false, error: ready.error, detail: ready.detail }+ try {+ argv = resolveEngine(engine, launch.argv, prefix)+ } catch (error) {+ const refused = windowsLaunchRefusal(error)+ return { ok: false, error: refused.error, detail: refused.detail }+ }+ backend = host+ } else {+ backend = deps.tmuxBackend()+ if (!backend) return { ok: false, error: 'TMUX_UNAVAILABLE' }+ }const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim().slice(0, 120) : nullconst label = buildHarnessSessionLabel(engine as AgentEngine)const result = await createAndRegisterPane({- tmuxBackend,+ tmuxBackend: backend,registry: deps.registry,engine: engine as AgentEngine,cwd: launch.workspace,// The owner's tmux starts the pane: in a folder the owner may enter (the guest's home gives the owner a// read ACL). The helper changes to the workspace as the guest.spawnCwd: launch.workspace,+ // Windows: the guest's host makes the pane in the workspace; when the engine exits it becomes the guest's+ // shell, as an owner's pane does. Nothing of this account's environment goes in (no `windowsPaneLaunch`:+ // its PATH is the owner's, which the guest may not read).+ ...(launch.guestHostUser ? { paneLaunch: { cwd: launch.workspace, afterExit: windowsAfterExit(engine) } } : {}),sessionLabel: label,- argv: launch.argv,+ argv,env: launch.env,bypassPermission,permissionMode,@@ -88,8 +152,8 @@ export function createGuestCreate(deps: GuestCreateDeps) {})if (!result.ok) return { ok: false, error: result.error, detail: result.detail }deps.announceSession(result.pending)- // No install here: the pane installs a missing engine for the guest itself (lib/guestPaneCommand.ts).- void deps.watchNewPane(engine as AgentEngine, result.pending, result.spawned, launch.argv, undefined)+ // The engine is installed before the pane opens (Windows); on macOS the pane's own bootstrap installs it.+ void deps.watchNewPane(engine as AgentEngine, result.pending, result.spawned, argv, undefined)console.log(`[agent] create guest pane open · ${engine} · agent ${result.pending.agentId}`)return { ok: true, session: result.pending }}diff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.tsindex 475424e85..8fe6c94f7 100644--- a/cli/src/core/agents/restoreLaunch.spec.ts+++ b/cli/src/core/agents/restoreLaunch.spec.ts@@ -69,6 +69,16 @@ describe('an old Swarm session with no saved role', () => {})})+describe('a guest\'s harness at boot', () => {+ it('is never relaunched as the owner: refused before a workspace or service is touched', async () => {+ const { deps, build } = setup()+ expect(await build({ ...entry, guest: '[email protected]' } as RegisteredSession, { current: () => true }))+ .toEqual({ error: 'GUEST_HARNESS', detail: expect.stringContaining('shared with you') })+ expect(deps.workspaceMissing).not.toHaveBeenCalled()+ expect(deps.launch).not.toHaveBeenCalled()+ })+})+describe('a restore launch Windows refuses', () => {it('fails that row alone, with its reason; any other error is thrown on', async () => {const { deps, build } = setup()diff --git a/cli/src/core/agents/restoreLaunch.ts b/cli/src/core/agents/restoreLaunch.tsindex 8043db48e..16f519b17 100644--- a/cli/src/core/agents/restoreLaunch.ts+++ b/cli/src/core/agents/restoreLaunch.ts@@ -5,6 +5,7 @@ import type { LaunchOverrides, LaunchOverridesResult } from '../../lib/launchOveimport type { RestoreAgentsDeps, RestoreLaunch } from '../../lib/restoreAgents.js'import { windowsLaunchRefusal } from '../../lib/windows/launch.js'import type { AdoptSwarmSkill } from '../api.js'+import { GUEST_HARNESS_REFUSAL } from '../guestPolicy.js'/** What a harness held for its Swarm role says in its pane, in the person's words. */export const SWARM_ROLE_HELD = 'Waiting for the Swarm to confirm this agent\'s role. It starts by itself once the Swarm answers.'@@ -23,6 +24,10 @@ interface RestoreLaunchDeps {export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps['buildLaunch'] {return async (given, { current, prepare, ...opts }) => {+ // A guest's harness is never relaunched this way: every relaunch builds an owner's launch, which would run+ // the guest's conversation as the owner, with the owner's keys (core/guestPolicy.ts GUEST_HARNESS_REFUSAL).+ // On Windows the pane also belonged to the guest's own host, whose task may be gone.+ if (given.guest) return { error: GUEST_HARNESS_REFUSAL.error, detail: GUEST_HARNESS_REFUSAL.detail }if (externalResumePending(given.externalResume)) return { held: 'search', holdScope: 'workspace',detail: given.launch?.state === 'held' ? given.launch.detail : 'Waiting to verify this external conversation.' }const missing = deps.workspaceMissing(given.cwd)diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 973dbcaff..e7ec9ca47 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -693,9 +693,13 @@ export interface GuestLaunchInput { email: string; engine: string; bypassPermiss/** A guest's harness as shared machines builds it (services/guestLaunches.ts): the pane's command, which runs* the engine as the guest's own OS user on the owner's subscription, the variables to set on the pane, and* `workspace`, where it starts (the guest's workspace or a folder the owner shares). The core opens it and- * records whose it is (core/agents/guestCreate.ts). */+ * records whose it is (core/agents/guestCreate.ts).+ *+ * `guestHostUser` is set where the pane must be made by the guest's own host rather than this account (Windows:+ * lib/windows/guestHostBackend.ts), whose panes already run as that user; its absence means the owner's backend+ * starts the pane and a helper hands it to the guest (macOS, Linux). */export type GuestLaunch =- | { ok: true; workspace: string; argv: string[]; env: Record<string, string> }+ | { ok: true; workspace: string; argv: string[]; env: Record<string, string>; guestHostUser?: string }| { ok: false; error: string; detail?: string }/** The core's call into shared machines: a guest's launch (docs/plans/2026-10-19-guest-machine-sharing-plan.md). */diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 9bd13c5cc..ac608586d 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -715,6 +715,13 @@ describe('createInput', () => {inputs.submitAgent('s1', 'typed')expect(log.mock.calls.flat().filter((line) => String(line).includes(' recv · '))).toHaveLength(3)+ // The remembered ids are bounded: an id that has scrolled out is logged again rather than kept for the life+ // of the daemon (256 ids, the backend's own retry window).+ const before = log.mock.calls.flat().filter((line) => String(line).includes(' recv · ')).length+ for (let i = 0; i < 256; i++) inputs.submitAgent('s1', 'held', `bulk-${i}`)+ inputs.submitAgent('s1', 'hello', 'd1')+ const after = log.mock.calls.flat().filter((line) => String(line).includes(' recv · ')).length+ expect(after - before).toBe(257)})})diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 3534ba37d..60270907b 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -321,8 +321,8 @@ export function createInput(deps: InputDeps) {if (loggedDeliveries.has(deliveryId)) return falseloggedDeliveries.add(deliveryId)if (loggedDeliveries.size > 256) {- const oldest = loggedDeliveries.values().next().value- if (oldest !== undefined) loggedDeliveries.delete(oldest)+ // Above 256 entries the set always has a first one; the type says `undefined` because an empty set has none.+ loggedDeliveries.delete(loggedDeliveries.values().next().value!)}return true}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 04b471e18..ad2228d89 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -69,6 +69,7 @@ import { isTerminalEngine, type AgentEngine } from '../engines/types.js'import { engineInstallRecipe } from '../lib/engineInstall.js'import { buildEngineLaunchArgv, engineLaunchEnv, supportsFirstPrompt } from '../lib/engineLaunch.js'import { isWindowsHeldPane, windowsPaneLaunch } from '../lib/windows/engineStart.js'+import { createGuestHostBackend } from '../lib/windows/guestHostBackend.js'import { workspaceMissing } from '../lib/workspaceCheck.js'import { HERMES_SYSTEM_MANAGED_DIR, type GridLaunchMachine } from '../lib/gridLaunchWire.js'import { writeGridConfigDir } from '../lib/gridConfigDir.js'@@ -3013,9 +3014,38 @@ async function runForeground(session: AuthSession | null): Promise<void> {log: (line) => console.log(line),})}+ // One host per guest, reached on its first launch and kept: a launch must not open a new pipe connection (and a new+ // reconnect timer) for a host that is already there.+ const guestHosts = new Map<string, Promise<ReturnType<typeof createGuestHostBackend> | null>>()+ const guestBackendFor = (user: string): Promise<ReturnType<typeof createGuestHostBackend> | null> => {+ const known = guestHosts.get(user)+ if (known) return known+ const reached = (async () => {+ const backend = createGuestHostBackend({ user })+ try {+ const prepared = await backend.prepare({ ownedPanes: new Map() })+ if (prepared.state !== 'ready') { backend.dispose(); return null }+ } catch (error) {+ // A task that is gone, or a host that cannot start, is no host: the create says "turn sharing on again"+ // rather than throwing out of the request.+ console.warn(`[guest] ${user} host unavailable · ${error instanceof Error ? error.message : String(error)}`)+ backend.dispose()+ return null+ }+ terminals.addBackend(backend)+ return backend+ })()+ guestHosts.set(user, reached)+ void reached.then((backend) => { if (!backend) guestHosts.delete(user) })+ return reached+ }const guestCreate = createGuestCreate({launch: (input) => (ports.sharedMachines ?? SHARED_MACHINES_OFF).guestLaunch(input),- tmuxBackend: () => tmuxBackend, registry, announceSession, watchNewPane,+ tmuxBackend: () => tmuxBackend,+ // Windows: a guest's panes are made on the guest's own host, which runs as that account; there is no owner+ // pane to hand over (lib/windows/guestHostBackend.ts).+ ...(process.platform === 'win32' ? { guestBackend: guestBackendFor } : {}),+ registry, announceSession, watchNewPane,})// The requests that start an agent's process, and the receipts of those asked with a creationId// (core/agents/launches.ts). The orchestrator and the cable create and fork through the socket's slots.diff --git a/cli/src/core/sharedMachinesLink.spec.ts b/cli/src/core/sharedMachinesLink.spec.tsindex 1d622197e..392d93e57 100644--- a/cli/src/core/sharedMachinesLink.spec.ts+++ b/cli/src/core/sharedMachinesLink.spec.ts@@ -19,6 +19,18 @@ describe('a guest\'s launch, asked of shared machines\' process', () => {expect(await createSharedMachinesLink(async () => ({ ok: false, error: 'GUEST_INVALID' })).guestLaunch(input)).toEqual({ ok: false, error: 'GUEST_INVALID' })})+ it('passes on the guest\'s own host when the launch names one, and nothing else', async () => {+ const answer = { ok: true, workspace: 'C:\\Users\\hg_0123456789ab\\work', argv: ['claude'], env: {},+ guestHostUser: 'hg_0123456789ab' }+ expect(await createSharedMachinesLink(async () => answer).guestLaunch(input))+ .toEqual({ ok: true, workspace: answer.workspace, argv: ['claude'], env: {}, guestHostUser: 'hg_0123456789ab' })+ // A name that is not a guest's is not a host this core may start a pane on.+ for (const guestHostUser of ['DELL', 'hg_x', '', 7, null]) {+ expect(await createSharedMachinesLink(async () => ({ ...answer, guestHostUser })).guestLaunch(input), String(guestHostUser))+ .toEqual(GUEST_LAUNCH_UNAVAILABLE)+ }+ })+it('runs nothing it cannot trust the shape of: a process down, failing, or answering oddly', async () => {for (const answer of [{ error: 'SERVICE_UNAVAILABLE' },diff --git a/cli/src/core/sharedMachinesLink.ts b/cli/src/core/sharedMachinesLink.tsindex 9ed03aef8..ed1fbc2b7 100644--- a/cli/src/core/sharedMachinesLink.ts+++ b/cli/src/core/sharedMachinesLink.ts@@ -6,6 +6,7 @@* The argv and the variables are checked here, as strings, because the core runs them in a pane.*/import { GUEST_LAUNCH_UNAVAILABLE, type GuestLaunch, type SharedMachinesCorePort } from './api.js'+import { isGuestUser } from '../lib/guestAccounts.js'/** Ask shared machines' process (core/serviceLinks.ts `call`, for `sharedMachines`): never rejects. */export type CallSharedMachines = (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>@@ -18,8 +19,10 @@ export function createSharedMachinesLink(call: CallSharedMachines): SharedMachinreturn {guestLaunch: async (input): Promise<GuestLaunch> => {const answer = await call('guestLaunch', { ...input })- if (answer.ok === true && typeof answer.workspace === 'string' && strings(answer.argv) && stringMap(answer.env)) {- return { ok: true, workspace: answer.workspace, argv: answer.argv, env: answer.env }+ if (answer.ok === true && typeof answer.workspace === 'string' && strings(answer.argv) && stringMap(answer.env)+ && (answer.guestHostUser === undefined || (typeof answer.guestHostUser === 'string' && isGuestUser(answer.guestHostUser)))) {+ return { ok: true, workspace: answer.workspace, argv: answer.argv, env: answer.env,+ ...(typeof answer.guestHostUser === 'string' ? { guestHostUser: answer.guestHostUser } : {}) }}if (answer.ok === false && typeof answer.error === 'string') {return { ok: false, error: answer.error, ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }diff --git a/cli/src/lib/guestAccounts.spec.ts b/cli/src/lib/guestAccounts.spec.tsindex cc3057e87..a346c6634 100644--- a/cli/src/lib/guestAccounts.spec.ts+++ b/cli/src/lib/guestAccounts.spec.ts@@ -138,9 +138,13 @@ describe('a guest\'s account, through the helper', () => {it('keeps guests\' homes under one root per platform, a workspace in each', () => {expect(guestHomeRoot('darwin')).toBe('/Users/Shared/HarnessGuests')expect(guestHomeRoot('linux')).toBe('/home/harness-guests')+ expect(guestHomeRoot('win32')).toBe('C:\\ProgramData\\HarnessGuests')expect(guestHomeRoot()).toBe(guestHomeRoot(process.platform))expect(guestWorkspaceFor('[email protected]', 'darwin')).toBe(`/Users/Shared/HarnessGuests/${USER}/work`)- expect(guestWorkspaceFor('[email protected]')).toBe(`${guestHomeRoot()}/${USER}/work`)+ // Windows guests have ordinary profiles, made by the setup task (`C:\Users\hg_<12 hex>\work`).+ expect(guestWorkspaceFor('[email protected]', 'win32')).toBe(`C:\\Users\\${USER}\\work`)+ expect(guestWorkspaceFor('[email protected]')).toBe(+ process.platform === 'win32' ? `C:\\Users\\${USER}\\work` : `${guestHomeRoot()}/${USER}/work`)})it('runs a command and hears its lines; a command that is not there is code null', async () => {diff --git a/cli/src/lib/guestAccounts.ts b/cli/src/lib/guestAccounts.tsindex 8c45aef2a..e09b5cc4e 100644--- a/cli/src/lib/guestAccounts.ts+++ b/cli/src/lib/guestAccounts.ts@@ -11,9 +11,12 @@ import { isAbsolute } from 'node:path'export const GUEST_HELPER_PATH = '/usr/local/libexec/harness/guest-helper'-/** Where guests' homes are (the helper's HOME_ROOT): never the owner's own home or `staff`'s reach. */+/** Where guests' homes are (the helper's HOME_ROOT): never the owner's own home or `staff`'s reach. On Windows the+ * guests' own tree (lib/windows/guestRequests.ts `WINDOWS_GUEST_ROOT`); their profiles are `C:\Users\hg_<12 hex>`. */export function guestHomeRoot(platform: NodeJS.Platform = process.platform): string {- return platform === 'darwin' ? '/Users/Shared/HarnessGuests' : '/home/harness-guests'+ if (platform === 'darwin') return '/Users/Shared/HarnessGuests'+ if (platform === 'win32') return 'C:\\ProgramData\\HarnessGuests'+ return '/home/harness-guests'}/** A folder of the owner's shared with every guest (docs/plans/2026-10-19-guest-machine-sharing-plan.md,@@ -93,9 +96,11 @@ export function guestUserFor(email: string): string {return `hg_${createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 12)}`}-/** Where a guest's harnesses start unless it picks a shared folder: `<home>/work`, as the helper makes it. */+/** Where a guest's harnesses start unless it picks a shared folder: `<home>/work`, as the helper makes it. Windows+ * guests have an ordinary profile (`C:\Users\hg_<12 hex>\work`), made by the setup task. */export function guestWorkspaceFor(email: string, platform: NodeJS.Platform = process.platform): string {- return `${guestHomeRoot(platform)}/${guestUserFor(email)}/work`+ const user = guestUserFor(email)+ return platform === 'win32' ? `C:\\Users\\${user}\\work` : `${guestHomeRoot(platform)}/${user}/work`}export function isGuestUser(user: string): boolean {diff --git a/cli/src/lib/guestHelperInstall.spec.ts b/cli/src/lib/guestHelperInstall.spec.tsindex 0112a2c71..1a93f0542 100644--- a/cli/src/lib/guestHelperInstall.spec.ts+++ b/cli/src/lib/guestHelperInstall.spec.ts@@ -155,7 +155,7 @@ describe('installing the helper', () => {it('refuses a platform with no sudo, and an owner name it cannot write into the drop-in', async () => {const runner = vi.fn<GuestRunner>(async () => ok)- expect(await installGuestHelper({ owner: 'ann', runner, platform: 'win32' })).toMatchObject({ ok: false, code: 'UNSUPPORTED' })+ expect(await installGuestHelper({ owner: 'ann', runner, platform: 'freebsd' })).toMatchObject({ ok: false, code: 'UNSUPPORTED' })expect(await installGuestHelper({ owner: 'root', runner, platform: 'darwin' })).toMatchObject({ ok: false, code: 'FAILED' })expect(runner).not.toHaveBeenCalled()})diff --git a/cli/src/lib/guestHelperInstall.ts b/cli/src/lib/guestHelperInstall.tsindex 1bcc6becc..20552386b 100644--- a/cli/src/lib/guestHelperInstall.ts+++ b/cli/src/lib/guestHelperInstall.ts@@ -17,6 +17,7 @@ import { HOOK_SCRIPT } from '../engines/kit/notifyHooks.js'import { GUEST_HELPER_PATH, runGuestCommand, type GuestRunner } from './guestAccounts.js'import { guestHelperScript, guestSudoersTemplate, helperScriptVersion } from './guestHelperAssets.js'import { managedNodePath } from './nodeRuntime.js'+import type { RunAdmin } from '../team/admin.js'export const GUEST_SUDOERS_PATH = '/etc/sudoers.d/harness-guests'export const GUEST_NODE_DIR = '/usr/local/lib/harness/node'@@ -123,10 +124,20 @@ export interface GuestHelperInstallOptions {hookScript?: string | null/** Whether `pkexec` and a desktop session are there (Linux). */graphical?: boolean+ /** A test's stand-in for the Windows UAC runner. */+ admin?: RunAdmin+ /** Windows: the owner's profile, `%USERPROFILE%`. */+ ownerHome?: string}export async function installGuestHelper(options: GuestHelperInstallOptions = {}): Promise<GuestHelperInstallResult> {const platform = options.platform ?? process.platform+ // Windows's script builders (and the Team imports they bring) are loaded only there: every other platform, and+ // every service sharing the edge host's process, must not carry them (src/leanEntry.spec.ts).+ if (platform === 'win32') {+ const { installWindowsGuestHelper } = await import('./windows/guestHelperInstallWin.js')+ return installWindowsGuestHelper(options, GUEST_HELPER_PROMPT)+ }if (platform !== 'darwin' && platform !== 'linux') {return { ok: false, code: 'UNSUPPORTED', message: 'Sharing this computer needs macOS or Linux.' }}@@ -190,6 +201,7 @@ export interface GuestHelperStatus { state: GuestHelperState; version: number |export interface GuestHelperStatusDeps {runner?: GuestRunner+ platform?: NodeJS.PlatformhelperPath?: string/** The installed helper's text, or null when there is none (no sudo needed: it is 0755). */read?: (path: string) => string | null@@ -204,6 +216,11 @@ export async function guestHelperStatus(deps: GuestHelperStatusDeps = {}): Promireturn null}})+ const platform = deps.platform ?? process.platform+ if (platform === 'win32') {+ const { windowsGuestHelperStatus } = await import('./windows/guestHelperInstallWin.js')+ return windowsGuestHelperStatus(deps, read)+ }const text = read(helperPath)if (text === null) return { state: 'missing', version: null }const version = helperScriptVersion(text)diff --git a/cli/src/lib/guestHelperInstall.win.spec.ts b/cli/src/lib/guestHelperInstall.win.spec.tsnew file mode 100644index 000000000..f23c44b97--- /dev/null+++ b/cli/src/lib/guestHelperInstall.win.spec.ts@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from 'vitest'+import { guestHelperStatus, installGuestHelper } from './guestHelperInstall.js'+import { WINDOWS_GUEST_SETUP_VERSION } from './windows/guestRequests.js'+import type { RunAdmin } from '../team/admin.js'++const SID = 'S-1-5-21-1111111111-2222222222-3333333333-1001'+const whoami = async () => ({ code: 0, stdout: `"HOST\\\\owner","${SID}"\n`, stderr: '' })++describe('installing guest sharing on Windows', () => {+ it('asks once, with the owner SID, the guest tree and the setup task', async () => {+ let script = ''+ const admin = vi.fn<RunAdmin>(async (build) => { script = build('C:\\\\stage').script; return { ok: true, stdout: '' } })+ const result = await installGuestHelper({ platform: 'win32', owner: 'owner', ownerHome: 'C:\\Users\\owner', runner: whoami, admin })+ expect(result).toEqual({ ok: true })+ expect(admin).toHaveBeenCalledTimes(1)+ expect(script).toContain("$OWNER_SID = 'S-1-5-21-1111111111-2222222222-3333333333-1001'")+ expect(script).toContain("$ROOT = 'C:\\ProgramData\\HarnessGuests'")+ expect(script).toContain('Harness Guests Setup')+ expect(script).toContain('HighestAvailable')+ // What a guest installs its engine with is staged with the host: its Node runtime and npm.+ expect(script).toContain('$NODE_SRC = ')+ expect(script).toContain('node-')+ })++ it('reports a cancelled UAC prompt and refuses a missing profile or SID', async () => {+ const cancelled = vi.fn<RunAdmin>(async () => ({ ok: false, code: 'CANCELLED', message: 'cancelled' }))+ expect(await installGuestHelper({ platform: 'win32', owner: 'owner', ownerHome: 'C:\\Users\\owner', runner: whoami, admin: cancelled }))+ .toEqual({ ok: false, code: 'CANCELLED', message: 'cancelled' })+ expect(await installGuestHelper({ platform: 'win32', owner: 'owner', ownerHome: 'not-a-profile', runner: whoami, admin: cancelled }))+ .toMatchObject({ ok: false, code: 'FAILED' })+ expect(await installGuestHelper({ platform: 'win32', owner: 'owner', ownerHome: 'C:\\Users\\owner', runner: async () => ({ code: 1, stdout: '', stderr: '' }), admin: cancelled }))+ .toMatchObject({ ok: false, code: 'FAILED' })+ })+})++describe('the Windows helper state', () => {+ const read = (text: string | null) => () => text+ const current = String(WINDOWS_GUEST_SETUP_VERSION)+ it('is ready only with the current version and the setup task', async () => {+ expect(await guestHelperStatus({ platform: 'win32', read: read(`${current}\n`), runner: async () => ({ code: 0, stdout: '', stderr: '' }) }))+ .toEqual({ state: 'ready', version: WINDOWS_GUEST_SETUP_VERSION })+ expect(await guestHelperStatus({ platform: 'win32', read: read(`${current}\n`), runner: async () => ({ code: 1, stdout: '', stderr: '' }) }))+ .toEqual({ state: 'missing', version: WINDOWS_GUEST_SETUP_VERSION })+ expect(await guestHelperStatus({ platform: 'win32', read: read(null), runner: async () => ({ code: 0, stdout: '', stderr: '' }) }))+ .toEqual({ state: 'missing', version: null })+ expect(await guestHelperStatus({ platform: 'win32', read: read('0\n'), runner: async () => ({ code: 0, stdout: '', stderr: '' }) }))+ .toEqual({ state: 'outdated', version: 0 })+ })+})diff --git a/cli/src/lib/guestPaneCommand.spec.ts b/cli/src/lib/guestPaneCommand.spec.tsindex 5db03b818..fa017f3a8 100644--- a/cli/src/lib/guestPaneCommand.spec.ts+++ b/cli/src/lib/guestPaneCommand.spec.ts@@ -55,6 +55,20 @@ describe('a guest\'s pane', () => {it('is for the engines whose subscription the relay spends', () => {expect(GUEST_LAUNCH_ENGINES).toEqual(['claude', 'codex'])})++ it('is made by the guest\'s own host on Windows: the engine itself, with only the relay\'s variables', () => {+ const claude = guestPaneCommand({ account, engine: 'claude', relayUrl: relay, token: 'guest-token', bypassPermission: true, platform: 'win32' })+ // No helper, no `/bin/sh` bootstrap, and the token never on the command line.+ expect(claude.argv).toEqual(['claude', '--dangerously-skip-permissions'])+ expect(claude.argv.join(' ')).not.toContain('guest-token')+ expect(claude.env).toEqual({ ANTHROPIC_BASE_URL: `${relay}/claude`, ANTHROPIC_AUTH_TOKEN: 'guest-token' })+ const codex = guestPaneCommand({ account, engine: 'codex', relayUrl: relay, token: 'guest-token', bypassPermission: false,+ permissionFlags: ['--approve-for-me'], prompt: 'Fix the tests', platform: 'win32' })+ expect(codex.argv[0]).toBe('codex')+ expect(codex.argv).toContain(`model_providers.harness_owner.base_url="${relay}/codex"`)+ expect(codex.argv.slice(-2)).toEqual(['--approve-for-me', 'Fix the tests'])+ expect(codex.env).toEqual({ HARNESS_RELAY_TOKEN: 'guest-token' })+ })})// The bootstrap runs for real, with a fake `sudo` on PATH that logs what it is asked and answers whether thediff --git a/cli/src/lib/guestPaneCommand.ts b/cli/src/lib/guestPaneCommand.tsindex 489bb4615..b839a120d 100644--- a/cli/src/lib/guestPaneCommand.ts+++ b/cli/src/lib/guestPaneCommand.ts@@ -52,9 +52,17 @@ export interface GuestPaneInput {/** The owner's LANG, so the guest's terminal reads text as the owner's does. */lang?: stringhelperPath?: string+ /** Where the pane is made; `process.platform` when absent. Windows has no helper: its pane is made by the guest's own host. */+ platform?: NodeJS.Platform}-/** The pane's argv and the variables to set on it (`tmux new-session -e`), which the helper passes on. */+/**+ * The pane's argv and the variables to set on it (`tmux new-session -e`), which the helper passes on.+ *+ * On Windows the pane is created by the guest's own `harness-pty` host (lib/windows/guestHostBackend.ts), so the+ * process is already the guest's: there is no helper, no install check and no `sudo`, and the argv is the engine+ * itself with the relay's variables. The engine must be installed for that account (the guest's own PATH).+ */export function guestPaneCommand(input: GuestPaneInput): { argv: string[]; env: Record<string, string> } {const { account, engine, relayUrl, token } = inputconst helperPath = input.helperPath ?? GUEST_HELPER_PATH@@ -69,6 +77,14 @@ export function guestPaneCommand(input: GuestPaneInput): { argv: string[]; env:...(engine === 'claude' ? claudeRelayEnv(relayUrl, token) : codexRelayEnv(token)),}const cwd = input.cwd ?? account.workspace+ // The guest's own host makes this pane as the guest: the engine runs directly, and only the relay's+ // variables travel with it (no helper, and nothing of the owner's).+ if ((input.platform ?? process.platform) === 'win32') {+ return {+ argv: engineArgv,+ env: engine === 'claude' ? claudeRelayEnv(relayUrl, token) : codexRelayEnv(token),+ }+ }const run = guestRunCommand(account.user, cwd, env, engineArgv, helperPath)return {argv: ['/bin/sh', '-c', GUEST_PANE_BOOTSTRAP, 'harness-guest', helperPath, account.user, cwd, engine, ...run.argv],diff --git a/cli/src/lib/paneEngineProcess.spec.ts b/cli/src/lib/paneEngineProcess.spec.tsindex 1aaf5865a..a8ac91c9a 100644--- a/cli/src/lib/paneEngineProcess.spec.ts+++ b/cli/src/lib/paneEngineProcess.spec.ts@@ -11,6 +11,15 @@ function backendWithRoot(root: number | 'missing' | null): TerminalBackend {}describe('lookupPaneEngineProcess', () => {+ it('reads the table a backend holds (a guest host) rather than the machine\'s own', async () => {+ const rows = [+ { pid: 10, parentPid: 1, args: 'engine', startMarker: 'm10', executable: 'engine' },+ { pid: 20, parentPid: 10, args: 'claude', startMarker: 'w:2', executable: 'claude' },+ ]+ const backend = { rootProcess: async () => 10, processTable: () => async () => rows as never }+ expect(await lookupPaneEngineProcess(backend, runtime, 'claude')).toMatchObject({ ok: true })+ })+it('says gone when the backend has no such pane', async () => {const found = await lookupPaneEngineProcess(backendWithRoot('missing'), runtime, 'claude')expect(found).toEqual({ ok: false, unknown: false, reason: 'tmux:%1 has no pane' })diff --git a/cli/src/lib/paneEngineProcess.ts b/cli/src/lib/paneEngineProcess.tsindex 55a1fb673..4214362f3 100644--- a/cli/src/lib/paneEngineProcess.ts+++ b/cli/src/lib/paneEngineProcess.ts@@ -4,13 +4,14 @@*/import type { AgentEngine } from '../engines/types.js'import { registry, type ProcessIdentity, type RegisteredSession } from './registry.js'-import { comparableStartMarker, enrichProcessRows, processRows, processTreePids, selectEngineProcess } from './processTable.js'+import { comparableStartMarker, enrichProcessRows, processRows, processTreePids, selectEngineProcess, type ProcessRow } from './processTable.js'import type { TerminalBackend } from './terminalBackend.js'import { processIdentityOf, sameProcessIdentity, terminalRuntimeLabel } from './terminalRuntime.js'import type { TerminalRuntimeRef } from './terminalTypes.js'-/** What the lookups below need of a backend: the pane's own root process. */-type PaneRootSource = Pick<TerminalBackend, 'rootProcess'>+/** What the lookups below need of a backend: the pane's own root process, and the table its panes are in when that is+ * not the machine's own (a guest's host). */+type PaneRootSource = Pick<TerminalBackend, 'rootProcess'> & Pick<Partial<TerminalBackend>, 'processTable'>/*** Resolve the stable CLI process below one tmux pane, ahead of short-lived helper descendants — and say@@ -26,6 +27,8 @@ export async function lookupPaneEngineProcess(backend: PaneRootSource,runtime: TerminalRuntimeRef,engine: AgentEngine,+ /** The table to read; the backend's own when it has one (a guest's host), else the machine's. */+ readRows: () => Promise<ProcessRow[] | null> = backend.processTable?.() ?? processRows,): Promise<PaneProcessLookup> {const label = terminalRuntimeLabel(runtime)const rootPid = await backend.rootProcess(runtime)@@ -34,7 +37,7 @@ export async function lookupPaneEngineProcess(// pane was killed counted as active for good. A failed call is still no evidence either way.if (rootPid === 'missing') return { ok: false, unknown: false, reason: `${label} has no pane` }if (!rootPid) return { ok: false, unknown: true, reason: `${label} could not be resolved` }- const rows = await processRows()+ const rows = await readRows()if (!rows) return { ok: false, unknown: true, reason: 'the process table could not be read' }const enrichedRows = await enrichProcessRows(rows, processTreePids(rows, [rootPid]))const process = selectEngineProcess(enrichedRows, rootPid, engine)diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.tsindex c30e83606..98f82915e 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -173,7 +173,8 @@ export const LAUNCH_ERROR_CODES = ['stop_unconfirmed',// A guest on a machine shared with it (core/guestPolicy.ts, core/agents/guestCreate.ts, services/guestLaunches.ts).'guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required',- 'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',+ 'guest_engine_unsupported', 'guest_engine_check_failed', 'guest_engine_install_failed', 'guest_host_unavailable',+ 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing','guest_helper_not_authorized', 'guest_helper_failed',// The `setup` kind's own codes, named for a delete or restart refusal (cli/src/lib/productUsageSignals.ts).'tmux_unavailable', 'pty_host_unavailable', 'tmux_too_old_for_dsh', 'tmux_too_old_for_grid', 'engine_unavailable', 'native_launch_held',diff --git a/cli/src/lib/ptyHostBackend.ts b/cli/src/lib/ptyHostBackend.tsindex c39537f98..203495efd 100644--- a/cli/src/lib/ptyHostBackend.ts+++ b/cli/src/lib/ptyHostBackend.ts@@ -107,6 +107,9 @@ export interface PtyHostBackendOptions {platform?: NodeJS.Platform/** End a process and its descendants (windows/treeKill.ts `endProcessTree`); a seam for tests. */endTree?: (pid: number) => Promise<TreeKillOutcome>+ /** A host running in another account (a guest's): its panes are validated against that host's process table, and it+ * never installs this daemon's machine-wide process table and signaller (the owner's own host keeps those). */+ guestHost?: boolean}/**@@ -171,6 +174,8 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {private readonly owner: () => stringprivate readonly platform: NodeJS.Platformprivate readonly endTree: (pid: number) => Promise<TreeKillOutcome>+ /** A guest's host: its own process table, never the machine-wide one (`installWindowsSeams`). */+ private readonly guestHost: boolean/** Whether this backend set the process table source and the agent signaller (Windows), for `dispose`. */private windowsSeams = falseprivate client: PtyHostClient | null = null@@ -209,6 +214,7 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {? ((home) => reachPtyHost(home, drainInstance, liveness)): (async (home) => ensurePtyHost(home, { target: await this.pinnedTarget(liveness), liveness })))this.endTree = options.endTree ?? ((pid) => this.endTreeOf(pid))+ this.guestHost = options.guestHost === true}/**@@ -261,7 +267,7 @@ export class PtyHostBackend implements TerminalBackend<PtyRuntimeRef> {this.disposed = falsethis.cancelReconnect()// The process table and the signaller are the machine's, not a host's: the create backend's alone.- if (this.platform === 'win32' && !this.draining) this.installWindowsSeams()+ if (this.platform === 'win32' && !this.draining && !this.guestHost) this.installWindowsSeams()if (this.gone) return { state: 'ready' }const reached = await this.launch(this.home)if (this.draining && 'unavailable' in reached) {diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex ed55aa5a8..9d793d028 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -1,3 +1,4 @@+import type { ProcessRow } from './processTable.js'import type { AgentEngine } from '../engines/types.js'import type {SubmitOptions,@@ -65,6 +66,11 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimpaneInfo(runtime: Ref): Promise<TerminalPaneInfo | null>/** The pane's own root process, 'missing' when the backend says the pane does not exist, null when it could not ask. */rootProcess(runtime: Ref): Promise<number | 'missing' | null>+ /**+ * The process table this backend's panes are in, when it is not the machine's own: a guest's host runs in another+ * account and the owner's `ps` cannot see its processes (nor may it). Absent means the machine's own table.+ */+ processTable?(): (() => Promise<ProcessRow[] | null>) | undefined/** Byte streaming is optional per backend. */openStream?(diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.tsindex 9d43ff6b0..4947a3ad0 100644--- a/cli/src/lib/terminalBackendCoordinator.spec.ts+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts@@ -168,6 +168,22 @@ describe('TerminalBackendCoordinator', () => {expect(captures).toHaveBeenCalledTimes(3)})+ it('routes a host added later (a guest\'s), and keeps it when the configured hosts are listed again', () => {+ const owner = backend('tmux:default', vi.fn())+ const guest = backend('ptyhost:p3-0.5.55-gu0123456789ab', vi.fn())+ const coordinator = new TerminalBackendCoordinator([owner], ['tmux'])+ const guestRuntime: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p3-0.5.55-gu0123456789ab', paneId: '%1' }+ coordinator.addBackend(guest)+ expect(coordinator.backendFor(guestRuntime)).toBe(guest)+ // The configured hosts re-listed (a tmux recovery) must not drop the guest's host.+ coordinator.replaceBackends([owner])+ expect(coordinator.backendFor(guestRuntime)).toBe(guest)+ expect(coordinator.instances()).toEqual([owner, guest])+ // A guest removed: its host is no longer this daemon's to route.+ coordinator.removeBackend(guest)+ expect(coordinator.backendFor(guestRuntime)).toBeUndefined()+ })+it('uses lease-aware pre-dispatch fallback but never retries ambiguous completion', async () => {const tmuxBackend = backend('tmux:default', submitBy({ state: 'failed', dispatch: 'rejected', reason: 'rejected' }))const coordinator = new TerminalBackendCoordinator([tmuxBackend], ['tmux'])diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex d9dd90ec1..0a4b0dbfd 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -80,6 +80,9 @@ const defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => {/** Resolves all terminal I/O through validated backend-scoped locators. */export class TerminalBackendCoordinator {private readonly byInstance = new Map<string, TerminalBackend>()+ /** Backends added after construction (a guest's host, reached on demand): kept across `replaceBackends`, which+ * re-lists the configured hosts and must not drop them. */+ private readonly added = new Set<TerminalBackend>()private readonly unknownRetryMs: readonly number[]private readonly sleep: (ms: number) => Promise<void>private changing: (agentId: string) => boolean = () => false@@ -133,7 +136,22 @@ export class TerminalBackendCoordinator {replaceBackends(backends: readonly TerminalBackend[]): void {this.byInstance.clear()- for (const backend of backends) this.byInstance.set(backend.instanceId, backend)+ for (const backend of [...backends, ...this.added]) this.byInstance.set(backend.instanceId, backend)+ }++ /**+ * A backend reached after this daemon started (a guest's own host on Windows): its panes are routed and validated+ * as the configured hosts' are, and it stays listed through any `replaceBackends`.+ */+ addBackend(backend: TerminalBackend): void {+ this.added.add(backend)+ this.byInstance.set(backend.instanceId, backend)+ }++ /** The backend is gone for good (its guest was removed): its panes are no longer this daemon's to route. */+ removeBackend(backend: TerminalBackend): void {+ this.added.delete(backend)+ if (this.byInstance.get(backend.instanceId) === backend) this.byInstance.delete(backend.instanceId)}instances(): TerminalBackend[] {diff --git a/cli/src/lib/windows/guestEngine.spec.ts b/cli/src/lib/windows/guestEngine.spec.tsnew file mode 100644index 000000000..dc96e0f4a--- /dev/null+++ b/cli/src/lib/windows/guestEngine.spec.ts@@ -0,0 +1,103 @@+import { describe, expect, it, vi } from 'vitest'+import type { TerminalRuntimeRef } from '../terminalTypes.js'+import { ensureGuestEngine, guestEngineInstallArgv, guestEngineInstallable, guestEngineProbeArgv,+ guestNpmCli, guestNodeDir, guestNodeExe, type GuestEngineBackend } from './guestEngine.js'++const runtime = (paneId: string): TerminalRuntimeRef => ({ backend: 'ptyhost', instance: 'p3-0.5.55-gu0123456789ab', paneId })+const HOME = 'C:\\Users\\hg_0123456789ab'+const PREFIX = 'C:\\ProgramData\\HarnessGuests\\hosts\\hg_0123456789ab\\engines'++// The guest's own host, faked: each pane it makes is answered with the states the test lists, then comes to rest.+function backend(states: Array<Record<string, unknown>>, over: { createFails?: boolean; capture?: string } = {}) {+ let made = 0+ const queue = [...states]+ const next = () => (queue.length > 1 ? queue.shift()! : queue[0] ?? { dead: true, exitStatus: 0, command: 'node', engineExit: null })+ const created: TerminalRuntimeRef[] = []+ const killed: TerminalRuntimeRef[] = []+ const host = {+ create: vi.fn(async (request: { command?: string[]; label?: string }) => {+ if (over.createFails) return { state: 'failed' as const, dispatch: 'not_started' as const, reason: 'no guest host' }+ const at = runtime(`%${++made}`)+ created.push(at)+ return { state: 'succeeded' as const, dispatch: 'executed' as const, runtime: at }+ }),+ kill: vi.fn(async (at: TerminalRuntimeRef) => { killed.push(at); return { state: 'succeeded' as const, dispatch: 'executed' as const } }),+ paneState: vi.fn(async () => next()),+ capture: vi.fn(async () => ({ state: 'succeeded' as const, value: over.capture ?? '' })),+ }+ return { host: host as unknown as GuestEngineBackend, created, killed, calls: host.create }+}++const options = { user: 'hg_0123456789ab', engine: 'claude', cwd: HOME, prefix: PREFIX, setupVersion: 2, sleep: async () => {}, now: () => 0 }++describe('a guest\'s engine on Windows', () => {+ it('is installed as the guest, from the Node runtime staged beside the host, into that account\'s own prefix', () => {+ expect(guestNodeDir(2)).toBe('C:\\ProgramData\\HarnessGuests\\bin\\node-2')+ expect(guestNodeExe(2)).toBe(`${guestNodeDir(2)}\\node.exe`)+ expect(guestNpmCli(2)).toBe(`${guestNodeDir(2)}\\node_modules\\npm\\bin\\npm-cli.js`)+ expect(guestEngineProbeArgv('claude')).toEqual(['cmd.exe', '/d', '/s', '/c', 'where claude'])+ expect(guestEngineInstallArgv('codex', PREFIX, 2)).toEqual([guestNodeExe(2), guestNpmCli(2),+ 'install', '--global', '--prefix', PREFIX, '--no-fund', '--no-audit', '--loglevel=error', '@openai/codex'])+ expect(guestEngineInstallArgv('claude', PREFIX, 2).at(-1)).toBe('@anthropic-ai/claude-code')+ // Only the engines whose subscription the relay spends are a guest's to have.+ expect(guestEngineInstallable('claude')).toBe(true)+ expect(guestEngineInstallable('opencode')).toBe(false)+ })++ it('runs nothing more when the account already has the engine', async () => {+ const log = vi.fn()+ const f = backend([{ dead: true, exitStatus: 0, command: 'cmd.exe', engineExit: null }])+ expect(await ensureGuestEngine(f.host, { ...options, log })).toEqual({ ok: true })+ expect(f.calls).toHaveBeenCalledTimes(1)+ expect(f.calls.mock.calls[0]![0]).toMatchObject({ command: ['cmd.exe', '/d', '/s', '/c', 'where claude'], cwd: HOME })+ expect(f.killed).toHaveLength(1)+ expect(log).not.toHaveBeenCalled()+ })++ it('installs it in its own pane when it is missing, and asks nothing of the person', async () => {+ const log = vi.fn()+ const f = backend([+ { dead: true, exitStatus: 1, command: 'cmd.exe', engineExit: null },+ { dead: true, exitStatus: 0, command: 'node.exe', engineExit: null },+ ])+ expect(await ensureGuestEngine(f.host, { ...options, log })).toEqual({ ok: true })+ expect(f.calls).toHaveBeenCalledTimes(2)+ expect(f.calls.mock.calls[1]![0]).toMatchObject({ label: 'guest-engine-install-claude', command: guestEngineInstallArgv('claude', PREFIX, 2) })+ expect(f.killed).toHaveLength(2)+ expect(log.mock.calls.flat().join(' ')).toContain('install · claude · hg_0123456789ab')+ })++ it('says what npm said when it fails, never a bare failure', async () => {+ const f = backend([+ { dead: true, exitStatus: 1, command: 'cmd.exe', engineExit: null },+ { dead: true, exitStatus: 1, command: 'node.exe', engineExit: null },+ ], { capture: 'npm ERR! code EAI_AGAIN\nnpm ERR! network\n' })+ expect(await ensureGuestEngine(f.host, options)).toEqual({ ok: false, error: 'GUEST_ENGINE_INSTALL_FAILED',+ detail: 'npm ERR! code EAI_AGAIN npm ERR! network' })+ expect(f.killed).toHaveLength(2)+ })++ it('stops an install that never finishes, and says so in words', async () => {+ let clock = 0+ const f = backend([+ { dead: true, exitStatus: 1, command: 'cmd.exe', engineExit: null },+ { dead: false, exitStatus: null, command: 'node.exe', engineExit: null },+ ])+ expect(await ensureGuestEngine(f.host, { ...options, now: () => clock, sleep: async () => { clock += 1000 }, installTimeoutMs: 2000 }))+ .toMatchObject({ ok: false, error: 'GUEST_ENGINE_INSTALL_FAILED', detail: expect.stringContaining('did not finish in time') })+ expect(f.killed).toHaveLength(2)+ })++ it('refuses an engine a guest\'s harness cannot be, before anything runs', async () => {+ const f = backend([])+ expect(await ensureGuestEngine(f.host, { ...options, engine: 'opencode' }))+ .toMatchObject({ ok: false, error: 'GUEST_ENGINE_UNSUPPORTED' })+ expect(f.calls).not.toHaveBeenCalled()+ })++ it('says the host could not check, rather than installing into nothing', async () => {+ const f = backend([], { createFails: true })+ expect(await ensureGuestEngine(f.host, options)).toEqual({ ok: false, error: 'GUEST_ENGINE_CHECK_FAILED', detail: 'no guest host' })+ expect(f.calls).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/lib/windows/guestEngine.ts b/cli/src/lib/windows/guestEngine.tsnew file mode 100644index 000000000..8632b8305--- /dev/null+++ b/cli/src/lib/windows/guestEngine.ts@@ -0,0 +1,135 @@+/**+ * Installing a guest's engine on Windows (docs/superpowers/specs/2026-11-05-windows-guests-design.md): the Windows twin+ * of the macOS helper's `install` (lib/guestAccounts.ts `installGuestEngine`), which runs the engine's installer as the+ * guest so the engine lands in that account's own profile.+ *+ * Only the guest's own host can run a process as the guest, so this asks it to run two short panes: one that asks+ * whether the engine is on that account's PATH (`where claude`), and, when it is not, the package manager itself from+ * the Node runtime the setup task staged for guests. Both are plain argv — no shell text, no prompt, no flag of the+ * person's. The engine then starts in its own pane exactly as an owner's does, with the guest's PATH carrying+ * `%USERPROFILE%\.local` (the setup task writes that into the host's wrapper).+ */+import { ENGINE_WINDOWS_INSTALL } from '../engineInstall.js'+import type { TerminalBackend } from '../terminalBackend.js'+import type { TerminalRuntimeRef } from '../terminalTypes.js'+import { WINDOWS_GUEST_ROOT } from './guestRequests.js'++/** The Node runtime the setup task copies for guests, beside the signed pty (`guestScript.ts`). */+export function guestNodeDir(setupVersion: number): string {+ return `${WINDOWS_GUEST_ROOT}\\bin\\node-${setupVersion}`+}+export function guestNodeExe(setupVersion: number): string {+ return `${guestNodeDir(setupVersion)}\\node.exe`+}+/** npm ships inside Node's Windows distribution, beside `node.exe`. */+export function guestNpmCli(setupVersion: number): string {+ return `${guestNodeDir(setupVersion)}\\node_modules\\npm\\bin\\npm-cli.js`+}++/** The engines a guest's harness may be: the two the subscription relay can spend (lib/guestPaneCommand.ts). */+export const GUEST_INSTALLABLE_ENGINES = ['claude', 'codex'] as const+export type GuestInstallableEngine = (typeof GUEST_INSTALLABLE_ENGINES)[number]++/** Whether [engine] is one this machine may install for a guest. */+export function guestEngineInstallable(engine: string): engine is GuestInstallableEngine {+ return (GUEST_INSTALLABLE_ENGINES as readonly string[]).includes(engine)+}++/** `where <engine>`: the account's PATH answers with where it would run it. */+export function guestEngineProbeArgv(engine: GuestInstallableEngine): string[] {+ return ['cmd.exe', '/d', '/s', '/c', `where ${engine}`]+}++/**+ * The engine's own installer as the guest: npm from the staged Node, into [prefix] — the guest host's own `engines`+ * folder, which the guest may write and the owner may read (so the daemon resolves the shim it wrote, exactly as it+ * resolves one of its own: lib/windows/launch.ts `windowsEngineArgv`).+ */+export function guestEngineInstallArgv(engine: GuestInstallableEngine, prefix: string, setupVersion: number): string[] {+ const install = ENGINE_WINDOWS_INSTALL[engine]+ if (!('npm' in install)) throw new Error(`${engine} has no npm install on Windows`)+ return [guestNodeExe(setupVersion), guestNpmCli(setupVersion), 'install', '--global', '--prefix', prefix,+ '--no-fund', '--no-audit', '--loglevel=error', install.npm]+}++/** What this helper needs of a terminal backend: make a pane, ask what it runs, read it, close it. */+export type GuestEngineBackend = Pick<TerminalBackend, 'create' | 'kill' | 'paneState' | 'capture'>++export interface GuestEngineOptions {+ user: string+ engine: string+ /** The guest's workspace: where both short panes run. */+ cwd: string+ /** The guest host's `engines` folder: where npm installs as the guest, and where the daemon later resolves the engine. */+ prefix: string+ setupVersion: number+ /** The person's language is not needed here: both panes only install and record their status. */+ checkTimeoutMs?: number+ installTimeoutMs?: number+ pollMs?: number+ sleep?: (ms: number) => Promise<void>+ now?: () => number+ log?: (line: string) => void+}++export type GuestEngineResult = { ok: true } | { ok: false; error: 'GUEST_ENGINE_UNSUPPORTED' | 'GUEST_ENGINE_CHECK_FAILED' | 'GUEST_ENGINE_INSTALL_FAILED'; detail: string }++/** The last lines a failed pane said, for the person to read as the reason. */+function tail(text: string, limit = 8): string {+ return text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-limit).join(' ').slice(0, 600)+}++async function waitForExit(backend: GuestEngineBackend, runtime: TerminalRuntimeRef,+ options: { timeoutMs: number; pollMs: number; sleep: (ms: number) => Promise<void>; now: () => number }): Promise<number | null> {+ const deadline = options.now() + options.timeoutMs+ for (;;) {+ const state = await backend.paneState(runtime)+ // A pane that is gone has no exit status to report; unknown is asked again until the deadline.+ if (state === 'gone') return null+ if (state !== 'unknown' && state.dead) return state.exitStatus+ if (options.now() >= deadline) return null+ await options.sleep(options.pollMs)+ }+}++/**+ * Makes sure [engine] is installed for [user], installing it in a pane on the guest's own host when it is not. Answers+ * a failure with the pane's own last words, so the person is told what npm said rather than "it did not work".+ */+export async function ensureGuestEngine(backend: GuestEngineBackend, options: GuestEngineOptions): Promise<GuestEngineResult> {+ if (!guestEngineInstallable(options.engine)) {+ return { ok: false, error: 'GUEST_ENGINE_UNSUPPORTED', detail: 'You can start Claude Code or Codex on this computer.' }+ }+ const engine = options.engine+ const log = options.log ?? (() => {})+ const pollMs = options.pollMs ?? 500+ const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const now = options.now ?? Date.now+ const wait = { pollMs, sleep, now }++ const asked = await backend.create({ cwd: options.cwd, label: 'guest-engine-check', command: guestEngineProbeArgv(engine) })+ if (asked.state !== 'succeeded') {+ return { ok: false, error: 'GUEST_ENGINE_CHECK_FAILED', detail: asked.reason || 'The guest\'s host could not check for the engine.' }+ }+ const present = await waitForExit(backend, asked.runtime, { ...wait, timeoutMs: options.checkTimeoutMs ?? 30_000 })+ await backend.kill(asked.runtime)+ if (present === 0) return { ok: true }++ log(`install · ${engine} · ${options.user}${present === null ? ' · the check did not answer' : ''}`)+ const installing = await backend.create({ cwd: options.cwd, label: `guest-engine-install-${engine}`,+ command: guestEngineInstallArgv(engine, options.prefix, options.setupVersion) })+ if (installing.state !== 'succeeded') {+ return { ok: false, error: 'GUEST_ENGINE_INSTALL_FAILED', detail: installing.reason || 'The guest\'s host could not start the install.' }+ }+ const status = await waitForExit(backend, installing.runtime, { ...wait, timeoutMs: options.installTimeoutMs ?? 20 * 60_000 })+ const said = await backend.capture(installing.runtime, { historyLines: 60, ansi: false })+ await backend.kill(installing.runtime)+ if (status === 0) {+ log(`install · ${engine} · ${options.user} · done`)+ return { ok: true }+ }+ const words = said.state === 'succeeded' ? tail(said.value) : ''+ return { ok: false, error: 'GUEST_ENGINE_INSTALL_FAILED',+ detail: words || (status === null ? `Installing ${engine} did not finish in time. Try again from this computer.`+ : `Installing ${engine} failed on this computer (${status}).`) }+}diff --git a/cli/src/lib/windows/guestHelperInstallWin.ts b/cli/src/lib/windows/guestHelperInstallWin.tsnew file mode 100644index 000000000..7ebc3255a--- /dev/null+++ b/cli/src/lib/windows/guestHelperInstallWin.ts@@ -0,0 +1,55 @@+/**+ * The Windows side of guest sharing's one-time install (lib/guestHelperInstall.ts): the guest tree, the SYSTEM+ * setup task and the version file, all behind one UAC prompt through the proven Team admin runner. Loading this+ * module is what pulls the PowerShell script builders (and their Team imports) in, so lib/guestHelperInstall.ts+ * imports it only when the platform is Windows: the edge host's other services must not carry that code (and+ * its zod) in the process they share (src/leanEntry.spec.ts).+ */+import { userInfo } from 'node:os'+import { dirname } from 'node:path'+import { ptyHostBinary } from '../ptyHost/launch.js'+import { managedNodePath } from '../nodeRuntime.js'+import { runGuestCommand, type GuestRunner } from '../guestAccounts.js'+import { WHOAMI_USER_ARGS, windowsUserSid } from '../../team/windowsTeam.js'+import { WINDOWS_GUEST_SETUP_VERSION, WINDOWS_GUEST_VERSION_FILE, buildWindowsGuestInstallScript,+ buildWindowsGuestProcessorScript } from './guestScript.js'+import { WINDOWS_GUEST_TASK } from './guestSetupClient.js'+import type { RunAdmin } from '../../team/admin.js'+import type { GuestHelperInstallOptions, GuestHelperInstallResult, GuestHelperStatus, GuestHelperStatusDeps } from '../guestHelperInstall.js'++/** The Windows one-time install: the proven UAC runner, the guest tree/task, one prompt. */+export async function installWindowsGuestHelper(options: GuestHelperInstallOptions,+ prompt: string): Promise<GuestHelperInstallResult> {+ if (process.env.HARNESS_WINDOWS_GUESTS === '0') {+ return { ok: false, code: 'UNSUPPORTED', message: 'Sharing this computer is turned off on this build.' }+ }+ const runner = options.runner ?? runGuestCommand+ const owner = options.owner ?? userInfo().username+ const ownerHome = options.ownerHome ?? process.env.USERPROFILE ?? ''+ if (!/^[A-Za-z]:\\Users\\[A-Za-z0-9_.-]+$/.test(ownerHome)) {+ return { ok: false, code: 'FAILED', message: 'Could not find the owner\'s Windows profile (%USERPROFILE%).' }+ }+ const who = await runner('whoami', WHOAMI_USER_ARGS, { timeoutMs: 30_000 })+ const ownerSid = who.code === 0 ? windowsUserSid(who.stdout) : null+ if (!ownerSid) return { ok: false, code: 'FAILED', message: 'Could not read this account\'s SID (whoami /user).' }+ const processor = buildWindowsGuestProcessorScript({ owner, ownerHome, ownerSid, version: String(WINDOWS_GUEST_SETUP_VERSION) })+ const script = buildWindowsGuestInstallScript({ owner, ownerHome, ownerSid, processor, version: String(WINDOWS_GUEST_SETUP_VERSION),+ ptySrc: ptyHostBinary(), nodeSrc: dirname(managedNodePath()) })+ const admin: RunAdmin = options.admin ?? (await import('../../team/admin.js')).adminRunner({ platform: 'win32', runner })+ const result = await admin(() => ({ script }), prompt)+ if (result.ok) return { ok: true }+ return { ok: false, code: result.code === 'NO_PROMPT' ? 'FAILED' : result.code, message: result.message }+}++/** Whether sharing is on here: the version file this CLI writes, and the setup task registered to run it. */+export async function windowsGuestHelperStatus(deps: GuestHelperStatusDeps,+ read: (path: string) => string | null): Promise<GuestHelperStatus> {+ const installed = read(WINDOWS_GUEST_VERSION_FILE)+ if (installed === null) return { state: 'missing', version: null }+ const version = Number(installed.trim())+ if (!Number.isInteger(version) || version < WINDOWS_GUEST_SETUP_VERSION) {+ return { state: 'outdated', version: Number.isFinite(version) ? version : null }+ }+ const task = await (deps.runner ?? runGuestCommand)('schtasks.exe', ['/query', '/tn', WINDOWS_GUEST_TASK], { timeoutMs: 10_000 })+ return { state: task.code === 0 ? 'ready' : 'missing', version }+}diff --git a/cli/src/lib/windows/guestHostBackend.spec.ts b/cli/src/lib/windows/guestHostBackend.spec.tsnew file mode 100644index 000000000..e74ab3515--- /dev/null+++ b/cli/src/lib/windows/guestHostBackend.spec.ts@@ -0,0 +1,58 @@+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { createGuestHostBackend, guestHostHome, guestHostTask, waitForGuestHost } from './guestHostBackend.js'++const discovery = (instance: string, version: string, protocol: number, pid: number) => JSON.stringify({+ protocol, instance, endpoint: `\\\\.\\pipe\\harness-pty-${instance}`, pid, version,+ token: '0123456789abcdef0123456789abcdef01234567',+})++describe('a guest host', () => {+ it('lives under the guest tree and starts the task the setup task registered', () => {+ expect(guestHostHome('hg_0123456789ab')).toBe('C:\\ProgramData\\HarnessGuests\\hosts\\hg_0123456789ab')+ expect(guestHostTask('hg_0123456789ab')).toBe('\\Harness\\Guests\\hg_0123456789ab')+ })++ it('picks the newest discovery file the guest published', async () => {+ const home = mkdtempSync(join(tmpdir(), 'guest-host-'))+ mkdirSync(join(home, 'run'))+ writeFileSync(join(home, 'run', 'pty-host-p2-0.0.1.json'), discovery('p2-0.0.1', '0.0.1', 2, 11))+ writeFileSync(join(home, 'run', 'pty-host-p2-9.9.9.json'), discovery('p2-9.9.9', '9.9.9', 2, 22))+ writeFileSync(join(home, 'run', 'other.json'), '{}')+ // Both hosts are alive in this test: the newest wins.+ expect((await waitForGuestHost(home, { user: 'hg_x', waitMs: 0, liveness: { alive: () => true } }))?.instance).toBe('p2-9.9.9')+ })++ it('never dials a discovery file whose host has gone, as a setup re-run leaves behind', async () => {+ const home = mkdtempSync(join(tmpdir(), 'guest-host-stale-'))+ mkdirSync(join(home, 'run'))+ writeFileSync(join(home, 'run', 'pty-host-p3-0.5.55.json'), discovery('p3-0.5.55', '0.5.55', 3, 11))+ writeFileSync(join(home, 'run', 'pty-host-p3-0.5.55-gu0123456789ab.json'), discovery('p3-0.5.55-gu0123456789ab', '0.5.55', 3, 22))+ // The old host's pid is gone; the tagged one runs. The dead file is newer only by name, never picked.+ const liveness = { alive: (pid: number) => pid === 22 }+ expect((await waitForGuestHost(home, { user: 'hg_x', waitMs: 0, liveness }))?.instance).toBe('p3-0.5.55-gu0123456789ab')+ expect(await waitForGuestHost(home, { user: 'hg_x', waitMs: 0, liveness: { alive: () => false } })).toBeNull()+ })++ it('answers an unavailable host, never a throw, when its task cannot start', async () => {+ const home = mkdtempSync(join(tmpdir(), 'guest-host-task-'))+ const backend = createGuestHostBackend({ user: 'hg_x', home, startTask: async () => { throw new Error('the task is gone') },+ list: () => [], waitMs: 0, sleep: async () => {} })+ expect(await backend.prepare({ ownedPanes: new Map() })).toMatchObject({ state: 'unavailable', code: 'PTY_HOST_UNAVAILABLE' })+ backend.dispose()+ })++ it('returns null when nothing is published in the window', async () => {+ const home = mkdtempSync(join(tmpdir(), 'guest-host-empty-'))+ expect(await waitForGuestHost(home, { user: 'hg_x', waitMs: 0 })).toBeNull()+ })++ it('uses only files whose instance and protocol a host really writes', async () => {+ const home = mkdtempSync(join(tmpdir(), 'guest-host-bad-'))+ mkdirSync(join(home, 'run'))+ writeFileSync(join(home, 'run', 'pty-host-p2-9.9.9.json'), JSON.stringify({ instance: 'p2-1.0.0', protocol: 2, endpoint: 'x', pid: 1, version: '9.9.9', token: 'short' }))+ expect(await waitForGuestHost(home, { user: 'hg_x', waitMs: 0 })).toBeNull()+ })+})diff --git a/cli/src/lib/windows/guestHostBackend.ts b/cli/src/lib/windows/guestHostBackend.tsnew file mode 100644index 000000000..96210d06e--- /dev/null+++ b/cli/src/lib/windows/guestHostBackend.ts@@ -0,0 +1,94 @@+/**+ * The owner's side of a guest host (docs/superpowers/specs/2026-11-05-windows-guests-design.md): point the existing+ * `PtyHostBackend` at the guest's host home, start `\Harness\Guests\<user>` (the task the setup task registered), and+ * reuse the exact pane backend the owner uses. No second pane implementation and no engine launched as the owner.+ *+ * The signed pty writes its discovery token and pipe with the owner's SID too (`HARNESS_PTY_SHARE_SID`, set by the guest+ * host task), so this process can read the token and connect. The host and every pane it makes run as the guest.+ */+import { readdirSync } from 'node:fs'+import { join } from 'node:path'+import { runGuestCommand, type GuestRunner } from '../guestAccounts.js'+import { guestHostHome } from './guestRequests.js'+import { PtyHostBackend } from '../ptyHostBackend.js'+import { discoveredHostDead, reachPtyHost, readInstanceDiscovery, type HostLiveness } from '../ptyHost/launch.js'+import type { PtyHostDiscovery } from '../ptyHost/client.js'++export { guestHostHome }+export const guestHostTask = (user: string): string => `\\Harness\\Guests\\${user}`++export interface GuestHostBackendOptions {+ user: string+ home?: string+ /** Starts the guest host task; a seam for tests. */+ startTask?: (task: string) => Promise<void>+ waitMs?: number+ pollMs?: number+ sleep?: (ms: number) => Promise<void>+ now?: () => number+ /** The files in the host home's `run` folder; a seam for tests. */+ list?: (directory: string) => string[]+ runner?: GuestRunner+ /** Whether a discovery file's host still runs; its pid alone (`ptyHost/launch.ts`). A seam for tests. */+ liveness?: HostLiveness+}++const DISCOVERY = /^pty-host-(.+)\.json$/++/** The newest discovery file the guest host published, or null within the window. */+export async function waitForGuestHost(home: string, options: GuestHostBackendOptions): Promise<PtyHostDiscovery | null> {+ const waitMs = options.waitMs ?? 15_000+ const pollMs = options.pollMs ?? 250+ const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const now = options.now ?? Date.now+ const list = options.list ?? ((directory: string) => {+ try { return readdirSync(directory) } catch { return [] }+ })+ const deadline = now() + waitMs+ for (;;) {+ const found: PtyHostDiscovery[] = []+ for (const name of list(join(home, 'run'))) {+ const match = DISCOVERY.exec(name)+ if (!match) continue+ const discovery = readInstanceDiscovery(home, match[1]!)+ // A host that exited leaves its discovery file behind (an update stops one, the next starts another): never+ // dialled, or the launch would wait on a file whose host is gone.+ if (discovery && !await discoveredHostDead(home, discovery, options.liveness)) found.push(discovery)+ }+ if (found.length) {+ found.sort((a, b) => a.protocol - b.protocol || a.version.localeCompare(b.version) || a.instance.localeCompare(b.instance))+ return found.at(-1)!+ }+ if (now() >= deadline) return null+ await sleep(pollMs)+ }+}++/** A pty backend whose host home is the guest's and whose start is the guest's task, not a process this account spawns. */+export function createGuestHostBackend(options: GuestHostBackendOptions): PtyHostBackend {+ const home = options.home ?? guestHostHome(options.user)+ const startTask = options.startTask ?? (async (task: string) => {+ const result = await (options.runner ?? runGuestCommand)('schtasks.exe', ['/run', '/tn', task], { timeoutMs: 30_000 })+ if (result.code !== 0) throw new Error(result.stderr.trim() || `could not start ${task} (schtasks ${result.code})`)+ })+ return new PtyHostBackend({+ home,+ platform: 'win32',+ target: null,+ // A guest's host is not the daemon's own: its table validates its panes, and it never replaces the machine-wide+ // process table and signaller the owner's agents rely on.+ guestHost: true,+ launch: async (hostHome: string) => {+ try {+ await startTask(guestHostTask(options.user))+ } catch (error) {+ // A task that is gone (the guest was removed, or sharing is off) is an unavailable host, never a throw out of+ // a create: the person is told to turn sharing on again.+ return { unavailable: (error as Error).message || 'the guest host task could not be started', code: 'PTY_HOST_UNAVAILABLE' }+ }+ const discovery = await waitForGuestHost(hostHome, options)+ if (!discovery) return { unavailable: 'the guest host did not publish a discovery file', code: 'PTY_HOST_UNAVAILABLE' }+ return reachPtyHost(hostHome, discovery.instance)+ },+ })+}diff --git a/cli/src/lib/windows/guestRequests.spec.ts b/cli/src/lib/windows/guestRequests.spec.tsnew file mode 100644index 000000000..e55a5325d--- /dev/null+++ b/cli/src/lib/windows/guestRequests.spec.ts@@ -0,0 +1,94 @@+import { createHash } from 'node:crypto'+import { describe, expect, it } from 'vitest'+import {+ GUEST_REQUEST_MAX_BYTES, WINDOWS_GUEST_ROOT, GuestRequestError, canonicalGuestEmail, guestAnswerFile, guestHomeFor,+ guestRequestFile, guestWorkspaceFor, newGuestRequestId, parseGuestSetupAnswer, parseGuestSetupRequest,+} from './guestRequests.js'++const OWNER = 'C:\\Users\\owner'+const USER = `hg_${createHash('sha256').update('[email protected]').digest('hex').slice(0, 12)}`+const ID = 'a'.repeat(32)+const options = { ownerHome: OWNER }+const request = (value: Record<string, unknown>) => JSON.stringify({ id: ID, ...value })+const code = (fn: () => unknown): string => {+ try {+ fn()+ } catch (error) {+ if (error instanceof GuestRequestError) return error.code+ throw error+ }+ throw new Error('expected a GuestRequestError')+}++describe('the guest setup root', () => {+ it('is the guests\' own tree, never the Team account\'s readable ProgramData folder', () => {+ expect(WINDOWS_GUEST_ROOT).toBe('C:\\ProgramData\\HarnessGuests')+ expect(WINDOWS_GUEST_ROOT).not.toContain('ProgramData\\Harness\\')+ expect(guestRequestFile(ID)).toBe(`${WINDOWS_GUEST_ROOT}\\requests\\${ID}.json`)+ expect(guestAnswerFile(ID)).toBe(`${WINDOWS_GUEST_ROOT}\\answers\\${ID}.json`)+ })++ it('derives the same account as macOS and the exact profile and workspace Windows must make', () => {+ expect(canonicalGuestEmail(' [email protected] ')).toBe('[email protected]')+ expect(USER).toMatch(/^hg_[0-9a-f]{12}$/)+ expect(guestHomeFor(USER)).toBe(`C:\\Users\\${USER}`)+ expect(guestWorkspaceFor(USER)).toBe(`C:\\Users\\${USER}\\work`)+ expect(newGuestRequestId()).toMatch(/^[0-9a-f]{32}$/)+ })+})++describe('a setup request', () => {+ it('accepts ensure, remove, unshare and share, and derives a guest user for an email', () => {+ expect(parseGuestSetupRequest(request({ op: 'ensure', email: ' [email protected] ' }), options))+ .toEqual({ id: ID, op: 'ensure', email: '[email protected]', user: USER })+ expect(parseGuestSetupRequest(request({ op: 'remove', user: USER }), options)).toEqual({ id: ID, op: 'remove', user: USER })+ expect(parseGuestSetupRequest(request({ op: 'unshare', user: USER }), options)).toEqual({ id: ID, op: 'unshare', user: USER })+ expect(parseGuestSetupRequest(request({ op: 'share', user: USER, folders: [{ path: 'C:\\Users\\owner\\work', write: true }] }), options))+ .toEqual({ id: ID, op: 'share', user: USER, folders: [{ path: 'C:\\Users\\owner\\work', write: true }] })+ expect(parseGuestSetupRequest(request({ op: 'share', user: USER, folders: [] }), options))+ .toEqual({ id: ID, op: 'share', user: USER, folders: [] })+ })++ it('refuses an unknown key, a missing one, a bad id, op, email, user, path or level', () => {+ expect(code(() => parseGuestSetupRequest(request({ op: 'ensure', email: '[email protected]', extra: 1 }), options))).toBe('INVALID_REQUEST')+ expect(code(() => parseGuestSetupRequest(JSON.stringify({ id: ID, op: 'ensure' }), options))).toBe('INVALID_REQUEST')+ expect(code(() => parseGuestSetupRequest(JSON.stringify({ id: 'A'.repeat(32), op: 'ensure', email: '[email protected]' }), options))).toBe('INVALID_ID')+ expect(code(() => parseGuestSetupRequest(request({ op: 'root' }), options))).toBe('INVALID_REQUEST')+ for (const email of ['', 'a', 'a@', '@b.co', 'a [email protected]', 'a\[email protected]']) {+ expect(code(() => parseGuestSetupRequest(request({ op: 'ensure', email }), options)), email).toBe('INVALID_EMAIL')+ }+ expect(code(() => parseGuestSetupRequest(request({ op: 'remove', user: 'owner' }), options))).toBe('INVALID_USER')+ expect(code(() => parseGuestSetupRequest(request({ op: 'share', user: USER, folders: [{ path: 'C:\\Windows', write: false }] }), options))).toBe('INVALID_PATH')+ expect(code(() => parseGuestSetupRequest(request({ op: 'share', user: USER, folders: [{ path: 'C:\\work', write: 'yes' }] }), options))).toBe('INVALID_REQUEST')+ expect(code(() => parseGuestSetupRequest(request({ op: 'share', user: USER, folders: [{ path: 'C:\\Work\\A', write: false }, { path: 'c:\\work\\a', write: true }] }), options))).toBe('INVALID_REQUEST')+ })++ it('refuses bad JSON, a non-object, and a request over its size limit', () => {+ expect(code(() => parseGuestSetupRequest('{', options))).toBe('INVALID_JSON')+ expect(code(() => parseGuestSetupRequest('[]', options))).toBe('INVALID_REQUEST')+ expect(code(() => parseGuestSetupRequest('x'.repeat(GUEST_REQUEST_MAX_BYTES + 1), options))).toBe('TOO_LARGE')+ })+})++describe('the setup answer', () => {+ const ensure = parseGuestSetupRequest(request({ op: 'ensure', email: '[email protected]' }), options)+ const answer = (value: Record<string, unknown>) => JSON.stringify({ id: ID, ...value })++ it('accepts the account and its exact profile, and a refusal with a bounded plain detail', () => {+ expect(parseGuestSetupAnswer(answer({ ok: true, user: USER, home: guestHomeFor(USER), workspace: guestWorkspaceFor(USER) }), ensure))+ .toEqual({ id: ID, ok: true, user: USER, home: guestHomeFor(USER), workspace: guestWorkspaceFor(USER) })+ expect(parseGuestSetupAnswer(answer({ ok: false, detail: 'Windows would not make the profile.' }), ensure))+ .toEqual({ id: ID, ok: false, detail: 'Windows would not make the profile.' })+ expect(parseGuestSetupAnswer(answer({ ok: true, user: USER, home: guestHomeFor(USER), workspace: guestWorkspaceFor(USER), detail: 'Windows keeps the profile until restart.' }), ensure))+ .toEqual({ id: ID, ok: true, user: USER, home: guestHomeFor(USER), workspace: guestWorkspaceFor(USER), detail: 'Windows keeps the profile until restart.' })+ })++ it('refuses another request, another guest, another profile, bad fields, and detail with a control character', () => {+ expect(code(() => parseGuestSetupAnswer(answer({ id: 'b'.repeat(32), ok: false, detail: 'x' }), ensure))).toBe('INVALID_ID')+ expect(code(() => parseGuestSetupAnswer(answer({ ok: true, user: 'hg_ffffffffffff', home: guestHomeFor('hg_ffffffffffff'), workspace: guestWorkspaceFor('hg_ffffffffffff') }), ensure))).toBe('INVALID_USER')+ expect(code(() => parseGuestSetupAnswer(answer({ ok: true, user: USER, home: 'D:\\x', workspace: guestWorkspaceFor(USER) }), ensure))).toBe('INVALID_PATH')+ expect(code(() => parseGuestSetupAnswer(answer({ ok: true, user: USER, home: guestHomeFor(USER), workspace: guestWorkspaceFor(USER), extra: 1 }), ensure))).toBe('INVALID_REQUEST')+ expect(code(() => parseGuestSetupAnswer(answer({ ok: false, detail: 'bad\u0007detail' }), ensure))).toBe('INVALID_REQUEST')+ expect(code(() => parseGuestSetupAnswer(answer({ ok: 'yes' }), ensure))).toBe('INVALID_REQUEST')+ })+})diff --git a/cli/src/lib/windows/guestRequests.ts b/cli/src/lib/windows/guestRequests.tsnew file mode 100644index 000000000..a1d4f92d1--- /dev/null+++ b/cli/src/lib/windows/guestRequests.ts@@ -0,0 +1,228 @@+/**+ * The only thing the Windows guest setup task accepts (docs/superpowers/specs/2026-11-05-windows-guests-design.md,+ * "Setup: one UAC prompt"): one small JSON file naming one validated operation. The owner writes it; the SYSTEM task+ * reads it, does exactly that, writes one answer, and deletes it. Nothing on a command line, nothing a guest can write.+ *+ * The root is **not** under `C:\ProgramData\Harness`: that folder is readable by Users for the Team account (team.json,+ * its status and relay), and every guest is in Users. Keeping guests under it would let a guest read the owner's Team+ * subscription relay. `C:\ProgramData\HarnessGuests` is the guests' own tree: the owner and SYSTEM, the shared runtime+ * for guests to read, and nothing else.+ */+import { randomBytes } from 'node:crypto'+import { guestUserFor, isGuestUser } from '../guestAccounts.js'+import { GUEST_SHARE_MAX, checkGuestSharePath, type GuestSharedFolder } from './guestShare.js'++export const WINDOWS_GUEST_ROOT = 'C:\\ProgramData\\HarnessGuests'+export const WINDOWS_GUEST_REQUESTS = `${WINDOWS_GUEST_ROOT}\\requests`+export const WINDOWS_GUEST_ANSWERS = `${WINDOWS_GUEST_ROOT}\\answers`+export const WINDOWS_GUEST_RECORDS = `${WINDOWS_GUEST_ROOT}\\records`+export const WINDOWS_GUEST_SCRIPTS = `${WINDOWS_GUEST_ROOT}\\scripts`+export const WINDOWS_GUEST_RUNTIME = `${WINDOWS_GUEST_ROOT}\\runtime`+export const WINDOWS_GUEST_HOOK = `${WINDOWS_GUEST_ROOT}\\hook`+/** One home per guest host (`hosts\<user>`): its discovery file, logs and `host.cmd`. */+export const WINDOWS_GUEST_HOSTS = `${WINDOWS_GUEST_ROOT}\\hosts`+/** A guest's own host home (lib/windows/guestHostBackend.ts starts its task on it). */+export const guestHostHome = (user: string): string => `${WINDOWS_GUEST_HOSTS}\\${user}`+/** The format the installer/processor tree is in: an installed tree older than this is set up again. */+export const WINDOWS_GUEST_SETUP_VERSION = 3+/** Where the installer writes the version it put in place. */+export const WINDOWS_GUEST_VERSION_FILE = `${WINDOWS_GUEST_ROOT}\\version`++/** The macOS form's cap, and the same one the setup record enforces. */+export const GUEST_REQUEST_MAX_BYTES = 16_384+export const GUEST_ANSWER_DETAIL_MAX = 2_000++export const guestHomeFor = (user: string): string => `C:\\Users\\${user}`+export const guestWorkspaceFor = (user: string): string => `${guestHomeFor(user)}\\work`++export type GuestSetupOperation = 'ensure' | 'remove' | 'share' | 'unshare'++export interface GuestEnsureRequest {+ id: string+ op: 'ensure'+ email: string+ /** Derived from the email, the same name the macOS helper uses, so the platforms agree in tests. */+ user: string+}+export interface GuestAccountRequest { id: string; op: 'remove' | 'unshare'; user: string }+/** The owner's whole set, not one folder: the SYSTEM task changes only the difference from its record. */+export interface GuestShareRequest { id: string; op: 'share'; user: string; folders: GuestSharedFolder[] }+export type GuestSetupRequest = GuestEnsureRequest | GuestAccountRequest | GuestShareRequest++export type GuestRequestErrorCode =+ | 'INVALID_JSON'+ | 'INVALID_REQUEST'+ | 'TOO_LARGE'+ | 'INVALID_EMAIL'+ | 'INVALID_USER'+ | 'INVALID_PATH'+ | 'INVALID_ID'++export class GuestRequestError extends Error {+ constructor(readonly code: GuestRequestErrorCode, message: string) {+ super(message)+ this.name = 'GuestRequestError'+ }+}++const fail = (code: GuestRequestErrorCode, message: string): never => {+ throw new GuestRequestError(code, message)+}++const ID = /^[0-9a-f]{32}$/+/** One `@`, no spaces or controls, a local part of at most 64 and a domain of at most 253 characters. */+const EMAIL = /^[^\s@\u0000-\u001f]{1,64}@[^\s@\u0000-\u001f]{1,253}$/++/** A fresh request id: 128 random bits, the name nobody can guess and the SYSTEM task accepts once. */+export const newGuestRequestId = (): string => randomBytes(16).toString('hex')++export const guestRequestFile = (id: string): string => `${WINDOWS_GUEST_REQUESTS}\\${id}.json`+export const guestAnswerFile = (id: string): string => `${WINDOWS_GUEST_ANSWERS}\\${id}.json`++export function canonicalGuestEmail(email: string): string {+ const value = typeof email === 'string' ? email.trim().toLowerCase() : ''+ if (!EMAIL.test(value)) fail('INVALID_EMAIL', 'the email is not a plain address')+ return value+}++export interface ParseGuestRequestOptions {+ ownerHome: string+ fixedDrives?: ReadonlySet<string>+ isReparse?: (path: string) => boolean+}++function onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {+ const keys = Object.keys(value).sort()+ const want = [...allowed].sort()+ if (keys.length !== want.length || keys.some((key, i) => key !== want[i])) {+ fail('INVALID_REQUEST', `the request must name exactly ${allowed.join(', ')}`)+ }+}++/** Required keys and optional ones: no other key, every required one present. */+function keys(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): void {+ const allowed = new Set([...required, ...optional])+ if (Object.keys(value).some((key) => !allowed.has(key)) || required.some((key) => !(key in value))) {+ fail('INVALID_REQUEST', `the answer must name ${required.join(', ')}${optional.length ? ` (optionally ${optional.join(', ')})` : ''}`)+ }+}++function text(value: unknown, what: string, max = 400): string {+ if (typeof value !== 'string' || value.length === 0 || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) {+ throw new GuestRequestError('INVALID_REQUEST', `${what} must be plain text`)+ }+ return value+}++/**+ * One request from its JSON text. Every field is checked here and again by the SYSTEM script; an unknown key is a+ * refusal, not ignored, so a client that expects another operation to happen is told.+ */+export function parseGuestSetupRequest(source: string, options: ParseGuestRequestOptions): GuestSetupRequest {+ if (typeof source !== 'string') fail('INVALID_JSON', 'the request is not text')+ if (Buffer.byteLength(source, 'utf8') > GUEST_REQUEST_MAX_BYTES) fail('TOO_LARGE', 'the request is too large')+ let value: unknown+ try {+ value = JSON.parse(source)+ } catch {+ fail('INVALID_JSON', 'the request is not JSON')+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail('INVALID_REQUEST', 'the request must be an object')+ const request = value as Record<string, unknown>+ const id = typeof request.id === 'string' && ID.test(request.id) ? request.id : fail('INVALID_ID', 'the request id is not 128 random bits')+ const op = request.op+ if (op === 'ensure') {+ onlyKeys(request, ['id', 'op', 'email'])+ const email = canonicalGuestEmail(request.email as string)+ return { id, op, email, user: guestUserFor(email) }+ }+ if (op === 'remove' || op === 'unshare') {+ onlyKeys(request, ['id', 'op', 'user'])+ const user = text(request.user, 'user', 32)+ if (!isGuestUser(user)) fail('INVALID_USER', 'the user is not a guest account')+ return { id, op, user }+ }+ if (op === 'share') {+ onlyKeys(request, ['id', 'op', 'user', 'folders'])+ const user = text(request.user, 'user', 32)+ if (!isGuestUser(user)) fail('INVALID_USER', 'the user is not a guest account')+ if (!Array.isArray(request.folders) || request.folders.length > GUEST_SHARE_MAX) {+ return fail('INVALID_REQUEST', `folders must be an array of at most ${GUEST_SHARE_MAX}`)+ }+ const folders: GuestSharedFolder[] = []+ const seen = new Set<string>()+ for (const entry of request.folders) {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return fail('INVALID_REQUEST', 'each folder must be an object')+ const folder = entry as Record<string, unknown>+ onlyKeys(folder, ['path', 'write'])+ if (typeof folder.write !== 'boolean') return fail('INVALID_REQUEST', 'each folder needs write: true or false')+ const path = text(folder.path, 'path', 1_024)+ let checked: ReturnType<typeof checkGuestSharePath>+ try {+ checked = checkGuestSharePath(path, {+ ownerHome: options.ownerHome,+ ...(options.fixedDrives ? { fixedDrives: options.fixedDrives } : {}),+ ...(options.isReparse ? { isReparse: options.isReparse } : {}),+ })+ } catch (error) {+ throw new GuestRequestError('INVALID_PATH', error instanceof Error ? error.message : 'the folder cannot be shared')+ }+ const key = checked.path.toLowerCase()+ if (seen.has(key)) return fail('INVALID_REQUEST', `the folder ${checked.path} is named twice`)+ seen.add(key)+ folders.push({ path: checked.path, write: folder.write })+ }+ return { id, op, user, folders }+ }+ return fail('INVALID_REQUEST', 'op must be ensure, remove, share or unshare')+}++export type GuestSetupAnswer =+ | { id: string; ok: true; user: string; home: string; workspace: string; detail?: string }+ | { id: string; ok: false; detail: string }++function hasControl(text: string): boolean {+ return /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(text)+}++/**+ * The SYSTEM task's answer. An answer names the request it answers, and on success the account and its real profile+ * (Windows may suffix a profile folder; the setup reads `Win32_UserProfile.LocalPath`, not a guess). The caller+ * compares the user with the one it asked for, so an answer swapped in from another request is refused.+ */+export function parseGuestSetupAnswer(source: string, expected: GuestSetupRequest): GuestSetupAnswer {+ if (typeof source !== 'string' || Buffer.byteLength(source, 'utf8') > GUEST_REQUEST_MAX_BYTES) {+ fail('INVALID_JSON', 'the answer is not a small text')+ }+ let value: unknown+ try {+ value = JSON.parse(source)+ } catch {+ fail('INVALID_JSON', 'the answer is not JSON')+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail('INVALID_REQUEST', 'the answer must be an object')+ const answer = value as Record<string, unknown>+ if (answer.id !== expected.id) fail('INVALID_ID', 'the answer names another request')+ if (answer.ok === true) {+ keys(answer, ['id', 'ok', 'user', 'home', 'workspace'], ['detail'])+ const user = text(answer.user, 'user', 32)+ if (!isGuestUser(user)) fail('INVALID_USER', 'the answer names no guest account')+ if (user !== expected.user) fail('INVALID_USER', 'the answer names another guest account')+ const home = text(answer.home, 'home', 1_024)+ const workspace = text(answer.workspace, 'workspace', 1_024)+ const detail = answer.detail === undefined ? undefined : text(answer.detail, 'detail', GUEST_ANSWER_DETAIL_MAX)+ if (home !== guestHomeFor(user) || workspace !== guestWorkspaceFor(user)) {+ fail('INVALID_PATH', 'the answer\'s profile is not the guest\'s')+ }+ return { id: expected.id, ok: true, user, home, workspace, ...(detail ? { detail } : {}) }+ }+ if (answer.ok === false) {+ onlyKeys(answer, ['id', 'ok', 'detail'])+ const detail = typeof answer.detail === 'string' ? answer.detail.trim() : ''+ if (!detail || detail.length > GUEST_ANSWER_DETAIL_MAX || hasControl(detail)) {+ fail('INVALID_REQUEST', 'the answer has no usable detail')+ }+ return { id: expected.id, ok: false, detail }+ }+ return fail('INVALID_REQUEST', 'ok must be true or false')+}diff --git a/cli/src/lib/windows/guestScript.spec.ts b/cli/src/lib/windows/guestScript.spec.tsnew file mode 100644index 000000000..89e85fed7--- /dev/null+++ b/cli/src/lib/windows/guestScript.spec.ts@@ -0,0 +1,167 @@+import { describe, expect, it } from 'vitest'+import { buildWindowsGuestInstallScript, buildWindowsGuestProcessorScript } from './guestScript.js'++const SID = 'S-1-5-21-1111111111-2222222222-3333333333-1001'+const install = (over: Record<string, string> = {}) => buildWindowsGuestInstallScript({+ owner: 'owner', ownerHome: 'C:\\Users\\owner', ownerSid: SID, processor: 'Write-Output ok', version: '1.2.3', ...over,+})+const processor = (over: Record<string, string> = {}) => buildWindowsGuestProcessorScript({ owner: 'owner', ownerHome: 'C:\\Users\\owner', ownerSid: SID, ...over })++describe('the guest install script', () => {+ it('uses its own tree, never the Users-readable Team folder', () => {+ const script = install()+ expect(script).toContain("$ROOT = 'C:\\ProgramData\\HarnessGuests'")+ expect(script).not.toContain("$ROOT = 'C:\\ProgramData\\Harness\\guests'")+ expect(script).toContain('Harness Guests')+ })++ it('builds the guest/owner SIDs into the SDDL at run time, not as single-quoted literals', () => {+ const script = install()+ expect(script).toContain('Set-Folder $ROOT ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x20;;;" + $guestSid + ")(A;OICI;0x1200a9;;;" + $OWNER_SID + ")")')+ expect(script).not.toMatch(/Set-Folder \$ROOT 'O:/)+ })++ it('makes the setup task SYSTEM, on demand, one at a time, with the owner able to start it unelevated', () => {+ const script = install()+ expect(script).toContain('<RunLevel>HighestAvailable</RunLevel>')+ expect(script).toContain("RegisterTask($TASK_NAME, $taskXml, 6, 'SYSTEM', $null, 5, $sddl)")+ expect(script).toContain('<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>')+ expect(script).toContain('<AllowStartOnDemand>true</AllowStartOnDemand>')+ expect(script).toContain('(A;;FRFX;;;')+ expect(script).not.toContain('New-LocalGroup -Name $group')+ })++ it('writes the processor from base64 and a guest-readable probe, not through a here-string', () => {+ const script = install()+ expect(script).toContain('FromBase64String($processorB64)')+ expect(script).toContain("$probe = Join-Path $SCRIPTS 'probe.ps1'")+ expect(script).toContain("$probeText = \"try { [IO.File]::ReadAllText('$SENTINEL')")+ expect(script).not.toContain('$processorText = @\'')+ })++ it('stages the Node runtime guests install their engine with, and only once per setup version', () => {+ const script = install({ nodeSrc: 'C:\\Program Files\\nodejs' })+ expect(script).toContain("$NODE_SRC = 'C:\\Program Files\\nodejs'")+ expect(script).toContain("$NODEBIN = 'C:\\ProgramData\\HarnessGuests\\bin\\node-1.2.3'")+ expect(script).toContain('Copy-Item -LiteralPath $NODE_SRC -Destination $NODEBIN -Recurse -Force')+ // The marker says the copy finished; a partial copy is replaced rather than trusted.+ expect(script).toContain("$nodeMark = Join-Path $NODEBIN '.complete'")+ expect(script).toContain('if (Test-Path -LiteralPath $NODEBIN) { Remove-Item -LiteralPath $NODEBIN -Recurse -Force }')+ // Read/execute for guests is $BIN's, inherited by everything copied under it.+ expect(script).toContain('0x1200a9;;;" + $guestSid')+ // A build without one stages none: sharing still works for an already-installed engine.+ expect(install()).toContain("$NODE_SRC = ''")+ })++ it('rewrites the wrapper of every guest set up before this version, so none keeps the old host or PATH', () => {+ const script = install()+ expect(script).toContain("Get-ChildItem -LiteralPath $HOSTS -Directory -Filter 'hg_*'")+ expect(script).toContain("$wrapper = Join-Path $_.FullName 'host.cmd'")+ expect(script).toContain("$tag = 'gu' + $_.Name.Substring(3)")+ expect(script).toContain('[IO.File]::WriteAllText($wrapper, $text)')+ // Only when a host was staged: a build with no pty must never rewrite a working wrapper to name nothing.+ expect(script).toContain("if ($PTYBIN -and (Test-Path -LiteralPath (Join-Path $PTYBIN 'harness-pty.exe')))")+ })++ it('writes the version last, so a tree that failed to stage never reads as ready', () => {+ const script = install()+ const versionAt = script.indexOf('[IO.File]::WriteAllText($VERSION_FILE')+ const taskAt = script.indexOf('RegisterTask($TASK_NAME')+ expect(versionAt).toBeGreaterThan(taskAt)+ })++ it('stops every guest host before a re-run, and stages the new host beside the old one it must not overwrite', () => {+ const script = install()+ expect(script).toContain(`$PTYBIN = Join-Path $BIN ('pty-' + $VERSION)`)+ expect(script).toContain('Copy-Item -LiteralPath $PTY_SRC -Destination (Join-Path $PTYBIN "harness-pty.exe") -Force -ErrorAction Stop')+ expect(script).toContain('if (-not (Test-Path -LiteralPath (Join-Path $PTYBIN "harness-pty.exe")))')+ expect(script).toContain('Get-ScheduledTask -TaskPath $HOST_TASK_PATH -ErrorAction SilentlyContinue')+ expect(script).toContain('Stop-ScheduledTask -TaskName $_.TaskName')+ expect(script).toContain('/F /IM harness-pty.exe /FI ("USERNAME eq " + $env:COMPUTERNAME')+ })++ it('refuses a bad owner, SID or version', () => {+ expect(() => install({ owner: "o'brien" })).toThrow()+ expect(() => install({ ownerSid: 'owner' })).toThrow()+ expect(() => install({ version: '..' })).toThrow()+ })+})++describe('the guest processor', () => {+ it('names the owner and sentinel, and never has a read-only $home variable', () => {+ const text = processor()+ expect(text).toContain("$OWNER = 'owner'")+ expect(text).toContain("$SENTINEL = 'C:\\Users\\owner\\.harness-guest-privacy'")+ expect(text).not.toMatch(/\$home\b/)+ expect(text).toContain('$guestHome')+ })++ it('sets the batch logon right before running as the guest, and uses a guest-run probe', () => {+ const text = processor()+ expect(text).toContain('function Set-BatchLogon')+ expect(text.indexOf('Set-BatchLogon $sid $true')).toBeLessThan(text.indexOf('$code = Run-As $user $pw "exit 0"'))+ expect(text).toContain("$probe = Join-Path $ROOT 'scripts\\probe.ps1'")+ expect(text).toContain('if ($code -eq 0) { return $true }')+ expect(text).toContain('throw "the guest privacy probe did not run')+ })++ it('grants only the shared folder: Windows Bypass traverse checking needs no parent ACE', () => {+ const text = processor()+ expect(text).toContain('Bypass traverse checking')+ expect(text).not.toMatch(/foreach \(\$parent in @\(Ancestors/)+ expect(text).toContain('$desired[$key] = @{ path = $path; level = $level }')+ })++ it('uses the drive colon correctly and refuses ADS after it', () => {+ const text = processor()+ expect(text).toContain("$path.Substring(3) -match '[<>:\"|?*]'")+ expect(text).not.toContain("$path -match '[<>:\"|?*]'")+ })++ it('kills the guest with taskkill, not a WMI loop over every process', () => {+ const text = processor()+ expect(text).toContain('taskkill.exe')+ expect(text).not.toContain('Get-CimInstance Win32_Process | ForEach-Object')+ })++ it('checks the request shape before the privileged switch, and a missing user is not success', () => {+ const text = processor()+ expect(text).toContain('the ensure request is not valid')+ expect(text).toContain('the $op request is not valid')+ expect(text).toContain('the share request is not valid')+ expect(text).toContain('the guest account $user is not here')+ // The path policy refuses the profile-holding folder and every system root the daemon's own check refuses.+ expect(text).toContain('the folder that holds every profile cannot be shared')+ expect(text).toContain('"c:\\programdata"')+ expect(text).toContain('"c:\\recovery"')+ // A leftover folder from an earlier account of the same name would suffix the new profile; it is cleared first.+ expect(text).toContain('Windows still holds an earlier guest')+ expect(text).toContain('restart this PC, then share with them again')+ })++ it('gives the guest\'s host its own instance and the owner SID, and lets only the owner start it', () => {+ const text = processor()+ // The host runs the same binary as the owner's: the tag keeps its instance, and every route keyed by it, apart.+ expect(text).toContain('$instanceTag = "gu" + $user.Substring(3)')+ expect(text).toContain('set `"HARNESS_PTY_INSTANCE_TAG=$instanceTag`"')+ expect(text).toContain('set `"HARNESS_PTY_SHARE_SID=$OWNER_SID`"')+ // The guest's own npm prefix and the staged Node are on every pane's PATH: that is where its engine is installed.+ expect(text).toContain('set `"PATH=$hostHome\\engines;%USERPROFILE%\\.local;$NODEBIN;%PATH%`"')+ expect(text).toContain('serve --home `"$hostHome`"')+ // The host is the build staged for this setup version, never a file an older host still runs.+ expect(text).toContain('$PTY_BIN = \'C:\\ProgramData\\HarnessGuests\\bin\\pty-3\\harness-pty.exe\'')+ // Owner: start/stop only; the guest's task cannot be changed by the guest.+ expect(text).toContain('(A;;FRFX;;;" + $OWNER_SID + ")"')+ // A laptop on battery keeps the guest's host, and a start on battery is allowed (the schema defaults stop it).+ expect(text).toContain('<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>')+ expect(text).toContain('<Priority>4</Priority>')+ // A re-run stops the instance still running the old wrapper (old tag, old PATH) before registering the new one.+ expect(text).toContain('if ($running.State -eq 4) { $running.Stop() }')+ })++ it('refuses more than one request and removes the request when it answers', () => {+ const text = processor()+ expect(text).toContain("if ($files.Count -ne 1)")+ expect(text).toContain('finally { Remove-Item -LiteralPath $files[0].FullName')+ })+})diff --git a/cli/src/lib/windows/guestScript.ts b/cli/src/lib/windows/guestScript.tsnew file mode 100644index 000000000..e8b9a24ed--- /dev/null+++ b/cli/src/lib/windows/guestScript.ts@@ -0,0 +1,537 @@+/**+ * The two Windows scripts behind guest sharing (docs/superpowers/specs/2026-11-05-windows-guests-design.md):+ *+ * - the elevated installer, run once behind UAC, which makes the **Harness Guests** group, the guest tree+ * (`C:\ProgramData\HarnessGuests`, never under the Users-readable Team folder), the privacy sentinel and the+ * `\Harness\Harness Guests Setup` SYSTEM task;+ * - the processor that task runs, which accepts exactly one validated request file and performs one of+ * `ensure`, `share`, `unshare`, `remove`. It is the only code that creates an account, changes an ACL or deletes a+ * profile, and it never takes a command line from the owner or a guest.+ *+ * Values go in single-quoted (`ps`), assigned once. The processor reads its request as JSON at run time, so no value+ * from a person is ever interpolated into PowerShell source. Account passwords are made inside the processor and handed+ * only to Task Scheduler's COM call, as the Team setup does.+ */+import { ps } from '../../team/windowsScript.js'+import { WINDOWS_GUEST_ANSWERS, WINDOWS_GUEST_RECORDS, WINDOWS_GUEST_REQUESTS, WINDOWS_GUEST_ROOT,+ WINDOWS_GUEST_SCRIPTS, WINDOWS_GUEST_SETUP_VERSION, WINDOWS_GUEST_VERSION_FILE } from './guestRequests.js'+import { WINDOWS_GUEST_TASK, WINDOWS_GUEST_TASK_NAME, WINDOWS_GUEST_TASK_PATH } from './guestSetupClient.js'++export { WINDOWS_GUEST_SETUP_VERSION, WINDOWS_GUEST_VERSION_FILE }++export const WINDOWS_GUEST_GROUP = 'Harness Guests'+export const WINDOWS_GUEST_SENTINEL = '.harness-guest-privacy'++/** The guest tree, as SDDL: SYSTEM/Administrators full; guests read/execute only where a harness needs it. */+export const GUEST_SDDL = {+ root: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x20;;;$guestSid)(A;OICI;0x1200a9;;;$OWNER_SID)"',+ requests: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;$OWNER_SID)"',+ answers: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;$OWNER_SID)"',+ records: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;$OWNER_SID)"',+ runtime: '"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;$OWNER_SID)(A;OICI;0x1200a9;;;$guestSid)"',+} as const++const PRELUDE = [+ "$ErrorActionPreference = 'Stop'",+ "$ProgressPreference = 'SilentlyContinue'",+ '[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)',+ 'function say([string]$m) { [Console]::Out.Write("harness: $m`n") }',+ 'function die([string]$m, [int]$code = 1) { [Console]::Error.Write("harness: $m`n"); exit $code }',+ 'trap { die ($_.Exception.Message + " at " + $_.InvocationInfo.PositionMessage) 1 }',+ "$ADMINS = 'S-1-5-32-544'",+ "$USERS = 'S-1-5-32-545'",+ "$SYSTEM_SID = 'S-1-5-18'",+ "$ICACLS = Join-Path $env:SystemRoot 'System32\\icacls.exe'",+ "$POWERSHELL = Join-Path $env:SystemRoot 'System32\\WindowsPowerShell\\v1.0\\powershell.exe'",+ "$CMD = Join-Path $env:SystemRoot 'System32\\cmd.exe'",+ '$REPARSE = [IO.FileAttributes]::ReparsePoint',+ 'function Owner-Of([string]$path) { (Get-Acl -LiteralPath $path).GetOwner([Security.Principal.SecurityIdentifier]).Value }',+ 'function Item-At([string]$path) { Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue }',+ 'function Set-Folder([string]$path, [string]$sddl) {',+ ' $item = Item-At $path',+ ' if ($item) {',+ ' if (-not $item.PSIsContainer -or ($item.Attributes -band $REPARSE)) { die "$path is not a plain folder" 6 }',+ ' $owner = Owner-Of $path',+ ' if ($owner -ne $ADMINS -and $owner -ne $SYSTEM_SID) { die "$path does not belong to Administrators" 6 }',+ ' } else {',+ ' $made = New-Object Security.AccessControl.DirectorySecurity',+ ' $made.SetSecurityDescriptorSddlForm($sddl)',+ ' [void][IO.Directory]::CreateDirectory($path, $made)',+ ' }',+ ' $acl = New-Object Security.AccessControl.DirectorySecurity',+ " $acl.SetSecurityDescriptorSddlForm($sddl, 'Access')",+ ' (Item-At $path).SetAccessControl($acl)',+ '}',+ "if ($env:OS -ne 'Windows_NT') { die 'guest sharing is for Windows' 3 }",+ 'if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {',+ " die 'run as an administrator (User Account Control)' 3",+ '}',+ "if ($env:ProgramData -ne 'C:\\ProgramData') { die \"guest sharing needs C:\\ProgramData (this computer's is $env:ProgramData)\" 3 }",+]++export interface WindowsGuestInstallInput {+ owner: string+ ownerHome: string+ ownerSid: string+ /** The processor text, staged next to the installer. */+ processor: string+ version: string+ /** The signed harness-pty.exe to stage for guests; null when this build has none. */+ ptySrc?: string | null+ /** The Node runtime's folder (node.exe and npm) to stage so a guest can install its engine; null when this build has none. */+ nodeSrc?: string | null+}++/**+ * One elevated run. It creates the group and the tree with their ACLs in one step, writes the processor and the version,+ * makes the owner's privacy sentinel if it is missing, and registers the SYSTEM task with a security descriptor that+ * lets the owner start it **without elevation** and gives every signed-in account only read access. It never creates a+ * guest account: that is the processor's job, one request at a time.+ */+export function buildWindowsGuestInstallScript(input: WindowsGuestInstallInput): string {+ if (!/^[A-Za-z0-9_.-]{1,20}$/.test(input.owner)) throw new Error('not an owner account')+ if (!/^S-1-\d+(-\d+)+$/.test(input.ownerSid)) throw new Error('not an owner SID')+ if (!/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(input.version) || input.version === '.' || input.version === '..') throw new Error('not a version')+ return [+ '# Harness guest sharing install (cli/src/lib/windows/guestScript.ts), run once elevated behind User Account Control.',+ '# Running it again repairs the group, tree, sentinel and task; it never removes a guest.',+ ...PRELUDE,+ `$OWNER = ${ps(input.owner)}`,+ `$OWNER_HOME = ${ps(input.ownerHome)}`,+ `$OWNER_SID = ${ps(input.ownerSid)}`,+ `$GROUP = ${ps(WINDOWS_GUEST_GROUP)}`,+ `$ROOT = ${ps(WINDOWS_GUEST_ROOT)}`,+ `$REQ = ${ps(WINDOWS_GUEST_REQUESTS)}`,+ `$ANS = ${ps(WINDOWS_GUEST_ANSWERS)}`,+ `$REC = ${ps(WINDOWS_GUEST_RECORDS)}`,+ `$SCRIPTS = ${ps(WINDOWS_GUEST_SCRIPTS)}`,+ `$BIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin`)}`,+ `$HOSTS = ${ps(`${WINDOWS_GUEST_ROOT}\\hosts`)}`,+ `$PTY_SRC = ${ps(input.ptySrc ?? '')}`,+ `$NODE_SRC = ${ps(input.nodeSrc ?? '')}`,+ `$VERSION_FILE = ${ps(WINDOWS_GUEST_VERSION_FILE)}`,+ `$TASK_PATH = ${ps(WINDOWS_GUEST_TASK_PATH)}`,+ `$HOST_TASK_PATH = ${ps('\\Harness\\Guests\\')}`,+ `$TASK_NAME = ${ps(WINDOWS_GUEST_TASK_NAME)}`,+ `$TASK = ${ps(WINDOWS_GUEST_TASK)}`,+ `$SENTINEL = ${ps(`${input.ownerHome}\\${WINDOWS_GUEST_SENTINEL}`)}`,+ `$PROCESSOR = ${ps(`${WINDOWS_GUEST_SCRIPTS}\\process.ps1`)}`,+ `$VERSION = ${ps(input.version)}`,+ // The staged runtime's folder, named for the setup version the installer wrote: the daemon computes the same one+ // (lib/windows/guestEngine.ts `guestNodeDir`).+ `$NODEBIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin\\node-${input.version}`)}`,+ '',+ '# 1. The group. Guests join it; it is never Administrators.',+ '$existingGroup = Get-LocalGroup -Name $GROUP -ErrorAction SilentlyContinue',+ 'if (-not $existingGroup) { New-LocalGroup -Name $GROUP -Description "People this computer is shared with" | Out-Null }',+ '$guestSid = (Get-LocalGroup -Name $GROUP).SID.Value',+ 'say "the group $GROUP is $guestSid"',+ '',+ '# 2. The tree. Its own root, never under C:\\ProgramData\\Harness: that folder is Users-readable for the Team account.',+ // SDDL must be built at run time: a single-quoted string would pass "$guestSid" to the ACL parser literally.+ 'Set-Folder $ROOT ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;;0x20;;;" + $guestSid + ")(A;OICI;0x1200a9;;;" + $OWNER_SID + ")")',+ 'Set-Folder $REQ ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;" + $OWNER_SID + ")")',+ 'Set-Folder $ANS ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1301bf;;;" + $OWNER_SID + ")")',+ 'Set-Folder $REC ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")")',+ // The hosts root is listable by guests, as the macOS guests' home root is: npm stats its way up from a guest's own+ // engines folder (`hosts\<user>\engines`), and a list of `hg_<hex>` names is all it may see — each home inside keeps+ // its own guest-only ACL (`Set-GuestHost`).+ 'Set-Folder $HOSTS ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")(A;OICI;0x1200a9;;;" + $guestSid + ")")',+ 'Set-Folder $SCRIPTS ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")(A;OICI;0x1200a9;;;" + $guestSid + ")")',+ '',+ '# 3. The processor. Base64, so no here-string inside the processor can end this script\'s. Written new, then renamed.',+ `$next = $PROCESSOR + '.next-' + [guid]::NewGuid().ToString('N')`,+ `$processorB64 = ${ps(Buffer.from(input.processor, 'utf8').toString('base64'))}`,+ '[IO.File]::WriteAllText($next, [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($processorB64)))',+ 'Move-Item -LiteralPath $next -Destination $PROCESSOR -Force',+ // The guest runs this file, not a quoted -Command: cmd.exe was mangling braces and quotes, and a parse error+ // looked exactly like "the guest read the sentinel".+ "$probe = Join-Path $SCRIPTS 'probe.ps1'",+ "$probeNext = $probe + '.next-' + [guid]::NewGuid().ToString('N')",+ `$probeText = "try { [IO.File]::ReadAllText('$SENTINEL') | Out-Null; exit 9 } catch { exit 0 }"`,+ '[IO.File]::WriteAllText($probeNext, $probeText)',+ 'Move-Item -LiteralPath $probeNext -Destination $probe -Force',+ "if ($PTY_SRC) {",+ " Set-Folder $BIN (\"O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;\" + $OWNER_SID + \")(A;OICI;0x1200a9;;;\" + $guestSid + \")\")",+ // A setup re-run after an update stages the new host beside the old one (a running host keeps its file open) and+ // ends every guest's host first, so the next harness starts the new build. A version already staged and in use is+ // the same file: it stays (a re-run of one version never replaces a running binary with itself).+ ` $PTYBIN = Join-Path $BIN ('pty-' + $VERSION)`,+ ' Set-Folder $PTYBIN ("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;" + $OWNER_SID + ")(A;OICI;0x1200a9;;;" + $guestSid + ")")',+ ' Get-ScheduledTask -TaskPath $HOST_TASK_PATH -ErrorAction SilentlyContinue | ForEach-Object { try { Stop-ScheduledTask -TaskName $_.TaskName -TaskPath $_.TaskPath -ErrorAction Stop } catch {} }',+ ' Get-LocalUser | Where-Object { $_.Name -like \'hg_*\' } | ForEach-Object {',+ ' & (Join-Path $env:SystemRoot "System32\\taskkill.exe") /F /IM harness-pty.exe /FI ("USERNAME eq " + $env:COMPUTERNAME + "\\" + $_.Name) 2>$null | Out-Null',+ ' }',+ ' try { Copy-Item -LiteralPath $PTY_SRC -Destination (Join-Path $PTYBIN "harness-pty.exe") -Force -ErrorAction Stop }',+ ' catch { if (-not (Test-Path -LiteralPath (Join-Path $PTYBIN "harness-pty.exe"))) { die "the terminal host could not be staged: $($_.Exception.Message)" 9 } }',+ '}',+ // The Node runtime guests' engines are installed with (node.exe beside npm), in a folder named for this setup version+ // so a host running from an older one is never overwritten under it. The marker says the copy finished; a copy that+ // stopped part-way is made again. It inherits $BIN's guest read/execute.+ "if ($NODE_SRC) {",+ " $nodeMark = Join-Path $NODEBIN '.complete'",+ " if (-not (Test-Path -LiteralPath $nodeMark)) {",+ " if (Test-Path -LiteralPath $NODEBIN) { Remove-Item -LiteralPath $NODEBIN -Recurse -Force }",+ " try { Copy-Item -LiteralPath $NODE_SRC -Destination $NODEBIN -Recurse -Force } catch { die \"could not stage the Node runtime for guests: $($_.Exception.Message)\" 7 }",+ " [IO.File]::WriteAllText($nodeMark, \"ok`r`n\")",+ ' }',+ '}',+ // Guests that were here before this setup version: their task still runs the wrapper written for the old host and+ // Node. The task path and its password do not change, and their hosts were stopped above, so the wrapper is rewritten+ // in place with this version's binary and PATH. Only when a host was staged: a build with no pty (a dev bundle) must+ // never rewrite a working wrapper to name nothing.+ "if ($PTYBIN -and (Test-Path -LiteralPath (Join-Path $PTYBIN 'harness-pty.exe'))) {",+ " Get-ChildItem -LiteralPath $HOSTS -Directory -Filter 'hg_*' -ErrorAction SilentlyContinue | ForEach-Object {",+ " $wrapper = Join-Path $_.FullName 'host.cmd'",+ ' if (-not (Test-Path -LiteralPath $wrapper)) { return }',+ " $tag = 'gu' + $_.Name.Substring(3)",+ ' $text = "@echo off`r`nset `"HARNESS_PTY_SHARE_SID=$OWNER_SID`"`r`nset `"HARNESS_PTY_INSTANCE_TAG=$tag`"`r`nset `"PATH=$($_.FullName)\\engines;%USERPROFILE%\\.local;$NODEBIN;%PATH%`"`r`n`"$PTYBIN\\harness-pty.exe`" serve --home `"$($_.FullName)`"`r`n"',+ ' [IO.File]::WriteAllText($wrapper, $text)',+ ' }',+ '}',+ '',+ '# 4. The privacy sentinel: inherited ACL, owned by the owner, checked as a guest on every ensure.',+ '$old = Item-At $SENTINEL',+ 'if ($old) { if ($old.PSIsContainer -or ($old.Attributes -band $REPARSE)) { die "$SENTINEL is not a plain file" 6 } }',+ 'else {',+ ' $rights = [Security.AccessControl.FileSystemRights]::Write',+ ' $f = New-Object IO.FileStream($SENTINEL, [IO.FileMode]::CreateNew, $rights, [IO.FileShare]::None, 4096, [IO.FileOptions]::None)',+ ' try { $b = [Text.Encoding]::UTF8.GetBytes("Harness guest privacy check. A guest must not read this file.`r`n"); $f.Write($b, 0, $b.Length) } finally { $f.Dispose() }',+ '}',+ '',+ '# 5. The SYSTEM setup task. Its SD lets the owner start it unelevated (FRFX on the owner SID) and lets any signed-in',+ '# account read it; a guest has neither. It cannot run twice at once, and it has no trigger: only the owner starts it.',+ "$sddl = 'D:(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;' + $OWNER_SID + ')'",+ '$taskXml = @\'',+ '<?xml version="1.0" encoding="UTF-16"?>',+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',+ ' <RegistrationInfo><Description>Harness guest setup: one validated request at a time, as SYSTEM.</Description>',+ ' <SecurityDescriptor>D:(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;__OWNER_SID__)</SecurityDescriptor></RegistrationInfo>',+ ' <Principals><Principal id="Setup"><RunLevel>HighestAvailable</RunLevel></Principal></Principals>',+ ' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>',+ ' <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled>',+ ' <Hidden>true</Hidden><ExecutionTimeLimit>PT15M</ExecutionTimeLimit><Priority>4</Priority></Settings>',+ ' <Actions Context="Setup"><Exec><Command>__POWERSHELL__</Command>',+ ' <Arguments>-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "__PROCESSOR__"</Arguments></Exec></Actions>',+ '</Task>',+ "'@",+ '$taskXml = $taskXml.Replace("__OWNER_SID__", $OWNER_SID).Replace("__POWERSHELL__", $POWERSHELL).Replace("__PROCESSOR__", $PROCESSOR)',+ '$scheduler = New-Object -ComObject Schedule.Service',+ '$scheduler.Connect()',+ "$folderName = $TASK_PATH.Trim('\\')",+ "try { $folder = $scheduler.GetFolder(\"\\$folderName\") } catch { $folder = $scheduler.GetFolder('\\').CreateFolder($folderName) }",+ "try { [void]$folder.RegisterTask($TASK_NAME, $taskXml, 6, 'SYSTEM', $null, 5, $sddl) }",+ 'catch { die "Task Scheduler would not take the guest setup task ($($_.Exception.Message))" 8 }',+ // Last: a tree that failed to stage must read as "not set up", never as ready.+ '[IO.File]::WriteAllText($VERSION_FILE, "$VERSION`r`n")',+ 'say "the guest setup task $TASK runs as SYSTEM; $OWNER can start it without elevation"',+ 'exit 0',+ '',+ ].join('\n')+}++/** The processor's PowerShell. Kept as one function so its text can be tested without a Windows machine. */+export function buildWindowsGuestProcessorScript(input: { owner: string; ownerHome: string; ownerSid: string; version?: string }): string {+ if (!/^[A-Za-z0-9_.-]{1,20}$/.test(input.owner)) throw new Error('not an owner account')+ if (!input.ownerHome.startsWith('C:\\Users\\')) throw new Error('not an owner profile')+ if (!/^S-1-\d+(-\d+)+$/.test(input.ownerSid)) throw new Error('not an owner SID')+ const version = input.version ?? String(WINDOWS_GUEST_SETUP_VERSION)+ if (!/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/.test(version) || version === '.' || version === '..') throw new Error('not a version')+ return [+ '# Harness guest setup processor (cli/src/lib/windows/guestScript.ts), run by the SYSTEM task. No arguments: it',+ '# accepts exactly one request file, checks it, performs one operation, writes one answer and deletes the request.',+ ...PRELUDE,+ `$OWNER = ${ps(input.owner)}`,+ `$OWNER_HOME = ${ps(input.ownerHome)}`,+ `$OWNER_SID = ${ps(input.ownerSid)}`,+ `$BIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin`)}`,+ `$PTY_BIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin\\pty-${version}\\harness-pty.exe`)}`,+ `$NODEBIN = ${ps(`${WINDOWS_GUEST_ROOT}\\bin\\node-${version}`)}`,+ `$HOSTS = ${ps(`${WINDOWS_GUEST_ROOT}\\hosts`)}`,+ `$HOST_TASK_PATH = ${ps('\\Harness\\Guests\\')}`,+ `$SENTINEL = ${ps(`${input.ownerHome}\\${WINDOWS_GUEST_SENTINEL}`)}`,+ `$ROOT = ${ps(WINDOWS_GUEST_ROOT)}`,+ `$REQ = ${ps(WINDOWS_GUEST_REQUESTS)}`,+ `$ANS = ${ps(WINDOWS_GUEST_ANSWERS)}`,+ `$REC = ${ps(WINDOWS_GUEST_RECORDS)}`,+ `$GROUP = ${ps(WINDOWS_GUEST_GROUP)}`,+ "$MAX_FOLDERS = 20",+ "$REPARSE = [IO.FileAttributes]::ReparsePoint",+ 'function Answer($id, $ok, $detail, $user, $guestHome, $workspace) {',+ ' $body = [ordered]@{ id = $id; ok = [bool]$ok }',+ ' if ($ok) { $body.user = $user; $body.home = $guestHome; $body.workspace = $workspace; if ($detail) { $body.detail = $detail } } else { $body.detail = $detail }',+ ' $next = Join-Path $ANS ($id + ".next")',+ ' [IO.File]::WriteAllText($next, ($body | ConvertTo-Json -Compress))',+ ' Move-Item -LiteralPath $next -Destination (Join-Path $ANS ($id + ".json")) -Force',+ '}',+ 'function Refuse($id, [string]$detail) { Answer $id $false $detail $null $null $null; exit 0 }',+ 'function Guest-Sid([string]$user) { (Get-LocalUser -Name $user -ErrorAction Stop).SID.Value }',+ 'function Guest-Exists([string]$user) { [bool](Get-LocalUser -Name $user -ErrorAction SilentlyContinue) }',+ 'function Guest-Home([string]$user) { "C:\\Users\\$user" }',+ 'function Guest-Workspace([string]$user) { (Guest-Home $user) + "\\work" }',+ 'function Guest-Name([string]$email) {',+ ' $sha = [Security.Cryptography.SHA256]::Create()',+ ' try { $hex = -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($email)) | ForEach-Object { $_.ToString("x2") }) } finally { $sha.Dispose() }',+ ' return "hg_" + $hex.Substring(0, 12)',+ '}',+ 'function Check-Path([string]$path) {',+ ' if ($path -notmatch \'^[A-Za-z]:\\\\\' -or $path.Length -gt 259 -or $path.Substring(3) -match \'[<>:"|?*]\' -or $path -match \'\\\\$\') { throw "not a plain absolute Windows path" }',+ ' $full = [IO.Path]::GetFullPath($path)',+ ' if ($full -ne $path) { throw "not a normalized path: $path" }',+ ' $parts = $path.Substring(3).Split("\\")',+ ' if ($parts.Count -eq 0 -or ($parts | Where-Object { $_ -eq "" -or $_ -eq "." -or $_ -eq ".." -or $_ -match \'[. ]$\' -or $_ -match \'^(?i:con|prn|aux|nul|com[1-9]|lpt[1-9])(\\.|$)\' })) { throw "not a plain folder name" }',+ ' $lower = $path.ToLowerInvariant()',+ ' foreach ($root in @("c:\\windows", "c:\\program files", "c:\\program files (x86)", "c:\\programdata", "c:\\`$recycle.bin", "c:\\system volume information", "c:\\recovery", "c:\\boot", "c:\\perflogs")) {',+ ' if ($lower -eq $root -or $lower.StartsWith($root + "\\")) { throw "$path cannot be shared" }',+ ' }',+ ' if ($parts.Count -eq 1 -and $parts[0] -ieq "Users") { throw "the folder that holds every profile cannot be shared" }',+ ' if ($parts[0] -ieq "Users" -and $parts.Count -ge 2 -and $parts[1] -ine $OWNER -and $parts[1] -notin @("Public", "Default", "Default User", "All Users")) { throw "another user profile cannot be shared" }',+ ' $at = $path',+ ' while ($at -and $at.Length -gt 3) {',+ ' $item = Item-At $at',+ ' if ($item -and ($item.Attributes -band $REPARSE)) { throw "$at is a junction or another reparse point" }',+ ' $at = Split-Path -Parent $at',+ ' }',+ ' return $full',+ '}',+ 'function Ancestors([string]$path) {',+ ' $parts = $path.Substring(3).Split("\\")',+ ' $out = @()',+ ' for ($i = 1; $i -lt $parts.Count; $i++) { $out += ($path.Substring(0, 2) + "\\" + (($parts[0..($i - 1)]) -join "\\")) }',+ ' return $out',+ '}',+ 'function Ace([string]$level) { if ($level -eq "read") { "(OI)(CI)(RX)" } elseif ($level -eq "edit") { "(OI)(CI)M" } else { "(X)" } }',+ 'function Apply-Ace([string]$user, [string]$sid, [string]$path, [string]$level) {',+ ' & $ICACLS $path /grant:r ("*" + $sid + ":" + (Ace $level)) /L /q | Out-Null',+ ' if ($LASTEXITCODE -ne 0) { throw "icacls could not grant $level on $path" }',+ '}',+ 'function Remove-Ace([string]$sid, [string]$path) {',+ ' & $ICACLS $path /remove:g ("*" + $sid) /L /q | Out-Null',+ ' if ($LASTEXITCODE -ne 0) { throw "icacls could not remove access on $path" }',+ '}',+ 'function Record-Of([string]$user) {',+ ' $file = Join-Path $REC ($user + ".json")',+ ' if (-not (Test-Path -LiteralPath $file)) { return @() }',+ ' return @(Get-Content -LiteralPath $file -Raw | ConvertFrom-Json)',+ '}',+ 'function Save-Record([string]$user, $entries) {',+ ' $next = Join-Path $REC ($user + ".next")',+ ' [IO.File]::WriteAllText($next, (ConvertTo-Json -InputObject @($entries) -Compress))',+ ' Move-Item -LiteralPath $next -Destination (Join-Path $REC ($user + ".json")) -Force',+ '}',+ 'function Share([string]$user, $folders) {',+ ' $sid = Guest-Sid $user',+ ' if (-not $sid) { throw "the guest account $user is not here" }',+ ' if (@($folders).Count -gt $MAX_FOLDERS) { throw "at most $MAX_FOLDERS folders can be shared" }',+ ' $desired = [ordered]@{}',+ ' foreach ($folder in @($folders)) {',+ ' $path = Check-Path ([string]$folder.path)',+ ' if ($folder.write -isnot [bool]) { throw "a folder needs write true or false" }',+ ' $level = if ($folder.write) { "edit" } else { "read" }',+ ' $key = $path.ToLowerInvariant()',+ ' if ($desired.Contains($key)) { throw "the folder $path is named twice" }',+ ' $desired[$key] = @{ path = $path; level = $level }',+ ' }',+ '# Windows Bypass traverse checking: no parent ACE. Only the folder itself is granted.',+ ' $before = @{}',+ ' foreach ($entry in @(Record-Of $user)) { $before[[string]$entry.path.ToLowerInvariant()] = $entry }',+ ' $changed = $false',+ ' foreach ($key in $desired.Keys) {',+ ' $want = $desired[$key]',+ ' $had = $before[$key]',+ ' if (-not $had -or [string]$had.level -ne $want.level) { Apply-Ace $user $sid $want.path $want.level; $changed = $true }',+ ' }',+ ' foreach ($key in $before.Keys) { if (-not $desired.Contains($key)) { Remove-Ace $sid ([string]$before[$key].path); $changed = $true } }',+ ' Save-Record $user @($desired.Values)',+ ' return $changed',+ '}',+ '# The guest must be refused the owner\'s sentinel: exit 0 means refused, exit 9 means it read the file.',+ 'function Probe([string]$user, [string]$password) {',+ " $probe = Join-Path $ROOT 'scripts\\probe.ps1'",+ " $probeLine = 'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"' + $probe + '\"'",+ ' $code = Run-As $user $password $probeLine 1',+ ' if ($code -eq 0) { return $true }',+ ' if ($code -eq 9) { return $false }',+ ' throw "the guest privacy probe did not run (result $code)"',+ '}',+ 'function Run-As([string]$user, [string]$password, [string]$line, [int]$minutes) {',+ ' $scheduler = New-Object -ComObject Schedule.Service',+ ' $scheduler.Connect()',+ ' $arguments = [System.Security.SecurityElement]::Escape("/d /s /c `"$line`"")',+ ' $xml = @\'',+ '<?xml version="1.0" encoding="UTF-16"?>',+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',+ ' <Principals><Principal id="G"><LogonType>Password</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>',+ ' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><ExecutionTimeLimit>PT__MINUTES__M</ExecutionTimeLimit></Settings>',+ ' <Actions Context="G"><Exec><Command>cmd.exe</Command><Arguments>__ARGS__</Arguments></Exec></Actions>',+ '</Task>',+ "'@",+ ' $xml = $xml.Replace("__ARGS__", $arguments).Replace("__MINUTES__", [string]$minutes)',+ ' $name = "Harness guest probe " + [guid]::NewGuid().ToString("N")',+ ' $task = $scheduler.GetFolder("\\").RegisterTask($name, $xml, 6, $user, $password, 1)',+ ' try { [void]$task.Run($null); $deadline = (Get-Date).AddMinutes($minutes); do { Start-Sleep -Milliseconds 300 } while (($task.State -in @(2, 4) -or $task.LastTaskResult -eq 0x41301) -and (Get-Date) -lt $deadline); return [int]$task.LastTaskResult }',+ ' finally { $scheduler.GetFolder("\\").DeleteTask($name, 0) }',+ '}',+ '# Task Scheduler gives a password logon only when the right is granted; New-LocalUser does not grant it.',+ 'function Set-BatchLogon([string]$sid, [bool]$grant) {',+ ' $inf = Join-Path $env:TEMP ("harness-guest-rights-" + [guid]::NewGuid().ToString("N") + ".inf")',+ ' & (Join-Path $env:SystemRoot "System32\\secedit.exe") /export /areas USER_RIGHTS /cfg $inf /quiet | Out-Null',+ ' if ($LASTEXITCODE -ne 0) { throw "could not read the batch logon right" }',+ ' try {',+ ' $line = @(Get-Content -LiteralPath $inf | Where-Object { $_ -like "SeBatchLogonRight*" })',+ ' $listed = if ($line.Count) { @(($line[0] -split "=", 2)[1].Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } else { @() }',+ ' $now = @(foreach ($e in $listed) { if ($e.StartsWith("*")) { $e } else { try { "*" + (New-Object Security.Principal.NTAccount($e)).Translate([Security.Principal.SecurityIdentifier]).Value } catch { $e } } })',+ ' $entry = "*$sid"',+ ' if ($grant -eq ($now -contains $entry)) { return }',+ ' $next = @($now | Where-Object { $_ -ne $entry })',+ ' if ($grant) { $next += $entry }',+ ' $text = @\'',+ '[Unicode]',+ 'Unicode=yes',+ '[Version]',+ 'signature="$CHICAGO$"',+ 'Revision=1',+ '[Privilege Rights]',+ 'SeBatchLogonRight = __RIGHTS__',+ "'@",+ ' $text = $text.Replace("__RIGHTS__", ($next -join ","))',+ ' Set-Content -LiteralPath $inf -Encoding Unicode -Value $text',+ ' & (Join-Path $env:SystemRoot "System32\\secedit.exe") /configure /db (Join-Path $env:TEMP "harness-guest-rights.sdb") /cfg $inf /areas USER_RIGHTS /quiet | Out-Null',+ ' if ($LASTEXITCODE -ne 0) { throw "could not change the batch logon right" }',+ ' } finally { Remove-Item -LiteralPath $inf -Force -ErrorAction SilentlyContinue }',+ '}',+ '# The guest\'s own terminal host: it runs as the guest, its discovery token and pipe are shared with the owner\'s',+ '# SID only, and the owner starts/stops the task without elevation. No trigger: the owner\'s daemon starts it.',+ 'function Set-GuestHost([string]$user, [string]$pw, [string]$sid) {',+ ' if (-not (Test-Path -LiteralPath $PTY_BIN)) { throw "the terminal host is not staged; turn sharing on again" }',+ ' $hostHome = Join-Path $HOSTS $user',+ ' if (-not (Test-Path -LiteralPath $hostHome)) { [void][IO.Directory]::CreateDirectory($hostHome) }',+ ' & $ICACLS $hostHome /inheritance:r /grant:r ("*" + $sid + ":(OI)(CI)F") ("*" + $SYSTEM_SID + ":(OI)(CI)F") ("*" + $ADMINS + ":(OI)(CI)F") ("*" + $OWNER_SID + ":(OI)(CI)(RX)") /L /q | Out-Null',+ ' if ($LASTEXITCODE -ne 0) { throw "could not secure the guest host folder $hostHome" }',+ ' $wrapper = Join-Path $hostHome "host.cmd"',+ // The tag keeps this account\'s host instance (and every pane route keyed by it) apart from the owner\'s, which+ // runs the same binary: lib/../pty/src/instance.rs `INSTANCE_TAG_VAR`. `hg_<hex>` -> `gu<hex>`.+ ' $instanceTag = "gu" + $user.Substring(3)',+ ' $text = "@echo off`r`nset `"HARNESS_PTY_SHARE_SID=$OWNER_SID`"`r`nset `"HARNESS_PTY_INSTANCE_TAG=$instanceTag`"`r`nset `"PATH=$hostHome\\engines;%USERPROFILE%\\.local;$NODEBIN;%PATH%`"`r`n`"$PTY_BIN`" serve --home `"$hostHome`"`r`n"',+ ' [IO.File]::WriteAllText($wrapper, $text)',+ ' $line = "/d /s /c `"" + $wrapper + "`""',+ ' $arguments = [System.Security.SecurityElement]::Escape($line)',+ ' $xml = @\'',+ '<?xml version="1.0" encoding="UTF-16"?>',+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',+ ' <Principals><Principal id="Guest"><LogonType>Password</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>',+ // A laptop on battery must keep the guest's host, and a start on battery must be allowed: the defaults stop it.+ ' <Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><AllowStartOnDemand>true</AllowStartOnDemand><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><Enabled>true</Enabled><Hidden>true</Hidden><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><Priority>4</Priority></Settings>',+ ' <Actions Context="Guest"><Exec><Command>cmd.exe</Command><Arguments>__ARGS__</Arguments></Exec></Actions>',+ '</Task>',+ "'@",+ ' $xml = $xml.Replace("__ARGS__", $arguments)',+ ' $sddl = "D:(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;" + $OWNER_SID + ")"',+ ' $scheduler = New-Object -ComObject Schedule.Service',+ ' $scheduler.Connect()',+ " $folderName = $HOST_TASK_PATH.Trim('\\')",+ " try { $folder = $scheduler.GetFolder(\"\\$folderName\") } catch { $folder = $scheduler.GetFolder('\\').CreateFolder($folderName) }",+ // A setup re-run registers a new wrapper with a new instance tag and PATH: an instance still running would keep the+ // old one and never publish the tag the new daemon waits for, so it is stopped first (state 4 is Running).+ ' try { $running = $folder.GetTask($user); if ($running.State -eq 4) { $running.Stop() } } catch {}',+ ' [void]$folder.RegisterTask($user, $xml, 6, $user, $pw, 1, $sddl)',+ '}',+ 'function Ensure([string]$email, [string]$id) {',+ ' if ($email -notmatch \'^[^\\s@]{1,64}@[^\\s@]{1,253}$\') { Refuse $id "the email is not a plain address" }',+ ' $user = Guest-Name $email.ToLowerInvariant()',+ ' $guestHome = Guest-Home $user',+ ' $workspace = Guest-Workspace $user',+ ' $account = Get-LocalUser -Name $user -ErrorAction SilentlyContinue',+ ' if ($account) {',+ ' $profiles = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $account.SID.Value })',+ ' if ($profiles.Count -ne 1 -or $profiles[0].LocalPath -ne $guestHome) { Refuse $id "the account $user does not have the profile Windows must make" }',+ ' Answer $id $true $null $user $guestHome $workspace; return',+ ' }',+ ' $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"',+ ' $rng = [Security.Cryptography.RandomNumberGenerator]::Create()',+ ' try { $byte = New-Object byte[] 1; do { $chars = New-Object char[] 40; for ($i = 0; $i -lt 40;) { $rng.GetBytes($byte); if ($byte[0] -lt 248) { $chars[$i] = $alphabet[$byte[0] % 62]; $i++ } }; $pw = New-Object string (, $chars) } until ($pw -cmatch "[A-Z]" -and $pw -cmatch "[a-z]" -and $pw -match "[0-9]") } finally { $rng.Dispose() }',+ ' $sec = New-Object Security.SecureString; foreach ($c in $pw.ToCharArray()) { $sec.AppendChar($c) }; $sec.MakeReadOnly()',+ ' try { New-LocalUser -Name $user -FullName $user -Description "Harness guest (sharing)" -Password $sec -PasswordNeverExpires -AccountNeverExpires -UserMayNotChangePassword | Out-Null } catch { Refuse $id ("Windows would not make a local account: " + $_.Exception.Message) }',+ ' Add-LocalGroupMember -SID $USERS -Member $user',+ ' Add-LocalGroupMember -Group $GROUP -Member $user',+ ' $sid = Guest-Sid $user',+ ' $admin = @(Get-LocalGroupMember -SID $ADMINS | Where-Object { $_.SID.Value -eq $sid })',+ ' if ($admin.Count -ne 0) { Refuse $id "Windows put the guest in Administrators; sharing is off" }',+ ' New-Item -Path "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" -Force | Out-Null',+ ' New-ItemProperty -LiteralPath "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" -Name $user -Value 0 -PropertyType DWord -Force | Out-Null',+ ' Set-BatchLogon $sid $true',+ // A folder left by an earlier account of the same name makes Windows suffix the new profile (`…DESKTOP-0TFH0OJ.001`),+ // which is not the path a guest's harness may use. This account is new, so nothing in that folder is anyone's now;+ // refusing is only right when it cannot be removed (another process holds it).+ ' if (Test-Path -LiteralPath $guestHome) {',+ ' try { Remove-Item -LiteralPath $guestHome -Recurse -Force -ErrorAction Stop } catch { Refuse $id ("Windows still holds an earlier guest\'s profile at " + $guestHome + "; restart this PC, then share with them again (" + $_.Exception.Message + ")") }',+ ' }',+ ' foreach ($stale in @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $sid -and $_.LocalPath -ne $guestHome })) {',+ ' try { Remove-CimInstance -InputObject $stale -ErrorAction Stop } catch { Refuse $id ("Windows still holds an earlier guest\'s profile for " + $user + "; restart this PC, then share with them again (" + $_.Exception.Message + ")") }',+ ' }',+ ' $code = Run-As $user $pw "exit 0" 5',+ ' if ($code -ne 0) { Refuse $id ("Windows did not sign the guest in to make its profile (result " + $code + ")") }',+ ' $profiles = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $sid })',+ ' if ($profiles.Count -ne 1 -or $profiles[0].LocalPath -ne $guestHome) { Refuse $id "Windows did not make the guest profile at $guestHome" }',+ ' [void][IO.Directory]::CreateDirectory($workspace)',+ ' & $ICACLS $workspace /inheritance:r /grant:r ("*" + $sid + ":(OI)(CI)F") ("*" + $SYSTEM_SID + ":(OI)(CI)F") ("*" + $ADMINS + ":(OI)(CI)F") /L /q | Out-Null',+ ' if (-not (Probe $user $pw)) { Refuse $id "the guest can read the owner\'s privacy sentinel; sharing is off" }',+ ' Set-GuestHost $user $pw $sid',+ ' Answer $id $true $null $user $guestHome $workspace',+ '}',+ 'function Remove-Guest([string]$user, [string]$id) {',+ ' if (-not (Guest-Exists $user)) { Refuse $id "the guest account $user is not here" }',+ ' $sid = Guest-Sid $user',+ ' foreach ($entry in @(Record-Of $user)) { try { Remove-Ace $sid ([string]$entry.path) } catch { } }',+ ' Remove-Item -LiteralPath (Join-Path $REC ($user + ".json")) -Force -ErrorAction SilentlyContinue',+ // No per-process WMI: an owner-side loop over every process is what hung the PC during the spike. taskkill filters by+ // the account name in the kernel and stops the whole tree.+ ' & (Join-Path $env:SystemRoot "System32\\schtasks.exe") /end /tn ($HOST_TASK_PATH + $user) 2>$null | Out-Null',+ ' & (Join-Path $env:SystemRoot "System32\\schtasks.exe") /delete /tn ($HOST_TASK_PATH + $user) /f 2>$null | Out-Null',+ ' Remove-Item -LiteralPath (Join-Path $HOSTS $user) -Recurse -Force -ErrorAction SilentlyContinue',+ ' & (Join-Path $env:SystemRoot "System32\\taskkill.exe") /FI ("USERNAME eq " + $user) /F /T 2>$null | Out-Null',+ ' Set-BatchLogon $sid $false',+ ' $profiles = @(Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $sid })',+ ' $pending = $null',+ ' if ($profiles.Count -eq 1) {',+ ' try { Remove-CimInstance -InputObject $profiles[0] -ErrorAction Stop } catch { $pending = "Windows keeps the guest profile until the next restart: " + $_.Exception.Message }',+ ' }',+ // The account goes even when Windows holds its profile: no SID means no access, and the restart releases the files.+ ' try { Remove-LocalUser -Name $user -ErrorAction Stop } catch { Refuse $id ("Windows would not delete the guest account: " + $_.Exception.Message) }',+ ' try { Remove-LocalGroupMember -Group $GROUP -Member $user -ErrorAction SilentlyContinue } catch { }',+ ' Remove-ItemProperty -LiteralPath "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList" -Name $user -ErrorAction SilentlyContinue',+ ' Remove-Item -LiteralPath (Join-Path $REC ($user + ".json")) -Force -ErrorAction SilentlyContinue',+ ' if ($pending) { Answer $id $true $pending $user (Guest-Home $user) (Guest-Workspace $user) } else { Answer $id $true $null $user (Guest-Home $user) (Guest-Workspace $user) }',+ '}',+ '',+ '# Exactly one request. Two at once is a client bug, not something to guess between.',+ '$files = @(Get-ChildItem -LiteralPath $REQ -Filter "*.json" -File)',+ 'if ($files.Count -eq 0) { exit 0 }',+ 'if ($files.Count -ne 1) { die "more than one guest setup request is waiting" 4 }',+ '$request = Get-Content -LiteralPath $files[0].FullName -Raw | ConvertFrom-Json',+ '$id = [string]$request.id',+ 'if ($id -notmatch \'^[0-9a-f]{32}$\') { Remove-Item -LiteralPath $files[0].FullName -Force; exit 4 }',+ // The SYSTEM task is the privileged side: never trust the JSON shape. Mirror parseGuestSetupRequest.ts.+ '$names = @($request.PSObject.Properties.Name | Sort-Object)',+ '$op = [string]$request.op',+ '$guest = \'^hg_[0-9a-f]{12}$\'',+ 'if ($op -eq "ensure") {',+ ' if (($names -join ",") -ne "email,id,op" -or [string]$request.email -notmatch \'^[^\\s@]{1,64}@[^\\s@]{1,253}$\') { Refuse $id "the ensure request is not valid" }',+ '} elseif ($op -in @("remove", "unshare")) {',+ ' if (($names -join ",") -ne "id,op,user" -or [string]$request.user -notmatch $guest) { Refuse $id "the $op request is not valid" }',+ '} elseif ($op -eq "share") {',+ ' if (($names -join ",") -ne "folders,id,op,user" -or [string]$request.user -notmatch $guest -or @($request.folders).Count -gt $MAX_FOLDERS) { Refuse $id "the share request is not valid" }',+ '} else { Refuse $id "the request names no operation" }',+ 'try {',+ ' switch ([string]$request.op) {',+ ' "ensure" { Ensure ([string]$request.email).ToLowerInvariant().Trim() $id }',+ ' "remove" { Remove-Guest ([string]$request.user) $id }',+ ' "share" { $changed = Share ([string]$request.user) @($request.folders); Answer $id $true $null ([string]$request.user) (Guest-Home ([string]$request.user)) (Guest-Workspace ([string]$request.user)) }',+ ' "unshare" { $changed = Share ([string]$request.user) @(); Answer $id $true $null ([string]$request.user) (Guest-Home ([string]$request.user)) (Guest-Workspace ([string]$request.user)) }',+ ' default { Refuse $id "the request names no operation" }',+ ' }',+ '} catch { Refuse $id $_.Exception.Message } finally { Remove-Item -LiteralPath $files[0].FullName -Force -ErrorAction SilentlyContinue }',+ 'exit 0',+ '',+ ].join('\n')+}diff --git a/cli/src/lib/windows/guestSetupClient.spec.ts b/cli/src/lib/windows/guestSetupClient.spec.tsnew file mode 100644index 000000000..37a426496--- /dev/null+++ b/cli/src/lib/windows/guestSetupClient.spec.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from 'vitest'+import { guestUserFor } from '../guestAccounts.js'+import {+ GuestSetupError, WINDOWS_GUEST_TASK, createGuestSetupClient, type GuestSetupFs,+} from './guestSetupClient.js'+import { guestAnswerFile, guestRequestFile } from './guestRequests.js'++const OWNER = 'C:\\Users\\owner'+const EMAIL = '[email protected]'+const USER = guestUserFor(EMAIL)++class MemFs implements GuestSetupFs {+ files = new Map<string, string>()+ dirs = new Set<string>()+ renames: Array<[string, string]> = []+ mkdir(path: string) { this.dirs.add(path) }+ write(path: string, text: string) {+ if (this.files.has(path)) throw new Error(`already there: ${path}`)+ this.files.set(path, text)+ }+ rename(from: string, to: string) {+ const text = this.files.get(from)+ if (text === undefined) throw new Error(`no file: ${from}`)+ this.files.delete(from)+ this.files.set(to, text)+ this.renames.push([from, to])+ }+ read(path: string) {+ const text = this.files.get(path)+ if (text === undefined) throw new Error(`no file: ${path}`)+ return text+ }+ exists(path: string) { return this.files.has(path) }+ unlink(path: string) { this.files.delete(path) }+}++const answer = (request: Record<string, unknown>, over: Record<string, unknown> = {}) => {+ const user = typeof request.user === 'string' ? request.user : guestUserFor(String(request.email))+ return JSON.stringify({ id: request.id, ok: true, user, home: `C:\\Users\\${user}`, workspace: `C:\\Users\\${user}\\work`, ...over })+}++/** A setup task stand-in that answers the request it finds, as the SYSTEM script would. */+function setup(fs: MemFs, respond: (request: Record<string, unknown>) => string | null = (r) => answer(r)) {+ let runs = 0+ const startTask = async () => {+ runs+++ const request = [...fs.files.keys()].find((path) => path.startsWith('C:\\ProgramData\\HarnessGuests\\requests\\') && path.endsWith('.json'))+ if (!request) throw new Error('no request')+ const body = JSON.parse(fs.read(request)) as Record<string, unknown>+ const response = respond(body)+ if (response !== null) fs.write(guestAnswerFile(String(body.id)), response)+ }+ return { startTask, runs: () => runs }+}++const client = (fs: MemFs, startTask: () => Promise<void>, over: Record<string, unknown> = {}) => {+ let clock = 0+ return createGuestSetupClient({+ ownerHome: OWNER, fs, startTask, timeoutMs: 1_000, pollMs: 100,+ sleep: async (ms) => { clock += ms }, now: () => clock, ...over,+ })+}++describe('the guest setup client', () => {+ it('writes one atomic request, starts the task, reads and deletes the answer, and caches one ensure per email', async () => {+ const fs = new MemFs()+ const task = setup(fs)+ const setupClient = client(fs, task.startTask)+ const [a, b] = await Promise.all([setupClient.ensureGuest(' [email protected] '), setupClient.ensureGuest(EMAIL)])+ expect(a).toEqual({ user: USER, home: `C:\\Users\\${USER}`, workspace: `C:\\Users\\${USER}\\work` })+ expect(b).toEqual(a)+ expect(task.runs()).toBe(1)+ expect(fs.renames).toHaveLength(1)+ expect([...fs.files.keys()].some((path) => path.endsWith('.tmp'))).toBe(false)+ expect([...fs.files.keys()].some((path) => path.includes('\\requests\\') || path.includes('\\answers\\'))).toBe(false)+ })++ it('sends the owner\'s whole folder set, read and edit, in one request', async () => {+ const fs = new MemFs()+ let seen: unknown+ const task = setup(fs, (request) => { seen = request.folders; return answer(request) })+ await client(fs, task.startTask).setFolders(USER, [{ path: 'C:\\Users\\owner\\work', write: true }, { path: 'D:\\docs', write: false }])+ expect(seen).toEqual([{ path: 'C:\\Users\\owner\\work', write: true }, { path: 'D:\\docs', write: false }])+ })++ it('starts again after a failed ensure: a failure is not cached', async () => {+ const fs = new MemFs()+ let first = true+ const task = setup(fs, (request) => {+ if (!first) return answer(request)+ first = false+ return JSON.stringify({ id: request.id, ok: false, detail: 'Windows would not make the profile.' })+ })+ const setupClient = client(fs, task.startTask)+ await expect(setupClient.ensureGuest(EMAIL)).rejects.toMatchObject({ code: 'REQUEST_FAILED', message: 'Windows would not make the profile.' })+ await expect(setupClient.ensureGuest(EMAIL)).resolves.toMatchObject({ user: USER })+ expect(task.runs()).toBe(2)+ })++ it('refuses an answer for another request, removes the request, and says so', async () => {+ const fs = new MemFs()+ const task = setup(fs, (request) => JSON.stringify({ id: 'b'.repeat(32), ok: false, detail: 'x' }))+ await expect(client(fs, task.startTask).ensureGuest(EMAIL)).rejects.toMatchObject({ code: 'INVALID_ANSWER' })+ expect([...fs.files.keys()].some((path) => path.includes('\\requests\\'))).toBe(false)+ })++ it('removes the request when the task cannot start or does not answer in time', async () => {+ const fs = new MemFs()+ const noTask = async () => { throw new GuestSetupError('TASK_FAILED', 'no task') }+ await expect(client(fs, noTask).ensureGuest(EMAIL)).rejects.toMatchObject({ code: 'TASK_FAILED' })+ expect([...fs.files.keys()].some((path) => path.includes('\\requests\\'))).toBe(false)++ const silent = async () => {}+ await expect(client(fs, silent).ensureGuest(EMAIL)).rejects.toMatchObject({ code: 'TIMEOUT' })+ expect([...fs.files.keys()].some((path) => path.includes('\\requests\\'))).toBe(false)+ })++ it('removes a guest and reports the task\'s refusal', async () => {+ const fs = new MemFs()+ const task = setup(fs, (request) => {+ if (request.op === 'remove') return JSON.stringify({ id: request.id, ok: false, detail: 'Windows still holds the profile.' })+ return answer(request)+ })+ await expect(client(fs, task.startTask).removeGuest(USER)).rejects.toMatchObject({ code: 'REQUEST_FAILED', message: 'Windows still holds the profile.' })+ })++ it('names the task the setup makes, at the Harness task folder', () => {+ expect(WINDOWS_GUEST_TASK).toBe('\\Harness\\Harness Guests Setup')+ expect(guestRequestFile('a'.repeat(32))).toContain('C:\\ProgramData\\HarnessGuests\\requests\\')+ expect(guestAnswerFile('a'.repeat(32))).toContain('C:\\ProgramData\\HarnessGuests\\answers\\')+ })+})diff --git a/cli/src/lib/windows/guestSetupClient.ts b/cli/src/lib/windows/guestSetupClient.tsnew file mode 100644index 000000000..621d73f5a--- /dev/null+++ b/cli/src/lib/windows/guestSetupClient.ts@@ -0,0 +1,179 @@+/**+ * The owner's side of the Windows guest setup task (docs/superpowers/specs/2026-11-05-windows-guests-design.md). One+ * request file with an unguessable id, the SYSTEM task started without elevation, one answer file, and the request+ * deleted. Requests are serialized: the task's `MultipleInstances=IgnoreNew` would otherwise leave the second request+ * unanswered while the first is still running.+ *+ * Nothing here trusts an answer by itself: the same [parseGuestSetupRequest] the task uses checks the request, and+ * [parseGuestSetupAnswer] checks the id, the guest's SID-derived name and the exact profile Windows was asked for.+ */+import { spawn } from 'node:child_process'+import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'+import { canonicalGuestEmail, guestAnswerFile, guestRequestFile, newGuestRequestId, parseGuestSetupAnswer,+ parseGuestSetupRequest, WINDOWS_GUEST_ANSWERS, WINDOWS_GUEST_REQUESTS, type GuestSetupRequest } from './guestRequests.js'+import type { GuestSharedFolder } from './guestShare.js'++export const WINDOWS_GUEST_TASK_PATH = '\\Harness\\'+export const WINDOWS_GUEST_TASK_NAME = 'Harness Guests Setup'+export const WINDOWS_GUEST_TASK = `${WINDOWS_GUEST_TASK_PATH}${WINDOWS_GUEST_TASK_NAME}`++export interface WindowsGuestAccount { user: string; home: string; workspace: string }++export interface GuestSetupFs {+ mkdir(path: string): void+ write(path: string, text: string): void+ rename(from: string, to: string): void+ read(path: string): string+ exists(path: string): boolean+ unlink(path: string): void+}++export interface GuestSetupClientOptions {+ ownerHome: string+ fs?: GuestSetupFs+ /** Starts `\Harness\Harness Guests Setup` as the owner; no elevation (its task SD grants the owner). */+ startTask?: () => Promise<void>+ timeoutMs?: number+ pollMs?: number+ sleep?: (ms: number) => Promise<void>+ now?: () => number+ fixedDrives?: ReadonlySet<string>+ isReparse?: (path: string) => boolean+}++export type GuestSetupErrorCode = 'REQUEST_FAILED' | 'TASK_FAILED' | 'TIMEOUT' | 'INVALID_ANSWER'++export class GuestSetupError extends Error {+ constructor(readonly code: GuestSetupErrorCode, message: string) {+ super(message)+ this.name = 'GuestSetupError'+ }+}++const realFs: GuestSetupFs = {+ mkdir: (path) => { mkdirSync(path, { recursive: true }) },+ write: (path, text) => { writeFileSync(path, text, { encoding: 'utf8', flag: 'wx' }) },+ rename: (from, to) => { renameSync(from, to) },+ read: (path) => readFileSync(path, 'utf8'),+ exists: (path) => existsSync(path),+ unlink: (path) => { try { unlinkSync(path) } catch { /* already gone */ } },+}++/** Starts the task through `schtasks.exe`; the caller's task security descriptor allows it unelevated. */+export function startGuestSetupTask(): Promise<void> {+ return new Promise((resolve, reject) => {+ const child = spawn('schtasks.exe', ['/run', '/tn', WINDOWS_GUEST_TASK], { stdio: 'ignore', windowsHide: true })+ child.on('error', (error) => reject(new GuestSetupError('TASK_FAILED', `Could not start the guest setup task: ${error.message}`)))+ child.on('close', (code) => code === 0+ ? resolve()+ : reject(new GuestSetupError('TASK_FAILED', `The guest setup task could not be started (schtasks exit ${code}).`)))+ })+}++export interface GuestSetupClient {+ ensureGuest(email: string): Promise<WindowsGuestAccount>+ /** The owner's whole folder set for this guest; an empty list removes every shared folder. */+ setFolders(user: string, folders: readonly GuestSharedFolder[]): Promise<void>+ removeGuest(user: string): Promise<void>+}++export function createGuestSetupClient(options: GuestSetupClientOptions): GuestSetupClient {+ const fs = options.fs ?? realFs+ const startTask = options.startTask ?? startGuestSetupTask+ const timeoutMs = options.timeoutMs ?? 180_000+ const pollMs = options.pollMs ?? 500+ const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const now = options.now ?? Date.now+ const parseOptions = {+ ownerHome: options.ownerHome,+ ...(options.fixedDrives ? { fixedDrives: options.fixedDrives } : {}),+ ...(options.isReparse ? { isReparse: options.isReparse } : {}),+ }+ const emails = new Map<string, Promise<WindowsGuestAccount>>()+ // One request at a time: a second start while the task runs is ignored by its `IgnoreNew` policy and never answered.+ let queue: Promise<unknown> = Promise.resolve()++ const send = (request: GuestSetupRequest, timeout: number): Promise<ReturnType<typeof parseGuestSetupAnswer>> => {+ const run = async () => {+ const requestFile = guestRequestFile(request.id)+ const answerFile = guestAnswerFile(request.id)+ const temporary = `${requestFile}.tmp`+ fs.mkdir(WINDOWS_GUEST_REQUESTS)+ fs.mkdir(WINDOWS_GUEST_ANSWERS)+ try {+ fs.write(temporary, `${JSON.stringify(request)}\n`)+ fs.rename(temporary, requestFile)+ } catch (error) {+ fs.unlink(temporary)+ throw new GuestSetupError('REQUEST_FAILED', `Could not write the guest setup request: ${error instanceof Error ? error.message : String(error)}`)+ }+ try {+ await startTask()+ } catch (error) {+ fs.unlink(requestFile)+ throw error instanceof GuestSetupError ? error+ : new GuestSetupError('TASK_FAILED', error instanceof Error ? error.message : 'The guest setup task failed to start.')+ }+ const deadline = now() + timeout+ while (now() < deadline) {+ if (fs.exists(answerFile)) {+ let source: string+ try {+ source = fs.read(answerFile)+ } catch (error) {+ fs.unlink(requestFile)+ throw new GuestSetupError('INVALID_ANSWER', `Could not read the guest setup answer: ${error instanceof Error ? error.message : String(error)}`)+ } finally {+ fs.unlink(answerFile)+ }+ fs.unlink(requestFile)+ try {+ return parseGuestSetupAnswer(source, request)+ } catch (error) {+ throw new GuestSetupError('INVALID_ANSWER', error instanceof Error ? error.message : 'The guest setup answer is not usable.')+ }+ }+ await sleep(pollMs)+ }+ fs.unlink(requestFile)+ throw new GuestSetupError('TIMEOUT', 'The guest setup task did not answer in time. Check the task and try again.')+ }+ const next = queue.then(run, run)+ queue = next.catch(() => {})+ return next+ }++ const expectOk = (answer: ReturnType<typeof parseGuestSetupAnswer>): void => {+ if (!answer.ok) throw new GuestSetupError('REQUEST_FAILED', answer.detail)+ }++ return {+ ensureGuest(email) {+ const address = canonicalGuestEmail(email)+ const known = emails.get(address)+ if (known) return known+ const pending = (async () => {+ const request = parseGuestSetupRequest(JSON.stringify({ id: newGuestRequestId(), op: 'ensure', email: address }), parseOptions)+ // A first profile may take the one-shot task minutes (lib/windows/guestScript.ts Run-As): wait as a share does.+ const answer = await send(request, Math.max(timeoutMs, 10 * 60_000))+ expectOk(answer)+ if (!answer.ok) throw new GuestSetupError('REQUEST_FAILED', answer.detail)+ return { user: answer.user, home: answer.home, workspace: answer.workspace }+ })()+ emails.set(address, pending)+ pending.catch(() => { if (emails.get(address) === pending) emails.delete(address) })+ return pending+ },+ async setFolders(user, folders) {+ const request = parseGuestSetupRequest(JSON.stringify({+ id: newGuestRequestId(), op: 'share', user,+ folders: folders.map((folder) => ({ path: folder.path, write: folder.write })),+ }), parseOptions)+ expectOk(await send(request, Math.max(timeoutMs, 10 * 60_000)))+ },+ async removeGuest(user) {+ const request = parseGuestSetupRequest(JSON.stringify({ id: newGuestRequestId(), op: 'remove', user }), parseOptions)+ expectOk(await send(request, timeoutMs))+ },+ }+}diff --git a/cli/src/lib/windows/guestShare.spec.ts b/cli/src/lib/windows/guestShare.spec.tsnew file mode 100644index 000000000..0f659144d--- /dev/null+++ b/cli/src/lib/windows/guestShare.spec.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from 'vitest'+import {+ GUEST_SHARE_MAX, GuestShareError, checkGuestSharePath, guestAclGrant, guestAclRemove, planGuestAcl,+} from './guestShare.js'++const OWNER = 'C:\\Users\\owner'+const USER = 'hg_0123456789ab'+const SID = 'S-1-5-21-1111111111-2222222222-3333333333-1001'+const share = (path: string, write = false) => ({ path, write })++const code = (fn: () => unknown): string => {+ try {+ fn()+ } catch (error) {+ if (error instanceof GuestShareError) return error.code+ throw error+ }+ throw new Error('expected a GuestShareError')+}++describe('a folder the owner may share', () => {+ it('accepts a plain folder, its parents, spaces and Unicode, and marks the owner profile', () => {+ const checked = checkGuestSharePath('C:\\Users\\owner\\My Projects\\Über', { ownerHome: OWNER })+ expect(checked).toEqual({+ path: 'C:\\Users\\owner\\My Projects\\Über',+ ownerProfile: true,+ ancestors: ['C:\\Users', 'C:\\Users\\owner', 'C:\\Users\\owner\\My Projects'],+ })+ expect(checkGuestSharePath('D:\\work\\repo', { ownerHome: OWNER }).ownerProfile).toBe(false)+ })++ it('refuses a root, a system folder, Harness\'s own ProgramData, and another user\'s profile', () => {+ for (const path of [+ 'C:\\', 'C:\\Windows', 'C:\\Windows\\System32', 'C:\\Program Files\\App', 'C:\\Program Files (x86)\\App',+ 'C:\\ProgramData', 'C:\\ProgramData\\Harness', 'C:\\ProgramData\\Harness\\Guests', 'C:\\ProgramData\\HarnessGuests',+ // The profile-holding folder itself would inherit an ACE into every profile; the guests' own tree is never shared.+ 'C:\\Users', 'C:\\Users\\other\\work', 'C:\\Users\\Public',+ 'C:\\$Recycle.Bin', 'C:\\System Volume Information', 'C:\\Recovery', 'C:\\Boot', 'C:\\PerfLogs',+ ]) {+ expect(code(() => checkGuestSharePath(path, { ownerHome: OWNER })), path).toBe('INVALID_PATH')+ }+ })++ it('refuses names Windows would change, alternate streams, UNC and relative paths', () => {+ for (const path of [+ 'C:\\work\\..\\other', 'C:\\work\\a.', 'C:\\work\\a ', 'C:\\work\\CON', 'C:\\work\\lpt1.txt',+ 'C:\\work\\a:b', 'C:\\work\\a?b', 'C:\\work\\a*b', 'C:\\work\\a<b', 'C:\\work\\a|b', 'C:\\work\\a"b',+ 'C:/work', '\\\\server\\share', 'work', 'C:\\work\\\\x',+ ]) {+ expect(code(() => checkGuestSharePath(path, { ownerHome: OWNER })), path).toBe('INVALID_PATH')+ }+ })++ it('refuses a drive that is not a local fixed drive', () => {+ expect(code(() => checkGuestSharePath('Z:\\work', { ownerHome: OWNER, fixedDrives: new Set(['C:', 'D:']) }))).toBe('INVALID_PATH')+ expect(() => checkGuestSharePath('c:\\work', { ownerHome: OWNER, fixedDrives: new Set(['C:']) })).not.toThrow()+ })++ it('refuses a junction anywhere on the path, and the folder itself', () => {+ expect(code(() => checkGuestSharePath('C:\\Users\\owner\\link\\work', {+ ownerHome: OWNER, isReparse: (path) => path === 'C:\\Users\\owner\\link',+ }))).toBe('REPARSE')+ expect(code(() => checkGuestSharePath('C:\\Users\\owner\\work', {+ ownerHome: OWNER, isReparse: (path) => path === 'C:\\Users\\owner\\work',+ }))).toBe('REPARSE')+ })+})++describe('the ACLs', () => {+ it('gives a read folder RX (not R: a directory needs execute), an edit folder M, never F', () => {+ expect(guestAclGrant(USER, SID, 'C:\\work', 'read')).toEqual(['C:\\work', '/grant:r', `*${SID}:(OI)(CI)(RX)`, '/L', '/q'])+ expect(guestAclGrant(USER, SID, 'C:\\work', 'edit')).toEqual(['C:\\work', '/grant:r', `*${SID}:(OI)(CI)M`, '/L', '/q'])+ expect(guestAclGrant(USER, SID, 'C:\\work', 'traverse')).toEqual(['C:\\work', '/grant:r', `*${SID}:(X)`, '/L', '/q'])+ for (const level of ['read', 'edit', 'traverse'] as const) {+ const args = guestAclGrant(USER, SID, 'C:\\work', level)+ expect(args.join(' ')).not.toContain('(F)')+ expect(args).not.toContain('/T')+ }+ })++ it('removes only this guest, never recursively', () => {+ expect(guestAclRemove(USER, SID, 'C:\\work')).toEqual(['C:\\work', '/remove:g', `*${SID}`, '/L', '/q'])+ expect(guestAclRemove(USER, SID, 'C:\\work')).not.toContain('/T')+ })++ it('refuses a caller that is not a guest account, and a SID that is not one', () => {+ expect(code(() => guestAclGrant('owner', SID, 'C:\\work', 'read'))).toBe('NOT_A_GUEST')+ expect(code(() => guestAclGrant(USER, 'owner', 'C:\\work', 'read'))).toBe('INVALID_SID')+ })+})++describe('the difference between what a guest has and what the owner shares', () => {+ it('grants only the folder: Windows Bypass traverse checking needs no parent ACE', () => {+ const plan = planGuestAcl({+ ownerHome: OWNER, user: USER, sid: SID, current: [],+ next: [share('C:\\Users\\owner\\work\\project')],+ })+ expect(plan.grant.map((change) => [change.path, change.level])).toEqual([+ ['C:\\Users\\owner\\work\\project', 'read'],+ ])+ expect(plan.remove).toEqual([])+ expect(plan.record).toEqual([{ path: 'C:\\Users\\owner\\work\\project', level: 'read' }])+ })++ it('changes only the difference: the same folders cost nothing, read to edit is one grant', () => {+ const first = planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: [], next: [share('C:\\work\\a')] })+ const same = planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: first.record, next: [share('C:\\work\\a')] })+ expect(same.grant).toEqual([])+ expect(same.remove).toEqual([])+ const edit = planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: first.record, next: [share('C:\\work\\a', true)] })+ expect(edit.grant.map((change) => [change.path, change.level])).toEqual([['C:\\work\\a', 'edit']])+ })++ it('removes a folder the owner no longer shares, and nothing else', () => {+ const first = planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: [], next: [share('C:\\work\\a'), share('C:\\work\\b')] })+ const next = planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: first.record, next: [share('C:\\work\\b')] })+ expect(next.remove.map((change) => change.path)).toEqual(['C:\\work\\a'])+ expect(next.record.map((ace) => ace.path)).toEqual(['C:\\work\\b'])+ })++ it('keeps a shared parent at its share level even when it is also a parent of another share', () => {+ const plan = planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: [], next: [share('C:\\work', true), share('C:\\work\\child')] })+ expect(plan.record).toEqual([+ { path: 'C:\\work', level: 'edit' },+ { path: 'C:\\work\\child', level: 'read' },+ ])+ })++ it('refuses a path shared under two cases (Windows has one folder), and more than the cap', () => {+ expect(code(() => planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: [], next: [share('C:\\Work\\A'), share('c:\\work\\a')] }))).toBe('DUPLICATE')+ const many = Array.from({ length: GUEST_SHARE_MAX + 1 }, (_, i) => share(`C:\\work\\${i}`))+ expect(code(() => planGuestAcl({ ownerHome: OWNER, user: USER, sid: SID, current: [], next: many }))).toBe('TOO_MANY')+ })++ it('refuses a link in the next share, even when the record already names it', () => {+ expect(code(() => planGuestAcl({+ ownerHome: OWNER, user: USER, sid: SID,+ current: [{ path: 'C:\\Users\\owner\\link\\work', level: 'read' }],+ next: [share('C:\\Users\\owner\\link\\work')],+ isReparse: (path) => path === 'C:\\Users\\owner\\link',+ }))).toBe('REPARSE')+ })+})diff --git a/cli/src/lib/windows/guestShare.ts b/cli/src/lib/windows/guestShare.tsnew file mode 100644index 000000000..25eab6d7f--- /dev/null+++ b/cli/src/lib/windows/guestShare.ts@@ -0,0 +1,259 @@+/**+ * Windows shared folders for guests (docs/superpowers/specs/2026-11-05-windows-guests-design.md, "Shared folders").+ *+ * Pure description of what the elevated setup script has to do, so the hard parts are tested without a Windows PC:+ * the path checks (a root, another profile, a reparse point), the ACL shape (read is RX, edit is M, never F; `/grant:r`+ * replaces only our ACE, no `/T`), the traverse-only parents, and the difference between what a guest has and what the+ * owner now shares. The PowerShell side calls the same plan; it never builds these strings from user text.+ *+ * A shared folder is the owner's choice, not a trust boundary: a guest with edit can put files there, including a+ * junction. The setup script refuses reparse points on every component, and [isReparse] lets the caller refuse a path+ * whose real components are links before it is recorded.+ */+import { win32 } from 'node:path'+import { isGuestUser } from '../guestAccounts.js'+import { checkSid } from '../../team/windowsLayout.js'++/** The macOS form's cap: a guest sees at most this many folders. */+export const GUEST_SHARE_MAX = 20+/** MAX_PATH less its NUL, as every Windows API without the `\\?\` prefix takes it. */+export const GUEST_SHARE_MAX_PATH = 259++export type GuestShareLevel = 'read' | 'edit'+/** A shared folder's own ACE, or the search-only ACE every parent between it and the drive needs. */+export type GuestAceLevel = GuestShareLevel | 'traverse'++export interface GuestSharedFolder { path: string; write: boolean }+export interface GuestAce { path: string; level: GuestAceLevel }++export interface CheckedGuestShare {+ path: string+ /** The path is inside the owner's profile. Windows denies can beat our allow, so the setup checks it as a guest. */+ ownerProfile: boolean+ /** Every parent from the drive root down to the folder's, the ones that may need traverse-only. */+ ancestors: string[]+}++export type GuestShareErrorCode =+ | 'INVALID_PATH' // not a plain absolute local path, or a root/system/another profile+ | 'TOO_MANY' // more than GUEST_SHARE_MAX after duplicates are folded+ | 'DUPLICATE' // the same folder twice+ | 'REPARSE' // a component is a junction or another reparse point+ | 'NOT_A_GUEST' // not an `hg_<12 hex>` account+ | 'INVALID_SID'++export class GuestShareError extends Error {+ constructor(readonly code: GuestShareErrorCode, message: string) {+ super(message)+ this.name = 'GuestShareError'+ }+}++export interface GuestSharePathOptions {+ /** The owner's profile, `C:\Users\<owner>`; a path under `C:\Users` is only theirs or refused. */+ ownerHome: string+ /** Local fixed drives the owner may share from (drive letters, case-insensitive). Omitted accepts every letter. */+ fixedDrives?: ReadonlySet<string>+ /** Whether an existing path is a junction or another reparse point. The setup script checks the real ones. */+ isReparse?: (path: string) => boolean+}++const WINDOWS_ROOT = /^[A-Za-z]:\\/+const INVALID_SEGMENT = /[<>:"|?*\u0000-\u001f]/+const RESERVED = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i+const TRAILING = /[. ]$/++const SYSTEM_ROOTS = [+ 'C:\\Windows',+ 'C:\\Program Files',+ 'C:\\Program Files (x86)',+ 'C:\\ProgramData',+ 'C:\\$Recycle.Bin',+ 'C:\\System Volume Information',+ 'C:\\Recovery',+ 'C:\\Boot',+ 'C:\\PerfLogs',+]+const SYSTEM_NAMES = new Set(['public', 'default', 'default user', 'all users'])++const lower = (path: string): string => path.toLowerCase()+export const sameWindowsPath = (a: string, b: string): boolean => lower(win32.normalize(a)) === lower(win32.normalize(b))+const within = (path: string, root: string): boolean => {+ const p = lower(win32.normalize(path))+ const r = lower(win32.normalize(root)).replace(/\\+$/, '')+ return p === r || p.startsWith(`${r}\\`)+}++function fail(code: GuestShareErrorCode, message: string): never {+ throw new GuestShareError(code, message)+}++/** The owner's account name from their profile path (`C:\Users\owner`). */+function ownerName(ownerHome: string): string {+ try {+ checkWindowsProfile(ownerHome)+ } catch {+ fail('INVALID_PATH', `the owner's profile is not a plain Windows path: ${JSON.stringify(ownerHome)}`)+ }+ return win32.basename(ownerHome)+}++/** A plain absolute drive path: no UNC, no `/`, no `..`, no segment Windows would rename or reserve. */+function checkWindowsProfile(path: string): string {+ if (typeof path !== 'string' || path.length > GUEST_SHARE_MAX_PATH || !WINDOWS_ROOT.test(path)+ || win32.normalize(path) !== path) {+ fail('INVALID_PATH', `not a plain absolute Windows path: ${JSON.stringify(path)}`)+ }+ const segments = path.slice(3).split('\\')+ if (path.length === 3 || segments.some((segment) => segment === '' || segment === '.' || segment === '..'+ || INVALID_SEGMENT.test(segment) || TRAILING.test(segment) || RESERVED.test(segment))) {+ fail('INVALID_PATH', `not a plain absolute Windows path: ${JSON.stringify(path)}`)+ }+ return path+}++function ancestorsOf(path: string): string[] {+ const parts = path.slice(3).split('\\')+ const parents: string[] = []+ for (let i = 1; i < parts.length; i++) parents.push(`${path.slice(0, 2)}\\${parts.slice(0, i).join('\\')}`)+ return parents+}++/**+ * Checks one folder the owner wants to share, or why it cannot be: a root, a system folder, another user's profile,+ * a name Windows would change, or a link. The owner's own profile is allowed but marked: its deny ACEs may still beat+ * the guest's allow, which only the setup's real check can tell.+ */+export function checkGuestSharePath(path: string, options: GuestSharePathOptions): CheckedGuestShare {+ const owner = ownerName(options.ownerHome)+ checkWindowsProfile(path)+ const drive = path.slice(0, 2).toUpperCase()+ if (options.fixedDrives && !options.fixedDrives.has(drive) && !options.fixedDrives.has(drive.toLowerCase())) {+ fail('INVALID_PATH', `the drive ${drive} is not a local fixed drive`)+ }+ if (path.length === 3) fail('INVALID_PATH', 'a drive root cannot be shared')+ for (const root of SYSTEM_ROOTS) if (within(path, root)) fail('INVALID_PATH', `${root} cannot be shared`)++ const relative = path.slice(3).split('\\')+ // The folder that holds every profile: an ACE there would be inherited by profiles no guest may enter.+ if (relative.length === 1 && lower(relative[0]!) === 'users') fail('INVALID_PATH', 'the folder that holds every profile cannot be shared')+ if (lower(relative[0]!) === 'users' && relative.length >= 2) {+ const profile = relative[1]!+ if (lower(profile) !== lower(owner)) {+ fail('INVALID_PATH', 'another user\'s profile cannot be shared')+ }+ if (SYSTEM_NAMES.has(lower(profile))) fail('INVALID_PATH', 'a Windows profile folder cannot be shared')+ }++ const ancestors = ancestorsOf(path)+ if (options.isReparse) {+ for (const one of [...ancestors, path]) {+ if (options.isReparse(one)) fail('REPARSE', `${one} is a junction or another reparse point`)+ }+ }+ return { path, ownerProfile: within(path, options.ownerHome), ancestors }+}++/** The ACE a shared folder gets: read is RX (not R: a directory needs execute to be entered), edit is M, never F. */+export function guestShareAce(level: GuestShareLevel): string {+ return level === 'read' ? '(OI)(CI)(RX)' : '(OI)(CI)M'+}++/** A parent's ACE: search only, no listing. On a folder that is shared too, the share ACE is used instead. */+export function guestTraverseAce(): string {+ return '(X)'+}++export function guestAceFor(level: GuestAceLevel): string {+ return level === 'traverse' ? guestTraverseAce() : guestShareAce(level)+}++function checkGuest(user: string): string {+ if (!isGuestUser(user)) fail('NOT_A_GUEST', `not a guest account: ${JSON.stringify(user)}`)+ return user+}++function checkGuestSid(sid: string): string {+ try {+ return checkSid(sid, 'guest account')+ } catch {+ fail('INVALID_SID', `the guest account is not a SID: ${JSON.stringify(sid)}`)+ }+}++/** `icacls` arguments for one desired ACE (`/grant:r`: our entry, not a second one; `/L`: the path itself, never a link). */+export function guestAclGrant(user: string, sid: string, path: string, level: GuestAceLevel): string[] {+ checkGuest(user)+ checkGuestSid(sid)+ return [path, '/grant:r', `*${sid}:${guestAceFor(level)}`, '/L', '/q']+}++/** `icacls` arguments that remove only the guest's entries from [path]. */+export function guestAclRemove(user: string, sid: string, path: string): string[] {+ checkGuest(user)+ checkGuestSid(sid)+ return [path, '/remove:g', `*${sid}`, '/L', '/q']+}++export interface GuestAclPlanInput {+ ownerHome: string+ user: string+ sid: string+ /** What the setup record says the guest has now. */+ current: readonly GuestAce[]+ /** The folders the owner shares now, as the form sends them. */+ next: readonly GuestSharedFolder[]+ fixedDrives?: ReadonlySet<string>+ isReparse?: (path: string) => boolean+}++export interface GuestAclChange { path: string; level: GuestAceLevel; args: string[] }+export interface GuestAclPlan {+ grant: GuestAclChange[]+ remove: GuestAclChange[]+ /** What to keep as the setup record once every command has succeeded. */+ record: GuestAce[]+}++/**+ * What changes between the guest's recorded ACEs and the owner's current folders: shared folders get read/edit, every+ * parent up to the drive gets traverse-only, a path no longer needed loses the guest's entries, and a path shared and+ * a parent of another keeps its share ACE. A folder the owner still shares is never weakened to traverse.+ */+export function planGuestAcl(input: GuestAclPlanInput): GuestAclPlan {+ const desired = new Map<string, GuestAce>()+ const shares: Array<{ path: string; level: GuestShareLevel }> = []+ const seen = new Set<string>()+ for (const folder of input.next) {+ const checked = checkGuestSharePath(folder.path, {+ ownerHome: input.ownerHome,+ ...(input.fixedDrives ? { fixedDrives: input.fixedDrives } : {}),+ ...(input.isReparse ? { isReparse: input.isReparse } : {}),+ })+ const key = lower(checked.path)+ if (seen.has(key)) fail('DUPLICATE', `the folder ${checked.path} is shared twice`)+ seen.add(key)+ shares.push({ path: checked.path, level: folder.write ? 'edit' : 'read' })+ }+ if (shares.length > GUEST_SHARE_MAX) fail('TOO_MANY', `at most ${GUEST_SHARE_MAX} folders can be shared`)+ // Windows gives every account "Bypass traverse checking" (SeChangeNotifyPrivilege), so a guest opens a shared+ // folder by its full path without an ACE on any parent. No parent is touched: that keeps the owner's profile+ // untouched, and it avoids the hang a DACL write on C:\Users\<owner> caused on the real PC (2026-11-05).+ for (const share of shares) desired.set(lower(share.path), share)++ const before = new Map<string, GuestAce>()+ for (const ace of input.current) before.set(lower(ace.path), ace)+ const grant: GuestAclChange[] = []+ for (const [key, ace] of desired) {+ const had = before.get(key)+ if (had?.level === ace.level) continue+ grant.push({ path: ace.path, level: ace.level, args: guestAclGrant(input.user, input.sid, ace.path, ace.level) })+ }+ const remove: GuestAclChange[] = []+ for (const [key, ace] of before) {+ if (desired.has(key)) continue+ remove.push({ path: ace.path, level: ace.level, args: guestAclRemove(input.user, input.sid, ace.path) })+ }+ const record = [...desired.values()].map((ace) => ({ path: ace.path, level: ace.level }))+ return { grant, remove, record }+}diff --git a/cli/src/lib/windows/windowsGuestAccounts.spec.ts b/cli/src/lib/windows/windowsGuestAccounts.spec.tsnew file mode 100644index 000000000..cd81a660a--- /dev/null+++ b/cli/src/lib/windows/windowsGuestAccounts.spec.ts@@ -0,0 +1,31 @@+import { describe, expect, it, vi } from 'vitest'+import { createWindowsGuestAccounts } from './windowsGuestAccounts.js'++// The guests' accounts on Windows: the setup task does the privileged work, so this only speaks its contract+// (lib/windows/guestSetupClient.ts) and reads which guests have a host home. Never sudo, never a password here.+describe('a Windows guest\'s account, as a launch reads it', () => {+ const account = { user: 'hg_0123456789ab', home: 'C:\\Users\\hg_0123456789ab', workspace: 'C:\\Users\\hg_0123456789ab\\work' }++ it('makes the account through the setup task, and shares the owner\'s whole set as its own', async () => {+ const client = { ensureGuest: vi.fn(async () => account), setFolders: vi.fn(async () => {}), removeGuest: vi.fn(async () => {}) }+ const accounts = createWindowsGuestAccounts({ ownerHome: 'C:\\Users\\DELL', client })+ expect(await accounts.ensureGuest('[email protected]')).toEqual(account)+ expect(client.ensureGuest).toHaveBeenCalledWith('[email protected]')+ const folders = [{ path: 'C:\\Users\\DELL\\code', write: true }]+ await accounts.shareFolders(account.user, folders)+ expect(client.setFolders).toHaveBeenCalledWith(account.user, folders)+ await accounts.shareFolders(account.user, [])+ expect(client.setFolders).toHaveBeenLastCalledWith(account.user, [])+ })++ it('lists the guests that have a host home, and only those, as the sync reads them', () => {+ const accounts = createWindowsGuestAccounts({ ownerHome: 'C:\\Users\\DELL',+ client: { ensureGuest: vi.fn(), setFolders: vi.fn(), removeGuest: vi.fn() },+ hosts: () => ['hg_bbbbbbbbbbbb', 'DELL', 'hg_aaaaaaaaaaaa', 'hg_nothex', '.tmp'] })+ expect(accounts.guests()).toEqual(['hg_aaaaaaaaaaaa', 'hg_bbbbbbbbbbbb'])+ const none = createWindowsGuestAccounts({ ownerHome: 'C:\\Users\\DELL',+ client: { ensureGuest: vi.fn(), setFolders: vi.fn(), removeGuest: vi.fn() }, hosts: () => { throw Object.assign(new Error('gone'), { code: 'ENOENT' }) } })+ // A tree that is not there yet is no guest, not an error: sharing may not be on.+ expect(none.guests()).toEqual([])+ })+})diff --git a/cli/src/lib/windows/windowsGuestAccounts.ts b/cli/src/lib/windows/windowsGuestAccounts.tsnew file mode 100644index 000000000..adf17613c--- /dev/null+++ b/cli/src/lib/windows/windowsGuestAccounts.ts@@ -0,0 +1,44 @@+/**+ * The guests' OS accounts on Windows, as services/guestLaunches.ts reads them: a thin adapter over the setup task+ * (lib/windows/guestSetupClient.ts), which does the privileged work through `\Harness\Harness Guests Setup`. There is+ * no `sudo` and no helper here, and the owner never holds a guest's password: the setup task makes the account.+ *+ * Only what a launch, a share change and the sync read is here. Installing an engine as the guest is the guest's own+ * step (the engine is on the guest's PATH in its host's pane), so nothing in this path installs it from the owner's.+ */+import { readdirSync } from 'node:fs'+import { isGuestUser, type GuestAccount, type SharedFolder } from '../guestAccounts.js'+import { WINDOWS_GUEST_HOSTS } from './guestRequests.js'+import { createGuestSetupClient, type GuestSetupClient } from './guestSetupClient.js'++export interface WindowsGuestAccountsDeps {+ /** The owner's profile; the setup client uses it to refuse paths inside other profiles. */+ ownerHome: string+ /** The setup task's client; a seam for tests. */+ client?: Pick<GuestSetupClient, 'ensureGuest' | 'setFolders' | 'removeGuest'>+ /** The names in the guest host root (`hosts\<user>`), which the setup task makes per guest; a seam for tests. */+ hosts?: () => string[]+}++/** What guestLaunches needs of the accounts (lib/guestAccounts.ts `GuestAccounts`, narrower). */+export interface WindowsGuestAccounts {+ ensureGuest(email: string): Promise<GuestAccount>+ shareFolders(user: string, folders: readonly SharedFolder[]): Promise<void>+ guests(): string[]+}++export function createWindowsGuestAccounts(deps: WindowsGuestAccountsDeps): WindowsGuestAccounts {+ const client = deps.client ?? createGuestSetupClient({ ownerHome: deps.ownerHome })+ const hosts = deps.hosts ?? (() => {+ try { return readdirSync(WINDOWS_GUEST_HOSTS) } catch { return [] }+ })+ return {+ // The setup task derives the same `hg_<12 hex>` the macOS helper does, and answers with the exact profile.+ ensureGuest: (email) => client.ensureGuest(email),+ // The setup task takes the owner's whole set: it changes only the difference from its own record.+ shareFolders: (user, folders) => client.setFolders(user, folders.map((folder) => ({ path: folder.path, write: folder.write }))),+ // Every guest with a host home has an account the owner may share with; one mid-remove may still be listed and+ // is simply asked for no folders again. A tree that is not there yet is no guest, not an error.+ guests: () => { try { return hosts().filter(isGuestUser).sort() } catch { return [] } },+ }+}diff --git a/cli/src/services/devicesProcess.spec.ts b/cli/src/services/devicesProcess.spec.tsindex d5348aa37..6dab5d7fa 100644--- a/cli/src/services/devicesProcess.spec.ts+++ b/cli/src/services/devicesProcess.spec.ts@@ -305,6 +305,9 @@ describe('what the core tells the devices, reaching their port', () => {stop()h.event({ kind: 'notice', notice: { type: 'machines_changed', reason: 'renamed' } })expect(heard).toHaveLength(1)+ // A notice that is not an object is nothing to hand on, not a listener's to explain.+ for (const notice of [null, 'renamed', 7]) h.event({ kind: 'notice', notice })+ expect(heard).toHaveLength(1)})it('is each kind of notice, read as the port takes it', () => {diff --git a/cli/src/services/guestLaunches.spec.ts b/cli/src/services/guestLaunches.spec.tsindex 2edc0edad..8fe5e64bd 100644--- a/cli/src/services/guestLaunches.spec.ts+++ b/cli/src/services/guestLaunches.spec.ts@@ -66,6 +66,19 @@ describe('a guest\'s harness, as shared machines builds it', () => {await launches.stop()})+ it('on Windows names the guest\'s own host and runs the engine directly, with no owner pane or helper', async () => {+ const relay = { port: 1, url: 'http://127.0.0.1:1', adoptToken: () => {}, mintToken: () => 't', revoke: () => {}, close: async () => {} }+ const launches = createGuestLaunches({+ accounts: { ensureGuest: async () => ({ user: KIM, home: `C:\\Users\\${KIM}`, workspace: `C:\\Users\\${KIM}\\work` }), shareFolders: async () => {}, guests: () => [KIM] } as unknown as GuestAccounts,+ helperState: async () => 'ready', startRelay: async () => relay, platform: 'win32',+ })+ const launched = await launches.launch(input)+ expect(launched).toEqual({ ok: true, workspace: `C:\\Users\\${KIM}\\work`, argv: ['claude', '--dangerously-skip-permissions'],+ env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:1/claude', ANTHROPIC_AUTH_TOKEN: 't' }, guestHostUser: KIM })+ // Every other platform leaves the pane to the owner's backend and the helper.+ expect(await setup().launches.launch(input)).not.toHaveProperty('guestHostUser')+ })+it('starts nothing for a session whose guest it cannot name, or an engine whose subscription it cannot spend', async () => {const { launches, accounts } = setup()expect(await launches.launch({ ...input, email: ' ' })).toEqual({ ok: false, error: 'NOT_YOUR_HARNESS', detail: expect.any(String) })diff --git a/cli/src/services/guestLaunches.ts b/cli/src/services/guestLaunches.tsindex d21cfd586..014fa1b0e 100644--- a/cli/src/services/guestLaunches.ts+++ b/cli/src/services/guestLaunches.ts@@ -8,7 +8,7 @@* the owner's subscriptions, even from a harness still running, and keeps none of the owner's folders; every* guest still named has exactly the folders the owner shares.*/-import { isAbsolute, resolve } from 'node:path'+import { isAbsolute, resolve, sep } from 'node:path'import type { GuestLaunch, GuestLaunchInput } from '../core/api.js'import { GuestHelperError, guestUserFor, type GuestAccounts, type SharedFolder } from '../lib/guestAccounts.js'import type { GuestHelperState } from '../lib/guestHelperInstall.js'@@ -16,7 +16,9 @@ import { GUEST_LAUNCH_ENGINES, guestPaneCommand, type GuestLaunchEngine } from 'import type { SubscriptionRelay } from '../lib/subscriptionRelay.js'export interface GuestLaunchesDeps {- accounts: GuestAccounts+ /** The guests' accounts; only what a launch and a share change read (lib/guestAccounts.ts, or the+ * Windows setup client's adapter, lib/windows/windowsGuestAccounts.ts). */+ accounts: Pick<GuestAccounts, 'ensureGuest' | 'shareFolders' | 'guests'>/** Whether the owner turned guest access on here: the helper installed, current and allowed. */helperState: () => Promise<GuestHelperState>startRelay: () => Promise<SubscriptionRelay>@@ -24,6 +26,8 @@ export interface GuestLaunchesDeps {folders?: () => SharedFolder[]helperPath?: stringlang?: string+ /** The platform the pane is made on; `process.platform` when absent. Windows makes it on the guest's own host. */+ platform?: NodeJS.Platformlog?: (line: string) => void}@@ -47,11 +51,12 @@ const HELPER_REQUIRED: Record<Exclude<GuestHelperState, 'ready'>, string> = {/** Whether [path] (resolved) is [folder] or inside it. */const within = (path: string, folder: string): boolean => {const root = resolve(folder)- return path === root || path.startsWith(`${root}/`)+ return path === root || path.startsWith(`${root}${sep}`)}export function createGuestLaunches(deps: GuestLaunchesDeps): GuestLaunches {const log = deps.log ?? (() => {})+ const platforms = deps.platform ?? process.platformconst folders = deps.folders ?? (() => [])let relay: Promise<SubscriptionRelay> | null = null/** Whom tokens were minted for, to revoke when sharing with them ends. */@@ -107,12 +112,14 @@ export function createGuestLaunches(deps: GuestLaunchesDeps): GuestLaunches {minted.add(guest)const where = folder && start ? start : account.workspaceconst command = guestPaneCommand({- account, engine: engine as GuestLaunchEngine, relayUrl: running.url, token, bypassPermission, cwd: where,+ account, engine: engine as GuestLaunchEngine, relayUrl: running.url, token, bypassPermission, cwd: where, platform: platforms,...(permissionFlags ? { permissionFlags } : {}),...(prompt ? { prompt } : {}), ...(deps.lang ? { lang: deps.lang } : {}), ...(deps.helperPath ? { helperPath: deps.helperPath } : {}),})log(`launch · ${engine} · ${account.user}`)- return { ok: true, workspace: where, argv: command.argv, env: command.env }+ // Windows: the pane is made by the guest's own host, whose panes already run as the guest (lib/windows/).+ return { ok: true, workspace: where, argv: command.argv, env: command.env,+ ...(platforms === 'win32' ? { guestHostUser: account.user } : {}) }},async sync(still, shared) {for (const guest of [...minted]) {diff --git a/cli/src/services/sharedMachines.spec.ts b/cli/src/services/sharedMachines.spec.tsindex 850f8ded8..62ea3fe77 100644--- a/cli/src/services/sharedMachines.spec.ts+++ b/cli/src/services/sharedMachines.spec.ts@@ -7,7 +7,7 @@ import { emptyPorts, type Asker, type BackendNotice } from '../core/api.js'import type { GuestHelperState } from '../lib/guestHelperInstall.js'import type { PortFailure, SharedMachine, SharedMachinesPort, SharePolicy } from '../lib/sharedMachinesPort.js'import type { GuestLaunches } from './guestLaunches.js'-import { guestLaunchInput, normalizeEmails, normalizeFolders, ownerFolderProblem, readPolicy, SHARE_EMAILS_MAX, SHARED_FOLDERS_MAX,+import { guestLaunchInput, machineGuests, normalizeEmails, normalizeFolders, ownerFolderProblem, readPolicy, sameSharedPath, withinSharedPath, SHARE_EMAILS_MAX, SHARED_FOLDERS_MAX,SHARED_MACHINES_REQUESTS, startSharedMachines, stillShared, trustedKeys } from './sharedMachines.js'// The real guests reach the machine (the helper, sudo, the owner's sign-ins, a loopback relay): never in a test. The@@ -412,6 +412,16 @@ describe('shared machines', () => {expect(readPolicy(file).folders).toEqual([])})+ it('treats one Windows folder spelled two ways as one folder, and POSIX paths as exact', () => {+ expect(sameSharedPath('c:\\ProgramData\\HarnessGuests', 'C:\\ProgramData\\HarnessGuests', 'win32')).toBe(true)+ expect(sameSharedPath('C:\\Users\\DELL', 'C:\\Users\\Dell', 'win32')).toBe(true)+ expect(sameSharedPath('/Users/dee', '/users/dee', 'darwin')).toBe(false)+ expect(sameSharedPath('/Users/dee', '/Users/dee', 'darwin')).toBe(true)+ expect(withinSharedPath('C:\\ProgramData\\HarnessGuests\\requests', 'c:\\programdata\\harnessguests', 'win32')).toBe(true)+ expect(withinSharedPath('/Users/Shared/HarnessGuests/hg_x', '/Users/Shared/HarnessGuests', 'darwin')).toBe(true)+ expect(withinSharedPath('/Users/Shared/HarnessGuestsX', '/Users/Shared/HarnessGuests', 'darwin')).toBe(false)+ })+it('says in words why a folder cannot be shared, before the helper would', () => {const home = mkdtempSync(join(tmpdir(), 'owner-home-'))try {@@ -434,6 +444,12 @@ describe('shared machines', () => {})})+ it('builds the real guests from the setup task on Windows, and the helper elsewhere', () => {+ // Only their construction: the accounts' own contracts are tested beside them (the setup client, the helper).+ expect(typeof machineGuests(() => {}, file, 'win32').launch).toBe('function')+ expect(typeof machineGuests(() => {}, file, 'darwin').launch).toBe('function')+ })+it('reads a launch the core asked for, and nothing else as one', () => {expect(guestLaunchInput({ ...input, extra: 1 })).toEqual(input)expect(guestLaunchInput({ ...input, prompt: 'Fix the tests' })).toEqual({ ...input, prompt: 'Fix the tests' })diff --git a/cli/src/services/sharedMachines.ts b/cli/src/services/sharedMachines.tsindex b7200e6ee..bb9e6dbef 100644--- a/cli/src/services/sharedMachines.ts+++ b/cli/src/services/sharedMachines.ts@@ -26,12 +26,13 @@* while anything is shared either way.*/import { homedir } from 'node:os'-import { isAbsolute, join, resolve } from 'node:path'+import { isAbsolute, join, parse, resolve, sep, win32 } from 'node:path'import { readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'import type { CoreApi, CorePorts, GuestLaunchInput, ServiceRequests } from '../core/api.js'import { createGuestAccounts, guestHomeRoot, guestWorkspaceFor, type SharedFolder } from '../lib/guestAccounts.js'import { guestHelperStatus, installGuestHelper, type GuestHelperInstallResult, type GuestHelperState } from '../lib/guestHelperInstall.js'import { createOwnerSubscriptions } from '../lib/ownerSubscriptions.js'+import { createWindowsGuestAccounts } from '../lib/windows/windowsGuestAccounts.js'import { failed, type PortFailure, type ShareMember, type SharedMachinesPort, type SharePolicy,type SharedTrustPeer } from '../lib/sharedMachinesPort.js'import { startSubscriptionRelay } from '../lib/subscriptionRelay.js'@@ -93,20 +94,38 @@ export function normalizeFolders(raw: unknown): SharedFolder[] | null {const { path, write } = (folder ?? {}) as { path?: unknown; write?: unknown }if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096 || /[\t\n\r\0]/.test(path) || typeof write !== 'boolean') return nullconst resolved = resolve(path)- if (resolved === '/' || folders.some((f) => f.path === resolved)) return null+ if (resolved === parse(resolved).root || folders.some((f) => f.path === resolved)) return nullfolders.push({ path: resolved, write })}return folders}+/** Whether two resolved paths name one folder on [platform]: Windows has one spelling per folder, so it ignores+ * case there (`c:\\programdata\\harnessguests` must not slip past the guests' root); POSIX paths are exact. */+export function sameSharedPath(a: string, b: string, platform: NodeJS.Platform = process.platform): boolean {+ return platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b+}++/** Whether [path] is [root] or inside it, with Windows' one-spelling rule. */+export function withinSharedPath(path: string, root: string, platform: NodeJS.Platform = process.platform): boolean {+ if (sameSharedPath(path, root, platform)) return true+ const separator = platform === 'win32' ? win32.sep : sep+ return platform === 'win32'+ ? path.toLowerCase().startsWith(`${root.toLowerCase()}${separator}`)+ : path.startsWith(`${root}${separator}`)+}+/** The helper's own rules, said here first in words: a folder of the owner's, on this computer, never its whole* home or a guest's. */export function ownerFolderProblem(path: string, home = homedir(), guests = guestHomeRoot(), uid = process.getuid?.()): string | null {let infotry { info = statSync(path) } catch { return `No such folder on this computer: ${path}` }if (!info.isDirectory()) return `Not a folder: ${path}`- if (resolve(path) === resolve(home)) return 'Your whole home folder cannot be shared. Choose a folder in it.'- if (path === guests || path.startsWith(`${guests}/`)) return `This folder belongs to someone you share with and can't be shared: ${path}`+ if (sameSharedPath(resolve(path), resolve(home))) return 'Your whole home folder cannot be shared. Choose a folder in it.'+ // The guests' own tree: their host homes and records, which the setup task owns (`\` or `/`, by platform).+ const guestRoot = resolve(guests)+ const resolved = resolve(path)+ if (withinSharedPath(resolved, guestRoot)) return `This folder belongs to someone you share with and can't be shared: ${path}`if (uid !== undefined && info.uid !== uid) return `Only your own folders can be shared: ${path}`return null}@@ -149,14 +168,18 @@ export function trustedKeys(local: LocalPolicy, remote: SharePolicy): SharedTrusconst answerFailure = (f: PortFailure): Record<string, unknown> => ({ error: f.failed.code, message: f.failed.message })-/** The real guests: OS accounts through the helper, the owner's sign-ins read where the engines keep them. */-function machineGuests(log: (line: string) => void, file: string): GuestLaunches {+/** The real guests: OS accounts through the setup task on Windows, the helper elsewhere, the owner's sign-ins+ * read where the engines keep them. Exported with its platform so a test proves both accounts' sides. */+export function machineGuests(log: (line: string) => void, file: string, platform: NodeJS.Platform = process.platform): GuestLaunches {return createGuestLaunches({- accounts: createGuestAccounts(),+ accounts: platform === 'win32'+ ? createWindowsGuestAccounts({ ownerHome: process.env.USERPROFILE ?? homedir() })+ : createGuestAccounts(),helperState: async () => (await guestHelperStatus()).state,folders: () => readPolicy(file).folders,startRelay: () => startSubscriptionRelay({ owner: createOwnerSubscriptions(), log: (line) => log(`relay · ${line}`) }),...(process.env.LANG ? { lang: process.env.LANG } : {}),+ platform,log: (line) => log(`guest ${line}`),})}diff --git a/desktop/lib/core/guest_folders.dart b/desktop/lib/core/guest_folders.dartindex e677fe22a..568f00e8f 100644--- a/desktop/lib/core/guest_folders.dart+++ b/desktop/lib/core/guest_folders.dart@@ -5,6 +5,10 @@ library;import 'package:flutter/foundation.dart';+/// Whether [path] is absolute on the machine being shared: POSIX `/…`, or a Windows drive `C:\\…`.+bool isAbsoluteGuestPath(String path) =>+ path.startsWith('/') || RegExp(r'^[A-Za-z]:[\\/]').hasMatch(path);+@immutableclass GuestFolder {const GuestFolder({required this.path, required this.write});@@ -29,7 +33,7 @@ class GuestFolders {for (final folder in json['folders'] as List? ?? const [])if (folder is Map &&folder['path'] is String &&- (folder['path'] as String).startsWith('/'))+ isAbsoluteGuestPath(folder['path'] as String))GuestFolder(path: folder['path'] as String,write: folder['write'] == true,diff --git a/desktop/lib/widgets/machine_sharing_form.dart b/desktop/lib/widgets/machine_sharing_form.dartindex ff05c574d..ab9231f34 100644--- a/desktop/lib/widgets/machine_sharing_form.dart+++ b/desktop/lib/widgets/machine_sharing_form.dart@@ -451,7 +451,7 @@ class MachineSharingFormState extends State<MachineSharingForm> {Future<String?> _pickFolder(BuildContext context) {final typed = _folderValue.text.trim();- final start = typed.startsWith('/') ? typed : null;+ final start = isAbsoluteGuestPath(typed) ? typed : null;return app.stateOf(widget.machineId)?.isLocalMachine == true? whileNativePicker(() => getDirectoryPath(@@ -488,13 +488,14 @@ class MachineSharingFormState extends State<MachineSharingForm> {await _chooseFolder();return;}- final path = typed.length > 1 && typed.endsWith('/')+ // The folder itself, whichever separator this machine writes (`/` on macOS and Linux, `\` on Windows).+ final path = typed.length > 1 && (typed.endsWith('/') || typed.endsWith('\\'))? typed.substring(0, typed.length - 1): typed;String? problem;- if (!path.startsWith('/')) {+ if (!isAbsoluteGuestPath(path)) {problem =- 'Enter the folder’s full path on $_name, like /Users/you/project.';+ 'Enter the folder’s full path on $_name, like /Users/you/project or C:\\Users\\you\\project.';} else if (_folders.any((folder) => folder.path == path)) {problem = '${_folderName(path)} is already shared.';} else if (_folders.length >= machineSharedFoldersMax) {@@ -1388,12 +1389,12 @@ class MachineSharingFormState extends State<MachineSharingForm> {/// A folder's own name: what a person recognises it by.String _folderName(String path) {- final parts = path.split('/').where((part) => part.isNotEmpty);+ final parts = path.split(RegExp(r'[\\/]')).where((part) => part.isNotEmpty);return parts.isEmpty ? '/' : parts.last;}/// Where it is: the folder that holds it.String _folderParent(String path) {- final cut = path.lastIndexOf('/');+ final cut = path.lastIndexOf(RegExp(r'[\\/]'));return cut <= 0 ? '/' : path.substring(0, cut);}diff --git a/desktop/test/guest_folders_windows_test.dart b/desktop/test/guest_folders_windows_test.dartnew file mode 100644index 000000000..cf5353829--- /dev/null+++ b/desktop/test/guest_folders_windows_test.dart@@ -0,0 +1,30 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/guest_folders.dart';++void main() {+ test('a Windows machine keeps its workspace and folders, not only POSIX paths', () {+ final places = GuestFolders.fromJson({+ 'workspace': r'C:\Users\hg_0123456789ab\work',+ 'folders': [+ {'path': r'C:\Users\DELL\project', 'write': true},+ {'path': r'D:\docs', 'write': false},+ {'path': '/Users/owner/mac-project', 'write': false},+ {'path': 'relative', 'write': false},+ ],+ });+ expect(places.workspace, r'C:\Users\hg_0123456789ab\work');+ expect(places.folders.map((folder) => (folder.path, folder.write)), [+ (r'C:\Users\DELL\project', true),+ (r'D:\docs', false),+ ('/Users/owner/mac-project', false),+ ]);+ });++ test('the shared form accepts either absolute shape', () {+ expect(isAbsoluteGuestPath(r'C:\Users\owner\project'), isTrue);+ expect(isAbsoluteGuestPath('D:/work'), isTrue);+ expect(isAbsoluteGuestPath('/Users/owner/project'), isTrue);+ expect(isAbsoluteGuestPath(r'Users\owner'), isFalse);+ expect(isAbsoluteGuestPath('project'), isFalse);+ });+}diff --git a/docs/superpowers/specs/2026-11-05-windows-guests-design.md b/docs/superpowers/specs/2026-11-05-windows-guests-design.mdnew file mode 100644index 000000000..ea1d6e63c--- /dev/null+++ b/docs/superpowers/specs/2026-11-05-windows-guests-design.md@@ -0,0 +1,512 @@+# Windows guest machine sharing — design++**Status:** foundation implemented (`guestShare`, `guestRequests`, `guestSetupClient`, 28 tests); the+elevated setup script, relay/hook split, guest host and UI are tracked in tasks #7, #10, #12 and #11.+**Date:** 2026-11-05+**Related:** [guest machine sharing plan](../../plans/2026-10-19-guest-machine-sharing-plan.md),+[Windows parity plan](../plans/2026-11-04-windows-parity.md) Task 15, [Windows rules](../../windows-rules.md).++## Goal++A person on Windows can share **this computer** with named people (email, or everyone at a+domain) exactly as a Mac can:++- each guest's harnesses run as **their own Windows user**, never the owner's;+- a guest cannot read the owner's files, logins, harnesses, or another guest's;+- guests can use the owner's **Claude and Codex subscription** through the owner's relay;+- the owner shares **specific folders**, read-only or read-write, and nothing else;+- the owner approves **once** with a UAC prompt; guests are never prompted;+- the machine card where work is assigned shows **Claude Code and Codex details** (installed,+ signed in, subscription), as the Mac's Share form does.++## Non-goals++- Full owner rights (removed on every platform, 2026-10-19).+- Guest device pairing, per-person limits/approval/activity views, Store apps or web panes.+- Any change to macOS or Linux behavior, or to the existing Windows **Team account**+ (`harnessteam`, for teammates' Swarm agents).+- Extending guests to the Team account or to a second machine from the same guest.++## What exists today++### macOS / Linux (the model to match)++- One guest per email: OS user `hg_<12 hex>` (`cli/src/lib/guestAccounts.ts`), created on first+ use by a root helper. The owner approves **once**; the helper + sudoers drop-in then run+ without a password (`cli/src/lib/guestHelperInstall.ts`).+- A guest pane lives in the owner's tmux, but the engine runs as the guest:+ `sudo -n helper run <user> --cwd … --pass KEY … -- <argv>` with an allowlisted environment+ (`guestRunCommand`, `cli/lib/guestPaneCommand.ts`).+- Shared folders are ACLs on exactly those folders (`shareFolders`); the helper also adds+ search-only entries on the closed parents. It records what it granted, changes only the+ difference, and removes a guest's entries when sharing with them ends.+- The subscription relay is loopback HTTP with a per-guest bearer token; Claude gets+ `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN`, Codex a `harness_owner` provider+ (`cli/src/lib/subscriptionRelay.ts`, `services/guestLaunches.ts`).+- The core and gateway enforce a default-deny guest policy, per-agent ownership, no group-key+ broadcasts, a loopback credential, and only Claude Code/Codex launches+ (`cli/src/core/guestPolicy.ts`, `backendSocket.ts`, `gateway/gateway.ts`).+- Guest harnesses cannot be restarted, resumed, forked or retargeted; a guest starts a new one.++### Windows today++- The **Team account** works: `harnessteam`, a standard local user (Users only, never+ Administrators), a random password known only to Task Scheduler, its own profile and task,+ hidden from the sign-in screen, with ACL and privacy probes+ (`cli/src/team/windowsScript.ts`, `windowsTeam.ts`).+- **Guest sharing is explicitly unsupported**: `installGuestHelper` returns+ `UNSUPPORTED` — “Sharing this computer needs macOS or Linux.”+ (`cli/src/lib/guestHelperInstall.ts:131`), so the Share form has no folder picker and no+ per-guest engine details on Windows.+- Parity Task 15 records the gap: a spike (“can one daemon drive panes on a second+ `harness-pty` in another account?”), a design with a Design section, a named security+ review, then code.++## Verified Windows constraints++| Constraint | Consequence |+|---|---|+| No sudo; elevation is a UAC consent (`Start-Process -Verb RunAs`) | One prompt at setup; **no prompt per guest or per harness** |+| `New-LocalUser` + a profile under `C:\Users\<user>` | Guest home is OS-created; ACL it to the guest, SYSTEM, Administrators only |+| A standard user (Users SID `S-1-5-32-545`), never Administrators (`…-544`) | Same “least privilege” rule as the Team account |+| Random password in Task Scheduler's LSA secret, never in a file or argv | The guest host can run as the guest without the owner holding a password |+| Task Scheduler `LogonType=Password`, `RunLevel=LeastPrivilege` | Per-guest host can run in a non-interactive session (session 0) |+| `SpecialAccounts\UserList` hides an account from the sign-in screen | Guest accounts stay invisible, as the Team account does |+| Smart App Control blocks unsigned executables | Only Microsoft/OpenJS/signed Harness binaries; scripts run by signed `powershell.exe` |+| Loopback TCP carries no credential on Windows | The daemon identifies the caller by the connecting process's SID (`lib/peerAccount.ts`) and refuses another account. The guest relay and hook must be a **deliberate, token-authenticated exception** to that check, or guests can reach the owner's API |+| Reparse points/junctions are followed by naive ACL tools | Refuse them when sharing; never grant through a link |+| Profiles can be locked at delete time (`PendingFileRenameOperations`) | Unshare must report “restart to finish”, as the Team remove does |++## Architecture++### Recommended: a per-guest harness host (Option B)++```+ owner (DELL) guest (hg_<12hex>)+ ┌─────────────────────────────┐ ┌──────────────────────────────┐+ │ Harness Desktop / core │ authenticated│ harness-pty.exe (as guest) │+ │ • guest policy │ named pipe │ • ConPTY panes │+ │ • relay 127.0.0.1:<port> ├──────────────►│ • engine = claude / codex │+ │ • hook + local credential │ │ • cwd = workspace/shared │+ └──────────────┬──────────────┘ └──────────────┬───────────────┘+ │ owner's link (ACL'd file) │ env: relay token,+ ▼ ▼ hook token+ C:\ProgramData\Harness\… C:\Users\hg_x\work+```++Why: the OS enforces the identity. The owner's process never holds a guest password, the+guest's engine is a child of a process already running as the guest. The core already supports+several pty host versions/instances and host-scoped `create`/`respawn` (`ptyHosts`,+`PtyHostDrain`, `lib/ptyHost/protocol.ts`); a host in **another OS account** is exactly what the+spike must prove, not an existing capability. It mirrors the proven Team account.++The **spike must prove** the parts the code does not yet prove: a second host in another+account at session 0, its pipe authentication, upgrade/restart, and the desktop attaching to+its panes. If the spike fails, fall back to Option A (below), not to a half-built B.++### Alternatives considered++- **Option A — owner host + a privileged token broker.** The owner's `harness-pty` creates the+ engine with `CreateProcessWithLogonW`/`CreateProcessAsUser`. This needs a new **signed**+ service or helper holding guest credentials (DPAPI) and a much larger privileged surface.+ Kept as a fallback only if B cannot attach a guest host to the desktop.+- **Option C — a full Harness daemon per guest.** Duplicates supervision, updates, ports and+ logs for no extra isolation over B. Rejected.++### Setup: one UAC prompt, then no prompts++One elevated PowerShell script, staged in a folder only the owner and SYSTEM can change,+values validated and single-quoted like `windowsScript.ts` (no string interpolation of input),+idempotent on every step:++1. A local group **Harness Guests** (members are added per guest; never Administrators).+2. `C:\ProgramData\HarnessGuests\` — scripts, the shared **Node runtime** (signed OpenJS+ `node.exe`), the hook script, request/response folders. ACL: SYSTEM/Administrators full,+ the owner's user read (and write only to the request folder), guests traversal only.+ **Not `C:\ProgramData\Harness`:** that folder is readable by `Users` for the Team account+ (`team.json`, its status and relay), and every guest is in `Users`; a guest subtree there+ would let a guest read the owner's Team relay. The guest root is its own tree.+3. A **guest setup task** running as SYSTEM, startable by the owner without elevation (its+ task security descriptor grants the owner), which performs only a fixed, validated set:+ `ensure <email>`, `remove <user>`, `share <user> <read|write> <path>`, `unshare <user>`.+ Requests and answers are files in ACL'd folders, never a command line from the owner.+4. A **guest host task template** (`\Harness\Guests\…`) registered on first use with+ `LogonType=Password`, `RunLevel=LeastPrivilege`, hidden; its SD lets the owner start/stop it.+5. The relay/hook runtime is the owner's; nothing privileged listens for guests beyond the+ existing loopback relay.++Two boundaries make this safe, and both need a test:++- **The task can be started without elevation.** Its security descriptor grants the owner+ Start/Stop and denies guests. If Windows will not give a non-admin task that SD, the design+ stops here: per-guest UAC is not acceptable.+- **The prompt is once per setup version, not once ever.** A helper/runtime update changes the+ version and the form asks the owner to turn sharing on again (one UAC prompt); guests still+ never see one. Say so in the form.+- **No time-of-check/time-of-use hole.** Each request is a file with a random id in a folder+ guests cannot write (owner write, SYSTEM full, guests none); the SYSTEM task reads one+ validated operation and arguments, writes one answer to an ACL'd answer file, and deletes the+ request. It never runs a command line from a mutable file; `MultipleInstances=IgnoreNew`+ refuses a second start; a request naming another owner/guest is refused.++Why a setup task, not a service: no new privileged executable, no always-on surface; it uses+the same signed `powershell.exe`/`node.exe` and the Team account's proven task model. The+request/answer folders are the boundary and must be ACL-tested.++### Guest account++- Name `hg_<12 hex of sha256(lowercase email)>` (same derivation as+ `cli/src/lib/guestAccounts.ts`, so the two platforms agree in tests).+- `New-LocalUser` standard, `-PasswordNeverExpires -AccountNeverExpires -UserMayNotChangePassword`,+ random 40-char password (same generator as the Team script), hidden through+ `SpecialAccounts\UserList`, added to **Users** and **Harness Guests**, never Administrators.+- Profile `C:\Users\hg_x` (OS-created); ACL: guest full, SYSTEM/Administrators full, no `Users`+ access, no inheritance from the owner's home. Workspace `C:\Users\hg_x\work`.+ **Order matters:** `New-LocalUser` creates no profile. The setup task first runs a one-shot+ task as the guest to create the profile, reads the real `Win32_UserProfile.LocalPath` (Windows+ may suffix it), and only then creates/ACLs `work`. A profile it cannot create, or one that is+ not exactly `C:\Users\hg_x`, is refused before anything is shared.+- Delete on unshare: stop the host task and its job object, remove ACLs and tasks, remove the+ user and `Win32_UserProfile`, then report a profile Windows could not release.++### Panes and launches++- A guest harness is started only by the guest policy: Claude Code or Codex, a new harness,+ first message as the engine's argument.+- The guest host creates a ConPTY pane and runs the engine directly as the guest:+ - `cwd`: the guest workspace, or a folder the owner shared (checked by the setup record);+ - env **allowlist**: `TERM`, `COLORTERM`, `LANG`, relay vars, hook vars, `HARNESS_AGENT_ID`;+ no owner `PATH`, `HOME`, `USERPROFILE`, keys or launch script;+ - the shell after exit is the guest's own `cmd.exe`/PowerShell, not the owner's.+- No restart/resume/fork/retarget/restore of a guest row (same refusals as macOS); the guest+ starts a new harness.+- Engine installs run inside the guest's pane on first use, using the shared Node runtime and+ the guest's writable `%USERPROFILE%\.local`; the guest sees progress.++### Guest-host routing, registry and restore++The existing create path (`core/agents/create.ts` → `createAndRegisterPane` → the owner's+`tmuxBackend`) opens panes on the **owner's** host. A guest needs a different host, and this is a+core change, not only a new module:++- A guest row records the host instance (the guest's pipe) in its registry entry; `guestCreate`+ and every later terminal request resolve that host, never the owner's.+- Restore, restart, resume, fork and retarget must **skip/refuse** a row with `guest` (the same+ refusals macOS has). Restore must not rebuild a guest pane as the owner — that is the worst+ possible failure, and it is a test of its own.+- A host that is not running is started by the owner's daemon through the guest's task and+ waited for with a bounded timeout; a failure says which step failed and leaves the row stopped,+ not “starting” forever.++### Host lifecycle and updates++- A guest host is pinned to the CLI/pty version that started it. A CLI or pty update stops each+ guest host through the existing drain (or asks it to shut down when empty).+- A running guest harness **ends** on that restart (guest rows cannot be resumed), and the guest+ starts a new one; the chat says so before it happens.+- A guest host that is missing, outdated or refuses its pipe is reported in the machine card; it+ is never silently replaced by the owner's host.++### Shared folders++- Owner picks folders; each is **read** or **editable** (max 20, as macOS).+- Grant the guest's **SID** (never a name), replacing our own ACE only: `icacls "<path>"+ /grant:r "*<sid>:(OI)(CI)(RX)"` for read (a directory needs `RX`, not bare `R`) or+ `(OI)(CI)M` for edit; **never** `F`. No `/T`: inheritance carries the one ACE.+- Traverse only: each parent up to the drive root gets `(X)` for the guest, recorded as an+ *entry of its own* so unshare removes exactly what was added. No list on parents.+- Refuse: reparse points/junctions anywhere on the path, a path that resolves outside the+ owner's profile/drive rules, system roots (`C:\`, `C:\Windows`, `Program Files*`), another+ user's profile, and paths with invalid characters.+- **A folder inside the owner's profile is the hard case.** Windows evaluates deny ACEs before+ allow, and the owner's profile may remove or deny `Users`/`Authenticated Users`; an allow for+ the guest SID cannot override a deny. The spike must share a real folder under+ `C:\Users\<owner>` with the profile's actual ACL. If the guest cannot traverse, shared folders+ are restricted to a dedicated root outside user profiles (for example+ `C:\ProgramData\Harness\Shared`) instead of weakening the owner's profile.+- The setup task keeps a root/SYSTEM-owned record of every grant (path, SID, level); a second+ share changes only the difference; unshare removes only recorded ACEs and leaves the owner's.+- A large folder propagates for minutes; the form says so, the operation is cancellable, and+ the sharing read waits for it (same known gap as macOS).+- A guest asks `guest_folders` for its workspace and the folders; New Harness offers them;+ a harness may start in one only when the record says it is shared with that guest.++### Relay and hooks++- The owner's relay stays loopback-only (`127.0.0.1`), per-guest bearer tokens minted in+ memory, revoked when the share ends. It swaps in the owner's tokens; guests never see them.+- **Listener split:** Windows refuses a loopback caller from another account by SID+ (`lib/peerAccount.ts`). The relay and the hook are therefore their own listener (or explicitly+ exempt routes) that accept a guest SID **only** when it presents a live per-guest token; every+ other loopback route keeps the owner-SID check. A test proves a guest can reach the relay and+ cannot reach `/api/status` or the local WS.+- Claude: `ANTHROPIC_BASE_URL=http://127.0.0.1:<port>/claude`, `ANTHROPIC_AUTH_TOKEN=<guest token>`.+ Codex: `-c model_provider="harness_owner" …`, `env_key=HARNESS_RELAY_TOKEN`.+- The guest's engine gets a **guest-scoped hook token** (`HARNESS_HOOK_TOKEN`) and the shared+ `notify.mjs`; the owner's daemon validates token + agent id. Known gap (turn status) is the+ same as macOS and is not widened.+- Loopback has no user identity on Windows, so the relay must reject anything without a live+ guest token; the owner's local credential (ACL'd file) protects every other local route.++### UI++- **Share form (Windows)** — same as macOS: emails/domain, guest access on (one UAC prompt),+ folders read/edit, engines Claude Code and Codex with their state, and the warning that a+ shared folder's contents are readable. Remove the “needs macOS or Linux” refusal.+- **Machine/assignment card** — below the machine, show each engine: installed, signed in,+ using the owner's subscription, and its last check (the data the Team status already prints).+ A guest sees only its own engines and subscription.+- **Guest view** — “Guest · shared by <owner>”; only its own harnesses; no devices, settings,+ share, folder browsing outside its workspace/shared folders, or model management.+- Every failure names the step and the next action (UAC cancelled, folder refused, profile+ locked, engine install failed).++## Security model++| Trust boundary | Who crosses it | Control |+|---|---|---|+| Owner ↔ guest files | guest processes | NTFS ACLs on the profile; traverse-only on parents (optional) |+| Owner ↔ guest harnesses | guest API clients | default-deny policy, per-agent ownership, loopback credential |+| Guest ↔ subscription | guest env | per-guest relay token, revoked on unshare; owner tokens never leave the relay |+| Guest ↔ other guest | same machine | separate SIDs, separate profiles, separate host tasks, per-email tokens |+| Owner ↔ privileged setup | UAC | one explicit consent; staged, validated, idempotent script |+| Guest ↔ elevation | UAC | standard user; no admin group; no service the guest can ask |++Threats and answers:++1. **Read the owner's files.** Profile ACL denies Users; no traverse granted except shared+ paths' parents; reparse points refused; privacy probes run on every sharing read.+2. **Become administrator.** Users only; setup script asserts the account is not in+ Administrators; UAC cannot be triggered silently by a hidden account.+3. **Impersonate the owner on loopback.** The relay requires a guest token; the local+ credential file is ACL'd to the owner+SYSTEM; guest processes are refused every other route.+4. **Read another guest.** Separate SIDs/profiles/tasks; tokens per email; no shared group read.+5. **Escape through a link.** `icacls` never follows a reparse point when we grant; the path is+ resolved and refused if any component is one.+6. **Leave access behind.** Grants recorded by SID and path; unshare removes only ours; a test+ proves a guest loses access after unshare.+7. **Steal a task password.** The password lives only in Task Scheduler's LSA secret and is+ generated inside the elevated script; never printed, logged, written, or on a command line.+8. **Blocked unsigned binary.** Only signed binaries; the setup script is text under+ `C:\ProgramData\Harness` (ACL'd) run by signed `powershell.exe`/`node.exe`.+9. **Resource abuse.** 20 folders, guest cap, engine install timeout, share operation+ cancellable; logs name the guest user, never the email or a path.++## Design checklist (AGENTS)++- **Growth:** one account, profile, host task and ACE set per active guest; all removed when+ the share ends or the owner turns sharing off; no unbounded list (cap guests and folders).+ The setup record is the source of truth for deletion.+- **Concurrency:** one `ensure` per email (same in-memory promise pattern as macOS); one+ share operation per user serialized; ACL changes serialized per folder; task registration+ idempotent; a second setup task start is refused by the task's `MultipleInstances=IgnoreNew`.+- **Read cost:** a sharing read touches only the policy and the setup record; no owner file is+ read; `guest_folders` answers one guest only; engine probes stay at their existing cadence.+- **Scale:** 10× today's guests (tens, not hundreds). The first limit to show is the number of+ hidden accounts/tasks (Windows sign-in and Task Scheduler) and profile disk; a metric warns+ before that. One host per guest, not per harness.+- **Compatibility:** Windows-only modules behind `platform === 'win32'`; macOS/Linux paths are+ not touched; an older CLI without this feature keeps answering `UNSUPPORTED`; the backend+ keeps enforcing who may ask. The Team account and its files are unchanged.+- **Migration and rollback:** no existing Windows guests — the first share creates everything.+ A feature flag (`HARNESS_WINDOWS_GUESTS=0`) turns the form back to unsupported; rollback runs+ the same unshare/remove path for every recorded guest, then deletes the group and+ `C:\ProgramData\Harness\guests`. macOS/Linux rollback is “do nothing”.+- **Audience:** the daemon enforces guest identity from the relay/gateway; the server never+ trusts a client's claim about who it is.+- **Identity:** guest email → account name → SID; never the owner's login, profile or token;+ the owner's Windows account is not used for guest work.+- **Failure:** every step answers with the failing step and a next action; a cancelled UAC,+ refused folder, locked profile, blocked engine and uninstalled helper each have their own+ sentence; nothing fails silently.+- **Platforms:** Windows 10/11 x64 and ARM64; Smart App Control on; no Store apps or web panes;+ macOS and Linux keep their current behavior byte for byte.++## Data and APIs (planned)++- `SharedFolder { path: string; write: boolean }` (unchanged).+- `GuestAccount { user: 'hg_<12hex>'; home: 'C:\Users\hg_x'; workspace: '…\work' }`.+- Setup requests: `ensure <email>`, `remove <user>`, `share <user> <read|write> <path>`,+ `unshare <user>`; answers JSON `{ ok, user, home, workspace, detail? }`.+- New Windows module(s): `lib/windows/guestAccounts.ts`, `lib/windows/guestSetup.ts`,+ `lib/windows/guestHost.ts`; `guestHelperInstall.ts` gains a `win32` branch instead of+ returning `UNSUPPORTED`; `sharedMachines.ts` and the UI use the same ports they already use.+- No change to `GuestLaunchInput`/`GuestLaunch`, the policy, or the relay contract.++## Spike (must pass before code)++On the PC, in a throwaway Windows account, with a signed build:++1. Start `harness-pty.exe` as a hidden standard user from a scheduled task at session 0; can+ the owner's core create and read a pane over an authenticated pipe? Does the desktop attach?+2. Can the owner start that task without elevation (task SD)? Can the guest's processes be+ killed without leftovers (job object)?+3. `icacls` grants and removals for a guest SID on a nested folder, with traverse-only parents;+ unshare leaves no access.+4. Do Claude Code and Codex install and run as the guest with the shared Node runtime and the+ relay? Does npm work there?+5. Does the guest's engine reach the loopback relay, and does the owner's daemon reject a+ request without the guest token?+6. Does unshare delete the profile, or leave `PendingFileRenameOperations`? What does the form+ say?+7. Smart App Control: are all started binaries allowed, and does the event log stay empty?++Record each answer in this document before implementation. If (1) fails, stop and design+Option A properly; do not ship a partial guest feature.++## Test plan++- **Unit:** account-name derivation, setup request validation, ACL argument building (SIDs,+ read/edit, traverse), reparse refusal, record/removal diff, policy identity, sizes/caps.+- **Windows integration (VM, two accounts):** create → launch a pane as the guest → the owner's+ profile is unreadable → a shared read folder is readable, write folder writable, another+ folder is not → unshare → no access and no account/task left.+- **Failure injection:** UAC cancelled, task refused, locked profile, link in the path, engine+ install fails, relay down.+- **Regression:** macOS/Linux guest e2e (`cli/e2e/sharedMachines.e2e.ts`), the Team account+ tests, and the normal Windows CLI/desktop suites stay green.+- **Manual, on the PC:** one UAC prompt on first share; a guest harness answers; Explorer shows+ only the shared folder; after unshare Windows shows nothing of the guest.+- **Acceptance:** the Mac's “What a guest can do” table holds on Windows line for line.++## Rollout++1. Spike + this design reviewed by a named security reviewer.+2. Implementation behind the flag; Windows-only modules and tests.+3. Manual PC pass; then the form is enabled for everyone; the flag stays for rollback one+ release.+4. If anything is wrong, roll back with the flag and run the recorded unshare/remove path;+ macOS/Linux are unaffected.++## Review findings (2026-11-05)++Re-reading the plan against the code found these. Each is either corrected above or is a gate+before implementation.++### Critical++1. **The guest relay/hook cannot use the owner's loopback door.** On Windows the daemon sets+ the local credential and, with it, asks Windows who owns the caller's process+ (`localWsServer.ts`, `hookServer.ts`, `lib/peerAccount.ts`); a guest is another account and+ is refused. But the guest's engine **must** reach the relay and the hook. They need their own+ listener (or exempt routes) that accepts a guest SID only with a live per-guest token, while+ every owner route keeps the SID check. Without the split, guests either cannot use the+ subscription or can reach the owner's API. Corrected in “Relay and hooks”; test both+ directions.+2. **A folder inside the owner's profile may be unshareable.** Deny ACEs beat an allow; the+ profile's real ACL is the test. Fallback: a dedicated shared root outside profiles. Corrected+ in “Shared folders”.+3. **`New-LocalUser` makes no profile.** Workspace/ACL work before the first logon fails.+ Corrected with the create-profile-first order.+4. **Guest rows need a host, and restore must never use the owner's.** The create path currently+ targets the owner's `tmuxBackend`; a guest row must carry its host instance, and+ restore/restart/resume must refuse it. This is a core change, now its own section.+5. **The setup and host tasks must start without elevation.** If a non-admin task SD cannot+ grant Start/Stop, the owner is prompted per guest — unacceptable. Gate before code.++### High++6. **Host updates.** A pty/CLI update ends running guest harnesses (they cannot resume) and each+ guest host must be drained and replaced. Now stated, with the copy the guest sees.+7. **Setup request TOCTOU.** A SYSTEM task reading a file must take one validated operation from+ an ACL'd, unguessable request and write one ACL'd answer; a guest must not write either. Now+ stated.+8. **`icacls` read is `RX`, not `R`, and grants must replace our own ACE (`/grant:r`, no `/T`).**+ Corrected.+9. **Prompt recurrence after an update.** Corrected: once per setup version.+10. **Shared folders vs `fs_list_dir`.** The Mac policy allows `fs_list_dir` only inside the+ workspace; with shared folders, New Harness must offer them and the policy must allow+ exactly those paths, not all of them. Add to the policy work.+11. **Engine details before the first harness.** The machine card needs the guest's engine state+ (installed/signed in). Probing as the guest needs a host/task; otherwise the form shows the+ setup record, not a live probe. Decide in the UI task.+12. **A guest can occupy the owner API's peer-lookup slots** (four at once, 32 waiting) by+ connecting to the owner's port; the SID lookup refuses it, but the owner's own clients can+ queue behind it. The separate relay/hook listener keeps the hot path apart; add a per-source+ bound or a fast refusal for a guest SID in the owner API.++### Medium++13. **Host token file.** The pipe token must live in an ACL'd file (owner + SYSTEM) and the+ guest must not be able to modify it; the guest host's task SD must deny the guest.+14. **Unshare cleanup.** Stop the host and its job, remove only recorded ACEs/tasks/UserList,+ delete the profile (or say “restart to finish”), then remove the account; a test proves no+ access remains.+15. **Windows path UI.** Drive letters, backslashes, a picker that works on the machine being+ shared, and local fixed drives only; the Mac form's `/Users/...` example does not apply.+16. **Do not weaken the owner profile.** No blanket `Users` grant and no removing deny ACEs to+ make a folder work; the dedicated shared root is the safe fallback.+17. **The Team account.** Guests join `Users`; verify `harnessteam`'s profile and the guests'+ profiles cannot list each other, and that the Team task/ACLs are untouched.+18. **Firewall/Defender.** Only loopback listeners; no inbound rule; confirm no Windows Firewall+ prompt is added by the guest host.++### Missed security controls (second pass)++These are not in the first threat table and must be in the implementation.++1. **Pipes, not only TCP.** The owner's daemon pipe, the pty host pipes and a guest+ host's pipe are separate doors. Each must have an ACL and token that deny another+ account (including another guest); test a guest opening the owner's pipe and the Team+ account's pipe/port. A pipe is not covered by the loopback SID check.+2. **Cross-feature secrets.** The Windows PC also has the **Team account** and its+ `C:\ProgramData\Harness\team-relay-*` (the owner's subscription relay) and `team.json`.+ A guest must not read `C:\Users\harnessteam`, the team relay folder, the team status+ files, or any Harness GitHub-App token. Audit the existing `C:\ProgramData\Harness`+ ACLs; a guest in `Users` must be denied, and the Team account/tasks must stay untouched.+ The guest tree is therefore **`C:\ProgramData\HarnessGuests`**, never a subtree of the+ Team folder: an inherited `Users` read on the parent would expose `team.json` and the+ relay even if the guest folder itself was tight.+3. **A guest privacy sentinel.** As the Team account has: a file in the owner's profile the+ guest must not read. Check it on every sharing read and after any ACL change; if a guest+ can read it, turn sharing off and say so. The document says “privacy probes” without+ defining the guest's; this is it.+4. **The relay is not an open proxy.** A guest token must allow only the fixed upstream+ paths and methods the engine needs (Claude messages, Codex responses), with bounded+ bodies, no arbitrary headers or hosts. Otherwise a guest uses the owner's token for+ anything the vendor accepts. Also bind tokens to one guest and one agent.+5. **Guest-created reparse points.** A guest with **write** to a shared folder can create a+ junction inside it (directory junctions are not always privileged). The owner's process+ could then follow it into the owner's files. Refuse/scan reparse points in shared+ folders; re-check on each sharing read and before a harness starts there.+6. **A writable shared folder is untrusted code.** A harness started in it reads the+ guest's files: hooks, `AGENTS.md`, project scripts, a malicious `git` config. Warn the+ owner explicitly; default to **read-only** folders; never auto-approve in a shared+ folder; the engine's permission mode is the owner's.+7. **Hook token binding.** A guest hook token must resolve to exactly one guest and one+ agent; a token cannot report a turn, an alert or a stop for another agent. Test a token+ from guest A naming guest B's agent.+8. **No owner secret in argv, machine-wide env, or a task action.** A guest can query+ `Win32_Process` command lines and task actions, and inherits **machine-wide** environment+ variables. Audit `C:\ProgramData` and HKLM for anything Harness adds; keep relay and+ subscription tokens in memory only.+9. **Port squatting.** On a restart a guest can bind the owner's loopback port first. The+ owner's clients on Windows use the pipe and send no TCP credential; verify no client+ (especially an older one) sends it over TCP, and that a port held by a guest is detected+ and moved off (`portHolderIsThisAccount`), as the Team boundary already does.+10. **Server-side enforcement and audit.** The backend must enforce guest identity for+ starts/messages as macOS does, not only the desktop UI. Log each guest action with the+ guest SID/user and the agent id, never the email or a secret; the owner can see it.+11. **Abuse and resource use.** One guest can spend the owner's subscription, CPU, disk and+ the 20-folder limit. The owner accepts the subscription risk; add a per-guest log and an+ optional rate limit, and keep the folder/guest caps.+12. **Task tampering.** A guest must have no write/change right on its host task (only the+ owner and SYSTEM); otherwise it could change the action, the principal or the token.+ Test the task SD from a guest token.++## No-break guarantees++- Every Windows branch is new code; existing macOS/Linux guest code paths are untouched.+- The Team account (`harnessteam`) and its task/ACLs are not modified; guests use `hg_*`.+- A machine that has never shared on Windows behaves exactly as today (`UNSUPPORTED`).+- The release is gated on the existing OS-specific suites plus the new Windows tests.++## Open questions++- Per-guest host vs. token broker: resolved by spike question 1.+- Where the guest profile lives (default `C:\Users` vs a redirected profile root): default is+ safer with Windows tools; revisit only if the sign-in list or disk says otherwise.+- How a guest sees engine state before its first harness (probe as the guest, or the setup+ record's cache) — needs a UX decision.+- Whether a shared folder may be on another drive or a network path: propose “local fixed+ drives only” first.diff --git a/pty/src/instance.rs b/pty/src/instance.rsindex 7e08a18aa..af80091fe 100644--- a/pty/src/instance.rs+++ b/pty/src/instance.rs@@ -37,9 +37,30 @@ pub fn instance_name(protocol: u32, version: &str) -> String {}}-/// This build's instance.+/// This build's instance, plus an optional tag from the environment: a guest's host runs in another account's home+/// with the same binary, so without its own tag its instance, and every pane route keyed by it, would be the owner's+/// (docs/superpowers/specs/2026-11-05-windows-guests-design.md). The task that starts a guest host sets it; every+/// other host leaves it unset, and keeps the plain name.+pub const INSTANCE_TAG_VAR: &str = "HARNESS_PTY_INSTANCE_TAG";++/// The tag [INSTANCE_TAG_VAR] names, when it is one: `[A-Za-z0-9-]{1,16}`, so it stays safe in a file name, a pipe+/// name, a socket path and `HARNESS_PANE`. Anything else is ignored (the host keeps its own instance).+fn instance_tag() -> Option<String> {+ let tag = std::env::var(INSTANCE_TAG_VAR).ok()?;+ let good = (1..=16).contains(&tag.len())+ && tag+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-');+ good.then_some(tag)+}++/// This build's instance, with the tag a guest host's task gave it.pub fn current() -> String {- instance_name(PROTOCOL, VERSION)+ let base = instance_name(PROTOCOL, VERSION);+ match instance_tag() {+ Some(tag) => format!("{base}-{tag}"),+ None => base,+ }}/// `<run_dir>/pty-host-<instance>.<ext>`.@@ -86,9 +107,30 @@ mod tests {#[test]fn current_is_this_builds_instance() {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());assert_eq!(current(), instance_name(PROTOCOL, VERSION));}+ // The tag is process-global (an environment variable), so the tests that read it take turns.+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++ #[test]+ fn a_tag_names_a_guest_hosts_instance_apart_and_an_unusable_one_is_ignored() {+ let _guard = ENV_LOCK.lock().unwrap_or_else(|error| error.into_inner());+ let base = instance_name(PROTOCOL, VERSION);+ // A guest host runs the same binary in its own account: its tag keeps its instance, and every route keyed by+ // it, apart from the owner's.+ unsafe { std::env::set_var(INSTANCE_TAG_VAR, "gu0123456789ab") };+ assert_eq!(current(), format!("{base}-gu0123456789ab"));+ // A tag is a file name, a pipe name and a socket path: anything else is no tag at all.+ for bad in ["bad tag", "gu_0123456789ab", "", "x".repeat(17).as_str()] {+ unsafe { std::env::set_var(INSTANCE_TAG_VAR, bad) };+ assert_eq!(current(), base, "{bad:?}");+ }+ unsafe { std::env::remove_var(INSTANCE_TAG_VAR) };+ assert_eq!(current(), base);+ }+#[test]fn a_long_home_uses_the_hashed_socket_name() {let instance = "p2-0.4.20";