Skip to content

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

Rust

Non-blocking subagents, refine guidance, and orchestration messaging behavioral fix (#338)

Seth Kartend4fdb8e4944a
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index e54cfd088b..226a8d740c 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Changed subagent and refinement guidance to favor non-blocking subagent tasks by default, use disk-backed tracking for long-running fan-out, inspect or message live subagents when agent observation/messaging skills are available, and capture reusable delegation roles, procedures, facts, preferences, and prompt addendums with `/refine`.
- Changed `attach_image` to resize and compress large inline image attachments before storing them for rendering and replay ([#340](https://github.com/PrimeIntellect-ai/prime-agent/pull/340) by [@sethkarten](https://github.com/sethkarten)).
- Fixed heartbeat and goal continuation prompts rendering like ordinary user messages ([ENG-4482](https://linear.app/primeintellect/issue/ENG-4482/heartbeat-message-should-have-a-different-ui-from-user-message)).
- Fixed `/heartbeat` guidance to show `stop` and the `every <duration> <instruction>` interval syntax ([ENG-4484](https://linear.app/primeintellect/issue/ENG-4484/improve-heartbeat-command-syntax-guidance-in-ui)).
diff --git a/packages/coding-agent/skills/agent-message/SKILL.md b/packages/coding-agent/skills/agent-message/SKILL.md
index 9b79b93876..6e7a42e687 100644
--- a/packages/coding-agent/skills/agent-message/SKILL.md
+++ b/packages/coding-agent/skills/agent-message/SKILL.md
@@ -20,7 +20,9 @@ receipt = await agent_message.send("worker", "Please inspect the latest result."
- `await agent_message.list_agents()` — returns `current` and `agents`, where
each agent includes active session id, session id, optional name, runtime
- kind, cwd, streaming state, and pending message count.
+ kind, cwd, streaming state, and pending message count. This includes live
+ subagents; filter by `runtimeKind == "subagent"`, `parentActiveSessionId`,
+ or `rlmChildId` before messaging a specific subagent.
- `await agent_message.send(target, message, mode="auto")` — sends one direct
text message to an active session. `target` is resolved by the daemon like
other live-session selectors. `mode` is `"auto"`, `"follow_up"`, or
diff --git a/packages/coding-agent/skills/agent-observe/SKILL.md b/packages/coding-agent/skills/agent-observe/SKILL.md
index bee9b89d76..1bae5b30c4 100644
--- a/packages/coding-agent/skills/agent-observe/SKILL.md
+++ b/packages/coding-agent/skills/agent-observe/SKILL.md
@@ -23,7 +23,9 @@ recent = await agent_observe.recent_messages("worker", limit=6)
- `await agent_observe.list_agents()` returns `current` and `agents`. Each
agent includes active session id, session id, optional name, runtime kind,
cwd, status, streaming state, message count, pending count, and a latest
- message preview.
+ message preview. This includes subagents shown in the agents view; filter
+ by `runtimeKind == "subagent"` and `parentSessionId` or
+ `parentActiveSessionId` to inspect subagents that belong to your session.
- `await agent_observe.get_agent(target)` returns one agent summary. `target`
is resolved like other live-session selectors: active id, session id/name, or
unambiguous suffix.
diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.ts
index ee04b12a93..d4f6fdd863 100644
--- a/packages/coding-agent/src/core/prompts/rlm.ts
+++ b/packages/coding-agent/src/core/prompts/rlm.ts
@@ -28,9 +28,9 @@ const IPYTHON_CONTROL_PROMPT = [
"",
"Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.",
"",
- "RLM-native call contract for refined continual harness entries: installed Python skills are called from IPython as `await <skill_import>(...)` with keyword arguments, or as `<skill_import> ...` from shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and calling `await rlm('sub-task')`, or `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",
+ "RLM-native call contract for refined continual harness entries: installed Python skills are called from IPython as `await <skill_import>(...)` with keyword arguments, or as `<skill_import> ...` from shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",
"",
- "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",
+ "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `/refine` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",
].join("\n");
export function buildRlmPrompt(options: RlmPromptOptions): string {
@@ -38,6 +38,9 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {
const installedSkills = options.installedSkills ?? [];
const allowRecursion = options.allowRecursion ?? true;
const activeTools = options.activeTools ?? [];
+ const hasIpython = options.activeTools === undefined ? true : activeTools.includes("ipython");
+ const canRunShellSkills = hasIpython || activeTools.includes("bash");
+ const hasAgentObserveSkill = installedSkills.includes("agent_observe");
const parts = [
"You are a general purpose agent that uses code to solve tasks.",
"You solve tasks by breaking down problems into sub-tasks, writing and executing code, observing results, and iterating one step at a time.",
@@ -55,14 +58,20 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {
}
if (installedSkills.length > 0) {
const installed = installedSkills.map((skill) => `\`${skill}\``).join(", ");
- skillLines.push(`Installed skills (pre-imported): ${installed}.`);
- skillLines.push(
- "Each skill is an async function by the same name. Inspect with `help(<skill>)` or `inspect.signature(<skill>.run)`.",
- );
- skillLines.push(
- "Each skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.",
- );
- if (installedSkills.includes("edit")) {
+ if (hasIpython) {
+ skillLines.push(`Installed skills (pre-imported): ${installed}.`);
+ skillLines.push(
+ "Each skill is an async function by the same name. Inspect with `help(<skill>)` or `inspect.signature(<skill>.run)`.",
+ );
+ } else if (canRunShellSkills) {
+ skillLines.push(`Installed skills available as shell commands: ${installed}.`);
+ }
+ if (canRunShellSkills) {
+ skillLines.push(
+ "Each skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.",
+ );
+ }
+ if (hasIpython && installedSkills.includes("edit")) {
skillLines.push(
"For targeted existing-file edits, prefer the pre-imported async `edit` skill from IPython: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.",
);
@@ -72,16 +81,20 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {
parts.push("", ...skillLines);
}
- if (allowRecursion) {
+ if (allowRecursion && hasIpython) {
parts.push(
"",
- "A callable `rlm` is already in your global namespace — call it directly with `await rlm('sub-task')` to spawn a recursive sub-agent. Returns an `RLMResult` with `.answer` (string), `.usage`, `.turns`, and `.session_dir`.",
- "For parallel sub-agents, use normal Python async patterns such as `await asyncio.gather(rlm('task1'), rlm('task2'))`; `asyncio` is already imported.",
+ "A callable `rlm` is already in your global namespace. It returns an `RLMResult` with `.answer` (string), `.usage`, `.turns`, and `.session_dir`. A direct `await rlm('sub-task')` is valid only when the result is immediately required.",
+ "Sub-agents should not block Prime Agent by default: start them with `task = asyncio.create_task(rlm('sub-task'))`, keep the task handle, continue any independent work, and await the task only when you need its result.",
+ hasAgentObserveSkill
+ ? "For long-running fan-out, do not rely only on in-memory `asyncio.Task` handles: they can be lost if the kernel restarts or state is restored. Write a small disk registry under `os.environ.get('RLM_SESSION_DIR')` when set, or another explicit project path otherwise, with each subtask prompt/label and observed active session or child ids; recover status later with `agent_observe`."
+ : "For long-running fan-out, do not rely only on in-memory `asyncio.Task` handles: they can be lost if the kernel restarts or state is restored. Write a small disk registry under `os.environ.get('RLM_SESSION_DIR')` when set, or another explicit project path otherwise, with each subtask prompt/label and observed active session or child ids so work can be reconciled after restore.",
+ "For parallel sub-agents, launch them together and collect them with normal Python async patterns such as `await asyncio.gather(rlm('task1'), rlm('task2'))`; `asyncio` is already imported.",
"For sub-agent work that can run in the background, keep the task handle from `asyncio.create_task(rlm('sub-task'))` so you do not block the main execution path; use normal task callbacks, `task.done()`, or `await task` later to observe completion and read the returned `RLMResult.answer`.",
);
}
- if (activeTools.includes("ipython")) {
+ if (hasIpython) {
parts.push("", IPYTHON_CONTROL_PROMPT);
}
@@ -89,14 +102,12 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {
}
/**
- * Supplemental sub-agent delegation guidance, appended AFTER the trained
- * `buildRlmPrompt` prefix (see system-prompt.ts). This is intentionally NOT part of
- * `buildRlmPrompt`'s `parts` array: the text that function emits is frozen as the v1
- * training prefix and must stay byte-identical. The trained recursion block already
- * covers the mechanics (`await rlm(...)`, `asyncio.gather`, `asyncio.create_task`);
- * this block adds the *when* and *why* — the decision guidance the trained prefix
- * lacks — in the same When -> Why -> (menu) order Claude Code's Agent tool uses. The
- * subagent-spec "menu" itself renders just after this, inside the harness-state block.
+ * Supplemental sub-agent delegation guidance, appended after the base RLM
+ * prompt (see system-prompt.ts). The recursion block covers the mechanics
+ * (`rlm(...)`, `asyncio.gather`, `asyncio.create_task`); this block adds the
+ * when and why in the same When -> Why -> menu order Claude Code's Agent tool
+ * uses. The subagent-spec menu itself renders just after this, inside the
+ * harness-state block.
*/
export function buildSubagentGuidance(): string {
return [
@@ -104,15 +115,23 @@ export function buildSubagentGuidance(): string {
"",
"You already have `rlm` in scope. This is about *when* to spawn one — which matters as much as how.",
"",
- "Reach for `await rlm(...)` when:",
- "- you have independent sub-tasks that can run in parallel — fan them out with `await asyncio.gather(rlm('task1'), rlm('task2'))` rather than working them one after another;",
- "- a sub-task would mean reading across many files, outputs, or sources you don't need to keep — delegate it and you keep the answer, not the raw material;",
- "- the sub-task matches one of your saved subagent specs (listed in the harness state below) — turn the spec into a concise task prompt and call `rlm` with it.",
+ "Default to non-blocking subagents: create an `asyncio` task, keep the handle, continue independent work, and await only at the collection point where the result is needed.",
+ "For subagent work that must survive kernel restarts, state restore, or compaction, persist a disk-backed registry before or immediately after spawning: after importing `os` and `Path`, store the subtask label, prompt, start time, and any observed `activeSessionId`, `rlmChildId`, or `session_dir` under `Path(os.environ['RLM_SESSION_DIR'])` when that variable is set, or another explicit project path otherwise. Treat in-memory `asyncio.Task` objects as convenience handles only; after restore, reload the registry and recover status from live subagent sessions instead of assuming those task objects still exist.",
+ 'If the `agent_observe` skill is installed, use it like the agents view to inspect live subagents without awaiting them: list agents with `await agent_observe.list_agents()`, filter `runtimeKind == "subagent"` and `parentSessionId` or `parentActiveSessionId`, and read bounded previews with `await agent_observe.recent_messages(target, limit=...)`.',
+ "If the `agent_message` skill is installed, live subagents are addressable like other active agents: list targets with `await agent_message.list_agents()` and send concise coordination or steering messages with `await agent_message.send(target, message, mode='auto')`; use `mode='steer'` only when you intend to interrupt current work.",
"",
- "Do it inline instead when the step is a single known lookup, edit, or command — there, a sub-agent just adds latency. Once you've delegated a sub-task, await its handle and use the result instead of redoing the work yourself.",
+ "Reach for sub-agents when:",
+ "- you have independent sub-tasks that can run in parallel — fan them out with `asyncio.create_task(rlm('task'))` or collect a batch with `await asyncio.gather(rlm('task1'), rlm('task2'))` rather than working them one after another;",
+ "- a sub-task would mean reading across many files, outputs, or sources you don't need to keep — delegate it and keep the answer, not the raw material;",
+ "- the sub-task matches one of your saved subagent specs (listed in the harness state below) — turn the spec into a concise task prompt and start it with `asyncio.create_task(rlm('task'))` unless you need the result immediately.",
+ "",
+ "Do it inline instead when the step is a single known lookup, edit, or command — there, a sub-agent just adds latency. Once you've delegated a sub-task, keep its task handle and use the result instead of redoing the work yourself.",
"",
"For example:",
"```python",
+ "from pathlib import Path",
+ "import os",
+ "",
"# Independent sub-tasks in parallel — each returns just its conclusion, not the files it read",
"auth, api = await asyncio.gather(",
" rlm('Summarize how authentication works in this repo: entrypoints, token flow, and key files.'),",
@@ -125,10 +144,15 @@ export function buildSubagentGuidance(): string {
"",
"# Background — kick off a slow sub-task, keep working, collect it later",
"task = asyncio.create_task(rlm('Run the full test suite and report any failures with root causes.'))",
+ "# For long-running fan-out, also persist a label/prompt/id registry.",
+ "# Use RLM_SESSION_DIR when set; otherwise choose an explicit project path.",
+ "# Example: registry_root = Path(os.environ['RLM_SESSION_DIR']) if os.environ.get('RLM_SESSION_DIR') else Path('subagent-registry')",
+ "# registry_root.joinpath('subagents.jsonl').write_text(...)",
"# ... continue with other work while it runs ...",
"failures = (await task).answer",
"```",
"",
"These are illustrations, not a fixed menu: delegate any self-contained sub-task that fits the cases above.",
+ "When you notice a delegation role, procedure, fact, preference, or behavior policy that should be reused, use `/refine` to create or update the smallest relevant subagent spec, skill, memory, or prompt addendum.",
].join("\n");
}
diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.ts
index f4b1ad481d..a54f59a19d 100644
--- a/packages/coding-agent/src/core/refinement/refinement.ts
+++ b/packages/coding-agent/src/core/refinement/refinement.ts
@@ -123,7 +123,7 @@ Continual harness components:
- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.
- memory: durable facts, decisions, failures, preferences, and outcomes.
- skill: installed Python REPL skill. Skill create/update edits MUST include a \`reference\` object with \`{"type":"python"}\`, a Python import, and a callable or call pattern; they also MUST include an \`arguments\` object describing accepted inputs, required fields, defaults, and constraints. Use \`{}\` for \`arguments\` only when the Python callable truly needs no external inputs. Include the RLM-native call form \`await <skill_import>(...)\`.
-- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: create a concise task prompt and call \`await rlm("sub-task")\`; for independent parallel subagents use \`await asyncio.gather(rlm("task1"), rlm("task2"))\`. Do not invent wrappers like \`run_subagent(...)\`.
+- subagent: reusable delegation specs, including purpose, instructions, and when to invoke. Include the RLM-native call form: create a concise task prompt, start \`asyncio.create_task(rlm("sub-task"))\` by default, keep the task handle, and await only when the result is needed; for independent parallel subagents use \`await asyncio.gather(rlm("task1"), rlm("task2"))\`. Use direct \`await rlm("sub-task")\` only when the result is immediately required. Do not invent wrappers like \`run_subagent(...)\`.
Scope and persistence policy:
- The default editable continual harness store is local to the current Prime Agent session. Use it for session-specific progress, active task state, current-run coordination notes, temporary blockers, and project facts that should not affect other sessions.
@@ -131,7 +131,8 @@ Scope and persistence policy:
- Entry ids in the harness overview may carry a display-only \`local:\` or \`global:\` prefix. Always use the bare id (no prefix) in edits.
- All edits in one refinement apply only to the requested scope's store. During a local refinement, global entries are read-only context: never propose update or delete edits for them; create a local entry instead when a session-specific override is genuinely needed.
- Project/workspace-specific lessons may be persisted globally only when the title, path, or content explicitly names the project/workspace and the lesson is likely to be reused in future sessions for that project. Prefer local edits when the lesson only belongs in the current conversation.
-- Use memory for declarative facts and preferences, skill for repeatable procedures exposed as Python calls, prompt for narrow behavioral policy addenda, and subagent for reusable delegation roles.
+- Use memory for declarative facts and preferences, skill for repeatable procedures exposed as Python calls, prompt for narrow behavioral policy addendums, and subagent for reusable delegation roles.
+- Create or update the smallest relevant component: repeated delegation roles should become subagent specs, repeated procedures should become skills, durable facts/preferences should become memories, and narrow behavioral policies should become prompt addendums.
- When an edit is persisted, include metadata such as \`{"scope":"local"}\` or \`{"scope":"global"}\` when that helps future review understand the intended blast radius.
Use the trajectory, current continual harness state, and prior refinement history. Prefer
@@ -390,11 +391,14 @@ export function formatHarnessStateForPrompt(
maxEntriesPerKind?: number;
maxRefinements?: number;
maxContentLength?: number;
+ includeIpythonExamples?: boolean;
+ includeShellExamples?: boolean;
} = {},
): string {
const maxEntriesPerKind = options.maxEntriesPerKind ?? DEFAULT_OVERVIEW_ENTRY_LIMIT;
const maxRefinements = options.maxRefinements ?? DEFAULT_OVERVIEW_REFINEMENT_LIMIT;
const maxContentLength = options.maxContentLength ?? DEFAULT_OVERVIEW_CONTENT_LIMIT;
+ const includeIpythonExamples = options.includeIpythonExamples ?? true;
const lines = [
"# Continual Harness State",
"",
@@ -403,9 +407,13 @@ export function formatHarnessStateForPrompt(
"Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.",
"Use these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.",
"",
- "When to call `/refine`: after a repeated failure, a reusable tactic emerges, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `/refine` continual harness edits small and evidence-backed.",
+ "When to call `/refine`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `/refine` continual harness edits small and evidence-backed.",
"",
- "Call contract: use installed Python skills as `await <skill_import>(...)` in IPython, or `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are invoked by composing a concise task prompt and calling `await rlm('sub-task')`; use `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",
+ includeIpythonExamples
+ ? "Call contract: use installed Python skills as `await <skill_import>(...)` in IPython, or `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are invoked by composing a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then awaiting only when the result is needed; use `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries."
+ : options.includeShellExamples
+ ? "Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without IPython; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents an IPython kernel."
+ : "Call contract: continual harness entries are routing/context hints only in sessions without IPython or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.",
"",
];
@@ -416,11 +424,11 @@ export function formatHarnessStateForPrompt(
);
totalEntries += entries.length;
// Render subagent specs as a task-shaped roster the model can match against — the
- // analogue of Claude Code's agent-type menu — rather than a bare count. The
- // invocation hint makes clear each spec is reached through the single `rlm` entrypoint.
- if (kind === "subagent" && entries.length > 0) {
+ // analogue of Claude Code's agent-type menu — rather than a bare count. In
+ // IPython sessions, include the native `rlm` invocation hint.
+ if (kind === "subagent" && entries.length > 0 && includeIpythonExamples) {
lines.push(
- `${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and calling \`await rlm('<task>')\`)`,
+ `${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and starting \`asyncio.create_task(rlm('<task>'))\` by default)`,
);
} else {
lines.push(`${kind}: ${entries.length}`);
diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.ts
index f3d573015c..7a9154fd96 100644
--- a/packages/coding-agent/src/core/system-prompt.ts
+++ b/packages/coding-agent/src/core/system-prompt.ts
@@ -59,6 +59,8 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
const contextFiles = providedContextFiles ?? [];
const skills = providedSkills ?? [];
const tools = selectedTools ?? ["ipython"];
+ const hasIpython = tools.includes("ipython");
+ const hasBash = tools.includes("bash");
const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
if (customPrompt) {
@@ -85,7 +87,7 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
prompt += `\nCurrent working directory: ${promptCwd}`;
if (harnessState) {
- prompt += `\n\n${formatHarnessStateForPrompt(harnessState)}`;
+ prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash })}`;
}
if (appendSection) {
@@ -106,12 +108,12 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
// Appended AFTER the trained buildRlmPrompt prefix, and before the harness-state
// menu, so the model reads when/why to delegate and then sees the concrete subagent
// specs it can match against — the same ordering as Claude Code's Agent tool.
- if (allowRecursion ?? true) {
+ if ((allowRecursion ?? true) && hasIpython) {
prompt += `\n\n${buildSubagentGuidance()}`;
}
if (harnessState) {
- prompt += `\n\n${formatHarnessStateForPrompt(harnessState)}`;
+ prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash })}`;
}
const guidelines = formatPromptGuidelines(promptGuidelines);
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 0a01acb643..b2746fc233 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -145,6 +145,102 @@ describe("daemon mode helpers", () => {
});
});
+ it("lists and sends agent messages to live subagents", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const parentState = makeState("parent");
+ parentState.runtime = {
+ ...parentState.runtime,
+ cwd: "/tmp",
+ metadata: { kind: "top-level", createdAt: 1 },
+ session: {
+ sessionId: "session-parent",
+ sessionName: "Parent",
+ isStreaming: false,
+ pendingMessageCount: 0,
+ },
+ } as never;
+ const subagentState = makeState("child", "parent") as ActiveSessionState & {
+ runtime: ActiveSessionState["runtime"] & {
+ session: {
+ sessionId: string;
+ sessionName: string;
+ isStreaming: boolean;
+ pendingMessageCount: number;
+ acceptAgentMessagePrompt: ReturnType<typeof vi.fn>;
+ };
+ };
+ };
+ const acceptAgentMessagePrompt = vi.fn(
+ (message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {
+ options?.preflightResult?.(true);
+ return Promise.resolve(message);
+ },
+ );
+ subagentState.runtime = {
+ ...subagentState.runtime,
+ cwd: "/tmp",
+ metadata: {
+ ...subagentState.runtime.metadata,
+ rlmChildId: "child-1",
+ },
+ session: {
+ sessionId: "session-child",
+ sessionName: "Subagent",
+ isStreaming: false,
+ pendingMessageCount: 0,
+ acceptAgentMessagePrompt,
+ },
+ } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ createAgentMessageListResult(current: ActiveSessionState): {
+ agents: Array<{
+ activeSessionId: string;
+ runtimeKind?: string;
+ parentActiveSessionId?: string;
+ rlmChildId?: string;
+ }>;
+ };
+ sendAgentSessionMessage(options: {
+ targetSelector: string;
+ message: string;
+ fromState?: ActiveSessionState;
+ origin: "agent" | "cli";
+ }): Promise<unknown>;
+ };
+ internals.sessions.set(parentState.activeSessionId, parentState);
+ internals.sessions.set(subagentState.activeSessionId, subagentState);
+
+ const subagentSummary = internals
+ .createAgentMessageListResult(parentState)
+ .agents.find((agent) => agent.activeSessionId === subagentState.activeSessionId);
+ expect(subagentSummary).toMatchObject({
+ runtimeKind: "subagent",
+ parentActiveSessionId: parentState.activeSessionId,
+ rlmChildId: "child-1",
+ });
+
+ await expect(
+ internals.sendAgentSessionMessage({
+ targetSelector: subagentState.activeSessionId,
+ message: "report current progress",
+ fromState: parentState,
+ origin: "agent",
+ }),
+ ).resolves.toMatchObject({
+ deliveryStatus: "delivered",
+ target: { activeSessionId: subagentState.activeSessionId, runtimeKind: "subagent" },
+ });
+ expect(acceptAgentMessagePrompt).toHaveBeenCalledOnce();
+ expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("To: Subagent, active child");
+ expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("report current progress");
+ });
+
it("reports queued status when a direct accept races into the queue", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.ts
index 7bf2ca075f..7a71db4532 100644
--- a/packages/coding-agent/test/system-prompt.test.ts
+++ b/packages/coding-agent/test/system-prompt.test.ts
@@ -79,13 +79,26 @@ describe("buildRlmPrompt", () => {
"",
"Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.",
"",
- "RLM-native call contract for refined continual harness entries: installed Python skills are called from IPython as `await <skill_import>(...)` with keyword arguments, or as `<skill_import> ...` from shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and calling `await rlm('sub-task')`, or `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",
+ "RLM-native call contract for refined continual harness entries: installed Python skills are called from IPython as `await <skill_import>(...)` with keyword arguments, or as `<skill_import> ...` from shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",
"",
- "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",
+ "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `/refine` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",
].join("\n"),
);
});
+ test("defaults omitted activeTools to ipython guidance", () => {
+ const prompt = buildRlmPrompt({
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ installedSkills: ["websearch"],
+ });
+
+ expect(prompt).toContain("Installed skills (pre-imported): `websearch`.");
+ expect(prompt).toContain("A callable `rlm` is already in your global namespace");
+ expect(prompt).toContain("IPython is the agent's long-lived notebook");
+ expect(prompt).toContain("Each `%%bash` cell runs in a throw-away subshell");
+ });
+
test("only documents ipython shell prefixes when ipython is active", () => {
const prompt = buildRlmPrompt({
cwd: "/repo",
@@ -97,6 +110,42 @@ describe("buildRlmPrompt", () => {
expect(prompt).not.toContain("IPython is the agent's long-lived notebook");
});
+ test("keeps shell skill command guidance when ipython is inactive", () => {
+ const prompt = buildRlmPrompt({
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ installedSkills: ["websearch"],
+ activeTools: ["bash"],
+ allowRecursion: false,
+ });
+
+ expect(prompt).toContain("Installed skills available as shell commands: `websearch`.");
+ expect(prompt).toContain("Each skill is also available as a shell command");
+ expect(prompt).toContain("`<skill> --help`");
+ expect(prompt).not.toContain("Installed skills (pre-imported)");
+ expect(prompt).not.toContain("Each skill is an async function");
+ });
+
+ test("mentions agent observation recovery only when the skill is installed", () => {
+ const withoutObserve = buildRlmPrompt({
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ activeTools: ["ipython"],
+ });
+ const withObserve = buildRlmPrompt({
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ installedSkills: ["agent_observe"],
+ activeTools: ["ipython"],
+ });
+
+ expect(withoutObserve).toContain(
+ "Write a small disk registry under `os.environ.get('RLM_SESSION_DIR')` when set",
+ );
+ expect(withoutObserve).not.toContain("recover status later with `agent_observe`");
+ expect(withObserve).toContain("recover status later with `agent_observe`");
+ });
+
test("documents the %%bash first-line rule when ipython is active", () => {
const prompt = buildRlmPrompt({
cwd: "/repo",
@@ -250,9 +299,15 @@ describe("buildSystemPrompt", () => {
expect(prompt).toContain("Call contract: use installed Python skills as `await <skill_import>(...)`");
expect(prompt).toContain("Continual harness skill entries are Python REPL skills");
expect(prompt).toContain("Continual harness subagent entries are invoked by composing a concise task prompt");
+ expect(prompt).toContain("asyncio.create_task(rlm('sub-task'))");
expect(prompt).toContain("await rlm('sub-task')");
+ expect(prompt).toContain("only when the result is immediately required");
expect(prompt).toContain("after a repeated failure");
expect(prompt).toContain("a reusable tactic emerges");
+ expect(prompt).toContain("a repeated delegation role should become a subagent spec");
+ expect(prompt).toContain("a repeated procedure should become a skill");
+ expect(prompt).toContain("a durable fact/preference should become a memory");
+ expect(prompt).toContain("a narrow behavioral policy should become a prompt addendum");
expect(prompt).toContain("validation shows a continual harness entry is wrong");
expect(prompt).toContain("[global:focused_edits] Focused edits (policy, v1)");
expect(prompt).toContain("[global:validation] Validation (repo/prime-agent, v2): Run `npm run check`");
@@ -322,6 +377,21 @@ describe("buildSystemPrompt", () => {
expect(prompt).toContain("await rlm('sub-task')");
expect(prompt).toContain("asyncio.gather");
expect(prompt).toContain("asyncio.create_task");
+ expect(prompt).toContain("Sub-agents should not block Prime Agent by default");
+ expect(prompt).toContain("Default to non-blocking subagents");
+ expect(prompt).toContain("disk-backed registry");
+ expect(prompt).toContain("RLM_SESSION_DIR");
+ expect(prompt).toContain("from pathlib import Path");
+ expect(prompt).toContain("import os");
+ expect(prompt).toContain("kernel restarts, state restore, or compaction");
+ expect(prompt).toContain("agent_observe.list_agents");
+ expect(prompt).toContain('runtimeKind == "subagent"');
+ expect(prompt).toContain("parentSessionId");
+ expect(prompt).toContain("parentActiveSessionId");
+ expect(prompt).toContain("agent_observe.recent_messages");
+ expect(prompt).toContain("agent_message.list_agents");
+ expect(prompt).toContain("agent_message.send");
+ expect(prompt).toContain("mode='steer'");
expect(prompt).toContain("sub-agent work that can run in the background");
expect(prompt).toContain("do not block the main execution path");
expect(prompt).toContain("keep the task handle");
@@ -356,6 +426,10 @@ describe("buildSystemPrompt", () => {
expect(prompt).toContain("await <skill_import>(...)");
expect(prompt).toContain("Python `reference` and `arguments` contract");
expect(prompt).toContain("await asyncio.gather(rlm('task1'), rlm('task2'))");
+ expect(prompt).toContain("Use `/refine` to turn repeated delegation patterns into reusable subagent specs");
+ expect(prompt).toContain("repeated procedures into skills");
+ expect(prompt).toContain("durable facts/preferences into memories");
+ expect(prompt).toContain("narrow behavioral policies into prompt addendums");
expect(prompt).toContain("call_skill(...)");
expect(prompt).toContain("run_subagent(...)");
expect(prompt).toContain("named subagent registries");
@@ -371,6 +445,95 @@ describe("buildSystemPrompt", () => {
expect(prompt).not.toContain("## Anti-patterns");
});
+ test("omits ipython-only subagent guidance when ipython is inactive", () => {
+ const harnessState: HarnessState = {
+ schema: 1,
+ entries: {
+ prompt: {},
+ memory: {},
+ skill: {},
+ subagent: {
+ worker: {
+ id: "worker",
+ kind: "subagent",
+ title: "Worker",
+ content: "Review a self-contained task and report findings.",
+ path: "review",
+ reference: {},
+ arguments: {},
+ metadata: {},
+ source: "refine",
+ created_at: "2026-06-08T00:00:00.000Z",
+ updated_at: "2026-06-08T00:00:00.000Z",
+ version: 1,
+ },
+ },
+ },
+ refinements: [],
+ };
+ const prompt = buildSystemPrompt({
+ selectedTools: ["bash"],
+ contextFiles: [],
+ skills: [],
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ harnessState,
+ });
+
+ expect(prompt).toContain("You are a general purpose agent that uses code to solve tasks.");
+ expect(prompt).toContain("# Continual Harness State");
+ expect(prompt).toContain("Call contract: use installed skills as shell commands");
+ expect(prompt).toContain("subagent: 1");
+ expect(prompt).not.toContain("IPython is the agent's long-lived notebook");
+ expect(prompt).not.toContain("Default to non-blocking subagents");
+ expect(prompt).not.toContain("agent_observe.list_agents");
+ expect(prompt).not.toContain("asyncio.create_task");
+ expect(prompt).not.toContain("await <skill_import>");
+ });
+
+ test("omits shell guidance from harness state when shell is inactive", () => {
+ const harnessState: HarnessState = {
+ schema: 1,
+ entries: {
+ prompt: {},
+ memory: {},
+ skill: {},
+ subagent: {
+ worker: {
+ id: "worker",
+ kind: "subagent",
+ title: "Worker",
+ content: "Review a self-contained task and report findings.",
+ path: "review",
+ reference: {},
+ arguments: {},
+ metadata: {},
+ source: "refine",
+ created_at: "2026-06-08T00:00:00.000Z",
+ updated_at: "2026-06-08T00:00:00.000Z",
+ version: 1,
+ },
+ },
+ },
+ refinements: [],
+ };
+ const prompt = buildSystemPrompt({
+ selectedTools: ["edit"],
+ contextFiles: [],
+ skills: [],
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ harnessState,
+ });
+
+ expect(prompt).toContain("# Continual Harness State");
+ expect(prompt).toContain("without IPython or shell access");
+ expect(prompt).not.toContain("use installed skills as shell commands");
+ expect(prompt).not.toContain("<skill_import> ...");
+ expect(prompt).not.toContain("asyncio.create_task");
+ expect(prompt).not.toContain("await <skill_import>");
+ });
+
test("custom prompt override bypasses the rlm harness body", () => {
const harnessState: HarnessState = {
schema: 1,