nexos-connect 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -16
- package/dist/index.js +584 -266
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/main.ts","../src/cli/classify-failure.ts","../src/shared/text/describe-error.ts","../src/ui/cancelled-error.ts","../src/cli/exit-code.ts","../src/cli/usage-error.ts","../src/cli/environment.ts","../src/product/gateway/gateway-errors.ts","../src/product/gateway/desired-config.ts","../src/product/gateway/gateway-request.ts","../src/product/gateway/models/predefined-models.ts","../src/shared/text/has-line-break.ts","../src/shared/text/read-non-blank.ts","../src/cli/help.ts","../src/cli/parse-cli-arguments.ts","../src/shared/file-formats/shell/escape-posix-single-quoted.ts","../src/shared/file-formats/shell/escape-powershell-single-quoted.ts","../src/product/secrets/key-prefix.ts","../src/product/secrets/masker.ts","../src/shared/platform/has-binary.ts","../src/shared/file-system/is-file.ts","../src/shared/file-system/is-missing-file-error.ts","../src/shared/platform/platform-context.ts","../src/commands/forget-key/forget-key.ts","../src/cli/refuse-prompts.ts","../src/flows/key/find-existing-keys.ts","../src/harnesses/claude-code/claude-code.ts","../src/shared/text/display-path.ts","../src/shared/file-system/find-first-existing-file.ts","../src/harnesses/detect-config-file.ts","../src/harnesses/read-jsonc-file.ts","../src/shared/file-formats/config-errors.ts","../src/shared/file-formats/jsonc.ts","../src/shared/file-formats/detect-line-ending.ts","../src/shared/file-formats/key-path.ts","../src/shared/file-formats/key-original.ts","../src/shared/file-formats/split-byte-order-mark.ts","../src/shared/file-system/read-file-if-exists.ts","../src/shared/file-system/utf16-file-error.ts","../src/harnesses/codex/codex.ts","../src/shared/file-formats/toml.ts","../src/harnesses/copilot-cli/copilot-cli.ts","../src/harnesses/gemini-cli/gemini-cli.ts","../src/harnesses/opencode/opencode.ts","../src/harnesses/registry.ts","../src/product/storage/env-file/split-lines.ts","../src/product/storage/env-file/syntax/env-syntaxes.ts","../src/product/storage/env-file/syntax/posix-env-syntax.ts","../src/product/storage/env-file/syntax/env-syntax.ts","../src/product/storage/env-file/syntax/powershell-env-syntax.ts","../src/product/storage/env-file/parse-env-file.ts","../src/flows/key/key-step.ts","../src/product/gateway/models/protocol.ts","../src/ui/report/format-probes.ts","../src/ui/glyphs.ts","../src/ui/report/format-heading.ts","../src/ui/report/indent.ts","../src/flows/key/key-check.ts","../src/product/gateway/list-models.ts","../src/shared/text/format-count.ts","../src/product/gateway/model-schema.ts","../src/product/gateway/probe-result.ts","../src/flows/key/probe-summaries.ts","../src/product/gateway/models/model-compatibility.ts","../src/ui/model-choices.ts","../src/flows/model/model-choice.ts","../src/flows/model/model-probe.ts","../src/product/gateway/models/router-availability.ts","../src/product/gateway/probe-anthropic.ts","../src/product/storage/preferences/preferences.ts","../src/shared/file-system/describe-file-error.ts","../src/flows/model/suggest-defaults.ts","../src/flows/model/model-step.ts","../src/flows/model/choose-checked-model.ts","../src/product/storage/env-file/env-file-path.ts","../src/commands/launch/launch.ts","../src/commands/restore/run-restore.ts","../src/cli/resolve-named-harnesses.ts","../src/product/storage/backups/resolve-backup-root.ts","../src/product/storage/restore-record/restore-record.ts","../src/shared/file-formats/config-format.ts","../src/shared/file-system/resolve-owner-only-mode.ts","../src/shared/file-system/write-file-with-mode.ts","../src/product/storage/restore-record/restore-record-location.ts","../src/ui/report/format-restore-preview.ts","../src/ui/report/format-preview.ts","../src/ui/diff/diff-lines.ts","../src/ui/diff/render-diff.ts","../src/ui/report/format-restore-result.ts","../src/commands/restore/restore-result.ts","../src/commands/restore/apply-restore.ts","../src/product/storage/backups/back-up-file.ts","../src/shared/file-system/read-file-mode.ts","../src/product/storage/backups/back-up-before-writing.ts","../src/product/storage/env-file/write-env-file.ts","../src/product/storage/restore-record/remove-harness-records.ts","../src/product/storage/env-file/render-env-file.ts","../src/commands/restore/restore-env-text.ts","../src/commands/restore/restore-plan.ts","../src/product/storage/env-file/read-env-file.ts","../src/commands/restore/restore-secrets.ts","../src/ui/report/format-detection.ts","../src/ui/report/format-result.ts","../src/commands/setup/setup-result.ts","../src/ui/format-list.ts","../src/ui/report/outcome-style.ts","../src/commands/setup/answers/describe-key-destination.ts","../src/commands/setup/answers/scope.ts","../src/commands/setup/answers/harness-selection.ts","../src/commands/setup/changes/apply-changes.ts","../src/commands/setup/changes/change-plan.ts","../src/product/storage/restore-record/add-originals.ts","../src/commands/setup/changes/record-originals.ts","../src/commands/setup/run-setup.ts","../src/harnesses/run-launch.ts","../src/product/storage/keychain/keystore.ts","../src/ui/output.ts","../src/ui/prompts/confirm.ts","../src/ui/prompts/key/ask-for-key.ts","../src/ui/prompts/key/ask-for-new-key.ts","../src/ui/prompts/key/choose-on-saved-key-rejected.ts","../src/ui/prompts/key/choose-saved-key.ts","../src/ui/prompts/model/ask-for-model-id.ts","../src/ui/back-keys.ts","../src/ui/prompts/model/choose-on-fetch-failure.ts","../src/ui/prompts/model/choose-saved-model.ts","../src/ui/prompts/model/select-model.ts","../src/ui/prompts/model/browse-catalogue.ts","../src/ui/prompts/select-harnesses.ts","../src/ui/prompts/select-restore-harnesses.ts","../src/ui/prompts/select-restore-scope.ts","../src/ui/prompts/select-scope.ts","../src/ui/spinner.ts","../src/ui/terminal-ui.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process'\nimport { createRequire } from 'node:module'\nimport os from 'node:os'\nimport path from 'node:path'\nimport crossSpawn from 'cross-spawn'\nimport pc from 'picocolors'\nimport * as v from 'valibot'\nimport { classifyFailure, exitCodeForFailure } from './cli/classify-failure'\nimport { KEY_ENV_VARIABLE } from './cli/environment'\nimport { EXIT_CODE, type AgentExitCode } from './cli/exit-code'\nimport { renderHelp } from './cli/help'\nimport { isAgentName, parseCliArguments, type CliOptions, type Command } from './cli/parse-cli-arguments'\nimport { forgetKey } from './commands/forget-key/forget-key'\nimport { launch } from './commands/launch/launch'\nimport { runRestore } from './commands/restore/run-restore'\nimport { runSetup } from './commands/setup/run-setup'\nimport type { Harness, LaunchingHarness } from './harnesses/harness'\nimport { findHarnessByBinary, harnesses } from './harnesses/registry'\nimport { runLaunch, type RunnerDeps } from './harnesses/run-launch'\nimport { DEFAULT_MODEL, PREDEFINED_MODELS } from './product/gateway/models/predefined-models'\nimport { createMasker } from './product/secrets/masker'\nimport { PROJECT_BACKUP_DIRECTORY, USER_BACKUP_DIRECTORY } from './product/storage/backups/resolve-backup-root'\nimport {\n KEYCHAIN_DISABLED,\n KEYCHAIN_ENV_VARIABLE,\n KEYCHAIN_INTERACTION_TIMEOUT_MS,\n KEYCHAIN_PROBE_TIMEOUT_MS,\n createKeystore,\n} from './product/storage/keychain/keystore'\nimport { createPlatformContext, type PlatformContext } from './shared/platform/platform-context'\nimport { describeError } from './shared/text/describe-error'\nimport { createTerminalUi, type TerminalUi } from './ui/terminal-ui'\n\nconst NODE_AND_SCRIPT_ARGUMENT_COUNT = 2\n\nconst masker = createMasker({ secrets: [] })\n\nconst keystore = createKeystore({\n importKeyring: () => import('@napi-rs/keyring'),\n platform: process.platform,\n isWsl: () => process.env.WSL_DISTRO_NAME !== undefined || /microsoft/i.test(os.release()),\n hasMacKeychain: () =>\n spawnSync('security', ['default-keychain'], { stdio: 'ignore', timeout: KEYCHAIN_PROBE_TIMEOUT_MS }).status === 0,\n isEnabled: process.env[KEYCHAIN_ENV_VARIABLE] !== KEYCHAIN_DISABLED,\n probeTimeoutMs: KEYCHAIN_PROBE_TIMEOUT_MS,\n interactionTimeoutMs: KEYCHAIN_INTERACTION_TIMEOUT_MS,\n})\n\nconst runnerDeps: RunnerDeps = {\n spawn: (command, commandArguments, options) => crossSpawn(command, commandArguments, options),\n tmpdir: os.tmpdir,\n pid: process.pid,\n uid: process.getuid?.(),\n isAlive: isProcessAlive,\n signals: process,\n stdin: process.stdin,\n env: process.env,\n onError: (message) => console.error(masker.maskText(message)),\n}\n\n/** EPERM means the pid exists but belongs to someone else — alive. */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\nasync function main(): Promise<number> {\n const ui = createTerminalUi({ input: process.stdin, output: process.stdout, onInterrupt: listenForSigint })\n\n try {\n return await runCommand(ui)\n } catch (error) {\n const failure = classifyFailure(error, masker)\n if (failure.kind === 'usage') console.error(pc.red(failure.message))\n if (failure.kind === 'cancelled') ui.cancel('Cancelled.')\n if (failure.kind === 'unexpected') ui.log.error(failure.message)\n return exitCodeForFailure(failure)\n }\n}\n\nfunction listenForSigint(listener: () => void): () => void {\n process.once('SIGINT', listener)\n return () => process.removeListener('SIGINT', listener)\n}\n\nconst HELP = renderHelp({\n harnessIds: harnesses.map((harness) => harness.id),\n launchBinaries: launchableBinaries(),\n predefinedModelIds: PREDEFINED_MODELS.map((model) => model.id),\n defaultModel: DEFAULT_MODEL,\n backupDirectories: {\n user: path.join('~', USER_BACKUP_DIRECTORY),\n project: `.${path.sep}${PROJECT_BACKUP_DIRECTORY}`,\n },\n})\n\nfunction isLaunchingHarness(harness: Harness): harness is LaunchingHarness {\n return harness.kind === 'configurable' && harness.launch !== undefined\n}\n\nfunction launchableBinaries(): string[] {\n return harnesses.filter(isLaunchingHarness).map((harness) => harness.binary)\n}\n\nfunction describeUnknownAgent(binary: string): string {\n const oneOf = `One of: ${launchableBinaries().join(', ')}`\n if (isAgentName(binary)) return `Unknown agent \"${binary}\". ${oneOf}`\n\n return `Unknown agent. ${oneOf}. To pass a key, use --key or set $${KEY_ENV_VARIABLE}.`\n}\n\nconst PackageSchema = v.object({ version: v.string() })\n\nasync function runCommand(ui: TerminalUi): Promise<number> {\n const options = parseCliArguments(process.argv.slice(NODE_AND_SCRIPT_ARGUMENT_COUNT))\n\n if (options.shouldShowHelp) {\n console.log(HELP)\n return EXIT_CODE.ok\n }\n if (options.shouldShowVersion) {\n console.log(v.parse(PackageSchema, createRequire(import.meta.url)('../package.json')).version)\n return EXIT_CODE.ok\n }\n\n if (options.command.kind === 'forget-key') return await forgetKey({ keystore, ui, masker })\n if (options.command.kind === 'launch') return await runLaunchCommand({ command: options.command, options, ui })\n\n const commandParams = {\n options,\n baseContext: createContext(),\n ui,\n now: () => new Date(),\n masker,\n }\n if (options.command.kind === 'restore') return await runRestore(commandParams)\n\n return await runSetup({ ...commandParams, fetch, keystore })\n}\n\nfunction createContext(): PlatformContext {\n return createPlatformContext({\n home: os.homedir(),\n cwd: process.cwd(),\n platform: process.platform,\n env: process.env,\n isInteractive: process.stdin.isTTY === true && process.stdout.isTTY === true,\n })\n}\n\ntype LaunchCommandParams = {\n command: Extract<Command, { kind: 'launch' }>\n options: CliOptions\n ui: TerminalUi\n}\n\nasync function runLaunchCommand({ command, options, ui }: LaunchCommandParams): Promise<AgentExitCode> {\n const { binary, passthrough } = command\n const harness = findHarnessByBinary(binary)\n if (harness === undefined) {\n console.error(pc.red(masker.maskText(describeUnknownAgent(binary))))\n console.error(`\\n${HELP}`)\n return EXIT_CODE.usage\n }\n if (!isLaunchingHarness(harness)) {\n const reason =\n harness.kind === 'unsupported' ? `not configurable — ${harness.reason}` : 'cannot be started this way'\n console.error(pc.red(`${harness.label}: ${reason}`))\n return EXIT_CODE.usage\n }\n\n const ctx = createContext()\n ui.intro(`nexos-connect — starting ${harness.label} through the nexos.ai Gateway`)\n const result = await launch(\n { harness, passthrough, options, env: process.env },\n {\n keystore,\n ui,\n masker,\n ctx,\n fetch,\n runLaunch: (recipe, recipePassthrough) => runLaunch(recipe, recipePassthrough, runnerDeps),\n },\n )\n if ('signal' in result) {\n // Our own handlers are gone by now, so the default action ends this process too.\n process.kill(process.pid, result.signal)\n return EXIT_CODE.failed\n }\n return result.code\n}\n\nfunction finish(exitCode: number): void {\n // A hung keychain call leaves a native thread holding the event loop open; only a forced exit ends it.\n if (keystore.isHung) process.exit(exitCode)\n process.exitCode = exitCode\n}\n\nvoid main()\n .then(finish)\n .catch((error: unknown) => {\n console.error(pc.red(masker.maskText(describeError(error))))\n finish(EXIT_CODE.failed)\n })\n","import { match } from 'ts-pattern'\nimport type { Masker } from '../product/secrets/masker'\nimport { describeError } from '../shared/text/describe-error'\nimport { CancelledError } from '../ui/cancelled-error'\nimport { EXIT_CODE, type ExitCode } from './exit-code'\nimport { UsageError } from './usage-error'\n\nexport type Failure =\n | { kind: 'usage'; message: string }\n | { kind: 'cancelled' }\n | { kind: 'unexpected'; message: string }\n\nconst UNEXPECTED_NEXT_STEP =\n 'Run again with --dry-run to see what would change. If this keeps happening, it is a bug — please report it.'\n\nexport function classifyFailure(error: unknown, masker: Masker): Failure {\n if (error instanceof CancelledError) return { kind: 'cancelled' }\n\n const message = masker.maskText(describeError(error))\n if (error instanceof UsageError) return { kind: 'usage', message }\n\n return { kind: 'unexpected', message: `${message}\\n${UNEXPECTED_NEXT_STEP}` }\n}\n\nexport function exitCodeForFailure(failure: Failure): ExitCode {\n return match(failure.kind)\n .with('usage', () => EXIT_CODE.usage)\n .with('cancelled', () => EXIT_CODE.cancelled)\n .with('unexpected', () => EXIT_CODE.failed)\n .exhaustive()\n}\n","export function describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import * as clack from '@clack/prompts'\n\nexport class CancelledError extends Error {\n constructor() {\n super('cancelled by the user')\n this.name = 'CancelledError'\n }\n}\n\n// Narrowing on clack's cancel symbol leaves the wider `symbol` in the union, hence the cast.\nexport async function throwIfCancelled<T>(pending: Promise<T | symbol>): Promise<Exclude<T, symbol>> {\n const value = await pending\n if (clack.isCancel(value)) throw new CancelledError()\n return value as Exclude<T, symbol>\n}\n","export const EXIT_CODE = { ok: 0, failed: 1, usage: 2, cancelled: 130 } as const\n\nexport type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE]\n\n/** `npx nexos-connect <agent>` passes the started agent's own exit code through unchanged. */\nexport type AgentExitCode = number\n","export class UsageError extends Error {\n override readonly name = 'UsageError'\n}\n","import * as v from 'valibot'\nimport { trimTrailingSlashes } from '../product/gateway/gateway-request'\nimport { normalizeModel } from '../product/gateway/models/predefined-models'\nimport type { EnvironmentVariables } from '../shared/platform/platform-context'\nimport { hasLineBreak } from '../shared/text/has-line-break'\nimport { readNonBlank } from '../shared/text/read-non-blank'\nimport { UsageError } from './usage-error'\n\nexport const KEY_ENV_VARIABLE = 'NEXOS_API_KEY'\nexport const MODEL_ENV_VARIABLE = 'NEXOS_MODEL'\nexport const GATEWAY_ENV_VARIABLE = 'NEXOS_BASE_URL'\n\nexport type EnvironmentInputs = {\n key: string | undefined\n model: string | undefined\n gatewayHost: string | undefined\n}\n\nconst BlankAsAbsentSchema = v.pipe(v.optional(v.string()), v.transform(readNonBlank))\n\nconst ModelSchema = v.pipe(\n BlankAsAbsentSchema,\n v.transform((model) => (model === undefined ? undefined : normalizeModel(model))),\n)\n\nconst EnvironmentSchema = v.object({\n [KEY_ENV_VARIABLE]: BlankAsAbsentSchema,\n [MODEL_ENV_VARIABLE]: ModelSchema,\n [GATEWAY_ENV_VARIABLE]: BlankAsAbsentSchema,\n})\n\nexport function readEnvironmentInputs(env: EnvironmentVariables): EnvironmentInputs {\n const parsed = v.safeParse(EnvironmentSchema, env)\n if (!parsed.success) throw new UsageError(parsed.issues[0].message)\n\n return {\n key: parsed.output[KEY_ENV_VARIABLE],\n model: parsed.output[MODEL_ENV_VARIABLE],\n gatewayHost: parseGatewayHost(parsed.output[GATEWAY_ENV_VARIABLE]),\n }\n}\n\nexport function parseEnvironmentKey(key: string | undefined): string | undefined {\n if (key !== undefined && hasLineBreak(key)) {\n throw new UsageError(`$${KEY_ENV_VARIABLE} contains a line break. Set it on one line, or pass --key.`)\n }\n\n return key\n}\n\nconst UNSET_HINT = 'Unset it to use the nexos.ai gateway.'\n\nconst LOOPBACK_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]']\n\nfunction parseGatewayHost(value: string | undefined): string | undefined {\n if (value === undefined) return undefined\n\n const host = trimTrailingSlashes(value)\n if (!URL.canParse(host)) throw new UsageError(`$${GATEWAY_ENV_VARIABLE} is not a URL. ${UNSET_HINT}`)\n\n const { protocol, hostname } = new URL(host)\n const isEncrypted = protocol === 'https:'\n const isLocalPlainHttp = protocol === 'http:' && LOOPBACK_HOSTNAMES.includes(hostname)\n if (isEncrypted || isLocalPlainHttp) return host\n\n throw new UsageError(`$${GATEWAY_ENV_VARIABLE} must be an https:// URL, or http:// on this machine. ${UNSET_HINT}`)\n}\n","import { match } from 'ts-pattern'\nimport type { Masker } from '../secrets/masker'\nimport { API_KEYS_URL } from './desired-config'\n\nexport type GatewayFailure = GatewayUnreachableError | GatewayTimeoutError\n\nexport type UnreachableReason =\n | {\n kind: 'network'\n causeCode: string | undefined\n causeMessage: string\n }\n | { kind: 'redirect' }\n | { kind: 'invalid-header' }\n\nexport type GatewayUnreachableErrorParams = { endpoint: string; reason: UnreachableReason }\n\nexport class GatewayUnreachableError extends Error {\n readonly kind = 'unreachable'\n readonly endpoint: string\n readonly reason: UnreachableReason\n\n constructor({ endpoint, reason }: GatewayUnreachableErrorParams) {\n super(`Could not reach ${endpoint} (${reason.kind}).`)\n this.name = 'GatewayUnreachableError'\n this.endpoint = endpoint\n this.reason = reason\n }\n}\n\nexport type GatewayTimeoutErrorParams = { endpoint: string; timeoutMs: number }\n\nexport class GatewayTimeoutError extends Error {\n readonly kind = 'timed-out'\n readonly endpoint: string\n readonly timeoutMs: number\n\n constructor({ endpoint, timeoutMs }: GatewayTimeoutErrorParams) {\n super(`No response from ${endpoint} within ${formatSeconds(timeoutMs)}.`)\n this.name = 'GatewayTimeoutError'\n this.endpoint = endpoint\n this.timeoutMs = timeoutMs\n }\n}\n\nexport function isGatewayFailure(error: unknown): error is GatewayFailure {\n return error instanceof GatewayUnreachableError || error instanceof GatewayTimeoutError\n}\n\nconst NETWORK_NEXT_STEP = 'check your network or proxy, or rerun with --no-verify'\n\nexport function describeGatewayFailure(failure: GatewayFailure, masker: Masker): string {\n return match(failure)\n .with({ kind: 'unreachable' }, ({ reason }) => describeUnreachable(reason, masker))\n .with(\n { kind: 'timed-out' },\n ({ timeoutMs }) => `no response within ${formatSeconds(timeoutMs)} — ${NETWORK_NEXT_STEP}`,\n )\n .exhaustive()\n}\n\nconst SNIPPET_MAX_LENGTH = 200\n\n// Masked before truncating: a key cut short no longer matches, and would print in part.\nexport function formatHttpFailure(status: number, explanation: string, masker: Masker): string {\n const snippet = masker.maskText(explanation).replace(/\\s+/g, ' ').trim().slice(0, SNIPPET_MAX_LENGTH)\n return snippet === '' ? `HTTP ${status}` : `HTTP ${status} — ${snippet}`\n}\n\nconst REDIRECT_DESCRIPTION =\n 'the gateway answered with a redirect, which is refused — ' +\n 'check for a proxy or captive portal, or rerun with --no-verify'\nconst INVALID_HEADER_DESCRIPTION = `the key holds a character an HTTP header cannot carry, so it was not sent — copy it again from ${API_KEYS_URL}`\n\nfunction describeUnreachable(reason: UnreachableReason, masker: Masker): string {\n return match(reason)\n .with({ kind: 'network' }, ({ causeCode, causeMessage }) =>\n masker.maskText(`could not connect (${causeCode ?? causeMessage}) — ${NETWORK_NEXT_STEP}`),\n )\n .with({ kind: 'redirect' }, () => REDIRECT_DESCRIPTION)\n .with({ kind: 'invalid-header' }, () => INVALID_HEADER_DESCRIPTION)\n .exhaustive()\n}\n\nconst MS_PER_SECOND = 1_000\n\nfunction formatSeconds(milliseconds: number): string {\n return `${milliseconds / MS_PER_SECOND}s`\n}\n","export type DesiredConfig = {\n anthropicBaseUrl: string\n openaiBaseUrl: string\n apiKey: string\n model: string\n}\n\nexport const GATEWAY_HOST = 'https://api.nexos.ai'\n\nexport const API_KEYS_URL = 'https://workspace.nexos.ai/gateway/api-keys'\n\nexport type GatewayUrls = Pick<DesiredConfig, 'anthropicBaseUrl' | 'openaiBaseUrl'>\n\nconst OPENAI_PATH = '/v1'\n\nexport function buildGatewayUrls(host: string): GatewayUrls {\n return { anthropicBaseUrl: host, openaiBaseUrl: `${host}${OPENAI_PATH}` }\n}\n\nexport type BuildDesiredConfigParams = { gatewayUrls: GatewayUrls; apiKey: string; model: string }\n\nexport function buildDesiredConfig({ gatewayUrls, apiKey, model }: BuildDesiredConfigParams): DesiredConfig {\n return { ...gatewayUrls, apiKey, model }\n}\n","import { GatewayTimeoutError, GatewayUnreachableError, type UnreachableReason } from './gateway-errors'\n\nexport type Fetch = (url: string, init: RequestInit) => Promise<Response>\n\nexport type RequestGatewayParams = {\n url: string\n init: RequestInit\n fetch: Fetch\n timeoutMs: number\n signal?: AbortSignal | undefined\n}\n\nexport type GatewayResponse = { status: number; text: string }\n\nexport const GATEWAY_TIMEOUT_MS = 15_000\n\nexport async function requestGateway(params: RequestGatewayParams): Promise<GatewayResponse> {\n const { url, init } = params\n if (!hasValidHeaders(init.headers)) {\n throw new GatewayUnreachableError({ endpoint: url, reason: { kind: 'invalid-header' } })\n }\n\n const response = await exchangeWithinTimeout(params)\n if (isRedirectStatus(response.status)) {\n throw new GatewayUnreachableError({ endpoint: url, reason: { kind: 'redirect' } })\n }\n\n return response\n}\n\nconst SUCCESS_STATUS_MIN = 200\nconst SUCCESS_STATUS_MAX = 299\n\nexport function isSuccessStatus(status: number): boolean {\n return status >= SUCCESS_STATUS_MIN && status <= SUCCESS_STATUS_MAX\n}\n\n// oxlint-disable-next-line no-magic-numbers -- HTTP statuses, named by the list\nexport const KEY_REJECTED_STATUSES = [401, 403] as const\n\nexport function trimTrailingSlashes(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction hasValidHeaders(headers: RequestInit['headers']): boolean {\n try {\n new Headers(headers)\n return true\n } catch {\n return false\n }\n}\n\nasync function exchangeWithinTimeout({\n url,\n init,\n fetch,\n timeoutMs,\n signal: cancelSignal,\n}: RequestGatewayParams): Promise<GatewayResponse> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = cancelSignal === undefined ? timeoutSignal : AbortSignal.any([cancelSignal, timeoutSignal])\n try {\n return await rejectOnAbort(exchange(url, { ...init, redirect: 'manual', signal }, fetch), signal)\n } catch (error) {\n if (cancelSignal?.aborted === true) throw cancelSignal.reason\n if (timeoutSignal.aborted) throw new GatewayTimeoutError({ endpoint: url, timeoutMs })\n const reason: UnreachableReason = {\n kind: 'network',\n causeCode: findCauseCode(error),\n causeMessage: findDeepestMessage(error),\n }\n throw new GatewayUnreachableError({ endpoint: url, reason })\n }\n}\n\n// oxlint-disable-next-line no-magic-numbers -- HTTP statuses, named by the list\nconst REDIRECT_STATUSES: readonly number[] = [301, 302, 303, 307, 308]\n\nfunction isRedirectStatus(status: number): boolean {\n return REDIRECT_STATUSES.includes(status)\n}\n\nasync function exchange(url: string, init: RequestInit, fetch: Fetch): Promise<GatewayResponse> {\n const response = await fetch(url, init)\n return { status: response.status, text: await response.text() }\n}\n\nasync function rejectOnAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n const aborted = new Promise<never>((_resolve, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true })\n })\n return await Promise.race([work, aborted])\n}\n\nfunction findCauseCode(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined\n if ('code' in error && typeof error.code === 'string') return error.code\n return findCauseCode(error.cause)\n}\n\nfunction findDeepestMessage(error: unknown): string {\n if (!(error instanceof Error)) return String(error)\n if (error.cause instanceof Error) return findDeepestMessage(error.cause)\n return error.message\n}\n","export const PREDEFINED_MODELS = [{ id: 'auto-code', hint: 'nexos.ai router — the default' }] as const\n\nexport const DEFAULT_MODEL: string = PREDEFINED_MODELS[0].id\n\n/** Claude Code's own syntax for the router at 1M context; every other agent would send it verbatim. */\nexport const ONE_MILLION_CONTEXT_ROUTER = `${DEFAULT_MODEL}[1m]`\n\nexport function isPredefinedModel(model: string): boolean {\n return PREDEFINED_MODELS.some((predefined) => predefined.id === model)\n}\n\n// The gateway refuses a router prompt over 1,048,572 tokens; Claude Code's `[1m]` assumes 1,000,000 as well.\nconst ROUTER_CONTEXT_TOKENS = 1_000_000\n\n/** The window to give an agent that cannot know the model's own; undefined for any model but the router. */\nexport function findContextWindow(model: string): number | undefined {\n return model === DEFAULT_MODEL ? ROUTER_CONTEXT_TOKENS : undefined\n}\n\nexport function normalizeModel(model: string): string {\n return model === ONE_MILLION_CONTEXT_ROUTER ? DEFAULT_MODEL : model\n}\n","const LINE_BREAK_PATTERN = /[\\r\\n]/\n\nexport function hasLineBreak(text: string): boolean {\n return LINE_BREAK_PATTERN.test(text)\n}\n","export function readNonBlank(value: string | undefined): string | undefined {\n const trimmed = value?.trim()\n return trimmed === '' ? undefined : trimmed\n}\n","import { API_KEYS_URL } from '../product/gateway/desired-config'\nimport { KEY_ENV_VARIABLE, MODEL_ENV_VARIABLE } from './environment'\nimport { EXIT_CODE } from './exit-code'\n\nexport const COMMAND_NAME = 'nexos-connect'\nexport const RESTORE_COMMAND = 'restore'\nexport const TAGLINE = `${COMMAND_NAME} — point your coding agents at the nexos.ai Gateway`\n\nexport type RenderHelpParams = {\n harnessIds: readonly string[]\n launchBinaries: readonly string[]\n predefinedModelIds: readonly string[]\n defaultModel: string\n backupDirectories: { user: string; project: string }\n}\n\nexport function renderHelp({\n harnessIds,\n launchBinaries,\n predefinedModelIds,\n defaultModel,\n backupDirectories,\n}: RenderHelpParams): string {\n const predefinedModels = predefinedModelIds.join(', ')\n return `${TAGLINE}\n\nUsage\n npx ${COMMAND_NAME} [options] point the agents at the gateway\n npx ${COMMAND_NAME} <agent> [options] [-- <agent arguments>]\n npx ${COMMAND_NAME} forget-key\n npx ${COMMAND_NAME} ${RESTORE_COMMAND} [options] put back what it changed in each agent's config\n\n <agent> starts one agent once, pointed at the gateway, without changing its config.\n One of: ${launchBinaries.join(', ')}.\n\nRuns interactively with no options. Every question has a flag that answers it,\nso the flags exist for scripting and CI as much as for convenience.\n\n${RESTORE_COMMAND} puts every key ${COMMAND_NAME} set back the way it was before the first\nsetup, and keeps everything added since. It takes --harnesses, --scope, --yes,\n--dry-run and --backup-dir; --yes restores every agent it has a record of.\n\nOptions\n --harnesses <ids> Comma-separated agent ids; skips the picker.\n One of: ${harnessIds.join(', ')}\n --key <key> nexos.ai API key. Falls back to $${KEY_ENV_VARIABLE}, then the key saved\n in your system keychain, then a prompt.\n --save-key Save the key in your system keychain for future runs, once it\n passes the key check. A usage error on a machine with no keychain.\n --model <id> Model every agent should use; skips the model picker.\n Falls back to $${MODEL_ENV_VARIABLE}, then the agents' saved default, then\n the picker: ${predefinedModels}, or any id from GET /v1/models.\n --save-model Save the model as the default of each agent it is used for,\n without asking. Never on a dry run.\n --scope <scope> Where to write: user (the default — your home directory,\n applying everywhere) or project (this directory only).\n -y, --yes Answer every question with its default: user scope, the\n detected agents, a key already on this machine, and the\n agents' saved default model, else ${defaultModel}. A gateway that\n rejects the router is a usage error; one that could not\n confirm it only warns. Writes without asking; a failed key\n check warns and continues.\n --dry-run Show the diffs and write nothing.\n --no-verify Skip the gateway entirely (useful offline). The model picker\n then shows no model list; ${predefinedModels} is not offered.\n --backup-dir <path> Where originals are copied, in a <timestamp> folder.\n Default: ${backupDirectories.user} (user scope), ${backupDirectories.project} (project).\n -h, --help Show this help.\n -v, --version Show the version.\n\nStarting an agent takes --key, --model, --save-key, --save-model, --no-verify\nand --yes only. Its model is --model, else $${MODEL_ENV_VARIABLE}, else the agent's saved default, else\nthe picker (--yes: ${defaultModel}).\n\nExit codes\n ${EXIT_CODE.ok} done\n ${EXIT_CODE.failed} an agent failed, while planning or while writing; or an agent could not start\n ${EXIT_CODE.usage} usage error, or a question asked with no terminal to answer it\n ${EXIT_CODE.cancelled} cancelled, by Ctrl-C or by declining a confirmation\n Once an agent has started, its own exit code passes through unchanged.\n\nGet a key at ${API_KEYS_URL}\n`\n}\n","import { parseArgs, type ParseArgsOptionsConfig } from 'node:util'\nimport { match } from 'ts-pattern'\nimport { normalizeModel } from '../product/gateway/models/predefined-models'\nimport { createMasker } from '../product/secrets/masker'\nimport { CONFIG_SCOPES, isConfigScope, type ConfigScope } from '../shared/platform/platform-context'\nimport { describeError } from '../shared/text/describe-error'\nimport { hasLineBreak } from '../shared/text/has-line-break'\nimport { readNonBlank } from '../shared/text/read-non-blank'\nimport { COMMAND_NAME, RESTORE_COMMAND } from './help'\nimport { UsageError } from './usage-error'\n\nexport const FORGET_KEY_COMMAND = 'forget-key'\n\nexport type Command =\n | { kind: 'setup' }\n | { kind: 'restore' }\n | { kind: 'launch'; binary: string; passthrough: string[] }\n | { kind: 'forget-key' }\n\nexport type CliOptions = {\n command: Command\n harnessIds: string[]\n key: string | undefined\n model: string | undefined\n scope: ConfigScope | undefined\n shouldAssumeYes: boolean\n shouldSaveKey: boolean\n shouldSaveModel: boolean\n isDryRun: boolean\n shouldVerify: boolean\n backupDirectory: string | undefined\n shouldShowHelp: boolean\n shouldShowVersion: boolean\n}\n\nexport function parseCliArguments(argv: readonly string[]): CliOptions {\n const { values, tokens } = parseFlags(argv)\n return {\n command: commandFrom(tokens, values),\n harnessIds: parseHarnessIds(values.harnesses),\n key: values.key === undefined ? undefined : parseKeyFlag(values.key),\n model: parseModelFlag(values.model),\n scope: parseScope(values.scope),\n shouldAssumeYes: values.yes === true,\n shouldSaveKey: values['save-key'] === true,\n shouldSaveModel: values['save-model'] === true,\n isDryRun: values['dry-run'] === true,\n shouldVerify: values['no-verify'] !== true,\n backupDirectory: readNonBlank(values['backup-dir']),\n shouldShowHelp: values.help === true,\n shouldShowVersion: values.version === true,\n }\n}\n\nconst FLAGS = {\n harnesses: { type: 'string' },\n key: { type: 'string' },\n model: { type: 'string' },\n scope: { type: 'string' },\n yes: { type: 'boolean', short: 'y' },\n 'save-key': { type: 'boolean' },\n 'save-model': { type: 'boolean' },\n 'dry-run': { type: 'boolean' },\n 'no-verify': { type: 'boolean' },\n 'backup-dir': { type: 'string' },\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n} as const satisfies ParseArgsOptionsConfig\n\ntype ArgumentToken = { kind: string; value?: string | undefined }\n\nfunction parseFlags(argv: readonly string[]) {\n try {\n return parseArgs({ args: [...argv], options: FLAGS, allowPositionals: true, tokens: true, strict: true })\n } catch (error) {\n throw new UsageError(describeParseError(error, argv))\n }\n}\n\n/** True when an agent was named before `--`, so an unknown option is likely its own argument. */\nfunction hasNamedAgent(argv: readonly string[]): boolean {\n for (const argument of argv) {\n if (argument === '--') return false\n if (!argument.startsWith('-') && isAgentName(argument)) return true\n }\n return false\n}\n\ntype FlagValues = ReturnType<typeof parseFlags>['values']\n\nconst HELP_HINT = `Run npx ${COMMAND_NAME} --help to see the options.`\n\nfunction describeParseError(error: unknown, argv: readonly string[]): string {\n const message = describeError(error)\n const code = error instanceof Error && 'code' in error ? error.code : undefined\n return match(code)\n .with('ERR_PARSE_ARGS_UNKNOWN_OPTION', () => describeUnknownOption(message, argv))\n .otherwise(() => createMasker({ secrets: [] }).maskText(message))\n}\n\nconst QUOTED_PATTERN = /'([^']*)'/\nconst OPTION_NAME_PATTERN = /^--?[a-z][a-z-]{0,29}$/\n\nfunction describeUnknownOption(message: string, argv: readonly string[]): string {\n const option = QUOTED_PATTERN.exec(message)?.[1]\n if (option === undefined || !OPTION_NAME_PATTERN.test(option)) return `Unknown option. ${HELP_HINT}`\n\n const hint = hasNamedAgent(argv) ? ' If it belongs to the agent, put it after --.' : ''\n return `Unknown option ${option}. ${HELP_HINT}${hint}`\n}\n\nconst PASSTHROUGH_MISUSE = `\\`--\\` passes arguments to an agent, e.g. npx ${COMMAND_NAME} claude -- --resume`\n\nconst AGENT_NAME_PATTERN = /^[a-z][a-z-]{0,29}$/\n\n/** A positional is only ever echoed when it can be an agent name, never when it may be a pasted key. */\nexport function isAgentName(value: string): boolean {\n return AGENT_NAME_PATTERN.test(value)\n}\n\ntype CommandParts = { name: string | undefined; passthrough: string[] | null; values: FlagValues }\ntype LaunchParts = { name: string; passthrough: string[] | null; values: FlagValues }\n\nfunction commandFrom(tokens: readonly ArgumentToken[], values: FlagValues): Command {\n const terminatorIndex = tokens.findIndex((token) => token.kind === 'option-terminator')\n const before = terminatorIndex === -1 ? tokens : tokens.slice(0, terminatorIndex)\n const passthrough =\n terminatorIndex === -1 ? null : tokens.slice(terminatorIndex + 1).map((token) => token.value ?? '')\n\n const positionals = before.flatMap((token) => (token.kind === 'positional' ? [token.value ?? ''] : []))\n if (positionals.length > 1) throw new UsageError(describeExtraCommands(positionals))\n\n const [name] = positionals\n if (name === undefined || name === FORGET_KEY_COMMAND) return commandWithoutAgent({ name, passthrough, values })\n if (name === RESTORE_COMMAND) return restoreCommand({ name, passthrough, values })\n\n return launchCommand({ name, passthrough, values })\n}\n\nfunction describeExtraCommands(positionals: readonly string[]): string {\n const hint = \"Put the agent's own arguments after --, and a key with --key.\"\n if (positionals.every(isAgentName)) return `Expected one command, got: ${positionals.join(' ')}. ${hint}`\n\n return `Expected one command, got more than one argument. ${hint}`\n}\n\nfunction commandWithoutAgent({ name, passthrough, values }: CommandParts): Command {\n if (passthrough !== null) throw new UsageError(PASSTHROUGH_MISUSE)\n if (name === undefined) return { kind: 'setup' }\n\n const flags = Object.keys(values).filter((flag) => flag !== 'help' && flag !== 'version')\n if (flags.length > 0) throw new UsageError(`${FORGET_KEY_COMMAND} takes no options (got --${flags[0]}).`)\n return { kind: 'forget-key' }\n}\n\nfunction restoreCommand({ passthrough, values }: CommandParts): Command {\n if (passthrough !== null) throw new UsageError(PASSTHROUGH_MISUSE)\n assertRestoreFlags(values)\n return { kind: 'restore' }\n}\n\nconst LAUNCH_UNSUPPORTED_FLAGS = ['harnesses', 'scope', 'dry-run', 'backup-dir'] as const\n\nfunction launchCommand({ name, passthrough, values }: LaunchParts): Command {\n const unsupported = LAUNCH_UNSUPPORTED_FLAGS.filter((flag) => flag in values)\n if (unsupported.length > 0) {\n const shown = isAgentName(name) ? name : '<agent>'\n throw new UsageError(\n `--${unsupported[0]} is for setup only. npx ${COMMAND_NAME} ${shown} takes --key, --model, --save-key, --save-model, --no-verify and --yes.`,\n )\n }\n return { kind: 'launch', binary: name, passthrough: passthrough ?? [] }\n}\n\nconst RESTORE_UNSUPPORTED_FLAGS = ['key', 'model', 'save-model', 'no-verify'] as const\n\nfunction assertRestoreFlags(flags: FlagValues): void {\n const unsupported = RESTORE_UNSUPPORTED_FLAGS.find((name) => flags[name] !== undefined)\n if (unsupported !== undefined) throw new UsageError(`--${unsupported} does not apply to ${RESTORE_COMMAND}.`)\n}\n\nconst HARNESS_ID_SEPARATOR = ','\n\nfunction parseHarnessIds(value: string | undefined): string[] {\n if (value === undefined) return []\n\n const ids = value.split(HARNESS_ID_SEPARATOR).flatMap((id) => readNonBlank(id) ?? [])\n return [...new Set(ids)]\n}\n\nfunction parseKeyFlag(value: string): string {\n const key = readNonBlank(value)\n if (key === undefined) throw new UsageError('--key is empty. Pass a key, or drop --key to be prompted.')\n if (hasLineBreak(key)) throw new UsageError('--key contains a line break. Paste the key on one line.')\n\n return key\n}\n\nfunction parseModelFlag(value: string | undefined): string | undefined {\n const model = readNonBlank(value)\n return model === undefined ? undefined : normalizeModel(model)\n}\n\nfunction parseScope(value: string | undefined): ConfigScope | undefined {\n const scope = readNonBlank(value)\n if (scope === undefined) return undefined\n if (!isConfigScope(scope)) throw new UsageError(`--scope must be one of: ${CONFIG_SCOPES.join(', ')}`)\n\n return scope\n}\n","export function escapePosixSingleQuoted(value: string): string {\n return value.replace(/'/g, `'\\\\''`)\n}\n","// PowerShell also ends a single-quoted string at any of the typographic single quotes.\nexport const POWERSHELL_SINGLE_QUOTES = \"'‘’‚‛\"\n\nconst POWERSHELL_SINGLE_QUOTE = new RegExp(`[${POWERSHELL_SINGLE_QUOTES}]`, 'g')\n\nexport function escapePowerShellSingleQuoted(value: string): string {\n return value.replace(POWERSHELL_SINGLE_QUOTE, (quote) => quote + quote)\n}\n","export const KEY_PREFIXES = ['nexos-', 'user-'] as const\n\nexport type KeyPrefix = (typeof KEY_PREFIXES)[number]\n\nexport function findKeyPrefix(key: string): KeyPrefix | undefined {\n return KEY_PREFIXES.find((prefix) => key.startsWith(prefix))\n}\n\nexport function hasKnownKeyPrefix(key: string): boolean {\n return findKeyPrefix(key) !== undefined\n}\n","import { escapePosixSingleQuoted } from '../../shared/file-formats/shell/escape-posix-single-quoted'\nimport { escapePowerShellSingleQuoted } from '../../shared/file-formats/shell/escape-powershell-single-quoted'\nimport { KEY_PREFIXES, findKeyPrefix } from './key-prefix'\n\nexport interface Masker {\n maskText(text: string): string\n registerSecrets(secrets: readonly string[]): void\n}\n\nexport type CreateMaskerParams = { secrets: readonly string[] }\n\nconst MIN_SHAPE_BODY_LENGTH = 16\nconst KEY_PREFIX_ALTERNATIVES = KEY_PREFIXES.map(escapeForRegex).join('|')\nconst KEY_SHAPE_PATTERN = new RegExp(\n `(?<![/\\\\w])(?:${KEY_PREFIX_ALTERNATIVES})[A-Za-z0-9_-]{${MIN_SHAPE_BODY_LENGTH},}(?![/\\\\w])`,\n 'g',\n)\n\nexport function createMasker({ secrets }: CreateMaskerParams): Masker {\n const registeredSecrets = [...secrets]\n let findIdentitySpans = buildIdentityMatching(registeredSecrets)\n\n return {\n maskText: (text) => replaceSpans(text, pickOuterSpans([...findIdentitySpans(text), ...findShapeSpans(text)])),\n registerSecrets: (newSecrets) => {\n registeredSecrets.push(...newSecrets)\n findIdentitySpans = buildIdentityMatching(registeredSecrets)\n },\n }\n}\n\ntype MaskSpan = { start: number; end: number; mask: string }\n\nfunction buildIdentityMatching(secrets: readonly string[]): (text: string) => MaskSpan[] {\n const masksByForm = new Map<string, string>()\n for (const secret of secrets.filter((secret) => secret.trim() !== '')) {\n const mask = maskKey(secret)\n for (const form of listEscapedForms(secret)) {\n if (!masksByForm.has(form)) masksByForm.set(form, mask)\n }\n }\n if (masksByForm.size === 0) return () => []\n\n const alternatives = [...masksByForm.keys()].sort((first, second) => second.length - first.length)\n const pattern = new RegExp(alternatives.map(buildFormPattern).join('|'), 'g')\n return (text) => [...text.matchAll(pattern)].map((match) => toSpan(match, masksByForm.get(match[0]) ?? match[0]))\n}\n\nfunction findShapeSpans(text: string): MaskSpan[] {\n return [...text.matchAll(KEY_SHAPE_PATTERN)].map((match) => toSpan(match, maskKey(match[0])))\n}\n\nfunction toSpan(match: RegExpExecArray, mask: string): MaskSpan {\n return { start: match.index, end: match.index + match[0].length, mask }\n}\n\n// Leftmost, then longest: a key wins over a registered secret inside it, and a registered key over\n// the part of it that its shape alone matches.\nfunction pickOuterSpans(spans: readonly MaskSpan[]): MaskSpan[] {\n const picked: MaskSpan[] = []\n for (const span of [...spans].sort((first, second) => first.start - second.start || second.end - first.end)) {\n if (span.start >= (picked.at(-1)?.end ?? 0)) picked.push(span)\n }\n return picked\n}\n\nfunction replaceSpans(text: string, spans: readonly MaskSpan[]): string {\n const ends = [0, ...spans.map((span) => span.end)]\n const pieces = spans.map((span, index) => text.slice(ends[index], span.start) + span.mask)\n return pieces.join('') + text.slice(ends.at(-1))\n}\n\nconst MIN_SUBSTRING_FORM_LENGTH = 16\nconst TOKEN_CHARACTER = '[A-Za-z0-9_-]'\n\nfunction buildFormPattern(form: string): string {\n const escaped = escapeForRegex(form)\n if (form.length >= MIN_SUBSTRING_FORM_LENGTH) return escaped\n\n return `(?<!${TOKEN_CHARACTER})${escaped}(?!${TOKEN_CHARACTER})`\n}\n\nconst MIN_BODY_LENGTH_FOR_HINT = 32\nconst HINT_HEAD_LENGTH = 4\nconst HINT_TAIL_LENGTH = 4\n\nfunction maskKey(key: string): string {\n const prefix = findKeyPrefix(key) ?? ''\n const body = key.slice(prefix.length)\n if (body.length < MIN_BODY_LENGTH_FOR_HINT) return `${prefix}…`\n\n return `${prefix}${body.slice(0, HINT_HEAD_LENGTH)}…${body.slice(-HINT_TAIL_LENGTH)}`\n}\n\nfunction listEscapedForms(secret: string): string[] {\n const json = JSON.stringify(secret).slice(1, -1)\n const forms = [\n secret,\n json,\n escapePosixSingleQuoted(secret),\n escapePowerShellSingleQuoted(secret),\n encodeURIComponent(secret),\n ]\n return [...new Set(forms)]\n}\n\nfunction escapeForRegex(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport { isFile } from '../file-system/is-file'\nimport type { EnvironmentVariables } from './platform-context'\n\nexport function hasBinary(name: string, env: EnvironmentVariables, platform: NodeJS.Platform): boolean {\n const lookup = resolvePathLookup(platform, env)\n const directories = (env.PATH ?? '')\n .split(lookup.delimiter)\n .map(lookup.normalizeEntry)\n .filter((directory) => directory !== '')\n\n const candidates = directories.flatMap((directory) =>\n lookup.executableExtensions.map((extension) => path.join(directory, name + extension)),\n )\n return candidates.some(isSearchableFile)\n}\n\ntype PathLookup = {\n delimiter: string\n executableExtensions: string[]\n normalizeEntry: (entry: string) => string\n}\n\nconst WINDOWS_PATH_DELIMITER = ';'\nconst POSIX_PATH_DELIMITER = ':'\nconst WINDOWS_DEFAULT_PATHEXT = '.EXE;.CMD;.BAT'\nconst WINDOWS_PATHEXT_DELIMITER = ';'\nconst QUOTE = '\"'\n\n// Not `path.delimiter`: that follows the host, so a win32 lookup on POSIX would split on colons.\nfunction resolvePathLookup(platform: NodeJS.Platform, env: EnvironmentVariables): PathLookup {\n return match(platform)\n .with('win32', () => ({\n delimiter: WINDOWS_PATH_DELIMITER,\n executableExtensions: (env.PATHEXT ?? WINDOWS_DEFAULT_PATHEXT)\n .split(WINDOWS_PATHEXT_DELIMITER)\n .filter((extension) => extension !== ''),\n normalizeEntry: (entry: string) => entry.replaceAll(QUOTE, ''),\n }))\n .otherwise(() => ({\n delimiter: POSIX_PATH_DELIMITER,\n executableExtensions: [''],\n normalizeEntry: (entry: string) => entry,\n }))\n}\n\nfunction isSearchableFile(candidate: string): boolean {\n try {\n return isFile(candidate)\n } catch {\n return false\n }\n}\n","import fs from 'node:fs'\nimport { isMissingFileError } from './is-missing-file-error'\n\nexport function isFile(filePath: string): boolean {\n try {\n return fs.statSync(filePath).isFile()\n } catch (error) {\n if (isMissingFileError(error)) return false\n throw error\n }\n}\n","const MISSING_FILE_CODES: readonly unknown[] = ['ENOENT', 'ENOTDIR']\n\nexport function isMissingFileError(error: unknown): boolean {\n return error instanceof Error && 'code' in error && MISSING_FILE_CODES.includes(error.code)\n}\n","import { hasBinary } from './has-binary'\n\nexport const CONFIG_SCOPES = ['user', 'project'] as const\n\nexport type ConfigScope = (typeof CONFIG_SCOPES)[number]\n\nexport const DEFAULT_SCOPE: ConfigScope = 'user'\n\nexport function isConfigScope(value: string): value is ConfigScope {\n return CONFIG_SCOPES.some((scope) => scope === value)\n}\n\nexport type EnvironmentVariables = Readonly<Record<string, string | undefined>>\n\nexport interface PlatformContext {\n home: string\n cwd: string\n platform: NodeJS.Platform\n env: EnvironmentVariables\n isInteractive: boolean\n scope: ConfigScope\n hasBinary(name: string): boolean\n}\n\nexport type CreatePlatformContextParams = Omit<PlatformContext, 'scope' | 'hasBinary'>\n\nexport function createPlatformContext(params: CreatePlatformContextParams): PlatformContext {\n return {\n ...params,\n scope: DEFAULT_SCOPE,\n hasBinary: (name) => hasBinary(name, params.env, params.platform),\n }\n}\n","import { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { Keystore } from '../../product/storage/keychain/keystore'\nimport { describeError } from '../../shared/text/describe-error'\nimport type { TerminalUi } from '../../ui/terminal-ui'\n\nexport type ForgetKeyParams = { keystore: Keystore; ui: Pick<TerminalUi, 'log'>; masker: Masker }\n\nexport async function forgetKey({ keystore, ui, masker }: ForgetKeyParams): Promise<ExitCode> {\n const availability = await keystore.availability()\n if (availability.kind === 'unavailable') {\n if (availability.hasPossibleEntry) {\n ui.log.error(`${availability.reason} — the saved key, if any, was not removed.`)\n return EXIT_CODE.failed\n }\n ui.log.info(`${availability.reason} — nothing to forget.`)\n return EXIT_CODE.ok\n }\n try {\n ui.log.success((await keystore.clear()) ? 'Forgot the saved key.' : 'No saved key to forget.')\n return EXIT_CODE.ok\n } catch (error) {\n // The saved key is never loaded here, so only masking by shape applies.\n ui.log.error(\n masker.maskText(\n `Could not remove the saved key: ${describeError(error)}. ` +\n 'Remove the \"nexos-connect\" item from your system keychain by hand.',\n ),\n )\n return EXIT_CODE.failed\n }\n}\n","import type { TerminalUi } from '../ui/terminal-ui'\nimport { KEY_ENV_VARIABLE } from './environment'\nimport { UsageError } from './usage-error'\n\ntype Refusal = { question: string; answers: string }\n\nconst MODEL_REFUSAL: Refusal = { question: 'which model to use', answers: '--model' }\nconst KEY_REFUSAL: Refusal = { question: 'for the key', answers: `--key, or set $${KEY_ENV_VARIABLE}` }\n\nexport function refusePrompts(ui: TerminalUi): TerminalUi {\n return {\n ...ui,\n selectScope: refuse({ question: 'where to write', answers: '--scope, or --yes for user level' }),\n selectHarnesses: refuse({\n question: 'which agents to configure',\n answers: '--harnesses, or --yes for the detected agents',\n }),\n askForKey: refuse(KEY_REFUSAL),\n askToKeepOrReplaceKey: refuse({\n question: 'whether to keep the key found on this machine',\n answers: '--yes to keep it, or --key',\n }),\n askForNewKey: refuse(KEY_REFUSAL),\n chooseSavedKey: refuse({ question: 'which key to use', answers: `--key, or set $${KEY_ENV_VARIABLE}` }),\n chooseOnSavedKeyRejected: refuse({ question: 'what to do about the rejected saved key', answers: '--key' }),\n confirm: refuse({ question: 'for confirmation', answers: '--yes' }),\n chooseSavedModel: refuse({\n question: 'which saved model to use',\n answers: '--model, or --yes for the saved default',\n }),\n selectModel: refuse(MODEL_REFUSAL),\n askForModelId: refuse(MODEL_REFUSAL),\n chooseOnFetchFailure: refuse({\n question: 'what to do after the failed check',\n answers: '--model, or --yes to continue',\n }),\n selectRestoreScope: refuse({ question: 'which configs to restore', answers: '--scope, or --yes for user level' }),\n selectRestoreHarnesses: refuse({\n question: 'which agents to restore',\n answers: '--harnesses, or --yes for every agent it has a record of',\n }),\n }\n}\n\nfunction refuse({ question, answers }: Refusal): () => Promise<never> {\n return async () => {\n throw new UsageError(`Cannot ask ${question} without a terminal. Pass ${answers}.`)\n }\n}\n","import * as v from 'valibot'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport { harnesses } from '../../harnesses/registry'\nimport { parseEnvFile } from '../../product/storage/env-file/parse-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport { readFileIfExists } from '../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { hasLineBreak } from '../../shared/text/has-line-break'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\n\nexport type FindExistingKeysParams = { ctx: PlatformContext; envPath: string; shell: Shell }\n\nconst OfferableKeySchema = v.pipe(\n v.string(),\n v.check((key) => !hasLineBreak(key)),\n)\n\nexport type ExistingKeys = { offered: string | undefined; all: string[] }\n\nexport function findExistingKeys({ ctx, envPath, shell }: FindExistingKeysParams): ExistingKeys {\n const userContext: PlatformContext = { ...ctx, scope: 'user' }\n const projectContext: PlatformContext = { ...ctx, scope: 'project' }\n const machineKeys = [...readEnvFileKeys(envPath, shell), ...readHarnessKeys(userContext)]\n const otherSecrets = [\n ...readHarnessKeys(projectContext),\n ...readFromEachHarness((harness) => harness.readSecrets?.(userContext) ?? []),\n ...readFromEachHarness((harness) => harness.readSecrets?.(projectContext) ?? []),\n ]\n const offered = machineKeys.find((key) => v.is(OfferableKeySchema, key))\n return { offered, all: [...machineKeys, ...otherSecrets] }\n}\n\nfunction readEnvFileKeys(envPath: string, shell: Shell): string[] {\n const envText = readSafely(() => readFileIfExists(envPath)) ?? null\n if (envText === null) return []\n\n const variables = parseEnvFile(envText, shell)\n return listKeyEnvVariables().flatMap((name) => readNonBlank(variables.get(name)) ?? [])\n}\n\nfunction listKeyEnvVariables(): string[] {\n const names = harnesses.flatMap((harness) =>\n harness.kind === 'configurable' && harness.keyEnvVariable !== undefined ? [harness.keyEnvVariable] : [],\n )\n return [...new Set(names)]\n}\n\nfunction readHarnessKeys(ctx: PlatformContext): string[] {\n return readFromEachHarness((harness) => {\n const key = readNonBlank(harness.readKey?.(ctx))\n return key === undefined ? [] : [key]\n })\n}\n\nfunction readFromEachHarness(read: (harness: ConfigurableHarness) => readonly string[]): string[] {\n return harnesses.flatMap((harness) =>\n harness.kind === 'configurable' ? (readSafely(() => read(harness)) ?? []) : [],\n )\n}\n\nfunction readSafely<T>(read: () => T): T | undefined {\n try {\n return read()\n } catch {\n return undefined\n }\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport * as v from 'valibot'\nimport { GATEWAY_HOST, type DesiredConfig } from '../../product/gateway/desired-config'\nimport { DEFAULT_MODEL, ONE_MILLION_CONTEXT_ROUTER } from '../../product/gateway/models/predefined-models'\nimport type { KeyPathUpdate } from '../../shared/file-formats/key-path'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { FileContribution, LaunchingHarness } from '../harness'\nimport { readJsoncFile } from '../read-jsonc-file'\n\nconst BINARY = 'claude'\n\nexport const claudeCode: LaunchingHarness = {\n kind: 'configurable',\n id: 'claude-code',\n label: 'Claude Code',\n binary: BINARY,\n protocols: ['anthropic'],\n projectSupport: { kind: 'supported' },\n detect: (ctx) => detectConfigFile(listSettingsCandidates(ctx), ctx.home),\n configPath: (ctx) => resolveSettingsPath(ctx),\n plan: (desired, ctx) => [planSettings(desired, ctx)],\n launch: (desired) => ({\n binary: BINARY,\n arguments: ['--settings', SETTINGS_PLACEHOLDER],\n env: {},\n files: [\n {\n name: SHARED_SETTINGS_FILE,\n content: `${JSON.stringify({ [ENV_BLOCK]: launchEnv(desired) }, null, JSON_INDENT)}\\n`,\n placeholder: SETTINGS_PLACEHOLDER,\n },\n ],\n }),\n launchNotes: [\n 'Running /model saves that model to your Claude Code settings.',\n 'This session is kept in your history like any other.',\n ],\n readKey: (ctx) => readGatewayToken(ctx),\n readSecrets: (ctx) => readCredentials(ctx),\n warnings: (ctx) => warnAboutApiKey(ctx),\n postSetupNotes: [\n 'Restart Claude Code after setup: it reads its settings only when it starts.',\n \"Claude Code ranks its settings, highest first: managed settings, --settings, the project's \" +\n \"settings.local.json, the project's settings.json, then the user's settings.json. A higher one that sets \" +\n 'the same values overrides this file.',\n ],\n}\n\nconst CONFIG_DIRECTORY = '.claude'\nconst SHARED_SETTINGS_FILE = 'settings.json'\nconst LOCAL_SETTINGS_FILE = 'settings.local.json'\nconst SETTINGS_PLACEHOLDER = '{settings}'\nconst JSON_INDENT = 2\n\nfunction resolveSettingsPath(ctx: PlatformContext): string {\n return match(ctx.scope)\n .with('user', () => path.join(ctx.home, CONFIG_DIRECTORY, SHARED_SETTINGS_FILE))\n .with('project', () => path.join(ctx.cwd, CONFIG_DIRECTORY, LOCAL_SETTINGS_FILE))\n .exhaustive()\n}\n\nfunction listSettingsCandidates(ctx: PlatformContext): string[] {\n return match(ctx.scope)\n .with('user', () => [resolveSettingsPath(ctx)])\n .with('project', () => [resolveSettingsPath(ctx), path.join(ctx.cwd, CONFIG_DIRECTORY, SHARED_SETTINGS_FILE)])\n .exhaustive()\n}\n\nconst ENV_BLOCK = 'env'\nconst BASE_URL_VARIABLE = 'ANTHROPIC_BASE_URL'\nconst AUTH_TOKEN_VARIABLE = 'ANTHROPIC_AUTH_TOKEN'\nconst MODEL_VARIABLE = 'ANTHROPIC_MODEL'\nconst API_KEY_VARIABLE = 'ANTHROPIC_API_KEY'\nconst MODEL_SETTING = 'model'\n\n// Claude Code picks these by itself, for subagents, skills and background calls, so each names the chosen model too.\nconst MODEL_ALIAS_VARIABLES = [\n 'ANTHROPIC_DEFAULT_OPUS_MODEL',\n 'ANTHROPIC_DEFAULT_SONNET_MODEL',\n 'ANTHROPIC_DEFAULT_HAIKU_MODEL',\n 'ANTHROPIC_DEFAULT_FABLE_MODEL',\n 'CLAUDE_CODE_SUBAGENT_MODEL',\n]\n// Turns off the telemetry, error reports and auto-updates that go to Anthropic rather than the gateway, and labels\n// each request (main turn, subagent, compaction) for the router.\nconst RECOMMENDED_ENV: Readonly<Record<string, string>> = {\n CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',\n DISABLE_TELEMETRY: '1',\n DISABLE_ERROR_REPORTING: '1',\n CLAUDE_CODE_GATEWAY_HINT_HEADERS: '1',\n}\n\nfunction gatewayEnv(desired: DesiredConfig): Record<string, string> {\n const model = toClaudeCodeModel(desired.model)\n return {\n [BASE_URL_VARIABLE]: desired.anthropicBaseUrl,\n [AUTH_TOKEN_VARIABLE]: desired.apiKey,\n ...Object.fromEntries(MODEL_ALIAS_VARIABLES.map((name) => [name, model])),\n ...RECOMMENDED_ENV,\n }\n}\n\n// ANTHROPIC_MODEL outranks every model setting, so this run starts on the model chosen for it.\nfunction launchEnv(desired: DesiredConfig): Record<string, string> {\n return { ...gatewayEnv(desired), [MODEL_VARIABLE]: toClaudeCodeModel(desired.model) }\n}\n\n// Without the suffix Claude Code assumes a 200k window for a model it does not know, and compacts there.\nfunction toClaudeCodeModel(model: string): string {\n return model === DEFAULT_MODEL ? ONE_MILLION_CONTEXT_ROUTER : model\n}\n\nfunction planSettings(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n const envUpdates = Object.entries(gatewayEnv(desired)).map(([name, value]): KeyPathUpdate => [\n [ENV_BLOCK, name],\n value,\n ])\n return {\n kind: 'file',\n path: resolveSettingsPath(ctx),\n hasSecret: true,\n edits: () => ({\n format: 'jsonc',\n updates: [\n // /model saves to the model setting, which ANTHROPIC_MODEL would override at every start.\n [[ENV_BLOCK, MODEL_VARIABLE], undefined],\n ...envUpdates,\n [[MODEL_SETTING], toClaudeCodeModel(desired.model)],\n ],\n }),\n }\n}\n\nfunction readGatewayToken(ctx: PlatformContext): string | undefined {\n const env = readSettingsEnv(ctx)\n if (!isGatewayUrl(env?.[BASE_URL_VARIABLE])) return undefined\n\n return env?.[AUTH_TOKEN_VARIABLE]\n}\n\nfunction readCredentials(ctx: PlatformContext): string[] {\n const env = readSettingsEnv(ctx)\n return [env?.[AUTH_TOKEN_VARIABLE], env?.[API_KEY_VARIABLE]].flatMap((value) => readNonBlank(value) ?? [])\n}\n\nfunction warnAboutApiKey(ctx: PlatformContext): string[] {\n if ((readSettingsEnv(ctx)?.[API_KEY_VARIABLE] ?? '') === '') return []\n\n const settingsPath = displayPath(resolveSettingsPath(ctx), ctx.home)\n return [\n `${settingsPath} also sets ${ENV_BLOCK}.${API_KEY_VARIABLE}, which can conflict with ${AUTH_TOKEN_VARIABLE}. ` +\n 'Consider removing it.',\n ]\n}\n\nconst OptionalTextSchema = v.fallback(v.optional(v.string()), undefined)\n\nconst SettingsSchema = v.looseObject({\n [ENV_BLOCK]: v.fallback(\n v.optional(\n v.looseObject({\n [BASE_URL_VARIABLE]: OptionalTextSchema,\n [AUTH_TOKEN_VARIABLE]: OptionalTextSchema,\n [API_KEY_VARIABLE]: OptionalTextSchema,\n }),\n ),\n undefined,\n ),\n})\n\ntype SettingsEnv = NonNullable<v.InferOutput<typeof SettingsSchema>[typeof ENV_BLOCK]>\n\nfunction readSettingsEnv(ctx: PlatformContext): SettingsEnv | undefined {\n const settings = readJsoncFile(resolveSettingsPath(ctx), SettingsSchema)\n return settings.kind === 'valid' ? settings.value[ENV_BLOCK] : undefined\n}\n\nconst GATEWAY_HOSTNAME = new URL(GATEWAY_HOST).hostname\n\nfunction isGatewayUrl(url: string | undefined): boolean {\n return url !== undefined && URL.canParse(url) && new URL(url).hostname === GATEWAY_HOSTNAME\n}\n","import path from 'node:path'\n\nconst HOME_SHORTHAND = '~'\n\nexport function displayPath(filePath: string, home: string): string {\n if (home === '' || !filePath.startsWith(home + path.sep)) return filePath\n\n return HOME_SHORTHAND + filePath.slice(home.length)\n}\n\nconst CURRENT_DIRECTORY = '.'\n\nexport function displayRelativePath(filePath: string, directory: string): string {\n return CURRENT_DIRECTORY + path.sep + path.relative(directory, filePath)\n}\n","import { isFile } from './is-file'\n\nexport function findFirstExistingFile(candidates: readonly string[]): string | null {\n return candidates.find((candidate) => isFile(candidate)) ?? null\n}\n","import { findFirstExistingFile } from '../shared/file-system/find-first-existing-file'\nimport { displayPath } from '../shared/text/display-path'\nimport type { DetectResult } from './harness'\n\nexport function detectConfigFile(candidates: readonly string[], home: string): DetectResult {\n const existing = findFirstExistingFile(candidates)\n if (existing === null) {\n const missing = candidates.map((candidate) => displayPath(candidate, home))\n return { isFound: false, detail: `no ${missing.join(' or ')}` }\n }\n\n return { isFound: true, detail: displayPath(existing, home) }\n}\n","import * as v from 'valibot'\nimport { ConfigFormatError } from '../shared/file-formats/config-errors'\nimport { parseJsonc } from '../shared/file-formats/jsonc'\nimport { readFileIfExists } from '../shared/file-system/read-file-if-exists'\n\nexport type JsoncConfig<T> = { kind: 'absent' } | { kind: 'invalid' } | { kind: 'valid'; value: T }\n\nexport function readJsoncFile<TSchema extends v.GenericSchema>(\n filePath: string,\n schema: TSchema,\n): JsoncConfig<v.InferOutput<TSchema>> {\n return parseJsoncConfig(readFileIfExists(filePath), schema)\n}\n\nexport function parseJsoncConfig<TSchema extends v.GenericSchema>(\n text: string | null,\n schema: TSchema,\n): JsoncConfig<v.InferOutput<TSchema>> {\n if (text === null) return { kind: 'absent' }\n\n try {\n const parsed = v.safeParse(schema, parseJsonc(text))\n return parsed.success ? { kind: 'valid', value: parsed.output } : { kind: 'invalid' }\n } catch (error) {\n if (error instanceof ConfigFormatError) return { kind: 'invalid' }\n throw error\n }\n}\n","export abstract class ConfigFormatError extends Error {}\n\nexport type ConfigSyntaxErrorParams = { line: number; column: number; reason: string }\n\nexport class ConfigSyntaxError extends ConfigFormatError {\n readonly line: number\n readonly column: number\n readonly reason: string\n\n constructor({ line, column, reason }: ConfigSyntaxErrorParams) {\n super(`invalid syntax at line ${line}, column ${column} (${reason}). Fix it, then run again.`)\n this.name = 'ConfigSyntaxError'\n this.line = line\n this.column = column\n this.reason = reason\n }\n}\n\nconst FOUND_TYPE_LABELS = {\n null: 'null',\n array: 'an array',\n date: 'a date',\n string: 'a string',\n number: 'a number',\n boolean: 'a boolean',\n other: 'an unsupported value',\n} as const\n\nexport type FoundType = keyof typeof FOUND_TYPE_LABELS\n\nexport type UnmergeableValueErrorParams = { keyPath: readonly string[]; foundType: FoundType }\n\nexport class UnmergeableValueError extends ConfigFormatError {\n readonly keyPath: readonly string[]\n readonly foundType: FoundType\n\n constructor({ keyPath, foundType }: UnmergeableValueErrorParams) {\n const location = describeLocation(keyPath)\n super(\n `cannot merge into ${location}: it is ${FOUND_TYPE_LABELS[foundType]}, not an object. ` +\n 'Make it an object or remove it, then run again.',\n )\n this.name = 'UnmergeableValueError'\n this.keyPath = keyPath\n this.foundType = foundType\n }\n}\n\nexport type ReservedKeyErrorParams = { keyPath: readonly string[]; key: string }\n\nexport class ReservedKeyError extends ConfigFormatError {\n readonly keyPath: readonly string[]\n readonly key: string\n\n constructor({ keyPath, key }: ReservedKeyErrorParams) {\n super(`cannot write ${describeLocation(keyPath)}: \"${key}\" is a reserved name. Use another name, then run again.`)\n this.name = 'ReservedKeyError'\n this.keyPath = keyPath\n this.key = key\n }\n}\n\nexport type DuplicateKeyErrorParams = { keyPath: readonly string[] }\n\nexport class DuplicateKeyError extends ConfigFormatError {\n readonly keyPath: readonly string[]\n\n constructor({ keyPath }: DuplicateKeyErrorParams) {\n super(\n `cannot edit ${describeLocation(keyPath)}: it appears more than once in the same object. ` +\n 'Keep one, then run again.',\n )\n this.name = 'DuplicateKeyError'\n this.keyPath = keyPath\n }\n}\n\nexport class MergeConflictError extends ConfigFormatError {\n constructor() {\n super('cannot set the values without changing other settings in it. Set them by hand, then run again.')\n this.name = 'MergeConflictError'\n }\n}\n\nfunction describeLocation(keyPath: readonly string[]): string {\n if (keyPath.length === 0) return 'the top level'\n return `\"${keyPath.join('.')}\"`\n}\n","import {\n applyEdits,\n findNodeAtLocation,\n modify,\n parse,\n parseTree,\n printParseErrorCode,\n type FormattingOptions,\n type Node,\n type ParseError,\n type ParseErrorCode,\n type ParseOptions,\n} from 'jsonc-parser'\nimport { ConfigSyntaxError, DuplicateKeyError } from './config-errors'\nimport { detectLineEnding, type LineEnding } from './detect-line-ending'\nimport { listCreatedParents, listMissingParents, type KeyOriginal } from './key-original'\nimport {\n assertMergeable,\n assertTopLevelTable,\n readPath,\n type KeyPath,\n type KeyPathUpdates,\n type Table,\n} from './key-path'\nimport { splitByteOrderMark } from './split-byte-order-mark'\n\nconst PARSE_OPTIONS: ParseOptions = { allowTrailingComma: true, disallowComments: false }\n\nexport function parseJsonc(text: string | null): Table {\n const { body } = splitByteOrderMark(text ?? '')\n if (body.trim() === '') return {}\n\n const value = parseJsoncValue(body)\n assertTopLevelTable(value)\n return value\n}\n\nexport function parseJsoncValue(source: string): unknown {\n const errors: ParseError[] = []\n const value: unknown = parse(source, errors, PARSE_OPTIONS)\n const [firstError] = errors\n if (firstError !== undefined) {\n const position = locateOffset(source, firstError.offset)\n throw new ConfigSyntaxError({ ...position, reason: describeErrorCode(firstError.error) })\n }\n return value\n}\n\nconst EMPTY_DOCUMENT = '{}'\n\nexport function renderJsonc(current: string | null, updates: KeyPathUpdates): string {\n const { byteOrderMark, body } = splitByteOrderMark(current ?? '')\n const existing = parseJsonc(body)\n const tree = parseTree(body, [], PARSE_OPTIONS)\n for (const [keyPath] of updates) {\n assertNoDuplicateKey(tree, keyPath)\n assertMergeable(existing, keyPath)\n }\n\n const formattingOptions = detectFormatting(body)\n const edited = updates\n .filter(([keyPath, value]) => value !== undefined || readPath(existing, keyPath) !== undefined)\n .reduce(\n (text, [keyPath, value]) => setValue({ text, keyPath, value, formattingOptions }),\n body.trim() === '' ? EMPTY_DOCUMENT : body,\n )\n return byteOrderMark + endWithLineEnding(edited, formattingOptions.eol)\n}\n\nexport function readJsoncOriginals(current: string | null, keyPaths: readonly KeyPath[]): KeyOriginal[] {\n const { body } = splitByteOrderMark(current ?? '')\n const document = parseJsonc(body)\n return keyPaths.map((keyPath) => ({\n keyPath,\n original: readSource(body, keyPath),\n createdParents: listMissingParents(document, keyPath),\n }))\n}\n\nexport function restoreJsonc(current: string, originals: readonly KeyOriginal[]): string {\n const { byteOrderMark, body } = splitByteOrderMark(current)\n const document = parseJsonc(body)\n const tree = parseTree(body, [], PARSE_OPTIONS)\n for (const { keyPath, original } of originals) {\n assertNoDuplicateKey(tree, keyPath)\n if (original !== null) {\n assertMergeable(document, keyPath)\n // Parsed only to throw: a value that exists now is replaced by this text verbatim.\n parseJsoncValue(original)\n }\n }\n\n const formattingOptions = detectFormatting(body)\n const restored = originals.reduce((text, key) => restoreKey({ text, key, formattingOptions }), body)\n const pruned = listCreatedParents(originals).reduce(\n (text, keyPath) => removeEmptyObject({ text, keyPath, formattingOptions }),\n restored,\n )\n return byteOrderMark + pruned\n}\n\ntype TextPosition = { line: number; column: number }\n\nfunction locateOffset(text: string, offset: number): TextPosition {\n const before = text.slice(0, offset)\n const lineStart = before.lastIndexOf('\\n') + 1\n return { line: before.split('\\n').length, column: offset - lineStart + 1 }\n}\n\nconst WORD_BOUNDARY = /(?<=[a-z])(?=[A-Z])/g\n\nfunction describeErrorCode(code: ParseErrorCode): string {\n return printParseErrorCode(code).replace(WORD_BOUNDARY, ' ').toLowerCase()\n}\n\n// `modify` edits the first of two equal keys, while `JSON.parse`, and so the agent, reads the last.\nfunction assertNoDuplicateKey(root: Node | undefined, keyPath: KeyPath): void {\n let node = root\n for (const [index, key] of keyPath.entries()) {\n const values = listPropertyValues(node, key)\n if (values.length > 1) throw new DuplicateKeyError({ keyPath: keyPath.slice(0, index + 1) })\n node = values[0]\n }\n}\n\nfunction listPropertyValues(node: Node | undefined, key: string): Node[] {\n if (node?.type !== 'object') return []\n\n return (node.children ?? []).flatMap((property) => {\n const [keyNode, valueNode] = property.children ?? []\n return keyNode?.value === key && valueNode !== undefined ? [valueNode] : []\n })\n}\n\nconst DEFAULT_INDENT = ' '\nconst DEFAULT_LINE_ENDING: LineEnding = '\\n'\nconst FIRST_INDENTED_KEY = /^([ \\t]+)\"/m\n\ntype DetectedFormatting = FormattingOptions & { eol: LineEnding }\n\nfunction detectFormatting(text: string): DetectedFormatting {\n const indent = FIRST_INDENTED_KEY.exec(text)?.[1] ?? DEFAULT_INDENT\n const isSpaceIndented = !indent.startsWith('\\t')\n return {\n insertSpaces: isSpaceIndented,\n tabSize: isSpaceIndented ? indent.length : 1,\n eol: detectLineEnding(text) ?? DEFAULT_LINE_ENDING,\n }\n}\n\nfunction endWithLineEnding(text: string, lineEnding: LineEnding): string {\n return text.endsWith('\\n') ? text : text + lineEnding\n}\n\nfunction findNode(text: string, keyPath: KeyPath): Node | undefined {\n const root = parseTree(text, [], PARSE_OPTIONS)\n return root === undefined ? undefined : findNodeAtLocation(root, [...keyPath])\n}\n\nfunction readSource(text: string, keyPath: KeyPath): string | null {\n const node = findNode(text, keyPath)\n return node === undefined ? null : text.slice(node.offset, node.offset + node.length)\n}\n\ntype RestoreKeyParams = { text: string; key: KeyOriginal; formattingOptions: FormattingOptions }\n\nfunction restoreKey({ text, key, formattingOptions }: RestoreKeyParams): string {\n const node = findNode(text, key.keyPath)\n if (node === undefined && key.original === null) return text\n if (key.original === null) return setValue({ text, keyPath: key.keyPath, value: undefined, formattingOptions })\n if (node === undefined) {\n const value = parseJsoncValue(key.original)\n return setValue({ text, keyPath: key.keyPath, value, formattingOptions })\n }\n\n return text.slice(0, node.offset) + key.original + text.slice(node.offset + node.length)\n}\n\ntype RemoveEmptyObjectParams = { text: string; keyPath: KeyPath; formattingOptions: FormattingOptions }\n\nfunction removeEmptyObject({ text, keyPath, formattingOptions }: RemoveEmptyObjectParams): string {\n const node = findNode(text, keyPath)\n if (node?.type !== 'object' || (node.children ?? []).length > 0) return text\n\n return setValue({ text, keyPath, value: undefined, formattingOptions })\n}\n\ntype SetValueParams = { text: string; keyPath: KeyPath; value: unknown; formattingOptions: FormattingOptions }\n\nfunction setValue({ text, keyPath, value, formattingOptions }: SetValueParams): string {\n return applyEdits(text, modify(text, [...keyPath], value, { formattingOptions }))\n}\n","export type LineEnding = '\\n' | '\\r\\n'\n\nexport function detectLineEnding(text: string): LineEnding | undefined {\n if (text.includes('\\r\\n')) return '\\r\\n'\n if (text.includes('\\n')) return '\\n'\n return undefined\n}\n","import { match, P } from 'ts-pattern'\nimport * as v from 'valibot'\nimport { ReservedKeyError, UnmergeableValueError, type FoundType } from './config-errors'\n\nexport type KeyPath = readonly [string, ...string[]]\n/** A value of undefined removes the key, so a key that would override ours cannot linger. */\nexport type KeyPathUpdate = readonly [KeyPath, unknown]\nexport type KeyPathUpdates = readonly [KeyPathUpdate, ...KeyPathUpdate[]]\n\nconst TableSchema = v.pipe(\n v.unknown(),\n v.check((value) => !Array.isArray(value) && !(value instanceof Date)),\n v.record(v.string(), v.unknown()),\n)\n\nexport type Table = v.InferOutput<typeof TableSchema>\n\nexport function assertTopLevelTable(value: unknown): asserts value is Table {\n if (!isTable(value)) throw new UnmergeableValueError({ keyPath: [], foundType: describeFoundType(value) })\n}\n\nexport function assertMergeable(document: Table, keyPath: KeyPath): void {\n assertNoReservedKey(keyPath)\n\n const { parents } = splitLeaf(keyPath)\n let table = document\n for (const [index, key] of parents.entries()) {\n if (!Object.hasOwn(table, key)) return\n\n const value = table[key]\n if (!isTable(value)) {\n const keyPathToValue = parents.slice(0, index + 1)\n throw new UnmergeableValueError({ keyPath: keyPathToValue, foundType: describeFoundType(value) })\n }\n table = value\n }\n}\n\nexport function setPath(document: Table, keyPath: KeyPath, value: unknown): void {\n assertMergeable(document, keyPath)\n\n const { parents, leaf } = splitLeaf(keyPath)\n let table = document\n for (const key of parents) table = getOrCreateChildTable(table, key)\n table[leaf] = value\n}\n\nexport function readPath(document: Table, keyPath: KeyPath): unknown {\n let value: unknown = document\n for (const key of keyPath) {\n if (!isTable(value) || !Object.hasOwn(value, key)) return undefined\n value = value[key]\n }\n return value\n}\n\nexport function deletePath(document: Table, keyPath: KeyPath): void {\n const [first, ...rest] = keyPath\n const leaf = rest.pop()\n if (leaf === undefined) {\n delete document[first]\n return\n }\n\n const parent = readPath(document, [first, ...rest])\n if (isTable(parent)) delete parent[leaf]\n}\n\nexport function isEmptyTable(value: unknown): boolean {\n return isTable(value) && Object.keys(value).length === 0\n}\n\nconst RESERVED_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction assertNoReservedKey(keyPath: KeyPath): void {\n const reserved = keyPath.find((key) => RESERVED_KEYS.has(key))\n if (reserved !== undefined) throw new ReservedKeyError({ keyPath, key: reserved })\n}\n\nexport type SplitLeafResult = { parents: readonly string[]; leaf: string }\n\nexport function splitLeaf(keyPath: KeyPath): SplitLeafResult {\n const [first, ...rest] = keyPath\n const leaf = rest.pop()\n if (leaf === undefined) return { parents: [], leaf: first }\n return { parents: [first, ...rest], leaf }\n}\n\nfunction isTable(value: unknown): value is Table {\n return v.is(TableSchema, value)\n}\n\nfunction describeFoundType(value: unknown): FoundType {\n return match(value)\n .returnType<FoundType>()\n .with(null, () => 'null')\n .with(P.array(), () => 'array')\n .with(P.instanceOf(Date), () => 'date')\n .with(P.string, () => 'string')\n .with(P.union(P.number, P.bigint), () => 'number')\n .with(P.boolean, () => 'boolean')\n .otherwise(() => 'other')\n}\n\nfunction getOrCreateChildTable(table: Table, key: string): Table {\n const existing = Object.hasOwn(table, key) ? table[key] : undefined\n if (isTable(existing)) return existing\n\n const created: Table = {}\n table[key] = created\n return created\n}\n","import { readPath, type KeyPath, type Table } from './key-path'\n\n/** `original` is the value's source text as the file had it, or `null` when the key was absent. */\nexport type KeyOriginal = { keyPath: KeyPath; original: string | null; createdParents: readonly KeyPath[] }\n\nexport function listMissingParents(document: Table, keyPath: KeyPath): KeyPath[] {\n const parentPaths = listParentPaths(keyPath)\n const firstMissing = parentPaths.findIndex((parentPath) => readPath(document, parentPath) === undefined)\n return firstMissing === -1 ? [] : parentPaths.slice(firstMissing)\n}\n\nfunction listParentPaths([first, ...rest]: KeyPath): KeyPath[] {\n return rest.map((_, index) => [first, ...rest.slice(0, index)])\n}\n\nexport function listCreatedParents(originals: readonly KeyOriginal[]): KeyPath[] {\n const byPath = new Map<string, KeyPath>()\n for (const keyPath of originals.flatMap(({ createdParents }) => createdParents)) {\n byPath.set(JSON.stringify(keyPath), keyPath)\n }\n return [...byPath.values()].sort((first, second) => second.length - first.length)\n}\n","const BYTE_ORDER_MARK = ''\n\nexport type SplitByteOrderMarkResult = { byteOrderMark: string; body: string }\n\nexport function splitByteOrderMark(text: string): SplitByteOrderMarkResult {\n if (!text.startsWith(BYTE_ORDER_MARK)) return { byteOrderMark: '', body: text }\n return { byteOrderMark: BYTE_ORDER_MARK, body: text.slice(BYTE_ORDER_MARK.length) }\n}\n","import fs from 'node:fs'\nimport { isMissingFileError } from './is-missing-file-error'\nimport { Utf16FileError } from './utf16-file-error'\n\nexport function readFileIfExists(filePath: string): string | null {\n const bytes = readBytesIfExists(filePath)\n if (bytes === null) return null\n if (hasUtf16ByteOrderMark(bytes)) throw new Utf16FileError(filePath)\n\n return bytes.toString('utf8')\n}\n\nfunction readBytesIfExists(filePath: string): Buffer | null {\n try {\n return fs.readFileSync(filePath)\n } catch (error) {\n if (isMissingFileError(error)) return null\n throw error\n }\n}\n\nconst BYTE_ORDER_MARK = '\\uFEFF'\nconst UTF16_BYTE_ORDER_MARKS = [\n Buffer.from(BYTE_ORDER_MARK, 'utf16le'),\n Buffer.from(BYTE_ORDER_MARK, 'utf16le').swap16(),\n]\n\nfunction hasUtf16ByteOrderMark(bytes: Buffer): boolean {\n return UTF16_BYTE_ORDER_MARKS.some((byteOrderMark) => bytes.subarray(0, byteOrderMark.length).equals(byteOrderMark))\n}\n","export class Utf16FileError extends Error {\n readonly filePath: string\n\n constructor(filePath: string) {\n super(`${filePath} is saved as UTF-16. Re-save it as UTF-8, then run again.`)\n this.name = 'Utf16FileError'\n this.filePath = filePath\n }\n}\n","import path from 'node:path'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { DEFAULT_MODEL } from '../../product/gateway/models/predefined-models'\nimport { readPath } from '../../shared/file-formats/key-path'\nimport { parseToml, type TomlUpdate } from '../../shared/file-formats/toml'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { FileContribution, LaunchingHarness } from '../harness'\n\nconst BINARY = 'codex'\nconst API_KEY_VARIABLE = 'NEXOS_API_KEY'\n// Codex's default, written out to replace a \"chat\" left from an older config: Codex now refuses to start on it.\nconst WIRE_API = 'responses'\n\nexport const codex: LaunchingHarness = {\n kind: 'configurable',\n id: 'codex',\n label: 'OpenAI Codex',\n binary: BINARY,\n protocols: ['openai-responses'],\n projectSupport: { kind: 'unsupported', reason: 'a repo-level config.toml cannot set the provider or its base_url' },\n keyEnvVariable: API_KEY_VARIABLE,\n detect: (ctx) => detectConfigFile([resolveConfigPath(ctx)], ctx.home),\n configPath: (ctx) => resolveConfigPath(ctx),\n plan: (desired, ctx) => [\n planConfig(desired, ctx),\n { kind: 'env', variables: { [API_KEY_VARIABLE]: desired.apiKey } },\n ],\n launch: (desired) => {\n const overrides = [\n `model=${JSON.stringify(desired.model)}`,\n `model_provider=${JSON.stringify(RUN_PROVIDER_ID)}`,\n ...Object.entries(providerFields(desired)).map(\n ([field, value]) => `model_providers.${RUN_PROVIDER_ID}.${field}=${JSON.stringify(value)}`,\n ),\n ...[...PRIVACY_UPDATES, ...listRouterUpdates(desired)].map(\n ([keyPath, value]) => `${keyPath.join('.')}=${JSON.stringify(value)}`,\n ),\n ]\n return {\n binary: BINARY,\n arguments: overrides.flatMap((override) => ['-c', override]),\n env: { [API_KEY_VARIABLE]: desired.apiKey },\n subcommands: SESSION_SUBCOMMANDS,\n }\n },\n launchNotes: [\n 'Running /model saves that model to ~/.codex/config.toml.',\n 'A later plain `codex resume` of this session points at a \"nexos-run\" provider that no longer exists.',\n ],\n postSetupNotes: [\n `OpenAI Codex requires wire_api = \"${WIRE_API}\": if the gateway does not serve /v1/responses, ` +\n 'Codex fails even though its config is correct.',\n ],\n}\n\nconst CONFIG_DIRECTORY = '.codex'\nconst CONFIG_FILE = 'config.toml'\n\nfunction resolveConfigPath(ctx: PlatformContext): string {\n return path.join(ctx.home, CONFIG_DIRECTORY, CONFIG_FILE)\n}\n\nconst PROVIDER_ID = 'nexos'\nconst RUN_PROVIDER_ID = 'nexos-run'\n// Display only, but never \"OpenAI\": Codex treats a provider of that name as OpenAI itself.\nconst PROVIDER_NAME = 'nexos.ai'\n\n// Codex drops every root-level -c once the subcommand is given one of its own, the gateway's included.\nconst SESSION_SUBCOMMANDS = ['exec', 'e', 'review', 'resume', 'fork']\n\nfunction providerFields(desired: DesiredConfig): Record<string, string> {\n return { name: PROVIDER_NAME, base_url: desired.openaiBaseUrl, env_key: API_KEY_VARIABLE, wire_api: WIRE_API }\n}\n\n// Codex sends usage metrics to OpenAI whatever the provider, and /feedback uploads its logs there.\nconst PRIVACY_UPDATES: readonly TomlUpdate[] = [\n [['analytics', 'enabled'], false],\n [['feedback', 'enabled'], false],\n]\n\nconst WEB_SEARCH_KEY_PATH = ['web_search'] as const\nconst WEB_SEARCH_DISABLED = 'disabled'\n\n// OpenAI's hosted web search goes out with every turn, and the router may hand a turn to a backend without it.\nfunction listRouterUpdates(desired: DesiredConfig): TomlUpdate[] {\n return desired.model === DEFAULT_MODEL ? [[WEB_SEARCH_KEY_PATH, WEB_SEARCH_DISABLED]] : []\n}\n\nfunction planConfig(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n const updates: TomlUpdate[] = [\n [['model'], desired.model],\n [['model_provider'], PROVIDER_ID],\n ...Object.entries(providerFields(desired)).map(([field, value]): TomlUpdate => [\n ['model_providers', PROVIDER_ID, field],\n value,\n ]),\n ...PRIVACY_UPDATES,\n ...listRouterUpdates(desired),\n ]\n return {\n kind: 'file',\n path: resolveConfigPath(ctx),\n hasSecret: false,\n edits: (current) => ({\n format: 'toml',\n updates: [...updates, ...listLeftoverRemovals({ desired, current })],\n }),\n }\n}\n\ntype LeftoverRemovalsParams = { desired: DesiredConfig; current: string | null }\n\n// Lifts only the \"disabled\" set up for the router: any other web_search is the user's own choice.\nfunction listLeftoverRemovals({ desired, current }: LeftoverRemovalsParams): TomlUpdate[] {\n if (desired.model === DEFAULT_MODEL) return []\n\n const isRouterLeftover = readPath(parseToml(current ?? ''), WEB_SEARCH_KEY_PATH) === WEB_SEARCH_DISABLED\n return isRouterLeftover ? [[WEB_SEARCH_KEY_PATH, undefined]] : []\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport { getStaticTOMLValue, ParseError, parseTOML, traverseNodes, type AST } from 'toml-eslint-parser'\nimport { match } from 'ts-pattern'\nimport { ConfigSyntaxError, MergeConflictError, ReservedKeyError } from './config-errors'\nimport { detectLineEnding, type LineEnding } from './detect-line-ending'\nimport { listCreatedParents, listMissingParents, type KeyOriginal } from './key-original'\nimport { deletePath, isEmptyTable, readPath, setPath, splitLeaf, type KeyPath, type Table } from './key-path'\nimport { splitByteOrderMark } from './split-byte-order-mark'\n\n/** A value of undefined removes the key, so a key that would override ours cannot linger. */\nexport type TomlUpdate = readonly [KeyPath, string | boolean | undefined]\n\nexport function parseToml(text: string): Table {\n return readTable(parseProgram(splitByteOrderMark(text).body))\n}\n\nexport function renderToml(current: string | null, updates: readonly TomlUpdate[]): string {\n const { byteOrderMark, body } = splitByteOrderMark(current ?? '')\n const expected = readTable(parseProgram(body))\n for (const [keyPath, value] of updates) {\n if (value === undefined) deletePath(expected, keyPath)\n else setPath(expected, keyPath, value)\n }\n\n const lineEnding = detectLineEnding(body) ?? DEFAULT_LINE_ENDING\n const edited = updates.reduce((text, update) => spliceUpdate({ text, lineEnding }, update), body)\n if (!isDeepStrictEqual(readTable(parseOwnEdit(edited)), expected)) {\n throw new MergeConflictError()\n }\n return byteOrderMark + edited\n}\n\nexport function readTomlOriginals(current: string | null, keyPaths: readonly KeyPath[]): KeyOriginal[] {\n const { body } = splitByteOrderMark(current ?? '')\n const program = parseProgram(body)\n const document = readTable(program)\n const entries = listKeyValues(program)\n return keyPaths.map((keyPath) => ({\n keyPath,\n original: readSource(body, entries, keyPath),\n createdParents: listMissingParents(document, keyPath),\n }))\n}\n\nexport function restoreToml(current: string, originals: readonly KeyOriginal[]): string {\n const { byteOrderMark, body } = splitByteOrderMark(current)\n const createdParents = listCreatedParents(originals)\n const expected = readTable(parseProgram(body))\n for (const key of originals) applyOriginal(expected, key)\n for (const keyPath of createdParents) {\n if (isEmptyTable(readPath(expected, keyPath))) deletePath(expected, keyPath)\n }\n\n const lineEnding = detectLineEnding(body) ?? DEFAULT_LINE_ENDING\n const restored = originals.reduce((text, key) => restoreKey({ text, lineEnding }, key), body)\n const pruned = createdParents.reduce((text, keyPath) => removeEmptyTable({ text, lineEnding }, keyPath), restored)\n if (!isDeepStrictEqual(readTable(parseOwnEdit(pruned)), expected)) {\n throw new MergeConflictError()\n }\n return byteOrderMark + pruned\n}\n\nconst PARSER_OPTIONS = { tomlVersion: '1.1' } as const\n\nfunction parseProgram(text: string): AST.TOMLProgram {\n try {\n return parseTOML(text, PARSER_OPTIONS)\n } catch (error) {\n if (!(error instanceof ParseError)) throw error\n throw new ConfigSyntaxError({\n line: error.lineNumber,\n column: error.column + 1,\n reason: error.message,\n })\n }\n}\n\nfunction readTable(program: AST.TOMLProgram): Table {\n assertNoPrototypeKey(program)\n return getStaticTOMLValue(program)\n}\n\n// getStaticTOMLValue assigns keys plainly, so a `__proto__` key would write onto Object.prototype.\nconst PROTOTYPE_KEY = '__proto__'\n\nfunction assertNoPrototypeKey(program: AST.TOMLProgram): void {\n traverseNodes(program, {\n enterNode(node) {\n if (node.type !== 'TOMLKey') return\n\n const keys = node.keys.map(readKeyName)\n const index = keys.indexOf(PROTOTYPE_KEY)\n if (index !== -1) {\n throw new ReservedKeyError({\n keyPath: keys.slice(0, index + 1),\n key: PROTOTYPE_KEY,\n })\n }\n },\n leaveNode() {},\n })\n}\n\nfunction readKeyName(key: AST.TOMLBare | AST.TOMLQuoted): string {\n return key.type === 'TOMLBare' ? key.name : key.value\n}\n\nconst DEFAULT_LINE_ENDING: LineEnding = '\\n'\n\ntype TomlSource = { text: string; lineEnding: LineEnding }\n\nfunction spliceUpdate(source: TomlSource, [keyPath, value]: TomlUpdate): string {\n const program = parseOwnEdit(source.text)\n const entries = listKeyValues(program)\n const current = entries.find((entry) => isSamePath(entry.path, keyPath))\n if (value === undefined) return current === undefined ? source.text : removeKeyValue(source, program, current)\n if (current !== undefined) return replaceValue(source, current.keyValue.value, value)\n\n return insertKeyValue({ source, program, entries, keyPath, valueText: formatValue(value) })\n}\n\ntype InsertKeyValueParams = {\n source: TomlSource\n program: AST.TOMLProgram\n entries: readonly KeyValueEntry[]\n keyPath: KeyPath\n valueText: string\n}\n\nfunction insertKeyValue({ source, program, entries, keyPath, valueText }: InsertKeyValueParams): string {\n const { parents, leaf } = splitLeaf(keyPath)\n const keyValueText = formatKeyValue([leaf], valueText)\n\n return match(findPlacement(program, entries, parents))\n .with({ kind: 'top-level' }, () => insertTopLevel(source, program, keyValueText))\n .with({ kind: 'table' }, ({ table }) => insertLineAfter(source, table.range[1], keyValueText))\n .with({ kind: 'dotted' }, ({ entry }) => {\n const keys = [...parents.slice(entry.tablePath.length), leaf]\n return insertBesideDottedKey(source, entry, formatKeyValue(keys, valueText))\n })\n .with({ kind: 'inline' }, ({ inlineTable, keysInside }) =>\n insertIntoInlineTable(source, inlineTable, nestInInlineTables(keysInside, keyValueText)),\n )\n .with({ kind: 'new-table' }, () => appendTable(source, parents, keyValueText))\n .exhaustive()\n}\n\nfunction parseOwnEdit(text: string): AST.TOMLProgram {\n try {\n return parseProgram(text)\n } catch (error) {\n if (error instanceof ConfigSyntaxError) throw new MergeConflictError()\n throw error\n }\n}\n\ntype TomlPath = readonly (string | number)[]\n\ntype KeyValueEntry = {\n path: TomlPath\n keyValue: AST.TOMLKeyValue\n tablePath: TomlPath\n}\n\nfunction listKeyValues(program: AST.TOMLProgram): KeyValueEntry[] {\n return program.body[0].body.flatMap((node) => {\n if (node.type === 'TOMLTable') {\n return listInBody(node.body, node.resolvedKey)\n }\n return listInBody([node], [])\n })\n}\n\nfunction listInBody(keyValues: readonly AST.TOMLKeyValue[], tablePath: TomlPath): KeyValueEntry[] {\n return keyValues.flatMap((keyValue) => {\n const path = [...tablePath, ...keyValue.key.keys.map(readKeyName)]\n const entry = { path, keyValue, tablePath }\n if (keyValue.value.type !== 'TOMLInlineTable') return [entry]\n return [entry, ...listInBody(keyValue.value.body, path)]\n })\n}\n\nfunction isSamePath(path: TomlPath, other: TomlPath): boolean {\n return path.length === other.length && path.every((key, index) => key === other[index])\n}\n\nfunction replaceValue(source: TomlSource, node: AST.TOMLContentNode, value: string | boolean): string {\n if (node.type === 'TOMLValue' && node.value === value) return source.text\n return replaceRange(source, node.range, formatValue(value))\n}\n\ntype Placement =\n | { kind: 'top-level' }\n | { kind: 'table'; table: AST.TOMLTable }\n | { kind: 'dotted'; entry: KeyValueEntry }\n | {\n kind: 'inline'\n inlineTable: AST.TOMLInlineTable\n keysInside: readonly string[]\n }\n | { kind: 'new-table' }\n\nfunction findPlacement(\n program: AST.TOMLProgram,\n entries: readonly KeyValueEntry[],\n tablePath: readonly string[],\n): Placement {\n if (tablePath.length === 0) return { kind: 'top-level' }\n\n const table = findStandardTable(program, tablePath)\n if (table !== undefined) return { kind: 'table', table }\n\n const dotted = entries.findLast((entry) => isDottedKeyUnder(entry, tablePath))\n if (dotted !== undefined) return { kind: 'dotted', entry: dotted }\n\n for (let length = tablePath.length; length > 0; length--) {\n const prefix = tablePath.slice(0, length)\n const value = entries.find((entry) => isSamePath(entry.path, prefix))?.keyValue.value\n if (value?.type === 'TOMLInlineTable') {\n return {\n kind: 'inline',\n inlineTable: value,\n keysInside: tablePath.slice(length),\n }\n }\n }\n\n return { kind: 'new-table' }\n}\n\nfunction findStandardTable(program: AST.TOMLProgram, tablePath: TomlPath): AST.TOMLTable | undefined {\n return program.body[0].body\n .filter((node) => node.type === 'TOMLTable')\n .find((candidate) => candidate.kind === 'standard' && isSamePath(candidate.resolvedKey, tablePath))\n}\n\nfunction isDottedKeyUnder(entry: KeyValueEntry, tablePath: readonly string[]): boolean {\n return (\n entry.tablePath.length < tablePath.length &&\n entry.path.length > tablePath.length &&\n isSamePath(entry.path.slice(0, tablePath.length), tablePath)\n )\n}\n\nfunction insertTopLevel(source: TomlSource, program: AST.TOMLProgram, keyValueText: string): string {\n const nodes = program.body[0].body\n const lastKeyValue = nodes.findLast((node) => node.type === 'TOMLKeyValue')\n if (lastKeyValue !== undefined) {\n return insertLineAfter(source, lastKeyValue.range[1], keyValueText)\n }\n\n const firstTable = nodes.find((node) => node.type === 'TOMLTable')\n if (firstTable === undefined) return appendLine(source, keyValueText)\n\n const lineStart = source.text.lastIndexOf('\\n', firstTable.range[0] - 1) + 1\n return replaceRange(source, [lineStart, lineStart], keyValueText + source.lineEnding + source.lineEnding)\n}\n\nfunction insertLineAfter(source: TomlSource, offset: number, line: string): string {\n const lineEnd = findLineEnd(source.text, offset)\n return replaceRange(source, [lineEnd, lineEnd], source.lineEnding + line)\n}\n\nfunction findLineEnd(text: string, offset: number): number {\n const newline = text.indexOf('\\n', offset)\n if (newline === -1) return text.length\n return text[newline - 1] === '\\r' ? newline - 1 : newline\n}\n\nfunction appendLine(source: TomlSource, line: string): string {\n const { text, lineEnding } = source\n const separator = text === '' || text.endsWith('\\n') ? '' : lineEnding\n return text + separator + line + lineEnding\n}\n\nfunction insertBesideDottedKey(source: TomlSource, entry: KeyValueEntry, keyValueText: string): string {\n const offset = entry.keyValue.range[1]\n if (entry.keyValue.parent.type !== 'TOMLInlineTable') {\n return insertLineAfter(source, offset, keyValueText)\n }\n return replaceRange(source, [offset, offset], `, ${keyValueText}`)\n}\n\nfunction insertIntoInlineTable(source: TomlSource, inlineTable: AST.TOMLInlineTable, keyValueText: string): string {\n const lastKeyValue = inlineTable.body.at(-1)\n if (lastKeyValue === undefined) {\n return replaceRange(source, inlineTable.range, `{ ${keyValueText} }`)\n }\n\n const offset = lastKeyValue.range[1]\n return replaceRange(source, [offset, offset], `, ${keyValueText}`)\n}\n\nfunction nestInInlineTables(tableKeys: readonly string[], keyValueText: string): string {\n return tableKeys.reduceRight((inner, key) => `${formatKey(key)} = { ${inner} }`, keyValueText)\n}\n\nfunction appendTable(source: TomlSource, tablePath: readonly string[], keyValueText: string): string {\n const { text, lineEnding } = source\n const header = `[${tablePath.map(formatKey).join('.')}]`\n return text + findSeparatorBeforeTable(source) + header + lineEnding + keyValueText + lineEnding\n}\n\nfunction findSeparatorBeforeTable({ text, lineEnding }: TomlSource): string {\n if (text.trim() === '') return ''\n if (text.endsWith('\\n')) return lineEnding\n return lineEnding + lineEnding\n}\n\nfunction replaceRange({ text }: TomlSource, [start, end]: AST.Range, replacement: string): string {\n return text.slice(0, start) + replacement + text.slice(end)\n}\n\nfunction formatKeyValue(keys: readonly string[], valueText: string): string {\n return `${keys.map(formatKey).join('.')} = ${valueText}`\n}\n\nconst BARE_KEY = /^[A-Za-z0-9_-]+$/\n\nfunction formatKey(key: string): string {\n return BARE_KEY.test(key) ? key : formatString(key)\n}\n\nfunction formatValue(value: string | boolean): string {\n return typeof value === 'boolean' ? String(value) : formatString(value)\n}\n\n// JSON's escapes are valid in a TOML basic string, but TOML also requires DEL (U+007F) escaped.\nconst DELETE_CHARACTER = /\\u007f/g\n\nfunction formatString(value: string): string {\n return JSON.stringify(value).replace(DELETE_CHARACTER, '\\\\u007f')\n}\n\nfunction readSource(text: string, entries: readonly KeyValueEntry[], keyPath: KeyPath): string | null {\n const entry = entries.find((candidate) => isSamePath(candidate.path, keyPath))\n if (entry === undefined) return null\n\n const [start, end] = entry.keyValue.value.range\n return text.slice(start, end)\n}\n\nfunction applyOriginal(expected: Table, { keyPath, original }: KeyOriginal): void {\n if (original === null) {\n deletePath(expected, keyPath)\n return\n }\n\n setPath(expected, keyPath, parseTomlValue(original))\n}\n\nconst VALUE_KEY = 'value'\n\nexport function parseTomlValue(source: string): unknown {\n return readTable(parseProgram(`${VALUE_KEY} = ${source}`))[VALUE_KEY]\n}\n\nfunction restoreKey(source: TomlSource, { keyPath, original }: KeyOriginal): string {\n const program = parseOwnEdit(source.text)\n const entries = listKeyValues(program)\n const current = entries.find((entry) => isSamePath(entry.path, keyPath))\n if (original === null) return current === undefined ? source.text : removeKeyValue(source, program, current)\n if (current !== undefined) return replaceRange(source, current.keyValue.value.range, original)\n\n return insertKeyValue({ source, program, entries, keyPath, valueText: original })\n}\n\nfunction removeEmptyTable(source: TomlSource, keyPath: KeyPath): string {\n const program = parseOwnEdit(source.text)\n if (!isEmptyTable(readPath(readTable(program), keyPath))) return source.text\n\n const entry = listKeyValues(program).find((candidate) => isSamePath(candidate.path, keyPath))\n if (entry !== undefined) return removeKeyValue(source, program, entry)\n\n const table = findStandardTable(program, keyPath)\n return table === undefined ? source.text : removeTableHeader(source, table)\n}\n\nfunction removeKeyValue(source: TomlSource, program: AST.TOMLProgram, { keyValue }: KeyValueEntry): string {\n if (keyValue.parent.type === 'TOMLInlineTable') return removeFromInlineTable(source, keyValue.parent, keyValue)\n\n const isLastTopLevel = keyValue.parent.type === 'TOMLTopLevelTable' && countTopLevelKeyValues(program) === 1\n const removed = removeLine(source, keyValue.range)\n if (!isLastTopLevel) return removed.text\n\n return removeLineBreakAt(removed.text, removed.offset)\n}\n\nconst EMPTY_INLINE_TABLE = '{}'\n\nfunction removeFromInlineTable(\n source: TomlSource,\n inlineTable: AST.TOMLInlineTable,\n keyValue: AST.TOMLKeyValue,\n): string {\n const index = inlineTable.body.indexOf(keyValue)\n const previous = inlineTable.body[index - 1]\n if (previous !== undefined) return replaceRange(source, [previous.range[1], keyValue.range[1]], '')\n\n const next = inlineTable.body[index + 1]\n if (next !== undefined) return replaceRange(source, [keyValue.range[0], next.range[0]], '')\n\n return replaceRange(source, inlineTable.range, EMPTY_INLINE_TABLE)\n}\n\nfunction countTopLevelKeyValues(program: AST.TOMLProgram): number {\n return program.body[0].body.filter((node) => node.type === 'TOMLKeyValue').length\n}\n\n// Also drops the blank line appendTable put before the section, so the sections around it keep one between them.\nfunction removeTableHeader(source: TomlSource, table: AST.TOMLTable): string {\n const { text, offset } = removeLine(source, [table.range[0], table.key.range[1]])\n const isFollowedByBlank = offset === text.length || measureLineBreakAt(text, offset) > 0\n if (!isFollowedByBlank) return text\n if (offset === 0) return removeLineBreakAt(text, offset)\n if (!isBlankLineBefore(text, offset)) return text\n\n return text.slice(0, offset - measureLineBreakBefore(text, offset)) + text.slice(offset)\n}\n\ntype RemovedLine = { text: string; offset: number }\n\nfunction removeLine({ text }: TomlSource, [start, end]: AST.Range): RemovedLine {\n const lineStart = text.lastIndexOf('\\n', start - 1) + 1\n const lineEnd = findLineEnd(text, end)\n const lineBreakLength = measureLineBreakAt(text, lineEnd)\n if (lineBreakLength > 0 || lineStart === 0) {\n return { text: text.slice(0, lineStart) + text.slice(lineEnd + lineBreakLength), offset: lineStart }\n }\n\n const offset = lineStart - measureLineBreakBefore(text, lineStart)\n return { text: text.slice(0, offset) + text.slice(lineEnd), offset }\n}\n\nfunction removeLineBreakAt(text: string, offset: number): string {\n return text.slice(0, offset) + text.slice(offset + measureLineBreakAt(text, offset))\n}\n\nconst CRLF = '\\r\\n'\nconst LF = '\\n'\n\nfunction measureLineBreakAt(text: string, offset: number): number {\n if (text.startsWith(CRLF, offset)) return CRLF.length\n if (text.startsWith(LF, offset)) return LF.length\n return 0\n}\n\nfunction measureLineBreakBefore(text: string, offset: number): number {\n if (text.slice(0, offset).endsWith(CRLF)) return CRLF.length\n if (text.slice(0, offset).endsWith(LF)) return LF.length\n return 0\n}\n\nfunction isBlankLineBefore(text: string, offset: number): boolean {\n const lineBreakLength = measureLineBreakBefore(text, offset)\n if (lineBreakLength === 0) return false\n\n const lineStart = offset - lineBreakLength\n return lineStart === 0 || text[lineStart - 1] === LF\n}\n","import type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { findContextWindow } from '../../product/gateway/models/predefined-models'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport type { DetectResult, LaunchingHarness } from '../harness'\n\nconst BINARY = 'copilot'\nconst TYPE_VARIABLE = 'COPILOT_PROVIDER_TYPE'\nconst BASE_URL_VARIABLE = 'COPILOT_PROVIDER_BASE_URL'\nconst API_KEY_VARIABLE = 'COPILOT_PROVIDER_API_KEY'\n// A custom provider has no default model: without one, Copilot CLI refuses to run.\nconst MODEL_VARIABLE = 'COPILOT_MODEL'\n// Copilot CLI assumes 128K for a model it does not know, and applies this to every model the provider serves.\nconst MAX_PROMPT_TOKENS_VARIABLE = 'COPILOT_PROVIDER_MAX_PROMPT_TOKENS'\n// The provider variables Copilot CLI reads that this run leaves unset: inherited from the shell, each would swap\n// the key, the endpoint or the request shape, and in offline mode the GHES pair replaces the provider outright.\nconst OTHER_PROVIDER_VARIABLES = [\n 'COPILOT_PROVIDER_API_KEY_COMMAND',\n 'COPILOT_PROVIDER_BEARER_TOKEN',\n 'COPILOT_PROVIDER_WIRE_API',\n 'COPILOT_PROVIDER_TRANSPORT',\n 'COPILOT_PROVIDER_AZURE_API_VERSION',\n 'COPILOT_PROVIDER_HEADERS',\n 'COPILOT_PROVIDER_MODEL_ID',\n 'COPILOT_PROVIDER_WIRE_MODEL',\n 'COPILOT_PROVIDER_MAX_OUTPUT_TOKENS',\n 'COPILOT_PROVIDER_GHES_HOST',\n 'COPILOT_PROVIDER_GHES_TOKEN',\n]\nconst PROVIDER_TYPE = 'openai'\n\nexport const copilotCli: LaunchingHarness = {\n kind: 'configurable',\n id: 'copilot-cli',\n label: 'GitHub Copilot CLI',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: {\n kind: 'unsupported',\n reason: 'it reads COPILOT_PROVIDER_* from the environment, which nothing project-local sets',\n },\n keyEnvVariable: API_KEY_VARIABLE,\n detect: (ctx) => detectBinary(ctx),\n plan: (desired) => [{ kind: 'env', variables: providerEnv(desired) }],\n launch: (desired) => ({\n binary: BINARY,\n arguments: [],\n env: { ...providerEnv(desired), ...Object.fromEntries(OTHER_PROVIDER_VARIABLES.map((name) => [name, undefined])) },\n }),\n launchNotes: ['This session is kept in your Copilot CLI history like any other.'],\n postSetupNotes: [\n 'GitHub Copilot CLI starts on the model chosen here; for another, start it with `copilot --model <id>` or run setup again.',\n 'Run `copilot help providers` to see which variables your version supports, in case these names have drifted.',\n ],\n}\n\nfunction providerEnv(desired: DesiredConfig): Record<string, string | undefined> {\n const contextTokens = findContextWindow(desired.model)\n return {\n [TYPE_VARIABLE]: PROVIDER_TYPE,\n [BASE_URL_VARIABLE]: desired.openaiBaseUrl,\n [API_KEY_VARIABLE]: desired.apiKey,\n [MODEL_VARIABLE]: desired.model,\n [MAX_PROMPT_TOKENS_VARIABLE]: contextTokens === undefined ? undefined : String(contextTokens),\n }\n}\n\nfunction detectBinary(ctx: PlatformContext): DetectResult {\n const isFound = ctx.hasBinary(BINARY)\n return { isFound, detail: isFound ? `${BINARY} found on PATH` : `${BINARY} not found on PATH` }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { isMissingFileError } from '../../shared/file-system/is-missing-file-error'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport type { DetectResult, UnsupportedHarness } from '../harness'\n\nexport const geminiCli: UnsupportedHarness = {\n kind: 'unsupported',\n id: 'gemini-cli',\n label: 'Gemini CLI',\n binary: 'gemini',\n reason: \"speaks Gemini's native generateContent protocol, not OpenAI or Anthropic\",\n detect: (ctx) => detectConfigDirectory(ctx),\n}\n\nconst CONFIG_DIRECTORY = '.gemini'\n\nfunction detectConfigDirectory(ctx: PlatformContext): DetectResult {\n const directory = path.join(ctx.home, CONFIG_DIRECTORY)\n if (!isDirectory(directory)) return { isFound: false, detail: `no ${displayPath(directory, ctx.home)}` }\n\n return { isFound: true, detail: 'installed, but not configurable through the nexos.ai Gateway' }\n}\n\nfunction isDirectory(directoryPath: string): boolean {\n try {\n return fs.statSync(directoryPath).isDirectory()\n } catch (error) {\n if (isMissingFileError(error)) return false\n throw error\n }\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport * as v from 'valibot'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { findContextWindow } from '../../product/gateway/models/predefined-models'\nimport { renderJsonc } from '../../shared/file-formats/jsonc'\nimport type { KeyPathUpdate, KeyPathUpdates } from '../../shared/file-formats/key-path'\nimport { findFirstExistingFile } from '../../shared/file-system/find-first-existing-file'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { DetectResult, FileContribution, LaunchingHarness } from '../harness'\nimport { parseJsoncConfig, readJsoncFile, type JsoncConfig } from '../read-jsonc-file'\n\nconst BINARY = 'opencode'\n\nexport const opencode: LaunchingHarness = {\n kind: 'configurable',\n id: 'opencode',\n label: 'OpenCode',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: { kind: 'supported' },\n detect: (ctx) => detectOpenCode(ctx),\n configPath: (ctx) => resolveConfigPath(ctx),\n plan: (desired, ctx) => [planConfig(desired, ctx)],\n launch: (desired) => {\n // The run provider names its key through the environment, so the key never reaches argv.\n const config = renderJsonc(null, [\n ...providerUpdates({ providerId: RUN_PROVIDER_ID, apiKey: `{env:${RUN_KEY_VARIABLE}}`, desired }),\n // Leaves no other provider to drift to, OpenCode's own free models included, which send prompts outside nexos.ai.\n [['enabled_providers'], [RUN_PROVIDER_ID]],\n ])\n return {\n binary: BINARY,\n arguments: [],\n env: {\n [CONFIG_CONTENT_VARIABLE]: config,\n [RUN_KEY_VARIABLE]: desired.apiKey,\n [MODELS_FETCH_SWITCH]: SWITCH_ON,\n },\n }\n },\n launchNotes: [\n 'OpenCode adds the \"nexos-run\" model to its recent models, where it shows as unavailable in later sessions.',\n ],\n readKey: (ctx) => readProviderKey(ctx),\n readSecrets: (ctx) => readProviderSecrets(ctx),\n postSetupNotes: [\n 'OpenCode keeps its own credentials in its auth.json; this key goes in the provider block instead, ' +\n 'so no /connect step is needed.',\n ],\n}\n\nfunction detectOpenCode(ctx: PlatformContext): DetectResult {\n const detected = detectConfigFile(listConfigCandidates(ctx), ctx.home)\n if (detected.isFound || ctx.scope === 'project' || !ctx.hasBinary(BINARY)) return detected\n\n return { isFound: true, detail: `${BINARY} found on PATH` }\n}\n\nconst USER_CONFIG_DIRECTORY = path.join('.config', 'opencode')\nconst JSON_CONFIG_FILE = 'opencode.json'\nconst JSONC_CONFIG_FILE = 'opencode.jsonc'\n\nfunction listConfigCandidates(ctx: PlatformContext): readonly [string, string] {\n const directory = match(ctx.scope)\n .with('user', () => path.join(ctx.home, USER_CONFIG_DIRECTORY))\n .with('project', () => ctx.cwd)\n .exhaustive()\n return [path.join(directory, JSON_CONFIG_FILE), path.join(directory, JSONC_CONFIG_FILE)]\n}\n\nfunction resolveConfigPath(ctx: PlatformContext): string {\n const candidates = listConfigCandidates(ctx)\n return findFirstExistingFile(candidates) ?? candidates[0]\n}\n\nfunction planConfig(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n return {\n kind: 'file',\n path: resolveConfigPath(ctx),\n hasSecret: true,\n edits: (current) => ({ format: 'jsonc', updates: listUpdates(desired, parseJsoncConfig(current, ConfigSchema)) }),\n }\n}\n\nconst PROVIDER_ID = 'nexos'\nconst PROVIDER_NAME = 'nexos.ai'\nconst PROVIDER_PACKAGE = '@ai-sdk/openai-compatible'\nconst RUN_PROVIDER_ID = 'nexos-run'\nconst RUN_KEY_VARIABLE = 'NEXOS_API_KEY'\nconst CONFIG_CONTENT_VARIABLE = 'OPENCODE_CONFIG_CONTENT'\n// OpenCode refreshes its catalogue of other providers' models from models.opencode.ai every hour; a run needs none.\nconst MODELS_FETCH_SWITCH = 'OPENCODE_DISABLE_MODELS_FETCH'\nconst SWITCH_ON = '1'\nexport const CONFIG_SCHEMA_URL = 'https://opencode.ai/config.json'\n\ntype ProviderUpdatesParams = { providerId: string; apiKey: string; desired: DesiredConfig }\n\nfunction providerUpdates({ providerId, apiKey, desired }: ProviderUpdatesParams): KeyPathUpdates {\n return [\n [['provider', providerId, 'npm'], PROVIDER_PACKAGE],\n [['provider', providerId, 'name'], PROVIDER_NAME],\n [['provider', providerId, 'options', 'baseURL'], desired.openaiBaseUrl],\n [['provider', providerId, 'options', 'apiKey'], apiKey],\n [['provider', providerId, 'models', desired.model, 'name'], desired.model],\n ...listLimitUpdates({ providerId, model: desired.model }),\n [['model'], `${providerId}/${desired.model}`],\n ]\n}\n\ntype LimitUpdatesParams = { providerId: string; model: string }\n\n// OpenCode's config takes both limits or neither, and caps output at this anyway.\nconst OUTPUT_TOKENS = 32_000\n\n// With no context limit OpenCode never compacts ahead of time, only once the gateway has refused a prompt.\nfunction listLimitUpdates({ providerId, model }: LimitUpdatesParams): KeyPathUpdate[] {\n const contextTokens = findContextWindow(model)\n if (contextTokens === undefined) return []\n\n return [\n [['provider', providerId, 'models', model, 'limit', 'context'], contextTokens],\n [['provider', providerId, 'models', model, 'limit', 'output'], OUTPUT_TOKENS],\n ]\n}\n\nfunction listUpdates(desired: DesiredConfig, config: JsoncConfig<OpenCodeConfig>): KeyPathUpdates {\n const updates = providerUpdates({ providerId: PROVIDER_ID, apiKey: desired.apiKey, desired })\n if (!isMissingSchemaUrl(config)) return updates\n\n return [[['$schema'], CONFIG_SCHEMA_URL], ...updates]\n}\n\nfunction isMissingSchemaUrl(config: JsoncConfig<OpenCodeConfig>): boolean {\n return match(config)\n .with({ kind: 'absent' }, () => true)\n .with({ kind: 'invalid' }, () => false)\n .with({ kind: 'valid' }, ({ value }) => value.$schema === undefined)\n .exhaustive()\n}\n\nfunction readProviderKey(ctx: PlatformContext): string | undefined {\n const config = readJsoncFile(resolveConfigPath(ctx), ConfigSchema)\n const apiKey = config.kind === 'valid' ? config.value.provider?.[PROVIDER_ID]?.options?.apiKey : undefined\n return apiKey === undefined || isSubstitution(apiKey) ? undefined : apiKey\n}\n\nconst SUBSTITUTION_MARKERS = ['{env:', '{file:'] as const\n\nfunction isSubstitution(value: string): boolean {\n return SUBSTITUTION_MARKERS.some((marker) => value.includes(marker))\n}\n\nconst ProvidersSchema = v.looseObject({\n provider: v.fallback(v.optional(v.record(v.string(), v.unknown())), undefined),\n})\nconst ProviderKeySchema = v.looseObject({ options: v.looseObject({ apiKey: v.string() }) })\n\nfunction readProviderSecrets(ctx: PlatformContext): string[] {\n const config = readJsoncFile(resolveConfigPath(ctx), ProvidersSchema)\n if (config.kind !== 'valid') return []\n\n return Object.values(config.value.provider ?? {}).flatMap((provider) => {\n const parsed = v.safeParse(ProviderKeySchema, provider)\n if (!parsed.success || isSubstitution(parsed.output.options.apiKey)) return []\n return readNonBlank(parsed.output.options.apiKey) ?? []\n })\n}\n\nconst ConfigSchema = v.looseObject({\n $schema: v.optional(v.unknown()),\n provider: v.optional(\n v.looseObject({\n [PROVIDER_ID]: v.optional(\n v.looseObject({ options: v.optional(v.looseObject({ apiKey: v.optional(v.string()) })) }),\n ),\n }),\n ),\n})\n\ntype OpenCodeConfig = v.InferOutput<typeof ConfigSchema>\n","import { claudeCode } from './claude-code/claude-code'\nimport { codex } from './codex/codex'\nimport { copilotCli } from './copilot-cli/copilot-cli'\nimport { geminiCli } from './gemini-cli/gemini-cli'\nimport type { Harness } from './harness'\nimport { opencode } from './opencode/opencode'\n\nexport const harnesses: readonly Harness[] = [claudeCode, codex, opencode, copilotCli, geminiCli]\n\nexport function findHarness(id: string): Harness | undefined {\n return harnesses.find((harness) => harness.id === id)\n}\n\nexport function findHarnessByBinary(binary: string): Harness | undefined {\n return harnesses.find((harness) => harness.binary === binary)\n}\n","const LINE_BREAK = /\\r?\\n/\n\nexport function splitLines(text: string): string[] {\n return text.split(LINE_BREAK)\n}\n","import { match } from 'ts-pattern'\nimport type { EnvSyntax, Shell } from './env-syntax'\nimport { POSIX_ENV_SYNTAX } from './posix-env-syntax'\nimport { POWERSHELL_ENV_SYNTAX } from './powershell-env-syntax'\n\nexport const ENV_SYNTAXES: Readonly<Record<Shell, EnvSyntax>> = {\n posix: POSIX_ENV_SYNTAX,\n powershell: POWERSHELL_ENV_SYNTAX,\n}\n\nexport function resolveShell(platform: NodeJS.Platform): Shell {\n return match(platform)\n .returnType<Shell>()\n .with('win32', () => 'powershell')\n .otherwise(() => 'posix')\n}\n","import path from 'node:path'\nimport { escapePosixSingleQuoted } from '../../../../shared/file-formats/shell/escape-posix-single-quoted'\nimport { createAssignmentMatcher, ENV_DIRECTORY_NAME, formatHeaderLines, type EnvSyntax } from './env-syntax'\n\nconst POSIX_FILE_NAME = 'env'\nconst POSIX_ASSIGNMENT = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/\nconst POSIX_LOAD_COMMAND = `source ${path.posix.join('~', ENV_DIRECTORY_NAME, POSIX_FILE_NAME)}`\n\nexport const POSIX_ENV_SYNTAX: EnvSyntax = {\n fileName: POSIX_FILE_NAME,\n defaultLineEnding: '\\n',\n headerLines: formatHeaderLines(`# Load in your shell with: ${POSIX_LOAD_COMMAND}`),\n normalizeName: (name) => name,\n matchAssignment: createAssignmentMatcher(POSIX_ASSIGNMENT),\n formatAssignment: ({ name, value }) => `export ${name}=${quotePosixValue(value)}`,\n parseValue: parsePosixValue,\n loadCommand: POSIX_LOAD_COMMAND,\n}\n\nconst SHELL_SAFE_VALUE = /^[A-Za-z0-9_./:@+-]*$/\n\nfunction quotePosixValue(value: string): string {\n if (SHELL_SAFE_VALUE.test(value)) return value\n return `'${escapePosixSingleQuoted(value)}'`\n}\n\nconst POSIX_WORD_SEGMENT = /'([^']*)'|\"((?:[^\"\\\\$`]|\\\\.)*)\"|\\\\(.)|([^\\s'\"\\\\$`;&|<>()]+)/gy\nconst DOUBLE_QUOTED_ESCAPE = /\\\\([$`\"\\\\])/g\nconst BLANK_OR_COMMENT = /^(?:\\s+(?:#.*)?)?$/\n\nfunction parsePosixValue(rawValue: string): string | undefined {\n const segments = [...rawValue.matchAll(POSIX_WORD_SEGMENT)]\n const wordLength = segments.reduce((length, segment) => length + segment[0].length, 0)\n if (!BLANK_OR_COMMENT.test(rawValue.slice(wordLength))) return undefined\n\n return segments.map(decodePosixSegment).join('')\n}\n\nfunction decodePosixSegment([, singleQuoted, doubleQuoted, escaped, bare]: RegExpExecArray): string {\n if (doubleQuoted !== undefined) return doubleQuoted.replace(DOUBLE_QUOTED_ESCAPE, '$1')\n return singleQuoted ?? escaped ?? bare ?? ''\n}\n","import type { LineEnding } from '../../../../shared/file-formats/detect-line-ending'\n\nexport const SHELLS = ['posix', 'powershell'] as const\n\nexport type Shell = (typeof SHELLS)[number]\n\nexport type Assignment = { name: string; rawValue: string }\n\nexport type EnvVariable = { name: string; value: string }\n\nexport interface EnvSyntax {\n readonly fileName: string\n readonly defaultLineEnding: LineEnding\n readonly headerLines: readonly string[]\n normalizeName(name: string): string\n matchAssignment(line: string): Assignment | undefined\n formatAssignment(variable: EnvVariable): string\n parseValue(rawValue: string): string | undefined\n readonly loadCommand: string\n}\n\nexport const ENV_DIRECTORY_NAME = '.nexos'\n\nconst MANAGED_HEADER_LINE = '# nexos.ai Gateway — managed by nexos-connect.'\nconst PRESERVED_HEADER_LINES = [\n '# Hand-added entries are preserved; re-running nexos-connect updates the',\n '# variables it owns and leaves everything else alone.',\n] as const\n\n/** Re-renders recognise a header by these exact lines, so rewording one orphans it in every existing file. */\nexport function formatHeaderLines(loadInstruction: string): readonly string[] {\n return [MANAGED_HEADER_LINE, loadInstruction, ...PRESERVED_HEADER_LINES]\n}\n\nexport function createAssignmentMatcher(pattern: RegExp): EnvSyntax['matchAssignment'] {\n return (line) => {\n const [, name, rawValue] = pattern.exec(line) ?? []\n if (name === undefined || rawValue === undefined) return undefined\n return { name, rawValue }\n }\n}\n","import path from 'node:path'\nimport {\n escapePowerShellSingleQuoted,\n POWERSHELL_SINGLE_QUOTES as SINGLE_QUOTES,\n} from '../../../../shared/file-formats/shell/escape-powershell-single-quoted'\nimport { createAssignmentMatcher, ENV_DIRECTORY_NAME, formatHeaderLines, type EnvSyntax } from './env-syntax'\n\nconst POWERSHELL_FILE_NAME = 'env.ps1'\nconst POWERSHELL_ASSIGNMENT = /^\\s*\\$\\{?[Ee][Nn][Vv]:([A-Za-z_][A-Za-z0-9_]*)\\}?\\s*=\\s*(.*)$/\n\n// `$HOME`, not `~`: PowerShell resolves `~` against the current provider's home, which may not be the user's.\nconst POWERSHELL_LOAD_COMMAND = `. \"${path.win32.join('$HOME', ENV_DIRECTORY_NAME, POWERSHELL_FILE_NAME)}\"`\n\nexport const POWERSHELL_ENV_SYNTAX: EnvSyntax = {\n fileName: POWERSHELL_FILE_NAME,\n defaultLineEnding: '\\r\\n',\n headerLines: formatHeaderLines(`# Load in your PowerShell session with: ${POWERSHELL_LOAD_COMMAND}`),\n normalizeName: (name) => name.toUpperCase(),\n matchAssignment: createAssignmentMatcher(POWERSHELL_ASSIGNMENT),\n // Always quoted: a bare `https://…` is a parse error in PowerShell, and single quotes stop interpolation.\n formatAssignment: ({ name, value }) => `$env:${name} = '${escapePowerShellSingleQuoted(value)}'`,\n parseValue: parsePowerShellValue,\n loadCommand: POWERSHELL_LOAD_COMMAND,\n}\n\nconst TRAILING_COMMENT = String.raw`\\s*(?:#.*)?$`\nconst SINGLE_QUOTED_VALUE = new RegExp(\n `^[${SINGLE_QUOTES}]((?:[^${SINGLE_QUOTES}]|[${SINGLE_QUOTES}]{2})*)[${SINGLE_QUOTES}]${TRAILING_COMMENT}`,\n)\nconst ESCAPED_SINGLE_QUOTE = new RegExp(`[${SINGLE_QUOTES}]([${SINGLE_QUOTES}])`, 'g')\nconst DOUBLE_QUOTED_VALUE = new RegExp(`^\"((?:[^\"$\\`]|\"\")*)\"${TRAILING_COMMENT}`)\nconst ESCAPED_DOUBLE_QUOTE = /\"\"/g\n\nfunction parsePowerShellValue(rawValue: string): string | undefined {\n const [, singleQuoted] = SINGLE_QUOTED_VALUE.exec(rawValue) ?? []\n if (singleQuoted !== undefined) return singleQuoted.replace(ESCAPED_SINGLE_QUOTE, '$1')\n\n const [, doubleQuoted] = DOUBLE_QUOTED_VALUE.exec(rawValue) ?? []\n return doubleQuoted?.replace(ESCAPED_DOUBLE_QUOTE, '\"')\n}\n","import { splitLines } from './split-lines'\nimport type { Shell } from './syntax/env-syntax'\nimport { ENV_SYNTAXES } from './syntax/env-syntaxes'\n\nexport function parseEnvFile(text: string, shell: Shell): Map<string, string> {\n const syntax = ENV_SYNTAXES[shell]\n const values = new Map<string, string>()\n\n for (const line of splitLines(text)) {\n const assignment = syntax.matchAssignment(line)\n if (assignment === undefined) continue\n\n const name = syntax.normalizeName(assignment.name)\n const value = syntax.parseValue(assignment.rawValue)\n if (value === undefined) values.delete(name)\n else values.set(name, value)\n }\n\n return values\n}\n","import * as v from 'valibot'\nimport { COMMAND_NAME } from '../../cli/help'\nimport { FORGET_KEY_COMMAND } from '../../cli/parse-cli-arguments'\nimport { UsageError } from '../../cli/usage-error'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport { KEY_PREFIXES, hasKnownKeyPrefix } from '../../product/secrets/key-prefix'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { Availability, Keystore } from '../../product/storage/keychain/keystore'\nimport { describeError } from '../../shared/text/describe-error'\nimport { hasLineBreak } from '../../shared/text/has-line-break'\nimport { CancelledError } from '../../ui/cancelled-error'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport type { ExistingKeys } from './find-existing-keys'\n\nexport type KeySource = 'flag' | 'env' | 'saved' | 'pasted' | 'kept'\n\nexport type ResolvedKey = { key: string; source: KeySource; shouldSave: boolean }\n\nexport type CheckOutcome = 'passed' | 'failed' | 'skipped'\n\nexport type KeyStepInput = {\n flagKey: string | undefined\n envKey: string | undefined\n shouldSaveKey: boolean\n shouldAssumeYes: boolean\n isDryRun: boolean\n existingKeys(): ExistingKeys\n destination: string\n}\n\nexport type KeyStepDeps = { keystore: Keystore; ui: TerminalUi; masker: Masker }\n\nexport type KeyStepRun = { input: KeyStepInput; deps: KeyStepDeps; resolved: ResolvedKey }\n\nexport async function resolveKey(input: KeyStepInput, deps: KeyStepDeps): Promise<ResolvedKey> {\n const { keystore, ui } = deps\n\n if (input.shouldSaveKey) {\n const availability = await keystore.availability()\n if (availability.kind === 'unavailable') throw new UsageError(`--save-key can't be used: ${availability.reason}.`)\n }\n if (input.flagKey !== undefined) return { key: input.flagKey, source: 'flag', shouldSave: input.shouldSaveKey }\n if (input.envKey !== undefined) return { key: input.envKey, source: 'env', shouldSave: input.shouldSaveKey }\n\n const availability = await keystore.availability()\n const saved = availability.kind === 'available' ? await loadSaved(deps) : undefined\n\n if (saved !== undefined) {\n deps.masker.registerSecrets([saved])\n if (input.shouldAssumeYes || (await ui.chooseSavedKey(deps.masker.maskText(saved))) === 'use') {\n return { key: saved, source: 'saved', shouldSave: false }\n }\n const key = await ui.askForNewKey()\n return await finishKey({ input, deps, availability, answer: { kind: 'pasted', key }, isReplacingSavedKey: true })\n }\n\n const existing = input.existingKeys()\n if (input.shouldAssumeYes && existing.offered !== undefined) {\n return { key: existing.offered, source: 'kept', shouldSave: false }\n }\n return await promptForKey({ input, deps, availability, existing: existing.offered })\n}\n\nconst SavedKeySchema = v.pipe(\n v.string(),\n v.trim(),\n v.nonEmpty(),\n v.check((key) => !hasLineBreak(key)),\n)\n\nconst FORGET_KEY_HINT = `npx ${COMMAND_NAME} ${FORGET_KEY_COMMAND}`\n\nasync function loadSaved({ keystore, ui, masker }: KeyStepDeps): Promise<string | undefined> {\n let saved: string | undefined\n try {\n saved = await keystore.load()\n } catch (error) {\n ui.dim(\n masker.maskText(\n `Could not read the saved key from your system keychain: ${describeError(error)}. ` +\n `Run \\`${FORGET_KEY_HINT}\\` if this keeps happening.`,\n ),\n )\n return undefined\n }\n if (saved === undefined) return undefined\n\n const parsed = v.safeParse(SavedKeySchema, saved)\n if (!parsed.success) {\n ui.dim(`The saved key is not usable. Run \\`${FORGET_KEY_HINT}\\` and save it again.`)\n return undefined\n }\n return parsed.output\n}\n\ntype PromptForKeyParams = {\n input: KeyStepInput\n deps: KeyStepDeps\n availability: Availability\n existing: string | undefined\n}\n\nasync function promptForKey(params: PromptForKeyParams): Promise<ResolvedKey> {\n return await finishKey({ ...params, answer: await askExistingOrNew(params), isReplacingSavedKey: false })\n}\n\ntype FinishKeyParams = {\n input: KeyStepInput\n deps: KeyStepDeps\n availability: Availability\n answer: KeyAnswer\n isReplacingSavedKey: boolean\n}\n\nasync function finishKey({\n input,\n deps,\n availability,\n answer,\n isReplacingSavedKey,\n}: FinishKeyParams): Promise<ResolvedKey> {\n if (hasLineBreak(answer.key)) throw new UsageError('The pasted key contains a line break. Paste it on one line.')\n\n return {\n key: answer.key,\n source: answer.kind,\n shouldSave: await askToSave({ input, availability, ui: deps.ui, isReplacingSavedKey }),\n }\n}\n\ntype KeyAnswer = { kind: 'kept' | 'pasted'; key: string }\n\ntype AskExistingOrNewParams = { input: KeyStepInput; deps: KeyStepDeps; existing: string | undefined }\n\nasync function askExistingOrNew({ input, deps, existing }: AskExistingOrNewParams): Promise<KeyAnswer> {\n const { ui, masker } = deps\n if (existing === undefined) return { kind: 'pasted', key: await ui.askForKey({ destination: input.destination }) }\n\n masker.registerSecrets([existing])\n const answer = await ui.askToKeepOrReplaceKey({\n destination: input.destination,\n maskedExistingKey: masker.maskText(existing),\n })\n return answer.kind === 'kept' ? { kind: 'kept', key: existing } : { kind: 'pasted', key: answer.key }\n}\n\ntype AskToSaveParams = {\n input: KeyStepInput\n availability: Availability\n ui: TerminalUi\n isReplacingSavedKey: boolean\n}\n\n/** Default No, and never under `--yes`: saving must always be an explicit choice. */\nasync function askToSave({ input, availability, ui, isReplacingSavedKey }: AskToSaveParams): Promise<boolean> {\n if (input.shouldSaveKey) return true\n // A dry run writes nothing, so its answer cannot matter: do not ask.\n if (input.isDryRun) return false\n if (availability.kind === 'unavailable') {\n ui.dim(`${availability.reason} — the key will not be saved.`)\n return false\n }\n if (input.shouldAssumeYes) return false\n\n const question = isReplacingSavedKey\n ? 'Replace the key saved in your system keychain with this one?'\n : 'Save this key in your system keychain for future runs?'\n\n return await ui.confirm(question, false)\n}\n\nexport function isKeyUsable(key: string): boolean {\n return key.trim() !== ''\n}\n\n/** Warns about an unexpected shape and registers the key, so every later message masks it. */\nexport function adoptKey(key: string, { ui, masker }: { ui: TerminalUi; masker: Masker }): void {\n const warning = findKeyShapeWarning(key)\n if (warning !== undefined) ui.log.warn(warning)\n masker.registerSecrets([key])\n}\n\nexport function findKeyShapeWarning(key: string): string | undefined {\n if (hasKnownKeyPrefix(key)) return undefined\n\n const prefixes = KEY_PREFIXES.map((prefix) => `\"${prefix}\"`).join(' or ')\n return `That key does not look like a nexos.ai key (expected a ${prefixes} prefix). Continuing anyway.`\n}\n\n/** A key that failed the check is never saved, even when the run continues. */\nexport async function commitSave(\n resolved: ResolvedKey,\n check: CheckOutcome,\n { keystore, ui, masker }: KeyStepDeps,\n): Promise<void> {\n if (!resolved.shouldSave) return\n if (check === 'failed') {\n ui.log.warn('The key failed the check, so it was not saved to your system keychain.')\n return\n }\n\n try {\n await keystore.save(resolved.key)\n ui.log.success('Saved the key to your system keychain.')\n } catch (error) {\n ui.log.warn(masker.maskText(`Couldn't save the key to your system keychain: ${describeError(error)}`))\n }\n}\n\nexport function isSavedKeyRejection(resolved: ResolvedKey, probe: ProbeResult): boolean {\n return resolved.source === 'saved' && probe.kind === 'key-rejected'\n}\n\nexport type ReplaceRejectedKeyParams = {\n input: KeyStepInput\n rejected: ResolvedKey\n probe: ProbeResult\n deps: KeyStepDeps\n}\n\n/** A rejected saved key fails the same way on every retry, so it is replaced rather than retried. */\nexport async function replaceRejectedKey({\n input,\n rejected,\n probe,\n deps,\n}: ReplaceRejectedKeyParams): Promise<ResolvedKey | null> {\n const { keystore, ui, masker } = deps\n const status = probe.status ?? 0\n\n if (input.shouldAssumeYes) {\n ui.log.error(`The saved key was rejected (HTTP ${status}).`)\n ui.log.info(`Run \\`${FORGET_KEY_HINT}\\`, or pass --key.`)\n return null\n }\n\n ui.log.warn(`The gateway rejected the saved key (HTTP ${status}).`)\n if ((await ui.chooseOnSavedKeyRejected(status)) === 'cancel') throw new CancelledError()\n\n if (input.isDryRun) {\n ui.dim('Dry run — the saved key was not removed.')\n } else {\n try {\n await keystore.clear()\n } catch (error) {\n ui.log.warn(\n masker.maskText(\n `Could not remove the saved key: ${describeError(error)}. It is still saved; ` +\n `run \\`${FORGET_KEY_HINT}\\`.`,\n ),\n )\n }\n }\n\n const existing = input.existingKeys().offered\n return await promptForKey({\n input,\n deps,\n availability: await keystore.availability(),\n existing: existing === rejected.key ? undefined : existing,\n })\n}\n","export const PROTOCOLS = ['anthropic', 'openai-chat', 'openai-responses'] as const\n\nexport type Protocol = (typeof PROTOCOLS)[number]\n\nexport const PROTOCOL_ENDPOINTS = {\n anthropic: 'messages',\n 'openai-chat': 'chat_completion',\n 'openai-responses': 'responses',\n} as const satisfies Record<Protocol, string>\n","import pc from 'picocolors'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport { INDENT } from './indent'\n\nexport function formatProbes(results: readonly ProbeResult[]): string[] {\n return [...formatHeading('Key check'), ...results.flatMap(formatProbe)]\n}\n\nconst SURFACE_COLUMN_WIDTH = 10\n\nfunction formatProbe(result: ProbeResult): string[] {\n const colour = result.kind === 'passed' ? pc.dim : pc.yellow\n const glyph = result.kind === 'passed' ? pc.green(GLYPHS.success) : pc.yellow(GLYPHS.warning)\n return [\n ` ${glyph} ${result.surface.padEnd(SURFACE_COLUMN_WIDTH)} ${pc.dim(result.endpoint)}`,\n `${INDENT}${colour(result.detail)}`,\n ]\n}\n","export const GLYPHS = {\n success: '✓',\n unchanged: '=',\n absent: '·',\n failure: '✗',\n warning: '!',\n next: '→',\n elided: '…',\n} as const\n","import pc from 'picocolors'\n\nexport function formatHeading(text: string): string[] {\n return ['', pc.bold(text)]\n}\n","export const INDENT = ' '\nexport const NESTED_INDENT = ' '\n\nexport type IndentLinesParams = { text: string; indent: string }\n\nexport function indentLines({ text, indent }: IndentLinesParams): string[] {\n const lines = text.endsWith('\\n') ? text.slice(0, -1).split('\\n') : text.split('\\n')\n return lines.map((line) => (line === '' ? '' : indent + line))\n}\n","import { match } from 'ts-pattern'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport { listModels } from '../../product/gateway/list-models'\nimport type { ModelInfo } from '../../product/gateway/model-schema'\nimport { DEFAULT_MODEL } from '../../product/gateway/models/predefined-models'\nimport { isKeyAccepted, type ProbeResult } from '../../product/gateway/probe-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatCount } from '../../shared/text/format-count'\nimport { formatProbes } from '../../ui/report/format-probes'\nimport type { Spinner } from '../../ui/spinner'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { isSavedKeyRejection, type CheckOutcome, type ResolvedKey } from './key-step'\nimport { PROBE_SUMMARIES } from './probe-summaries'\n\nexport type KeyCheck = {\n probes: ProbeResult[]\n models: ModelInfo[]\n decidedModel: string | undefined\n resolvedKey: ResolvedKey\n outcome: CheckOutcome\n isAborted: boolean\n}\n\nexport function skippedKeyCheck(resolvedKey: ResolvedKey): KeyCheck {\n return { probes: [], models: [], decidedModel: undefined, resolvedKey, outcome: 'skipped', isAborted: false }\n}\n\nexport type CheckKeyParams = {\n openaiBaseUrl: string\n requestedModel: string | undefined\n shouldAssumeYes: boolean\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n resolved: ResolvedKey\n onSavedKeyRejected?(rejected: ResolvedKey, probe: ProbeResult): Promise<ResolvedKey | null>\n}\n\nexport async function checkKey(params: CheckKeyParams): Promise<KeyCheck> {\n const spinner = params.ui.spinner()\n spinner.start('Checking the key and fetching the model list…')\n return await attemptKeyCheck({ ...params, spinner })\n}\n\ntype AttemptKeyCheckParams = CheckKeyParams & { spinner: Spinner }\n\nasync function attemptKeyCheck(params: AttemptKeyCheckParams): Promise<KeyCheck> {\n const { openaiBaseUrl, masker, fetch, spinner, ui, resolved } = params\n const { probe, models } = await spinner.waitFor((signal) =>\n listModels({ openaiBaseUrl, apiKey: resolved.key, masker, fetch, signal }),\n )\n spinner.stop(summarizeKeyCheck(probe, models.length))\n if (isKeyAccepted(probe)) {\n return {\n probes: [probe],\n models,\n decidedModel: undefined,\n resolvedKey: resolved,\n outcome: 'passed',\n isAborted: false,\n }\n }\n\n if (isSavedKeyRejection(resolved, probe) && params.onSavedKeyRejected !== undefined) {\n const replaced = await params.onSavedKeyRejected(resolved, probe)\n if (replaced === null) {\n return {\n probes: [],\n models: [],\n decidedModel: undefined,\n resolvedKey: resolved,\n outcome: 'failed',\n isAborted: true,\n }\n }\n spinner.start('Checking the new key…')\n return await attemptKeyCheck({ ...params, resolved: replaced })\n }\n\n const continuation = findContinuation(params)\n if (continuation !== undefined) {\n ui.log.warn(continuation)\n return {\n probes: [probe],\n models: [],\n decidedModel: undefined,\n resolvedKey: resolved,\n outcome: 'failed',\n isAborted: false,\n }\n }\n\n ui.print(formatProbes([probe]))\n const choice = await ui.chooseOnFetchFailure()\n return await match(choice)\n .with('retry', async () => {\n spinner.start('Checking again…')\n return await attemptKeyCheck(params)\n })\n .with('manual', async () => ({\n probes: [],\n models: [],\n decidedModel: await ui.askForModelId(),\n resolvedKey: resolved,\n outcome: 'failed' as const,\n isAborted: false,\n }))\n .with('default', async () => ({\n probes: [],\n models: [],\n decidedModel: DEFAULT_MODEL,\n resolvedKey: resolved,\n outcome: 'failed' as const,\n isAborted: false,\n }))\n .exhaustive()\n}\n\nfunction summarizeKeyCheck(probe: ProbeResult, modelCount: number): string {\n return match(probe.kind)\n .with('passed', () => `Key verified — ${formatCount(modelCount, 'model')} available.`)\n .with('bad-response', () => 'Key verified, but the model list could not be read.')\n .otherwise((kind) => PROBE_SUMMARIES[kind])\n}\n\nexport const ASSUMED_YES_CONTINUATION = 'Continuing despite the failed check (--yes).'\n\nfunction findContinuation({ shouldAssumeYes, requestedModel, masker }: CheckKeyParams): string | undefined {\n if (shouldAssumeYes) return ASSUMED_YES_CONTINUATION\n if (requestedModel === undefined) return undefined\n\n return masker.maskText(`Continuing despite the failed check — \"${requestedModel}\" was named explicitly.`)\n}\n","import { P, match } from 'ts-pattern'\nimport { formatCount } from '../../shared/text/format-count'\nimport type { Masker } from '../secrets/masker'\nimport { describeGatewayFailure, formatHttpFailure, isGatewayFailure } from './gateway-errors'\nimport {\n GATEWAY_TIMEOUT_MS,\n KEY_REJECTED_STATUSES,\n isSuccessStatus,\n requestGateway,\n trimTrailingSlashes,\n type Fetch,\n type GatewayResponse,\n} from './gateway-request'\nimport { ModelListSchema, OpenAiErrorSchema, parseJsonBody, type ModelInfo } from './model-schema'\nimport type { ProbeKind, ProbeResult } from './probe-result'\n\nexport type ListModelsResult = {\n probe: ProbeResult\n models: ModelInfo[]\n}\n\nexport type ListModelsParams = {\n openaiBaseUrl: string\n apiKey: string\n masker: Masker\n fetch: Fetch\n signal?: AbortSignal\n}\n\nconst MODELS_PATH = '/models'\nconst BEARER_PREFIX = 'Bearer '\n\nexport async function listModels({\n openaiBaseUrl,\n apiKey,\n masker,\n fetch,\n signal,\n}: ListModelsParams): Promise<ListModelsResult> {\n const endpoint = `${trimTrailingSlashes(openaiBaseUrl)}${MODELS_PATH}`\n const probe = (kind: ProbeKind, detail: string, status: number | undefined): ProbeResult => ({\n kind,\n surface: 'gateway',\n endpoint,\n detail,\n ...(status === undefined ? {} : { status }),\n })\n\n try {\n const response = await requestGateway({\n url: endpoint,\n init: { method: 'GET', headers: { authorization: `${BEARER_PREFIX}${apiKey}` } },\n fetch,\n timeoutMs: GATEWAY_TIMEOUT_MS,\n signal,\n })\n const { kind, detail, models, status } = readListing(response, masker)\n return { probe: probe(kind, detail, status), models }\n } catch (error) {\n if (!isGatewayFailure(error)) throw error\n return { probe: probe(error.kind, describeGatewayFailure(error, masker), undefined), models: [] }\n }\n}\n\ntype Listing = { kind: ProbeKind; detail: string; models: ModelInfo[]; status: number }\n\nfunction readListing({ status, text }: GatewayResponse, masker: Masker): Listing {\n if (!isSuccessStatus(status)) {\n const rejection = parseJsonBody(OpenAiErrorSchema, text)?.error\n const detail = formatHttpFailure(status, rejection?.message ?? text, masker)\n return { kind: classifyRejection(status, rejection?.code ?? undefined), detail, models: [], status }\n }\n\n const models = parseJsonBody(ModelListSchema, text)\n if (models === undefined) {\n const detail = `HTTP ${status} — authenticated, but the model list could not be read`\n return { kind: 'bad-response', detail, models: [], status }\n }\n const detail = `HTTP ${status} — authenticated, ${formatCount(models.length, 'model')} available`\n return { kind: 'passed', detail, models, status }\n}\n\nconst INVALID_KEY_ERROR_CODE = 'invalid_api_key'\n\ntype RejectionKind = Extract<ProbeKind, 'key-rejected' | 'bad-status'>\n\nfunction classifyRejection(status: number, errorCode: string | undefined): RejectionKind {\n return match({ status, errorCode })\n .returnType<RejectionKind>()\n .with({ status: P.union(...KEY_REJECTED_STATUSES) }, { errorCode: INVALID_KEY_ERROR_CODE }, () => 'key-rejected')\n .otherwise(() => 'bad-status')\n}\n","export function formatCount(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`\n}\n","import * as v from 'valibot'\n\nconst OptionalTextSchema = v.fallback(v.optional(v.pipe(v.string(), v.nonEmpty())), undefined)\nconst OptionalCountSchema = v.fallback(v.optional(v.pipe(v.number(), v.finite())), undefined)\nconst EndpointsSchema = v.fallback(v.pipe(v.array(v.unknown()), v.transform(keepStrings)), [])\n\nconst ModelSchema = v.pipe(\n v.object({\n id: v.pipe(v.string(), v.nonEmpty()),\n developer: OptionalTextSchema,\n owned_by: OptionalTextSchema,\n context_length: OptionalCountSchema,\n region: OptionalTextSchema,\n endpoints: EndpointsSchema,\n }),\n v.transform((entry) => ({\n id: entry.id,\n developer: entry.developer ?? entry.owned_by ?? null,\n contextLength: entry.context_length ?? null,\n region: entry.region ?? null,\n endpoints: entry.endpoints,\n })),\n)\n\nexport type ModelInfo = v.InferOutput<typeof ModelSchema>\n\nexport const ModelListSchema = v.pipe(\n v.object({ data: v.array(v.unknown()) }),\n v.transform(({ data }) => keepUsableModels(data)),\n)\n\nexport const OpenAiErrorSchema = v.object({\n error: v.object({\n message: v.string(),\n type: v.optional(v.string()),\n code: v.optional(v.nullable(v.string())),\n }),\n})\n\nexport const AnthropicErrorSchema = v.object({\n type: v.literal('error'),\n error: v.object({ type: v.string(), message: v.string() }),\n})\n\nexport function parseJsonBody<TSchema extends v.GenericSchema>(\n schema: TSchema,\n text: string,\n): v.InferOutput<TSchema> | undefined {\n const result = v.safeParse(schema, parseJson(text))\n return result.success ? result.output : undefined\n}\n\nfunction keepStrings(values: unknown[]): string[] {\n return values.filter((value) => typeof value === 'string')\n}\n\nfunction keepUsableModels(entries: unknown[]): ModelInfo[] {\n const modelsById = new Map<string, ModelInfo>()\n for (const entry of entries) {\n const model = v.safeParse(ModelSchema, entry)\n if (model.success && !modelsById.has(model.output.id)) modelsById.set(model.output.id, model.output)\n }\n return [...modelsById.values()]\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n","import { match } from 'ts-pattern'\n\nexport type ProbeSurface = 'gateway' | 'anthropic'\n\nexport type ProbeKind =\n | 'passed'\n | 'key-rejected'\n | 'model-rejected'\n | 'unreachable'\n | 'timed-out'\n | 'bad-status'\n | 'bad-response'\n\nexport type ProbeResult = {\n kind: ProbeKind\n surface: ProbeSurface\n endpoint: string\n detail: string\n /** The HTTP status, when there was a response; absent for a network failure or a timeout. */\n status?: number\n}\n\nexport function isKeyAccepted(probe: ProbeResult): boolean {\n return match(probe.kind)\n .with('passed', 'bad-response', () => true)\n .with('key-rejected', 'model-rejected', 'unreachable', 'timed-out', 'bad-status', () => false)\n .exhaustive()\n}\n","import type { ProbeKind } from '../../product/gateway/probe-result'\n\nexport const PROBE_SUMMARIES: Readonly<Record<ProbeKind, string>> = {\n passed: 'The check passed.',\n 'key-rejected': 'The gateway rejected the key.',\n 'model-rejected': 'The gateway rejected the model.',\n unreachable: 'Could not reach the gateway.',\n 'timed-out': 'The gateway did not answer in time.',\n 'bad-status': 'The gateway answered with an error.',\n 'bad-response': 'The gateway answered, but its reply could not be read.',\n}\n","import type { ModelInfo } from '../model-schema'\nimport { PROTOCOL_ENDPOINTS, type Protocol } from './protocol'\n\nexport function isModelCompatible(model: ModelInfo, protocols: readonly Protocol[]): boolean {\n return findUnservedProtocols(model, protocols).length === 0\n}\n\nexport function findUnservedProtocols(model: ModelInfo, protocols: readonly Protocol[]): Protocol[] {\n if (model.endpoints.length === 0) return []\n return protocols.filter((protocol) => !model.endpoints.includes(PROTOCOL_ENDPOINTS[protocol]))\n}\n","import type { ModelInfo } from '../product/gateway/model-schema'\nimport { isModelCompatible } from '../product/gateway/models/model-compatibility'\nimport { PREDEFINED_MODELS } from '../product/gateway/models/predefined-models'\nimport type { Protocol } from '../product/gateway/models/protocol'\n\nexport const BROWSE_VALUE = '\\u0000browse'\nexport const MANUAL_VALUE = '\\u0000manual'\n\nexport type ModelChoice = { value: string; label: string; hint?: string }\n\nexport type ModelChoices = {\n rows: ModelChoice[]\n browsable: ModelInfo[]\n hiddenCount: number\n isRouterOffered: boolean\n}\n\nconst MANUAL_ROW: ModelChoice = {\n value: MANUAL_VALUE,\n label: 'Type a model id…',\n hint: 'no model list available',\n}\n\nexport function buildModelChoices(\n models: readonly ModelInfo[],\n protocols: readonly Protocol[],\n isRouterOffered: boolean,\n): ModelChoices {\n const compatible = models.filter((model) => isModelCompatible(model, protocols))\n const usable = compatible.length > 0 ? compatible : models\n const browsable = [...usable].sort((first, second) => first.id.localeCompare(second.id))\n const hiddenCount = models.length - usable.length\n\n const routerRows = isRouterOffered ? PREDEFINED_MODELS.map(({ id, hint }) => ({ value: id, label: id, hint })) : []\n const lastRow = models.length > 0 ? buildBrowseRow(browsable.length) : MANUAL_ROW\n return { rows: [...routerRows, lastRow], browsable, hiddenCount, isRouterOffered }\n}\n\nexport type ModelSuggestion = { model: string; hint: string }\n\n/** The router rows lead, and the browse or manual row stays last. */\nexport function addSuggestionRows(choices: ModelChoices, suggestions: readonly ModelSuggestion[]): ModelChoices {\n const suggestionRows = suggestions.map(({ model, hint }) => ({ value: model, label: model, hint }))\n const { rows } = choices\n return { ...choices, rows: [...rows.slice(0, -1), ...suggestionRows, ...rows.slice(-1)] }\n}\n\nfunction buildBrowseRow(availableCount: number): ModelChoice {\n return { value: BROWSE_VALUE, label: 'Choose from available models…', hint: `${availableCount} available` }\n}\n\nexport function formatModelHint(model: ModelInfo): string {\n const context = model.contextLength === null ? null : `${formatContextLength(model.contextLength)} context`\n return [model.developer, context, model.region].filter((part) => part !== null).join(' · ')\n}\n\nconst THOUSAND = 1_000\nconst MILLION = 1_000_000\nconst MILLION_DECIMAL_PLACES = 1\n\nexport function formatContextLength(tokens: number): string {\n if (tokens < THOUSAND) return String(tokens)\n\n const thousands = Math.round(tokens / THOUSAND)\n if (thousands < THOUSAND) return `${thousands}k`\n\n return `${Number((tokens / MILLION).toFixed(MILLION_DECIMAL_PLACES))}M`\n}\n","import { MODEL_ENV_VARIABLE } from '../../cli/environment'\nimport { UsageError } from '../../cli/usage-error'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport type { ModelInfo } from '../../product/gateway/model-schema'\nimport { findUnservedProtocols } from '../../product/gateway/models/model-compatibility'\nimport { DEFAULT_MODEL, isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport { PROTOCOL_ENDPOINTS, type Protocol } from '../../product/gateway/models/protocol'\nimport type { RouterAvailability } from '../../product/gateway/models/router-availability'\nimport { addSuggestionRows, buildModelChoices, type ModelSuggestion } from '../../ui/model-choices'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport type { KeyCheck } from '../key/key-check'\n\nexport const UNAVAILABLE_ROUTER_REFUSAL = `${DEFAULT_MODEL} is not available for this key. Pass --model, or set $${MODEL_ENV_VARIABLE}.`\n\nexport type ChooseModelParams = {\n keyCheck: KeyCheck\n requestedModel: string | undefined\n routerAvailability: RouterAvailability\n shouldAssumeYes: boolean\n protocols: readonly Protocol[]\n suggestions: readonly ModelSuggestion[]\n ui: TerminalUi\n}\n\nexport async function chooseModel({\n keyCheck,\n requestedModel,\n routerAvailability,\n shouldAssumeYes,\n protocols,\n suggestions,\n ui,\n}: ChooseModelParams): Promise<string> {\n if (keyCheck.decidedModel !== undefined) return keyCheck.decidedModel\n if (requestedModel !== undefined) return requestedModel\n\n const isRouterOffered = routerAvailability === 'available'\n if (shouldAssumeYes) {\n if (routerAvailability === 'unavailable') throw new UsageError(UNAVAILABLE_ROUTER_REFUSAL)\n if (!isRouterOffered) {\n ui.log.warn(`Could not confirm that ${DEFAULT_MODEL} is available. Continuing anyway (--yes).`)\n }\n return DEFAULT_MODEL\n }\n\n return await ui.selectModel(\n addSuggestionRows(buildModelChoices(keyCheck.models, protocols, isRouterOffered), suggestions),\n )\n}\n\nexport type FindModelWarningsParams = {\n model: string\n models: readonly ModelInfo[]\n configurable: readonly ConfigurableHarness[]\n routerAvailability: RouterAvailability\n}\n\nexport function findModelWarnings({\n model,\n models,\n configurable,\n routerAvailability,\n}: FindModelWarningsParams): string[] {\n if (isPredefinedModel(model)) {\n return routerAvailability === 'unavailable'\n ? [`\"${model}\" is not available for this key. Continuing because you named it.`]\n : []\n }\n if (models.length === 0) return []\n\n const listed = models.find((candidate) => candidate.id === model)\n if (listed === undefined) {\n return [`\"${model}\" is not in the list this key can see. Continuing — the gateway may still accept it.`]\n }\n\n return configurable.flatMap((harness) => {\n const unserved = findUnservedProtocols(listed, harness.protocols)\n if (unserved.length === 0) return []\n\n const endpoints = unserved.map((protocol) => PROTOCOL_ENDPOINTS[protocol]).join(', ')\n return [`${harness.label}: \"${model}\" does not advertise ${endpoints}. It may still work.`]\n })\n}\n","import { match } from 'ts-pattern'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport { DEFAULT_MODEL } from '../../product/gateway/models/predefined-models'\nimport { classifyRouterAvailability, type RouterAvailability } from '../../product/gateway/models/router-availability'\nimport { probeAnthropic } from '../../product/gateway/probe-anthropic'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { ASSUMED_YES_CONTINUATION } from '../key/key-check'\nimport { PROBE_SUMMARIES } from '../key/probe-summaries'\n\nexport type ProbeModelParams = {\n anthropicBaseUrl: string\n key: string\n model: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\nexport async function probeModel(params: ProbeModelParams): Promise<ProbeResult> {\n const { anthropicBaseUrl, key, model, ui, masker, fetch } = params\n const spinner = ui.spinner()\n spinner.start(masker.maskText(`Checking \"${model}\" against the gateway…`))\n const probe = await spinner.waitFor((signal) =>\n probeAnthropic({ anthropicBaseUrl, apiKey: key, model, masker, fetch, signal }),\n )\n spinner.stop(summarizeModelProbe(probe))\n return probe\n}\n\nexport type RouterProbe = { availability: RouterAvailability; probe: ProbeResult }\n\nexport type ProbeRouterParams = {\n anthropicBaseUrl: string\n key: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\n/** Silent on purpose: its result only decides which rows the picker offers. */\nexport async function probeRouter({\n anthropicBaseUrl,\n key,\n ui,\n masker,\n fetch,\n}: ProbeRouterParams): Promise<RouterProbe> {\n const probe = await ui\n .spinner()\n .waitQuietly((signal) =>\n probeAnthropic({ anthropicBaseUrl, apiKey: key, model: DEFAULT_MODEL, masker, fetch, signal }),\n )\n return { availability: classifyRouterAvailability(probe), probe }\n}\n\nexport type ShouldContinueAfterProbeParams = {\n probe: ProbeResult\n shouldAssumeYes: boolean\n consequence: string\n ui: TerminalUi\n}\n\nexport async function shouldContinueAfterProbe({\n probe,\n shouldAssumeYes,\n consequence,\n ui,\n}: ShouldContinueAfterProbeParams): Promise<boolean> {\n if (probe.kind === 'passed') return true\n if (shouldAssumeYes) {\n ui.log.warn(ASSUMED_YES_CONTINUATION)\n return true\n }\n\n return await ui.confirm(`Continue anyway? ${consequence}`, false)\n}\n\nfunction summarizeModelProbe(probe: ProbeResult): string {\n return match(probe.kind)\n .with('passed', () => 'Model verified.')\n .otherwise((kind) => PROBE_SUMMARIES[kind])\n}\n","import { match } from 'ts-pattern'\nimport type { ProbeResult } from '../probe-result'\n\nexport const ROUTER_AVAILABILITY = ['available', 'unavailable', 'unknown'] as const\n\nexport type RouterAvailability = (typeof ROUTER_AVAILABILITY)[number]\n\nexport function classifyRouterAvailability(probe: ProbeResult): RouterAvailability {\n return match(probe.kind)\n .returnType<RouterAvailability>()\n .with('passed', () => 'available')\n .with('model-rejected', () => 'unavailable')\n .otherwise(() => 'unknown')\n}\n","import { P, match } from 'ts-pattern'\nimport type { Masker } from '../secrets/masker'\nimport { describeGatewayFailure, formatHttpFailure, isGatewayFailure } from './gateway-errors'\nimport {\n GATEWAY_TIMEOUT_MS,\n KEY_REJECTED_STATUSES,\n isSuccessStatus,\n requestGateway,\n trimTrailingSlashes,\n type Fetch,\n} from './gateway-request'\nimport { AnthropicErrorSchema, parseJsonBody } from './model-schema'\nimport type { ProbeKind, ProbeResult } from './probe-result'\n\nexport type ProbeAnthropicParams = {\n anthropicBaseUrl: string\n apiKey: string\n model: string\n masker: Masker\n fetch: Fetch\n signal?: AbortSignal\n}\n\nconst MESSAGES_PATH = '/v1/messages'\nconst ANTHROPIC_VERSION = '2023-06-01'\nconst PING_MAX_TOKENS = 1\nconst PING_TEXT = 'ping'\n\nexport async function probeAnthropic({\n anthropicBaseUrl,\n apiKey,\n model,\n masker,\n fetch,\n signal,\n}: ProbeAnthropicParams): Promise<ProbeResult> {\n const endpoint = `${trimTrailingSlashes(anthropicBaseUrl)}${MESSAGES_PATH}`\n const probe = (kind: ProbeKind, detail: string, status: number | undefined): ProbeResult => ({\n kind,\n surface: 'anthropic',\n endpoint,\n detail,\n ...(status === undefined ? {} : { status }),\n })\n\n try {\n const response = await requestGateway({\n url: endpoint,\n init: {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': ANTHROPIC_VERSION,\n },\n body: JSON.stringify({\n model,\n max_tokens: PING_MAX_TOKENS,\n messages: [{ role: 'user', content: PING_TEXT }],\n }),\n },\n fetch,\n timeoutMs: GATEWAY_TIMEOUT_MS,\n signal,\n })\n if (isSuccessStatus(response.status)) {\n return probe('passed', `HTTP ${response.status} — authenticated`, response.status)\n }\n\n const rejection = parseJsonBody(AnthropicErrorSchema, response.text)?.error\n const detail = formatHttpFailure(response.status, rejection?.message ?? response.text, masker)\n return probe(classifyRejection(response.status, rejection?.type), detail, response.status)\n } catch (error) {\n if (!isGatewayFailure(error)) throw error\n return probe(error.kind, describeGatewayFailure(error, masker), undefined)\n }\n}\n\nconst MODEL_NOT_FOUND_STATUS = 404\nconst KEY_REJECTED_ERROR_TYPES = ['authentication_error', 'permission_error'] as const\nconst MODEL_NOT_FOUND_ERROR_TYPE = 'not_found_error'\n\ntype RejectionKind = Extract<ProbeKind, 'key-rejected' | 'model-rejected' | 'bad-status'>\n\nfunction classifyRejection(status: number, errorType: string | undefined): RejectionKind {\n return match({ status, errorType })\n .returnType<RejectionKind>()\n .with(\n { status: P.union(...KEY_REJECTED_STATUSES) },\n { errorType: P.union(...KEY_REJECTED_ERROR_TYPES) },\n () => 'key-rejected',\n )\n .with({ status: MODEL_NOT_FOUND_STATUS }, { errorType: MODEL_NOT_FOUND_ERROR_TYPE }, () => 'model-rejected')\n .otherwise(() => 'bad-status')\n}\n","import { randomUUID } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport * as v from 'valibot'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport { displayPath } from '../../../shared/text/display-path'\nimport { normalizeModel } from '../../gateway/models/predefined-models'\nimport { ENV_DIRECTORY_NAME } from '../env-file/syntax/env-syntax'\n\nconst PREFERENCES_FILE = 'preferences.json'\n\nexport function resolvePreferencesPath(home: string): string {\n return path.join(home, ENV_DIRECTORY_NAME, PREFERENCES_FILE)\n}\n\nconst ModelIdSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.transform(normalizeModel))\n\nconst PreferencesSchema = v.looseObject({\n defaultModels: v.optional(v.record(v.string(), ModelIdSchema), {}),\n})\n\ntype Preferences = v.InferOutput<typeof PreferencesSchema>\n\n/** Keyed by harness id. */\nexport type DefaultModels = Readonly<Record<string, string>>\n\nexport class PreferencesError extends Error {\n override readonly name = 'PreferencesError'\n}\n\nexport function readDefaultModels(home: string): DefaultModels {\n return readPreferences(home).defaultModels\n}\n\nexport type SaveDefaultModelsParams = { home: string; defaultModels: DefaultModels }\n\nconst JSON_INDENT = 2\n\nexport function saveDefaultModels({ home, defaultModels }: SaveDefaultModelsParams): void {\n const current = readPreferences(home)\n const next: Preferences = { ...current, defaultModels: { ...current.defaultModels, ...defaultModels } }\n writeAtomically(resolvePreferencesPath(home), `${JSON.stringify(next, null, JSON_INDENT)}\\n`)\n}\n\nfunction readPreferences(home: string): Preferences {\n const filePath = resolvePreferencesPath(home)\n const text = readFileIfExists(filePath)\n if (text === null) return { defaultModels: {} }\n\n const parsed = v.safeParse(PreferencesSchema, parseJson(text))\n if (!parsed.success) {\n throw new PreferencesError(\n `${displayPath(filePath, home)} is not a preferences file nexos-connect can read. Fix it or delete it.`,\n )\n }\n return parsed.output\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n if (error instanceof SyntaxError) return undefined\n throw error\n }\n}\n\n// Two runs may save at once; a rename never leaves the file half-written for the other to read.\nfunction writeAtomically(filePath: string, content: string): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n try {\n fs.writeFileSync(temporaryPath, content)\n fs.renameSync(temporaryPath, filePath)\n } catch (error) {\n fs.rmSync(temporaryPath, { force: true })\n throw error\n }\n}\n","import * as v from 'valibot'\nimport { describeError } from '../text/describe-error'\nimport { displayPath } from '../text/display-path'\nimport { Utf16FileError } from './utf16-file-error'\n\nexport type FileAction = 'read' | 'write'\n\nexport type DescribeFileErrorParams = { error: unknown; action: FileAction; home: string }\n\nexport function describeFileError({ error, action, home }: DescribeFileErrorParams): string {\n const failure = readFileFailure(error)\n if (failure === undefined) return describeError(error)\n\n return `${displayPath(failure.path, home)}: cannot ${action} it (${failure.reason}). ${failure.nextStep}, then run again.`\n}\n\ntype FileFailure = { path: string; reason: string; nextStep: string }\n\nconst FileSystemErrorSchema = v.object({ code: v.string(), path: v.string() })\n\nconst PERMISSION_CODES: readonly string[] = ['EACCES', 'EPERM', 'EROFS']\n\nfunction readFileFailure(error: unknown): FileFailure | undefined {\n if (error instanceof Utf16FileError) {\n return { path: error.filePath, reason: 'saved as UTF-16', nextStep: 'Re-save it as UTF-8' }\n }\n if (!v.is(FileSystemErrorSchema, error)) return undefined\n\n const nextStep = PERMISSION_CODES.includes(error.code) ? 'Check its permissions' : 'Check that path'\n return { path: error.path, reason: error.code, nextStep }\n}\n","import type { Harness } from '../../harnesses/harness'\nimport type { ModelInfo } from '../../product/gateway/model-schema'\nimport { isModelCompatible } from '../../product/gateway/models/model-compatibility'\nimport { isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport type { Protocol } from '../../product/gateway/models/protocol'\nimport type { DefaultModels } from '../../product/storage/preferences/preferences'\nimport type { ModelSuggestion } from '../../ui/model-choices'\n\n/** The distinct defaults of the agents being set up or started, each with the agents it belongs to. */\nexport function findOwnDefaults(defaultModels: DefaultModels, targets: readonly Harness[]): ModelSuggestion[] {\n return groupByModel(defaultModels, targets)\n}\n\nexport type FindBorrowedDefaultsParams = {\n defaultModels: DefaultModels\n targets: readonly Harness[]\n harnesses: readonly Harness[]\n models: readonly ModelInfo[]\n protocols: readonly Protocol[]\n}\n\n/**\n * Other agents' defaults, offered as picker rows. A router already has its row, an own default was\n * just turned down, and a model the list says the targets cannot use would only fail.\n */\nexport function findBorrowedDefaults(params: FindBorrowedDefaultsParams): ModelSuggestion[] {\n const { defaultModels, targets, models, protocols } = params\n const targetIds = new Set(targets.map((harness) => harness.id))\n const ownModels = new Set(targets.flatMap((harness) => defaultModels[harness.id] ?? []))\n const others = params.harnesses.filter((harness) => !targetIds.has(harness.id))\n\n return groupByModel(defaultModels, others).filter(\n ({ model }) => !ownModels.has(model) && !isPredefinedModel(model) && isServed({ model, models, protocols }),\n )\n}\n\ntype IsServedParams = { model: string; models: readonly ModelInfo[]; protocols: readonly Protocol[] }\n\nfunction isServed({ model, models, protocols }: IsServedParams): boolean {\n if (models.length === 0) return true\n\n const listed = models.find((candidate) => candidate.id === model)\n return listed !== undefined && isModelCompatible(listed, protocols)\n}\n\nfunction groupByModel(defaultModels: DefaultModels, harnesses: readonly Harness[]): ModelSuggestion[] {\n const labelsByModel = new Map<string, string[]>()\n for (const harness of harnesses) {\n const model = defaultModels[harness.id]\n if (model !== undefined) labelsByModel.set(model, [...(labelsByModel.get(model) ?? []), harness.label])\n }\n\n return [...labelsByModel].map(([model, labels]) => ({ model, hint: `default for ${labels.join(', ')}` }))\n}\n","import type { CliOptions } from '../../cli/parse-cli-arguments'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport { isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport type { Masker } from '../../product/secrets/masker'\nimport {\n PreferencesError,\n readDefaultModels,\n saveDefaultModels,\n type DefaultModels,\n} from '../../product/storage/preferences/preferences'\nimport { describeFileError, type FileAction } from '../../shared/file-system/describe-file-error'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { findOwnDefaults } from './suggest-defaults'\n\nexport type ModelSource = 'flag' | 'env' | 'default' | 'picked'\n\n/** `isReadable` is false for a file that could not be read: nothing is offered from it or saved over it. */\nexport type ModelPreferences = { defaultModels: DefaultModels; isReadable: boolean }\n\nexport function loadModelPreferences(home: string, ui: TerminalUi): ModelPreferences {\n try {\n return { defaultModels: readDefaultModels(home), isReadable: true }\n } catch (error) {\n ui.log.warn(\n `${describePreferencesError({ error, action: 'read', home })} ` +\n 'Default models are neither offered nor saved until then.',\n )\n return { defaultModels: {}, isReadable: false }\n }\n}\n\nexport type RequestModelParams = {\n flagModel: string | undefined\n envModel: string | undefined\n targets: readonly ConfigurableHarness[]\n preferences: ModelPreferences\n shouldAssumeYes: boolean\n ui: TerminalUi\n}\n\nexport type RequestedModel = { model: string; source: Exclude<ModelSource, 'picked'> }\n\n/** The model settled before the key check; undefined leaves it to the picker. */\nexport async function requestModel(params: RequestModelParams): Promise<RequestedModel | undefined> {\n const { targets, preferences, ui } = params\n if (params.flagModel !== undefined) return { model: params.flagModel, source: 'flag' }\n if (params.envModel !== undefined) return { model: params.envModel, source: 'env' }\n\n const ownDefaults = findOwnDefaults(preferences.defaultModels, targets).filter(\n ({ model }) => !isPredefinedModel(model),\n )\n if (ownDefaults.length === 0) return undefined\n if (params.shouldAssumeYes) {\n const shared = findSharedDefault(preferences.defaultModels, targets)\n return shared === undefined ? undefined : { model: shared, source: 'default' }\n }\n\n const chosen = await ui.chooseSavedModel(ownDefaults)\n return chosen === undefined ? undefined : { model: chosen, source: 'default' }\n}\n\n/** `--yes` never picks between defaults, nor borrows one for an agent that has none. */\nfunction findSharedDefault(defaultModels: DefaultModels, targets: readonly ConfigurableHarness[]): string | undefined {\n const [first, ...rest] = targets.map((harness) => defaultModels[harness.id])\n if (first === undefined || isPredefinedModel(first)) return undefined\n return rest.every((model) => model === first) ? first : undefined\n}\n\nexport type DecideModelSaveParams = {\n model: string\n source: ModelSource\n targets: readonly ConfigurableHarness[]\n preferences: ModelPreferences\n options: Pick<CliOptions, 'shouldSaveModel' | 'shouldAssumeYes' | 'isDryRun'>\n ui: TerminalUi\n}\n\n/** The agents to save the model for. Asked only after a pick, default No; `--save-model` says yes without asking. */\nexport async function decideModelSave(params: DecideModelSaveParams): Promise<ConfigurableHarness[]> {\n const { model, preferences, options, ui } = params\n if (!preferences.isReadable) return []\n if (isPredefinedModel(model)) return []\n\n const changed = params.targets.filter((harness) => preferences.defaultModels[harness.id] !== model)\n if (changed.length === 0) return []\n if (options.shouldSaveModel) return changed\n if (params.source !== 'picked' || options.shouldAssumeYes || options.isDryRun) return []\n\n const labels = changed.map((harness) => harness.label).join(', ')\n return (await ui.confirm(`Make ${model} your default for ${labels}?`, false)) ? changed : []\n}\n\nexport type CommitModelSaveParams = {\n model: string\n harnesses: readonly ConfigurableHarness[]\n home: string\n ui: TerminalUi\n masker: Masker\n}\n\n/** A default is a convenience: failing to save one warns and never fails the run. */\nexport function commitModelSave({ model, harnesses, home, ui, masker }: CommitModelSaveParams): void {\n if (harnesses.length === 0) return\n\n const labels = harnesses.map((harness) => harness.label).join(', ')\n try {\n saveDefaultModels({ home, defaultModels: Object.fromEntries(harnesses.map((harness) => [harness.id, model])) })\n ui.log.success(masker.maskText(`Saved ${model} as the default model for ${labels}.`))\n } catch (error) {\n const reason = describePreferencesError({ error, action: 'write', home })\n ui.log.warn(masker.maskText(`Couldn't save ${model} as the default model: ${reason}`))\n }\n}\n\ntype DescribePreferencesErrorParams = { error: unknown; action: FileAction; home: string }\n\nfunction describePreferencesError({ error, action, home }: DescribePreferencesErrorParams): string {\n return error instanceof PreferencesError ? error.message : describeFileError({ error, action, home })\n}\n","import type { CliOptions } from '../../cli/parse-cli-arguments'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport { harnesses } from '../../harnesses/registry'\nimport type { GatewayUrls } from '../../product/gateway/desired-config'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport { DEFAULT_MODEL, isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport { PROTOCOLS } from '../../product/gateway/models/protocol'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatProbes } from '../../ui/report/format-probes'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { checkKey, skippedKeyCheck, type KeyCheck } from '../key/key-check'\nimport {\n adoptKey,\n isKeyUsable,\n replaceRejectedKey,\n type CheckOutcome,\n type KeyStepRun,\n type ResolvedKey,\n} from '../key/key-step'\nimport { chooseModel, findModelWarnings } from './model-choice'\nimport { probeModel, probeRouter, shouldContinueAfterProbe, type RouterProbe } from './model-probe'\nimport { decideModelSave, requestModel, type ModelPreferences } from './model-step'\nimport { findBorrowedDefaults } from './suggest-defaults'\n\nexport type ChooseCheckedModelParams = {\n keyStep: KeyStepRun\n configurable: readonly ConfigurableHarness[]\n envModel: string | undefined\n preferences: ModelPreferences\n gatewayUrls: GatewayUrls\n options: Pick<CliOptions, 'model' | 'shouldVerify' | 'shouldAssumeYes' | 'shouldSaveModel' | 'isDryRun'>\n /** What still happens when the user continues past a failed model probe. */\n probeConsequence: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\nexport type ModelDecision =\n | {\n kind: 'chosen'\n model: string\n resolvedKey: ResolvedKey\n check: CheckOutcome\n /** The agents to save the model for once the run goes ahead. */\n modelSave: ConfigurableHarness[]\n }\n | { kind: 'declined' }\n | { kind: 'aborted' }\n\nexport async function chooseCheckedModel(params: ChooseCheckedModelParams): Promise<ModelDecision> {\n const { keyStep, configurable, preferences, gatewayUrls, options, ui, masker } = params\n const gatewayParams = { ui, masker, fetch: params.fetch }\n const requested = await requestModel({\n flagModel: options.model,\n envModel: params.envModel,\n targets: configurable,\n preferences,\n shouldAssumeYes: options.shouldAssumeYes,\n ui,\n })\n const requestedModel = requested?.model\n const keyCheck: KeyCheck = options.shouldVerify\n ? await checkKey({\n ...gatewayParams,\n openaiBaseUrl: gatewayUrls.openaiBaseUrl,\n requestedModel,\n shouldAssumeYes: options.shouldAssumeYes,\n resolved: keyStep.resolved,\n onSavedKeyRejected: async (rejected, probe) => {\n const replaced = await replaceRejectedKey({ input: keyStep.input, rejected, probe, deps: keyStep.deps })\n if (replaced === null) return null\n if (!isKeyUsable(replaced.key)) return null\n adoptKey(replaced.key, { ui, masker })\n return replaced\n },\n })\n : skippedKeyCheck(keyStep.resolved)\n if (keyCheck.isAborted) return { kind: 'aborted' }\n\n const routerProbe = await probeRouterIfOffered({\n keyCheck,\n requestedModel,\n anthropicBaseUrl: gatewayUrls.anthropicBaseUrl,\n ui,\n masker,\n fetch: params.fetch,\n })\n const routerAvailability = routerProbe?.availability ?? 'unknown'\n\n const protocols = PROTOCOLS.filter((protocol) => configurable.some((harness) => harness.protocols.includes(protocol)))\n const suggestions = findBorrowedDefaults({\n defaultModels: preferences.defaultModels,\n targets: configurable,\n harnesses,\n models: keyCheck.models,\n protocols,\n })\n const { shouldAssumeYes } = options\n const model = await chooseModel({\n keyCheck,\n requestedModel,\n routerAvailability,\n shouldAssumeYes,\n protocols,\n suggestions,\n ui,\n })\n for (const warning of findModelWarnings({ model, models: keyCheck.models, configurable, routerAvailability })) {\n ui.log.warn(masker.maskText(warning))\n }\n\n const source = requested?.source ?? 'picked'\n const modelSave = await decideModelSave({ model, source, targets: configurable, preferences, options, ui })\n const chosen = {\n kind: 'chosen',\n model,\n resolvedKey: keyCheck.resolvedKey,\n check: keyCheck.outcome,\n modelSave,\n } as const\n if (!options.shouldVerify || !protocols.includes('anthropic')) {\n printProbes(keyCheck.probes, ui)\n return chosen\n }\n\n const reusedRouterProbe = model === DEFAULT_MODEL ? routerProbe : undefined\n const probe =\n reusedRouterProbe === undefined\n ? await probeModel({\n ...gatewayParams,\n anthropicBaseUrl: gatewayUrls.anthropicBaseUrl,\n model,\n key: keyCheck.resolvedKey.key,\n })\n : reusedRouterProbe.probe\n printProbes([...keyCheck.probes, probe], ui)\n\n if (reusedRouterProbe !== undefined && routerAvailability === 'unknown') return chosen\n\n const shouldContinue = await shouldContinueAfterProbe({\n probe,\n shouldAssumeYes,\n consequence: params.probeConsequence,\n ui,\n })\n return shouldContinue ? chosen : { kind: 'declined' }\n}\n\nfunction printProbes(probes: readonly ProbeResult[], ui: TerminalUi): void {\n if (probes.length > 0) ui.print(formatProbes(probes))\n}\n\ntype ProbeRouterIfOfferedParams = {\n keyCheck: KeyCheck\n requestedModel: string | undefined\n anthropicBaseUrl: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\nasync function probeRouterIfOffered({\n keyCheck,\n requestedModel,\n anthropicBaseUrl,\n ui,\n masker,\n fetch,\n}: ProbeRouterIfOfferedParams): Promise<RouterProbe | undefined> {\n if (keyCheck.outcome !== 'passed') return undefined\n if (requestedModel !== undefined && !isPredefinedModel(requestedModel)) return undefined\n\n return await probeRouter({ anthropicBaseUrl, key: keyCheck.resolvedKey.key, ui, masker, fetch })\n}\n","import path from 'node:path'\nimport { ENV_DIRECTORY_NAME, type Shell } from './syntax/env-syntax'\nimport { ENV_SYNTAXES } from './syntax/env-syntaxes'\n\nexport function resolveEnvFilePath(home: string, shell: Shell): string {\n return path.join(home, ENV_DIRECTORY_NAME, ENV_SYNTAXES[shell].fileName)\n}\n","import { GATEWAY_ENV_VARIABLE, parseEnvironmentKey, readEnvironmentInputs } from '../../cli/environment'\nimport { EXIT_CODE } from '../../cli/exit-code'\nimport type { CliOptions } from '../../cli/parse-cli-arguments'\nimport { refusePrompts } from '../../cli/refuse-prompts'\nimport { findExistingKeys } from '../../flows/key/find-existing-keys'\nimport {\n adoptKey,\n commitSave,\n isKeyUsable,\n resolveKey,\n type KeyStepDeps,\n type KeyStepInput,\n} from '../../flows/key/key-step'\nimport { chooseCheckedModel } from '../../flows/model/choose-checked-model'\nimport { commitModelSave, loadModelPreferences } from '../../flows/model/model-step'\nimport type { LaunchingHarness, LaunchRecipe } from '../../harnesses/harness'\nimport type { LaunchResult } from '../../harnesses/run-launch'\nimport { GATEWAY_HOST, buildDesiredConfig, buildGatewayUrls } from '../../product/gateway/desired-config'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport type { Masker } from '../../product/secrets/masker'\nimport { resolveEnvFilePath } from '../../product/storage/env-file/env-file-path'\nimport { resolveShell } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport type { Keystore } from '../../product/storage/keychain/keystore'\nimport type { EnvironmentVariables, PlatformContext } from '../../shared/platform/platform-context'\nimport type { TerminalUi } from '../../ui/terminal-ui'\n\nexport type LaunchOptions = Pick<\n CliOptions,\n 'key' | 'model' | 'shouldSaveKey' | 'shouldSaveModel' | 'shouldVerify' | 'shouldAssumeYes'\n>\n\nexport type LaunchInput = {\n harness: LaunchingHarness\n passthrough: readonly string[]\n options: LaunchOptions\n env: EnvironmentVariables\n}\n\nexport type LaunchDeps = {\n keystore: Keystore\n ui: TerminalUi\n masker: Masker\n ctx: PlatformContext\n fetch: Fetch\n runLaunch(recipe: LaunchRecipe, passthrough: readonly string[]): Promise<LaunchResult>\n}\n\nconst DESTINATION = 'It is passed to the agent for this run and is not written to any agent config.'\n\nexport async function launch(input: LaunchInput, rawDeps: LaunchDeps): Promise<LaunchResult> {\n const { harness, options } = input\n const { masker, ctx } = rawDeps\n const ui = ctx.isInteractive ? rawDeps.ui : refusePrompts(rawDeps.ui)\n\n // Checked first, so nobody pastes a key for an agent that is not there.\n if (!ctx.hasBinary(harness.binary)) {\n ui.log.error(`${harness.binary} not found on PATH. Install ${harness.label} first.`)\n return { code: EXIT_CODE.failed }\n }\n\n const environment = readEnvironmentInputs(input.env)\n const gatewayUrls = buildGatewayUrls(environment.gatewayHost ?? GATEWAY_HOST)\n if (environment.gatewayHost !== undefined) {\n ui.log.warn(masker.maskText(`Using the gateway at ${environment.gatewayHost} — $${GATEWAY_ENV_VARIABLE} is set.`))\n }\n const keyDeps: KeyStepDeps = { keystore: rawDeps.keystore, ui, masker }\n const keyInput = aKeyStepInput({ ctx, options, environmentKey: environment.key, masker })\n const resolved = await resolveKey(keyInput, keyDeps)\n if (!isKeyUsable(resolved.key)) {\n ui.cancel('No API key provided.')\n return { code: EXIT_CODE.failed }\n }\n adoptKey(resolved.key, { ui, masker })\n\n const decision = await chooseCheckedModel({\n keyStep: { input: keyInput, deps: keyDeps, resolved },\n configurable: [harness],\n envModel: environment.model,\n preferences: loadModelPreferences(ctx.home, ui),\n gatewayUrls,\n options: { ...options, isDryRun: false },\n probeConsequence: 'The agent will still start.',\n ui,\n masker,\n fetch: rawDeps.fetch,\n })\n if (decision.kind === 'declined') {\n ui.cancel('Aborted — the agent was not started.')\n return { code: EXIT_CODE.cancelled }\n }\n if (decision.kind === 'aborted') return { code: EXIT_CODE.failed }\n\n await commitSave(decision.resolvedKey, decision.check, keyDeps)\n commitModelSave({ model: decision.model, harnesses: decision.modelSave, home: ctx.home, ui, masker })\n\n const desired = buildDesiredConfig({ gatewayUrls, apiKey: decision.resolvedKey.key, model: decision.model })\n const recipe = harness.launch(desired)\n if (harness.launchNotes !== undefined) {\n ui.note(harness.launchNotes.join('\\n'), 'Nothing is written to your config, but')\n }\n return await rawDeps.runLaunch(recipe, input.passthrough)\n}\n\ntype KeyStepInputParams = {\n ctx: PlatformContext\n options: LaunchOptions\n environmentKey: string | undefined\n masker: Masker\n}\n\nfunction aKeyStepInput({ ctx, options, environmentKey, masker }: KeyStepInputParams): KeyStepInput {\n const shell = resolveShell(ctx.platform)\n const existingKeys = findExistingKeys({ ctx, envPath: resolveEnvFilePath(ctx.home, shell), shell })\n masker.registerSecrets(existingKeys.all)\n\n return {\n flagKey: options.key,\n envKey: options.key === undefined ? parseEnvironmentKey(environmentKey) : undefined,\n shouldSaveKey: options.shouldSaveKey,\n shouldAssumeYes: options.shouldAssumeYes,\n isDryRun: false,\n existingKeys: () => existingKeys,\n destination: DESTINATION,\n }\n}\n","import path from 'node:path'\nimport { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport { TAGLINE } from '../../cli/help'\nimport type { CliOptions } from '../../cli/parse-cli-arguments'\nimport { refusePrompts } from '../../cli/refuse-prompts'\nimport { resolveNamedHarnesses } from '../../cli/resolve-named-harnesses'\nimport type { Harness } from '../../harnesses/harness'\nimport { findHarness } from '../../harnesses/registry'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatBackupTimestamp, resolveBackupRoot } from '../../product/storage/backups/resolve-backup-root'\nimport { resolveEnvFilePath } from '../../product/storage/env-file/env-file-path'\nimport { resolveShell } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport {\n createEmptyRestoreRecord,\n readRestoreRecord,\n RestoreRecordError,\n type RestoreRecord,\n} from '../../product/storage/restore-record/restore-record'\nimport { resolveRestoreRecordLocation } from '../../product/storage/restore-record/restore-record-location'\nimport { DEFAULT_SCOPE, type ConfigScope, type PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatCount } from '../../shared/text/format-count'\nimport type { RestoreChoice } from '../../ui/prompts/select-restore-harnesses'\nimport { formatRestorePreview } from '../../ui/report/format-restore-preview'\nimport { formatRestoreResult } from '../../ui/report/format-restore-result'\nimport type { ResultMode } from '../../ui/report/format-result'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { applyRestore } from './apply-restore'\nimport { planRestore, type RestoreCandidate, type RestorePlan } from './restore-plan'\nimport { exitCodeForRestore, isPlannedRestore } from './restore-result'\nimport { listRestoreSecrets } from './restore-secrets'\n\nexport type RunRestoreParams = {\n options: CliOptions\n baseContext: PlatformContext\n ui: TerminalUi\n now: () => Date\n masker: Masker\n}\n\nconst FINISHED_WITH_ERRORS = 'Finished with errors.'\nconst DRY_RUN_OUTRO = 'Dry run — nothing was restored.'\nconst CONFIRMATION = 'Restore these files? Current versions are backed up first.'\n\nexport async function runRestore(params: RunRestoreParams): Promise<ExitCode> {\n const { options, masker } = params\n const ui = params.baseContext.isInteractive ? params.ui : refusePrompts(params.ui)\n ui.intro(TAGLINE)\n\n const namedHarnesses = resolveNamedHarnesses(options.harnessIds)\n const scope = await resolveRestoreScope({ options, baseContext: params.baseContext, ui })\n const ctx: PlatformContext = { ...params.baseContext, scope }\n const recordRead = readRecord(ctx)\n if (recordRead.kind === 'failed') {\n ui.log.error(masker.maskText(recordRead.error))\n ui.outro(FINISHED_WITH_ERRORS)\n return EXIT_CODE.failed\n }\n\n const { record } = recordRead\n if (namedHarnesses.length === 0 && Object.keys(record.harnesses).length === 0) {\n const recordPath = displayPath(resolveRestoreRecordLocation(ctx).filePath, ctx.home)\n ui.outro(`Nothing to restore — nexos-connect has not set up any agent at ${scope} scope (${recordPath}).`)\n return EXIT_CODE.ok\n }\n\n const candidates = await selectCandidates({\n namedHarnesses,\n record,\n ctx,\n shouldAssumeYes: options.shouldAssumeYes,\n ui,\n })\n if (candidates.length === 0) {\n ui.cancel('No agents selected — nothing to do.')\n return EXIT_CODE.ok\n }\n\n const run: RestoreRun = { ...params, ui, ctx }\n const plan = planSelected({ run, candidates, record })\n if (options.isDryRun) return report({ run, plan, mode: { kind: 'dry-run' }, outro: DRY_RUN_OUTRO })\n\n const hasChanges = plan.outcomes.some((outcome) => outcome.kind === 'restored')\n if (hasChanges && !options.shouldAssumeYes && !(await ui.confirm(CONFIRMATION, true))) {\n ui.cancel('Aborted — nothing was restored.')\n return EXIT_CODE.cancelled\n }\n\n const applied = applySelected(run, plan)\n const outro = exitCodeForRestore(applied.outcomes) === EXIT_CODE.ok ? 'Done.' : FINISHED_WITH_ERRORS\n const mode = { kind: 'written', backupRoot: applied.backupRoot } as const\n return report({ run, plan: { outcomes: applied.outcomes, envFile: applied.envFile }, mode, outro })\n}\n\ntype RestoreRun = RunRestoreParams & { ui: TerminalUi; ctx: PlatformContext }\n\ntype ResolveRestoreScopeParams = { options: CliOptions; baseContext: PlatformContext; ui: TerminalUi }\n\nasync function resolveRestoreScope({ options, baseContext, ui }: ResolveRestoreScopeParams): Promise<ConfigScope> {\n if (options.scope !== undefined) return options.scope\n if (options.shouldAssumeYes) return DEFAULT_SCOPE\n\n return await ui.selectRestoreScope({\n userAgents: listRecordedLabels({ ...baseContext, scope: 'user' }),\n projectAgents: listRecordedLabels({ ...baseContext, scope: 'project' }),\n })\n}\n\nfunction listRecordedLabels(ctx: PlatformContext): string[] {\n const recordRead = readRecord(ctx)\n if (recordRead.kind === 'failed') return []\n\n return Object.keys(recordRead.record.harnesses).map(labelOf)\n}\n\ntype RecordRead = { kind: 'read'; record: RestoreRecord } | { kind: 'failed'; error: string }\n\nfunction readRecord(ctx: PlatformContext): RecordRead {\n try {\n const record = readRestoreRecord({ filePath: resolveRestoreRecordLocation(ctx).filePath, home: ctx.home })\n return { kind: 'read', record: record ?? createEmptyRestoreRecord() }\n } catch (error) {\n if (!(error instanceof RestoreRecordError)) throw error\n return { kind: 'failed', error: error.message }\n }\n}\n\nfunction labelOf(harnessId: string): string {\n return findHarness(harnessId)?.label ?? harnessId\n}\n\ntype SelectCandidatesParams = {\n namedHarnesses: readonly Harness[]\n record: RestoreRecord\n ctx: PlatformContext\n shouldAssumeYes: boolean\n ui: TerminalUi\n}\n\nasync function selectCandidates(params: SelectCandidatesParams): Promise<RestoreCandidate[]> {\n const { namedHarnesses, record, ctx, ui } = params\n if (namedHarnesses.length > 0) return namedHarnesses.map((harness) => toCandidate(harness.id, record))\n\n const recordedIds = Object.keys(record.harnesses)\n if (params.shouldAssumeYes) return recordedIds.map((id) => toCandidate(id, record))\n\n const chosenIds = await ui.selectRestoreHarnesses(recordedIds.map((id) => describeChoice({ id, record, ctx })))\n return chosenIds.map((id) => toCandidate(id, record))\n}\n\nfunction toCandidate(id: string, record: RestoreRecord): RestoreCandidate {\n return { target: { id, label: labelOf(id) }, record: record.harnesses[id] ?? null }\n}\n\ntype DescribeChoiceParams = { id: string; record: RestoreRecord; ctx: PlatformContext }\n\nconst ENV_VARIABLES_HINT = 'environment variables'\n\n// Joined without fromRecordedPath's check: a hint only shows a path, and planning fails a path outside the root.\nfunction describeChoice({ id, record, ctx }: DescribeChoiceParams): RestoreChoice {\n const harness = record.harnesses[id]\n const root = resolveRestoreRecordLocation(ctx).root\n const files = (harness?.files ?? []).map((file) => displayPath(path.join(root, ...file.path), ctx.home))\n const variables = (harness?.envVariables.length ?? 0) > 0 ? [ENV_VARIABLES_HINT] : []\n return { value: id, label: labelOf(id), hint: [...files, ...variables].join(', ') }\n}\n\ntype PlanSelectedParams = { run: RestoreRun; candidates: readonly RestoreCandidate[]; record: RestoreRecord }\n\nfunction planSelected({ run, candidates, record }: PlanSelectedParams): RestorePlan {\n const { ctx, masker, ui } = run\n const shell = resolveShell(ctx.platform)\n const envPath = resolveEnvFilePath(ctx.home, shell)\n masker.registerSecrets(listRestoreSecrets({ record, ctx, envPath, shell }))\n\n const plan = planRestore({ candidates, record, ctx, envPath, shell })\n const files = plan.outcomes.flatMap((outcome) => (isPlannedRestore(outcome) ? outcome.files : []))\n const hasFailedAgent = plan.outcomes.some((outcome) => outcome.kind === 'failed')\n ui.print(\n formatRestorePreview({ files, envFile: plan.envFile, scope: ctx.scope, hasFailedAgent, home: ctx.home, masker }),\n )\n return plan\n}\n\nfunction applySelected(run: RestoreRun, plan: RestorePlan): ReturnType<typeof applyRestore> {\n const { options, ctx, ui } = run\n const backupRoot = resolveBackupRoot({\n scope: ctx.scope,\n home: ctx.home,\n cwd: ctx.cwd,\n stamp: formatBackupTimestamp(run.now()),\n backupDirectory: options.backupDirectory,\n })\n\n const spinner = ui.spinner()\n spinner.start('Backing up current versions and restoring…')\n const applied = applyRestore({ plan, ctx, backupRoot })\n spinner.stop(`Restored ${formatCount(applied.writtenCount, 'file')}.`)\n return applied\n}\n\ntype ReportParams = { run: RestoreRun; plan: RestorePlan; mode: ResultMode; outro: string }\n\nfunction report({ run, plan, mode, outro }: ReportParams): ExitCode {\n const { ui, ctx, masker } = run\n ui.print(formatRestoreResult({ outcomes: plan.outcomes, envFile: plan.envFile, mode, home: ctx.home, masker }))\n ui.outro(outro)\n return exitCodeForRestore(plan.outcomes)\n}\n","import type { Harness } from '../harnesses/harness'\nimport { findHarness, harnesses } from '../harnesses/registry'\nimport { UsageError } from './usage-error'\n\nexport function resolveNamedHarnesses(ids: readonly string[]): Harness[] {\n const unknownIds = ids.filter((id) => findHarness(id) === undefined)\n if (unknownIds.length > 0) {\n const noun = unknownIds.length === 1 ? 'id' : 'ids'\n const knownIds = harnesses.map((harness) => harness.id).join(', ')\n throw new UsageError(`Unknown agent ${noun}: ${unknownIds.join(', ')}. Known ids: ${knownIds}.`)\n }\n\n return ids.flatMap((id) => findHarness(id) ?? [])\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport type { ConfigScope } from '../../../shared/platform/platform-context'\n\nexport const PROJECT_BACKUP_DIRECTORY = '.nexos-backup'\nexport const USER_BACKUP_DIRECTORY = path.join('.nexos', 'backups')\n\nexport function formatBackupTimestamp(now: Date): string {\n return now.toISOString().replace(/[:.]/g, '-')\n}\n\nexport type ResolveBackupRootParams = {\n scope: ConfigScope\n home: string\n cwd: string\n stamp: string\n backupDirectory: string | undefined\n}\n\nexport type BackupRoot = {\n path: string\n gitIgnoredDirectory: string | null\n}\n\nexport function resolveBackupRoot({ scope, home, cwd, stamp, backupDirectory }: ResolveBackupRootParams): BackupRoot {\n if (backupDirectory !== undefined) {\n return { path: path.join(path.resolve(cwd, backupDirectory), stamp), gitIgnoredDirectory: null }\n }\n return match(scope)\n .returnType<BackupRoot>()\n .with('user', () => ({ path: path.join(home, USER_BACKUP_DIRECTORY, stamp), gitIgnoredDirectory: null }))\n .with('project', () => {\n const directory = path.join(cwd, PROJECT_BACKUP_DIRECTORY)\n return { path: path.join(directory, stamp), gitIgnoredDirectory: directory }\n })\n .exhaustive()\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport * as v from 'valibot'\nimport { CONFIG_FORMATS } from '../../../shared/file-formats/config-format'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport { resolveOwnerOnlyMode } from '../../../shared/file-system/resolve-owner-only-mode'\nimport { writeFileWithMode } from '../../../shared/file-system/write-file-with-mode'\nimport { displayPath } from '../../../shared/text/display-path'\n\nexport const FILE_ORIGINS = ['absent', 'blank', 'content'] as const\n\nexport type FileOrigin = (typeof FILE_ORIGINS)[number]\n\nconst RECORD_VERSION = 1\n\nconst SegmentsSchema = v.pipe(v.tupleWithRest([v.string()], v.string()), v.readonly())\n\nconst RecordedKeySchema = v.object({\n keyPath: SegmentsSchema,\n original: v.nullable(v.string()),\n createdParents: v.pipe(v.array(SegmentsSchema), v.readonly()),\n holdsSecret: v.boolean(),\n})\n\nconst RecordedFileSchema = v.object({\n path: SegmentsSchema,\n format: v.picklist(CONFIG_FORMATS),\n origin: v.picklist(FILE_ORIGINS),\n keys: v.pipe(v.array(RecordedKeySchema), v.readonly()),\n})\n\nconst RecordedEnvVariableSchema = v.object({ name: v.string(), original: v.nullable(v.string()) })\n\nconst HarnessRecordSchema = v.object({\n files: v.pipe(v.array(RecordedFileSchema), v.readonly()),\n envVariables: v.pipe(v.array(RecordedEnvVariableSchema), v.readonly()),\n})\n\nconst RestoreRecordSchema = v.object({\n version: v.literal(RECORD_VERSION),\n harnesses: v.record(v.string(), HarnessRecordSchema),\n})\n\nexport type RecordedPath = v.InferOutput<typeof SegmentsSchema>\n/** `holdsSecret` marks a key setup wrote the API key into, so whatever it held before may be a key too. */\nexport type RecordedKey = v.InferOutput<typeof RecordedKeySchema>\nexport type RecordedFile = v.InferOutput<typeof RecordedFileSchema>\nexport type RecordedEnvVariable = v.InferOutput<typeof RecordedEnvVariableSchema>\nexport type HarnessRecord = v.InferOutput<typeof HarnessRecordSchema>\nexport type RestoreRecord = v.InferOutput<typeof RestoreRecordSchema>\n\nexport function createEmptyRestoreRecord(): RestoreRecord {\n return { version: RECORD_VERSION, harnesses: {} }\n}\n\nexport class RestoreRecordError extends Error {\n override readonly name = 'RestoreRecordError'\n}\n\nexport type ReadRestoreRecordParams = { filePath: string; home: string }\n\nexport function readRestoreRecord({ filePath, home }: ReadRestoreRecordParams): RestoreRecord | null {\n const text = readFileIfExists(filePath)\n if (text === null) return null\n\n const shownPath = displayPath(filePath, home)\n const json = parseJson(text)\n if (isNewerRecord(json)) {\n throw new RestoreRecordError(`${shownPath} was written by a newer nexos-connect. Update it, then run again.`)\n }\n\n const parsed = v.safeParse(RestoreRecordSchema, json)\n if (!parsed.success) {\n throw new RestoreRecordError(\n `${shownPath} is not a restore record nexos-connect can read. Fix it, or move it aside to start a new one, ` +\n 'then run again.',\n )\n }\n return parsed.output\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n if (error instanceof SyntaxError) return undefined\n throw error\n }\n}\n\nconst VersionSchema = v.object({ version: v.number() })\n\nfunction isNewerRecord(json: unknown): boolean {\n const parsed = v.safeParse(VersionSchema, json)\n return parsed.success && parsed.output.version > RECORD_VERSION\n}\n\nexport type WriteRestoreRecordParams = { filePath: string; record: RestoreRecord; platform: NodeJS.Platform }\n\nconst RECORD_DIRECTORY_MODE = 0o700\nconst JSON_INDENT = 2\n\n/** A record with no harness left is deleted, so a full restore leaves no file behind. */\nexport function writeRestoreRecord({ filePath, record, platform }: WriteRestoreRecordParams): void {\n if (Object.keys(record.harnesses).length === 0) {\n fs.rmSync(filePath, { force: true })\n return\n }\n\n fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: RECORD_DIRECTORY_MODE })\n const content = `${JSON.stringify(record, null, JSON_INDENT)}\\n`\n writeFileWithMode({ filePath, content, mode: resolveOwnerOnlyMode(platform) })\n}\n","import { match } from 'ts-pattern'\nimport { parseJsonc, parseJsoncValue, readJsoncOriginals, renderJsonc, restoreJsonc } from './jsonc'\nimport type { KeyOriginal } from './key-original'\nimport type { KeyPathUpdates } from './key-path'\nimport { parseToml, parseTomlValue, readTomlOriginals, renderToml, restoreToml, type TomlUpdate } from './toml'\n\nexport const CONFIG_FORMATS = ['jsonc', 'toml'] as const\n\nexport type ConfigFormat = (typeof CONFIG_FORMATS)[number]\n\nexport type ConfigEdits =\n | { format: 'jsonc'; updates: KeyPathUpdates }\n | { format: 'toml'; updates: readonly TomlUpdate[] }\n\nexport function renderConfig(current: string | null, edits: ConfigEdits): string {\n return match(edits)\n .with({ format: 'jsonc' }, ({ updates }) => renderJsonc(current, updates))\n .with({ format: 'toml' }, ({ updates }) => renderToml(current, updates))\n .exhaustive()\n}\n\nexport function readOriginals(current: string | null, edits: ConfigEdits): KeyOriginal[] {\n const keyPaths = edits.updates.map(([keyPath]) => keyPath)\n return match(edits.format)\n .with('jsonc', () => readJsoncOriginals(current, keyPaths))\n .with('toml', () => readTomlOriginals(current, keyPaths))\n .exhaustive()\n}\n\nexport type RestoreConfigParams = { format: ConfigFormat; current: string; originals: readonly KeyOriginal[] }\n\nexport function restoreConfig({ format, current, originals }: RestoreConfigParams): string {\n return match(format)\n .with('jsonc', () => restoreJsonc(current, originals))\n .with('toml', () => restoreToml(current, originals))\n .exhaustive()\n}\n\nexport function isEmptyConfig(format: ConfigFormat, text: string): boolean {\n const document = match(format)\n .with('jsonc', () => parseJsonc(text))\n .with('toml', () => parseToml(text))\n .exhaustive()\n return Object.keys(document).length === 0\n}\n\nexport function parseValueSource(format: ConfigFormat, source: string): unknown {\n return match(format)\n .with('jsonc', () => parseJsoncValue(source))\n .with('toml', () => parseTomlValue(source))\n .exhaustive()\n}\n","import { match } from 'ts-pattern'\n\nconst OWNER_ONLY_MODE = 0o600\n\n// chmod on Windows only toggles the read-only bit, so 0600 there would claim a protection the ACL does not give.\nexport function resolveOwnerOnlyMode(platform: NodeJS.Platform): number | null {\n return match(platform)\n .returnType<number | null>()\n .with('win32', () => null)\n .otherwise(() => OWNER_ONLY_MODE)\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nexport type WriteFileWithModeParams = { filePath: string; content: string; mode: number | null }\n\nexport function writeFileWithMode({ filePath, content, mode }: WriteFileWithModeParams): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n if (mode === null) {\n fs.writeFileSync(filePath, content)\n return\n }\n\n // Before the write too, so the key never lands under looser bits; `mode` covers only a new file, through the umask.\n if (fs.existsSync(filePath)) fs.chmodSync(filePath, mode)\n fs.writeFileSync(filePath, content, { mode })\n fs.chmodSync(filePath, mode)\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { PROJECT_BACKUP_DIRECTORY } from '../backups/resolve-backup-root'\nimport { ENV_DIRECTORY_NAME } from '../env-file/syntax/env-syntax'\nimport type { RecordedPath } from './restore-record'\n\nexport const RESTORE_RECORD_FILE = 'restore-record.json'\n\nexport type RestoreRecordLocation = { filePath: string; root: string; gitIgnoredDirectory: string | null }\n\nexport function resolveRestoreRecordLocation(ctx: PlatformContext): RestoreRecordLocation {\n return match(ctx.scope)\n .returnType<RestoreRecordLocation>()\n .with('user', () => ({\n filePath: path.join(ctx.home, ENV_DIRECTORY_NAME, RESTORE_RECORD_FILE),\n root: ctx.home,\n gitIgnoredDirectory: null,\n }))\n .with('project', () => {\n const directory = path.join(ctx.cwd, PROJECT_BACKUP_DIRECTORY)\n return { filePath: path.join(directory, RESTORE_RECORD_FILE), root: ctx.cwd, gitIgnoredDirectory: directory }\n })\n .exhaustive()\n}\n\nexport function toRecordedPath(filePath: string, root: string): RecordedPath {\n const [first, ...rest] = path.relative(root, filePath).split(path.sep)\n if (first === undefined || !isInsideRoot(filePath, root)) {\n throw new Error(`${filePath} is outside ${root}, so it cannot be recorded for a restore.`)\n }\n return [first, ...rest]\n}\n\n// The record is a plain file, at project scope one a repository could ship, so its paths are not trusted.\nexport function fromRecordedPath(recordedPath: RecordedPath, root: string): string {\n const filePath = path.join(root, ...recordedPath)\n if (!isInsideRoot(filePath, root)) {\n throw new Error(\n `${filePath} is outside ${root}, so it cannot be restored. Remove it from the restore record, then run again.`,\n )\n }\n return filePath\n}\n\nfunction isInsideRoot(filePath: string, root: string): boolean {\n const relativePath = path.relative(root, filePath)\n const [first] = relativePath.split(path.sep)\n return relativePath !== '' && first !== '..' && !path.isAbsolute(relativePath)\n}\n","import pc from 'picocolors'\nimport type { RestoreEnvPlan, RestoreFilePlan } from '../../commands/restore/restore-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { ConfigScope } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatHeading } from './format-heading'\nimport { formatFileDiff } from './format-preview'\n\nexport type FormatRestorePreviewParams = {\n files: readonly RestoreFilePlan[]\n envFile: RestoreEnvPlan | null\n scope: ConfigScope\n hasFailedAgent: boolean\n home: string\n masker: Masker\n}\n\nconst NOTHING_TO_RESTORE = 'Nothing to change — every selected agent is already as it was.'\nconst NOTHING_TO_RESTORE_AFTER_FAILURE =\n 'Nothing to change — an agent failed while planning; the report below says why.'\n\nexport function formatRestorePreview(params: FormatRestorePreviewParams): string[] {\n const { files, envFile, scope, hasFailedAgent, home, masker } = params\n const heading = formatHeading(`Planned restore ${pc.dim(`(scope: ${scope})`)}`)\n const changedFiles = files.filter((file) => file.isChanged)\n const changedEnvFile = envFile?.isChanged === true ? [envFile] : []\n if (changedFiles.length === 0 && changedEnvFile.length === 0) {\n return [...heading, ` ${pc.dim(hasFailedAgent ? NOTHING_TO_RESTORE_AFTER_FAILURE : NOTHING_TO_RESTORE)}`]\n }\n\n return [\n ...heading,\n ...changedFiles.flatMap((file) => formatRestoredFile({ file, home, masker })),\n ...changedEnvFile.flatMap((change) => formatFileDiff({ change, home, masker })),\n ]\n}\n\nconst DELETION_NOTE = 'deleted — nexos-connect created it'\n\ntype FormatRestoredFileParams = { file: RestoreFilePlan; home: string; masker: Masker }\n\nfunction formatRestoredFile({ file, home, masker }: FormatRestoredFileParams): string[] {\n if (file.after === null) return ['', ` ${pc.bold(displayPath(file.path, home))} ${pc.dim(`(${DELETION_NOTE})`)}`]\n\n const change = { path: file.path, before: file.before, after: file.after, isChanged: file.isChanged }\n return formatFileDiff({ change, home, masker })\n}\n","import pc from 'picocolors'\nimport type { FilePlan } from '../../commands/setup/setup-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { ConfigScope } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatCount } from '../../shared/text/format-count'\nimport { countChangedLines, diffLines } from '../diff/diff-lines'\nimport { renderDiff } from '../diff/render-diff'\nimport { formatHeading } from './format-heading'\n\nexport type FormatPreviewParams = {\n changes: readonly FilePlan[]\n model: string\n scope: ConfigScope\n hasFailedAgent: boolean\n home: string\n masker: Masker\n}\n\nconst NOTHING_TO_CHANGE = 'Nothing to change — every selected agent is already configured or was skipped.'\nconst NOTHING_TO_CHANGE_AFTER_FAILURE = 'Nothing to change — an agent failed while planning; the report below says why.'\n\nexport function formatPreview({ changes, model, scope, hasFailedAgent, home, masker }: FormatPreviewParams): string[] {\n const heading = formatHeading(`Planned changes ${pc.dim(`(scope: ${scope}, model: ${masker.maskText(model)})`)}`)\n if (changes.length === 0) {\n const note = hasFailedAgent ? NOTHING_TO_CHANGE_AFTER_FAILURE : NOTHING_TO_CHANGE\n return [...heading, ` ${pc.dim(note)}`]\n }\n\n return [...heading, ...changes.flatMap((change) => formatFileDiff({ change, home, masker }))]\n}\n\nexport type FormatFileDiffParams = { change: FilePlan; home: string; masker: Masker }\n\nexport function formatFileDiff({ change, home, masker }: FormatFileDiffParams): string[] {\n const diff = diffLines({ before: masker.maskText(change.before ?? ''), after: masker.maskText(change.after) })\n const lineCount = formatCount(countChangedLines(diff), 'line')\n const lineCountNote = change.before === null ? `new file, ${lineCount}` : lineCount\n return ['', ` ${pc.bold(displayPath(change.path, home))} ${pc.dim(`(${lineCountNote})`)}`, ...renderDiff(diff)]\n}\n","export type DiffLine = { kind: 'unchanged' | 'added' | 'removed'; text: string }\n\nexport type DiffLinesParams = { before: string; after: string }\n\nexport function diffLines({ before, after }: DiffLinesParams): DiffLine[] {\n const beforeLines = splitTerminatedLines(before)\n const afterLines = splitTerminatedLines(after)\n const table = buildCommonLengthTable({ beforeLines, afterLines })\n\n const diff: DiffLine[] = []\n let beforeIndex = 0\n let afterIndex = 0\n while (beforeIndex < beforeLines.length && afterIndex < afterLines.length) {\n const beforeLine = beforeLines[beforeIndex]!\n const afterLine = afterLines[afterIndex]!\n if (beforeLine === afterLine) {\n diff.push(toDiffLine('unchanged', beforeLine))\n beforeIndex++\n afterIndex++\n } else if (table[beforeIndex + 1]![afterIndex]! >= table[beforeIndex]![afterIndex + 1]!) {\n diff.push(toDiffLine('removed', beforeLine))\n beforeIndex++\n } else {\n diff.push(toDiffLine('added', afterLine))\n afterIndex++\n }\n }\n for (const line of beforeLines.slice(beforeIndex)) diff.push(toDiffLine('removed', line))\n for (const line of afterLines.slice(afterIndex)) diff.push(toDiffLine('added', line))\n return diff\n}\n\nexport function countChangedLines(lines: readonly DiffLine[]): number {\n return lines.filter((line) => line.kind !== 'unchanged').length\n}\n\nconst TERMINATED_LINE_PATTERN = /[^\\n]*\\n|[^\\n]+$/g\nconst LINE_TERMINATOR = '\\n'\n\nfunction splitTerminatedLines(text: string): string[] {\n return text.match(TERMINATED_LINE_PATTERN) ?? []\n}\n\nfunction toDiffLine(kind: DiffLine['kind'], line: string): DiffLine {\n return { kind, text: line.endsWith(LINE_TERMINATOR) ? line.slice(0, -LINE_TERMINATOR.length) : line }\n}\n\ntype BuildCommonLengthTableParams = { beforeLines: readonly string[]; afterLines: readonly string[] }\n\nfunction buildCommonLengthTable({ beforeLines, afterLines }: BuildCommonLengthTableParams): number[][] {\n const table = Array.from({ length: beforeLines.length + 1 }, () =>\n Array.from({ length: afterLines.length + 1 }, () => 0),\n )\n for (let beforeIndex = beforeLines.length - 1; beforeIndex >= 0; beforeIndex--) {\n for (let afterIndex = afterLines.length - 1; afterIndex >= 0; afterIndex--) {\n if (beforeLines[beforeIndex] === afterLines[afterIndex]) {\n table[beforeIndex]![afterIndex] = table[beforeIndex + 1]![afterIndex + 1]! + 1\n } else {\n table[beforeIndex]![afterIndex] = Math.max(\n table[beforeIndex + 1]![afterIndex]!,\n table[beforeIndex]![afterIndex + 1]!,\n )\n }\n }\n }\n return table\n}\n","import pc from 'picocolors'\nimport { match } from 'ts-pattern'\nimport { GLYPHS } from '../glyphs'\nimport type { DiffLine } from './diff-lines'\n\nconst DIFF_CONTEXT_LINES = 2\nconst ADDED_PREFIX = ' + '\nconst REMOVED_PREFIX = ' - '\nconst UNCHANGED_PREFIX = ' '\n\nexport function renderDiff(lines: readonly DiffLine[]): string[] {\n const visibleIndexes = findVisibleIndexes(lines)\n if (visibleIndexes.size === 0) return [pc.dim(`${UNCHANGED_PREFIX}(no change)`)]\n\n const rendered: string[] = []\n let isSkipping = false\n for (const [index, line] of lines.entries()) {\n if (visibleIndexes.has(index)) {\n rendered.push(renderLine(line))\n isSkipping = false\n continue\n }\n if (!isSkipping) rendered.push(pc.dim(`${UNCHANGED_PREFIX}${GLYPHS.elided}`))\n isSkipping = true\n }\n return rendered\n}\n\nfunction findVisibleIndexes(lines: readonly DiffLine[]): Set<number> {\n const visibleIndexes = new Set<number>()\n for (const [index, line] of lines.entries()) {\n if (line.kind === 'unchanged') continue\n const first = Math.max(0, index - DIFF_CONTEXT_LINES)\n const last = Math.min(lines.length - 1, index + DIFF_CONTEXT_LINES)\n for (let visibleIndex = first; visibleIndex <= last; visibleIndex++) visibleIndexes.add(visibleIndex)\n }\n return visibleIndexes\n}\n\nfunction renderLine(line: DiffLine): string {\n return match(line.kind)\n .with('added', () => pc.green(`${ADDED_PREFIX}${line.text}`))\n .with('removed', () => pc.red(`${REMOVED_PREFIX}${line.text}`))\n .with('unchanged', () => pc.dim(`${UNCHANGED_PREFIX}${line.text}`))\n .exhaustive()\n}\n","import pc from 'picocolors'\nimport { P, match } from 'ts-pattern'\nimport {\n RESTORE_OUTCOME_KINDS,\n type PlannedRestore,\n type RestoreEnvPlan,\n type RestoreFilePlan,\n type RestoreOutcome,\n type RestoreOutcomeKind,\n} from '../../commands/restore/restore-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { parseEnvFile } from '../../product/storage/env-file/parse-env-file'\nimport { displayPath } from '../../shared/text/display-path'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport type { ResultMode } from './format-result'\nimport { INDENT } from './indent'\nimport type { StatusStyle } from './outcome-style'\n\nexport type FormatRestoreResultParams = {\n outcomes: readonly RestoreOutcome[]\n envFile: RestoreEnvPlan | null\n mode: ResultMode\n home: string\n masker: Masker\n}\n\nexport function formatRestoreResult(params: FormatRestoreResultParams): string[] {\n const heading = params.mode.kind === 'dry-run' ? 'Result (dry run)' : 'Result'\n return [\n ...formatHeading(heading),\n ...params.outcomes.flatMap((outcome) => formatOutcome(outcome, params)),\n ...formatEnvFileStep(params),\n ...formatBackups(params),\n ...formatSummary(params.outcomes),\n ]\n}\n\nconst RESTORE_OUTCOME_STYLE: Readonly<Record<RestoreOutcomeKind, StatusStyle>> = {\n restored: { glyph: GLYPHS.success, colour: pc.green, label: 'restored' },\n unchanged: { glyph: GLYPHS.unchanged, colour: pc.green, label: 'already as it was' },\n 'nothing-to-restore': { glyph: GLYPHS.absent, colour: pc.yellow, label: 'nothing to restore' },\n failed: { glyph: GLYPHS.failure, colour: pc.red, label: 'failed' },\n}\n\nconst NO_RECORD = 'nexos-connect has no record of setting it up at this scope.'\n\nfunction formatOutcome(outcome: RestoreOutcome, { home, masker }: FormatRestoreResultParams): string[] {\n const style = RESTORE_OUTCOME_STYLE[outcome.kind]\n const body = match(outcome)\n .with({ kind: P.union('restored', 'unchanged') }, (planned) => formatPlannedRestore(planned, home, masker))\n .with({ kind: 'nothing-to-restore' }, () => [`${INDENT}${pc.dim(NO_RECORD)}`])\n .with({ kind: 'failed' }, ({ error }) => [`${INDENT}${pc.red(masker.maskText(error))}`])\n .exhaustive()\n return ['', ` ${style.colour(`${style.glyph} ${outcome.target.label} — ${style.label}`)}`, ...body]\n}\n\nfunction formatPlannedRestore(outcome: PlannedRestore, home: string, masker: Masker): string[] {\n const restartNote = `Restart ${outcome.target.label} so it reads the restored config.`\n return [\n ...outcome.files.filter((file) => file.isChanged).map((file) => `${INDENT}${pc.dim(describeFile(file, home))}`),\n ...outcome.warnings.map((warning) => `${INDENT}${pc.yellow(`${GLYPHS.warning} ${masker.maskText(warning)}`)}`),\n ...(outcome.kind === 'restored' ? [`${INDENT}${pc.cyan(`${GLYPHS.next} ${restartNote}`)}`] : []),\n ]\n}\n\nfunction describeFile(file: RestoreFilePlan, home: string): string {\n const action = file.after === null ? 'deleted' : 'put back'\n return `${displayPath(file.path, home)} — ${action}`\n}\n\nfunction formatEnvFileStep({ envFile, mode, home }: FormatRestoreResultParams): string[] {\n if (mode.kind === 'dry-run' || envFile === null || !envFile.isChanged) return []\n\n const isEmpty = parseEnvFile(envFile.after, envFile.shell).size === 0\n const emptyNote = `${displayPath(envFile.path, home)} no longer sets anything: you can delete it, and the line that loads it.`\n return [\n ...formatHeading('One more step'),\n ...(isEmpty ? [` ${emptyNote}`] : []),\n ` ${pc.dim('Shells open now keep the variables it set; a new shell starts without them.')}`,\n ]\n}\n\nfunction formatBackups({ mode, home, masker }: FormatRestoreResultParams): string[] {\n if (mode.kind === 'dry-run' || mode.backupRoot === null) return []\n\n const backupRoot = masker.maskText(displayPath(mode.backupRoot, home))\n return [...formatHeading('Backups'), ` Current versions copied to ${pc.bold(backupRoot)}`]\n}\n\nfunction formatSummary(outcomes: readonly RestoreOutcome[]): string[] {\n const countsByKind = new Map<RestoreOutcomeKind, number>()\n for (const { kind } of outcomes) countsByKind.set(kind, (countsByKind.get(kind) ?? 0) + 1)\n\n const counts = RESTORE_OUTCOME_KINDS.map(\n (kind) => `${countsByKind.get(kind) ?? 0} ${RESTORE_OUTCOME_STYLE[kind].label}`,\n )\n return [...formatHeading('Summary'), ` ${counts.join(', ')}`]\n}\n","import { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedEnvVariable, RecordedPath } from '../../product/storage/restore-record/restore-record'\n\nexport type RestoreTarget = { id: string; label: string }\n\n/** `after` is `null` for a file nexos-connect created, which restore deletes. */\nexport type RestoreFilePlan = {\n path: string\n recordedPath: RecordedPath\n before: string\n after: string | null\n isChanged: boolean\n}\n\nexport type RestoreEnvPlan = { path: string; before: string; after: string; isChanged: boolean; shell: Shell }\n\nexport const RESTORE_OUTCOME_KINDS = ['restored', 'unchanged', 'nothing-to-restore', 'failed'] as const\n\nexport type RestoreOutcomeKind = (typeof RESTORE_OUTCOME_KINDS)[number]\n\nexport type PlannedRestore = {\n kind: 'restored' | 'unchanged'\n target: RestoreTarget\n files: readonly RestoreFilePlan[]\n envVariables: readonly RecordedEnvVariable[]\n warnings: readonly string[]\n}\n\nexport type NothingToRestore = { kind: 'nothing-to-restore'; target: RestoreTarget }\n\nexport type FailedRestore = { kind: 'failed'; target: RestoreTarget; error: string }\n\nexport type RestoreOutcome = PlannedRestore | NothingToRestore | FailedRestore\n\nexport function isPlannedRestore(outcome: RestoreOutcome): outcome is PlannedRestore {\n return outcome.kind === 'restored' || outcome.kind === 'unchanged'\n}\n\n// Only a named agent can come out with nothing to restore, and naming one asks for a restore that cannot happen.\nexport function exitCodeForRestore(outcomes: readonly RestoreOutcome[]): ExitCode {\n const isFailed = outcomes.some((outcome) => outcome.kind === 'failed' || outcome.kind === 'nothing-to-restore')\n return isFailed ? EXIT_CODE.failed : EXIT_CODE.ok\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { backUpBeforeWriting, ENV_FILE_BACKUP_DIRECTORY } from '../../product/storage/backups/back-up-before-writing'\nimport type { BackupRoot } from '../../product/storage/backups/resolve-backup-root'\nimport { writeEnvFile } from '../../product/storage/env-file/write-env-file'\nimport { removeHarnessRecords } from '../../product/storage/restore-record/remove-harness-records'\nimport { readRestoreRecord, writeRestoreRecord } from '../../product/storage/restore-record/restore-record'\nimport { resolveRestoreRecordLocation } from '../../product/storage/restore-record/restore-record-location'\nimport { describeFileError } from '../../shared/file-system/describe-file-error'\nimport { readFileMode } from '../../shared/file-system/read-file-mode'\nimport { writeFileWithMode } from '../../shared/file-system/write-file-with-mode'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { restoreEnvText } from './restore-env-text'\nimport type { RestorePlan } from './restore-plan'\nimport {\n isPlannedRestore,\n type RestoreEnvPlan,\n type RestoreFilePlan,\n type RestoreOutcome,\n type RestoreTarget,\n} from './restore-result'\n\nexport type ApplyRestoreParams = { plan: RestorePlan; ctx: PlatformContext; backupRoot: BackupRoot }\n\nexport type ApplyRestoreResult = {\n outcomes: RestoreOutcome[]\n envFile: RestoreEnvPlan | null\n writtenCount: number\n backupRoot: string | null\n}\n\nexport function applyRestore(params: ApplyRestoreParams): ApplyRestoreResult {\n const agentWrites = params.plan.outcomes.map((outcome) => restoreAgentFiles(outcome, params))\n const outcomes = agentWrites.map(({ outcome }) => outcome)\n const envFile = replanEnvFile(params.plan.envFile, outcomes)\n const envWrite = restoreSharedEnvFile({ outcomes, envFile, params })\n const writtenFiles = [...agentWrites.flatMap(({ writtenFiles }) => writtenFiles), ...envWrite.writtenFiles]\n return {\n outcomes: forgetRestored(envWrite.outcomes, params.ctx),\n envFile,\n writtenCount: writtenFiles.length,\n backupRoot: writtenFiles.some((file) => file.isBackedUp) ? params.backupRoot.path : null,\n }\n}\n\ntype WrittenFile = { isBackedUp: boolean }\n\ntype AgentWrite = { outcome: RestoreOutcome; writtenFiles: WrittenFile[] }\n\nfunction restoreAgentFiles(outcome: RestoreOutcome, params: ApplyRestoreParams): AgentWrite {\n if (outcome.kind !== 'restored') return { outcome, writtenFiles: [] }\n\n const writtenFiles: WrittenFile[] = []\n for (const file of outcome.files.filter((plan) => plan.isChanged)) {\n try {\n writtenFiles.push(restoreFile({ file, target: outcome.target, params }))\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: params.ctx.home })\n return { outcome: { kind: 'failed', target: outcome.target, error: reason }, writtenFiles }\n }\n }\n return { outcome, writtenFiles }\n}\n\ntype RestoreFileParams = { file: RestoreFilePlan; target: RestoreTarget; params: ApplyRestoreParams }\n\nfunction restoreFile({ file, target, params }: RestoreFileParams): WrittenFile {\n const { ctx, backupRoot } = params\n const relativePath = path.join(target.id, path.basename(file.path))\n const backup = backUpBeforeWriting({ filePath: file.path, before: file.before, backupRoot, relativePath, ctx })\n if (file.after === null) {\n fs.rmSync(file.path)\n return backup\n }\n\n writeFileWithMode({ filePath: file.path, content: file.after, mode: readFileMode(file.path, ctx.platform) })\n return backup\n}\n\n// Leaves out the variables of an agent whose files could not be restored, as setup leaves out a failed agent's.\nfunction replanEnvFile(envFile: RestoreEnvPlan | null, outcomes: readonly RestoreOutcome[]): RestoreEnvPlan | null {\n if (envFile === null) return null\n\n const variables = outcomes.flatMap((outcome) => (isPlannedRestore(outcome) ? outcome.envVariables : []))\n const after = restoreEnvText({ current: envFile.before, variables, shell: envFile.shell })\n return { ...envFile, after, isChanged: after !== envFile.before }\n}\n\ntype RestoreSharedEnvFileParams = {\n outcomes: RestoreOutcome[]\n envFile: RestoreEnvPlan | null\n params: ApplyRestoreParams\n}\n\ntype EnvWrite = { outcomes: RestoreOutcome[]; writtenFiles: WrittenFile[] }\n\nfunction restoreSharedEnvFile({ outcomes, envFile, params }: RestoreSharedEnvFileParams): EnvWrite {\n if (envFile === null || !envFile.isChanged) return { outcomes, writtenFiles: [] }\n\n const { ctx, backupRoot } = params\n try {\n const relativePath = path.join(ENV_FILE_BACKUP_DIRECTORY, path.basename(envFile.path))\n const backup = backUpBeforeWriting({\n filePath: envFile.path,\n before: envFile.before,\n backupRoot,\n relativePath,\n ctx,\n })\n writeEnvFile({ filePath: envFile.path, content: envFile.after, platform: ctx.platform })\n return { outcomes, writtenFiles: [backup] }\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: ctx.home })\n return { outcomes: outcomes.map((outcome) => failIfRestoringEnvFile(outcome, reason)), writtenFiles: [] }\n }\n}\n\nfunction failIfRestoringEnvFile(outcome: RestoreOutcome, error: string): RestoreOutcome {\n if (!isPlannedRestore(outcome) || outcome.envVariables.length === 0) return outcome\n\n return { kind: 'failed', target: outcome.target, error }\n}\n\n// A failed agent keeps its record, so a second restore can finish the job.\nfunction forgetRestored(outcomes: readonly RestoreOutcome[], ctx: PlatformContext): RestoreOutcome[] {\n const restoredIds = outcomes.filter(isPlannedRestore).map(({ target }) => target.id)\n if (restoredIds.length === 0) return [...outcomes]\n\n const { filePath } = resolveRestoreRecordLocation(ctx)\n try {\n const record = readRestoreRecord({ filePath, home: ctx.home })\n if (record !== null) {\n writeRestoreRecord({ filePath, record: removeHarnessRecords(record, restoredIds), platform: ctx.platform })\n }\n return [...outcomes]\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: ctx.home })\n return outcomes.map((outcome) => failIfPlanned(outcome, reason))\n }\n}\n\nfunction failIfPlanned(outcome: RestoreOutcome, error: string): RestoreOutcome {\n if (!isPlannedRestore(outcome)) return outcome\n\n return { kind: 'failed', target: outcome.target, error }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { readFileMode } from '../../../shared/file-system/read-file-mode'\n\nexport type BackUpFileParams = {\n source: string\n root: string\n relativePath: string\n platform: NodeJS.Platform\n}\n\nconst BACKUP_DIRECTORY_MODE = 0o700\nconst OWNER_PERMISSION_BITS = 0o700\n\nexport function backUpFile({ source, root, relativePath, platform }: BackUpFileParams): void {\n const destination = path.join(root, relativePath)\n fs.mkdirSync(path.dirname(destination), { recursive: true, mode: BACKUP_DIRECTORY_MODE })\n fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL)\n\n const mode = readFileMode(source, platform)\n if (mode !== null) fs.chmodSync(destination, mode & OWNER_PERMISSION_BITS)\n}\n\nconst IGNORE_EVERYTHING = '*\\n'\n\nexport function ignoreBackupsInGit(directory: string): void {\n const ignoreFile = path.join(directory, '.gitignore')\n if (fs.existsSync(ignoreFile)) return\n\n fs.mkdirSync(directory, { recursive: true, mode: BACKUP_DIRECTORY_MODE })\n fs.writeFileSync(ignoreFile, IGNORE_EVERYTHING)\n}\n","import fs from 'node:fs'\nimport { isMissingFileError } from './is-missing-file-error'\n\nconst PERMISSION_BITS = 0o777\n\nexport function readFileMode(filePath: string, platform: NodeJS.Platform): number | null {\n if (platform === 'win32') return null\n\n try {\n return fs.statSync(filePath).mode & PERMISSION_BITS\n } catch (error) {\n if (isMissingFileError(error)) return null\n throw error\n }\n}\n","import { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath } from '../../../shared/text/display-path'\nimport { backUpFile, ignoreBackupsInGit } from './back-up-file'\nimport type { BackupRoot } from './resolve-backup-root'\n\nexport const ENV_FILE_BACKUP_DIRECTORY = '_env'\n\nexport type BackUpBeforeWritingParams = {\n filePath: string\n before: string | null\n backupRoot: BackupRoot\n relativePath: string\n ctx: PlatformContext\n}\n\nexport type BackUpBeforeWritingResult = { isBackedUp: boolean }\n\n/** Throws, copying nothing, when the file no longer holds `before`: the preview did not show what it holds now. */\nexport function backUpBeforeWriting(params: BackUpBeforeWritingParams): BackUpBeforeWritingResult {\n const { filePath, before, backupRoot, ctx } = params\n assertUnchangedSincePreview({ filePath, before, home: ctx.home })\n if (before === null) return { isBackedUp: false }\n\n if (backupRoot.gitIgnoredDirectory !== null) ignoreBackupsInGit(backupRoot.gitIgnoredDirectory)\n backUpFile({ source: filePath, root: backupRoot.path, relativePath: params.relativePath, platform: ctx.platform })\n return { isBackedUp: true }\n}\n\ntype AssertUnchangedSincePreviewParams = { filePath: string; before: string | null; home: string }\n\nfunction assertUnchangedSincePreview({ filePath, before, home }: AssertUnchangedSincePreviewParams): void {\n if (readFileIfExists(filePath) === before) return\n\n throw new Error(\n `${displayPath(filePath, home)} changed after the preview, so it was left as it is. ` +\n 'Run again to see the new changes.',\n )\n}\n","import { resolveOwnerOnlyMode } from '../../../shared/file-system/resolve-owner-only-mode'\nimport { writeFileWithMode } from '../../../shared/file-system/write-file-with-mode'\n\nexport type WriteEnvFileParams = { filePath: string; content: string; platform: NodeJS.Platform }\n\nexport function writeEnvFile({ filePath, content, platform }: WriteEnvFileParams): void {\n writeFileWithMode({ filePath, content, mode: resolveOwnerOnlyMode(platform) })\n}\n","import type { RestoreRecord } from './restore-record'\n\nexport function removeHarnessRecords(record: RestoreRecord, harnessIds: readonly string[]): RestoreRecord {\n const harnesses = Object.fromEntries(Object.entries(record.harnesses).filter(([id]) => !harnessIds.includes(id)))\n return { ...record, harnesses }\n}\n","import { detectLineEnding, type LineEnding } from '../../../shared/file-formats/detect-line-ending'\nimport { splitByteOrderMark } from '../../../shared/file-formats/split-byte-order-mark'\nimport { splitLines } from './split-lines'\nimport { SHELLS, type EnvSyntax, type EnvVariable, type Shell } from './syntax/env-syntax'\nimport { ENV_SYNTAXES } from './syntax/env-syntaxes'\n\n/** Undefined removes the variable's assignments rather than writing one. */\nexport type EnvFileVariables = Readonly<Record<string, string | undefined>>\n\nexport type RenderEnvFileParams = { current: string | null; variables: EnvFileVariables; shell: Shell }\n\nexport function renderEnvFile({ current, variables, shell }: RenderEnvFileParams): string {\n const syntax = ENV_SYNTAXES[shell]\n const { byteOrderMark, body: existing } = splitByteOrderMark(current ?? '')\n const lineEnding = detectLineEnding(existing) ?? syntax.defaultLineEnding\n const removedNames = new Set(\n Object.entries(variables).flatMap(([name, value]) => (value === undefined ? [syntax.normalizeName(name)] : [])),\n )\n\n const bodyLines = splitLines(existing).filter(\n (line) => !isHeaderLine(line) && !isAssignmentOf({ line, names: removedNames, syntax }),\n )\n const { lines, missing } = replaceAssignments({ lines: bodyLines, variables, syntax })\n const body = appendMissing({ lines: trimBlankLines(lines), missing, syntax })\n\n return byteOrderMark + joinLines([...syntax.headerLines, ...body], lineEnding)\n}\n\nexport type RemoveEnvVariablesParams = { current: string; names: readonly string[]; shell: Shell }\n\nexport function removeEnvVariables({ current, names, shell }: RemoveEnvVariablesParams): string {\n const syntax = ENV_SYNTAXES[shell]\n const { byteOrderMark, body: existing } = splitByteOrderMark(current)\n const lineEnding = detectLineEnding(existing) ?? syntax.defaultLineEnding\n const removedNames = new Set(names.map((name) => syntax.normalizeName(name)))\n\n const bodyLines = splitLines(existing).filter(\n (line) => !isHeaderLine(line) && !isAssignmentOf({ line, names: removedNames, syntax }),\n )\n return byteOrderMark + joinLines([...syntax.headerLines, ...trimBlankLines(bodyLines)], lineEnding)\n}\n\nconst HEADER_LINES = SHELLS.flatMap((shell) => ENV_SYNTAXES[shell].headerLines)\n\nfunction isHeaderLine(line: string): boolean {\n return HEADER_LINES.some((headerLine) => line.startsWith(headerLine))\n}\n\ntype ReplaceAssignmentsParams = { lines: readonly string[]; variables: EnvFileVariables; syntax: EnvSyntax }\ntype ReplaceAssignmentsResult = { lines: string[]; missing: EnvVariable[] }\n\nfunction replaceAssignments(params: ReplaceAssignmentsParams): ReplaceAssignmentsResult {\n const { lines, variables, syntax } = params\n const pending = new Map(\n Object.entries(variables).flatMap(([name, value]) =>\n value === undefined ? [] : [[syntax.normalizeName(name), { name, value }] as const],\n ),\n )\n const replacedNames = new Set<string>()\n const kept: string[] = []\n\n for (const line of lines) {\n const name = matchNormalizedName(line, syntax)\n if (name !== undefined && replacedNames.has(name)) continue\n\n const variable = name === undefined ? undefined : pending.get(name)\n if (name === undefined || variable === undefined) {\n kept.push(line)\n continue\n }\n\n kept.push(syntax.formatAssignment(variable))\n pending.delete(name)\n replacedNames.add(name)\n }\n\n return { lines: kept, missing: [...pending.values()] }\n}\n\nfunction matchNormalizedName(line: string, syntax: EnvSyntax): string | undefined {\n const assignment = syntax.matchAssignment(line)\n if (assignment === undefined) return undefined\n return syntax.normalizeName(assignment.name)\n}\n\ntype IsAssignmentOfParams = { line: string; names: ReadonlySet<string>; syntax: EnvSyntax }\n\nfunction isAssignmentOf({ line, names, syntax }: IsAssignmentOfParams): boolean {\n const name = matchNormalizedName(line, syntax)\n return name !== undefined && names.has(name)\n}\n\nfunction trimBlankLines(lines: readonly string[]): readonly string[] {\n const firstIndex = lines.findIndex((line) => !isBlank(line))\n if (firstIndex === -1) return []\n\n const lastIndex = lines.findLastIndex((line) => !isBlank(line))\n return lines.slice(firstIndex, lastIndex + 1)\n}\n\nfunction isBlank(line: string): boolean {\n return line.trim() === ''\n}\n\ntype AppendMissingParams = { lines: readonly string[]; missing: readonly EnvVariable[]; syntax: EnvSyntax }\n\nfunction appendMissing({ lines, missing, syntax }: AppendMissingParams): readonly string[] {\n if (missing.length === 0) return lines\n\n const assignments = [...missing].sort(compareByName).map((variable) => syntax.formatAssignment(variable))\n if (lines.length === 0) return assignments\n return [...lines, '', ...assignments]\n}\n\nfunction compareByName(first: EnvVariable, second: EnvVariable): number {\n if (first.name < second.name) return -1\n if (first.name > second.name) return 1\n return 0\n}\n\nfunction joinLines(lines: readonly string[], lineEnding: LineEnding): string {\n return lines.map((line) => line + lineEnding).join('')\n}\n","import { removeEnvVariables, renderEnvFile } from '../../product/storage/env-file/render-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedEnvVariable } from '../../product/storage/restore-record/restore-record'\n\nexport type RestoreEnvTextParams = { current: string; variables: readonly RecordedEnvVariable[]; shell: Shell }\n\nexport function restoreEnvText({ current, variables, shell }: RestoreEnvTextParams): string {\n const withOriginals = setOriginalsBack({ current, variables, shell })\n const removedNames = variables.filter(({ original }) => original === null).map(({ name }) => name)\n if (removedNames.length === 0) return withOriginals\n\n return removeEnvVariables({ current: withOriginals, names: removedNames, shell })\n}\n\nfunction setOriginalsBack({ current, variables, shell }: RestoreEnvTextParams): string {\n const originals = Object.fromEntries(\n variables.flatMap(({ name, original }) => (original === null ? [] : [[name, original]])),\n )\n if (Object.keys(originals).length === 0) return current\n\n return renderEnvFile({ current, variables: originals, shell })\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport { PROJECT_BACKUP_DIRECTORY, USER_BACKUP_DIRECTORY } from '../../product/storage/backups/resolve-backup-root'\nimport { NO_ENV_FILE, readEnvFile, type EnvFileRead } from '../../product/storage/env-file/read-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type {\n HarnessRecord,\n RecordedEnvVariable,\n RecordedFile,\n RestoreRecord,\n} from '../../product/storage/restore-record/restore-record'\nimport {\n fromRecordedPath,\n resolveRestoreRecordLocation,\n} from '../../product/storage/restore-record/restore-record-location'\nimport { ConfigFormatError } from '../../shared/file-formats/config-errors'\nimport { isEmptyConfig, restoreConfig } from '../../shared/file-formats/config-format'\nimport { describeFileError } from '../../shared/file-system/describe-file-error'\nimport { readFileIfExists } from '../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { restoreEnvText } from './restore-env-text'\nimport {\n isPlannedRestore,\n type RestoreEnvPlan,\n type RestoreFilePlan,\n type RestoreOutcome,\n type RestoreTarget,\n} from './restore-result'\n\nexport type RestoreCandidate = { target: RestoreTarget; record: HarnessRecord | null }\n\nexport type PlanRestoreParams = {\n candidates: readonly RestoreCandidate[]\n record: RestoreRecord\n ctx: PlatformContext\n envPath: string\n shell: Shell\n}\n\nexport type RestorePlan = { outcomes: RestoreOutcome[]; envFile: RestoreEnvPlan | null }\n\nexport function planRestore(params: PlanRestoreParams): RestorePlan {\n const { candidates, ctx, envPath } = params\n const hasEnvVariables = candidates.some(({ record }) => (record?.envVariables.length ?? 0) > 0)\n const envFileRead = hasEnvVariables ? readEnvFile({ envPath, home: ctx.home }) : NO_ENV_FILE\n const namesKept = listNamesRecordedElsewhere(params)\n const outcomes = candidates.map((candidate) => planCandidate({ candidate, envFileRead, namesKept, params }))\n return { outcomes, envFile: planEnvFile({ outcomes, envFileRead, params }) }\n}\n\n// A variable another agent still has recorded is still that agent's, so restoring this one must leave it.\nfunction listNamesRecordedElsewhere({ candidates, record }: PlanRestoreParams): ReadonlySet<string> {\n const selectedIds = candidates.map(({ target }) => target.id)\n const others = Object.entries(record.harnesses).filter(([id]) => !selectedIds.includes(id))\n return new Set(others.flatMap(([, harness]) => harness.envVariables.map(({ name }) => name)))\n}\n\ntype PlanCandidateParams = {\n candidate: RestoreCandidate\n envFileRead: EnvFileRead\n namesKept: ReadonlySet<string>\n params: PlanRestoreParams\n}\n\nfunction planCandidate({ candidate, envFileRead, namesKept, params }: PlanCandidateParams): RestoreOutcome {\n const { target, record } = candidate\n if (record === null) return { kind: 'nothing-to-restore', target }\n\n const envVariables = record.envVariables.filter(({ name }) => !namesKept.has(name))\n if (envVariables.length > 0 && envFileRead.kind === 'failed') {\n return { kind: 'failed', target, error: envFileRead.error }\n }\n\n try {\n const { files, warnings } = planRecordedFiles(record.files, params.ctx)\n const hasEnvChange = hasOwnEnvChange({ envFileRead, envVariables, shell: params.shell })\n const isChanged = hasEnvChange || files.some((file) => file.isChanged)\n return { kind: isChanged ? 'restored' : 'unchanged', target, files, envVariables, warnings }\n } catch (error) {\n return { kind: 'failed', target, error: describeFileError({ error, action: 'read', home: params.ctx.home }) }\n }\n}\n\ntype HasOwnEnvChangeParams = {\n envFileRead: EnvFileRead\n envVariables: readonly RecordedEnvVariable[]\n shell: Shell\n}\n\nfunction hasOwnEnvChange({ envFileRead, envVariables, shell }: HasOwnEnvChangeParams): boolean {\n if (envFileRead.kind !== 'read' || envFileRead.text === null || envVariables.length === 0) return false\n\n return restoreEnvText({ current: envFileRead.text, variables: envVariables, shell }) !== envFileRead.text\n}\n\ntype PlannedFiles = { files: RestoreFilePlan[]; warnings: string[] }\n\nfunction planRecordedFiles(recordedFiles: readonly RecordedFile[], ctx: PlatformContext): PlannedFiles {\n const results = recordedFiles.map((file) => planRecordedFile(file, ctx))\n return {\n files: results.flatMap((result) => (result.kind === 'planned' ? [result.plan] : [])),\n warnings: results.flatMap((result) => (result.kind === 'missing' ? result.warnings : [])),\n }\n}\n\ntype RecordedFileResult = { kind: 'planned'; plan: RestoreFilePlan } | { kind: 'missing'; warnings: string[] }\n\nfunction planRecordedFile(file: RecordedFile, ctx: PlatformContext): RecordedFileResult {\n const filePath = fromRecordedPath(file.path, resolveRestoreRecordLocation(ctx).root)\n const before = readFileIfExists(filePath)\n if (before === null) {\n return { kind: 'missing', warnings: file.origin === 'content' ? [describeMissingFile(filePath, ctx)] : [] }\n }\n\n const after = restoreFile({ file, before, filePath, home: ctx.home })\n return {\n kind: 'planned',\n plan: { path: filePath, recordedPath: file.path, before, after, isChanged: before !== after },\n }\n}\n\nfunction describeMissingFile(filePath: string, ctx: PlatformContext): string {\n const backups = match(ctx.scope)\n .with('user', () => path.join(ctx.home, USER_BACKUP_DIRECTORY))\n .with('project', () => path.join(ctx.cwd, PROJECT_BACKUP_DIRECTORY))\n .exhaustive()\n return (\n `${displayPath(filePath, ctx.home)} no longer exists, so it was left as it is. Copies from before each run ` +\n `are under ${displayPath(backups, ctx.home)}, unless --backup-dir put them elsewhere.`\n )\n}\n\ntype RestoreFileParams = { file: RecordedFile; before: string; filePath: string; home: string }\n\nfunction restoreFile({ file, before, filePath, home }: RestoreFileParams): string | null {\n try {\n const restored = restoreConfig({ format: file.format, current: before, originals: file.keys })\n if (file.origin === 'content' || !isEmptyConfig(file.format, restored)) return restored\n\n return file.origin === 'blank' ? '' : null\n } catch (error) {\n if (!(error instanceof ConfigFormatError)) throw error\n throw new Error(`${displayPath(filePath, home)}: ${error.message}`, { cause: error })\n }\n}\n\ntype PlanEnvFileParams = { outcomes: readonly RestoreOutcome[]; envFileRead: EnvFileRead; params: PlanRestoreParams }\n\nfunction planEnvFile({ outcomes, envFileRead, params }: PlanEnvFileParams): RestoreEnvPlan | null {\n const variables = outcomes.flatMap((outcome) => (isPlannedRestore(outcome) ? outcome.envVariables : []))\n if (variables.length === 0 || envFileRead.kind === 'failed' || envFileRead.text === null) return null\n\n const before = envFileRead.text\n const after = restoreEnvText({ current: before, variables, shell: params.shell })\n return { path: params.envPath, before, after, isChanged: before !== after, shell: params.shell }\n}\n","import { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\n\nexport type EnvFileRead = { kind: 'read'; text: string | null } | { kind: 'failed'; error: string }\n\nexport const NO_ENV_FILE: EnvFileRead = { kind: 'read', text: null }\n\nexport type ReadEnvFileParams = { envPath: string; home: string }\n\nexport function readEnvFile({ envPath, home }: ReadEnvFileParams): EnvFileRead {\n try {\n return { kind: 'read', text: readFileIfExists(envPath) }\n } catch (error) {\n return { kind: 'failed', error: describeFileError({ error, action: 'read', home }) }\n }\n}\n","import { findExistingKeys } from '../../flows/key/find-existing-keys'\nimport { harnesses } from '../../harnesses/registry'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { HarnessRecord, RecordedFile, RestoreRecord } from '../../product/storage/restore-record/restore-record'\nimport { ConfigFormatError } from '../../shared/file-formats/config-errors'\nimport { parseValueSource } from '../../shared/file-formats/config-format'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\n\nexport type ListRestoreSecretsParams = { record: RestoreRecord; ctx: PlatformContext; envPath: string; shell: Shell }\n\n/** The keys a restore diff can show: the ones on disk now, and the ones the record puts back. */\nexport function listRestoreSecrets({ record, ctx, envPath, shell }: ListRestoreSecretsParams): string[] {\n const recorded = Object.values(record.harnesses).flatMap((harness) => [\n ...harness.files.flatMap(listFileSecrets),\n ...listEnvSecrets(harness),\n ])\n return [...findExistingKeys({ ctx, envPath, shell }).all, ...recorded]\n}\n\nfunction listFileSecrets(file: RecordedFile): string[] {\n return file.keys.flatMap(({ original, holdsSecret }) => {\n if (!holdsSecret || original === null) return []\n\n const value = readOriginalValue(file, original)\n return typeof value === 'string' ? [value] : []\n })\n}\n\n// An original that no longer parses fails its agent when the restore is planned, which reports it.\nfunction readOriginalValue(file: RecordedFile, original: string): unknown {\n try {\n return parseValueSource(file.format, original)\n } catch (error) {\n if (error instanceof ConfigFormatError) return undefined\n throw error\n }\n}\n\nconst KEY_ENV_VARIABLES = harnesses.flatMap((harness) =>\n harness.kind === 'configurable' && harness.keyEnvVariable !== undefined ? [harness.keyEnvVariable] : [],\n)\n\nfunction listEnvSecrets(harness: HarnessRecord): string[] {\n return harness.envVariables.flatMap(({ name, original }) =>\n KEY_ENV_VARIABLES.includes(name) && original !== null ? [original] : [],\n )\n}\n","import pc from 'picocolors'\nimport type { DetectedHarness, Detection } from '../../commands/setup/answers/harness-selection'\nimport type { Harness } from '../../harnesses/harness'\nimport type { Masker } from '../../product/secrets/masker'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport { INDENT } from './indent'\nimport type { StatusStyle } from './outcome-style'\n\nexport function formatDetection(rows: readonly DetectedHarness[], masker: Masker): string[] {\n return [\n ...formatHeading('Where each agent keeps its settings'),\n ...rows.flatMap((row) => formatDetectionRow(row, masker)),\n ]\n}\n\nconst LABEL_COLUMN_WIDTH = 24\n\ntype DetectionStatus = Detection['kind'] | 'not-configurable'\n\nconst DETECTION_STYLE: Readonly<Record<DetectionStatus, StatusStyle>> = {\n found: { glyph: GLYPHS.success, colour: pc.green, label: 'found' },\n 'not-found': { glyph: GLYPHS.absent, colour: pc.dim, label: 'not found' },\n failed: { glyph: GLYPHS.failure, colour: pc.red, label: 'could not check' },\n 'not-configurable': { glyph: GLYPHS.failure, colour: pc.yellow, label: 'not configurable' },\n}\n\nfunction formatDetectionRow({ harness, detection }: DetectedHarness, masker: Masker): string[] {\n const style = DETECTION_STYLE[findDetectionStatus(harness, detection)]\n return [\n ` ${style.colour(style.glyph)} ${harness.label.padEnd(LABEL_COLUMN_WIDTH)} ${style.colour(style.label)}`,\n `${INDENT}${pc.dim(masker.maskText(detection.detail))}`,\n ]\n}\n\nfunction findDetectionStatus(harness: Harness, detection: Detection): DetectionStatus {\n if (harness.kind === 'unsupported' && detection.kind !== 'failed') return 'not-configurable'\n\n return detection.kind\n}\n","import pc from 'picocolors'\nimport { P, match } from 'ts-pattern'\nimport {\n OUTCOME_KINDS,\n type EnvPlan,\n type HarnessOutcome,\n type OutcomeKind,\n type PlannedOutcome,\n} from '../../commands/setup/setup-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { ENV_SYNTAXES } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatList } from '../format-list'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport { INDENT, NESTED_INDENT, indentLines } from './indent'\nimport { OUTCOME_STYLE } from './outcome-style'\n\nexport type ResultMode = { kind: 'dry-run' } | { kind: 'written'; backupRoot: string | null }\n\nexport type RunHint = { binary: string; label: string }\n\nexport type FormatResultParams = {\n outcomes: readonly HarnessOutcome[]\n envFile: EnvPlan | null\n mode: ResultMode\n home: string\n masker: Masker\n runHints: readonly RunHint[]\n}\n\nexport function formatResult(params: FormatResultParams): string[] {\n const heading = params.mode.kind === 'dry-run' ? 'Result (dry run)' : 'Result'\n return [\n ...formatHeading(heading),\n ...params.outcomes.flatMap((outcome) => formatOutcome(outcome, params)),\n ...formatLoadStep(params),\n ...formatBackups(params),\n ...formatSummary(params.outcomes),\n ...formatRunHints(params),\n ]\n}\n\nfunction formatOutcome(outcome: HarnessOutcome, params: FormatResultParams): string[] {\n const { masker } = params\n const style = OUTCOME_STYLE[outcome.kind]\n const body = match(outcome)\n .with({ kind: P.union('updated', 'unchanged') }, (planned) => formatPlannedOutcome(planned, params))\n .with({ kind: 'not-found' }, ({ detail }) => [`${INDENT}${pc.dim(masker.maskText(detail))}`])\n .with({ kind: 'unsupported' }, ({ harness }) => [`${INDENT}${pc.dim(harness.reason)}`])\n .with({ kind: 'failed' }, ({ error }) => [`${INDENT}${pc.red(masker.maskText(error))}`])\n .exhaustive()\n return ['', ` ${style.colour(`${style.glyph} ${outcome.harness.label} — ${style.label}`)}`, ...body]\n}\n\nfunction formatPlannedOutcome(outcome: PlannedOutcome, { envFile, home, masker }: FormatResultParams): string[] {\n return [\n `${INDENT}${pc.dim(masker.maskText(outcome.detail))}`,\n ...outcome.warnings.map((warning) => `${INDENT}${pc.yellow(`${GLYPHS.warning} ${masker.maskText(warning)}`)}`),\n ...outcome.files.filter((file) => file.isChanged).flatMap((file) => formatResultingFile(file.after, masker)),\n ...(envFile === null ? [] : formatEnvVariables({ outcome, envFile, home, masker })),\n ...formatPostSetupNotes(outcome),\n ]\n}\n\nfunction formatResultingFile(content: string, masker: Masker): string[] {\n return [\n `${INDENT}${pc.dim('resulting file:')}`,\n ...indentLines({ text: masker.maskText(content), indent: NESTED_INDENT }),\n ]\n}\n\ntype FormatEnvVariablesParams = { outcome: PlannedOutcome; envFile: EnvPlan; home: string; masker: Masker }\n\nfunction formatEnvVariables({ outcome, envFile, home, masker }: FormatEnvVariablesParams): string[] {\n const variables = Object.entries(outcome.envVariables).flatMap(([name, value]) =>\n value === undefined ? [] : [[name, value] as const],\n )\n if (variables.length === 0) return []\n\n const syntax = ENV_SYNTAXES[envFile.shell]\n return [\n `${INDENT}${pc.dim(`variables in ${displayPath(envFile.path, home)}:`)}`,\n ...variables.map(([name, value]) => `${NESTED_INDENT}${masker.maskText(syntax.formatAssignment({ name, value }))}`),\n ]\n}\n\nfunction formatPostSetupNotes({ kind, harness }: PlannedOutcome): string[] {\n if (kind === 'unchanged') return []\n\n return (harness.postSetupNotes ?? []).map((note) => `${INDENT}${pc.cyan(`${GLYPHS.next} ${note}`)}`)\n}\n\nfunction formatLoadStep({ outcomes, envFile, mode }: FormatResultParams): string[] {\n if (mode.kind === 'dry-run' || envFile === null || !envFile.isChanged) return []\n\n const readers = outcomes\n .filter((outcome) => outcome.kind === 'updated' && Object.keys(outcome.envVariables).length > 0)\n .map((outcome) => outcome.harness.label)\n if (readers.length === 0) return []\n\n const [verb, pronoun] = readers.length === 1 ? ['reads', 'it'] : ['read', 'they']\n const { loadCommand } = ENV_SYNTAXES[envFile.shell]\n return [\n ...formatHeading('One more step'),\n ` ${formatList(readers)} ${verb} the key from the environment. Load it with:`,\n `${INDENT}${pc.bold(loadCommand)}`,\n ` ${pc.dim(`Until then ${pronoun} will not see the key.`)}`,\n ...match(envFile.shell)\n .with('powershell', () => [\n ` ${pc.dim('That lasts for this session only. Add the same line to $PROFILE to keep it.')}`,\n ])\n .with('posix', () => [])\n .exhaustive(),\n ]\n}\n\nfunction formatBackups({ mode, home, masker }: FormatResultParams): string[] {\n if (mode.kind === 'dry-run' || mode.backupRoot === null) return []\n\n const backupRoot = masker.maskText(displayPath(mode.backupRoot, home))\n return [...formatHeading('Backups'), ` Originals copied to ${pc.bold(backupRoot)}`]\n}\n\nfunction formatSummary(outcomes: readonly HarnessOutcome[]): string[] {\n const countsByKind = new Map<OutcomeKind, number>()\n for (const { kind } of outcomes) countsByKind.set(kind, (countsByKind.get(kind) ?? 0) + 1)\n\n const counts = OUTCOME_KINDS.map((kind) => `${countsByKind.get(kind) ?? 0} ${OUTCOME_STYLE[kind].label}`)\n return [...formatHeading('Summary'), ` ${counts.join(', ')}`]\n}\n\nfunction formatRunHints({ runHints, mode }: FormatResultParams): string[] {\n if (mode.kind !== 'written' || runHints.length === 0) return []\n\n return ['', \"You're all set up.\", ...runHints.map(formatRunHint)]\n}\n\nfunction formatRunHint({ binary, label }: RunHint): string {\n return ` Run \\`${binary}\\` to use ${label} with the nexos.ai Gateway.`\n}\n","import { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport type { ConfigurableHarness, Harness, UnsupportedHarness } from '../../harnesses/harness'\nimport type { EnvFileVariables } from '../../product/storage/env-file/render-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedKey } from '../../product/storage/restore-record/restore-record'\nimport type { ConfigFormat } from '../../shared/file-formats/config-format'\n\nexport type FilePlan = { path: string; before: string | null; after: string; isChanged: boolean }\n\nexport type HarnessFilePlan = FilePlan & {\n hasSecret: boolean\n format: ConfigFormat\n originals: readonly RecordedKey[]\n}\n\nexport type EnvPlan = FilePlan & { shell: Shell }\n\nexport const OUTCOME_KINDS = ['updated', 'unchanged', 'not-found', 'unsupported', 'failed'] as const\n\nexport type OutcomeKind = (typeof OUTCOME_KINDS)[number]\n\nexport type PlannedOutcome = {\n kind: 'updated' | 'unchanged'\n harness: ConfigurableHarness\n detail: string\n files: readonly HarnessFilePlan[]\n envVariables: EnvFileVariables\n warnings: readonly string[]\n}\n\nexport type NotFoundOutcome = { kind: 'not-found'; harness: Harness; detail: string }\n\nexport type UnsupportedOutcome = { kind: 'unsupported'; harness: UnsupportedHarness }\n\nexport type FailedOutcome = { kind: 'failed'; harness: Harness; error: string }\n\nexport type HarnessOutcome = PlannedOutcome | NotFoundOutcome | UnsupportedOutcome | FailedOutcome\n\nexport function isPlanned(outcome: HarnessOutcome): outcome is PlannedOutcome {\n return outcome.kind === 'updated' || outcome.kind === 'unchanged'\n}\n\nexport function exitCodeFor(outcomes: readonly HarnessOutcome[]): ExitCode {\n return outcomes.some((outcome) => outcome.kind === 'failed') ? EXIT_CODE.failed : EXIT_CODE.ok\n}\n","export function formatList(items: readonly string[]): string {\n if (items.length <= 1) return items.join('')\n\n return `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`\n}\n","import pc from 'picocolors'\nimport type { OutcomeKind } from '../../commands/setup/setup-result'\nimport { GLYPHS } from '../glyphs'\n\nexport type StatusStyle = { glyph: string; colour: (text: string) => string; label: string }\n\nexport const OUTCOME_STYLE: Readonly<Record<OutcomeKind, StatusStyle>> = {\n updated: { glyph: GLYPHS.success, colour: pc.green, label: 'updated' },\n unchanged: { glyph: GLYPHS.unchanged, colour: pc.green, label: 'already configured' },\n 'not-found': { glyph: GLYPHS.absent, colour: pc.dim, label: 'not found' },\n unsupported: { glyph: GLYPHS.failure, colour: pc.yellow, label: 'not configurable' },\n failed: { glyph: GLYPHS.failure, colour: pc.red, label: 'failed' },\n}\n","import { match } from 'ts-pattern'\nimport type { ConfigurableHarness } from '../../../harnesses/harness'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath, displayRelativePath } from '../../../shared/text/display-path'\nimport { formatList } from '../../../ui/format-list'\nimport { listConfigPaths } from './scope'\n\nexport type DescribeKeyDestinationParams = {\n configurable: readonly ConfigurableHarness[]\n ctx: PlatformContext\n envPath: string\n}\n\nexport function describeKeyDestination({ configurable, ctx, envPath }: DescribeKeyDestinationParams): string {\n const configReaders = configurable.filter((harness) => harness.keyEnvVariable === undefined)\n const configFiles = listConfigPaths(configReaders, ctx).map((filePath) => displayScopedPath(filePath, ctx))\n const envReaders = configurable\n .filter((harness) => harness.keyEnvVariable !== undefined)\n .map((harness) => harness.label)\n if (envReaders.length === 0) return `It will be written to ${formatList(configFiles)}.`\n\n const envFile = `${displayPath(envPath, ctx.home)} for ${formatList(envReaders)}`\n if (configFiles.length === 0) return `It will be written to ${envFile}.`\n\n return `It will be written to ${formatList(configFiles)}, and to ${envFile}.`\n}\n\nfunction displayScopedPath(filePath: string, ctx: PlatformContext): string {\n return match(ctx.scope)\n .with('user', () => displayPath(filePath, ctx.home))\n .with('project', () => displayRelativePath(filePath, ctx.cwd))\n .exhaustive()\n}\n","import type { ConfigurableHarness } from '../../../harnesses/harness'\nimport { harnesses } from '../../../harnesses/registry'\nimport { DEFAULT_SCOPE, type ConfigScope, type PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath, displayRelativePath } from '../../../shared/text/display-path'\nimport type { SelectScopeParams } from '../../../ui/prompts/select-scope'\nimport type { TerminalUi } from '../../../ui/terminal-ui'\n\nexport type ResolveScopeParams = {\n requestedScope: ConfigScope | undefined\n shouldAssumeYes: boolean\n baseContext: PlatformContext\n ui: TerminalUi\n}\n\nexport async function resolveScope({\n requestedScope,\n shouldAssumeYes,\n baseContext,\n ui,\n}: ResolveScopeParams): Promise<ConfigScope> {\n if (requestedScope !== undefined) return requestedScope\n if (shouldAssumeYes) return DEFAULT_SCOPE\n\n return await ui.selectScope(describeScopeTargets(baseContext))\n}\n\nfunction describeScopeTargets(ctx: PlatformContext): SelectScopeParams {\n const configurable = harnesses.filter((harness) => harness.kind === 'configurable')\n const projectConfigurable = configurable.filter((harness) => harness.projectSupport.kind === 'supported')\n return {\n userPaths: listConfigPaths(configurable, { ...ctx, scope: 'user' }).map((filePath) =>\n displayPath(filePath, ctx.home),\n ),\n projectPaths: listConfigPaths(projectConfigurable, { ...ctx, scope: 'project' }).map((filePath) =>\n displayRelativePath(filePath, ctx.cwd),\n ),\n }\n}\n\nexport function listConfigPaths(configurable: readonly ConfigurableHarness[], ctx: PlatformContext): string[] {\n return configurable.flatMap((harness) => listConfigPath(harness, ctx))\n}\n\nfunction listConfigPath(harness: ConfigurableHarness, ctx: PlatformContext): string[] {\n if (harness.configPath === undefined) return []\n\n try {\n return [harness.configPath(ctx)]\n } catch {\n return []\n }\n}\n","import { UsageError } from '../../../cli/usage-error'\nimport type { Harness } from '../../../harnesses/harness'\nimport { harnesses } from '../../../harnesses/registry'\nimport { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport type { ConfigScope, PlatformContext } from '../../../shared/platform/platform-context'\nimport type { HarnessChoice } from '../../../ui/prompts/select-harnesses'\nimport type { TerminalUi } from '../../../ui/terminal-ui'\n\nexport type Detection = { kind: 'found' | 'not-found' | 'failed'; detail: string }\n\nexport type DetectedHarness = { harness: Harness; detection: Detection }\n\nexport type SelectHarnessesParams = {\n namedHarnesses: readonly Harness[]\n ctx: PlatformContext\n shouldAssumeYes: boolean\n ui: TerminalUi\n}\n\nexport async function selectHarnesses({\n namedHarnesses,\n ctx,\n shouldAssumeYes,\n ui,\n}: SelectHarnessesParams): Promise<DetectedHarness[]> {\n if (namedHarnesses.length > 0) return detectHarnesses(namedHarnesses, ctx)\n\n const detected = detectHarnesses(harnesses, ctx)\n if (shouldAssumeYes) return detected.filter((candidate) => isDefaultChoice(candidate, ctx.scope))\n\n const chosenIds = await ui.selectHarnesses(detected.map((candidate) => describeHarnessChoice(candidate, ctx.scope)))\n return detected.filter(({ harness }) => chosenIds.includes(harness.id))\n}\n\nexport type AssertProjectSupportParams = {\n selected: readonly DetectedHarness[]\n scope: ConfigScope\n isScopeNamed: boolean\n}\n\nexport function assertProjectSupport({ selected, scope, isScopeNamed }: AssertProjectSupportParams): void {\n if (scope === 'user') return\n\n const refusals = selected.flatMap(({ harness }) => listProjectRefusal(harness))\n if (refusals.length === 0) return\n\n const nextStep = isScopeNamed ? 'Drop --scope project' : 'Choose the user scope'\n throw new UsageError(`${refusals.join('\\n')}\\n${nextStep}, or drop those agents from --harnesses.`)\n}\n\nfunction listProjectRefusal(harness: Harness): string[] {\n if (harness.kind !== 'configurable' || harness.projectSupport.kind === 'supported') return []\n\n return [`${harness.label}: ${harness.projectSupport.reason}`]\n}\n\nfunction detectHarnesses(candidates: readonly Harness[], ctx: PlatformContext): DetectedHarness[] {\n return candidates.map((harness) => ({ harness, detection: detectAtScope(harness, ctx) }))\n}\n\nfunction detectAtScope(harness: Harness, ctx: PlatformContext): Detection {\n try {\n return detectWithUserFallback(harness, ctx)\n } catch (error) {\n return { kind: 'failed', detail: describeFileError({ error, action: 'read', home: ctx.home }) }\n }\n}\n\nfunction detectWithUserFallback(harness: Harness, ctx: PlatformContext): Detection {\n const atScope = harness.detect(ctx)\n if (atScope.isFound) return { kind: 'found', detail: atScope.detail }\n if (ctx.scope === 'user' || harness.kind === 'unsupported') return { kind: 'not-found', detail: atScope.detail }\n\n const atUserScope = harness.detect({ ...ctx, scope: 'user' })\n if (!atUserScope.isFound) return { kind: 'not-found', detail: atScope.detail }\n\n const detail = `${atScope.detail} — ${harness.label} is set up at user level (${atUserScope.detail})`\n return { kind: 'found', detail }\n}\n\nconst DETECTION_HINTS: Readonly<Record<Detection['kind'], string>> = {\n found: 'found',\n 'not-found': 'not found',\n failed: 'could not check',\n}\n\nfunction describeHarnessChoice(candidate: DetectedHarness, scope: ConfigScope): HarnessChoice {\n const ineligibility = findIneligibility(candidate.harness, scope)\n return {\n value: candidate.harness.id,\n label: candidate.harness.label,\n hint: ineligibility ?? DETECTION_HINTS[candidate.detection.kind],\n isDisabled: ineligibility !== undefined,\n }\n}\n\nfunction isDefaultChoice({ harness, detection }: DetectedHarness, scope: ConfigScope): boolean {\n return findIneligibility(harness, scope) === undefined && detection.kind === 'found'\n}\n\nfunction findIneligibility(harness: Harness, scope: ConfigScope): string | undefined {\n if (harness.kind === 'unsupported') return `not configurable — ${harness.reason}`\n if (scope === 'user' || harness.projectSupport.kind === 'supported') return undefined\n\n return `no project-level config — ${harness.projectSupport.reason}`\n}\n","import path from 'node:path'\nimport { backUpBeforeWriting, ENV_FILE_BACKUP_DIRECTORY } from '../../../product/storage/backups/back-up-before-writing'\nimport type { BackupRoot } from '../../../product/storage/backups/resolve-backup-root'\nimport { writeEnvFile } from '../../../product/storage/env-file/write-env-file'\nimport { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport { readFileMode } from '../../../shared/file-system/read-file-mode'\nimport { resolveOwnerOnlyMode } from '../../../shared/file-system/resolve-owner-only-mode'\nimport { writeFileWithMode } from '../../../shared/file-system/write-file-with-mode'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport type { EnvPlan, FilePlan, HarnessFilePlan, HarnessOutcome } from '../setup-result'\nimport { renderEnvPlan, type ChangePlan } from './change-plan'\nimport { recordEnvOriginals, recordFileOriginals } from './record-originals'\n\nexport type ApplyChangesParams = {\n plan: ChangePlan\n ctx: PlatformContext\n backupRoot: BackupRoot\n}\n\nexport type ApplyChangesResult = {\n outcomes: HarnessOutcome[]\n envFile: EnvPlan | null\n writtenCount: number\n backupRoot: string | null\n}\n\nexport function applyChanges(params: ApplyChangesParams): ApplyChangesResult {\n const agentWrites = params.plan.outcomes.map((outcome) => writeAgentFiles(outcome, params))\n const outcomes = agentWrites.map(({ outcome }) => outcome)\n const envFile = replanEnvFile(params.plan.envFile, outcomes)\n const envWrite = writeSharedEnvFile({ outcomes, envFile, params })\n const writtenFiles = [...agentWrites.flatMap(({ writtenFiles }) => writtenFiles), ...envWrite.writtenFiles]\n return {\n outcomes: envWrite.outcomes,\n envFile,\n writtenCount: writtenFiles.length,\n backupRoot: writtenFiles.some((file) => file.isBackedUp) ? params.backupRoot.path : null,\n }\n}\n\ntype WrittenFile = { isBackedUp: boolean }\n\ntype AgentWrite = { outcome: HarnessOutcome; writtenFiles: WrittenFile[] }\n\nfunction writeAgentFiles(outcome: HarnessOutcome, params: ApplyChangesParams): AgentWrite {\n if (outcome.kind !== 'updated') return { outcome, writtenFiles: [] }\n\n const writtenFiles: WrittenFile[] = []\n for (const file of outcome.files.filter((plan) => plan.isChanged)) {\n try {\n const relativePath = path.join(outcome.harness.id, path.basename(file.path))\n const record = (): void => recordFileOriginals({ harnessId: outcome.harness.id, file, ctx: params.ctx })\n const write = (): void =>\n writeFileWithMode({ filePath: file.path, content: file.after, mode: resolveWriteMode(file, params.ctx) })\n writtenFiles.push(backUpThenWrite({ file, relativePath, record, write, params }))\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: params.ctx.home })\n return { outcome: { kind: 'failed', harness: outcome.harness, error: reason }, writtenFiles }\n }\n }\n return { outcome, writtenFiles }\n}\n\nfunction replanEnvFile(envFile: EnvPlan | null, outcomes: readonly HarnessOutcome[]): EnvPlan | null {\n if (envFile === null) return null\n\n return renderEnvPlan({ outcomes, before: envFile.before, envPath: envFile.path, shell: envFile.shell })\n}\n\ntype WriteSharedEnvFileParams = { outcomes: HarnessOutcome[]; envFile: EnvPlan | null; params: ApplyChangesParams }\n\ntype EnvWrite = { outcomes: HarnessOutcome[]; writtenFiles: WrittenFile[] }\n\nfunction writeSharedEnvFile({ outcomes, envFile, params }: WriteSharedEnvFileParams): EnvWrite {\n if (envFile === null || !envFile.isChanged) return { outcomes, writtenFiles: [] }\n\n try {\n const relativePath = path.join(ENV_FILE_BACKUP_DIRECTORY, path.basename(envFile.path))\n const { ctx } = params\n const record = (): void => recordEnvOriginals({ outcomes, envFile, ctx })\n const write = (): void => writeEnvFile({ filePath: envFile.path, content: envFile.after, platform: ctx.platform })\n return { outcomes, writtenFiles: [backUpThenWrite({ file: envFile, relativePath, record, write, params })] }\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: params.ctx.home })\n return { outcomes: outcomes.map((outcome) => failIfWritingEnvFile(outcome, reason)), writtenFiles: [] }\n }\n}\n\nfunction failIfWritingEnvFile(outcome: HarnessOutcome, error: string): HarnessOutcome {\n if (outcome.kind !== 'updated' || Object.keys(outcome.envVariables).length === 0) return outcome\n\n return { kind: 'failed', harness: outcome.harness, error }\n}\n\ntype BackUpThenWriteParams = {\n file: FilePlan\n relativePath: string\n record: () => void\n write: () => void\n params: ApplyChangesParams\n}\n\nfunction backUpThenWrite({ file, relativePath, record, write, params }: BackUpThenWriteParams): WrittenFile {\n const { ctx, backupRoot } = params\n const backup = backUpBeforeWriting({ filePath: file.path, before: file.before, backupRoot, relativePath, ctx })\n record()\n write()\n return backup\n}\n\nfunction resolveWriteMode(file: HarnessFilePlan, ctx: PlatformContext): number | null {\n const existingMode = readFileMode(file.path, ctx.platform)\n if (existingMode !== null || !file.hasSecret) return existingMode\n\n return resolveOwnerOnlyMode(ctx.platform)\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport type { ConfigurableHarness, Contribution, FileContribution } from '../../../harnesses/harness'\nimport type { DesiredConfig } from '../../../product/gateway/desired-config'\nimport { NO_ENV_FILE, readEnvFile, type EnvFileRead } from '../../../product/storage/env-file/read-env-file'\nimport { renderEnvFile, type EnvFileVariables } from '../../../product/storage/env-file/render-env-file'\nimport type { Shell } from '../../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedKey } from '../../../product/storage/restore-record/restore-record'\nimport { ConfigFormatError } from '../../../shared/file-formats/config-errors'\nimport { readOriginals, renderConfig, type ConfigFormat } from '../../../shared/file-formats/config-format'\nimport { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath, displayRelativePath } from '../../../shared/text/display-path'\nimport type { DetectedHarness } from '../answers/harness-selection'\nimport {\n isPlanned,\n type EnvPlan,\n type FailedOutcome,\n type FilePlan,\n type HarnessFilePlan,\n type HarnessOutcome,\n type PlannedOutcome,\n} from '../setup-result'\n\nexport type PlanChangesParams = {\n selected: readonly DetectedHarness[]\n desired: DesiredConfig\n ctx: PlatformContext\n envPath: string\n shell: Shell\n isDryRun: boolean\n}\n\nexport type ChangePlan = { outcomes: HarnessOutcome[]; envFile: EnvPlan | null }\n\nexport function planChanges(params: PlanChangesParams): ChangePlan {\n const { envPath, shell } = params\n const drafts = params.selected.map((candidate) => planHarness(candidate, params))\n const envFileRead = drafts.some(hasEnvVariables) ? readEnvFile({ envPath, home: params.ctx.home }) : NO_ENV_FILE\n const outcomes = drafts.map((draft) => settleOutcome({ draft, envFileRead, shell }))\n return { outcomes, envFile: planEnvFile({ outcomes, envFileRead, envPath, shell }) }\n}\n\nexport function listChangedFiles({ outcomes, envFile }: ChangePlan): FilePlan[] {\n const changedFiles = outcomes.flatMap((outcome) =>\n outcome.kind === 'updated' ? outcome.files.filter((file) => file.isChanged) : [],\n )\n return envFile?.isChanged === true ? [...changedFiles, envFile] : changedFiles\n}\n\nexport type RenderEnvPlanParams = {\n outcomes: readonly HarnessOutcome[]\n before: string | null\n envPath: string\n shell: Shell\n}\n\nexport function renderEnvPlan({ outcomes, before, envPath, shell }: RenderEnvPlanParams): EnvPlan | null {\n const variables = Object.fromEntries(\n outcomes.flatMap((outcome) => (isPlanned(outcome) ? Object.entries(outcome.envVariables) : [])),\n )\n if (Object.keys(variables).length === 0) return null\n\n const after = renderEnvFile({ current: before, variables, shell })\n return { path: envPath, before, after, isChanged: before !== after, shell }\n}\n\ntype Draft = Exclude<HarnessOutcome, PlannedOutcome> | (Omit<PlannedOutcome, 'kind'> & { kind: 'planned' })\n\nfunction planHarness({ harness, detection }: DetectedHarness, params: PlanChangesParams): Draft {\n if (harness.kind === 'unsupported') return { kind: 'unsupported', harness }\n if (detection.kind === 'failed') return { kind: 'failed', harness, error: detection.detail }\n if (detection.kind === 'not-found') {\n return { kind: 'not-found', harness, detail: `${detection.detail} — skipped, and no config was created` }\n }\n\n try {\n return planConfigurableHarness(harness, params)\n } catch (error) {\n return { kind: 'failed', harness, error: describeFileError({ error, action: 'read', home: params.ctx.home }) }\n }\n}\n\nconst PROJECT_ENV_REFUSAL =\n 'The env file it reads is user-level only, so a project-level run cannot set it up. Run again with --scope user.'\n\nfunction planConfigurableHarness(harness: ConfigurableHarness, { desired, ctx, isDryRun }: PlanChangesParams): Draft {\n const contributions = harness.plan(desired, ctx)\n if (ctx.scope === 'project' && contributions.some(({ kind }) => kind === 'env')) {\n return { kind: 'failed', harness, error: PROJECT_ENV_REFUSAL }\n }\n\n const files = contributions.flatMap((contribution) =>\n contribution.kind === 'file' ? [planFile({ contribution, apiKey: desired.apiKey, home: ctx.home })] : [],\n )\n const repositoryWarnings = files.flatMap((file) => warnAboutRepository(file, ctx, isDryRun))\n return {\n kind: 'planned',\n harness,\n detail: files.length > 0 ? files.map((file) => displayPath(file.path, ctx.home)).join(', ') : ENV_ONLY_DETAIL,\n files,\n envVariables: collectEnvVariables(contributions),\n warnings: [...repositoryWarnings, ...(harness.warnings?.(ctx) ?? [])],\n }\n}\n\nconst ENV_ONLY_DETAIL = 'environment variables only'\n\ntype PlanFileParams = { contribution: FileContribution; apiKey: string; home: string }\n\nfunction planFile({ contribution, apiKey, home }: PlanFileParams): HarnessFilePlan {\n const before = readFileIfExists(contribution.path)\n const rendered = renderFileContribution({ contribution, before, apiKey, home })\n const isChanged = before !== rendered.after\n return { path: contribution.path, before, ...rendered, isChanged, hasSecret: contribution.hasSecret }\n}\n\ntype RenderFileContributionParams = PlanFileParams & { before: string | null }\n\ntype RenderedFile = { after: string; format: ConfigFormat; originals: RecordedKey[] }\n\nfunction renderFileContribution(params: RenderFileContributionParams): RenderedFile {\n const { contribution, before, apiKey, home } = params\n try {\n const edits = contribution.edits(before)\n const secretKeyPaths = edits.updates.flatMap(([keyPath, value]) => (value === apiKey ? [keyPath] : []))\n const originals = readOriginals(before, edits).map((original) => ({\n ...original,\n holdsSecret: secretKeyPaths.some((keyPath) => isDeepStrictEqual(keyPath, original.keyPath)),\n }))\n return { after: renderConfig(before, edits), format: edits.format, originals }\n } catch (error) {\n if (!(error instanceof ConfigFormatError)) throw error\n throw new Error(`${displayPath(contribution.path, home)}: ${error.message}`, { cause: error })\n }\n}\n\nfunction warnAboutRepository(file: HarnessFilePlan, ctx: PlatformContext, isDryRun: boolean): string[] {\n if (ctx.scope === 'user' || !file.hasSecret) return []\n\n const displayedPath = displayRelativePath(file.path, ctx.cwd)\n const location = isDryRun ? `A real run puts the key in ${displayedPath}` : `${displayedPath} holds the key`\n return [`${location}, inside your repository — make sure it is gitignored before committing.`]\n}\n\nfunction collectEnvVariables(contributions: readonly Contribution[]): EnvFileVariables {\n return Object.fromEntries(\n contributions.flatMap((contribution) =>\n contribution.kind === 'env' ? Object.entries(contribution.variables) : [],\n ),\n )\n}\n\nfunction hasEnvVariables(draft: Draft): boolean {\n return draft.kind === 'planned' && Object.keys(draft.envVariables).length > 0\n}\n\ntype SettleOutcomeParams = { draft: Draft; envFileRead: EnvFileRead; shell: Shell }\n\nfunction settleOutcome({ draft, envFileRead, shell }: SettleOutcomeParams): HarnessOutcome {\n if (draft.kind !== 'planned') return draft\n if (envFileRead.kind === 'failed' && hasEnvVariables(draft)) return failWith(draft, envFileRead.error)\n\n const envText = envFileRead.kind === 'read' ? envFileRead.text : null\n const hasOwnEnvChange =\n hasEnvVariables(draft) && renderEnvFile({ current: envText, variables: draft.envVariables, shell }) !== envText\n const isChanged = hasOwnEnvChange || draft.files.some((file) => file.isChanged)\n return { ...draft, kind: isChanged ? 'updated' : 'unchanged' }\n}\n\nfunction failWith({ harness }: Draft, error: string): FailedOutcome {\n return { kind: 'failed', harness, error }\n}\n\ntype PlanEnvFileParams = {\n outcomes: readonly HarnessOutcome[]\n envFileRead: EnvFileRead\n envPath: string\n shell: Shell\n}\n\nfunction planEnvFile({ outcomes, envFileRead, envPath, shell }: PlanEnvFileParams): EnvPlan | null {\n if (envFileRead.kind === 'failed') return null\n\n return renderEnvPlan({ outcomes, before: envFileRead.text, envPath, shell })\n}\n","import type { FileOrigin, HarnessRecord, RecordedEnvVariable, RecordedFile, RestoreRecord } from './restore-record'\n\nexport function classifyFileOrigin(before: string | null): FileOrigin {\n if (before === null) return 'absent'\n return before.trim() === '' ? 'blank' : 'content'\n}\n\nexport type AddFileOriginalsParams = { record: RestoreRecord; harnessId: string; file: RecordedFile }\n\n/** First touch wins: a key already recorded keeps its original, and only new key paths are added. */\nexport function addFileOriginals({ record, harnessId, file }: AddFileOriginalsParams): RestoreRecord {\n const harness = readHarnessRecord(record, harnessId)\n const existing = harness.files.find((recorded) => isSamePath(recorded.path, file.path))\n const others = harness.files.filter((recorded) => recorded !== existing)\n return withHarnessRecord(record, harnessId, { ...harness, files: [...others, mergeFile(existing, file)] })\n}\n\nexport type AddEnvOriginalsParams = {\n record: RestoreRecord\n harnessId: string\n variables: readonly RecordedEnvVariable[]\n isFileAbsent: boolean\n}\n\nexport function addEnvOriginals({ record, harnessId, variables, isFileAbsent }: AddEnvOriginalsParams): RestoreRecord {\n const harness = readHarnessRecord(record, harnessId)\n const kept = isFileAbsent ? [] : harness.envVariables\n const added = variables.filter((variable) => !kept.some(({ name }) => name === variable.name))\n return withHarnessRecord(record, harnessId, { ...harness, envVariables: [...kept, ...added] })\n}\n\nconst EMPTY_HARNESS_RECORD: HarnessRecord = { files: [], envVariables: [] }\n\nfunction readHarnessRecord(record: RestoreRecord, harnessId: string): HarnessRecord {\n return record.harnesses[harnessId] ?? EMPTY_HARNESS_RECORD\n}\n\nfunction withHarnessRecord(record: RestoreRecord, harnessId: string, harness: HarnessRecord): RestoreRecord {\n return { ...record, harnesses: { ...record.harnesses, [harnessId]: harness } }\n}\n\n// A file absent now was deleted since it was recorded, so what it held then is no longer anything to restore.\nfunction mergeFile(existing: RecordedFile | undefined, file: RecordedFile): RecordedFile {\n if (existing === undefined || file.origin === 'absent') return file\n\n const added = file.keys.filter((key) => !existing.keys.some(({ keyPath }) => isSamePath(keyPath, key.keyPath)))\n return { ...existing, keys: [...existing.keys, ...added] }\n}\n\nfunction isSamePath(path: readonly string[], other: readonly string[]): boolean {\n return path.length === other.length && path.every((segment, index) => segment === other[index])\n}\n","import { ignoreBackupsInGit } from '../../../product/storage/backups/back-up-file'\nimport { parseEnvFile } from '../../../product/storage/env-file/parse-env-file'\nimport { ENV_SYNTAXES } from '../../../product/storage/env-file/syntax/env-syntaxes'\nimport {\n addEnvOriginals,\n addFileOriginals,\n classifyFileOrigin,\n} from '../../../product/storage/restore-record/add-originals'\nimport {\n createEmptyRestoreRecord,\n readRestoreRecord,\n writeRestoreRecord,\n type RecordedFile,\n type RestoreRecord,\n} from '../../../product/storage/restore-record/restore-record'\nimport {\n resolveRestoreRecordLocation,\n toRecordedPath,\n type RestoreRecordLocation,\n} from '../../../product/storage/restore-record/restore-record-location'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport type { EnvPlan, HarnessFilePlan, HarnessOutcome } from '../setup-result'\n\nexport type RecordFileOriginalsParams = { harnessId: string; file: HarnessFilePlan; ctx: PlatformContext }\n\nexport function recordFileOriginals({ harnessId, file, ctx }: RecordFileOriginalsParams): void {\n const location = resolveRestoreRecordLocation(ctx)\n const recordedFile: RecordedFile = {\n path: toRecordedPath(file.path, location.root),\n format: file.format,\n origin: classifyFileOrigin(file.before),\n keys: file.originals,\n }\n updateRestoreRecord(location, ctx, (record) => addFileOriginals({ record, harnessId, file: recordedFile }))\n}\n\nexport type RecordEnvOriginalsParams = { outcomes: readonly HarnessOutcome[]; envFile: EnvPlan; ctx: PlatformContext }\n\nexport function recordEnvOriginals({ outcomes, envFile, ctx }: RecordEnvOriginalsParams): void {\n const syntax = ENV_SYNTAXES[envFile.shell]\n const currentValues = parseEnvFile(envFile.before ?? '', envFile.shell)\n const isFileAbsent = envFile.before === null\n\n updateRestoreRecord(resolveRestoreRecordLocation(ctx), ctx, (record) =>\n outcomes.reduce((updated, outcome) => {\n if (outcome.kind !== 'updated') return updated\n\n const variables = Object.keys(outcome.envVariables).map((name) => ({\n name,\n original: currentValues.get(syntax.normalizeName(name)) ?? null,\n }))\n if (variables.length === 0) return updated\n return addEnvOriginals({ record: updated, harnessId: outcome.harness.id, variables, isFileAbsent })\n }, record),\n )\n}\n\nfunction updateRestoreRecord(\n location: RestoreRecordLocation,\n ctx: PlatformContext,\n update: (record: RestoreRecord) => RestoreRecord,\n): void {\n if (location.gitIgnoredDirectory !== null) ignoreBackupsInGit(location.gitIgnoredDirectory)\n\n const record = readRestoreRecord({ filePath: location.filePath, home: ctx.home }) ?? createEmptyRestoreRecord()\n writeRestoreRecord({ filePath: location.filePath, record: update(record), platform: ctx.platform })\n}\n","import {\n GATEWAY_ENV_VARIABLE,\n parseEnvironmentKey,\n readEnvironmentInputs,\n type EnvironmentInputs,\n} from '../../cli/environment'\nimport { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport { TAGLINE } from '../../cli/help'\nimport type { CliOptions } from '../../cli/parse-cli-arguments'\nimport { refusePrompts } from '../../cli/refuse-prompts'\nimport { resolveNamedHarnesses } from '../../cli/resolve-named-harnesses'\nimport { findExistingKeys } from '../../flows/key/find-existing-keys'\nimport {\n adoptKey,\n commitSave,\n isKeyUsable,\n resolveKey,\n type KeyStepDeps,\n type KeyStepInput,\n type KeyStepRun,\n} from '../../flows/key/key-step'\nimport { chooseCheckedModel } from '../../flows/model/choose-checked-model'\nimport { commitModelSave, loadModelPreferences } from '../../flows/model/model-step'\nimport type { ConfigurableHarness, Harness } from '../../harnesses/harness'\nimport {\n GATEWAY_HOST,\n buildDesiredConfig,\n buildGatewayUrls,\n type GatewayUrls,\n} from '../../product/gateway/desired-config'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatBackupTimestamp, resolveBackupRoot } from '../../product/storage/backups/resolve-backup-root'\nimport { resolveEnvFilePath } from '../../product/storage/env-file/env-file-path'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport { resolveShell } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport type { Keystore } from '../../product/storage/keychain/keystore'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { formatCount } from '../../shared/text/format-count'\nimport { formatDetection } from '../../ui/report/format-detection'\nimport { formatPreview } from '../../ui/report/format-preview'\nimport { formatResult, type ResultMode, type RunHint } from '../../ui/report/format-result'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { describeKeyDestination } from './answers/describe-key-destination'\nimport {\n assertProjectSupport,\n selectHarnesses,\n type DetectedHarness,\n type Detection,\n} from './answers/harness-selection'\nimport { resolveScope } from './answers/scope'\nimport { applyChanges, type ApplyChangesResult } from './changes/apply-changes'\nimport { listChangedFiles, planChanges, type ChangePlan } from './changes/change-plan'\nimport { exitCodeFor, isPlanned, type HarnessOutcome } from './setup-result'\n\nexport type RunSetupParams = {\n options: CliOptions\n baseContext: PlatformContext\n ui: TerminalUi\n fetch: Fetch\n now: () => Date\n masker: Masker\n keystore: Keystore\n}\n\nconst FINISHED_WITH_ERRORS = 'Finished with errors.'\n\nexport async function runSetup(params: RunSetupParams): Promise<ExitCode> {\n const { options, masker } = params\n const ui = params.baseContext.isInteractive ? params.ui : refusePrompts(params.ui)\n ui.intro(TAGLINE)\n\n const environment = readEnvironmentInputs(params.baseContext.env)\n masker.registerSecrets([options.key, environment.key].flatMap((key) => key ?? []))\n const gatewayUrls = buildGatewayUrls(environment.gatewayHost ?? GATEWAY_HOST)\n if (environment.gatewayHost !== undefined) {\n ui.log.warn(masker.maskText(`Using the gateway at ${environment.gatewayHost} — $${GATEWAY_ENV_VARIABLE} is set.`))\n }\n const namedHarnesses = resolveNamedHarnesses(options.harnessIds)\n const scope = await resolveScope({\n requestedScope: options.scope,\n shouldAssumeYes: options.shouldAssumeYes,\n baseContext: params.baseContext,\n ui,\n })\n const ctx: PlatformContext = { ...params.baseContext, scope }\n const selected = await selectHarnesses({ namedHarnesses, ctx, shouldAssumeYes: options.shouldAssumeYes, ui })\n assertProjectSupport({ selected, scope, isScopeNamed: options.scope !== undefined })\n if (selected.length === 0) {\n ui.cancel('No agents selected — nothing to do.')\n return EXIT_CODE.ok\n }\n\n warnAboutUnsupported(selected, ui)\n if (!selected.some(({ harness }) => harness.kind === 'configurable')) {\n ui.outro('Nothing to configure.')\n return EXIT_CODE.ok\n }\n const found = selected.flatMap(listFoundConfigurable)\n if (found.length === 0) return endWithNothingFound(selected, ui, masker)\n\n const shell = resolveShell(ctx.platform)\n const run: SetupRun = { ...params, ui, ctx, shell, envPath: resolveEnvFilePath(ctx.home, shell), gatewayUrls }\n const keyStep = await establishKey({ run, configurable: found, environment })\n if (keyStep === null) return EXIT_CODE.failed\n\n const modelDecision = await chooseCheckedModel({\n keyStep,\n configurable: found,\n envModel: environment.model,\n preferences: loadModelPreferences(ctx.home, ui),\n gatewayUrls,\n options,\n probeConsequence: options.isDryRun\n ? 'The dry run writes nothing either way.'\n : 'The configs will still be written.',\n ui,\n masker,\n fetch: params.fetch,\n })\n if (modelDecision.kind === 'declined') return abort(ui)\n if (modelDecision.kind === 'aborted') return EXIT_CODE.failed\n\n const { model, resolvedKey, check, modelSave } = modelDecision\n const saveModelFor = (outcomes: readonly HarnessOutcome[]): void => {\n const configuredHarnesses = listConfigured(modelSave, outcomes)\n commitModelSave({ model, harnesses: configuredHarnesses, home: ctx.home, ui, masker })\n }\n const key = resolvedKey.key\n\n ui.print(formatDetection(selected, masker))\n const desired = buildDesiredConfig({ gatewayUrls, apiKey: key, model })\n const plan = planChanges({ selected, desired, ctx, envPath: run.envPath, shell, isDryRun: options.isDryRun })\n const changes = listChangedFiles(plan)\n const isPlanFailed = exitCodeFor(plan.outcomes) !== EXIT_CODE.ok\n ui.print(formatPreview({ changes, model, scope, hasFailedAgent: isPlanFailed, home: ctx.home, masker }))\n\n if (options.isDryRun) {\n if (resolvedKey.shouldSave) ui.dim('Dry run — the key was not saved.')\n if (modelSave.length > 0) ui.dim('Dry run — the default model was not saved.')\n return reportResult({ run, plan, mode: { kind: 'dry-run' }, outro: 'Dry run — nothing was written.' })\n }\n if (changes.length === 0) {\n await commitSave(resolvedKey, check, keyStep.deps)\n saveModelFor(plan.outcomes)\n const mode = { kind: 'written', backupRoot: null } as const\n const outro = isPlanFailed ? FINISHED_WITH_ERRORS : 'Nothing to do — already configured.'\n return reportResult({ run, plan, mode, outro })\n }\n if (!options.shouldAssumeYes && !(await ui.confirm('Write these changes? Originals are backed up first.', true))) {\n return abort(ui)\n }\n\n await commitSave(resolvedKey, check, keyStep.deps)\n const applied = writeChanges(run, plan)\n saveModelFor(applied.outcomes)\n const outro = exitCodeFor(applied.outcomes) === EXIT_CODE.ok ? 'Done.' : FINISHED_WITH_ERRORS\n const mode = { kind: 'written', backupRoot: applied.backupRoot } as const\n return reportResult({ run, plan: { outcomes: applied.outcomes, envFile: applied.envFile }, mode, outro })\n}\n\ntype SetupRun = RunSetupParams & {\n ui: TerminalUi\n ctx: PlatformContext\n shell: Shell\n envPath: string\n gatewayUrls: GatewayUrls\n}\n\nfunction warnAboutUnsupported(selected: readonly DetectedHarness[], ui: TerminalUi): void {\n for (const { harness } of selected) {\n if (harness.kind === 'unsupported') ui.log.warn(`${harness.label}: not configurable — ${harness.reason}`)\n }\n}\n\nfunction listFoundConfigurable({ harness, detection }: DetectedHarness): ConfigurableHarness[] {\n if (harness.kind !== 'configurable' || detection.kind !== 'found') return []\n\n return [harness]\n}\n\nfunction endWithNothingFound(selected: readonly DetectedHarness[], ui: TerminalUi, masker: Masker): ExitCode {\n ui.print(formatDetection(selected, masker))\n const hasFailedCheck = selected.some(({ harness, detection }) => isConfigurableUnchecked(harness, detection))\n if (hasFailedCheck) {\n ui.outro(FINISHED_WITH_ERRORS)\n return EXIT_CODE.failed\n }\n\n ui.outro('Nothing to configure — none of the selected agents was found.')\n return EXIT_CODE.ok\n}\n\nfunction isConfigurableUnchecked(harness: Harness, detection: Detection): boolean {\n return harness.kind === 'configurable' && detection.kind === 'failed'\n}\n\ntype EstablishKeyParams = {\n run: SetupRun\n configurable: readonly ConfigurableHarness[]\n environment: EnvironmentInputs\n}\n\nasync function establishKey({ run, configurable, environment }: EstablishKeyParams): Promise<KeyStepRun | null> {\n const { ctx, envPath, shell, ui, masker, options } = run\n // Read eagerly: the diff shows lines this run removes, so every key already on disk must be\n // registered for masking even when the key comes from a flag and no prompt is reached.\n const existingKeys = findExistingKeys({ ctx, envPath, shell })\n masker.registerSecrets(existingKeys.all)\n\n const deps: KeyStepDeps = { keystore: run.keystore, ui, masker }\n const input: KeyStepInput = {\n flagKey: options.key,\n envKey: options.key === undefined ? parseEnvironmentKey(environment.key) : undefined,\n shouldSaveKey: options.shouldSaveKey,\n shouldAssumeYes: options.shouldAssumeYes,\n isDryRun: options.isDryRun,\n existingKeys: () => existingKeys,\n destination: describeKeyDestination({ configurable, ctx, envPath }),\n }\n\n const resolved = await resolveKey(input, deps)\n if (!isKeyUsable(resolved.key)) {\n ui.cancel('No API key provided.')\n return null\n }\n adoptKey(resolved.key, { ui, masker })\n return { input, deps, resolved }\n}\n\n/** A default is saved only for an agent this run configured, not one whose write failed. */\nfunction listConfigured(\n harnesses: readonly ConfigurableHarness[],\n outcomes: readonly HarnessOutcome[],\n): ConfigurableHarness[] {\n const configuredIds = new Set(outcomes.filter(isPlanned).map((outcome) => outcome.harness.id))\n return harnesses.filter((harness) => configuredIds.has(harness.id))\n}\n\nfunction writeChanges(run: SetupRun, plan: ChangePlan): ApplyChangesResult {\n const { options, ctx, ui } = run\n const backupRoot = resolveBackupRoot({\n scope: ctx.scope,\n home: ctx.home,\n cwd: ctx.cwd,\n stamp: formatBackupTimestamp(run.now()),\n backupDirectory: options.backupDirectory,\n })\n\n const spinner = ui.spinner()\n spinner.start('Backing up originals and writing configs…')\n const applied = applyChanges({ plan, ctx, backupRoot })\n spinner.stop(`Wrote ${formatCount(applied.writtenCount, 'file')}.`)\n return applied\n}\n\ntype ReportResultParams = { run: SetupRun; plan: ChangePlan; mode: ResultMode; outro: string }\n\nfunction reportResult({ run, plan, mode, outro }: ReportResultParams): ExitCode {\n const { ui, ctx, masker } = run\n ui.print(\n formatResult({\n outcomes: plan.outcomes,\n envFile: plan.envFile,\n mode,\n home: ctx.home,\n masker,\n runHints: listRunHints(plan.outcomes, ctx),\n }),\n )\n ui.outro(outro)\n return exitCodeFor(plan.outcomes)\n}\n\nfunction listRunHints(outcomes: readonly HarnessOutcome[], ctx: PlatformContext): RunHint[] {\n return outcomes\n .filter(isPlanned)\n .flatMap(({ harness }) => (ctx.hasBinary(harness.binary) ? [{ binary: harness.binary, label: harness.label }] : []))\n}\n\nfunction abort(ui: TerminalUi): ExitCode {\n ui.cancel('Aborted — nothing was written.')\n return EXIT_CODE.cancelled\n}\n","import type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { describeError } from '../shared/text/describe-error'\nimport type { LaunchRecipe } from './launch-recipe'\n\nexport const LAUNCH_DIRECTORY_PREFIX = 'nexos-connect-'\nconst STALE_DIRECTORY_PATTERN = new RegExp(`^${LAUNCH_DIRECTORY_PREFIX}(\\\\d+)-`)\nconst OWNER_ONLY_MODE = 0o600\n\nexport type LaunchResult = { code: number } | { signal: NodeJS.Signals }\n\nexport interface RunnerDeps {\n spawn(command: string, commandArguments: string[], options: SpawnOptions): ChildProcess\n tmpdir(): string\n pid: number\n /** Undefined where the platform has no uids (Windows). */\n uid: number | undefined\n isAlive(pid: number): boolean\n signals: Pick<NodeJS.EventEmitter, 'on' | 'off'>\n stdin: Pick<NodeJS.ReadStream, 'isTTY' | 'setRawMode' | 'pause'>\n env: NodeJS.ProcessEnv\n onError(message: string): void\n}\n\n/**\n * Temp dirs carry their run's pid, so only a dir whose run is gone is removed: a concurrent\n * session's settings file must outlive this run.\n */\nexport function sweepStaleDirectories(deps: Pick<RunnerDeps, 'tmpdir' | 'uid' | 'isAlive'>): void {\n const root = deps.tmpdir()\n let names: string[]\n try {\n names = fs.readdirSync(root)\n } catch {\n return\n }\n\n for (const name of names) {\n const match = STALE_DIRECTORY_PATTERN.exec(name)\n if (match === null) continue\n\n const directory = path.join(root, name)\n try {\n if (deps.isAlive(Number(match[1]))) continue\n if (deps.uid !== undefined && fs.statSync(directory).uid !== deps.uid) continue\n fs.rmSync(directory, { recursive: true, force: true })\n } catch {\n // Already gone, or not ours to remove.\n }\n }\n}\n\n/**\n * Ctrl-C reaches the whole foreground process group, so SIGINT is ignored here — the agent decides\n * what it means — and this process outlives it to clean up.\n */\nexport async function runLaunch(\n recipe: LaunchRecipe,\n passthrough: readonly string[],\n deps: RunnerDeps,\n): Promise<LaunchResult> {\n sweepStaleDirectories(deps)\n\n let directory: string | null = null\n const cleanup = (): void => {\n if (directory === null) return\n fs.rmSync(directory, { recursive: true, force: true })\n directory = null\n }\n deps.signals.on('exit', cleanup)\n\n let commandArguments = recipe.arguments\n if (recipe.files !== undefined && recipe.files.length > 0) {\n try {\n directory = fs.mkdtempSync(path.join(deps.tmpdir(), `${LAUNCH_DIRECTORY_PREFIX}${deps.pid}-`))\n const byPlaceholder = new Map<string, string>()\n for (const file of recipe.files) {\n const target = path.join(directory, file.name)\n fs.writeFileSync(target, file.content, { mode: OWNER_ONLY_MODE, flag: 'wx' })\n byPlaceholder.set(file.placeholder, target)\n }\n commandArguments = commandArguments.map((argument) => byPlaceholder.get(argument) ?? argument)\n } catch (error) {\n cleanup()\n deps.signals.off('exit', cleanup)\n deps.onError(\n `Couldn't write the temporary settings file in ${deps.tmpdir()}: ${describeError(error)}. Check $TMPDIR.`,\n )\n return { code: 1 }\n }\n }\n\n const env: NodeJS.ProcessEnv = { ...deps.env }\n for (const [name, value] of Object.entries(recipe.env)) {\n if (value === undefined) delete env[name]\n else env[name] = value\n }\n\n // Prompts may have left stdin flowing or raw; either would steal the agent's keystrokes.\n if (deps.stdin.isTTY) deps.stdin.setRawMode(false)\n deps.stdin.pause()\n\n return new Promise((resolve) => {\n let child: ChildProcess | undefined\n const ignore = (): void => {}\n // A signal listener is called with no argument, so each forwards the signal it is registered for.\n const forwardTermination = (): void => {\n child?.kill('SIGTERM')\n }\n const forwardHangup = (): void => {\n child?.kill('SIGHUP')\n }\n\n let isSettled = false\n const finish = (result: LaunchResult): void => {\n if (isSettled) return\n isSettled = true\n deps.signals.off('SIGINT', ignore)\n deps.signals.off('SIGTERM', forwardTermination)\n deps.signals.off('SIGHUP', forwardHangup)\n deps.signals.off('exit', cleanup)\n cleanup()\n resolve(result)\n }\n\n try {\n const subcommands = recipe.subcommands ?? []\n const joined = joinArguments({ recipeArguments: commandArguments, subcommands, passthrough })\n child = deps.spawn(recipe.binary, joined, { stdio: 'inherit', env })\n } catch (error) {\n deps.onError(`Couldn't start ${recipe.binary}: ${describeError(error)}`)\n finish({ code: 1 })\n return\n }\n\n deps.signals.on('SIGINT', ignore)\n deps.signals.on('SIGTERM', forwardTermination)\n deps.signals.on('SIGHUP', forwardHangup)\n child.once('error', (error) => {\n deps.onError(`Couldn't start ${recipe.binary}: ${error.message}`)\n finish({ code: 1 })\n })\n child.once('exit', (code, signal) => finish(signal !== null ? { signal } : { code: code ?? 1 }))\n })\n}\n\nexport type JoinArgumentsParams = {\n recipeArguments: readonly string[]\n subcommands: readonly string[]\n passthrough: readonly string[]\n}\n\nexport function joinArguments({ recipeArguments, subcommands, passthrough }: JoinArgumentsParams): string[] {\n const [first, ...rest] = passthrough\n if (first !== undefined && subcommands.includes(first)) return [first, ...recipeArguments, ...rest]\n\n return [...recipeArguments, ...passthrough]\n}\n","import { randomUUID } from 'node:crypto'\nimport type { AsyncEntry, EntryOptions } from '@napi-rs/keyring'\n\n/** The one export the store uses, so the native module is only reached through `importKeyring`. */\nexport interface Keyring {\n AsyncEntry: new (service: string, username: string, options?: EntryOptions) => AsyncEntry\n}\n\nconst SERVICE = 'nexos-connect'\nconst ACCOUNT = 'default'\nconst PROBE_ACCOUNT = 'probe'\nconst LINUX_STORE: EntryOptions = { linux: { store: 'secret-service' } }\nconst MS_PER_SECOND = 1_000\n\nexport const KEYCHAIN_ENV_VARIABLE = 'NEXOS_KEYCHAIN'\nexport const KEYCHAIN_DISABLED = 'off'\n\n/** Secret Service can hang indefinitely over SSH, in Docker and under WSL. */\nexport const KEYCHAIN_PROBE_TIMEOUT_MS = 2_000\n/** A read or write can wait on a keychain password dialog, so it gets a user-scale budget. */\nexport const KEYCHAIN_INTERACTION_TIMEOUT_MS = 120_000\n\nexport const KEYCHAIN_UNAVAILABLE = {\n disabled: 'The system keychain is disabled',\n wsl: 'WSL has no reachable system keychain',\n noBinding: 'No keychain support for this platform',\n noMacKeychain: 'No default macOS keychain',\n noKeychain: 'No system keychain found',\n timedOut: 'The system keychain did not answer in time',\n} as const\n\n/** Reasons under which an entry saved by an earlier run can still be in the keychain. */\nconst REASONS_THAT_MAY_HOLD_A_KEY: ReadonlySet<string> = new Set([\n KEYCHAIN_UNAVAILABLE.disabled,\n KEYCHAIN_UNAVAILABLE.noKeychain,\n KEYCHAIN_UNAVAILABLE.timedOut,\n])\n\nexport type Availability = { kind: 'available' } | { kind: 'unavailable'; reason: string; hasPossibleEntry: boolean }\n\nexport interface Keystore {\n availability(): Promise<Availability>\n load(): Promise<string | undefined>\n save(key: string): Promise<void>\n /** Whether there was an entry to remove. */\n clear(): Promise<boolean>\n /**\n * A native call timed out. Its thread is still blocked and holds the event loop open, so the\n * process has to be ended with `process.exit`.\n */\n readonly isHung: boolean\n}\n\nexport interface KeystoreDeps {\n importKeyring(): Promise<Keyring>\n platform: NodeJS.Platform\n isWsl(): boolean\n hasMacKeychain(): boolean\n /** False when `$NEXOS_KEYCHAIN=off`, the escape hatch the e2e sandbox uses. */\n isEnabled: boolean\n probeTimeoutMs: number\n interactionTimeoutMs: number\n}\n\nfunction unavailable(reason: string): Availability {\n return { kind: 'unavailable', reason, hasPossibleEntry: REASONS_THAT_MAY_HOLD_A_KEY.has(reason) }\n}\n\nexport function createKeystore(deps: KeystoreDeps): Keystore {\n let keyring: Keyring | undefined\n let probed: Promise<Availability> | undefined\n let isHung = false\n\n function entry(account: string): AsyncEntry {\n if (keyring === undefined) throw new Error('the keychain was used before availability() passed')\n return new keyring.AsyncEntry(SERVICE, account, LINUX_STORE)\n }\n\n // Raced against a timer rather than left to the signal alone: aborting only cancels native work\n // that has not started, and a hung D-Bus call has.\n function withTimeout<T>(operation: (signal: AbortSignal) => Promise<T>, timeoutMs: number): Promise<T> {\n if (isHung) return Promise.reject(new Error(KEYCHAIN_UNAVAILABLE.timedOut))\n\n const controller = new AbortController()\n let timer: NodeJS.Timeout | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n isHung = true\n controller.abort()\n reject(new Error(`the system keychain did not answer within ${timeoutMs / MS_PER_SECOND}s`))\n }, timeoutMs)\n })\n return Promise.race([operation(controller.signal), timeout]).finally(() => clearTimeout(timer))\n }\n\n async function probe(): Promise<Availability> {\n if (!deps.isEnabled) return unavailable(KEYCHAIN_UNAVAILABLE.disabled)\n if (deps.platform === 'linux' && deps.isWsl()) return unavailable(KEYCHAIN_UNAVAILABLE.wsl)\n\n let loaded: Keyring\n try {\n loaded = await deps.importKeyring()\n } catch {\n return unavailable(KEYCHAIN_UNAVAILABLE.noBinding)\n }\n if (deps.platform === 'darwin' && !deps.hasMacKeychain()) return unavailable(KEYCHAIN_UNAVAILABLE.noMacKeychain)\n\n try {\n const token = randomUUID()\n const read = await withTimeout(async (signal) => {\n const probeEntry = new loaded.AsyncEntry(SERVICE, PROBE_ACCOUNT, LINUX_STORE)\n try {\n await probeEntry.setPassword(token, signal)\n return await probeEntry.getPassword(signal)\n } finally {\n // Best effort, and without the aborted signal: a timed-out delete cannot succeed anyway.\n await probeEntry.deleteCredential().catch(() => false)\n }\n }, deps.probeTimeoutMs)\n if (read !== token) return unavailable(KEYCHAIN_UNAVAILABLE.noKeychain)\n\n // Only now is the module safe to use: a failed probe must not leave a usable `keyring`.\n keyring = loaded\n return { kind: 'available' }\n } catch {\n return unavailable(isHung ? KEYCHAIN_UNAVAILABLE.timedOut : KEYCHAIN_UNAVAILABLE.noKeychain)\n }\n }\n\n return {\n availability: () => (isHung ? Promise.resolve(unavailable(KEYCHAIN_UNAVAILABLE.timedOut)) : (probed ??= probe())),\n load: () =>\n withTimeout(async (signal) => (await entry(ACCOUNT).getPassword(signal)) ?? undefined, deps.interactionTimeoutMs),\n save: (key) => withTimeout(async (signal) => entry(ACCOUNT).setPassword(key, signal), deps.interactionTimeoutMs),\n clear: () => withTimeout(async (signal) => entry(ACCOUNT).deleteCredential(signal), deps.interactionTimeoutMs),\n get isHung() {\n return isHung\n },\n }\n}\n","import * as clack from '@clack/prompts'\nimport pc from 'picocolors'\nimport type { PromptIo } from './prompt-io'\n\nexport function intro(message: string, io: PromptIo): void {\n clack.intro(message, { output: io.output })\n}\n\nexport function outro(message: string, io: PromptIo): void {\n clack.outro(message, { output: io.output })\n}\n\nexport function cancel(message: string, io: PromptIo): void {\n clack.cancel(message, { output: io.output })\n}\n\nexport interface Log {\n info(message: string): void\n warn(message: string): void\n error(message: string): void\n success(message: string): void\n}\n\nexport function createLog(io: PromptIo): Log {\n return {\n info: (message) => clack.log.info(message, { output: io.output }),\n warn: (message) => clack.log.warn(message, { output: io.output }),\n error: (message) => clack.log.error(message, { output: io.output }),\n success: (message) => clack.log.success(message, { output: io.output }),\n }\n}\n\nexport function printLines(lines: readonly string[], io: PromptIo): void {\n io.output.write(`${lines.join('\\n')}\\n`)\n}\n\n/** A side remark: worth saying, never worth stopping for. */\nexport function dim(message: string, io: PromptIo): void {\n clack.log.message(pc.dim(message), { output: io.output })\n}\n\nexport function note(message: string, title: string, io: PromptIo): void {\n clack.note(message, title, { output: io.output })\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport async function confirm(message: string, shouldDefaultToYes: boolean, io: PromptIo): Promise<boolean> {\n return await throwIfCancelled(clack.confirm({ message, initialValue: shouldDefaultToYes, ...io }))\n}\n","import * as clack from '@clack/prompts'\nimport { API_KEYS_URL } from '../../../product/gateway/desired-config'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type AskForKeyParams = { destination: string }\n\nexport async function askForKey({ destination }: AskForKeyParams, io: PromptIo): Promise<string> {\n clack.note(`Create a key at:\\n ${API_KEYS_URL}\\n\\n${destination}`, 'You need a nexos.ai API key', {\n output: io.output,\n })\n\n const value = await throwIfCancelled(\n clack.password({\n message: 'Paste your nexos.ai API key',\n validate: (value) => ((value ?? '').trim() === '' ? 'Paste a key, or press Ctrl-C to quit.' : undefined),\n ...io,\n }),\n )\n return value.trim()\n}\n\nexport type AskToKeepOrReplaceKeyParams = { destination: string; maskedExistingKey: string }\n\nexport type KeyAnswer = { kind: 'kept' } | { kind: 'replaced'; key: string }\n\nexport async function askToKeepOrReplaceKey(\n { destination, maskedExistingKey }: AskToKeepOrReplaceKeyParams,\n io: PromptIo,\n): Promise<KeyAnswer> {\n clack.note(\n `A nexos.ai API key was found on this machine (${maskedExistingKey}).\\n` +\n 'Press Enter to keep it, or paste a new one to replace it.\\n\\n' +\n `Need a different key? Create one at:\\n ${API_KEYS_URL}\\n\\n${destination}`,\n 'nexos.ai API key',\n { output: io.output },\n )\n\n const value = await throwIfCancelled(\n clack.password({ message: 'Paste a new key, or press Enter to keep the existing one', ...io }),\n )\n const pasted = value.trim()\n return pasted === '' ? { kind: 'kept' } : { kind: 'replaced', key: pasted }\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\n/** A paste with no key to fall back on: the user has just declined the one on offer. */\nexport async function askForNewKey(io: PromptIo): Promise<string> {\n const value = await throwIfCancelled(\n clack.password({\n message: 'Paste your nexos.ai API key',\n validate: (value) => ((value ?? '').trim() === '' ? 'A key is required' : undefined),\n ...io,\n }),\n )\n return value.trim()\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type RejectedKeyChoice = 'forget' | 'cancel'\n\nexport async function chooseOnSavedKeyRejected(status: number, io: PromptIo): Promise<RejectedKeyChoice> {\n return await throwIfCancelled(\n clack.select<RejectedKeyChoice>({\n message: `The gateway rejected the saved key (HTTP ${status}). What next?`,\n options: [\n { value: 'forget', label: 'Forget it and paste a new key' },\n { value: 'cancel', label: 'Cancel' },\n ],\n initialValue: 'forget',\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type SavedKeyChoice = 'use' | 'paste'\n\nexport async function chooseSavedKey(maskedKey: string, io: PromptIo): Promise<SavedKeyChoice> {\n return await throwIfCancelled(\n clack.select<SavedKeyChoice>({\n message: 'Which nexos.ai API key?',\n options: [\n { value: 'use', label: `Use saved key ${maskedKey}`, hint: 'from your system keychain' },\n { value: 'paste', label: 'Paste a new key' },\n ],\n initialValue: 'use',\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_MODEL } from '../../../product/gateway/models/predefined-models'\nimport { withBackKeys, type BackKeysResult } from '../../back-keys'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\n// No `validate`: clack runs it before it applies `defaultValue`, so Enter on an empty field would be refused.\nconst MODEL_ID_PROMPT: clack.TextOptions = {\n message: `Model id (Enter for ${DEFAULT_MODEL})`,\n placeholder: DEFAULT_MODEL,\n defaultValue: DEFAULT_MODEL,\n}\n\nconst REQUIRED_MODEL_ID_PROMPT: clack.TextOptions = {\n message: 'Model id',\n validate: (value) =>\n value === undefined || value.trim() === '' ? 'Type a model id, or press Esc to go back.' : undefined,\n}\n\nexport async function askForModelId(io: PromptIo): Promise<string> {\n const typed = await throwIfCancelled(clack.text({ ...MODEL_ID_PROMPT, ...io }))\n return normalizeModelId(typed)\n}\n\nexport async function askForModelIdWithBack(io: PromptIo): Promise<BackKeysResult<string>> {\n const typed = await withBackKeys({\n isFieldEmpty: () => false,\n run: () => clack.text({ ...MODEL_ID_PROMPT, ...io }),\n input: io.input,\n })\n if (typed.kind === 'back') return typed\n\n return { kind: 'chosen', value: normalizeModelId(typed.value) }\n}\n\nexport async function askForRequiredModelIdWithBack(io: PromptIo): Promise<BackKeysResult<string>> {\n const typed = await withBackKeys({\n isFieldEmpty: () => false,\n run: () => clack.text({ ...REQUIRED_MODEL_ID_PROMPT, ...io }),\n input: io.input,\n })\n if (typed.kind === 'back') return typed\n\n return { kind: 'chosen', value: typed.value.trim() }\n}\n\nfunction normalizeModelId(typed: string): string {\n const modelId = typed.trim()\n return modelId === '' ? DEFAULT_MODEL : modelId\n}\n","import type { EventEmitter } from 'node:events'\nimport type { Key } from 'node:readline'\nimport * as clack from '@clack/prompts'\nimport { CancelledError } from './cancelled-error'\n\nconst ESCAPE_KEY = 'escape'\nconst EDITING_BACK_KEYS = ['left', 'backspace', 'delete'] as const\n\nexport function isBackKeystroke(key: Key | undefined, isFieldEmpty: boolean): boolean {\n if (key?.name === ESCAPE_KEY) return true\n return isFieldEmpty && isEditingBackKey(key?.name)\n}\n\nexport type BackKeysResult<T> = { kind: 'chosen'; value: T } | { kind: 'back' }\n\nexport type WithBackKeysParams<T> = {\n isFieldEmpty: () => boolean\n run: () => Promise<T | typeof clack.CANCEL_SYMBOL>\n input: EventEmitter\n}\n\n// Clack reports Esc and Ctrl-C as one cancel symbol, so a keypress listener that runs first tells them apart.\nexport async function withBackKeys<T>({ isFieldEmpty, run, input }: WithBackKeysParams<T>): Promise<BackKeysResult<T>> {\n let isGoingBack = false\n\n const onKeypress = (_character: string | undefined, key: Key): void => {\n const name = key?.name\n if (name === undefined) return\n\n isGoingBack = isBackKeystroke(key, isFieldEmpty())\n\n if (!isEditingBackKey(name)) return\n if (isGoingBack) clack.settings.aliases.set(name, 'cancel')\n else clack.settings.aliases.delete(name)\n }\n\n input.prependListener('keypress', onKeypress)\n try {\n const value = await run()\n if (!clack.isCancel(value)) return { kind: 'chosen', value }\n if (isGoingBack) return { kind: 'back' }\n throw new CancelledError()\n } finally {\n input.removeListener('keypress', onKeypress)\n for (const name of EDITING_BACK_KEYS) clack.settings.aliases.delete(name)\n }\n}\n\nfunction isEditingBackKey(name: string | undefined): boolean {\n return EDITING_BACK_KEYS.some((editingKey) => editingKey === name)\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_MODEL } from '../../../product/gateway/models/predefined-models'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type FetchFailureChoice = 'retry' | 'manual' | 'default'\n\nexport async function chooseOnFetchFailure(io: PromptIo): Promise<FetchFailureChoice> {\n return await throwIfCancelled(\n clack.select<FetchFailureChoice>({\n message: 'Could not fetch the model list. What next?',\n options: [\n { value: 'retry', label: 'Try again', hint: 'send the same request again' },\n { value: 'manual', label: 'Type a model id…', hint: 'if you know which one you want' },\n { value: 'default', label: `Use ${DEFAULT_MODEL}`, hint: 'the gateway router' },\n ],\n initialValue: 'retry',\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { ModelSuggestion } from '../../model-choices'\nimport type { PromptIo } from '../../prompt-io'\n\nconst ANOTHER_MODEL_VALUE = '\\u0000another'\n\n/** Resolves to the default chosen, or to undefined when the user wants the model picker instead. */\nexport async function chooseSavedModel(\n defaults: readonly ModelSuggestion[],\n io: PromptIo,\n): Promise<string | undefined> {\n const chosen = await throwIfCancelled(\n clack.select<string>({\n message: 'Which model should your agents use?',\n options: [\n ...defaults.map(({ model, hint }) => ({ value: model, label: `Use ${model}`, hint })),\n { value: ANOTHER_MODEL_VALUE, label: 'Choose another model…' },\n ],\n ...io,\n }),\n )\n return chosen === ANOTHER_MODEL_VALUE ? undefined : chosen\n}\n","import * as clack from '@clack/prompts'\nimport { formatCount } from '../../../shared/text/format-count'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport { BROWSE_VALUE, MANUAL_VALUE, type ModelChoices } from '../../model-choices'\nimport { createLog } from '../../output'\nimport type { PromptIo } from '../../prompt-io'\nimport { askForModelIdWithBack, askForRequiredModelIdWithBack } from './ask-for-model-id'\nimport { browseCatalogue } from './browse-catalogue'\n\nconst TYPED_ID_BACK_KEY_NOTE = 'Esc goes back to the list above.'\nconst CATALOGUE_BACK_KEYS_NOTE = 'Esc goes back to the list above, and so do ← and Delete while the filter is empty.'\n\nexport async function selectModel(choices: ModelChoices, io: PromptIo): Promise<string> {\n const log = createLog(io)\n const rows: clack.Option<string>[] = choices.rows.map((row) => ({\n value: row.value,\n label: row.label,\n ...(row.hint !== undefined ? { hint: row.hint } : {}),\n }))\n\n let cameBackFrom: string | undefined\n let hasNotedTypedIdBackKey = false\n let hasNotedCatalogueBackKeys = false\n\n for (;;) {\n const initialValue = cameBackFrom ?? rows[0]?.value\n const chosenRow = await throwIfCancelled(\n clack.select<string>({\n message: 'Which model should your agents use?',\n options: rows,\n ...(initialValue === undefined ? {} : { initialValue }),\n ...io,\n }),\n )\n\n if (chosenRow !== BROWSE_VALUE && chosenRow !== MANUAL_VALUE) return chosenRow\n\n if (chosenRow === MANUAL_VALUE) {\n if (!hasNotedTypedIdBackKey) log.info(TYPED_ID_BACK_KEY_NOTE)\n hasNotedTypedIdBackKey = true\n\n const typed = choices.isRouterOffered ? await askForModelIdWithBack(io) : await askForRequiredModelIdWithBack(io)\n if (typed.kind === 'chosen') return typed.value\n cameBackFrom = MANUAL_VALUE\n continue\n }\n\n if (!hasNotedCatalogueBackKeys) {\n log.info(CATALOGUE_BACK_KEYS_NOTE)\n if (choices.hiddenCount > 0) log.info(formatHiddenModelsNote(choices.hiddenCount))\n }\n hasNotedCatalogueBackKeys = true\n\n const browsed = await browseCatalogue(choices, io)\n if (browsed.kind === 'chosen') return browsed.value\n cameBackFrom = BROWSE_VALUE\n }\n}\n\nexport function formatHiddenModelsNote(hiddenCount: number): string {\n const subject = hiddenCount === 1 ? 'it does' : 'they do'\n return `${formatCount(hiddenCount, 'model')} hidden — ${subject} not serve the API your selected agents use.`\n}\n","import * as clack from '@clack/prompts'\nimport { withBackKeys, type BackKeysResult } from '../../back-keys'\nimport { formatModelHint, type ModelChoices } from '../../model-choices'\nimport type { PromptIo } from '../../prompt-io'\n\nconst CATALOGUE_VISIBLE_ROWS = 15\n\nexport async function browseCatalogue(choices: ModelChoices, io: PromptIo): Promise<BackKeysResult<string>> {\n const catalogue: clack.Option<string>[] = choices.browsable.map((model) => {\n const hint = formatModelHint(model)\n return { value: model.id, label: model.id, ...(hint !== '' ? { hint } : {}) }\n })\n\n // Clack calls an options function with `this` bound to the prompt, whose `userInput` is the live filter.\n let readFilterText = (): string => ''\n\n return await withBackKeys({\n isFieldEmpty: () => readFilterText() === '',\n run: () =>\n clack.autocomplete<string>({\n message: 'Model',\n maxItems: CATALOGUE_VISIBLE_ROWS,\n options: function (this: { readonly userInput: string }) {\n readFilterText = () => this.userInput\n return catalogue\n },\n ...io,\n }),\n input: io.input,\n })\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport type HarnessChoice = { value: string; label: string; hint: string; isDisabled: boolean }\n\nexport async function selectHarnesses(choices: readonly HarnessChoice[], io: PromptIo): Promise<string[]> {\n return await throwIfCancelled(\n clack.multiselect<string>({\n message: 'Which agents should use the nexos.ai Gateway?',\n options: choices.map((choice) => ({\n value: choice.value,\n label: choice.label,\n hint: choice.hint,\n disabled: choice.isDisabled,\n })),\n initialValues: [],\n required: true,\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport type RestoreChoice = { value: string; label: string; hint: string }\n\nexport async function selectRestoreHarnesses(choices: readonly RestoreChoice[], io: PromptIo): Promise<string[]> {\n return await throwIfCancelled(\n clack.multiselect<string>({\n message: 'Which agents should get their original config back?',\n options: choices.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: choices.map(({ value }) => value),\n required: false,\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_SCOPE, type ConfigScope } from '../../shared/platform/platform-context'\nimport { throwIfCancelled } from '../cancelled-error'\nimport { formatList } from '../format-list'\nimport type { PromptIo } from '../prompt-io'\n\nexport type SelectRestoreScopeParams = { userAgents: readonly string[]; projectAgents: readonly string[] }\n\nexport async function selectRestoreScope(\n { userAgents, projectAgents }: SelectRestoreScopeParams,\n io: PromptIo,\n): Promise<ConfigScope> {\n return await throwIfCancelled(\n clack.select<ConfigScope>({\n message: 'Which configs should get their original setup back?',\n options: [\n { value: 'user', label: 'User-level', hint: describeRecordedAgents(userAgents) },\n { value: 'project', label: 'Project-level', hint: `this directory — ${describeRecordedAgents(projectAgents)}` },\n ],\n initialValue: DEFAULT_SCOPE,\n ...io,\n }),\n )\n}\n\nfunction describeRecordedAgents(agents: readonly string[]): string {\n return agents.length === 0 ? 'nothing to restore' : formatList(agents)\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_SCOPE, type ConfigScope } from '../../shared/platform/platform-context'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport type SelectScopeParams = { userPaths: readonly string[]; projectPaths: readonly string[] }\n\nexport async function selectScope({ userPaths, projectPaths }: SelectScopeParams, io: PromptIo): Promise<ConfigScope> {\n return await throwIfCancelled(\n clack.select<ConfigScope>({\n message: 'Where should the configs be written?',\n options: [\n { value: 'user', label: 'User-level', hint: `applies everywhere — ${userPaths.join(', ')}` },\n { value: 'project', label: 'Project-level', hint: `this directory only — ${projectPaths.join(', ')}` },\n ],\n initialValue: DEFAULT_SCOPE,\n ...io,\n }),\n )\n}\n","import type { Readable, Writable } from 'node:stream'\nimport * as clack from '@clack/prompts'\nimport pc from 'picocolors'\nimport { CancelledError } from './cancelled-error'\nimport { GLYPHS } from './glyphs'\nimport type { PromptIo } from './prompt-io'\n\nexport interface Spinner {\n start(message: string): void\n stop(message: string): void\n waitFor<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>\n /**\n * Waits under the same Ctrl-C handling as `waitFor`, drawing nothing and reporting nothing.\n * It owns the terminal while it runs: never overlap it with `start`, or with another spinner on\n * the same terminal, because whichever finishes first clears raw mode and pauses the stream.\n */\n waitQuietly<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>\n}\n\n// Not clack's spinner: it reads Ctrl-C from stdin itself and answers by exiting the process with 0.\nexport function createSpinner(io: PromptIo): Spinner {\n const taskController = new AbortController()\n const cancelled = new Promise<never>((_resolve, reject) => {\n taskController.signal.addEventListener('abort', () => reject(taskController.signal.reason), { once: true })\n })\n cancelled.catch(() => {})\n\n let stopSpinning: (() => void) | null = null\n const end = (): void => {\n stopSpinning?.()\n stopSpinning = null\n }\n const cancel = (): void => {\n end()\n taskController.abort(new CancelledError())\n }\n\n const waitFor = async <T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> => {\n try {\n return await Promise.race([task(taskController.signal), cancelled])\n } catch (error) {\n end()\n throw error\n }\n }\n\n return {\n start: (message) => {\n end()\n stopSpinning = spin({ io, message, onCancel: cancel })\n },\n stop: (message) => {\n if (stopSpinning === null) return\n\n end()\n io.output.write(`${pc.green(clack.S_STEP_SUBMIT)} ${message}\\n`)\n },\n waitFor,\n waitQuietly: async (task) => {\n const stopListening = listenForCancel(io, cancel)\n try {\n return await waitFor(task)\n } finally {\n stopListening()\n }\n },\n }\n}\n\ntype SpinParams = { io: PromptIo; message: string; onCancel: () => void }\n\nfunction spin({ io, message, onCancel }: SpinParams): () => void {\n io.output.write(`${pc.gray(clack.S_BAR)}\\n`)\n const stopAnimating = isTerminalOutput(io.output) ? animate(io.output, message) : () => {}\n const stopListening = listenForCancel(io, onCancel)\n\n return () => {\n stopListening()\n stopAnimating()\n }\n}\n\nconst FRAMES = clack.unicode ? ['◒', '◐', '◓', '◑'] : ['•', 'o', 'O', '0']\nconst FRAME_INTERVAL_MS = 80\nconst HIDE_CURSOR = '\\u001b[?25l'\nconst SHOW_CURSOR = '\\u001b[?25h'\nconst CLEAR_LINE = '\\r\\u001b[2K'\nconst FRAME_WIDTH = 4\n\nfunction animate(output: TerminalOutput, message: string): () => void {\n const text = fitToWidth(message, output.columns)\n let frameIndex = 0\n const drawFrame = (): void => {\n output.write(`${CLEAR_LINE}${pc.magenta(FRAMES[frameIndex % FRAMES.length] ?? '')} ${text}`)\n frameIndex += 1\n }\n\n output.write(HIDE_CURSOR)\n drawFrame()\n const timer = setInterval(drawFrame, FRAME_INTERVAL_MS)\n return () => {\n clearInterval(timer)\n output.write(`${CLEAR_LINE}${SHOW_CURSOR}`)\n }\n}\n\nfunction fitToWidth(text: string, columns: number): string {\n const width = columns - FRAME_WIDTH\n if (width <= 0 || text.length <= width) return text\n\n return `${text.slice(0, width - GLYPHS.elided.length)}${GLYPHS.elided}`\n}\n\nconst CTRL_C = '\\u0003'\nconst ESCAPE = '\\u001b'\n\nfunction listenForCancel({ input, onInterrupt }: PromptIo, onCancel: () => void): () => void {\n const stopInterruptListening = onInterrupt(onCancel)\n if (!isTerminalInput(input)) return stopInterruptListening\n\n const onData = (chunk: Buffer | string): void => {\n if (isCancelKeystroke(String(chunk))) onCancel()\n }\n input.setRawMode(true)\n input.on('data', onData)\n input.resume()\n return () => {\n stopInterruptListening()\n input.removeListener('data', onData)\n input.setRawMode(false)\n input.pause()\n }\n}\n\nfunction isCancelKeystroke(chunk: string): boolean {\n return chunk.includes(CTRL_C) || chunk === ESCAPE\n}\n\ntype TerminalInput = Readable & { setRawMode(isRaw: boolean): unknown }\n\nfunction isTerminalInput(input: Readable): input is TerminalInput {\n return 'isTTY' in input && input.isTTY === true && 'setRawMode' in input && typeof input.setRawMode === 'function'\n}\n\ntype TerminalOutput = Writable & { columns: number }\n\nfunction isTerminalOutput(output: Writable): output is TerminalOutput {\n return 'isTTY' in output && output.isTTY === true && 'columns' in output && typeof output.columns === 'number'\n}\n","import type { ConfigScope } from '../shared/platform/platform-context'\nimport type { ModelChoices, ModelSuggestion } from './model-choices'\nimport { cancel, createLog, dim, intro, note, outro, printLines, type Log } from './output'\nimport type { PromptIo } from './prompt-io'\nimport { confirm } from './prompts/confirm'\nimport {\n askForKey,\n askToKeepOrReplaceKey,\n type AskForKeyParams,\n type AskToKeepOrReplaceKeyParams,\n type KeyAnswer,\n} from './prompts/key/ask-for-key'\nimport { askForNewKey } from './prompts/key/ask-for-new-key'\nimport { chooseOnSavedKeyRejected, type RejectedKeyChoice } from './prompts/key/choose-on-saved-key-rejected'\nimport { chooseSavedKey, type SavedKeyChoice } from './prompts/key/choose-saved-key'\nimport { askForModelId } from './prompts/model/ask-for-model-id'\nimport { chooseOnFetchFailure, type FetchFailureChoice } from './prompts/model/choose-on-fetch-failure'\nimport { chooseSavedModel } from './prompts/model/choose-saved-model'\nimport { selectModel } from './prompts/model/select-model'\nimport { selectHarnesses, type HarnessChoice } from './prompts/select-harnesses'\nimport { selectRestoreHarnesses, type RestoreChoice } from './prompts/select-restore-harnesses'\nimport { selectRestoreScope, type SelectRestoreScopeParams } from './prompts/select-restore-scope'\nimport { selectScope, type SelectScopeParams } from './prompts/select-scope'\nimport { createSpinner, type Spinner } from './spinner'\n\nexport interface TerminalUi {\n intro(message: string): void\n outro(message: string): void\n cancel(message: string): void\n log: Log\n print(lines: readonly string[]): void\n dim(message: string): void\n note(message: string, title: string): void\n spinner(): Spinner\n selectScope(params: SelectScopeParams): Promise<ConfigScope>\n selectHarnesses(choices: readonly HarnessChoice[]): Promise<string[]>\n askForKey(params: AskForKeyParams): Promise<string>\n askToKeepOrReplaceKey(params: AskToKeepOrReplaceKeyParams): Promise<KeyAnswer>\n askForNewKey(): Promise<string>\n chooseSavedKey(maskedKey: string): Promise<SavedKeyChoice>\n chooseOnSavedKeyRejected(status: number): Promise<RejectedKeyChoice>\n confirm(message: string, shouldDefaultToYes: boolean): Promise<boolean>\n chooseSavedModel(defaults: readonly ModelSuggestion[]): Promise<string | undefined>\n selectModel(choices: ModelChoices): Promise<string>\n askForModelId(): Promise<string>\n chooseOnFetchFailure(): Promise<FetchFailureChoice>\n selectRestoreScope(params: SelectRestoreScopeParams): Promise<ConfigScope>\n selectRestoreHarnesses(choices: readonly RestoreChoice[]): Promise<string[]>\n}\n\nexport function createTerminalUi(io: PromptIo): TerminalUi {\n return {\n intro: (message) => intro(message, io),\n outro: (message) => outro(message, io),\n cancel: (message) => cancel(message, io),\n log: createLog(io),\n print: (lines) => printLines(lines, io),\n dim: (message) => dim(message, io),\n note: (message, title) => note(message, title, io),\n spinner: () => createSpinner(io),\n selectScope: (params) => selectScope(params, io),\n selectHarnesses: (choices) => selectHarnesses(choices, io),\n askForKey: (params) => askForKey(params, io),\n askToKeepOrReplaceKey: (params) => askToKeepOrReplaceKey(params, io),\n askForNewKey: () => askForNewKey(io),\n chooseSavedKey: (maskedKey) => chooseSavedKey(maskedKey, io),\n chooseOnSavedKeyRejected: (status) => chooseOnSavedKeyRejected(status, io),\n confirm: (message, shouldDefaultToYes) => confirm(message, shouldDefaultToYes, io),\n chooseSavedModel: (defaults) => chooseSavedModel(defaults, io),\n selectModel: (choices) => selectModel(choices, io),\n askForModelId: () => askForModelId(io),\n chooseOnFetchFailure: () => chooseOnFetchFailure(io),\n selectRestoreScope: (params) => selectRestoreScope(params, io),\n sel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AI,EAAE;AACzB,WAAO,UAAU;AAAA,EACnB;AACA,MAAI,CAAC,mBAAmB,OAAO,GAAG;AAChC,UAAM,SACJ,QAAQ,SAAS,gBAAgB,2BAAsB,QAAQ,MAAM,KAAK;AAC5E,YAAQ,MAAMA,KAAG,IAAI,GAAG,QAAQ,KAAK,KAAK,MAAM,EAAE,CAAC;AACnD,WAAO,UAAU;AAAA,EACnB;AAEA,QAAM,MAAM,cAAc;AAC1B,KAAG,MAAM,iCAA4B,QAAQ,KAAK,+BAA+B;AACjF,QAAM,SAAS,MAAM;AAAA,IACnB,EAAE,SAAS,aAAa,SAAS,KAAK,QAAQ,IAAI;AAAA,IAClD;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW,CAAC,QAAQ,sBAAsB,UAAU,QAAQ,mBAAmB,UAAU;AAAA,IAC3F;AAAA,EACF;AACA,MAAI,YAAY,QAAQ;AAEtB,YAAQ,KAAK,QAAQ,KAAK,OAAO,MAAM;AACvC,WAAO,UAAU;AAAA,EACnB;AACA,SAAO,OAAO;AAChB;AAEA,SAAS,OAAO,UAAwB;AAEtC,MAAI,SAAS,OAAQ,SAAQ,KAAK,QAAQ;AAC1C,UAAQ,WAAW;AACrB;AAEA,KAAK,KAAK,EACP,KAAK,MAAM,EACX,MAAM,CAAC,UAAmB;AACzB,UAAQ,MAAMA,KAAG,IAAI,OAAO,SAAS,cAAc,KAAK,CAAC,CAAC,CAAC;AAC3D,SAAO,UAAU,MAAM;AACzB,CAAC;","names":["path","pc","v","masker","match","masker","match","fetch","text","match","text","secret","match","match","match","match","keystore","masker","v","path","match","v","path","v","text","match","v","match","text","text","fs","fs","BYTE_ORDER_MARK","text","match","path","settings","path","match","text","DEFAULT_LINE_ENDING","readSource","restoreKey","match","path","BINARY","API_KEY_VARIABLE","CONFIG_DIRECTORY","path","BINARY","BASE_URL_VARIABLE","API_KEY_VARIABLE","MODEL_VARIABLE","fs","path","CONFIG_DIRECTORY","path","fs","path","match","v","BINARY","resolveConfigPath","planConfig","RUN_PROVIDER_ID","path","match","PROVIDER_ID","PROVIDER_NAME","text","match","path","path","path","path","match","text","v","keystore","availability","masker","check","pc","text","text","pc","match","P","match","v","OptionalTextSchema","ModelSchema","text","masker","fetch","text","detail","match","P","match","masker","fetch","match","match","match","match","P","match","masker","fetch","classifyRejection","match","P","masker","fetch","match","fs","path","v","path","JSON_INDENT","text","parseJson","fs","v","harnesses","harnesses","masker","masker","probe","fetch","path","path","masker","path","path","match","fs","path","v","match","match","text","match","fs","path","text","parseJson","JSON_INDENT","record","fs","path","path","match","match","path","pc","pc","text","pc","match","pc","match","masker","pc","note","masker","pc","pc","P","match","pc","masker","match","P","fs","path","fs","path","fs","fs","path","fs","record","harnesses","writtenFiles","path","fs","record","path","match","hasEnvVariables","record","restoreFile","match","path","record","masker","record","outro","path","pc","masker","pc","pc","P","match","pc","pc","formatOutcome","formatBackups","formatSummary","masker","match","P","pc","note","match","match","path","isDeepStrictEqual","planEnvFile","isDeepStrictEqual","hasOwnEnvChange","record","isSamePath","path","record","replanEnvFile","writtenFiles","path","record","FINISHED_WITH_ERRORS","masker","key","check","mode","outro","harnesses","fs","path","OWNER_ONLY_MODE","fs","match","path","finish","randomUUID","MS_PER_SECOND","clack","pc","intro","outro","cancel","note","clack","confirm","clack","value","clack","value","clack","clack","clack","clack","clack","clack","clack","clack","log","clack","selectHarnesses","clack","clack","clack","clack","pc","cancel","pc","text","intro","outro","cancel","note","selectHarnesses","confirm","pc","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/main.ts","../src/cli/classify-failure.ts","../src/shared/text/describe-error.ts","../src/ui/cancelled-error.ts","../src/cli/exit-code.ts","../src/cli/usage-error.ts","../src/cli/environment.ts","../src/product/gateway/gateway-errors.ts","../src/product/gateway/desired-config.ts","../src/product/gateway/gateway-request.ts","../src/product/gateway/models/predefined-models.ts","../src/shared/text/has-line-break.ts","../src/shared/text/read-non-blank.ts","../src/cli/help.ts","../src/cli/parse-cli-arguments.ts","../src/shared/file-formats/shell/escape-posix-single-quoted.ts","../src/shared/file-formats/shell/escape-powershell-single-quoted.ts","../src/product/secrets/key-prefix.ts","../src/product/secrets/masker.ts","../src/shared/platform/has-binary.ts","../src/shared/file-system/is-file.ts","../src/shared/file-system/is-missing-file-error.ts","../src/shared/platform/platform-context.ts","../src/commands/forget-key/forget-key.ts","../src/cli/refuse-prompts.ts","../src/flows/key/find-existing-keys.ts","../src/harnesses/claude-code/claude-code.ts","../src/shared/text/display-path.ts","../src/shared/file-system/find-first-existing-file.ts","../src/harnesses/detect-config-file.ts","../src/harnesses/read-jsonc-file.ts","../src/shared/file-formats/config-errors.ts","../src/shared/file-formats/jsonc.ts","../src/shared/file-formats/detect-line-ending.ts","../src/shared/file-formats/key-path.ts","../src/shared/file-formats/key-original.ts","../src/shared/file-formats/split-byte-order-mark.ts","../src/shared/file-system/read-file-if-exists.ts","../src/shared/file-system/utf16-file-error.ts","../src/harnesses/codex/codex.ts","../src/shared/file-formats/toml.ts","../src/harnesses/copilot-cli/copilot-cli.ts","../src/harnesses/crush/crush.ts","../src/shared/text/read-literal-key.ts","../src/harnesses/gemini-cli/gemini-cli.ts","../src/harnesses/opencode/opencode.ts","../src/harnesses/pi/pi.ts","../src/harnesses/qwen-code/qwen.ts","../src/harnesses/registry.ts","../src/product/storage/env-file/split-lines.ts","../src/product/storage/env-file/syntax/env-syntaxes.ts","../src/product/storage/env-file/syntax/posix-env-syntax.ts","../src/product/storage/env-file/syntax/env-syntax.ts","../src/product/storage/env-file/syntax/powershell-env-syntax.ts","../src/product/storage/env-file/parse-env-file.ts","../src/flows/key/key-step.ts","../src/product/gateway/models/protocol.ts","../src/ui/report/format-probes.ts","../src/ui/glyphs.ts","../src/ui/report/format-heading.ts","../src/ui/report/indent.ts","../src/flows/key/key-check.ts","../src/product/gateway/list-models.ts","../src/shared/text/format-count.ts","../src/product/gateway/model-schema.ts","../src/product/gateway/probe-result.ts","../src/flows/key/probe-summaries.ts","../src/product/gateway/models/model-compatibility.ts","../src/ui/model-choices.ts","../src/flows/model/model-choice.ts","../src/flows/model/model-probe.ts","../src/product/gateway/models/router-availability.ts","../src/product/gateway/probe-anthropic.ts","../src/product/storage/preferences/preferences.ts","../src/shared/file-system/describe-file-error.ts","../src/flows/model/suggest-defaults.ts","../src/flows/model/model-step.ts","../src/flows/model/choose-checked-model.ts","../src/product/storage/env-file/env-file-path.ts","../src/commands/launch/launch.ts","../src/commands/restore/run-restore.ts","../src/cli/resolve-named-harnesses.ts","../src/product/storage/backups/resolve-backup-root.ts","../src/product/storage/restore-record/restore-record.ts","../src/shared/file-formats/config-format.ts","../src/shared/file-system/resolve-owner-only-mode.ts","../src/shared/file-system/write-file-with-mode.ts","../src/product/storage/restore-record/restore-record-location.ts","../src/ui/report/format-restore-preview.ts","../src/ui/report/format-preview.ts","../src/ui/diff/diff-lines.ts","../src/ui/diff/render-diff.ts","../src/ui/report/format-restore-result.ts","../src/commands/restore/restore-result.ts","../src/commands/restore/apply-restore.ts","../src/product/storage/backups/back-up-file.ts","../src/shared/file-system/read-file-mode.ts","../src/product/storage/backups/back-up-before-writing.ts","../src/product/storage/env-file/write-env-file.ts","../src/product/storage/restore-record/remove-harness-records.ts","../src/product/storage/env-file/render-env-file.ts","../src/commands/restore/restore-env-text.ts","../src/commands/restore/restore-plan.ts","../src/product/storage/env-file/read-env-file.ts","../src/commands/restore/restore-secrets.ts","../src/ui/report/format-detection.ts","../src/ui/report/format-result.ts","../src/commands/setup/setup-result.ts","../src/ui/format-list.ts","../src/ui/report/outcome-style.ts","../src/commands/setup/answers/describe-key-destination.ts","../src/commands/setup/answers/scope.ts","../src/commands/setup/answers/harness-selection.ts","../src/commands/setup/changes/apply-changes.ts","../src/commands/setup/changes/change-plan.ts","../src/product/storage/restore-record/add-originals.ts","../src/commands/setup/changes/record-originals.ts","../src/commands/setup/run-setup.ts","../src/harnesses/run-launch.ts","../src/product/storage/keychain/keystore.ts","../src/ui/output.ts","../src/ui/prompts/confirm.ts","../src/ui/prompts/key/ask-for-key.ts","../src/ui/prompts/key/ask-for-new-key.ts","../src/ui/prompts/key/choose-on-saved-key-rejected.ts","../src/ui/prompts/key/choose-saved-key.ts","../src/ui/prompts/model/ask-for-model-id.ts","../src/ui/back-keys.ts","../src/ui/prompts/model/choose-on-fetch-failure.ts","../src/ui/prompts/model/choose-saved-model.ts","../src/ui/prompts/model/select-model.ts","../src/ui/prompts/model/browse-catalogue.ts","../src/ui/prompts/select-harnesses.ts","../src/ui/prompts/select-restore-harnesses.ts","../src/ui/prompts/select-restore-scope.ts","../src/ui/prompts/select-scope.ts","../src/ui/spinner.ts","../src/ui/terminal-ui.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process'\nimport { createRequire } from 'node:module'\nimport os from 'node:os'\nimport path from 'node:path'\nimport crossSpawn from 'cross-spawn'\nimport pc from 'picocolors'\nimport * as v from 'valibot'\nimport { classifyFailure, exitCodeForFailure } from './cli/classify-failure'\nimport { KEY_ENV_VARIABLE } from './cli/environment'\nimport { EXIT_CODE, type AgentExitCode } from './cli/exit-code'\nimport { renderHelp } from './cli/help'\nimport { isAgentName, parseCliArguments, type CliOptions, type Command } from './cli/parse-cli-arguments'\nimport { forgetKey } from './commands/forget-key/forget-key'\nimport { launch } from './commands/launch/launch'\nimport { runRestore } from './commands/restore/run-restore'\nimport { runSetup } from './commands/setup/run-setup'\nimport type { Harness, LaunchingHarness } from './harnesses/harness'\nimport { findHarnessByBinary, harnesses } from './harnesses/registry'\nimport { runLaunch, type RunnerDeps } from './harnesses/run-launch'\nimport { DEFAULT_MODEL, PREDEFINED_MODELS } from './product/gateway/models/predefined-models'\nimport { createMasker } from './product/secrets/masker'\nimport { PROJECT_BACKUP_DIRECTORY, USER_BACKUP_DIRECTORY } from './product/storage/backups/resolve-backup-root'\nimport {\n KEYCHAIN_DISABLED,\n KEYCHAIN_ENV_VARIABLE,\n KEYCHAIN_INTERACTION_TIMEOUT_MS,\n KEYCHAIN_PROBE_TIMEOUT_MS,\n createKeystore,\n} from './product/storage/keychain/keystore'\nimport { createPlatformContext, type PlatformContext } from './shared/platform/platform-context'\nimport { describeError } from './shared/text/describe-error'\nimport { createTerminalUi, type TerminalUi } from './ui/terminal-ui'\n\nconst NODE_AND_SCRIPT_ARGUMENT_COUNT = 2\n\nconst masker = createMasker({ secrets: [] })\n\nconst keystore = createKeystore({\n importKeyring: () => import('@napi-rs/keyring'),\n platform: process.platform,\n isWsl: () => process.env.WSL_DISTRO_NAME !== undefined || /microsoft/i.test(os.release()),\n hasMacKeychain: () =>\n spawnSync('security', ['default-keychain'], { stdio: 'ignore', timeout: KEYCHAIN_PROBE_TIMEOUT_MS }).status === 0,\n isEnabled: process.env[KEYCHAIN_ENV_VARIABLE] !== KEYCHAIN_DISABLED,\n probeTimeoutMs: KEYCHAIN_PROBE_TIMEOUT_MS,\n interactionTimeoutMs: KEYCHAIN_INTERACTION_TIMEOUT_MS,\n})\n\nconst runnerDeps: RunnerDeps = {\n spawn: (command, commandArguments, options) => crossSpawn(command, commandArguments, options),\n tmpdir: os.tmpdir,\n pid: process.pid,\n uid: process.getuid?.(),\n isAlive: isProcessAlive,\n signals: process,\n stdin: process.stdin,\n env: process.env,\n onError: (message) => console.error(masker.maskText(message)),\n}\n\n/** EPERM means the pid exists but belongs to someone else — alive. */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\nasync function main(): Promise<number> {\n const ui = createTerminalUi({ input: process.stdin, output: process.stdout, onInterrupt: listenForSigint })\n\n try {\n return await runCommand(ui)\n } catch (error) {\n const failure = classifyFailure(error, masker)\n if (failure.kind === 'usage') console.error(pc.red(failure.message))\n if (failure.kind === 'cancelled') ui.cancel('Cancelled.')\n if (failure.kind === 'unexpected') ui.log.error(failure.message)\n return exitCodeForFailure(failure)\n }\n}\n\nfunction listenForSigint(listener: () => void): () => void {\n process.once('SIGINT', listener)\n return () => process.removeListener('SIGINT', listener)\n}\n\nconst HELP = renderHelp({\n harnessIds: harnesses.map((harness) => harness.id),\n launchBinaries: launchableBinaries(),\n predefinedModelIds: PREDEFINED_MODELS.map((model) => model.id),\n defaultModel: DEFAULT_MODEL,\n backupDirectories: {\n user: path.join('~', USER_BACKUP_DIRECTORY),\n project: `.${path.sep}${PROJECT_BACKUP_DIRECTORY}`,\n },\n})\n\nfunction isLaunchingHarness(harness: Harness): harness is LaunchingHarness {\n return harness.kind === 'configurable' && harness.launch !== undefined\n}\n\nfunction launchableBinaries(): string[] {\n return harnesses.filter(isLaunchingHarness).map((harness) => harness.binary)\n}\n\nfunction describeUnknownAgent(binary: string): string {\n const oneOf = `One of: ${launchableBinaries().join(', ')}`\n if (isAgentName(binary)) return `Unknown agent \"${binary}\". ${oneOf}`\n\n return `Unknown agent. ${oneOf}. To pass a key, use --key or set $${KEY_ENV_VARIABLE}.`\n}\n\nconst PackageSchema = v.object({ version: v.string() })\n\nasync function runCommand(ui: TerminalUi): Promise<number> {\n const options = parseCliArguments(process.argv.slice(NODE_AND_SCRIPT_ARGUMENT_COUNT))\n\n if (options.shouldShowHelp) {\n console.log(HELP)\n return EXIT_CODE.ok\n }\n if (options.shouldShowVersion) {\n console.log(v.parse(PackageSchema, createRequire(import.meta.url)('../package.json')).version)\n return EXIT_CODE.ok\n }\n\n if (options.command.kind === 'forget-key') return await forgetKey({ keystore, ui, masker })\n if (options.command.kind === 'launch') return await runLaunchCommand({ command: options.command, options, ui })\n\n const commandParams = {\n options,\n baseContext: createContext(),\n ui,\n now: () => new Date(),\n masker,\n }\n if (options.command.kind === 'restore') return await runRestore(commandParams)\n\n return await runSetup({ ...commandParams, fetch, keystore })\n}\n\nfunction createContext(): PlatformContext {\n return createPlatformContext({\n home: os.homedir(),\n cwd: process.cwd(),\n platform: process.platform,\n env: process.env,\n isInteractive: process.stdin.isTTY === true && process.stdout.isTTY === true,\n })\n}\n\ntype LaunchCommandParams = {\n command: Extract<Command, { kind: 'launch' }>\n options: CliOptions\n ui: TerminalUi\n}\n\nasync function runLaunchCommand({ command, options, ui }: LaunchCommandParams): Promise<AgentExitCode> {\n const { binary, passthrough } = command\n const harness = findHarnessByBinary(binary)\n if (harness === undefined) {\n console.error(pc.red(masker.maskText(describeUnknownAgent(binary))))\n console.error(`\\n${HELP}`)\n return EXIT_CODE.usage\n }\n if (!isLaunchingHarness(harness)) {\n const reason =\n harness.kind === 'unsupported' ? `not configurable — ${harness.reason}` : 'cannot be started this way'\n console.error(pc.red(`${harness.label}: ${reason}`))\n return EXIT_CODE.usage\n }\n\n const ctx = createContext()\n ui.intro(`nexos-connect — starting ${harness.label} through the nexos.ai Gateway`)\n const result = await launch(\n { harness, passthrough, options, env: process.env },\n {\n keystore,\n ui,\n masker,\n ctx,\n fetch,\n runLaunch: (recipe, recipePassthrough) => runLaunch(recipe, recipePassthrough, runnerDeps),\n },\n )\n if ('signal' in result) {\n // Our own handlers are gone by now, so the default action ends this process too.\n process.kill(process.pid, result.signal)\n return EXIT_CODE.failed\n }\n return result.code\n}\n\nfunction finish(exitCode: number): void {\n // A hung keychain call leaves a native thread holding the event loop open; only a forced exit ends it.\n if (keystore.isHung) process.exit(exitCode)\n process.exitCode = exitCode\n}\n\nvoid main()\n .then(finish)\n .catch((error: unknown) => {\n console.error(pc.red(masker.maskText(describeError(error))))\n finish(EXIT_CODE.failed)\n })\n","import { match } from 'ts-pattern'\nimport type { Masker } from '../product/secrets/masker'\nimport { describeError } from '../shared/text/describe-error'\nimport { CancelledError } from '../ui/cancelled-error'\nimport { EXIT_CODE, type ExitCode } from './exit-code'\nimport { UsageError } from './usage-error'\n\nexport type Failure =\n | { kind: 'usage'; message: string }\n | { kind: 'cancelled' }\n | { kind: 'unexpected'; message: string }\n\nconst UNEXPECTED_NEXT_STEP =\n 'Run again with --dry-run to see what would change. If this keeps happening, it is a bug — please report it.'\n\nexport function classifyFailure(error: unknown, masker: Masker): Failure {\n if (error instanceof CancelledError) return { kind: 'cancelled' }\n\n const message = masker.maskText(describeError(error))\n if (error instanceof UsageError) return { kind: 'usage', message }\n\n return { kind: 'unexpected', message: `${message}\\n${UNEXPECTED_NEXT_STEP}` }\n}\n\nexport function exitCodeForFailure(failure: Failure): ExitCode {\n return match(failure.kind)\n .with('usage', () => EXIT_CODE.usage)\n .with('cancelled', () => EXIT_CODE.cancelled)\n .with('unexpected', () => EXIT_CODE.failed)\n .exhaustive()\n}\n","export function describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import * as clack from '@clack/prompts'\n\nexport class CancelledError extends Error {\n constructor() {\n super('cancelled by the user')\n this.name = 'CancelledError'\n }\n}\n\n// Narrowing on clack's cancel symbol leaves the wider `symbol` in the union, hence the cast.\nexport async function throwIfCancelled<T>(pending: Promise<T | symbol>): Promise<Exclude<T, symbol>> {\n const value = await pending\n if (clack.isCancel(value)) throw new CancelledError()\n return value as Exclude<T, symbol>\n}\n","export const EXIT_CODE = { ok: 0, failed: 1, usage: 2, cancelled: 130 } as const\n\nexport type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE]\n\n/** `npx nexos-connect <agent>` passes the started agent's own exit code through unchanged. */\nexport type AgentExitCode = number\n","export class UsageError extends Error {\n override readonly name = 'UsageError'\n}\n","import * as v from 'valibot'\nimport { trimTrailingSlashes } from '../product/gateway/gateway-request'\nimport { normalizeModel } from '../product/gateway/models/predefined-models'\nimport type { EnvironmentVariables } from '../shared/platform/platform-context'\nimport { hasLineBreak } from '../shared/text/has-line-break'\nimport { readNonBlank } from '../shared/text/read-non-blank'\nimport { UsageError } from './usage-error'\n\nexport const KEY_ENV_VARIABLE = 'NEXOS_API_KEY'\nexport const MODEL_ENV_VARIABLE = 'NEXOS_MODEL'\nexport const GATEWAY_ENV_VARIABLE = 'NEXOS_BASE_URL'\n\nexport type EnvironmentInputs = {\n key: string | undefined\n model: string | undefined\n gatewayHost: string | undefined\n}\n\nconst BlankAsAbsentSchema = v.pipe(v.optional(v.string()), v.transform(readNonBlank))\n\nconst ModelSchema = v.pipe(\n BlankAsAbsentSchema,\n v.transform((model) => (model === undefined ? undefined : normalizeModel(model))),\n)\n\nconst EnvironmentSchema = v.object({\n [KEY_ENV_VARIABLE]: BlankAsAbsentSchema,\n [MODEL_ENV_VARIABLE]: ModelSchema,\n [GATEWAY_ENV_VARIABLE]: BlankAsAbsentSchema,\n})\n\nexport function readEnvironmentInputs(env: EnvironmentVariables): EnvironmentInputs {\n const parsed = v.safeParse(EnvironmentSchema, env)\n if (!parsed.success) throw new UsageError(parsed.issues[0].message)\n\n return {\n key: parsed.output[KEY_ENV_VARIABLE],\n model: parsed.output[MODEL_ENV_VARIABLE],\n gatewayHost: parseGatewayHost(parsed.output[GATEWAY_ENV_VARIABLE]),\n }\n}\n\nexport function parseEnvironmentKey(key: string | undefined): string | undefined {\n if (key !== undefined && hasLineBreak(key)) {\n throw new UsageError(`$${KEY_ENV_VARIABLE} contains a line break. Set it on one line, or pass --key.`)\n }\n\n return key\n}\n\nconst UNSET_HINT = 'Unset it to use the nexos.ai gateway.'\n\nconst LOOPBACK_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]']\n\nfunction parseGatewayHost(value: string | undefined): string | undefined {\n if (value === undefined) return undefined\n\n const host = trimTrailingSlashes(value)\n if (!URL.canParse(host)) throw new UsageError(`$${GATEWAY_ENV_VARIABLE} is not a URL. ${UNSET_HINT}`)\n\n const { protocol, hostname } = new URL(host)\n const isEncrypted = protocol === 'https:'\n const isLocalPlainHttp = protocol === 'http:' && LOOPBACK_HOSTNAMES.includes(hostname)\n if (isEncrypted || isLocalPlainHttp) return host\n\n throw new UsageError(`$${GATEWAY_ENV_VARIABLE} must be an https:// URL, or http:// on this machine. ${UNSET_HINT}`)\n}\n","import { match } from 'ts-pattern'\nimport type { Masker } from '../secrets/masker'\nimport { API_KEYS_URL } from './desired-config'\n\nexport type GatewayFailure = GatewayUnreachableError | GatewayTimeoutError\n\nexport type UnreachableReason =\n | {\n kind: 'network'\n causeCode: string | undefined\n causeMessage: string\n }\n | { kind: 'redirect' }\n | { kind: 'invalid-header' }\n\nexport type GatewayUnreachableErrorParams = { endpoint: string; reason: UnreachableReason }\n\nexport class GatewayUnreachableError extends Error {\n readonly kind = 'unreachable'\n readonly endpoint: string\n readonly reason: UnreachableReason\n\n constructor({ endpoint, reason }: GatewayUnreachableErrorParams) {\n super(`Could not reach ${endpoint} (${reason.kind}).`)\n this.name = 'GatewayUnreachableError'\n this.endpoint = endpoint\n this.reason = reason\n }\n}\n\nexport type GatewayTimeoutErrorParams = { endpoint: string; timeoutMs: number }\n\nexport class GatewayTimeoutError extends Error {\n readonly kind = 'timed-out'\n readonly endpoint: string\n readonly timeoutMs: number\n\n constructor({ endpoint, timeoutMs }: GatewayTimeoutErrorParams) {\n super(`No response from ${endpoint} within ${formatSeconds(timeoutMs)}.`)\n this.name = 'GatewayTimeoutError'\n this.endpoint = endpoint\n this.timeoutMs = timeoutMs\n }\n}\n\nexport function isGatewayFailure(error: unknown): error is GatewayFailure {\n return error instanceof GatewayUnreachableError || error instanceof GatewayTimeoutError\n}\n\nconst NETWORK_NEXT_STEP = 'check your network or proxy, or rerun with --no-verify'\n\nexport function describeGatewayFailure(failure: GatewayFailure, masker: Masker): string {\n return match(failure)\n .with({ kind: 'unreachable' }, ({ reason }) => describeUnreachable(reason, masker))\n .with(\n { kind: 'timed-out' },\n ({ timeoutMs }) => `no response within ${formatSeconds(timeoutMs)} — ${NETWORK_NEXT_STEP}`,\n )\n .exhaustive()\n}\n\nconst SNIPPET_MAX_LENGTH = 200\n\n// Masked before truncating: a key cut short no longer matches, and would print in part.\nexport function formatHttpFailure(status: number, explanation: string, masker: Masker): string {\n const snippet = masker.maskText(explanation).replace(/\\s+/g, ' ').trim().slice(0, SNIPPET_MAX_LENGTH)\n return snippet === '' ? `HTTP ${status}` : `HTTP ${status} — ${snippet}`\n}\n\nconst REDIRECT_DESCRIPTION =\n 'the gateway answered with a redirect, which is refused — ' +\n 'check for a proxy or captive portal, or rerun with --no-verify'\nconst INVALID_HEADER_DESCRIPTION = `the key holds a character an HTTP header cannot carry, so it was not sent — copy it again from ${API_KEYS_URL}`\n\nfunction describeUnreachable(reason: UnreachableReason, masker: Masker): string {\n return match(reason)\n .with({ kind: 'network' }, ({ causeCode, causeMessage }) =>\n masker.maskText(`could not connect (${causeCode ?? causeMessage}) — ${NETWORK_NEXT_STEP}`),\n )\n .with({ kind: 'redirect' }, () => REDIRECT_DESCRIPTION)\n .with({ kind: 'invalid-header' }, () => INVALID_HEADER_DESCRIPTION)\n .exhaustive()\n}\n\nconst MS_PER_SECOND = 1_000\n\nfunction formatSeconds(milliseconds: number): string {\n return `${milliseconds / MS_PER_SECOND}s`\n}\n","export type DesiredConfig = {\n anthropicBaseUrl: string\n openaiBaseUrl: string\n apiKey: string\n model: string\n}\n\nexport const GATEWAY_HOST = 'https://api.nexos.ai'\n\nexport const API_KEYS_URL = 'https://workspace.nexos.ai/gateway/api-keys'\n\nexport type GatewayUrls = Pick<DesiredConfig, 'anthropicBaseUrl' | 'openaiBaseUrl'>\n\nconst OPENAI_PATH = '/v1'\n\nexport function buildGatewayUrls(host: string): GatewayUrls {\n return { anthropicBaseUrl: host, openaiBaseUrl: `${host}${OPENAI_PATH}` }\n}\n\nexport type BuildDesiredConfigParams = { gatewayUrls: GatewayUrls; apiKey: string; model: string }\n\nexport function buildDesiredConfig({ gatewayUrls, apiKey, model }: BuildDesiredConfigParams): DesiredConfig {\n return { ...gatewayUrls, apiKey, model }\n}\n","import { GatewayTimeoutError, GatewayUnreachableError, type UnreachableReason } from './gateway-errors'\n\nexport type Fetch = (url: string, init: RequestInit) => Promise<Response>\n\nexport type RequestGatewayParams = {\n url: string\n init: RequestInit\n fetch: Fetch\n timeoutMs: number\n signal?: AbortSignal | undefined\n}\n\nexport type GatewayResponse = { status: number; text: string }\n\nexport const GATEWAY_TIMEOUT_MS = 15_000\n\nexport async function requestGateway(params: RequestGatewayParams): Promise<GatewayResponse> {\n const { url, init } = params\n if (!hasValidHeaders(init.headers)) {\n throw new GatewayUnreachableError({ endpoint: url, reason: { kind: 'invalid-header' } })\n }\n\n const response = await exchangeWithinTimeout(params)\n if (isRedirectStatus(response.status)) {\n throw new GatewayUnreachableError({ endpoint: url, reason: { kind: 'redirect' } })\n }\n\n return response\n}\n\nconst SUCCESS_STATUS_MIN = 200\nconst SUCCESS_STATUS_MAX = 299\n\nexport function isSuccessStatus(status: number): boolean {\n return status >= SUCCESS_STATUS_MIN && status <= SUCCESS_STATUS_MAX\n}\n\n// oxlint-disable-next-line no-magic-numbers -- HTTP statuses, named by the list\nexport const KEY_REJECTED_STATUSES = [401, 403] as const\n\nexport function trimTrailingSlashes(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction hasValidHeaders(headers: RequestInit['headers']): boolean {\n try {\n new Headers(headers)\n return true\n } catch {\n return false\n }\n}\n\nasync function exchangeWithinTimeout({\n url,\n init,\n fetch,\n timeoutMs,\n signal: cancelSignal,\n}: RequestGatewayParams): Promise<GatewayResponse> {\n const timeoutSignal = AbortSignal.timeout(timeoutMs)\n const signal = cancelSignal === undefined ? timeoutSignal : AbortSignal.any([cancelSignal, timeoutSignal])\n try {\n return await rejectOnAbort(exchange(url, { ...init, redirect: 'manual', signal }, fetch), signal)\n } catch (error) {\n if (cancelSignal?.aborted === true) throw cancelSignal.reason\n if (timeoutSignal.aborted) throw new GatewayTimeoutError({ endpoint: url, timeoutMs })\n const reason: UnreachableReason = {\n kind: 'network',\n causeCode: findCauseCode(error),\n causeMessage: findDeepestMessage(error),\n }\n throw new GatewayUnreachableError({ endpoint: url, reason })\n }\n}\n\n// oxlint-disable-next-line no-magic-numbers -- HTTP statuses, named by the list\nconst REDIRECT_STATUSES: readonly number[] = [301, 302, 303, 307, 308]\n\nfunction isRedirectStatus(status: number): boolean {\n return REDIRECT_STATUSES.includes(status)\n}\n\nasync function exchange(url: string, init: RequestInit, fetch: Fetch): Promise<GatewayResponse> {\n const response = await fetch(url, init)\n return { status: response.status, text: await response.text() }\n}\n\nasync function rejectOnAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n const aborted = new Promise<never>((_resolve, reject) => {\n signal.addEventListener('abort', () => reject(signal.reason), { once: true })\n })\n return await Promise.race([work, aborted])\n}\n\nfunction findCauseCode(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined\n if ('code' in error && typeof error.code === 'string') return error.code\n return findCauseCode(error.cause)\n}\n\nfunction findDeepestMessage(error: unknown): string {\n if (!(error instanceof Error)) return String(error)\n if (error.cause instanceof Error) return findDeepestMessage(error.cause)\n return error.message\n}\n","export const PREDEFINED_MODELS = [{ id: 'auto-code', hint: 'nexos.ai router — the default' }] as const\n\nexport const DEFAULT_MODEL: string = PREDEFINED_MODELS[0].id\n\n/** Claude Code's own syntax for the router at 1M context; every other agent would send it verbatim. */\nexport const ONE_MILLION_CONTEXT_ROUTER = `${DEFAULT_MODEL}[1m]`\n\nexport function isPredefinedModel(model: string): boolean {\n return PREDEFINED_MODELS.some((predefined) => predefined.id === model)\n}\n\n// The gateway refuses a router prompt over 1,048,572 tokens; Claude Code's `[1m]` assumes 1,000,000 as well.\nconst ROUTER_CONTEXT_TOKENS = 1_000_000\n\n/** The window to give an agent that cannot know the model's own; undefined for any model but the router. */\nexport function findContextWindow(model: string): number | undefined {\n return model === DEFAULT_MODEL ? ROUTER_CONTEXT_TOKENS : undefined\n}\n\nexport function normalizeModel(model: string): string {\n return model === ONE_MILLION_CONTEXT_ROUTER ? DEFAULT_MODEL : model\n}\n","const LINE_BREAK_PATTERN = /[\\r\\n]/\n\nexport function hasLineBreak(text: string): boolean {\n return LINE_BREAK_PATTERN.test(text)\n}\n","export function readNonBlank(value: string | undefined): string | undefined {\n const trimmed = value?.trim()\n return trimmed === '' ? undefined : trimmed\n}\n","import { API_KEYS_URL } from '../product/gateway/desired-config'\nimport { KEY_ENV_VARIABLE, MODEL_ENV_VARIABLE } from './environment'\nimport { EXIT_CODE } from './exit-code'\n\nexport const COMMAND_NAME = 'nexos-connect'\nexport const RESTORE_COMMAND = 'restore'\nexport const TAGLINE = `${COMMAND_NAME} — point your coding agents at the nexos.ai Gateway`\n\nexport type RenderHelpParams = {\n harnessIds: readonly string[]\n launchBinaries: readonly string[]\n predefinedModelIds: readonly string[]\n defaultModel: string\n backupDirectories: { user: string; project: string }\n}\n\nexport function renderHelp({\n harnessIds,\n launchBinaries,\n predefinedModelIds,\n defaultModel,\n backupDirectories,\n}: RenderHelpParams): string {\n const predefinedModels = predefinedModelIds.join(', ')\n return `${TAGLINE}\n\nUsage\n npx ${COMMAND_NAME} [options] point the agents at the gateway\n npx ${COMMAND_NAME} <agent> [options] [-- <agent arguments>]\n npx ${COMMAND_NAME} forget-key\n npx ${COMMAND_NAME} ${RESTORE_COMMAND} [options] put back what it changed in each agent's config\n\n <agent> starts one agent once, pointed at the gateway, without changing its config.\n One of: ${launchBinaries.join(', ')}.\n\nRuns interactively with no options. Every question has a flag that answers it,\nso the flags exist for scripting and CI as much as for convenience.\n\n${RESTORE_COMMAND} puts every key ${COMMAND_NAME} set back the way it was before the first\nsetup, and keeps everything added since. It takes --harnesses, --scope, --yes,\n--dry-run and --backup-dir; --yes restores every agent it has a record of.\n\nOptions\n --harnesses <ids> Comma-separated agent ids; skips the picker.\n One of: ${harnessIds.join(', ')}\n --key <key> nexos.ai API key. Falls back to $${KEY_ENV_VARIABLE}, then the key saved\n in your system keychain, then a prompt.\n --save-key Save the key in your system keychain for future runs, once it\n passes the key check. A usage error on a machine with no keychain.\n --model <id> Model every agent should use; skips the model picker.\n Falls back to $${MODEL_ENV_VARIABLE}, then the agents' saved default, then\n the picker: ${predefinedModels}, or any id from GET /v1/models.\n --save-model Save the model as the default of each agent it is used for,\n without asking. Never on a dry run.\n --scope <scope> Where to write: user (the default — your home directory,\n applying everywhere) or project (this directory only).\n -y, --yes Answer every question with its default: user scope, the\n detected agents, a key already on this machine, and the\n agents' saved default model, else ${defaultModel}. A gateway that\n rejects the router is a usage error; one that could not\n confirm it only warns. Writes without asking; a failed key\n check warns and continues.\n --dry-run Show the diffs and write nothing.\n --no-verify Skip the gateway entirely (useful offline). The model picker\n then shows no model list; ${predefinedModels} is not offered.\n --backup-dir <path> Where originals are copied, in a <timestamp> folder.\n Default: ${backupDirectories.user} (user scope), ${backupDirectories.project} (project).\n -h, --help Show this help.\n -v, --version Show the version.\n\nStarting an agent takes --key, --model, --save-key, --save-model, --no-verify\nand --yes only. Its model is --model, else $${MODEL_ENV_VARIABLE}, else the agent's saved default, else\nthe picker (--yes: ${defaultModel}).\n\nExit codes\n ${EXIT_CODE.ok} done\n ${EXIT_CODE.failed} an agent failed, while planning or while writing; or an agent could not start\n ${EXIT_CODE.usage} usage error, or a question asked with no terminal to answer it\n ${EXIT_CODE.cancelled} cancelled, by Ctrl-C or by declining a confirmation\n Once an agent has started, its own exit code passes through unchanged.\n\nGet a key at ${API_KEYS_URL}\n`\n}\n","import { parseArgs, type ParseArgsOptionsConfig } from 'node:util'\nimport { match } from 'ts-pattern'\nimport { normalizeModel } from '../product/gateway/models/predefined-models'\nimport { createMasker } from '../product/secrets/masker'\nimport { CONFIG_SCOPES, isConfigScope, type ConfigScope } from '../shared/platform/platform-context'\nimport { describeError } from '../shared/text/describe-error'\nimport { hasLineBreak } from '../shared/text/has-line-break'\nimport { readNonBlank } from '../shared/text/read-non-blank'\nimport { COMMAND_NAME, RESTORE_COMMAND } from './help'\nimport { UsageError } from './usage-error'\n\nexport const FORGET_KEY_COMMAND = 'forget-key'\n\nexport type Command =\n | { kind: 'setup' }\n | { kind: 'restore' }\n | { kind: 'launch'; binary: string; passthrough: string[] }\n | { kind: 'forget-key' }\n\nexport type CliOptions = {\n command: Command\n harnessIds: string[]\n key: string | undefined\n model: string | undefined\n scope: ConfigScope | undefined\n shouldAssumeYes: boolean\n shouldSaveKey: boolean\n shouldSaveModel: boolean\n isDryRun: boolean\n shouldVerify: boolean\n backupDirectory: string | undefined\n shouldShowHelp: boolean\n shouldShowVersion: boolean\n}\n\nexport function parseCliArguments(argv: readonly string[]): CliOptions {\n const { values, tokens } = parseFlags(argv)\n return {\n command: commandFrom(tokens, values),\n harnessIds: parseHarnessIds(values.harnesses),\n key: values.key === undefined ? undefined : parseKeyFlag(values.key),\n model: parseModelFlag(values.model),\n scope: parseScope(values.scope),\n shouldAssumeYes: values.yes === true,\n shouldSaveKey: values['save-key'] === true,\n shouldSaveModel: values['save-model'] === true,\n isDryRun: values['dry-run'] === true,\n shouldVerify: values['no-verify'] !== true,\n backupDirectory: readNonBlank(values['backup-dir']),\n shouldShowHelp: values.help === true,\n shouldShowVersion: values.version === true,\n }\n}\n\nconst FLAGS = {\n harnesses: { type: 'string' },\n key: { type: 'string' },\n model: { type: 'string' },\n scope: { type: 'string' },\n yes: { type: 'boolean', short: 'y' },\n 'save-key': { type: 'boolean' },\n 'save-model': { type: 'boolean' },\n 'dry-run': { type: 'boolean' },\n 'no-verify': { type: 'boolean' },\n 'backup-dir': { type: 'string' },\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n} as const satisfies ParseArgsOptionsConfig\n\ntype ArgumentToken = { kind: string; value?: string | undefined }\n\nfunction parseFlags(argv: readonly string[]) {\n try {\n return parseArgs({ args: [...argv], options: FLAGS, allowPositionals: true, tokens: true, strict: true })\n } catch (error) {\n throw new UsageError(describeParseError(error, argv))\n }\n}\n\n/** True when an agent was named before `--`, so an unknown option is likely its own argument. */\nfunction hasNamedAgent(argv: readonly string[]): boolean {\n for (const argument of argv) {\n if (argument === '--') return false\n if (!argument.startsWith('-') && isAgentName(argument)) return true\n }\n return false\n}\n\ntype FlagValues = ReturnType<typeof parseFlags>['values']\n\nconst HELP_HINT = `Run npx ${COMMAND_NAME} --help to see the options.`\n\nfunction describeParseError(error: unknown, argv: readonly string[]): string {\n const message = describeError(error)\n const code = error instanceof Error && 'code' in error ? error.code : undefined\n return match(code)\n .with('ERR_PARSE_ARGS_UNKNOWN_OPTION', () => describeUnknownOption(message, argv))\n .otherwise(() => createMasker({ secrets: [] }).maskText(message))\n}\n\nconst QUOTED_PATTERN = /'([^']*)'/\nconst OPTION_NAME_PATTERN = /^--?[a-z][a-z-]{0,29}$/\n\nfunction describeUnknownOption(message: string, argv: readonly string[]): string {\n const option = QUOTED_PATTERN.exec(message)?.[1]\n if (option === undefined || !OPTION_NAME_PATTERN.test(option)) return `Unknown option. ${HELP_HINT}`\n\n const hint = hasNamedAgent(argv) ? ' If it belongs to the agent, put it after --.' : ''\n return `Unknown option ${option}. ${HELP_HINT}${hint}`\n}\n\nconst PASSTHROUGH_MISUSE = `\\`--\\` passes arguments to an agent, e.g. npx ${COMMAND_NAME} claude -- --resume`\n\nconst AGENT_NAME_PATTERN = /^[a-z][a-z-]{0,29}$/\n\n/** A positional is only ever echoed when it can be an agent name, never when it may be a pasted key. */\nexport function isAgentName(value: string): boolean {\n return AGENT_NAME_PATTERN.test(value)\n}\n\ntype CommandParts = { name: string | undefined; passthrough: string[] | null; values: FlagValues }\ntype LaunchParts = { name: string; passthrough: string[] | null; values: FlagValues }\n\nfunction commandFrom(tokens: readonly ArgumentToken[], values: FlagValues): Command {\n const terminatorIndex = tokens.findIndex((token) => token.kind === 'option-terminator')\n const before = terminatorIndex === -1 ? tokens : tokens.slice(0, terminatorIndex)\n const passthrough =\n terminatorIndex === -1 ? null : tokens.slice(terminatorIndex + 1).map((token) => token.value ?? '')\n\n const positionals = before.flatMap((token) => (token.kind === 'positional' ? [token.value ?? ''] : []))\n if (positionals.length > 1) throw new UsageError(describeExtraCommands(positionals))\n\n const [name] = positionals\n if (name === undefined || name === FORGET_KEY_COMMAND) return commandWithoutAgent({ name, passthrough, values })\n if (name === RESTORE_COMMAND) return restoreCommand({ name, passthrough, values })\n\n return launchCommand({ name, passthrough, values })\n}\n\nfunction describeExtraCommands(positionals: readonly string[]): string {\n const hint = \"Put the agent's own arguments after --, and a key with --key.\"\n if (positionals.every(isAgentName)) return `Expected one command, got: ${positionals.join(' ')}. ${hint}`\n\n return `Expected one command, got more than one argument. ${hint}`\n}\n\nfunction commandWithoutAgent({ name, passthrough, values }: CommandParts): Command {\n if (passthrough !== null) throw new UsageError(PASSTHROUGH_MISUSE)\n if (name === undefined) return { kind: 'setup' }\n\n const flags = Object.keys(values).filter((flag) => flag !== 'help' && flag !== 'version')\n if (flags.length > 0) throw new UsageError(`${FORGET_KEY_COMMAND} takes no options (got --${flags[0]}).`)\n return { kind: 'forget-key' }\n}\n\nfunction restoreCommand({ passthrough, values }: CommandParts): Command {\n if (passthrough !== null) throw new UsageError(PASSTHROUGH_MISUSE)\n assertRestoreFlags(values)\n return { kind: 'restore' }\n}\n\nconst LAUNCH_UNSUPPORTED_FLAGS = ['harnesses', 'scope', 'dry-run', 'backup-dir'] as const\n\nfunction launchCommand({ name, passthrough, values }: LaunchParts): Command {\n const unsupported = LAUNCH_UNSUPPORTED_FLAGS.filter((flag) => flag in values)\n if (unsupported.length > 0) {\n const shown = isAgentName(name) ? name : '<agent>'\n throw new UsageError(\n `--${unsupported[0]} is for setup only. npx ${COMMAND_NAME} ${shown} takes --key, --model, --save-key, --save-model, --no-verify and --yes.`,\n )\n }\n return { kind: 'launch', binary: name, passthrough: passthrough ?? [] }\n}\n\nconst RESTORE_UNSUPPORTED_FLAGS = ['key', 'model', 'save-model', 'no-verify'] as const\n\nfunction assertRestoreFlags(flags: FlagValues): void {\n const unsupported = RESTORE_UNSUPPORTED_FLAGS.find((name) => flags[name] !== undefined)\n if (unsupported !== undefined) throw new UsageError(`--${unsupported} does not apply to ${RESTORE_COMMAND}.`)\n}\n\nconst HARNESS_ID_SEPARATOR = ','\n\nfunction parseHarnessIds(value: string | undefined): string[] {\n if (value === undefined) return []\n\n const ids = value.split(HARNESS_ID_SEPARATOR).flatMap((id) => readNonBlank(id) ?? [])\n return [...new Set(ids)]\n}\n\nfunction parseKeyFlag(value: string): string {\n const key = readNonBlank(value)\n if (key === undefined) throw new UsageError('--key is empty. Pass a key, or drop --key to be prompted.')\n if (hasLineBreak(key)) throw new UsageError('--key contains a line break. Paste the key on one line.')\n\n return key\n}\n\nfunction parseModelFlag(value: string | undefined): string | undefined {\n const model = readNonBlank(value)\n return model === undefined ? undefined : normalizeModel(model)\n}\n\nfunction parseScope(value: string | undefined): ConfigScope | undefined {\n const scope = readNonBlank(value)\n if (scope === undefined) return undefined\n if (!isConfigScope(scope)) throw new UsageError(`--scope must be one of: ${CONFIG_SCOPES.join(', ')}`)\n\n return scope\n}\n","export function escapePosixSingleQuoted(value: string): string {\n return value.replace(/'/g, `'\\\\''`)\n}\n","// PowerShell also ends a single-quoted string at any of the typographic single quotes.\nexport const POWERSHELL_SINGLE_QUOTES = \"'‘’‚‛\"\n\nconst POWERSHELL_SINGLE_QUOTE = new RegExp(`[${POWERSHELL_SINGLE_QUOTES}]`, 'g')\n\nexport function escapePowerShellSingleQuoted(value: string): string {\n return value.replace(POWERSHELL_SINGLE_QUOTE, (quote) => quote + quote)\n}\n","export const KEY_PREFIXES = ['nexos-', 'user-'] as const\n\nexport type KeyPrefix = (typeof KEY_PREFIXES)[number]\n\nexport function findKeyPrefix(key: string): KeyPrefix | undefined {\n return KEY_PREFIXES.find((prefix) => key.startsWith(prefix))\n}\n\nexport function hasKnownKeyPrefix(key: string): boolean {\n return findKeyPrefix(key) !== undefined\n}\n","import { escapePosixSingleQuoted } from '../../shared/file-formats/shell/escape-posix-single-quoted'\nimport { escapePowerShellSingleQuoted } from '../../shared/file-formats/shell/escape-powershell-single-quoted'\nimport { KEY_PREFIXES, findKeyPrefix } from './key-prefix'\n\nexport interface Masker {\n maskText(text: string): string\n registerSecrets(secrets: readonly string[]): void\n}\n\nexport type CreateMaskerParams = { secrets: readonly string[] }\n\nconst MIN_SHAPE_BODY_LENGTH = 16\nconst KEY_PREFIX_ALTERNATIVES = KEY_PREFIXES.map(escapeForRegex).join('|')\nconst KEY_SHAPE_PATTERN = new RegExp(\n `(?<![/\\\\w])(?:${KEY_PREFIX_ALTERNATIVES})[A-Za-z0-9_-]{${MIN_SHAPE_BODY_LENGTH},}(?![/\\\\w])`,\n 'g',\n)\n\nexport function createMasker({ secrets }: CreateMaskerParams): Masker {\n const registeredSecrets = [...secrets]\n let findIdentitySpans = buildIdentityMatching(registeredSecrets)\n\n return {\n maskText: (text) => replaceSpans(text, pickOuterSpans([...findIdentitySpans(text), ...findShapeSpans(text)])),\n registerSecrets: (newSecrets) => {\n registeredSecrets.push(...newSecrets)\n findIdentitySpans = buildIdentityMatching(registeredSecrets)\n },\n }\n}\n\ntype MaskSpan = { start: number; end: number; mask: string }\n\nfunction buildIdentityMatching(secrets: readonly string[]): (text: string) => MaskSpan[] {\n const masksByForm = new Map<string, string>()\n for (const secret of secrets.filter((secret) => secret.trim() !== '')) {\n const mask = maskKey(secret)\n for (const form of listEscapedForms(secret)) {\n if (!masksByForm.has(form)) masksByForm.set(form, mask)\n }\n }\n if (masksByForm.size === 0) return () => []\n\n const alternatives = [...masksByForm.keys()].sort((first, second) => second.length - first.length)\n const pattern = new RegExp(alternatives.map(buildFormPattern).join('|'), 'g')\n return (text) => [...text.matchAll(pattern)].map((match) => toSpan(match, masksByForm.get(match[0]) ?? match[0]))\n}\n\nfunction findShapeSpans(text: string): MaskSpan[] {\n return [...text.matchAll(KEY_SHAPE_PATTERN)].map((match) => toSpan(match, maskKey(match[0])))\n}\n\nfunction toSpan(match: RegExpExecArray, mask: string): MaskSpan {\n return { start: match.index, end: match.index + match[0].length, mask }\n}\n\n// Leftmost, then longest: a key wins over a registered secret inside it, and a registered key over\n// the part of it that its shape alone matches.\nfunction pickOuterSpans(spans: readonly MaskSpan[]): MaskSpan[] {\n const picked: MaskSpan[] = []\n for (const span of [...spans].sort((first, second) => first.start - second.start || second.end - first.end)) {\n if (span.start >= (picked.at(-1)?.end ?? 0)) picked.push(span)\n }\n return picked\n}\n\nfunction replaceSpans(text: string, spans: readonly MaskSpan[]): string {\n const ends = [0, ...spans.map((span) => span.end)]\n const pieces = spans.map((span, index) => text.slice(ends[index], span.start) + span.mask)\n return pieces.join('') + text.slice(ends.at(-1))\n}\n\nconst MIN_SUBSTRING_FORM_LENGTH = 16\nconst TOKEN_CHARACTER = '[A-Za-z0-9_-]'\n\nfunction buildFormPattern(form: string): string {\n const escaped = escapeForRegex(form)\n if (form.length >= MIN_SUBSTRING_FORM_LENGTH) return escaped\n\n return `(?<!${TOKEN_CHARACTER})${escaped}(?!${TOKEN_CHARACTER})`\n}\n\nconst MIN_BODY_LENGTH_FOR_HINT = 32\nconst HINT_HEAD_LENGTH = 4\nconst HINT_TAIL_LENGTH = 4\n\nfunction maskKey(key: string): string {\n const prefix = findKeyPrefix(key) ?? ''\n const body = key.slice(prefix.length)\n if (body.length < MIN_BODY_LENGTH_FOR_HINT) return `${prefix}…`\n\n return `${prefix}${body.slice(0, HINT_HEAD_LENGTH)}…${body.slice(-HINT_TAIL_LENGTH)}`\n}\n\nfunction listEscapedForms(secret: string): string[] {\n const json = JSON.stringify(secret).slice(1, -1)\n const forms = [\n secret,\n json,\n escapePosixSingleQuoted(secret),\n escapePowerShellSingleQuoted(secret),\n encodeURIComponent(secret),\n ]\n return [...new Set(forms)]\n}\n\nfunction escapeForRegex(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport { isFile } from '../file-system/is-file'\nimport type { EnvironmentVariables } from './platform-context'\n\nexport function hasBinary(name: string, env: EnvironmentVariables, platform: NodeJS.Platform): boolean {\n const lookup = resolvePathLookup(platform, env)\n const directories = (env.PATH ?? '')\n .split(lookup.delimiter)\n .map(lookup.normalizeEntry)\n .filter((directory) => directory !== '')\n\n const candidates = directories.flatMap((directory) =>\n lookup.executableExtensions.map((extension) => path.join(directory, name + extension)),\n )\n return candidates.some(isSearchableFile)\n}\n\ntype PathLookup = {\n delimiter: string\n executableExtensions: string[]\n normalizeEntry: (entry: string) => string\n}\n\nconst WINDOWS_PATH_DELIMITER = ';'\nconst POSIX_PATH_DELIMITER = ':'\nconst WINDOWS_DEFAULT_PATHEXT = '.EXE;.CMD;.BAT'\nconst WINDOWS_PATHEXT_DELIMITER = ';'\nconst QUOTE = '\"'\n\n// Not `path.delimiter`: that follows the host, so a win32 lookup on POSIX would split on colons.\nfunction resolvePathLookup(platform: NodeJS.Platform, env: EnvironmentVariables): PathLookup {\n return match(platform)\n .with('win32', () => ({\n delimiter: WINDOWS_PATH_DELIMITER,\n executableExtensions: (env.PATHEXT ?? WINDOWS_DEFAULT_PATHEXT)\n .split(WINDOWS_PATHEXT_DELIMITER)\n .filter((extension) => extension !== ''),\n normalizeEntry: (entry: string) => entry.replaceAll(QUOTE, ''),\n }))\n .otherwise(() => ({\n delimiter: POSIX_PATH_DELIMITER,\n executableExtensions: [''],\n normalizeEntry: (entry: string) => entry,\n }))\n}\n\nfunction isSearchableFile(candidate: string): boolean {\n try {\n return isFile(candidate)\n } catch {\n return false\n }\n}\n","import fs from 'node:fs'\nimport { isMissingFileError } from './is-missing-file-error'\n\nexport function isFile(filePath: string): boolean {\n try {\n return fs.statSync(filePath).isFile()\n } catch (error) {\n if (isMissingFileError(error)) return false\n throw error\n }\n}\n","const MISSING_FILE_CODES: readonly unknown[] = ['ENOENT', 'ENOTDIR']\n\nexport function isMissingFileError(error: unknown): boolean {\n return error instanceof Error && 'code' in error && MISSING_FILE_CODES.includes(error.code)\n}\n","import { hasBinary } from './has-binary'\n\nexport const CONFIG_SCOPES = ['user', 'project'] as const\n\nexport type ConfigScope = (typeof CONFIG_SCOPES)[number]\n\nexport const DEFAULT_SCOPE: ConfigScope = 'user'\n\nexport function isConfigScope(value: string): value is ConfigScope {\n return CONFIG_SCOPES.some((scope) => scope === value)\n}\n\nexport type EnvironmentVariables = Readonly<Record<string, string | undefined>>\n\nexport interface PlatformContext {\n home: string\n cwd: string\n platform: NodeJS.Platform\n env: EnvironmentVariables\n isInteractive: boolean\n scope: ConfigScope\n hasBinary(name: string): boolean\n}\n\nexport type CreatePlatformContextParams = Omit<PlatformContext, 'scope' | 'hasBinary'>\n\nexport function createPlatformContext(params: CreatePlatformContextParams): PlatformContext {\n return {\n ...params,\n scope: DEFAULT_SCOPE,\n hasBinary: (name) => hasBinary(name, params.env, params.platform),\n }\n}\n","import { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { Keystore } from '../../product/storage/keychain/keystore'\nimport { describeError } from '../../shared/text/describe-error'\nimport type { TerminalUi } from '../../ui/terminal-ui'\n\nexport type ForgetKeyParams = { keystore: Keystore; ui: Pick<TerminalUi, 'log'>; masker: Masker }\n\nexport async function forgetKey({ keystore, ui, masker }: ForgetKeyParams): Promise<ExitCode> {\n const availability = await keystore.availability()\n if (availability.kind === 'unavailable') {\n if (availability.hasPossibleEntry) {\n ui.log.error(`${availability.reason} — the saved key, if any, was not removed.`)\n return EXIT_CODE.failed\n }\n ui.log.info(`${availability.reason} — nothing to forget.`)\n return EXIT_CODE.ok\n }\n try {\n ui.log.success((await keystore.clear()) ? 'Forgot the saved key.' : 'No saved key to forget.')\n return EXIT_CODE.ok\n } catch (error) {\n // The saved key is never loaded here, so only masking by shape applies.\n ui.log.error(\n masker.maskText(\n `Could not remove the saved key: ${describeError(error)}. ` +\n 'Remove the \"nexos-connect\" item from your system keychain by hand.',\n ),\n )\n return EXIT_CODE.failed\n }\n}\n","import type { TerminalUi } from '../ui/terminal-ui'\nimport { KEY_ENV_VARIABLE } from './environment'\nimport { UsageError } from './usage-error'\n\ntype Refusal = { question: string; answers: string }\n\nconst MODEL_REFUSAL: Refusal = { question: 'which model to use', answers: '--model' }\nconst KEY_REFUSAL: Refusal = { question: 'for the key', answers: `--key, or set $${KEY_ENV_VARIABLE}` }\n\nexport function refusePrompts(ui: TerminalUi): TerminalUi {\n return {\n ...ui,\n selectScope: refuse({ question: 'where to write', answers: '--scope, or --yes for user level' }),\n selectHarnesses: refuse({\n question: 'which agents to configure',\n answers: '--harnesses, or --yes for the detected agents',\n }),\n askForKey: refuse(KEY_REFUSAL),\n askToKeepOrReplaceKey: refuse({\n question: 'whether to keep the key found on this machine',\n answers: '--yes to keep it, or --key',\n }),\n askForNewKey: refuse(KEY_REFUSAL),\n chooseSavedKey: refuse({ question: 'which key to use', answers: `--key, or set $${KEY_ENV_VARIABLE}` }),\n chooseOnSavedKeyRejected: refuse({ question: 'what to do about the rejected saved key', answers: '--key' }),\n confirm: refuse({ question: 'for confirmation', answers: '--yes' }),\n chooseSavedModel: refuse({\n question: 'which saved model to use',\n answers: '--model, or --yes for the saved default',\n }),\n selectModel: refuse(MODEL_REFUSAL),\n askForModelId: refuse(MODEL_REFUSAL),\n chooseOnFetchFailure: refuse({\n question: 'what to do after the failed check',\n answers: '--model, or --yes to continue',\n }),\n selectRestoreScope: refuse({ question: 'which configs to restore', answers: '--scope, or --yes for user level' }),\n selectRestoreHarnesses: refuse({\n question: 'which agents to restore',\n answers: '--harnesses, or --yes for every agent it has a record of',\n }),\n }\n}\n\nfunction refuse({ question, answers }: Refusal): () => Promise<never> {\n return async () => {\n throw new UsageError(`Cannot ask ${question} without a terminal. Pass ${answers}.`)\n }\n}\n","import * as v from 'valibot'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport { harnesses } from '../../harnesses/registry'\nimport { parseEnvFile } from '../../product/storage/env-file/parse-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport { readFileIfExists } from '../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { hasLineBreak } from '../../shared/text/has-line-break'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\n\nexport type FindExistingKeysParams = { ctx: PlatformContext; envPath: string; shell: Shell }\n\nconst OfferableKeySchema = v.pipe(\n v.string(),\n v.check((key) => !hasLineBreak(key)),\n)\n\nexport type ExistingKeys = { offered: string | undefined; all: string[] }\n\nexport function findExistingKeys({ ctx, envPath, shell }: FindExistingKeysParams): ExistingKeys {\n const userContext: PlatformContext = { ...ctx, scope: 'user' }\n const projectContext: PlatformContext = { ...ctx, scope: 'project' }\n const machineKeys = [...readEnvFileKeys(envPath, shell), ...readHarnessKeys(userContext)]\n const otherSecrets = [\n ...readHarnessKeys(projectContext),\n ...readFromEachHarness((harness) => harness.readSecrets?.(userContext) ?? []),\n ...readFromEachHarness((harness) => harness.readSecrets?.(projectContext) ?? []),\n ]\n const offered = machineKeys.find((key) => v.is(OfferableKeySchema, key))\n return { offered, all: [...machineKeys, ...otherSecrets] }\n}\n\nfunction readEnvFileKeys(envPath: string, shell: Shell): string[] {\n const envText = readSafely(() => readFileIfExists(envPath)) ?? null\n if (envText === null) return []\n\n const variables = parseEnvFile(envText, shell)\n return listKeyEnvVariables().flatMap((name) => readNonBlank(variables.get(name)) ?? [])\n}\n\nfunction listKeyEnvVariables(): string[] {\n const names = harnesses.flatMap((harness) =>\n harness.kind === 'configurable' && harness.keyEnvVariable !== undefined ? [harness.keyEnvVariable] : [],\n )\n return [...new Set(names)]\n}\n\nfunction readHarnessKeys(ctx: PlatformContext): string[] {\n return readFromEachHarness((harness) => {\n const key = readNonBlank(harness.readKey?.(ctx))\n return key === undefined ? [] : [key]\n })\n}\n\nfunction readFromEachHarness(read: (harness: ConfigurableHarness) => readonly string[]): string[] {\n return harnesses.flatMap((harness) =>\n harness.kind === 'configurable' ? (readSafely(() => read(harness)) ?? []) : [],\n )\n}\n\nfunction readSafely<T>(read: () => T): T | undefined {\n try {\n return read()\n } catch {\n return undefined\n }\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport * as v from 'valibot'\nimport { GATEWAY_HOST, type DesiredConfig } from '../../product/gateway/desired-config'\nimport { DEFAULT_MODEL, ONE_MILLION_CONTEXT_ROUTER } from '../../product/gateway/models/predefined-models'\nimport type { KeyPathUpdate } from '../../shared/file-formats/key-path'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { FileContribution, LaunchingHarness } from '../harness'\nimport { readJsoncFile } from '../read-jsonc-file'\n\nconst BINARY = 'claude'\n\nexport const claudeCode: LaunchingHarness = {\n kind: 'configurable',\n id: 'claude-code',\n label: 'Claude Code',\n binary: BINARY,\n protocols: ['anthropic'],\n projectSupport: { kind: 'supported' },\n detect: (ctx) => detectConfigFile(listSettingsCandidates(ctx), ctx.home),\n configPath: (ctx) => resolveSettingsPath(ctx),\n plan: (desired, ctx) => [planSettings(desired, ctx)],\n launch: (desired) => ({\n binary: BINARY,\n arguments: ['--settings', SETTINGS_PLACEHOLDER],\n env: {},\n files: [\n {\n name: SHARED_SETTINGS_FILE,\n content: `${JSON.stringify({ [ENV_BLOCK]: launchEnv(desired) }, null, JSON_INDENT)}\\n`,\n placeholder: SETTINGS_PLACEHOLDER,\n },\n ],\n }),\n launchNotes: [\n 'Running /model saves that model to your Claude Code settings.',\n 'This session is kept in your history like any other.',\n ],\n readKey: (ctx) => readGatewayToken(ctx),\n readSecrets: (ctx) => readCredentials(ctx),\n warnings: (ctx) => warnAboutApiKey(ctx),\n postSetupNotes: [\n 'Restart Claude Code after setup: it reads its settings only when it starts.',\n \"Claude Code ranks its settings, highest first: managed settings, --settings, the project's \" +\n \"settings.local.json, the project's settings.json, then the user's settings.json. A higher one that sets \" +\n 'the same values overrides this file.',\n ],\n}\n\nconst CONFIG_DIRECTORY = '.claude'\nconst SHARED_SETTINGS_FILE = 'settings.json'\nconst LOCAL_SETTINGS_FILE = 'settings.local.json'\nconst SETTINGS_PLACEHOLDER = '{settings}'\nconst JSON_INDENT = 2\n\nfunction resolveSettingsPath(ctx: PlatformContext): string {\n return match(ctx.scope)\n .with('user', () => path.join(ctx.home, CONFIG_DIRECTORY, SHARED_SETTINGS_FILE))\n .with('project', () => path.join(ctx.cwd, CONFIG_DIRECTORY, LOCAL_SETTINGS_FILE))\n .exhaustive()\n}\n\nfunction listSettingsCandidates(ctx: PlatformContext): string[] {\n return match(ctx.scope)\n .with('user', () => [resolveSettingsPath(ctx)])\n .with('project', () => [resolveSettingsPath(ctx), path.join(ctx.cwd, CONFIG_DIRECTORY, SHARED_SETTINGS_FILE)])\n .exhaustive()\n}\n\nconst ENV_BLOCK = 'env'\nconst BASE_URL_VARIABLE = 'ANTHROPIC_BASE_URL'\nconst AUTH_TOKEN_VARIABLE = 'ANTHROPIC_AUTH_TOKEN'\nconst MODEL_VARIABLE = 'ANTHROPIC_MODEL'\nconst API_KEY_VARIABLE = 'ANTHROPIC_API_KEY'\nconst MODEL_SETTING = 'model'\n\n// Claude Code picks these by itself, for subagents, skills and background calls, so each names the chosen model too.\nconst MODEL_ALIAS_VARIABLES = [\n 'ANTHROPIC_DEFAULT_OPUS_MODEL',\n 'ANTHROPIC_DEFAULT_SONNET_MODEL',\n 'ANTHROPIC_DEFAULT_HAIKU_MODEL',\n 'ANTHROPIC_DEFAULT_FABLE_MODEL',\n 'CLAUDE_CODE_SUBAGENT_MODEL',\n]\n// Turns off the telemetry, error reports and auto-updates that go to Anthropic rather than the gateway, and labels\n// each request (main turn, subagent, compaction) for the router.\nconst RECOMMENDED_ENV: Readonly<Record<string, string>> = {\n CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',\n DISABLE_TELEMETRY: '1',\n DISABLE_ERROR_REPORTING: '1',\n CLAUDE_CODE_GATEWAY_HINT_HEADERS: '1',\n}\n\nfunction gatewayEnv(desired: DesiredConfig): Record<string, string> {\n const model = toClaudeCodeModel(desired.model)\n return {\n [BASE_URL_VARIABLE]: desired.anthropicBaseUrl,\n [AUTH_TOKEN_VARIABLE]: desired.apiKey,\n ...Object.fromEntries(MODEL_ALIAS_VARIABLES.map((name) => [name, model])),\n ...RECOMMENDED_ENV,\n }\n}\n\n// ANTHROPIC_MODEL outranks every model setting, so this run starts on the model chosen for it.\nfunction launchEnv(desired: DesiredConfig): Record<string, string> {\n return { ...gatewayEnv(desired), [MODEL_VARIABLE]: toClaudeCodeModel(desired.model) }\n}\n\n// Without the suffix Claude Code assumes a 200k window for a model it does not know, and compacts there.\nfunction toClaudeCodeModel(model: string): string {\n return model === DEFAULT_MODEL ? ONE_MILLION_CONTEXT_ROUTER : model\n}\n\nfunction planSettings(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n const envUpdates = Object.entries(gatewayEnv(desired)).map(([name, value]): KeyPathUpdate => [\n [ENV_BLOCK, name],\n value,\n ])\n return {\n kind: 'file',\n path: resolveSettingsPath(ctx),\n hasSecret: true,\n edits: () => ({\n format: 'jsonc',\n updates: [\n // /model saves to the model setting, which ANTHROPIC_MODEL would override at every start.\n [[ENV_BLOCK, MODEL_VARIABLE], undefined],\n ...envUpdates,\n [[MODEL_SETTING], toClaudeCodeModel(desired.model)],\n ],\n }),\n }\n}\n\nfunction readGatewayToken(ctx: PlatformContext): string | undefined {\n const env = readSettingsEnv(ctx)\n if (!isGatewayUrl(env?.[BASE_URL_VARIABLE])) return undefined\n\n return env?.[AUTH_TOKEN_VARIABLE]\n}\n\nfunction readCredentials(ctx: PlatformContext): string[] {\n const env = readSettingsEnv(ctx)\n return [env?.[AUTH_TOKEN_VARIABLE], env?.[API_KEY_VARIABLE]].flatMap((value) => readNonBlank(value) ?? [])\n}\n\nfunction warnAboutApiKey(ctx: PlatformContext): string[] {\n if ((readSettingsEnv(ctx)?.[API_KEY_VARIABLE] ?? '') === '') return []\n\n const settingsPath = displayPath(resolveSettingsPath(ctx), ctx.home)\n return [\n `${settingsPath} also sets ${ENV_BLOCK}.${API_KEY_VARIABLE}, which can conflict with ${AUTH_TOKEN_VARIABLE}. ` +\n 'Consider removing it.',\n ]\n}\n\nconst OptionalTextSchema = v.fallback(v.optional(v.string()), undefined)\n\nconst SettingsSchema = v.looseObject({\n [ENV_BLOCK]: v.fallback(\n v.optional(\n v.looseObject({\n [BASE_URL_VARIABLE]: OptionalTextSchema,\n [AUTH_TOKEN_VARIABLE]: OptionalTextSchema,\n [API_KEY_VARIABLE]: OptionalTextSchema,\n }),\n ),\n undefined,\n ),\n})\n\ntype SettingsEnv = NonNullable<v.InferOutput<typeof SettingsSchema>[typeof ENV_BLOCK]>\n\nfunction readSettingsEnv(ctx: PlatformContext): SettingsEnv | undefined {\n const settings = readJsoncFile(resolveSettingsPath(ctx), SettingsSchema)\n return settings.kind === 'valid' ? settings.value[ENV_BLOCK] : undefined\n}\n\nconst GATEWAY_HOSTNAME = new URL(GATEWAY_HOST).hostname\n\nfunction isGatewayUrl(url: string | undefined): boolean {\n return url !== undefined && URL.canParse(url) && new URL(url).hostname === GATEWAY_HOSTNAME\n}\n","import path from 'node:path'\n\nconst HOME_SHORTHAND = '~'\n\nexport function displayPath(filePath: string, home: string): string {\n if (home === '' || !filePath.startsWith(home + path.sep)) return filePath\n\n return HOME_SHORTHAND + filePath.slice(home.length)\n}\n\nconst CURRENT_DIRECTORY = '.'\n\nexport function displayRelativePath(filePath: string, directory: string): string {\n return CURRENT_DIRECTORY + path.sep + path.relative(directory, filePath)\n}\n","import { isFile } from './is-file'\n\nexport function findFirstExistingFile(candidates: readonly string[]): string | null {\n return candidates.find((candidate) => isFile(candidate)) ?? null\n}\n","import { findFirstExistingFile } from '../shared/file-system/find-first-existing-file'\nimport { displayPath } from '../shared/text/display-path'\nimport type { DetectResult } from './harness'\n\nexport function detectConfigFile(candidates: readonly string[], home: string): DetectResult {\n const existing = findFirstExistingFile(candidates)\n if (existing === null) {\n const missing = candidates.map((candidate) => displayPath(candidate, home))\n return { isFound: false, detail: `no ${missing.join(' or ')}` }\n }\n\n return { isFound: true, detail: displayPath(existing, home) }\n}\n","import * as v from 'valibot'\nimport { ConfigFormatError } from '../shared/file-formats/config-errors'\nimport { parseJsonc } from '../shared/file-formats/jsonc'\nimport { readFileIfExists } from '../shared/file-system/read-file-if-exists'\n\nexport type JsoncConfig<T> = { kind: 'absent' } | { kind: 'invalid' } | { kind: 'valid'; value: T }\n\nexport function readJsoncFile<TSchema extends v.GenericSchema>(\n filePath: string,\n schema: TSchema,\n): JsoncConfig<v.InferOutput<TSchema>> {\n return parseJsoncConfig(readFileIfExists(filePath), schema)\n}\n\nexport function parseJsoncConfig<TSchema extends v.GenericSchema>(\n text: string | null,\n schema: TSchema,\n): JsoncConfig<v.InferOutput<TSchema>> {\n if (text === null) return { kind: 'absent' }\n\n try {\n const parsed = v.safeParse(schema, parseJsonc(text))\n return parsed.success ? { kind: 'valid', value: parsed.output } : { kind: 'invalid' }\n } catch (error) {\n if (error instanceof ConfigFormatError) return { kind: 'invalid' }\n throw error\n }\n}\n","export abstract class ConfigFormatError extends Error {}\n\nexport type ConfigSyntaxErrorParams = { line: number; column: number; reason: string }\n\nexport class ConfigSyntaxError extends ConfigFormatError {\n readonly line: number\n readonly column: number\n readonly reason: string\n\n constructor({ line, column, reason }: ConfigSyntaxErrorParams) {\n super(`invalid syntax at line ${line}, column ${column} (${reason}). Fix it, then run again.`)\n this.name = 'ConfigSyntaxError'\n this.line = line\n this.column = column\n this.reason = reason\n }\n}\n\nconst FOUND_TYPE_LABELS = {\n null: 'null',\n array: 'an array',\n date: 'a date',\n string: 'a string',\n number: 'a number',\n boolean: 'a boolean',\n other: 'an unsupported value',\n} as const\n\nexport type FoundType = keyof typeof FOUND_TYPE_LABELS\n\nexport type UnmergeableValueErrorParams = { keyPath: readonly string[]; foundType: FoundType }\n\nexport class UnmergeableValueError extends ConfigFormatError {\n readonly keyPath: readonly string[]\n readonly foundType: FoundType\n\n constructor({ keyPath, foundType }: UnmergeableValueErrorParams) {\n const location = describeLocation(keyPath)\n super(\n `cannot merge into ${location}: it is ${FOUND_TYPE_LABELS[foundType]}, not an object. ` +\n 'Make it an object or remove it, then run again.',\n )\n this.name = 'UnmergeableValueError'\n this.keyPath = keyPath\n this.foundType = foundType\n }\n}\n\nexport type ReservedKeyErrorParams = { keyPath: readonly string[]; key: string }\n\nexport class ReservedKeyError extends ConfigFormatError {\n readonly keyPath: readonly string[]\n readonly key: string\n\n constructor({ keyPath, key }: ReservedKeyErrorParams) {\n super(`cannot write ${describeLocation(keyPath)}: \"${key}\" is a reserved name. Use another name, then run again.`)\n this.name = 'ReservedKeyError'\n this.keyPath = keyPath\n this.key = key\n }\n}\n\nexport type DuplicateKeyErrorParams = { keyPath: readonly string[] }\n\nexport class DuplicateKeyError extends ConfigFormatError {\n readonly keyPath: readonly string[]\n\n constructor({ keyPath }: DuplicateKeyErrorParams) {\n super(\n `cannot edit ${describeLocation(keyPath)}: it appears more than once in the same object. ` +\n 'Keep one, then run again.',\n )\n this.name = 'DuplicateKeyError'\n this.keyPath = keyPath\n }\n}\n\nexport class MergeConflictError extends ConfigFormatError {\n constructor() {\n super('cannot set the values without changing other settings in it. Set them by hand, then run again.')\n this.name = 'MergeConflictError'\n }\n}\n\nfunction describeLocation(keyPath: readonly string[]): string {\n if (keyPath.length === 0) return 'the top level'\n return `\"${keyPath.join('.')}\"`\n}\n","import {\n applyEdits,\n findNodeAtLocation,\n modify,\n parse,\n parseTree,\n printParseErrorCode,\n type FormattingOptions,\n type Node,\n type ParseError,\n type ParseErrorCode,\n type ParseOptions,\n} from 'jsonc-parser'\nimport { ConfigSyntaxError, DuplicateKeyError } from './config-errors'\nimport { detectLineEnding, type LineEnding } from './detect-line-ending'\nimport { listCreatedParents, listMissingParents, type KeyOriginal } from './key-original'\nimport {\n assertMergeable,\n assertTopLevelTable,\n readPath,\n type KeyPath,\n type KeyPathUpdates,\n type Table,\n} from './key-path'\nimport { splitByteOrderMark } from './split-byte-order-mark'\n\nconst PARSE_OPTIONS: ParseOptions = { allowTrailingComma: true, disallowComments: false }\n\nexport function parseJsonc(text: string | null): Table {\n const { body } = splitByteOrderMark(text ?? '')\n if (body.trim() === '') return {}\n\n const value = parseJsoncValue(body)\n assertTopLevelTable(value)\n return value\n}\n\nexport function parseJsoncValue(source: string): unknown {\n const errors: ParseError[] = []\n const value: unknown = parse(source, errors, PARSE_OPTIONS)\n const [firstError] = errors\n if (firstError !== undefined) {\n const position = locateOffset(source, firstError.offset)\n throw new ConfigSyntaxError({ ...position, reason: describeErrorCode(firstError.error) })\n }\n return value\n}\n\nconst EMPTY_DOCUMENT = '{}'\n\nexport function renderJsonc(current: string | null, updates: KeyPathUpdates): string {\n const { byteOrderMark, body } = splitByteOrderMark(current ?? '')\n const existing = parseJsonc(body)\n const tree = parseTree(body, [], PARSE_OPTIONS)\n for (const [keyPath] of updates) {\n assertNoDuplicateKey(tree, keyPath)\n assertMergeable(existing, keyPath)\n }\n\n const formattingOptions = detectFormatting(body)\n const edited = updates\n .filter(([keyPath, value]) => value !== undefined || readPath(existing, keyPath) !== undefined)\n .reduce(\n (text, [keyPath, value]) => setValue({ text, keyPath, value, formattingOptions }),\n body.trim() === '' ? EMPTY_DOCUMENT : body,\n )\n return byteOrderMark + endWithLineEnding(edited, formattingOptions.eol)\n}\n\nexport function readJsoncOriginals(current: string | null, keyPaths: readonly KeyPath[]): KeyOriginal[] {\n const { body } = splitByteOrderMark(current ?? '')\n const document = parseJsonc(body)\n return keyPaths.map((keyPath) => ({\n keyPath,\n original: readSource(body, keyPath),\n createdParents: listMissingParents(document, keyPath),\n }))\n}\n\nexport function restoreJsonc(current: string, originals: readonly KeyOriginal[]): string {\n const { byteOrderMark, body } = splitByteOrderMark(current)\n const document = parseJsonc(body)\n const tree = parseTree(body, [], PARSE_OPTIONS)\n for (const { keyPath, original } of originals) {\n assertNoDuplicateKey(tree, keyPath)\n if (original !== null) {\n assertMergeable(document, keyPath)\n // Parsed only to throw: a value that exists now is replaced by this text verbatim.\n parseJsoncValue(original)\n }\n }\n\n const formattingOptions = detectFormatting(body)\n const restored = originals.reduce((text, key) => restoreKey({ text, key, formattingOptions }), body)\n const pruned = listCreatedParents(originals).reduce(\n (text, keyPath) => removeEmptyObject({ text, keyPath, formattingOptions }),\n restored,\n )\n return byteOrderMark + pruned\n}\n\ntype TextPosition = { line: number; column: number }\n\nfunction locateOffset(text: string, offset: number): TextPosition {\n const before = text.slice(0, offset)\n const lineStart = before.lastIndexOf('\\n') + 1\n return { line: before.split('\\n').length, column: offset - lineStart + 1 }\n}\n\nconst WORD_BOUNDARY = /(?<=[a-z])(?=[A-Z])/g\n\nfunction describeErrorCode(code: ParseErrorCode): string {\n return printParseErrorCode(code).replace(WORD_BOUNDARY, ' ').toLowerCase()\n}\n\n// `modify` edits the first of two equal keys, while `JSON.parse`, and so the agent, reads the last.\nfunction assertNoDuplicateKey(root: Node | undefined, keyPath: KeyPath): void {\n let node = root\n for (const [index, key] of keyPath.entries()) {\n const values = listPropertyValues(node, key)\n if (values.length > 1) throw new DuplicateKeyError({ keyPath: keyPath.slice(0, index + 1) })\n node = values[0]\n }\n}\n\nfunction listPropertyValues(node: Node | undefined, key: string): Node[] {\n if (node?.type !== 'object') return []\n\n return (node.children ?? []).flatMap((property) => {\n const [keyNode, valueNode] = property.children ?? []\n return keyNode?.value === key && valueNode !== undefined ? [valueNode] : []\n })\n}\n\nconst DEFAULT_INDENT = ' '\nconst DEFAULT_LINE_ENDING: LineEnding = '\\n'\nconst FIRST_INDENTED_KEY = /^([ \\t]+)\"/m\n\ntype DetectedFormatting = FormattingOptions & { eol: LineEnding }\n\nfunction detectFormatting(text: string): DetectedFormatting {\n const indent = FIRST_INDENTED_KEY.exec(text)?.[1] ?? DEFAULT_INDENT\n const isSpaceIndented = !indent.startsWith('\\t')\n return {\n insertSpaces: isSpaceIndented,\n tabSize: isSpaceIndented ? indent.length : 1,\n eol: detectLineEnding(text) ?? DEFAULT_LINE_ENDING,\n }\n}\n\nfunction endWithLineEnding(text: string, lineEnding: LineEnding): string {\n return text.endsWith('\\n') ? text : text + lineEnding\n}\n\nfunction findNode(text: string, keyPath: KeyPath): Node | undefined {\n const root = parseTree(text, [], PARSE_OPTIONS)\n return root === undefined ? undefined : findNodeAtLocation(root, [...keyPath])\n}\n\nfunction readSource(text: string, keyPath: KeyPath): string | null {\n const node = findNode(text, keyPath)\n return node === undefined ? null : text.slice(node.offset, node.offset + node.length)\n}\n\ntype RestoreKeyParams = { text: string; key: KeyOriginal; formattingOptions: FormattingOptions }\n\nfunction restoreKey({ text, key, formattingOptions }: RestoreKeyParams): string {\n const node = findNode(text, key.keyPath)\n if (node === undefined && key.original === null) return text\n if (key.original === null) return setValue({ text, keyPath: key.keyPath, value: undefined, formattingOptions })\n if (node === undefined) {\n const value = parseJsoncValue(key.original)\n return setValue({ text, keyPath: key.keyPath, value, formattingOptions })\n }\n\n return text.slice(0, node.offset) + key.original + text.slice(node.offset + node.length)\n}\n\ntype RemoveEmptyObjectParams = { text: string; keyPath: KeyPath; formattingOptions: FormattingOptions }\n\nfunction removeEmptyObject({ text, keyPath, formattingOptions }: RemoveEmptyObjectParams): string {\n const node = findNode(text, keyPath)\n if (node?.type !== 'object' || (node.children ?? []).length > 0) return text\n\n return setValue({ text, keyPath, value: undefined, formattingOptions })\n}\n\ntype SetValueParams = { text: string; keyPath: KeyPath; value: unknown; formattingOptions: FormattingOptions }\n\nfunction setValue({ text, keyPath, value, formattingOptions }: SetValueParams): string {\n return applyEdits(text, modify(text, [...keyPath], value, { formattingOptions }))\n}\n","export type LineEnding = '\\n' | '\\r\\n'\n\nexport function detectLineEnding(text: string): LineEnding | undefined {\n if (text.includes('\\r\\n')) return '\\r\\n'\n if (text.includes('\\n')) return '\\n'\n return undefined\n}\n","import { match, P } from 'ts-pattern'\nimport * as v from 'valibot'\nimport { ReservedKeyError, UnmergeableValueError, type FoundType } from './config-errors'\n\nexport type KeyPath = readonly [string, ...string[]]\n/** A value of undefined removes the key, so a key that would override ours cannot linger. */\nexport type KeyPathUpdate = readonly [KeyPath, unknown]\nexport type KeyPathUpdates = readonly [KeyPathUpdate, ...KeyPathUpdate[]]\n\nconst TableSchema = v.pipe(\n v.unknown(),\n v.check((value) => !Array.isArray(value) && !(value instanceof Date)),\n v.record(v.string(), v.unknown()),\n)\n\nexport type Table = v.InferOutput<typeof TableSchema>\n\nexport function assertTopLevelTable(value: unknown): asserts value is Table {\n if (!isTable(value)) throw new UnmergeableValueError({ keyPath: [], foundType: describeFoundType(value) })\n}\n\nexport function assertMergeable(document: Table, keyPath: KeyPath): void {\n assertNoReservedKey(keyPath)\n\n const { parents } = splitLeaf(keyPath)\n let table = document\n for (const [index, key] of parents.entries()) {\n if (!Object.hasOwn(table, key)) return\n\n const value = table[key]\n if (!isTable(value)) {\n const keyPathToValue = parents.slice(0, index + 1)\n throw new UnmergeableValueError({ keyPath: keyPathToValue, foundType: describeFoundType(value) })\n }\n table = value\n }\n}\n\nexport function setPath(document: Table, keyPath: KeyPath, value: unknown): void {\n assertMergeable(document, keyPath)\n\n const { parents, leaf } = splitLeaf(keyPath)\n let table = document\n for (const key of parents) table = getOrCreateChildTable(table, key)\n table[leaf] = value\n}\n\nexport function readPath(document: Table, keyPath: KeyPath): unknown {\n let value: unknown = document\n for (const key of keyPath) {\n if (!isTable(value) || !Object.hasOwn(value, key)) return undefined\n value = value[key]\n }\n return value\n}\n\nexport function deletePath(document: Table, keyPath: KeyPath): void {\n const [first, ...rest] = keyPath\n const leaf = rest.pop()\n if (leaf === undefined) {\n delete document[first]\n return\n }\n\n const parent = readPath(document, [first, ...rest])\n if (isTable(parent)) delete parent[leaf]\n}\n\nexport function isEmptyTable(value: unknown): boolean {\n return isTable(value) && Object.keys(value).length === 0\n}\n\nconst RESERVED_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction assertNoReservedKey(keyPath: KeyPath): void {\n const reserved = keyPath.find((key) => RESERVED_KEYS.has(key))\n if (reserved !== undefined) throw new ReservedKeyError({ keyPath, key: reserved })\n}\n\nexport type SplitLeafResult = { parents: readonly string[]; leaf: string }\n\nexport function splitLeaf(keyPath: KeyPath): SplitLeafResult {\n const [first, ...rest] = keyPath\n const leaf = rest.pop()\n if (leaf === undefined) return { parents: [], leaf: first }\n return { parents: [first, ...rest], leaf }\n}\n\nfunction isTable(value: unknown): value is Table {\n return v.is(TableSchema, value)\n}\n\nfunction describeFoundType(value: unknown): FoundType {\n return match(value)\n .returnType<FoundType>()\n .with(null, () => 'null')\n .with(P.array(), () => 'array')\n .with(P.instanceOf(Date), () => 'date')\n .with(P.string, () => 'string')\n .with(P.union(P.number, P.bigint), () => 'number')\n .with(P.boolean, () => 'boolean')\n .otherwise(() => 'other')\n}\n\nfunction getOrCreateChildTable(table: Table, key: string): Table {\n const existing = Object.hasOwn(table, key) ? table[key] : undefined\n if (isTable(existing)) return existing\n\n const created: Table = {}\n table[key] = created\n return created\n}\n","import { readPath, type KeyPath, type Table } from './key-path'\n\n/** `original` is the value's source text as the file had it, or `null` when the key was absent. */\nexport type KeyOriginal = { keyPath: KeyPath; original: string | null; createdParents: readonly KeyPath[] }\n\nexport function listMissingParents(document: Table, keyPath: KeyPath): KeyPath[] {\n const parentPaths = listParentPaths(keyPath)\n const firstMissing = parentPaths.findIndex((parentPath) => readPath(document, parentPath) === undefined)\n return firstMissing === -1 ? [] : parentPaths.slice(firstMissing)\n}\n\nfunction listParentPaths([first, ...rest]: KeyPath): KeyPath[] {\n return rest.map((_, index) => [first, ...rest.slice(0, index)])\n}\n\nexport function listCreatedParents(originals: readonly KeyOriginal[]): KeyPath[] {\n const byPath = new Map<string, KeyPath>()\n for (const keyPath of originals.flatMap(({ createdParents }) => createdParents)) {\n byPath.set(JSON.stringify(keyPath), keyPath)\n }\n return [...byPath.values()].sort((first, second) => second.length - first.length)\n}\n","const BYTE_ORDER_MARK = ''\n\nexport type SplitByteOrderMarkResult = { byteOrderMark: string; body: string }\n\nexport function splitByteOrderMark(text: string): SplitByteOrderMarkResult {\n if (!text.startsWith(BYTE_ORDER_MARK)) return { byteOrderMark: '', body: text }\n return { byteOrderMark: BYTE_ORDER_MARK, body: text.slice(BYTE_ORDER_MARK.length) }\n}\n","import fs from 'node:fs'\nimport { isMissingFileError } from './is-missing-file-error'\nimport { Utf16FileError } from './utf16-file-error'\n\nexport function readFileIfExists(filePath: string): string | null {\n const bytes = readBytesIfExists(filePath)\n if (bytes === null) return null\n if (hasUtf16ByteOrderMark(bytes)) throw new Utf16FileError(filePath)\n\n return bytes.toString('utf8')\n}\n\nfunction readBytesIfExists(filePath: string): Buffer | null {\n try {\n return fs.readFileSync(filePath)\n } catch (error) {\n if (isMissingFileError(error)) return null\n throw error\n }\n}\n\nconst BYTE_ORDER_MARK = '\\uFEFF'\nconst UTF16_BYTE_ORDER_MARKS = [\n Buffer.from(BYTE_ORDER_MARK, 'utf16le'),\n Buffer.from(BYTE_ORDER_MARK, 'utf16le').swap16(),\n]\n\nfunction hasUtf16ByteOrderMark(bytes: Buffer): boolean {\n return UTF16_BYTE_ORDER_MARKS.some((byteOrderMark) => bytes.subarray(0, byteOrderMark.length).equals(byteOrderMark))\n}\n","export class Utf16FileError extends Error {\n readonly filePath: string\n\n constructor(filePath: string) {\n super(`${filePath} is saved as UTF-16. Re-save it as UTF-8, then run again.`)\n this.name = 'Utf16FileError'\n this.filePath = filePath\n }\n}\n","import path from 'node:path'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { DEFAULT_MODEL } from '../../product/gateway/models/predefined-models'\nimport { readPath } from '../../shared/file-formats/key-path'\nimport { parseToml, type TomlUpdate } from '../../shared/file-formats/toml'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { FileContribution, LaunchingHarness } from '../harness'\n\nconst BINARY = 'codex'\nconst API_KEY_VARIABLE = 'NEXOS_API_KEY'\n// Codex's default, written out to replace a \"chat\" left from an older config: Codex now refuses to start on it.\nconst WIRE_API = 'responses'\n\nexport const codex: LaunchingHarness = {\n kind: 'configurable',\n id: 'codex',\n label: 'OpenAI Codex',\n binary: BINARY,\n protocols: ['openai-responses'],\n projectSupport: { kind: 'unsupported', reason: 'a repo-level config.toml cannot set the provider or its base_url' },\n keyEnvVariable: API_KEY_VARIABLE,\n detect: (ctx) => detectConfigFile([resolveConfigPath(ctx)], ctx.home),\n configPath: (ctx) => resolveConfigPath(ctx),\n plan: (desired, ctx) => [\n planConfig(desired, ctx),\n { kind: 'env', variables: { [API_KEY_VARIABLE]: desired.apiKey } },\n ],\n launch: (desired) => {\n const overrides = [\n `model=${JSON.stringify(desired.model)}`,\n `model_provider=${JSON.stringify(RUN_PROVIDER_ID)}`,\n ...Object.entries(providerFields(desired)).map(\n ([field, value]) => `model_providers.${RUN_PROVIDER_ID}.${field}=${JSON.stringify(value)}`,\n ),\n ...[...PRIVACY_UPDATES, ...listRouterUpdates(desired)].map(\n ([keyPath, value]) => `${keyPath.join('.')}=${JSON.stringify(value)}`,\n ),\n ]\n return {\n binary: BINARY,\n arguments: overrides.flatMap((override) => ['-c', override]),\n env: { [API_KEY_VARIABLE]: desired.apiKey },\n subcommands: SESSION_SUBCOMMANDS,\n }\n },\n launchNotes: [\n 'Running /model saves that model to ~/.codex/config.toml.',\n 'A later plain `codex resume` of this session points at a \"nexos-run\" provider that no longer exists.',\n ],\n postSetupNotes: [\n `OpenAI Codex requires wire_api = \"${WIRE_API}\": if the gateway does not serve /v1/responses, ` +\n 'Codex fails even though its config is correct.',\n ],\n}\n\nconst CONFIG_DIRECTORY = '.codex'\nconst CONFIG_FILE = 'config.toml'\n\nfunction resolveConfigPath(ctx: PlatformContext): string {\n return path.join(ctx.home, CONFIG_DIRECTORY, CONFIG_FILE)\n}\n\nconst PROVIDER_ID = 'nexos'\nconst RUN_PROVIDER_ID = 'nexos-run'\n// Display only, but never \"OpenAI\": Codex treats a provider of that name as OpenAI itself.\nconst PROVIDER_NAME = 'nexos.ai'\n\n// Codex drops every root-level -c once the subcommand is given one of its own, the gateway's included.\nconst SESSION_SUBCOMMANDS = ['exec', 'e', 'review', 'resume', 'fork']\n\nfunction providerFields(desired: DesiredConfig): Record<string, string> {\n return { name: PROVIDER_NAME, base_url: desired.openaiBaseUrl, env_key: API_KEY_VARIABLE, wire_api: WIRE_API }\n}\n\n// Codex sends usage metrics to OpenAI whatever the provider, and /feedback uploads its logs there.\nconst PRIVACY_UPDATES: readonly TomlUpdate[] = [\n [['analytics', 'enabled'], false],\n [['feedback', 'enabled'], false],\n]\n\nconst WEB_SEARCH_KEY_PATH = ['web_search'] as const\nconst WEB_SEARCH_DISABLED = 'disabled'\n\n// OpenAI's hosted web search goes out with every turn, and the router may hand a turn to a backend without it.\nfunction listRouterUpdates(desired: DesiredConfig): TomlUpdate[] {\n return desired.model === DEFAULT_MODEL ? [[WEB_SEARCH_KEY_PATH, WEB_SEARCH_DISABLED]] : []\n}\n\nfunction planConfig(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n const updates: TomlUpdate[] = [\n [['model'], desired.model],\n [['model_provider'], PROVIDER_ID],\n ...Object.entries(providerFields(desired)).map(([field, value]): TomlUpdate => [\n ['model_providers', PROVIDER_ID, field],\n value,\n ]),\n ...PRIVACY_UPDATES,\n ...listRouterUpdates(desired),\n ]\n return {\n kind: 'file',\n path: resolveConfigPath(ctx),\n hasSecret: false,\n edits: (current) => ({\n format: 'toml',\n updates: [...updates, ...listLeftoverRemovals({ desired, current })],\n }),\n }\n}\n\ntype LeftoverRemovalsParams = { desired: DesiredConfig; current: string | null }\n\n// Lifts only the \"disabled\" set up for the router: any other web_search is the user's own choice.\nfunction listLeftoverRemovals({ desired, current }: LeftoverRemovalsParams): TomlUpdate[] {\n if (desired.model === DEFAULT_MODEL) return []\n\n const isRouterLeftover = readPath(parseToml(current ?? ''), WEB_SEARCH_KEY_PATH) === WEB_SEARCH_DISABLED\n return isRouterLeftover ? [[WEB_SEARCH_KEY_PATH, undefined]] : []\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport { getStaticTOMLValue, ParseError, parseTOML, traverseNodes, type AST } from 'toml-eslint-parser'\nimport { match } from 'ts-pattern'\nimport { ConfigSyntaxError, MergeConflictError, ReservedKeyError } from './config-errors'\nimport { detectLineEnding, type LineEnding } from './detect-line-ending'\nimport { listCreatedParents, listMissingParents, type KeyOriginal } from './key-original'\nimport { deletePath, isEmptyTable, readPath, setPath, splitLeaf, type KeyPath, type Table } from './key-path'\nimport { splitByteOrderMark } from './split-byte-order-mark'\n\n/** A value of undefined removes the key, so a key that would override ours cannot linger. */\nexport type TomlUpdate = readonly [KeyPath, string | boolean | undefined]\n\nexport function parseToml(text: string): Table {\n return readTable(parseProgram(splitByteOrderMark(text).body))\n}\n\nexport function renderToml(current: string | null, updates: readonly TomlUpdate[]): string {\n const { byteOrderMark, body } = splitByteOrderMark(current ?? '')\n const expected = readTable(parseProgram(body))\n for (const [keyPath, value] of updates) {\n if (value === undefined) deletePath(expected, keyPath)\n else setPath(expected, keyPath, value)\n }\n\n const lineEnding = detectLineEnding(body) ?? DEFAULT_LINE_ENDING\n const edited = updates.reduce((text, update) => spliceUpdate({ text, lineEnding }, update), body)\n if (!isDeepStrictEqual(readTable(parseOwnEdit(edited)), expected)) {\n throw new MergeConflictError()\n }\n return byteOrderMark + edited\n}\n\nexport function readTomlOriginals(current: string | null, keyPaths: readonly KeyPath[]): KeyOriginal[] {\n const { body } = splitByteOrderMark(current ?? '')\n const program = parseProgram(body)\n const document = readTable(program)\n const entries = listKeyValues(program)\n return keyPaths.map((keyPath) => ({\n keyPath,\n original: readSource(body, entries, keyPath),\n createdParents: listMissingParents(document, keyPath),\n }))\n}\n\nexport function restoreToml(current: string, originals: readonly KeyOriginal[]): string {\n const { byteOrderMark, body } = splitByteOrderMark(current)\n const createdParents = listCreatedParents(originals)\n const expected = readTable(parseProgram(body))\n for (const key of originals) applyOriginal(expected, key)\n for (const keyPath of createdParents) {\n if (isEmptyTable(readPath(expected, keyPath))) deletePath(expected, keyPath)\n }\n\n const lineEnding = detectLineEnding(body) ?? DEFAULT_LINE_ENDING\n const restored = originals.reduce((text, key) => restoreKey({ text, lineEnding }, key), body)\n const pruned = createdParents.reduce((text, keyPath) => removeEmptyTable({ text, lineEnding }, keyPath), restored)\n if (!isDeepStrictEqual(readTable(parseOwnEdit(pruned)), expected)) {\n throw new MergeConflictError()\n }\n return byteOrderMark + pruned\n}\n\nconst PARSER_OPTIONS = { tomlVersion: '1.1' } as const\n\nfunction parseProgram(text: string): AST.TOMLProgram {\n try {\n return parseTOML(text, PARSER_OPTIONS)\n } catch (error) {\n if (!(error instanceof ParseError)) throw error\n throw new ConfigSyntaxError({\n line: error.lineNumber,\n column: error.column + 1,\n reason: error.message,\n })\n }\n}\n\nfunction readTable(program: AST.TOMLProgram): Table {\n assertNoPrototypeKey(program)\n return getStaticTOMLValue(program)\n}\n\n// getStaticTOMLValue assigns keys plainly, so a `__proto__` key would write onto Object.prototype.\nconst PROTOTYPE_KEY = '__proto__'\n\nfunction assertNoPrototypeKey(program: AST.TOMLProgram): void {\n traverseNodes(program, {\n enterNode(node) {\n if (node.type !== 'TOMLKey') return\n\n const keys = node.keys.map(readKeyName)\n const index = keys.indexOf(PROTOTYPE_KEY)\n if (index !== -1) {\n throw new ReservedKeyError({\n keyPath: keys.slice(0, index + 1),\n key: PROTOTYPE_KEY,\n })\n }\n },\n leaveNode() {},\n })\n}\n\nfunction readKeyName(key: AST.TOMLBare | AST.TOMLQuoted): string {\n return key.type === 'TOMLBare' ? key.name : key.value\n}\n\nconst DEFAULT_LINE_ENDING: LineEnding = '\\n'\n\ntype TomlSource = { text: string; lineEnding: LineEnding }\n\nfunction spliceUpdate(source: TomlSource, [keyPath, value]: TomlUpdate): string {\n const program = parseOwnEdit(source.text)\n const entries = listKeyValues(program)\n const current = entries.find((entry) => isSamePath(entry.path, keyPath))\n if (value === undefined) return current === undefined ? source.text : removeKeyValue(source, program, current)\n if (current !== undefined) return replaceValue(source, current.keyValue.value, value)\n\n return insertKeyValue({ source, program, entries, keyPath, valueText: formatValue(value) })\n}\n\ntype InsertKeyValueParams = {\n source: TomlSource\n program: AST.TOMLProgram\n entries: readonly KeyValueEntry[]\n keyPath: KeyPath\n valueText: string\n}\n\nfunction insertKeyValue({ source, program, entries, keyPath, valueText }: InsertKeyValueParams): string {\n const { parents, leaf } = splitLeaf(keyPath)\n const keyValueText = formatKeyValue([leaf], valueText)\n\n return match(findPlacement(program, entries, parents))\n .with({ kind: 'top-level' }, () => insertTopLevel(source, program, keyValueText))\n .with({ kind: 'table' }, ({ table }) => insertLineAfter(source, table.range[1], keyValueText))\n .with({ kind: 'dotted' }, ({ entry }) => {\n const keys = [...parents.slice(entry.tablePath.length), leaf]\n return insertBesideDottedKey(source, entry, formatKeyValue(keys, valueText))\n })\n .with({ kind: 'inline' }, ({ inlineTable, keysInside }) =>\n insertIntoInlineTable(source, inlineTable, nestInInlineTables(keysInside, keyValueText)),\n )\n .with({ kind: 'new-table' }, () => appendTable(source, parents, keyValueText))\n .exhaustive()\n}\n\nfunction parseOwnEdit(text: string): AST.TOMLProgram {\n try {\n return parseProgram(text)\n } catch (error) {\n if (error instanceof ConfigSyntaxError) throw new MergeConflictError()\n throw error\n }\n}\n\ntype TomlPath = readonly (string | number)[]\n\ntype KeyValueEntry = {\n path: TomlPath\n keyValue: AST.TOMLKeyValue\n tablePath: TomlPath\n}\n\nfunction listKeyValues(program: AST.TOMLProgram): KeyValueEntry[] {\n return program.body[0].body.flatMap((node) => {\n if (node.type === 'TOMLTable') {\n return listInBody(node.body, node.resolvedKey)\n }\n return listInBody([node], [])\n })\n}\n\nfunction listInBody(keyValues: readonly AST.TOMLKeyValue[], tablePath: TomlPath): KeyValueEntry[] {\n return keyValues.flatMap((keyValue) => {\n const path = [...tablePath, ...keyValue.key.keys.map(readKeyName)]\n const entry = { path, keyValue, tablePath }\n if (keyValue.value.type !== 'TOMLInlineTable') return [entry]\n return [entry, ...listInBody(keyValue.value.body, path)]\n })\n}\n\nfunction isSamePath(path: TomlPath, other: TomlPath): boolean {\n return path.length === other.length && path.every((key, index) => key === other[index])\n}\n\nfunction replaceValue(source: TomlSource, node: AST.TOMLContentNode, value: string | boolean): string {\n if (node.type === 'TOMLValue' && node.value === value) return source.text\n return replaceRange(source, node.range, formatValue(value))\n}\n\ntype Placement =\n | { kind: 'top-level' }\n | { kind: 'table'; table: AST.TOMLTable }\n | { kind: 'dotted'; entry: KeyValueEntry }\n | {\n kind: 'inline'\n inlineTable: AST.TOMLInlineTable\n keysInside: readonly string[]\n }\n | { kind: 'new-table' }\n\nfunction findPlacement(\n program: AST.TOMLProgram,\n entries: readonly KeyValueEntry[],\n tablePath: readonly string[],\n): Placement {\n if (tablePath.length === 0) return { kind: 'top-level' }\n\n const table = findStandardTable(program, tablePath)\n if (table !== undefined) return { kind: 'table', table }\n\n const dotted = entries.findLast((entry) => isDottedKeyUnder(entry, tablePath))\n if (dotted !== undefined) return { kind: 'dotted', entry: dotted }\n\n for (let length = tablePath.length; length > 0; length--) {\n const prefix = tablePath.slice(0, length)\n const value = entries.find((entry) => isSamePath(entry.path, prefix))?.keyValue.value\n if (value?.type === 'TOMLInlineTable') {\n return {\n kind: 'inline',\n inlineTable: value,\n keysInside: tablePath.slice(length),\n }\n }\n }\n\n return { kind: 'new-table' }\n}\n\nfunction findStandardTable(program: AST.TOMLProgram, tablePath: TomlPath): AST.TOMLTable | undefined {\n return program.body[0].body\n .filter((node) => node.type === 'TOMLTable')\n .find((candidate) => candidate.kind === 'standard' && isSamePath(candidate.resolvedKey, tablePath))\n}\n\nfunction isDottedKeyUnder(entry: KeyValueEntry, tablePath: readonly string[]): boolean {\n return (\n entry.tablePath.length < tablePath.length &&\n entry.path.length > tablePath.length &&\n isSamePath(entry.path.slice(0, tablePath.length), tablePath)\n )\n}\n\nfunction insertTopLevel(source: TomlSource, program: AST.TOMLProgram, keyValueText: string): string {\n const nodes = program.body[0].body\n const lastKeyValue = nodes.findLast((node) => node.type === 'TOMLKeyValue')\n if (lastKeyValue !== undefined) {\n return insertLineAfter(source, lastKeyValue.range[1], keyValueText)\n }\n\n const firstTable = nodes.find((node) => node.type === 'TOMLTable')\n if (firstTable === undefined) return appendLine(source, keyValueText)\n\n const lineStart = source.text.lastIndexOf('\\n', firstTable.range[0] - 1) + 1\n return replaceRange(source, [lineStart, lineStart], keyValueText + source.lineEnding + source.lineEnding)\n}\n\nfunction insertLineAfter(source: TomlSource, offset: number, line: string): string {\n const lineEnd = findLineEnd(source.text, offset)\n return replaceRange(source, [lineEnd, lineEnd], source.lineEnding + line)\n}\n\nfunction findLineEnd(text: string, offset: number): number {\n const newline = text.indexOf('\\n', offset)\n if (newline === -1) return text.length\n return text[newline - 1] === '\\r' ? newline - 1 : newline\n}\n\nfunction appendLine(source: TomlSource, line: string): string {\n const { text, lineEnding } = source\n const separator = text === '' || text.endsWith('\\n') ? '' : lineEnding\n return text + separator + line + lineEnding\n}\n\nfunction insertBesideDottedKey(source: TomlSource, entry: KeyValueEntry, keyValueText: string): string {\n const offset = entry.keyValue.range[1]\n if (entry.keyValue.parent.type !== 'TOMLInlineTable') {\n return insertLineAfter(source, offset, keyValueText)\n }\n return replaceRange(source, [offset, offset], `, ${keyValueText}`)\n}\n\nfunction insertIntoInlineTable(source: TomlSource, inlineTable: AST.TOMLInlineTable, keyValueText: string): string {\n const lastKeyValue = inlineTable.body.at(-1)\n if (lastKeyValue === undefined) {\n return replaceRange(source, inlineTable.range, `{ ${keyValueText} }`)\n }\n\n const offset = lastKeyValue.range[1]\n return replaceRange(source, [offset, offset], `, ${keyValueText}`)\n}\n\nfunction nestInInlineTables(tableKeys: readonly string[], keyValueText: string): string {\n return tableKeys.reduceRight((inner, key) => `${formatKey(key)} = { ${inner} }`, keyValueText)\n}\n\nfunction appendTable(source: TomlSource, tablePath: readonly string[], keyValueText: string): string {\n const { text, lineEnding } = source\n const header = `[${tablePath.map(formatKey).join('.')}]`\n return text + findSeparatorBeforeTable(source) + header + lineEnding + keyValueText + lineEnding\n}\n\nfunction findSeparatorBeforeTable({ text, lineEnding }: TomlSource): string {\n if (text.trim() === '') return ''\n if (text.endsWith('\\n')) return lineEnding\n return lineEnding + lineEnding\n}\n\nfunction replaceRange({ text }: TomlSource, [start, end]: AST.Range, replacement: string): string {\n return text.slice(0, start) + replacement + text.slice(end)\n}\n\nfunction formatKeyValue(keys: readonly string[], valueText: string): string {\n return `${keys.map(formatKey).join('.')} = ${valueText}`\n}\n\nconst BARE_KEY = /^[A-Za-z0-9_-]+$/\n\nfunction formatKey(key: string): string {\n return BARE_KEY.test(key) ? key : formatString(key)\n}\n\nfunction formatValue(value: string | boolean): string {\n return typeof value === 'boolean' ? String(value) : formatString(value)\n}\n\n// JSON's escapes are valid in a TOML basic string, but TOML also requires DEL (U+007F) escaped.\nconst DELETE_CHARACTER = /\\u007f/g\n\nfunction formatString(value: string): string {\n return JSON.stringify(value).replace(DELETE_CHARACTER, '\\\\u007f')\n}\n\nfunction readSource(text: string, entries: readonly KeyValueEntry[], keyPath: KeyPath): string | null {\n const entry = entries.find((candidate) => isSamePath(candidate.path, keyPath))\n if (entry === undefined) return null\n\n const [start, end] = entry.keyValue.value.range\n return text.slice(start, end)\n}\n\nfunction applyOriginal(expected: Table, { keyPath, original }: KeyOriginal): void {\n if (original === null) {\n deletePath(expected, keyPath)\n return\n }\n\n setPath(expected, keyPath, parseTomlValue(original))\n}\n\nconst VALUE_KEY = 'value'\n\nexport function parseTomlValue(source: string): unknown {\n return readTable(parseProgram(`${VALUE_KEY} = ${source}`))[VALUE_KEY]\n}\n\nfunction restoreKey(source: TomlSource, { keyPath, original }: KeyOriginal): string {\n const program = parseOwnEdit(source.text)\n const entries = listKeyValues(program)\n const current = entries.find((entry) => isSamePath(entry.path, keyPath))\n if (original === null) return current === undefined ? source.text : removeKeyValue(source, program, current)\n if (current !== undefined) return replaceRange(source, current.keyValue.value.range, original)\n\n return insertKeyValue({ source, program, entries, keyPath, valueText: original })\n}\n\nfunction removeEmptyTable(source: TomlSource, keyPath: KeyPath): string {\n const program = parseOwnEdit(source.text)\n if (!isEmptyTable(readPath(readTable(program), keyPath))) return source.text\n\n const entry = listKeyValues(program).find((candidate) => isSamePath(candidate.path, keyPath))\n if (entry !== undefined) return removeKeyValue(source, program, entry)\n\n const table = findStandardTable(program, keyPath)\n return table === undefined ? source.text : removeTableHeader(source, table)\n}\n\nfunction removeKeyValue(source: TomlSource, program: AST.TOMLProgram, { keyValue }: KeyValueEntry): string {\n if (keyValue.parent.type === 'TOMLInlineTable') return removeFromInlineTable(source, keyValue.parent, keyValue)\n\n const isLastTopLevel = keyValue.parent.type === 'TOMLTopLevelTable' && countTopLevelKeyValues(program) === 1\n const removed = removeLine(source, keyValue.range)\n if (!isLastTopLevel) return removed.text\n\n return removeLineBreakAt(removed.text, removed.offset)\n}\n\nconst EMPTY_INLINE_TABLE = '{}'\n\nfunction removeFromInlineTable(\n source: TomlSource,\n inlineTable: AST.TOMLInlineTable,\n keyValue: AST.TOMLKeyValue,\n): string {\n const index = inlineTable.body.indexOf(keyValue)\n const previous = inlineTable.body[index - 1]\n if (previous !== undefined) return replaceRange(source, [previous.range[1], keyValue.range[1]], '')\n\n const next = inlineTable.body[index + 1]\n if (next !== undefined) return replaceRange(source, [keyValue.range[0], next.range[0]], '')\n\n return replaceRange(source, inlineTable.range, EMPTY_INLINE_TABLE)\n}\n\nfunction countTopLevelKeyValues(program: AST.TOMLProgram): number {\n return program.body[0].body.filter((node) => node.type === 'TOMLKeyValue').length\n}\n\n// Also drops the blank line appendTable put before the section, so the sections around it keep one between them.\nfunction removeTableHeader(source: TomlSource, table: AST.TOMLTable): string {\n const { text, offset } = removeLine(source, [table.range[0], table.key.range[1]])\n const isFollowedByBlank = offset === text.length || measureLineBreakAt(text, offset) > 0\n if (!isFollowedByBlank) return text\n if (offset === 0) return removeLineBreakAt(text, offset)\n if (!isBlankLineBefore(text, offset)) return text\n\n return text.slice(0, offset - measureLineBreakBefore(text, offset)) + text.slice(offset)\n}\n\ntype RemovedLine = { text: string; offset: number }\n\nfunction removeLine({ text }: TomlSource, [start, end]: AST.Range): RemovedLine {\n const lineStart = text.lastIndexOf('\\n', start - 1) + 1\n const lineEnd = findLineEnd(text, end)\n const lineBreakLength = measureLineBreakAt(text, lineEnd)\n if (lineBreakLength > 0 || lineStart === 0) {\n return { text: text.slice(0, lineStart) + text.slice(lineEnd + lineBreakLength), offset: lineStart }\n }\n\n const offset = lineStart - measureLineBreakBefore(text, lineStart)\n return { text: text.slice(0, offset) + text.slice(lineEnd), offset }\n}\n\nfunction removeLineBreakAt(text: string, offset: number): string {\n return text.slice(0, offset) + text.slice(offset + measureLineBreakAt(text, offset))\n}\n\nconst CRLF = '\\r\\n'\nconst LF = '\\n'\n\nfunction measureLineBreakAt(text: string, offset: number): number {\n if (text.startsWith(CRLF, offset)) return CRLF.length\n if (text.startsWith(LF, offset)) return LF.length\n return 0\n}\n\nfunction measureLineBreakBefore(text: string, offset: number): number {\n if (text.slice(0, offset).endsWith(CRLF)) return CRLF.length\n if (text.slice(0, offset).endsWith(LF)) return LF.length\n return 0\n}\n\nfunction isBlankLineBefore(text: string, offset: number): boolean {\n const lineBreakLength = measureLineBreakBefore(text, offset)\n if (lineBreakLength === 0) return false\n\n const lineStart = offset - lineBreakLength\n return lineStart === 0 || text[lineStart - 1] === LF\n}\n","import type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { findContextWindow } from '../../product/gateway/models/predefined-models'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport type { DetectResult, LaunchingHarness } from '../harness'\n\nconst BINARY = 'copilot'\nconst TYPE_VARIABLE = 'COPILOT_PROVIDER_TYPE'\nconst BASE_URL_VARIABLE = 'COPILOT_PROVIDER_BASE_URL'\nconst API_KEY_VARIABLE = 'COPILOT_PROVIDER_API_KEY'\n// A custom provider has no default model: without one, Copilot CLI refuses to run.\nconst MODEL_VARIABLE = 'COPILOT_MODEL'\n// Copilot CLI assumes 128K for a model it does not know, and applies this to every model the provider serves.\nconst MAX_PROMPT_TOKENS_VARIABLE = 'COPILOT_PROVIDER_MAX_PROMPT_TOKENS'\n// The provider variables Copilot CLI reads that this run leaves unset: inherited from the shell, each would swap\n// the key, the endpoint or the request shape, and in offline mode the GHES pair replaces the provider outright.\nconst OTHER_PROVIDER_VARIABLES = [\n 'COPILOT_PROVIDER_API_KEY_COMMAND',\n 'COPILOT_PROVIDER_BEARER_TOKEN',\n 'COPILOT_PROVIDER_WIRE_API',\n 'COPILOT_PROVIDER_TRANSPORT',\n 'COPILOT_PROVIDER_AZURE_API_VERSION',\n 'COPILOT_PROVIDER_HEADERS',\n 'COPILOT_PROVIDER_MODEL_ID',\n 'COPILOT_PROVIDER_WIRE_MODEL',\n 'COPILOT_PROVIDER_MAX_OUTPUT_TOKENS',\n 'COPILOT_PROVIDER_GHES_HOST',\n 'COPILOT_PROVIDER_GHES_TOKEN',\n]\nconst PROVIDER_TYPE = 'openai'\n\nexport const copilotCli: LaunchingHarness = {\n kind: 'configurable',\n id: 'copilot-cli',\n label: 'GitHub Copilot CLI',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: {\n kind: 'unsupported',\n reason: 'it reads COPILOT_PROVIDER_* from the environment, which nothing project-local sets',\n },\n keyEnvVariable: API_KEY_VARIABLE,\n detect: (ctx) => detectBinary(ctx),\n plan: (desired) => [{ kind: 'env', variables: providerEnv(desired) }],\n launch: (desired) => ({\n binary: BINARY,\n arguments: [],\n env: { ...providerEnv(desired), ...Object.fromEntries(OTHER_PROVIDER_VARIABLES.map((name) => [name, undefined])) },\n }),\n launchNotes: ['This session is kept in your Copilot CLI history like any other.'],\n postSetupNotes: [\n 'GitHub Copilot CLI starts on the model chosen here; for another, start it with `copilot --model <id>` or run setup again.',\n 'Run `copilot help providers` to see which variables your version supports, in case these names have drifted.',\n ],\n}\n\nfunction providerEnv(desired: DesiredConfig): Record<string, string | undefined> {\n const contextTokens = findContextWindow(desired.model)\n return {\n [TYPE_VARIABLE]: PROVIDER_TYPE,\n [BASE_URL_VARIABLE]: desired.openaiBaseUrl,\n [API_KEY_VARIABLE]: desired.apiKey,\n [MODEL_VARIABLE]: desired.model,\n [MAX_PROMPT_TOKENS_VARIABLE]: contextTokens === undefined ? undefined : String(contextTokens),\n }\n}\n\nfunction detectBinary(ctx: PlatformContext): DetectResult {\n const isFound = ctx.hasBinary(BINARY)\n return { isFound, detail: isFound ? `${BINARY} found on PATH` : `${BINARY} not found on PATH` }\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport * as v from 'valibot'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { findContextWindow } from '../../product/gateway/models/predefined-models'\nimport type { KeyPathUpdates } from '../../shared/file-formats/key-path'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { readLiteralKey } from '../../shared/text/read-literal-key'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { ConfigurableHarness, DetectResult, FileContribution } from '../harness'\nimport { readJsoncFile } from '../read-jsonc-file'\n\nconst BINARY = 'crush'\nconst PROVIDER_ID = 'nexos'\nconst PROVIDER_NAME = 'nexos.ai'\n// \"openai\" means OpenAI itself to Crush, so a custom endpoint is \"openai-compat\".\nconst PROVIDER_TYPE = 'openai-compat'\nexport const CONFIG_SCHEMA_URL = 'https://charm.land/crush.json'\n\nexport const crush: ConfigurableHarness = {\n kind: 'configurable',\n id: 'crush',\n label: 'Crush',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: { kind: 'supported' },\n detect: (ctx) => detectCrush(ctx),\n configPath: (ctx) => resolveConfigPath(ctx),\n plan: (desired, ctx) => [planConfig(desired, ctx)],\n readKey: (ctx) => readProviderKey(ctx),\n readSecrets: (ctx) => readProviderSecrets(ctx),\n postSetupNotes: [\n 'Crush starts on the model setup chose. For another, run its `model large` command.',\n \"Crush ranks its config, highest first: the project's crushrc, the project's .crush.json or crush.json, \" +\n \"the user's crushrc, then the user's crush.json. A higher one that sets the same values overrides this file.\",\n ],\n}\n\n// At project scope only a project config counts: an installed binary alone is not a project setup.\nfunction detectCrush(ctx: PlatformContext): DetectResult {\n const detected = detectConfigFile([resolveConfigPath(ctx)], ctx.home)\n if (detected.isFound || ctx.scope === 'project' || !ctx.hasBinary(BINARY)) return detected\n\n return { isFound: true, detail: `${BINARY} found on PATH` }\n}\n\nconst USER_DIRECTORY = path.join('.config', 'crush')\nconst USER_FILE = 'crush.json'\nconst PROJECT_FILE = '.crush.json'\n\nfunction resolveConfigPath(ctx: PlatformContext): string {\n return match(ctx.scope)\n .with('user', () => path.join(ctx.home, USER_DIRECTORY, USER_FILE))\n .with('project', () => path.join(ctx.cwd, PROJECT_FILE))\n .exhaustive()\n}\n\nfunction planConfig(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n return {\n kind: 'file',\n path: resolveConfigPath(ctx),\n hasSecret: true,\n edits: () => ({ format: 'jsonc', updates: listUpdates(desired) }),\n }\n}\n\nfunction listUpdates(desired: DesiredConfig): KeyPathUpdates {\n const contextWindow = findContextWindow(desired.model)\n const modelEntry = {\n id: desired.model,\n name: desired.model,\n ...(contextWindow === undefined ? {} : { context_window: contextWindow }),\n }\n // Registering a provider does not switch Crush to it: the model slots name what a turn uses.\n const selection = { provider: PROVIDER_ID, model: desired.model }\n return [\n [['$schema'], CONFIG_SCHEMA_URL],\n [['providers', PROVIDER_ID, 'type'], PROVIDER_TYPE],\n [['providers', PROVIDER_ID, 'name'], PROVIDER_NAME],\n [['providers', PROVIDER_ID, 'base_url'], desired.openaiBaseUrl],\n [['providers', PROVIDER_ID, 'api_key'], desired.apiKey],\n [['providers', PROVIDER_ID, 'models'], [modelEntry]],\n [['models', 'large'], selection],\n [['models', 'small'], selection],\n ]\n}\n\nconst ConfigSchema = v.looseObject({\n providers: v.optional(\n v.looseObject({ [PROVIDER_ID]: v.optional(v.looseObject({ api_key: v.optional(v.string()) })) }),\n ),\n})\n\nfunction readProviderKey(ctx: PlatformContext): string | undefined {\n const config = readJsoncFile(resolveConfigPath(ctx), ConfigSchema)\n const apiKey = config.kind === 'valid' ? config.value.providers?.[PROVIDER_ID]?.api_key : undefined\n return readLiteralKey(apiKey)\n}\n\nconst ProvidersSchema = v.looseObject({ providers: v.optional(v.record(v.string(), v.unknown())) })\nconst ProviderKeySchema = v.looseObject({ api_key: v.string() })\n\nfunction readProviderSecrets(ctx: PlatformContext): string[] {\n const config = readJsoncFile(resolveConfigPath(ctx), ProvidersSchema)\n if (config.kind !== 'valid') return []\n\n return Object.values(config.value.providers ?? {}).flatMap((provider) => {\n const parsed = v.safeParse(ProviderKeySchema, provider)\n return parsed.success ? (readLiteralKey(parsed.output.api_key) ?? []) : []\n })\n}\n","import { readNonBlank } from './read-non-blank'\n\nconst COMMAND_PREFIX = '!'\nconst VARIABLE_MARKER = '$'\n\n/**\n * Reads a config value that holds a literal secret, or undefined when it holds nothing or a reference the agent\n * resolves at run time (a `$VAR`/`${VAR}` interpolation, or a leading `!command`). A reference must never be read\n * back as the key: offered as an existing key, it would be written into other agents' configs verbatim.\n */\nexport function readLiteralKey(value: string | undefined): string | undefined {\n const key = readNonBlank(value)\n return key === undefined || isConfigSubstitution(key) ? undefined : key\n}\n\nfunction isConfigSubstitution(value: string): boolean {\n return value.startsWith(COMMAND_PREFIX) || value.includes(VARIABLE_MARKER)\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { isMissingFileError } from '../../shared/file-system/is-missing-file-error'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport type { DetectResult, UnsupportedHarness } from '../harness'\n\nexport const geminiCli: UnsupportedHarness = {\n kind: 'unsupported',\n id: 'gemini-cli',\n label: 'Gemini CLI',\n binary: 'gemini',\n reason: \"speaks Gemini's native generateContent protocol, not OpenAI or Anthropic\",\n detect: (ctx) => detectConfigDirectory(ctx),\n}\n\nconst CONFIG_DIRECTORY = '.gemini'\n\nfunction detectConfigDirectory(ctx: PlatformContext): DetectResult {\n const directory = path.join(ctx.home, CONFIG_DIRECTORY)\n if (!isDirectory(directory)) return { isFound: false, detail: `no ${displayPath(directory, ctx.home)}` }\n\n return { isFound: true, detail: 'installed, but not configurable through the nexos.ai Gateway' }\n}\n\nfunction isDirectory(directoryPath: string): boolean {\n try {\n return fs.statSync(directoryPath).isDirectory()\n } catch (error) {\n if (isMissingFileError(error)) return false\n throw error\n }\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport * as v from 'valibot'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { findContextWindow } from '../../product/gateway/models/predefined-models'\nimport { renderJsonc } from '../../shared/file-formats/jsonc'\nimport type { KeyPathUpdate, KeyPathUpdates } from '../../shared/file-formats/key-path'\nimport { findFirstExistingFile } from '../../shared/file-system/find-first-existing-file'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { DetectResult, FileContribution, LaunchingHarness } from '../harness'\nimport { parseJsoncConfig, readJsoncFile, type JsoncConfig } from '../read-jsonc-file'\n\nconst BINARY = 'opencode'\n\nexport const opencode: LaunchingHarness = {\n kind: 'configurable',\n id: 'opencode',\n label: 'OpenCode',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: { kind: 'supported' },\n detect: (ctx) => detectOpenCode(ctx),\n configPath: (ctx) => resolveConfigPath(ctx),\n plan: (desired, ctx) => [planConfig(desired, ctx)],\n launch: (desired) => {\n // The run provider names its key through the environment, so the key never reaches argv.\n const config = renderJsonc(null, [\n ...providerUpdates({ providerId: RUN_PROVIDER_ID, apiKey: `{env:${RUN_KEY_VARIABLE}}`, desired }),\n // Leaves no other provider to drift to, OpenCode's own free models included, which send prompts outside nexos.ai.\n [['enabled_providers'], [RUN_PROVIDER_ID]],\n ])\n return {\n binary: BINARY,\n arguments: [],\n env: {\n [CONFIG_CONTENT_VARIABLE]: config,\n [RUN_KEY_VARIABLE]: desired.apiKey,\n [MODELS_FETCH_SWITCH]: SWITCH_ON,\n },\n }\n },\n launchNotes: [\n 'OpenCode adds the \"nexos-run\" model to its recent models, where it shows as unavailable in later sessions.',\n ],\n readKey: (ctx) => readProviderKey(ctx),\n readSecrets: (ctx) => readProviderSecrets(ctx),\n postSetupNotes: [\n 'OpenCode keeps its own credentials in its auth.json; this key goes in the provider block instead, ' +\n 'so no /connect step is needed.',\n ],\n}\n\nfunction detectOpenCode(ctx: PlatformContext): DetectResult {\n const detected = detectConfigFile(listConfigCandidates(ctx), ctx.home)\n if (detected.isFound || ctx.scope === 'project' || !ctx.hasBinary(BINARY)) return detected\n\n return { isFound: true, detail: `${BINARY} found on PATH` }\n}\n\nconst USER_CONFIG_DIRECTORY = path.join('.config', 'opencode')\nconst JSON_CONFIG_FILE = 'opencode.json'\nconst JSONC_CONFIG_FILE = 'opencode.jsonc'\n\nfunction listConfigCandidates(ctx: PlatformContext): readonly [string, string] {\n const directory = match(ctx.scope)\n .with('user', () => path.join(ctx.home, USER_CONFIG_DIRECTORY))\n .with('project', () => ctx.cwd)\n .exhaustive()\n return [path.join(directory, JSON_CONFIG_FILE), path.join(directory, JSONC_CONFIG_FILE)]\n}\n\nfunction resolveConfigPath(ctx: PlatformContext): string {\n const candidates = listConfigCandidates(ctx)\n return findFirstExistingFile(candidates) ?? candidates[0]\n}\n\nfunction planConfig(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n return {\n kind: 'file',\n path: resolveConfigPath(ctx),\n hasSecret: true,\n edits: (current) => ({ format: 'jsonc', updates: listUpdates(desired, parseJsoncConfig(current, ConfigSchema)) }),\n }\n}\n\nconst PROVIDER_ID = 'nexos'\nconst PROVIDER_NAME = 'nexos.ai'\nconst PROVIDER_PACKAGE = '@ai-sdk/openai-compatible'\nconst RUN_PROVIDER_ID = 'nexos-run'\nconst RUN_KEY_VARIABLE = 'NEXOS_API_KEY'\nconst CONFIG_CONTENT_VARIABLE = 'OPENCODE_CONFIG_CONTENT'\n// OpenCode refreshes its catalogue of other providers' models from models.opencode.ai every hour; a run needs none.\nconst MODELS_FETCH_SWITCH = 'OPENCODE_DISABLE_MODELS_FETCH'\nconst SWITCH_ON = '1'\nexport const CONFIG_SCHEMA_URL = 'https://opencode.ai/config.json'\n\ntype ProviderUpdatesParams = { providerId: string; apiKey: string; desired: DesiredConfig }\n\nfunction providerUpdates({ providerId, apiKey, desired }: ProviderUpdatesParams): KeyPathUpdates {\n return [\n [['provider', providerId, 'npm'], PROVIDER_PACKAGE],\n [['provider', providerId, 'name'], PROVIDER_NAME],\n [['provider', providerId, 'options', 'baseURL'], desired.openaiBaseUrl],\n [['provider', providerId, 'options', 'apiKey'], apiKey],\n [['provider', providerId, 'models', desired.model, 'name'], desired.model],\n ...listLimitUpdates({ providerId, model: desired.model }),\n [['model'], `${providerId}/${desired.model}`],\n ]\n}\n\ntype LimitUpdatesParams = { providerId: string; model: string }\n\n// OpenCode's config takes both limits or neither, and caps output at this anyway.\nconst OUTPUT_TOKENS = 32_000\n\n// With no context limit OpenCode never compacts ahead of time, only once the gateway has refused a prompt.\nfunction listLimitUpdates({ providerId, model }: LimitUpdatesParams): KeyPathUpdate[] {\n const contextTokens = findContextWindow(model)\n if (contextTokens === undefined) return []\n\n return [\n [['provider', providerId, 'models', model, 'limit', 'context'], contextTokens],\n [['provider', providerId, 'models', model, 'limit', 'output'], OUTPUT_TOKENS],\n ]\n}\n\nfunction listUpdates(desired: DesiredConfig, config: JsoncConfig<OpenCodeConfig>): KeyPathUpdates {\n const updates = providerUpdates({ providerId: PROVIDER_ID, apiKey: desired.apiKey, desired })\n if (!isMissingSchemaUrl(config)) return updates\n\n return [[['$schema'], CONFIG_SCHEMA_URL], ...updates]\n}\n\nfunction isMissingSchemaUrl(config: JsoncConfig<OpenCodeConfig>): boolean {\n return match(config)\n .with({ kind: 'absent' }, () => true)\n .with({ kind: 'invalid' }, () => false)\n .with({ kind: 'valid' }, ({ value }) => value.$schema === undefined)\n .exhaustive()\n}\n\nfunction readProviderKey(ctx: PlatformContext): string | undefined {\n const config = readJsoncFile(resolveConfigPath(ctx), ConfigSchema)\n const apiKey = config.kind === 'valid' ? config.value.provider?.[PROVIDER_ID]?.options?.apiKey : undefined\n return apiKey === undefined || isSubstitution(apiKey) ? undefined : apiKey\n}\n\nconst SUBSTITUTION_MARKERS = ['{env:', '{file:'] as const\n\nfunction isSubstitution(value: string): boolean {\n return SUBSTITUTION_MARKERS.some((marker) => value.includes(marker))\n}\n\nconst ProvidersSchema = v.looseObject({\n provider: v.fallback(v.optional(v.record(v.string(), v.unknown())), undefined),\n})\nconst ProviderKeySchema = v.looseObject({ options: v.looseObject({ apiKey: v.string() }) })\n\nfunction readProviderSecrets(ctx: PlatformContext): string[] {\n const config = readJsoncFile(resolveConfigPath(ctx), ProvidersSchema)\n if (config.kind !== 'valid') return []\n\n return Object.values(config.value.provider ?? {}).flatMap((provider) => {\n const parsed = v.safeParse(ProviderKeySchema, provider)\n if (!parsed.success || isSubstitution(parsed.output.options.apiKey)) return []\n return readNonBlank(parsed.output.options.apiKey) ?? []\n })\n}\n\nconst ConfigSchema = v.looseObject({\n $schema: v.optional(v.unknown()),\n provider: v.optional(\n v.looseObject({\n [PROVIDER_ID]: v.optional(\n v.looseObject({ options: v.optional(v.looseObject({ apiKey: v.optional(v.string()) })) }),\n ),\n }),\n ),\n})\n\ntype OpenCodeConfig = v.InferOutput<typeof ConfigSchema>\n","import path from 'node:path'\nimport * as v from 'valibot'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { findContextWindow } from '../../product/gateway/models/predefined-models'\nimport type { KeyPathUpdates } from '../../shared/file-formats/key-path'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { readLiteralKey } from '../../shared/text/read-literal-key'\nimport { readNonBlank } from '../../shared/text/read-non-blank'\nimport type { ConfigurableHarness, DetectResult, FileContribution } from '../harness'\nimport { readJsoncFile } from '../read-jsonc-file'\n\nconst BINARY = 'pi'\nconst PROVIDER_ID = 'nexos'\nconst PROVIDER_NAME = 'nexos.ai'\nconst API_TYPE = 'openai-completions'\n\nexport const pi: ConfigurableHarness = {\n kind: 'configurable',\n id: 'pi',\n label: 'Pi',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: {\n kind: 'unsupported',\n reason: 'it reads models.json only from its agent directory (~/.pi/agent), never from the project',\n },\n detect: (ctx) => detectBinary(ctx),\n configPath: (ctx) => resolveModelsPath(ctx),\n plan: (desired, ctx) => [planModels(desired, ctx), planSettings(desired, ctx)],\n readKey: (ctx) => readProviderKey(ctx),\n readSecrets: (ctx) => readProviderSecrets(ctx),\n postSetupNotes: [\n 'Pi starts on the model setup chose. Change it with /model, and press Ctrl+S to make that the default.',\n ],\n}\n\nfunction detectBinary(ctx: PlatformContext): DetectResult {\n const isFound = ctx.hasBinary(BINARY)\n return { isFound, detail: isFound ? `${BINARY} found on PATH` : `${BINARY} not found on PATH` }\n}\n\nconst DEFAULT_AGENT_DIRECTORY = path.join('.pi', 'agent')\nconst MODELS_FILE = 'models.json'\nconst SETTINGS_FILE = 'settings.json'\nconst HOME_PREFIX = '~'\n\n// Pi reads its agent directory from PI_CODING_AGENT_DIR when set, so a relocated install is configured where it looks.\nfunction resolveAgentDirectory(ctx: PlatformContext): string {\n const configured = readNonBlank(ctx.env.PI_CODING_AGENT_DIR)\n return configured === undefined\n ? path.join(ctx.home, DEFAULT_AGENT_DIRECTORY)\n : resolveConfiguredPath(configured, ctx)\n}\n\n// Pi expands a leading ~ and resolves anything relative against the working directory, so we match that.\nfunction resolveConfiguredPath(configured: string, ctx: PlatformContext): string {\n if (configured === HOME_PREFIX) return ctx.home\n if (configured.startsWith(`${HOME_PREFIX}${path.sep}`)) {\n return path.join(ctx.home, configured.slice(HOME_PREFIX.length + 1))\n }\n\n return path.resolve(ctx.cwd, configured)\n}\n\nfunction resolveModelsPath(ctx: PlatformContext): string {\n return path.join(resolveAgentDirectory(ctx), MODELS_FILE)\n}\n\nfunction resolveSettingsPath(ctx: PlatformContext): string {\n return path.join(resolveAgentDirectory(ctx), SETTINGS_FILE)\n}\n\nfunction planModels(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n return {\n kind: 'file',\n path: resolveModelsPath(ctx),\n hasSecret: true,\n edits: () => ({ format: 'jsonc', updates: listModelUpdates(desired) }),\n }\n}\n\n// Registering a provider does not switch Pi to it: settings.json names the startup provider and model.\nfunction planSettings(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n return {\n kind: 'file',\n path: resolveSettingsPath(ctx),\n hasSecret: false,\n edits: () => ({\n format: 'jsonc',\n updates: [\n [['defaultProvider'], PROVIDER_ID],\n [['defaultModel'], desired.model],\n ],\n }),\n }\n}\n\nfunction listModelUpdates(desired: DesiredConfig): KeyPathUpdates {\n const contextWindow = findContextWindow(desired.model)\n const modelEntry = {\n id: desired.model,\n name: desired.model,\n ...(contextWindow === undefined ? {} : { contextWindow }),\n }\n return [\n [['providers', PROVIDER_ID, 'baseUrl'], desired.openaiBaseUrl],\n [['providers', PROVIDER_ID, 'api'], API_TYPE],\n [['providers', PROVIDER_ID, 'apiKey'], desired.apiKey],\n [['providers', PROVIDER_ID, 'name'], PROVIDER_NAME],\n [['providers', PROVIDER_ID, 'models'], [modelEntry]],\n ]\n}\n\nconst ModelsSchema = v.looseObject({\n providers: v.optional(\n v.looseObject({ [PROVIDER_ID]: v.optional(v.looseObject({ apiKey: v.optional(v.string()) })) }),\n ),\n})\n\nfunction readProviderKey(ctx: PlatformContext): string | undefined {\n const models = readJsoncFile(resolveModelsPath(ctx), ModelsSchema)\n const apiKey = models.kind === 'valid' ? models.value.providers?.[PROVIDER_ID]?.apiKey : undefined\n return readLiteralKey(apiKey)\n}\n\nconst ProvidersSchema = v.looseObject({ providers: v.optional(v.record(v.string(), v.unknown())) })\nconst ProviderKeySchema = v.looseObject({ apiKey: v.string() })\n\nfunction readProviderSecrets(ctx: PlatformContext): string[] {\n const models = readJsoncFile(resolveModelsPath(ctx), ProvidersSchema)\n if (models.kind !== 'valid') return []\n\n return Object.values(models.value.providers ?? {}).flatMap((provider) => {\n const parsed = v.safeParse(ProviderKeySchema, provider)\n return parsed.success ? (readLiteralKey(parsed.output.apiKey) ?? []) : []\n })\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport * as v from 'valibot'\nimport type { DesiredConfig } from '../../product/gateway/desired-config'\nimport { MergeConflictError } from '../../shared/file-formats/config-errors'\nimport type { KeyPathUpdates } from '../../shared/file-formats/key-path'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { readLiteralKey } from '../../shared/text/read-literal-key'\nimport { detectConfigFile } from '../detect-config-file'\nimport type { ConfigurableHarness, DetectResult, FileContribution } from '../harness'\nimport { parseJsoncConfig, readJsoncFile } from '../read-jsonc-file'\n\nconst BINARY = 'qwen'\nconst KEY_VARIABLE = 'NEXOS_API_KEY'\nconst AUTH_TYPE = 'openai'\n\nexport const qwen: ConfigurableHarness = {\n kind: 'configurable',\n id: 'qwen-code',\n label: 'Qwen Code',\n binary: BINARY,\n protocols: ['openai-chat'],\n projectSupport: { kind: 'supported' },\n detect: (ctx) => detectQwen(ctx),\n configPath: (ctx) => resolveSettingsPath(ctx),\n plan: (desired, ctx) => [planSettings(desired, ctx)],\n readKey: (ctx) => readProviderKey(ctx),\n readSecrets: (ctx) => readProviderSecrets(ctx),\n postSetupNotes: [\n 'Qwen Code keeps the key in its settings file, so no /auth step is needed.',\n \"Qwen Code ranks its settings, highest first: the system settings file, the project's .qwen/settings.json, \" +\n \"then the user's ~/.qwen/settings.json. A higher one that sets the same values overrides this file.\",\n ],\n}\n\n// At project scope only a project config counts: an installed binary alone is not a project setup.\nfunction detectQwen(ctx: PlatformContext): DetectResult {\n const detected = detectConfigFile([resolveSettingsPath(ctx)], ctx.home)\n if (detected.isFound || ctx.scope === 'project' || !ctx.hasBinary(BINARY)) return detected\n\n return { isFound: true, detail: `${BINARY} found on PATH` }\n}\n\nconst USER_DIRECTORY = '.qwen'\nconst PROJECT_DIRECTORY = '.qwen'\nconst SETTINGS_FILE = 'settings.json'\n\nfunction resolveSettingsPath(ctx: PlatformContext): string {\n return match(ctx.scope)\n .with('user', () => path.join(ctx.home, USER_DIRECTORY, SETTINGS_FILE))\n .with('project', () => path.join(ctx.cwd, PROJECT_DIRECTORY, SETTINGS_FILE))\n .exhaustive()\n}\n\nfunction planSettings(desired: DesiredConfig, ctx: PlatformContext): FileContribution {\n return {\n kind: 'file',\n path: resolveSettingsPath(ctx),\n hasSecret: true,\n edits: (current) => ({ format: 'jsonc', updates: listUpdates(desired, current) }),\n }\n}\n\n// modelProviders.openai is the user's whole list of OpenAI-compatible models, so ours is merged into it, never\n// written over it.\nfunction listUpdates(desired: DesiredConfig, current: string | null): KeyPathUpdates {\n const provider = {\n id: desired.model,\n name: desired.model,\n baseUrl: desired.openaiBaseUrl,\n envKey: KEY_VARIABLE,\n }\n return [\n [\n ['modelProviders', 'openai'],\n [...listOtherOpenAiProviders(current), provider],\n ],\n [['env', KEY_VARIABLE], desired.apiKey],\n [['security', 'auth', 'selectedType'], AUTH_TYPE],\n [['model', 'name'], desired.model],\n ]\n}\n\nconst ModelProvidersSchema = v.looseObject({\n modelProviders: v.optional(v.looseObject({ openai: v.optional(v.unknown()) })),\n})\n\nconst NexosEntrySchema = v.looseObject({ envKey: v.literal(KEY_VARIABLE) })\n\nfunction listOtherOpenAiProviders(current: string | null): unknown[] {\n const parsed = parseJsoncConfig(current, ModelProvidersSchema)\n if (parsed.kind !== 'valid') return []\n\n const openai = parsed.value.modelProviders?.openai\n if (openai === undefined) return []\n if (!Array.isArray(openai)) throw new MergeConflictError()\n\n return openai.filter((entry) => !v.is(NexosEntrySchema, entry))\n}\n\nconst SettingsSchema = v.looseObject({\n env: v.optional(v.looseObject({ [KEY_VARIABLE]: v.optional(v.string()) })),\n})\n\nfunction readProviderKey(ctx: PlatformContext): string | undefined {\n const settings = readJsoncFile(resolveSettingsPath(ctx), SettingsSchema)\n return readLiteralKey(settings.kind === 'valid' ? settings.value.env?.[KEY_VARIABLE] : undefined)\n}\n\n// Qwen keeps every provider's key in this one file, so a diff can print any of them: register the key of every\n// model entry and the auth key, not just ours.\nconst SecretsSchema = v.looseObject({\n env: v.optional(v.record(v.string(), v.unknown())),\n security: v.optional(v.looseObject({ auth: v.optional(v.looseObject({ apiKey: v.optional(v.string()) })) })),\n modelProviders: v.optional(v.record(v.string(), v.unknown())),\n})\n\nconst ProviderEntrySchema = v.looseObject({ envKey: v.string() })\n\nfunction readProviderSecrets(ctx: PlatformContext): string[] {\n const settings = readJsoncFile(resolveSettingsPath(ctx), SecretsSchema)\n if (settings.kind !== 'valid') return []\n\n const { env = {}, security, modelProviders = {} } = settings.value\n const fromEnv = listProviderEnvKeys(modelProviders).flatMap((name) => readEnvSecret(env, name))\n const fromAuth = readOptionalKey(security?.auth?.apiKey)\n return [...fromEnv, ...fromAuth]\n}\n\nfunction listProviderEnvKeys(modelProviders: Record<string, unknown>): string[] {\n return Object.values(modelProviders).flatMap((providers) => {\n if (!Array.isArray(providers)) return []\n return providers.flatMap((entry) => {\n const parsed = v.safeParse(ProviderEntrySchema, entry)\n return parsed.success ? [parsed.output.envKey] : []\n })\n })\n}\n\nfunction readEnvSecret(env: Record<string, unknown>, name: string): string[] {\n const value = env[name]\n return typeof value === 'string' ? readOptionalKey(value) : []\n}\n\nfunction readOptionalKey(value: string | undefined): string[] {\n const key = readLiteralKey(value)\n return key === undefined ? [] : [key]\n}\n","import { claudeCode } from './claude-code/claude-code'\nimport { codex } from './codex/codex'\nimport { copilotCli } from './copilot-cli/copilot-cli'\nimport { crush } from './crush/crush'\nimport { geminiCli } from './gemini-cli/gemini-cli'\nimport type { Harness } from './harness'\nimport { opencode } from './opencode/opencode'\nimport { pi } from './pi/pi'\nimport { qwen } from './qwen-code/qwen'\n\nexport const harnesses: readonly Harness[] = [claudeCode, codex, opencode, copilotCli, pi, crush, qwen, geminiCli]\n\nexport function findHarness(id: string): Harness | undefined {\n return harnesses.find((harness) => harness.id === id)\n}\n\nexport function findHarnessByBinary(binary: string): Harness | undefined {\n return harnesses.find((harness) => harness.binary === binary)\n}\n","const LINE_BREAK = /\\r?\\n/\n\nexport function splitLines(text: string): string[] {\n return text.split(LINE_BREAK)\n}\n","import { match } from 'ts-pattern'\nimport type { EnvSyntax, Shell } from './env-syntax'\nimport { POSIX_ENV_SYNTAX } from './posix-env-syntax'\nimport { POWERSHELL_ENV_SYNTAX } from './powershell-env-syntax'\n\nexport const ENV_SYNTAXES: Readonly<Record<Shell, EnvSyntax>> = {\n posix: POSIX_ENV_SYNTAX,\n powershell: POWERSHELL_ENV_SYNTAX,\n}\n\nexport function resolveShell(platform: NodeJS.Platform): Shell {\n return match(platform)\n .returnType<Shell>()\n .with('win32', () => 'powershell')\n .otherwise(() => 'posix')\n}\n","import path from 'node:path'\nimport { escapePosixSingleQuoted } from '../../../../shared/file-formats/shell/escape-posix-single-quoted'\nimport { createAssignmentMatcher, ENV_DIRECTORY_NAME, formatHeaderLines, type EnvSyntax } from './env-syntax'\n\nconst POSIX_FILE_NAME = 'env'\nconst POSIX_ASSIGNMENT = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/\nconst POSIX_LOAD_COMMAND = `source ${path.posix.join('~', ENV_DIRECTORY_NAME, POSIX_FILE_NAME)}`\n\nexport const POSIX_ENV_SYNTAX: EnvSyntax = {\n fileName: POSIX_FILE_NAME,\n defaultLineEnding: '\\n',\n headerLines: formatHeaderLines(`# Load in your shell with: ${POSIX_LOAD_COMMAND}`),\n normalizeName: (name) => name,\n matchAssignment: createAssignmentMatcher(POSIX_ASSIGNMENT),\n formatAssignment: ({ name, value }) => `export ${name}=${quotePosixValue(value)}`,\n parseValue: parsePosixValue,\n loadCommand: POSIX_LOAD_COMMAND,\n}\n\nconst SHELL_SAFE_VALUE = /^[A-Za-z0-9_./:@+-]*$/\n\nfunction quotePosixValue(value: string): string {\n if (SHELL_SAFE_VALUE.test(value)) return value\n return `'${escapePosixSingleQuoted(value)}'`\n}\n\nconst POSIX_WORD_SEGMENT = /'([^']*)'|\"((?:[^\"\\\\$`]|\\\\.)*)\"|\\\\(.)|([^\\s'\"\\\\$`;&|<>()]+)/gy\nconst DOUBLE_QUOTED_ESCAPE = /\\\\([$`\"\\\\])/g\nconst BLANK_OR_COMMENT = /^(?:\\s+(?:#.*)?)?$/\n\nfunction parsePosixValue(rawValue: string): string | undefined {\n const segments = [...rawValue.matchAll(POSIX_WORD_SEGMENT)]\n const wordLength = segments.reduce((length, segment) => length + segment[0].length, 0)\n if (!BLANK_OR_COMMENT.test(rawValue.slice(wordLength))) return undefined\n\n return segments.map(decodePosixSegment).join('')\n}\n\nfunction decodePosixSegment([, singleQuoted, doubleQuoted, escaped, bare]: RegExpExecArray): string {\n if (doubleQuoted !== undefined) return doubleQuoted.replace(DOUBLE_QUOTED_ESCAPE, '$1')\n return singleQuoted ?? escaped ?? bare ?? ''\n}\n","import type { LineEnding } from '../../../../shared/file-formats/detect-line-ending'\n\nexport const SHELLS = ['posix', 'powershell'] as const\n\nexport type Shell = (typeof SHELLS)[number]\n\nexport type Assignment = { name: string; rawValue: string }\n\nexport type EnvVariable = { name: string; value: string }\n\nexport interface EnvSyntax {\n readonly fileName: string\n readonly defaultLineEnding: LineEnding\n readonly headerLines: readonly string[]\n normalizeName(name: string): string\n matchAssignment(line: string): Assignment | undefined\n formatAssignment(variable: EnvVariable): string\n parseValue(rawValue: string): string | undefined\n readonly loadCommand: string\n}\n\nexport const ENV_DIRECTORY_NAME = '.nexos'\n\nconst MANAGED_HEADER_LINE = '# nexos.ai Gateway — managed by nexos-connect.'\nconst PRESERVED_HEADER_LINES = [\n '# Hand-added entries are preserved; re-running nexos-connect updates the',\n '# variables it owns and leaves everything else alone.',\n] as const\n\n/** Re-renders recognise a header by these exact lines, so rewording one orphans it in every existing file. */\nexport function formatHeaderLines(loadInstruction: string): readonly string[] {\n return [MANAGED_HEADER_LINE, loadInstruction, ...PRESERVED_HEADER_LINES]\n}\n\nexport function createAssignmentMatcher(pattern: RegExp): EnvSyntax['matchAssignment'] {\n return (line) => {\n const [, name, rawValue] = pattern.exec(line) ?? []\n if (name === undefined || rawValue === undefined) return undefined\n return { name, rawValue }\n }\n}\n","import path from 'node:path'\nimport {\n escapePowerShellSingleQuoted,\n POWERSHELL_SINGLE_QUOTES as SINGLE_QUOTES,\n} from '../../../../shared/file-formats/shell/escape-powershell-single-quoted'\nimport { createAssignmentMatcher, ENV_DIRECTORY_NAME, formatHeaderLines, type EnvSyntax } from './env-syntax'\n\nconst POWERSHELL_FILE_NAME = 'env.ps1'\nconst POWERSHELL_ASSIGNMENT = /^\\s*\\$\\{?[Ee][Nn][Vv]:([A-Za-z_][A-Za-z0-9_]*)\\}?\\s*=\\s*(.*)$/\n\n// `$HOME`, not `~`: PowerShell resolves `~` against the current provider's home, which may not be the user's.\nconst POWERSHELL_LOAD_COMMAND = `. \"${path.win32.join('$HOME', ENV_DIRECTORY_NAME, POWERSHELL_FILE_NAME)}\"`\n\nexport const POWERSHELL_ENV_SYNTAX: EnvSyntax = {\n fileName: POWERSHELL_FILE_NAME,\n defaultLineEnding: '\\r\\n',\n headerLines: formatHeaderLines(`# Load in your PowerShell session with: ${POWERSHELL_LOAD_COMMAND}`),\n normalizeName: (name) => name.toUpperCase(),\n matchAssignment: createAssignmentMatcher(POWERSHELL_ASSIGNMENT),\n // Always quoted: a bare `https://…` is a parse error in PowerShell, and single quotes stop interpolation.\n formatAssignment: ({ name, value }) => `$env:${name} = '${escapePowerShellSingleQuoted(value)}'`,\n parseValue: parsePowerShellValue,\n loadCommand: POWERSHELL_LOAD_COMMAND,\n}\n\nconst TRAILING_COMMENT = String.raw`\\s*(?:#.*)?$`\nconst SINGLE_QUOTED_VALUE = new RegExp(\n `^[${SINGLE_QUOTES}]((?:[^${SINGLE_QUOTES}]|[${SINGLE_QUOTES}]{2})*)[${SINGLE_QUOTES}]${TRAILING_COMMENT}`,\n)\nconst ESCAPED_SINGLE_QUOTE = new RegExp(`[${SINGLE_QUOTES}]([${SINGLE_QUOTES}])`, 'g')\nconst DOUBLE_QUOTED_VALUE = new RegExp(`^\"((?:[^\"$\\`]|\"\")*)\"${TRAILING_COMMENT}`)\nconst ESCAPED_DOUBLE_QUOTE = /\"\"/g\n\nfunction parsePowerShellValue(rawValue: string): string | undefined {\n const [, singleQuoted] = SINGLE_QUOTED_VALUE.exec(rawValue) ?? []\n if (singleQuoted !== undefined) return singleQuoted.replace(ESCAPED_SINGLE_QUOTE, '$1')\n\n const [, doubleQuoted] = DOUBLE_QUOTED_VALUE.exec(rawValue) ?? []\n return doubleQuoted?.replace(ESCAPED_DOUBLE_QUOTE, '\"')\n}\n","import { splitLines } from './split-lines'\nimport type { Shell } from './syntax/env-syntax'\nimport { ENV_SYNTAXES } from './syntax/env-syntaxes'\n\nexport function parseEnvFile(text: string, shell: Shell): Map<string, string> {\n const syntax = ENV_SYNTAXES[shell]\n const values = new Map<string, string>()\n\n for (const line of splitLines(text)) {\n const assignment = syntax.matchAssignment(line)\n if (assignment === undefined) continue\n\n const name = syntax.normalizeName(assignment.name)\n const value = syntax.parseValue(assignment.rawValue)\n if (value === undefined) values.delete(name)\n else values.set(name, value)\n }\n\n return values\n}\n","import * as v from 'valibot'\nimport { COMMAND_NAME } from '../../cli/help'\nimport { FORGET_KEY_COMMAND } from '../../cli/parse-cli-arguments'\nimport { UsageError } from '../../cli/usage-error'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport { KEY_PREFIXES, hasKnownKeyPrefix } from '../../product/secrets/key-prefix'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { Availability, Keystore } from '../../product/storage/keychain/keystore'\nimport { describeError } from '../../shared/text/describe-error'\nimport { hasLineBreak } from '../../shared/text/has-line-break'\nimport { CancelledError } from '../../ui/cancelled-error'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport type { ExistingKeys } from './find-existing-keys'\n\nexport type KeySource = 'flag' | 'env' | 'saved' | 'pasted' | 'kept'\n\nexport type ResolvedKey = { key: string; source: KeySource; shouldSave: boolean }\n\nexport type CheckOutcome = 'passed' | 'failed' | 'skipped'\n\nexport type KeyStepInput = {\n flagKey: string | undefined\n envKey: string | undefined\n shouldSaveKey: boolean\n shouldAssumeYes: boolean\n isDryRun: boolean\n existingKeys(): ExistingKeys\n destination: string\n}\n\nexport type KeyStepDeps = { keystore: Keystore; ui: TerminalUi; masker: Masker }\n\nexport type KeyStepRun = { input: KeyStepInput; deps: KeyStepDeps; resolved: ResolvedKey }\n\nexport async function resolveKey(input: KeyStepInput, deps: KeyStepDeps): Promise<ResolvedKey> {\n const { keystore, ui } = deps\n\n if (input.shouldSaveKey) {\n const availability = await keystore.availability()\n if (availability.kind === 'unavailable') throw new UsageError(`--save-key can't be used: ${availability.reason}.`)\n }\n if (input.flagKey !== undefined) return { key: input.flagKey, source: 'flag', shouldSave: input.shouldSaveKey }\n if (input.envKey !== undefined) return { key: input.envKey, source: 'env', shouldSave: input.shouldSaveKey }\n\n const availability = await keystore.availability()\n const saved = availability.kind === 'available' ? await loadSaved(deps) : undefined\n\n if (saved !== undefined) {\n deps.masker.registerSecrets([saved])\n if (input.shouldAssumeYes || (await ui.chooseSavedKey(deps.masker.maskText(saved))) === 'use') {\n return { key: saved, source: 'saved', shouldSave: false }\n }\n const key = await ui.askForNewKey()\n return await finishKey({ input, deps, availability, answer: { kind: 'pasted', key }, isReplacingSavedKey: true })\n }\n\n const existing = input.existingKeys()\n if (input.shouldAssumeYes && existing.offered !== undefined) {\n return { key: existing.offered, source: 'kept', shouldSave: false }\n }\n return await promptForKey({ input, deps, availability, existing: existing.offered })\n}\n\nconst SavedKeySchema = v.pipe(\n v.string(),\n v.trim(),\n v.nonEmpty(),\n v.check((key) => !hasLineBreak(key)),\n)\n\nconst FORGET_KEY_HINT = `npx ${COMMAND_NAME} ${FORGET_KEY_COMMAND}`\n\nasync function loadSaved({ keystore, ui, masker }: KeyStepDeps): Promise<string | undefined> {\n let saved: string | undefined\n try {\n saved = await keystore.load()\n } catch (error) {\n ui.dim(\n masker.maskText(\n `Could not read the saved key from your system keychain: ${describeError(error)}. ` +\n `Run \\`${FORGET_KEY_HINT}\\` if this keeps happening.`,\n ),\n )\n return undefined\n }\n if (saved === undefined) return undefined\n\n const parsed = v.safeParse(SavedKeySchema, saved)\n if (!parsed.success) {\n ui.dim(`The saved key is not usable. Run \\`${FORGET_KEY_HINT}\\` and save it again.`)\n return undefined\n }\n return parsed.output\n}\n\ntype PromptForKeyParams = {\n input: KeyStepInput\n deps: KeyStepDeps\n availability: Availability\n existing: string | undefined\n}\n\nasync function promptForKey(params: PromptForKeyParams): Promise<ResolvedKey> {\n return await finishKey({ ...params, answer: await askExistingOrNew(params), isReplacingSavedKey: false })\n}\n\ntype FinishKeyParams = {\n input: KeyStepInput\n deps: KeyStepDeps\n availability: Availability\n answer: KeyAnswer\n isReplacingSavedKey: boolean\n}\n\nasync function finishKey({\n input,\n deps,\n availability,\n answer,\n isReplacingSavedKey,\n}: FinishKeyParams): Promise<ResolvedKey> {\n if (hasLineBreak(answer.key)) throw new UsageError('The pasted key contains a line break. Paste it on one line.')\n\n return {\n key: answer.key,\n source: answer.kind,\n shouldSave: await askToSave({ input, availability, ui: deps.ui, isReplacingSavedKey }),\n }\n}\n\ntype KeyAnswer = { kind: 'kept' | 'pasted'; key: string }\n\ntype AskExistingOrNewParams = { input: KeyStepInput; deps: KeyStepDeps; existing: string | undefined }\n\nasync function askExistingOrNew({ input, deps, existing }: AskExistingOrNewParams): Promise<KeyAnswer> {\n const { ui, masker } = deps\n if (existing === undefined) return { kind: 'pasted', key: await ui.askForKey({ destination: input.destination }) }\n\n masker.registerSecrets([existing])\n const answer = await ui.askToKeepOrReplaceKey({\n destination: input.destination,\n maskedExistingKey: masker.maskText(existing),\n })\n return answer.kind === 'kept' ? { kind: 'kept', key: existing } : { kind: 'pasted', key: answer.key }\n}\n\ntype AskToSaveParams = {\n input: KeyStepInput\n availability: Availability\n ui: TerminalUi\n isReplacingSavedKey: boolean\n}\n\n/** Default No, and never under `--yes`: saving must always be an explicit choice. */\nasync function askToSave({ input, availability, ui, isReplacingSavedKey }: AskToSaveParams): Promise<boolean> {\n if (input.shouldSaveKey) return true\n // A dry run writes nothing, so its answer cannot matter: do not ask.\n if (input.isDryRun) return false\n if (availability.kind === 'unavailable') {\n ui.dim(`${availability.reason} — the key will not be saved.`)\n return false\n }\n if (input.shouldAssumeYes) return false\n\n const question = isReplacingSavedKey\n ? 'Replace the key saved in your system keychain with this one?'\n : 'Save this key in your system keychain for future runs?'\n\n return await ui.confirm(question, false)\n}\n\nexport function isKeyUsable(key: string): boolean {\n return key.trim() !== ''\n}\n\n/** Warns about an unexpected shape and registers the key, so every later message masks it. */\nexport function adoptKey(key: string, { ui, masker }: { ui: TerminalUi; masker: Masker }): void {\n const warning = findKeyShapeWarning(key)\n if (warning !== undefined) ui.log.warn(warning)\n masker.registerSecrets([key])\n}\n\nexport function findKeyShapeWarning(key: string): string | undefined {\n if (hasKnownKeyPrefix(key)) return undefined\n\n const prefixes = KEY_PREFIXES.map((prefix) => `\"${prefix}\"`).join(' or ')\n return `That key does not look like a nexos.ai key (expected a ${prefixes} prefix). Continuing anyway.`\n}\n\n/** A key that failed the check is never saved, even when the run continues. */\nexport async function commitSave(\n resolved: ResolvedKey,\n check: CheckOutcome,\n { keystore, ui, masker }: KeyStepDeps,\n): Promise<void> {\n if (!resolved.shouldSave) return\n if (check === 'failed') {\n ui.log.warn('The key failed the check, so it was not saved to your system keychain.')\n return\n }\n\n try {\n await keystore.save(resolved.key)\n ui.log.success('Saved the key to your system keychain.')\n } catch (error) {\n ui.log.warn(masker.maskText(`Couldn't save the key to your system keychain: ${describeError(error)}`))\n }\n}\n\nexport function isSavedKeyRejection(resolved: ResolvedKey, probe: ProbeResult): boolean {\n return resolved.source === 'saved' && probe.kind === 'key-rejected'\n}\n\nexport type ReplaceRejectedKeyParams = {\n input: KeyStepInput\n rejected: ResolvedKey\n probe: ProbeResult\n deps: KeyStepDeps\n}\n\n/** A rejected saved key fails the same way on every retry, so it is replaced rather than retried. */\nexport async function replaceRejectedKey({\n input,\n rejected,\n probe,\n deps,\n}: ReplaceRejectedKeyParams): Promise<ResolvedKey | null> {\n const { keystore, ui, masker } = deps\n const status = probe.status ?? 0\n\n if (input.shouldAssumeYes) {\n ui.log.error(`The saved key was rejected (HTTP ${status}).`)\n ui.log.info(`Run \\`${FORGET_KEY_HINT}\\`, or pass --key.`)\n return null\n }\n\n ui.log.warn(`The gateway rejected the saved key (HTTP ${status}).`)\n if ((await ui.chooseOnSavedKeyRejected(status)) === 'cancel') throw new CancelledError()\n\n if (input.isDryRun) {\n ui.dim('Dry run — the saved key was not removed.')\n } else {\n try {\n await keystore.clear()\n } catch (error) {\n ui.log.warn(\n masker.maskText(\n `Could not remove the saved key: ${describeError(error)}. It is still saved; ` +\n `run \\`${FORGET_KEY_HINT}\\`.`,\n ),\n )\n }\n }\n\n const existing = input.existingKeys().offered\n return await promptForKey({\n input,\n deps,\n availability: await keystore.availability(),\n existing: existing === rejected.key ? undefined : existing,\n })\n}\n","export const PROTOCOLS = ['anthropic', 'openai-chat', 'openai-responses'] as const\n\nexport type Protocol = (typeof PROTOCOLS)[number]\n\nexport const PROTOCOL_ENDPOINTS = {\n anthropic: 'messages',\n 'openai-chat': 'chat_completion',\n 'openai-responses': 'responses',\n} as const satisfies Record<Protocol, string>\n","import pc from 'picocolors'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport { INDENT } from './indent'\n\nexport function formatProbes(results: readonly ProbeResult[]): string[] {\n return [...formatHeading('Key check'), ...results.flatMap(formatProbe)]\n}\n\nconst SURFACE_COLUMN_WIDTH = 10\n\nfunction formatProbe(result: ProbeResult): string[] {\n const colour = result.kind === 'passed' ? pc.dim : pc.yellow\n const glyph = result.kind === 'passed' ? pc.green(GLYPHS.success) : pc.yellow(GLYPHS.warning)\n return [\n ` ${glyph} ${result.surface.padEnd(SURFACE_COLUMN_WIDTH)} ${pc.dim(result.endpoint)}`,\n `${INDENT}${colour(result.detail)}`,\n ]\n}\n","export const GLYPHS = {\n success: '✓',\n unchanged: '=',\n absent: '·',\n failure: '✗',\n warning: '!',\n next: '→',\n elided: '…',\n} as const\n","import pc from 'picocolors'\n\nexport function formatHeading(text: string): string[] {\n return ['', pc.bold(text)]\n}\n","export const INDENT = ' '\nexport const NESTED_INDENT = ' '\n\nexport type IndentLinesParams = { text: string; indent: string }\n\nexport function indentLines({ text, indent }: IndentLinesParams): string[] {\n const lines = text.endsWith('\\n') ? text.slice(0, -1).split('\\n') : text.split('\\n')\n return lines.map((line) => (line === '' ? '' : indent + line))\n}\n","import { match } from 'ts-pattern'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport { listModels } from '../../product/gateway/list-models'\nimport type { ModelInfo } from '../../product/gateway/model-schema'\nimport { DEFAULT_MODEL } from '../../product/gateway/models/predefined-models'\nimport { isKeyAccepted, type ProbeResult } from '../../product/gateway/probe-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatCount } from '../../shared/text/format-count'\nimport { formatProbes } from '../../ui/report/format-probes'\nimport type { Spinner } from '../../ui/spinner'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { isSavedKeyRejection, type CheckOutcome, type ResolvedKey } from './key-step'\nimport { PROBE_SUMMARIES } from './probe-summaries'\n\nexport type KeyCheck = {\n probes: ProbeResult[]\n models: ModelInfo[]\n decidedModel: string | undefined\n resolvedKey: ResolvedKey\n outcome: CheckOutcome\n isAborted: boolean\n}\n\nexport function skippedKeyCheck(resolvedKey: ResolvedKey): KeyCheck {\n return { probes: [], models: [], decidedModel: undefined, resolvedKey, outcome: 'skipped', isAborted: false }\n}\n\nexport type CheckKeyParams = {\n openaiBaseUrl: string\n requestedModel: string | undefined\n shouldAssumeYes: boolean\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n resolved: ResolvedKey\n onSavedKeyRejected?(rejected: ResolvedKey, probe: ProbeResult): Promise<ResolvedKey | null>\n}\n\nexport async function checkKey(params: CheckKeyParams): Promise<KeyCheck> {\n const spinner = params.ui.spinner()\n spinner.start('Checking the key and fetching the model list…')\n return await attemptKeyCheck({ ...params, spinner })\n}\n\ntype AttemptKeyCheckParams = CheckKeyParams & { spinner: Spinner }\n\nasync function attemptKeyCheck(params: AttemptKeyCheckParams): Promise<KeyCheck> {\n const { openaiBaseUrl, masker, fetch, spinner, ui, resolved } = params\n const { probe, models } = await spinner.waitFor((signal) =>\n listModels({ openaiBaseUrl, apiKey: resolved.key, masker, fetch, signal }),\n )\n spinner.stop(summarizeKeyCheck(probe, models.length))\n if (isKeyAccepted(probe)) {\n return {\n probes: [probe],\n models,\n decidedModel: undefined,\n resolvedKey: resolved,\n outcome: 'passed',\n isAborted: false,\n }\n }\n\n if (isSavedKeyRejection(resolved, probe) && params.onSavedKeyRejected !== undefined) {\n const replaced = await params.onSavedKeyRejected(resolved, probe)\n if (replaced === null) {\n return {\n probes: [],\n models: [],\n decidedModel: undefined,\n resolvedKey: resolved,\n outcome: 'failed',\n isAborted: true,\n }\n }\n spinner.start('Checking the new key…')\n return await attemptKeyCheck({ ...params, resolved: replaced })\n }\n\n const continuation = findContinuation(params)\n if (continuation !== undefined) {\n ui.log.warn(continuation)\n return {\n probes: [probe],\n models: [],\n decidedModel: undefined,\n resolvedKey: resolved,\n outcome: 'failed',\n isAborted: false,\n }\n }\n\n ui.print(formatProbes([probe]))\n const choice = await ui.chooseOnFetchFailure()\n return await match(choice)\n .with('retry', async () => {\n spinner.start('Checking again…')\n return await attemptKeyCheck(params)\n })\n .with('manual', async () => ({\n probes: [],\n models: [],\n decidedModel: await ui.askForModelId(),\n resolvedKey: resolved,\n outcome: 'failed' as const,\n isAborted: false,\n }))\n .with('default', async () => ({\n probes: [],\n models: [],\n decidedModel: DEFAULT_MODEL,\n resolvedKey: resolved,\n outcome: 'failed' as const,\n isAborted: false,\n }))\n .exhaustive()\n}\n\nfunction summarizeKeyCheck(probe: ProbeResult, modelCount: number): string {\n return match(probe.kind)\n .with('passed', () => `Key verified — ${formatCount(modelCount, 'model')} available.`)\n .with('bad-response', () => 'Key verified, but the model list could not be read.')\n .otherwise((kind) => PROBE_SUMMARIES[kind])\n}\n\nexport const ASSUMED_YES_CONTINUATION = 'Continuing despite the failed check (--yes).'\n\nfunction findContinuation({ shouldAssumeYes, requestedModel, masker }: CheckKeyParams): string | undefined {\n if (shouldAssumeYes) return ASSUMED_YES_CONTINUATION\n if (requestedModel === undefined) return undefined\n\n return masker.maskText(`Continuing despite the failed check — \"${requestedModel}\" was named explicitly.`)\n}\n","import { P, match } from 'ts-pattern'\nimport { formatCount } from '../../shared/text/format-count'\nimport type { Masker } from '../secrets/masker'\nimport { describeGatewayFailure, formatHttpFailure, isGatewayFailure } from './gateway-errors'\nimport {\n GATEWAY_TIMEOUT_MS,\n KEY_REJECTED_STATUSES,\n isSuccessStatus,\n requestGateway,\n trimTrailingSlashes,\n type Fetch,\n type GatewayResponse,\n} from './gateway-request'\nimport { ModelListSchema, OpenAiErrorSchema, parseJsonBody, type ModelInfo } from './model-schema'\nimport type { ProbeKind, ProbeResult } from './probe-result'\n\nexport type ListModelsResult = {\n probe: ProbeResult\n models: ModelInfo[]\n}\n\nexport type ListModelsParams = {\n openaiBaseUrl: string\n apiKey: string\n masker: Masker\n fetch: Fetch\n signal?: AbortSignal\n}\n\nconst MODELS_PATH = '/models'\nconst BEARER_PREFIX = 'Bearer '\n\nexport async function listModels({\n openaiBaseUrl,\n apiKey,\n masker,\n fetch,\n signal,\n}: ListModelsParams): Promise<ListModelsResult> {\n const endpoint = `${trimTrailingSlashes(openaiBaseUrl)}${MODELS_PATH}`\n const probe = (kind: ProbeKind, detail: string, status: number | undefined): ProbeResult => ({\n kind,\n surface: 'gateway',\n endpoint,\n detail,\n ...(status === undefined ? {} : { status }),\n })\n\n try {\n const response = await requestGateway({\n url: endpoint,\n init: { method: 'GET', headers: { authorization: `${BEARER_PREFIX}${apiKey}` } },\n fetch,\n timeoutMs: GATEWAY_TIMEOUT_MS,\n signal,\n })\n const { kind, detail, models, status } = readListing(response, masker)\n return { probe: probe(kind, detail, status), models }\n } catch (error) {\n if (!isGatewayFailure(error)) throw error\n return { probe: probe(error.kind, describeGatewayFailure(error, masker), undefined), models: [] }\n }\n}\n\ntype Listing = { kind: ProbeKind; detail: string; models: ModelInfo[]; status: number }\n\nfunction readListing({ status, text }: GatewayResponse, masker: Masker): Listing {\n if (!isSuccessStatus(status)) {\n const rejection = parseJsonBody(OpenAiErrorSchema, text)?.error\n const detail = formatHttpFailure(status, rejection?.message ?? text, masker)\n return { kind: classifyRejection(status, rejection?.code ?? undefined), detail, models: [], status }\n }\n\n const models = parseJsonBody(ModelListSchema, text)\n if (models === undefined) {\n const detail = `HTTP ${status} — authenticated, but the model list could not be read`\n return { kind: 'bad-response', detail, models: [], status }\n }\n const detail = `HTTP ${status} — authenticated, ${formatCount(models.length, 'model')} available`\n return { kind: 'passed', detail, models, status }\n}\n\nconst INVALID_KEY_ERROR_CODE = 'invalid_api_key'\n\ntype RejectionKind = Extract<ProbeKind, 'key-rejected' | 'bad-status'>\n\nfunction classifyRejection(status: number, errorCode: string | undefined): RejectionKind {\n return match({ status, errorCode })\n .returnType<RejectionKind>()\n .with({ status: P.union(...KEY_REJECTED_STATUSES) }, { errorCode: INVALID_KEY_ERROR_CODE }, () => 'key-rejected')\n .otherwise(() => 'bad-status')\n}\n","export function formatCount(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? '' : 's'}`\n}\n","import * as v from 'valibot'\n\nconst OptionalTextSchema = v.fallback(v.optional(v.pipe(v.string(), v.nonEmpty())), undefined)\nconst OptionalCountSchema = v.fallback(v.optional(v.pipe(v.number(), v.finite())), undefined)\nconst EndpointsSchema = v.fallback(v.pipe(v.array(v.unknown()), v.transform(keepStrings)), [])\n\nconst ModelSchema = v.pipe(\n v.object({\n id: v.pipe(v.string(), v.nonEmpty()),\n developer: OptionalTextSchema,\n owned_by: OptionalTextSchema,\n context_length: OptionalCountSchema,\n region: OptionalTextSchema,\n endpoints: EndpointsSchema,\n }),\n v.transform((entry) => ({\n id: entry.id,\n developer: entry.developer ?? entry.owned_by ?? null,\n contextLength: entry.context_length ?? null,\n region: entry.region ?? null,\n endpoints: entry.endpoints,\n })),\n)\n\nexport type ModelInfo = v.InferOutput<typeof ModelSchema>\n\nexport const ModelListSchema = v.pipe(\n v.object({ data: v.array(v.unknown()) }),\n v.transform(({ data }) => keepUsableModels(data)),\n)\n\nexport const OpenAiErrorSchema = v.object({\n error: v.object({\n message: v.string(),\n type: v.optional(v.string()),\n code: v.optional(v.nullable(v.string())),\n }),\n})\n\nexport const AnthropicErrorSchema = v.object({\n type: v.literal('error'),\n error: v.object({ type: v.string(), message: v.string() }),\n})\n\nexport function parseJsonBody<TSchema extends v.GenericSchema>(\n schema: TSchema,\n text: string,\n): v.InferOutput<TSchema> | undefined {\n const result = v.safeParse(schema, parseJson(text))\n return result.success ? result.output : undefined\n}\n\nfunction keepStrings(values: unknown[]): string[] {\n return values.filter((value) => typeof value === 'string')\n}\n\nfunction keepUsableModels(entries: unknown[]): ModelInfo[] {\n const modelsById = new Map<string, ModelInfo>()\n for (const entry of entries) {\n const model = v.safeParse(ModelSchema, entry)\n if (model.success && !modelsById.has(model.output.id)) modelsById.set(model.output.id, model.output)\n }\n return [...modelsById.values()]\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n","import { match } from 'ts-pattern'\n\nexport type ProbeSurface = 'gateway' | 'anthropic'\n\nexport type ProbeKind =\n | 'passed'\n | 'key-rejected'\n | 'model-rejected'\n | 'unreachable'\n | 'timed-out'\n | 'bad-status'\n | 'bad-response'\n\nexport type ProbeResult = {\n kind: ProbeKind\n surface: ProbeSurface\n endpoint: string\n detail: string\n /** The HTTP status, when there was a response; absent for a network failure or a timeout. */\n status?: number\n}\n\nexport function isKeyAccepted(probe: ProbeResult): boolean {\n return match(probe.kind)\n .with('passed', 'bad-response', () => true)\n .with('key-rejected', 'model-rejected', 'unreachable', 'timed-out', 'bad-status', () => false)\n .exhaustive()\n}\n","import type { ProbeKind } from '../../product/gateway/probe-result'\n\nexport const PROBE_SUMMARIES: Readonly<Record<ProbeKind, string>> = {\n passed: 'The check passed.',\n 'key-rejected': 'The gateway rejected the key.',\n 'model-rejected': 'The gateway rejected the model.',\n unreachable: 'Could not reach the gateway.',\n 'timed-out': 'The gateway did not answer in time.',\n 'bad-status': 'The gateway answered with an error.',\n 'bad-response': 'The gateway answered, but its reply could not be read.',\n}\n","import type { ModelInfo } from '../model-schema'\nimport { PROTOCOL_ENDPOINTS, type Protocol } from './protocol'\n\nexport function isModelCompatible(model: ModelInfo, protocols: readonly Protocol[]): boolean {\n return findUnservedProtocols(model, protocols).length === 0\n}\n\nexport function findUnservedProtocols(model: ModelInfo, protocols: readonly Protocol[]): Protocol[] {\n if (model.endpoints.length === 0) return []\n return protocols.filter((protocol) => !model.endpoints.includes(PROTOCOL_ENDPOINTS[protocol]))\n}\n","import type { ModelInfo } from '../product/gateway/model-schema'\nimport { isModelCompatible } from '../product/gateway/models/model-compatibility'\nimport { PREDEFINED_MODELS } from '../product/gateway/models/predefined-models'\nimport type { Protocol } from '../product/gateway/models/protocol'\n\nexport const BROWSE_VALUE = '\\u0000browse'\nexport const MANUAL_VALUE = '\\u0000manual'\n\nexport type ModelChoice = { value: string; label: string; hint?: string }\n\nexport type ModelChoices = {\n rows: ModelChoice[]\n browsable: ModelInfo[]\n hiddenCount: number\n isRouterOffered: boolean\n}\n\nconst MANUAL_ROW: ModelChoice = {\n value: MANUAL_VALUE,\n label: 'Type a model id…',\n hint: 'no model list available',\n}\n\nexport function buildModelChoices(\n models: readonly ModelInfo[],\n protocols: readonly Protocol[],\n isRouterOffered: boolean,\n): ModelChoices {\n const compatible = models.filter((model) => isModelCompatible(model, protocols))\n const usable = compatible.length > 0 ? compatible : models\n const browsable = [...usable].sort((first, second) => first.id.localeCompare(second.id))\n const hiddenCount = models.length - usable.length\n\n const routerRows = isRouterOffered ? PREDEFINED_MODELS.map(({ id, hint }) => ({ value: id, label: id, hint })) : []\n const lastRow = models.length > 0 ? buildBrowseRow(browsable.length) : MANUAL_ROW\n return { rows: [...routerRows, lastRow], browsable, hiddenCount, isRouterOffered }\n}\n\nexport type ModelSuggestion = { model: string; hint: string }\n\n/** The router rows lead, and the browse or manual row stays last. */\nexport function addSuggestionRows(choices: ModelChoices, suggestions: readonly ModelSuggestion[]): ModelChoices {\n const suggestionRows = suggestions.map(({ model, hint }) => ({ value: model, label: model, hint }))\n const { rows } = choices\n return { ...choices, rows: [...rows.slice(0, -1), ...suggestionRows, ...rows.slice(-1)] }\n}\n\nfunction buildBrowseRow(availableCount: number): ModelChoice {\n return { value: BROWSE_VALUE, label: 'Choose from available models…', hint: `${availableCount} available` }\n}\n\nexport function formatModelHint(model: ModelInfo): string {\n const context = model.contextLength === null ? null : `${formatContextLength(model.contextLength)} context`\n return [model.developer, context, model.region].filter((part) => part !== null).join(' · ')\n}\n\nconst THOUSAND = 1_000\nconst MILLION = 1_000_000\nconst MILLION_DECIMAL_PLACES = 1\n\nexport function formatContextLength(tokens: number): string {\n if (tokens < THOUSAND) return String(tokens)\n\n const thousands = Math.round(tokens / THOUSAND)\n if (thousands < THOUSAND) return `${thousands}k`\n\n return `${Number((tokens / MILLION).toFixed(MILLION_DECIMAL_PLACES))}M`\n}\n","import { MODEL_ENV_VARIABLE } from '../../cli/environment'\nimport { UsageError } from '../../cli/usage-error'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport type { ModelInfo } from '../../product/gateway/model-schema'\nimport { findUnservedProtocols } from '../../product/gateway/models/model-compatibility'\nimport { DEFAULT_MODEL, isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport { PROTOCOL_ENDPOINTS, type Protocol } from '../../product/gateway/models/protocol'\nimport type { RouterAvailability } from '../../product/gateway/models/router-availability'\nimport { addSuggestionRows, buildModelChoices, type ModelSuggestion } from '../../ui/model-choices'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport type { KeyCheck } from '../key/key-check'\n\nexport const UNAVAILABLE_ROUTER_REFUSAL = `${DEFAULT_MODEL} is not available for this key. Pass --model, or set $${MODEL_ENV_VARIABLE}.`\n\nexport type ChooseModelParams = {\n keyCheck: KeyCheck\n requestedModel: string | undefined\n routerAvailability: RouterAvailability\n shouldAssumeYes: boolean\n protocols: readonly Protocol[]\n suggestions: readonly ModelSuggestion[]\n ui: TerminalUi\n}\n\nexport async function chooseModel({\n keyCheck,\n requestedModel,\n routerAvailability,\n shouldAssumeYes,\n protocols,\n suggestions,\n ui,\n}: ChooseModelParams): Promise<string> {\n if (keyCheck.decidedModel !== undefined) return keyCheck.decidedModel\n if (requestedModel !== undefined) return requestedModel\n\n const isRouterOffered = routerAvailability === 'available'\n if (shouldAssumeYes) {\n if (routerAvailability === 'unavailable') throw new UsageError(UNAVAILABLE_ROUTER_REFUSAL)\n if (!isRouterOffered) {\n ui.log.warn(`Could not confirm that ${DEFAULT_MODEL} is available. Continuing anyway (--yes).`)\n }\n return DEFAULT_MODEL\n }\n\n return await ui.selectModel(\n addSuggestionRows(buildModelChoices(keyCheck.models, protocols, isRouterOffered), suggestions),\n )\n}\n\nexport type FindModelWarningsParams = {\n model: string\n models: readonly ModelInfo[]\n configurable: readonly ConfigurableHarness[]\n routerAvailability: RouterAvailability\n}\n\nexport function findModelWarnings({\n model,\n models,\n configurable,\n routerAvailability,\n}: FindModelWarningsParams): string[] {\n if (isPredefinedModel(model)) {\n return routerAvailability === 'unavailable'\n ? [`\"${model}\" is not available for this key. Continuing because you named it.`]\n : []\n }\n if (models.length === 0) return []\n\n const listed = models.find((candidate) => candidate.id === model)\n if (listed === undefined) {\n return [`\"${model}\" is not in the list this key can see. Continuing — the gateway may still accept it.`]\n }\n\n return configurable.flatMap((harness) => {\n const unserved = findUnservedProtocols(listed, harness.protocols)\n if (unserved.length === 0) return []\n\n const endpoints = unserved.map((protocol) => PROTOCOL_ENDPOINTS[protocol]).join(', ')\n return [`${harness.label}: \"${model}\" does not advertise ${endpoints}. It may still work.`]\n })\n}\n","import { match } from 'ts-pattern'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport { DEFAULT_MODEL } from '../../product/gateway/models/predefined-models'\nimport { classifyRouterAvailability, type RouterAvailability } from '../../product/gateway/models/router-availability'\nimport { probeAnthropic } from '../../product/gateway/probe-anthropic'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { ASSUMED_YES_CONTINUATION } from '../key/key-check'\nimport { PROBE_SUMMARIES } from '../key/probe-summaries'\n\nexport type ProbeModelParams = {\n anthropicBaseUrl: string\n key: string\n model: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\nexport async function probeModel(params: ProbeModelParams): Promise<ProbeResult> {\n const { anthropicBaseUrl, key, model, ui, masker, fetch } = params\n const spinner = ui.spinner()\n spinner.start(masker.maskText(`Checking \"${model}\" against the gateway…`))\n const probe = await spinner.waitFor((signal) =>\n probeAnthropic({ anthropicBaseUrl, apiKey: key, model, masker, fetch, signal }),\n )\n spinner.stop(summarizeModelProbe(probe))\n return probe\n}\n\nexport type RouterProbe = { availability: RouterAvailability; probe: ProbeResult }\n\nexport type ProbeRouterParams = {\n anthropicBaseUrl: string\n key: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\n/** Silent on purpose: its result only decides which rows the picker offers. */\nexport async function probeRouter({\n anthropicBaseUrl,\n key,\n ui,\n masker,\n fetch,\n}: ProbeRouterParams): Promise<RouterProbe> {\n const probe = await ui\n .spinner()\n .waitQuietly((signal) =>\n probeAnthropic({ anthropicBaseUrl, apiKey: key, model: DEFAULT_MODEL, masker, fetch, signal }),\n )\n return { availability: classifyRouterAvailability(probe), probe }\n}\n\nexport type ShouldContinueAfterProbeParams = {\n probe: ProbeResult\n shouldAssumeYes: boolean\n consequence: string\n ui: TerminalUi\n}\n\nexport async function shouldContinueAfterProbe({\n probe,\n shouldAssumeYes,\n consequence,\n ui,\n}: ShouldContinueAfterProbeParams): Promise<boolean> {\n if (probe.kind === 'passed') return true\n if (shouldAssumeYes) {\n ui.log.warn(ASSUMED_YES_CONTINUATION)\n return true\n }\n\n return await ui.confirm(`Continue anyway? ${consequence}`, false)\n}\n\nfunction summarizeModelProbe(probe: ProbeResult): string {\n return match(probe.kind)\n .with('passed', () => 'Model verified.')\n .otherwise((kind) => PROBE_SUMMARIES[kind])\n}\n","import { match } from 'ts-pattern'\nimport type { ProbeResult } from '../probe-result'\n\nexport const ROUTER_AVAILABILITY = ['available', 'unavailable', 'unknown'] as const\n\nexport type RouterAvailability = (typeof ROUTER_AVAILABILITY)[number]\n\nexport function classifyRouterAvailability(probe: ProbeResult): RouterAvailability {\n return match(probe.kind)\n .returnType<RouterAvailability>()\n .with('passed', () => 'available')\n .with('model-rejected', () => 'unavailable')\n .otherwise(() => 'unknown')\n}\n","import { P, match } from 'ts-pattern'\nimport type { Masker } from '../secrets/masker'\nimport { describeGatewayFailure, formatHttpFailure, isGatewayFailure } from './gateway-errors'\nimport {\n GATEWAY_TIMEOUT_MS,\n KEY_REJECTED_STATUSES,\n isSuccessStatus,\n requestGateway,\n trimTrailingSlashes,\n type Fetch,\n} from './gateway-request'\nimport { AnthropicErrorSchema, parseJsonBody } from './model-schema'\nimport type { ProbeKind, ProbeResult } from './probe-result'\n\nexport type ProbeAnthropicParams = {\n anthropicBaseUrl: string\n apiKey: string\n model: string\n masker: Masker\n fetch: Fetch\n signal?: AbortSignal\n}\n\nconst MESSAGES_PATH = '/v1/messages'\nconst ANTHROPIC_VERSION = '2023-06-01'\nconst PING_MAX_TOKENS = 1\nconst PING_TEXT = 'ping'\n\nexport async function probeAnthropic({\n anthropicBaseUrl,\n apiKey,\n model,\n masker,\n fetch,\n signal,\n}: ProbeAnthropicParams): Promise<ProbeResult> {\n const endpoint = `${trimTrailingSlashes(anthropicBaseUrl)}${MESSAGES_PATH}`\n const probe = (kind: ProbeKind, detail: string, status: number | undefined): ProbeResult => ({\n kind,\n surface: 'anthropic',\n endpoint,\n detail,\n ...(status === undefined ? {} : { status }),\n })\n\n try {\n const response = await requestGateway({\n url: endpoint,\n init: {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': ANTHROPIC_VERSION,\n },\n body: JSON.stringify({\n model,\n max_tokens: PING_MAX_TOKENS,\n messages: [{ role: 'user', content: PING_TEXT }],\n }),\n },\n fetch,\n timeoutMs: GATEWAY_TIMEOUT_MS,\n signal,\n })\n if (isSuccessStatus(response.status)) {\n return probe('passed', `HTTP ${response.status} — authenticated`, response.status)\n }\n\n const rejection = parseJsonBody(AnthropicErrorSchema, response.text)?.error\n const detail = formatHttpFailure(response.status, rejection?.message ?? response.text, masker)\n return probe(classifyRejection(response.status, rejection?.type), detail, response.status)\n } catch (error) {\n if (!isGatewayFailure(error)) throw error\n return probe(error.kind, describeGatewayFailure(error, masker), undefined)\n }\n}\n\nconst MODEL_NOT_FOUND_STATUS = 404\nconst KEY_REJECTED_ERROR_TYPES = ['authentication_error', 'permission_error'] as const\nconst MODEL_NOT_FOUND_ERROR_TYPE = 'not_found_error'\n\ntype RejectionKind = Extract<ProbeKind, 'key-rejected' | 'model-rejected' | 'bad-status'>\n\nfunction classifyRejection(status: number, errorType: string | undefined): RejectionKind {\n return match({ status, errorType })\n .returnType<RejectionKind>()\n .with(\n { status: P.union(...KEY_REJECTED_STATUSES) },\n { errorType: P.union(...KEY_REJECTED_ERROR_TYPES) },\n () => 'key-rejected',\n )\n .with({ status: MODEL_NOT_FOUND_STATUS }, { errorType: MODEL_NOT_FOUND_ERROR_TYPE }, () => 'model-rejected')\n .otherwise(() => 'bad-status')\n}\n","import { randomUUID } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport * as v from 'valibot'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport { displayPath } from '../../../shared/text/display-path'\nimport { normalizeModel } from '../../gateway/models/predefined-models'\nimport { ENV_DIRECTORY_NAME } from '../env-file/syntax/env-syntax'\n\nconst PREFERENCES_FILE = 'preferences.json'\n\nexport function resolvePreferencesPath(home: string): string {\n return path.join(home, ENV_DIRECTORY_NAME, PREFERENCES_FILE)\n}\n\nconst ModelIdSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.transform(normalizeModel))\n\nconst PreferencesSchema = v.looseObject({\n defaultModels: v.optional(v.record(v.string(), ModelIdSchema), {}),\n})\n\ntype Preferences = v.InferOutput<typeof PreferencesSchema>\n\n/** Keyed by harness id. */\nexport type DefaultModels = Readonly<Record<string, string>>\n\nexport class PreferencesError extends Error {\n override readonly name = 'PreferencesError'\n}\n\nexport function readDefaultModels(home: string): DefaultModels {\n return readPreferences(home).defaultModels\n}\n\nexport type SaveDefaultModelsParams = { home: string; defaultModels: DefaultModels }\n\nconst JSON_INDENT = 2\n\nexport function saveDefaultModels({ home, defaultModels }: SaveDefaultModelsParams): void {\n const current = readPreferences(home)\n const next: Preferences = { ...current, defaultModels: { ...current.defaultModels, ...defaultModels } }\n writeAtomically(resolvePreferencesPath(home), `${JSON.stringify(next, null, JSON_INDENT)}\\n`)\n}\n\nfunction readPreferences(home: string): Preferences {\n const filePath = resolvePreferencesPath(home)\n const text = readFileIfExists(filePath)\n if (text === null) return { defaultModels: {} }\n\n const parsed = v.safeParse(PreferencesSchema, parseJson(text))\n if (!parsed.success) {\n throw new PreferencesError(\n `${displayPath(filePath, home)} is not a preferences file nexos-connect can read. Fix it or delete it.`,\n )\n }\n return parsed.output\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n if (error instanceof SyntaxError) return undefined\n throw error\n }\n}\n\n// Two runs may save at once; a rename never leaves the file half-written for the other to read.\nfunction writeAtomically(filePath: string, content: string): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n try {\n fs.writeFileSync(temporaryPath, content)\n fs.renameSync(temporaryPath, filePath)\n } catch (error) {\n fs.rmSync(temporaryPath, { force: true })\n throw error\n }\n}\n","import * as v from 'valibot'\nimport { describeError } from '../text/describe-error'\nimport { displayPath } from '../text/display-path'\nimport { Utf16FileError } from './utf16-file-error'\n\nexport type FileAction = 'read' | 'write'\n\nexport type DescribeFileErrorParams = { error: unknown; action: FileAction; home: string }\n\nexport function describeFileError({ error, action, home }: DescribeFileErrorParams): string {\n const failure = readFileFailure(error)\n if (failure === undefined) return describeError(error)\n\n return `${displayPath(failure.path, home)}: cannot ${action} it (${failure.reason}). ${failure.nextStep}, then run again.`\n}\n\ntype FileFailure = { path: string; reason: string; nextStep: string }\n\nconst FileSystemErrorSchema = v.object({ code: v.string(), path: v.string() })\n\nconst PERMISSION_CODES: readonly string[] = ['EACCES', 'EPERM', 'EROFS']\n\nfunction readFileFailure(error: unknown): FileFailure | undefined {\n if (error instanceof Utf16FileError) {\n return { path: error.filePath, reason: 'saved as UTF-16', nextStep: 'Re-save it as UTF-8' }\n }\n if (!v.is(FileSystemErrorSchema, error)) return undefined\n\n const nextStep = PERMISSION_CODES.includes(error.code) ? 'Check its permissions' : 'Check that path'\n return { path: error.path, reason: error.code, nextStep }\n}\n","import type { Harness } from '../../harnesses/harness'\nimport type { ModelInfo } from '../../product/gateway/model-schema'\nimport { isModelCompatible } from '../../product/gateway/models/model-compatibility'\nimport { isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport type { Protocol } from '../../product/gateway/models/protocol'\nimport type { DefaultModels } from '../../product/storage/preferences/preferences'\nimport type { ModelSuggestion } from '../../ui/model-choices'\n\n/** The distinct defaults of the agents being set up or started, each with the agents it belongs to. */\nexport function findOwnDefaults(defaultModels: DefaultModels, targets: readonly Harness[]): ModelSuggestion[] {\n return groupByModel(defaultModels, targets)\n}\n\nexport type FindBorrowedDefaultsParams = {\n defaultModels: DefaultModels\n targets: readonly Harness[]\n harnesses: readonly Harness[]\n models: readonly ModelInfo[]\n protocols: readonly Protocol[]\n}\n\n/**\n * Other agents' defaults, offered as picker rows. A router already has its row, an own default was\n * just turned down, and a model the list says the targets cannot use would only fail.\n */\nexport function findBorrowedDefaults(params: FindBorrowedDefaultsParams): ModelSuggestion[] {\n const { defaultModels, targets, models, protocols } = params\n const targetIds = new Set(targets.map((harness) => harness.id))\n const ownModels = new Set(targets.flatMap((harness) => defaultModels[harness.id] ?? []))\n const others = params.harnesses.filter((harness) => !targetIds.has(harness.id))\n\n return groupByModel(defaultModels, others).filter(\n ({ model }) => !ownModels.has(model) && !isPredefinedModel(model) && isServed({ model, models, protocols }),\n )\n}\n\ntype IsServedParams = { model: string; models: readonly ModelInfo[]; protocols: readonly Protocol[] }\n\nfunction isServed({ model, models, protocols }: IsServedParams): boolean {\n if (models.length === 0) return true\n\n const listed = models.find((candidate) => candidate.id === model)\n return listed !== undefined && isModelCompatible(listed, protocols)\n}\n\nfunction groupByModel(defaultModels: DefaultModels, harnesses: readonly Harness[]): ModelSuggestion[] {\n const labelsByModel = new Map<string, string[]>()\n for (const harness of harnesses) {\n const model = defaultModels[harness.id]\n if (model !== undefined) labelsByModel.set(model, [...(labelsByModel.get(model) ?? []), harness.label])\n }\n\n return [...labelsByModel].map(([model, labels]) => ({ model, hint: `default for ${labels.join(', ')}` }))\n}\n","import type { CliOptions } from '../../cli/parse-cli-arguments'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport { isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport type { Masker } from '../../product/secrets/masker'\nimport {\n PreferencesError,\n readDefaultModels,\n saveDefaultModels,\n type DefaultModels,\n} from '../../product/storage/preferences/preferences'\nimport { describeFileError, type FileAction } from '../../shared/file-system/describe-file-error'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { findOwnDefaults } from './suggest-defaults'\n\nexport type ModelSource = 'flag' | 'env' | 'default' | 'picked'\n\n/** `isReadable` is false for a file that could not be read: nothing is offered from it or saved over it. */\nexport type ModelPreferences = { defaultModels: DefaultModels; isReadable: boolean }\n\nexport function loadModelPreferences(home: string, ui: TerminalUi): ModelPreferences {\n try {\n return { defaultModels: readDefaultModels(home), isReadable: true }\n } catch (error) {\n ui.log.warn(\n `${describePreferencesError({ error, action: 'read', home })} ` +\n 'Default models are neither offered nor saved until then.',\n )\n return { defaultModels: {}, isReadable: false }\n }\n}\n\nexport type RequestModelParams = {\n flagModel: string | undefined\n envModel: string | undefined\n targets: readonly ConfigurableHarness[]\n preferences: ModelPreferences\n shouldAssumeYes: boolean\n ui: TerminalUi\n}\n\nexport type RequestedModel = { model: string; source: Exclude<ModelSource, 'picked'> }\n\n/** The model settled before the key check; undefined leaves it to the picker. */\nexport async function requestModel(params: RequestModelParams): Promise<RequestedModel | undefined> {\n const { targets, preferences, ui } = params\n if (params.flagModel !== undefined) return { model: params.flagModel, source: 'flag' }\n if (params.envModel !== undefined) return { model: params.envModel, source: 'env' }\n\n const ownDefaults = findOwnDefaults(preferences.defaultModels, targets).filter(\n ({ model }) => !isPredefinedModel(model),\n )\n if (ownDefaults.length === 0) return undefined\n if (params.shouldAssumeYes) {\n const shared = findSharedDefault(preferences.defaultModels, targets)\n return shared === undefined ? undefined : { model: shared, source: 'default' }\n }\n\n const chosen = await ui.chooseSavedModel(ownDefaults)\n return chosen === undefined ? undefined : { model: chosen, source: 'default' }\n}\n\n/** `--yes` never picks between defaults, nor borrows one for an agent that has none. */\nfunction findSharedDefault(defaultModels: DefaultModels, targets: readonly ConfigurableHarness[]): string | undefined {\n const [first, ...rest] = targets.map((harness) => defaultModels[harness.id])\n if (first === undefined || isPredefinedModel(first)) return undefined\n return rest.every((model) => model === first) ? first : undefined\n}\n\nexport type DecideModelSaveParams = {\n model: string\n source: ModelSource\n targets: readonly ConfigurableHarness[]\n preferences: ModelPreferences\n options: Pick<CliOptions, 'shouldSaveModel' | 'shouldAssumeYes' | 'isDryRun'>\n ui: TerminalUi\n}\n\n/** The agents to save the model for. Asked only after a pick, default No; `--save-model` says yes without asking. */\nexport async function decideModelSave(params: DecideModelSaveParams): Promise<ConfigurableHarness[]> {\n const { model, preferences, options, ui } = params\n if (!preferences.isReadable) return []\n if (isPredefinedModel(model)) return []\n\n const changed = params.targets.filter((harness) => preferences.defaultModels[harness.id] !== model)\n if (changed.length === 0) return []\n if (options.shouldSaveModel) return changed\n if (params.source !== 'picked' || options.shouldAssumeYes || options.isDryRun) return []\n\n const labels = changed.map((harness) => harness.label).join(', ')\n return (await ui.confirm(`Make ${model} your default for ${labels}?`, false)) ? changed : []\n}\n\nexport type CommitModelSaveParams = {\n model: string\n harnesses: readonly ConfigurableHarness[]\n home: string\n ui: TerminalUi\n masker: Masker\n}\n\n/** A default is a convenience: failing to save one warns and never fails the run. */\nexport function commitModelSave({ model, harnesses, home, ui, masker }: CommitModelSaveParams): void {\n if (harnesses.length === 0) return\n\n const labels = harnesses.map((harness) => harness.label).join(', ')\n try {\n saveDefaultModels({ home, defaultModels: Object.fromEntries(harnesses.map((harness) => [harness.id, model])) })\n ui.log.success(masker.maskText(`Saved ${model} as the default model for ${labels}.`))\n } catch (error) {\n const reason = describePreferencesError({ error, action: 'write', home })\n ui.log.warn(masker.maskText(`Couldn't save ${model} as the default model: ${reason}`))\n }\n}\n\ntype DescribePreferencesErrorParams = { error: unknown; action: FileAction; home: string }\n\nfunction describePreferencesError({ error, action, home }: DescribePreferencesErrorParams): string {\n return error instanceof PreferencesError ? error.message : describeFileError({ error, action, home })\n}\n","import type { CliOptions } from '../../cli/parse-cli-arguments'\nimport type { ConfigurableHarness } from '../../harnesses/harness'\nimport { harnesses } from '../../harnesses/registry'\nimport type { GatewayUrls } from '../../product/gateway/desired-config'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport { DEFAULT_MODEL, isPredefinedModel } from '../../product/gateway/models/predefined-models'\nimport { PROTOCOLS } from '../../product/gateway/models/protocol'\nimport type { ProbeResult } from '../../product/gateway/probe-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatProbes } from '../../ui/report/format-probes'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { checkKey, skippedKeyCheck, type KeyCheck } from '../key/key-check'\nimport {\n adoptKey,\n isKeyUsable,\n replaceRejectedKey,\n type CheckOutcome,\n type KeyStepRun,\n type ResolvedKey,\n} from '../key/key-step'\nimport { chooseModel, findModelWarnings } from './model-choice'\nimport { probeModel, probeRouter, shouldContinueAfterProbe, type RouterProbe } from './model-probe'\nimport { decideModelSave, requestModel, type ModelPreferences } from './model-step'\nimport { findBorrowedDefaults } from './suggest-defaults'\n\nexport type ChooseCheckedModelParams = {\n keyStep: KeyStepRun\n configurable: readonly ConfigurableHarness[]\n envModel: string | undefined\n preferences: ModelPreferences\n gatewayUrls: GatewayUrls\n options: Pick<CliOptions, 'model' | 'shouldVerify' | 'shouldAssumeYes' | 'shouldSaveModel' | 'isDryRun'>\n /** What still happens when the user continues past a failed model probe. */\n probeConsequence: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\nexport type ModelDecision =\n | {\n kind: 'chosen'\n model: string\n resolvedKey: ResolvedKey\n check: CheckOutcome\n /** The agents to save the model for once the run goes ahead. */\n modelSave: ConfigurableHarness[]\n }\n | { kind: 'declined' }\n | { kind: 'aborted' }\n\nexport async function chooseCheckedModel(params: ChooseCheckedModelParams): Promise<ModelDecision> {\n const { keyStep, configurable, preferences, gatewayUrls, options, ui, masker } = params\n const gatewayParams = { ui, masker, fetch: params.fetch }\n const requested = await requestModel({\n flagModel: options.model,\n envModel: params.envModel,\n targets: configurable,\n preferences,\n shouldAssumeYes: options.shouldAssumeYes,\n ui,\n })\n const requestedModel = requested?.model\n const keyCheck: KeyCheck = options.shouldVerify\n ? await checkKey({\n ...gatewayParams,\n openaiBaseUrl: gatewayUrls.openaiBaseUrl,\n requestedModel,\n shouldAssumeYes: options.shouldAssumeYes,\n resolved: keyStep.resolved,\n onSavedKeyRejected: async (rejected, probe) => {\n const replaced = await replaceRejectedKey({ input: keyStep.input, rejected, probe, deps: keyStep.deps })\n if (replaced === null) return null\n if (!isKeyUsable(replaced.key)) return null\n adoptKey(replaced.key, { ui, masker })\n return replaced\n },\n })\n : skippedKeyCheck(keyStep.resolved)\n if (keyCheck.isAborted) return { kind: 'aborted' }\n\n const routerProbe = await probeRouterIfOffered({\n keyCheck,\n requestedModel,\n anthropicBaseUrl: gatewayUrls.anthropicBaseUrl,\n ui,\n masker,\n fetch: params.fetch,\n })\n const routerAvailability = routerProbe?.availability ?? 'unknown'\n\n const protocols = PROTOCOLS.filter((protocol) => configurable.some((harness) => harness.protocols.includes(protocol)))\n const suggestions = findBorrowedDefaults({\n defaultModels: preferences.defaultModels,\n targets: configurable,\n harnesses,\n models: keyCheck.models,\n protocols,\n })\n const { shouldAssumeYes } = options\n const model = await chooseModel({\n keyCheck,\n requestedModel,\n routerAvailability,\n shouldAssumeYes,\n protocols,\n suggestions,\n ui,\n })\n for (const warning of findModelWarnings({ model, models: keyCheck.models, configurable, routerAvailability })) {\n ui.log.warn(masker.maskText(warning))\n }\n\n const source = requested?.source ?? 'picked'\n const modelSave = await decideModelSave({ model, source, targets: configurable, preferences, options, ui })\n const chosen = {\n kind: 'chosen',\n model,\n resolvedKey: keyCheck.resolvedKey,\n check: keyCheck.outcome,\n modelSave,\n } as const\n if (!options.shouldVerify || !protocols.includes('anthropic')) {\n printProbes(keyCheck.probes, ui)\n return chosen\n }\n\n const reusedRouterProbe = model === DEFAULT_MODEL ? routerProbe : undefined\n const probe =\n reusedRouterProbe === undefined\n ? await probeModel({\n ...gatewayParams,\n anthropicBaseUrl: gatewayUrls.anthropicBaseUrl,\n model,\n key: keyCheck.resolvedKey.key,\n })\n : reusedRouterProbe.probe\n printProbes([...keyCheck.probes, probe], ui)\n\n if (reusedRouterProbe !== undefined && routerAvailability === 'unknown') return chosen\n\n const shouldContinue = await shouldContinueAfterProbe({\n probe,\n shouldAssumeYes,\n consequence: params.probeConsequence,\n ui,\n })\n return shouldContinue ? chosen : { kind: 'declined' }\n}\n\nfunction printProbes(probes: readonly ProbeResult[], ui: TerminalUi): void {\n if (probes.length > 0) ui.print(formatProbes(probes))\n}\n\ntype ProbeRouterIfOfferedParams = {\n keyCheck: KeyCheck\n requestedModel: string | undefined\n anthropicBaseUrl: string\n ui: TerminalUi\n masker: Masker\n fetch: Fetch\n}\n\nasync function probeRouterIfOffered({\n keyCheck,\n requestedModel,\n anthropicBaseUrl,\n ui,\n masker,\n fetch,\n}: ProbeRouterIfOfferedParams): Promise<RouterProbe | undefined> {\n if (keyCheck.outcome !== 'passed') return undefined\n if (requestedModel !== undefined && !isPredefinedModel(requestedModel)) return undefined\n\n return await probeRouter({ anthropicBaseUrl, key: keyCheck.resolvedKey.key, ui, masker, fetch })\n}\n","import path from 'node:path'\nimport { ENV_DIRECTORY_NAME, type Shell } from './syntax/env-syntax'\nimport { ENV_SYNTAXES } from './syntax/env-syntaxes'\n\nexport function resolveEnvFilePath(home: string, shell: Shell): string {\n return path.join(home, ENV_DIRECTORY_NAME, ENV_SYNTAXES[shell].fileName)\n}\n","import { GATEWAY_ENV_VARIABLE, parseEnvironmentKey, readEnvironmentInputs } from '../../cli/environment'\nimport { EXIT_CODE } from '../../cli/exit-code'\nimport type { CliOptions } from '../../cli/parse-cli-arguments'\nimport { refusePrompts } from '../../cli/refuse-prompts'\nimport { findExistingKeys } from '../../flows/key/find-existing-keys'\nimport {\n adoptKey,\n commitSave,\n isKeyUsable,\n resolveKey,\n type KeyStepDeps,\n type KeyStepInput,\n} from '../../flows/key/key-step'\nimport { chooseCheckedModel } from '../../flows/model/choose-checked-model'\nimport { commitModelSave, loadModelPreferences } from '../../flows/model/model-step'\nimport type { LaunchingHarness, LaunchRecipe } from '../../harnesses/harness'\nimport type { LaunchResult } from '../../harnesses/run-launch'\nimport { GATEWAY_HOST, buildDesiredConfig, buildGatewayUrls } from '../../product/gateway/desired-config'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport type { Masker } from '../../product/secrets/masker'\nimport { resolveEnvFilePath } from '../../product/storage/env-file/env-file-path'\nimport { resolveShell } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport type { Keystore } from '../../product/storage/keychain/keystore'\nimport type { EnvironmentVariables, PlatformContext } from '../../shared/platform/platform-context'\nimport type { TerminalUi } from '../../ui/terminal-ui'\n\nexport type LaunchOptions = Pick<\n CliOptions,\n 'key' | 'model' | 'shouldSaveKey' | 'shouldSaveModel' | 'shouldVerify' | 'shouldAssumeYes'\n>\n\nexport type LaunchInput = {\n harness: LaunchingHarness\n passthrough: readonly string[]\n options: LaunchOptions\n env: EnvironmentVariables\n}\n\nexport type LaunchDeps = {\n keystore: Keystore\n ui: TerminalUi\n masker: Masker\n ctx: PlatformContext\n fetch: Fetch\n runLaunch(recipe: LaunchRecipe, passthrough: readonly string[]): Promise<LaunchResult>\n}\n\nconst DESTINATION = 'It is passed to the agent for this run and is not written to any agent config.'\n\nexport async function launch(input: LaunchInput, rawDeps: LaunchDeps): Promise<LaunchResult> {\n const { harness, options } = input\n const { masker, ctx } = rawDeps\n const ui = ctx.isInteractive ? rawDeps.ui : refusePrompts(rawDeps.ui)\n\n // Checked first, so nobody pastes a key for an agent that is not there.\n if (!ctx.hasBinary(harness.binary)) {\n ui.log.error(`${harness.binary} not found on PATH. Install ${harness.label} first.`)\n return { code: EXIT_CODE.failed }\n }\n\n const environment = readEnvironmentInputs(input.env)\n const gatewayUrls = buildGatewayUrls(environment.gatewayHost ?? GATEWAY_HOST)\n if (environment.gatewayHost !== undefined) {\n ui.log.warn(masker.maskText(`Using the gateway at ${environment.gatewayHost} — $${GATEWAY_ENV_VARIABLE} is set.`))\n }\n const keyDeps: KeyStepDeps = { keystore: rawDeps.keystore, ui, masker }\n const keyInput = aKeyStepInput({ ctx, options, environmentKey: environment.key, masker })\n const resolved = await resolveKey(keyInput, keyDeps)\n if (!isKeyUsable(resolved.key)) {\n ui.cancel('No API key provided.')\n return { code: EXIT_CODE.failed }\n }\n adoptKey(resolved.key, { ui, masker })\n\n const decision = await chooseCheckedModel({\n keyStep: { input: keyInput, deps: keyDeps, resolved },\n configurable: [harness],\n envModel: environment.model,\n preferences: loadModelPreferences(ctx.home, ui),\n gatewayUrls,\n options: { ...options, isDryRun: false },\n probeConsequence: 'The agent will still start.',\n ui,\n masker,\n fetch: rawDeps.fetch,\n })\n if (decision.kind === 'declined') {\n ui.cancel('Aborted — the agent was not started.')\n return { code: EXIT_CODE.cancelled }\n }\n if (decision.kind === 'aborted') return { code: EXIT_CODE.failed }\n\n await commitSave(decision.resolvedKey, decision.check, keyDeps)\n commitModelSave({ model: decision.model, harnesses: decision.modelSave, home: ctx.home, ui, masker })\n\n const desired = buildDesiredConfig({ gatewayUrls, apiKey: decision.resolvedKey.key, model: decision.model })\n const recipe = harness.launch(desired)\n if (harness.launchNotes !== undefined) {\n ui.note(harness.launchNotes.join('\\n'), 'Nothing is written to your config, but')\n }\n return await rawDeps.runLaunch(recipe, input.passthrough)\n}\n\ntype KeyStepInputParams = {\n ctx: PlatformContext\n options: LaunchOptions\n environmentKey: string | undefined\n masker: Masker\n}\n\nfunction aKeyStepInput({ ctx, options, environmentKey, masker }: KeyStepInputParams): KeyStepInput {\n const shell = resolveShell(ctx.platform)\n const existingKeys = findExistingKeys({ ctx, envPath: resolveEnvFilePath(ctx.home, shell), shell })\n masker.registerSecrets(existingKeys.all)\n\n return {\n flagKey: options.key,\n envKey: options.key === undefined ? parseEnvironmentKey(environmentKey) : undefined,\n shouldSaveKey: options.shouldSaveKey,\n shouldAssumeYes: options.shouldAssumeYes,\n isDryRun: false,\n existingKeys: () => existingKeys,\n destination: DESTINATION,\n }\n}\n","import path from 'node:path'\nimport { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport { TAGLINE } from '../../cli/help'\nimport type { CliOptions } from '../../cli/parse-cli-arguments'\nimport { refusePrompts } from '../../cli/refuse-prompts'\nimport { resolveNamedHarnesses } from '../../cli/resolve-named-harnesses'\nimport type { Harness } from '../../harnesses/harness'\nimport { findHarness } from '../../harnesses/registry'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatBackupTimestamp, resolveBackupRoot } from '../../product/storage/backups/resolve-backup-root'\nimport { resolveEnvFilePath } from '../../product/storage/env-file/env-file-path'\nimport { resolveShell } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport {\n createEmptyRestoreRecord,\n readRestoreRecord,\n RestoreRecordError,\n type RestoreRecord,\n} from '../../product/storage/restore-record/restore-record'\nimport { resolveRestoreRecordLocation } from '../../product/storage/restore-record/restore-record-location'\nimport { DEFAULT_SCOPE, type ConfigScope, type PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatCount } from '../../shared/text/format-count'\nimport type { RestoreChoice } from '../../ui/prompts/select-restore-harnesses'\nimport { formatRestorePreview } from '../../ui/report/format-restore-preview'\nimport { formatRestoreResult } from '../../ui/report/format-restore-result'\nimport type { ResultMode } from '../../ui/report/format-result'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { applyRestore } from './apply-restore'\nimport { planRestore, type RestoreCandidate, type RestorePlan } from './restore-plan'\nimport { exitCodeForRestore, isPlannedRestore } from './restore-result'\nimport { listRestoreSecrets } from './restore-secrets'\n\nexport type RunRestoreParams = {\n options: CliOptions\n baseContext: PlatformContext\n ui: TerminalUi\n now: () => Date\n masker: Masker\n}\n\nconst FINISHED_WITH_ERRORS = 'Finished with errors.'\nconst DRY_RUN_OUTRO = 'Dry run — nothing was restored.'\nconst CONFIRMATION = 'Restore these files? Current versions are backed up first.'\n\nexport async function runRestore(params: RunRestoreParams): Promise<ExitCode> {\n const { options, masker } = params\n const ui = params.baseContext.isInteractive ? params.ui : refusePrompts(params.ui)\n ui.intro(TAGLINE)\n\n const namedHarnesses = resolveNamedHarnesses(options.harnessIds)\n const scope = await resolveRestoreScope({ options, baseContext: params.baseContext, ui })\n const ctx: PlatformContext = { ...params.baseContext, scope }\n const recordRead = readRecord(ctx)\n if (recordRead.kind === 'failed') {\n ui.log.error(masker.maskText(recordRead.error))\n ui.outro(FINISHED_WITH_ERRORS)\n return EXIT_CODE.failed\n }\n\n const { record } = recordRead\n if (namedHarnesses.length === 0 && Object.keys(record.harnesses).length === 0) {\n const recordPath = displayPath(resolveRestoreRecordLocation(ctx).filePath, ctx.home)\n ui.outro(`Nothing to restore — nexos-connect has not set up any agent at ${scope} scope (${recordPath}).`)\n return EXIT_CODE.ok\n }\n\n const candidates = await selectCandidates({\n namedHarnesses,\n record,\n ctx,\n shouldAssumeYes: options.shouldAssumeYes,\n ui,\n })\n if (candidates.length === 0) {\n ui.cancel('No agents selected — nothing to do.')\n return EXIT_CODE.ok\n }\n\n const run: RestoreRun = { ...params, ui, ctx }\n const plan = planSelected({ run, candidates, record })\n if (options.isDryRun) return report({ run, plan, mode: { kind: 'dry-run' }, outro: DRY_RUN_OUTRO })\n\n const hasChanges = plan.outcomes.some((outcome) => outcome.kind === 'restored')\n if (hasChanges && !options.shouldAssumeYes && !(await ui.confirm(CONFIRMATION, true))) {\n ui.cancel('Aborted — nothing was restored.')\n return EXIT_CODE.cancelled\n }\n\n const applied = applySelected(run, plan)\n const outro = exitCodeForRestore(applied.outcomes) === EXIT_CODE.ok ? 'Done.' : FINISHED_WITH_ERRORS\n const mode = { kind: 'written', backupRoot: applied.backupRoot } as const\n return report({ run, plan: { outcomes: applied.outcomes, envFile: applied.envFile }, mode, outro })\n}\n\ntype RestoreRun = RunRestoreParams & { ui: TerminalUi; ctx: PlatformContext }\n\ntype ResolveRestoreScopeParams = { options: CliOptions; baseContext: PlatformContext; ui: TerminalUi }\n\nasync function resolveRestoreScope({ options, baseContext, ui }: ResolveRestoreScopeParams): Promise<ConfigScope> {\n if (options.scope !== undefined) return options.scope\n if (options.shouldAssumeYes) return DEFAULT_SCOPE\n\n return await ui.selectRestoreScope({\n userAgents: listRecordedLabels({ ...baseContext, scope: 'user' }),\n projectAgents: listRecordedLabels({ ...baseContext, scope: 'project' }),\n })\n}\n\nfunction listRecordedLabels(ctx: PlatformContext): string[] {\n const recordRead = readRecord(ctx)\n if (recordRead.kind === 'failed') return []\n\n return Object.keys(recordRead.record.harnesses).map(labelOf)\n}\n\ntype RecordRead = { kind: 'read'; record: RestoreRecord } | { kind: 'failed'; error: string }\n\nfunction readRecord(ctx: PlatformContext): RecordRead {\n try {\n const record = readRestoreRecord({ filePath: resolveRestoreRecordLocation(ctx).filePath, home: ctx.home })\n return { kind: 'read', record: record ?? createEmptyRestoreRecord() }\n } catch (error) {\n if (!(error instanceof RestoreRecordError)) throw error\n return { kind: 'failed', error: error.message }\n }\n}\n\nfunction labelOf(harnessId: string): string {\n return findHarness(harnessId)?.label ?? harnessId\n}\n\ntype SelectCandidatesParams = {\n namedHarnesses: readonly Harness[]\n record: RestoreRecord\n ctx: PlatformContext\n shouldAssumeYes: boolean\n ui: TerminalUi\n}\n\nasync function selectCandidates(params: SelectCandidatesParams): Promise<RestoreCandidate[]> {\n const { namedHarnesses, record, ctx, ui } = params\n if (namedHarnesses.length > 0) return namedHarnesses.map((harness) => toCandidate(harness.id, record))\n\n const recordedIds = Object.keys(record.harnesses)\n if (params.shouldAssumeYes) return recordedIds.map((id) => toCandidate(id, record))\n\n const chosenIds = await ui.selectRestoreHarnesses(recordedIds.map((id) => describeChoice({ id, record, ctx })))\n return chosenIds.map((id) => toCandidate(id, record))\n}\n\nfunction toCandidate(id: string, record: RestoreRecord): RestoreCandidate {\n return { target: { id, label: labelOf(id) }, record: record.harnesses[id] ?? null }\n}\n\ntype DescribeChoiceParams = { id: string; record: RestoreRecord; ctx: PlatformContext }\n\nconst ENV_VARIABLES_HINT = 'environment variables'\n\n// Joined without fromRecordedPath's check: a hint only shows a path, and planning fails a path outside the root.\nfunction describeChoice({ id, record, ctx }: DescribeChoiceParams): RestoreChoice {\n const harness = record.harnesses[id]\n const root = resolveRestoreRecordLocation(ctx).root\n const files = (harness?.files ?? []).map((file) => displayPath(path.join(root, ...file.path), ctx.home))\n const variables = (harness?.envVariables.length ?? 0) > 0 ? [ENV_VARIABLES_HINT] : []\n return { value: id, label: labelOf(id), hint: [...files, ...variables].join(', ') }\n}\n\ntype PlanSelectedParams = { run: RestoreRun; candidates: readonly RestoreCandidate[]; record: RestoreRecord }\n\nfunction planSelected({ run, candidates, record }: PlanSelectedParams): RestorePlan {\n const { ctx, masker, ui } = run\n const shell = resolveShell(ctx.platform)\n const envPath = resolveEnvFilePath(ctx.home, shell)\n masker.registerSecrets(listRestoreSecrets({ record, ctx, envPath, shell }))\n\n const plan = planRestore({ candidates, record, ctx, envPath, shell })\n const files = plan.outcomes.flatMap((outcome) => (isPlannedRestore(outcome) ? outcome.files : []))\n const hasFailedAgent = plan.outcomes.some((outcome) => outcome.kind === 'failed')\n ui.print(\n formatRestorePreview({ files, envFile: plan.envFile, scope: ctx.scope, hasFailedAgent, home: ctx.home, masker }),\n )\n return plan\n}\n\nfunction applySelected(run: RestoreRun, plan: RestorePlan): ReturnType<typeof applyRestore> {\n const { options, ctx, ui } = run\n const backupRoot = resolveBackupRoot({\n scope: ctx.scope,\n home: ctx.home,\n cwd: ctx.cwd,\n stamp: formatBackupTimestamp(run.now()),\n backupDirectory: options.backupDirectory,\n })\n\n const spinner = ui.spinner()\n spinner.start('Backing up current versions and restoring…')\n const applied = applyRestore({ plan, ctx, backupRoot })\n spinner.stop(`Restored ${formatCount(applied.writtenCount, 'file')}.`)\n return applied\n}\n\ntype ReportParams = { run: RestoreRun; plan: RestorePlan; mode: ResultMode; outro: string }\n\nfunction report({ run, plan, mode, outro }: ReportParams): ExitCode {\n const { ui, ctx, masker } = run\n ui.print(formatRestoreResult({ outcomes: plan.outcomes, envFile: plan.envFile, mode, home: ctx.home, masker }))\n ui.outro(outro)\n return exitCodeForRestore(plan.outcomes)\n}\n","import type { Harness } from '../harnesses/harness'\nimport { findHarness, harnesses } from '../harnesses/registry'\nimport { UsageError } from './usage-error'\n\nexport function resolveNamedHarnesses(ids: readonly string[]): Harness[] {\n const unknownIds = ids.filter((id) => findHarness(id) === undefined)\n if (unknownIds.length > 0) {\n const noun = unknownIds.length === 1 ? 'id' : 'ids'\n const knownIds = harnesses.map((harness) => harness.id).join(', ')\n throw new UsageError(`Unknown agent ${noun}: ${unknownIds.join(', ')}. Known ids: ${knownIds}.`)\n }\n\n return ids.flatMap((id) => findHarness(id) ?? [])\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport type { ConfigScope } from '../../../shared/platform/platform-context'\n\nexport const PROJECT_BACKUP_DIRECTORY = '.nexos-backup'\nexport const USER_BACKUP_DIRECTORY = path.join('.nexos', 'backups')\n\nexport function formatBackupTimestamp(now: Date): string {\n return now.toISOString().replace(/[:.]/g, '-')\n}\n\nexport type ResolveBackupRootParams = {\n scope: ConfigScope\n home: string\n cwd: string\n stamp: string\n backupDirectory: string | undefined\n}\n\nexport type BackupRoot = {\n path: string\n gitIgnoredDirectory: string | null\n}\n\nexport function resolveBackupRoot({ scope, home, cwd, stamp, backupDirectory }: ResolveBackupRootParams): BackupRoot {\n if (backupDirectory !== undefined) {\n return { path: path.join(path.resolve(cwd, backupDirectory), stamp), gitIgnoredDirectory: null }\n }\n return match(scope)\n .returnType<BackupRoot>()\n .with('user', () => ({ path: path.join(home, USER_BACKUP_DIRECTORY, stamp), gitIgnoredDirectory: null }))\n .with('project', () => {\n const directory = path.join(cwd, PROJECT_BACKUP_DIRECTORY)\n return { path: path.join(directory, stamp), gitIgnoredDirectory: directory }\n })\n .exhaustive()\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport * as v from 'valibot'\nimport { CONFIG_FORMATS } from '../../../shared/file-formats/config-format'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport { resolveOwnerOnlyMode } from '../../../shared/file-system/resolve-owner-only-mode'\nimport { writeFileWithMode } from '../../../shared/file-system/write-file-with-mode'\nimport { displayPath } from '../../../shared/text/display-path'\n\nexport const FILE_ORIGINS = ['absent', 'blank', 'content'] as const\n\nexport type FileOrigin = (typeof FILE_ORIGINS)[number]\n\nconst RECORD_VERSION = 1\n\nconst SegmentsSchema = v.pipe(v.tupleWithRest([v.string()], v.string()), v.readonly())\n\nconst RecordedKeySchema = v.object({\n keyPath: SegmentsSchema,\n original: v.nullable(v.string()),\n createdParents: v.pipe(v.array(SegmentsSchema), v.readonly()),\n holdsSecret: v.boolean(),\n})\n\nconst RecordedFileSchema = v.object({\n path: SegmentsSchema,\n format: v.picklist(CONFIG_FORMATS),\n origin: v.picklist(FILE_ORIGINS),\n keys: v.pipe(v.array(RecordedKeySchema), v.readonly()),\n})\n\nconst RecordedEnvVariableSchema = v.object({ name: v.string(), original: v.nullable(v.string()) })\n\nconst HarnessRecordSchema = v.object({\n files: v.pipe(v.array(RecordedFileSchema), v.readonly()),\n envVariables: v.pipe(v.array(RecordedEnvVariableSchema), v.readonly()),\n})\n\nconst RestoreRecordSchema = v.object({\n version: v.literal(RECORD_VERSION),\n harnesses: v.record(v.string(), HarnessRecordSchema),\n})\n\nexport type RecordedPath = v.InferOutput<typeof SegmentsSchema>\n/** `holdsSecret` marks a key setup wrote the API key into, so whatever it held before may be a key too. */\nexport type RecordedKey = v.InferOutput<typeof RecordedKeySchema>\nexport type RecordedFile = v.InferOutput<typeof RecordedFileSchema>\nexport type RecordedEnvVariable = v.InferOutput<typeof RecordedEnvVariableSchema>\nexport type HarnessRecord = v.InferOutput<typeof HarnessRecordSchema>\nexport type RestoreRecord = v.InferOutput<typeof RestoreRecordSchema>\n\nexport function createEmptyRestoreRecord(): RestoreRecord {\n return { version: RECORD_VERSION, harnesses: {} }\n}\n\nexport class RestoreRecordError extends Error {\n override readonly name = 'RestoreRecordError'\n}\n\nexport type ReadRestoreRecordParams = { filePath: string; home: string }\n\nexport function readRestoreRecord({ filePath, home }: ReadRestoreRecordParams): RestoreRecord | null {\n const text = readFileIfExists(filePath)\n if (text === null) return null\n\n const shownPath = displayPath(filePath, home)\n const json = parseJson(text)\n if (isNewerRecord(json)) {\n throw new RestoreRecordError(`${shownPath} was written by a newer nexos-connect. Update it, then run again.`)\n }\n\n const parsed = v.safeParse(RestoreRecordSchema, json)\n if (!parsed.success) {\n throw new RestoreRecordError(\n `${shownPath} is not a restore record nexos-connect can read. Fix it, or move it aside to start a new one, ` +\n 'then run again.',\n )\n }\n return parsed.output\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n if (error instanceof SyntaxError) return undefined\n throw error\n }\n}\n\nconst VersionSchema = v.object({ version: v.number() })\n\nfunction isNewerRecord(json: unknown): boolean {\n const parsed = v.safeParse(VersionSchema, json)\n return parsed.success && parsed.output.version > RECORD_VERSION\n}\n\nexport type WriteRestoreRecordParams = { filePath: string; record: RestoreRecord; platform: NodeJS.Platform }\n\nconst RECORD_DIRECTORY_MODE = 0o700\nconst JSON_INDENT = 2\n\n/** A record with no harness left is deleted, so a full restore leaves no file behind. */\nexport function writeRestoreRecord({ filePath, record, platform }: WriteRestoreRecordParams): void {\n if (Object.keys(record.harnesses).length === 0) {\n fs.rmSync(filePath, { force: true })\n return\n }\n\n fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: RECORD_DIRECTORY_MODE })\n const content = `${JSON.stringify(record, null, JSON_INDENT)}\\n`\n writeFileWithMode({ filePath, content, mode: resolveOwnerOnlyMode(platform) })\n}\n","import { match } from 'ts-pattern'\nimport { parseJsonc, parseJsoncValue, readJsoncOriginals, renderJsonc, restoreJsonc } from './jsonc'\nimport type { KeyOriginal } from './key-original'\nimport type { KeyPathUpdates } from './key-path'\nimport { parseToml, parseTomlValue, readTomlOriginals, renderToml, restoreToml, type TomlUpdate } from './toml'\n\nexport const CONFIG_FORMATS = ['jsonc', 'toml'] as const\n\nexport type ConfigFormat = (typeof CONFIG_FORMATS)[number]\n\nexport type ConfigEdits =\n | { format: 'jsonc'; updates: KeyPathUpdates }\n | { format: 'toml'; updates: readonly TomlUpdate[] }\n\nexport function renderConfig(current: string | null, edits: ConfigEdits): string {\n return match(edits)\n .with({ format: 'jsonc' }, ({ updates }) => renderJsonc(current, updates))\n .with({ format: 'toml' }, ({ updates }) => renderToml(current, updates))\n .exhaustive()\n}\n\nexport function readOriginals(current: string | null, edits: ConfigEdits): KeyOriginal[] {\n const keyPaths = edits.updates.map(([keyPath]) => keyPath)\n return match(edits.format)\n .with('jsonc', () => readJsoncOriginals(current, keyPaths))\n .with('toml', () => readTomlOriginals(current, keyPaths))\n .exhaustive()\n}\n\nexport type RestoreConfigParams = { format: ConfigFormat; current: string; originals: readonly KeyOriginal[] }\n\nexport function restoreConfig({ format, current, originals }: RestoreConfigParams): string {\n return match(format)\n .with('jsonc', () => restoreJsonc(current, originals))\n .with('toml', () => restoreToml(current, originals))\n .exhaustive()\n}\n\nexport function isEmptyConfig(format: ConfigFormat, text: string): boolean {\n const document = match(format)\n .with('jsonc', () => parseJsonc(text))\n .with('toml', () => parseToml(text))\n .exhaustive()\n return Object.keys(document).length === 0\n}\n\nexport function parseValueSource(format: ConfigFormat, source: string): unknown {\n return match(format)\n .with('jsonc', () => parseJsoncValue(source))\n .with('toml', () => parseTomlValue(source))\n .exhaustive()\n}\n","import { match } from 'ts-pattern'\n\nconst OWNER_ONLY_MODE = 0o600\n\n// chmod on Windows only toggles the read-only bit, so 0600 there would claim a protection the ACL does not give.\nexport function resolveOwnerOnlyMode(platform: NodeJS.Platform): number | null {\n return match(platform)\n .returnType<number | null>()\n .with('win32', () => null)\n .otherwise(() => OWNER_ONLY_MODE)\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\n\nexport type WriteFileWithModeParams = { filePath: string; content: string; mode: number | null }\n\nexport function writeFileWithMode({ filePath, content, mode }: WriteFileWithModeParams): void {\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n if (mode === null) {\n fs.writeFileSync(filePath, content)\n return\n }\n\n // Before the write too, so the key never lands under looser bits; `mode` covers only a new file, through the umask.\n if (fs.existsSync(filePath)) fs.chmodSync(filePath, mode)\n fs.writeFileSync(filePath, content, { mode })\n fs.chmodSync(filePath, mode)\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { PROJECT_BACKUP_DIRECTORY } from '../backups/resolve-backup-root'\nimport { ENV_DIRECTORY_NAME } from '../env-file/syntax/env-syntax'\nimport type { RecordedPath } from './restore-record'\n\nexport const RESTORE_RECORD_FILE = 'restore-record.json'\n\nexport type RestoreRecordLocation = { filePath: string; root: string; gitIgnoredDirectory: string | null }\n\nexport function resolveRestoreRecordLocation(ctx: PlatformContext): RestoreRecordLocation {\n return match(ctx.scope)\n .returnType<RestoreRecordLocation>()\n .with('user', () => ({\n filePath: path.join(ctx.home, ENV_DIRECTORY_NAME, RESTORE_RECORD_FILE),\n root: ctx.home,\n gitIgnoredDirectory: null,\n }))\n .with('project', () => {\n const directory = path.join(ctx.cwd, PROJECT_BACKUP_DIRECTORY)\n return { filePath: path.join(directory, RESTORE_RECORD_FILE), root: ctx.cwd, gitIgnoredDirectory: directory }\n })\n .exhaustive()\n}\n\nexport function toRecordedPath(filePath: string, root: string): RecordedPath {\n const [first, ...rest] = path.relative(root, filePath).split(path.sep)\n if (first === undefined || !isInsideRoot(filePath, root)) {\n throw new Error(`${filePath} is outside ${root}, so it cannot be recorded for a restore.`)\n }\n return [first, ...rest]\n}\n\n// The record is a plain file, at project scope one a repository could ship, so its paths are not trusted.\nexport function fromRecordedPath(recordedPath: RecordedPath, root: string): string {\n const filePath = path.join(root, ...recordedPath)\n if (!isInsideRoot(filePath, root)) {\n throw new Error(\n `${filePath} is outside ${root}, so it cannot be restored. Remove it from the restore record, then run again.`,\n )\n }\n return filePath\n}\n\nfunction isInsideRoot(filePath: string, root: string): boolean {\n const relativePath = path.relative(root, filePath)\n const [first] = relativePath.split(path.sep)\n return relativePath !== '' && first !== '..' && !path.isAbsolute(relativePath)\n}\n","import pc from 'picocolors'\nimport type { RestoreEnvPlan, RestoreFilePlan } from '../../commands/restore/restore-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { ConfigScope } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatHeading } from './format-heading'\nimport { formatFileDiff } from './format-preview'\n\nexport type FormatRestorePreviewParams = {\n files: readonly RestoreFilePlan[]\n envFile: RestoreEnvPlan | null\n scope: ConfigScope\n hasFailedAgent: boolean\n home: string\n masker: Masker\n}\n\nconst NOTHING_TO_RESTORE = 'Nothing to change — every selected agent is already as it was.'\nconst NOTHING_TO_RESTORE_AFTER_FAILURE =\n 'Nothing to change — an agent failed while planning; the report below says why.'\n\nexport function formatRestorePreview(params: FormatRestorePreviewParams): string[] {\n const { files, envFile, scope, hasFailedAgent, home, masker } = params\n const heading = formatHeading(`Planned restore ${pc.dim(`(scope: ${scope})`)}`)\n const changedFiles = files.filter((file) => file.isChanged)\n const changedEnvFile = envFile?.isChanged === true ? [envFile] : []\n if (changedFiles.length === 0 && changedEnvFile.length === 0) {\n return [...heading, ` ${pc.dim(hasFailedAgent ? NOTHING_TO_RESTORE_AFTER_FAILURE : NOTHING_TO_RESTORE)}`]\n }\n\n return [\n ...heading,\n ...changedFiles.flatMap((file) => formatRestoredFile({ file, home, masker })),\n ...changedEnvFile.flatMap((change) => formatFileDiff({ change, home, masker })),\n ]\n}\n\nconst DELETION_NOTE = 'deleted — nexos-connect created it'\n\ntype FormatRestoredFileParams = { file: RestoreFilePlan; home: string; masker: Masker }\n\nfunction formatRestoredFile({ file, home, masker }: FormatRestoredFileParams): string[] {\n if (file.after === null) return ['', ` ${pc.bold(displayPath(file.path, home))} ${pc.dim(`(${DELETION_NOTE})`)}`]\n\n const change = { path: file.path, before: file.before, after: file.after, isChanged: file.isChanged }\n return formatFileDiff({ change, home, masker })\n}\n","import pc from 'picocolors'\nimport type { FilePlan } from '../../commands/setup/setup-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport type { ConfigScope } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatCount } from '../../shared/text/format-count'\nimport { countChangedLines, diffLines } from '../diff/diff-lines'\nimport { renderDiff } from '../diff/render-diff'\nimport { formatHeading } from './format-heading'\n\nexport type FormatPreviewParams = {\n changes: readonly FilePlan[]\n model: string\n scope: ConfigScope\n hasFailedAgent: boolean\n home: string\n masker: Masker\n}\n\nconst NOTHING_TO_CHANGE = 'Nothing to change — every selected agent is already configured or was skipped.'\nconst NOTHING_TO_CHANGE_AFTER_FAILURE = 'Nothing to change — an agent failed while planning; the report below says why.'\n\nexport function formatPreview({ changes, model, scope, hasFailedAgent, home, masker }: FormatPreviewParams): string[] {\n const heading = formatHeading(`Planned changes ${pc.dim(`(scope: ${scope}, model: ${masker.maskText(model)})`)}`)\n if (changes.length === 0) {\n const note = hasFailedAgent ? NOTHING_TO_CHANGE_AFTER_FAILURE : NOTHING_TO_CHANGE\n return [...heading, ` ${pc.dim(note)}`]\n }\n\n return [...heading, ...changes.flatMap((change) => formatFileDiff({ change, home, masker }))]\n}\n\nexport type FormatFileDiffParams = { change: FilePlan; home: string; masker: Masker }\n\nexport function formatFileDiff({ change, home, masker }: FormatFileDiffParams): string[] {\n const diff = diffLines({ before: masker.maskText(change.before ?? ''), after: masker.maskText(change.after) })\n const lineCount = formatCount(countChangedLines(diff), 'line')\n const lineCountNote = change.before === null ? `new file, ${lineCount}` : lineCount\n return ['', ` ${pc.bold(displayPath(change.path, home))} ${pc.dim(`(${lineCountNote})`)}`, ...renderDiff(diff)]\n}\n","export type DiffLine = { kind: 'unchanged' | 'added' | 'removed'; text: string }\n\nexport type DiffLinesParams = { before: string; after: string }\n\nexport function diffLines({ before, after }: DiffLinesParams): DiffLine[] {\n const beforeLines = splitTerminatedLines(before)\n const afterLines = splitTerminatedLines(after)\n const table = buildCommonLengthTable({ beforeLines, afterLines })\n\n const diff: DiffLine[] = []\n let beforeIndex = 0\n let afterIndex = 0\n while (beforeIndex < beforeLines.length && afterIndex < afterLines.length) {\n const beforeLine = beforeLines[beforeIndex]!\n const afterLine = afterLines[afterIndex]!\n if (beforeLine === afterLine) {\n diff.push(toDiffLine('unchanged', beforeLine))\n beforeIndex++\n afterIndex++\n } else if (table[beforeIndex + 1]![afterIndex]! >= table[beforeIndex]![afterIndex + 1]!) {\n diff.push(toDiffLine('removed', beforeLine))\n beforeIndex++\n } else {\n diff.push(toDiffLine('added', afterLine))\n afterIndex++\n }\n }\n for (const line of beforeLines.slice(beforeIndex)) diff.push(toDiffLine('removed', line))\n for (const line of afterLines.slice(afterIndex)) diff.push(toDiffLine('added', line))\n return diff\n}\n\nexport function countChangedLines(lines: readonly DiffLine[]): number {\n return lines.filter((line) => line.kind !== 'unchanged').length\n}\n\nconst TERMINATED_LINE_PATTERN = /[^\\n]*\\n|[^\\n]+$/g\nconst LINE_TERMINATOR = '\\n'\n\nfunction splitTerminatedLines(text: string): string[] {\n return text.match(TERMINATED_LINE_PATTERN) ?? []\n}\n\nfunction toDiffLine(kind: DiffLine['kind'], line: string): DiffLine {\n return { kind, text: line.endsWith(LINE_TERMINATOR) ? line.slice(0, -LINE_TERMINATOR.length) : line }\n}\n\ntype BuildCommonLengthTableParams = { beforeLines: readonly string[]; afterLines: readonly string[] }\n\nfunction buildCommonLengthTable({ beforeLines, afterLines }: BuildCommonLengthTableParams): number[][] {\n const table = Array.from({ length: beforeLines.length + 1 }, () =>\n Array.from({ length: afterLines.length + 1 }, () => 0),\n )\n for (let beforeIndex = beforeLines.length - 1; beforeIndex >= 0; beforeIndex--) {\n for (let afterIndex = afterLines.length - 1; afterIndex >= 0; afterIndex--) {\n if (beforeLines[beforeIndex] === afterLines[afterIndex]) {\n table[beforeIndex]![afterIndex] = table[beforeIndex + 1]![afterIndex + 1]! + 1\n } else {\n table[beforeIndex]![afterIndex] = Math.max(\n table[beforeIndex + 1]![afterIndex]!,\n table[beforeIndex]![afterIndex + 1]!,\n )\n }\n }\n }\n return table\n}\n","import pc from 'picocolors'\nimport { match } from 'ts-pattern'\nimport { GLYPHS } from '../glyphs'\nimport type { DiffLine } from './diff-lines'\n\nconst DIFF_CONTEXT_LINES = 2\nconst ADDED_PREFIX = ' + '\nconst REMOVED_PREFIX = ' - '\nconst UNCHANGED_PREFIX = ' '\n\nexport function renderDiff(lines: readonly DiffLine[]): string[] {\n const visibleIndexes = findVisibleIndexes(lines)\n if (visibleIndexes.size === 0) return [pc.dim(`${UNCHANGED_PREFIX}(no change)`)]\n\n const rendered: string[] = []\n let isSkipping = false\n for (const [index, line] of lines.entries()) {\n if (visibleIndexes.has(index)) {\n rendered.push(renderLine(line))\n isSkipping = false\n continue\n }\n if (!isSkipping) rendered.push(pc.dim(`${UNCHANGED_PREFIX}${GLYPHS.elided}`))\n isSkipping = true\n }\n return rendered\n}\n\nfunction findVisibleIndexes(lines: readonly DiffLine[]): Set<number> {\n const visibleIndexes = new Set<number>()\n for (const [index, line] of lines.entries()) {\n if (line.kind === 'unchanged') continue\n const first = Math.max(0, index - DIFF_CONTEXT_LINES)\n const last = Math.min(lines.length - 1, index + DIFF_CONTEXT_LINES)\n for (let visibleIndex = first; visibleIndex <= last; visibleIndex++) visibleIndexes.add(visibleIndex)\n }\n return visibleIndexes\n}\n\nfunction renderLine(line: DiffLine): string {\n return match(line.kind)\n .with('added', () => pc.green(`${ADDED_PREFIX}${line.text}`))\n .with('removed', () => pc.red(`${REMOVED_PREFIX}${line.text}`))\n .with('unchanged', () => pc.dim(`${UNCHANGED_PREFIX}${line.text}`))\n .exhaustive()\n}\n","import pc from 'picocolors'\nimport { P, match } from 'ts-pattern'\nimport {\n RESTORE_OUTCOME_KINDS,\n type PlannedRestore,\n type RestoreEnvPlan,\n type RestoreFilePlan,\n type RestoreOutcome,\n type RestoreOutcomeKind,\n} from '../../commands/restore/restore-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { parseEnvFile } from '../../product/storage/env-file/parse-env-file'\nimport { displayPath } from '../../shared/text/display-path'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport type { ResultMode } from './format-result'\nimport { INDENT } from './indent'\nimport type { StatusStyle } from './outcome-style'\n\nexport type FormatRestoreResultParams = {\n outcomes: readonly RestoreOutcome[]\n envFile: RestoreEnvPlan | null\n mode: ResultMode\n home: string\n masker: Masker\n}\n\nexport function formatRestoreResult(params: FormatRestoreResultParams): string[] {\n const heading = params.mode.kind === 'dry-run' ? 'Result (dry run)' : 'Result'\n return [\n ...formatHeading(heading),\n ...params.outcomes.flatMap((outcome) => formatOutcome(outcome, params)),\n ...formatEnvFileStep(params),\n ...formatBackups(params),\n ...formatSummary(params.outcomes),\n ]\n}\n\nconst RESTORE_OUTCOME_STYLE: Readonly<Record<RestoreOutcomeKind, StatusStyle>> = {\n restored: { glyph: GLYPHS.success, colour: pc.green, label: 'restored' },\n unchanged: { glyph: GLYPHS.unchanged, colour: pc.green, label: 'already as it was' },\n 'nothing-to-restore': { glyph: GLYPHS.absent, colour: pc.yellow, label: 'nothing to restore' },\n failed: { glyph: GLYPHS.failure, colour: pc.red, label: 'failed' },\n}\n\nconst NO_RECORD = 'nexos-connect has no record of setting it up at this scope.'\n\nfunction formatOutcome(outcome: RestoreOutcome, { home, masker }: FormatRestoreResultParams): string[] {\n const style = RESTORE_OUTCOME_STYLE[outcome.kind]\n const body = match(outcome)\n .with({ kind: P.union('restored', 'unchanged') }, (planned) => formatPlannedRestore(planned, home, masker))\n .with({ kind: 'nothing-to-restore' }, () => [`${INDENT}${pc.dim(NO_RECORD)}`])\n .with({ kind: 'failed' }, ({ error }) => [`${INDENT}${pc.red(masker.maskText(error))}`])\n .exhaustive()\n return ['', ` ${style.colour(`${style.glyph} ${outcome.target.label} — ${style.label}`)}`, ...body]\n}\n\nfunction formatPlannedRestore(outcome: PlannedRestore, home: string, masker: Masker): string[] {\n const restartNote = `Restart ${outcome.target.label} so it reads the restored config.`\n return [\n ...outcome.files.filter((file) => file.isChanged).map((file) => `${INDENT}${pc.dim(describeFile(file, home))}`),\n ...outcome.warnings.map((warning) => `${INDENT}${pc.yellow(`${GLYPHS.warning} ${masker.maskText(warning)}`)}`),\n ...(outcome.kind === 'restored' ? [`${INDENT}${pc.cyan(`${GLYPHS.next} ${restartNote}`)}`] : []),\n ]\n}\n\nfunction describeFile(file: RestoreFilePlan, home: string): string {\n const action = file.after === null ? 'deleted' : 'put back'\n return `${displayPath(file.path, home)} — ${action}`\n}\n\nfunction formatEnvFileStep({ envFile, mode, home }: FormatRestoreResultParams): string[] {\n if (mode.kind === 'dry-run' || envFile === null || !envFile.isChanged) return []\n\n const isEmpty = parseEnvFile(envFile.after, envFile.shell).size === 0\n const emptyNote = `${displayPath(envFile.path, home)} no longer sets anything: you can delete it, and the line that loads it.`\n return [\n ...formatHeading('One more step'),\n ...(isEmpty ? [` ${emptyNote}`] : []),\n ` ${pc.dim('Shells open now keep the variables it set; a new shell starts without them.')}`,\n ]\n}\n\nfunction formatBackups({ mode, home, masker }: FormatRestoreResultParams): string[] {\n if (mode.kind === 'dry-run' || mode.backupRoot === null) return []\n\n const backupRoot = masker.maskText(displayPath(mode.backupRoot, home))\n return [...formatHeading('Backups'), ` Current versions copied to ${pc.bold(backupRoot)}`]\n}\n\nfunction formatSummary(outcomes: readonly RestoreOutcome[]): string[] {\n const countsByKind = new Map<RestoreOutcomeKind, number>()\n for (const { kind } of outcomes) countsByKind.set(kind, (countsByKind.get(kind) ?? 0) + 1)\n\n const counts = RESTORE_OUTCOME_KINDS.map(\n (kind) => `${countsByKind.get(kind) ?? 0} ${RESTORE_OUTCOME_STYLE[kind].label}`,\n )\n return [...formatHeading('Summary'), ` ${counts.join(', ')}`]\n}\n","import { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedEnvVariable, RecordedPath } from '../../product/storage/restore-record/restore-record'\n\nexport type RestoreTarget = { id: string; label: string }\n\n/** `after` is `null` for a file nexos-connect created, which restore deletes. */\nexport type RestoreFilePlan = {\n path: string\n recordedPath: RecordedPath\n before: string\n after: string | null\n isChanged: boolean\n}\n\nexport type RestoreEnvPlan = { path: string; before: string; after: string; isChanged: boolean; shell: Shell }\n\nexport const RESTORE_OUTCOME_KINDS = ['restored', 'unchanged', 'nothing-to-restore', 'failed'] as const\n\nexport type RestoreOutcomeKind = (typeof RESTORE_OUTCOME_KINDS)[number]\n\nexport type PlannedRestore = {\n kind: 'restored' | 'unchanged'\n target: RestoreTarget\n files: readonly RestoreFilePlan[]\n envVariables: readonly RecordedEnvVariable[]\n warnings: readonly string[]\n}\n\nexport type NothingToRestore = { kind: 'nothing-to-restore'; target: RestoreTarget }\n\nexport type FailedRestore = { kind: 'failed'; target: RestoreTarget; error: string }\n\nexport type RestoreOutcome = PlannedRestore | NothingToRestore | FailedRestore\n\nexport function isPlannedRestore(outcome: RestoreOutcome): outcome is PlannedRestore {\n return outcome.kind === 'restored' || outcome.kind === 'unchanged'\n}\n\n// Only a named agent can come out with nothing to restore, and naming one asks for a restore that cannot happen.\nexport function exitCodeForRestore(outcomes: readonly RestoreOutcome[]): ExitCode {\n const isFailed = outcomes.some((outcome) => outcome.kind === 'failed' || outcome.kind === 'nothing-to-restore')\n return isFailed ? EXIT_CODE.failed : EXIT_CODE.ok\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { backUpBeforeWriting, ENV_FILE_BACKUP_DIRECTORY } from '../../product/storage/backups/back-up-before-writing'\nimport type { BackupRoot } from '../../product/storage/backups/resolve-backup-root'\nimport { writeEnvFile } from '../../product/storage/env-file/write-env-file'\nimport { removeHarnessRecords } from '../../product/storage/restore-record/remove-harness-records'\nimport { readRestoreRecord, writeRestoreRecord } from '../../product/storage/restore-record/restore-record'\nimport { resolveRestoreRecordLocation } from '../../product/storage/restore-record/restore-record-location'\nimport { describeFileError } from '../../shared/file-system/describe-file-error'\nimport { readFileMode } from '../../shared/file-system/read-file-mode'\nimport { writeFileWithMode } from '../../shared/file-system/write-file-with-mode'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { restoreEnvText } from './restore-env-text'\nimport type { RestorePlan } from './restore-plan'\nimport {\n isPlannedRestore,\n type RestoreEnvPlan,\n type RestoreFilePlan,\n type RestoreOutcome,\n type RestoreTarget,\n} from './restore-result'\n\nexport type ApplyRestoreParams = { plan: RestorePlan; ctx: PlatformContext; backupRoot: BackupRoot }\n\nexport type ApplyRestoreResult = {\n outcomes: RestoreOutcome[]\n envFile: RestoreEnvPlan | null\n writtenCount: number\n backupRoot: string | null\n}\n\nexport function applyRestore(params: ApplyRestoreParams): ApplyRestoreResult {\n const agentWrites = params.plan.outcomes.map((outcome) => restoreAgentFiles(outcome, params))\n const outcomes = agentWrites.map(({ outcome }) => outcome)\n const envFile = replanEnvFile(params.plan.envFile, outcomes)\n const envWrite = restoreSharedEnvFile({ outcomes, envFile, params })\n const writtenFiles = [...agentWrites.flatMap(({ writtenFiles }) => writtenFiles), ...envWrite.writtenFiles]\n return {\n outcomes: forgetRestored(envWrite.outcomes, params.ctx),\n envFile,\n writtenCount: writtenFiles.length,\n backupRoot: writtenFiles.some((file) => file.isBackedUp) ? params.backupRoot.path : null,\n }\n}\n\ntype WrittenFile = { isBackedUp: boolean }\n\ntype AgentWrite = { outcome: RestoreOutcome; writtenFiles: WrittenFile[] }\n\nfunction restoreAgentFiles(outcome: RestoreOutcome, params: ApplyRestoreParams): AgentWrite {\n if (outcome.kind !== 'restored') return { outcome, writtenFiles: [] }\n\n const writtenFiles: WrittenFile[] = []\n for (const file of outcome.files.filter((plan) => plan.isChanged)) {\n try {\n writtenFiles.push(restoreFile({ file, target: outcome.target, params }))\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: params.ctx.home })\n return { outcome: { kind: 'failed', target: outcome.target, error: reason }, writtenFiles }\n }\n }\n return { outcome, writtenFiles }\n}\n\ntype RestoreFileParams = { file: RestoreFilePlan; target: RestoreTarget; params: ApplyRestoreParams }\n\nfunction restoreFile({ file, target, params }: RestoreFileParams): WrittenFile {\n const { ctx, backupRoot } = params\n const relativePath = path.join(target.id, path.basename(file.path))\n const backup = backUpBeforeWriting({ filePath: file.path, before: file.before, backupRoot, relativePath, ctx })\n if (file.after === null) {\n fs.rmSync(file.path)\n return backup\n }\n\n writeFileWithMode({ filePath: file.path, content: file.after, mode: readFileMode(file.path, ctx.platform) })\n return backup\n}\n\n// Leaves out the variables of an agent whose files could not be restored, as setup leaves out a failed agent's.\nfunction replanEnvFile(envFile: RestoreEnvPlan | null, outcomes: readonly RestoreOutcome[]): RestoreEnvPlan | null {\n if (envFile === null) return null\n\n const variables = outcomes.flatMap((outcome) => (isPlannedRestore(outcome) ? outcome.envVariables : []))\n const after = restoreEnvText({ current: envFile.before, variables, shell: envFile.shell })\n return { ...envFile, after, isChanged: after !== envFile.before }\n}\n\ntype RestoreSharedEnvFileParams = {\n outcomes: RestoreOutcome[]\n envFile: RestoreEnvPlan | null\n params: ApplyRestoreParams\n}\n\ntype EnvWrite = { outcomes: RestoreOutcome[]; writtenFiles: WrittenFile[] }\n\nfunction restoreSharedEnvFile({ outcomes, envFile, params }: RestoreSharedEnvFileParams): EnvWrite {\n if (envFile === null || !envFile.isChanged) return { outcomes, writtenFiles: [] }\n\n const { ctx, backupRoot } = params\n try {\n const relativePath = path.join(ENV_FILE_BACKUP_DIRECTORY, path.basename(envFile.path))\n const backup = backUpBeforeWriting({\n filePath: envFile.path,\n before: envFile.before,\n backupRoot,\n relativePath,\n ctx,\n })\n writeEnvFile({ filePath: envFile.path, content: envFile.after, platform: ctx.platform })\n return { outcomes, writtenFiles: [backup] }\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: ctx.home })\n return { outcomes: outcomes.map((outcome) => failIfRestoringEnvFile(outcome, reason)), writtenFiles: [] }\n }\n}\n\nfunction failIfRestoringEnvFile(outcome: RestoreOutcome, error: string): RestoreOutcome {\n if (!isPlannedRestore(outcome) || outcome.envVariables.length === 0) return outcome\n\n return { kind: 'failed', target: outcome.target, error }\n}\n\n// A failed agent keeps its record, so a second restore can finish the job.\nfunction forgetRestored(outcomes: readonly RestoreOutcome[], ctx: PlatformContext): RestoreOutcome[] {\n const restoredIds = outcomes.filter(isPlannedRestore).map(({ target }) => target.id)\n if (restoredIds.length === 0) return [...outcomes]\n\n const { filePath } = resolveRestoreRecordLocation(ctx)\n try {\n const record = readRestoreRecord({ filePath, home: ctx.home })\n if (record !== null) {\n writeRestoreRecord({ filePath, record: removeHarnessRecords(record, restoredIds), platform: ctx.platform })\n }\n return [...outcomes]\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: ctx.home })\n return outcomes.map((outcome) => failIfPlanned(outcome, reason))\n }\n}\n\nfunction failIfPlanned(outcome: RestoreOutcome, error: string): RestoreOutcome {\n if (!isPlannedRestore(outcome)) return outcome\n\n return { kind: 'failed', target: outcome.target, error }\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport { readFileMode } from '../../../shared/file-system/read-file-mode'\n\nexport type BackUpFileParams = {\n source: string\n root: string\n relativePath: string\n platform: NodeJS.Platform\n}\n\nconst BACKUP_DIRECTORY_MODE = 0o700\nconst OWNER_PERMISSION_BITS = 0o700\n\nexport function backUpFile({ source, root, relativePath, platform }: BackUpFileParams): void {\n const destination = path.join(root, relativePath)\n fs.mkdirSync(path.dirname(destination), { recursive: true, mode: BACKUP_DIRECTORY_MODE })\n fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL)\n\n const mode = readFileMode(source, platform)\n if (mode !== null) fs.chmodSync(destination, mode & OWNER_PERMISSION_BITS)\n}\n\nconst IGNORE_EVERYTHING = '*\\n'\n\nexport function ignoreBackupsInGit(directory: string): void {\n const ignoreFile = path.join(directory, '.gitignore')\n if (fs.existsSync(ignoreFile)) return\n\n fs.mkdirSync(directory, { recursive: true, mode: BACKUP_DIRECTORY_MODE })\n fs.writeFileSync(ignoreFile, IGNORE_EVERYTHING)\n}\n","import fs from 'node:fs'\nimport { isMissingFileError } from './is-missing-file-error'\n\nconst PERMISSION_BITS = 0o777\n\nexport function readFileMode(filePath: string, platform: NodeJS.Platform): number | null {\n if (platform === 'win32') return null\n\n try {\n return fs.statSync(filePath).mode & PERMISSION_BITS\n } catch (error) {\n if (isMissingFileError(error)) return null\n throw error\n }\n}\n","import { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath } from '../../../shared/text/display-path'\nimport { backUpFile, ignoreBackupsInGit } from './back-up-file'\nimport type { BackupRoot } from './resolve-backup-root'\n\nexport const ENV_FILE_BACKUP_DIRECTORY = '_env'\n\nexport type BackUpBeforeWritingParams = {\n filePath: string\n before: string | null\n backupRoot: BackupRoot\n relativePath: string\n ctx: PlatformContext\n}\n\nexport type BackUpBeforeWritingResult = { isBackedUp: boolean }\n\n/** Throws, copying nothing, when the file no longer holds `before`: the preview did not show what it holds now. */\nexport function backUpBeforeWriting(params: BackUpBeforeWritingParams): BackUpBeforeWritingResult {\n const { filePath, before, backupRoot, ctx } = params\n assertUnchangedSincePreview({ filePath, before, home: ctx.home })\n if (before === null) return { isBackedUp: false }\n\n if (backupRoot.gitIgnoredDirectory !== null) ignoreBackupsInGit(backupRoot.gitIgnoredDirectory)\n backUpFile({ source: filePath, root: backupRoot.path, relativePath: params.relativePath, platform: ctx.platform })\n return { isBackedUp: true }\n}\n\ntype AssertUnchangedSincePreviewParams = { filePath: string; before: string | null; home: string }\n\nfunction assertUnchangedSincePreview({ filePath, before, home }: AssertUnchangedSincePreviewParams): void {\n if (readFileIfExists(filePath) === before) return\n\n throw new Error(\n `${displayPath(filePath, home)} changed after the preview, so it was left as it is. ` +\n 'Run again to see the new changes.',\n )\n}\n","import { resolveOwnerOnlyMode } from '../../../shared/file-system/resolve-owner-only-mode'\nimport { writeFileWithMode } from '../../../shared/file-system/write-file-with-mode'\n\nexport type WriteEnvFileParams = { filePath: string; content: string; platform: NodeJS.Platform }\n\nexport function writeEnvFile({ filePath, content, platform }: WriteEnvFileParams): void {\n writeFileWithMode({ filePath, content, mode: resolveOwnerOnlyMode(platform) })\n}\n","import type { RestoreRecord } from './restore-record'\n\nexport function removeHarnessRecords(record: RestoreRecord, harnessIds: readonly string[]): RestoreRecord {\n const harnesses = Object.fromEntries(Object.entries(record.harnesses).filter(([id]) => !harnessIds.includes(id)))\n return { ...record, harnesses }\n}\n","import { detectLineEnding, type LineEnding } from '../../../shared/file-formats/detect-line-ending'\nimport { splitByteOrderMark } from '../../../shared/file-formats/split-byte-order-mark'\nimport { splitLines } from './split-lines'\nimport { SHELLS, type EnvSyntax, type EnvVariable, type Shell } from './syntax/env-syntax'\nimport { ENV_SYNTAXES } from './syntax/env-syntaxes'\n\n/** Undefined removes the variable's assignments rather than writing one. */\nexport type EnvFileVariables = Readonly<Record<string, string | undefined>>\n\nexport type RenderEnvFileParams = { current: string | null; variables: EnvFileVariables; shell: Shell }\n\nexport function renderEnvFile({ current, variables, shell }: RenderEnvFileParams): string {\n const syntax = ENV_SYNTAXES[shell]\n const { byteOrderMark, body: existing } = splitByteOrderMark(current ?? '')\n const lineEnding = detectLineEnding(existing) ?? syntax.defaultLineEnding\n const removedNames = new Set(\n Object.entries(variables).flatMap(([name, value]) => (value === undefined ? [syntax.normalizeName(name)] : [])),\n )\n\n const bodyLines = splitLines(existing).filter(\n (line) => !isHeaderLine(line) && !isAssignmentOf({ line, names: removedNames, syntax }),\n )\n const { lines, missing } = replaceAssignments({ lines: bodyLines, variables, syntax })\n const body = appendMissing({ lines: trimBlankLines(lines), missing, syntax })\n\n return byteOrderMark + joinLines([...syntax.headerLines, ...body], lineEnding)\n}\n\nexport type RemoveEnvVariablesParams = { current: string; names: readonly string[]; shell: Shell }\n\nexport function removeEnvVariables({ current, names, shell }: RemoveEnvVariablesParams): string {\n const syntax = ENV_SYNTAXES[shell]\n const { byteOrderMark, body: existing } = splitByteOrderMark(current)\n const lineEnding = detectLineEnding(existing) ?? syntax.defaultLineEnding\n const removedNames = new Set(names.map((name) => syntax.normalizeName(name)))\n\n const bodyLines = splitLines(existing).filter(\n (line) => !isHeaderLine(line) && !isAssignmentOf({ line, names: removedNames, syntax }),\n )\n return byteOrderMark + joinLines([...syntax.headerLines, ...trimBlankLines(bodyLines)], lineEnding)\n}\n\nconst HEADER_LINES = SHELLS.flatMap((shell) => ENV_SYNTAXES[shell].headerLines)\n\nfunction isHeaderLine(line: string): boolean {\n return HEADER_LINES.some((headerLine) => line.startsWith(headerLine))\n}\n\ntype ReplaceAssignmentsParams = { lines: readonly string[]; variables: EnvFileVariables; syntax: EnvSyntax }\ntype ReplaceAssignmentsResult = { lines: string[]; missing: EnvVariable[] }\n\nfunction replaceAssignments(params: ReplaceAssignmentsParams): ReplaceAssignmentsResult {\n const { lines, variables, syntax } = params\n const pending = new Map(\n Object.entries(variables).flatMap(([name, value]) =>\n value === undefined ? [] : [[syntax.normalizeName(name), { name, value }] as const],\n ),\n )\n const replacedNames = new Set<string>()\n const kept: string[] = []\n\n for (const line of lines) {\n const name = matchNormalizedName(line, syntax)\n if (name !== undefined && replacedNames.has(name)) continue\n\n const variable = name === undefined ? undefined : pending.get(name)\n if (name === undefined || variable === undefined) {\n kept.push(line)\n continue\n }\n\n kept.push(syntax.formatAssignment(variable))\n pending.delete(name)\n replacedNames.add(name)\n }\n\n return { lines: kept, missing: [...pending.values()] }\n}\n\nfunction matchNormalizedName(line: string, syntax: EnvSyntax): string | undefined {\n const assignment = syntax.matchAssignment(line)\n if (assignment === undefined) return undefined\n return syntax.normalizeName(assignment.name)\n}\n\ntype IsAssignmentOfParams = { line: string; names: ReadonlySet<string>; syntax: EnvSyntax }\n\nfunction isAssignmentOf({ line, names, syntax }: IsAssignmentOfParams): boolean {\n const name = matchNormalizedName(line, syntax)\n return name !== undefined && names.has(name)\n}\n\nfunction trimBlankLines(lines: readonly string[]): readonly string[] {\n const firstIndex = lines.findIndex((line) => !isBlank(line))\n if (firstIndex === -1) return []\n\n const lastIndex = lines.findLastIndex((line) => !isBlank(line))\n return lines.slice(firstIndex, lastIndex + 1)\n}\n\nfunction isBlank(line: string): boolean {\n return line.trim() === ''\n}\n\ntype AppendMissingParams = { lines: readonly string[]; missing: readonly EnvVariable[]; syntax: EnvSyntax }\n\nfunction appendMissing({ lines, missing, syntax }: AppendMissingParams): readonly string[] {\n if (missing.length === 0) return lines\n\n const assignments = [...missing].sort(compareByName).map((variable) => syntax.formatAssignment(variable))\n if (lines.length === 0) return assignments\n return [...lines, '', ...assignments]\n}\n\nfunction compareByName(first: EnvVariable, second: EnvVariable): number {\n if (first.name < second.name) return -1\n if (first.name > second.name) return 1\n return 0\n}\n\nfunction joinLines(lines: readonly string[], lineEnding: LineEnding): string {\n return lines.map((line) => line + lineEnding).join('')\n}\n","import { removeEnvVariables, renderEnvFile } from '../../product/storage/env-file/render-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedEnvVariable } from '../../product/storage/restore-record/restore-record'\n\nexport type RestoreEnvTextParams = { current: string; variables: readonly RecordedEnvVariable[]; shell: Shell }\n\nexport function restoreEnvText({ current, variables, shell }: RestoreEnvTextParams): string {\n const withOriginals = setOriginalsBack({ current, variables, shell })\n const removedNames = variables.filter(({ original }) => original === null).map(({ name }) => name)\n if (removedNames.length === 0) return withOriginals\n\n return removeEnvVariables({ current: withOriginals, names: removedNames, shell })\n}\n\nfunction setOriginalsBack({ current, variables, shell }: RestoreEnvTextParams): string {\n const originals = Object.fromEntries(\n variables.flatMap(({ name, original }) => (original === null ? [] : [[name, original]])),\n )\n if (Object.keys(originals).length === 0) return current\n\n return renderEnvFile({ current, variables: originals, shell })\n}\n","import path from 'node:path'\nimport { match } from 'ts-pattern'\nimport { PROJECT_BACKUP_DIRECTORY, USER_BACKUP_DIRECTORY } from '../../product/storage/backups/resolve-backup-root'\nimport { NO_ENV_FILE, readEnvFile, type EnvFileRead } from '../../product/storage/env-file/read-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type {\n HarnessRecord,\n RecordedEnvVariable,\n RecordedFile,\n RestoreRecord,\n} from '../../product/storage/restore-record/restore-record'\nimport {\n fromRecordedPath,\n resolveRestoreRecordLocation,\n} from '../../product/storage/restore-record/restore-record-location'\nimport { ConfigFormatError } from '../../shared/file-formats/config-errors'\nimport { isEmptyConfig, restoreConfig } from '../../shared/file-formats/config-format'\nimport { describeFileError } from '../../shared/file-system/describe-file-error'\nimport { readFileIfExists } from '../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { displayPath } from '../../shared/text/display-path'\nimport { restoreEnvText } from './restore-env-text'\nimport {\n isPlannedRestore,\n type RestoreEnvPlan,\n type RestoreFilePlan,\n type RestoreOutcome,\n type RestoreTarget,\n} from './restore-result'\n\nexport type RestoreCandidate = { target: RestoreTarget; record: HarnessRecord | null }\n\nexport type PlanRestoreParams = {\n candidates: readonly RestoreCandidate[]\n record: RestoreRecord\n ctx: PlatformContext\n envPath: string\n shell: Shell\n}\n\nexport type RestorePlan = { outcomes: RestoreOutcome[]; envFile: RestoreEnvPlan | null }\n\nexport function planRestore(params: PlanRestoreParams): RestorePlan {\n const { candidates, ctx, envPath } = params\n const hasEnvVariables = candidates.some(({ record }) => (record?.envVariables.length ?? 0) > 0)\n const envFileRead = hasEnvVariables ? readEnvFile({ envPath, home: ctx.home }) : NO_ENV_FILE\n const namesKept = listNamesRecordedElsewhere(params)\n const outcomes = candidates.map((candidate) => planCandidate({ candidate, envFileRead, namesKept, params }))\n return { outcomes, envFile: planEnvFile({ outcomes, envFileRead, params }) }\n}\n\n// A variable another agent still has recorded is still that agent's, so restoring this one must leave it.\nfunction listNamesRecordedElsewhere({ candidates, record }: PlanRestoreParams): ReadonlySet<string> {\n const selectedIds = candidates.map(({ target }) => target.id)\n const others = Object.entries(record.harnesses).filter(([id]) => !selectedIds.includes(id))\n return new Set(others.flatMap(([, harness]) => harness.envVariables.map(({ name }) => name)))\n}\n\ntype PlanCandidateParams = {\n candidate: RestoreCandidate\n envFileRead: EnvFileRead\n namesKept: ReadonlySet<string>\n params: PlanRestoreParams\n}\n\nfunction planCandidate({ candidate, envFileRead, namesKept, params }: PlanCandidateParams): RestoreOutcome {\n const { target, record } = candidate\n if (record === null) return { kind: 'nothing-to-restore', target }\n\n const envVariables = record.envVariables.filter(({ name }) => !namesKept.has(name))\n if (envVariables.length > 0 && envFileRead.kind === 'failed') {\n return { kind: 'failed', target, error: envFileRead.error }\n }\n\n try {\n const { files, warnings } = planRecordedFiles(record.files, params.ctx)\n const hasEnvChange = hasOwnEnvChange({ envFileRead, envVariables, shell: params.shell })\n const isChanged = hasEnvChange || files.some((file) => file.isChanged)\n return { kind: isChanged ? 'restored' : 'unchanged', target, files, envVariables, warnings }\n } catch (error) {\n return { kind: 'failed', target, error: describeFileError({ error, action: 'read', home: params.ctx.home }) }\n }\n}\n\ntype HasOwnEnvChangeParams = {\n envFileRead: EnvFileRead\n envVariables: readonly RecordedEnvVariable[]\n shell: Shell\n}\n\nfunction hasOwnEnvChange({ envFileRead, envVariables, shell }: HasOwnEnvChangeParams): boolean {\n if (envFileRead.kind !== 'read' || envFileRead.text === null || envVariables.length === 0) return false\n\n return restoreEnvText({ current: envFileRead.text, variables: envVariables, shell }) !== envFileRead.text\n}\n\ntype PlannedFiles = { files: RestoreFilePlan[]; warnings: string[] }\n\nfunction planRecordedFiles(recordedFiles: readonly RecordedFile[], ctx: PlatformContext): PlannedFiles {\n const results = recordedFiles.map((file) => planRecordedFile(file, ctx))\n return {\n files: results.flatMap((result) => (result.kind === 'planned' ? [result.plan] : [])),\n warnings: results.flatMap((result) => (result.kind === 'missing' ? result.warnings : [])),\n }\n}\n\ntype RecordedFileResult = { kind: 'planned'; plan: RestoreFilePlan } | { kind: 'missing'; warnings: string[] }\n\nfunction planRecordedFile(file: RecordedFile, ctx: PlatformContext): RecordedFileResult {\n const filePath = fromRecordedPath(file.path, resolveRestoreRecordLocation(ctx).root)\n const before = readFileIfExists(filePath)\n if (before === null) {\n return { kind: 'missing', warnings: file.origin === 'content' ? [describeMissingFile(filePath, ctx)] : [] }\n }\n\n const after = restoreFile({ file, before, filePath, home: ctx.home })\n return {\n kind: 'planned',\n plan: { path: filePath, recordedPath: file.path, before, after, isChanged: before !== after },\n }\n}\n\nfunction describeMissingFile(filePath: string, ctx: PlatformContext): string {\n const backups = match(ctx.scope)\n .with('user', () => path.join(ctx.home, USER_BACKUP_DIRECTORY))\n .with('project', () => path.join(ctx.cwd, PROJECT_BACKUP_DIRECTORY))\n .exhaustive()\n return (\n `${displayPath(filePath, ctx.home)} no longer exists, so it was left as it is. Copies from before each run ` +\n `are under ${displayPath(backups, ctx.home)}, unless --backup-dir put them elsewhere.`\n )\n}\n\ntype RestoreFileParams = { file: RecordedFile; before: string; filePath: string; home: string }\n\nfunction restoreFile({ file, before, filePath, home }: RestoreFileParams): string | null {\n try {\n const restored = restoreConfig({ format: file.format, current: before, originals: file.keys })\n if (file.origin === 'content' || !isEmptyConfig(file.format, restored)) return restored\n\n return file.origin === 'blank' ? '' : null\n } catch (error) {\n if (!(error instanceof ConfigFormatError)) throw error\n throw new Error(`${displayPath(filePath, home)}: ${error.message}`, { cause: error })\n }\n}\n\ntype PlanEnvFileParams = { outcomes: readonly RestoreOutcome[]; envFileRead: EnvFileRead; params: PlanRestoreParams }\n\nfunction planEnvFile({ outcomes, envFileRead, params }: PlanEnvFileParams): RestoreEnvPlan | null {\n const variables = outcomes.flatMap((outcome) => (isPlannedRestore(outcome) ? outcome.envVariables : []))\n if (variables.length === 0 || envFileRead.kind === 'failed' || envFileRead.text === null) return null\n\n const before = envFileRead.text\n const after = restoreEnvText({ current: before, variables, shell: params.shell })\n return { path: params.envPath, before, after, isChanged: before !== after, shell: params.shell }\n}\n","import { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\n\nexport type EnvFileRead = { kind: 'read'; text: string | null } | { kind: 'failed'; error: string }\n\nexport const NO_ENV_FILE: EnvFileRead = { kind: 'read', text: null }\n\nexport type ReadEnvFileParams = { envPath: string; home: string }\n\nexport function readEnvFile({ envPath, home }: ReadEnvFileParams): EnvFileRead {\n try {\n return { kind: 'read', text: readFileIfExists(envPath) }\n } catch (error) {\n return { kind: 'failed', error: describeFileError({ error, action: 'read', home }) }\n }\n}\n","import { findExistingKeys } from '../../flows/key/find-existing-keys'\nimport { harnesses } from '../../harnesses/registry'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { HarnessRecord, RecordedFile, RestoreRecord } from '../../product/storage/restore-record/restore-record'\nimport { ConfigFormatError } from '../../shared/file-formats/config-errors'\nimport { parseValueSource } from '../../shared/file-formats/config-format'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\n\nexport type ListRestoreSecretsParams = { record: RestoreRecord; ctx: PlatformContext; envPath: string; shell: Shell }\n\n/** The keys a restore diff can show: the ones on disk now, and the ones the record puts back. */\nexport function listRestoreSecrets({ record, ctx, envPath, shell }: ListRestoreSecretsParams): string[] {\n const recorded = Object.values(record.harnesses).flatMap((harness) => [\n ...harness.files.flatMap(listFileSecrets),\n ...listEnvSecrets(harness),\n ])\n return [...findExistingKeys({ ctx, envPath, shell }).all, ...recorded]\n}\n\nfunction listFileSecrets(file: RecordedFile): string[] {\n return file.keys.flatMap(({ original, holdsSecret }) => {\n if (!holdsSecret || original === null) return []\n\n const value = readOriginalValue(file, original)\n return typeof value === 'string' ? [value] : []\n })\n}\n\n// An original that no longer parses fails its agent when the restore is planned, which reports it.\nfunction readOriginalValue(file: RecordedFile, original: string): unknown {\n try {\n return parseValueSource(file.format, original)\n } catch (error) {\n if (error instanceof ConfigFormatError) return undefined\n throw error\n }\n}\n\nconst KEY_ENV_VARIABLES = harnesses.flatMap((harness) =>\n harness.kind === 'configurable' && harness.keyEnvVariable !== undefined ? [harness.keyEnvVariable] : [],\n)\n\nfunction listEnvSecrets(harness: HarnessRecord): string[] {\n return harness.envVariables.flatMap(({ name, original }) =>\n KEY_ENV_VARIABLES.includes(name) && original !== null ? [original] : [],\n )\n}\n","import pc from 'picocolors'\nimport type { DetectedHarness, Detection } from '../../commands/setup/answers/harness-selection'\nimport type { Harness } from '../../harnesses/harness'\nimport type { Masker } from '../../product/secrets/masker'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport { INDENT } from './indent'\nimport type { StatusStyle } from './outcome-style'\n\nexport function formatDetection(rows: readonly DetectedHarness[], masker: Masker): string[] {\n return [\n ...formatHeading('Where each agent keeps its settings'),\n ...rows.flatMap((row) => formatDetectionRow(row, masker)),\n ]\n}\n\nconst LABEL_COLUMN_WIDTH = 24\n\ntype DetectionStatus = Detection['kind'] | 'not-configurable'\n\nconst DETECTION_STYLE: Readonly<Record<DetectionStatus, StatusStyle>> = {\n found: { glyph: GLYPHS.success, colour: pc.green, label: 'found' },\n 'not-found': { glyph: GLYPHS.absent, colour: pc.dim, label: 'not found' },\n failed: { glyph: GLYPHS.failure, colour: pc.red, label: 'could not check' },\n 'not-configurable': { glyph: GLYPHS.failure, colour: pc.yellow, label: 'not configurable' },\n}\n\nfunction formatDetectionRow({ harness, detection }: DetectedHarness, masker: Masker): string[] {\n const style = DETECTION_STYLE[findDetectionStatus(harness, detection)]\n return [\n ` ${style.colour(style.glyph)} ${harness.label.padEnd(LABEL_COLUMN_WIDTH)} ${style.colour(style.label)}`,\n `${INDENT}${pc.dim(masker.maskText(detection.detail))}`,\n ]\n}\n\nfunction findDetectionStatus(harness: Harness, detection: Detection): DetectionStatus {\n if (harness.kind === 'unsupported' && detection.kind !== 'failed') return 'not-configurable'\n\n return detection.kind\n}\n","import pc from 'picocolors'\nimport { P, match } from 'ts-pattern'\nimport {\n OUTCOME_KINDS,\n type EnvPlan,\n type HarnessOutcome,\n type OutcomeKind,\n type PlannedOutcome,\n} from '../../commands/setup/setup-result'\nimport type { Masker } from '../../product/secrets/masker'\nimport { ENV_SYNTAXES } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport { displayPath } from '../../shared/text/display-path'\nimport { formatList } from '../format-list'\nimport { GLYPHS } from '../glyphs'\nimport { formatHeading } from './format-heading'\nimport { INDENT, NESTED_INDENT, indentLines } from './indent'\nimport { OUTCOME_STYLE } from './outcome-style'\n\nexport type ResultMode = { kind: 'dry-run' } | { kind: 'written'; backupRoot: string | null }\n\nexport type RunHint = { binary: string; label: string }\n\nexport type FormatResultParams = {\n outcomes: readonly HarnessOutcome[]\n envFile: EnvPlan | null\n mode: ResultMode\n home: string\n masker: Masker\n runHints: readonly RunHint[]\n}\n\nexport function formatResult(params: FormatResultParams): string[] {\n const heading = params.mode.kind === 'dry-run' ? 'Result (dry run)' : 'Result'\n return [\n ...formatHeading(heading),\n ...params.outcomes.flatMap((outcome) => formatOutcome(outcome, params)),\n ...formatLoadStep(params),\n ...formatBackups(params),\n ...formatSummary(params.outcomes),\n ...formatRunHints(params),\n ]\n}\n\nfunction formatOutcome(outcome: HarnessOutcome, params: FormatResultParams): string[] {\n const { masker } = params\n const style = OUTCOME_STYLE[outcome.kind]\n const body = match(outcome)\n .with({ kind: P.union('updated', 'unchanged') }, (planned) => formatPlannedOutcome(planned, params))\n .with({ kind: 'not-found' }, ({ detail }) => [`${INDENT}${pc.dim(masker.maskText(detail))}`])\n .with({ kind: 'unsupported' }, ({ harness }) => [`${INDENT}${pc.dim(harness.reason)}`])\n .with({ kind: 'failed' }, ({ error }) => [`${INDENT}${pc.red(masker.maskText(error))}`])\n .exhaustive()\n return ['', ` ${style.colour(`${style.glyph} ${outcome.harness.label} — ${style.label}`)}`, ...body]\n}\n\nfunction formatPlannedOutcome(outcome: PlannedOutcome, { envFile, home, masker }: FormatResultParams): string[] {\n return [\n `${INDENT}${pc.dim(masker.maskText(outcome.detail))}`,\n ...outcome.warnings.map((warning) => `${INDENT}${pc.yellow(`${GLYPHS.warning} ${masker.maskText(warning)}`)}`),\n ...outcome.files.filter((file) => file.isChanged).flatMap((file) => formatResultingFile(file.after, masker)),\n ...(envFile === null ? [] : formatEnvVariables({ outcome, envFile, home, masker })),\n ...formatPostSetupNotes(outcome),\n ]\n}\n\nfunction formatResultingFile(content: string, masker: Masker): string[] {\n return [\n `${INDENT}${pc.dim('resulting file:')}`,\n ...indentLines({ text: masker.maskText(content), indent: NESTED_INDENT }),\n ]\n}\n\ntype FormatEnvVariablesParams = { outcome: PlannedOutcome; envFile: EnvPlan; home: string; masker: Masker }\n\nfunction formatEnvVariables({ outcome, envFile, home, masker }: FormatEnvVariablesParams): string[] {\n const variables = Object.entries(outcome.envVariables).flatMap(([name, value]) =>\n value === undefined ? [] : [[name, value] as const],\n )\n if (variables.length === 0) return []\n\n const syntax = ENV_SYNTAXES[envFile.shell]\n return [\n `${INDENT}${pc.dim(`variables in ${displayPath(envFile.path, home)}:`)}`,\n ...variables.map(([name, value]) => `${NESTED_INDENT}${masker.maskText(syntax.formatAssignment({ name, value }))}`),\n ]\n}\n\nfunction formatPostSetupNotes({ kind, harness }: PlannedOutcome): string[] {\n if (kind === 'unchanged') return []\n\n return (harness.postSetupNotes ?? []).map((note) => `${INDENT}${pc.cyan(`${GLYPHS.next} ${note}`)}`)\n}\n\nfunction formatLoadStep({ outcomes, envFile, mode }: FormatResultParams): string[] {\n if (mode.kind === 'dry-run' || envFile === null || !envFile.isChanged) return []\n\n const readers = outcomes\n .filter((outcome) => outcome.kind === 'updated' && Object.keys(outcome.envVariables).length > 0)\n .map((outcome) => outcome.harness.label)\n if (readers.length === 0) return []\n\n const [verb, pronoun] = readers.length === 1 ? ['reads', 'it'] : ['read', 'they']\n const { loadCommand } = ENV_SYNTAXES[envFile.shell]\n return [\n ...formatHeading('One more step'),\n ` ${formatList(readers)} ${verb} the key from the environment. Load it with:`,\n `${INDENT}${pc.bold(loadCommand)}`,\n ` ${pc.dim(`Until then ${pronoun} will not see the key.`)}`,\n ...match(envFile.shell)\n .with('powershell', () => [\n ` ${pc.dim('That lasts for this session only. Add the same line to $PROFILE to keep it.')}`,\n ])\n .with('posix', () => [])\n .exhaustive(),\n ]\n}\n\nfunction formatBackups({ mode, home, masker }: FormatResultParams): string[] {\n if (mode.kind === 'dry-run' || mode.backupRoot === null) return []\n\n const backupRoot = masker.maskText(displayPath(mode.backupRoot, home))\n return [...formatHeading('Backups'), ` Originals copied to ${pc.bold(backupRoot)}`]\n}\n\nfunction formatSummary(outcomes: readonly HarnessOutcome[]): string[] {\n const countsByKind = new Map<OutcomeKind, number>()\n for (const { kind } of outcomes) countsByKind.set(kind, (countsByKind.get(kind) ?? 0) + 1)\n\n const counts = OUTCOME_KINDS.map((kind) => `${countsByKind.get(kind) ?? 0} ${OUTCOME_STYLE[kind].label}`)\n return [...formatHeading('Summary'), ` ${counts.join(', ')}`]\n}\n\nfunction formatRunHints({ runHints, mode }: FormatResultParams): string[] {\n if (mode.kind !== 'written' || runHints.length === 0) return []\n\n return ['', \"You're all set up.\", ...runHints.map(formatRunHint)]\n}\n\nfunction formatRunHint({ binary, label }: RunHint): string {\n return ` Run \\`${binary}\\` to use ${label} with the nexos.ai Gateway.`\n}\n","import { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport type { ConfigurableHarness, Harness, UnsupportedHarness } from '../../harnesses/harness'\nimport type { EnvFileVariables } from '../../product/storage/env-file/render-env-file'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedKey } from '../../product/storage/restore-record/restore-record'\nimport type { ConfigFormat } from '../../shared/file-formats/config-format'\n\nexport type FilePlan = { path: string; before: string | null; after: string; isChanged: boolean }\n\nexport type HarnessFilePlan = FilePlan & {\n hasSecret: boolean\n format: ConfigFormat\n originals: readonly RecordedKey[]\n}\n\nexport type EnvPlan = FilePlan & { shell: Shell }\n\nexport const OUTCOME_KINDS = ['updated', 'unchanged', 'not-found', 'unsupported', 'failed'] as const\n\nexport type OutcomeKind = (typeof OUTCOME_KINDS)[number]\n\nexport type PlannedOutcome = {\n kind: 'updated' | 'unchanged'\n harness: ConfigurableHarness\n detail: string\n files: readonly HarnessFilePlan[]\n envVariables: EnvFileVariables\n warnings: readonly string[]\n}\n\nexport type NotFoundOutcome = { kind: 'not-found'; harness: Harness; detail: string }\n\nexport type UnsupportedOutcome = { kind: 'unsupported'; harness: UnsupportedHarness }\n\nexport type FailedOutcome = { kind: 'failed'; harness: Harness; error: string }\n\nexport type HarnessOutcome = PlannedOutcome | NotFoundOutcome | UnsupportedOutcome | FailedOutcome\n\nexport function isPlanned(outcome: HarnessOutcome): outcome is PlannedOutcome {\n return outcome.kind === 'updated' || outcome.kind === 'unchanged'\n}\n\nexport function exitCodeFor(outcomes: readonly HarnessOutcome[]): ExitCode {\n return outcomes.some((outcome) => outcome.kind === 'failed') ? EXIT_CODE.failed : EXIT_CODE.ok\n}\n","export function formatList(items: readonly string[]): string {\n if (items.length <= 1) return items.join('')\n\n return `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`\n}\n","import pc from 'picocolors'\nimport type { OutcomeKind } from '../../commands/setup/setup-result'\nimport { GLYPHS } from '../glyphs'\n\nexport type StatusStyle = { glyph: string; colour: (text: string) => string; label: string }\n\nexport const OUTCOME_STYLE: Readonly<Record<OutcomeKind, StatusStyle>> = {\n updated: { glyph: GLYPHS.success, colour: pc.green, label: 'updated' },\n unchanged: { glyph: GLYPHS.unchanged, colour: pc.green, label: 'already configured' },\n 'not-found': { glyph: GLYPHS.absent, colour: pc.dim, label: 'not found' },\n unsupported: { glyph: GLYPHS.failure, colour: pc.yellow, label: 'not configurable' },\n failed: { glyph: GLYPHS.failure, colour: pc.red, label: 'failed' },\n}\n","import { match } from 'ts-pattern'\nimport type { ConfigurableHarness } from '../../../harnesses/harness'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath, displayRelativePath } from '../../../shared/text/display-path'\nimport { formatList } from '../../../ui/format-list'\nimport { listConfigPaths } from './scope'\n\nexport type DescribeKeyDestinationParams = {\n configurable: readonly ConfigurableHarness[]\n ctx: PlatformContext\n envPath: string\n}\n\nexport function describeKeyDestination({ configurable, ctx, envPath }: DescribeKeyDestinationParams): string {\n const configReaders = configurable.filter((harness) => harness.keyEnvVariable === undefined)\n const configFiles = listConfigPaths(configReaders, ctx).map((filePath) => displayScopedPath(filePath, ctx))\n const envReaders = configurable\n .filter((harness) => harness.keyEnvVariable !== undefined)\n .map((harness) => harness.label)\n if (envReaders.length === 0) return `It will be written to ${formatList(configFiles)}.`\n\n const envFile = `${displayPath(envPath, ctx.home)} for ${formatList(envReaders)}`\n if (configFiles.length === 0) return `It will be written to ${envFile}.`\n\n return `It will be written to ${formatList(configFiles)}, and to ${envFile}.`\n}\n\nfunction displayScopedPath(filePath: string, ctx: PlatformContext): string {\n return match(ctx.scope)\n .with('user', () => displayPath(filePath, ctx.home))\n .with('project', () => displayRelativePath(filePath, ctx.cwd))\n .exhaustive()\n}\n","import type { ConfigurableHarness } from '../../../harnesses/harness'\nimport { harnesses } from '../../../harnesses/registry'\nimport { DEFAULT_SCOPE, type ConfigScope, type PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath, displayRelativePath } from '../../../shared/text/display-path'\nimport type { SelectScopeParams } from '../../../ui/prompts/select-scope'\nimport type { TerminalUi } from '../../../ui/terminal-ui'\n\nexport type ResolveScopeParams = {\n requestedScope: ConfigScope | undefined\n shouldAssumeYes: boolean\n baseContext: PlatformContext\n ui: TerminalUi\n}\n\nexport async function resolveScope({\n requestedScope,\n shouldAssumeYes,\n baseContext,\n ui,\n}: ResolveScopeParams): Promise<ConfigScope> {\n if (requestedScope !== undefined) return requestedScope\n if (shouldAssumeYes) return DEFAULT_SCOPE\n\n return await ui.selectScope(describeScopeTargets(baseContext))\n}\n\nfunction describeScopeTargets(ctx: PlatformContext): SelectScopeParams {\n const configurable = harnesses.filter((harness) => harness.kind === 'configurable')\n const projectConfigurable = configurable.filter((harness) => harness.projectSupport.kind === 'supported')\n return {\n userPaths: listConfigPaths(configurable, { ...ctx, scope: 'user' }).map((filePath) =>\n displayPath(filePath, ctx.home),\n ),\n projectPaths: listConfigPaths(projectConfigurable, { ...ctx, scope: 'project' }).map((filePath) =>\n displayRelativePath(filePath, ctx.cwd),\n ),\n }\n}\n\nexport function listConfigPaths(configurable: readonly ConfigurableHarness[], ctx: PlatformContext): string[] {\n return configurable.flatMap((harness) => listConfigPath(harness, ctx))\n}\n\nfunction listConfigPath(harness: ConfigurableHarness, ctx: PlatformContext): string[] {\n if (harness.configPath === undefined) return []\n\n try {\n return [harness.configPath(ctx)]\n } catch {\n return []\n }\n}\n","import { UsageError } from '../../../cli/usage-error'\nimport type { Harness } from '../../../harnesses/harness'\nimport { harnesses } from '../../../harnesses/registry'\nimport { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport type { ConfigScope, PlatformContext } from '../../../shared/platform/platform-context'\nimport type { HarnessChoice } from '../../../ui/prompts/select-harnesses'\nimport type { TerminalUi } from '../../../ui/terminal-ui'\n\nexport type Detection = { kind: 'found' | 'not-found' | 'failed'; detail: string }\n\nexport type DetectedHarness = { harness: Harness; detection: Detection }\n\nexport type SelectHarnessesParams = {\n namedHarnesses: readonly Harness[]\n ctx: PlatformContext\n shouldAssumeYes: boolean\n ui: TerminalUi\n}\n\nexport async function selectHarnesses({\n namedHarnesses,\n ctx,\n shouldAssumeYes,\n ui,\n}: SelectHarnessesParams): Promise<DetectedHarness[]> {\n if (namedHarnesses.length > 0) return detectHarnesses(namedHarnesses, ctx)\n\n const detected = detectHarnesses(harnesses, ctx)\n if (shouldAssumeYes) return detected.filter((candidate) => isDefaultChoice(candidate, ctx.scope))\n\n const chosenIds = await ui.selectHarnesses(detected.map((candidate) => describeHarnessChoice(candidate, ctx.scope)))\n return detected.filter(({ harness }) => chosenIds.includes(harness.id))\n}\n\nexport type AssertProjectSupportParams = {\n selected: readonly DetectedHarness[]\n scope: ConfigScope\n isScopeNamed: boolean\n}\n\nexport function assertProjectSupport({ selected, scope, isScopeNamed }: AssertProjectSupportParams): void {\n if (scope === 'user') return\n\n const refusals = selected.flatMap(({ harness }) => listProjectRefusal(harness))\n if (refusals.length === 0) return\n\n const nextStep = isScopeNamed ? 'Drop --scope project' : 'Choose the user scope'\n throw new UsageError(`${refusals.join('\\n')}\\n${nextStep}, or drop those agents from --harnesses.`)\n}\n\nfunction listProjectRefusal(harness: Harness): string[] {\n if (harness.kind !== 'configurable' || harness.projectSupport.kind === 'supported') return []\n\n return [`${harness.label}: ${harness.projectSupport.reason}`]\n}\n\nfunction detectHarnesses(candidates: readonly Harness[], ctx: PlatformContext): DetectedHarness[] {\n return candidates.map((harness) => ({ harness, detection: detectAtScope(harness, ctx) }))\n}\n\nfunction detectAtScope(harness: Harness, ctx: PlatformContext): Detection {\n try {\n return detectWithUserFallback(harness, ctx)\n } catch (error) {\n return { kind: 'failed', detail: describeFileError({ error, action: 'read', home: ctx.home }) }\n }\n}\n\nfunction detectWithUserFallback(harness: Harness, ctx: PlatformContext): Detection {\n const atScope = harness.detect(ctx)\n if (atScope.isFound) return { kind: 'found', detail: atScope.detail }\n if (ctx.scope === 'user' || harness.kind === 'unsupported') return { kind: 'not-found', detail: atScope.detail }\n\n const atUserScope = harness.detect({ ...ctx, scope: 'user' })\n if (!atUserScope.isFound) return { kind: 'not-found', detail: atScope.detail }\n\n const detail = `${atScope.detail} — ${harness.label} is set up at user level (${atUserScope.detail})`\n return { kind: 'found', detail }\n}\n\nconst DETECTION_HINTS: Readonly<Record<Detection['kind'], string>> = {\n found: 'found',\n 'not-found': 'not found',\n failed: 'could not check',\n}\n\nfunction describeHarnessChoice(candidate: DetectedHarness, scope: ConfigScope): HarnessChoice {\n const ineligibility = findIneligibility(candidate.harness, scope)\n return {\n value: candidate.harness.id,\n label: candidate.harness.label,\n hint: ineligibility ?? DETECTION_HINTS[candidate.detection.kind],\n isDisabled: ineligibility !== undefined,\n }\n}\n\nfunction isDefaultChoice({ harness, detection }: DetectedHarness, scope: ConfigScope): boolean {\n return findIneligibility(harness, scope) === undefined && detection.kind === 'found'\n}\n\nfunction findIneligibility(harness: Harness, scope: ConfigScope): string | undefined {\n if (harness.kind === 'unsupported') return `not configurable — ${harness.reason}`\n if (scope === 'user' || harness.projectSupport.kind === 'supported') return undefined\n\n return `no project-level config — ${harness.projectSupport.reason}`\n}\n","import path from 'node:path'\nimport { backUpBeforeWriting, ENV_FILE_BACKUP_DIRECTORY } from '../../../product/storage/backups/back-up-before-writing'\nimport type { BackupRoot } from '../../../product/storage/backups/resolve-backup-root'\nimport { writeEnvFile } from '../../../product/storage/env-file/write-env-file'\nimport { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport { readFileMode } from '../../../shared/file-system/read-file-mode'\nimport { resolveOwnerOnlyMode } from '../../../shared/file-system/resolve-owner-only-mode'\nimport { writeFileWithMode } from '../../../shared/file-system/write-file-with-mode'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport type { EnvPlan, FilePlan, HarnessFilePlan, HarnessOutcome } from '../setup-result'\nimport { renderEnvPlan, type ChangePlan } from './change-plan'\nimport { recordEnvOriginals, recordFileOriginals } from './record-originals'\n\nexport type ApplyChangesParams = {\n plan: ChangePlan\n ctx: PlatformContext\n backupRoot: BackupRoot\n}\n\nexport type ApplyChangesResult = {\n outcomes: HarnessOutcome[]\n envFile: EnvPlan | null\n writtenCount: number\n backupRoot: string | null\n}\n\nexport function applyChanges(params: ApplyChangesParams): ApplyChangesResult {\n const agentWrites = params.plan.outcomes.map((outcome) => writeAgentFiles(outcome, params))\n const outcomes = agentWrites.map(({ outcome }) => outcome)\n const envFile = replanEnvFile(params.plan.envFile, outcomes)\n const envWrite = writeSharedEnvFile({ outcomes, envFile, params })\n const writtenFiles = [...agentWrites.flatMap(({ writtenFiles }) => writtenFiles), ...envWrite.writtenFiles]\n return {\n outcomes: envWrite.outcomes,\n envFile,\n writtenCount: writtenFiles.length,\n backupRoot: writtenFiles.some((file) => file.isBackedUp) ? params.backupRoot.path : null,\n }\n}\n\ntype WrittenFile = { isBackedUp: boolean }\n\ntype AgentWrite = { outcome: HarnessOutcome; writtenFiles: WrittenFile[] }\n\nfunction writeAgentFiles(outcome: HarnessOutcome, params: ApplyChangesParams): AgentWrite {\n if (outcome.kind !== 'updated') return { outcome, writtenFiles: [] }\n\n const writtenFiles: WrittenFile[] = []\n for (const file of outcome.files.filter((plan) => plan.isChanged)) {\n try {\n const relativePath = path.join(outcome.harness.id, path.basename(file.path))\n const record = (): void => recordFileOriginals({ harnessId: outcome.harness.id, file, ctx: params.ctx })\n const write = (): void =>\n writeFileWithMode({ filePath: file.path, content: file.after, mode: resolveWriteMode(file, params.ctx) })\n writtenFiles.push(backUpThenWrite({ file, relativePath, record, write, params }))\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: params.ctx.home })\n return { outcome: { kind: 'failed', harness: outcome.harness, error: reason }, writtenFiles }\n }\n }\n return { outcome, writtenFiles }\n}\n\nfunction replanEnvFile(envFile: EnvPlan | null, outcomes: readonly HarnessOutcome[]): EnvPlan | null {\n if (envFile === null) return null\n\n return renderEnvPlan({ outcomes, before: envFile.before, envPath: envFile.path, shell: envFile.shell })\n}\n\ntype WriteSharedEnvFileParams = { outcomes: HarnessOutcome[]; envFile: EnvPlan | null; params: ApplyChangesParams }\n\ntype EnvWrite = { outcomes: HarnessOutcome[]; writtenFiles: WrittenFile[] }\n\nfunction writeSharedEnvFile({ outcomes, envFile, params }: WriteSharedEnvFileParams): EnvWrite {\n if (envFile === null || !envFile.isChanged) return { outcomes, writtenFiles: [] }\n\n try {\n const relativePath = path.join(ENV_FILE_BACKUP_DIRECTORY, path.basename(envFile.path))\n const { ctx } = params\n const record = (): void => recordEnvOriginals({ outcomes, envFile, ctx })\n const write = (): void => writeEnvFile({ filePath: envFile.path, content: envFile.after, platform: ctx.platform })\n return { outcomes, writtenFiles: [backUpThenWrite({ file: envFile, relativePath, record, write, params })] }\n } catch (error) {\n const reason = describeFileError({ error, action: 'write', home: params.ctx.home })\n return { outcomes: outcomes.map((outcome) => failIfWritingEnvFile(outcome, reason)), writtenFiles: [] }\n }\n}\n\nfunction failIfWritingEnvFile(outcome: HarnessOutcome, error: string): HarnessOutcome {\n if (outcome.kind !== 'updated' || Object.keys(outcome.envVariables).length === 0) return outcome\n\n return { kind: 'failed', harness: outcome.harness, error }\n}\n\ntype BackUpThenWriteParams = {\n file: FilePlan\n relativePath: string\n record: () => void\n write: () => void\n params: ApplyChangesParams\n}\n\nfunction backUpThenWrite({ file, relativePath, record, write, params }: BackUpThenWriteParams): WrittenFile {\n const { ctx, backupRoot } = params\n const backup = backUpBeforeWriting({ filePath: file.path, before: file.before, backupRoot, relativePath, ctx })\n record()\n write()\n return backup\n}\n\nfunction resolveWriteMode(file: HarnessFilePlan, ctx: PlatformContext): number | null {\n const existingMode = readFileMode(file.path, ctx.platform)\n if (existingMode !== null || !file.hasSecret) return existingMode\n\n return resolveOwnerOnlyMode(ctx.platform)\n}\n","import { isDeepStrictEqual } from 'node:util'\nimport type { ConfigurableHarness, Contribution, FileContribution } from '../../../harnesses/harness'\nimport type { DesiredConfig } from '../../../product/gateway/desired-config'\nimport { NO_ENV_FILE, readEnvFile, type EnvFileRead } from '../../../product/storage/env-file/read-env-file'\nimport { renderEnvFile, type EnvFileVariables } from '../../../product/storage/env-file/render-env-file'\nimport type { Shell } from '../../../product/storage/env-file/syntax/env-syntax'\nimport type { RecordedKey } from '../../../product/storage/restore-record/restore-record'\nimport { ConfigFormatError } from '../../../shared/file-formats/config-errors'\nimport { readOriginals, renderConfig, type ConfigFormat } from '../../../shared/file-formats/config-format'\nimport { describeFileError } from '../../../shared/file-system/describe-file-error'\nimport { readFileIfExists } from '../../../shared/file-system/read-file-if-exists'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport { displayPath, displayRelativePath } from '../../../shared/text/display-path'\nimport type { DetectedHarness } from '../answers/harness-selection'\nimport {\n isPlanned,\n type EnvPlan,\n type FailedOutcome,\n type FilePlan,\n type HarnessFilePlan,\n type HarnessOutcome,\n type PlannedOutcome,\n} from '../setup-result'\n\nexport type PlanChangesParams = {\n selected: readonly DetectedHarness[]\n desired: DesiredConfig\n ctx: PlatformContext\n envPath: string\n shell: Shell\n isDryRun: boolean\n}\n\nexport type ChangePlan = { outcomes: HarnessOutcome[]; envFile: EnvPlan | null }\n\nexport function planChanges(params: PlanChangesParams): ChangePlan {\n const { envPath, shell } = params\n const drafts = params.selected.map((candidate) => planHarness(candidate, params))\n const envFileRead = drafts.some(hasEnvVariables) ? readEnvFile({ envPath, home: params.ctx.home }) : NO_ENV_FILE\n const outcomes = drafts.map((draft) => settleOutcome({ draft, envFileRead, shell }))\n return { outcomes, envFile: planEnvFile({ outcomes, envFileRead, envPath, shell }) }\n}\n\nexport function listChangedFiles({ outcomes, envFile }: ChangePlan): FilePlan[] {\n const changedFiles = outcomes.flatMap((outcome) =>\n outcome.kind === 'updated' ? outcome.files.filter((file) => file.isChanged) : [],\n )\n return envFile?.isChanged === true ? [...changedFiles, envFile] : changedFiles\n}\n\nexport type RenderEnvPlanParams = {\n outcomes: readonly HarnessOutcome[]\n before: string | null\n envPath: string\n shell: Shell\n}\n\nexport function renderEnvPlan({ outcomes, before, envPath, shell }: RenderEnvPlanParams): EnvPlan | null {\n const variables = Object.fromEntries(\n outcomes.flatMap((outcome) => (isPlanned(outcome) ? Object.entries(outcome.envVariables) : [])),\n )\n if (Object.keys(variables).length === 0) return null\n\n const after = renderEnvFile({ current: before, variables, shell })\n return { path: envPath, before, after, isChanged: before !== after, shell }\n}\n\ntype Draft = Exclude<HarnessOutcome, PlannedOutcome> | (Omit<PlannedOutcome, 'kind'> & { kind: 'planned' })\n\nfunction planHarness({ harness, detection }: DetectedHarness, params: PlanChangesParams): Draft {\n if (harness.kind === 'unsupported') return { kind: 'unsupported', harness }\n if (detection.kind === 'failed') return { kind: 'failed', harness, error: detection.detail }\n if (detection.kind === 'not-found') {\n return { kind: 'not-found', harness, detail: `${detection.detail} — skipped, and no config was created` }\n }\n\n try {\n return planConfigurableHarness(harness, params)\n } catch (error) {\n return { kind: 'failed', harness, error: describeFileError({ error, action: 'read', home: params.ctx.home }) }\n }\n}\n\nconst PROJECT_ENV_REFUSAL =\n 'The env file it reads is user-level only, so a project-level run cannot set it up. Run again with --scope user.'\n\nfunction planConfigurableHarness(harness: ConfigurableHarness, { desired, ctx, isDryRun }: PlanChangesParams): Draft {\n const contributions = harness.plan(desired, ctx)\n if (ctx.scope === 'project' && contributions.some(({ kind }) => kind === 'env')) {\n return { kind: 'failed', harness, error: PROJECT_ENV_REFUSAL }\n }\n\n const files = contributions.flatMap((contribution) =>\n contribution.kind === 'file' ? [planFile({ contribution, apiKey: desired.apiKey, home: ctx.home })] : [],\n )\n const repositoryWarnings = files.flatMap((file) => warnAboutRepository(file, ctx, isDryRun))\n return {\n kind: 'planned',\n harness,\n detail: files.length > 0 ? files.map((file) => displayPath(file.path, ctx.home)).join(', ') : ENV_ONLY_DETAIL,\n files,\n envVariables: collectEnvVariables(contributions),\n warnings: [...repositoryWarnings, ...(harness.warnings?.(ctx) ?? [])],\n }\n}\n\nconst ENV_ONLY_DETAIL = 'environment variables only'\n\ntype PlanFileParams = { contribution: FileContribution; apiKey: string; home: string }\n\nfunction planFile({ contribution, apiKey, home }: PlanFileParams): HarnessFilePlan {\n const before = readFileIfExists(contribution.path)\n const rendered = renderFileContribution({ contribution, before, apiKey, home })\n const isChanged = before !== rendered.after\n return { path: contribution.path, before, ...rendered, isChanged, hasSecret: contribution.hasSecret }\n}\n\ntype RenderFileContributionParams = PlanFileParams & { before: string | null }\n\ntype RenderedFile = { after: string; format: ConfigFormat; originals: RecordedKey[] }\n\nfunction renderFileContribution(params: RenderFileContributionParams): RenderedFile {\n const { contribution, before, apiKey, home } = params\n try {\n const edits = contribution.edits(before)\n const secretKeyPaths = edits.updates.flatMap(([keyPath, value]) => (value === apiKey ? [keyPath] : []))\n const originals = readOriginals(before, edits).map((original) => ({\n ...original,\n holdsSecret: secretKeyPaths.some((keyPath) => isDeepStrictEqual(keyPath, original.keyPath)),\n }))\n return { after: renderConfig(before, edits), format: edits.format, originals }\n } catch (error) {\n if (!(error instanceof ConfigFormatError)) throw error\n throw new Error(`${displayPath(contribution.path, home)}: ${error.message}`, { cause: error })\n }\n}\n\nfunction warnAboutRepository(file: HarnessFilePlan, ctx: PlatformContext, isDryRun: boolean): string[] {\n if (ctx.scope === 'user' || !file.hasSecret) return []\n\n const displayedPath = displayRelativePath(file.path, ctx.cwd)\n const location = isDryRun ? `A real run puts the key in ${displayedPath}` : `${displayedPath} holds the key`\n return [`${location}, inside your repository — make sure it is gitignored before committing.`]\n}\n\nfunction collectEnvVariables(contributions: readonly Contribution[]): EnvFileVariables {\n return Object.fromEntries(\n contributions.flatMap((contribution) =>\n contribution.kind === 'env' ? Object.entries(contribution.variables) : [],\n ),\n )\n}\n\nfunction hasEnvVariables(draft: Draft): boolean {\n return draft.kind === 'planned' && Object.keys(draft.envVariables).length > 0\n}\n\ntype SettleOutcomeParams = { draft: Draft; envFileRead: EnvFileRead; shell: Shell }\n\nfunction settleOutcome({ draft, envFileRead, shell }: SettleOutcomeParams): HarnessOutcome {\n if (draft.kind !== 'planned') return draft\n if (envFileRead.kind === 'failed' && hasEnvVariables(draft)) return failWith(draft, envFileRead.error)\n\n const envText = envFileRead.kind === 'read' ? envFileRead.text : null\n const hasOwnEnvChange =\n hasEnvVariables(draft) && renderEnvFile({ current: envText, variables: draft.envVariables, shell }) !== envText\n const isChanged = hasOwnEnvChange || draft.files.some((file) => file.isChanged)\n return { ...draft, kind: isChanged ? 'updated' : 'unchanged' }\n}\n\nfunction failWith({ harness }: Draft, error: string): FailedOutcome {\n return { kind: 'failed', harness, error }\n}\n\ntype PlanEnvFileParams = {\n outcomes: readonly HarnessOutcome[]\n envFileRead: EnvFileRead\n envPath: string\n shell: Shell\n}\n\nfunction planEnvFile({ outcomes, envFileRead, envPath, shell }: PlanEnvFileParams): EnvPlan | null {\n if (envFileRead.kind === 'failed') return null\n\n return renderEnvPlan({ outcomes, before: envFileRead.text, envPath, shell })\n}\n","import type { FileOrigin, HarnessRecord, RecordedEnvVariable, RecordedFile, RestoreRecord } from './restore-record'\n\nexport function classifyFileOrigin(before: string | null): FileOrigin {\n if (before === null) return 'absent'\n return before.trim() === '' ? 'blank' : 'content'\n}\n\nexport type AddFileOriginalsParams = { record: RestoreRecord; harnessId: string; file: RecordedFile }\n\n/** First touch wins: a key already recorded keeps its original, and only new key paths are added. */\nexport function addFileOriginals({ record, harnessId, file }: AddFileOriginalsParams): RestoreRecord {\n const harness = readHarnessRecord(record, harnessId)\n const existing = harness.files.find((recorded) => isSamePath(recorded.path, file.path))\n const others = harness.files.filter((recorded) => recorded !== existing)\n return withHarnessRecord(record, harnessId, { ...harness, files: [...others, mergeFile(existing, file)] })\n}\n\nexport type AddEnvOriginalsParams = {\n record: RestoreRecord\n harnessId: string\n variables: readonly RecordedEnvVariable[]\n isFileAbsent: boolean\n}\n\nexport function addEnvOriginals({ record, harnessId, variables, isFileAbsent }: AddEnvOriginalsParams): RestoreRecord {\n const harness = readHarnessRecord(record, harnessId)\n const kept = isFileAbsent ? [] : harness.envVariables\n const added = variables.filter((variable) => !kept.some(({ name }) => name === variable.name))\n return withHarnessRecord(record, harnessId, { ...harness, envVariables: [...kept, ...added] })\n}\n\nconst EMPTY_HARNESS_RECORD: HarnessRecord = { files: [], envVariables: [] }\n\nfunction readHarnessRecord(record: RestoreRecord, harnessId: string): HarnessRecord {\n return record.harnesses[harnessId] ?? EMPTY_HARNESS_RECORD\n}\n\nfunction withHarnessRecord(record: RestoreRecord, harnessId: string, harness: HarnessRecord): RestoreRecord {\n return { ...record, harnesses: { ...record.harnesses, [harnessId]: harness } }\n}\n\n// A file absent now was deleted since it was recorded, so what it held then is no longer anything to restore.\nfunction mergeFile(existing: RecordedFile | undefined, file: RecordedFile): RecordedFile {\n if (existing === undefined || file.origin === 'absent') return file\n\n const added = file.keys.filter((key) => !existing.keys.some(({ keyPath }) => isSamePath(keyPath, key.keyPath)))\n return { ...existing, keys: [...existing.keys, ...added] }\n}\n\nfunction isSamePath(path: readonly string[], other: readonly string[]): boolean {\n return path.length === other.length && path.every((segment, index) => segment === other[index])\n}\n","import { ignoreBackupsInGit } from '../../../product/storage/backups/back-up-file'\nimport { parseEnvFile } from '../../../product/storage/env-file/parse-env-file'\nimport { ENV_SYNTAXES } from '../../../product/storage/env-file/syntax/env-syntaxes'\nimport {\n addEnvOriginals,\n addFileOriginals,\n classifyFileOrigin,\n} from '../../../product/storage/restore-record/add-originals'\nimport {\n createEmptyRestoreRecord,\n readRestoreRecord,\n writeRestoreRecord,\n type RecordedFile,\n type RestoreRecord,\n} from '../../../product/storage/restore-record/restore-record'\nimport {\n resolveRestoreRecordLocation,\n toRecordedPath,\n type RestoreRecordLocation,\n} from '../../../product/storage/restore-record/restore-record-location'\nimport type { PlatformContext } from '../../../shared/platform/platform-context'\nimport type { EnvPlan, HarnessFilePlan, HarnessOutcome } from '../setup-result'\n\nexport type RecordFileOriginalsParams = { harnessId: string; file: HarnessFilePlan; ctx: PlatformContext }\n\nexport function recordFileOriginals({ harnessId, file, ctx }: RecordFileOriginalsParams): void {\n const location = resolveRestoreRecordLocation(ctx)\n const recordedFile: RecordedFile = {\n path: toRecordedPath(file.path, location.root),\n format: file.format,\n origin: classifyFileOrigin(file.before),\n keys: file.originals,\n }\n updateRestoreRecord(location, ctx, (record) => addFileOriginals({ record, harnessId, file: recordedFile }))\n}\n\nexport type RecordEnvOriginalsParams = { outcomes: readonly HarnessOutcome[]; envFile: EnvPlan; ctx: PlatformContext }\n\nexport function recordEnvOriginals({ outcomes, envFile, ctx }: RecordEnvOriginalsParams): void {\n const syntax = ENV_SYNTAXES[envFile.shell]\n const currentValues = parseEnvFile(envFile.before ?? '', envFile.shell)\n const isFileAbsent = envFile.before === null\n\n updateRestoreRecord(resolveRestoreRecordLocation(ctx), ctx, (record) =>\n outcomes.reduce((updated, outcome) => {\n if (outcome.kind !== 'updated') return updated\n\n const variables = Object.keys(outcome.envVariables).map((name) => ({\n name,\n original: currentValues.get(syntax.normalizeName(name)) ?? null,\n }))\n if (variables.length === 0) return updated\n return addEnvOriginals({ record: updated, harnessId: outcome.harness.id, variables, isFileAbsent })\n }, record),\n )\n}\n\nfunction updateRestoreRecord(\n location: RestoreRecordLocation,\n ctx: PlatformContext,\n update: (record: RestoreRecord) => RestoreRecord,\n): void {\n if (location.gitIgnoredDirectory !== null) ignoreBackupsInGit(location.gitIgnoredDirectory)\n\n const record = readRestoreRecord({ filePath: location.filePath, home: ctx.home }) ?? createEmptyRestoreRecord()\n writeRestoreRecord({ filePath: location.filePath, record: update(record), platform: ctx.platform })\n}\n","import {\n GATEWAY_ENV_VARIABLE,\n parseEnvironmentKey,\n readEnvironmentInputs,\n type EnvironmentInputs,\n} from '../../cli/environment'\nimport { EXIT_CODE, type ExitCode } from '../../cli/exit-code'\nimport { TAGLINE } from '../../cli/help'\nimport type { CliOptions } from '../../cli/parse-cli-arguments'\nimport { refusePrompts } from '../../cli/refuse-prompts'\nimport { resolveNamedHarnesses } from '../../cli/resolve-named-harnesses'\nimport { findExistingKeys } from '../../flows/key/find-existing-keys'\nimport {\n adoptKey,\n commitSave,\n isKeyUsable,\n resolveKey,\n type KeyStepDeps,\n type KeyStepInput,\n type KeyStepRun,\n} from '../../flows/key/key-step'\nimport { chooseCheckedModel } from '../../flows/model/choose-checked-model'\nimport { commitModelSave, loadModelPreferences } from '../../flows/model/model-step'\nimport type { ConfigurableHarness, Harness } from '../../harnesses/harness'\nimport {\n GATEWAY_HOST,\n buildDesiredConfig,\n buildGatewayUrls,\n type GatewayUrls,\n} from '../../product/gateway/desired-config'\nimport type { Fetch } from '../../product/gateway/gateway-request'\nimport type { Masker } from '../../product/secrets/masker'\nimport { formatBackupTimestamp, resolveBackupRoot } from '../../product/storage/backups/resolve-backup-root'\nimport { resolveEnvFilePath } from '../../product/storage/env-file/env-file-path'\nimport type { Shell } from '../../product/storage/env-file/syntax/env-syntax'\nimport { resolveShell } from '../../product/storage/env-file/syntax/env-syntaxes'\nimport type { Keystore } from '../../product/storage/keychain/keystore'\nimport type { PlatformContext } from '../../shared/platform/platform-context'\nimport { formatCount } from '../../shared/text/format-count'\nimport { formatDetection } from '../../ui/report/format-detection'\nimport { formatPreview } from '../../ui/report/format-preview'\nimport { formatResult, type ResultMode, type RunHint } from '../../ui/report/format-result'\nimport type { TerminalUi } from '../../ui/terminal-ui'\nimport { describeKeyDestination } from './answers/describe-key-destination'\nimport {\n assertProjectSupport,\n selectHarnesses,\n type DetectedHarness,\n type Detection,\n} from './answers/harness-selection'\nimport { resolveScope } from './answers/scope'\nimport { applyChanges, type ApplyChangesResult } from './changes/apply-changes'\nimport { listChangedFiles, planChanges, type ChangePlan } from './changes/change-plan'\nimport { exitCodeFor, isPlanned, type HarnessOutcome } from './setup-result'\n\nexport type RunSetupParams = {\n options: CliOptions\n baseContext: PlatformContext\n ui: TerminalUi\n fetch: Fetch\n now: () => Date\n masker: Masker\n keystore: Keystore\n}\n\nconst FINISHED_WITH_ERRORS = 'Finished with errors.'\n\nexport async function runSetup(params: RunSetupParams): Promise<ExitCode> {\n const { options, masker } = params\n const ui = params.baseContext.isInteractive ? params.ui : refusePrompts(params.ui)\n ui.intro(TAGLINE)\n\n const environment = readEnvironmentInputs(params.baseContext.env)\n masker.registerSecrets([options.key, environment.key].flatMap((key) => key ?? []))\n const gatewayUrls = buildGatewayUrls(environment.gatewayHost ?? GATEWAY_HOST)\n if (environment.gatewayHost !== undefined) {\n ui.log.warn(masker.maskText(`Using the gateway at ${environment.gatewayHost} — $${GATEWAY_ENV_VARIABLE} is set.`))\n }\n const namedHarnesses = resolveNamedHarnesses(options.harnessIds)\n const scope = await resolveScope({\n requestedScope: options.scope,\n shouldAssumeYes: options.shouldAssumeYes,\n baseContext: params.baseContext,\n ui,\n })\n const ctx: PlatformContext = { ...params.baseContext, scope }\n const selected = await selectHarnesses({ namedHarnesses, ctx, shouldAssumeYes: options.shouldAssumeYes, ui })\n assertProjectSupport({ selected, scope, isScopeNamed: options.scope !== undefined })\n if (selected.length === 0) {\n ui.cancel('No agents selected — nothing to do.')\n return EXIT_CODE.ok\n }\n\n warnAboutUnsupported(selected, ui)\n if (!selected.some(({ harness }) => harness.kind === 'configurable')) {\n ui.outro('Nothing to configure.')\n return EXIT_CODE.ok\n }\n const found = selected.flatMap(listFoundConfigurable)\n if (found.length === 0) return endWithNothingFound(selected, ui, masker)\n\n const shell = resolveShell(ctx.platform)\n const run: SetupRun = { ...params, ui, ctx, shell, envPath: resolveEnvFilePath(ctx.home, shell), gatewayUrls }\n const keyStep = await establishKey({ run, configurable: found, environment })\n if (keyStep === null) return EXIT_CODE.failed\n\n const modelDecision = await chooseCheckedModel({\n keyStep,\n configurable: found,\n envModel: environment.model,\n preferences: loadModelPreferences(ctx.home, ui),\n gatewayUrls,\n options,\n probeConsequence: options.isDryRun\n ? 'The dry run writes nothing either way.'\n : 'The configs will still be written.',\n ui,\n masker,\n fetch: params.fetch,\n })\n if (modelDecision.kind === 'declined') return abort(ui)\n if (modelDecision.kind === 'aborted') return EXIT_CODE.failed\n\n const { model, resolvedKey, check, modelSave } = modelDecision\n const saveModelFor = (outcomes: readonly HarnessOutcome[]): void => {\n const configuredHarnesses = listConfigured(modelSave, outcomes)\n commitModelSave({ model, harnesses: configuredHarnesses, home: ctx.home, ui, masker })\n }\n const key = resolvedKey.key\n\n ui.print(formatDetection(selected, masker))\n const desired = buildDesiredConfig({ gatewayUrls, apiKey: key, model })\n const plan = planChanges({ selected, desired, ctx, envPath: run.envPath, shell, isDryRun: options.isDryRun })\n const changes = listChangedFiles(plan)\n const isPlanFailed = exitCodeFor(plan.outcomes) !== EXIT_CODE.ok\n ui.print(formatPreview({ changes, model, scope, hasFailedAgent: isPlanFailed, home: ctx.home, masker }))\n\n if (options.isDryRun) {\n if (resolvedKey.shouldSave) ui.dim('Dry run — the key was not saved.')\n if (modelSave.length > 0) ui.dim('Dry run — the default model was not saved.')\n return reportResult({ run, plan, mode: { kind: 'dry-run' }, outro: 'Dry run — nothing was written.' })\n }\n if (changes.length === 0) {\n await commitSave(resolvedKey, check, keyStep.deps)\n saveModelFor(plan.outcomes)\n const mode = { kind: 'written', backupRoot: null } as const\n const outro = isPlanFailed ? FINISHED_WITH_ERRORS : 'Nothing to do — already configured.'\n return reportResult({ run, plan, mode, outro })\n }\n if (!options.shouldAssumeYes && !(await ui.confirm('Write these changes? Originals are backed up first.', true))) {\n return abort(ui)\n }\n\n await commitSave(resolvedKey, check, keyStep.deps)\n const applied = writeChanges(run, plan)\n saveModelFor(applied.outcomes)\n const outro = exitCodeFor(applied.outcomes) === EXIT_CODE.ok ? 'Done.' : FINISHED_WITH_ERRORS\n const mode = { kind: 'written', backupRoot: applied.backupRoot } as const\n return reportResult({ run, plan: { outcomes: applied.outcomes, envFile: applied.envFile }, mode, outro })\n}\n\ntype SetupRun = RunSetupParams & {\n ui: TerminalUi\n ctx: PlatformContext\n shell: Shell\n envPath: string\n gatewayUrls: GatewayUrls\n}\n\nfunction warnAboutUnsupported(selected: readonly DetectedHarness[], ui: TerminalUi): void {\n for (const { harness } of selected) {\n if (harness.kind === 'unsupported') ui.log.warn(`${harness.label}: not configurable — ${harness.reason}`)\n }\n}\n\nfunction listFoundConfigurable({ harness, detection }: DetectedHarness): ConfigurableHarness[] {\n if (harness.kind !== 'configurable' || detection.kind !== 'found') return []\n\n return [harness]\n}\n\nfunction endWithNothingFound(selected: readonly DetectedHarness[], ui: TerminalUi, masker: Masker): ExitCode {\n ui.print(formatDetection(selected, masker))\n const hasFailedCheck = selected.some(({ harness, detection }) => isConfigurableUnchecked(harness, detection))\n if (hasFailedCheck) {\n ui.outro(FINISHED_WITH_ERRORS)\n return EXIT_CODE.failed\n }\n\n ui.outro('Nothing to configure — none of the selected agents was found.')\n return EXIT_CODE.ok\n}\n\nfunction isConfigurableUnchecked(harness: Harness, detection: Detection): boolean {\n return harness.kind === 'configurable' && detection.kind === 'failed'\n}\n\ntype EstablishKeyParams = {\n run: SetupRun\n configurable: readonly ConfigurableHarness[]\n environment: EnvironmentInputs\n}\n\nasync function establishKey({ run, configurable, environment }: EstablishKeyParams): Promise<KeyStepRun | null> {\n const { ctx, envPath, shell, ui, masker, options } = run\n // Read eagerly: the diff shows lines this run removes, so every key already on disk must be\n // registered for masking even when the key comes from a flag and no prompt is reached.\n const existingKeys = findExistingKeys({ ctx, envPath, shell })\n masker.registerSecrets(existingKeys.all)\n\n const deps: KeyStepDeps = { keystore: run.keystore, ui, masker }\n const input: KeyStepInput = {\n flagKey: options.key,\n envKey: options.key === undefined ? parseEnvironmentKey(environment.key) : undefined,\n shouldSaveKey: options.shouldSaveKey,\n shouldAssumeYes: options.shouldAssumeYes,\n isDryRun: options.isDryRun,\n existingKeys: () => existingKeys,\n destination: describeKeyDestination({ configurable, ctx, envPath }),\n }\n\n const resolved = await resolveKey(input, deps)\n if (!isKeyUsable(resolved.key)) {\n ui.cancel('No API key provided.')\n return null\n }\n adoptKey(resolved.key, { ui, masker })\n return { input, deps, resolved }\n}\n\n/** A default is saved only for an agent this run configured, not one whose write failed. */\nfunction listConfigured(\n harnesses: readonly ConfigurableHarness[],\n outcomes: readonly HarnessOutcome[],\n): ConfigurableHarness[] {\n const configuredIds = new Set(outcomes.filter(isPlanned).map((outcome) => outcome.harness.id))\n return harnesses.filter((harness) => configuredIds.has(harness.id))\n}\n\nfunction writeChanges(run: SetupRun, plan: ChangePlan): ApplyChangesResult {\n const { options, ctx, ui } = run\n const backupRoot = resolveBackupRoot({\n scope: ctx.scope,\n home: ctx.home,\n cwd: ctx.cwd,\n stamp: formatBackupTimestamp(run.now()),\n backupDirectory: options.backupDirectory,\n })\n\n const spinner = ui.spinner()\n spinner.start('Backing up originals and writing configs…')\n const applied = applyChanges({ plan, ctx, backupRoot })\n spinner.stop(`Wrote ${formatCount(applied.writtenCount, 'file')}.`)\n return applied\n}\n\ntype ReportResultParams = { run: SetupRun; plan: ChangePlan; mode: ResultMode; outro: string }\n\nfunction reportResult({ run, plan, mode, outro }: ReportResultParams): ExitCode {\n const { ui, ctx, masker } = run\n ui.print(\n formatResult({\n outcomes: plan.outcomes,\n envFile: plan.envFile,\n mode,\n home: ctx.home,\n masker,\n runHints: listRunHints(plan.outcomes, ctx),\n }),\n )\n ui.outro(outro)\n return exitCodeFor(plan.outcomes)\n}\n\nfunction listRunHints(outcomes: readonly HarnessOutcome[], ctx: PlatformContext): RunHint[] {\n return outcomes\n .filter(isPlanned)\n .flatMap(({ harness }) => (ctx.hasBinary(harness.binary) ? [{ binary: harness.binary, label: harness.label }] : []))\n}\n\nfunction abort(ui: TerminalUi): ExitCode {\n ui.cancel('Aborted — nothing was written.')\n return EXIT_CODE.cancelled\n}\n","import type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { describeError } from '../shared/text/describe-error'\nimport type { LaunchRecipe } from './launch-recipe'\n\nexport const LAUNCH_DIRECTORY_PREFIX = 'nexos-connect-'\nconst STALE_DIRECTORY_PATTERN = new RegExp(`^${LAUNCH_DIRECTORY_PREFIX}(\\\\d+)-`)\nconst OWNER_ONLY_MODE = 0o600\n\nexport type LaunchResult = { code: number } | { signal: NodeJS.Signals }\n\nexport interface RunnerDeps {\n spawn(command: string, commandArguments: string[], options: SpawnOptions): ChildProcess\n tmpdir(): string\n pid: number\n /** Undefined where the platform has no uids (Windows). */\n uid: number | undefined\n isAlive(pid: number): boolean\n signals: Pick<NodeJS.EventEmitter, 'on' | 'off'>\n stdin: Pick<NodeJS.ReadStream, 'isTTY' | 'setRawMode' | 'pause'>\n env: NodeJS.ProcessEnv\n onError(message: string): void\n}\n\n/**\n * Temp dirs carry their run's pid, so only a dir whose run is gone is removed: a concurrent\n * session's settings file must outlive this run.\n */\nexport function sweepStaleDirectories(deps: Pick<RunnerDeps, 'tmpdir' | 'uid' | 'isAlive'>): void {\n const root = deps.tmpdir()\n let names: string[]\n try {\n names = fs.readdirSync(root)\n } catch {\n return\n }\n\n for (const name of names) {\n const match = STALE_DIRECTORY_PATTERN.exec(name)\n if (match === null) continue\n\n const directory = path.join(root, name)\n try {\n if (deps.isAlive(Number(match[1]))) continue\n if (deps.uid !== undefined && fs.statSync(directory).uid !== deps.uid) continue\n fs.rmSync(directory, { recursive: true, force: true })\n } catch {\n // Already gone, or not ours to remove.\n }\n }\n}\n\n/**\n * Ctrl-C reaches the whole foreground process group, so SIGINT is ignored here — the agent decides\n * what it means — and this process outlives it to clean up.\n */\nexport async function runLaunch(\n recipe: LaunchRecipe,\n passthrough: readonly string[],\n deps: RunnerDeps,\n): Promise<LaunchResult> {\n sweepStaleDirectories(deps)\n\n let directory: string | null = null\n const cleanup = (): void => {\n if (directory === null) return\n fs.rmSync(directory, { recursive: true, force: true })\n directory = null\n }\n deps.signals.on('exit', cleanup)\n\n let commandArguments = recipe.arguments\n if (recipe.files !== undefined && recipe.files.length > 0) {\n try {\n directory = fs.mkdtempSync(path.join(deps.tmpdir(), `${LAUNCH_DIRECTORY_PREFIX}${deps.pid}-`))\n const byPlaceholder = new Map<string, string>()\n for (const file of recipe.files) {\n const target = path.join(directory, file.name)\n fs.writeFileSync(target, file.content, { mode: OWNER_ONLY_MODE, flag: 'wx' })\n byPlaceholder.set(file.placeholder, target)\n }\n commandArguments = commandArguments.map((argument) => byPlaceholder.get(argument) ?? argument)\n } catch (error) {\n cleanup()\n deps.signals.off('exit', cleanup)\n deps.onError(\n `Couldn't write the temporary settings file in ${deps.tmpdir()}: ${describeError(error)}. Check $TMPDIR.`,\n )\n return { code: 1 }\n }\n }\n\n const env: NodeJS.ProcessEnv = { ...deps.env }\n for (const [name, value] of Object.entries(recipe.env)) {\n if (value === undefined) delete env[name]\n else env[name] = value\n }\n\n // Prompts may have left stdin flowing or raw; either would steal the agent's keystrokes.\n if (deps.stdin.isTTY) deps.stdin.setRawMode(false)\n deps.stdin.pause()\n\n return new Promise((resolve) => {\n let child: ChildProcess | undefined\n const ignore = (): void => {}\n // A signal listener is called with no argument, so each forwards the signal it is registered for.\n const forwardTermination = (): void => {\n child?.kill('SIGTERM')\n }\n const forwardHangup = (): void => {\n child?.kill('SIGHUP')\n }\n\n let isSettled = false\n const finish = (result: LaunchResult): void => {\n if (isSettled) return\n isSettled = true\n deps.signals.off('SIGINT', ignore)\n deps.signals.off('SIGTERM', forwardTermination)\n deps.signals.off('SIGHUP', forwardHangup)\n deps.signals.off('exit', cleanup)\n cleanup()\n resolve(result)\n }\n\n try {\n const subcommands = recipe.subcommands ?? []\n const joined = joinArguments({ recipeArguments: commandArguments, subcommands, passthrough })\n child = deps.spawn(recipe.binary, joined, { stdio: 'inherit', env })\n } catch (error) {\n deps.onError(`Couldn't start ${recipe.binary}: ${describeError(error)}`)\n finish({ code: 1 })\n return\n }\n\n deps.signals.on('SIGINT', ignore)\n deps.signals.on('SIGTERM', forwardTermination)\n deps.signals.on('SIGHUP', forwardHangup)\n child.once('error', (error) => {\n deps.onError(`Couldn't start ${recipe.binary}: ${error.message}`)\n finish({ code: 1 })\n })\n child.once('exit', (code, signal) => finish(signal !== null ? { signal } : { code: code ?? 1 }))\n })\n}\n\nexport type JoinArgumentsParams = {\n recipeArguments: readonly string[]\n subcommands: readonly string[]\n passthrough: readonly string[]\n}\n\nexport function joinArguments({ recipeArguments, subcommands, passthrough }: JoinArgumentsParams): string[] {\n const [first, ...rest] = passthrough\n if (first !== undefined && subcommands.includes(first)) return [first, ...recipeArguments, ...rest]\n\n return [...recipeArguments, ...passthrough]\n}\n","import { randomUUID } from 'node:crypto'\nimport type { AsyncEntry, EntryOptions } from '@napi-rs/keyring'\n\n/** The one export the store uses, so the native module is only reached through `importKeyring`. */\nexport interface Keyring {\n AsyncEntry: new (service: string, username: string, options?: EntryOptions) => AsyncEntry\n}\n\nconst SERVICE = 'nexos-connect'\nconst ACCOUNT = 'default'\nconst PROBE_ACCOUNT = 'probe'\nconst LINUX_STORE: EntryOptions = { linux: { store: 'secret-service' } }\nconst MS_PER_SECOND = 1_000\n\nexport const KEYCHAIN_ENV_VARIABLE = 'NEXOS_KEYCHAIN'\nexport const KEYCHAIN_DISABLED = 'off'\n\n/** Secret Service can hang indefinitely over SSH, in Docker and under WSL. */\nexport const KEYCHAIN_PROBE_TIMEOUT_MS = 2_000\n/** A read or write can wait on a keychain password dialog, so it gets a user-scale budget. */\nexport const KEYCHAIN_INTERACTION_TIMEOUT_MS = 120_000\n\nexport const KEYCHAIN_UNAVAILABLE = {\n disabled: 'The system keychain is disabled',\n wsl: 'WSL has no reachable system keychain',\n noBinding: 'No keychain support for this platform',\n noMacKeychain: 'No default macOS keychain',\n noKeychain: 'No system keychain found',\n timedOut: 'The system keychain did not answer in time',\n} as const\n\n/** Reasons under which an entry saved by an earlier run can still be in the keychain. */\nconst REASONS_THAT_MAY_HOLD_A_KEY: ReadonlySet<string> = new Set([\n KEYCHAIN_UNAVAILABLE.disabled,\n KEYCHAIN_UNAVAILABLE.noKeychain,\n KEYCHAIN_UNAVAILABLE.timedOut,\n])\n\nexport type Availability = { kind: 'available' } | { kind: 'unavailable'; reason: string; hasPossibleEntry: boolean }\n\nexport interface Keystore {\n availability(): Promise<Availability>\n load(): Promise<string | undefined>\n save(key: string): Promise<void>\n /** Whether there was an entry to remove. */\n clear(): Promise<boolean>\n /**\n * A native call timed out. Its thread is still blocked and holds the event loop open, so the\n * process has to be ended with `process.exit`.\n */\n readonly isHung: boolean\n}\n\nexport interface KeystoreDeps {\n importKeyring(): Promise<Keyring>\n platform: NodeJS.Platform\n isWsl(): boolean\n hasMacKeychain(): boolean\n /** False when `$NEXOS_KEYCHAIN=off`, the escape hatch the e2e sandbox uses. */\n isEnabled: boolean\n probeTimeoutMs: number\n interactionTimeoutMs: number\n}\n\nfunction unavailable(reason: string): Availability {\n return { kind: 'unavailable', reason, hasPossibleEntry: REASONS_THAT_MAY_HOLD_A_KEY.has(reason) }\n}\n\nexport function createKeystore(deps: KeystoreDeps): Keystore {\n let keyring: Keyring | undefined\n let probed: Promise<Availability> | undefined\n let isHung = false\n\n function entry(account: string): AsyncEntry {\n if (keyring === undefined) throw new Error('the keychain was used before availability() passed')\n return new keyring.AsyncEntry(SERVICE, account, LINUX_STORE)\n }\n\n // Raced against a timer rather than left to the signal alone: aborting only cancels native work\n // that has not started, and a hung D-Bus call has.\n function withTimeout<T>(operation: (signal: AbortSignal) => Promise<T>, timeoutMs: number): Promise<T> {\n if (isHung) return Promise.reject(new Error(KEYCHAIN_UNAVAILABLE.timedOut))\n\n const controller = new AbortController()\n let timer: NodeJS.Timeout | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n isHung = true\n controller.abort()\n reject(new Error(`the system keychain did not answer within ${timeoutMs / MS_PER_SECOND}s`))\n }, timeoutMs)\n })\n return Promise.race([operation(controller.signal), timeout]).finally(() => clearTimeout(timer))\n }\n\n async function probe(): Promise<Availability> {\n if (!deps.isEnabled) return unavailable(KEYCHAIN_UNAVAILABLE.disabled)\n if (deps.platform === 'linux' && deps.isWsl()) return unavailable(KEYCHAIN_UNAVAILABLE.wsl)\n\n let loaded: Keyring\n try {\n loaded = await deps.importKeyring()\n } catch {\n return unavailable(KEYCHAIN_UNAVAILABLE.noBinding)\n }\n if (deps.platform === 'darwin' && !deps.hasMacKeychain()) return unavailable(KEYCHAIN_UNAVAILABLE.noMacKeychain)\n\n try {\n const token = randomUUID()\n const read = await withTimeout(async (signal) => {\n const probeEntry = new loaded.AsyncEntry(SERVICE, PROBE_ACCOUNT, LINUX_STORE)\n try {\n await probeEntry.setPassword(token, signal)\n return await probeEntry.getPassword(signal)\n } finally {\n // Best effort, and without the aborted signal: a timed-out delete cannot succeed anyway.\n await probeEntry.deleteCredential().catch(() => false)\n }\n }, deps.probeTimeoutMs)\n if (read !== token) return unavailable(KEYCHAIN_UNAVAILABLE.noKeychain)\n\n // Only now is the module safe to use: a failed probe must not leave a usable `keyring`.\n keyring = loaded\n return { kind: 'available' }\n } catch {\n return unavailable(isHung ? KEYCHAIN_UNAVAILABLE.timedOut : KEYCHAIN_UNAVAILABLE.noKeychain)\n }\n }\n\n return {\n availability: () => (isHung ? Promise.resolve(unavailable(KEYCHAIN_UNAVAILABLE.timedOut)) : (probed ??= probe())),\n load: () =>\n withTimeout(async (signal) => (await entry(ACCOUNT).getPassword(signal)) ?? undefined, deps.interactionTimeoutMs),\n save: (key) => withTimeout(async (signal) => entry(ACCOUNT).setPassword(key, signal), deps.interactionTimeoutMs),\n clear: () => withTimeout(async (signal) => entry(ACCOUNT).deleteCredential(signal), deps.interactionTimeoutMs),\n get isHung() {\n return isHung\n },\n }\n}\n","import * as clack from '@clack/prompts'\nimport pc from 'picocolors'\nimport type { PromptIo } from './prompt-io'\n\nexport function intro(message: string, io: PromptIo): void {\n clack.intro(message, { output: io.output })\n}\n\nexport function outro(message: string, io: PromptIo): void {\n clack.outro(message, { output: io.output })\n}\n\nexport function cancel(message: string, io: PromptIo): void {\n clack.cancel(message, { output: io.output })\n}\n\nexport interface Log {\n info(message: string): void\n warn(message: string): void\n error(message: string): void\n success(message: string): void\n}\n\nexport function createLog(io: PromptIo): Log {\n return {\n info: (message) => clack.log.info(message, { output: io.output }),\n warn: (message) => clack.log.warn(message, { output: io.output }),\n error: (message) => clack.log.error(message, { output: io.output }),\n success: (message) => clack.log.success(message, { output: io.output }),\n }\n}\n\nexport function printLines(lines: readonly string[], io: PromptIo): void {\n io.output.write(`${lines.join('\\n')}\\n`)\n}\n\n/** A side remark: worth saying, never worth stopping for. */\nexport function dim(message: string, io: PromptIo): void {\n clack.log.message(pc.dim(message), { output: io.output })\n}\n\nexport function note(message: string, title: string, io: PromptIo): void {\n clack.note(message, title, { output: io.output })\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport async function confirm(message: string, shouldDefaultToYes: boolean, io: PromptIo): Promise<boolean> {\n return await throwIfCancelled(clack.confirm({ message, initialValue: shouldDefaultToYes, ...io }))\n}\n","import * as clack from '@clack/prompts'\nimport { API_KEYS_URL } from '../../../product/gateway/desired-config'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type AskForKeyParams = { destination: string }\n\nexport async function askForKey({ destination }: AskForKeyParams, io: PromptIo): Promise<string> {\n clack.note(`Create a key at:\\n ${API_KEYS_URL}\\n\\n${destination}`, 'You need a nexos.ai API key', {\n output: io.output,\n })\n\n const value = await throwIfCancelled(\n clack.password({\n message: 'Paste your nexos.ai API key',\n validate: (value) => ((value ?? '').trim() === '' ? 'Paste a key, or press Ctrl-C to quit.' : undefined),\n ...io,\n }),\n )\n return value.trim()\n}\n\nexport type AskToKeepOrReplaceKeyParams = { destination: string; maskedExistingKey: string }\n\nexport type KeyAnswer = { kind: 'kept' } | { kind: 'replaced'; key: string }\n\nexport async function askToKeepOrReplaceKey(\n { destination, maskedExistingKey }: AskToKeepOrReplaceKeyParams,\n io: PromptIo,\n): Promise<KeyAnswer> {\n clack.note(\n `A nexos.ai API key was found on this machine (${maskedExistingKey}).\\n` +\n 'Press Enter to keep it, or paste a new one to replace it.\\n\\n' +\n `Need a different key? Create one at:\\n ${API_KEYS_URL}\\n\\n${destination}`,\n 'nexos.ai API key',\n { output: io.output },\n )\n\n const value = await throwIfCancelled(\n clack.password({ message: 'Paste a new key, or press Enter to keep the existing one', ...io }),\n )\n const pasted = value.trim()\n return pasted === '' ? { kind: 'kept' } : { kind: 'replaced', key: pasted }\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\n/** A paste with no key to fall back on: the user has just declined the one on offer. */\nexport async function askForNewKey(io: PromptIo): Promise<string> {\n const value = await throwIfCancelled(\n clack.password({\n message: 'Paste your nexos.ai API key',\n validate: (value) => ((value ?? '').trim() === '' ? 'A key is required' : undefined),\n ...io,\n }),\n )\n return value.trim()\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type RejectedKeyChoice = 'forget' | 'cancel'\n\nexport async function chooseOnSavedKeyRejected(status: number, io: PromptIo): Promise<RejectedKeyChoice> {\n return await throwIfCancelled(\n clack.select<RejectedKeyChoice>({\n message: `The gateway rejected the saved key (HTTP ${status}). What next?`,\n options: [\n { value: 'forget', label: 'Forget it and paste a new key' },\n { value: 'cancel', label: 'Cancel' },\n ],\n initialValue: 'forget',\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type SavedKeyChoice = 'use' | 'paste'\n\nexport async function chooseSavedKey(maskedKey: string, io: PromptIo): Promise<SavedKeyChoice> {\n return await throwIfCancelled(\n clack.select<SavedKeyChoice>({\n message: 'Which nexos.ai API key?',\n options: [\n { value: 'use', label: `Use saved key ${maskedKey}`, hint: 'from your system keychain' },\n { value: 'paste', label: 'Paste a new key' },\n ],\n initialValue: 'use',\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_MODEL } from '../../../product/gateway/models/predefined-models'\nimport { withBackKeys, type BackKeysResult } from '../../back-keys'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\n// No `validate`: clack runs it before it applies `defaultValue`, so Enter on an empty field would be refused.\nconst MODEL_ID_PROMPT: clack.TextOptions = {\n message: `Model id (Enter for ${DEFAULT_MODEL})`,\n placeholder: DEFAULT_MODEL,\n defaultValue: DEFAULT_MODEL,\n}\n\nconst REQUIRED_MODEL_ID_PROMPT: clack.TextOptions = {\n message: 'Model id',\n validate: (value) =>\n value === undefined || value.trim() === '' ? 'Type a model id, or press Esc to go back.' : undefined,\n}\n\nexport async function askForModelId(io: PromptIo): Promise<string> {\n const typed = await throwIfCancelled(clack.text({ ...MODEL_ID_PROMPT, ...io }))\n return normalizeModelId(typed)\n}\n\nexport async function askForModelIdWithBack(io: PromptIo): Promise<BackKeysResult<string>> {\n const typed = await withBackKeys({\n isFieldEmpty: () => false,\n run: () => clack.text({ ...MODEL_ID_PROMPT, ...io }),\n input: io.input,\n })\n if (typed.kind === 'back') return typed\n\n return { kind: 'chosen', value: normalizeModelId(typed.value) }\n}\n\nexport async function askForRequiredModelIdWithBack(io: PromptIo): Promise<BackKeysResult<string>> {\n const typed = await withBackKeys({\n isFieldEmpty: () => false,\n run: () => clack.text({ ...REQUIRED_MODEL_ID_PROMPT, ...io }),\n input: io.input,\n })\n if (typed.kind === 'back') return typed\n\n return { kind: 'chosen', value: typed.value.trim() }\n}\n\nfunction normalizeModelId(typed: string): string {\n const modelId = typed.trim()\n return modelId === '' ? DEFAULT_MODEL : modelId\n}\n","import type { EventEmitter } from 'node:events'\nimport type { Key } from 'node:readline'\nimport * as clack from '@clack/prompts'\nimport { CancelledError } from './cancelled-error'\n\nconst ESCAPE_KEY = 'escape'\nconst EDITING_BACK_KEYS = ['left', 'backspace', 'delete'] as const\n\nexport function isBackKeystroke(key: Key | undefined, isFieldEmpty: boolean): boolean {\n if (key?.name === ESCAPE_KEY) return true\n return isFieldEmpty && isEditingBackKey(key?.name)\n}\n\nexport type BackKeysResult<T> = { kind: 'chosen'; value: T } | { kind: 'back' }\n\nexport type WithBackKeysParams<T> = {\n isFieldEmpty: () => boolean\n run: () => Promise<T | typeof clack.CANCEL_SYMBOL>\n input: EventEmitter\n}\n\n// Clack reports Esc and Ctrl-C as one cancel symbol, so a keypress listener that runs first tells them apart.\nexport async function withBackKeys<T>({ isFieldEmpty, run, input }: WithBackKeysParams<T>): Promise<BackKeysResult<T>> {\n let isGoingBack = false\n\n const onKeypress = (_character: string | undefined, key: Key): void => {\n const name = key?.name\n if (name === undefined) return\n\n isGoingBack = isBackKeystroke(key, isFieldEmpty())\n\n if (!isEditingBackKey(name)) return\n if (isGoingBack) clack.settings.aliases.set(name, 'cancel')\n else clack.settings.aliases.delete(name)\n }\n\n input.prependListener('keypress', onKeypress)\n try {\n const value = await run()\n if (!clack.isCancel(value)) return { kind: 'chosen', value }\n if (isGoingBack) return { kind: 'back' }\n throw new CancelledError()\n } finally {\n input.removeListener('keypress', onKeypress)\n for (const name of EDITING_BACK_KEYS) clack.settings.aliases.delete(name)\n }\n}\n\nfunction isEditingBackKey(name: string | undefined): boolean {\n return EDITING_BACK_KEYS.some((editingKey) => editingKey === name)\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_MODEL } from '../../../product/gateway/models/predefined-models'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { PromptIo } from '../../prompt-io'\n\nexport type FetchFailureChoice = 'retry' | 'manual' | 'default'\n\nexport async function chooseOnFetchFailure(io: PromptIo): Promise<FetchFailureChoice> {\n return await throwIfCancelled(\n clack.select<FetchFailureChoice>({\n message: 'Could not fetch the model list. What next?',\n options: [\n { value: 'retry', label: 'Try again', hint: 'send the same request again' },\n { value: 'manual', label: 'Type a model id…', hint: 'if you know which one you want' },\n { value: 'default', label: `Use ${DEFAULT_MODEL}`, hint: 'the gateway router' },\n ],\n initialValue: 'retry',\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport type { ModelSuggestion } from '../../model-choices'\nimport type { PromptIo } from '../../prompt-io'\n\nconst ANOTHER_MODEL_VALUE = '\\u0000another'\n\n/** Resolves to the default chosen, or to undefined when the user wants the model picker instead. */\nexport async function chooseSavedModel(\n defaults: readonly ModelSuggestion[],\n io: PromptIo,\n): Promise<string | undefined> {\n const chosen = await throwIfCancelled(\n clack.select<string>({\n message: 'Which model should your agents use?',\n options: [\n ...defaults.map(({ model, hint }) => ({ value: model, label: `Use ${model}`, hint })),\n { value: ANOTHER_MODEL_VALUE, label: 'Choose another model…' },\n ],\n ...io,\n }),\n )\n return chosen === ANOTHER_MODEL_VALUE ? undefined : chosen\n}\n","import * as clack from '@clack/prompts'\nimport { formatCount } from '../../../shared/text/format-count'\nimport { throwIfCancelled } from '../../cancelled-error'\nimport { BROWSE_VALUE, MANUAL_VALUE, type ModelChoices } from '../../model-choices'\nimport { createLog } from '../../output'\nimport type { PromptIo } from '../../prompt-io'\nimport { askForModelIdWithBack, askForRequiredModelIdWithBack } from './ask-for-model-id'\nimport { browseCatalogue } from './browse-catalogue'\n\nconst TYPED_ID_BACK_KEY_NOTE = 'Esc goes back to the list above.'\nconst CATALOGUE_BACK_KEYS_NOTE = 'Esc goes back to the list above, and so do ← and Delete while the filter is empty.'\n\nexport async function selectModel(choices: ModelChoices, io: PromptIo): Promise<string> {\n const log = createLog(io)\n const rows: clack.Option<string>[] = choices.rows.map((row) => ({\n value: row.value,\n label: row.label,\n ...(row.hint !== undefined ? { hint: row.hint } : {}),\n }))\n\n let cameBackFrom: string | undefined\n let hasNotedTypedIdBackKey = false\n let hasNotedCatalogueBackKeys = false\n\n for (;;) {\n const initialValue = cameBackFrom ?? rows[0]?.value\n const chosenRow = await throwIfCancelled(\n clack.select<string>({\n message: 'Which model should your agents use?',\n options: rows,\n ...(initialValue === undefined ? {} : { initialValue }),\n ...io,\n }),\n )\n\n if (chosenRow !== BROWSE_VALUE && chosenRow !== MANUAL_VALUE) return chosenRow\n\n if (chosenRow === MANUAL_VALUE) {\n if (!hasNotedTypedIdBackKey) log.info(TYPED_ID_BACK_KEY_NOTE)\n hasNotedTypedIdBackKey = true\n\n const typed = choices.isRouterOffered ? await askForModelIdWithBack(io) : await askForRequiredModelIdWithBack(io)\n if (typed.kind === 'chosen') return typed.value\n cameBackFrom = MANUAL_VALUE\n continue\n }\n\n if (!hasNotedCatalogueBackKeys) {\n log.info(CATALOGUE_BACK_KEYS_NOTE)\n if (choices.hiddenCount > 0) log.info(formatHiddenModelsNote(choices.hiddenCount))\n }\n hasNotedCatalogueBackKeys = true\n\n const browsed = await browseCatalogue(choices, io)\n if (browsed.kind === 'chosen') return browsed.value\n cameBackFrom = BROWSE_VALUE\n }\n}\n\nexport function formatHiddenModelsNote(hiddenCount: number): string {\n const subject = hiddenCount === 1 ? 'it does' : 'they do'\n return `${formatCount(hiddenCount, 'model')} hidden — ${subject} not serve the API your selected agents use.`\n}\n","import * as clack from '@clack/prompts'\nimport { withBackKeys, type BackKeysResult } from '../../back-keys'\nimport { formatModelHint, type ModelChoices } from '../../model-choices'\nimport type { PromptIo } from '../../prompt-io'\n\nconst CATALOGUE_VISIBLE_ROWS = 15\n\nexport async function browseCatalogue(choices: ModelChoices, io: PromptIo): Promise<BackKeysResult<string>> {\n const catalogue: clack.Option<string>[] = choices.browsable.map((model) => {\n const hint = formatModelHint(model)\n return { value: model.id, label: model.id, ...(hint !== '' ? { hint } : {}) }\n })\n\n // Clack calls an options function with `this` bound to the prompt, whose `userInput` is the live filter.\n let readFilterText = (): string => ''\n\n return await withBackKeys({\n isFieldEmpty: () => readFilterText() === '',\n run: () =>\n clack.autocomplete<string>({\n message: 'Model',\n maxItems: CATALOGUE_VISIBLE_ROWS,\n options: function (this: { readonly userInput: string }) {\n readFilterText = () => this.userInput\n return catalogue\n },\n ...io,\n }),\n input: io.input,\n })\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport type HarnessChoice = { value: string; label: string; hint: string; isDisabled: boolean }\n\nexport async function selectHarnesses(choices: readonly HarnessChoice[], io: PromptIo): Promise<string[]> {\n return await throwIfCancelled(\n clack.multiselect<string>({\n message: 'Which agents should use the nexos.ai Gateway?',\n options: choices.map((choice) => ({\n value: choice.value,\n label: choice.label,\n hint: choice.hint,\n disabled: choice.isDisabled,\n })),\n initialValues: [],\n required: true,\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport type RestoreChoice = { value: string; label: string; hint: string }\n\nexport async function selectRestoreHarnesses(choices: readonly RestoreChoice[], io: PromptIo): Promise<string[]> {\n return await throwIfCancelled(\n clack.multiselect<string>({\n message: 'Which agents should get their original config back?',\n options: choices.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: choices.map(({ value }) => value),\n required: false,\n ...io,\n }),\n )\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_SCOPE, type ConfigScope } from '../../shared/platform/platform-context'\nimport { throwIfCancelled } from '../cancelled-error'\nimport { formatList } from '../format-list'\nimport type { PromptIo } from '../prompt-io'\n\nexport type SelectRestoreScopeParams = { userAgents: readonly string[]; projectAgents: readonly string[] }\n\nexport async function selectRestoreScope(\n { userAgents, projectAgents }: SelectRestoreScopeParams,\n io: PromptIo,\n): Promise<ConfigScope> {\n return await throwIfCancelled(\n clack.select<ConfigScope>({\n message: 'Which configs should get their original setup back?',\n options: [\n { value: 'user', label: 'User-level', hint: describeRecordedAgents(userAgents) },\n { value: 'project', label: 'Project-level', hint: `this directory — ${describeRecordedAgents(projectAgents)}` },\n ],\n initialValue: DEFAULT_SCOPE,\n ...io,\n }),\n )\n}\n\nfunction describeRecordedAgents(agents: readonly string[]): string {\n return agents.length === 0 ? 'nothing to restore' : formatList(agents)\n}\n","import * as clack from '@clack/prompts'\nimport { DEFAULT_SCOPE, type ConfigScope } from '../../shared/platform/platform-context'\nimport { throwIfCancelled } from '../cancelled-error'\nimport type { PromptIo } from '../prompt-io'\n\nexport type SelectScopeParams = { userPaths: readonly string[]; projectPaths: readonly string[] }\n\nexport async function selectScope({ userPaths, projectPaths }: SelectScopeParams, io: PromptIo): Promise<ConfigScope> {\n return await throwIfCancelled(\n clack.select<ConfigScope>({\n message: 'Where should the configs be written?',\n options: [\n { value: 'user', label: 'User-level', hint: `applies everywhere — ${userPaths.join(', ')}` },\n { value: 'project', label: 'Project-level', hint: `this directory only — ${projectPaths.join(', ')}` },\n ],\n initialValue: DEFAULT_SCOPE,\n ...io,\n }),\n )\n}\n","import type { Readable, Writable } from 'node:stream'\nimport * as clack from '@clack/prompts'\nimport pc from 'picocolors'\nimport { CancelledError } from './cancelled-error'\nimport { GLYPHS } from './glyphs'\nimport type { PromptIo } from './prompt-io'\n\nexport interface Spinner {\n start(message: string): void\n stop(message: string): void\n waitFor<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>\n /**\n * Waits under the same Ctrl-C handling as `waitFor`, drawing nothing and reporting nothing.\n * It owns the terminal while it runs: never overlap it with `start`, or with another spinner on\n * the same terminal, because whichever finishes first clears raw mode and pauses the stream.\n */\n waitQuietly<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>\n}\n\n// Not clack's spinner: it reads Ctrl-C from stdin itself and answers by exiting the process with 0.\nexport function createSpinner(io: PromptIo): Spinner {\n const taskController = new AbortController()\n const cancelled = new Promise<never>((_resolve, reject) => {\n taskController.signal.addEventListener('abort', () => reject(taskController.signal.reason), { once: true })\n })\n cancelled.catch(() => {})\n\n let stopSpinning: (() => void) | null = null\n const end = (): void => {\n stopSpinning?.()\n stopSpinning = null\n }\n const cancel = (): void => {\n end()\n taskController.abort(new CancelledError())\n }\n\n const waitFor = async <T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> => {\n try {\n return await Promise.race([task(taskController.signal), cancelled])\n } catch (error) {\n end()\n throw error\n }\n }\n\n return {\n start: (message) => {\n end()\n stopSpinning = spin({ io, message, onCancel: cancel })\n },\n stop: (message) => {\n if (stopSpinning === null) return\n\n end()\n io.output.write(`${pc.green(clack.S_STEP_SUBMIT)} ${message}\\n`)\n },\n waitFor,\n waitQuietly: async (task) => {\n const stopListening = listenForCancel(io, cancel)\n try {\n return await waitFor(task)\n } finally {\n stopListening()\n }\n },\n }\n}\n\ntype SpinParams = { io: PromptIo; message: string; onCancel: () => void }\n\nfunction spin({ io, message, onCancel }: SpinParams): () => void {\n io.output.write(`${pc.gray(clack.S_BAR)}\\n`)\n const stopAnimating = isTerminalOutput(io.output) ? animate(io.output, message) : () => {}\n const stopListening = listenForCancel(io, onCancel)\n\n return () => {\n stopListening()\n stopAnimating()\n }\n}\n\nconst FRAMES = clack.unicode ? ['◒', '◐', '◓', '◑'] : ['•', 'o', 'O', '0']\nconst FRAME_INTERVAL_MS = 80\nconst HIDE_CURSOR = '\\u001b[?25l'\nconst SHOW_CURSOR = '\\u001b[?25h'\nconst CLEAR_LINE = '\\r\\u001b[2K'\nconst FRAME_WIDTH = 4\n\nfunction animate(output: TerminalOutput, message: string): () => void {\n const text = fitToWidth(message, output.columns)\n let frameIndex = 0\n const drawFrame = (): void => {\n output.write(`${CLEAR_LINE}${pc.magenta(FRAMES[frameIndex % FRAMES.length] ?? '')} ${text}`)\n frameIndex += 1\n }\n\n output.write(HIDE_CURSOR)\n drawFrame()\n const timer = setInterval(drawFrame, FRAME_INTERVAL_MS)\n return () => {\n clearInterval(timer)\n output.write(`${CLEAR_LINE}${SHOW_CURSOR}`)\n }\n}\n\nfunction fitToWidth(text: string, columns: number): string {\n const width = columns - FRAME_WIDTH\n if (width <= 0 || text.length <= width) return text\n\n return `${text.slice(0, width - GLYPHS.elided.length)}${GLYPHS.elided}`\n}\n\nconst CTRL_C = '\\u0003'\nconst ESCAPE = '\\u001b'\n\nfunction listenForCancel({ input, onInterrupt }: PromptIo, onCancel: () => void): () => void {\n const stopInterruptListening = onInterrupt(onCancel)\n if (!isTerminalInput(input)) return stopInterruptListening\n\n const onData = (chunk: Buffer | string): void => {\n if (isCancelKeystroke(String(chunk))) onCancel()\n }\n input.setRawMode(true)\n input.on('data', onData)\n input.resume()\n return () => {\n stopInterruptListening()\n input.removeListener('data', onData)\n input.setRawMode(false)\n input.pause()\n }\n}\n\nfunction isCancelKeystroke(chunk: string): boolean {\n return chunk.includes(CTRL_C) || chunk === ESCAPE\n}\n\ntype TerminalInput = Readable & { setRawMode(isRaw: boolean): unknown }\n\nfunction isTerminalInput(input: Readable): input is TerminalInput {\n return 'isTTY' in input && input.isTTY === true && 'setRawMode' in input && typeof input.setRawMode === 'function'\n}\n\ntype TerminalOutput = Writable & { columns: number }\n\nfunction isTerminalOutput(output: Writable): output is TerminalOutput {\n return 'isTTY' in output && output.isTTY === true && 'columns' in output && typeof output.columns === 'number'\n}\n","import type { ConfigScope } from '../shared/platform/platform-context'\nimport type { ModelChoices, ModelSuggestion } from './model-choices'\nimport { cancel, createLog, dim, intro, note, outro, printLines, type Log } from './output'\nimport type { PromptIo } from './prompt-io'\nimport { confirm } from './prompts/confirm'\nimport {\n askForKey,\n askToKeepOrReplaceKey,\n type AskForKeyParams,\n type AskToKeepOrReplaceKeyParams,\n type KeyAnswer,\n} from './prompts/key/ask-for-key'\nimport { askForNewKey } from './prompts/key/ask-for-new-key'\nimport { chooseOnSavedKeyRejected, type RejectedKeyChoice } from './prompts/key/choose-on-saved-key-rejected'\nimport { chooseSavedKey, type SavedKeyChoice } from './prompts/key/choose-saved-key'\nimport { askForModelId } from './prompts/model/ask-for-model-id'\nimport { chooseOnFetchFailure, type FetchFailureChoice } from './prompts/model/choose-on-fetch-failure'\nimport { chooseSavedModel } from './prompts/model/choose-saved-model'\nimport { selectModel } from './prompts/model/select-model'\nimport { selectHarnesses, type HarnessChoice } from './prompts/select-harnesses'\nimport { selectRestoreHarnesses, type RestoreChoice } from './prompts/select-restore-harnesses'\nimport { selectRestoreScope, type SelectRestoreScopeParams } from './prompts/select-restore-scope'\nimport { selectScope, type SelectScopeParams } from './prompts/select-scope'\nimport { createSpinner, type Spinner } from './spinner'\n\nexport interface TerminalUi {\n intro(message: string): void\n outro(message: string): void\n cancel(message: string): void\n log: Log\n print(lines: readonly string[]): void\n dim(message: string): void\n note(message: string, title: string): void\n spinner(): Spinner\n selectScope(params: SelectScopeParams): Promise<ConfigScope>\n selectHarnesses(choices: readonly HarnessChoice[]): Promise<string[]>\n askForKey(params: AskForKeyParams): Promise<string>\n askToKeepOrReplaceKey(params: AskToKeepOrReplaceKeyParams): Promise<KeyAnswer>\n askForNewKey(): Promise<string>\n chooseSavedKey(maskedKey: string): Promise<SavedKeyChoice>\n chooseOnSavedKeyRejected(status: number): Promise<RejectedKeyChoice>\n confirm(message: string, shouldDefaultToYes: boolean): Promise<boolean>\n chooseSavedModel(defaults: readonly ModelSuggestion[]): Promise<string | undefined>\n selectModel(choices: ModelChoices): Promise<string>\n askForModelId(): Promise<string>\n chooseOnFetchFailure(): Promise<FetchFailureChoice>\n selectRestoreScope(params: SelectRestoreScopeParams): Promise<ConfigScope>\n selectRestoreHarnesses(choices: readonly RestoreChoice[]): Promise<string[]>\n}\n\nexport function createTerminalUi(io: PromptIo): TerminalUi {\n return {\n intro: (message) => intro(message, io),\n outro: (message) => outro(message, io),\n cancel: (message) => cancel(message, io),\n log: createLog(io),\n print: (lines) => printLines(lines, io),\n dim: (message) => dim(message, io),\n note: (message, title) => note(message, title, io),\n spinner: () => createSpinner(io),\n selectScope: (params) => selectScope(params, io),\n selectHarnesses: (choices) => selectHarnesses(choices, io),\n askForKey: (params) => askForKey(params, io),\n askToKeepOrReplaceKey: (params) => askToKeepOrReplaceKey(params, io),\n askForNewKey: () => askForNewKey(io),\n chooseSavedKey: (maskedKey) => chooseSavedKey(maskedKey, io),\n chooseOnSavedKeyRejected: (status) => chooseOnSavedKeyRejected(status, io),\n confirm: (message, shouldDefaultToYes) => confirm(message, shouldDefaultToYes, io),\n chooseSavedModel: (defaults) => chooseSavedModel(defaults, io),\n selectModel: (choices) => selectModel(choices, io),\n askForModelId: () => askForModelId(io),\n chooseOnFetchFailure: () => chooseOnFetchFailure(io),\n selectRestoreScope: (params) => selectRestoreScope(params, io),\n selectRestoreHarnesses: (choices) => selectRestoreHarnesses(choices, io),\n }\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;AACf,OAAOA,YAAU;AACjB,OAAO,gBAAgB;AACvB,OAAOC,UAAQ;AACf,YAAYC,SAAO;;;ACNnB,SAAS,aAAa;;;ACAf,SAAS,cAAc,OAAwB;AACpD,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;ACFA,YAAY,WAAW;AAEhB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,cAAc;AACZ,UAAM,uBAAuB;AAC7B,SAAK,OAAO;AAAA,EACd;AACF;AAGA,eAAsB,iBAAoB,SAA2D;AACnG,QAAM,QAAQ,MAAM;AACpB,MAAU,eAAS,KAAK,EAAG,OAAM,IAAI,eAAe;AACpD,SAAO;AACT;;;ACdO,IAAM,YAAY,EAAE,IAAI,GAAG,QAAQ,GAAG,OAAO,GAAG,WAAW,IAAI;;;ACA/D,IAAM,aAAN,cAAyB,MAAM;AAAA,EAClB,OAAO;AAC3B;;;AJUA,IAAM,uBACJ;AAEK,SAAS,gBAAgB,OAAgBC,SAAyB;AACvE,MAAI,iBAAiB,eAAgB,QAAO,EAAE,MAAM,YAAY;AAEhE,QAAM,UAAUA,QAAO,SAAS,cAAc,KAAK,CAAC;AACpD,MAAI,iBAAiB,WAAY,QAAO,EAAE,MAAM,SAAS,QAAQ;AAEjE,SAAO,EAAE,MAAM,cAAc,SAAS,GAAG,OAAO;AAAA,EAAK,oBAAoB,GAAG;AAC9E;AAEO,SAAS,mBAAmB,SAA4B;AAC7D,SAAO,MAAM,QAAQ,IAAI,E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,SAAS,KAAK,QAAQ,IAAI;AAAA,IAClD;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW,CAAC,QAAQ,sBAAsB,UAAU,QAAQ,mBAAmB,UAAU;AAAA,IAC3F;AAAA,EACF;AACA,MAAI,YAAY,QAAQ;AAEtB,YAAQ,KAAK,QAAQ,KAAK,OAAO,MAAM;AACvC,WAAO,UAAU;AAAA,EACnB;AACA,SAAO,OAAO;AAChB;AAEA,SAAS,OAAO,UAAwB;AAEtC,MAAI,SAAS,OAAQ,SAAQ,KAAK,QAAQ;AAC1C,UAAQ,WAAW;AACrB;AAEA,KAAK,KAAK,EACP,KAAK,MAAM,EACX,MAAM,CAAC,UAAmB;AACzB,UAAQ,MAAMA,KAAG,IAAI,OAAO,SAAS,cAAc,KAAK,CAAC,CAAC,CAAC;AAC3D,SAAO,UAAU,MAAM;AACzB,CAAC;","names":["path","pc","v","masker","match","masker","match","fetch","text","match","text","secret","match","match","match","match","keystore","masker","v","path","match","v","path","v","text","match","v","match","text","text","fs","fs","BYTE_ORDER_MARK","text","match","path","settings","path","match","text","DEFAULT_LINE_ENDING","readSource","restoreKey","match","path","BINARY","API_KEY_VARIABLE","CONFIG_DIRECTORY","path","BINARY","BASE_URL_VARIABLE","API_KEY_VARIABLE","MODEL_VARIABLE","path","match","v","BINARY","PROVIDER_ID","PROVIDER_NAME","PROVIDER_TYPE","resolveConfigPath","planConfig","path","match","fs","path","CONFIG_DIRECTORY","path","fs","path","match","v","BINARY","resolveConfigPath","planConfig","RUN_PROVIDER_ID","readProviderKey","readProviderSecrets","path","match","listUpdates","ConfigSchema","PROVIDER_ID","PROVIDER_NAME","CONFIG_SCHEMA_URL","ProvidersSchema","ProviderKeySchema","path","v","BINARY","PROVIDER_ID","PROVIDER_NAME","detectBinary","planSettings","readProviderKey","readProviderSecrets","path","resolveSettingsPath","ProvidersSchema","ProviderKeySchema","path","match","v","BINARY","resolveSettingsPath","planSettings","readProviderKey","readProviderSecrets","USER_DIRECTORY","SETTINGS_FILE","match","path","listUpdates","SettingsSchema","settings","text","match","path","path","path","path","match","text","v","keystore","availability","masker","check","pc","text","text","pc","match","P","match","v","OptionalTextSchema","ModelSchema","text","masker","fetch","text","detail","match","P","match","masker","fetch","match","match","match","match","P","match","masker","fetch","classifyRejection","match","P","masker","fetch","match","fs","path","v","path","JSON_INDENT","text","parseJson","fs","v","harnesses","harnesses","masker","masker","probe","fetch","path","path","masker","path","path","match","fs","path","v","match","match","text","match","fs","path","text","parseJson","JSON_INDENT","record","fs","path","path","match","match","path","pc","pc","text","pc","match","pc","match","masker","pc","note","masker","pc","pc","P","match","pc","masker","match","P","fs","path","fs","path","fs","fs","path","fs","record","harnesses","writtenFiles","path","fs","record","path","match","hasEnvVariables","record","restoreFile","match","path","record","masker","record","outro","path","pc","masker","pc","pc","P","match","pc","pc","formatOutcome","formatBackups","formatSummary","masker","match","P","pc","note","match","match","path","isDeepStrictEqual","planEnvFile","isDeepStrictEqual","hasOwnEnvChange","record","isSamePath","path","record","replanEnvFile","writtenFiles","path","record","FINISHED_WITH_ERRORS","masker","key","check","mode","outro","harnesses","fs","path","OWNER_ONLY_MODE","fs","match","path","finish","randomUUID","MS_PER_SECOND","clack","pc","intro","outro","cancel","note","clack","confirm","clack","value","clack","value","clack","clack","clack","clack","clack","clack","clack","clack","log","clack","selectHarnesses","clack","clack","clack","clack","pc","cancel","pc","text","intro","outro","cancel","note","selectHarnesses","confirm","pc","path"]}
|