mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-05 23:19:43 +02:00
Custom Model Endpoint Profiles (#393) let a session point its CLI at a custom OpenAI-compatible endpoint by injecting env vars or a config file and restarting the CLI in place. Review of the apply path found four things, two of them destructive. This lands all four plus the smaller items from the same review. 1. Clearing a selection did not clear it. The injected vars reach the CLI via `tmux setenv`, which persists at the tmux-session level and is inherited by `respawn-pane` (measured: `setenv FOO bar` survived two successive `respawn-pane -k`), so deleting the keys from the session's envOverrides relaunched the CLI still pointed at the old endpoint, and for the configDir kinds at a HOME/CODEX_HOME/GROK_HOME that had just been deleted. `Session.setCustomModel()` now reports the removed keys, queues them (`_pendingEnvUnsets`), and `RespawnPaneOptions.unsetEnvKeys` carries them into `applyEnvOverrides()`, which `setenv -u`s them before re-applying the live overrides, on the same path that already unsets the legacy CLAUDE_CODE_EFFORT_LEVEL. Verified on a private tmux socket that `setenv -u HOME` hands the next respawn the global HOME back. 2. Applying a model to a local claude session killed the pane. The relaunch was `claude --session-id <id>` and Claude refuses an id that already has a transcript, and unlike the dead-pane respawn this one kills a working pane first. `restartCli()` now pins the live conversation id as the resume id for that respawn when the CLI's launch declares a `fallback` chain, which renders the same `--resume <id> || --session-id <id>` shape the docker and remote pane commands use. Gated on the registry shape, not the CLI id: an entry whose resume id is minted by the CLI itself never declares that chain. 3. pi, omp and grok wrote their config file and then launched without the `--model` that selects it, so the file was ignored. The registry entry now declares `customModelInjection.launchModel` (`custom/{modelId}` for pi and omp, grok's `[model.codeman-custom]` block name), the builder renders it, and `_withCustomModelLaunchModel()` applies it onto the respawn options through `legacyConfigField`, leaving the stored <Mode>Config untouched so a clear falls back to the user's own model. A model id the CLI's `model` token pattern cannot carry is refused with a 400 rather than silently dropped by the argv engine. 4. Remote (SSH) and Docker sessions reported `restarted: true` and changed nothing: their `restartCli()` reattaches the durable tmux rather than relaunching the agent, and the env lands on the local pane. Both are refused with a 400 until those paths are plumbed. Smaller items from the same review: - The selection survives a Codeman restart as the disk-only `__customModel` bookkeeping (endpoint, model, injected key NAMES, config dir, launch model; never the values, which carry the API key). Recovery re-derives the values from the endpoint store through the same apply path the route uses and keeps the bookkeeping even when the endpoint is gone, so a later clear still has keys to unset. - Discovery goes through `webviewFetch()`, so the RESOLVED address is judged by the same egress guard the web-tab proxy uses, and `baseUrl` reuses `webviewUrlSchema` (http(s) only, no embedded credentials, link-local and cloud-metadata addresses refused). undici's `fetch failed` wrapper is unwrapped so the user sees the ECONNREFUSED underneath. - `custom-model-hosts.json` is written 0600 via tmp+rename, the per-session config dir 0700/0600 (pi and omp embed the key literally), and that dir is removed with the session. - `PR.md` is gone from the repo root and the design doc moved to `docs/custom-model-endpoints-plan.md` with the LAN address and the personal name scrubbed; every reference follows. The guide's `authStyle` text matches the shipped schema (`bearer | api-key`, default `bearer`) and says that `customModelEndpointsEnabled` is read by nothing until the picker lands. - `config/tsconfig.scripts.json` typechecks `scripts/test-local-llm-harnesses.ts` (four real type errors fixed). It is not yet wired into `npm run typecheck` because that line differs on master; adding `&& tsc -p config/tsconfig.scripts.json` there is the one-line follow-up. Tests: `test/session-custom-model-restart.test.ts` drives a real Session and fails on the unfixed code for items 1 to 3; the route suite covers item 4 and the pattern refusal; `test/tmux-manager.test.ts` pins that the unsets run before the overrides and that a shell-metachar key never reaches tmux. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
97 lines
4.0 KiB
TypeScript
97 lines
4.0 KiB
TypeScript
/**
|
|
* @fileoverview The one IO wrapper around `custom-model-injection.ts`'s pure
|
|
* `ConfigDirInjection` output — deliberately split out so that file, the
|
|
* discovery routes, and `scripts/test-local-llm-harnesses.ts` (via tsx) can
|
|
* all share EXACTLY one "write these files, merge this env" implementation.
|
|
* Before this existed, the route and the standalone script each carried
|
|
* their own copy of this logic, which is exactly the kind of drift the CLI
|
|
* registry's "declare once, consume everywhere" design exists to prevent —
|
|
* see docs/custom-model-endpoints-plan.md and the "dynamic to support
|
|
* cli-registry changes" requirement it was written against.
|
|
*/
|
|
|
|
import { chmodSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
|
import { join, dirname } from 'node:path';
|
|
import { dataPath } from './config/instance.js';
|
|
import type { CliEntry } from './config/cli-registry/types.js';
|
|
import {
|
|
buildCustomModelInjection,
|
|
type ConfigDirInjection,
|
|
type CustomModelEndpoint,
|
|
} from './custom-model-injection.js';
|
|
|
|
/** Where a session's isolated `configDir`-kind files live: never the user's real CLI config path. */
|
|
export function customModelConfigDir(sessionId: string): string {
|
|
return join(dataPath('custom-model-configs'), sessionId);
|
|
}
|
|
|
|
/**
|
|
* Writes a `ConfigDirInjection`'s files under `baseDir` and returns the full
|
|
* envOverrides object a caller should merge into the session/process env
|
|
* (the dir-redirect var plus any `extraEnv` the config file references by
|
|
* name). Never touches anything outside `baseDir` — the caller is
|
|
* responsible for choosing an isolated directory (never the user's real
|
|
* `~/.codex`, `~/.pi`, etc.).
|
|
*
|
|
* pi and omp embed the API key literally in the file, so the tree is written
|
|
* 0700/0600 like every other secret-bearing file under `~/.codeman`; the chmod
|
|
* covers a re-apply onto a file that already exists (`mode` only applies at
|
|
* creation).
|
|
*/
|
|
export function applyConfigDirInjection(baseDir: string, injection: ConfigDirInjection): Record<string, string> {
|
|
for (const file of injection.files) {
|
|
const filePath = join(baseDir, file.relPath);
|
|
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
|
writeFileSync(filePath, file.content, { encoding: 'utf8', mode: 0o600 });
|
|
chmodSync(filePath, 0o600);
|
|
}
|
|
return { [injection.dirEnvVar]: baseDir, ...injection.extraEnv };
|
|
}
|
|
|
|
/** Best-effort recursive removal of a previously-written configDir. Never throws. */
|
|
export function removeConfigDir(dir: string | undefined): void {
|
|
if (!dir) return;
|
|
try {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
} catch {
|
|
// best-effort cleanup only
|
|
}
|
|
}
|
|
|
|
/** What applying an endpoint to a session yields, ready for `Session.setCustomModel()`. */
|
|
export interface AppliedCustomModel {
|
|
envOverrides: Record<string, string>;
|
|
envKeys: string[];
|
|
configDir?: string;
|
|
launchModel?: string;
|
|
}
|
|
|
|
/**
|
|
* Compute (and for the `configDir` kind, write) everything a session needs to run
|
|
* against `endpoint`/`modelId`. Returns undefined for a CLI with no mechanism.
|
|
*
|
|
* Idempotent on purpose: the boot-recovery path calls it again for a session that
|
|
* was already pointed at an endpoint, so the config files are rewritten in place
|
|
* (same content) and the env values, which are never persisted because they carry
|
|
* the API key, are re-derived from the endpoint store instead.
|
|
*/
|
|
export function applyCustomModelInjection(
|
|
entry: Pick<CliEntry, 'capabilities'>,
|
|
endpoint: CustomModelEndpoint,
|
|
modelId: string,
|
|
sessionId: string
|
|
): AppliedCustomModel | undefined {
|
|
const injection = buildCustomModelInjection(entry, endpoint, modelId);
|
|
if (injection.kind === 'unsupported') return undefined;
|
|
if (injection.kind === 'env') {
|
|
return {
|
|
envOverrides: injection.envOverrides,
|
|
envKeys: Object.keys(injection.envOverrides),
|
|
launchModel: injection.launchModel,
|
|
};
|
|
}
|
|
const configDir = customModelConfigDir(sessionId);
|
|
const envOverrides = applyConfigDirInjection(configDir, injection);
|
|
return { envOverrides, envKeys: Object.keys(envOverrides), configDir, launchModel: injection.launchModel };
|
|
}
|