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
fix(cli): ask the engine whether it takes the flag we launch it with
0xken15fae457ff3785
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 39a7169f5..e0a674589 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -73,7 +73,7 @@ import { gridAvailable } from './lib/gridExec.js'import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'import { isTerminalEngine, type AgentEngine } from './engines/types.js'import { engineInstallRecipe } from './lib/engineInstall.js'-import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, commandSupportsFlagInInteractiveShell, namedAgentArgs, permissionModeApproves, permissionModeFlags } from './lib/engineLaunch.js'+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported } from './lib/engineLaunch.js'import { workspaceMissing } from './lib/workspaceCheck.js'import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'@@ -85,6 +85,7 @@ import { AgentRestartCoordinator, bypassPermissionFor, restartAgent, type Restarimport { claudeContinuation, findLiveSession, findResumedTranscript } from './lib/sessionRepair.js'import { TmuxBackend } from './lib/tmuxBackend.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'+import { describeAgentCreateFailure, summarizePaneOutput } from './lib/agentCreateDiagnosis.js'import { createAndRegisterPane } from './lib/createAgentPane.js'import { forkName, planFork } from './lib/forkAgent.js'import { restoreAgents } from './lib/restoreAgents.js'@@ -4315,10 +4316,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {// pane that fails to come up is reported failed by the frame regardless of this field.refreshGridWebSearch(entry.agentId, built.overrides)const { env: launchEnv, extraArgs, clearEnv } = built.overrides+ // The engine may have been downgraded while the daemon was down. Coming back in Ask beats+ // coming back as a pane of help text, and beats not coming back at all.+ const permission = await downgradedPermission(entry, entry.bypassPermission === true, 'restore')const argv = buildEngineLaunchArgv(entry.engine, {...opts,- bypassPermission: entry.bypassPermission === true,- ...(entry.permissionMode ? { permissionMode: entry.permissionMode } : {}),+ bypassPermission: permission.bypassPermission === true,+ ...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),...(entry.cwd ? { cwd: entry.cwd } : {}),...(extraArgs.length ? { extraArgs } : {}),@@ -4540,6 +4544,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {// the error where it was printed and types the command again, rather than being handed a// "Start failed" tile they cannot type into.if (paneState.engineExit !== null) {+ // Say what happened before the evidence goes. The pane is about to become an ordinary+ // terminal and `releaseEngine` rewrites the launch to `ready`, so after this point nothing+ // anywhere — frame, registry, archive — records that an engine was ever meant to be here+ // or why it left. openharness#285 was exactly this: opencode printed its help over a flag+ // it did not know, and the only trace was one line saying the pane had become a terminal.+ // `describeAgentCreateFailure` was written for this and had no caller.+ const captured = await captureTerminal(pending.agentId, 40)+ console.warn(`[agent] create · ${engine} · agent ${sid(pending.agentId)} · `+ + describeAgentCreateFailure({+ state: { dead: true, exitStatus: paneState.engineExit, command: engine },+ output: summarizePaneOutput(captured ?? ''),+ engineBin: command[0],+ shellName: null,+ processes: [],+ elapsedMs: Date.now() - startedAt,+ }))await clearPaneRemainOnExit(spawned.runtime.paneId)// A hook may have bound a conversation while this watcher was awaiting its probe.// Archive the current row, not the pre-hook pending snapshot.@@ -4583,26 +4603,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {permissionMode = pinnedModebypassPermission = permissionModeApproves(pinnedMode)}- // `--approve-for-me` was added after older Codex CLI releases. Refuse the- // incompatible Auto mode before opening a pane, rather than letting Codex- // reject the flag and leaving the person in an unexpected fallback shell.- // Ask mode has no flag and remains a useful workaround until Codex updates.- const codexAutoApprove =- engine === 'codex' &&- (permissionMode !== null- ? permissionModeFlags(engine, permissionMode)?.includes('--approve-for-me') === true- : bypassPermission)- if (codexAutoApprove) {- const support = await commandSupportsFlagInInteractiveShell(- engineBin('codex'),- '--approve-for-me',- )- if (support === 'unsupported') {- const detail =- 'Your installed Codex CLI does not support --approve-for-me, which Harness uses for Auto approvals. Update Codex and try again, or choose Ask permissions for this harness.'- console.warn(`[agent] create codex refused · ${detail}`)- return { ok: false, error: 'CODEX_CLI_TOO_OLD', detail }- }+ // An engine too old for the flag this permission mode launches it with prints its help and+ // exits; the wrapper then hands the pane to a shell, and what the person gets is a terminal+ // full of help text with nothing anywhere saying why (openharness#285, opencode without+ // `--auto`). Refuse before opening a pane — this is a launch somebody is waiting on, and Ask+ // works today. Codex has been checked this way since it gained `--approve-for-me`; every other+ // engine with a permission flag was not, and carried the same failure.+ const refusal = await refusePermissionFlagIfUnsupported(engine, { permissionMode, bypassPermission })+ if (refusal) {+ console.warn(`[agent] create refused · ${engine} · ${refusal.detail}`)+ return { ok: false, ...refusal }}// A domain-specific harness: put its files into the workspace first (template, AGENTS.md, skill// links) and take its env/argv for the launch. Refused, never approximated, when it is not here.@@ -4825,6 +4835,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {...(plan.level === 'native' ? { forkSessionId: plan.forkSessionId } : {}),...(firstPrompt ? { firstPrompt } : {}),}+ // Same refusal as create: the clone inherits the source's permission mode, and an engine that+ // has since been downgraded would hand back a pane of help text instead of a harness.+ const forkRefusal = await refusePermissionFlagIfUnsupported(engine, launchOptions)+ if (forkRefusal) {+ console.warn(`[agent] fork refused · ${engine} · ${forkRefusal.detail}`)+ return { ok: false, ...forkRefusal }+ }prepareApiTools(source.cwd, engine)const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)@@ -4875,10 +4892,40 @@ async function runForeground(session: AuthSession | null): Promise<void> {&& current.tmuxPane === session.tmuxPane && current.engine === session.engine}+ /**+ * The permission this relaunch can actually ask for. Nobody is waiting on a restart, a retarget, a+ * restore or a resume, so an engine that no longer takes the row's flag costs it the mode, not the+ * harness — the alternative is a pane of help text, or no pane at all (openharness#285).+ *+ * The row is NOT rewritten. `permissionMode` is the person's recorded choice and `setPermissionMode`+ * is fill-only for that reason; an engine put back the way it was gets Auto again on the next+ * relaunch, with nobody having to ask for it twice. The row stops CLAIMING the mode on its own:+ * discovery re-derives `bypassPermission` from the live argv on every pass (`setBypassPermission`+ * above), so a launch without the flag reads as one within a reconcile.+ */+ const downgradedPermission = async (+ session: RegisteredSession,+ bypassPermission: boolean,+ what: string,+ ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }> => {+ const { choice, droppedFlag } = await dropPermissionFlagIfUnsupported(session.engine, {+ permissionMode: session.permissionMode ?? null,+ bypassPermission,+ })+ if (droppedFlag) {+ console.warn(`[agent] ${what} ${sid(session.agentId)} · ${session.engine} does not take ${droppedFlag}`+ + ` · starting in Ask · update ${session.engine} to get ${session.permissionMode ?? 'Auto'} back`)+ }+ return choice+ }+const paneSwapDeps = (session: RegisteredSession,runtime: TmuxRuntimeRef,launch: { env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},+ /** The mode this swap may actually ask for — the row's own, unless the engine on disk has since+ * stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */+ permissionMode: string | null = session.permissionMode ?? null,): RestartAgentDeps => ({prepareResume: () => prepareSessionResume(session),holdOpen: async () => {@@ -4922,7 +4969,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {...opts,// The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and// Plan or Accept edits would come back as Ask without it.- ...(session.permissionMode ? { permissionMode: session.permissionMode } : {}),+ ...(permissionMode ? { permissionMode } : {}),...(session.cwd ? { cwd: session.cwd } : {}),...(launch.extraArgs?.length ? { extraArgs: launch.extraArgs } : {}),// A pane swap onto a grid has to clear the same vendor credentials a fresh create does, for the@@ -5107,10 +5154,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {return { ok: false, error: 'GRID_CLEAR_FAILED', detail: 'reason' in cleared ? cleared.reason : 'tmux would not clear the pane environment' }}}+ const retargetPermission = await downgradedPermission(session,+ await bypassPermissionFor(session, () => liveBypassPermission(session)), 'retarget')const outcome = await restartAgent({ engine: session.engine, sessionId: session.sessionId },- await bypassPermissionFor(session, () => liveBypassPermission(session)),- paneSwapDeps(session, pane, built.overrides),+ retargetPermission.bypassPermission === true,+ paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null),)if (!outcome.ok) {console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)@@ -5248,11 +5297,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {agentReconciler.holdRoute(routeKey)try {- const bypassPermission = await bypassPermissionFor(session, () => liveBypassPermission(session))+ const restartPermission = await downgradedPermission(session,+ await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart')const outcome = await restartAgent({ engine, sessionId: session.sessionId },- bypassPermission,- { ...paneSwapDeps(session, runtime, built.overrides), isCurrent: current },+ restartPermission.bypassPermission === true,+ { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null), isCurrent: current },)if (!current()) return changeddiff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex 6bcaab8e4..b45b684d2 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -18,6 +18,11 @@ import {buildEngineLaunchArgv,commandAvailableInInteractiveShell,commandSupportsFlagInInteractiveShell,+ dropPermissionFlagIfUnsupported,+ permissionFlagToVerify,+ permissionModeFlags,+ refusePermissionFlagIfUnsupported,+ resetCommandFlagSupportCache,engineFallbackPrelude,firstPromptArgs,gridPanePrelude,@@ -602,6 +607,76 @@ describe('commandAvailableInInteractiveShell', () => {})})+/** A fake engine whose `--help` prints exactly `help`, and nothing else. */+function fakeEngine(dir: string, name: string, help: string): void {+ writeFileSync(join(dir, name), `#!/bin/sh\nif [ "$1" = "--help" ]; then printf "%s\\n" '${help}'; exit 0; fi\nexit 2\n`)+ chmodSync(join(dir, name), 0o700)+}++describe('the permission gates', () => {+ /** A fake opencode on the probe shell's PATH, and the shell that will find it. */+ function withFakeOpencode(help: string): string {+ const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-gate-'))+ dirs.push(binDir)+ process.env.HARNESS_ENGINE_TEST_PATH = binDir+ fakeEngine(binDir, 'opencode', help)+ return bashProbeShell()+ }++ it('refuses a create whose engine does not take the flag, naming the engine and the flag', async () => {+ const shell = withFakeOpencode('--auto-update')+ const refusal = await refusePermissionFlagIfUnsupported('opencode', { permissionMode: 'auto' }, shell)+ expect(refusal?.error).toBe('CODEX_CLI_TOO_OLD')+ expect(refusal?.detail).toContain('opencode')+ expect(refusal?.detail).toContain('--auto')+ })++ it('lets a create through when the flag is there, and when there is no flag to check', async () => {+ const shell = withFakeOpencode('--auto')+ await expect(refusePermissionFlagIfUnsupported('opencode', { permissionMode: 'auto' }, shell)).resolves.toBeNull()+ await expect(refusePermissionFlagIfUnsupported('opencode', { permissionMode: 'ask' }, shell)).resolves.toBeNull()+ })++ it('drops the flag for a relaunch instead of refusing it, leaving the launch in Ask', async () => {+ const shell = withFakeOpencode('--auto-update')+ const dropped = await dropPermissionFlagIfUnsupported('opencode', { permissionMode: 'auto', bypassPermission: true }, shell)+ expect(dropped).toEqual({ choice: { permissionMode: 'ask', bypassPermission: false }, droppedFlag: '--auto' })+ })++ it('leaves a relaunch alone when the flag is supported', async () => {+ const shell = withFakeOpencode('--auto')+ const kept = await dropPermissionFlagIfUnsupported('opencode', { permissionMode: 'auto', bypassPermission: true }, shell)+ expect(kept).toEqual({ choice: { permissionMode: 'auto', bypassPermission: true }, droppedFlag: null })+ })+})++describe('permissionFlagToVerify', () => {+ it('names the single token a mode adds', () => {+ expect(permissionFlagToVerify('opencode', { permissionMode: 'auto' })).toBe('--auto')+ expect(permissionFlagToVerify('cursor', { permissionMode: 'auto' })).toBe('--force')+ expect(permissionFlagToVerify('codex', { permissionMode: 'auto' })).toBe('--approve-for-me')+ })++ it('reads the bypass table when no mode was recorded', () => {+ expect(permissionFlagToVerify('opencode', { bypassPermission: true })).toBe('--auto')+ expect(permissionFlagToVerify('opencode', { bypassPermission: false })).toBeNull()+ })++ // The documented limit: help never prints the pair, so only the token can be asked about, and a+ // build that lists `--permission-mode` while having dropped the `auto` VALUE is not caught here.+ it('takes the flag token of a pair, never its value', () => {+ expect(permissionModeFlags('claude', 'auto')).toEqual(['--permission-mode', 'auto'])+ expect(permissionFlagToVerify('claude', { permissionMode: 'auto' })).toBe('--permission-mode')+ expect(permissionFlagToVerify('codex', { permissionMode: 'readOnly' })).toBe('--sandbox')+ })++ it('has nothing to verify for Ask, an engine with no table, or a terminal', () => {+ expect(permissionFlagToVerify('claude', { permissionMode: 'ask' })).toBeNull()+ expect(permissionFlagToVerify('muse', { bypassPermission: true })).toBeNull()+ expect(permissionFlagToVerify('terminal', { bypassPermission: true })).toBeNull()+ })+})+describe('commandSupportsFlagInInteractiveShell', () => {it('distinguishes an older CLI help surface from a supported flag', async () => {const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-capability-'))@@ -627,6 +702,53 @@ describe('commandSupportsFlagInInteractiveShell', () => {).resolves.toBe('supported')})+ // openharness#285: opencode 1.14.51 has no `--auto`, prints its help and exits, and the wrapper+ // hands the pane to a shell. A substring match reads `--auto-update` in a newer help as support+ // for `--auto` and launches that very pane.+ it('does not read a longer flag as the one it was asked about', async () => {+ const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-boundary-'))+ dirs.push(binDir)+ process.env.HARNESS_ENGINE_TEST_PATH = binDir++ fakeEngine(binDir, 'opencode', '--auto-update keep opencode current')+ await expect(commandSupportsFlagInInteractiveShell('opencode', '--auto', bashProbeShell()))+ .resolves.toBe('unsupported')++ fakeEngine(binDir, 'opencode', '--auto approve automatically')+ await expect(commandSupportsFlagInInteractiveShell('opencode', '--auto', bashProbeShell()))+ .resolves.toBe('supported')+ })++ it('answers a flag that ends the help text', async () => {+ const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-tail-'))+ dirs.push(binDir)+ process.env.HARNESS_ENGINE_TEST_PATH = binDir+ fakeEngine(binDir, 'cursor-agent', '--force')+ await expect(commandSupportsFlagInInteractiveShell('cursor-agent', '--force', bashProbeShell()))+ .resolves.toBe('supported')+ })++ // Every relaunch asks, and a restore asks once per agent. Only the working answer is remembered:+ // the cure for the other two is to change the engine on disk, and a remembered refusal would+ // outlive the upgrade that fixed it — which is how openharness#285's reporter resolved theirs.+ it('remembers that a flag IS supported, and keeps asking when it is not', async () => {+ const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-cache-'))+ dirs.push(binDir)+ process.env.HARNESS_ENGINE_TEST_PATH = binDir+ const shell = bashProbeShell()++ fakeEngine(binDir, 'opencode', '--auto')+ await expect(commandSupportsFlagInInteractiveShell('opencode', '--auto', shell)).resolves.toBe('supported')+ // Downgraded underneath us; the cached yes stands until the cache is reset.+ fakeEngine(binDir, 'opencode', '--auto-update')+ await expect(commandSupportsFlagInInteractiveShell('opencode', '--auto', shell)).resolves.toBe('supported')+ resetCommandFlagSupportCache()+ await expect(commandSupportsFlagInInteractiveShell('opencode', '--auto', shell)).resolves.toBe('unsupported')+ // A refusal is never remembered, so the upgrade is seen at once.+ fakeEngine(binDir, 'opencode', '--auto')+ await expect(commandSupportsFlagInInteractiveShell('opencode', '--auto', shell)).resolves.toBe('supported')+ })+// A shell's own failure exits 1 — as zsh's read-only `status` did — and must not read as a missing// flag: only the probe's own "not in the help" exit refuses an engine.it('does not read a shell failure as a missing flag', async () => {diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex c5d13df01..ac3defed9 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -811,6 +811,23 @@ export type CommandFlagSupport = 'supported' | 'unsupported' | 'unknown'*/const FLAG_UNSUPPORTED_EXIT = 64+/**+ * The pairs this probe has seen the engine SUPPORT.+ *+ * Every relaunch asks, and a post-reboot restore asks once per agent, so the working case — which+ * is nearly every case — is worth answering from memory instead of spawning `--help` again.+ *+ * Only `supported` is kept, deliberately. The remedy for the other two answers is to change the+ * engine on disk: openharness#285 was closed by its reporter upgrading opencode until it had+ * `--auto`. A cached `unsupported` would go on refusing that upgraded engine until the daemon+ * happened to restart, which is the one outcome worth more than the spawn it saves. `unknown` is+ * not kept for the same reason at shorter range: one slow `--help` would turn Auto off machine-wide.+ */+const flagSupportCache = new Set<string>()++/** Test seam, and for a machine where the engine was just upgraded. */+export function resetCommandFlagSupportCache(): void { flagSupportCache.clear() }+/*** Checks a CLI's own help from the same interactive shell that would launch* it. `unknown` is deliberately non-blocking: a broken or unusually slow help@@ -821,6 +838,8 @@ export async function commandSupportsFlagInInteractiveShell(flag: string,shell: string | undefined = undefined,): Promise<CommandFlagSupport> {+ const key = `${command}\u0000${flag}\u0000${shell ?? ''}`+ if (flagSupportCache.has(key)) return 'supported'const interactive = interactiveEngineShell(shell)if (!interactive) return 'unknown'// `harness_help_status`, not `status`: in zsh `status` is a read-only special parameter (an alias@@ -832,7 +851,11 @@ export async function commandSupportsFlagInInteractiveShell('help="$("$1" --help 2>&1)"','harness_help_status=$?','[ "$harness_help_status" -eq 0 ] || exit 2',- `case "$help" in *"$2"*) exit 0 ;; *) exit ${FLAG_UNSUPPORTED_EXIT} ;; esac`,+ // The flag, not a longer one that starts with it. A plain `*"$2"*` reads `--auto-update` in+ // opencode's help as support for `--auto` — and then launches the very pane openharness#285+ // reported, full of help text. So: followed by something that cannot continue a flag, or+ // ending the help. `[!…]` is POSIX and behaves the same in sh, bash and zsh (measured).+ `case "$help" in *"$2"[!A-Za-z0-9-]*|*"$2") exit 0 ;; *) exit ${FLAG_UNSUPPORTED_EXIT} ;; esac`,].join('\n')return await new Promise((resolve) => {execFile(@@ -840,12 +863,92 @@ export async function commandSupportsFlagInInteractiveShell([...interactive.args, script, 'harness-engine-capability', command, flag],{ timeout: 5_000 },(error) => {- if (!error) resolve('supported')- else {- const code = (error as { code?: number | string }).code- resolve(Number(code) === FLAG_UNSUPPORTED_EXIT ? 'unsupported' : 'unknown')- }+ const answer: CommandFlagSupport = !error+ ? 'supported'+ : Number((error as { code?: number | string }).code) === FLAG_UNSUPPORTED_EXIT ? 'unsupported' : 'unknown'+ if (answer === 'supported') flagSupportCache.add(key)+ resolve(answer)},)})}++/** What a launch would add for its permission mode, and whether the engine on disk knows it. */+export interface PermissionLaunchChoice {+ permissionMode?: string | null+ bypassPermission?: boolean+}++/**+ * The flag whose support decides whether this launch can keep its permission mode, or null when the+ * launch adds none — an `ask` mode, an engine with no entry in the tables, a terminal.+ *+ * Only the flag TOKEN, never its value. `permissionModeFlags('claude', 'auto')` is a pair,+ * `['--permission-mode', 'auto']`, and so is codex's `readOnly`; no `--help` prints a pair+ * literally, so a build that lists `--permission-mode` but no longer accepts `auto` is not caught+ * here. The single-token modes — `opencode --auto`, `cursor --force`, `codex --approve-for-me` —+ * are answered exactly, and the first of those is what openharness#285 was about.+ */+export function permissionFlagToVerify(engine: AgentEngine, choice: PermissionLaunchChoice): string | null {+ const flags = choice.permissionMode+ ? permissionModeFlags(engine, choice.permissionMode)+ : choice.bypassPermission ? BYPASS_PERMISSION_FLAGS[engine] : null+ return flags?.find((token) => token.startsWith('--')) ?? null+}++/**+ * Ask the engine on disk whether it knows the flag this launch would pass it.+ *+ * `null` means "launch as asked": either nothing is being added, or the engine takes it, or the+ * probe could not tell (`unknown` never refuses — see `commandSupportsFlagInInteractiveShell`).+ */+async function unsupportedPermissionFlag(+ engine: AgentEngine,+ choice: PermissionLaunchChoice,+ shell: string | undefined,+): Promise<string | null> {+ const flag = permissionFlagToVerify(engine, choice)+ if (!flag) return null+ const support = await commandSupportsFlagInInteractiveShell(engineBin(engine), flag, shell)+ return support === 'unsupported' ? flag : null+}++/**+ * For a launch somebody is waiting on — create, fork. Refusing is kinder than opening a pane that+ * the engine will fill with its own help text and leave: the person is here, and Ask works today.+ *+ * The wire code is `CODEX_CLI_TOO_OLD` for every engine. The name is historical — this began as a+ * codex-only check — and it stays because clients key on it: a code missing from the desktop's+ * `refusedBeforeLaunch` set is not merely unlabelled there, it leaves the New Harness dialog saying+ * the machine "has not confirmed the new harness yet". The daemon self-updates and the app does+ * not, so the detail below is what an older app shows, and it names the engine itself.+ */+export async function refusePermissionFlagIfUnsupported(+ engine: AgentEngine,+ choice: PermissionLaunchChoice,+ shell: string | undefined = undefined,+): Promise<{ error: string; detail: string } | null> {+ const flag = await unsupportedPermissionFlag(engine, choice, shell)+ if (!flag) return null+ return {+ error: 'CODEX_CLI_TOO_OLD',+ detail: `The ${engine} CLI on this machine does not support ${flag}, which Harness uses for this permission mode. `+ + `Update ${engine} and try again, or choose Ask permissions for this harness.`,+ }+}++/**+ * For a launch nobody is waiting on — restore after a reboot, resume, restart, retarget. Here a+ * refusal costs the whole harness, pane and scrollback included, to save a permission mode; so the+ * flag is dropped and the launch goes ahead in Ask. The caller records that on the row, because a+ * row that goes on claiming Auto while running without it is the more expensive lie.+ */+export async function dropPermissionFlagIfUnsupported<T extends PermissionLaunchChoice>(+ engine: AgentEngine,+ choice: T,+ shell: string | undefined = undefined,+): Promise<{ choice: T; droppedFlag: string | null }> {+ const droppedFlag = await unsupportedPermissionFlag(engine, choice, shell)+ if (!droppedFlag) return { choice, droppedFlag: null }+ return { choice: { ...choice, permissionMode: 'ask', bypassPermission: false }, droppedFlag }+}diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex 5017f57a6..6b4a4ed85 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -18,10 +18,14 @@ import { installedDsh } from '../dsh/installed.js'vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn() }))vi.mock('./tmuxAgentDiscovery.js', () => ({ listTmuxPanes: vi.fn() }))vi.mock('./tmux.js', () => ({ checkSessionRuntime: vi.fn(), clearPaneRemainOnExit: vi.fn(), resolvePaneEngineProcess: vi.fn(), tmuxPaneState: vi.fn() }))-// `resumeCapability` reads the real flag table through this module; only the argv builder is faked.+// `resumeCapability` reads the real flag table through this module; only the argv builder and the+// capability gate are faked. The gate would otherwise spawn the tester's own login shell to ask+// `<engine> --help` about a flag, which is neither this file's subject nor the same answer on two+// machines. Its own behaviour is covered in `engineLaunch.spec.ts`.vi.mock('./engineLaunch.js', async importOriginal => ({...(await importOriginal<typeof import('./engineLaunch.js')>()),buildEngineLaunchArgv: vi.fn(() => ['fixture-engine']),+ dropPermissionFlagIfUnsupported: vi.fn(async (_engine: unknown, choice: unknown) => ({ choice, droppedFlag: null })),}))vi.mock('./engineBin.js', () => ({ enginePathOverride: vi.fn(() => undefined) }))vi.mock('./engineInstall.js', () => ({ engineInstallRecipe: () => ({ command: 'fixture-install' }) }))diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.tsindex fa1910a2e..1d449a305 100644--- a/cli/src/lib/resumeAgentService.ts+++ b/cli/src/lib/resumeAgentService.ts@@ -9,7 +9,7 @@ import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, timport { listTmuxPanes } from './tmuxAgentDiscovery.js'import { enginePathOverride } from './engineBin.js'import { engineInstallRecipe } from './engineInstall.js'-import { buildEngineLaunchArgv } from './engineLaunch.js'+import { buildEngineLaunchArgv, dropPermissionFlagIfUnsupported } from './engineLaunch.js'import { workspaceMissing } from './workspaceCheck.js'import { buildHarnessSessionLabel } from './harnessSessionLabel.js'import { createAndRegisterPane, type CreateAgentPaneDeps } from './createAgentPane.js'@@ -184,10 +184,21 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {}if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }const { env: launchEnv, extraArgs, clearEnv } = built.overrides+ // The engine may have been downgraded since this harness was paused. Nobody is waiting on+ // the mode the way they are waiting on the harness, so the flag goes and the launch stays+ // (openharness#285). The row keeps its recorded mode; discovery re-derives the live one.+ const { choice: permission, droppedFlag } = await dropPermissionFlagIfUnsupported(saved.engine, {+ permissionMode: saved.permissionMode ?? null,+ bypassPermission: saved.bypassPermission === true,+ })+ if (droppedFlag) {+ console.warn(`[resume] ${sid(saved.agentId)} · ${saved.engine} does not take ${droppedFlag}`+ + ` · resuming in Ask · update ${saved.engine} to get ${saved.permissionMode ?? 'Auto'} back`)+ }const options = {resumeSessionId,- bypassPermission: saved.bypassPermission === true,- ...(saved.permissionMode ? { permissionMode: saved.permissionMode } : {}),+ bypassPermission: permission.bypassPermission === true,+ ...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),cwd: saved.cwd,...(extraArgs.length ? { extraArgs } : {}),...(clearEnv.length ? { clearEnv } : {}),