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
feat: record and reuse agent permission modes from live process arguments
0xken15944b13724dc7
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 5aa058e8d..975346af3 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -77,7 +77,7 @@ import { writeGridConfigDir } from './lib/gridConfigDir.js'import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallback.js'-import { AgentRestartCoordinator, restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'+import { AgentRestartCoordinator, bypassPermissionFor, restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'import { 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'@@ -102,6 +102,7 @@ import type { AgentDshContext } from './lib/agentFrame.js'import { basename } from 'node:path'import {bypassPermissionActive,+ permissionModeFromArgv,clearPaneRemainOnExit,resolvePaneEngineProcess,tmuxPaneState,@@ -2885,6 +2886,14 @@ async function runForeground(session: AuthSession): Promise<void> {// `observed.engine`, not `current.engine`: for a terminal that just adopted one, the row's// engine was `terminal` a line ago, which has no bypass flag and would read every launch as "no".registry.setBypassPermission(current.agentId, bypassPermissionActive(observed.engine, observed.args))+ // And the exact MODE, fill-only: a row that recorded one at create is authoritative, and one+ // that never did (adopted from a terminal, written by an older build, created by a path that+ // passes no mode) learns it from the same argv — so its restart brings back+ // `--dangerously-skip-permissions`, not the auto mode `bypassPermission` alone would pick.+ if (!current.permissionMode) {+ const mode = permissionModeFromArgv(observed.engine, observed.args)+ if (mode) registry.setPermissionMode(current.agentId, mode)+ }// Same idea for a Codex profile: a row that never learned which CODEX_HOME its process runs// under learns it from the process, before the hook path validates a transcript against it.// Fill-only — a profile the row already knows is never re-derived.@@ -4553,8 +4562,9 @@ async function runForeground(session: AuthSession): Promise<void> {log: (message) => console.log(message),})- /** The bypass-permission mode the LIVE process was launched with — there is nowhere to read it from- * once that process is dead, so both swap paths read it before signalling anything. */+ /** The bypass-permission flag the LIVE process was launched with. The fallback behind+ * `bypassPermissionFor` for a row that recorded neither a mode nor the flag (written before either+ * was persisted, and not yet seen by a discovery scan); read before anything is signalled. */const liveBypassPermission = async (session: RegisteredSession): Promise<boolean> => {const identity = session.processIdentityif (!identity) return false@@ -4716,7 +4726,7 @@ async function runForeground(session: AuthSession): Promise<void> {}const outcome = await restartAgent({ engine: session.engine, sessionId: session.sessionId },- await liveBypassPermission(session),+ await bypassPermissionFor(session, () => liveBypassPermission(session)),paneSwapDeps(session, pane, built.overrides),)if (!outcome.ok) {@@ -4823,10 +4833,11 @@ async function runForeground(session: AuthSession): Promise<void> {* mid-kill, or — worse — mint a brand-new agent for the relaunched process the instant it appears,* before this handler gets to rebind it.*- * The bypass-permission mode is read from the LIVE process argv before anything is signalled (there is- * nowhere else to read it from once the process is dead); the sessionId to resume comes from the- * registry's live-synced field, not from the original launch argv (the user may have resumed/switched- * sessions from inside the engine's own terminal since launch).+ * The permission mode comes from the registry row (`bypassPermissionFor`): what create recorded, or+ * what discovery read off the live argv since — the live process is probed only for a row that has+ * neither, and before anything is signalled. The sessionId to resume comes from the registry's+ * live-synced field, not from the original launch argv (the user may have resumed/switched sessions+ * from inside the engine's own terminal since launch).*/backend.onRestartAgent = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {const session = registry.resolve(agentId)@@ -4847,8 +4858,13 @@ async function runForeground(session: AuthSession): Promise<void> {if (isTerminalEngine(engine)) {agentReconciler.holdRoute(routeKey)try {+ // The same opening a fresh terminal tile prints (`onCreateAgent`'s `terminalHint`): a+ // restarted tile is a fresh shell too, and should look like one.const respawned = await tmuxBackend.respawn(runtime, {- command: buildEngineLaunchArgv(engine, session.cwd ? { cwd: session.cwd } : {}),+ command: buildEngineLaunchArgv(engine, {+ ...(session.cwd ? { cwd: session.cwd } : {}),+ terminalHint: { machineName: terminalHintMachineName() },+ }),cwd: homedir(),})if (!current()) return changed@@ -4878,7 +4894,7 @@ async function runForeground(session: AuthSession): Promise<void> {agentReconciler.holdRoute(routeKey)try {- const bypassPermission = await liveBypassPermission(session)+ const bypassPermission = await bypassPermissionFor(session, () => liveBypassPermission(session))const outcome = await restartAgent({ engine, sessionId: session.sessionId },bypassPermission,diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex d38cc53dd..fa3a92757 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -1382,6 +1382,32 @@ describe('registry across a reboot and pane loss', () => {expect(saved[0]).not.toHaveProperty('bypassPermission')})+ it('fills in the permission mode discovery read off a live argv, and keeps it across a reload', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ const pending = registry.openPendingAgent({+ engine: 'claude',+ runtimes: [{ backend: 'tmux', paneId: '%9' }],+ cwd: '/tmp/demo',+ bypassPermission: true,+ })+ expect(pending).not.toHaveProperty('permissionMode')++ expect(registry.setPermissionMode(pending!.agentId, 'full')).toBe(true)+ expect(registry.byAgent(pending!.agentId)?.permissionMode).toBe('full')+ // Idempotent; fill-only, so the recorded mode is never re-derived into another; and a name that+ // is not a mode is refused as it is on load.+ expect(registry.setPermissionMode(pending!.agentId, 'full')).toBe(true)+ expect(registry.setPermissionMode(pending!.agentId, 'plan')).toBe(false)+ expect(registry.setPermissionMode(pending!.agentId, '--dangerously-skip-permissions')).toBe(false)+ expect(registry.setPermissionMode('nope', 'full')).toBe(false)+ expect(registry.byAgent(pending!.agentId)?.permissionMode).toBe('full')++ const { registry: reloaded } = await loadRegistryModule()+ reloaded.load()+ expect(reloaded.byAgent(pending!.agentId)?.permissionMode).toBe('full')+ })+const GRID_LAUNCH = {networkId: 'grid-abc',networkName: 'Team grid',diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex f946ee387..176916250 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -1586,6 +1586,20 @@ class Registry {return true}+ /** Fill in the mode a row did not record — discovery read it off the live argv — so a relaunch can+ * reapply exactly that mode rather than the yes/no `bypassPermission` reduces it to. Fill-only,+ * like `setCodexHome`: the mode create recorded is the person's choice and is never re-derived+ * (the same name again is a no-op). A name that is not a mode is refused, as on load. */+ setPermissionMode(agentId: string, permissionMode: string): boolean {+ const session = this.agents.get(agentId)+ if (!session || !permissionModeName(permissionMode)) return false+ if (session.permissionMode) return session.permissionMode === permissionMode+ session.permissionMode = permissionMode+ session.updatedAt = Date.now()+ this.save()+ return true+ }+/** Fill in the Codex profile a row did not know (discovery read it off the live process). Never* replaces one it already has — the profile is chosen once, see `codexHome`. */setCodexHome(agentId: string, codexHome: string): boolean {diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.tsindex fc3246ea2..caf998538 100644--- a/cli/src/lib/restartAgent.spec.ts+++ b/cli/src/lib/restartAgent.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { AgentRestartCoordinator, restartAgent, type RestartAgentDeps } from './restartAgent.js'+import { AgentRestartCoordinator, bypassPermissionFor, restartAgent, type RestartAgentDeps } from './restartAgent.js'import type { ProcessIdentity } from './registry.js'const IDENTITY: ProcessIdentity = { pid: 555, executable: 'claude', startMarker: 'Mon Aug 3 09:05:00 2026' }@@ -219,3 +219,29 @@ describe('restart cancellation', () => {expect(await coordinator.run('a', async () => ({ ok: false, error: 'fresh' }))).toEqual({ ok: false, error: 'fresh' })})})++describe('bypassPermissionFor', () => {+ const probe = () => {+ const fn = vi.fn(async () => true)+ return fn+ }++ it('answers from the recorded mode without touching the live process', async () => {+ const live = probe()+ await expect(bypassPermissionFor({ permissionMode: 'full' }, live)).resolves.toBe(true)+ await expect(bypassPermissionFor({ permissionMode: 'auto', bypassPermission: false }, live)).resolves.toBe(true)+ // Plan is not a yes, whatever the boolean beside it says.+ await expect(bypassPermissionFor({ permissionMode: 'plan', bypassPermission: true }, live)).resolves.toBe(false)+ await expect(bypassPermissionFor({ permissionMode: 'ask' }, live)).resolves.toBe(false)+ expect(live).not.toHaveBeenCalled()+ })++ it('falls back to the recorded flag, then to the live process only for a row that has neither', async () => {+ const live = probe()+ await expect(bypassPermissionFor({ bypassPermission: true }, live)).resolves.toBe(true)+ await expect(bypassPermissionFor({ bypassPermission: false }, live)).resolves.toBe(false)+ expect(live).not.toHaveBeenCalled()+ await expect(bypassPermissionFor({}, live)).resolves.toBe(true)+ expect(live).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.tsindex 9e288d3c0..f7f994d63 100644--- a/cli/src/lib/restartAgent.ts+++ b/cli/src/lib/restartAgent.ts@@ -12,6 +12,27 @@import type { AgentEngine } from '../engines/types.js'import type { RegisteredSession, ProcessIdentity } from './registry.js'import type { TerminateOutcome } from './deleteAgentFallback.js'+import { permissionModeApproves } from './engineLaunch.js'++/**+ * Whether the relaunch approves on its own — from the ROW first, and the live process only for a row+ * that never learned.+ *+ * The row is what create wrote and what discovery keeps in step with the live argv, so it is the+ * answer even once the process is dead or `ps` has failed. Reading the live argv instead was the+ * original design (there was nothing else to read then), and it is what lost the flag: a `ps` that+ * timed out read as "no", and an agent typed into a terminal with the skip-everything flag came back+ * in the auto mode. The mode outranks the boolean — Plan is not a yes — and `buildArgv` reapplies the+ * mode itself; this only settles the yes/no the engines without a mode table launch with.+ */+export async function bypassPermissionFor(+ session: Pick<RegisteredSession, 'permissionMode' | 'bypassPermission'>,+ probeLive: () => Promise<boolean>,+): Promise<boolean> {+ if (session.permissionMode) return permissionModeApproves(session.permissionMode)+ if (session.bypassPermission !== undefined) return session.bypassPermission+ return probeLive()+}export type RestartOutcome =| { ok: true; processIdentity: ProcessIdentity; resumed: boolean }diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex 3ed39b39d..cc0c40199 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -7,6 +7,7 @@ import type { AgentCommandOwnershipSnapshot } from './engineBin.js'import {ambiguousAgentProcess,bypassPermissionActive,+ permissionModeFromArgv,engineProcessMatch,engineProcessMatchScore,LSTART_MARKER_RE,@@ -283,11 +284,41 @@ describe('tmux process primitives', () => {expect(resumeSessionId('claude', 'claude --continue')).toBeNull()})+ it('reads the exact permission mode a live process was launched with', () => {+ expect(permissionModeFromArgv('claude', '/usr/local/bin/claude --dangerously-skip-permissions')).toBe('full')+ expect(permissionModeFromArgv('claude', 'claude --permission-mode plan --resume abc')).toBe('plan')+ expect(permissionModeFromArgv('claude', 'claude --permission-mode=acceptEdits')).toBe('acceptEdits')+ expect(permissionModeFromArgv('claude', 'claude --permission-mode auto')).toBe('auto')+ expect(permissionModeFromArgv('codex', 'codex --dangerously-bypass-approvals-and-sandbox')).toBe('full')+ expect(permissionModeFromArgv('codex', 'codex --sandbox read-only')).toBe('readOnly')+ expect(permissionModeFromArgv('codex', 'codex resume abc --approve-for-me')).toBe('auto')+ expect(permissionModeFromArgv('cursor', 'cursor-agent --force')).toBe('auto')+ expect(permissionModeFromArgv('opencode', 'opencode --auto')).toBe('auto')+ // Skip-everything outranks a mode named beside it: that process runs without permissions.+ expect(permissionModeFromArgv('claude', 'claude --permission-mode plan --dangerously-skip-permissions')).toBe('full')+ })++ it('names no mode for an argv that carries none — never `ask`, never a guess', () => {+ // No flag is silence, not a choice; `bypassPermission` keeps deciding there.+ expect(permissionModeFromArgv('claude', 'claude --resume abc')).toBeNull()+ // A mode the table does not know cannot be reapplied, so it is not recorded.+ expect(permissionModeFromArgv('claude', 'claude --permission-mode bogus')).toBeNull()+ expect(permissionModeFromArgv('claude', 'claude --permission-mode manual auto')).toBeNull()+ expect(permissionModeFromArgv('codex', 'codex --sandbox workspace-write')).toBeNull()+ // Only an exact token counts, as for the bypass flag.+ expect(permissionModeFromArgv('claude', 'claude "please avoid --dangerously-skip-permissions for now"')).toBeNull()+ expect(permissionModeFromArgv('claude', 'claude --dangerously-skip-permissions-explained')).toBeNull()+ // Engines with no mode table.+ expect(permissionModeFromArgv('pi', 'pi --dangerously-skip-permissions')).toBeNull()+ expect(permissionModeFromArgv('terminal', 'zsh -l')).toBeNull()+ })+it('reads bypass-permission mode from a live process argv via exact token match', () => {expect(bypassPermissionActive('claude', '/usr/local/bin/claude --permission-mode auto')).toBe(true)expect(bypassPermissionActive('claude', 'claude --permission-mode=auto --resume abc')).toBe(true)expect(bypassPermissionActive('codex', 'codex resume abc --approve-for-me')).toBe(true)- // Launched before the auto modes: the old flags still count, and a relaunch uses the auto mode.+ // Launched before the auto modes: the old flags still count as approving (and, recorded as the+ // `full` mode, come back as themselves on a relaunch).expect(bypassPermissionActive('claude', '/usr/local/bin/claude --dangerously-skip-permissions')).toBe(true)expect(bypassPermissionActive('codex', 'codex --dangerously-bypass-approvals-and-sandbox'))@@ -307,6 +338,7 @@ describe('tmux process primitives', () => {expect(bypassPermissionActive('claude', 'claude --resume abc')).toBe(false)// Another mode, or "auto" that is not the mode's value.expect(bypassPermissionActive('claude', 'claude --permission-mode plan')).toBe(false)+ expect(bypassPermissionActive('codex', 'codex --sandbox read-only')).toBe(false)expect(bypassPermissionActive('claude', 'claude --permission-mode manual auto')).toBe(false)expect(bypassPermissionActive('claude', 'claude auto --permission-mode')).toBe(false)})diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 33494e851..2d4de2e18 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -14,7 +14,7 @@ import {executableFileIdentity,type AgentCommandOwnershipSnapshot,} from './engineBin.js'-import { BYPASS_PERMISSION_FLAGS } from './engineLaunch.js'+import { BYPASS_PERMISSION_FLAGS, PERMISSION_MODES, permissionModeApproves } from './engineLaunch.js'import { psEnv } from './childLocale.js'function cleanPaneTitle(title: string): string | null {@@ -585,28 +585,55 @@ const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]/*** Whether a live process's argv already contains every flag this engine's confirmed bypass-permission- * mode requires — read from the running process BEFORE restart signals it, so the relaunch can reapply- * the exact autonomy mode the agent had (there is nowhere else to read it from once the process is- * dead). Token-exact via `argvTokens`, not a substring `.includes()` check on the raw string, so a- * prompt or argument that merely CONTAINS the flag text cannot false-positive. Engines with no- * confirmed bypass flag (`BYPASS_PERMISSION_FLAGS[engine] === null`) always read false — never guess.+ * mode requires. Discovery reads it off every running agent and keeps the registry row's+ * `bypassPermission` in step with it, which is what a relaunch reads (a row written before the field+ * existed learns it here). Token-exact via `argvTokens`, not a substring `.includes()` check on the raw+ * string, so a prompt or argument that merely CONTAINS the flag text cannot false-positive. Engines+ * with no confirmed bypass flag (`BYPASS_PERMISSION_FLAGS[engine] === null`) always read false — never+ * guess.*/export function bypassPermissionActive(engine: RegisteredSession['engine'], args: string): boolean {const flags = BYPASS_PERMISSION_FLAGS[engine]if (!flags) return false+ // A named mode says exactly how much the engine approves on its own (`full` — the old+ // skip-everything flag — included); only an argv naming none falls back to the bare flag check.const tokens = argvTokens(args)- // The flags in order, as launch writes them (`--permission-mode auto` is two tokens, and "auto"- // alone elsewhere in argv is not the mode) — or `--flag=value` as one.- const inOrder = (want: readonly string[]): boolean => tokens.some((_, i) => want.every((flag, j) => tokens[i + j] === flag))- || (want.length === 2 && tokens.includes(`${want[0]}=${want[1]}`))- // An agent launched before the auto modes carried the old skip-everything flag; it still counts as- // approving on its own, and a relaunch brings it back in the auto mode.- return inOrder(flags) || (LEGACY_BYPASS_FLAGS[engine] ?? []).some((legacy) => inOrder(legacy))+ const mode = permissionModeFromTokens(engine, tokens)+ return mode ? permissionModeApproves(mode) : flagsInOrder(tokens, flags)+}++/**+ * The permission mode a live process's argv names — the inverse of `permissionModeFlags`, so the row+ * of an agent somebody typed into a terminal (or one written before modes were recorded) can carry+ * the SAME mode a created one does, and a relaunch brings it back exactly: `--dangerously-skip-permissions`+ * comes back as `--dangerously-skip-permissions`, not downgraded to the auto mode. Null when argv+ * names no mode — which is not `ask` (a person picking Ask records it; an argv with no flag is just+ * silent), so `bypassPermission` keeps deciding there as before. Token-exact like+ * `bypassPermissionActive`; an engine with no mode table reads null.+ */+export function permissionModeFromArgv(engine: RegisteredSession['engine'], args: string): string | null {+ return permissionModeFromTokens(engine, argvTokens(args))}-const LEGACY_BYPASS_FLAGS: Partial<Record<RegisteredSession['engine'], string[][]>> = {- claude: [['--dangerously-skip-permissions']],- codex: [['--dangerously-bypass-approvals-and-sandbox']],+function permissionModeFromTokens(engine: RegisteredSession['engine'], tokens: readonly string[]): string | null {+ const modes = PERMISSION_MODES[engine]+ if (!modes) return null+ // `full` is checked ahead of the rest where the engine has it: its flag is a single token no other+ // mode shares, and an argv carrying both it and `--permission-mode` is running without permissions+ // whatever else it says. `ask` is empty and can never be "found".+ const names = ['full', ...Object.keys(modes).filter((mode) => mode !== 'full')]+ for (const mode of names) {+ const flags = modes[mode]+ if (flags?.length && flagsInOrder(tokens, flags)) return mode+ }+ return null+}++/** The flags in order, as launch writes them (`--permission-mode auto` is two tokens, and "auto"+ * alone elsewhere in argv is not the mode) — or `--flag=value` as one. */+function flagsInOrder(tokens: readonly string[], want: readonly string[]): boolean {+ return tokens.some((_, i) => want.every((flag, j) => tokens[i + j] === flag))+ || (want.length === 2 && tokens.includes(`${want[0]}=${want[1]}`))}/** The session id an engine was told to resume, or null when argv does not name one. */