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
reach a bootstrap provider's harness from Launch in Shell and Refresh Models
[._.]/ Adam Eivyab11184e3227
diff --git a/scripts/migrations/391-credential-bootstrap-mode-siblings.js b/scripts/migrations/391-credential-bootstrap-mode-siblings.jsnew file mode 100644index 0000000000..ed272dea9a--- /dev/null+++ b/scripts/migrations/391-credential-bootstrap-mode-siblings.js@@ -0,0 +1,38 @@+/**+ * Converge a CLI/TUI pair whose credential bootstrap landed on only ONE mode.+ *+ * The AI Providers page renders a conventional pair as one card and opens the+ * editor on its representative (the CLI mode), but `updateProvider` did not fan+ * `credentialBootstrap` out to the sibling — so a Bootstrap Command typed into+ * that one editor never reached the TUI record, which is what "Launch in Shell"+ * spawns. The fan-out is fixed in `sharedModeUpdates` and `unifyProviderModes`+ * now repairs a pair that arrived asymmetric anyway; this is the one-time pass+ * over an install that configured one before either existed.+ *+ * It is the migration-355 wrapper on purpose: the convergence rule lives beside+ * the pairing rule it belongs to and runs on every `providers.json` read, so an+ * asymmetric pair arriving later — peer sync, a hand edit, a restored backup —+ * heals without waiting for a migration.+ */++import { unifyProviderModes } from '../../server/lib/aiToolkit/internal/providerModes.js';+import { readProvidersDoc, writeJsonAtomic } from './_lib.js';++async function up({ rootDir }) {+ const doc = await readProvidersDoc({ rootDir });+ if (!doc.ok) {+ if (doc.reason === 'no-file') console.log('📄 data/providers.json not present — skipping credential-bootstrap sibling repair');+ else if (doc.reason === 'unreadable') console.log(`⚠️ data/providers.json: invalid JSON, skipping (${doc.err.message})`);+ else console.log('⚠️ data/providers.json: unexpected shape, skipping');+ return { ok: false, reason: doc.reason, updated: 0 };+ }++ const changed = unifyProviderModes(doc.config);+ if (changed) {+ await writeJsonAtomic(doc.path, doc.config);+ console.log('🔑 data/providers.json: converged CLI/TUI mode siblings (credential bootstrap, enablement, models)');+ }+ return { ok: true, updated: changed ? 1 : 0 };+}++export default { up };diff --git a/scripts/migrations/391-credential-bootstrap-mode-siblings.test.js b/scripts/migrations/391-credential-bootstrap-mode-siblings.test.jsnew file mode 100644index 0000000000..a01cfa4778--- /dev/null+++ b/scripts/migrations/391-credential-bootstrap-mode-siblings.test.js@@ -0,0 +1,62 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './391-credential-bootstrap-mode-siblings.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const BOOTSTRAP = { command: 'token-cli', args: ['run'] };+const pair = (extra = {}) => ({+ example: { id: 'example', name: 'Example CLI', type: 'cli', command: 'example', args: ['--print'], enabled: true, models: ['a'], ...extra.cli },+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'example', args: [], enabled: true, models: ['a'], ...extra.tui },+});++describe('migration 391 — credential bootstrap on mode siblings', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-391-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('gives the sibling the pair’s one bootstrap, and re-runs clean', async () => {+ writeJson(providersPath, { activeProvider: 'example', providers: pair({ cli: { credentialBootstrap: BOOTSTRAP } }) });++ expect(await migration.up({ rootDir })).toMatchObject({ ok: true, updated: 1 });+ const out = readJson(providersPath);+ expect(out.providers['example-tui'].credentialBootstrap).toEqual(BOOTSTRAP);+ // Mode-specific argv is untouched — only the connection's auth converges.+ expect(out.providers['example-tui'].args).toEqual([]);+ expect(out.activeProvider).toBe('example');++ expect(await migration.up({ rootDir })).toMatchObject({ ok: true, updated: 0 });+ expect(readJson(providersPath)).toEqual(out);+ });++ it('leaves a pair alone when both modes name a bootstrap, and when they are not the same connection', async () => {+ const other = { command: 'other-cli' };+ const providers = {+ ...pair({ cli: { credentialBootstrap: BOOTSTRAP }, tui: { credentialBootstrap: other } }),+ // Same harness, different backend: two connections, not one card.+ split: { id: 'split', type: 'cli', command: 'split', models: [], envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434' }, credentialBootstrap: BOOTSTRAP },+ 'split-tui': { id: 'split-tui', type: 'tui', command: 'split', models: [], envVars: {} },+ };+ writeJson(providersPath, { providers });++ expect(await migration.up({ rootDir })).toMatchObject({ ok: true, updated: 0 });+ const out = readJson(providersPath).providers;+ expect(out['example-tui'].credentialBootstrap).toEqual(other);+ expect(out['split-tui']).not.toHaveProperty('credentialBootstrap');+ });++ it('skips an install with no providers file', async () => {+ expect(await migration.up({ rootDir })).toMatchObject({ ok: false, reason: 'no-file', updated: 0 });+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 4654917f24..f4590345a0 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 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. Both also return `wrapped`, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: `needsProcessGroup(wrapped)` says whether to spawn `detached` and kill with `{ processGroup: true }` (POSIX only — Windows' `taskkill /T` is already tree-wide), and `processGroupKillable(child, processGroup)` adapts a child for the aiToolkit runner's external-run registry, whose vendored `killProcessTree` has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. `trackDetachedGroup(child, processGroup)` / `signalDetachedGroups(signal, logFailure)` are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at `npm start`) from orphaning one. |+| `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`. The pure argv composition lives in `aiToolkit/internal/credentialBootstrap.js` (`composeBootstrapSpawn` / `hasCredentialBootstrap`, dependency-free), re-exported through here so the vendored toolkit's own catalog probes compose the same shape without importing out. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. Both also return `wrapped`, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: `needsProcessGroup(wrapped)` says whether to spawn `detached` and kill with `{ processGroup: true }` (POSIX only — Windows' `taskkill /T` is already tree-wide), and `processGroupKillable(child, processGroup)` adapts a child for the aiToolkit runner's external-run registry, whose vendored `killProcessTree` has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. `trackDetachedGroup(child, processGroup)` / `signalDetachedGroups(signal, logFailure)` are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at `npm start`) from orphaning one. || `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/credentialBootstrap.js b/server/lib/aiToolkit/internal/credentialBootstrap.jsnew file mode 100644index 0000000000..3afb66d619--- /dev/null+++ b/server/lib/aiToolkit/internal/credentialBootstrap.js@@ -0,0 +1,61 @@+/**+ * The PURE argv shape of a provider's credential bootstrap: what to spawn when+ * a CLI/TUI provider's auth is provisioned by an external CLI at spawn time+ * rather than by a static `apiKey` PortOS stores.+ *+ * It lives in this directory — the lowest, dependency-free layer — because+ * BOTH sides need it and only this direction is legal: the vendored toolkit may+ * not import out to PortOS modules, while `server/lib/credentialBootstrap.js`+ * (the host's spawn-site helper, which adds the public-review safety skip and+ * the Windows shim resolution) imports this leaf rather than restating the+ * shape. The toolkit's own child spawns — the model-catalog probes behind the+ * provider card's **Refresh Models** button — call it directly, because a probe+ * that runs the bare harness runs it with no credential and answers for the+ * wrong account (or fails outright), exactly as a bare run would.+ *+ * Imports nothing.+ */++/** 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 to actually spawn for this provider: the bootstrap CLI in+ * front of the harness invocation when one is configured, or the harness+ * invocation unchanged otherwise. Never touches the filesystem or PATH.+ *+ * 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.+ * `claude-code` where `provider.command` is the literal binary `claude`); it+ * defaults to the harness binary.+ *+ * `wrapped` says whether the bootstrap CLI is now the direct child. The host's+ * teardown keys on it (`server/lib/credentialBootstrap.js#needsProcessGroup`,+ * #7496): a wrapper that forks rather than execs the harness would survive a+ * per-pid signal, so a wrapped spawn needs its own process group.+ *+ * @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[], wrapped: boolean}}+ */+export function composeBootstrapSpawn(provider, command, args) {+ const harnessArgs = Array.isArray(args) ? args : [];+ if (!hasCredentialBootstrap(provider)) return { command, args: harnessArgs, wrapped: false };+ const bootstrap = provider.credentialBootstrap;+ 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],+ wrapped: true,+ };+}diff --git a/server/lib/aiToolkit/internal/providerModes.js b/server/lib/aiToolkit/internal/providerModes.jsindex 97fdaa9841..9e0a8e71b3 100644--- a/server/lib/aiToolkit/internal/providerModes.js+++ b/server/lib/aiToolkit/internal/providerModes.js@@ -1,6 +1,7 @@// Keep execution IDs stable: saved tasks and older peers still select a mode.// Pair only conventional sibling IDs with the same harness and connection.import { isDeepStrictEqual } from 'node:util';+import { hasCredentialBootstrap } from './credentialBootstrap.js';const MODE_KEY_DEFAULTS = { endpoint: '', apiKey: '', envVars: {}, credentialBootstrap: null };@@ -24,7 +25,9 @@ export function providerModeGroups(providers) {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;// `credentialBootstrap` is the connection's auth when there is no apiKey,- // so siblings that disagree on it are two connections, not one.+ // so siblings naming DIFFERENT ones are two connections, not one. A pair+ // where only one names a bootstrap is the asymmetry `unifyProviderModes`+ // converges, so it does not reach here as a lasting split.if (!MODE_GROUPED_KEYS.every(key =>isDeepStrictEqual(cli[key] || MODE_KEY_DEFAULTS[key], tui[key] || MODE_KEY_DEFAULTS[key]))) continue;groups.push([cli, tui]);@@ -36,7 +39,15 @@ export function providerModeGroups(providers) {export function sharedModeUpdates(updates, sibling) {// Arguments, timeouts, routing consent and model pins remain mode-specific.- const shared = Object.fromEntries(['enabled', 'models', 'modelContextWindows'].filter(key => Object.hasOwn(updates, key)).map(key => [key, updates[key]]));+ //+ // `credentialBootstrap` is shared for the same reason the pairing test above+ // keys on it: it is the connection's AUTH, not a mode's argv. The editor opens+ // the group's representative (the CLI mode), so a bootstrap saved there and+ // not fanned out leaves the TUI mode — the one "Launch in Shell" launches —+ // spawning a bare harness that falls through to ambient vendor auth, and+ // splits the one card in two. `unifyProviderModes` converges a pair that+ // arrived asymmetric by some other route.+ const shared = Object.fromEntries(['enabled', 'models', 'modelContextWindows', 'credentialBootstrap'].filter(key => Object.hasOwn(updates, key)).map(key => [key, updates[key]]));// A caller deliberately repicking a default with a new catalog (the editor// or harness discovery) must repair a removed sibling default too. Ordinary// catalog probes omit defaultModel and retain their existing pin semantics.@@ -46,9 +57,41 @@ export function sharedModeUpdates(updates, sibling) {return shared;}-export function unifyProviderModes(data) {+/**+ * Give a mode sibling the credential bootstrap its pair already carries.+ *+ * Grouped over a projection with `credentialBootstrap` ERASED, because an+ * asymmetric pair is invisible to the real rule — the bootstrap is exactly the+ * value it disagrees on. Only this fill uses the loose grouping; the+ * enablement/model convergence below keeps the strict one.+ *+ * Exactly one named bootstrap is repaired. Two different ones are a deliberate+ * configuration (two connections), and picking a winner between two credentials+ * is nobody's call to make silently.+ */+function fillModeSiblingBootstrap(providers) {+ const byId = new Map(providers.map(provider => [provider.id, provider]));let changed = false;- for (const group of providerModeGroups(Object.values(data.providers || {}))) {+ for (const group of providerModeGroups(providers.map(provider => ({ ...provider, credentialBootstrap: undefined })))) {+ if (group.length < 2) continue;+ const modes = group.map(({ id }) => byId.get(id)).filter(Boolean);+ const named = modes.filter(hasCredentialBootstrap);+ if (named.length !== 1) continue;+ for (const mode of modes) {+ if (hasCredentialBootstrap(mode)) continue;+ mode.credentialBootstrap = structuredClone(named[0].credentialBootstrap);+ changed = true;+ }+ }+ return changed;+}++export function unifyProviderModes(data) {+ const providers = Object.values(data.providers || {});+ // Bootstrap FIRST: a pair split only by an unfanned bootstrap is rejoined+ // here, so the convergence below sees the one connection it actually is.+ let changed = fillModeSiblingBootstrap(providers);+ for (const group of providerModeGroups(providers)) {if (group.length < 2) continue;const enabled = group.some(provider => provider.enabled === true);const models = [...new Set(group.flatMap(provider => provider.models || []))];diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 8a93afe62f..2a61db9d66 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -1,3 +1,4 @@+import { composeBootstrapSpawn } from './internal/credentialBootstrap.js';import { expandModePair, providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';import { readFile, rename } from 'fs/promises';import { existsSync } from 'fs';@@ -131,6 +132,21 @@ function escapeCmdMetacharsIfUnquoted(value) {return str.replace(CMD_METACHAR_RE, '^$&');}+/**+ * What a model-catalog probe should actually spawn for a provider, and the+ * label its failure messages must name.+ *+ * The bootstrap wrap belongs on EVERY probe (a bare harness runs with no+ * credential and answers for the wrong account — see+ * `internal/credentialBootstrap.js`), and every message has to name what really+ * ran or a missing bootstrap binary reports itself as the harness failing.+ * Stating both once keeps the next vendor fetcher from spawning bare.+ */+function resolveProbeSpawn(provider, defaultBin, args) {+ const spawned = composeBootstrapSpawn(provider, provider?.command || defaultBin, args);+ return { ...spawned, label: `'${spawned.command} ${spawned.args.join(' ')}'` };+}+// windowsHide is applied here rather than by importing server/lib/childProcess.js:// the aiToolkit is contractually self-contained (see aiToolkit/AGENTS.md), so it// carries its own copy of the default. Without it, every CLI probe below spawns@@ -824,12 +840,23 @@ export function createProviderService(config = {}) {// "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;+ // Applied to the fanned-out siblings too: a cleared sibling that kept a+ // stored `null` would no longer read as "never had one".+ const dropClearedBootstrap = (record) => {+ if (record.credentialBootstrap === null) delete record.credentialBootstrap;+ };+ dropClearedBootstrap(provider);+ // Grouped BEFORE the edit lands: a bootstrap set on one mode is exactly+ // the value `providerModeGroups` pairs on, so reading the group after+ // would find the siblings already split and skip the fan-out that keeps+ // them together.const group = providerModeGroups(Object.values(data.providers)).find(modes => modes.some(mode => mode.id === id));data.providers[id] = provider;for (const sibling of group || []) {- if (sibling.id !== id) Object.assign(sibling, sharedModeUpdates(updates, sibling));+ if (sibling.id === id) continue;+ Object.assign(sibling, sharedModeUpdates(updates, sibling));+ dropClearedBootstrap(sibling);}await saveProviders(data);return provider;@@ -899,9 +926,8 @@ export function createProviderService(config = {}) {const lookup = isWin32 ? 'where' : 'which';// 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;+ // behind it, off PATH), else the harness itself.+ const probeCommand = composeBootstrapSpawn(provider, provider.command, []).command;const { stdout } = await execFileAsync(lookup, [probeCommand], { windowsHide: true }).catch(() => ({ stdout: '', stderr: 'not found' }));@@ -1544,8 +1570,9 @@ export function createProviderService(config = {}) {* @returns {Promise<string[]>} parsed ids; empty only when explicitly recognized*/async _execCliModelList(provider, defaultBin, parse, listArgs = ['models'], isEmptyCatalog = () => false) {- const bin = provider?.command || defaultBin;- const { command, args } = prepareWindowsSafeSpawn(bin, listArgs);+ const spawned = resolveProbeSpawn(provider, defaultBin, listArgs);+ const probe = spawned.label;+ const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);const pending = execFileAsync(command, args, {timeout: 15000,env: { ...process.env, ...provider?.envVars },@@ -1562,12 +1589,12 @@ export function createProviderService(config = {}) {const { stdout } = await pending.catch((err) => {const output = `${err.stdout || ''}\n${err.stderr || ''}`;if (!err.killed && isEmptyCatalog(output)) return { stdout: output };- throw new Error(`'${bin} ${listArgs.join(' ')}' failed: ${err?.message || 'could not run the binary'}`);+ throw new Error(`${probe} failed: ${err?.message || 'could not run the binary'}`);});const listed = parse(stdout);if (listed.length === 0 && !isEmptyCatalog(stdout)) {- throw new Error(`'${bin} ${listArgs.join(' ')}' returned no model ids`);+ throw new Error(`${probe} returned no model ids`);}return listed;},@@ -1611,15 +1638,16 @@ export function createProviderService(config = {}) {* consistent with _execCliModelList and _fetchOllamaToolCapableModels.*/async _fetchCodexModels(provider) {- const bin = provider?.command || 'codex';+ const spawned = resolveProbeSpawn(provider, 'codex', ['app-server']);+ const probe = spawned.label;// On Windows, npm places a POSIX `codex` stub beside its runnable// `codex.cmd` shim. `spawn('codex')` can select the former (or fail to// resolve it entirely), even though the provider passed its capability// check. Resolve the extension-bearing shim before the safe cmd.exe// wrapper below, matching the other CLI probes in this module.const childEnv = { ...process.env, ...provider?.envVars };- const resolvedBin = resolveWindowsExecutable(bin, process.platform === 'win32', childEnv) || bin;- const { command, args } = prepareWindowsSafeSpawn(resolvedBin, ['app-server']);+ const resolvedBin = resolveWindowsExecutable(spawned.command, process.platform === 'win32', childEnv) || spawned.command;+ const { command, args } = prepareWindowsSafeSpawn(resolvedBin, spawned.args);return new Promise((resolve, reject) => {let settled = false;let child;@@ -1635,7 +1663,7 @@ export function createProviderService(config = {}) {};const timer = setTimeout(() => {- settle(new Error(`'${bin} app-server' timed out waiting for model catalog`));+ settle(new Error(`${probe} timed out waiting for model catalog`));}, 15000);timer.unref?.();@@ -1646,18 +1674,18 @@ export function createProviderService(config = {}) {windowsHide: true,});} catch (err) {- settle(new Error(`'${bin} app-server' failed to spawn: ${err?.message || err}`));+ settle(new Error(`${probe} failed to spawn: ${err?.message || err}`));return;}child.on('error', (err) => {- settle(new Error(`'${bin} app-server' failed: ${err?.message || err}`));+ settle(new Error(`${probe} failed: ${err?.message || err}`));});child.stdin?.on('error', () => {});child.on('exit', (code, signal) => {- settle(new Error(`'${bin} app-server' exited prematurely with code ${code ?? signal}`));+ settle(new Error(`${probe} exited prematurely with code ${code ?? signal}`));});let buffer = '';@@ -1675,7 +1703,7 @@ export function createProviderService(config = {}) {child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'model/list', params: {} }) + '\n');} else if (msg.id === 2) {if (msg.error) {- settle(new Error(`'${bin} app-server' model/list error: ${msg.error.message || JSON.stringify(msg.error)}`));+ settle(new Error(`${probe} model/list error: ${msg.error.message || JSON.stringify(msg.error)}`));return;}const rawModels = msg.result?.data || msg.result?.models || [];@@ -1684,7 +1712,7 @@ export function createProviderService(config = {}) {.map((m) => (typeof m === 'string' ? m : m?.id || m?.model)).filter(Boolean);if (ids.length === 0) {- settle(new Error(`'${bin} app-server' returned no model ids`));+ settle(new Error(`${probe} returned no model ids`));return;}settle(null, [...new Set(ids)]);diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 7b58fd6d8d..5cebf906f8 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -97,17 +97,51 @@ describe('Provider Service', () => {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 () => {+ it('does not pair CLI/TUI modes as one connection when they name DIFFERENT credential bootstraps', 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'] },+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'example', enabled: true, models: ['b'], credentialBootstrap: { command: 'other-cli' } },} }));- // Unpaired: neither enablement nor models unify across the two.+ // Two credentials are two connections: nothing converges, and neither+ // enablement nor models unify across the two.expect((await providerService.getProviderById('example')).enabled).toBe(false);+ expect((await providerService.getProviderById('example')).credentialBootstrap).toEqual({ command: 'token-cli' });await providerService.updateProvider('example-tui', { models: ['c'] });expect((await providerService.getProviderById('example')).models).toEqual(['a']);});+ it('converges a pair that carries the bootstrap on only ONE mode', async () => {+ // The asymmetry the fan-out now prevents can still ARRIVE — a record+ // written before it, a hand-edited file, a restored backup — and the TUI+ // mode is what "Launch in Shell" spawns, so the load-time convergence+ // repairs it rather than leaving the card split and the launch bare.+ await writeFile(join(TEST_DATA_DIR, 'providers.json'), JSON.stringify({ activeProvider: 'example', providers: {+ example: { id: 'example', name: 'Example CLI', type: 'cli', command: 'example', enabled: true, models: ['a'], credentialBootstrap: { command: 'token-cli', args: ['run'] } },+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'example', enabled: true, models: ['a'] },+ } }));+ expect((await providerService.getProviderById('example-tui')).credentialBootstrap).toEqual({ command: 'token-cli', args: ['run'] });+ });++ it('fans a credential bootstrap out to the mode sibling, set and cleared', async () => {+ // Why the connection's auth has to reach the sibling: see+ // `sharedModeUpdates`. The TUI mode is what "Launch in Shell" spawns.+ await writeFile(join(TEST_DATA_DIR, 'providers.json'), JSON.stringify({ activeProvider: 'example', providers: {+ example: { id: 'example', name: 'Example CLI', type: 'cli', command: 'example', enabled: true, models: ['a'], args: ['--print'] },+ 'example-tui': { id: 'example-tui', name: 'Example TUI', type: 'tui', command: 'example', enabled: true, models: ['a'], args: [] },+ } }));+ const bootstrap = { command: 'token-cli', args: ['run'] };+ await providerService.updateProvider('example', { credentialBootstrap: bootstrap });+ expect((await providerService.getProviderById('example-tui')).credentialBootstrap).toEqual(bootstrap);+ // Mode-specific argv still never crosses over.+ expect((await providerService.getProviderById('example-tui')).args).toEqual([]);+ // Cleared the same way it was set: the key is dropped on BOTH records, so+ // neither reads as a stored `null` the pairing test would treat as a+ // different value from the other's absent key.+ await providerService.updateProvider('example', { credentialBootstrap: null });+ expect(await providerService.getProviderById('example')).not.toHaveProperty('credentialBootstrap');+ expect(await providerService.getProviderById('example-tui')).not.toHaveProperty('credentialBootstrap');+ });+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) => {@@ -129,6 +163,28 @@ describe('Provider Service', () => {expect(await providerService._fetchPiModels({ command })).toEqual([]);});+ it.skipIf(process.platform === 'win32')('probes the catalog through the credential bootstrap, not the bare harness', async () => {+ // The harness itself is never on PATH here: it exists only behind the+ // bootstrap CLI, which is the point — a probe that spawned the bare+ // harness would fail outright rather than answer for the credential the+ // bootstrap mints. The stub refuses any argv but the wrapped shape.+ const bootstrap = join(TEST_DATA_DIR, 'token-cli');+ await writeFile(bootstrap, [+ '#!/usr/bin/env node',+ "const argv = process.argv.slice(2).join(' ');",+ "if (argv !== 'run pi-harness -- --list-models') { console.error('unexpected argv: ' + argv); process.exit(9); }",+ "console.log('provider model context max-out thinking images');",+ "console.log('example model-a 200K 32K yes yes');",+ ].join('\n'));+ await chmod(bootstrap, 0o755);++ const provider = await providerService.createProvider({+ name: 'Bootstrapped Pi', type: 'cli', command: join(TEST_DATA_DIR, 'pi'), models: [],+ credentialBootstrap: { command: bootstrap, args: ['run'], harnessId: 'pi-harness', argsSeparator: '--' },+ });+ expect((await providerService.refreshProviderModels(provider.id)).models).toEqual(['example/model-a']);+ });+it('should create a provider', async () => {const provider = await providerService.createProvider({name: 'Test Provider',diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.jsindex eeb030e119..39c083540b 100644--- a/server/lib/credentialBootstrap.js+++ b/server/lib/credentialBootstrap.js@@ -29,7 +29,9 @@* `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`,+ * (`providerUsage.js`), the model-catalog probes behind Refresh Models (the+ * toolkit's `_execCliModelList` / `_fetchCodexModels`, which reach the shape+ * through the leaf below), and the readiness probes (`providerPrerequisites.js`,* the toolkit's `testProvider`).** A public-review posture (`isPublicReviewRestrictedProfile`) is NEVER@@ -46,19 +48,23 @@* `signalDetachedGroups` / `processGroupKillable` below are that half of the* contract — see `needsProcessGroup` (#7496).*- * 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.+ * The argv SHAPE is composed one layer down, by the dependency-free+ * `aiToolkit/internal/credentialBootstrap.js` leaf (which documents why it sits+ * there); this module adds the public-review skip, the Windows resolution, and+ * the teardown half above.+ *+ * Imports only `bufferedSpawn.js`, `agentExecutionProfiles.js` (both of which+ * `cliProviderRun.js` already depends on directly) and that leaf, so any spawn+ * site — including the standalone `portos-autofixer` process via+ * `cliProviderRun.js` — can import this module without dragging in the rest of+ * the AI toolkit or the data layer.*/import { IS_WIN32, resolveWindowsExecutable, prepareWindowsSafeSpawn, killProcessTree } from './bufferedSpawn.js';import { isPublicReviewRestrictedProfile } from './agentExecutionProfiles.js';+import { composeBootstrapSpawn, hasCredentialBootstrap } from './aiToolkit/internal/credentialBootstrap.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;-}+export { hasCredentialBootstrap };/*** The command+args PortOS should actually spawn for this provider: the@@ -67,18 +73,9 @@ export function hasCredentialBootstrap(provider) {* 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.+ * The shape it composes — and why `harnessId` and `argsSeparator` exist — is+ * documented on `composeBootstrapSpawn`. What this adds is the safety skip: a+ * public-review posture is returned UNWRAPPED.** @param {{credentialBootstrap?: {command: string, args?: string[], harnessId?: string, argsSeparator?: string}}|null|undefined} provider* @param {string} command - the harness binary PortOS would otherwise spawn@@ -96,19 +93,10 @@ export function hasCredentialBootstrap(provider) {* @returns {{command: string, args: string[], wrapped: boolean}}*/export function applyCredentialBootstrap(provider, command, args, { safetyProfile = null } = {}) {- const bootstrap = provider?.credentialBootstrap;- const harnessArgs = Array.isArray(args) ? args : [];- if (!hasCredentialBootstrap(provider) || isPublicReviewRestrictedProfile(safetyProfile)) {- return { command, args: harnessArgs, wrapped: false };- }- 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],- wrapped: true,- };+ // A restricted posture composes against NO provider rather than short-circuiting,+ // so argv normalization — and the `wrapped` flag teardown keys on — is stated+ // in exactly one place.+ return composeBootstrapSpawn(isPublicReviewRestrictedProfile(safetyProfile) ? null : provider, command, args);}/**diff --git a/server/services/harnesses.js b/server/services/harnesses.jsindex e063ac67c9..c55a98c67c 100644--- a/server/services/harnesses.js+++ b/server/services/harnesses.js@@ -30,7 +30,9 @@* path calls it (root AGENTS.md, AI Provider Usage Policy).*/+import { isDeepStrictEqual } from 'node:util';import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { hasCredentialBootstrap, resolveCliSpawn } from '../lib/credentialBootstrap.js';import { commandOutput } from '../lib/commandExists.js';import { compareHarnessVersions, parseHarnessModels, parseNpmLatestVersion } from '../lib/harnessOutput.js';import { findCommandOnPath } from '../lib/processEnv.js';@@ -244,6 +246,21 @@ export async function listHarnesses({ fresh = false, run = commandOutput, ...pro}));}+/**+ * The ONE credential every record this refresh writes agrees on, or null.+ *+ * A single probe serves every target, so it can only run under a credential all+ * of them share: one distinct bootstrap across all targets is unambiguous, and+ * anything else — a mix of bootstrapped and not, or two different ones — cannot+ * be served by one spawn and probes bare, exactly as it always did.+ */+const soleCredentialBootstrap = (targets) => {+ const named = targets.filter(hasCredentialBootstrap);+ if (named.length === 0 || named.length !== targets.length) return null;+ return named.every((target) => isDeepStrictEqual(target.credentialBootstrap, named[0].credentialBootstrap))+ ? named[0] : null;+};+/*** Ask a harness which models it knows about, and write the answer to every* provider that draws from its own catalog.@@ -268,15 +285,27 @@ export async function refreshHarnessModels(id, { run = commandOutput, ...probeDeupdated: [],};}+ const findCommand = probeDeps.findCommand || findCommandOnPath;++ // The records this refresh will WRITE, resolved before the probe because the+ // credential the probe must run under belongs to THEM — not to whichever+ // card's button was clicked, and not to the ambient account.+ const targets = providersForHarness(await providerService.listProviders(), runtime).filter(usesHarnessCatalog);+ const credentialed = soleCredentialBootstrap(targets);+// The SAME injected runner answers the availability probe, so a caller (and a// test) drives one child-process boundary rather than two. Cache-respecting:// the page rendered from a probe seconds ago, and re-spawning the binary for// a 15s worst case ahead of the 45s models probe would double the wait on a// user-facing button. A binary that broke since then still refuses below.- const findCommand = probeDeps.findCommand || findCommandOnPath;- const status = await getProviderRuntimeStatus(runtime.id, { ...probeDeps, probeCommand: run });- if (!status?.installed) {- return { ok: false, reason: `${runtime.label} is not installed on this host.`, models: [], updated: [] };+ // Skipped entirely for a credentialed harness: it is reached through its+ // bootstrap CLI and need not be on PATH, so the probe would spawn a binary to+ // answer a question it would answer wrongly.+ if (!credentialed) {+ const status = await getProviderRuntimeStatus(runtime.id, { ...probeDeps, probeCommand: run });+ if (!status?.installed) {+ return { ok: false, reason: `${runtime.label} is not installed on this host.`, models: [], updated: [] };+ }}// `opencode models` prints from an on-disk catalog OpenCode refreshes on its@@ -290,24 +319,29 @@ export async function refreshHarnessModels(id, { run = commandOutput, ...probeDeconsole.log(`📚 ${runtime.label} catalog: ${catalog.primed ? 'refreshed' : 'left alone'} — ${catalog.reason}`);}- // Resolve and `prepareCliSpawn` exactly as the version probe does. An- // npm-installed harness is a `.cmd` shim on Windows, which `execFile` under- // `shell: false` refuses outright — the probe would answer nothing and the- // page would tell a signed-in user to go sign in.- const resolved = await findCommand(runtime.command);- const probe = prepareCliSpawn(resolved || runtime.command, [...runtime.modelsArgs]);+ // Resolve exactly as the version probe does. An npm-installed harness is a+ // `.cmd` shim on Windows, which `execFile` under `shell: false` refuses+ // outright — the probe would answer nothing and the page would tell a+ // signed-in user to go sign in. A credentialed harness skips the PATH walk+ // (it need not be there); `resolveCliSpawn` resolves the bootstrap binary's+ // own shim instead.+ const resolved = credentialed ? null : await findCommand(runtime.command);+ const probe = resolveCliSpawn(credentialed, resolved || runtime.command, [...runtime.modelsArgs], process.env);const stdout = await run(probe.command, probe.args, { timeoutMs: MODELS_PROBE_TIMEOUT_MS });const models = parseHarnessModels(runtime.id, stdout);if (models.length === 0) {+ // Name what RAN, and only send the user to a terminal when a terminal could+ // help: a credentialed harness mints its own auth and is not something they+ // can sign in to by hand.+ const ran = `\`${probe.command} ${probe.args.join(' ')}\` returned no models.`;return {ok: false,- reason: `\`${runtime.command} ${runtime.modelsArgs.join(' ')}\` returned no models. Sign in to ${runtime.label} in a terminal, then try again.`,+ reason: credentialed ? ran : `${ran} Sign in to ${runtime.label} in a terminal, then try again.`,models: [],updated: [],};}- const targets = providersForHarness(await providerService.listProviders(), runtime).filter(usesHarnessCatalog);const updated = [];for (const provider of targets) {// Hold the record's namespace scope (see `storedNamespaces`). A filter thatdiff --git a/server/services/harnesses.test.js b/server/services/harnesses.test.jsindex f328178d22..cf2a4edaff 100644--- a/server/services/harnesses.test.js+++ b/server/services/harnesses.test.js@@ -233,6 +233,38 @@ describe('refreshHarnessModels', () => {expect(opencodeCatalog.primeOpencodeCatalogCache).toHaveBeenCalledTimes(1);});+ // The credential comes from the records the refresh will WRITE, so BOTH+ // buttons (the provider card's and the Harnesses page's) probe under it. A+ // bootstrapped harness reaches its binary through that CLI and need not be on+ // PATH at all, which is why the "not installed" refusal steps aside.+ it('probes under the credential its write targets share, even when the harness is not on PATH', async () => {+ const run = vi.fn(async (command, args) => (args.includes('models') ? OPENCODE_MODELS : ''));+ const bootstrap = { command: 'token-cli', args: ['run'], harnessId: 'opencode-harness', argsSeparator: '--' };+ providerService.listProviders.mockResolvedValue([+ { id: 'boot-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: bootstrap },+ { id: 'boot-tui', type: 'tui', command: 'opencode', models: [], credentialBootstrap: { ...bootstrap } },+ ]);++ const result = await refreshHarnessModels('opencode', { run, findCommand: async () => null });++ expect(result.ok).toBe(true);+ expect(run).toHaveBeenCalledWith('token-cli', ['run', 'opencode-harness', '--', 'models'], expect.anything());+ });++ // One probe cannot serve two credentials, so a mix runs bare rather than+ // handing one record's token to another record's refresh.+ it('probes bare when only some write targets carry a bootstrap', async () => {+ const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));+ providerService.listProviders.mockResolvedValue([+ { id: 'boot-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-cli' } },+ { id: 'plain-cli', type: 'cli', command: 'opencode', models: [] },+ ]);++ await refreshHarnessModels('opencode', { run, ...found });++ expect(run).toHaveBeenCalledWith('/example/opencode', ['models'], expect.anything());+ });+it('writes the harness catalog only to providers that draw from it', async () => {const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));