A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Let subagents be spawned with their own reasoning level (#1510)
Sebastian Müller824a9ee3b51e
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex b352e3e250..a6dbf5fd94 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,7 @@## [Unreleased]+- Added a `thinking` option to `rlm.run` for spawning subagents with an explicit reasoning level; invalid levels for the resolved child model fail spawn.- Changed opening the agents view (full or scoped) with a draft prompt to auto-stash the draft instead of refusing; the draft is restored into the editor when the session is reopened.- Fixed Shift+Enter no longer inserting a newline in terminals that send a literal `\n` (for example a Ghostty `shift+enter=text:\n` mapping): the byte decoded as `ctrl+j` and triggered the new edit-diff toggle instead of the editor newline.- Removed a system prompt paragraph referring to an async `bash()` kernel helper and managed jobs that do not exist in the runtime.diff --git a/packages/coding-agent/docs/rlm-runtime.md b/packages/coding-agent/docs/rlm-runtime.mdindex 4de095cf01..39573e7a80 100644--- a/packages/coding-agent/docs/rlm-runtime.md+++ b/packages/coding-agent/docs/rlm-runtime.md@@ -150,8 +150,9 @@ await rlm.run("subtask")Supported `rlm.run` options are:-- `name`: a unique readable child session name; and-- `model`: an exact `provider/model` selector from `rlm.find_models()`.+- `name`: a unique readable child session name;+- `model`: an exact `provider/model` selector from `rlm.find_models()`; and+- `thinking`: an explicit child reasoning level; must be valid for the resolved child model, defaults to the parent level (clamped to the child model).Unknown options fail instead of being ignored. Model search is bounded to active, non-expired credentials. If an exact selection is unavailable or fails auth preflight, spawn fails instead of silently falling back to another model. A child otherwise inherits the parent model.diff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.tsindex 63eb53f2cf..fed99107ef 100644--- a/packages/coding-agent/src/cli/args.ts+++ b/packages/coding-agent/src/cli/args.ts@@ -4,6 +4,7 @@import type { ThinkingLevel } from "@earendil-works/pi-agent-core";import { APP_NAME } from "../config.js";+import { THINKING_LEVELS } from "../core/thinking-levels.js";export type Mode = "text" | "json" | "rpc" | "acp" | "daemon";@@ -59,14 +60,13 @@ export interface Args {diagnostics: Array<{ type: "warning" | "error"; message: string }>;}-const VALID_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;const REMOVED_BUILTIN_TOOL_NAMES = new Set(["read", "write", "grep", "find", "ls"]);const BUILTIN_TOOL_NAMES = ["ipython"];export const INTERNAL_RUNTIME_COMMAND_MARKER = "\0prime-agent-runtime-command";export function isValidThinkingLevel(level: string): level is ThinkingLevel {- return VALID_THINKING_LEVELS.includes(level as ThinkingLevel);+ return THINKING_LEVELS.includes(level as ThinkingLevel);}export function parseArgs(args: string[]): Args {@@ -172,7 +172,7 @@ export function parseArgs(args: string[]): Args {} else {result.diagnostics.push({type: "warning",- message: `Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`,+ message: `Invalid thinking level "${level}". Valid values: ${THINKING_LEVELS.join(", ")}`,});}} else if (arg === "--print" || arg === "-p") {diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex d82129e2a7..8a37cdc357 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -209,6 +209,7 @@ import {findRlmModelMatches,normalizeRequestedRlmSubagentModel,normalizeRequestedRlmSubagentSessionName,+ normalizeRequestedRlmSubagentThinkingLevel,type RlmDeleteSubagentResult,type RlmFindModelsResult,type RlmListSubagentsResult,@@ -254,6 +255,7 @@ import {} from "./slash-commands.js";import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.js";import { type BuildSystemPromptOptions, buildSystemPrompt } from "./system-prompt.js";+import { THINKING_LEVELS } from "./thinking-levels.js";import { type BashOperations, createLocalBashOperations } from "./tools/bash.js";import { createAllToolDefinitions } from "./tools/index.js";import { IpythonKernelProvisioner } from "./tools/ipython.js";@@ -870,8 +872,6 @@ interface RlmSubagentModelSelection {model: Model<Api>;}-const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];-const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";@@ -8785,6 +8785,7 @@ export class AgentSession {spawnCode?: string;sessionDir: string;model: Model<any>;+ thinkingLevel?: ThinkingLevel;}): CreateRlmSubagentRuntimeOptions {return {parentSession: this,@@ -8794,7 +8795,8 @@ export class AgentSession {spawnCode: options.spawnCode,sessionDir: options.sessionDir,model: options.model,- thinkingLevel: clampThinkingLevel(options.model, this.thinkingLevel) as ThinkingLevel,+ thinkingLevel:+ options.thinkingLevel ?? (clampThinkingLevel(options.model, this.thinkingLevel) as ThinkingLevel),serviceTier:this.serviceTier === "priority" && !supportsFastMode(options.model) ? "default" : this.serviceTier,scopedModels: [...this._scopedModels],@@ -9445,13 +9447,14 @@ export class AgentSession {kwargs: Record<string, unknown> = {},spawnCode?: string,): Promise<RlmSpawnHandle> {- const { name: rawName, model: rawModel, ...unsupported } = kwargs;+ const { name: rawName, model: rawModel, thinking: rawThinking, ...unsupported } = kwargs;const unsupportedKwargs = Object.keys(unsupported);if (unsupportedKwargs.length > 0) {throw new Error(`Unsupported rlm.run kwargs: ${unsupportedKwargs.sort().join(", ")}`);}const requestedSessionName = normalizeRequestedRlmSubagentSessionName(rawName);const requestedModel = normalizeRequestedRlmSubagentModel(rawModel);+ const requestedThinkingLevel = normalizeRequestedRlmSubagentThinkingLevel(rawThinking);if (requestedSessionName) assertDirectAgentMessageTarget(requestedSessionName);if (this._rlmDepth >= this._rlmMaxDepth) {throw new Error(@@ -9471,6 +9474,14 @@ export class AgentSession {} finally {if (requestedSessionName) this._pendingRlmSubagentSessionNames.delete(requestedSessionName);}+ if (requestedThinkingLevel !== undefined) {+ const supported = getSupportedThinkingLevels(modelSelection.model) as ThinkingLevel[];+ if (!supported.includes(requestedThinkingLevel)) {+ throw new Error(+ `Requested thinking level "${requestedThinkingLevel}" is not supported by model "${modelSelection.model.provider}/${modelSelection.model.id}"; supported levels: ${supported.join(", ")}`,+ );+ }+ }if (this._disposed || this._disposing) throw new Error("Cannot spawn a subagent after its parent was disposed");const childSessionDir = this._createChildRlmSessionDir();@@ -9541,6 +9552,7 @@ export class AgentSession {spawnCode,sessionDir: childSessionDir,model: modelSelection.model,+ thinkingLevel: requestedThinkingLevel,}),onSessionPublished: publishChildSession,};diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex 4841138866..a43c096145 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -149,7 +149,7 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {"","A callable `rlm` is already in your global namespace. `await rlm('sub-task')` spawns a child and returns immediately after task admission with `rlm_child_id`, `name`, `session_dir`, and `model`; it never waits for or returns the child's answer.","Choose a stable child name with `await rlm('sub-task', name='api-reviewer')`; names must be unique among siblings. If omitted, the host generates a readable unique name.",- "A child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`.",+ "A child inherits your model. If a different model is explicitly requested, use `await rlm.find_models(...)` and an exact returned selector. An unavailable requested model fails spawn; decide whether to retry or omit `model`. Children also inherit your thinking level; the `thinking` option overrides it with any level the resolved child model supports, and an unsupported level fails spawn.",);if (hasAgentMessage) {parts.push(diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex 55585d8107..9ad98857ee 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -3,6 +3,7 @@ import type { Api, Model, ServiceTier } from "@earendil-works/pi-ai";import type { AgentSession } from "./agent-session.js";import type { ToolDefinition } from "./extensions/index.js";import type { HostRequestHandler } from "./kernel/index.js";+import { THINKING_LEVELS } from "./thinking-levels.js";/** Request emitted by `rlm.run`; cellSourceCode preserves the spawning cell for display. */export interface RlmRunRequest {@@ -58,7 +59,6 @@ const RLM_SUBAGENT_SESSION_NAME_MAX_LENGTH = 64;export const DEFAULT_RLM_MODEL_SEARCH_LIMIT = 8;export const MAX_RLM_MODEL_SEARCH_LIMIT = 20;-/** Validate and normalize an orchestrator-supplied subagent session name. */export function normalizeRequestedRlmSubagentSessionName(value: unknown): string | undefined {if (value === undefined) {return undefined;@@ -76,7 +76,20 @@ export function normalizeRequestedRlmSubagentSessionName(value: unknown): stringreturn name;}-/** Validate and normalize an orchestrator-supplied subagent model reference. */+export function normalizeRequestedRlmSubagentThinkingLevel(value: unknown): ThinkingLevel | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (typeof value !== "string") {+ throw new Error("rlm.run thinking must be a string");+ }+ const level = value.trim().toLowerCase();+ if (!THINKING_LEVELS.includes(level as ThinkingLevel)) {+ throw new Error(`rlm.run thinking must be one of: ${THINKING_LEVELS.join(", ")}`);+ }+ return level as ThinkingLevel;+}+export function normalizeRequestedRlmSubagentModel(value: unknown): string | undefined {if (value === undefined) {return undefined;diff --git a/packages/coding-agent/src/core/thinking-levels.ts b/packages/coding-agent/src/core/thinking-levels.tsnew file mode 100644index 0000000000..e7c76805f5--- /dev/null+++ b/packages/coding-agent/src/core/thinking-levels.ts@@ -0,0 +1,3 @@+import type { ThinkingLevel } from "@earendil-works/pi-agent-core";++export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex f066f02b11..05e24a2ea8 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -2168,6 +2168,17 @@ describe("AgentSession rlm recursion", () => {);});+ it("rejects a non-string rlm.run thinking kwarg", async () => {+ const root = createSession();++ await expect(root.runRlmChild("nested", { thinking: 3 })).rejects.toThrow("rlm.run thinking must be a string");+ });++ it("rejects an unknown rlm.run thinking level", async () => {+ const root = createSession();+ await expect(root.runRlmChild("nested", { thinking: "ultra" })).rejects.toThrow("must be one of");+ });+it("cancels active rlm children when the parent session is disposed", async () => {let releaseChild: () => void = () => {};const release = new Promise<void>((resolve) => {diff --git a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.tsindex 61de890c05..64b5d630ee 100644--- a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts+++ b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts@@ -306,6 +306,77 @@ describe("ENG-4649 subagent model selection", () => {}});+ it.each([+ { childReasoning: true, thinking: "low" as const },+ { childReasoning: false, thinking: "off" as const },+ ])("applies an explicit $thinking thinking level to the child", async ({ childReasoning, thinking }) => {+ const harness = await createHarness({+ provider,+ models: [+ { id: "parent-model", reasoning: true },+ { id: "child-model", reasoning: childReasoning },+ ],+ });+ try {+ harness.session.setThinkingLevel("high");+ harness.setResponses([fauxAssistantMessage("child answer")]);++ await harness.session.runRlmChild("use explicit effort", {+ model: `${provider}/child-model`,+ thinking,+ });+ await vi.waitFor(async () => {+ const childEntry = (await harness.session.listRlmSubagents()).subagents[0];+ const child = harness.session.getRlmChildSession(childEntry!.rlm_child_id);+ expect(child?.thinkingLevel).toBe(thinking);+ });+ } finally {+ harness.cleanup();+ }+ });++ it("inherits the parent thinking level when no override is supplied", async () => {+ const harness = await createHarness({+ provider,+ models: [+ { id: "parent-model", reasoning: true },+ { id: "child-model", reasoning: true },+ ],+ });+ try {+ harness.session.setThinkingLevel("high");+ harness.setResponses([fauxAssistantMessage("child answer")]);++ await harness.session.runRlmChild("inherit effort", { model: `${provider}/child-model` });+ await vi.waitFor(async () => {+ const childEntry = (await harness.session.listRlmSubagents()).subagents[0];+ const child = harness.session.getRlmChildSession(childEntry!.rlm_child_id);+ expect(child?.thinkingLevel).toBe("high");+ });+ } finally {+ harness.cleanup();+ }+ });++ it("fails spawn when an explicit thinking level is unsupported by the resolved model", async () => {+ const harness = await createHarness({+ provider,+ models: [+ { id: "parent-model", reasoning: true },+ { id: "child-model", reasoning: false },+ ],+ });+ try {+ await expect(+ harness.session.runRlmChild("think hard", { model: `${provider}/child-model`, thinking: "high" }),+ ).rejects.toThrow(+ `Requested thinking level "high" is not supported by model "${provider}/child-model"; supported levels: off`,+ );+ } finally {+ harness.cleanup();+ }+ });+it("inherits the parent model when no override is supplied", async () => {const harness = await createHarness({provider,diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 0c746fec9b..4dd279c1f3 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -144,6 +144,8 @@ async def run(prompt: str, **kwargs: Any) -> RLMSpawnHandle:"""Spawn a recursive Prime Agent child and return once its task is admitted.``model`` selects a child with an exact ``provider/model`` selector.+ ``thinking`` sets the child reasoning level (e.g. 'off', 'low', 'medium', 'high');+ defaults to the parent level; levels invalid for the resolved model fail the spawn."""if not isinstance(prompt, str):raise TypeError(f"prompt must be str, got {type(prompt).__name__}")