Skip to content

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.

feat(agents): vanilla-env 'Restart on subscription' — strip gateway/inherited provider env to relaunch an agent vanilla

Darren Kattan7380a26aa4de
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index ad0403235..27e627782 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -99,7 +99,7 @@ import {
} from './codex-identity-proxy'
import { ensureNodeToken, ensureRemoteNodeToken, sweepNodeToken } from './agents/node-token-service'
import { clearNode as clearNodeAgentStatus } from './agent-status-mirror'
-import { hasSharedIdentity, setCustomAgentBaseResolver, type AgentId } from '../shared/agents/config'
+import { hasSharedIdentity, setCustomAgentBaseResolver, vanillaEnvStripPattern, type AgentId } from '../shared/agents/config'
import { findCustomAgent } from '../shared/agents/custom-agent'
import { applyCustomAgentEnv, customAgentEnvArgs } from './custom-agent-env'
import {
@@ -2767,17 +2767,34 @@ export class PtyManager {
// A plain terminal has no agentId and must never receive provider credentials. The hook env's
// historical Claude fallback does not apply here: gateway access is an explicit agent
// capability, not a terminal default.
- const gatewayEnv = options.agentId
- ? modelGatewayEnv(
- this.getSettings().modelGateway,
- options.agentId,
- options.agentModel,
- process.env as Record<string, string | undefined>,
- this.getModelGatewaySecret()
- )
- : {}
+ //
+ // "Restart on subscription" / `vanillaLaunchDefault`: strip the gateway + inherited provider env
+ // so the agent runs against its OWN default provider (Claude's subscription, Copilot's GitHub
+ // routing). `vanillaEnvStripPattern` resolves through the base harness; null ⇒ the agent has no
+ // strip set ⇒ no-op (gemini/grok/opencode are left alone). `buildPtyEnv` runs only in `spawnNew`
+ // (a fresh session), never on a warm reattach, so toggling the setting never strips an
+ // already-running session — only the next fresh launch.
+ const stripRe =
+ options.clearEnv || this.getSettings().vanillaLaunchDefault
+ ? vanillaEnvStripPattern((options.agentId ?? 'claude') as AgentId)
+ : null
+ const gatewayEnv =
+ options.agentId && !stripRe
+ ? modelGatewayEnv(
+ this.getSettings().modelGateway,
+ options.agentId,
+ options.agentModel,
+ process.env as Record<string, string | undefined>,
+ this.getModelGatewaySecret()
+ )
+ : {}
if (!options.sshRemote) {
for (const [k, v] of Object.entries(gatewayEnv)) env[k] = v
+ // Strip inherited provider vars so a vanilla session does not fall back to a LaunchAgent-set
+ // ANTHROPIC_BASE_URL instead of the subscription. Local only — see the note above.
+ if (stripRe) {
+ for (const k of Object.keys(env)) if (stripRe.test(k)) delete env[k]
+ }
}
// The OWNING project's env (`.nodeterm/settings.json`, local overlay + TRUSTED shared half —
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index b742685f5..d0d880722 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -392,6 +392,175 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
}
})
+ // "Restart on subscription": clearEnv spawns the session VANILLA — skip the gateway AND strip
+ // inherited provider vars (a LaunchAgent/zshrc export a GUI launch still inherits) so the agent
+ // falls back to its OWN default provider. Both moves are gated on the agent's vanillaEnvPattern
+ // (resolved through its base harness). The strip runs BEFORE custom-agent env, so a user who
+ // explicitly declares a provider var on a custom agent still wins.
+ it('clearEnv skips the gateway and strips inherited provider env for claude', async () => {
+ const inheritedBase = process.env.ANTHROPIC_BASE_URL
+ const inheritedKey = process.env.ANTHROPIC_API_KEY
+ const inheritedDir = process.env.CLAUDE_CONFIG_DIR
+ process.env.ANTHROPIC_BASE_URL = 'https://launchagent-gateway.example.test'
+ process.env.ANTHROPIC_API_KEY = 'sk-inherited'
+ process.env.CLAUDE_CONFIG_DIR = '/home/me/.nodeterm/claude-accounts/abc'
+ try {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: {
+ baseUrl: 'https://bifrost.example.test',
+ apiKey: 'vk-gateway'
+ }
+ }))
+ m.registerIpc()
+
+ await create(80, 24, 'vanilla-claude', { agentId: 'claude', clearEnv: true })
+
+ const env = spawnArgs[0].env
+ // (1) the gateway is NOT injected …
+ expect(env.ANTHROPIC_BASE_URL).toBeUndefined()
+ expect(env.ANTHROPIC_AUTH_TOKEN).toBeUndefined()
+ // … and (2) the INHERITED provider vars are stripped too, so the session does not fall back
+ // to the LaunchAgent-set base URL instead of the subscription.
+ expect(env.ANTHROPIC_BASE_URL).toBeUndefined()
+ expect(env.ANTHROPIC_API_KEY).toBeUndefined()
+ // CLAUDE_CONFIG_DIR is the managed-account dir, NOT a provider credential — stripping it
+ // would break account isolation, so it survives a vanilla relaunch.
+ expect(env.CLAUDE_CONFIG_DIR).toBe('/home/me/.nodeterm/claude-accounts/abc')
+ } finally {
+ for (const [k, v] of [
+ ['ANTHROPIC_BASE_URL', inheritedBase],
+ ['ANTHROPIC_API_KEY', inheritedKey],
+ ['CLAUDE_CONFIG_DIR', inheritedDir]
+ ] as const) {
+ if (v === undefined) delete process.env[k]
+ else process.env[k] = v
+ }
+ }
+ })
+
+ it('clearEnv is one-directional: unset, the gateway is injected as usual', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-gateway' }
+ }))
+ m.registerIpc()
+
+ await create(80, 24, 'gateway-claude', { agentId: 'claude' })
+
+ expect(spawnArgs[0].env.ANTHROPIC_BASE_URL).toBe('https://bifrost.example.test/anthropic')
+ expect(spawnArgs[0].env.ANTHROPIC_AUTH_TOKEN).toBe('vk-gateway')
+ })
+
+ it('clearEnv strips COPILOT_PROVIDER_* for copilot but keeps the home dir', async () => {
+ const inheritedHome = process.env.COPILOT_HOME
+ const inheritedProviderKey = process.env.COPILOT_PROVIDER_API_KEY
+ process.env.COPILOT_HOME = '/home/me/.copilot'
+ process.env.COPILOT_PROVIDER_API_KEY = 'sk-inherited'
+ try {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-gateway' }
+ }))
+ m.registerIpc()
+
+ await create(80, 24, 'vanilla-copilot', { agentId: 'copilot', clearEnv: true })
+
+ const env = spawnArgs[0].env
+ // Gateway + inherited provider vars both gone.
+ expect(env.COPILOT_PROVIDER_API_KEY).toBeUndefined()
+ expect(env.COPILOT_PROVIDER_BASE_URL).toBeUndefined()
+ // Home dir is a config dir, not a credential — survives.
+ expect(env.COPILOT_HOME).toBe('/home/me/.copilot')
+ } finally {
+ for (const [k, v] of [
+ ['COPILOT_HOME', inheritedHome],
+ ['COPILOT_PROVIDER_API_KEY', inheritedProviderKey]
+ ] as const) {
+ if (v === undefined) delete process.env[k]
+ else process.env[k] = v
+ }
+ }
+ })
+
+ // The global "Launch on subscription" default is the counterpart to the per-node `clearEnv`
+ // recycle: read LIVE at spawn, so a fresh launch strips the gateway + inherited provider env
+ // WITHOUT a per-node flag (and survives a reboot, since the setting is the source of truth, not
+ // a one-shot data field that is cleared after its single use).
+ it('vanillaLaunchDefault strips the gateway + inherited env on a fresh spawn (no per-node clearEnv)', async () => {
+ const inheritedBase = process.env.ANTHROPIC_BASE_URL
+ const inheritedDir = process.env.CLAUDE_CONFIG_DIR
+ process.env.ANTHROPIC_BASE_URL = 'https://launchagent-gateway.example.test'
+ process.env.CLAUDE_CONFIG_DIR = '/home/me/.nodeterm/claude-accounts/abc'
+ try {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ vanillaLaunchDefault: true,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-gateway' }
+ }))
+ m.registerIpc()
+
+ // No `clearEnv` on the node — the SETTING is what strips. This is the new-session case the
+ // per-node action could not serve (it recycles, which needs a session with turns to resume).
+ await create(80, 24, 'vanilla-default-claude', { agentId: 'claude' })
+
+ const env = spawnArgs[0].env
+ expect(env.ANTHROPIC_BASE_URL).toBeUndefined()
+ expect(env.ANTHROPIC_AUTH_TOKEN).toBeUndefined()
+ // Inherited provider var stripped too — no fall-back to the LaunchAgent gateway.
+ expect(env.ANTHROPIC_BASE_URL).toBeUndefined()
+ // Account isolation survives (config dir is not a provider credential).
+ expect(env.CLAUDE_CONFIG_DIR).toBe('/home/me/.nodeterm/claude-accounts/abc')
+ } finally {
+ for (const [k, v] of [
+ ['ANTHROPIC_BASE_URL', inheritedBase],
+ ['CLAUDE_CONFIG_DIR', inheritedDir]
+ ] as const) {
+ if (v === undefined) delete process.env[k]
+ else process.env[k] = v
+ }
+ }
+ })
+
+ it('vanillaLaunchDefault is a no-op for an agent with no strip pattern, and off keeps the gateway', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ vanillaLaunchDefault: true,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-gateway' }
+ }))
+ m.registerIpc()
+
+ // gemini has no vanillaEnvPattern (and no gateway route at all) → the setting strips nothing
+ // and the spawn proceeds normally. A global toggle must not change an agent it does not cover:
+ // a non-provider env var (PATH) survives the strip pass untouched. (A provider var inherited
+ // from the host env is NOT stripped either — gemini has no pattern — which is the no-op.)
+ await create(80, 24, 'vanilla-default-gemini', { agentId: 'gemini' })
+ expect(typeof spawnArgs[0].env.PATH).toBe('string')
+
+ // And with the setting OFF (the default), a claude spawn keeps the gateway — the non-disruptive
+ // upgrade guarantee for existing users. (spawnArgs accumulates within a test: this is [1].)
+ const m2 = new PtyManager()
+ m2.init(() => ({
+ ...DEFAULT_SETTINGS,
+ vanillaLaunchDefault: false,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-gateway' }
+ }))
+ m2.registerIpc()
+ await create(80, 24, 'gateway-claude-default-off', { agentId: 'claude' })
+ expect(spawnArgs[1].env.ANTHROPIC_BASE_URL).toBe('https://bifrost.example.test/anthropic')
+ expect(spawnArgs[1].env.ANTHROPIC_AUTH_TOKEN).toBe('vk-gateway')
+ })
+
// ── `fresh` drives scrollback replay + agent resume: it must still be computed from tmux ──
it('fresh:false on a WARM reattach (tmux session already exists) — no cold restore', async () => {
await tmuxManager()
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 229dd8ae4..af905ca6a 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -318,6 +318,7 @@ import {
agentRestartFn,
guardConcurrentRestart,
planBulkRestart,
+ clearEnvEligibility,
restartEligibility,
restartSessionId,
settleRestart,
@@ -412,8 +413,10 @@ import {
canRename,
canContextLink,
canSwitchModel,
+ capabilityAgentId,
createdAgentId,
resumeCommand,
+ vanillaEnvStripPattern,
AGENT_CONFIG,
BUILTIN_AGENT_IDS,
type AgentId,
@@ -6198,20 +6201,23 @@ export function Canvas() {
nodeId: string,
targetAgentId?: AgentId,
targetModel?: string,
- restartShell?: boolean
+ restartShell?: boolean,
+ clearEnv?: boolean
) => {
const fn = agentRestartFn(nodeId)
if (!fn) return // node unmounted between opening the menu and clicking
- const action = restartShell
- ? 'Restart'
- : targetModel
- ? 'Model switch'
- : targetAgentId
- ? 'Reopen'
- : 'Restart'
+ const action = clearEnv
+ ? 'Restart on subscription'
+ : restartShell
+ ? 'Restart'
+ : targetModel
+ ? 'Model switch'
+ : targetAgentId
+ ? 'Reopen'
+ : 'Restart'
let outcome: RestartOutcome
try {
- outcome = await fn(targetAgentId, targetModel, restartShell)
+ outcome = await fn(targetAgentId, targetModel, restartShell, clearEnv)
} catch {
// The transport under the restart threw (a relay socket still CONNECTING rejects the very
// first write). Unhandled, this rejection made the action a silent no-op — the user clicked
@@ -6255,11 +6261,13 @@ export function Canvas() {
outcome === 'restarted'
? {
kind: 'info',
- text: targetModel
- ? `Switched to ${targetModel} — conversation resumed.`
- : targetLabel
- ? `Session reopened as ${targetLabel} — conversation resumed.`
- : 'Agent restarted — conversation resumed.'
+ text: clearEnv
+ ? 'Restarted on subscription — conversation resumed.'
+ : targetModel
+ ? `Switched to ${targetModel} — conversation resumed.`
+ : targetLabel
+ ? `Session reopened as ${targetLabel} — conversation resumed.`
+ : 'Agent restarted — conversation resumed.'
}
: outcome === 'exit-timeout'
? {
@@ -7993,6 +8001,44 @@ export function Canvas() {
: 'Quits the CLI, respawns a fresh shell (picks up env/profile changes), then resumes.'),
onClick: () => void restartAgentNode(ids[0], undefined, undefined, true)
},
+ // "Restart on subscription": recycle the session VANILLA — strip the gateway + inherited
+ // provider env so the agent falls back to its OWN default provider (Claude's
+ // subscription, Copilot's GitHub routing). No model/agent change; the cold-restore
+ // auto-resume keeps the same conversation. Shown only for an agent with a strip set
+ // (claude/codex/copilot builtins). Gated on `clearEnvEligibility`, NOT the shared `why`:
+ // clearEnv uses `terminateForeground` (SIGTERM by PID, no `/exit` into a dialog), so it
+ // is safe to interrupt a `working`/`blocked` session — which is its primary scenario
+ // (gateway overload shows up mid-turn, and "wait for the turn" is impossible when the
+ // gateway is down). Refused over relay for the same reason "Restart agent and shell" is
+ // — the stripped env belongs to this machine's settings store, not the host's core.
+ // Hideable (unlike the recovery restart rows above), because it is a convenience, not a
+ // recovery lever.
+ ...(vanillaEnvStripPattern(sourceAgentId ?? ('claude' as AgentId)) &&
+ !isHidden('vanilla-restart', hidden)
+ ? [
+ {
+ label:
+ capabilityAgentId(sourceAgentId ?? ('claude' as AgentId)) === 'copilot'
+ ? 'Restart on Copilot defaults'
+ : 'Restart on subscription',
+ icon: <IconPower />,
+ disabled:
+ !clearEnvEligibility(sourceAgentId, sessionId).ok ||
+ session.source === 'relay' ||
+ !agentRestartFn(ids[0]),
+ hint:
+ !clearEnvEligibility(sourceAgentId, sessionId).ok
+ ? 'Nothing to resume yet — this session has not reported an id.'
+ : session.source === 'relay'
+ ? 'Restart the shell on the machine hosting this relay session.'
+ : !agentRestartFn(ids[0])
+ ? 'This terminal is not attached right now.'
+ : 'Restarts the session with gateway/provider env stripped — uses your own subscription/credentials.',
+ onClick: () =>
+ void restartAgentNode(ids[0], undefined, undefined, undefined, true)
+ }
+ ]
+ : []),
...(variants.length
? ([
{
diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsx
index 6a8b922c5..2f7c64927 100644
--- a/src/renderer/components/settings/sections/AgentsSection.tsx
+++ b/src/renderer/components/settings/sections/AgentsSection.tsx
@@ -72,6 +72,22 @@ const ROWS = {
'opencode'
]
},
+ vanillaLaunch: {
+ title: 'Launch on subscription',
+ keywords: [
+ 'subscription',
+ 'vanilla',
+ 'gateway',
+ 'provider',
+ 'default',
+ 'anthropic',
+ 'openai',
+ 'copilot',
+ 'env',
+ 'credentials',
+ 'clear env'
+ ]
+ },
permissionMode: {
title: 'Permission mode',
keywords: [
@@ -441,6 +457,19 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
))}
</div>
</SearchableRow>
+ <SearchableRow {...ROWS.vanillaLaunch}>
+ <FieldRow
+ label="Launch on subscription"
+ description="Spawn every fresh agent session with gateway and inherited provider env stripped, so it runs against its OWN default provider — Claude's subscription, Copilot's GitHub routing — instead of a configured model gateway or a LaunchAgent-set override. The per-node “Restart on subscription” action does the same for one node; this is its global counterpart. The managed-account config dir is kept, so account isolation survives. Off by default — it changes which provider every agent node uses."
+ control={
+ <Switch
+ checked={settings.vanillaLaunchDefault}
+ ariaLabel="Launch on subscription by default"
+ onChange={(on) => update({ vanillaLaunchDefault: on })}
+ />
+ }
+ />
+ </SearchableRow>
<SearchableRow {...ROWS.permissionMode}>
<FieldRow
label="Permission mode"
diff --git a/src/renderer/lib/ui-visibility.test.ts b/src/renderer/lib/ui-visibility.test.ts
index 0db7422ad..be8f8efbc 100644
--- a/src/renderer/lib/ui-visibility.test.ts
+++ b/src/renderer/lib/ui-visibility.test.ts
@@ -24,7 +24,7 @@ describe('hideable inventories', () => {
it('list the agreed ids and nothing destructive', () => {
expect(HIDEABLE_MENU_ITEMS.map((r) => r.id)).toEqual([
'group', 'remove-from-group', 'colors', 'icon', 'duplicate', 'snap-zone', 'collapse',
- 'markdown-view', 'refresh-terminal'
+ 'markdown-view', 'refresh-terminal', 'vanilla-restart'
])
expect(HIDEABLE_HEADER_BUTTONS.map((r) => r.id)).toEqual([
'maximize', 'refresh', 'mic', 'ai-name', 'comments', 'hide-fanout', 'tidy-fanout'
diff --git a/src/renderer/lib/ui-visibility.ts b/src/renderer/lib/ui-visibility.ts
index 312211f60..9171f262c 100644
--- a/src/renderer/lib/ui-visibility.ts
+++ b/src/renderer/lib/ui-visibility.ts
@@ -27,7 +27,8 @@ export const HIDEABLE_MENU_ITEMS: readonly HideableRow[] = [
{ id: 'snap-zone', label: 'Snap to zone' },
{ id: 'collapse', label: 'Collapse / Expand' },
{ id: 'markdown-view', label: 'Markdown view' },
- { id: 'refresh-terminal', label: 'Refresh terminal' }
+ { id: 'refresh-terminal', label: 'Refresh terminal' },
+ { id: 'vanilla-restart', label: 'Restart on subscription' }
]
/** Hideable terminal node header buttons, in header order. */
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 7211e4ca2..176add5fa 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -125,6 +125,7 @@ import {
registerAgentHibernate,
registerAgentPause,
registerAgentRestart,
+ clearEnvEligibility,
restartEligibility,
restartSessionId,
RESTART_EXIT_TIMEOUT_MS,
@@ -2995,6 +2996,9 @@ export function TerminalNode({
ownerProjectId: sshProjectId ?? useProjects.getState().activeProjectId,
agentId: data.agentId,
agentModel: data.agentModel,
+ // "Restart on subscription": ride the spawn's env-strip path. Cleared below once the
+ // spawn resolves so an ordinary Restart re-applies the gateway (one-shot).
+ clearEnv: data.clearEnv === true,
accountId: data.accountId,
sshRemote,
// Belt AND braces: the guard above cannot see a `ssh` executable that has gone missing,
@@ -3356,6 +3360,11 @@ export function TerminalNode({
// the auto-resume branch below must be skipped — only an explicit Resume (which reuses the
// same command-building path through the registered hibernate/wake pair) may relaunch it.
const pausedNow = !!useAgentStatus.getState().byId[id]?.paused
+ // The clear-env strip is one-shot: once this spawn has applied it, clear the flag so a later
+ // ordinary Restart re-applies the gateway. (The recycle action re-sets it for its own spawn.)
+ if (data.clearEnv) {
+ updateNodeData(id, { clearEnv: undefined })
+ }
// Run a one-shot command on first open (e.g. "gh auth login" or the agent CLI), then
// forget it.
if (data.initialCommand) {
@@ -3599,7 +3608,7 @@ export function TerminalNode({
}
const unregisterRestart = registerAgentRestart(
id,
- guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean) => {
+ guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean, clearEnv?: boolean) => {
const st = useAgentStatus.getState().byId[id]
const currentNode = getNode(id)
const agentSessionId = restartSessionId(st?.sessionId, currentNode?.data.agentSessionId)
@@ -3608,6 +3617,37 @@ export function TerminalNode({
// value captured when the pane attached, or a later plain Restart would silently reopen
// the old agent again.
const sourceAgentId = createdAgentId(currentNode?.data)
+ // "Restart on subscription": recycle the session VANILLA — strip the gateway + inherited
+ // provider env so the agent falls back to its OWN default provider (Claude's subscription,
+ // Copilot's GitHub routing). No model change, no agent change: same agent, same
+ // conversation, resumed by the cold-restore path once the fresh shell is up. It recycles
+ // (not in-place `/exit`) for the same reason a model switch does — tmux env changes do not
+ // retroactively change an existing shell, so the gateway vars baked into the live session
+ // can only be dropped by respawning. Relay sessions belong to another core/settings store,
+ // so this Mac's gateway-stripped env must never be pushed into one.
+ //
+ // This branch is gated SEPARATELY from the shared `restartEligibility` below: clearEnv
+ // uses `terminateForeground` (SIGTERM the foreground group by PID — no `/exit` typed into
+ // the pane), so it is safe to interrupt a `working`/`blocked` session. Gateway overload —
+ // the scenario this exists for — shows up mid-turn, and "wait for the turn to finish" is
+ // impossible when the gateway is down. `clearEnvEligibility` permits busy for that reason;
+ // `restartEligibility` must NOT, because its `/exit` would answer a permission dialog.
+ if (clearEnv) {
+ if (session.source === 'relay') return 'not-eligible'
+ const clearGate = clearEnvEligibility(sourceAgentId, agentSessionId)
+ if (!clearGate.ok || !sourceAgentId) return 'not-eligible'
+ // Identity-gated (same as a model switch): core SIGTERMs the foreground group ONLY if
+ // this agent still owns it, so a stale menu can never kill vim or a build in this pane.
+ if (!(await api.pty.terminateForeground(id, sourceAgentId))) return 'not-eligible'
+ transport.recycle(id)
+ // `clearEnv` rides the respawn's `transport.create` (read from data above) to strip env at
+ // spawn; the cold-restore auto-resume relaunches the same agent against the default provider.
+ updateNodeData(id, (node) => ({
+ clearEnv: true,
+ respawnNonce: ((node.data.respawnNonce as number | undefined) ?? 0) + 1
+ }))
+ return 'restarted'
+ }
const gate = restartEligibility(sourceAgentId, st?.state, agentSessionId)
if (!gate.ok || !sourceAgentId || !agentSessionId || !restartTarget())
return 'not-eligible'
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index e6666de20..2d1a0f26c 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -95,6 +95,29 @@ export function restartSessionId(live: unknown, persisted: unknown): string | un
return undefined
}
+/**
+ * "Restart on subscription" (clear-env) has the same interruption contract as a model switch: it
+ * never writes the harness exit command into the composer — core proves the expected agent owns
+ * the foreground process group and terminates that group by PID before the pane is recycled — so a
+ * `working` or `blocked` session may be interrupted safely (unlike `restartEligibility`, which must
+ * reject those states because its `/exit` would be typed AS THE ANSWER to a permission dialog).
+ * Gateway overload — the scenario this feature exists for — shows up mid-turn: the turn is stuck or
+ * failing, and "wait for the turn to finish" is exactly what you cannot do when the gateway is down.
+ *
+ * The durable requirements are shared with restart: the harness must support resume and there must
+ * be a provider session id to carry into the replacement process. The strip set itself is checked
+ * by the caller through `vanillaEnvStripPattern` (only claude/codex/copilot builtins have one).
+ */
+export function clearEnvEligibility(
+ agentId: string | undefined,
+ sessionId: string | undefined
+): { ok: true } | { ok: false; reason: Exclude<IneligibleReason, 'working'> } {
+ if (!agentId || !canResume(agentId) || !exitSequence(agentId))
+ return { ok: false, reason: 'not-resumable' }
+ if (!sessionId) return { ok: false, reason: 'no-session' }
+ return { ok: true }
+}
+
export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible'
export const RESTART_EXIT_TIMEOUT_MS = 6000
@@ -451,7 +474,13 @@ export function guardConcurrentRestart<T extends string, Args extends unknown[]>
export type AgentRestartFn = (
targetAgentId?: AgentId,
targetModel?: string,
- restartShell?: boolean
+ restartShell?: boolean,
+ // "Restart on subscription": recycle the session VANILLA — strip the gateway + inherited
+ // provider env so the agent falls back to its OWN default provider. No model/agent change; the
+ // cold-restore auto-resume keeps the same conversation. Uses `clearEnvEligibility` (permits busy,
+ // since `terminateForeground` is PID-safe — no `/exit` typed into a dialog) and recycles the same
+ // way a model switch does, because tmux env changes do not retroactively change an existing shell.
+ clearEnv?: boolean
) => Promise<RestartOutcome>
const restartFns = new Map<string, AgentRestartFn>()
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index b22189c23..ec3dadcbf 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -60,7 +60,8 @@ describe('copilot capabilities', () => {
color: '#8957e5',
launchCmd: 'copilot',
promptInjectionMode: 'flag-interactive',
- expectedProcess: 'copilot'
+ expectedProcess: 'copilot',
+ vanillaEnvPattern: '^COPILOT_PROVIDER_'
})
expect(hasHooks('copilot')).toBe(true)
expect(canResume('copilot')).toBe(true)
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index a64994fca..5e15b49c2 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -32,6 +32,23 @@ export interface AgentConfig {
*/
argvPromptSeparator?: string
expectedProcess: string
+ /**
+ * Env var NAME pattern (regex source) to unset so the agent runs against its OWN default
+ * provider instead of a gateway/inherited override. Matched against the var name only, never
+ * the value. Stripped at spawn only when the node opts into "clear env" (a one-shot
+ * context-menu action) or the global `vanillaLaunchDefault` setting is on. Defined per builtin
+ * so the spawn site and the Settings toggle share one source of truth (a duplicated rule
+ * drifts). Resolved through the base harness via `vanillaEnvStripPattern`, so a custom agent
+ * inheriting a builtin (once custom-agent baseAgent lands) gets the same strip set.
+ *
+ * SECURITY: builtin patterns are static/trusted literals, but the value is a regex source applied
+ * to env var names. `vanillaEnvStripPattern` compiles it once behind a try/catch and caches; a
+ * malformed literal throws at compile (caught) and yields null (no strip). It is only ever
+ * `regex.test(envVarName)` in core — never `eval`'d or interpolated into a command. This mirrors
+ * the "re-validate at the interpolation site" rule (`isPermissionMode`, `SAFE_SESSION_ID`): the
+ * type is compile-time, the runtime match is guarded.
+ */
+ vanillaEnvPattern?: string
}
export const BUILTIN_AGENT_IDS: readonly BuiltinAgentId[] = [
@@ -49,14 +66,24 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
color: '#d97757',
launchCmd: 'claude',
promptInjectionMode: 'argv',
- expectedProcess: 'claude'
+ expectedProcess: 'claude',
+ // `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN`/`ANTHROPIC_API_KEY` (gateway + inherited) + the
+ // OAuth token. Deliberately EXCLUDES `CLAUDE_CONFIG_DIR` — that is the managed-account dir, not
+ // a provider credential; stripping it would break account isolation and is unrelated to "run on
+ // subscription". A broad `CLAUDE_*` is unsafe (`CLAUDE_CONFIG_DIR`, and nodeterm's own
+ // `CLAUDE_HOOK_EVENTS` etc. are code constants, not env the pane sets).
+ vanillaEnvPattern: '^(ANTHROPIC_|CLAUDE_CODE_OAUTH_TOKEN$)'
},
codex: {
label: 'Codex',
color: '#10a37f',
launchCmd: 'codex',
promptInjectionMode: 'argv',
- expectedProcess: 'codex'
+ expectedProcess: 'codex',
+ // The gateway vars only. Codex credentials live under `CODEX_HOME` (a config dir, like claude's)
+ // not `CODEX_*` env, so a broad `CODEX_*` strip is unverified and excluded. Narrowing to the two
+ // known gateway vars avoids touching unrelated `OPENAI_*` the user may set.
+ vanillaEnvPattern: '^(OPENAI_BASE_URL|OPENAI_API_KEY)$'
},
gemini: {
label: 'Gemini',
@@ -95,7 +122,10 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
// `--prompt` is explicitly non-interactive and exits after one response. The installed
// 1.0.80 CLI's `--interactive <prompt>` starts the ordinary TUI and submits the prompt there.
promptInjectionMode: 'flag-interactive',
- expectedProcess: 'copilot'
+ expectedProcess: 'copilot',
+ // All `COPILOT_PROVIDER_*` gateway vars. Excludes `COPILOT_HOME` (config dir) and
+ // `COPILOT_HOOK_*` (nodeterm constants).
+ vanillaEnvPattern: '^COPILOT_PROVIDER_'
}
}
@@ -350,6 +380,31 @@ export function capabilityAgentId(id: AgentId): AgentId {
return baseAgentOf(id) ?? id
}
+/**
+ * The compiled env-var-NAME strip pattern for an agent, resolved through its base harness (so a
+ * custom agent inheriting a builtin gets the builtin's strip set once custom-agent baseAgent lands).
+ * `null` ⇒ the agent has no strip set (gemini/grok/opencode, or any unknown id) ⇒ the vanilla
+ * relaunch action is hidden and the strip is a no-op. Compiled once and cached; a malformed
+ * `vanillaEnvPattern` literal throws at compile, is caught, and yields `null` (no strip) — see the
+ * security note on `AgentConfig.vanillaEnvPattern`. The cache key is the regex SOURCE string, so two
+ * agents sharing a pattern share one compiled `RegExp`.
+ */
+const VANILLA_PATTERN_CACHE = new Map<string, RegExp | null>()
+export function vanillaEnvStripPattern(id: AgentId): RegExp | null {
+ const source = AGENT_CONFIG[capabilityAgentId(id) as BuiltinAgentId]?.vanillaEnvPattern
+ if (!source) return null
+ const cached = VANILLA_PATTERN_CACHE.get(source)
+ if (cached !== undefined) return cached
+ let compiled: RegExp | null
+ try {
+ compiled = new RegExp(source)
+ } catch {
+ compiled = null
+ }
+ VANILLA_PATTERN_CACHE.set(source, compiled)
+ return compiled
+}
+
const includes = (list: readonly string[], id: AgentId): boolean =>
list.includes(capabilityAgentId(id))
diff --git a/src/shared/agents/vanilla-env.test.ts b/src/shared/agents/vanilla-env.test.ts
new file mode 100644
index 000000000..ed7e41a72
--- /dev/null
+++ b/src/shared/agents/vanilla-env.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect, afterEach } from 'vitest'
+import { vanillaEnvStripPattern, setCustomAgentBaseResolver } from './config'
+
+afterEach(() => setCustomAgentBaseResolver(null))
+
+describe('vanillaEnvStripPattern', () => {
+ it('claude strips ANTHROPIC_* + the OAuth token but keeps the config dir', () => {
+ const re = vanillaEnvStripPattern('claude')!
+ expect(re).not.toBeNull()
+ // Provider + inherited auth vars the gateway and a LaunchAgent export.
+ expect(re.test('ANTHROPIC_BASE_URL')).toBe(true)
+ expect(re.test('ANTHROPIC_AUTH_TOKEN')).toBe(true)
+ expect(re.test('ANTHROPIC_API_KEY')).toBe(true)
+ expect(re.test('CLAUDE_CODE_OAUTH_TOKEN')).toBe(true)
+ // The managed-account config dir is NOT a provider credential — stripping it would break
+ // account isolation, so the pattern must leave it alone.
+ expect(re.test('CLAUDE_CONFIG_DIR')).toBe(false)
+ // nodeterm's own code constants (not env the pane sets) are left alone.
+ expect(re.test('CLAUDE_HOOK_EVENTS')).toBe(false)
+ })
+
+ it('codex strips only the two known gateway vars', () => {
+ const re = vanillaEnvStripPattern('codex')!
+ expect(re.test('OPENAI_BASE_URL')).toBe(true)
+ expect(re.test('OPENAI_API_KEY')).toBe(true)
+ // Codex credentials live under CODEX_HOME (a config dir), not CODEX_* env — a broad strip is
+ // unverified, so unrelated OPENAI_* the user may set must survive.
+ expect(re.test('OPENAI_ORG_ID')).toBe(false)
+ expect(re.test('CODEX_HOME')).toBe(false)
+ })
+
+ it('copilot strips COPILOT_PROVIDER_* but keeps the home dir + hook constants', () => {
+ const re = vanillaEnvStripPattern('copilot')!
+ expect(re.test('COPILOT_PROVIDER_API_KEY')).toBe(true)
+ expect(re.test('COPILOT_PROVIDER_BASE_URL')).toBe(true)
+ expect(re.test('COPILOT_HOME')).toBe(false)
+ expect(re.test('COPILOT_HOOK_EVENTS')).toBe(false)
+ })
+
+ it('gemini/grok/opencode have no pattern (the action is hidden for them)', () => {
+ expect(vanillaEnvStripPattern('gemini')).toBeNull()
+ expect(vanillaEnvStripPattern('grok')).toBeNull()
+ expect(vanillaEnvStripPattern('opencode')).toBeNull()
+ // A plain custom agent with no base inherits nothing.
+ expect(vanillaEnvStripPattern('custom:plain')).toBeNull()
+ })
+
+ it('a custom agent inherits its base harness pattern', () => {
+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))
+ const re = vanillaEnvStripPattern('custom:proxy')!
+ expect(re.test('ANTHROPIC_BASE_URL')).toBe(true)
+ expect(re.test('CLAUDE_CONFIG_DIR')).toBe(false)
+ })
+
+ it('is cached: the same source compiles once', () => {
+ const a = vanillaEnvStripPattern('claude')
+ const b = vanillaEnvStripPattern('claude')
+ expect(a).toBe(b) // referentially identical — the cache returns the same compiled RegExp
+ })
+})
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 285f14aad..5a14b6457 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -107,6 +107,14 @@ export interface PtyCreateOptions {
agentId?: AgentId
/** Per-node model override. Applied through the node's base harness on launch/cold restore. */
agentModel?: string
+ /**
+ * One-shot: spawn (or re-spawn after a recycle) with gateway + inherited provider env stripped
+ * so the agent runs against its OWN default provider (Claude's subscription, Copilot's GitHub
+ * routing) instead of the configured gateway/inherited override. The strip set is per-agent
+ * (`vanillaEnvStripPattern`); `CLAUDE_CONFIG_DIR` is deliberately kept (account isolation
+ * survives). Cleared after the spawn resolves so a later ordinary Restart re-applies the gateway.
+ */
+ clearEnv?: boolean
/** Managed Claude account: inject CLAUDE_CONFIG_DIR for this account into the session env. */
accountId?: string
/**
@@ -358,6 +366,13 @@ export interface CanvasNodeState {
agentId?: AgentId
/** Model selected for this agent node through the shared model gateway. */
agentModel?: string
+ /**
+ * One-shot "Restart on subscription" flag: when set, the next `transport.create` strips gateway +
+ * inherited provider env (per `vanillaEnvStripPattern`) so the agent resumes against its own
+ * default provider. Set by the clear-env recycle action, cleared after the spawn resolves so an
+ * ordinary Restart re-applies the gateway. See `PtyCreateOptions.clearEnv`.
+ */
+ clearEnv?: boolean
/** Set while this node is armed but not yet launched — see PendingLaunch. */
pendingLaunch?: PendingLaunch
/**
@@ -1553,6 +1568,15 @@ export interface Settings {
* driver runs in `default`). Overridable per project via Project.defaultPermissionMode.
* `auto` is version-gated: CLIs below 2.1.71 reject the value, so it degrades to no flag. */
claudePermissionMode: AgentPermissionMode
+ /**
+ * When on, EVERY fresh agent launch spawns with gateway + inherited provider env stripped, so the
+ * agent runs against its OWN default provider (Claude's subscription, Copilot's GitHub routing)
+ * instead of a configured gateway/inherited override. The per-node one-shot `data.clearEnv`
+ * (cleared after its single recycle) is the per-node action; this is its global counterpart.
+ * Default OFF — opt-in, because it changes which provider every agent node uses. Does NOT strip
+ * `CLAUDE_CONFIG_DIR` (account isolation survives). See `vanillaEnvStripPattern`.
+ */
+ vanillaLaunchDefault: boolean
/** "Eco": exit the agent CLI of a session that has been idle AND offscreen for
* `agentHibernationIdleMinutes`, reclaiming its RAM; the conversation is resumed automatically
* when the node is viewed again. Default OFF — opt-in, because it stops a real process.
@@ -1748,6 +1772,9 @@ export const DEFAULT_SETTINGS: Settings = {
// Sessions start in auto mode out of the box. Existing users pick this up on hydrate
// (settings hydrate merges over DEFAULT_SETTINGS) — a deliberate behavior change.
claudePermissionMode: 'auto',
+ // Opt-in: strips the gateway/inherited provider env on every fresh launch so agents run against
+ // their own default provider. Off by default — changes which provider every agent node uses.
+ vanillaLaunchDefault: false,
// Opt-in: hibernation exits a live CLI, so nobody gets it without asking. The 30-minute floor
// is deliberately long — shorter windows exit sessions the user is between turns on.
agentHibernationEnabled: false,