diff --git a/README.md b/README.md index 09ddb17..c2bb891 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,14 @@ returns immediately and the formatted result is posted into the transcript when refused, so a runaway loop cannot hide behind a queue. Both use the same `REPL_RLM_BUDGET`-overrideable spend default. +Model routing: the `rlm` tool accepts `model`/`provider` to route the loop to a specific model. With +neither, the client resolves a model in order: `REPL_RLM_BASE_URL` (an `https://` OpenAI-compatible +endpoint with `REPL_RLM_API_KEY`/`REPL_RLM_MODEL`), then `REPL_RLM_DEFAULT_MODEL` (+ +`REPL_RLM_DEFAULT_PROVIDER`) with `REPL_RLM_FALLBACK_MODELS` (comma list of `provider/model-id`, tried +on a 429), then the session's main model. Run `/rlm-setup` once after install to bake these exports into +your shell profile: it defaults to the session model (no fallback) and offers a custom model/provider and +a 429 fallback chain (X fallback models → the chain is your default + X). + Each iteration runs in a fresh sandbox — no variables, imports, or state carry over between iterations, so each snippet must be self-contained. Diagnostics fed back to the model are offset-corrected: line numbers refer to the model's own code, and no preamble source is shown diff --git a/coverage-baseline.json b/coverage-baseline.json index 29e9331..d1fe687 100644 --- a/coverage-baseline.json +++ b/coverage-baseline.json @@ -15,7 +15,8 @@ "src/redact.ts": 99.71, "src/registry.ts": 98.45, "src/repl.ts": 100, - "src/rlm_client.ts": 90.76, + "src/rlm_client.ts": 93.27, + "src/rlm_setup.ts": 94.5, "src/rlm_tools.ts": 100, "src/rlm.ts": 99.66, "src/sandbox.ts": 98.14, diff --git a/extensions/repl-extension.ts b/extensions/repl-extension.ts index 555d427..a5ca659 100644 --- a/extensions/repl-extension.ts +++ b/extensions/repl-extension.ts @@ -1,3 +1,5 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; import { defineTool } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { maskSecrets, redact } from "../src/redact.js"; @@ -7,6 +9,13 @@ import { escapeNoticeName } from "../src/toolstore.js"; import type { ApprovalRequest, ApprovalDecision } from "../src/types.js"; import { runRlm, type RlmIteration, type RlmResult } from "../src/rlm.js"; import { createLlmClient, type RlmClientContext } from "../src/rlm_client.js"; +import { + applyRlmExportBlock, + applyRlmSetupEnv, + detectShellProfile, + renderRlmExportBlock, + type RlmSetupConfig, +} from "../src/rlm_setup.js"; // ── The model boundary (src/model_boundary.ts) ─────────────────── // @@ -835,7 +844,11 @@ interface CommandCtx extends RlmClientContext { cwd: string; hasUI: boolean; isProjectTrusted(): boolean; - ui: { notify: (message: string, type?: "info" | "warning" | "error") => void }; + ui: { + notify: (message: string, type?: "info" | "warning" | "error") => void; + confirm: (title: string, message: string) => Promise; + input: (title: string, placeholder?: string) => Promise; + }; } /** Extension registration surface — the subset of pi's API this file uses. */ @@ -1728,4 +1741,75 @@ export default function (pi: ReplExtensionApi) { ctx.ui.notify("rlm: aborting…", "info"); }, }); + + pi.registerCommand("rlm-setup", { + description: + "Configure the rlm model: default model/provider (session model by default) and an optional 429 fallback chain, baked into your shell profile.", + handler: async (_args, ctx) => { + const session = ctx.model; + let model = session?.id ?? ""; + let provider = session?.provider ?? ""; + + let useSession = true; + if (session) { + const label = provider ? `${model} (${provider})` : model; + useSession = await ctx.ui.confirm( + "repl-simple: rlm model", + `Use the session model ${label} as the rlm default?`, + ); + } + + if (!session || !useSession) { + const custom = await ctx.ui.input( + "repl-simple: rlm custom model", + "model id, e.g. openai/gpt-oss-120b", + ); + if (custom === undefined || custom.trim() === "") { + ctx.ui.notify("rlm setup cancelled — no model chosen.", "info"); + return; + } + model = custom.trim(); + const prov = await ctx.ui.input( + "repl-simple: rlm provider", + "provider, e.g. groq (leave empty for none)", + ); + provider = (prov ?? "").trim(); + } + + const fallbackOn = await ctx.ui.confirm( + "repl-simple: rlm fallback", + "Enable a fallback chain, tried in order on HTTP 429?", + ); + let fallbackModels = ""; + if (fallbackOn) { + const chain = await ctx.ui.input( + "repl-simple: rlm fallback chain", + "comma-separated provider/model-id, e.g. groq/qwen/qwen3.8-27b,openrouter/poolside/laguna-s-2.1:free", + ); + fallbackModels = (chain ?? "").trim(); + } + + const config: RlmSetupConfig = { + model, + provider: provider || undefined, + fallbackModels: fallbackModels || undefined, + }; + + const profile = detectShellProfile(process.env.SHELL, homedir()); + const block = renderRlmExportBlock(config, profile); + let current = ""; + try { + current = await readFile(profile, "utf8"); + } catch { + current = ""; + } + await writeFile(profile, applyRlmExportBlock(current, block), "utf8"); + applyRlmSetupEnv(config); + + ctx.ui.notify( + `rlm setup: wrote ${profile}. Applied to this session; run \`source ${profile}\` (or open a new shell) to persist.`, + "info", + ); + }, + }); } diff --git a/skills/repl-simple/SKILL.md b/skills/repl-simple/SKILL.md index c74c864..b2316b9 100644 --- a/skills/repl-simple/SKILL.md +++ b/skills/repl-simple/SKILL.md @@ -34,6 +34,15 @@ Sandboxed Python execution in pi via [Monty](https://github.com/pydantic/monty) The loop's sandbox is **read-only**: the mutating bridge tools (`bash`, `edit`, `write`) and `http_get` are denied, so it reads and reasons over the repo but never changes it. Each call is a multi-LLM-call loop with real cost, bounded by `REPL_RLM_BUDGET` (default 500 000 estimated tokens). +**Model routing** — when the `rlm` tool is called without `model`/`provider` and `REPL_RLM_BASE_URL` +is unset, the client resolves `REPL_RLM_DEFAULT_MODEL` (+ optional `REPL_RLM_DEFAULT_PROVIDER`) through +the host registry, then tries `REPL_RLM_FALLBACK_MODELS` (a comma-separated list of `provider/model-id` +entries) in order on a 429, and finally falls back to the session's main model. + +Run **`/rlm-setup`** once after install to bake these exports into your shell profile. It defaults to +your session model (no fallback) and asks whether to opt in to a custom model/provider and a 429 +fallback chain — X fallback models make the chain your default + X. + The answer is **untrusted** — the inner model's own output, not a verified result. Treat it as a hypothesis to check. Every result carries a `status` (`ok` / `max_iterations` / `budget_exhausted` / `aborted` / `error`) and an `answerSource` (`submitted` / `salvaged` / `synthesised`). **Use `rlm` for:** diff --git a/src/rlm_client.ts b/src/rlm_client.ts index 6067219..719612f 100644 --- a/src/rlm_client.ts +++ b/src/rlm_client.ts @@ -219,10 +219,83 @@ async function completeViaRegistry( return extractText(reply); } +// ── Env-default tier ──────────────────────────────────────────── + +const RLM_DEFAULT_MODEL_VAR = "REPL_RLM_DEFAULT_MODEL"; +const RLM_DEFAULT_PROVIDER_VAR = "REPL_RLM_DEFAULT_PROVIDER"; +const RLM_FALLBACK_MODELS_VAR = "REPL_RLM_FALLBACK_MODELS"; + +/** A non-empty env value, or `undefined`. */ +function envValue(name: string): string | undefined { + const raw = process.env[name]; + if (raw === undefined || raw.trim() === "") return undefined; + return raw.trim(); +} + +/** + * The env-default config from `REPL_RLM_DEFAULT_MODEL` / `REPL_RLM_DEFAULT_PROVIDER`, + * mirroring the injected `{ model, provider }` shape. Undefined when neither is + * set (the tier is off). + */ +function envDefaultConfig(): RlmClientConfig | undefined { + const model = envValue(RLM_DEFAULT_MODEL_VAR); + const provider = envValue(RLM_DEFAULT_PROVIDER_VAR); + if (!model && !provider) return undefined; + return { model, provider }; +} + +/** + * Parse `REPL_RLM_FALLBACK_MODELS`, a comma-separated list of + * `provider/model-id` entries (split on the first `/`), or bare `model-id` + * entries. Empty and whitespace entries are dropped. + */ +function parseFallbackConfigs(raw: string | undefined): RlmClientConfig[] { + if (!raw || raw.trim() === "") return []; + return raw + .split(",") + .map((entry) => entry.trim()) + .filter((entry) => entry !== "") + .map((entry) => { + const slash = entry.indexOf("/"); + if (slash === -1) return { model: entry }; + return { provider: entry.slice(0, slash), model: entry.slice(slash + 1) }; + }); +} + +/** True when an error is a provider rate limit (HTTP 429) worth falling back from. */ +function isRateLimitError(err: unknown): boolean { + return err instanceof Error && /429/.test(err.message); +} + +/** + * Call the registry with each model in order, skipping to the next only on a + * 429 rate-limit error. A non-429 error rethrows immediately (it is not a + * quota problem another model can fix), and an exhausted list rethrows the + * last error. + */ +async function completeViaRegistryWithFallback( + registry: RlmModelRegistry, + models: RlmModel[], + systemPrompt: string, + messages: Array<{ role: "user" | "assistant"; content: string }>, + signal?: AbortSignal, +): Promise { + let lastError: unknown; + for (const model of models) { + try { + return await completeViaRegistry(registry, model, systemPrompt, messages, signal); + } catch (err) { + lastError = err; + if (!isRateLimitError(err)) throw err; + } + } + throw lastError; +} + // ── Factory ────────────────────────────────────────────────────── /** - * Build an `LlmClient` that routes calls to one of three tiers, in priority + * Build an `LlmClient` that routes calls to one of four tiers, in priority * order: * * 1. **Injected** — `config.model` / `config.provider` resolve a model through @@ -230,7 +303,10 @@ async function completeViaRegistry( * `modelRegistry.complete` (which handles per-model auth, OAuth included). * 2. **Env** — `process.env.REPL_RLM_BASE_URL` (an `https://` OpenAI-compatible * endpoint) with `REPL_RLM_API_KEY` and `REPL_RLM_MODEL` (default `"rlm"`). - * 3. **Default** — `ctx.model` via `modelRegistry.complete`. + * 3. **Env-default** — `REPL_RLM_DEFAULT_MODEL` / `REPL_RLM_DEFAULT_PROVIDER` + * resolve a model through the same registry, then `REPL_RLM_FALLBACK_MODELS` + * (comma list of `provider/model-id`) are tried in order on a 429. + * 4. **Default** — `ctx.model` via `modelRegistry.complete`. */ export function createLlmClient(ctx: RlmClientContext, config: RlmClientConfig = {}): LlmClient { return { @@ -248,10 +324,31 @@ export function createLlmClient(ctx: RlmClientContext, config: RlmClientConfig = return completeViaEnvEndpoint(systemPrompt, messages, signal, baseUrl); } + const defaultConfig = envDefaultConfig(); + if (defaultConfig) { + const primary = resolveInjectedModel(ctx, defaultConfig); + if (!primary) { + throw new Error( + `RLM model not found for ${describeConfig(defaultConfig)} ` + + `(${RLM_DEFAULT_MODEL_VAR}/${RLM_DEFAULT_PROVIDER_VAR})`, + ); + } + const fallbacks = parseFallbackConfigs(process.env[RLM_FALLBACK_MODELS_VAR]) + .map((fallback) => resolveInjectedModel(ctx, fallback)) + .filter((model): model is RlmModel => model !== undefined); + return completeViaRegistryWithFallback( + ctx.modelRegistry, + [primary, ...fallbacks], + systemPrompt, + messages, + signal, + ); + } + if (!ctx.model) { throw new Error( "RLM client has no model: set config.model/config.provider, " + - "REPL_RLM_BASE_URL, or ctx.model", + "REPL_RLM_BASE_URL, REPL_RLM_DEFAULT_MODEL, or ctx.model", ); } return completeViaRegistry(ctx.modelRegistry, ctx.model, systemPrompt, messages, signal); diff --git a/src/rlm_setup.ts b/src/rlm_setup.ts new file mode 100644 index 0000000..5c12dab --- /dev/null +++ b/src/rlm_setup.ts @@ -0,0 +1,91 @@ +// Pure helpers for the `/rlm-setup` command: resolve the shell profile that +// holds the RLM exports, render the managed export block, and rewrite a +// profile's content idempotently. Free of I/O so the file and env mutation +// stay in the extension and the logic is unit-testable. + +/** The env-config knobs the rlm client reads (see `src/rlm_client.ts`). */ +export interface RlmSetupConfig { + model?: string; + provider?: string; + /** Comma-separated `provider/model-id` fallbacks; empty/undefined = no fallback line. */ + fallbackModels?: string; +} + +export const RLM_BLOCK_START = "# >>> repl-simple rlm (managed) >>>"; +export const RLM_BLOCK_END = "# <<< repl-simple rlm (managed) <<<"; + +const RLM_ENV_VARS = { + model: "REPL_RLM_DEFAULT_MODEL", + provider: "REPL_RLM_DEFAULT_PROVIDER", + fallbackModels: "REPL_RLM_FALLBACK_MODELS", +} as const; + +/** The shell profile that should hold the exports for the given shell. */ +export function detectShellProfile(shellEnv: string | undefined, homeDir: string): string { + const base = shellEnv ? (shellEnv.split("/").pop() ?? "") : ""; + if (base === "fish") return `${homeDir}/.config/fish/config.fish`; + if (base === "zsh") return `${homeDir}/.zshrc`; + if (base === "bash") return `${homeDir}/.bashrc`; + return `${homeDir}/.profile`; +} + +function isFishProfile(profilePath: string): boolean { + return profilePath.endsWith("/config.fish"); +} + +/** Quote a value for a double-quoted shell assignment. */ +function shellQuote(value: string): string { + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +/** + * Render the managed export block. Fish profiles use `set -gx`; everything + * else uses `export`. Empty fields are omitted, so disabling fallback removes + * the line rather than exporting an empty string. + */ +export function renderRlmExportBlock(config: RlmSetupConfig, profilePath: string): string { + const fish = isFishProfile(profilePath); + const lines: string[] = [RLM_BLOCK_START]; + const assign = (name: string, value: string): string => + fish ? `set -gx ${name} ${shellQuote(value)}` : `export ${name}=${shellQuote(value)}`; + + if (config.model) lines.push(assign(RLM_ENV_VARS.model, config.model)); + if (config.provider) lines.push(assign(RLM_ENV_VARS.provider, config.provider)); + if (config.fallbackModels) lines.push(assign(RLM_ENV_VARS.fallbackModels, config.fallbackModels)); + lines.push(RLM_BLOCK_END); + return lines.join("\n"); +} + +/** + * Rewrite `current` with `block` in place of any existing managed block, or + * append it when none is present. An unterminated start marker is treated as + * an empty block and replaced. + */ +export function applyRlmExportBlock(current: string, block: string): string { + const start = current.indexOf(RLM_BLOCK_START); + if (start === -1) { + const separator = current === "" || current.endsWith("\n") ? "" : "\n"; + return `${current}${separator}${block}\n`; + } + const end = current.indexOf(RLM_BLOCK_END, start); + if (end === -1) { + return `${current.slice(0, start)}${block}\n`; + } + const endLine = current.indexOf("\n", end); + const tail = endLine === -1 ? "" : current.slice(endLine + 1); + return `${current.slice(0, start)}${block}\n${tail}`; +} + +/** Set (or clear) the rlm env vars in the current process. */ +export function applyRlmSetupEnv(config: RlmSetupConfig): void { + const entries: Array<[string, string | undefined]> = [ + [RLM_ENV_VARS.model, config.model], + [RLM_ENV_VARS.provider, config.provider], + [RLM_ENV_VARS.fallbackModels, config.fallbackModels], + ]; + for (const [key, value] of entries) { + const trimmed = value?.trim(); + if (trimmed) process.env[key] = trimmed; + else delete process.env[key]; + } +} diff --git a/test/extension.test.ts b/test/extension.test.ts index fe8d058..3c92f25 100644 --- a/test/extension.test.ts +++ b/test/extension.test.ts @@ -590,6 +590,170 @@ describe("repl extension — /rlm command", () => { }); }); +// ── /rlm-setup ─────────────────────────────────────────────────── +// +// The one-shot install command: interactive (confirm/input), defaults to the +// session model with no fallback, and writes an idempotent managed block to +// the shell profile. Tests drive the dialogs with canned answers and point +// HOME at a temp dir so the file write is observable. + +describe("repl extension — /rlm-setup command", () => { + const RLM_KEYS = [ + "REPL_RLM_DEFAULT_MODEL", + "REPL_RLM_DEFAULT_PROVIDER", + "REPL_RLM_FALLBACK_MODELS", + ] as const; + + interface Answers { + confirm: boolean[]; + inputs: Array; + } + + function makeCtx(model: { id: string; provider?: string } | undefined, answers: Answers) { + const notes: Array<{ message: string; type?: string }> = []; + const ctx = { + model, + ui: { + notify: (message: string, type?: string) => notes.push({ message, type }), + confirm: async () => answers.confirm.shift() ?? false, + input: async () => answers.inputs.shift(), + }, + }; + return { ctx, notes }; + } + + function saveEnv(keys: readonly string[]): Map { + return new Map(keys.map((k) => [k, process.env[k]])); + } + + function restoreEnv(saved: Map): void { + for (const [k, v] of saved) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } + + async function runSetup( + model: { id: string; provider?: string } | undefined, + answers: Answers, + ): Promise<{ home: string; notes: Array<{ message: string; type?: string }> }> { + const home = mkdtempSync(join(tmpdir(), "repl-ext-rlm-setup-")); + const savedHome = process.env.HOME; + const savedShell = process.env.SHELL; + const savedRlm = saveEnv(RLM_KEYS); + process.env.HOME = home; + process.env.SHELL = "/bin/zsh"; + try { + const { commands } = await load(); + const setup = commands.find((c) => c.name === "rlm-setup"); + assert.ok(setup, "/rlm-setup did not register"); + const { ctx, notes } = makeCtx(model, answers); + await setup.handler("", ctx as never); + return { home, notes }; + } finally { + restoreEnv(savedRlm); + if (savedHome === undefined) delete process.env.HOME; + else process.env.HOME = savedHome; + if (savedShell === undefined) delete process.env.SHELL; + else process.env.SHELL = savedShell; + } + } + + it("defaults to the session model with no fallback", async () => { + const { home, notes } = await runSetup( + { id: "deepseek-v4-pro", provider: "deepseek" }, + { confirm: [true, false], inputs: [] }, + ); + const profile = readFileSync(join(home, ".zshrc"), "utf8"); + assert.match(profile, /export REPL_RLM_DEFAULT_MODEL="deepseek-v4-pro"/); + assert.match(profile, /export REPL_RLM_DEFAULT_PROVIDER="deepseek"/); + assert.doesNotMatch(profile, /REPL_RLM_FALLBACK_MODELS/); + assert.ok(notes.some((n) => /\.zshrc/.test(n.message))); + rmSync(home, { recursive: true, force: true }); + }); + + it("opts into a custom model and provider", async () => { + const { home } = await runSetup( + { id: "session-model", provider: "session-provider" }, + { confirm: [false, false], inputs: ["custom-model", "custom-provider"] }, + ); + const profile = readFileSync(join(home, ".zshrc"), "utf8"); + assert.match(profile, /export REPL_RLM_DEFAULT_MODEL="custom-model"/); + assert.match(profile, /export REPL_RLM_DEFAULT_PROVIDER="custom-provider"/); + rmSync(home, { recursive: true, force: true }); + }); + + it("renders the model label without a provider when the session has none", async () => { + const { home } = await runSetup({ id: "bare-model" }, { confirm: [true, false], inputs: [] }); + const profile = readFileSync(join(home, ".zshrc"), "utf8"); + assert.match(profile, /export REPL_RLM_DEFAULT_MODEL="bare-model"/); + assert.doesNotMatch(profile, /REPL_RLM_DEFAULT_PROVIDER/); + rmSync(home, { recursive: true, force: true }); + }); + + it("opts into a fallback chain", async () => { + const { home } = await runSetup( + { id: "m", provider: "p" }, + { confirm: [true, true], inputs: ["groq/a,openrouter/b"] }, + ); + const profile = readFileSync(join(home, ".zshrc"), "utf8"); + assert.match(profile, /export REPL_RLM_FALLBACK_MODELS="groq\/a,openrouter\/b"/); + rmSync(home, { recursive: true, force: true }); + }); + + it("cancels when the custom model is empty", async () => { + const { home, notes } = await runSetup( + { id: "session-model" }, + { confirm: [false], inputs: [""] }, + ); + assert.equal(existsSync(join(home, ".zshrc")), false); + assert.ok(notes.some((n) => /cancelled/.test(n.message))); + rmSync(home, { recursive: true, force: true }); + }); + + it("asks for a model when there is no session model", async () => { + const { home } = await runSetup(undefined, { confirm: [false], inputs: ["m1", "p1"] }); + const profile = readFileSync(join(home, ".zshrc"), "utf8"); + assert.match(profile, /export REPL_RLM_DEFAULT_MODEL="m1"/); + assert.match(profile, /export REPL_RLM_DEFAULT_PROVIDER="p1"/); + rmSync(home, { recursive: true, force: true }); + }); + + it("preserves existing profile content and replaces a prior managed block", async () => { + const home = mkdtempSync(join(tmpdir(), "repl-ext-rlm-setup-")); + const savedHome = process.env.HOME; + const savedShell = process.env.SHELL; + const savedRlm = saveEnv(RLM_KEYS); + process.env.HOME = home; + process.env.SHELL = "/bin/zsh"; + try { + const profile = join(home, ".zshrc"); + writeFileSync( + profile, + 'export PATH=/usr/bin\n# >>> repl-simple rlm (managed) >>>\nexport REPL_RLM_DEFAULT_MODEL="old"\n# <<< repl-simple rlm (managed) <<<\ntail-line\n', + ); + const { commands } = await load(); + const setup = commands.find((c) => c.name === "rlm-setup"); + assert.ok(setup); + const { ctx } = makeCtx({ id: "m", provider: "p" }, { confirm: [true, false], inputs: [] }); + await setup.handler("", ctx as never); + + const content = readFileSync(profile, "utf8"); + assert.match(content, /export PATH=\/usr\/bin/); + assert.match(content, /export REPL_RLM_DEFAULT_MODEL="m"/); + assert.doesNotMatch(content, /"old"/); + assert.match(content, /tail-line/); + } finally { + restoreEnv(savedRlm); + if (savedHome === undefined) delete process.env.HOME; + else process.env.HOME = savedHome; + if (savedShell === undefined) delete process.env.SHELL; + else process.env.SHELL = savedShell; + rmSync(home, { recursive: true, force: true }); + } + }); +}); + // ── RLM trace details ──────────────────────────────────────────── // // The `rlm` tool and `/rlm` command now persist the whole run — question, @@ -1243,11 +1407,11 @@ describe("repl extension — approval mode", () => { if (cwd) rmSync(cwd, { recursive: true, force: true }); }); - it("registers /repl-approvals, /repl-accept-preamble, /rlm, and /rlm-abort (#198)", async () => { + it("registers /repl-approvals, /repl-accept-preamble, /rlm, /rlm-abort, and /rlm-setup (#198)", async () => { const { commands } = await load(); assert.deepEqual( commands.map((c) => c.name), - ["repl-approvals", "repl-accept-preamble", "rlm", "rlm-abort"], + ["repl-approvals", "repl-accept-preamble", "rlm", "rlm-abort", "rlm-setup"], ); for (const command of commands) { assert.ok(command.description, `${command.name} needs a description to be discoverable`); diff --git a/test/rlm_client.test.ts b/test/rlm_client.test.ts index ffab341..7449f63 100644 --- a/test/rlm_client.test.ts +++ b/test/rlm_client.test.ts @@ -417,4 +417,206 @@ describe("createLlmClient", () => { assert.equal(text, ""); assert.equal(calls.length, 1); }); + + it("env-default tier routes through modelRegistry.complete when REPL_RLM_DEFAULT_MODEL is set", async () => { + const { calls, registry } = makeRegistry("env-default reply"); + const client = createLlmClient({ + model: undefined, + modelRegistry: registry, + scopedModels: [{ model: { id: "free-model" } }], + }); + + await withEnv({ REPL_RLM_DEFAULT_MODEL: "free-model" }, async () => { + const text = await client.query("sys", [{ role: "user", content: "hi" }]); + assert.equal(text, "env-default reply"); + }); + + assert.equal(calls.length, 1); + assert.equal(calls[0].model.id, "free-model"); + }); + + it("env-default tier rejects when the default model does not resolve", async () => { + const { calls, registry } = makeRegistry("unused"); + const client = createLlmClient({ model: undefined, modelRegistry: registry }); + + await withEnv({ REPL_RLM_DEFAULT_MODEL: "missing" }, async () => { + await assert.rejects( + client.query("sys", [{ role: "user", content: "hi" }]), + /RLM model not found/, + ); + }); + assert.equal(calls.length, 0); + }); + + it("env-default tier falls back to REPL_RLM_FALLBACK_MODELS on a 429", async () => { + const calls: RecordedCall[] = []; + const registry: RlmModelRegistry = { + find(provider, modelId) { + return { id: `${provider}/${modelId}`, provider }; + }, + complete(model, context, options) { + calls.push({ model, context, options }); + if (model.id === "groq/primary") { + return Promise.reject(new Error("429: rate limit")); + } + return Promise.resolve({ content: [{ type: "text", text: "fallback reply" }] }); + }, + }; + + const client = createLlmClient({ model: undefined, modelRegistry: registry }); + + await withEnv( + { + REPL_RLM_DEFAULT_MODEL: "primary", + REPL_RLM_DEFAULT_PROVIDER: "groq", + REPL_RLM_FALLBACK_MODELS: "openrouter/fallback-model", + }, + async () => { + const text = await client.query("sys", [{ role: "user", content: "hi" }]); + assert.equal(text, "fallback reply"); + }, + ); + + assert.equal(calls.length, 2); + assert.equal(calls[0].model.id, "groq/primary"); + assert.equal(calls[1].model.id, "openrouter/fallback-model"); + }); + + it("env-default tier does not fall back on a non-429 error", async () => { + const calls: RecordedCall[] = []; + const registry: RlmModelRegistry = { + find(provider, modelId) { + return { id: `${provider}/${modelId}`, provider }; + }, + complete(model, context, options) { + calls.push({ model, context, options }); + return Promise.reject(new Error("500: server error")); + }, + }; + + const client = createLlmClient({ model: undefined, modelRegistry: registry }); + + await withEnv( + { + REPL_RLM_DEFAULT_MODEL: "primary", + REPL_RLM_DEFAULT_PROVIDER: "groq", + REPL_RLM_FALLBACK_MODELS: "openrouter/fallback-model", + }, + async () => { + await assert.rejects( + client.query("sys", [{ role: "user", content: "hi" }]), + /500: server error/, + ); + }, + ); + + assert.equal(calls.length, 1); + assert.equal(calls[0].model.id, "groq/primary"); + }); + + it("env-default tier rethrows the last 429 when every model is rate-limited", async () => { + const calls: RecordedCall[] = []; + const registry: RlmModelRegistry = { + find(provider, modelId) { + return { id: `${provider}/${modelId}`, provider }; + }, + complete(model, context, options) { + calls.push({ model, context, options }); + return Promise.reject(new Error("429: rate limit")); + }, + }; + + const client = createLlmClient({ model: undefined, modelRegistry: registry }); + + await withEnv( + { + REPL_RLM_DEFAULT_MODEL: "primary", + REPL_RLM_DEFAULT_PROVIDER: "groq", + REPL_RLM_FALLBACK_MODELS: "openrouter/fallback-model,nvidia/third", + }, + async () => { + await assert.rejects( + client.query("sys", [{ role: "user", content: "hi" }]), + /429: rate limit/, + ); + }, + ); + + assert.equal(calls.length, 3); + }); + + it("injected tier wins over the env-default tier", async () => { + const { calls, registry } = makeRegistry("injected wins"); + const client = createLlmClient( + { + model: undefined, + modelRegistry: registry, + scopedModels: [{ model: { id: "injected-model" } }, { model: { id: "env-model" } }], + }, + { model: "injected-model" }, + ); + + await withEnv({ REPL_RLM_DEFAULT_MODEL: "env-model" }, async () => { + const text = await client.query("sys", [{ role: "user", content: "hi" }]); + assert.equal(text, "injected wins"); + }); + + assert.equal(calls.length, 1); + assert.equal(calls[0].model.id, "injected-model"); + }); + + it("env endpoint tier wins over the env-default tier", async () => { + const { registry } = makeRegistry("unused"); + const client = createLlmClient({ model: undefined, modelRegistry: registry }); + + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => { + return new Response( + JSON.stringify({ choices: [{ message: { content: "endpoint wins" } }] }), + { + status: 200, + }, + ); + }) as typeof fetch; + + try { + await withEnv( + { REPL_RLM_BASE_URL: "https://api.example.com", REPL_RLM_DEFAULT_MODEL: "env-model" }, + async () => { + const text = await client.query("sys", [{ role: "user", content: "hi" }]); + assert.equal(text, "endpoint wins"); + }, + ); + } finally { + globalThis.fetch = originalFetch; + } + }); + + it("env-default fallback accepts a bare model-id resolved through scopedModels", async () => { + const calls: RecordedCall[] = []; + const registry: RlmModelRegistry = { + complete(model, context, options) { + calls.push({ model, context, options }); + if (model.id === "primary") return Promise.reject(new Error("429: rate limit")); + return Promise.resolve({ content: [{ type: "text", text: "bare fallback reply" }] }); + }, + }; + const client = createLlmClient({ + model: undefined, + modelRegistry: registry, + scopedModels: [{ model: { id: "primary" } }, { model: { id: "bare-fallback" } }], + }); + + await withEnv( + { REPL_RLM_DEFAULT_MODEL: "primary", REPL_RLM_FALLBACK_MODELS: "bare-fallback" }, + async () => { + const text = await client.query("sys", [{ role: "user", content: "hi" }]); + assert.equal(text, "bare fallback reply"); + }, + ); + + assert.equal(calls.length, 2); + assert.equal(calls[0].model.id, "primary"); + assert.equal(calls[1].model.id, "bare-fallback"); + }); }); diff --git a/test/rlm_setup.test.ts b/test/rlm_setup.test.ts new file mode 100644 index 0000000..f300cbe --- /dev/null +++ b/test/rlm_setup.test.ts @@ -0,0 +1,113 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + RLM_BLOCK_END, + RLM_BLOCK_START, + applyRlmExportBlock, + applyRlmSetupEnv, + detectShellProfile, + renderRlmExportBlock, +} from "../src/rlm_setup.js"; + +describe("detectShellProfile", () => { + it("maps zsh, bash, fish, and unknown shells", () => { + assert.equal(detectShellProfile("/bin/zsh", "/home/u"), "/home/u/.zshrc"); + assert.equal(detectShellProfile("/bin/bash", "/home/u"), "/home/u/.bashrc"); + assert.equal( + detectShellProfile("/usr/bin/fish", "/home/u"), + "/home/u/.config/fish/config.fish", + ); + assert.equal(detectShellProfile(undefined, "/home/u"), "/home/u/.profile"); + assert.equal(detectShellProfile("/bin/sh", "/home/u"), "/home/u/.profile"); + }); +}); + +describe("renderRlmExportBlock", () => { + it("renders export lines and omits empty fields", () => { + const block = renderRlmExportBlock( + { model: "deepseek-v4-pro", provider: "deepseek" }, + "/home/u/.zshrc", + ); + assert.deepEqual(block.split("\n"), [ + RLM_BLOCK_START, + 'export REPL_RLM_DEFAULT_MODEL="deepseek-v4-pro"', + 'export REPL_RLM_DEFAULT_PROVIDER="deepseek"', + RLM_BLOCK_END, + ]); + }); + + it("renders the fallback line only when set", () => { + const block = renderRlmExportBlock( + { model: "m1", fallbackModels: "groq/a,openrouter/b" }, + "/home/u/.bashrc", + ); + assert.ok(block.includes('export REPL_RLM_FALLBACK_MODELS="groq/a,openrouter/b"')); + assert.ok(!block.includes("REPL_RLM_DEFAULT_PROVIDER")); + }); + + it("uses fish set -gx syntax", () => { + const block = renderRlmExportBlock( + { model: "m1", provider: "p1" }, + "/home/u/.config/fish/config.fish", + ); + assert.ok(block.includes('set -gx REPL_RLM_DEFAULT_MODEL "m1"')); + assert.ok(block.includes('set -gx REPL_RLM_DEFAULT_PROVIDER "p1"')); + }); + + it("escapes quotes and backslashes in values", () => { + const block = renderRlmExportBlock({ model: 'a"b\\c' }, "/home/u/.bashrc"); + assert.ok(block.includes('export REPL_RLM_DEFAULT_MODEL="a\\"b\\\\c"')); + }); +}); + +describe("applyRlmExportBlock", () => { + const block = "BLOCK"; + + it("appends to empty content", () => { + assert.equal(applyRlmExportBlock("", block), `${block}\n`); + }); + + it("appends to non-empty content with a separating newline", () => { + assert.equal(applyRlmExportBlock("line1\n", block), `line1\n${block}\n`); + assert.equal(applyRlmExportBlock("line1", block), `line1\n${block}\n`); + }); + + it("replaces an existing managed block", () => { + const before = `keep\n${RLM_BLOCK_START}\nold\n${RLM_BLOCK_END}\nafter\n`; + const expected = `keep\n${block}\nafter\n`; + assert.equal(applyRlmExportBlock(before, block), expected); + }); + + it("replaces an unterminated start marker", () => { + const before = `keep\n${RLM_BLOCK_START}\nold line without end`; + assert.equal(applyRlmExportBlock(before, block), `keep\n${block}\n`); + }); +}); + +describe("applyRlmSetupEnv", () => { + const KEYS = [ + "REPL_RLM_DEFAULT_MODEL", + "REPL_RLM_DEFAULT_PROVIDER", + "REPL_RLM_FALLBACK_MODELS", + ] as const; + + it("sets and clears the rlm env vars", () => { + const saved = new Map(KEYS.map((k) => [k, process.env[k]])); + try { + applyRlmSetupEnv({ model: "m", provider: "p", fallbackModels: "a/b" }); + assert.equal(process.env.REPL_RLM_DEFAULT_MODEL, "m"); + assert.equal(process.env.REPL_RLM_DEFAULT_PROVIDER, "p"); + assert.equal(process.env.REPL_RLM_FALLBACK_MODELS, "a/b"); + + applyRlmSetupEnv({ model: "m2" }); + assert.equal(process.env.REPL_RLM_DEFAULT_MODEL, "m2"); + assert.equal(process.env.REPL_RLM_DEFAULT_PROVIDER, undefined); + assert.equal(process.env.REPL_RLM_FALLBACK_MODELS, undefined); + } finally { + for (const [k, v] of saved) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } + }); +});