Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion coverage-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
86 changes: 85 additions & 1 deletion extensions/repl-extension.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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) ───────────────────
//
Expand Down Expand Up @@ -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<boolean>;
input: (title: string, placeholder?: string) => Promise<string | undefined>;
};
}

/** Extension registration surface — the subset of pi's API this file uses. */
Expand Down Expand Up @@ -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",
);
},
});
}
9 changes: 9 additions & 0 deletions skills/repl-simple/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:**
Expand Down
103 changes: 100 additions & 3 deletions src/rlm_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,18 +219,94 @@ 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<string> {
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
* `ctx.scopedModels` / `ctx.modelRegistry`, dispatched via
* `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 {
Expand All @@ -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);
Expand Down
91 changes: 91 additions & 0 deletions src/rlm_setup.ts
Original file line number Diff line number Diff line change
@@ -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];
}
}
Loading
Loading