Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add generic credential-bootstrap provider config for CLI/TUI harnesses
Adam Eivy9e12ce268fb2
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsxindex 9bebf9d71d..669103583d 100644--- a/client/src/components/providers/ProviderForm.jsx+++ b/client/src/components/providers/ProviderForm.jsx@@ -85,7 +85,12 @@ export default function ProviderForm({ provider, daemonReadiness = null, onCloseenvVars: provider?.envVars || {},secretEnvVars: provider?.secretEnvVars || [],headlessArgs: provider?.headlessArgs?.join(' ') || '',- tuiPromptDelayMs: provider?.tuiPromptDelayMs || 2500+ tuiPromptDelayMs: provider?.tuiPromptDelayMs || 2500,+ credentialBootstrapSetupCommand: provider?.credentialBootstrap?.setupCommand || '',+ credentialBootstrapCommand: provider?.credentialBootstrap?.command || '',+ credentialBootstrapArgs: provider?.credentialBootstrap?.args?.join(' ') || '',+ credentialBootstrapHarnessId: provider?.credentialBootstrap?.harnessId || '',+ credentialBootstrapArgsSeparator: provider?.credentialBootstrap?.argsSeparator || '',});const [activeTab, setActiveTab] = useDrawerTab('providerTab', 'connection', PROVIDER_FORM_TAB_IDS);@@ -374,6 +379,26 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose// running another vendor's binary, where it would be a stored lie.if (!isCodexProvider({ ...provider, ...data, id: provider?.id })) delete data.ignoreUserConfig;+ // Fold the three flat scratch fields into the nested shape the server+ // schema expects, omitting the object entirely when no bootstrap command+ // is named — an empty `credentialBootstrap: { command: '' }` would fail+ // the server's `min(1)` check on every unrelated save.+ const bootstrapCommand = formData.credentialBootstrapCommand.trim();+ data.credentialBootstrap = bootstrapCommand+ ? {+ ...(formData.credentialBootstrapSetupCommand.trim() ? { setupCommand: formData.credentialBootstrapSetupCommand.trim() } : {}),+ command: bootstrapCommand,+ args: formData.credentialBootstrapArgs ? formData.credentialBootstrapArgs.split(' ').filter(Boolean) : [],+ ...(formData.credentialBootstrapHarnessId.trim() ? { harnessId: formData.credentialBootstrapHarnessId.trim() } : {}),+ ...(formData.credentialBootstrapArgsSeparator.trim() ? { argsSeparator: formData.credentialBootstrapArgsSeparator.trim() } : {}),+ }+ : null;+ delete data.credentialBootstrapSetupCommand;+ delete data.credentialBootstrapCommand;+ delete data.credentialBootstrapArgs;+ delete data.credentialBootstrapHarnessId;+ delete data.credentialBootstrapArgsSeparator;+// Only send apiKey if user entered a new value (avoid overwriting existing key with empty string)if (!data.apiKey && provider) {delete data.apiKey;@@ -479,6 +504,77 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose/></FormField>+ {/* Generic support for a harness whose auth is provisioned by an+ external CLI at spawn time — e.g. a company-internal tool that+ mints a short-lived token for a proxy and execs the harness+ itself — instead of a static API key PortOS stores. When set,+ PortOS spawns the bootstrap command in front of the harness+ invocation above, exactly as typing `<bootstrap> run <harness>+ ...` would. Setup Command is shown for the user to run+ themselves; PortOS never executes it. */}+ <p className="text-sm text-gray-400 -mb-1">Credential Bootstrap (optional)</p>+ <FormField label="Setup Command" compact>+ <input+ type="text"+ value={formData.credentialBootstrapSetupCommand}+ onChange={(e) => setFormData(prev => ({ ...prev, credentialBootstrapSetupCommand: e.target.value }))}+ placeholder="One-time step shown to you, e.g. npm install -g @your-org/token-cli"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ </FormField>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <FormField label="Bootstrap Command" compact>+ <input+ type="text"+ value={formData.credentialBootstrapCommand}+ onChange={(e) => setFormData(prev => ({ ...prev, credentialBootstrapCommand: e.target.value }))}+ placeholder="e.g. token-cli"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ </FormField>+ <FormField label="Bootstrap Args" compact>+ <input+ type="text"+ value={formData.credentialBootstrapArgs}+ onChange={(e) => setFormData(prev => ({ ...prev, credentialBootstrapArgs: e.target.value }))}+ placeholder="e.g. run"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ </FormField>+ <FormField label="Harness ID (optional)" compact>+ <input+ type="text"+ value={formData.credentialBootstrapHarnessId}+ onChange={(e) => setFormData(prev => ({ ...prev, credentialBootstrapHarnessId: e.target.value }))}+ placeholder={`Defaults to Command above (${formData.command || 'e.g. claude'})`}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ </FormField>+ <FormField label="Args Separator (optional)" compact>+ <input+ type="text"+ value={formData.credentialBootstrapArgsSeparator}+ onChange={(e) => setFormData(prev => ({ ...prev, credentialBootstrapArgsSeparator: e.target.value }))}+ placeholder="e.g. --"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"+ />+ </FormField>+ </div>+ <p className="text-xs text-gray-500">+ For a CLI that provisions its own short-lived credential (e.g. a token for a proxy) and then+ runs the harness itself. <strong>Setup Command</strong> is a one-time step shown to you —+ PortOS never runs it. When a Bootstrap Command is set, PortOS spawns it in front of the harness+ (<code>{formData.credentialBootstrapCommand || '<bootstrap>'} {formData.credentialBootstrapArgs}{' '}+ {formData.credentialBootstrapHarnessId || formData.command || '<harness>'}{' '}+ {formData.credentialBootstrapArgsSeparator} …</code>) instead of the harness directly, and never+ routes this provider through the CoS Agent Runner (its fixed list of known harness binaries has+ no way to recognize a custom bootstrap binary). <strong>Harness ID</strong> overrides what PortOS calls the harness+ when the bootstrap CLI uses its own name for it instead of the binary above (e.g.{' '}+ <code>claude-code</code> rather than <code>claude</code>).{' '}+ <strong>Args Separator</strong> (e.g. <code>--</code>) is inserted before the harness's own+ arguments when the bootstrap CLI needs its flags kept apart from the harness's.+ </p>+{/* The CLI/TUI backends that can authenticate: the vLLM composestack is started with VLLM_API_KEY, so without this fieldthere is nowhere to put it and the container 401s everydiff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsxindex 53e3914a96..19e0055271 100644--- a/client/src/components/providers/ProviderForm.test.jsx+++ b/client/src/components/providers/ProviderForm.test.jsx@@ -98,6 +98,48 @@ describe('ProviderForm', () => {expect(screen.queryByText(/It rides both the spawned OpenCode provider/)).not.toBeInTheDocument();});+ it('folds the credential-bootstrap fields into the nested shape the server expects', async () => {+ renderForm();+ fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'Example Provider' } });+ fireEvent.change(screen.getByLabelText('Command *'), { target: { value: 'claude' } });+ fireEvent.change(screen.getByLabelText('Setup Command'), { target: { value: 'npm install -g @your-org/token-cli' } });+ fireEvent.change(screen.getByLabelText('Bootstrap Command'), { target: { value: 'token-cli' } });+ fireEvent.change(screen.getByLabelText('Bootstrap Args'), { target: { value: 'run' } });+ fireEvent.change(screen.getByLabelText('Harness ID (optional)'), { target: { value: 'claude-code' } });+ fireEvent.change(screen.getByLabelText('Args Separator (optional)'), { target: { value: '--' } });+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));++ await waitFor(() => expect(api.createProvider).toHaveBeenCalledWith(expect.objectContaining({+ credentialBootstrap: {+ setupCommand: 'npm install -g @your-org/token-cli',+ command: 'token-cli',+ args: ['run'],+ harnessId: 'claude-code',+ argsSeparator: '--',+ },+ })));+ // No flat scratch fields leak into the payload the server never declared.+ const [payload] = api.createProvider.mock.calls[0];+ expect(payload).not.toHaveProperty('credentialBootstrapCommand');+ expect(payload).not.toHaveProperty('credentialBootstrapArgs');+ });++ it('clears a previously-set credential bootstrap when the Bootstrap Command is emptied', async () => {+ renderForm({+ provider: {+ id: 'example-bootstrap', name: 'Example Bootstrap', type: 'cli', command: 'claude',+ credentialBootstrap: { command: 'token-cli', args: ['run'] },+ },+ });+ fireEvent.change(screen.getByLabelText('Bootstrap Command'), { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));++ // `null`, not omitted — an absent key means "unchanged" on a PATCH, which+ // would leave the stored bootstrap config in place after the user cleared it.+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalledWith('example-bootstrap', expect.objectContaining({+ credentialBootstrap: null,+ })));+ });});// #7447: this editor is the surface that literally names the budgeterdiff --git a/server/lib/README.md b/server/lib/README.mdindex 31f48b9c15..022f055e8f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -260,6 +260,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (`PUBLIC_REVIEW_EXECUTION_PROFILE`, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE`, `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE`); `publicReviewPostureForProfile` maps it to the enforceable POSTURE a provider must carry a maintained recipe for (`no-tool` or `sandboxed-actions`), which is how a pipeline stage stays vendor-agnostic. || `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `release-flow`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. || `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |+| `credentialBootstrap.js` | Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static `apiKey` PortOS stores — a `provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? }` record. `hasCredentialBootstrap(provider)` and `applyCredentialBootstrap(provider, command, args)` (pure) return the command+args PortOS should actually spawn: `<command> <args...> <harnessId ?? command> [<argsSeparator>] <args...>` — the bootstrap CLI in front of the harness invocation, naming the harness as `harnessId` when the bootstrap CLI uses its own identifier rather than the binary name, and inserting `argsSeparator` (e.g. `--`) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. `resolveCliSpawn(provider, command, args, childEnv)` composes that with Windows shim resolution (`bufferedSpawn.js`) for the three headless spawn sites that repeated the same sequence (`runner.js`, `cliProviderRun.js`, `visionCli.js`) — the argv analog of why `cliChildEnv.js`'s `buildCliChildEnv` exists. Every call site keeps resolving `provider.command`/`args` unchanged for vendor detection, prompt-delivery convention, and TUI ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call. || `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. || `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. |diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 81cdfe0566..6758d8329d 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -736,6 +736,9 @@ export function createProviderService(config = {}) {// every existing record stays byte-identical and an older install// reading this file sees nothing new....(providerData.ignoreUserConfig === true ? { ignoreUserConfig: true } : {}),+ // Generic credential-bootstrap wrapper — only persisted when a bootstrap+ // command is actually named, so every existing record stays byte-identical.+ ...(providerData.credentialBootstrap?.command ? { credentialBootstrap: providerData.credentialBootstrap } : {}),envVars: providerData.envVars || {},secretEnvVars: providerData.secretEnvVars || [],headlessArgs: providerData.headlessArgs || [],diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 2aa74d6bf6..c52dfbb7fd 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -193,6 +193,29 @@ export const providerSchema = z.object({// one an existing install already relies on, and an override that silently// turned itself on would be its own surprise.ignoreUserConfig: z.boolean().optional(),+ // A CLI/TUI provider whose harness auth is provisioned by an external CLI at+ // spawn time (e.g. a short-lived token for a proxy) rather than a static+ // `apiKey` PortOS stores. PortOS spawns `command`(+`args`) in front of the+ // harness invocation instead of the harness directly — the generic+ // `<bootstrap> run <harness> ...` shape. `setupCommand` is advisory only+ // (shown to the user as a one-time step, e.g. installing the bootstrap CLI's+ // package) — PortOS never executes it. Nullable so the editor can explicitly+ // clear a previously-set bootstrap back to "none" (absent means "unchanged"+ // on a PATCH, which is not the same as clearing it).+ credentialBootstrap: z.object({+ setupCommand: z.string().trim().max(500).optional(),+ command: z.string().trim().min(1).max(200),+ args: z.array(z.string().max(200)).max(20).optional(),+ // What PortOS names the harness AS, when calling the bootstrap CLI — some+ // wrapper CLIs use their own identifier for a harness rather than its+ // binary name (e.g. `claude-code` where `command` is the binary `claude`).+ // Defaults to `command` when unset.+ harnessId: z.string().trim().min(1).max(100).optional(),+ // Inserted between the harness identifier and the harness's OWN args —+ // some wrapper CLIs need their own flags kept apart from the wrapped+ // program's (e.g. `<bootstrap> run <harness> -- <harness args>`).+ argsSeparator: z.string().trim().max(20).optional(),+ }).strict().nullable().optional(),envVars: z.record(z.string()).optional(),secretEnvVars: z.array(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex 52ae22ea5b..68178aa667 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -19,13 +19,14 @@import { spawn } from './childProcess.js';import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from './bufferedSpawn.js';+import { killProcessTree, guardChildStdin } from './bufferedSpawn.js';import { buildCliChildEnv } from './cliChildEnv.js';import { modelPinIsOffered } from './localProviderRuntime.js';import { filterCallerModeEligible } from './callerModePolicy.js';import { buildVendorSpawnConfig, supportsPublicReviewProvider } from './providerVendors.js';import { isPublicReviewNoToolProfile } from './agentExecutionProfiles.js';import { resolveCliModel } from './providerModels.js';+import { resolveCliSpawn } from './credentialBootstrap.js';// How much stderr to hand back to callers. Enough to carry a rate-limit banner// or a stack's first frames, short enough to embed in an error message or a@@ -157,11 +158,12 @@ export function runCliProviderPrompt(args = {}) {// (cmd.exe /c) instead of enabling a shell — shell:true + an args array// does NOT escape arguments (DEP0190), so a prompt/path containing a// space would silently corrupt or be shell-injectable. Resolved against- // `childEnv` so a provider-configured PATH override is honored. See- // resolveWindowsExecutable/prepareWindowsSafeSpawn in- // server/lib/bufferedSpawn.js.- const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;- const { command: spawnCommand, args: wrappedArgs } = prepareWindowsSafeSpawn(resolvedCommand, spawnArgs);+ // `childEnv` so a provider-configured PATH override is honored.+ // `resolveCliSpawn` also applies a credential-bootstrap wrap+ // (credentialBootstrap.js) when configured — applied AFTER+ // prepareCliPrompt (above), which still keys prompt-delivery convention+ // off the harness's own command, not the bootstrap CLI's.+ const { command: spawnCommand, args: wrappedArgs } = resolveCliSpawn(provider, provider.command, spawnArgs, childEnv);const child = spawn(spawnCommand, wrappedArgs, {cwd: effectiveCwd,stdio: ['pipe', 'pipe', 'pipe'],@@ -188,7 +190,7 @@ export function runCliProviderPrompt(args = {}) {// a dead-stdin EPIPE is caught rather than thrown. A child that exits// before reading stdin would otherwise emit an unhandled 'error' on the// stdin stream — fatal in this non-request context (crashes the process).- child.on('error', (err) => done({ error: `Failed to spawn ${provider.command}: ${err.message}` }));+ child.on('error', (err) => done({ error: `Failed to spawn ${spawnCommand}: ${err.message}` }));child.stdout?.on('data', (d) => { const t = d.toString(); stdout += t; onData?.(t, 'stdout'); });child.stderr?.on('data', (d) => { const t = d.toString(); stderr += t; onData?.(t, 'stderr'); });diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.jsnew file mode 100644index 0000000000..c386063b52--- /dev/null+++ b/server/lib/credentialBootstrap.js@@ -0,0 +1,95 @@+/**+ * Generic "credential bootstrap" wrapping for a CLI/TUI provider whose auth is+ * provisioned by an external CLI at spawn time, rather than a static `apiKey`+ * PortOS stores — e.g. a company-internal tool that mints a short-lived token+ * for an OpenAI-compatible proxy and execs the harness itself once it's ready.+ * PortOS never needs to understand the credential, the proxy, or how the+ * bootstrap CLI hands the token to its child: it only needs to spawn the+ * bootstrap CLI in front of the harness invocation instead of the harness+ * directly, exactly the way a person would type `<bootstrap> run <harness>+ * <harness args...>` at a shell.+ *+ * `provider.command`/`args` keep naming the actual harness (claude, opencode,+ * …) everywhere else in the codebase — vendor detection, prompt-delivery+ * convention, and TUI ready-text heuristics all key off it, and would silently+ * break if the harness's identity were replaced by the bootstrap binary's. So+ * every spawn site keeps resolving the harness's own command/args exactly as+ * it does today, and only asks this module for the pair to actually hand to+ * `spawn`/`pty.spawn`, right before that call.+ *+ * Imports only `bufferedSpawn.js` (mirrors `cliProviderRun.js`, which already+ * depends on it directly) so any spawn site — including the standalone+ * `portos-autofixer` process via `cliProviderRun.js` — can import this module+ * without dragging in the AI toolkit or data layer.+ */++import { resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';++/** True when a provider names a bootstrap CLI to wrap its harness spawn. */+export function hasCredentialBootstrap(provider) {+ return typeof provider?.credentialBootstrap?.command === 'string' && provider.credentialBootstrap.command.length > 0;+}++/**+ * The command+args PortOS should actually spawn for this provider: the+ * bootstrap CLI in front of the harness invocation when configured, or the+ * harness invocation unchanged otherwise. Pure — never touches the filesystem+ * or PATH; Windows shim resolution still happens downstream, against whichever+ * command this returns.+ *+ * Shape: `<bootstrap.command> <bootstrap.args...> <harnessId> [<bootstrap.argsSeparator>] <args...>`.+ *+ * `argsSeparator` exists because a wrapper CLI commonly needs its own flags+ * kept apart from the harness's — e.g. `<bootstrap> run <harness> -- <harness+ * args>` — and without a configurable separator the harness's own flags would+ * be parsed as the bootstrap CLI's.+ *+ * `harnessId` exists because a bootstrap CLI's own name for a harness is not+ * always the binary PortOS spawns — e.g. a tool may want `claude-code` where+ * `provider.command` is the literal binary `claude`. Defaults to `command`+ * (the harness binary) when unset, which covers a bootstrap CLI that takes+ * the binary name directly.+ *+ * @param {{credentialBootstrap?: {command: string, args?: string[], harnessId?: string, argsSeparator?: string}}|null|undefined} provider+ * @param {string} command - the harness binary PortOS would otherwise spawn+ * @param {string[]} [args] - the harness's own argv+ * @returns {{command: string, args: string[]}}+ */+export function applyCredentialBootstrap(provider, command, args) {+ const bootstrap = provider?.credentialBootstrap;+ const harnessArgs = Array.isArray(args) ? args : [];+ if (!hasCredentialBootstrap(provider)) return { command, args: harnessArgs };+ const harnessId = (typeof bootstrap.harnessId === 'string' && bootstrap.harnessId) || command;+ const separator = (typeof bootstrap.argsSeparator === 'string' && bootstrap.argsSeparator && harnessArgs.length > 0)+ ? [bootstrap.argsSeparator] : [];+ return {+ command: bootstrap.command,+ args: [...(Array.isArray(bootstrap.args) ? bootstrap.args : []), harnessId, ...separator, ...harnessArgs],+ };+}++/**+ * `applyCredentialBootstrap` + Windows shim resolution in one call — the+ * shape every headless spawn site needs immediately before its literal+ * `spawn()` call. Mirrors why `cliChildEnv.js`'s `buildCliChildEnv` exists:+ * three sites (`runner.js`, `cliProviderRun.js`, `visionCli.js`) independently+ * repeated the same "wrap, then resolve, then prepare" sequence with the same+ * explanatory comment — precisely the copy-paste `cliChildEnv.js`'s own+ * docblock describes for env composition, one layer up for argv.+ *+ * TUI/PTY spawn sites (`agentTuiSpawning.js`, `tuiPromptRunner.js`) do their+ * own Windows resolution (or none) and are NOT expected to call this — see+ * their own `applyCredentialBootstrap` call sites.+ *+ * @param {object|null|undefined} provider+ * @param {string} command - the harness binary PortOS would otherwise spawn+ * @param {string[]} args - the harness's own argv+ * @param {NodeJS.ProcessEnv} childEnv - resolved against this so a+ * provider-configured PATH override is honored+ * @returns {{command: string, args: string[]}}+ */+export function resolveCliSpawn(provider, command, args, childEnv) {+ const bootstrapped = applyCredentialBootstrap(provider, command, args);+ const resolvedCommand = resolveWindowsExecutable(bootstrapped.command, undefined, childEnv) || bootstrapped.command;+ return prepareWindowsSafeSpawn(resolvedCommand, bootstrapped.args);+}diff --git a/server/lib/credentialBootstrap.test.js b/server/lib/credentialBootstrap.test.jsnew file mode 100644index 0000000000..c1f610811c--- /dev/null+++ b/server/lib/credentialBootstrap.test.js@@ -0,0 +1,94 @@+import { describe, it, expect, vi } from 'vitest';+import { hasCredentialBootstrap, applyCredentialBootstrap, resolveCliSpawn } from './credentialBootstrap.js';++vi.mock('./bufferedSpawn.js', async (importOriginal) => ({+ ...(await importOriginal()),+ resolveWindowsExecutable: vi.fn(() => null),+}));++describe('credentialBootstrap', () => {+ describe('hasCredentialBootstrap', () => {+ it('is true only when a non-empty bootstrap command is named', () => {+ expect(hasCredentialBootstrap({ credentialBootstrap: { command: 'token-cli' } })).toBe(true);+ expect(hasCredentialBootstrap({ credentialBootstrap: { command: '' } })).toBe(false);+ expect(hasCredentialBootstrap({ credentialBootstrap: {} })).toBe(false);+ expect(hasCredentialBootstrap({ credentialBootstrap: null })).toBe(false);+ expect(hasCredentialBootstrap({})).toBe(false);+ expect(hasCredentialBootstrap(null)).toBe(false);+ expect(hasCredentialBootstrap(undefined)).toBe(false);+ });+ });++ describe('applyCredentialBootstrap', () => {+ it('wraps the harness command with the bootstrap CLI in front', () => {+ const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'] } };+ expect(applyCredentialBootstrap(provider, 'opencode', ['run', '--print'])).toEqual({+ command: 'token-cli',+ args: ['run', 'opencode', 'run', '--print'],+ });+ });++ it('defaults bootstrap args to empty when none are configured', () => {+ const provider = { credentialBootstrap: { command: 'token-cli' } };+ expect(applyCredentialBootstrap(provider, 'claude', ['-p', '-'])).toEqual({+ command: 'token-cli',+ args: ['claude', '-p', '-'],+ });+ });++ it('returns the harness command unchanged when no bootstrap is configured', () => {+ expect(applyCredentialBootstrap({}, 'claude', ['-p', '-'])).toEqual({ command: 'claude', args: ['-p', '-'] });+ expect(applyCredentialBootstrap(null, 'claude', ['-p', '-'])).toEqual({ command: 'claude', args: ['-p', '-'] });+ expect(applyCredentialBootstrap({ credentialBootstrap: null }, 'claude', ['-p', '-'])).toEqual({+ command: 'claude',+ args: ['-p', '-'],+ });+ });++ it('names the harness with harnessId instead of the raw command when configured', () => {+ const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'], harnessId: 'claude-code' } };+ expect(applyCredentialBootstrap(provider, 'claude', ['-p', '-'])).toEqual({+ command: 'token-cli',+ args: ['run', 'claude-code', '-p', '-'],+ });+ });++ it('inserts a configured separator between the harness command and its own args', () => {+ const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' } };+ expect(applyCredentialBootstrap(provider, 'claude', ['-p', '-'])).toEqual({+ command: 'token-cli',+ args: ['run', 'claude', '--', '-p', '-'],+ });+ });++ it('omits the separator when the harness has no args to separate', () => {+ const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' } };+ expect(applyCredentialBootstrap(provider, 'claude', [])).toEqual({+ command: 'token-cli',+ args: ['run', 'claude'],+ });+ });++ it('defaults missing harness args to an empty array', () => {+ expect(applyCredentialBootstrap({}, 'claude')).toEqual({ command: 'claude', args: [] });+ expect(applyCredentialBootstrap({ credentialBootstrap: { command: 'token-cli' } }, 'claude')).toEqual({+ command: 'token-cli',+ args: ['claude'],+ });+ });+ });++ describe('resolveCliSpawn', () => {+ it('composes the credential-bootstrap wrap with Windows shim resolution', () => {+ const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'] } };+ expect(resolveCliSpawn(provider, 'claude', ['-p', '-'], process.env)).toEqual({+ command: 'token-cli',+ args: ['run', 'claude', '-p', '-'],+ });+ });++ it('falls through to the harness unchanged when no bootstrap is configured', () => {+ expect(resolveCliSpawn({}, 'claude', ['-p', '-'], process.env)).toEqual({ command: 'claude', args: ['-p', '-'] });+ });+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex f4b2eab1f7..58e86f647a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -207,6 +207,7 @@ export * from './promptFencing.js';export * from './promptPartials.js';export * from './promptSystemStages.js';export * from './promptTemplate.js';+export * from './credentialBootstrap.js';export * from './providerCooldown.js';export * from './providerModels.js';export * from './providerPrerequisites.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 9be257c8ed..b89339e0c1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -549,6 +549,18 @@ export const providerSchema = z.object({// non-allowlisted) endpoint — mirrors the aiToolkit providerSchema. Guards// SSRF / key exfiltration (server/lib/aiToolkit/endpointGuard.js).allowCustomEndpoint: z.boolean().optional(),+ // Kept in schema parity with aiToolkit's provider schema. Marks a CLI/TUI+ // provider whose harness auth is provisioned by an external CLI at spawn+ // time (a short-lived token for a proxy) rather than a static apiKey.+ // `setupCommand` is advisory only — PortOS never executes it. Nullable so+ // the editor can explicitly clear a previously-set bootstrap.+ credentialBootstrap: z.object({+ setupCommand: z.string().trim().max(500).optional(),+ command: z.string().trim().min(1).max(200),+ args: z.array(z.string().max(200)).max(20).optional(),+ harnessId: z.string().trim().min(1).max(100).optional(),+ argsSeparator: z.string().trim().max(20).optional(),+ }).strict().nullable().optional(),envVars: z.record(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),tuiPromptDelayMs: z.number().int().min(250).max(60000).optional(),diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 150ebcfa72..4c6cd431df 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -41,6 +41,7 @@ import { resolveForgeTokenEnv } from './forgeAuth.js';import { resolveAgentCliCwd } from '../lib/spawnCwd.js';import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';import { prClaimWasVerified } from '../lib/prDisposition.js';import { resolvePrOwnership } from '../lib/slashdoInvocation.js';import { doneSentinelPath } from '../lib/agentSentinel.js';@@ -230,7 +231,12 @@ export async function spawnDirectly({// /dev/stdin` via stdin (POSIX) / temp file (Windows); every other provider via// stdin (writePromptToStdin=true).const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(cliConfig.command, cliConfig.args, prompt, { cwd });- const preparedSpawn = prepareCliSpawn(cliConfig.command, deliveredArgs, childEnv);+ // A credential-bootstrap-configured provider spawns its bootstrap CLI in+ // front of the harness instead of the harness directly — see+ // credentialBootstrap.js. Applied AFTER prepareCliPrompt, which still keys+ // prompt-delivery convention off the harness's own command.+ const { command: bootstrappedCommand, args: bootstrappedArgs } = applyCredentialBootstrap(provider, cliConfig.command, deliveredArgs);+ const preparedSpawn = prepareCliSpawn(bootstrappedCommand, bootstrappedArgs, childEnv);const isolatedSpawn = isPrivateSecurityTask(task)? await import('../lib/privateSecuritySandbox.js').then(({ preparePrivateSecuritySpawn }) => preparePrivateSecuritySpawn({ ...preparedSpawn, env: childEnv, cwd, provider }))diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 93db28be80..1d9c02a231 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -68,6 +68,7 @@ import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { publicReviewPostureForProfile, supportsTuiPublicReviewActionsProvider, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';import { checkPublicReviewSpawnPreconditions } from '../lib/publicReviewSpawnGate.js';import { buildAgentRegistration, resolveExecutionMode } from '../lib/agentRegistrationRecord.js';+import { hasCredentialBootstrap } from '../lib/credentialBootstrap.js';import { applyTaskGenerationOverrides } from '../lib/taskGenerationOverrides.js';import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';@@ -481,7 +482,13 @@ async function runAgentSpawn(task) {// process and may inherit ambient tool configuration; the final stage's// provider-specific direct CLI recipe is what enforces its sandbox.// GitHub mutations still belong to the deterministic output hook.- const dispatchUseRunner = publicReview ? false : useRunner;+ //+ // A credential-bootstrap-configured provider is ALSO direct-only: the+ // runner is a separate process that validates the command it's asked to+ // spawn against a static allowlist of known harness binaries+ // (cos-runner/allowedCommands.js) and has no way to know about a user's+ // arbitrary bootstrap CLI, so routing it there would 400 at spawn time.+ const dispatchUseRunner = (publicReview || hasCredentialBootstrap(provider)) ? false : useRunner;let publicReviewPromptData = null;// Resolve the workspace and provision any worktree / JIRA branch the taskdiff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.jsindex 8c7350ef0c..ab98515ad1 100644--- a/server/services/agentLifecycle.postureGate.test.js+++ b/server/services/agentLifecycle.postureGate.test.js@@ -497,6 +497,42 @@ describe('public-review dispatch — direct-only, never the CoS runner (#6105)',});});+/**+ * A credential-bootstrap-configured provider is ALSO direct-only, for a+ * different reason than public review: the CoS runner is a separate process+ * that validates the command it's asked to spawn against a static allowlist+ * of known harness binaries (cos-runner/allowedCommands.js), which has no way+ * to recognize a user's arbitrary bootstrap CLI. Routing it there would 400 at+ * spawn time instead of running.+ */+describe('credential-bootstrap dispatch — direct-only, never the CoS runner', () => {+ it('sends a credential-bootstrap-configured provider to the direct spawner even with runner mode on', async () => {+ setUseRunner(true);+ // A non-TUI record, same reasoning as the public-review control above: an+ // ordinary TUI task is spawned as a PTY session, and the runner arm sits+ // on the headless side of that branch.+ vi.mocked(isTuiProvider).mockReturnValue(false);+ vi.mocked(resolveAgentProviderAndModel).mockResolvedValue({+ ok: true,+ provider: { ...CLAUDE_TUI, credentialBootstrap: { command: 'token-cli', args: ['run'] } },+ selectedModel: 'sonnet',+ modelSelection: {},+ });+ reachDispatch();++ await spawnAgentForTask({ id: 'task-credential-bootstrap-runner', metadata: {} });++ expect(spawnAgentViaRunner).not.toHaveBeenCalled();+ expect(spawnDirectly).toHaveBeenCalledTimes(1);+ });++ // The control that proves the assertion above isn't vacuous — an ordinary,+ // non-credential-bootstrap provider still reaches the runner with the exact+ // same `isTuiProvider`/`reachDispatch` setup — is the public-review describe+ // block's own control above ('still sends an ordinary task to the runner+ // when runner mode is on'), which uses an identical mock shape.+});+/*** The branch posture the agent card badges.*diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex fdb88c367c..ecc0a1389e 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -83,6 +83,7 @@ import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';import { shellHasLiveChild } from '../lib/shellLivenessProbe.js';import { appendRunEvent } from './agentRunEventLog.js';+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';// Agent-specific timing/lifecycle constants (not shared with the one-shot// runner — agents stay alive much longer and write a sentinel file when done).@@ -197,8 +198,8 @@ export async function createAgentTuiSession({const session = await spawnTuiSessionViaRunner({agentId,taskId,- command: tuiConfig.command,- args: tuiConfig.args,+ command: tuiConfig.spawnCommand,+ args: tuiConfig.spawnArgs,workspacePath: cwd,envVars: env,providerAuth: cliProviderAuthDescriptor(provider),@@ -227,7 +228,7 @@ export async function createAgentTuiSession({// paste gate before the spawn — exactly as the runner branch above does —// or the TUI's first bracketed-paste/input-ready bytes are discarded.onInitialCommandSent?.();- sessionId = shellService.spawnCommandSession(tuiConfig.command, tuiConfig.args, {+ sessionId = shellService.spawnCommandSession(tuiConfig.spawnCommand, tuiConfig.spawnArgs, {...sessionOptions,env,onData,@@ -308,9 +309,15 @@ export function buildTuiSpawnConfig(provider, model, {safetyProfile,tui: true,});+ // Public-review postures never get credential-bootstrap-wrapped — the+ // enforced recipe above IS the sandbox, and `spawnCommand`/`spawnArgs`+ // exist here (identical to `command`/`args`) only so every branch of this+ // function returns the same shape.return {command: recipe.command,args: recipe.args,+ spawnCommand: recipe.command,+ spawnArgs: recipe.args,commandLine: formatShellCommandLine(recipe.command, recipe.args, shell),promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS,};@@ -332,11 +339,22 @@ export function buildTuiSpawnConfig(provider, model, {if (systemPromptFile && isClaudeCommand(command)) {args = [...args, '--append-system-prompt-file', systemPromptFile];}- const commandLine = formatShellCommandLine(command, args, shell);+ // `command`/`args` keep naming the harness itself — every consumer of this+ // config (ready-text detection, permission-dialog handling, error messages)+ // keys off them by identity. `spawnCommand`/`spawnArgs` are what actually+ // gets launched: the bootstrap CLI in front of the harness invocation for a+ // credential-bootstrap-configured provider (see credentialBootstrap.js), or+ // an identical copy otherwise. `commandLine` (used both to type the harness+ // into a login shell and to display "what's running") is built from the+ // SPAWNED pair so it always matches the real process.+ const { command: spawnCommand, args: spawnArgs } = applyCredentialBootstrap(provider, command, args);+ const commandLine = formatShellCommandLine(spawnCommand, spawnArgs, shell);return {command,args,+ spawnCommand,+ spawnArgs,commandLine,promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS};diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex bd8c647e98..a73b0bb809 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -337,6 +337,42 @@ describe('agent TUI spawning', () => {expect(config.args).not.toContain('--settings');});+ // A credential-bootstrap-configured provider wraps the SPAWNED command, not+ // the identity every other consumer of this config keys on (ready-text+ // detection, permission-dialog handling, error messages) — see+ // credentialBootstrap.js. `command`/`args` must stay the harness itself;+ // only `spawnCommand`/`spawnArgs`/`commandLine` reflect the wrap.+ it('wraps spawnCommand/spawnArgs/commandLine for a credential-bootstrap provider, leaving command/args as the harness identity', () => {+ const config = buildTuiSpawnConfig({+ id: 'claude-tui',+ type: 'tui',+ command: 'claude',+ args: [],+ credentialBootstrap: { command: 'token-cli', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' },+ }, null);++ expect(config.command).toBe('claude');+ expect(config.args).toEqual([]);+ expect(config.spawnCommand).toBe('token-cli');+ expect(config.spawnArgs).toEqual(['run', 'claude-code']);+ expect(config.commandLine).toContain('token-cli');+ expect(config.commandLine).toContain('claude-code');+ });++ // Public-review postures are enforced recipes and must never be tampered+ // with by a user-configured wrapper — see the module docblock above.+ it('never wraps an actions-posture TUI session even when credentialBootstrap is configured', () => {+ const config = buildTuiSpawnConfig({+ id: 'claude-tui',+ type: 'tui',+ command: 'claude',+ credentialBootstrap: { command: 'token-cli', args: ['run'] },+ }, 'sonnet', { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE, effort: 'high' });++ expect(config.spawnCommand).toBe(config.command);+ expect(config.spawnArgs).toEqual(config.args);+ });+it('does not Bedrock-map a cursor TUI model id that merely contains "claude"', () => {process.env.CLAUDE_CODE_USE_BEDROCK = '1';const config = buildTuiSpawnConfig({@@ -631,6 +667,11 @@ describe('spawnTuiAgent runtime', () => {const defaultTuiConfig = {command: 'codex',args: [],+ // `spawnCommand`/`spawnArgs` are what a real `buildTuiSpawnConfig` always+ // populates (identical to `command`/`args` absent a credentialBootstrap+ // config) — see credentialBootstrap.test.js for that module's own coverage.+ spawnCommand: 'codex',+ spawnArgs: [],commandLine: 'codex',promptDelayMs: 100,};@@ -833,7 +874,7 @@ describe('spawnTuiAgent runtime', () => {runSpawn({provider: { id: 'claude-tui', name: 'Local Claude TUI', type: 'tui', command: 'claude', envVars: {} },safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,- tuiConfig: { command: 'claude', args: ['--permission-mode', 'plan'], commandLine: 'claude --permission-mode plan', promptDelayMs: 100 },+ tuiConfig: { command: 'claude', args: ['--permission-mode', 'plan'], spawnCommand: 'claude', spawnArgs: ['--permission-mode', 'plan'], commandLine: 'claude --permission-mode plan', promptDelayMs: 100 },});await flushMicrotasks();@@ -895,7 +936,7 @@ describe('spawnTuiAgent runtime', () => {runSpawn({provider: { id: 'claude-tui', name: 'Local Claude TUI', type: 'tui', command: 'claude', envVars: {} },safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,- tuiConfig: { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100 },+ tuiConfig: { command: 'claude', args: [], spawnCommand: 'claude', spawnArgs: [], commandLine: 'claude', promptDelayMs: 100 },});await flushMicrotasks();@@ -1132,7 +1173,7 @@ describe('spawnTuiAgent runtime', () => {const spawnPromise = runSpawn({provider: { ...defaultProvider, id: 'opencode-tui', name: 'OpenCode TUI' },- tuiConfig: { ...defaultTuiConfig, command: 'opencode', commandLine: 'opencode' },+ tuiConfig: { ...defaultTuiConfig, command: 'opencode', spawnCommand: 'opencode', commandLine: 'opencode' },});await flushMicrotasks();await capturedOnData(Buffer.from('OpenCode booting...\n'));@@ -1214,9 +1255,9 @@ describe('spawnTuiAgent runtime', () => {});// ── 1c. claude waits for bracketed-paste mode (input ready) before pasting ───- const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100 };+ const claudeTuiConfig = { command: 'claude', args: [], spawnCommand: 'claude', spawnArgs: [], commandLine: 'claude', promptDelayMs: 100 };// Antigravity (agy) gets the SAME positive input-ready gate as claude (#2705).- const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100 };+ const agyTuiConfig = { command: 'agy', args: [], spawnCommand: 'agy', spawnArgs: [], commandLine: 'agy', promptDelayMs: 100 };const pasteCount = () => vi.mocked(shellService.writeToSession).mock.calls.filter(([, d]) => typeof d === 'string' && d.includes('\x1b[200~')).length;// The launch shell turns bracketed-paste OFF to run the command, then claude@@ -1312,7 +1353,7 @@ describe('spawnTuiAgent runtime', () => {});it('Cursor workspace trust: selects the keyed choice before delivering the task', async () => {- runSpawn({ tuiConfig: { command: 'cursor-agent', args: ['--force'], commandLine: 'cursor-agent --force', promptDelayMs: 100 } });+ runSpawn({ tuiConfig: { command: 'cursor-agent', args: ['--force'], spawnCommand: 'cursor-agent', spawnArgs: ['--force'], commandLine: 'cursor-agent --force', promptDelayMs: 100 } });await flushMicrotasks();await capturedOnData(Buffer.from(`${PASTE_OFF}Do you trust the contents of this directory?\n/workspace/example\n▶ [a] Trust this workspace\n[q] Quit\n`));await flushMicrotasks();@@ -1944,7 +1985,7 @@ describe('spawnTuiAgent runtime', () => {// satisfy prefix verification. Retrying expanded/duplicated the input.runSpawn({provider: { id: 'grok-tui', name: 'Grok TUI', type: 'tui', envVars: {} },- tuiConfig: { ...defaultTuiConfig, command: 'grok', commandLine: 'grok' },+ tuiConfig: { ...defaultTuiConfig, command: 'grok', spawnCommand: 'grok', commandLine: 'grok' },prompt: 'A long UX audit prompt whose full prefix is hidden by the collapsed preview.',});await flushMicrotasks();@@ -2152,7 +2193,7 @@ describe('spawnTuiAgent runtime', () => {const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- runSpawn({ tuiConfig: { command: 'gemini', args: [], commandLine: 'gemini', promptDelayMs: 100 } });+ runSpawn({ tuiConfig: { command: 'gemini', args: [], spawnCommand: 'gemini', spawnArgs: [], commandLine: 'gemini', promptDelayMs: 100 } });await flushMicrotasks();// Same banner text codex prints — but this is a gemini session.await capturedOnData(Buffer.from('Starting MCP servers (0/3): a, b, c\n'));diff --git a/server/services/runner.js b/server/services/runner.jsindex 659c0097c0..c55a252090 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -10,8 +10,9 @@ import { resolveSpawnCwd } from '../lib/spawnCwd.js';import { hasModelFlag, extractBakedModel, isCodexProvider } from '../lib/providerModels.js';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';+import { resolveCliSpawn } from '../lib/credentialBootstrap.js';import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';+import { killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';import { isHostShuttingDown } from '../lib/hostShutdown.js';// `./ollamaAgentContext.js` (and the ollama daemon manager behind it) is imported// lazily inside the predicate-gated branch below, NOT here — see that call site.@@ -410,11 +411,13 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc// See the executeCliRun docblock above for why this is a resolve+wrap, not// a shell:true. Resolved against `childEnv` (not bare process.env) so a- // provider-configured PATH override is honored.+ // provider-configured PATH override is honored. `resolveCliSpawn` also+ // applies a credential-bootstrap wrap (credentialBootstrap.js) when+ // configured — applied AFTER prompt delivery is resolved (above), which+ // still keys off the harness's own command, not the bootstrap CLI's.const runCommand = vision?.invocation.command || provider.command;const runCwd = vision?.invocation.cwd || effectiveCwd;- const resolvedCommand = resolveWindowsExecutable(runCommand, undefined, childEnv) || runCommand;- const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);+ const { command: spawnCommand, args: spawnArgs } = resolveCliSpawn(provider, runCommand, args, childEnv);childProcess = spawn(spawnCommand, spawnArgs, {cwd: runCwd,@@ -538,7 +541,10 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scmetadata.outputSize = Buffer.byteLength(output);if (spawnError) {- metadata.error = describeSpawnFailure(spawnError, provider.command);+ // Name whatever was ACTUALLY spawned — for a credential-bootstrap+ // provider that's the bootstrap CLI, not the harness `provider.command`+ // names, and an ENOENT there means the bootstrap binary is missing.+ metadata.error = describeSpawnFailure(spawnError, spawnCommand);metadata.errorCategory = 'spawn_error';} else if (canceled) {metadata.canceled = true;diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 11f57afe69..1722908794 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -679,6 +679,38 @@ describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {});});+describe('executeCliRun — credential-bootstrap wrapping', () => {+ it('spawns the bootstrap CLI in front of the harness when credentialBootstrap is configured', async () => {+ const { resolveWindowsExecutable } = await import('../lib/bufferedSpawn.js');+ vi.mocked(resolveWindowsExecutable).mockReturnValueOnce(null);++ const child = makeChild();+ spawn.mockReturnValue(child);++ const provider = {+ id: 'claude',+ command: 'claude',+ args: [],+ timeout: 5000,+ credentialBootstrap: { command: 'token-cli', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' },+ };++ setImmediate(() => {+ child.stdout.emit('data', Buffer.from('output'));+ child.emit('close', 0);+ });++ await executeCliRun({ runId: 'run-credential-bootstrap', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE });++ const [command, args] = spawn.mock.calls.at(-1);+ expect(command).toBe('token-cli');+ expect(args).toEqual(expect.arrayContaining(['run', 'claude-code', '--']));+ // The harness's own prompt-delivery convention still applies (claude's+ // `-p -`) — resolved against `provider.command`, not the bootstrap CLI.+ expect(args).toEqual(expect.arrayContaining(['-p', '-']));+ });+});+describe('executeCliRun — stdin pipe containment (#5655)', () => {const provider = {id: 'codex', command: 'codex', args: [],diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.jsindex d63e79fab4..474ef7f84c 100644--- a/server/services/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -75,6 +75,7 @@ import {import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { isCodexCommand } from '../lib/codex.js';import { isClaudeCommand } from '../lib/providerModels.js';+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';// One-shot defaults that don't apply to the long-running agent path:// - hard run cap (5 min vs unbounded for agents)@@ -169,6 +170,13 @@ export async function executeTuiRun({ runId, provider, prompt, screenshots = [],args.push('--image', imagePath);}}+ // `command`/`args` keep naming the harness itself — every heuristic below+ // (isCodexCommand, isClaudeCommand, ready-text detection) keys off them by+ // identity. `spawnCommand`/`spawnArgs` are what actually gets launched: the+ // bootstrap CLI in front of the harness invocation for a credential-+ // bootstrap-configured provider (see credentialBootstrap.js), or an+ // identical copy otherwise.+ const { command: spawnCommand, args: spawnArgs } = applyCredentialBootstrap(provider, command, args);const promptDelayMs = provider.tuiPromptDelayMs ?? DEFAULT_TUI_PROMPT_DELAY_MS;const idleThresholdMs = idleMs ?? provider.tuiOneShotIdleMs ?? DEFAULT_ONE_SHOT_IDLE_MS;const totalTimeoutMs = timeout ?? provider.timeout ?? DEFAULT_TIMEOUT_MS;@@ -257,10 +265,10 @@ ${prompt}`;// provider, no cause, nothing to act on. Resolve against the CHILD's PATH// (`childEnv`, since a provider may override PATH with only its own bin dir)// and report the real reason with the 127 that probe already uses.- if (!findCommandOnPath(command, { env: childEnv, cwd: workingDir })) {+ if (!findCommandOnPath(spawnCommand, { env: childEnv, cwd: workingDir })) {return failRunRecord({runId,- error: `TUI command not found: ${command}`,+ error: `TUI command not found: ${spawnCommand}`,exitCode: 127,startTime: Date.now(),onData,@@ -272,7 +280,7 @@ ${prompt}`;let ptyProcess;try {- ptyProcess = ptySpawn(command, args, {+ ptyProcess = ptySpawn(spawnCommand, spawnArgs, {name: 'xterm-256color',cols: PTY_COLS,rows: PTY_ROWS,@@ -280,7 +288,7 @@ ${prompt}`;env: childEnv,});} catch (err) {- throw new Error(`Failed to spawn TUI '${command}': ${err.message}`);+ throw new Error(`Failed to spawn TUI '${spawnCommand}': ${err.message}`);}// Subscribe to exit IMMEDIATELY after spawn. A CLI can fail before its firstdiff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 4395c7d53a..2a68f13726 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -31,8 +31,9 @@ import { extname, join } from 'path';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';import { resolveCliModel, isCodexProvider, buildCodexStartupArgs, buildEffortArgs } from '../lib/providerModels.js';import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';+import { killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';+import { resolveCliSpawn } from '../lib/credentialBootstrap.js';const CLI_VISION_TIMEOUT_MS = 120000;const IMAGE_BASENAME = 'vision-input.png';@@ -242,10 +243,11 @@ async function runCliVisionSpawn({ provider, model, invocation, timeout, spawnIm// wrapper instead relies on Node's own correct non-shell argv escaping,// which DOES preserve spaces within each arg as a single token. Resolved// against `childEnv` so a provider-configured PATH override is honored.- // See resolveWindowsExecutable/prepareWindowsSafeSpawn in- // server/lib/bufferedSpawn.js.- const resolvedCommand = resolveWindowsExecutable(command, undefined, childEnv) || command;- const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, deliveredArgs);+ // `resolveCliSpawn` also applies a credential-bootstrap wrap+ // (credentialBootstrap.js) when configured — applied AFTER prepareCliPrompt+ // (above), which still keys prompt-delivery convention off the harness's+ // own command, not the bootstrap CLI's.+ const { command: spawnCommand, args: spawnArgs } = resolveCliSpawn(provider, command, deliveredArgs, childEnv);const text = await new Promise((resolve, reject) => {const child = spawnImpl(spawnCommand, spawnArgs, {