A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI] Add child progress notes and kernel-visible child snapshots (#2282)
Seth Kartenebe530d28c9f
diff --git a/packages/coding-agent/.changes/child-progress-notes.md b/packages/coding-agent/.changes/child-progress-notes.mdnew file mode 100644index 0000000000..3118b3e7c4--- /dev/null+++ b/packages/coding-agent/.changes/child-progress-notes.md@@ -0,0 +1,2 @@+- Added `rlm.progress.note`, a throttled child-to-parent progress channel: children report short in-flight notes that surface as `progressNote`, `lastActivityAt`, and `activityStaleMs` on child snapshots and in `rlm.list_subagents()` roster entries, so the parent kernel sees child state without polling or interrupting. `activityStaleMs` measures active (monotonic) time since the last tracked activity and stays unset while a child's activity is `executing`, so a long tool call reads as busy rather than stale and a host sleep does not mark every running child stale on wake.+- Extended the kernel runtime readiness check to require `rlm.progress_note`, so a `PRIME_AGENT_KERNEL_PYTHON` override older than the progress-note API fails fast with an actionable message instead of an `AttributeError` mid-run.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex af96fc909e..53d350f456 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -260,6 +260,7 @@ import {createRlmDeleteSubagentHostHandler,createRlmFindModelsHostHandler,createRlmListSubagentsHostHandler,+ createRlmProgressNoteHostHandler,createRlmRunHostHandler,findRlmModelMatches,findUniqueRlmShortFormModelMatch,@@ -273,6 +274,7 @@ import {type RlmDeleteSubagentResult,type RlmFindModelsResult,type RlmListSubagentsResult,+ type RlmProgressNoteResult,type RlmSpawnHandle,type RlmSubagentRegistryEntry,type RlmSubagentRuntime,@@ -377,6 +379,17 @@ export interface RlmChildAgentSnapshot {sessionDir: string;activity?: RlmChildAgentActivity;repliedSinceTask?: boolean;+ /** Latest child progress note (`rlm.progress.note`), newest wins. */+ progressNote?: string;+ /** Wall-clock ms of the last tracked child activity (seeded at admission, then model/tool/note events). */+ lastActivityAt?: number;+ /**+ * Active time in ms since the last tracked activity, once past the staleness+ * threshold, for a running child that is not executing a tool call.+ * Measured against the monotonic clock, so a host sleep that freezes the+ * session does not flag every running child stale on wake.+ */+ activityStaleMs?: number;error?: string;}@@ -433,6 +446,7 @@ export type AgentSessionEvent =sourceTokens?: readonly AuthSourceToken[];}| { type: "rlm_child_update"; child: RlmChildAgentSnapshot }+ | { type: "rlm_progress_note"; message: string; timestamp: number }| { type: "recap_update"; recap: string | undefined }| { type: "goal_update"; goal: GoalState }| {@@ -1004,6 +1018,20 @@ interface RlmChildRun {answerPreview?: string;toolUseCount: number;activity?: RlmChildAgentActivity;+ /** Bounded ring of the child's latest progress notes (newest last). */+ progressNotes: string[];+ /**+ * Wall-clock ms of the last tracked child activity; carried into snapshots.+ * Seeded at admission so a child that never emits a tracked event still+ * crosses the staleness threshold once running.+ */+ lastActivityAt?: number;+ /**+ * Monotonic counterpart of lastActivityAt (performance.now()), written by+ * the same events. Staleness measures this so wall-clock jumps (a host+ * sleep freezing the whole session) do not inflate it.+ */+ lastActivityMonotonicAt?: number;error?: string;abort: () => void;publication: AgentMessageDeferred;@@ -1046,6 +1074,16 @@ interface RlmSubagentModelSelection {const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";+/** Minimum spacing between accepted progress notes from one child session. */+const RLM_PROGRESS_NOTE_MIN_INTERVAL_MS = 10_000;+/** Bounded ring of progress notes kept per child run; the snapshot exposes the newest. */+const RLM_CHILD_PROGRESS_NOTE_RING_MAX = 5;+/** A running child with no tracked activity for this long reports activityStaleMs. */+const RLM_CHILD_STALE_ACTIVITY_THRESHOLD_MS = 10 * 60_000;+/** Hard cap for answer previews carried into kernel roster entries. */+const RLM_REGISTRY_ANSWER_PREVIEW_MAX_LENGTH = 200;+/** Hard cap for labels carried into kernel roster entries (snapshots keep the full prompt). */+const RLM_REGISTRY_LABEL_MAX_LENGTH = 200;function noopRlmChildAbort(): void {}function noopRlmChildEventUnsubscribe(): void {}@@ -1231,6 +1269,45 @@ export function rlmChildLabel(prompt: string): string {return prompt.replace(/\s+/g, " ").trim() || "child agent";}+/**+ * Record a tracked child activity on both clocks: lastActivityAt stays+ * wall-clock ms for snapshots, and its monotonic twin bounds staleness so a+ * host sleep cannot inflate it.+ */+function touchRlmChildActivity(run: RlmChildRun): void {+ run.lastActivityAt = Date.now();+ run.lastActivityMonotonicAt = performance.now();+}++/**+ * Lazily computed staleness for a running child: how long since the last+ * tracked activity, once past the threshold. Computed at snapshot build time+ * only — no background timers update it.+ *+ * A tool call in flight (activity "executing") is legitimately quiet for its+ * whole duration — a minutes-long bash() run emits no events while it works —+ * so an executing child never reports stale. Staleness measures active time:+ * the wall clock alone would mark every running child stale after a laptop+ * sleep, so the smaller of the wall and monotonic clock deltas bounds it to+ * time the host was actually awake.+ */+function rlmActivityStaleMs(+ status: RlmChildAgentStatus,+ activity: RlmChildAgentActivity | undefined,+ lastActivityAt: number | undefined,+ lastActivityMonotonicAt: number | undefined,+): number | undefined {+ if (status !== "running" || lastActivityAt === undefined) return undefined;+ if (activity?.kind === "executing") return undefined;+ const wallStaleMs = Date.now() - lastActivityAt;+ const monotonicStaleMs =+ lastActivityMonotonicAt === undefined ? wallStaleMs : performance.now() - lastActivityMonotonicAt;+ // Integer ms like every other roster wire field: performance.now() deltas+ // are fractional, and the kernel parser rejects non-int activity_stale_ms.+ const staleMs = Math.floor(Math.min(wallStaleMs, monotonicStaleMs));+ return staleMs >= RLM_CHILD_STALE_ACTIVITY_THRESHOLD_MS ? staleMs : undefined;+}+function readAssistantText(message: AssistantMessage): string {return message.content.filter((block) => block.type === "text")@@ -1464,6 +1541,8 @@ export class AgentSession {// Child usage not yet represented by an indexed attribution, including a delayed parent entry.private _rlmUnindexedChildUsage = new WeakMap<AssistantMessage, Usage>();private _activeRlmChildRuns = new Map<string, RlmChildRun>();+ /** Wall-clock ms of the last accepted progress note; throttles rlm.progress.note. */+ private _lastRlmProgressNoteAt: number | undefined;private _unsettledRlmChildRuns = new Set<RlmChildRun>();private _abandonedRlmQuiescenceChildIds = new Set<string>();private _rlmQuiescenceWaitAborts = new Set<AbortController>();@@ -10332,6 +10411,7 @@ export class AgentSession {"rlm.collect": createRlmCollectHostHandler((targets, timeoutMs) =>this.collectRlmChildren(targets, timeoutMs),),+ "rlm.progress.note": createRlmProgressNoteHostHandler((message) => this.noteRlmProgress(message)),"rlm.delete_subagent": createRlmDeleteSubagentHostHandler((target) => this.deleteRlmSubagent(target)),"model.info": async () => ({id: this.model?.id ?? null,@@ -10744,10 +10824,66 @@ export class AgentSession {return run.session?.sessionId;}+ /**+ * Child-side progress note admission. The host wrapper validated shape and+ * length; this throttles per session (event-loop spam guard) and re-emits+ * an `rlm_progress_note` event for the parent's child-event subscription.+ * Pull-based only: rejected notes return a retry hint instead of an error.+ */+ noteRlmProgress(message: string): RlmProgressNoteResult {+ const now = Date.now();+ const lastAt = this._lastRlmProgressNoteAt;+ if (lastAt !== undefined && now - lastAt < RLM_PROGRESS_NOTE_MIN_INTERVAL_MS) {+ return { accepted: false, retry_after_ms: RLM_PROGRESS_NOTE_MIN_INTERVAL_MS - (now - lastAt) };+ }+ this._lastRlmProgressNoteAt = now;+ this._emit({ type: "rlm_progress_note", message, timestamp: now });+ return { accepted: true, retry_after_ms: undefined };+ }+async listRlmSubagents(): Promise<RlmListSubagentsResult> {return this._buildRlmSubagentList(await this._agentMessageController?.listAgents());}+ /**+ * Project bounded snapshot fields onto kernel roster entries so the parent+ * model sees nearly as much as daemon clients do. Answer previews are+ * hard-capped here (compactRlmText already caps at 160).+ */+ private _rlmRegistryExtrasFromSnapshot(+ snapshot: RlmChildAgentSnapshot,+ ): Pick<+ RlmSubagentRegistryEntry,+ | "activity"+ | "tool_use_count"+ | "duration_ms"+ | "answer_preview"+ | "replied_since_task"+ | "progress_note"+ | "label"+ | "last_activity_at"+ | "activity_stale_ms"+ > {+ return {+ // Project to the registry's snake_case wire shape; the Python kernel+ // reads activity.tool_name directly from the JSON payload.+ activity: snapshot.activity+ ? {+ kind: snapshot.activity.kind,+ ...(snapshot.activity.toolName ? { tool_name: snapshot.activity.toolName } : {}),+ }+ : undefined,+ tool_use_count: snapshot.toolUseCount,+ duration_ms: snapshot.durationMs,+ answer_preview: snapshot.answerPreview?.slice(0, RLM_REGISTRY_ANSWER_PREVIEW_MAX_LENGTH),+ replied_since_task: snapshot.repliedSinceTask,+ progress_note: snapshot.progressNote,+ label: snapshot.label.slice(0, RLM_REGISTRY_LABEL_MAX_LENGTH),+ last_activity_at: snapshot.lastActivityAt,+ activity_stale_ms: snapshot.activityStaleMs,+ };+ }+private _buildRlmSubagentList(listedAgents?: AgentSessionMessageListResult): RlmListSubagentsResult {const daemonChildren = new Map<string, AgentSessionMessageAgentSummary>();const parentActiveSessionId = listedAgents?.current?.activeSessionId;@@ -10777,10 +10913,11 @@ export class AgentSession {session_name: daemonChild?.sessionName ?? run.session?.sessionName ?? run.sessionName,session_dir: run.sessionDir,status: run.status === "done" ? "completed" : run.status === "error" ? "error" : "running",+ ...this._rlmRegistryExtrasFromSnapshot(this._rlmChildSnapshotForRun(run)),});recorded.add(run.id);}- for (const [childId, { session: childSession }] of this._rlmChildSessions) {+ for (const [childId, { session: childSession, run: retainedRun }] of this._rlmChildSessions) {if (this._deletingRlmChildren.has(childId) ||recorded.has(childId) ||@@ -10793,6 +10930,9 @@ export class AgentSession {if (!sessionDir) {continue;}+ const extrasSnapshot = retainedRun+ ? this._rlmChildSnapshotForRun(retainedRun, childSession)+ : this._rlmChildSnapshotForSession(childId, childSession);subagents.push({rlm_child_id: childId,active_session_id: daemonChild?.activeSessionId ?? null,@@ -10801,6 +10941,7 @@ export class AgentSession {daemonChild?.sessionName ?? childSession.sessionName ?? createDefaultRlmSubagentSessionName("", childId),session_dir: sessionDir,status: "completed",+ ...this._rlmRegistryExtrasFromSnapshot(extrasSnapshot),});recorded.add(childId);}@@ -11318,6 +11459,9 @@ export class AgentSession {sessionDir: run.sessionDir,activity: run.activity,repliedSinceTask: child?._repliedToParentSinceTask,+ progressNote: run.progressNotes.at(-1),+ lastActivityAt: run.lastActivityAt,+ activityStaleMs: rlmActivityStaleMs(run.status, run.activity, run.lastActivityAt, run.lastActivityMonotonicAt),error: run.error,};}@@ -11784,6 +11928,7 @@ export class AgentSession {};let runningToolCount = 0;let childSession: AgentSession | undefined;+ const startedMonotonicAt = performance.now();const run: RlmChildRun = {id: childNodeId,prompt,@@ -11792,6 +11937,11 @@ export class AgentSession {model: modelSelection.model,status: "queued",toolUseCount: 0,+ progressNotes: [],+ // Seed the staleness clock at admission: a child hung before its+ // first tracked event still crosses the threshold once running.+ lastActivityAt: startedAt,+ lastActivityMonotonicAt: startedMonotonicAt,settled: false,abort: noopRlmChildAbort,publication: createAgentMessageDeferred(),@@ -11805,7 +11955,13 @@ export class AgentSession {this._unsettledRlmChildRuns.add(run);const emitChildUpdate = () => {const child = this._rlmChildSnapshotForRun(run);- const serialized = JSON.stringify(child);+ // Dedup compares observable child state, not clock-derived fields:+ // lastActivityAt advances on every streamed token delta and+ // activityStaleMs is recomputed on each snapshot build, so including+ // either would re-emit on every delta once answerPreview saturates its+ // cap. Emitted snapshots still carry both fields fresh.+ const { lastActivityAt: _lastActivityAt, activityStaleMs: _activityStaleMs, ...stable } = child;+ const serialized = JSON.stringify(stable);if (serialized === run.lastEmittedUpdate) return;run.lastEmittedUpdate = serialized;this._emit({ type: "rlm_child_update", child });@@ -11896,10 +12052,19 @@ export class AgentSession {}if (event.type === "agent_start") {run.activity = { kind: "waiting" };+ touchRlmChildActivity(run);emitChildUpdate();} else if (event.type === "agent_end") {flushPendingChildUsageAttribution();run.activity = undefined;+ touchRlmChildActivity(run);+ emitChildUpdate();+ } else if (event.type === "rlm_progress_note") {+ run.progressNotes.push(event.message);+ if (run.progressNotes.length > RLM_CHILD_PROGRESS_NOTE_RING_MAX) {+ run.progressNotes.shift();+ }+ touchRlmChildActivity(run);emitChildUpdate();} else if (event.type === "message_end" && event.message.role === "assistant") {const assistant = event.message as AssistantMessage;@@ -11931,12 +12096,14 @@ export class AgentSession {}const text = compactRlmText(readAssistantText(assistant));if (text) run.answerPreview = text;+ touchRlmChildActivity(run);emitChildUpdate();} else if (event.type === "message_start" || event.type === "message_update") {if (event.message.role === "assistant") {const text = compactRlmText(readAssistantText(event.message as AssistantMessage));if (text) run.answerPreview = text;run.activity = { kind: "writing" };+ touchRlmChildActivity(run);emitChildUpdate();}} else if (event.type === "tool_execution_start") {@@ -11944,10 +12111,12 @@ export class AgentSession {run.toolUseCount += 1;runningToolCount += 1;run.activity = { kind: "executing", toolName: event.toolName };+ touchRlmChildActivity(run);emitChildUpdate();} else if (event.type === "tool_execution_end") {runningToolCount = Math.max(0, runningToolCount - 1);if (runningToolCount === 0) run.activity = { kind: "waiting" };+ touchRlmChildActivity(run);emitChildUpdate();} else if (event.type === "session_info_changed" || event.type === "recap_update") {emitChildUpdate();diff --git a/packages/coding-agent/src/core/kernel/bootstrap.ts b/packages/coding-agent/src/core/kernel/bootstrap.tsindex bd9921caf3..126a7b248f 100644--- a/packages/coding-agent/src/core/kernel/bootstrap.ts+++ b/packages/coding-agent/src/core/kernel/bootstrap.ts@@ -87,7 +87,7 @@ const REQUIRED_HARNESS_METHODS = ["delete_prompt_note","record_refinement",];-const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')`;+const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert callable(rlm.spawn); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm.spawn); assert inspect.signature(rlm.spawn).parameters['name'].default is inspect.Parameter.empty; assert not hasattr(rlm, 'run'); assert not hasattr(rlm.rlm, 'run'); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert callable(rlm.create_session); assert callable(rlm.rlm.create_session); assert callable(rlm.progress_note); assert callable(rlm.rlm.progress_note); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 3; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')`;const BOOTSTRAP_VERSION_FILE = ".bootstrap-version";const BOOTSTRAP_LOCK_NAME = ".bootstrap.lock";const BOOTSTRAP_LOCK_RETRY_MS = 100;@@ -895,7 +895,7 @@ async function ensureKernelPythonUncached(const missing: string[] = [];if (!(await hasPrimeAgentRuntime(python))) {missing.push(- "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, and explicit harness CRUD methods",+ "a current prime-agent-runtime with callable rlm.spawn, rlm.create_session, rlm.host_request, rlm.progress_note, and explicit harness CRUD methods",);}if (missing.length === 0) {diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex d9bae2d69e..6a669324cf 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -72,6 +72,11 @@ export function buildChildAgentDoctrine(options: ChildAgentDoctrineOptions): str'When a task calls for an answer, reply explicitly with `await agent_message.send(message, receiver_role="parent")`. Not every message or task needs a reply; continue cleanup after sending and go idle normally.',);}+ if (hasIpython) {+ lines.push(+ "For long-running work, report brief progress with `await rlm.progress_note('...')` (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply.",+ );+ }return lines.join("\n");}@@ -218,6 +223,9 @@ export function buildSubagentGuidance();}lines.push("Use `await rlm.list_subagents()` after kernel restart or compaction.");+ lines.push(+ "Long-running children can report in-flight status with `await rlm.progress_note(...)`; `rlm.list_subagents()` shows each child's activity, latest progress note, and staleness.",+ );if (options.hasAgentObserve) {lines.push("Use `agent_observe` for bounded transcript inspection.");}diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex ac2b1ee95b..4455b00a5a 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -34,6 +34,15 @@ export interface RlmSpawnHandle {export type RlmSubagentRegistryStatus = "running" | "completed" | "error";+/**+ * Kernel-wire shape of a child activity snapshot: snake_case like the rest of+ * the registry, so `JSON.stringify` needs no key rewrite on the Python side.+ */+export interface RlmSubagentRegistryActivity {+ kind: "waiting" | "writing" | "executing";+ tool_name?: string;+}+export interface RlmSubagentRegistryEntry {rlm_child_id: string;active_session_id: string | null;@@ -41,6 +50,21 @@ export interface RlmSubagentRegistryEntry {session_name: string;session_dir: string;status: RlmSubagentRegistryStatus;+ /** Live-state extras, present when the run or retained session is locally available. */+ activity?: RlmSubagentRegistryActivity;+ tool_use_count?: number;+ duration_ms?: number;+ /** Compacted answer preview, hard-capped for the kernel roster. */+ answer_preview?: string;+ replied_since_task?: boolean;+ /** Latest child progress note (`rlm.progress.note`), newest wins. */+ progress_note?: string;+ /** One-line task label, hard-capped for the kernel roster. */+ label?: string;+ /** Wall-clock ms of the last tracked child activity; seeded at admission. */+ last_activity_at?: number;+ /** Set when a running child has had no tracked activity for the staleness threshold. */+ activity_stale_ms?: number;}export interface RlmListSubagentsResult {@@ -391,6 +415,37 @@ export function createRlmCollectHostHandler(handler: RlmCollectHandler): HostReq};}+export interface RlmProgressNoteResult {+ accepted: boolean;+ /** Milliseconds until the next note can be accepted; absent when accepted. */+ retry_after_ms: number | undefined;+}++export type RlmProgressNoteHandler = (message: string) => RlmProgressNoteResult;++/** Hard bound for one progress note; the session handler owns the time throttle. */+export const RLM_PROGRESS_NOTE_MAX_LENGTH = 512;++/**+ * Child progress notes: `rlm.progress.note` lets a child report short in-flight+ * status that its parent reads from snapshots and roster entries. Pull-based+ * only — notes never steer the parent or grow its message queue.+ */+export function createRlmProgressNoteHostHandler(handler: RlmProgressNoteHandler): HostRequestHandler {+ return async (payload) => {+ const raw = payload.message;+ if (typeof raw !== "string" || !raw.trim()) {+ throw new Error("rlm.progress.note message must be a non-empty string");+ }+ const message = raw.trim();+ if (message.length > RLM_PROGRESS_NOTE_MAX_LENGTH) {+ throw new Error(`rlm.progress.note message must be at most ${RLM_PROGRESS_NOTE_MAX_LENGTH} characters`);+ }+ const { accepted, retry_after_ms } = handler(message);+ return retry_after_ms === undefined ? { accepted } : { accepted, retry_after_ms };+ };+}+export interface RlmSubagentRuntime {session: AgentSession;}diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex c3941e1061..93fc27d514 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -569,6 +569,11 @@ export interface AgentConnectionRlmChildAgentSnapshot {recap?: string;sessionDir: string;activity?: AgentConnectionRlmChildAgentActivity;+ /** Latest child progress note (`rlm.progress.note`), newest wins. */+ progressNote?: string;+ lastActivityAt?: number;+ /** Set when a running child has had no tracked activity for the staleness threshold. */+ activityStaleMs?: number;error?: string;}@@ -615,6 +620,7 @@ export type AgentConnectionSessionEvent =}| { type: "auth_stale"; provider: string; sourceTokens?: readonly AuthSourceToken[] }| { type: "rlm_child_update"; child: AgentConnectionRlmChildAgentSnapshot }+ | { type: "rlm_progress_note"; message: string; timestamp: number }| { type: "recap_update"; recap: string | undefined }| { type: "goal_update"; goal: GoalState }| { type: "bash_start"; command: string; excludeFromContext: boolean; transient?: boolean; runId?: string }diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 039b3ab861..80df57db41 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -105,6 +105,7 @@ interface InspectableRlmRun {error?: string;abandonedForQuiescence?: boolean;activity?: { kind: string };+ progressNotes?: string[];emitUpdate?: () => void;publication?: { promise: Promise<void>; resolve(): void; reject(error: Error): void };settlement?: { promise: Promise<void>; resolve(): void; reject(error: Error): void };@@ -725,6 +726,7 @@ describe("AgentSession rlm recursion", () => {abort: () => {},status: index === 1 ? "queued" : "running",settled: false,+ progressNotes: [],});if (hiding === "detached") {@@ -737,6 +739,7 @@ describe("AgentSession rlm recursion", () => {abort: () => {},status: "cancelled",settled: false,+ progressNotes: [],detachedDeletion: {rlm_child_id: id,active_session_id: null,@@ -2149,6 +2152,11 @@ describe("AgentSession rlm recursion", () => {session_name: expectedSessionName,session_dir: result.session_dir,status: "completed",+ answer_preview: "child answer: retained worker",+ duration_ms: expect.any(Number),+ label: "retained worker",+ last_activity_at: expect.any(Number),+ replied_since_task: false,},],};@@ -2420,6 +2428,10 @@ describe("AgentSession rlm recursion", () => {session_name: createDefaultRlmSubagentSessionName("slow shard", rootRun.id),session_dir: rootRun.sessionDir,status: "running",+ activity: { kind: "waiting" },+ label: "slow shard",+ last_activity_at: expect.any(Number),+ replied_since_task: false,},],});@@ -3396,6 +3408,7 @@ describe("AgentSession rlm recursion", () => {abort: () => {},status: "running",settled: false,+ progressNotes: [],});const root = createSession();const rootInternals = root as unknown as InspectableRlmSession;@@ -3411,6 +3424,7 @@ describe("AgentSession rlm recursion", () => {publication: deferred(),settlement: deferred(),session: child,+ progressNotes: [],};rootInternals._activeRlmChildRuns.set(run.id, run);rootInternals._unsettledRlmChildRuns.add(run);diff --git a/packages/coding-agent/test/kernel-bootstrap.test.ts b/packages/coding-agent/test/kernel-bootstrap.test.tsindex d81ccee49c..5cfb8eb7c1 100644--- a/packages/coding-agent/test/kernel-bootstrap.test.ts+++ b/packages/coding-agent/test/kernel-bootstrap.test.ts@@ -545,6 +545,36 @@ dependencies = ["httpx"]await expect(ensureKernelPython()).rejects.toThrow(/current prime-agent-runtime with callable rlm\.spawn/);});+ it("rejects PRIME_AGENT_KERNEL_PYTHON with a pre-progress-note rlm runtime", async () => {+ const overridePython = join(tempDir, "override-python");+ // An rlm runtime older than rlm.progress_note: it satisfies every+ // earlier readiness probe but fails any check that asserts the new+ // API (regression: the readiness check skipped progress_note, so the+ // doctrine's advertised call hit AttributeError mid-run instead of+ // failing fast here).+ writeExecutable(+ overridePython,+ [+ "#!/bin/sh",+ 'if [ "$1" = "-c" ]; then',+ ' case "$2" in',+ ' "import rlm") exit 0 ;;',+ ' *"progress_note"*) exit 1 ;;',+ ' *"_harness_methods"*) exit 0 ;;',+ " *) exit 1 ;;",+ " esac",+ "fi",+ "exit 0",+ "",+ ].join("\n"),+ );+ process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;++ await expect(ensureKernelPython()).rejects.toThrow(+ /current prime-agent-runtime with callable rlm\.spawn, rlm\.create_session, rlm\.host_request, rlm\.progress_note/,+ );+ });+it("fails an invalid PRIME_AGENT_KERNEL_PYTHON without bootstrapping", async () => {const overridePython = join(tempDir, "override-python");writeFakePython(overridePython, []);diff --git a/packages/coding-agent/test/rlm-progress-notes.test.ts b/packages/coding-agent/test/rlm-progress-notes.test.tsnew file mode 100644index 0000000000..737b6694ae--- /dev/null+++ b/packages/coding-agent/test/rlm-progress-notes.test.ts@@ -0,0 +1,597 @@+import { mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Agent } from "@earendil-works/pi-agent-core";+import {+ type AssistantMessage,+ type Context,+ createAssistantMessageEventStream,+ getModel,+ type TextContent,+ type Usage,+} from "@earendil-works/pi-ai";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { AgentSession } from "../src/core/agent-session.js";+import { AuthStorage } from "../src/core/auth-storage.js";+import { convertToLlm } from "../src/core/messages.js";+import { ModelRegistry } from "../src/core/model-registry.js";+import { createRlmProgressNoteHostHandler, RLM_PROGRESS_NOTE_MAX_LENGTH } from "../src/core/rlm-runtime.js";+import { SessionManager } from "../src/core/session-manager.js";+import { SettingsManager } from "../src/core/settings-manager.js";+import { createTestResourceLoader } from "./utilities.js";++const model = getModel("anthropic", "claude-sonnet-4-5")!;++interface InspectableRlmRun {+ progressNotes: string[];+ lastActivityAt?: number;+ lastActivityMonotonicAt?: number;+ status: string;+ activity?: { kind: string };+ session?: AgentSession;+}++interface InspectableRlmSession {+ _activeRlmChildRuns: Map<string, InspectableRlmRun>;+}++interface InspectableNoteThrottle {+ _lastRlmProgressNoteAt?: number;+}++function userText(context: Context): string {+ const last = context.messages.at(-1);+ if (!last || last.role !== "user") return "";+ if (typeof last.content === "string") return last.content;+ return last.content+ .filter((block): block is TextContent => block.type === "text")+ .map((block) => block.text)+ .join(" ");+}++function usage(input = 7, output = 3): Usage {+ return {+ input,+ output,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: input + output,+ cost: { input, output, cacheRead: 0, cacheWrite: 0, total: input + output },+ };+}++function assistantMessage(text: string): AssistantMessage {+ return {+ role: "assistant",+ content: [{ type: "text", text }],+ api: model.api,+ provider: model.provider,+ model: model.id,+ usage: usage(),+ stopReason: "stop",+ timestamp: Date.now(),+ };+}++/**+ * A stream that stays open until the test completes it, keeping the child+ * running. Completion requested before the stream opens is applied when it+ * opens, so `complete` is race-proof against the child's turn admission.+ */+function heldAnswerStream(): {+ streamFn: (model: unknown, context: Context) => ReturnType<typeof createAssistantMessageEventStream>;+ complete: (text: string) => void;+} {+ let complete: ((text: string) => void) | undefined;+ let requestedBeforeOpen: string | undefined;+ const streamFn = (_model: unknown, context: Context) => {+ const stream = createAssistantMessageEventStream();+ complete = (text: string) => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage(`${text}: ${userText(context)}`) });+ };+ if (requestedBeforeOpen !== undefined) complete(requestedBeforeOpen);+ return stream;+ };+ return {+ streamFn,+ complete: (text) => {+ if (complete) complete(text);+ else requestedBeforeOpen = text;+ },+ };+}++async function waitFor(condition: () => boolean, timeoutMs = 5_000): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (!condition()) {+ if (Date.now() > deadline) {+ throw new Error("Timed out waiting for condition");+ }+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}++describe("rlm.progress.note child progress channel", () => {+ let tempDir: string;+ let session: AgentSession | undefined;++ beforeEach(() => {+ tempDir = join(tmpdir(), `pi-rlm-progress-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ mkdirSync(tempDir, { recursive: true });+ });++ afterEach(() => {+ session?.dispose();+ session = undefined;+ rmSync(tempDir, { recursive: true, force: true });+ });++ function makeSession(+ streamFn?: (model: unknown, context: Context) => ReturnType<typeof createAssistantMessageEventStream>,+ sessionsDir = join(tempDir, "sessions"),+ ): AgentSession {+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));+ authStorage.setRuntimeApiKey("anthropic", "test-key");+ const agent = new Agent({+ convertToLlm,+ getApiKey: () => "test-key",+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },+ streamFn:+ streamFn ??+ ((_model: unknown, context: Context) => {+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage(userText(context)) });+ });+ return stream;+ }),+ });+ return new AgentSession({+ agent,+ sessionManager: SessionManager.create(tempDir, sessionsDir),+ settingsManager: SettingsManager.create(tempDir, tempDir),+ cwd: tempDir,+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),+ resourceLoader: createTestResourceLoader(),+ });+ }++ it("validates host payload shape", async () => {+ const handler = createRlmProgressNoteHostHandler(() => ({ accepted: true, retry_after_ms: undefined }));+ await expect(handler({ message: 42 })).rejects.toThrow("non-empty string");+ await expect(handler({ message: " " })).rejects.toThrow("non-empty string");+ await expect(handler({ message: "x".repeat(RLM_PROGRESS_NOTE_MAX_LENGTH + 1) })).rejects.toThrow(+ `at most ${RLM_PROGRESS_NOTE_MAX_LENGTH}`,+ );+ // The bound counts UTF-16 code units, so 512 astral characters (1024+ // units) cross it; the Python-side cap measures the same way.+ await expect(handler({ message: "🎉".repeat(RLM_PROGRESS_NOTE_MAX_LENGTH) })).rejects.toThrow(+ `at most ${RLM_PROGRESS_NOTE_MAX_LENGTH}`,+ );+ await expect(handler({ message: " working on it " })).resolves.toEqual({ accepted: true });++ let received = "";+ const observing = createRlmProgressNoteHostHandler((message) => {+ received = message;+ return { accepted: true, retry_after_ms: undefined };+ });+ await observing({ message: " building tests " });+ expect(received).toBe("building tests");++ const throttled = createRlmProgressNoteHostHandler(() => ({ accepted: false, retry_after_ms: 1234 }));+ await expect(throttled({ message: "note" })).resolves.toEqual({ accepted: false, retry_after_ms: 1234 });+ });++ it("throttles repeated notes per session and emits one event each", () => {+ session = makeSession();+ const events: { message: string; timestamp: number }[] = [];+ session.subscribe((event) => {+ if (event.type === "rlm_progress_note") events.push({ message: event.message, timestamp: event.timestamp });+ });++ const first = session.noteRlmProgress("first note");+ expect(first.accepted).toBe(true);+ expect(first.retry_after_ms).toBeUndefined();++ const second = session.noteRlmProgress("second note");+ expect(second.accepted).toBe(false);+ expect(second.retry_after_ms).toBeGreaterThan(0);+ expect(second.retry_after_ms).toBeLessThanOrEqual(10_000);++ expect(events).toHaveLength(1);+ expect(events[0].message).toBe("first note");+ expect(events[0].timestamp).toBeGreaterThan(0);++ // Notes past the throttle window are accepted again.+ (session as unknown as InspectableNoteThrottle)._lastRlmProgressNoteAt = Date.now() - 10_001;+ const third = session.noteRlmProgress("third note");+ expect(third.accepted).toBe(true);+ expect(events).toHaveLength(2);+ expect(events[1].message).toBe("third note");+ });++ it("captures child notes into the run snapshot and roster entries", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const childUpdates: (string | undefined)[] = [];+ session.subscribe((event) => {+ if (event.type === "rlm_child_update" && event.child.progressNote !== undefined) {+ childUpdates.push(event.child.progressNote);+ }+ });++ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.get(handle.rlm_child_id)?.session !== undefined);+ const run = runs.get(handle.rlm_child_id)!;+ const child = run.session!;++ try {+ // The agent turn starts asynchronously after admission; wait for its+ // activity signal, then push a note mid-run.+ await waitFor(() => run.activity !== undefined);+ child.noteRlmProgress("halfway done");+ expect(run.progressNotes).toEqual(["halfway done"]);++ const snapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(snapshot?.progressNote).toBe("halfway done");+ expect(snapshot?.lastActivityAt).toBeGreaterThan(0);+ expect(snapshot?.activityStaleMs).toBeUndefined();+ expect(childUpdates).toContain("halfway done");++ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(entry?.progress_note).toBe("halfway done");+ expect(entry?.label).toBe("slow task");+ expect(["waiting", "writing"]).toContain(entry?.activity?.kind);+ expect(entry?.tool_use_count).toBeUndefined();+ expect(entry?.last_activity_at).toBeGreaterThan(0);+ expect(entry?.activity_stale_ms).toBeUndefined();++ // A tool execution must reach the roster in the registry's snake_case+ // activity shape (regression: toolName previously never reached the kernel).+ (child as unknown as { _emit: (event: unknown) => void })._emit({+ type: "tool_execution_start",+ toolCallId: "tool-1",+ toolName: "ipython",+ args: {},+ });+ const toolRoster = await session.listRlmSubagents();+ const toolEntry = toolRoster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(toolEntry?.activity).toEqual({ kind: "executing", tool_name: "ipython" });+ expect(toolEntry?.tool_use_count).toBe(1);+ } finally {+ held.complete("child answer");+ await waitFor(+ () => session!.getRlmChildSnapshots().every((candidate) => candidate.status !== "running"),+ 20_000,+ );+ }++ const settled = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(settled?.status).toBe("done");+ expect(settled?.progressNote).toBe("halfway done");+ expect(settled?.answerPreview).toContain("child answer");+ expect(settled?.lastActivityAt).toBeGreaterThan(0);+ // Staleness is a running-only signal; a finished child never reports it.+ expect(settled?.activityStaleMs).toBeUndefined();+ });++ it("bounds the note ring and always exposes the newest note", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.get(handle.rlm_child_id)?.session !== undefined);+ const run = runs.get(handle.rlm_child_id)!;+ const child = run.session!;++ try {+ // Notes flow while the child works; wait for the agent turn first.+ await waitFor(() => run.activity !== undefined);+ for (let index = 1; index <= 7; index += 1) {+ // Reset the per-session throttle so every note is admitted deterministically.+ (child as unknown as InspectableNoteThrottle)._lastRlmProgressNoteAt = 0;+ child.noteRlmProgress(`note ${index}`);+ }+ expect(run.progressNotes).toEqual(["note 3", "note 4", "note 5", "note 6", "note 7"]);+ expect(run.lastActivityAt).toBeGreaterThan(0);++ const snapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(snapshot?.progressNote).toBe("note 7");++ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(entry?.progress_note).toBe("note 7");+ } finally {+ held.complete("child answer");+ await waitFor(+ () => session!.getRlmChildSnapshots().every((candidate) => candidate.status !== "running"),+ 20_000,+ );+ }+ });++ it("reports staleness only while the child is running", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.get(handle.rlm_child_id)?.session !== undefined);+ const run = runs.get(handle.rlm_child_id)!;++ try {+ // The agent turn starts asynchronously; wait for its activity signal+ // so no tracked event can overwrite the simulated staleness below.+ await waitFor(() => run.activity !== undefined);+ // Simulate a child silent for the threshold of active time: age+ // both clocks together, as real elapsed time would.+ run.lastActivityAt = Date.now() - 11 * 60_000;+ run.lastActivityMonotonicAt = performance.now() - 11 * 60_000;+ const staleSnapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(staleSnapshot?.status).toBe("running");+ expect(staleSnapshot?.activityStaleMs).toBeGreaterThanOrEqual(10 * 60_000);++ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(entry?.activity_stale_ms).toBeGreaterThanOrEqual(10 * 60_000);++ // Fresh activity clears staleness at the next snapshot build.+ run.lastActivityAt = Date.now();+ const freshSnapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(freshSnapshot?.activityStaleMs).toBeUndefined();+ } finally {+ held.complete("child answer");+ await waitFor(+ () => session!.getRlmChildSnapshots().every((candidate) => candidate.status !== "running"),+ 20_000,+ );+ }+ });++ it("never marks a tool call in flight stale, even past the threshold", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.get(handle.rlm_child_id)?.session !== undefined, 20_000);+ const run = runs.get(handle.rlm_child_id)!;+ const child = run.session!;++ try {+ // The agent turn starts asynchronously; wait for its activity signal+ // so no tracked event can overwrite the injected tool execution.+ await waitFor(() => run.activity !== undefined, 20_000);+ const emitChild = (event: unknown) => (child as unknown as { _emit: (event: unknown) => void })._emit(event);+ emitChild({ type: "tool_execution_start", toolCallId: "tool-1", toolName: "bash", args: {} });++ // A long bash() call streams no child events for its whole+ // duration; age both clocks 11 minutes into that silence. The+ // child is busy executing, not stale (regression: staleness used+ // to ignore activity and flag exactly this case).+ run.lastActivityAt = Date.now() - 11 * 60_000;+ run.lastActivityMonotonicAt = performance.now() - 11 * 60_000;+ const executingSnapshot = session+ .getRlmChildSnapshots()+ .find((candidate) => candidate.id === handle.rlm_child_id);+ expect(executingSnapshot?.status).toBe("running");+ expect(executingSnapshot?.activity).toEqual({ kind: "executing", toolName: "bash" });+ expect(executingSnapshot?.activityStaleMs).toBeUndefined();++ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(entry?.activity).toEqual({ kind: "executing", tool_name: "bash" });+ expect(entry?.activity_stale_ms).toBeUndefined();++ // The suppression is executing-only: once the tool ends and the+ // child goes quiet again for the threshold, staleness returns.+ emitChild({ type: "tool_execution_end", toolCallId: "tool-1", args: {}, output: "" });+ run.lastActivityAt = Date.now() - 11 * 60_000;+ run.lastActivityMonotonicAt = performance.now() - 11 * 60_000;+ const waitingSnapshot = session+ .getRlmChildSnapshots()+ .find((candidate) => candidate.id === handle.rlm_child_id);+ expect(waitingSnapshot?.activity?.kind).toBe("waiting");+ expect(waitingSnapshot?.activityStaleMs).toBeGreaterThanOrEqual(10 * 60_000);+ } finally {+ held.complete("child answer");+ await waitFor(+ () => session!.getRlmChildSnapshots().every((candidate) => candidate.status !== "running"),+ 20_000,+ );+ }+ });++ it("does not flag a running child stale after a host-sleep wall-clock jump", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.get(handle.rlm_child_id)?.session !== undefined, 20_000);+ const run = runs.get(handle.rlm_child_id)!;++ try {+ // The agent turn starts asynchronously; wait for its activity signal+ // so no tracked event can overwrite the simulated wake below.+ await waitFor(() => run.activity !== undefined, 20_000);+ // Simulate waking from a six-hour laptop sleep: the wall clock+ // jumped, but the monotonic clock only advanced while the host+ // was awake (regression: wall-clock staleness marked every+ // running child stale on wake).+ run.lastActivityAt = Date.now() - 6 * 60 * 60_000;+ run.lastActivityMonotonicAt = performance.now() - 30_000;+ const wokeSnapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(wokeSnapshot?.status).toBe("running");+ expect(wokeSnapshot?.activityStaleMs).toBeUndefined();++ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(entry?.activity_stale_ms).toBeUndefined();++ // Staleness still measures genuinely idle active time: a child+ // silent for the threshold while the host is awake stays stale+ // even with the stale wall-clock reading still in place.+ run.lastActivityMonotonicAt = performance.now() - 11 * 60_000;+ const idleSnapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(idleSnapshot?.activityStaleMs).toBeGreaterThanOrEqual(10 * 60_000);+ // The monotonic delta is fractional, but staleness stays integer ms:+ // the kernel roster parser rejects non-int activity_stale_ms+ // (regression: performance.now() deltas used to leak floats onto+ // the wire and break rlm.list_subagents() for a stale child).+ expect(Number.isInteger(idleSnapshot?.activityStaleMs)).toBe(true);++ const idleRoster = await session.listRlmSubagents();+ const idleEntry = idleRoster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ expect(Number.isInteger(idleEntry?.activity_stale_ms)).toBe(true);+ expect(idleEntry?.activity_stale_ms).toBeGreaterThanOrEqual(10 * 60_000);+ } finally {+ held.complete("child answer");+ await waitFor(+ () => session!.getRlmChildSnapshots().every((candidate) => candidate.status !== "running"),+ 20_000,+ );+ }+ });++ it("seeds the staleness clock at admission for never-active children", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ const run = runs.get(handle.rlm_child_id)!;++ try {+ // Admission seeds the clock before any tracked event: a child hung+ // before its first activity still crosses the staleness threshold+ // once running. Previously the timestamp only appeared with the+ // first child event, so a never-active child was never stale.+ expect(run.lastActivityAt).toBeGreaterThan(0);+ expect(run.lastActivityMonotonicAt).toBeGreaterThan(0);+ } finally {+ held.complete("child answer");+ await waitFor(() => {+ const snapshot = session!.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ return snapshot?.status !== "running" && snapshot?.status !== "queued";+ }, 20_000);+ }+ });++ it("caps the kernel roster label while snapshots keep the full prompt", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ // rlmChildLabel collapses whitespace only; the collapsed label still+ // far exceeds the roster's hard cap.+ const longPrompt = "refactor the frobnicator ".repeat(40);+ const handle = await session.runRlmChild(longPrompt, { name: "worker-a" });++ try {+ const snapshot = session.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ expect(snapshot?.label.length).toBeGreaterThan(200);+ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === handle.rlm_child_id);+ // The kernel roster entry is bounded like the other wire extras; the+ // snapshot keeps the full label for the TUI.+ expect(entry?.label).toHaveLength(200);+ expect(entry?.label).toBe(snapshot?.label.slice(0, 200));+ } finally {+ held.complete("child answer");+ await waitFor(() => {+ const snapshot = session!.getRlmChildSnapshots().find((candidate) => candidate.id === handle.rlm_child_id);+ return snapshot?.status !== "running" && snapshot?.status !== "queued";+ }, 20_000);+ }+ });++ it("does not churn child updates on streaming deltas once the preview saturates", async () => {+ const held = heldAnswerStream();+ session = makeSession(held.streamFn);+ const handle = await session.runRlmChild("slow task", { name: "worker-a" });+ const runs = (session as unknown as InspectableRlmSession)._activeRlmChildRuns;+ await waitFor(() => runs.get(handle.rlm_child_id)?.session !== undefined);+ const run = runs.get(handle.rlm_child_id)!;+ const child = run.session!;+ const childUpdates: { preview?: string; activityKind?: string; activityToolName?: string }[] = [];+ session.subscribe((event) => {+ if (event.type === "rlm_child_update" && event.child.id === handle.rlm_child_id) {+ childUpdates.push({+ preview: event.child.answerPreview,+ activityKind: event.child.activity?.kind,+ activityToolName: event.child.activity?.toolName,+ });+ }+ });+ const emitChild = (event: unknown) => (child as unknown as { _emit: (event: unknown) => void })._emit(event);++ try {+ // The agent turn starts asynchronously; wait for its activity signal so+ // no tracked event can race the injected streaming deltas.+ await waitFor(() => run.activity !== undefined);+ // Streaming past the 160-character preview cap: like real token+ // deltas, appending text past the cap leaves the capped preview+ // unchanged, so only lastActivityAt still moves.+ const saturatedText = "saturation".repeat(40);+ const baseline = childUpdates.length;+ emitChild({ type: "message_update", message: assistantMessage(saturatedText) });+ await waitFor(() => childUpdates.length > baseline);+ expect(childUpdates.at(-1)?.preview).toHaveLength(160);++ // Saturated deltas must not re-emit (regression: the advancing+ // lastActivityAt used to defeat the snapshot dedup on every delta).+ const saturated = childUpdates.length;+ const lastActivityBefore = run.lastActivityAt;+ for (let index = 0; index < 3; index += 1) {+ await new Promise((resolve) => setTimeout(resolve, 2));+ emitChild({+ type: "message_update",+ message: assistantMessage(`${saturatedText}${"x".repeat(index + 1)}`),+ });+ }+ expect(childUpdates.length).toBe(saturated);++ // Staleness semantics survive: streaming still counts as activity.+ expect(run.lastActivityAt).toBeGreaterThan(lastActivityBefore ?? 0);+ const streamedSnapshot = session+ .getRlmChildSnapshots()+ .find((candidate) => candidate.id === handle.rlm_child_id);+ expect(streamedSnapshot?.activityStaleMs).toBeUndefined();++ // Real activity still emits: a changed preview, then a tool call.+ const changed = childUpdates.length;+ emitChild({ type: "message_update", message: assistantMessage(`changed ${saturatedText}`) });+ await waitFor(() => childUpdates.length > changed);+ expect(childUpdates.at(-1)?.preview).toContain("changed");++ const beforeTool = childUpdates.length;+ emitChild({ type: "tool_execution_start", toolCallId: "tool-1", toolName: "ipython", args: {} });+ await waitFor(() => childUpdates.length > beforeTool);+ expect(childUpdates.at(-1)?.activityKind).toBe("executing");+ expect(childUpdates.at(-1)?.activityToolName).toBe("ipython");+ } finally {+ held.complete("child answer");+ await waitFor(+ () => session!.getRlmChildSnapshots().every((candidate) => candidate.status !== "running"),+ 20_000,+ );+ }+ });++ it("carries live extras for externally restored retained children", async () => {+ session = makeSession();+ const childId = "restored-child";+ const child = makeSession(undefined, join(tempDir, "restored-child-sessions"));+ child.setSessionName("restored-worker");+ const restoredAnswer = assistantMessage("restored answer");+ restoredAnswer.content.push({ type: "toolCall", id: "tool-1", name: "ipython", arguments: {} });+ child.agent.state.messages.push(restoredAnswer);++ expect(session.registerRlmChildSession(childId, child)).toBe(true);+ const roster = await session.listRlmSubagents();+ const entry = roster.subagents.find((candidate) => candidate.rlm_child_id === childId);+ expect(entry?.answer_preview).toBe("restored answer");+ expect(entry?.tool_use_count).toBe(1);+ expect(entry?.label).toBe("restored-worker");+ expect(entry?.progress_note).toBeUndefined();+ expect(entry?.activity_stale_ms).toBeUndefined();+ child.dispose();+ });+});diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 05dc6ca4ce..ec62243a10 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -40,6 +40,12 @@ class RLMModel:selector: str+@dataclass(frozen=True)+class RLMSubagentActivity:+ kind: str+ tool_name: str | None = None++@dataclass(frozen=True)class RLMSubagent:rlm_child_id: str@@ -48,6 +54,21 @@ class RLMSubagent:session_name: strsession_dir: Pathstatus: str+ activity: RLMSubagentActivity | None = None+ tool_use_count: int | None = None+ duration_ms: int | None = None+ answer_preview: str | None = None+ replied_since_task: bool | None = None+ progress_note: str | None = None+ label: str | None = None+ last_activity_at: float | None = None+ activity_stale_ms: float | None = None+++@dataclass(frozen=True)+class RLMProgressNoteResult:+ accepted: bool+ retry_after_ms: int | None = None@dataclass(frozen=True)@@ -215,6 +236,48 @@ async def find_models(query: str = "", limit: int = 8) -> list[RLMModel]:return [_model_from_payload(model) for model in models]+def _optional_str_field(payload: dict[str, Any], field: str, operation: str) -> str | None:+ value = payload.get(field)+ if value is None:+ return None+ if not isinstance(value, str):+ raise RuntimeError(f"{operation} entry has invalid {field}")+ return value+++def _optional_int_field(payload: dict[str, Any], field: str, operation: str) -> int | None:+ value = payload.get(field)+ if value is None:+ return None+ if not isinstance(value, int) or isinstance(value, bool):+ raise RuntimeError(f"{operation} entry has invalid {field}")+ return value+++def _optional_bool_field(payload: dict[str, Any], field: str, operation: str) -> bool | None:+ value = payload.get(field)+ if value is None:+ return None+ if not isinstance(value, bool):+ raise RuntimeError(f"{operation} entry has invalid {field}")+ return value+++def _optional_activity_field(payload: dict[str, Any], operation: str) -> RLMSubagentActivity | None:+ value = payload.get("activity")+ if value is None:+ return None+ if not isinstance(value, dict):+ raise RuntimeError(f"{operation} entry has invalid activity")+ kind = value.get("kind")+ if kind not in {"waiting", "writing", "executing"}:+ raise RuntimeError(f"{operation} entry has invalid activity kind")+ tool_name = value.get("tool_name")+ if tool_name is not None and not isinstance(tool_name, str):+ raise RuntimeError(f"{operation} entry has invalid activity tool_name")+ return RLMSubagentActivity(kind=kind, tool_name=tool_name)++def _subagent_from_payload(payload: Any, operation: str = "rlm.list_subagents") -> RLMSubagent:if not isinstance(payload, dict):raise RuntimeError(f"{operation} returned an invalid subagent entry")@@ -243,6 +306,15 @@ def _subagent_from_payload(payload: Any, operation: str = "rlm.list_subagents")session_name=session_name,session_dir=Path(session_dir),status=status,+ activity=_optional_activity_field(payload, operation),+ tool_use_count=_optional_int_field(payload, "tool_use_count", operation),+ duration_ms=_optional_int_field(payload, "duration_ms", operation),+ answer_preview=_optional_str_field(payload, "answer_preview", operation),+ replied_since_task=_optional_bool_field(payload, "replied_since_task", operation),+ progress_note=_optional_str_field(payload, "progress_note", operation),+ label=_optional_str_field(payload, "label", operation),+ last_activity_at=_optional_int_field(payload, "last_activity_at", operation),+ activity_stale_ms=_optional_int_field(payload, "activity_stale_ms", operation),)@@ -352,6 +424,38 @@ async def collect(return [_child_result_from_payload(entry) for entry in results]+RLM_PROGRESS_NOTE_MAX_LENGTH = 512+++async def progress_note(message: str) -> RLMProgressNoteResult:+ """Report brief in-flight progress to the parent orchestrator.++ The note (at most 512 UTF-16 code units, about one per 10 seconds) reaches the+ parent's child snapshots and roster entries without steering the parent+ or requiring an explicit reply. A throttled note returns+ ``accepted=False`` with a ``retry_after_ms`` hint instead of raising.+ """+ if not isinstance(message, str):+ raise TypeError(f"message must be str, got {type(message).__name__}")+ stripped = message.strip()+ if not stripped:+ raise ValueError("message must not be empty")+ # The host measures message.length in UTF-16 code units, so 512 astral+ # characters are 1024 units there and would fail its check after Python+ # accepted them. Measure the stripped message the same way; surrogatepass+ # counts a lone surrogate as one unit, matching the host's length.+ if len(stripped.encode("utf-16-le", "surrogatepass")) // 2 > RLM_PROGRESS_NOTE_MAX_LENGTH:+ raise ValueError(f"message must be at most {RLM_PROGRESS_NOTE_MAX_LENGTH} characters")+ payload = await host_request("rlm.progress.note", {"message": stripped})+ accepted = payload.get("accepted")+ if not isinstance(accepted, bool):+ raise RuntimeError("rlm.progress.note returned an invalid accepted flag")+ retry_after_ms = payload.get("retry_after_ms")+ if retry_after_ms is not None and (not isinstance(retry_after_ms, int) or isinstance(retry_after_ms, bool)):+ raise RuntimeError("rlm.progress.note returned an invalid retry_after_ms")+ return RLMProgressNoteResult(accepted=accepted, retry_after_ms=retry_after_ms)++async def delete_subagent(target: str | RLMSubagent | RLMSpawnHandle) -> RLMSubagent:"""Delete one running or retained direct child from the current parent session.@@ -453,6 +557,9 @@ class _RLMNamespace:async def list_subagents(self) -> list[RLMSubagent]:return await list_subagents()+ async def progress_note(self, message: str) -> RLMProgressNoteResult:+ return await progress_note(message)+async def delete_subagent(self, target: str | RLMSubagent | RLMSpawnHandle) -> RLMSubagent:return await delete_subagent(target)@@ -491,8 +598,10 @@ __all__ = ["NotEnabled","RLMCreateSessionHandle","RLMModel",+ "RLMProgressNoteResult","RLMSpawnHandle","RLMSubagent",+ "RLMSubagentActivity","create_session","RefinementEvent","bash",@@ -503,6 +612,7 @@ __all__ = ["harness","host_request","list_subagents",+ "progress_note","rlm","spawn",]diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.pyindex 66d93c93fe..e1553d794e 100644--- a/prime-agent-runtime/test/test_subagent_registry.py+++ b/prime-agent-runtime/test/test_subagent_registry.py@@ -264,6 +264,174 @@ class RlmSubagentRegistryTest(unittest.TestCase):asyncio.run(rlm_module.list_subagents())+class RlmProgressNoteTest(unittest.TestCase):+ def test_progress_note_round_trips_an_accepted_note(self) -> None:+ host_request = AsyncMock(return_value={"accepted": True})++ with patch.object(rlm_module, "host_request", host_request):+ result = asyncio.run(rlm_module.rlm.progress_note("building tests"))++ self.assertTrue(result.accepted)+ self.assertIsNone(result.retry_after_ms)+ host_request.assert_awaited_once_with("rlm.progress.note", {"message": "building tests"})++ def test_progress_note_returns_the_throttle_hint(self) -> None:+ host_request = AsyncMock(return_value={"accepted": False, "retry_after_ms": 7000})++ with patch.object(rlm_module, "host_request", host_request):+ result = asyncio.run(rlm_module.rlm.progress_note("second note"))++ self.assertFalse(result.accepted)+ self.assertEqual(result.retry_after_ms, 7000)++ def test_progress_note_validates_the_message(self) -> None:+ with self.assertRaisesRegex(TypeError, "message must be str"):+ asyncio.run(rlm_module.rlm.progress_note(42))+ with self.assertRaisesRegex(ValueError, "empty"):+ asyncio.run(rlm_module.rlm.progress_note(" "))+ with self.assertRaisesRegex(ValueError, "at most 512"):+ asyncio.run(rlm_module.rlm.progress_note("x" * 513))+ # At the bound the message is accepted.+ host_request = AsyncMock(return_value={"accepted": True})+ with patch.object(rlm_module, "host_request", host_request):+ result = asyncio.run(rlm_module.rlm.progress_note("x" * 512))+ self.assertTrue(result.accepted)++ def test_progress_note_measures_utf16_length_at_the_boundary(self) -> None:+ # 512 astral characters are 1024 UTF-16 code units under the host's+ # message.length measure, so they must fail validation before the call.+ with self.assertRaisesRegex(ValueError, "at most 512"):+ asyncio.run(rlm_module.rlm.progress_note("🎉" * 512))+ # A BMP character plus one astral character crosses the same bound.+ with self.assertRaisesRegex(ValueError, "at most 512"):+ asyncio.run(rlm_module.rlm.progress_note("a" * 511 + "🎉"))++ # 256 astral characters are exactly 512 UTF-16 code units: accepted.+ host_request = AsyncMock(return_value={"accepted": True})+ with patch.object(rlm_module, "host_request", host_request):+ result = asyncio.run(rlm_module.rlm.progress_note("🎉" * 256))++ self.assertTrue(result.accepted)+ host_request.assert_awaited_once_with("rlm.progress.note", {"message": "🎉" * 256})++ # Lone surrogates are valid Python strings that json.dumps escapes and+ # the host accepts, so each must count as one UTF-16 code unit, not raise.+ host_request = AsyncMock(return_value={"accepted": True})+ with patch.object(rlm_module, "host_request", host_request):+ result = asyncio.run(rlm_module.rlm.progress_note("\ud800"))+ self.assertTrue(result.accepted)+ host_request.assert_awaited_once_with("rlm.progress.note", {"message": "\ud800"})+ with self.assertRaisesRegex(ValueError, "at most 512"):+ asyncio.run(rlm_module.rlm.progress_note("\ud800" * 513))++ def test_progress_note_rejects_invalid_payloads(self) -> None:+ host_request = AsyncMock(return_value={"retry_after_ms": 1000})+ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, "accepted"):+ asyncio.run(rlm_module.rlm.progress_note("note"))++ host_request = AsyncMock(return_value={"accepted": True, "retry_after_ms": "soon"})+ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, "retry_after_ms"):+ asyncio.run(rlm_module.rlm.progress_note("note"))+++class RlmSubagentExtrasTest(unittest.TestCase):+ def test_lists_live_state_extras_from_host(self) -> None:+ host_request = AsyncMock(+ return_value={+ "subagents": [+ {+ "rlm_child_id": "sub-a1b2c3d4",+ "active_session_id": None,+ "session_id": "session-child",+ "session_name": "worker-a",+ "session_dir": "/tmp/parent/sub-a1b2c3d4",+ "status": "running",+ "activity": {"kind": "executing", "tool_name": "ipython"},+ "tool_use_count": 3,+ "duration_ms": 4321,+ "answer_preview": "task finished cleanly",+ "replied_since_task": False,+ "progress_note": "halfway done",+ "label": "slow task",+ "last_activity_at": 1757700000000,+ "activity_stale_ms": None,+ }+ ]+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ subagents = asyncio.run(rlm_module.list_subagents())++ self.assertEqual(len(subagents), 1)+ entry = subagents[0]+ self.assertEqual(entry.activity.kind, "executing")+ self.assertEqual(entry.activity.tool_name, "ipython")+ self.assertEqual(entry.tool_use_count, 3)+ self.assertEqual(entry.duration_ms, 4321)+ self.assertEqual(entry.answer_preview, "task finished cleanly")+ self.assertFalse(entry.replied_since_task)+ self.assertEqual(entry.progress_note, "halfway done")+ self.assertEqual(entry.label, "slow task")+ self.assertEqual(entry.last_activity_at, 1757700000000)+ self.assertIsNone(entry.activity_stale_ms)++ def test_accepts_entries_missing_optional_extras(self) -> None:+ host_request = AsyncMock(+ return_value={+ "subagents": [+ {+ "rlm_child_id": "sub-old",+ "active_session_id": None,+ "session_id": None,+ "session_name": "worker-old",+ "session_dir": "/tmp/parent/sub-old",+ "status": "completed",+ }+ ]+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ subagents = asyncio.run(rlm_module.list_subagents())++ entry = subagents[0]+ self.assertIsNone(entry.activity)+ self.assertIsNone(entry.tool_use_count)+ self.assertIsNone(entry.duration_ms)+ self.assertIsNone(entry.answer_preview)+ self.assertIsNone(entry.replied_since_task)+ self.assertIsNone(entry.progress_note)+ self.assertIsNone(entry.label)+ self.assertIsNone(entry.last_activity_at)+ self.assertIsNone(entry.activity_stale_ms)++ def test_rejects_invalid_extras(self) -> None:+ base_entry = {+ "rlm_child_id": "sub-x",+ "active_session_id": None,+ "session_id": None,+ "session_name": "worker-x",+ "session_dir": "/tmp/parent/sub-x",+ "status": "running",+ }+ for extras, pattern in (+ ({"activity": {"kind": "nonsense"}}, "invalid activity kind"),+ ({"activity": {"kind": "executing", "tool_name": 7}}, "invalid activity tool_name"),+ ({"tool_use_count": "three"}, "invalid tool_use_count"),+ ({"replied_since_task": "no"}, "invalid replied_since_task"),+ ({"progress_note": 42}, "invalid progress_note"),+ ({"last_activity_at": "soon"}, "invalid last_activity_at"),+ ):+ with self.subTest(extras=extras):+ host_request = AsyncMock(return_value={"subagents": [{**base_entry, **extras}]})+ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, pattern):+ asyncio.run(rlm_module.list_subagents())++if __name__ == "__main__":unittest.main()