Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(windows): pty:execute-launch encodes agent launches for the pane's own shell
reviewc38a852cd017
diff --git a/src/core/launch-intent-execute.test.ts b/src/core/launch-intent-execute.test.tsnew file mode 100644index 000000000..9649ba8b5--- /dev/null+++ b/src/core/launch-intent-execute.test.ts@@ -0,0 +1,303 @@+// `pty:execute-launch` — gating, the Windows executable resolver, and the round trip that is the+// point of the whole channel: a prompt full of quote and shell metacharacters must arrive at the+// agent as ONE argv element on every Windows-native dialect. All of it runs on any OS: the planner+// only builds strings, and the argv is recovered here by the same parsers PowerShell and the+// Microsoft CRT apply.+import { describe, expect, it, vi } from 'vitest'+import {+ executeLaunchIntent,+ promptFromFileText,+ resolveWindowsAgentExecutable,+ windowsLaunchDialectForShell,+ windowsPowerShellPath,+ type LaunchIntentDeps,+ type LaunchTarget+} from './launch-intent-execute'+import type { PreparedAgentLaunch } from './agent-launch'+import type { AgentLaunchIntent } from '../shared/types'++const LAUNCH_ID = '123e4567-e89b-42d3-a456-426614174000'+const PS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'+const NPM_DIR = 'C:\\Users\\me\\AppData\\Roaming\\npm'+const NATIVE_DIR = 'C:\\Users\\me\\.local\\bin'++function target(extra: Partial<LaunchTarget> = {}): LaunchTarget {+ return {+ name: 'nt-node-1',+ sessionHost: true,+ remote: false,+ launchDialect: 'pwsh',+ agentId: 'claude',+ pathValue: `${NATIVE_DIR};${NPM_DIR}`,+ ...extra+ }+}++function deps(files: string[], extra: Partial<LaunchIntentDeps> = {}) {+ const plans: Array<{ name: string; launchId: string; plan: PreparedAgentLaunch }> = []+ const set = new Set(files.map((f) => f.toLowerCase()))+ const d: LaunchIntentDeps = {+ platform: 'win32',+ customAgents: () => [],+ sharedIdentityAvailable: async () => false,+ codexCaps: async () => ({ approvalValues: null, noDaemon: null }),+ exists: (candidate) => set.has(candidate.toLowerCase()),+ systemRoot: 'C:\\Windows',+ readPromptFile: async () => {+ throw new Error('no file')+ },+ execute: async (name, launchId, plan) => {+ plans.push({ name, launchId, plan })+ return { status: 'executed' }+ },+ isProtocolIncompatible: () => false,+ ...extra+ }+ return { d, plans }+}++const start = (prompt?: string, extra: Partial<AgentLaunchIntent> = {}): AgentLaunchIntent =>+ ({ kind: 'agent', action: 'start', agentId: 'claude', ...(prompt !== undefined ? { prompt } : {}), ...extra }) as AgentLaunchIntent++/** PowerShell single-quoted string literals, in order. */+function psLiterals(script: string): string[] {+ return [...script.matchAll(/'((?:[^']|'')*)'/gu)].map((m) => m[1].replace(/''/g, "'"))+}++/** CommandLineToArgvW / Microsoft CRT argument parsing for a command line's ARGUMENT part. */+function crtArgv(line: string): string[] {+ const out: string[] = []+ let i = 0+ while (i < line.length) {+ while (line[i] === ' ' || line[i] === '\t') i+++ if (i >= line.length) break+ let arg = ''+ let quoted = false+ for (; i < line.length; i++) {+ const ch = line[i]+ if (!quoted && (ch === ' ' || ch === '\t')) break+ if (ch === '\\') {+ let n = 0+ while (line[i] === '\\') {+ n+++ i+++ }+ if (line[i] === '"') {+ arg += '\\'.repeat(Math.floor(n / 2))+ if (n % 2) arg += '"'+ else quoted = !quoted+ } else {+ arg += '\\'.repeat(n)+ i--+ }+ continue+ }+ if (ch === '"') {+ quoted = !quoted+ continue+ }+ arg += ch+ }+ out.push(arg)+ }+ return out+}++/** The agent argv a prepared PowerShell script runs (native via Start-Process, or a `.ps1`). */+function scriptArgv(script: string): { executable: string; args: string[] } {+ const literals = psLiterals(script)+ if (script.startsWith('& ')) return { executable: literals[0], args: literals.slice(1) }+ expect(script).toMatch(/^\$ntAgent = Start-Process -FilePath '/u)+ return { executable: literals[0], args: literals[1] === undefined ? [] : crtArgv(literals[1]) }+}++function decodeCmd(command: string): string {+ const payload = command.match(/-EncodedCommand ([A-Za-z0-9+/]+=*)$/u)?.[1]+ expect(payload).toBeTruthy()+ return Buffer.from(payload as string, 'base64').toString('utf16le')+}++const NASTY = `it's "quoted" & 100% ^caret | <x> !bang $env:HOME \`tick; 開発`++describe('windowsLaunchDialectForShell', () => {+ it('names only the three Windows-native parsers, by basename, on win32', () => {+ expect(windowsLaunchDialectForShell('C:\\Program Files\\PowerShell\\7\\pwsh.exe', 'win32')).toBe('pwsh')+ expect(windowsLaunchDialectForShell('pwsh', 'win32')).toBe('pwsh')+ expect(windowsLaunchDialectForShell('"C:\\Program Files\\PowerShell\\7\\PWSH.EXE"', 'win32')).toBe('pwsh')+ expect(windowsLaunchDialectForShell(PS, 'win32')).toBe('windows-powershell')+ expect(windowsLaunchDialectForShell('powershell.exe', 'win32')).toBe('windows-powershell')+ expect(windowsLaunchDialectForShell('C:\\Windows\\System32\\cmd.exe', 'win32')).toBe('cmd')+ // Git Bash / WSL / anything else keep the host's dialect UNSET, exactly as before.+ expect(windowsLaunchDialectForShell('C:\\Program Files\\Git\\bin\\bash.exe', 'win32')).toBeUndefined()+ expect(windowsLaunchDialectForShell('wsl.exe', 'win32')).toBeUndefined()+ expect(windowsLaunchDialectForShell('nu.exe', 'win32')).toBeUndefined()+ expect(windowsLaunchDialectForShell(undefined, 'win32')).toBeUndefined()+ })++ it('is always undefined off win32, so a POSIX spawn request is unchanged', () => {+ for (const p of ['darwin', 'linux']) {+ expect(windowsLaunchDialectForShell('pwsh', p)).toBeUndefined()+ expect(windowsLaunchDialectForShell('/bin/zsh', p)).toBeUndefined()+ }+ })+})++describe('resolveWindowsAgentExecutable', () => {+ it('walks PATH in order, preferring a native image, then .ps1, then a batch shim', () => {+ const exists = (files: string[]) => (c: string) => files.includes(c)+ const path = `${NATIVE_DIR};"${NPM_DIR}"`+ expect(+ resolveWindowsAgentExecutable('claude', path, exists([`${NPM_DIR}\\claude.ps1`, `${NPM_DIR}\\claude.cmd`]))+ ).toEqual({ kind: 'powershell-script', executable: `${NPM_DIR}\\claude.ps1` })+ expect(+ resolveWindowsAgentExecutable('claude', path, exists([`${NATIVE_DIR}\\claude.exe`, `${NPM_DIR}\\claude.ps1`]))+ ).toEqual({ kind: 'native', executable: `${NATIVE_DIR}\\claude.exe` })+ expect(resolveWindowsAgentExecutable('claude', path, exists([`${NPM_DIR}\\claude.cmd`]))).toEqual({+ kind: 'cmd-script',+ executable: `${NPM_DIR}\\claude.cmd`+ })+ expect(resolveWindowsAgentExecutable('claude', path, exists([]))).toBeNull()+ })++ it('accepts an absolute path only when it exists, and never a relative one or a UNC dir', () => {+ const exe = 'C:\\Tools\\agent.exe'+ expect(resolveWindowsAgentExecutable(exe, '', (c) => c === exe)).toEqual({ kind: 'native', executable: exe })+ expect(resolveWindowsAgentExecutable('C:\\Tools\\agent', '', (c) => c === exe)).toEqual({ kind: 'native', executable: exe })+ expect(resolveWindowsAgentExecutable('.\\agent.exe', '', () => true)).toBeNull()+ expect(resolveWindowsAgentExecutable('agent', '\\\\server\\share', () => true)).toBeNull()+ })++ it('finds the inbox Windows PowerShell by its fixed system path', () => {+ expect(windowsPowerShellPath('C:\\Windows', (c) => c === PS)).toBe(PS)+ expect(windowsPowerShellPath('C:\\Windows', () => false)).toBeUndefined()+ })+})++describe('executeLaunchIntent gating', () => {+ const request = { launchId: LAUNCH_ID, intent: start('hi') }++ it.each([+ ['a POSIX core', { platform: 'darwin' }, {}],+ ['a Linux core', { platform: 'linux' }, {}],+ ['a tmux session', {}, { sessionHost: false }],+ ['an SSH session', {}, { remote: true }],+ ['a generation with no recorded dialect', {}, { launchDialect: undefined }],+ ['a Git Bash / WSL pane', {}, { launchDialect: 'posix' as const }]+ ])('answers unsupported-shell for %s and never reaches the host', async (_n, d, t) => {+ const { d: base, plans } = deps([`${NATIVE_DIR}\\claude.exe`], d as Partial<LaunchIntentDeps>)+ const execute = vi.fn(base.execute)+ const result = await executeLaunchIntent(target(t), request, { ...base, execute })+ expect(result).toMatchObject({ ok: false, reason: 'unsupported-shell' })+ expect(execute).not.toHaveBeenCalled()+ expect(plans).toHaveLength(0)+ })++ it('answers session-unavailable with no live session', async () => {+ const { d } = deps([])+ expect(await executeLaunchIntent(undefined, request, d)).toMatchObject({ ok: false, reason: 'session-unavailable' })+ })++ it('refuses a malformed request or a foreign owner before anything is resolved', async () => {+ const { d, plans } = deps([`${NATIVE_DIR}\\claude.exe`])+ expect(await executeLaunchIntent(target(), { ...request, launchId: 'x' }, d)).toMatchObject({ reason: 'invalid-intent' })+ expect(await executeLaunchIntent(target(), null, d)).toMatchObject({ reason: 'invalid-intent' })+ expect(await executeLaunchIntent(target({ agentId: undefined }), request, d)).toMatchObject({ reason: 'agent-unavailable' })+ expect(await executeLaunchIntent(target({ agentId: 'codex' }), request, d)).toMatchObject({ reason: 'agent-unavailable' })+ // A raw newline is a command boundary to every Windows parser; the planner refuses it.+ expect(await executeLaunchIntent(target(), { launchId: LAUNCH_ID, intent: start('a\nb') }, d)).toMatchObject({+ reason: 'invalid-intent'+ })+ expect(plans).toHaveLength(0)+ })++ it('reports a .cmd-only install as a pre-delivery refusal (the caller falls back)', async () => {+ const { d, plans } = deps([`${NPM_DIR}\\claude.cmd`])+ expect(await executeLaunchIntent(target(), request, d)).toMatchObject({ ok: false, reason: 'unsupported-shell' })+ expect(plans).toHaveLength(0)+ })++ it('splits host failures: protocol-incompatible is a refusal, anything else may have typed', async () => {+ const files = [`${NATIVE_DIR}\\claude.exe`]+ const v1 = deps(files, { execute: async () => { throw new Error('v1') }, isProtocolIncompatible: () => true })+ expect(await executeLaunchIntent(target(), request, v1.d)).toMatchObject({ reason: 'unsupported-shell' })+ const lost = deps(files, { execute: async () => { throw new Error('lost') } })+ const result = await executeLaunchIntent(target(), request, lost.d)+ expect(result).toEqual({ ok: false, reason: 'delivery-failed', message: expect.any(String) })+ // Never reflects launch material.+ expect(JSON.stringify(result)).not.toContain('claude.exe')+ })+})++describe('executeLaunchIntent round trip', () => {+ it('pwsh + native: the prompt is ONE argv element, byte for byte', async () => {+ const { d, plans } = deps([`${NATIVE_DIR}\\claude.exe`])+ const result = await executeLaunchIntent(+ target(),+ { launchId: LAUNCH_ID, intent: start(NASTY, { permissionMode: 'acceptEdits' }) },+ d+ )+ expect(result).toEqual({ ok: true })+ expect(plans).toHaveLength(1)+ expect(plans[0]).toMatchObject({ name: 'nt-node-1', launchId: LAUNCH_ID })+ expect(scriptArgv(plans[0].plan.command)).toEqual({+ executable: `${NATIVE_DIR}\\claude.exe`,+ args: [NASTY, '--permission-mode', 'acceptEdits']+ })+ })++ it('windows-powershell + .ps1 shim: quoted with doubled apostrophes, never POSIX quoting', async () => {+ const { d, plans } = deps([`${NPM_DIR}\\claude.ps1`])+ await executeLaunchIntent(target({ launchDialect: 'windows-powershell' }), { launchId: LAUNCH_ID, intent: start(NASTY) }, d)+ const { command } = plans[0].plan+ expect(command).not.toContain(`'\\''`)+ expect(scriptArgv(command)).toEqual({ executable: `${NPM_DIR}\\claude.ps1`, args: [NASTY] })+ })++ it('cmd: an ASCII-only outer line whose -EncodedCommand decodes to the same argv', async () => {+ const { d, plans } = deps([`${NATIVE_DIR}\\claude.exe`, PS])+ await executeLaunchIntent(target({ launchDialect: 'cmd' }), { launchId: LAUNCH_ID, intent: start(NASTY) }, d)+ const { command } = plans[0].plan+ expect(command.startsWith(`"${PS}" -NoLogo -NoProfile -EncodedCommand `)).toBe(true)+ expect([...command].every((ch) => ch.charCodeAt(0) <= 0x7f)).toBe(true)+ expect(command).not.toContain('%')+ expect(scriptArgv(decodeCmd(command))).toEqual({ executable: `${NATIVE_DIR}\\claude.exe`, args: [NASTY] })+ })++ it('cmd without the inbox PowerShell refuses rather than interpolating into cmd', async () => {+ const { d, plans } = deps([`${NATIVE_DIR}\\claude.exe`])+ expect(+ await executeLaunchIntent(target({ launchDialect: 'cmd' }), { launchId: LAUNCH_ID, intent: start(NASTY) }, d)+ ).toMatchObject({ reason: 'unsupported-shell' })+ expect(plans).toHaveLength(0)+ })++ it('reads a --prompt-file in core and flattens it to one argument (no `$(cat …)` anywhere)', async () => {+ const file = 'C:\\briefs\\task.md'+ const read = vi.fn(async () => `\uFEFF# Task\r\n\r\nFix it's "bug" & 50%\n`)+ const { d, plans } = deps([`${NATIVE_DIR}\\claude.exe`], { readPromptFile: read })+ expect(await executeLaunchIntent(target(), { launchId: LAUNCH_ID, intent: start(), promptFile: file }, d)).toEqual({ ok: true })+ expect(read).toHaveBeenCalledWith(file, 128 * 1024)+ expect(plans[0].plan.command).not.toContain('$(cat')+ expect(scriptArgv(plans[0].plan.command).args).toEqual([`# Task Fix it's "bug" & 50%`])+ })++ it('refuses a prompt file beside an inline prompt, a relative path, or an unreadable file', async () => {+ const { d, plans } = deps([`${NATIVE_DIR}\\claude.exe`], { readPromptFile: async () => 'x' })+ expect(+ await executeLaunchIntent(target(), { launchId: LAUNCH_ID, intent: start('a'), promptFile: 'C:\\x.md' }, d)+ ).toMatchObject({ reason: 'invalid-intent' })+ expect(+ await executeLaunchIntent(target(), { launchId: LAUNCH_ID, intent: start(), promptFile: 'x.md' }, d)+ ).toMatchObject({ reason: 'invalid-intent' })+ const unreadable = deps([`${NATIVE_DIR}\\claude.exe`])+ expect(+ await executeLaunchIntent(target(), { launchId: LAUNCH_ID, intent: start(), promptFile: 'C:\\x.md' }, unreadable.d)+ ).toMatchObject({ reason: 'invalid-intent' })+ expect(plans).toHaveLength(0)+ expect(unreadable.plans).toHaveLength(0)+ })++ it('collapses prompt-file whitespace like the legacy PowerShell `cat` join did', () => {+ expect(promptFromFileText('\uFEFFa\r\n\tb c\n')).toBe('a b c')+ })+})diff --git a/src/core/launch-intent-execute.ts b/src/core/launch-intent-execute.tsnew file mode 100644index 000000000..4efa14c63--- /dev/null+++ b/src/core/launch-intent-execute.ts@@ -0,0 +1,268 @@+// `pty:execute-launch` — the one production caller of `prepareAgentLaunch` ++// `sessionHostExecuteLaunch`.+//+// WHY: the renderer's legacy launch line is POSIX source (`'it'\''s'`, `"$(cat '<file>')"`). Typed+// into PowerShell or cmd.exe — the shells a Windows session-host pane actually runs — an apostrophe+// breaks the parse, Windows PowerShell 5.1 drops embedded double quotes before the CLI sees them,+// and cmd splits a single-quoted prompt into separate arguments. The trusted planner in+// `agent-launch.ts` already encodes argv correctly for each of those dialects; this module wires it+// to a LIVE session and nothing else.+//+// The gate is deliberately the narrowest one that closes the bug: a local session-host session on+// a win32 core whose host recorded a Windows-native dialect (pwsh / windows-powershell / cmd) at+// spawn. Everything else — tmux, Zellij, SSH, a plain shell, any POSIX core, Git Bash, WSL — is+// answered `unsupported-shell` before anything is read or typed, and the renderer keeps typing its+// legacy line, byte-identical to before.+//+// Failure split (the renderer acts on it): every refusal that happens BEFORE the host is asked is a+// "nothing was typed" answer the caller may safely fall back from. Only a host-side failure is+// `delivery-failed`, which the caller must NOT retry as a typed line — part of the launch may+// already be in the pane.++import fs from 'fs'+import path from 'path'+import type {+ AgentLaunchIntent,+ CustomAgent,+ LaunchIntentExecutionResult,+ LaunchIntentFailureReason+} from '../shared/types'+import type { ExecuteLaunchResult, SessionHostShellDialect } from '../session-host/protocol'+import {+ AgentLaunchPreparationError,+ prepareAgentLaunch,+ type AgentLaunchExecutableResolution,+ type PreparedAgentLaunch+} from './agent-launch'++/** The Windows-native dialects this channel encodes for. POSIX shells keep their legacy line. */+export type WindowsLaunchDialect = Exclude<SessionHostShellDialect, 'posix'>++/**+ * The launch dialect a Windows session-host pane gets, from the shell it is spawned with. Only the+ * three Windows-native parsers are named; anything else (Git Bash, WSL, nu, an unknown wrapper)+ * answers `undefined`, which leaves the host's dialect unset exactly as before this channel — the+ * host's kill-line choice for those shells is unchanged, and their launches stay on the legacy line.+ * Non-win32 is always `undefined`, so a POSIX spawn request is byte-identical.+ */+export function windowsLaunchDialectForShell(+ shell: string | undefined,+ platform: NodeJS.Platform | string+): WindowsLaunchDialect | undefined {+ if (platform !== 'win32' || !shell) return undefined+ const base = shell+ .trim()+ .replace(/^"(.*)"$/u, '$1')+ .replace(/^.*[\\/]/u, '')+ .toLowerCase()+ .replace(/\.exe$/u, '')+ if (base === 'pwsh') return 'pwsh'+ if (base === 'powershell') return 'windows-powershell'+ if (base === 'cmd') return 'cmd'+ return undefined+}++/** Within ONE PATH directory: a native image first, then PowerShell's own `.ps1` shim, and only+ * then a batch shim — which the planner refuses (a second cmd parse is not lossless), so a+ * `.cmd`-only install falls back to the legacy line rather than being mis-quoted. */+const WINDOWS_EXECUTABLE_SUFFIXES = ['.exe', '.com', '.ps1', '.cmd', '.bat'] as const++function kindForSuffix(file: string): AgentLaunchExecutableResolution['kind'] | null {+ const lower = file.toLowerCase()+ if (lower.endsWith('.exe') || lower.endsWith('.com')) return 'native'+ if (lower.endsWith('.ps1')) return 'powershell-script'+ if (lower.endsWith('.cmd') || lower.endsWith('.bat')) return 'cmd-script'+ return null+}++const DRIVE_ABSOLUTE = /^[A-Za-z]:[\\/]/u++/**+ * Resolve a bare agent program (`claude`, the codex launcher, an absolute path) to the file the+ * pane would run, against the PATH the session was spawned with. Never spawns; `exists` is the+ * only I/O. `null` = not found, which the planner reports as `agent-unavailable` (→ legacy line).+ */+export function resolveWindowsAgentExecutable(+ executable: string,+ pathValue: string | undefined,+ exists: (candidate: string) => boolean+): AgentLaunchExecutableResolution | null {+ const tryFile = (candidate: string): AgentLaunchExecutableResolution | null => {+ const kind = kindForSuffix(candidate)+ return kind && DRIVE_ABSOLUTE.test(candidate) && exists(candidate)+ ? { kind, executable: candidate }+ : null+ }+ const withSuffixes = (stem: string): AgentLaunchExecutableResolution | null => {+ if (kindForSuffix(stem)) return tryFile(stem)+ for (const suffix of WINDOWS_EXECUTABLE_SUFFIXES) {+ const hit = tryFile(stem + suffix)+ if (hit) return hit+ }+ return null+ }+ if (/[\\/]/u.test(executable)) {+ return path.win32.isAbsolute(executable) ? withSuffixes(executable) : null+ }+ for (const raw of (pathValue ?? '').split(';')) {+ const dir = raw.trim().replace(/^"(.*)"$/u, '$1')+ // Drive-letter directories only: the planner refuses anything else (UNC, relative), so+ // resolving into one would only turn a clean miss into a confusing refusal.+ if (!DRIVE_ABSOLUTE.test(dir)) continue+ const hit = withSuffixes(path.win32.join(dir, executable))+ if (hit) return hit+ }+ return null+}++/** cmd.exe's ASCII-safe wrapper: the inbox Windows PowerShell, by its fixed system path. */+export function windowsPowerShellPath(+ systemRoot: string | undefined,+ exists: (candidate: string) => boolean+): string | undefined {+ const candidate = path.win32.join(+ systemRoot || 'C:\\Windows',+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe'+ )+ return exists(candidate) ? candidate : undefined+}++/** What the core knows about the node's live session — never what the renderer claims. */+export interface LaunchTarget {+ /** The host session name (`nt-<id>`). */+ name: string+ sessionHost: boolean+ remote: boolean+ /** The dialect the HOST reported for this exact generation (attach / attachExisting result). */+ launchDialect?: SessionHostShellDialect+ /** The agent the node's session was spawned for (`PtyCreateOptions.agentId`). */+ agentId?: string+ /** The PATH (and PATHEXT-free resolution) the session was spawned with. */+ pathValue?: string+}++export interface LaunchIntentDeps {+ platform: NodeJS.Platform | string+ customAgents(): readonly CustomAgent[]+ sharedIdentityAvailable(): Promise<boolean>+ codexCaps(): Promise<{ approvalValues: readonly string[] | null; noDaemon?: boolean | null }>+ exists(candidate: string): boolean+ systemRoot?: string+ /** Read a prompt file, refusing anything over `maxBytes`. */+ readPromptFile(file: string, maxBytes: number): Promise<string>+ execute(name: string, launchId: string, plan: PreparedAgentLaunch): Promise<ExecuteLaunchResult>+ /** The session-host's "this host cannot launch at all" error — nothing was typed. */+ isProtocolIncompatible(error: unknown): boolean+}++const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu+/** Same ceiling as the planner's own prompt limit. */+const MAX_PROMPT_FILE_BYTES = 128 * 1024++const MESSAGES: Record<LaunchIntentFailureReason, string> = {+ 'invalid-intent': 'The agent launch request is invalid.',+ 'agent-unavailable': 'The configured agent is unavailable on this machine.',+ 'unsupported-shell': 'This terminal shell cannot safely launch the configured agent.',+ 'session-unavailable': 'The terminal session is not running.',+ 'delivery-failed': 'The agent launch could not be delivered to the terminal.'+}++function refuse(reason: LaunchIntentFailureReason): LaunchIntentExecutionResult {+ return { ok: false, reason, message: MESSAGES[reason] }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++/**+ * A prompt file's text as ONE argv element. Whitespace runs collapse to a single space: the+ * planner refuses control characters (a newline is a command boundary to every Windows parser),+ * and this is exactly what the legacy `"$(cat …)"` line produces in PowerShell, where `cat` is+ * `Get-Content` and an interpolated line array joins on spaces. A leading BOM is dropped.+ */+export function promptFromFileText(text: string): string {+ return text.replace(/^\uFEFF/u, '').replace(/\s+/gu, ' ').trim()+}++/**+ * Validate the request, gate on the live session, prepare a dialect-correct plan and hand it to+ * the host's exactly-once ledger. Never throws; never reflects launch material in its answer.+ */+export async function executeLaunchIntent(+ target: LaunchTarget | undefined,+ request: unknown,+ deps: LaunchIntentDeps+): Promise<LaunchIntentExecutionResult> {+ if (!target) return refuse('session-unavailable')+ if (deps.platform !== 'win32' || !target.sessionHost || target.remote) {+ return refuse('unsupported-shell')+ }+ const dialect = target.launchDialect+ if (dialect !== 'pwsh' && dialect !== 'windows-powershell' && dialect !== 'cmd') {+ return refuse('unsupported-shell')+ }+ if (!isRecord(request) || !isRecord(request.intent)) return refuse('invalid-intent')+ if (typeof request.launchId !== 'string' || !UUID_V4.test(request.launchId)) {+ return refuse('invalid-intent')+ }+ if (!target.agentId) return refuse('agent-unavailable')++ let intent = request.intent as AgentLaunchIntent+ if (request.promptFile !== undefined) {+ const file = request.promptFile+ if (+ typeof file !== 'string' ||+ intent.action !== 'start' ||+ Object.hasOwn(intent, 'prompt') ||+ // eslint-disable-next-line no-control-regex+ /[\x00-\x1f]/u.test(file) ||+ !DRIVE_ABSOLUTE.test(file.trim())+ ) {+ return refuse('invalid-intent')+ }+ let text: string+ try {+ text = await deps.readPromptFile(file.trim(), MAX_PROMPT_FILE_BYTES)+ } catch {+ return refuse('invalid-intent')+ }+ intent = { ...intent, prompt: promptFromFileText(text) }+ }++ let plan: PreparedAgentLaunch+ try {+ const custom = deps.customAgents().find((c) => c.id === target.agentId)+ const codex = await deps.codexCaps()+ plan = await prepareAgentLaunch(intent, dialect, {+ expectedAgentId: target.agentId,+ ...(custom ? { customAgent: custom } : {}),+ sharedIdentityAvailable: await deps.sharedIdentityAvailable(),+ resolveExecutableKind: async (executable) =>+ resolveWindowsAgentExecutable(executable, target.pathValue, deps.exists),+ windowsPowerShellPath: windowsPowerShellPath(deps.systemRoot, deps.exists),+ codexApprovalValues: codex.approvalValues,+ codexNoDaemon: codex.noDaemon+ })+ } catch (error) {+ return refuse(error instanceof AgentLaunchPreparationError ? error.code : 'invalid-intent')+ }++ try {+ await deps.execute(target.name, request.launchId, plan)+ return { ok: true }+ } catch (error) {+ // A host that cannot run a launch at all (protocol v1) refuses before writing anything.+ return refuse(deps.isProtocolIncompatible(error) ? 'unsupported-shell' : 'delivery-failed')+ }+}++/** Default prompt-file reader: a regular file, size-checked before it is read. */+export async function readPromptFileBounded(file: string, maxBytes: number): Promise<string> {+ const stat = await fs.promises.stat(file)+ if (!stat.isFile() || stat.size > maxBytes) throw new Error('prompt file is not readable')+ return fs.promises.readFile(file, 'utf8')+}diff --git a/src/core/pty-manager.execute-launch.test.ts b/src/core/pty-manager.execute-launch.test.tsnew file mode 100644index 000000000..7f10e21ba--- /dev/null+++ b/src/core/pty-manager.execute-launch.test.ts@@ -0,0 +1,95 @@+// `PtyManager.executeLaunch` — WHICH live sessions may reach the session host's launch ledger.+// The planner and the encoding are proven in launch-intent-execute.test.ts; this file pins the+// dispatch: only a local session-host session on a win32 core, with a dialect the host recorded,+// ever calls `sessionHostExecuteLaunch`. tmux, SSH, a POSIX core and an old generation never do.+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { sessionName } from './tmux-naming'++vi.mock('child_process', () => ({+ execFile: (_f: string, _a: string[], a?: unknown, b?: unknown) => {+ const cb = (typeof a === 'function' ? a : b) as ((e: Error | null, r?: unknown) => void) | undefined+ cb?.(null, { stdout: '', stderr: '' })+ return {}+ },+ execFileSync: (): string => ''+}))+vi.mock('node-pty', () => ({ spawn: () => ({}) }))++const host = vi.hoisted(() => ({+ execute: vi.fn(async (_name: string, _id: string, _plan: unknown) => ({ status: 'executed' as const }))+}))+vi.mock('./session-host-backend', async (original) => ({+ ...(await original<typeof import('./session-host-backend')>()),+ sessionHostExecuteLaunch: host.execute+}))++const NODE = 'node-1'+const LAUNCH_ID = '123e4567-e89b-42d3-a456-426614174000'+const EXE = 'C:\\Users\\me\\.local\\bin\\claude.exe'+const REQUEST = {+ launchId: LAUNCH_ID,+ intent: { kind: 'agent', action: 'start', agentId: 'claude', prompt: `it's "x"` }+}++type Mgr = {+ sessions: Map<string, unknown>+ byPersistKey: Map<string, string>+ launchIntentDepsOverride: Record<string, unknown>+ executeLaunch(k: unknown, r: unknown): Promise<{ ok: boolean; reason?: string }>+}++async function manager(platform: NodeJS.Platform, session: Record<string, unknown>): Promise<Mgr> {+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager({ runtimePlatform: platform }) as unknown as Mgr+ mgr.sessions.set('s1', { persistKey: NODE, indexKey: NODE, ...session })+ mgr.byPersistKey.set(NODE, 's1')+ mgr.launchIntentDepsOverride = {+ customAgents: () => [],+ sharedIdentityAvailable: async () => false,+ codexCaps: async () => ({ approvalValues: null, noDaemon: null }),+ exists: (c: string) => c === EXE+ }+ return mgr+}++const HOST_SESSION = {+ sessionHost: true,+ launchDialect: 'pwsh',+ launchAgentId: 'claude',+ launchPath: 'C:\\Users\\me\\.local\\bin'+}++describe('PtyManager.executeLaunch', () => {+ beforeEach(() => host.execute.mockClear())++ it('executes through the host ledger for a win32 local session-host pane', async () => {+ const mgr = await manager('win32', HOST_SESSION)+ expect(await mgr.executeLaunch(NODE, REQUEST)).toEqual({ ok: true })+ expect(host.execute).toHaveBeenCalledTimes(1)+ const [name, id, plan] = host.execute.mock.calls[0]+ expect(name).toBe(sessionName(NODE))+ expect(id).toBe(LAUNCH_ID)+ // A PowerShell plan for the resolved native image — never the POSIX `'\''` quoting.+ expect((plan as { command: string }).command).toContain(`Start-Process -FilePath '${EXE}'`)+ expect((plan as { command: string }).command).not.toContain(`'\\''`)+ })++ it.each([+ ['a local tmux session', 'win32', { sessionHost: false, tmuxBacked: true }],+ ['an SSH session', 'win32', { ...HOST_SESSION, sshRemote: { conn: {}, controlPath: '/x' } }],+ ['a session-host generation with no recorded dialect', 'win32', { ...HOST_SESSION, launchDialect: undefined }],+ ['a macOS core', 'darwin', HOST_SESSION],+ ['a Linux core', 'linux', HOST_SESSION]+ ] as const)('never reaches the host for %s', async (_n, platform, session) => {+ const mgr = await manager(platform, session as Record<string, unknown>)+ expect(await mgr.executeLaunch(NODE, REQUEST)).toMatchObject({ ok: false, reason: 'unsupported-shell' })+ expect(host.execute).not.toHaveBeenCalled()+ })++ it('answers session-unavailable for a node with no live session, or a non-string key', async () => {+ const mgr = await manager('win32', HOST_SESSION)+ expect(await mgr.executeLaunch('other-node', REQUEST)).toMatchObject({ reason: 'session-unavailable' })+ expect(await mgr.executeLaunch(42, REQUEST)).toMatchObject({ reason: 'session-unavailable' })+ expect(host.execute).not.toHaveBeenCalled()+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 0e7282b15..9309fe2f0 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -17,7 +17,8 @@ import {type PtyCreateResult,type PtyRecycleTarget,type Settings,- type TmuxStatus+ type TmuxStatus,+ type LaunchIntentExecutionResult} from '../shared/types'import { bundledTmuxPath, findCommand, findFixedTmux, tmuxInstall } from './tmux-hint'import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'@@ -213,9 +214,17 @@ import {sessionHostMessageEnvelope,sessionHostSendKeys,sessionHostSupported,+ sessionHostExecuteLaunch,SessionHostProtocolCompatibilityError} from './session-host-backend'import type { SessionHostPty } from './session-host-pty'+import type { SessionHostShellDialect } from '../session-host/protocol'+import {+ executeLaunchIntent,+ readPromptFileBounded,+ windowsLaunchDialectForShell,+ type LaunchIntentDeps+} from './launch-intent-execute'import { NativeWindowsPane } from './native-windows-pane'import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'@@ -863,6 +872,17 @@ interface Session {* so every path that would talk to the tmux socket asks this first. */zellij?: booleansessionHost?: boolean+ /**+ * Session-host only (`pty:execute-launch`, launch-intent-execute.ts). The dialect the HOST+ * reported for this exact generation — never re-derived here, because a warm attach after an app+ * restart must answer with what the live shell actually is, not with today's settings. Absent on+ * every other backend, on POSIX, and for a generation spawned before the host recorded one.+ */+ launchDialect?: SessionHostShellDialect+ /** The agent this session was spawned for and the PATH it was spawned with: the trusted+ * expected owner and the executable search path for an `executeLaunch`. Session-host only. */+ launchAgentId?: string+ launchPath?: string/*** A live link watcher's OWN tmux client (`attach-session -E -f ignore-size,read-only`, spawned by* `joinAsWatcher` when no Session was held). Never indexed, and invisible to the persistKey lookups@@ -2074,6 +2094,53 @@ export class PtyManager {platform().handle(IPC.ptyTerminateForeground, (persistKey: string, expectedAgentId?: string) =>this.terminateForeground(persistKey, expectedAgentId))+ platform().handle(IPC.ptyExecuteLaunch, (persistKey: unknown, request: unknown) =>+ this.executeLaunch(persistKey, request)+ )+ }++ /** Test seam: replace any of `executeLaunch`'s machine-reading dependencies. */+ private launchIntentDepsOverride: Partial<LaunchIntentDeps> = {}++ private launchIntentDeps(): LaunchIntentDeps {+ return {+ platform: this.runtimePlatform,+ customAgents: () => this.getSettings().customAgents ?? [],+ // Dynamic: both probe modules import from this file, so a static import would be a cycle.+ sharedIdentityAvailable: async () =>+ (await (await import('./codex-identity-caps')).codexIdentityCaps()).shared === true,+ codexCaps: async () => (await import('./codex-cli')).codexCliCaps(),+ exists: (candidate) => fs.existsSync(candidate),+ systemRoot: process.env.SystemRoot,+ readPromptFile: readPromptFileBounded,+ execute: sessionHostExecuteLaunch,+ isProtocolIncompatible: (error) => error instanceof SessionHostProtocolCompatibilityError,+ ...this.launchIntentDepsOverride+ }+ }++ /**+ * `pty:execute-launch`: encode a semantic agent launch for a node's live local Windows+ * session-host pane and deliver it through the host's exactly-once ledger. Every other session+ * answers `unsupported-shell` (nothing read, nothing typed) — see launch-intent-execute.ts.+ */+ async executeLaunch(persistKey: unknown, request: unknown): Promise<LaunchIntentExecutionResult> {+ const live = typeof persistKey === 'string' ? this.liveSessionForNode(persistKey) : undefined+ const s = live?.[1]+ return executeLaunchIntent(+ s && typeof persistKey === 'string'+ ? {+ name: sessionName(persistKey),+ sessionHost: !!s.sessionHost,+ remote: !!s.sshRemote,+ launchDialect: s.launchDialect,+ agentId: s.launchAgentId,+ pathValue: s.launchPath+ }+ : undefined,+ request,+ this.launchIntentDeps()+ )}/** Discover the backend for NEW local terminals without starting a session host. */@@ -2792,6 +2859,9 @@ export class PtyManager {}fresh = info.freshscreen = info.screen+ // The host's own word on this generation's parser (a warm attach reports the dialect the+ // shell was spawned with, whatever today's settings say). See `Session.launchDialect`.+ if (info.launchDialect) spawned.launchDialect = info.launchDialect// Session-host registration is provisional until the exact ready barrier above succeeds.// Only now is an owner's resurrection real enough to remove a prior deletion tombstone.if (spawned.indexKey) this.tombstones.delete(spawned.indexKey)@@ -4275,6 +4345,9 @@ export class PtyManager {}let proc: pty.IPty+ const hostLaunchDialect = useSessionHost+ ? windowsLaunchDialectForShell(localSessionShell, this.runtimePlatform)+ : undefinedif (useSessionHost) {// Cast to the small `IPty` subset this file actually touches — see `SessionHostPty`'s own// doc comment for exactly what it implements and why that is enough. Its constructor kicks@@ -4303,7 +4376,11 @@ export class PtyManager {args: localSessionArgs,env,cols: options.cols,- rows: options.rows+ rows: options.rows,+ // Win32 + a Windows-native shell only (pwsh / powershell / cmd): the host then accepts+ // a trusted `executeLaunch` for this generation. Absent everywhere else, so a POSIX+ // or Git Bash/WSL spawn request is byte-identical to before.+ ...(hostLaunchDialect ? { launchDialect: hostLaunchDialect } : {})},settings.tmuxScrollback)) as unknown as pty.IPty@@ -4405,6 +4482,8 @@ export class PtyManager {pausedBy: new Set<string>(),accountFallback,sessionHost: useSessionHost,+ ...(useSessionHost && options.agentId ? { launchAgentId: options.agentId } : {}),+ ...(useSessionHost && env[envPathKey(env)] ? { launchPath: env[envPathKey(env)] } : {}),...(isWatcherCreate(options) ? { watcherClient: true } : {}),...(useLocalZellij ? { zellij: true } : {})}diff --git a/src/core/pty-session-host.test.ts b/src/core/pty-session-host.test.tsindex 3774abde6..4b1081d49 100644--- a/src/core/pty-session-host.test.ts+++ b/src/core/pty-session-host.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { IPC } from '../shared/ipc'import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform, type FakePlatform } from './platform-fake'+import { DEFAULT_SETTINGS } from '../shared/types'const backend = vi.hoisted(() => ({supported: vi.fn(() => true),@@ -240,6 +241,66 @@ describe('PtyManager session-host contracts', () => {expect(spawn.args).toEqual([])})+ it('sends no launch dialect from a POSIX core, so its spawn request is unchanged', async () => {+ const { PtyManager } = await import('./pty-manager')+ for (const runtimePlatform of ['darwin', 'linux'] as const) {+ backend.create.mockClear()+ const m = new PtyManager({ runtimePlatform })+ ;(m as unknown as { getSettings: () => unknown }).getSettings = () => ({+ ...DEFAULT_SETTINGS,+ defaultShell: 'pwsh'+ })+ m.createDetached({ cols: 80, rows: 24, persistKey: `node-${runtimePlatform}` }, { onData: () => {}, onExit: () => {} })+ const spawn = backend.create.mock.calls[0][1] as Record<string, unknown>+ expect('launchDialect' in spawn).toBe(false)+ await m.killAll()+ }+ })++ const PS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'++ it('records the Windows-native dialect at spawn and keeps the HOST-reported one for execute-launch', async () => {+ const { PtyManager } = await import('./pty-manager')+ // The host answers with its own record of the generation's parser (a warm attach reports what+ // the shell WAS spawned as) — that, not the spawn request, is what the launch is encoded for.+ backend.create.mockImplementation(() =>+ fakeSessionHostPty(Promise.resolve({ fresh: true, launchDialect: 'cmd' }) as never)+ )+ const m = new PtyManager({ runtimePlatform: 'win32' })+ manager = m+ ;(m as unknown as { getSettings: () => unknown }).getSettings = () => ({+ ...DEFAULT_SETTINGS,+ defaultShell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe'+ })+ m.registerIpc()+ await host.handlers[IPC.ptyCreate](7, { cols: 80, rows: 24, persistKey: 'node-win', agentId: 'claude' })+ const spawn = backend.create.mock.calls[0][1] as { launchDialect?: string }+ expect(spawn.launchDialect).toBe('pwsh')++ const execute = vi.fn(async () => ({ status: 'executed' as const }))+ ;(m as unknown as { launchIntentDepsOverride: Record<string, unknown> }).launchIntentDepsOverride = {+ customAgents: () => [],+ sharedIdentityAvailable: async () => false,+ codexCaps: async () => ({ approvalValues: null, noDaemon: null }),+ exists: (c: string) => c === 'C:\\Tools\\claude.exe' || c === PS,+ systemRoot: 'C:\\Windows',+ execute+ }+ // The spawn PATH recorded here is this POSIX test host's; point it at a Windows directory.+ ;(m as unknown as { sessions: Map<string, { launchPath?: string }> }).sessions.forEach((s) => {+ s.launchPath = 'C:\\Tools'+ })+ const result = await host.handlers[IPC.ptyExecuteLaunch]('node-win', {+ launchId: '123e4567-e89b-42d3-a456-426614174000',+ intent: { kind: 'agent', action: 'start', agentId: 'claude', prompt: "it's" }+ })+ expect(result).toEqual({ ok: true })+ // Encoded for `cmd` (the host's word), not `pwsh` (the request): the ASCII-only wrapper line.+ const plan = (execute.mock.calls[0] as unknown[])[2] as { command: string }+ expect(plan.command.startsWith(`"${PS}" -NoLogo -NoProfile -EncodedCommand `)).toBe(true)+ expect(plan.command).not.toContain("it's")+ })+it('fails a create closed, parks racing followers, and publishes only the recovered generation', async () => {let rejectReady!: (error: Error) => voidconst pendingReady = new Promise<{ fresh: boolean }>((_, reject) => {diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex 30fbde2cf..42b58c086 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -298,6 +298,9 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([IPC.ptyPaneCwd,IPC.ptyTerminateForeground,IPC.ptyReadSessionName,+ // Executes an agent launch and reads a host-local prompt file. Also HOST-ONLY for every peer+ // (shared/host-control.ts); a relay tab never sends it (its terminals are not `source: 'local'`).+ IPC.ptyExecuteLaunch,// Workspace, project settings and setup: writes, probes of arbitrary folders, trust, scripts.IPC.workspaceSave,IPC.workspaceProbeFolder,diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex 69afa951b..349901a00 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -434,6 +434,9 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({export const SCOPED_REFUSED: ReadonlySet<string> = new Set<string>([// A whole-workspace write from a peer would replace the host's other projects.IPC.workspaceSave,+ // Host-only for every peer (shared/host-control.ts): it would type a launch on the host and read+ // a host-local prompt file into it. A relay tab never sends it.+ IPC.ptyExecuteLaunch,// Project settings / setup / trust: relay-api.ts keeps these LOCAL; the setup ones are host-only.IPC.projectSettingsRead,IPC.projectSettingsWriteShared,diff --git a/src/preload/index.ts b/src/preload/index.tsindex e389a5868..3f858296c 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -116,6 +116,7 @@ const api: NodeTerminalApi = {paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),launchHeadless: (req) => ipcRenderer.invoke(IPC.ptyLaunchHeadless, req),paneOwner: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneOwner, persistKey),+ executeLaunch: (persistKey, request) => ipcRenderer.invoke(IPC.ptyExecuteLaunch, persistKey, request),terminateForeground: (persistKey, expectedAgentId) =>ipcRenderer.invoke(IPC.ptyTerminateForeground, persistKey, expectedAgentId),readSessionName: (sessionId, accountId, agentId) =>diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 8df46c1e0..9bcc6212c 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -80,6 +80,7 @@ import {} from '../../shared/types'import type { PeerIdentity } from '../../shared/presence'import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'+import type { LaunchIntentExecutionResult } from '../../shared/types'import { buildStubApi, unsupported } from './stubs'import { sanitizeStationNotices } from '@shared/station-notice'import { sanitizeOutcomeRecords } from '@shared/station-outcome'@@ -316,6 +317,18 @@ export function buildRealApi(client.request(IPC.ptyPaneOwner, persistKey).catch(() => null) as Promise<PaneOwner | null>,terminateForeground: (persistKey, expectedAgentId) =>client.request(IPC.ptyTerminateForeground, persistKey, expectedAgentId).catch(() => false) as Promise<boolean>,+ // REAL: core registers it, so a server running on Windows answers with its own session host.+ // On the Linux server every call answers `unsupported-shell` and the caller types its legacy+ // line. A transport failure is `delivery-failed`, NOT a fallback: the reply may be what was+ // lost, and typing the legacy line after a launch that did land would start the agent twice.+ executeLaunch: (persistKey, request) =>+ (client.request(IPC.ptyExecuteLaunch, persistKey, request) as Promise<LaunchIntentExecutionResult>).catch(+ (): LaunchIntentExecutionResult => ({+ ok: false,+ reason: 'delivery-failed',+ message: 'The agent launch could not be delivered to the terminal.'+ })+ ),// No server handler — the session-name poll degrades to no adopted name. A PRE-EXISTING gap,// and not any one agent's: `IPC.ptyReadSessionName` has never been registered server-side, so// claude's, grok's and gemini's read legs are equally stubbed here (the write leg works on bothdiff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex f418b51dc..23eadd37d 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -77,6 +77,9 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([IPC.projectSetupConsentSubmit,IPC.projectSetupRequestTrust,IPC.ptyLaunchHeadless,+ // Executes an agent launch on the host and reads a host-local `--prompt-file` into it. A relay+ // tab never sends it (its pty bridge omits the member); this holds the refusal host-side too.+ IPC.ptyExecuteLaunch,// Prepare-for-update ends EVERY session on this machine's session host and quits the app. Only// the host's own user may do that. Raw ipcMain handlers (no peer reaches them); listed here too// so moving them onto the platform table later cannot quietly open them.diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 1bc9e6a1c..48867184e 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -38,6 +38,10 @@ export const IPC = {ptyPaneCwd: 'pty:pane-cwd',/** Desktop-only (#925): start a node's session with no viewer and deliver its held launch. */ptyLaunchHeadless: 'pty:launch-headless',+ /** Renderer → core: execute a semantic agent launch (`LaunchIntentRequest`) in a node's live+ * local Windows session-host pane, encoded for that pane's own shell (core/launch-intent-execute.ts).+ * Host-only (shared/host-control.ts): a relay peer must never make the host read a prompt file. */+ ptyExecuteLaunch: 'pty:execute-launch',/** Kernel truth about a node's tmux pane: its root pid, tty, tmux pane id, and the full argv of* its FOREGROUND process group (`PaneOwner`). The name-only `ptyPaneCommand` above cannot tell* an agent from anything else — an npm-installed CLI reports as `node`, and an agent reacheddiff --git a/src/shared/types.ts b/src/shared/types.tsindex 679d2e87a..02e958498 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -116,6 +116,30 @@ export type LaunchIntentExecutionResult =| { ok: true }| { ok: false; reason: LaunchIntentFailureReason; message: string }+/**+ * `pty:execute-launch` request (`PtyApi.executeLaunch`). `launchId` is a fresh UUID v4 per+ * delivery attempt — the session host's exactly-once ledger key. `promptFile` is the+ * canvas-control `--prompt-file` path: the core reads it (the file is on the core's machine) and+ * fills `intent.prompt`, so no shell ever has to expand `$(cat …)`. Only legal on a `start`+ * intent that carries no `prompt` of its own.+ */+export interface LaunchIntentRequest {+ launchId: string+ intent: AgentLaunchIntent+ promptFile?: string+}++/**+ * A semantic launch held beside a terminal node's legacy typed line (`data.launchIntent`). Bound+ * to the EXACT `command` it was assembled with: a writer delivering any other line (a manual Run+ * now of an edited command, a resume) never uses it. Live node data only — never serialized.+ */+export interface HeldLaunchIntent {+ command: string+ intent: AgentLaunchIntent+ promptFile?: string+}+export interface PtyCreateOptions {shell?: string/** Arguments for `shell` when it is run as the session program (e.g. ssh args). */@@ -1347,6 +1371,14 @@ export interface PtyApi {* it. `null` is "could not read", never evidence that the pane is free (see `isAgentPane`'s* three-valued verdict, which is what consumers should decide on). */paneOwner(persistKey: string): Promise<PaneOwner | null>+ /**+ * Execute a semantic agent launch in a node's live LOCAL Windows session-host pane: the core+ * encodes it for the pane's own shell (pwsh / Windows PowerShell / cmd) and the host types it+ * exactly once. Every other session (tmux, SSH, Zellij, plain shell, POSIX core, Git Bash/WSL)+ * answers `unsupported-shell`, and the caller keeps its legacy typed line. Optional: surfaces+ * that cannot serve it (relay tabs, test fakes) simply omit it — the caller's answer is the same.+ */+ executeLaunch?(persistKey: string, request: LaunchIntentRequest): Promise<LaunchIntentExecutionResult>/** Terminate the foreground process group in a node's pane. Returns false when the pane/process* cannot be safely identified; it never kills the pane's login shell. When `expectedAgentId` is* given, the kill happens only if that harness actually owns the foreground group (argv-verified)