Skip to content

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

address review (self): wrap every provider spawn site and never wrap a public-review posture

[._.]/ Adam Eivyd4f67907a056
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index 669103583d..91a6af8c7e 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -379,20 +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.
+ // Fold the five flat scratch fields into the nested shape the server
+ // schema expects. Only a CLI/TUI provider carries the field at all (the
+ // section above is gated the same way): an api-type save must not ship
+ // `credentialBootstrap: null` onto a record that never had one. A named
+ // bootstrap command becomes the object; an emptied one becomes an explicit
+ // `null` (absent means "unchanged" on a PATCH) — never
+ // `{ command: '' }`, which 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;
+ if (formData.type === 'cli' || formData.type === 'tui') {
+ 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;
@@ -573,6 +579,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
<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.
+ Bootstrap Args are stored and shown in clear text (agent records, run transcripts, the shell
+ line typed for a TUI session) — put a secret in Environment Variables marked secret, never here.
</p>
{/* The CLI/TUI backends that can authenticate: the vLLM compose
diff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsx
index 19e0055271..2e3978cefd 100644
--- a/client/src/components/providers/ProviderForm.test.jsx
+++ b/client/src/components/providers/ProviderForm.test.jsx
@@ -124,6 +124,19 @@ describe('ProviderForm', () => {
expect(payload).not.toHaveProperty('credentialBootstrapArgs');
});
+ it('sends no credentialBootstrap key at all for an api-type provider', async () => {
+ renderForm({
+ provider: { id: 'example-api', name: 'Example API', type: 'api', endpoint: 'https://api.example.com/v1' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ // The section is CLI/TUI-only, so an api save must not ship an explicit
+ // `null` (which the server would merge onto the record as a literal null).
+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalled());
+ const [, payload] = api.updateProvider.mock.calls[0];
+ expect(payload).not.toHaveProperty('credentialBootstrap');
+ });
+
it('clears a previously-set credential bootstrap when the Bootstrap Command is emptied', async () => {
renderForm({
provider: {
diff --git a/server/lib/README.md b/server/lib/README.md
index d3a672e9b4..64dd65c2e3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -260,7 +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. |
+| `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 the TUI's own ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call — plus anything that observes the launching shell or PATH (missing-binary detection, readiness probes), which must read the SPAWNED pair. A public-review posture is never wrapped (the enforced recipe is the sandbox); the skip lives in the helper, keyed on `safetyProfile`. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. |
| `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/internal/providerModes.js b/server/lib/aiToolkit/internal/providerModes.js
index 5ec32f1586..0ff0857fa8 100644
--- a/server/lib/aiToolkit/internal/providerModes.js
+++ b/server/lib/aiToolkit/internal/providerModes.js
@@ -2,6 +2,8 @@
// Pair only conventional sibling IDs with the same harness and connection.
import { isDeepStrictEqual } from 'node:util';
+const MODE_KEY_DEFAULTS = { endpoint: '', apiKey: '', envVars: {}, credentialBootstrap: null };
+
export function providerModeGroups(providers) {
const byId = new Map(providers.map(provider => [provider.id, provider]));
const paired = new Set();
@@ -10,8 +12,10 @@ export function providerModeGroups(providers) {
const stem = tui.id.replace(/-tui(?=-|$)/, '');
const cli = [byId.get(stem), byId.get(`${stem}-cli`)].find(provider => provider?.type === 'cli');
if (!cli || paired.has(cli.id) || !cli.command || cli.command !== tui.command) continue;
- if (!['endpoint', 'apiKey', 'envVars'].every(key =>
- isDeepStrictEqual(cli[key] || (key === 'envVars' ? {} : ''), tui[key] || (key === 'envVars' ? {} : '')))) continue;
+ // `credentialBootstrap` is the connection's auth when there is no apiKey,
+ // so siblings that disagree on it are two connections, not one.
+ if (!['endpoint', 'apiKey', 'envVars', 'credentialBootstrap'].every(key =>
+ isDeepStrictEqual(cli[key] || MODE_KEY_DEFAULTS[key], tui[key] || MODE_KEY_DEFAULTS[key]))) continue;
groups.push([cli, tui]);
paired.add(cli.id);
paired.add(tui.id);
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 6758d8329d..120d8fef27 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -769,6 +769,11 @@ export function createProviderService(config = {}) {
...updates,
id
};
+ // The editor clears a bootstrap with an explicit `null` (absent means
+ // "unchanged" on a PATCH). Drop the key rather than store the null, so
+ // the record reads exactly like one that never had a bootstrap — the
+ // invariant `createProvider` keeps by only writing the key when named.
+ if (provider.credentialBootstrap === null) delete provider.credentialBootstrap;
const group = providerModeGroups(Object.values(data.providers)).find(modes => modes.some(mode => mode.id === id));
data.providers[id] = provider;
@@ -841,7 +846,12 @@ export function createProviderService(config = {}) {
// Use execFile (no shell) so user-configured `provider.command` cannot
// inject extra shell commands via metacharacters.
const lookup = isWin32 ? 'where' : 'which';
- const { stdout } = await execFileAsync(lookup, [provider.command], { windowsHide: true })
+ // Probe what PortOS actually spawns: the credential-bootstrap CLI in
+ // front of the harness when one is named (the harness may then live
+ // behind it, off PATH), else the harness itself. Inline rather than
+ // imported — this directory stays self-contained.
+ const probeCommand = provider.credentialBootstrap?.command || provider.command;
+ const { stdout } = await execFileAsync(lookup, [probeCommand], { windowsHide: true })
.catch(() => ({ stdout: '', stderr: 'not found' }));
// `where` lists every match (one per line); `which` prints one. Take the
@@ -849,7 +859,7 @@ export function createProviderService(config = {}) {
const commandPath = stdout.split(/\r?\n/).map(s => s.trim()).find(Boolean) || '';
if (!commandPath) {
- return { success: false, error: `Command '${provider.command}' not found in PATH` };
+ return { success: false, error: `Command '${probeCommand}' not found in PATH` };
}
// On Windows, `where` can return the wrong file: npm ships an
@@ -897,7 +907,7 @@ export function createProviderService(config = {}) {
if (!everSpawned) {
return {
success: false,
- error: `Resolved '${provider.command}' to ${invokePath} but it could not be executed (a Windows .cmd/.bat npm shim is not directly spawnable by the agent runner)`,
+ error: `Resolved '${probeCommand}' to ${invokePath} but it could not be executed (a Windows .cmd/.bat npm shim is not directly spawnable by the agent runner)`,
};
}
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index 5b609fbd6a..00a18d32d1 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -46,6 +46,29 @@ describe('Provider Service', () => {
expect((await providerService.getActiveProvider()).id).toBe('remote');
});
+ it('persists a credential bootstrap only while one is named, and drops the key on an explicit clear', async () => {
+ const created = await providerService.createProvider({ name: 'Bootstrap CLI', type: 'cli', command: 'claude' });
+ expect(created).not.toHaveProperty('credentialBootstrap');
+ const bootstrap = { command: 'token-cli', args: ['run'] };
+ expect((await providerService.updateProvider(created.id, { credentialBootstrap: bootstrap })).credentialBootstrap).toEqual(bootstrap);
+ // The editor clears with an explicit `null` (absent = unchanged on a PATCH);
+ // the stored record must read like one that never had a bootstrap.
+ const cleared = await providerService.updateProvider(created.id, { credentialBootstrap: null });
+ expect(cleared).not.toHaveProperty('credentialBootstrap');
+ expect(await providerService.getProviderById(created.id)).not.toHaveProperty('credentialBootstrap');
+ });
+
+ it('does not pair CLI/TUI modes as one connection when only one carries a credential bootstrap', async () => {
+ await writeFile(join(TEST_DATA_DIR, 'providers.json'), JSON.stringify({ activeProvider: 'example-tui', providers: {
+ example: { id: 'example', name: 'Example CLI', type: 'cli', command: 'example', enabled: false, models: ['a'], credentialBootstrap: { command: 'token-cli' } },
+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'example', enabled: true, models: ['b'] },
+ } }));
+ // Unpaired: neither enablement nor models unify across the two.
+ expect((await providerService.getProviderById('example')).enabled).toBe(false);
+ await providerService.updateProvider('example-tui', { models: ['c'] });
+ expect((await providerService.getProviderById('example')).models).toEqual(['a']);
+ });
+
it.skipIf(process.platform === 'win32')('refreshes Pi models and distinguishes authentication from probe failure', async () => {
const command = join(TEST_DATA_DIR, 'pi');
const emit = async (text, code = 0) => {
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 68178aa667..b7814f6175 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -162,8 +162,9 @@ export function runCliProviderPrompt(args = {}) {
// `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);
+ // off the harness's own command, not the bootstrap CLI's — and never under
+ // a public-review `safetyProfile`, whose enforced recipe is the sandbox.
+ const { command: spawnCommand, args: wrappedArgs } = resolveCliSpawn(provider, provider.command, spawnArgs, childEnv, { safetyProfile });
const child = spawn(spawnCommand, wrappedArgs, {
cwd: effectiveCwd,
stdio: ['pipe', 'pipe', 'pipe'],
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index 4de2b01a28..19727ed29c 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -126,6 +126,23 @@ describe('runCliProviderPrompt', () => {
expect(child.forgeToken).toBeNull();
});
+ it.skipIf(process.platform === 'win32')('runs the enforced no-tool recipe on the harness itself, never through a configured credential bootstrap', async () => {
+ const { mkdtemp, writeFile, rm } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const dir = await mkdtemp(join(tmpdir(), 'review-cli-bootstrap-'));
+ const command = join(dir, 'claude');
+ await writeFile(command, '#!/usr/bin/env node\nprocess.stdin.resume(); process.stdin.on("end", () => process.stdout.write(JSON.stringify({ args: process.argv.slice(2) })));', { mode: 0o755 });
+ // The bootstrap binary does not exist: had the wrap applied, this spawn
+ // would ENOENT instead of reaching the harness script above.
+ const provider = { ...cli('example-claude'), command, credentialBootstrap: { command: join(dir, 'token-cli-missing'), args: ['run'] } };
+ const result = await runCliProviderPrompt({
+ provider, model: 'pinned-model', prompt: 'untrusted diff', cwd: dir, safetyProfile: 'public-review-gate',
+ }).finally(() => rm(dir, { recursive: true, force: true }));
+ expect(result.error).toBeUndefined();
+ expect(JSON.parse(result.text).args).toEqual(expect.arrayContaining(['--restricted', '--tools', '']));
+ });
+
it('rejects a missing command without spawning', async () => {
const result = await runCliProviderPrompt({ provider: { id: 'x' }, prompt: 'hi' });
expect(result.error).toMatch(/no command/i);
diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.js
index c386063b52..c7a9914211 100644
--- a/server/lib/credentialBootstrap.js
+++ b/server/lib/credentialBootstrap.js
@@ -11,19 +11,42 @@
*
* `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.
+ * convention, and the TUI's own 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. The
+ * one heuristic that must key on the SPAWNED pair instead is anything that
+ * observes the launching shell rather than the harness — a login shell's
+ * `command not found` names the bootstrap binary, so a PATH probe or a
+ * missing-binary detector reads `spawnCommand`, never `command`.
*
- * 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.
+ * EVERY site that spawns a provider's `command` must go through here — a site
+ * that spawns the bare harness runs it with no credential, and the harness
+ * then falls through to whatever ambient vendor auth the machine has, sending
+ * the prompt to the wrong backend with no error. Wrapped sites: the headless
+ * runners (`runner.js`, `cliProviderRun.js`, `visionCli.js`, `askService.js`,
+ * `opencodeTask.js`), the agent spawners (`agentCliSpawning.js`,
+ * `agentTuiSpawning.js`), the one-shot TUI runner (`tuiPromptRunner.js`), the
+ * "Launch in Shell" line (`tuiShellLaunch.js`), the TUI usage scrape
+ * (`providerUsage.js`), and the readiness probes (`providerPrerequisites.js`,
+ * the toolkit's `testProvider`).
+ *
+ * A public-review posture (`isPublicReviewRestrictedProfile`) is NEVER
+ * wrapped, at any site: the vendor's enforced no-tool/sandboxed recipe IS the
+ * sandbox, and its argv and env allowlists are both defeated by handing the
+ * recipe to a user-configured binary that mints and re-injects a credential.
+ * The skip lives here rather than at each call site so a new spawn site can't
+ * forget it.
+ *
+ * Imports only `bufferedSpawn.js` and `agentExecutionProfiles.js` (both of
+ * which `cliProviderRun.js` already depends on 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';
+import { isPublicReviewRestrictedProfile } from './agentExecutionProfiles.js';
/** True when a provider names a bootstrap CLI to wrap its harness spawn. */
export function hasCredentialBootstrap(provider) {
@@ -53,12 +76,14 @@ export function hasCredentialBootstrap(provider) {
* @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
+ * @param {{safetyProfile?: string|null}} [options] - the run's execution
+ * profile; a public-review posture is returned unwrapped (see module doc)
* @returns {{command: string, args: string[]}}
*/
-export function applyCredentialBootstrap(provider, command, args) {
+export function applyCredentialBootstrap(provider, command, args, { safetyProfile = null } = {}) {
const bootstrap = provider?.credentialBootstrap;
const harnessArgs = Array.isArray(args) ? args : [];
- if (!hasCredentialBootstrap(provider)) return { command, args: harnessArgs };
+ if (!hasCredentialBootstrap(provider) || isPublicReviewRestrictedProfile(safetyProfile)) 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] : [];
@@ -86,10 +111,11 @@ export function applyCredentialBootstrap(provider, command, args) {
* @param {string[]} args - the harness's own argv
* @param {NodeJS.ProcessEnv} childEnv - resolved against this so a
* provider-configured PATH override is honored
+ * @param {{safetyProfile?: string|null}} [options] - forwarded to `applyCredentialBootstrap`
* @returns {{command: string, args: string[]}}
*/
-export function resolveCliSpawn(provider, command, args, childEnv) {
- const bootstrapped = applyCredentialBootstrap(provider, command, args);
+export function resolveCliSpawn(provider, command, args, childEnv, options = {}) {
+ const bootstrapped = applyCredentialBootstrap(provider, command, args, options);
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.js
index c1f610811c..dd4dd062d5 100644
--- a/server/lib/credentialBootstrap.test.js
+++ b/server/lib/credentialBootstrap.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { hasCredentialBootstrap, applyCredentialBootstrap, resolveCliSpawn } from './credentialBootstrap.js';
+import { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from './agentExecutionProfiles.js';
vi.mock('./bufferedSpawn.js', async (importOriginal) => ({
...(await importOriginal()),
@@ -78,6 +79,30 @@ describe('credentialBootstrap', () => {
});
});
+ // A public-review posture's enforced recipe IS the sandbox: handing it to a
+ // user-configured binary defeats both its argv and env allowlists. The skip is
+ // keyed on the profile here, at the one point every spawn site goes through.
+ describe('public-review postures', () => {
+ const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'] } };
+
+ it.each([PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE])(
+ 'never wraps a %s spawn, even with a bootstrap configured', (safetyProfile) => {
+ expect(applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile })).toEqual({
+ command: 'claude',
+ args: ['--restricted'],
+ });
+ expect(resolveCliSpawn(provider, 'claude', ['--restricted'], process.env, { safetyProfile })).toEqual({
+ command: 'claude',
+ args: ['--restricted'],
+ });
+ });
+
+ it('still wraps an ordinary (profile-less or unknown-profile) spawn', () => {
+ expect(applyCredentialBootstrap(provider, 'claude', [], { safetyProfile: null }).command).toBe('token-cli');
+ expect(applyCredentialBootstrap(provider, 'claude', [], { safetyProfile: 'not-a-public-review-profile' }).command).toBe('token-cli');
+ });
+ });
+
describe('resolveCliSpawn', () => {
it('composes the credential-bootstrap wrap with Windows shim resolution', () => {
const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'] } };
diff --git a/server/lib/tuiShellLaunch.js b/server/lib/tuiShellLaunch.js
index 1195fbcb0a..9e77f38793 100644
--- a/server/lib/tuiShellLaunch.js
+++ b/server/lib/tuiShellLaunch.js
@@ -21,6 +21,7 @@ import { buildTuiInvocation } from './tuiHandshake.js';
import { formatShellCommandLine } from './shellCd.js';
import { resolveInteractiveShell } from './interactiveShellResolver.js';
import { composeProviderEnv } from './cliChildEnv.js';
+import { applyCredentialBootstrap } from './credentialBootstrap.js';
/**
* @param {object|null|undefined} provider - a RAW provider record (unredacted
@@ -31,8 +32,12 @@ import { composeProviderEnv } from './cliChildEnv.js';
*/
export function buildTuiShellLaunch(provider) {
if (provider?.type !== PROVIDER_TYPES.TUI) return null;
- const { command, args } = buildTuiInvocation(provider, provider.defaultModel);
- if (!command) return null;
+ const invocation = buildTuiInvocation(provider, provider.defaultModel);
+ if (!invocation.command) return null;
+ // What the shell must type is what every agent spawn runs: the bootstrap CLI
+ // in front of the harness for a credential-bootstrap provider (see
+ // credentialBootstrap.js) — a bare harness here would run with no credential.
+ const { command, args } = applyCredentialBootstrap(provider, invocation.command, invocation.args);
return {
commandLine: formatShellCommandLine(command, args, resolveInteractiveShell()),
env: composeProviderEnv({ provider, model: provider.defaultModel }),
diff --git a/server/lib/tuiShellLaunch.test.js b/server/lib/tuiShellLaunch.test.js
index cdd2b942c7..8084701af4 100644
--- a/server/lib/tuiShellLaunch.test.js
+++ b/server/lib/tuiShellLaunch.test.js
@@ -26,6 +26,20 @@ describe('buildTuiShellLaunch', () => {
expect(launch.env.ANTHROPIC_AUTH_TOKEN).toBe('local');
});
+ // The typed line is what every agent spawn runs — a bare harness here would
+ // launch with no credential and fall through to ambient vendor auth.
+ it('types the credential-bootstrap CLI in front of the harness when one is configured', () => {
+ const launch = buildTuiShellLaunch({
+ ...OLLAMA_CLAUDE_TUI,
+ credentialBootstrap: { command: 'token-cli', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' },
+ });
+ // Dialect-agnostic prefix check (PowerShell renders `& 'token-cli'`).
+ expect(launch.commandLine).toMatch(/^(?:& )?(['"])?token-cli\1?\s/);
+ expect(launch.commandLine).toContain('claude-code');
+ expect(launch.commandLine).toContain('qwen3:32b');
+ expect(launch.env.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:11434');
+ });
+
it('returns null for a non-TUI provider, so callers have one not-launchable case', () => {
expect(buildTuiShellLaunch({ ...OLLAMA_CLAUDE_TUI, type: 'cli' })).toBeNull();
expect(buildTuiShellLaunch({ ...OLLAMA_CLAUDE_TUI, type: 'api' })).toBeNull();
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 4c6cd431df..efb5da127c 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -234,8 +234,9 @@ export async function spawnDirectly({
// 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);
+ // prompt-delivery convention off the harness's own command — and never under
+ // a public-review `safetyProfile`, whose enforced recipe is the sandbox.
+ const { command: bootstrappedCommand, args: bootstrappedArgs } = applyCredentialBootstrap(provider, cliConfig.command, deliveredArgs, { safetyProfile });
const preparedSpawn = prepareCliSpawn(bootstrappedCommand, bootstrappedArgs, childEnv);
const isolatedSpawn = isPrivateSecurityTask(task)
? await import('../lib/privateSecuritySandbox.js')
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index ecc0a1389e..ec0b2b0c05 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -310,15 +310,17 @@ export function buildTuiSpawnConfig(provider, model, {
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.
+ // enforced recipe above IS the sandbox. `applyCredentialBootstrap` owns
+ // that skip (keyed on `safetyProfile`), so `spawnCommand`/`spawnArgs` come
+ // back identical to `command`/`args` and every branch of this function
+ // returns the same shape.
+ const { command: spawnCommand, args: spawnArgs } = applyCredentialBootstrap(provider, recipe.command, recipe.args, { safetyProfile });
return {
command: recipe.command,
args: recipe.args,
- spawnCommand: recipe.command,
- spawnArgs: recipe.args,
- commandLine: formatShellCommandLine(recipe.command, recipe.args, shell),
+ spawnCommand,
+ spawnArgs,
+ commandLine: formatShellCommandLine(spawnCommand, spawnArgs, shell),
promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS,
};
}
@@ -751,7 +753,10 @@ export async function spawnTuiAgent({
leaveOpen: leavesPrForHuman(task),
});
const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
- const commandName = tuiConfig.command.split('/').pop();
+ // The login shell prints "command not found" for the binary it was asked to
+ // run — the SPAWNED one, which for a credential-bootstrap provider is the
+ // bootstrap CLI, not the harness `tuiConfig.command` names.
+ const commandName = tuiConfig.spawnCommand.split('/').pop();
/**
* Where this session is in its lifecycle — the one value every path that
* ends a run reads and writes.
@@ -1538,7 +1543,7 @@ export async function spawnTuiAgent({
await finish({
success: false,
exitCode: 127,
- error: `TUI command not found: ${tuiConfig.command}`,
+ error: `TUI command not found: ${tuiConfig.spawnCommand}`,
reason: 'command-not-found'
});
}
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index a73b0bb809..666cf9c4a9 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -2234,6 +2234,31 @@ describe('spawnTuiAgent runtime', () => {
);
});
+ // A credential-bootstrap provider types `token-cli run codex …` into the
+ // login shell, so the shell's "command not found" names the BOOTSTRAP binary.
+ // Keying the probe on the harness (`tuiConfig.command`) would miss it and the
+ // run would hang to the wall-clock backstop instead of exiting 127.
+ it('command-not-found: detects a missing credential-bootstrap binary by the spawned command, not the harness', async () => {
+ const spawnPromise = runSpawn({
+ tuiConfig: { ...defaultTuiConfig, spawnCommand: 'token-cli', spawnArgs: ['run', 'codex'], commandLine: 'token-cli run codex' },
+ });
+ await flushMicrotasks();
+
+ await capturedOnData(Buffer.from('zsh: command not found: token-cli\n'));
+ await flushMicrotasks();
+
+ await spawnPromise;
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ success: false,
+ exitCode: 127,
+ completionReason: 'command-not-found',
+ error: 'TUI command not found: token-cli',
+ })
+ );
+ });
+
// ── 3. Shell-exit path with non-zero exit code ───────────────────────────────
it('shell-exit: finalizeAgent called with success:false and exitCode 1 when shell exits non-zero', async () => {
const spawnPromise = runSpawn();
diff --git a/server/services/askService.js b/server/services/askService.js
index be87d2e2f6..2999669874 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -38,6 +38,7 @@ import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/ant
import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
import { evaluateSecretEndpoint } from '../lib/aiToolkit/endpointGuard.js';
@@ -543,7 +544,11 @@ async function* streamCompletion(provider, model, prompt, signal) {
// launch it — a bare shim name ENOENTs otherwise. No-op off Windows. Mirrors
// the runner / agent / vision spawn paths. Resolved against childEnv so a
// provider PATH override is honored.
- const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(provider.command, deliveredArgs, childEnv);
+ // Credential-bootstrap wrap first (credentialBootstrap.js): Ask carries
+ // private records, and a bare harness would fall through to the machine's
+ // ambient vendor auth instead of the backend this provider is configured for.
+ const bootstrapped = applyCredentialBootstrap(provider, provider.command, deliveredArgs);
+ const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(bootstrapped.command, bootstrapped.args, childEnv);
const out = await new Promise((resolve, reject) => {
let buf = '';
const child = spawn(spawnCommand, spawnArgs, {
diff --git a/server/services/askService.test.js b/server/services/askService.test.js
index d9bed00e25..be370fa060 100644
--- a/server/services/askService.test.js
+++ b/server/services/askService.test.js
@@ -272,6 +272,33 @@ describe('runAsk', () => {
expect(fullText).toBe('Hello, world.');
});
+ // Ask carries private records: a bare harness spawn would fall through to the
+ // machine's ambient vendor auth and send the prompt to the wrong backend.
+ it('spawns a CLI provider through its credential bootstrap when one is configured', async () => {
+ providers.getActiveProvider.mockResolvedValue({
+ id: 'claude-code', type: 'cli', enabled: true, command: 'claude', args: [], defaultModel: 'sonnet',
+ credentialBootstrap: { command: 'token-cli', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' },
+ });
+ spawn.mockImplementation(() => {
+ const child = Object.assign(new EventEmitter(), {
+ stdout: new EventEmitter(), stderr: new EventEmitter(),
+ stdin: Object.assign(new EventEmitter(), { end: vi.fn() }), kill: vi.fn(),
+ });
+ setImmediate(() => { child.stdout.emit('data', Buffer.from('answer')); child.emit('close', 0); });
+ return child;
+ });
+
+ const events = [];
+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);
+
+ expect(events.at(-1).type).toBe('done');
+ const [command, args] = spawn.mock.calls[0];
+ expect(command).toBe('token-cli');
+ expect(args.slice(0, 3)).toEqual(['run', 'claude-code', '--']);
+ // The harness's own argv (Ask's model pin) follows the separator.
+ expect(args.slice(3)).toEqual(expect.arrayContaining(['--model', 'sonnet']));
+ });
+
it('keeps streamed content and emits an error when the canonical reader fails', async () => {
providers.getActiveProvider.mockResolvedValue(fakeStreamProvider());
const encoded = new TextEncoder().encode('data: {"choices":[{"delta":{"content":"partial"}}]}\n');
diff --git a/server/services/opencodeTask.js b/server/services/opencodeTask.js
index 2d6fb0230d..3f1d3a6cb0 100644
--- a/server/services/opencodeTask.js
+++ b/server/services/opencodeTask.js
@@ -20,6 +20,7 @@
import { ServerError } from '../lib/errorHandler.js';
import { runStreamingCommand } from '../lib/streamingSpawn.js';
import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { isOpencodeCommand, prefixOpencodeModel, getOpencodeLocalProviderNamespace } from '../lib/providerModels.js';
import { parseAgentLine } from '../lib/opencodeStream.js';
@@ -82,7 +83,9 @@ export async function runOpencodeTask({ provider, modelId, cwd, prompt, timeoutM
// Pins PWD to `cwd` (#3193) — OpenCode resolves its project root from PWD, so
// an inherited one would silently run the task in the PortOS checkout.
const env = buildCliChildEnv({ provider, model: modelId, cwd, guard: true });
- const spawnTarget = prepareCliSpawn(provider.command, args, env);
+ // Credential-bootstrap wrap first (credentialBootstrap.js), then shim resolution.
+ const bootstrapped = applyCredentialBootstrap(provider, provider.command, args);
+ const spawnTarget = prepareCliSpawn(bootstrapped.command, bootstrapped.args, env);
const result = await runStreamingCommand(spawnTarget.command, spawnTarget.args, (line) => {
const event = parseAgentLine(line);
diff --git a/server/services/opencodeTask.test.js b/server/services/opencodeTask.test.js
index 5e3bc62a40..a1b1435eaf 100644
--- a/server/services/opencodeTask.test.js
+++ b/server/services/opencodeTask.test.js
@@ -87,6 +87,18 @@ describe('runOpencodeTask', () => {
expect(args[args.indexOf('--dir') + 1]).toBe('/tmp/sandbox');
});
+ it('spawns the credential-bootstrap CLI in front of opencode when the provider names one', async () => {
+ runStreamingCommand.mockResolvedValue({ success: true });
+ await runOpencodeTask({
+ provider: { ...OPENCODE_OLLAMA_TUI, credentialBootstrap: { command: 'token-cli', args: ['run'], argsSeparator: '--' } },
+ modelId: 'qwen2.5-coder:32b', cwd: '/tmp/sandbox', prompt: 'fix it', timeoutMs: 1000,
+ });
+ const [command, args] = runStreamingCommand.mock.calls[0];
+ expect(command).toBe('token-cli');
+ expect(args.slice(0, 4)).toEqual(['run', 'opencode', '--', 'run']);
+ expect(args[args.indexOf('--model') + 1]).toBe('ollama/qwen2.5-coder:32b');
+ });
+
it('streams parsed frames and returns them for aggregation', async () => {
runStreamingCommand.mockImplementation(async (_cmd, _args, onLine) => {
onLine(JSON.stringify({ type: 'text', part: { type: 'text', text: 'Reading.' } }));
diff --git a/server/services/providerPrerequisites.js b/server/services/providerPrerequisites.js
index 095996d52c..1a7fb46f8c 100644
--- a/server/services/providerPrerequisites.js
+++ b/server/services/providerPrerequisites.js
@@ -38,6 +38,7 @@ import { PROVIDER_GATEWAYS } from '../lib/providerGateways.js';
import { readCodexRoutingOverride } from '../lib/codexUserConfig.js';
import { inferTuiCommand } from '../lib/providerVendors.js';
import { findCommandOnPath } from '../lib/processEnv.js';
+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
import { peekCodexAccountReadiness } from './codexAppServer.js';
import { getCodexOssSupport, peekCodexOssSupport, refreshCodexOssSupportInBackground } from './codexOssSupport.js';
import { codexOssLocalProvider } from '../lib/providerModels.js';
@@ -163,10 +164,17 @@ const prerequisiteReadinessFor = (provider, runtimes, gatewayKeySet) => {
const processProviderRuntimeStatus = (provider, { cwd = null, deferCwdDependent = false } = {}) => {
if (provider?.type !== 'cli' && provider?.type !== 'tui') return null;
if (!configuredCommandIsNormalized(provider)) return { installed: false, reasonCode: 'command' };
- const command = effectiveProcessCommand(provider);
- const effectiveProvider = { ...provider, command };
+ const harnessCommand = effectiveProcessCommand(provider);
+ const effectiveProvider = { ...provider, command: harnessCommand };
const runtimeKey = providerRuntimeKey(effectiveProvider);
- if (runtimeKey && getProviderRuntime(runtimeKey)) return null;
+ // A managed runtime installs the HARNESS; a credential-bootstrap provider
+ // still spawns its bootstrap binary in front of it, so that one is probed
+ // regardless. The probe targets whatever PortOS actually spawns
+ // (credentialBootstrap.js): the harness may legitimately be absent from PATH
+ // when the bootstrap CLI supplies it, and a missing bootstrap binary is the
+ // ENOENT every run would hit.
+ const { command } = applyCredentialBootstrap(provider, harnessCommand, []);
+ if (command === harnessCommand && runtimeKey && getProviderRuntime(runtimeKey)) return null;
const env = { ...process.env, ...(provider?.envVars || {}) };
const explicitRelativeCommand = /[\\/]/.test(command) && !isAbsolute(command);
const relativePathEntry = String(env.PATH || env.Path || '')
diff --git a/server/services/providerPrerequisites.test.js b/server/services/providerPrerequisites.test.js
index e149dcaef8..394f8d7948 100644
--- a/server/services/providerPrerequisites.test.js
+++ b/server/services/providerPrerequisites.test.js
@@ -186,6 +186,21 @@ describe('getProviderPrerequisiteReadinessMap', () => {
expect(getProviderRuntimeStatuses).not.toHaveBeenCalled();
});
+ // What gets spawned is the bootstrap binary; the harness may sit behind it,
+ // off PATH. Probing the harness would report green for a run that ENOENTs
+ // and red for one that works.
+ it('probes the credential-bootstrap binary instead of the harness when one is configured', async () => {
+ const present = basename(process.execPath);
+ const env = { PATH: dirname(process.execPath) };
+ await expect(getProviderPrerequisiteReadinessMap([
+ codex({ id: 'bootstrap-present', command: 'harness-not-on-path', envVars: env, credentialBootstrap: { command: present } }),
+ codex({ id: 'bootstrap-missing', command: present, envVars: env, credentialBootstrap: { command: 'token-cli-not-on-path' } }),
+ ])).resolves.toMatchObject({
+ 'bootstrap-present': { status: 'ready', reasonCodes: [] },
+ 'bootstrap-missing': { status: 'blocked', reasonCodes: ['runtime'] },
+ });
+ });
+
it('defers app-relative commands in the catalog and resolves them from the selected workspace', async () => {
const provider = codex({ id: 'app-local', command: `./${basename(process.execPath)}` });
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index fcf0585182..93524313f3 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -6,6 +6,7 @@ import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';
import { commandBasename } from '../lib/providerModels.js';
import { PROVIDER_FAMILIES, familyForProvider } from '../lib/providerFamilies.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
+import { applyCredentialBootstrap } from '../lib/credentialBootstrap.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
import { parseHumanReset, normalizeResetAt } from '../lib/quotaReset.js';
import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';
@@ -698,7 +699,11 @@ function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name, rea
// doesn't serve the previous account's quota from a stale entry.
const cacheKey = `${id}:${command}:${provider.type}:${JSON.stringify(env)}:${JSON.stringify(args)}`;
const card = await scrapeCache.read(cacheKey, async () => {
- const text = await scrapeTuiUsage({ command, args, slashCommand, env, readyMarker });
+ // The scrape spawns the provider like any other site: wrapped by its
+ // credential bootstrap when configured (credentialBootstrap.js), or the
+ // TUI comes up unauthenticated and never renders a usage panel.
+ const spawned = applyCredentialBootstrap(provider, command, args);
+ const text = await scrapeTuiUsage({ command: spawned.command, args: spawned.args, slashCommand, env, readyMarker });
// The panel's reset is relative (agy) or zone-less (grok) — both resolve
// against the read's own clock and the zone the child rendered in.
const { limits, plan } = parse(text, { now: Date.now(), timezone: tz });
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 89a29349f8..446ee85b11 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -611,6 +611,16 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {
scrapeTuiUsage.mockReset();
});
+ it('scrapes through the credential-bootstrap CLI when the provider names one', async () => {
+ getAllProviders.mockResolvedValueOnce({ activeProvider: 'agy', providers: [{
+ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy',
+ credentialBootstrap: { command: 'token-cli', args: ['run'] },
+ }] });
+ scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);
+ await getProviderQuotas();
+ expect(scrapeTuiUsage).toHaveBeenCalledWith(expect.objectContaining({ command: 'token-cli', args: ['run', 'agy'], slashCommand: '/usage' }));
+ });
+
it('surfaces a supported Antigravity card with parsed limits', async () => {
getAllProviders.mockResolvedValueOnce({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });
scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 1722908794..2fd607d051 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -704,10 +704,12 @@ describe('executeCliRun — credential-bootstrap wrapping', () => {
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', '-']));
+ // Exact order: bootstrap args, then the harness by its bootstrap-side id,
+ // then the separator, then the harness's own argv — whose prompt-delivery
+ // convention (claude's `-p -`) is still resolved against `provider.command`,
+ // not the bootstrap CLI. `arrayContaining` would pass with the separator
+ // after the harness args, the exact mistake the wrap exists to prevent.
+ expect(args).toEqual(['run', 'claude-code', '--', '-p', '-']);
});
});