Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI, feature] feat(coding-agent): tell the model when Python skills fail to import (#2381)

Seth Karten1272a3d6ea40
diff --git a/packages/coding-agent/.changes/kernel-skill-import-notice.md b/packages/coding-agent/.changes/kernel-skill-import-notice.md
new file mode 100644
index 0000000000..c3309e4aac
--- /dev/null
+++ b/packages/coding-agent/.changes/kernel-skill-import-notice.md
@@ -0,0 +1 @@
+- Added a session-start `[python-skills-unavailable]` notice when a pre-imported Python skill fails to import into the kernel. The report names each failed skill import and its import error so the model learns before its first call instead of from the unavailable-skill placeholder, in both the TUI and headless sessions.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index c23dd977aa..e8813da2cd 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -207,6 +207,7 @@ import {
HEARTBEAT_PROMPT_PREVIEW_LABEL,
IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
isSessionSlashCommandMessage,
+ PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
type RefinementSource,
RLM_CHILD_FAILURE_CUSTOM_TYPE,
RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
@@ -349,7 +350,7 @@ import { THINKING_LEVELS } from "./thinking-levels.js";
import { acpMcpToolNames, createAcpMcpToolDefinitions } from "./tools/acp-mcp.js";
import { type BashOperations, createLocalBashOperations } from "./tools/bash.js";
import { createAllToolDefinitions } from "./tools/index.js";
-import { IpythonKernelProvisioner } from "./tools/ipython.js";
+import { IpythonKernelProvisioner, type UnavailablePythonSkills } from "./tools/ipython.js";
import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
import {
addAssistantUsage,
@@ -8585,6 +8586,34 @@ export class AgentSession {
).catch(() => {});
}
+ /**
+ * Tell the model which pre-imported Python skills failed to import into the
+ * freshly started kernel, before it spends turns reading their SKILL.md and
+ * calling them (the placeholder objects only raise on first call).
+ */
+ private _onPythonSkillsUnavailable(errors: UnavailablePythonSkills): void {
+ const lines = ["[python-skills-unavailable]", ""];
+ lines.push(
+ "These installed Python skill modules failed to import into the Python kernel, so calling them raises an error:",
+ );
+ for (const [name, error] of Object.entries(errors)) {
+ lines.push(`- ${name}: ${error}`);
+ }
+ lines.push(
+ "",
+ "Their shell command forms fail the same way. Fix the import error first (for example install the missing dependency with `uv pip install <pkg>` or reinstall the skill into the kernel venv), or use another approach.",
+ );
+ void this.sendCustomMessage(
+ {
+ customType: PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
+ content: lines.join("\n"),
+ display: true,
+ details: { skills: Object.keys(errors) },
+ },
+ { deliverAs: "nextTurn" },
+ ).catch(() => {});
+ }
+
setSteeringMode(mode: "all" | "one-at-a-time"): void {
this.agent.steeringMode = mode;
this.settingsManager.setSteeringMode(mode);
@@ -10649,6 +10678,7 @@ export class AgentSession {
snapshotDir: this._ipythonKernelSnapshotDir,
readyGate: previousDispose,
onRestore: notifyRestore ? (result) => this._onIpythonStateRestored(result) : undefined,
+ onUnavailableSkills: (errors) => this._onPythonSkillsUnavailable(errors),
onBackgroundWorkSettled: () => {
this._maybeResumeGoalContinuationAfterRlmWork();
this._maybeResumeAutonomousContinuationAfterRlmWork();
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index 3ded6ee3a1..dc7227df43 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -39,6 +39,7 @@ export const BRANCH_SUMMARY_SUFFIX = `</summary>`;
export const HEARTBEAT_PROMPT_CUSTOM_TYPE = "heartbeat_prompt";
export const HEARTBEAT_PROMPT_PREVIEW_LABEL = "Heartbeat prompt";
export const IPYTHON_STATE_RESTORED_CUSTOM_TYPE = "ipython_state_restored";
+export const PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE = "python_skills_unavailable";
export const SESSION_SLASH_COMMAND_CUSTOM_TYPE = "session_slash_command";
export const SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE = "session_slash_command_result";
export const COMPACTION_OUTCOME_CUSTOM_TYPE = "compaction_outcome";
@@ -343,6 +344,11 @@ export interface IpythonStateRestoredDetails {
restored: boolean;
}
+/** Import names of the pre-imported Python skills that failed to import into the kernel. */
+export interface PythonSkillsUnavailableDetails {
+ skills: string[];
+}
+
export interface BranchSummaryMessage {
role: "branchSummary";
summary: string;
diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.ts
index 808031a5f3..92980ab98a 100644
--- a/packages/coding-agent/src/core/tools/ipython.ts
+++ b/packages/coding-agent/src/core/tools/ipython.ts
@@ -68,6 +68,38 @@ except Exception as _prime_agent_rlm_error:
rlm._raise_missing()
`.trim();
+/**
+ * Line the runtime bootstrap prints (once, after the skill import loop) when
+ * one or more pre-imported Python skills failed to import. The host scans the
+ * bootstrap cell's stdout for this marker so unavailable skills reach the
+ * model instead of failing only on first call.
+ */
+export const PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER = "__PRIME_AGENT_PYTHON_SKILL_IMPORT_ERRORS__";
+
+/** Map of skill import name -> import error, parsed from a bootstrap cell's stdout. */
+export type UnavailablePythonSkills = Record<string, string>;
+
+/** Extract the unavailable-skill report a bootstrap cell printed, or undefined. */
+export function parseUnavailablePythonSkills(stdout: string): UnavailablePythonSkills | undefined {
+ const at = stdout.indexOf(PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER);
+ if (at < 0) return undefined;
+ const raw = stdout.slice(at + PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER.length).trim();
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
+ const errors: UnavailablePythonSkills = {};
+ for (const [name, error] of Object.entries(parsed)) {
+ if (typeof error === "string" && error.length > 0) {
+ errors[name] = error;
+ }
+ }
+ return Object.keys(errors).length > 0 ? errors : undefined;
+}
+
export function buildRlmBootstrapCode(pythonSkills: readonly PythonSkillRuntimeInfo[] = []): string {
const baseCode = [RLM_BOOTSTRAP_HEADER_CODE, RLM_BOOTSTRAP_RUNTIME_CODE].join("\n\n");
const importNames = [...new Set(pythonSkills.map((skill) => skill.importName))];
@@ -134,11 +166,23 @@ for _prime_agent_skill_name in ${JSON.stringify(importNames)}:
_prime_agent_importlib.import_module(_prime_agent_skill_name)
)
except Exception as _prime_agent_skill_error:
- _PRIME_AGENT_SKILL_IMPORT_ERRORS[_prime_agent_skill_name] = str(_prime_agent_skill_error)
+ # An exception with an empty message would otherwise be dropped by the
+ # host-side parser; fall back to the exception type name.
+ _prime_agent_skill_error_text = (
+ str(_prime_agent_skill_error) or type(_prime_agent_skill_error).__name__
+ )
+ _PRIME_AGENT_SKILL_IMPORT_ERRORS[_prime_agent_skill_name] = _prime_agent_skill_error_text
globals()[_prime_agent_skill_name] = _PrimeAgentUnavailableSkill(
_prime_agent_skill_name,
- str(_prime_agent_skill_error),
+ _prime_agent_skill_error_text,
)
+
+if _PRIME_AGENT_SKILL_IMPORT_ERRORS:
+ import json as _prime_agent_json
+ print(
+ "${PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER}"
+ + _prime_agent_json.dumps(_PRIME_AGENT_SKILL_IMPORT_ERRORS)
+ )
`.trim();
}
@@ -293,6 +337,12 @@ export interface IpythonToolOptions {
* (some names restored or some failed), so the session can tell the model.
*/
onRestore?: (result: RestoreResult) => void;
+ /**
+ * Fires once per kernel start when installed Python skills failed to import
+ * into the kernel (skill import name -> import error), so the session can tell
+ * the model before it wastes turns calling them.
+ */
+ onUnavailableSkills?: (errors: UnavailablePythonSkills) => void;
/** Fires when the kernel's last live background bash() handle settles, so owed continuations can resume. */
onBackgroundWorkSettled?: () => void;
onLateSentAgentMessage?: (toolCallId: string, message: KernelSentAgentMessage) => void;
@@ -522,6 +572,12 @@ export class IpythonKernelProvisioner {
const details = [bootstrap.stderr, bootstrap.error?.traceback.join("\n")].filter(Boolean).join("\n");
throw new Error(`Failed to initialize rlm runtime in the Python kernel:\n${details}`);
}
+ // Broken skills stay importable-looking placeholders; report them so the
+ // model learns before its first call, not from the placeholder's error.
+ const unavailableSkills = parseUnavailablePythonSkills(bootstrap.stdout);
+ if (unavailableSkills) {
+ this.options?.onUnavailableSkills?.(unavailableSkills);
+ }
} catch (error) {
// Never leak the kernel process if startup fails after spawn — and never
// surface the failure before the teardown (final snapshot flush included)
diff --git a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts
index 786153dac7..17a97f577b 100644
--- a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts
@@ -18,6 +18,8 @@ import {
type HeartbeatPromptDetails,
IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
type IpythonStateRestoredDetails,
+ PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
+ type PythonSkillsUnavailableDetails,
RLM_CHILD_FAILURE_CUSTOM_TYPE,
RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
type RlmChildFailureDetails,
@@ -32,6 +34,7 @@ type InjectedPromptDetails =
| GoalContextDetails
| HeartbeatPromptDetails
| IpythonStateRestoredDetails
+ | PythonSkillsUnavailableDetails
| RlmChildFailureDetails
| RlmChildTerminalNoticeDetails;
type InjectedPromptMessage = CustomMessage<InjectedPromptDetails>;
@@ -43,6 +46,7 @@ export function isInjectedPromptMessage(message: AgentMessage): message is Injec
message.customType === HEARTBEAT_PROMPT_CUSTOM_TYPE ||
message.customType === GOAL_CONTEXT_CUSTOM_TYPE ||
message.customType === IPYTHON_STATE_RESTORED_CUSTOM_TYPE ||
+ message.customType === PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE ||
message.customType === RLM_CHILD_FAILURE_CUSTOM_TYPE ||
message.customType === RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE)
);
@@ -142,6 +146,14 @@ export class InjectedPromptMessageComponent extends Container {
const label = details?.restored === false ? "Started fresh Python kernel" : "Restored Python kernel state";
return `${theme.fg("accent", "◆")} ${theme.fg("muted", label)}`;
}
+ if (this.message.customType === PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE) {
+ const details = this.message.details as PythonSkillsUnavailableDetails | undefined;
+ const skills = details?.skills?.length
+ ? ` · ${truncateToWidth(details.skills.join(", "), Math.max(20, 90 - "Python skills unavailable · ".length))}`
+ : "";
+ const hint = this.expanded ? "" : ` ${expandCollapseHint("app.tools.expand", false)}`;
+ return theme.fg("muted", "Python skills unavailable") + theme.fg("dim", skills + hint);
+ }
if (
this.message.customType === RLM_CHILD_FAILURE_CUSTOM_TYPE ||
this.message.customType === RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE
diff --git a/packages/coding-agent/test/ipython-bootstrap.test.ts b/packages/coding-agent/test/ipython-bootstrap.test.ts
index 27957ac425..298a687b24 100644
--- a/packages/coding-agent/test/ipython-bootstrap.test.ts
+++ b/packages/coding-agent/test/ipython-bootstrap.test.ts
@@ -4,13 +4,13 @@ import { homedir, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { ReplKernelManager } from "../src/core/kernel/index.js";
-import { buildRlmBootstrapCode } from "../src/core/tools/ipython.js";
+import {
+ buildRlmBootstrapCode,
+ PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER,
+ parseUnavailablePythonSkills,
+} from "../src/core/tools/ipython.js";
describe("RLM bootstrap", () => {
- it("pre-imports asyncio so the prompt's subagent patterns work without a manual import", () => {
- expect(buildRlmBootstrapCode()).toMatch(/^import asyncio$/m);
- });
-
it("gives subagent registry operations the actionable missing-runtime fallback", () => {
const code = buildRlmBootstrapCode();
expect(code).toContain('async def find_models(self, query="", limit=8)');
@@ -49,6 +49,19 @@ describe("RLM bootstrap", () => {
expect(code).toContain("_PRIME_AGENT_SKILL_IMPORT_ERRORS");
expect(code).toContain("globals()[_prime_agent_skill_name] = _PrimeAgentUnavailableSkill");
});
+
+ it.each([
+ [
+ `${PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER}{"websearch":"No module named 'websearch'"}\n`,
+ { websearch: "No module named 'websearch'" },
+ ],
+ [`noise\n${PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER}{"edit":"boom"}`, { edit: "boom" }],
+ ["some unrelated kernel output", undefined],
+ [`${PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER}not json`, undefined],
+ [`${PYTHON_SKILL_IMPORT_ERROR_REPORT_MARKER}{}`, undefined],
+ ])("parses %j as %j", (stdout, expected) => {
+ expect(parseUnavailablePythonSkills(stdout as string)).toEqual(expected);
+ });
});
/** Find a python with a current rlm runtime, or null to skip. */
diff --git a/packages/coding-agent/test/suite/regressions/kernel-python-skills-unavailable.test.ts b/packages/coding-agent/test/suite/regressions/kernel-python-skills-unavailable.test.ts
new file mode 100644
index 0000000000..0fa7f3ca9c
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/kernel-python-skills-unavailable.test.ts
@@ -0,0 +1,39 @@
+import { fauxAssistantMessage } from "@earendil-works/pi-ai";
+import { describe, expect, it } from "vitest";
+import { PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE } from "../../../src/core/messages.js";
+import { createHarness, getMessageText } from "../harness.js";
+
+describe("Python skills unavailable message", () => {
+ it("queues the unavailable-skill report as next-turn context the model sees", async () => {
+ const harness = await createHarness();
+ try {
+ let providerSawUnavailableSkills = false;
+ harness.setResponses([
+ (context) => {
+ providerSawUnavailableSkills = context.messages.some((message) =>
+ getMessageText(message).includes("failed to import into the Python kernel"),
+ );
+ return fauxAssistantMessage("queued turn complete");
+ },
+ ]);
+
+ (
+ harness.session as unknown as { _onPythonSkillsUnavailable(errors: Record<string, string>): void }
+ )._onPythonSkillsUnavailable({
+ websearch: "No module named 'websearch'",
+ edit: "boom",
+ });
+ await harness.session.prompt("go");
+
+ const delivered = harness.session.messages.find(
+ (message) => message.role === "custom" && message.customType === PYTHON_SKILLS_UNAVAILABLE_CUSTOM_TYPE,
+ );
+ expect(delivered).toMatchObject({ display: true, details: { skills: ["websearch", "edit"] } });
+ expect(getMessageText(delivered!)).toContain("- websearch: No module named 'websearch'");
+ expect(getMessageText(delivered!)).toContain("- edit: boom");
+ expect(providerSawUnavailableSkills).toBe(true);
+ } finally {
+ harness.cleanup();
+ }
+ });
+});