A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Add experimental System 1 and System 2 Decision API control loop (#3350)
Arian Urdu56408e2a83af
diff --git a/README.md b/README.mdindex 7f306dbcae..e18b286b9d 100644--- a/README.md+++ b/README.md@@ -98,6 +98,11 @@ prime-agent update [--force] # Update Prime Agentprime-agent shutdown [--force] # Stop every agent, worker, and background service```+The experimental Decision API (the `decisionApi.systemOneModel` setting)+drives a decision model for real-time control tasks. See+[Decision API setup and smoke checks](docs/decision-api.md) for the setting+and verification in the persistent Python REPL.+## Built for Long-Running WorkPrime Agent is built for long-running work, especially for evaluations in research. These features are available in the TUI, and when run autonomously.diff --git a/crates/pa-ai/README.md b/crates/pa-ai/README.mdindex d16a1ff9f8..9c6565ba6b 100644--- a/crates/pa-ai/README.md+++ b/crates/pa-ai/README.md@@ -3,7 +3,7 @@Provider APIs and model registry.## Scope-Provider trait + per-provider streaming clients (anthropic, openai-completions/responses, google, bedrock, mistral, azure, prime-inference), model registry/resolution, usage accounting, stream-failure retry, provider-error shapes (per-SDK user-facing texts, diagnostic error names, connection-error profiles), bedrock transport selection (h2c prior-knowledge HTTP/2 cleartext, h2-preferred TLS ALPN, the http1 AWS_BEDROCK_FORCE_HTTP1/proxy mode), overflow handling, JSON repair parsing, faux provider for tests.+Provider trait + per-provider streaming clients (anthropic, openai-completions/responses, google, bedrock, mistral, azure, prime-inference, and the System One structured-decision protocol "systemone"), model registry/resolution, usage accounting, stream-failure retry, provider-error shapes (per-SDK user-facing texts, diagnostic error names, connection-error profiles), bedrock transport selection (h2c prior-knowledge HTTP/2 cleartext, h2-preferred TLS ALPN, the http1 AWS_BEDROCK_FORCE_HTTP1/proxy mode), overflow handling, JSON repair parsing, faux provider for tests.## Non-goalsNo agent loop, no tool execution, no session state, no UI. Receives/returns `pa-types` messages.diff --git a/crates/pa-ai/src/providers/mod.rs b/crates/pa-ai/src/providers/mod.rsindex bf92f4f716..6a0215869a 100644--- a/crates/pa-ai/src/providers/mod.rs+++ b/crates/pa-ai/src/providers/mod.rs@@ -16,4 +16,5 @@ pub mod openai_responses_hooks;pub mod openai_responses_shared;pub mod openai_responses_stream;pub mod simple_options;+pub mod systemone;pub mod transform_messages;diff --git a/crates/pa-ai/src/providers/systemone.rs b/crates/pa-ai/src/providers/systemone.rsnew file mode 100644index 0000000000..1a34b491ae--- /dev/null+++ b/crates/pa-ai/src/providers/systemone.rs@@ -0,0 +1,379 @@+//! The System One structured-decision protocol (Prime Inference's+//! `/api/v1/systemone` endpoint, the hosted port of the old `TypeSafe`+//! endpoint): the decision request body POSTs to the model's `baseUrl` ++//! `/systemone` with the merged request auth, and the reply envelope+//! (`model` + `answers`) becomes the assistant text. The host (pa-core)+//! owns the request and response policy; this is one registered transport+//! among the provider set, not a bespoke client.+//!+//! The body rides verbatim, so the protocol's full contract holds: one+//! state plus a schema of typed questions, answered with a probability for+//! every allowed option of every question in a single forward pass (the+//! clef model card's joint schema head). The host currently composes the+//! single `action` question; a multi-question schema passes through+//! unchanged.++use crate::event_stream::{+ create_assistant_message_event_stream, AssistantMessageEventStream, AssistantMessageEventWriter,+};+use crate::types::{Context, Model, SimpleStreamOptions, StreamOptions};+use crate::Provider;+use pa_types::ai::{AssistantContentBlock, AssistantMessage, StopReason, TextContent, Usage};+use serde_json::Value;++/// One request round-trip's wall-clock bound when the caller sets none.+const DEFAULT_TIMEOUT_MS: u64 = 30_000;+/// The error body's bounded excerpt.+const ERROR_BODY_CHARS: usize = 500;++pub struct SystemOneProvider;++impl Provider for SystemOneProvider {+ fn api(&self) -> &'static str {+ "systemone"+ }++ fn stream(+ &self,+ model: &Model,+ context: &Context,+ options: Option<&StreamOptions>,+ ) -> AssistantMessageEventStream {+ let (writer, reader) = create_assistant_message_event_stream();+ let model = model.clone();+ let request = systemone_request_body(context);+ let options = options.cloned();+ tokio::spawn(async move {+ serve_systemone(&writer, &model, request, options.as_ref()).await;+ });+ reader+ }++ fn stream_simple(+ &self,+ model: &Model,+ context: &Context,+ options: Option<&SimpleStreamOptions>,+ ) -> AssistantMessageEventStream {+ self.stream(model, context, options.map(|options| &options.base))+ }+}++/// The decision request body: the newest user message's JSON text.+fn systemone_request_body(context: &Context) -> Value {+ context+ .messages+ .iter()+ .rev()+ .find_map(|message| match message {+ pa_types::ai::Message::User(user) => {+ let text = user.content.text();+ serde_json::from_str::<Value>(&text).ok()+ }+ _ => None,+ })+ .unwrap_or(Value::Null)+}++/// One POST to the systemone endpoint; the reply envelope (or the surfaced+/// HTTP error) ends the stream as the final assistant message.+async fn serve_systemone(+ writer: &AssistantMessageEventWriter,+ model: &Model,+ request: Value,+ options: Option<&StreamOptions>,+) {+ let timeout_ms = options+ .and_then(|options| options.timeout_ms)+ .unwrap_or(DEFAULT_TIMEOUT_MS);+ let mut headers = reqwest::header::HeaderMap::new();+ headers.insert(+ reqwest::header::CONTENT_TYPE,+ "application/json".parse().unwrap(),+ );+ if let Some(api_key) = options.and_then(|options| options.api_key.as_deref()) {+ if let Ok(value) = reqwest::header::HeaderValue::from_str(&format!("Bearer {api_key}")) {+ headers.insert(reqwest::header::AUTHORIZATION, value);+ }+ }+ for (name, value) in options+ .and_then(|options| options.headers.as_ref())+ .into_iter()+ .flatten()+ {+ if let (Ok(name), Ok(value)) = (+ reqwest::header::HeaderName::from_bytes(name.as_bytes()),+ reqwest::header::HeaderValue::from_str(value),+ ) {+ headers.insert(name, value);+ }+ }+ let url = format!("{}/systemone", model.base_url.trim_end_matches('/'));+ let client = reqwest::Client::builder()+ .timeout(std::time::Duration::from_millis(timeout_ms))+ .default_headers(headers)+ .build()+ .expect("systemone client builds");+ let response = client.post(&url).json(&request).send().await;+ let message = match response {+ Ok(response) => {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ if status.is_success() {+ envelope_message(model, body)+ } else {+ let detail: String = body.chars().take(ERROR_BODY_CHARS).collect();+ error_message(+ model,+ &format!("systemone returned HTTP {status}: {detail}"),+ )+ }+ }+ Err(error) => error_message(model, &format!("the systemone request failed: {error}")),+ };+ writer.end(Some(message));+}++/// The reply envelope as the final assistant message.+fn envelope_message(model: &Model, body: String) -> AssistantMessage {+ let mut message =+ crate::event_stream::initial_assistant_message("systemone", &model.provider, &model.id);+ message+ .content+ .push(AssistantContentBlock::Text(TextContent {+ text: body,+ text_signature: None,+ rest: serde_json::Map::default(),+ }));+ message.usage = Usage::default();+ message+}++/// The surfaced transport error as the final assistant message.+fn error_message(model: &Model, error: &str) -> AssistantMessage {+ let mut message =+ crate::event_stream::initial_assistant_message("systemone", &model.provider, &model.id);+ message.stop_reason = StopReason::Error;+ message.error_message = Some(error.to_string());+ message+}++#[cfg(test)]+mod tests {+ use super::*;+ use pa_types::ai::{Message, UserContent, UserMessage};+ use serde_json::json;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ /// One request the loopback server received.+ #[derive(Debug, Clone)]+ struct Seen {+ path: String,+ authorization: Option<String>,+ team: Option<String>,+ body: Value,+ }++ /// A loopback server answering POST `<base>/systemone`.+ async fn serve(+ status: u16,+ reply: Value,+ seen: std::sync::Arc<std::sync::Mutex<Vec<Seen>>>,+ ) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move {+ while let Ok((mut socket, _)) = listener.accept().await {+ let mut raw = Vec::new();+ let mut chunk = [0u8; 4096];+ let (head, body) = loop {+ let read = socket.read(&mut chunk).await.unwrap();+ assert_ne!(read, 0, "the client closed mid-request");+ raw.extend_from_slice(&chunk[..read]);+ let text = String::from_utf8_lossy(&raw).to_string();+ let Some((head, body)) = text.split_once("\r\n\r\n") else {+ continue;+ };+ let length = head+ .lines()+ .find_map(|line| {+ let line = line.to_ascii_lowercase();+ line.strip_prefix("content-length:")?.trim().parse().ok()+ })+ .unwrap_or(0);+ if body.len() >= length {+ break (head.to_string(), body.to_string());+ }+ };+ let path = head+ .lines()+ .next()+ .unwrap_or_default()+ .split(' ')+ .nth(1)+ .unwrap_or_default()+ .to_string();+ let authorization = head.lines().find_map(|line| {+ let line = line.to_ascii_lowercase();+ line.strip_prefix("authorization:")+ .map(|value| value.trim().to_string())+ });+ let team = head.lines().find_map(|line| {+ let line = line.to_ascii_lowercase();+ line.strip_prefix("x-prime-team-id:")+ .map(|value| value.trim().to_string())+ });+ seen.lock().unwrap().push(Seen {+ path,+ authorization,+ team,+ body: serde_json::from_str(&body).unwrap_or(Value::Null),+ });+ let reply = reply.to_string();+ let response = format!(+ "HTTP/1.1 {status} Status\r\ncontent-type: application/json\r\n\+ content-length: {}\r\nconnection: close\r\n\r\n{reply}",+ reply.len()+ );+ socket.write_all(response.as_bytes()).await.unwrap();+ }+ });+ base+ }++ fn fixture_model(base_url: &str) -> Model {+ serde_json::from_value(json!({+ "id": "cloudflare/clef", "name": "clef", "api": "systemone",+ "provider": "prime-inference", "baseUrl": base_url, "reasoning": false,+ "input": ["text", "image"],+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },+ "contextWindow": 100_000, "maxTokens": 8192,+ }))+ .unwrap()+ }++ fn decision_context(request: &Value) -> Context {+ Context {+ system_prompt: None,+ messages: vec![Message::User(UserMessage {+ content: UserContent::Text(request.to_string()),+ timestamp: 0,+ rest: serde_json::Map::default(),+ })],+ tools: None,+ }+ }++ #[tokio::test]+ async fn posts_the_request_to_the_systemone_path_with_the_merged_auth() {+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let envelope = json!({+ "model": "cloudflare/clef",+ "answers": {"action": {"choice": "left", "confidence": 0.9, "probabilities": {"left": 0.9}}}+ });+ let base = serve(200, envelope.clone(), std::sync::Arc::clone(&seen)).await;+ let model = fixture_model(&base);+ let request = json!({+ "state": {"observation": {"x": 1}},+ "questions": {"action": {"type": "choice", "criteria": {"left": "go left"}}},+ "model": "cloudflare/clef"+ });+ let stream = SystemOneProvider.stream(+ &model,+ &decision_context(&request),+ Some(&StreamOptions {+ api_key: Some("test-key".to_string()),+ headers: Some(+ [("X-Prime-Team-ID".to_string(), "team-1".to_string())]+ .into_iter()+ .collect(),+ ),+ timeout_ms: Some(5_000),+ ..Default::default()+ }),+ );+ let message = stream.result().await;+ assert_eq!(message.stop_reason, StopReason::Stop);+ let text = message+ .content+ .iter()+ .map(|block| match block {+ AssistantContentBlock::Text(text) => text.text.clone(),+ _ => String::new(),+ })+ .collect::<String>();+ assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), envelope);+ let requests = seen.lock().unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(requests[0].path, "/systemone");+ assert_eq!(+ requests[0].authorization.as_deref(),+ Some("bearer test-key"),+ "the merged key rides the bearer header"+ );+ assert_eq!(+ requests[0].team.as_deref(),+ Some("team-1"),+ "the merged team header rides the request"+ );+ assert_eq!(+ requests[0].body, request,+ "the decision body rides verbatim"+ );+ }++ /// Clef's contract (the model card's joint schema head): one state+ /// plus a schema of typed questions, answered per question in one pass.+ /// The transport rides the schema verbatim; the host composes one+ /// question today.+ #[tokio::test]+ async fn a_multi_question_schema_rides_verbatim_and_answers_per_question() {+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let envelope = json!({+ "model": "cloudflare/clef",+ "answers": {+ "action": {"type": "choice", "choice": "left", "confidence": 0.9, "probabilities": {"left": 0.9, "right": 0.1}},+ "speed": {"type": "choice", "choice": "fast", "confidence": 0.6, "probabilities": {"fast": 0.6, "slow": 0.4}}+ }+ });+ let base = serve(200, envelope.clone(), std::sync::Arc::clone(&seen)).await;+ let model = fixture_model(&base);+ let request = json!({+ "state": {"frame": 1},+ "questions": {+ "action": {"type": "choice", "criteria": {"left": "go left", "right": "go right"}},+ "speed": {"type": "choice", "criteria": {"fast": "run", "slow": "crawl"}}+ },+ "model": "cloudflare/clef"+ });+ let stream = SystemOneProvider.stream(&model, &decision_context(&request), None);+ let message = stream.result().await;+ assert_eq!(message.stop_reason, StopReason::Stop);+ let requests = seen.lock().unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(requests[0].body, request, "the schema rides verbatim");+ let text = message+ .content+ .iter()+ .map(|block| match block {+ AssistantContentBlock::Text(text) => text.text.clone(),+ _ => String::new(),+ })+ .collect::<String>();+ assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), envelope);+ }++ #[tokio::test]+ async fn http_errors_surface_as_the_error_stop_reason() {+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let base = serve(404, json!({"error": "no such model"}), seen).await;+ let model = fixture_model(&base);+ let stream =+ SystemOneProvider.stream(&model, &decision_context(&json!({"state": {}})), None);+ let message = stream.result().await;+ assert_eq!(message.stop_reason, StopReason::Error);+ let error = message.error_message.unwrap();+ assert!(error.contains("HTTP 404"), "{error}");+ assert!(error.contains("no such model"), "{error}");+ }+}diff --git a/crates/pa-ai/src/registry.rs b/crates/pa-ai/src/registry.rsindex 9f6c33c302..83825ad9d4 100644--- a/crates/pa-ai/src/registry.rs+++ b/crates/pa-ai/src/registry.rs@@ -119,6 +119,7 @@ pub fn register_builtin_api_providers() {Arc::new(crate::providers::mistral::MistralConversationsProvider),Arc::new(crate::providers::bedrock::BedrockConverseStreamProvider),Arc::new(crate::providers::openai_codex_responses::OpenAICodexResponsesProvider),+ Arc::new(crate::providers::systemone::SystemOneProvider),];for provider in builtins {registry.insert(diff --git a/crates/pa-cli/src/prompt_command.rs b/crates/pa-cli/src/prompt_command.rsindex ffe4d7019c..3a5bf2ecaa 100644--- a/crates/pa-cli/src/prompt_command.rs+++ b/crates/pa-cli/src/prompt_command.rs@@ -99,11 +99,21 @@ fn assemble_breakdown(.collect::<std::collections::HashMap<String, pa_core::mcp::McpServerConfig>>();let (skill_overrides, generic_servers, _manager) =pa_core::mcp::McpManager::prompt_gating(user_servers, &agent_dir);- let resources = load_resources(ResourceLoaderOptions {+ // The decision-api skill rides the prompt only while the Decision API is+ // configured (decisionApi.systemOneModel is set).+ let decision_api_configured = pa_core::session_engine::decision_api::decision_api_configured(+ pa_core::settings::SettingsManager::create(cwd, &agent_dir).settings(),+ );+ let mut resources = load_resources(ResourceLoaderOptions {extra_builtin_skill_overrides: skill_overrides,system_prompt: None,..ResourceLoaderOptions::new(cwd.to_path_buf(), agent_dir)})?;+ if !decision_api_configured {+ resources.skills.retain(|skill| {+ skill.name != pa_core::session_engine::decision_api::DECISION_API_SKILL_NAME+ });+ }let breakdown = pa_core::prompts::system_prompt::system_prompt_breakdown(&pa_core::prompts::BuildSystemPromptOptions {cwd: cwd.display().to_string(),diff --git a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rsindex a224bb6a9d..e9ee37375b 100644--- a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs+++ b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs@@ -226,6 +226,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}}diff --git a/crates/pa-core/README.md b/crates/pa-core/README.mdindex 5b3d0d8d01..13287a8af7 100644--- a/crates/pa-core/README.md+++ b/crates/pa-core/README.md@@ -74,7 +74,48 @@ only: nothing wires it to a user-facing cloud toggle yet.No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-daemon), no TUI (pa-tui). No update coordination (the pa-cli coordinator owns the FSM; the update-flow seam here is the daemon-free support layer: `update::version` (semver/channel policy), `update::install` (the managed install-root layout), `update::release` (the channel manifest fetch), `update::download` (sha256-verified archive download + staging)). The package manager installs sources and resolves resource paths only. No workspace snapshot upload, transport, or remote materialization (staging and verification live here; the cloud attach surface owns the transport when it ships).## Public API-`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `session_engine::semantic_edges` (the TS `semantic-edges.ts` WRITER: `SemanticEdgeRecorder`/`SemanticEdgeIdentity`, `semantic_edge_ledger_path` + `last_committed_request_id`, and the `X-ACP-Model-Request-ID`/`Idempotency-Key` constants — one durable per-session ledger of model-request events, byte-compatible with the TS lines; the fold and any publishing stay downstream), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill_use_count` session counter counts at the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).+`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `session_engine::semantic_edges` (the TS `semantic-edges.ts` WRITER: `SemanticEdgeRecorder`/`SemanticEdgeIdentity`, `semantic_edge_ledger_path` + `last_committed_request_id`, and the `X-ACP-Model-Request-ID`/`Idempotency-Key` constants — one durable per-session ledger of model-request events, byte-compatible with the TS lines; the fold and any publishing stay downstream), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::decision_api::DECISION_API_SKILL_NAME` (the bundled gated skill name consumed by CLI prompt inspection) and `SessionEngine::{system_prompt, sync_decision_api_from_session}` (the prompt/status facade; shared switch and policy internals stay crate-internal). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous`/`/decision-api` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill_use_count` session counter counts at the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).++## Decision API ownership and public seams++The session engine owns activation policy, durable selected-branch+configuration, prompt selection, and Python skill pre-import policy. Decision+requests ride the ordinary provider transports: the `decision_api.decide`+host handler resolves the `decisionApi.systemOneModel` settings reference+through the model registry (`find_exact_model_reference_match` ++`get_api_key_and_headers`) and runs one completion against the resolved+model, so the Decision API keeps no transport, envelope, or credential store+of its own. Construction restores persisted branch metadata before selecting+the initial prompt or prewarming the kernel. Hosts synchronize from the+selected session after branch moves; compaction and windowed loading do not+erase persisted activation metadata.++Necessary public seams:++- `SessionEngine::system_prompt()` replaces the former writable public string+ field with a read-only view of the currently selected prompt. CLI prompt+ inspection, daemon export, and RPC use it; mutation remains engine-owned.+- `SessionEngine::sync_decision_api_from_session()` lets daemon/RPC hosts+ adopt the selected branch's persisted configuration after a branch move.+- `DECISION_API_SKILL_NAME` names the gated bundled skill for the CLI prompt+ command as well as the engine. The status row type and its durable-details+ decoder are imported from pa-types directly, with no core re-export.+- `IpythonKernelProvisionerOptions::preimport_filter` is the public kernel+ boot configuration field: an optional `Arc<dyn Fn(&KernelPythonSkill) -> bool+ + Send + Sync>` predicate evaluated each boot. Its type alias stays internal. Omitted means pre-import all skills;+ filtering does not uninstall packages. The engine uses it to gate the+ decision-api import while retaining ordinary skill installation.++These are new public APIs (the prompt accessor also changes an existing+API); the shared switch, host handler, and session policy implementation stay+crate-internal. Daemon snapshots read selected-branch persisted status without+exporting the switch; its inspection accessor is limited to core tests.+The former `AgentSession::restore_windowed_context` method is removed: hosts+adopt persisted metadata into the manager before engine construction, so the+initial prompt and kernel see the restored state immediately.+Dependency direction remains pa-core → pa-ai → pa-types. No session policy+moves into the shared vocabulary or transport crate. User setup and opt-in+live checks are documented in [the Decision API guide](../../docs/decision-api.md).## Depends onpa-types, pa-ai, pa-agent (one-way).diff --git a/crates/pa-core/src/auth/manager/lookup.rs b/crates/pa-core/src/auth/manager/lookup.rsindex 9e6f3157ac..3e4a2fdbdc 100644--- a/crates/pa-core/src/auth/manager/lookup.rs+++ b/crates/pa-core/src/auth/manager/lookup.rs@@ -9,6 +9,35 @@ use super::{};impl AuthStorage {+ /// Resolve a file-backed credential without blocking the async caller on+ /// disk locks, environment references, shell commands, or OAuth refresh.+ /// Empty resolved values are unavailable.+ ///+ /// # Errors+ /// Returns an error if storage cannot be read or parsed, or the blocking+ /// credential resolver cannot complete.+ #[tracing::instrument(skip_all)]+ pub async fn resolve_api_key(+ agent_dir: &std::path::Path,+ provider_id: &str,+ ) -> anyhow::Result<Option<String>> {+ let agent_dir = agent_dir.to_path_buf();+ let provider_id = provider_id.to_string();+ tokio::task::spawn_blocking(move || {+ let mut auth = Self::create(agent_dir);+ let key = auth+ .get_api_key(&provider_id)+ .filter(|key| !key.trim().is_empty());+ let errors = auth.drain_errors();+ if !errors.is_empty() {+ let detail = errors.join("; ");+ anyhow::bail!("Could not resolve API credentials: {detail}");+ }+ Ok(key)+ })+ .await?+ }+pub fn get_api_key_with_source_token(&mut self,provider_id: &str,diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rsindex 87ecc26a56..6c48587f6a 100644--- a/crates/pa-core/src/kernel/provisioner.rs+++ b/crates/pa-core/src/kernel/provisioner.rs@@ -100,6 +100,10 @@ pub struct KernelBootstrapStats {/// Reports kernel bootstrap results (the `kernel_bootstrap_*` session counters).pub type KernelBootstrapResultHandler = Arc<dyn Fn(KernelBootstrapStats) + Send + Sync>;+/// Decides at each kernel boot whether a Python skill is pre-imported; the+/// skill stays installed in the kernel venv either way.+pub(crate) type PythonSkillPreimportFilter = Arc<dyn Fn(&KernelPythonSkill) -> bool + Send + Sync>;+#[derive(Default, Clone)]pub struct IpythonKernelProvisionerOptions {/// Python override. Must have prime-agent-runtime installed.@@ -113,6 +117,8 @@ pub struct IpythonKernelProvisionerOptions {pub session_id: Option<String>,pub host_handlers: HostRequestHandlers,pub python_skills: Vec<KernelPythonSkill>,+ /// Narrows which `python_skills` a boot pre-imports (all when `None`).+ pub preimport_filter: Option<PythonSkillPreimportFilter>,/// Artifact directory of a persistent session; the revivable snapshot and/// the stderr log live there. `None` for ephemeral sessions.pub snapshot_dir: Option<PathBuf>,@@ -1035,7 +1041,18 @@ async fn start_kernel_impl(gate().await;}let snapshot_dir = options.snapshot_dir.clone();- let bootstrap_code = build_rlm_bootstrap_code(&options.python_skills);+ let preimported: Vec<KernelPythonSkill> = options+ .python_skills+ .iter()+ .filter(|skill| {+ options+ .preimport_filter+ .as_ref()+ .is_none_or(|preimport| preimport(skill))+ })+ .cloned()+ .collect();+ let bootstrap_code = build_rlm_bootstrap_code(&preimported);let mut env = options.env.clone();if let Some(shell_path) = &options.shell_path {env.insert(diff --git a/crates/pa-core/src/prompts/layers/core.md b/crates/pa-core/src/prompts/layers/core.mdindex 5b90cb5352..5efc0b5a66 100644--- a/crates/pa-core/src/prompts/layers/core.md+++ b/crates/pa-core/src/prompts/layers/core.md@@ -30,7 +30,7 @@ prime-agent is a recursive harness. Each session builds a tree of agents, startiThe following programmatic tools are available in the REPL for subagent management:-- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short+- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None, kind: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short; `kind` selects a dedicated child kind — `kind="decision"` spawns the Decision API child (the model comes from the `decisionApi.systemOneModel` setting and the child answers every message with one decision)- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handlesdiff --git a/crates/pa-core/src/session_engine/decision_api.rs b/crates/pa-core/src/session_engine/decision_api.rsnew file mode 100644index 0000000000..d3a5d47348--- /dev/null+++ b/crates/pa-core/src/session_engine/decision_api.rs@@ -0,0 +1,1098 @@+//! The experimental Decision API host: the `decision_api.decide` handler the+//! bundled decision-api skill calls, and the settings gate that controls the+//! skill's availability. The decision model is the `decisionApi.systemOneModel`+//! settings reference — resolved through the model registry exactly like+//! `imageModel` — and requests ride the ordinary provider transports, so the+//! Decision API has no transport, envelope, or credential store of its own.+//! The setting is the feature gate: unset (or unresolvable) and the skill+//! stays out of the prompt and every `decide()` refuses with an actionable+//! message naming the setting.++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++use anyhow::{anyhow, bail};+use pa_types::ai::{ModelInput, StopReason};+use serde_json::{json, Value};+use std::sync::Arc;++use crate::kernel::shared::{host_handler, HostRequestHandlers};+use crate::models::{find_exact_model_reference_match, ModelRegistry};++/// The bundled skill the setting gates.+pub const DECISION_API_SKILL_NAME: &str = "decision-api";+/// The default decision instructions (the skill's `DEFAULT_INSTRUCTIONS`).+const DEFAULT_INSTRUCTIONS: &str =+ "Choose the next action that best advances the goal given the observation.";+/// One decision's output budget: the answer is a single small JSON object.+const DECISION_MAX_TOKENS: u64 = 512;+/// One decision call's wall-clock bound.+const DECISION_TIMEOUT_MS: u64 = 30_000;+/// The request's image cap (the skill mirrors it client-side).+const MAX_IMAGES: usize = 4;++/// One parsed decision request: what System 1 is asked.+#[derive(Debug, Clone)]+struct DecisionRequest {+ state: Value,+ instructions: String,+ /// (action name, when it applies), in request order.+ criteria: Vec<(String, String)>,+ /// (mime type, base64 data) data-URL images, at most [`MAX_IMAGES`].+ images: Vec<(String, String)>,+}++/// Validate the kernel's request body into a [`DecisionRequest`].+fn parse_decision_request(+ mut request: serde_json::Map<String, Value>,+) -> anyhow::Result<DecisionRequest> {+ if let Some(model) = request.remove("model") {+ if !model.is_null() {+ bail!(+ "The decision model comes from the decisionApi.systemOneModel setting; the \+ request carries no model (got {model})."+ );+ }+ }+ let unknown: Vec<String> = request+ .keys()+ .filter(|key| !matches!(key.as_str(), "state" | "questions" | "images"))+ .cloned()+ .collect();+ if !unknown.is_empty() {+ bail!(+ "decision_api.decide got unsupported request fields: {}. Only \"state\", \+ \"questions\", and \"images\" are allowed.",+ unknown+ .iter()+ .map(|key| format!("{key:?}"))+ .collect::<Vec<_>>()+ .join(", ")+ );+ }+ let state = request+ .get("state")+ .cloned()+ .ok_or_else(|| anyhow!("decision_api.decide needs a \"state\" value"))?;+ let Some(question) = request+ .get("questions")+ .and_then(Value::as_object)+ .and_then(|questions| questions.get("action"))+ .cloned()+ else {+ bail!("decision_api.decide needs a \"questions\" object with an \"action\" question");+ };+ if let Some(kind) = question.get("type") {+ if kind != "choice" {+ bail!(+ "the \"action\" question must have type \"choice\", not {kind}. The Decision API \+ serves one action choice per request."+ );+ }+ }+ let instructions = match question.get("instructions") {+ None | Some(Value::Null) => DEFAULT_INSTRUCTIONS.to_string(),+ Some(Value::String(text)) => text.clone(),+ Some(other) => {+ bail!("the \"action\" question's instructions must be a string, not {other}.")+ }+ };+ let Some(criteria_value) = question.get("criteria").and_then(Value::as_object) else {+ bail!(+ "the \"action\" question needs a \"criteria\" object of action names to descriptions"+ );+ };+ if criteria_value.is_empty() {+ bail!("the \"action\" question's \"criteria\" object is empty; a decision needs actions to choose from");+ }+ let mut criteria = Vec::with_capacity(criteria_value.len());+ for (name, applies) in criteria_value {+ let Some(when) = applies.as_str() else {+ bail!("the \"criteria\" entry {name:?} must be a string describing when the action applies, not {applies}");+ };+ if name.is_empty() {+ bail!("the \"criteria\" object has an empty action name");+ }+ criteria.push((name.clone(), when.to_string()));+ }+ let mut images = Vec::new();+ match request.get("images") {+ None | Some(Value::Null) => {}+ Some(Value::Array(list)) => {+ if list.len() > MAX_IMAGES {+ bail!(+ "a decision carries at most {MAX_IMAGES} images, got {}",+ list.len()+ );+ }+ for image in list {+ let Some(url) = image.as_str() else {+ bail!("decision images must be data URL strings like \"data:image/png;base64,...\", got {image}");+ };+ images.push(parse_image_data_url(url)?);+ }+ }+ Some(other) => {+ bail!("decision \"images\" must be an array of data URL strings, not {other}.")+ }+ }+ Ok(DecisionRequest {+ state,+ instructions,+ criteria,+ images,+ })+}++/// Split one `data:<mime>;base64,<data>` URL into its parts.+fn parse_image_data_url(url: &str) -> anyhow::Result<(String, String)> {+ let invalid =+ || anyhow!("decision images must be data URL strings like \"data:image/png;base64,...\"");+ let (header, data) = url.split_once(',').ok_or_else(invalid)?;+ if !header.starts_with("data:image/") || !header.ends_with(";base64") {+ return Err(invalid());+ }+ let mime = header+ .strip_prefix("data:")+ .and_then(|rest| rest.strip_suffix(";base64"))+ .ok_or_else(invalid)?;+ if mime.is_empty() || data.is_empty() {+ return Err(invalid());+ }+ Ok((mime.to_string(), data.to_string()))+}++/// The actionable refusal when `decisionApi.systemOneModel` is unset.+fn unconfigured_message() -> String {+ "decisionApi.systemOneModel is not set in settings.json. Set it to the decision model \+ reference (\"provider/model-id\" or a bare id), e.g. \"prime-inference/clef\"."+ .to_string()+}++/// Whether the Decision API is configured: `decisionApi.systemOneModel` is+/// set to a non-empty reference. This gates the skill's prompt inclusion and+/// kernel pre-import; `decide()` resolves the reference at call time.+#[must_use]+pub fn decision_api_configured(settings: &crate::settings::types::Settings) -> bool {+ settings+ .decision_api+ .as_ref()+ .and_then(|decision| decision.system_one_model.as_deref())+ .is_some_and(|reference| !reference.trim().is_empty())+}++/// The pre-import filter that withholds the decision-api skill while it is+/// unconfigured; a configured gate pre-imports every skill.+#[must_use]+pub fn decision_api_preimport_filter(+ configured: bool,+) -> crate::kernel::provisioner::PythonSkillPreimportFilter {+ if configured {+ return Arc::new(|_| true);+ }+ Arc::new(|skill: &crate::kernel::bootstrap::KernelPythonSkill| {+ skill.name != DECISION_API_SKILL_NAME+ })+}++/// The actionable refusal when the configured reference does not resolve to+/// an available, authenticated model (the `imageModel` refusal shape).+fn unusable_message(reference: &str) -> String {+ format!(+ "decisionApi.systemOneModel \"{reference}\" could not be resolved to an available, \+ authenticated model.\n\nFix the decisionApi.systemOneModel setting (settings.json) or \+ authenticate the provider, then retry the decision."+ )+}++/// The resolved decision model with its request auth: the settings reference+/// resolved through the registry exactly like `imageModel` routing.+struct ResolvedDecisionModel {+ model: pa_types::ai::Model,+ api_key: Option<String>,+ headers: Option<BTreeMap<String, String>>,+}++impl ResolvedDecisionModel {+ /// The model's full selector, for prompts and status rows.+ fn label(&self) -> String {+ format!("{}/{}", self.model.provider, self.model.id)+ }+}++/// Resolve `decisionApi.systemOneModel` through the model registry:+/// the reference must match an available (authenticated) model, and its+/// request auth comes from the registry's merged resolution.+fn resolve_decision_model(cwd: &Path, agent_dir: &Path) -> Result<ResolvedDecisionModel, String> {+ let settings = crate::settings::SettingsManager::create(cwd, agent_dir);+ let reference = settings+ .settings()+ .decision_api+ .as_ref()+ .and_then(|decision| decision.system_one_model.clone())+ .and_then(|reference| {+ let trimmed = reference.trim().to_string();+ (!trimmed.is_empty()).then_some(trimmed)+ })+ .ok_or_else(unconfigured_message)?;+ let auth = crate::auth::AuthStorage::create(agent_dir);+ let mut registry = ModelRegistry::create(auth, agent_dir.join("models.json"));+ let available = registry.get_available();+ let available: Vec<pa_types::ai::Model> = available.into_iter().cloned().collect();+ let model = find_exact_model_reference_match(&reference, &available)+ .ok_or_else(|| unusable_message(&reference))?;+ let model = model.clone();+ let resolved = registry.get_api_key_and_headers(&model, None);+ if !resolved.ok {+ return Err(unusable_message(&reference));+ }+ Ok(ResolvedDecisionModel {+ model,+ api_key: resolved.api_key,+ headers: resolved.headers,+ })+}++/// The system prompt every decision request runs with: the answer protocol+/// (the skill material's decision contract).+const DECISION_SYSTEM_PROMPT: &str = "You are System 1, the decision model of a real-time control \+loop. Each request gives one situation (the state) and the actions available. Pick exactly one \+action and reply with a single JSON object, nothing else:\n\n{\"action\": {\"choice\": \+\"<one action name>\", \"confidence\": <number 0 to 1>, \"probabilities\": {\"<action name>\": \+<number>, ...}}}\n\n\"choice\" must be one of the request's action names. \"confidence\" is how \+confident you are that the choice is best. \"probabilities\" assigns a share to the action names. \+Reply with JSON only: no prose, no markdown, no code fences.";++/// The user half of one decision request.+fn decision_user_text(request: &DecisionRequest) -> String {+ use std::fmt::Write as _;+ let mut text = String::with_capacity(256);+ let _ = write!(text, "Instructions: {}", request.instructions);+ let _ = write!(text, "\n\nActions:");+ for (name, applies) in &request.criteria {+ let _ = write!(text, "\n- {name}: {applies}");+ }+ let state =+ serde_json::to_string_pretty(&request.state).unwrap_or_else(|_| request.state.to_string());+ let _ = write!(+ text,+ "\n\nState:\n{state}\n\nReply with one JSON object: {{\"action\": {{\"choice\": one \+ action name, \"confidence\": 0 to 1, \"probabilities\": {{action name: probability}}}}}}"+ );+ text+}++/// Build the completion context for one decision request: one user message+/// (text plus image blocks for vision-capable models).+fn build_decision_context(request: &DecisionRequest) -> pa_types::ai::Context {+ use pa_types::ai::{TextContent, UserMessage};+ let content = if request.images.is_empty() {+ pa_types::ai::UserContent::Text(decision_user_text(request))+ } else {+ let mut blocks = vec![pa_types::ai::UserContentBlock::Text(TextContent {+ text: decision_user_text(request),+ text_signature: None,+ rest: serde_json::Map::default(),+ })];+ for (mime, data) in &request.images {+ blocks.push(pa_types::ai::UserContentBlock::Image(+ pa_types::ai::ImageContent {+ data: data.clone(),+ mime_type: mime.clone(),+ rest: serde_json::Map::default(),+ },+ ));+ }+ pa_types::ai::UserContent::Blocks(blocks)+ };+ pa_types::ai::Context {+ system_prompt: Some(DECISION_SYSTEM_PROMPT.to_string()),+ messages: vec![pa_types::ai::Message::User(UserMessage {+ content,+ timestamp: 0,+ rest: serde_json::Map::default(),+ })],+ tools: None,+ }+}++/// Parse the model's reply into the `answers.action` object: the choice must+/// name one of the requested actions; confidence clamps to `0..=1`.+fn parse_decision_answer(reply: &str, criteria: &[(String, String)]) -> anyhow::Result<Value> {+ let actions: Vec<&str> = criteria.iter().map(|(name, _)| name.as_str()).collect();+ let raw = reply.trim();+ // The protocol asks for JSON only; tolerate a fenced or chatty reply by+ // slicing to the outermost object before repair-parsing.+ let candidate = match (raw.find('{'), raw.rfind('}')) {+ (Some(start), Some(end)) if end > start => &raw[start..=end],+ _ => raw,+ };+ let parsed = pa_ai::parse_json_with_repair(candidate).map_err(|error| {+ anyhow!("the decision model's reply was not valid JSON ({error}): {raw}")+ })?;+ let Some(answer) = parsed.get("action").and_then(Value::as_object) else {+ bail!("the decision model's reply has no \"action\" object: {raw}");+ };+ let Some(choice) = answer.get("choice").and_then(Value::as_str) else {+ bail!("the decision model's reply has no \"action\".\"choice\" string: {raw}");+ };+ if !actions.contains(&choice) {+ bail!(+ "the decision model chose {choice:?}, which is not one of the requested actions: {}",+ actions.join(", ")+ );+ }+ let confidence = answer+ .get("confidence")+ .and_then(Value::as_f64)+ .and_then(finite_or_none)+ .map(|confidence| confidence.clamp(0.0, 1.0));+ let probabilities = match answer.get("probabilities").and_then(Value::as_object) {+ Some(entries) => {+ let mut parsed = serde_json::Map::new();+ for (name, share) in entries {+ if let Some(value) = share.as_f64().and_then(finite_or_none) {+ parsed.insert(name.clone(), json!(value));+ }+ }+ Value::Object(parsed)+ }+ None => Value::Null,+ };+ Ok(json!({+ "choice": choice,+ "confidence": confidence,+ "probabilities": probabilities,+ }))+}++/// `None` for non-finite numbers, so no `NaN`/`Infinity` crosses the bridge.+fn finite_or_none(value: f64) -> Option<f64> {+ value.is_finite().then_some(value)+}++/// The api identifier of the System One structured-decision protocol: the+/// decision request body POSTs to the model's baseUrl + /systemone and the+/// reply envelope carries the answers (Prime Inference's hosted clef).+const SYSTEMONE_API: &str = "systemone";++/// Serve one decision request with the resolved model through the existing+/// provider transports: one non-streaming completion, parsed into the+/// decision envelope. System One models speak the native structured-decision+/// protocol; every other model answers the decision prompt.+async fn serve_decision(+ resolved: &ResolvedDecisionModel,+ request: &DecisionRequest,+) -> anyhow::Result<Value> {+ if resolved.model.api == SYSTEMONE_API {+ return serve_systemone(resolved, request).await;+ }+ let context = build_decision_context(request);+ let options = pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {+ max_tokens: Some(DECISION_MAX_TOKENS),+ timeout_ms: Some(DECISION_TIMEOUT_MS),+ api_key: resolved.api_key.clone(),+ headers: resolved+ .headers+ .as_ref()+ .map(|headers| headers.clone().into_iter().collect()),+ ..Default::default()+ });+ let response = pa_ai::complete_simple(&resolved.model, &context, Some(options))+ .await+ .map_err(|error| anyhow!("the decision model request failed: {error:?}"))?;+ match response.stop_reason {+ StopReason::Error => bail!(+ "the decision model call failed: {}",+ response+ .error_message+ .unwrap_or_else(|| "unknown provider error".to_string())+ ),+ StopReason::Aborted => bail!("the decision model call was aborted"),+ _ => {}+ }+ let reply = response+ .content+ .iter()+ .filter_map(|block| match block {+ pa_types::ai::AssistantContentBlock::Text(text) => Some(text.text.clone()),+ _ => None,+ })+ .collect::<Vec<_>>()+ .join("\n");+ if reply.trim().is_empty() {+ bail!("the decision model returned an empty reply");+ }+ let answer = parse_decision_answer(&reply, &request.criteria)?;+ Ok(json!({+ "model": resolved.label(),+ "answers": { "action": answer },+ }))+}++/// The settings decision model's resolved selector (`"provider/id"`):+/// the spawn seam uses this for the decision child's model, refusing with+/// the same actionable messages as `decide()` when the setting is unset or+/// unresolvable.+///+/// # Errors+///+/// Returns the unset/unresolvable-setting refusal.+pub fn decision_model_selector(cwd: &Path, agent_dir: &Path) -> Result<String, String> {+ resolve_decision_model(cwd, agent_dir).map(|resolved| resolved.label())+}++/// Serve one decision request: validate the kernel's request body, resolve+/// the settings model through the registry, and run one provider+/// completion. The session host handler and the daemon's decision child+/// share this path.+///+/// # Errors+///+/// Returns the request, setting, resolution, or provider failure as an+/// actionable message.+pub async fn serve_decision_request(+ request: Value,+ cwd: &Path,+ agent_dir: &Path,+) -> anyhow::Result<Value> {+ let Value::Object(request) = request else {+ bail!("decision_api.decide needs a request object");+ };+ let request = parse_decision_request(request)?;+ let resolved = resolve_decision_model(cwd, agent_dir).map_err(anyhow::Error::msg)?;+ if !request.images.is_empty() && !resolved.model.input.contains(&ModelInput::Image) {+ bail!(+ "{} does not accept image input, so decisions cannot carry images. Drop \+ the images, or set decisionApi.systemOneModel to a vision-capable model.",+ resolved.label()+ );+ }+ serve_decision(&resolved, &request).await+}++/// Serve one decision over the System One structured-decision protocol:+/// the request body rides to the endpoint verbatim and the reply envelope+/// passes through the same answer validation.+async fn serve_systemone(+ resolved: &ResolvedDecisionModel,+ request: &DecisionRequest,+) -> anyhow::Result<Value> {+ let mut criteria = serde_json::Map::new();+ for (name, applies) in &request.criteria {+ criteria.insert(name.clone(), json!(applies));+ }+ let mut body = json!({+ "state": request.state,+ "questions": { "action": {+ "type": "choice",+ "instructions": request.instructions,+ "criteria": Value::Object(criteria),+ } },+ "model": resolved.model.id,+ });+ if !request.images.is_empty() {+ let images = request+ .images+ .iter()+ .map(|(mime, data)| json!(format!("data:{mime};base64,{data}")))+ .collect::<Vec<_>>();+ body["images"] = Value::Array(images);+ }+ let context = pa_types::ai::Context {+ system_prompt: None,+ messages: vec![pa_types::ai::Message::User(pa_types::ai::UserMessage {+ content: pa_types::ai::UserContent::Text(body.to_string()),+ timestamp: 0,+ rest: serde_json::Map::default(),+ })],+ tools: None,+ };+ let options = pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {+ max_tokens: Some(DECISION_MAX_TOKENS),+ timeout_ms: Some(DECISION_TIMEOUT_MS),+ api_key: resolved.api_key.clone(),+ headers: resolved+ .headers+ .as_ref()+ .map(|headers| headers.clone().into_iter().collect()),+ ..Default::default()+ });+ let response = pa_ai::complete_simple(&resolved.model, &context, Some(options))+ .await+ .map_err(|error| anyhow!("the decision model request failed: {error:?}"))?;+ match response.stop_reason {+ StopReason::Error => bail!(+ "the decision model call failed: {}",+ response+ .error_message+ .unwrap_or_else(|| "unknown provider error".to_string())+ ),+ StopReason::Aborted => bail!("the decision model call was aborted"),+ _ => {}+ }+ let reply = response+ .content+ .iter()+ .filter_map(|block| match block {+ pa_types::ai::AssistantContentBlock::Text(text) => Some(text.text.clone()),+ _ => None,+ })+ .collect::<Vec<_>>()+ .join("\n");+ if reply.trim().is_empty() {+ bail!("the decision model returned an empty reply");+ }+ // The endpoint's envelope: {"model": ..., "answers": {"action": {...}}}.+ let raw = reply.trim();+ let candidate = match (raw.find('{'), raw.rfind('}')) {+ (Some(start), Some(end)) if end > start => &raw[start..=end],+ _ => raw,+ };+ let parsed = pa_ai::parse_json_with_repair(candidate).map_err(|error| {+ anyhow!("the decision model's reply was not valid JSON ({error}): {raw}")+ })?;+ let answers = parsed+ .get("answers")+ .cloned()+ .ok_or_else(|| anyhow!("the decision model's reply has no \"answers\" object: {raw}"))?;+ let answer = parse_decision_answer(&answers.to_string(), &request.criteria)?;+ // The envelope reports the resolved model's label (the chat path's+ // convention), never the endpoint's bare id.+ Ok(json!({+ "model": resolved.label(),+ "answers": { "action": answer },+ }))+}++/// Register `decision_api.decide`, resolving the decision model from the+/// settings under `agent_dir` on every call.+pub(crate) fn register_decision_api_handler(+ handlers: &mut HostRequestHandlers,+ cwd: PathBuf,+ agent_dir: PathBuf,+) {+ handlers.register(+ "decision_api.decide",+ host_handler(move |payload| {+ let cwd = cwd.clone();+ let agent_dir = agent_dir.clone();+ Box::pin(async move {+ let Some(request) = payload.data.get("request").cloned() else {+ bail!("decision_api.decide needs a request object");+ };+ serve_decision_request(request, &cwd, &agent_dir).await+ })+ }),+ );+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::kernel::shared::{HostHandlerFuture, HostRequestPayload};+ use std::path::Path;++ /// The registered `decision_api.decide`, called with a payload's data.+ fn decider(cwd: &Path, agent_dir: &Path) -> impl Fn(Value) -> HostHandlerFuture {+ let mut handlers = HostRequestHandlers::default();+ register_decision_api_handler(&mut handlers, cwd.to_path_buf(), agent_dir.to_path_buf());+ let decide = handlers+ .get("decision_api.decide")+ .expect("registered")+ .clone();+ move |data| {+ decide(HostRequestPayload {+ data,+ cell_source_code: None,+ })+ }+ }++ /// A fixture agent dir: settings.json naming the decision model and a+ /// custom registry provider carrying it (the api rides the faux provider).+ fn fixture_agent_dir(+ dir: &Path,+ decision_api: Option<&str>,+ model_input: &str,+ ) -> anyhow::Result<()> {+ let settings = match decision_api {+ Some(model) => json!({ "decisionApi": { "systemOneModel": model } }),+ None => json!({}),+ };+ std::fs::write(dir.join("settings.json"), settings.to_string())?;+ std::fs::write(+ dir.join("models.json"),+ format!(+ r#"{{ "providers": {{ "fixture-decisions": {{+ "baseUrl": "https://fixture.example", "apiKey": "fixture-key",+ "api": "faux-decision", "models": [+ {{ "id": "decision-model", "input": {model_input} }}+ ]+ }} }} }}"#+ ),+ )?;+ Ok(())+ }++ #[tokio::test]+ async fn decide_refuses_while_the_setting_is_missing_or_unusable() {+ let dir = tempfile::tempdir().unwrap();+ fixture_agent_dir(+ dir.path(),+ Some("fixture-decisions/decision-model"),+ r#"["text"]"#,+ )+ .unwrap();+ let call = decider(dir.path(), dir.path());+ let request = json!({ "request": { "state": {}, "questions": { "action": {+ "type": "choice",+ "criteria": { "left": "go left" }+ } } } });+ let error = |data| async { call(data).await.unwrap_err().to_string() };+ // An unset reference and an unresolvable one name the setting.+ fixture_agent_dir(dir.path(), None, r#"["text"]"#).unwrap();+ assert_eq!(+ error(request.clone()).await,+ "decisionApi.systemOneModel is not set in settings.json. Set it to the decision model \+ reference (\"provider/model-id\" or a bare id), e.g. \"prime-inference/clef\"."+ );+ fixture_agent_dir(dir.path(), Some("no-such/model"), r#"["text"]"#).unwrap();+ let refusal = error(request.clone()).await;+ assert!(+ refusal.starts_with(+ "decisionApi.systemOneModel \"no-such/model\" could not be resolved to an \+ available, authenticated model."+ ),+ "{refusal}"+ );+ assert!(+ refusal.contains("or authenticate the provider"),+ "the refusal names the recovery: {refusal}"+ );+ // A configured but unauthenticated reference is unusable too: the+ // provider has no key, so the model never becomes available.+ std::fs::write(+ dir.path().join("models.json"),+ r#"{ "providers": { "fixture-decisions": {+ "baseUrl": "https://fixture.example", "api": "faux-decision",+ "models": [ { "id": "decision-model", "input": ["text"] } ]+ } } }"#,+ )+ .unwrap();+ std::fs::write(+ dir.path().join("settings.json"),+ json!({ "decisionApi": { "systemOneModel": "decision-model" } }).to_string(),+ )+ .unwrap();+ assert!(+ error(request).await.contains("could not be resolved"),+ "an unauthenticated reference must refuse, not call a provider"+ );+ }++ #[tokio::test]+ async fn decide_validates_the_request_before_any_resolution() {+ let dir = tempfile::tempdir().unwrap();+ fixture_agent_dir(+ dir.path(),+ Some("fixture-decisions/decision-model"),+ r#"["text"]"#,+ )+ .unwrap();+ let call = decider(dir.path(), dir.path());+ let error = |data| async { call(data).await.unwrap_err().to_string() };+ let base = |request: Value| json!({ "request": request });+ assert_eq!(+ error(json!({})).await,+ "decision_api.decide needs a request object"+ );+ let good_question = json!({ "type": "choice", "criteria": { "left": "go left" } });+ let with_question =+ |question: Value| json!({ "state": {}, "questions": { "action": question } });+ assert_eq!(+ error(base(+ json!({ "state": {}, "questions": { "move": good_question } })+ ))+ .await,+ "decision_api.decide needs a \"questions\" object with an \"action\" question"+ );+ assert_eq!(+ error(base(with_question(+ json!({ "type": "rank", "criteria": {} })+ )))+ .await,+ "the \"action\" question must have type \"choice\", not \"rank\". The Decision API \+ serves one action choice per request."+ );+ assert_eq!(+ error(base(with_question(+ json!({ "type": "choice", "criteria": {} })+ )))+ .await,+ "the \"action\" question's \"criteria\" object is empty; a decision needs actions to \+ choose from"+ );+ assert_eq!(+ error(base(with_question(+ json!({ "type": "choice", "criteria": { "left": 7 } })+ )))+ .await,+ "the \"criteria\" entry \"left\" must be a string describing when the action applies, \+ not 7"+ );+ assert_eq!(+ error(base(json!({ "state": {}, "model": "jev-latest" }))).await,+ "The decision model comes from the decisionApi.systemOneModel setting; the request \+ carries no model (got \"jev-latest\")."+ );+ assert_eq!(+ error(base(json!({ "state": {}, "hint": true }))).await,+ "decision_api.decide got unsupported request fields: \"hint\". Only \"state\", \+ \"questions\", and \"images\" are allowed."+ );+ assert_eq!(+ error(base(json!({ "questions": { "action": good_question } }))).await,+ "decision_api.decide needs a \"state\" value"+ );+ let images = |list: Value| json!({ "state": {}, "questions": { "action": good_question }, "images": list });+ assert_eq!(+ error(base(images(json!([+ "data:image/png;base64,AA==",+ "not-a-data-url"+ ]))))+ .await,+ "decision images must be data URL strings like \"data:image/png;base64,...\""+ );+ let five: Vec<&str> = (0..5).map(|_| "data:image/png;base64,AA==").collect();+ assert_eq!(+ error(base(images(json!(five)))).await,+ "a decision carries at most 4 images, got 5"+ );+ }++ #[tokio::test]+ async fn decide_refuses_images_on_a_text_only_model() {+ let dir = tempfile::tempdir().unwrap();+ fixture_agent_dir(+ dir.path(),+ Some("fixture-decisions/decision-model"),+ r#"["text"]"#,+ )+ .unwrap();+ let call = decider(dir.path(), dir.path());+ let request = json!({ "request": { "state": {}, "questions": { "action": {+ "type": "choice", "criteria": { "left": "go left", "right": "go right" }+ } }, "images": [ "data:image/png;base64,AA==" ] } });+ let error = call(request).await.unwrap_err().to_string();+ assert_eq!(+ error,+ "fixture-decisions/decision-model does not accept image input, so decisions cannot \+ carry images. Drop the images, or set decisionApi.systemOneModel to a \+ vision-capable model."+ );+ }++ /// One decision round trip through the registry resolution and the+ /// provider transports, with the faux provider standing in for the wire:+ /// the answer's contract (choice, confidence, probabilities) and the+ /// request's reach (actions, state, images, key) are pinned.+ #[tokio::test]+ async fn decide_serves_one_round_trip_through_the_registry_and_provider() {+ static FAUX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ let registration = {+ let _guard = FAUX_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ pa_ai::faux::register_faux_provider(pa_ai::faux::RegisterFauxProviderOptions {+ api: Some("faux-decision".to_string()),+ provider: Some("fixture-decisions".to_string()),+ models: Some(vec![pa_ai::faux::FauxModelDefinition {+ id: "decision-model".to_string(),+ input: Some(vec![ModelInput::Text, ModelInput::Image]),+ ..Default::default()+ }]),+ ..Default::default()+ })+ };+ let dir = tempfile::tempdir().unwrap();+ fixture_agent_dir(dir.path(), Some("decision-model"), r#"["text", "image"]"#).unwrap();+ let call = decider(dir.path(), dir.path());++ // The served reply names an unrequested action: the refusal proves+ // the criteria reached the parse and the choice check is enforced.+ registration.set_responses(vec![pa_ai::faux::FauxResponseStep::Message(+ pa_ai::faux::faux_assistant_text_message(+ r#"{"action": {"choice": "jump", "confidence": 0.9}}"#,+ pa_ai::faux::FauxAssistantMessageOptions::default(),+ ),+ )]);+ let request = json!({ "request": { "state": { "x": 1 }, "questions": { "action": {+ "type": "choice", "instructions": "Track the target",+ "criteria": { "left": "go left", "right": "go right" }+ } } } });+ let error = call(request).await.unwrap_err().to_string();+ assert_eq!(+ error,+ "the decision model chose \"jump\", which is not one of the requested actions: left, \+ right"+ );++ // The good path: a fenced reply with an out-of-range confidence and+ // a non-finite share, both normalized by the host.+ let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));+ let seen_writer = std::sync::Arc::clone(&seen);+ registration.set_responses(vec![pa_ai::faux::FauxResponseStep::Factory(+ std::sync::Arc::new(+ move |context: &pa_ai::types::Context,+ options: Option<&pa_ai::types::StreamOptions>,+ _call: u64,+ model: &pa_types::ai::Model| {+ let mut text = String::new();+ for message in &context.messages {+ if let pa_types::ai::Message::User(user) = message {+ match &user.content {+ pa_types::ai::UserContent::Text(content) => text.push_str(content),+ pa_types::ai::UserContent::Blocks(blocks) => {+ for block in blocks {+ match block {+ pa_types::ai::UserContentBlock::Text(block) => {+ text.push_str(&block.text);+ }+ pa_types::ai::UserContentBlock::Image(_) => {+ text.push_str("<image>");+ }+ pa_types::ai::UserContentBlock::Raw(_) => {}+ }+ }+ }+ }+ }+ }+ *seen_writer.lock().unwrap() = text;+ let _ = (options.and_then(|options| options.api_key.clone()), model);+ Ok(pa_ai::faux::faux_assistant_text_message(+ "```json\n{\"action\": {\"choice\": \"left\", \"confidence\": 1.4, \+ \"probabilities\": {\"left\": 0.75, \"right\": 0.25}}}\n```",+ pa_ai::faux::FauxAssistantMessageOptions::default(),+ ))+ },+ ),+ )]);+ let request = json!({ "request": { "state": { "x": 1 }, "questions": { "action": {+ "type": "choice", "instructions": "Track the target",+ "criteria": { "left": "go left", "right": "go right" }+ } }, "images": [ "data:image/png;base64,AA==" ] } });+ let answer = call(request).await.unwrap();+ assert_eq!(answer["model"], "fixture-decisions/decision-model");+ assert_eq!(+ answer["answers"],+ json!({+ "action": {+ "choice": "left",+ "confidence": 1.0,+ "probabilities": { "left": 0.75, "right": 0.25 }+ }+ })+ );+ let seen = seen.lock().unwrap().clone();+ assert!(seen.contains("Instructions: Track the target"), "{seen}");+ assert!(seen.contains("- left: go left"), "{seen}");+ assert!(seen.contains("- right: go right"), "{seen}");+ assert!(seen.contains("\"x\""), "{seen}");+ assert!(seen.contains("<image>"), "{seen}");+ let received = registration.received_api_keys();+ assert!(+ received.len() >= 2+ && received+ .iter()+ .all(|key| key.as_deref() == Some("fixture-key")),+ "the registry-resolved key reaches the provider on every call: {received:?}"+ );+ }++ /// The fixture registry recipe with the System One decision api pointing+ /// at one loopback endpoint, plus the settings reference.+ async fn systemone_fixture(+ dir: &Path,+ reply: Value,+ seen: std::sync::Arc<std::sync::Mutex<Vec<(String, String, Value)>>>,+ ) -> anyhow::Result<String> {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;+ let base = format!("http://{}", listener.local_addr()?);+ tokio::spawn(async move {+ while let Ok((mut socket, _)) = listener.accept().await {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let mut raw = Vec::new();+ let mut chunk = [0u8; 4096];+ let (head, body) = loop {+ let read = socket.read(&mut chunk).await.unwrap();+ assert_ne!(read, 0, "the client closed mid-request");+ raw.extend_from_slice(&chunk[..read]);+ let text = String::from_utf8_lossy(&raw).to_string();+ let Some((head, body)) = text.split_once("\r\n\r\n") else {+ continue;+ };+ let length = head+ .lines()+ .find_map(|line| {+ let line = line.to_ascii_lowercase();+ line.strip_prefix("content-length:")?.trim().parse().ok()+ })+ .unwrap_or(0);+ if body.len() >= length {+ break (head.to_string(), body.to_string());+ }+ };+ let authorization = head+ .lines()+ .find_map(|line| {+ let line = line.to_ascii_lowercase();+ line.strip_prefix("authorization:")+ .map(|v| v.trim().to_string())+ })+ .unwrap_or_default();+ let request_line = head.lines().next().unwrap_or_default().split(' ');+ let path = request_line+ .into_iter()+ .nth(1)+ .unwrap_or_default()+ .to_string();+ seen.lock().unwrap().push((+ path,+ authorization,+ serde_json::from_str(&body).unwrap_or(Value::Null),+ ));+ let reply = reply.to_string();+ let response = format!(+ "HTTP/1.1 200 Status\r\ncontent-type: application/json\r\n\+ content-length: {}\r\nconnection: close\r\n\r\n{reply}",+ reply.len()+ );+ socket.write_all(response.as_bytes()).await.unwrap();+ }+ });+ std::fs::write(+ dir.join("settings.json"),+ json!({ "decisionApi": { "systemOneModel": "fixture-decisions/systemone-model" } })+ .to_string(),+ )?;+ std::fs::write(+ dir.join("models.json"),+ format!(+ r#"{{ "providers": {{ "fixture-decisions": {{+ "baseUrl": "{base}", "apiKey": "fixture-key", "api": "systemone",+ "models": [ {{ "id": "systemone-model", "input": ["text", "image"] }} ]+ }} }} }}"#+ ),+ )?;+ Ok(base)+ }++ #[test]+ fn decision_answers_parse_leniently_and_validate_the_choice() {+ let criteria = vec![+ ("left".to_string(), "go left".to_string()),+ ("right".to_string(), "go right".to_string()),+ ];+ let plain = parse_decision_answer(+ r#"{"action": {"choice": "right", "confidence": 0.5, "probabilities": {"right": 1}}}"#,+ &criteria,+ )+ .unwrap();+ assert_eq!(plain["choice"], "right");+ assert_eq!(plain["confidence"], 0.5);+ let fenced = parse_decision_answer(+ "prose\n```json\n{\"action\": {\"choice\": \"left\"}}\n```",+ &criteria,+ )+ .unwrap();+ assert_eq!(fenced["choice"], "left");+ assert!(fenced["confidence"].is_null());+ assert!(fenced["probabilities"].is_null());+ for bad in [+ "not json",+ "{}",+ "{\"action\": \"left\"}",+ "{\"action\": {\"choice\": \"up\"}}",+ "{\"action\": {\"choice\": 3}}",+ ] {+ assert!(parse_decision_answer(bad, &criteria).is_err(), "{bad}");+ }+ }++ /// One decision over the System One protocol, hermetic: the decide+ /// dispatch builds the protocol request, the endpoint envelope parses+ /// through the same answer validation, and the merged auth rides.+ #[tokio::test]+ async fn decide_serves_the_systemone_protocol_end_to_end() {+ let dir = tempfile::tempdir().unwrap();+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let envelope = json!({+ "model": "fixture-decisions/systemone-model",+ "answers": {"action": {"choice": "left", "confidence": 0.9, "probabilities": {"left": 0.9, "right": 0.1}}}+ });+ systemone_fixture(dir.path(), envelope.clone(), std::sync::Arc::clone(&seen))+ .await+ .unwrap();+ let call = decider(dir.path(), dir.path());+ let request = json!({ "request": { "state": {"observation": 1}, "questions": { "action": {+ "type": "choice", "criteria": {"left": "go left", "right": "go right"}+ } }, "images": ["data:image/png;base64,AA=="] } });+ let answer = call(request).await.unwrap();+ assert_eq!(answer["model"], "fixture-decisions/systemone-model");+ assert_eq!(answer["answers"]["action"]["choice"], "left", "{answer}");+ let requests = seen.lock().unwrap();+ assert_eq!(requests.len(), 1);+ assert_eq!(requests[0].0, "/systemone");+ assert_eq!(requests[0].1, "bearer fixture-key");+ let body = &requests[0].2;+ assert_eq!(body["model"], "systemone-model");+ assert_eq!(+ body["questions"]["action"]["criteria"],+ json!({"left": "go left", "right": "go right"})+ );+ assert_eq!(+ body["images"],+ json!(["data:image/png;base64,AA=="]),+ "the images ride the protocol request"+ );+ }++ #[test]+ fn catch_startup_and_artifacts_follow_the_environment_contract() {+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/catch");+ let output = std::process::Command::new("python3")+ .args(["-m", "unittest", "discover", "-s"])+ .arg(&root)+ .args(["-p", "test_*.py", "-v"])+ .output()+ .expect("python3 runs the Catch environment tests");+ assert!(+ output.status.success(),+ "Catch tests failed\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ }++ /// The skill's `Loop` and `decide` (image strings, step control, System 2's+ /// action gate) run as the package's own unittest.+ #[test]+ fn the_decision_api_python_loop_follows_its_contract() {+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../skills/decision-api");+ let output = std::process::Command::new("python3")+ .args(["-m", "unittest", "discover", "-s"])+ .arg(root.join("tests"))+ .arg("-v")+ .env("PYTHONPATH", root.join("src"))+ .output()+ .expect("python3 runs the decision-api loop tests");+ assert!(+ output.status.success(),+ "decision-api loop tests failed\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ }+}diff --git a/crates/pa-core/src/session_engine/decision_runtime_tests.rs b/crates/pa-core/src/session_engine/decision_runtime_tests.rsnew file mode 100644index 0000000000..5da6cdac0a--- /dev/null+++ b/crates/pa-core/src/session_engine/decision_runtime_tests.rs@@ -0,0 +1,348 @@+//! The Decision API's real-runtime fixtures: the kernel's settings-gated+//! skill pre-import and the real skill loop over the host bridge.++use std::path::Path;++use serde_json::{json, Value};++use super::engine::{create_session, SessionEngine, SessionEngineConfig};++async fn build_session(root: &Path, agent_dir: &std::path::Path) -> SessionEngine {+ let model = pa_agent::types::Model {+ id: "m".into(),+ name: "m".into(),+ api: "test".into(),+ provider: "test".into(),+ base_url: "http://localhost".into(),+ reasoning: false,+ cost: pa_agent::types::UsageCost::default(),+ context_window: 1_000,+ max_tokens: 100,+ max_tokens_explicit: false,+ };+ let provider = std::sync::Arc::new(pa_agent::scripted::ScriptedProvider::new(model.clone()));+ create_session(SessionEngineConfig {+ cwd: root.to_path_buf(),+ agent_dir: agent_dir.to_path_buf(),+ model: Some(model),+ stream_fn: Some(provider.stream_fn()),+ ..Default::default()+ })+ .await+ .unwrap()+}++// Real fixtures own their process-wide kernel registry and environment.+#[tracing::instrument]+async fn run_runtime_fixture_in_child(name: &str) -> bool {+ const CHILD_FIXTURE: &str = "PA_DECISION_API_RUNTIME_FIXTURE_CHILD";+ let test = format!("session_engine::decision_runtime_tests::{name}");+ if std::env::var(CHILD_FIXTURE).as_deref() == Ok(test.as_str()) {+ return false;+ }+ let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());+ command+ .args(["--exact", &test, "--nocapture"])+ .env(CHILD_FIXTURE, &test)+ .env("RUST_TEST_THREADS", "1")+ .kill_on_drop(true);+ let output = tokio::time::timeout(std::time::Duration::from_secs(240), command.output())+ .await+ .expect("isolated real fixture deadline")+ .expect("isolated real fixture starts");+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stderr = String::from_utf8_lossy(&output.stderr);+ for line in stdout.lines().chain(stderr.lines()) {+ eprintln!("[decision fixture child] {line}");+ }+ assert!(+ output.status.success(),+ "isolated fixture {test}: {}",+ output.status+ );+ assert!(+ stdout.contains("running 1 test"),+ "the exact child fixture must run"+ );+ assert!(+ stdout.contains(&format!("DECISION_API_REAL_FIXTURE_EXECUTED: {name}"))+ || stderr.contains("no installed kernel Python"),+ "fixture must report execution or its explicit runtime skip",+ );+ true+}++#[tokio::test]+async fn decision_api_preimports_the_skill_only_while_the_setting_is_set() {+ use crate::kernel::shared::{ExecuteOptions, ExecuteStatus};+ if run_runtime_fixture_in_child(+ "decision_api_preimports_the_skill_only_while_the_setting_is_set",+ )+ .await+ {+ return;+ }+ // This verifier needs an installed runtime; hermetic hosts can run the+ // metadata regressions without downloading a Python environment.+ let installed = std::env::var_os("PRIME_AGENT_KERNEL_PYTHON")+ .map(std::path::PathBuf::from)+ .or_else(|| {+ std::env::var_os("HOME").map(|home| {+ std::path::PathBuf::from(home).join(".prime/agent/kernel-venv/bin/python")+ })+ });+ if !installed.is_some_and(|path| path.exists()) {+ eprintln!("skipping decision API real-kernel verifier: no installed kernel Python");+ return;+ }+ for (configured, expected) in [(true, "True"), (false, "False")] {+ let dir = tempfile::tempdir().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ let settings = if configured {+ json!({ "decisionApi": { "systemOneModel": "fixture/model" } })+ } else {+ json!({})+ };+ std::fs::write(agent_dir.join("settings.json"), settings.to_string()).unwrap();+ let engine = build_session(dir.path(), &agent_dir).await;+ let skill_entry = "<name>decision-api</name>";+ assert_eq!(engine.system_prompt.contains(skill_entry), configured);+ let kernel = tokio::time::timeout(+ std::time::Duration::from_secs(60),+ engine.provisioner.ensure(None, None),+ )+ .await+ .expect("kernel bootstrap deadline")+ .expect("real kernel must start");+ let code = format!("assert ('decision_api' in globals()) == {expected}\nprint('ok')");+ let result = kernel+ .execute(&code, ExecuteOptions::default())+ .await+ .unwrap();+ assert_eq!(+ result.status,+ ExecuteStatus::Ok,+ "{:?}\n{}\n{}",+ result.error,+ result.stdout,+ result.stderr+ );+ engine.dispose_kernel().await;+ }+ println!("DECISION_API_REAL_FIXTURE_EXECUTED: decision_api_preimports_the_skill_only_while_the_setting_is_set");+}++#[tokio::test]+async fn decision_api_real_runtime_loop_routes_decisions_and_child_delivery_then_cleans_up() {+ use std::sync::{Arc, Mutex};++ use crate::kernel::manager::{KernelStartOptions, ReplKernelManager};+ use crate::kernel::shared::{+ host_handler, ExecuteOptions, ExecuteStatus, HostRequestHandlers, KernelManagerOptions,+ KernelShutdownOptions,+ };++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ enum FixtureRequest {+ Spawn,+ Send,+ Decision,+ Delete,+ }+ if run_runtime_fixture_in_child(+ "decision_api_real_runtime_loop_routes_decisions_and_child_delivery_then_cleans_up",+ )+ .await+ {+ return;+ }+ // This is a real REPL/skill bridge with synthetic child and reply+ // handlers. It never invokes a paid provider or starts a daemon child.+ let python = std::env::var_os("PRIME_AGENT_KERNEL_PYTHON")+ .map(std::path::PathBuf::from)+ .or_else(|| {+ std::env::var_os("HOME").map(|home| {+ std::path::PathBuf::from(home).join(".prime/agent/kernel-venv/bin/python")+ })+ });+ let Some(python) = python.filter(|path| path.exists()) else {+ eprintln!("skipping decision API real-runtime fixture: no installed kernel Python");+ return;+ };+ let events = Arc::new(Mutex::new(Vec::new()));+ let replies = Arc::new(Mutex::new(std::collections::HashMap::<String, Value>::new()));+ let mut handlers = HostRequestHandlers::new();+ for (name, kind) in [+ ("rlm.run", FixtureRequest::Spawn),+ ("agent_message.send", FixtureRequest::Send),+ ("decision_api.decision", FixtureRequest::Decision),+ ("rlm.delete_subagent", FixtureRequest::Delete),+ ] {+ let events = Arc::clone(&events);+ let replies = Arc::clone(&replies);+ handlers.register(name, host_handler(move |payload| {+ let events = Arc::clone(&events);+ let replies = Arc::clone(&replies);+ Box::pin(async move {+ events.lock().unwrap().push((kind, payload.data.clone()));+ match kind {+ FixtureRequest::Spawn => {+ let name = payload.data["kwargs"]["name"].clone();+ Ok(json!({"rlm_child_id":"fixture-child","name":name,"session_dir":"/tmp/fixture-child","model":"synthetic/child"}))+ }+ FixtureRequest::Send => {+ let text = payload.data["message"].as_str().unwrap();+ let message: serde_json::Value = serde_json::from_str(text)?;+ let name = payload.data["receiver_name"].as_str().unwrap_or("system-1");+ // The decision child's answer routes back through+ // the parent's per-child slot (the child records the+ // latest message-sourced goal and serves one decide).+ let state = message["state"].clone();+ let mut decision_state = state;+ if decision_state.get("goal").is_none() {+ decision_state["goal"] = json!("follow fixture strategy");+ }+ replies.lock().unwrap().insert(+ name.to_string(),+ json!({+ "type":"decision_api.decision","seq":message["seq"],+ "model":"synthetic/child",+ "decision":{"choice":"left","confidence":0.9,"probabilities":{"left":0.9,"right":0.1}}+ }),+ );+ Ok(json!({"deliveryStatus":"sent"}))+ }+ FixtureRequest::Decision => {+ let name = payload.data["name"].as_str().unwrap_or_default().to_string();+ if payload.data["close"] == true {+ replies.lock().unwrap().remove(&name);+ return Ok(Value::Null);+ }+ Ok(replies+ .lock()+ .unwrap()+ .get(&name)+ .cloned()+ .unwrap_or(Value::Null))+ }+ FixtureRequest::Delete => Ok(json!({"subagent":{+ "rlm_child_id":"fixture-child","session_name":payload.data["target"],+ "session_dir":"/tmp/fixture-child","status":"completed"+ },"outcome":"deleted"})),+ }+ })+ }));+ }+ let dir = tempfile::tempdir().unwrap();+ let manager = ReplKernelManager::new(KernelManagerOptions {+ python: Some(python),+ cwd: Some(dir.path().to_path_buf()),+ env: std::collections::HashMap::new(),+ session_id: Some("decision-runtime-fixture".to_string()),+ host_handlers: handlers,+ python_skills: Vec::new(),+ on_background_work_settled: None,+ snapshot: None,+ bootstrap_code: None,+ stderr_log_path: None,+ });+ manager.start(KernelStartOptions::default()).await.unwrap();+ // The fixture kernel carries no skill set (a bare ReplKernelManager),+ // so the skill imports resolve from the checkout's skill sources, never+ // a side-effect skill install some other test raced into the shared venv.+ let decision_skill =+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../skills/decision-api/src");+ let messaging_skill =+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../skills/agent-message/src");+ let source = serde_json::to_string(&decision_skill.display().to_string()).unwrap();+ let messaging_source = serde_json::to_string(&messaging_skill.display().to_string()).unwrap();+ let code = format!(+ r#"+import sys, asyncio, pathlib+sys.path.insert(0, {messaging_source})+sys.path.insert(0, {source})+import decision_api+assert pathlib.Path(decision_api.__file__).resolve().is_relative_to(pathlib.Path({source}).resolve())+assert decision_api.rlm.__file__ and decision_api.agent_message.__file__+actions_taken = []+observations_seen = 0+async def observe_fixture():+ global observations_seen+ observations_seen += 1+ if observations_seen > 2:+ return None+ return {{"frame": observations_seen}}+loop = decision_api.Loop(observe_fixture, actions_taken.append, {{"left":"go left", "right":"go right"}},+ objective="fixture objective", decide_timeout=15)+status = await asyncio.wait_for(loop.run(), 60)+assert actions_taken == ["left", "left"], actions_taken+assert loop.goal == "fixture objective", loop.status()+assert loop.errors == [], loop.errors+assert not status["running"]+print("fixture passed")+"#+ );+ let result = tokio::time::timeout(+ std::time::Duration::from_secs(120),+ manager.execute(&code, ExecuteOptions::default()),+ )+ .await+ .expect("real runtime fixture deadline")+ .expect("real runtime fixture execution");+ manager+ .shutdown(KernelShutdownOptions::default())+ .await+ .unwrap();+ assert_eq!(+ result.status,+ ExecuteStatus::Ok,+ "{:?}\n{}\n{}",+ result.error,+ result.stdout,+ result.stderr+ );+ assert_eq!(result.stdout, "fixture passed\n");+ let events = events.lock().unwrap();+ // The spawn carries the decision kind; the requests carry the step seqs.+ let spawned = events+ .iter()+ .find(|(kind, _)| *kind == FixtureRequest::Spawn)+ .unwrap();+ assert_eq!(spawned.1["kwargs"]["kind"], json!("decision"));+ assert!(+ spawned.1["prompt"]+ .as_str()+ .is_some_and(|prompt| prompt.contains("You are System 1")),+ "the child's protocol prompt composes from the skill material"+ );+ let sends: Vec<&Value> = events+ .iter()+ .filter(|(kind, _)| *kind == FixtureRequest::Send)+ .map(|(_, data)| data)+ .collect();+ assert_eq!(sends.len(), 2);+ let seqs: Vec<i64> = sends+ .iter()+ .filter_map(|send| {+ let message: Value = serde_json::from_str(send["message"].as_str()?).ok()?;+ message["seq"].as_i64()+ })+ .collect();+ assert_eq!(seqs, vec![0, 1]);+ assert!(+ sends+ .iter()+ .all(|send| send["receiver_role"] == json!("child")),+ "the requests address the decision child"+ );+ let deleted = events+ .iter()+ .find(|(kind, _)| *kind == FixtureRequest::Delete)+ .unwrap();+ assert_eq!(+ deleted.1["target"], spawned.1["kwargs"]["name"],+ "the loop's teardown deletes its decision child"+ );+ println!("DECISION_API_REAL_FIXTURE_EXECUTED: decision_api_real_runtime_loop_routes_decisions_and_child_delivery_then_cleans_up");+}diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex a502f37ca4..ffcae34ba1 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -177,6 +177,8 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Slet mut session_manager = config.session_manager.unwrap_or_else(|| SessionManager::in_memory(&cwd));+ let owns_resume_settings =+ session_manager.is_persisted() || config.conversation_log_path.is_none();let conversation_log = {let session = &session_manager;session@@ -217,6 +219,10 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S);let service_tier_preference = settings.get_default_service_tier();+ // Captured before `settings` moves into the resource loader: whether the+ // decision-api skill's settings gate is set (the prompt and the kernel's+ // pre-import filter read it below).+ let decision_api_configured = super::decision_api::decision_api_configured(settings.settings());// Captured before `settings` moves into the resource loader: the// compaction budget and the auto-refine gates.let compaction_settings = settings.settings().compaction.clone().unwrap_or_default();@@ -320,6 +326,11 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Scrate::mcp::McpManager::register_host_handlers(&mcp_manager, &mut handlers);let turn_boundary = Arc::new(super::turn_boundary::TurnBoundaryRequests::new());turn_boundary.register_model_info_handler(&mut handlers, model_info.clone());+ super::decision_api::register_decision_api_handler(+ &mut handlers,+ cwd.clone(),+ config.agent_dir.clone(),+ );let keep_recent_tokens = compaction_settings.keep_recent_tokens.unwrap_or(super::compaction::DEFAULT_KEEP_RECENT_TOKENS);@@ -403,10 +414,13 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S)as crate::kernel::provisioner::UnavailableSkillsCallback)};+ let preimport_filter =+ super::decision_api::decision_api_preimport_filter(decision_api_configured);let provisioner = super::runtime_wiring::kernel_provisioner(session_id,handlers,python_skills,+ preimport_filter,cwd.clone(),&config.agent_dir,session_artifact_dir,@@ -477,35 +491,52 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S&model_prompts.errors,));}- let system_prompt = crate::prompts::system_prompt::build_system_prompt(- &crate::prompts::system_prompt::BuildSystemPromptOptions {- custom_prompt: resources.system_prompt.clone(),- model_prompt_extras: model_prompts.extras.as_deref(),- vision_capable: prompt_vision_capable,- cwd: cwd.display().to_string(),- messages_path: conversation_log.clone(),- context_files: resources- .agents_files+ // The settings gate decides the prompt's decision-api skill: the skill+ // rides the prompt only while decisionApi.systemOneModel is set.+ let mut prompt_options = crate::prompts::system_prompt::BuildSystemPromptOptions {+ custom_prompt: resources.system_prompt.clone(),+ model_prompt_extras: model_prompts.extras.as_deref(),+ vision_capable: prompt_vision_capable,+ cwd: cwd.display().to_string(),+ messages_path: conversation_log.clone(),+ context_files: resources+ .agents_files+ .iter()+ .map(|file| (file.path.display().to_string(), file.content.clone()))+ .collect(),+ skills: resources.skills.clone(),+ selected_tools: Some(+ active_tool_names.iter()- .map(|file| (file.path.display().to_string(), file.content.clone()))- .collect(),- skills: resources.skills.clone(),- selected_tools: Some(- active_tool_names- .iter()- .map(String::as_str)- .collect::<Vec<_>>(),- ),- allow_recursion: config.allow_recursion,- // A spawned child's prompt must read "depth: N (not root)" with- // the child-agent reply doctrine, never the root identity.- rlm_depth: config.rlm_depth,- daemonless: config.rlm_subagent_host.is_none(),- generic_mcp_servers,- prompt_guidelines: Some(prompt_guidelines),- ..Default::default()- },- );+ .map(String::as_str)+ .collect::<Vec<_>>(),+ ),+ allow_recursion: config.allow_recursion,+ // A spawned child's prompt must read "depth: N (not root)" with+ // the child-agent reply doctrine, never the root identity.+ rlm_depth: config.rlm_depth,+ daemonless: config.rlm_subagent_host.is_none(),+ generic_mcp_servers,+ prompt_guidelines: Some(prompt_guidelines),+ ..Default::default()+ };+ if !decision_api_configured {+ prompt_options+ .skills+ .retain(|skill| skill.name != super::decision_api::DECISION_API_SKILL_NAME);+ }+ let system_prompt = crate::prompts::system_prompt::build_system_prompt(&prompt_options);+ // While the gate is off the skill is unreachable: the prompt omits it+ // and `/skill:` cannot invoke it; while it is on, the skill is an+ // ordinary session skill.+ let session_skills: Vec<crate::skills::Skill> = resources+ .skills+ .iter()+ .filter(|skill| {+ decision_api_configured || skill.name != super::decision_api::DECISION_API_SKILL_NAME+ })+ .cloned()+ .collect();// Captured before the digest context moves the local harness dir and// the loop wiring moves the session model: the factory host bridge's@@ -525,6 +556,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S&& skill.name == crate::prompts::system_prompt::REFINE_SKILL_NAME}),};+let (existing_messages, has_thinking_entry, has_service_tier_entry) = {let session = wiring.session.lock().await;let messages = super::compact_session::rebuilt_context_after_compaction(&session);@@ -538,10 +570,10 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Sif existing_messages.is_empty() {session.append_model_change(&model.provider, &model.id)?;session.append_thinking_level_change(&format!("{thinking_level:?}").to_lowercase())?;- } else if !has_thinking_entry {+ } else if owns_resume_settings && !has_thinking_entry {session.append_thinking_level_change(&format!("{thinking_level:?}").to_lowercase())?;}- if existing_messages.is_empty() || !has_service_tier_entry {+ if existing_messages.is_empty() || (owns_resume_settings && !has_service_tier_entry) {session.append_service_tier_change(Some(service_tier_preference))?;}}@@ -681,7 +713,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Sstd::sync::Arc::downgrade(&provisioner),));session.set_kernel_state_probe(Some(kernel_state_probe));- session.set_skills(resources.skills.clone());+ session.set_skills(session_skills.clone());session.set_image_model_router(config.image_model_router.clone());// The semantic-edge handoff: the daemon's child registry and retry// park read the recorder; the side question keeps the pre-semantic@@ -774,7 +806,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S});Ok(SessionEngine {session,- skills: resources.skills,+ skills: session_skills,skill_diagnostics: resources.skill_diagnostics,prompt_templates: resources.prompts,agents_files: resources.agents_files,diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rsindex e1c1e2b611..e612e304e1 100644--- a/crates/pa-core/src/session_engine/mod.rs+++ b/crates/pa-core/src/session_engine/mod.rs@@ -12,6 +12,7 @@ pub mod compaction;pub mod compaction_exec;pub mod compaction_trace;pub mod compaction_utils;+pub mod decision_api;pub mod engine;pub mod error_classify;pub mod factory_host;@@ -488,3 +489,5 @@ mod compaction_outcome_tests;#[cfg(test)]mod compaction_unblocked_tests;+#[cfg(test)]+mod decision_runtime_tests;diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rsindex 0015567949..3b94f2d421 100644--- a/crates/pa-core/src/session_engine/rlm_host.rs+++ b/crates/pa-core/src/session_engine/rlm_host.rs@@ -136,6 +136,10 @@ pub struct RlmSpawnRequest {pub model: Option<String>,/// Validated thinking level; the host checks model support.pub thinking: Option<String>,+ /// The decision-child spawn kind: `true` spawns the Decision API child+ /// (the model comes from `decisionApi.systemOneModel`, and the child's+ /// intake answers every message with one decision).+ pub decision_child: bool,/// The parent's in-flight turn request the spawn anchors to (TS/// `spawnedByRequestId`): `None` for a spawn outside an active run.pub spawned_by_request_id: Option<String>,@@ -489,7 +493,17 @@ fn register_run(handlers: &mut HostRequestHandlers, bridge: &Arc<RlmHostBridge>)fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmSpawnRequest> {const OPERATION: &str = "rlm.spawn";let kwargs = kwargs_from_payload(data);- reject_unsupported_kwargs(&kwargs, OPERATION, &["name", "model", "thinking"])?;+ reject_unsupported_kwargs(&kwargs, OPERATION, &["name", "model", "thinking", "kind"])?;+ let decision_child = match optional_string_kwarg(&kwargs, "kind", OPERATION)? {+ None => false,+ Some("decision") => true,+ Some(other) => {+ anyhow::bail!(+ "rlm.spawn kind must be \"decision\" when given, not {other:?}. Only the \+ Decision API child has a kind."+ )+ }+ };let name = optional_string_kwarg(&kwargs, "name", OPERATION)?;let name = normalize_requested_rlm_subagent_session_name(name, OPERATION)?;if let Some(name) = &name {@@ -505,6 +519,7 @@ fn spawn_request_from_payload(prompt: &str, data: &Value) -> anyhow::Result<RlmSname,model,thinking,+ decision_child,spawned_by_request_id: None,cell_source_code: None,})diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rsindex 221cde9b1d..6aa52a882c 100644--- a/crates/pa-core/src/session_engine/runtime_wiring.rs+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs@@ -210,6 +210,7 @@ pub fn kernel_provisioner(session_id: String,handlers: HostRequestHandlers,python_skills: Vec<KernelPythonSkill>,+ preimport_filter: crate::kernel::provisioner::PythonSkillPreimportFilter,cwd: std::path::PathBuf,agent_dir: &std::path::Path,snapshot_dir: Option<std::path::PathBuf>,@@ -233,6 +234,7 @@ pub fn kernel_provisioner(session_id: Some(session_id),host_handlers: handlers,python_skills,+ preimport_filter: Some(preimport_filter),// Only persistent sessions (which have an artifact dir) get// a revivable snapshot (TS `snapshotDir`).snapshot_dir,diff --git a/crates/pa-core/src/session_engine/session_commands.rs b/crates/pa-core/src/session_engine/session_commands.rsindex 892b5a9041..198a8fd90c 100644--- a/crates/pa-core/src/session_engine/session_commands.rs+++ b/crates/pa-core/src/session_engine/session_commands.rs@@ -1,7 +1,8 @@//! Session slash-command execution: the daemon-side behavior behind-//! `/compact`, `/refine`, `/goal`, and `/autonomous`. The host runtime owns-//! persistence of what this returns; errors carry the exact TS message and-//! the host renders the `Command failed: ...` result row.+//! `/compact`, `/refine`, `/goal`, and `/autonomous`. The+//! host runtime owns persistence of what this returns; errors carry the+//! exact TS message and the host renders the `Command failed: ...` result+//! row.use std::sync::Arc;diff --git a/crates/pa-core/src/settings/load.rs b/crates/pa-core/src/settings/load.rsindex 68d8c5dcf8..65ba0fc4d5 100644--- a/crates/pa-core/src/settings/load.rs+++ b/crates/pa-core/src/settings/load.rs@@ -33,6 +33,7 @@ const KNOWN_FIELDS: &[&str] = &["retry","providerBackupModel","imageModel",+ "decisionApi","autonomous","shellPath","quietStartup",diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rsindex b314860cef..02768961f7 100644--- a/crates/pa-core/src/settings/types.rs+++ b/crates/pa-core/src/settings/types.rs@@ -179,6 +179,16 @@ pub struct ImageSettings {pub block_images: Option<bool>,}+/// `decisionApi`: the experimental Decision API's model configuration.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DecisionApiSettings {+ /// The System 1 decision model reference ("provider/model-id" or a bare+ /// id), resolved through the model registry exactly like `imageModel`.+ /// Unset (or unresolvable): the Decision API stays off.+ pub system_one_model: Option<String>,+}+#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ThinkingBudgetsSettings {@@ -326,6 +336,8 @@ pub struct Settings {/// session model does not accept image input. Default: none - image turns on a text-only model/// fail with a configuration hint instead of silently dropping the images.pub image_model: Option<String>,+ /// The experimental Decision API's model configuration.+ pub decision_api: Option<DecisionApiSettings>,pub autonomous: Option<AutonomousSettings>,pub shell_path: Option<String>,pub quiet_startup: Option<bool>,diff --git a/crates/pa-core/tests/decision_api_live.rs b/crates/pa-core/tests/decision_api_live.rsnew file mode 100644index 0000000000..69047f3e84--- /dev/null+++ b/crates/pa-core/tests/decision_api_live.rs@@ -0,0 +1,227 @@+//! Decision API live checks: the Prime Inference clef endpoint.+//!+//! The offline pins always run: the registry recipe (baseUrl, the key from an+//! env-var name, the team header from the stored login, the vision-capable+//! `clef` model) resolves through the spawn seam, and the unset setting+//! refuses with `decide()`'s actionable message. The billed `decide()` round+//! trip is opt-in: `PA_DECISION_LIVE=1` with `PA_DECISION_LIVE_API_KEY`+//! (and `PA_DECISION_LIVE_TEAM_ID`) set, and the endpoint reachable.++use std::time::Duration;++use serde_json::{json, Value};++use pa_core::auth::AuthStorage;+use pa_core::models::{find_exact_model_reference_match, ModelRegistry};+use pa_core::session_engine::decision_api::{decision_model_selector, serve_decision_request};++const LIVE_ENV: &str = "PA_DECISION_LIVE";+const LIVE_KEY_ENV: &str = "PA_DECISION_LIVE_API_KEY";+const LIVE_TEAM_ENV: &str = "PA_DECISION_LIVE_TEAM_ID";+const ENDPOINT_HOST: &str = "api.pinference.ai";+const ENDPOINT_PORT: u16 = 443;++/// The registry recipe: the Prime Inference clef endpoint with the+/// vision-capable `clef` model. The `apiKey` is an env-var name; the+/// `X-Prime-Team-ID` header comes from the stored login's team.+fn recipe_models_json() -> String {+ r#"{ "providers": { "prime-inference": {+ "baseUrl": "https://api.pinference.ai/api/v1",+ "apiKey": "PA_DECISION_LIVE_API_KEY",+ "api": "systemone",+ "models": [ { "id": "cloudflare/clef", "input": ["text", "image"] } ]+ } } }"#+ .to_string()+}++/// One live fixture dir: the recipe's models.json, the stored login (the+/// key and team from the live env when set), and the decisionApi setting.+fn live_dir(key: Option<&str>, team: Option<&str>) -> tempfile::TempDir {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join("sessions")).unwrap();+ std::fs::write(dir.path().join("models.json"), recipe_models_json()).unwrap();+ let mut login = json!({ "prime-inference": {+ "type": "api_key",+ "key": key.unwrap_or("PA_DECISION_LIVE_API_KEY"),+ }});+ if let Some(team) = team {+ login["prime-inference"]["primeTeam"] = json!({ "teamId": team, "name": "decision live" });+ }+ std::fs::write(+ dir.path().join("auth.json"),+ serde_json::to_string(&login).unwrap(),+ )+ .unwrap();+ std::fs::write(+ dir.path().join("settings.json"),+ json!({ "decisionApi": { "systemOneModel": "prime-inference/cloudflare/clef" } })+ .to_string(),+ )+ .unwrap();+ dir+}++#[test]+fn the_clef_recipe_pins_the_spawn_seam_and_the_offline_refusals() {+ // The unset setting refuses with decide()'s actionable message — the+ // same refusal the spawn seam serves.+ let dir = live_dir(None, None);+ std::fs::write(dir.path().join("settings.json"), json!({}).to_string()).unwrap();+ let refusal = decision_model_selector(dir.path(), dir.path()).unwrap_err();+ assert!(+ refusal.starts_with("decisionApi.systemOneModel is not set in settings.json"),+ "{refusal}"+ );++ // The recipe resolves through the registry: the spawn seam's selector,+ // the vision-capable model, and the merged request auth (the env-var+ // key + the login's X-Prime-Team-ID header).+ let dir = live_dir(Some("fixture-key"), Some("fixture-team"));+ assert_eq!(+ decision_model_selector(dir.path(), dir.path()).unwrap(),+ "prime-inference/cloudflare/clef",+ "the spawn seam resolves the settings reference"+ );+ let auth = AuthStorage::create(dir.path());+ let mut registry = ModelRegistry::create(auth, dir.path().join("models.json"));+ let available: Vec<pa_types::ai::Model> =+ registry.get_available().into_iter().cloned().collect();+ let clef = find_exact_model_reference_match("cloudflare/clef", &available)+ .or_else(|| find_exact_model_reference_match("prime-inference/cloudflare/clef", &available))+ .expect("the recipe's clef model resolves")+ .clone();+ assert!(+ clef.input.contains(&pa_types::ai::ModelInput::Image),+ "the recipe's clef model is vision-capable"+ );+ assert_eq!(+ clef.api, "systemone",+ "the recipe rides the decision protocol"+ );+ let resolved = registry.get_api_key_and_headers(&clef, None);+ assert!(resolved.ok);+ assert!(resolved.api_key.is_some(), "the env-var key resolves");+ let headers = resolved.headers.expect("the login's team header merges");+ assert_eq!(+ headers.get("X-Prime-Team-ID").map(String::as_str),+ Some("fixture-team"),+ "the stored login scopes the team header"+ );++ // An unresolvable reference (the setting names a model the recipe does+ // not carry) refuses with the actionable message, never a provider call.+ std::fs::write(+ dir.path().join("settings.json"),+ json!({ "decisionApi": { "systemOneModel": "prime-inference/no-such-model" } }).to_string(),+ )+ .unwrap();+ let refusal = decision_model_selector(dir.path(), dir.path()).unwrap_err();+ assert!(+ refusal.contains("could not be resolved to an available, authenticated model"),+ "{refusal}"+ );+ assert!(+ refusal.contains("prime-inference/no-such-model"),+ "the refusal names the reference"+ );+}++/// The network-availability gate: an opted-in run (the live env set) probes+/// the endpoint before any billed call.+async fn endpoint_reachable() -> bool {+ if std::env::var_os(LIVE_ENV).as_deref() != Some(std::ffi::OsStr::new("1")) {+ eprintln!("{LIVE_ENV} not set; skipping the live clef decide round trip");+ return false;+ }+ if std::env::var_os(LIVE_KEY_ENV).is_none() {+ eprintln!("{LIVE_KEY_ENV} not set; skipping the live clef decide round trip");+ return false;+ }+ let probe = tokio::time::timeout(+ Duration::from_secs(5),+ tokio::net::TcpStream::connect((ENDPOINT_HOST, ENDPOINT_PORT)),+ )+ .await;+ if let Ok(Ok(_)) = probe {+ true+ } else {+ eprintln!("{ENDPOINT_HOST} unreachable; skipping the live clef decide round trip");+ false+ }+}++/// One end-to-end `decide()` round trip over the clef endpoint: the text+/// decision and the vision (image) decision, through the same host path the+/// decision child serves.+#[tokio::test]+async fn the_clef_endpoint_serves_the_decide_round_trip() {+ if !endpoint_reachable().await {+ return;+ }+ let key = std::env::var(LIVE_KEY_ENV).unwrap();+ let team = std::env::var(LIVE_TEAM_ENV).ok();+ let dir = live_dir(Some(&key), team.as_deref());+ let cwd = dir.path().to_path_buf();+ let agent_dir = dir.path().to_path_buf();+ let actions = json!({+ "left": "Move toward a target on the left",+ "right": "Move toward a target on the right",+ "wait": "Do nothing while already aligned",+ });+ let request = json!({+ "state": { "observation": { "target_direction": "left" }, "goal": "Move toward the target" },+ "questions": { "action": {+ "type": "choice",+ "instructions": "Choose the next action that best advances the goal given the observation.",+ "criteria": actions,+ } }+ });+ let answer = serve_decision_request(request.clone(), &cwd, &agent_dir)+ .await+ .expect("the live clef decide round trip");+ assert_eq!(+ answer["model"], "prime-inference/cloudflare/clef",+ "{answer}"+ );+ let decision = &answer["answers"]["action"];+ let choice = decision["choice"].as_str().unwrap();+ assert!(+ ["left", "right", "wait"].contains(&choice),+ "the choice names a requested action: {decision}"+ );+ let confidence = decision["confidence"].as_f64().unwrap();+ assert!(+ (0.0..=1.0).contains(&confidence),+ "confidence stays in 0..=1: {decision}"+ );+ eprintln!("live clef text decision: {decision}");++ // The vision path: one small real PNG rides as an image block.+ let request = json!({+ "state": { "observation": { "frame": "a small red square centered" }, "goal": "Move toward the target" },+ "questions": { "action": {+ "type": "choice",+ "instructions": "Choose the next action that best advances the goal given the observation.",+ "criteria": actions,+ } },+ "images": [ format!("data:image/png;base64,{}", RED_SQUARE_PNG) ],+ });+ let answer = serve_decision_request(request, &cwd, &agent_dir)+ .await+ .expect("the live clef vision decide round trip");+ assert_eq!(+ answer["model"], "prime-inference/cloudflare/clef",+ "{answer}"+ );+ let decision = &answer["answers"]["action"];+ let choice = decision["choice"].as_str().unwrap();+ assert!(+ ["left", "right", "wait"].contains(&choice),+ "the vision choice names a requested action: {decision}"+ );+ eprintln!("live clef vision decision: {decision}");+ let _ = Value::Null;+}++/// A small (8x8) solid-red PNG: real image bytes, not a degenerate 1x1.+const RED_SQUARE_PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEUlEQVR42mP4z8CAFTEMLQkAKP8/wc53yE8AAAAASUVORK5CYII=";diff --git a/crates/pa-core/tests/prompt_guards.rs b/crates/pa-core/tests/prompt_guards.rsindex 6496cc1b90..0a9654cfc2 100644--- a/crates/pa-core/tests/prompt_guards.rs+++ b/crates/pa-core/tests/prompt_guards.rs@@ -150,9 +150,10 @@ const INTERNAL_HOST_REQUESTS: &[&str] =&["model.info", "mcp.config", "mcp.refresh", "mcp.begin_login"];/// Map one registered host-request type to the prompt token that documents-/// it. `None` when the request is host-internal.+/// it. `None` when the request is host-internal or belongs to a gated skill.fn prompt_token_for_host_request(request: &str) -> Option<String> {- if INTERNAL_HOST_REQUESTS.contains(&request) {+ let module = request.split('.').next().unwrap_or_default();+ if INTERNAL_HOST_REQUESTS.contains(&request) || gated_bundled_skills().contains(module) {return None;}Some(@@ -340,20 +341,22 @@ fn python_skill_functions(package_path: &Path) -> Vec<String> {functions}-/// Bundled skills that are auth-gated builtin MCP integrations: they are disabled in sessions whose-/// user is not logged into the integration, so the prompt documents them only through the dynamic-/// skills inventory (and its generic "additional skills may exist" note), not as API surface.-fn auth_gated_bundled_skills() -> BTreeSet<String> {+/// Bundled skills that are gated: the auth-gated builtin MCP integrations+/// (disabled when the user is not logged in) and the Decision API (hidden+/// while decisionApi.systemOneModel is unset). The prompt documents them only+/// through the dynamic skills inventory, not as API surface.+fn gated_bundled_skills() -> BTreeSet<String> {pa_core::mcp::BUILTIN_MCP_CATALOG.iter().map(|(server, _, _)| server.to_string())+ .chain(std::iter::once("decision_api".to_string())).collect()}/// (import name, public functions) for every bundled Python skill that is-/// always available (auth-gated integrations excluded).+/// always available (gated skills excluded).fn bundled_python_skills() -> Vec<(String, Vec<String>)> {- let gated = auth_gated_bundled_skills();+ let gated = gated_bundled_skills();sorted_bundled_skills().into_iter().filter(|skill| {@@ -498,6 +501,8 @@ const TS_PACKAGED_SKILL_SET: &[&str] = &["agent-observe","attach-image","compact",+ // Experimental, no TS counterpart yet.+ "decision-api","edit","goal","mcp",diff --git a/crates/pa-daemon/README.md b/crates/pa-daemon/README.mdindex 3000ef68d7..ae7e0f8f8e 100644--- a/crates/pa-daemon/README.md+++ b/crates/pa-daemon/README.md@@ -257,6 +257,16 @@ attached UIs daemon-wide).## Non-goalsNo agent behavior inside workers beyond hosting a pa-core engine; no UI.+The Decision API child (`rlm.spawn(kind="decision")`) runs the decision+engine: one spawned session whose every message is one decision request —+served by the `decisionApi.systemOneModel` model through the ordinary+provider transports (the shared pa-core decision path), with the parent's+tagged goal messages routed into its goal input (the newest seq wins) and+each answer returned to the parent as a tagged `decision_api.decision`+message the loop awaits. The spawn resolves the child's model through the+registry and refuses with the setting's actionable message while it is+unset or unresolvable.+## Public APISupervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_worker_mcp_login}` (the worker's browser+callback login behind `mcp.begin_login`; wired by the agent engine before sessions register host handlers), client connection API for pa-tui/pa-cli, `acp::daemon::{run_daemon_attached_acp_mode, DaemonAcpOptions}` (pa-cli dispatches `--mode acp` through it), `agent_messaging::LinkAgentMessageController` + `rlm_children::{SupervisorChildSessions, ParentIdentity, RlmChildIdentity}` (e2e verifiers construct the worker-side family controller and the children registry; the engine wires the same types), `agent_engine::AgentSessionEngine::dispose_kernel` (the session-end kernel teardown the worker invokes at kill/shutdown/orphan exit — the engine outlives the session, so the pa-core engine-drop teardown cannot run there), the worker's `get_mcp_connections` command (`mcp_connections.rs`: the `/mcp` view's roster from the session's MCP manager overlaid with the session kernel's per-server tool listing, plus the api-key credential rows the same response serves — Rust-native session-plane extension; the TS daemon has no counterpart). Supervision internals `pub(crate)`.@@ -264,6 +274,12 @@ Supervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_wo## Depends onpa-types, pa-core (one-way).+Attach snapshots derive the Decision API state from the selected session-store+branch, including the window's pre-compaction metadata. This private store getter+runs before the lazy session engine builds and never resolves auth, models, or the+kernel. Branch replacement changes the next snapshot immediately; explicit off+and malformed status rows clear earlier state.+The composition root initializes the packaged product version with`protocol::configure_app_version` before entering daemon or worker mode.`protocol::app_version` supplies that identity to both hello frames and updatediff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex 8dc23d855e..0626bbc383 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -101,6 +101,10 @@ pub(crate) type SettledKernelRelease =/// A [`SessionEngine`] running real agent turns.pub struct AgentSessionEngine {+ /// Latest decision reply per live decision child; shared with its kernel+ /// host handler (`decision_api.decision`).+ pub(crate) decision_replies:+ Arc<std::sync::Mutex<std::collections::HashMap<String, Option<Value>>>>,pub(crate) runtime: crate::async_safe_runtime::AsyncSafeRuntime,pub(crate) config: AgentEngineConfig,/// The session-scoped ACP MCP store, shared with the core engine's prompt gating.diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex fbdfe10e63..02ad5de033 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -125,6 +125,7 @@ impl AgentSessionEngine {// unseeded (None keeps the TS default "one-at-a-time").let queue_modes = std::sync::Mutex::new((None, None));Ok(Self {+ decision_replies: Arc::default(),runtime,config,mcp,@@ -493,6 +494,9 @@ impl AgentSessionEngine {}if let Some(entries) = pending_branch {built.session.rebuild_branch_context(entries).await?;+ // The Decision API follows the adopted context: the provider+ // row the restored branch carries becomes the session's switch+ // before the engine is installed and any turn runs.// A moved branch restores its own park (the early return would leave the previous// branch's park armed).self.restore_quota_park(built).await;@@ -776,6 +780,31 @@ impl AgentSessionEngine {self.children.clone(),));let mut handlers = HostRequestHandlers::default();+ let replies = Arc::clone(&self.decision_replies);+ handlers.register(+ "decision_api.decision",+ pa_core::kernel::shared::host_handler(move |payload| {+ let replies = Arc::clone(&replies);+ Box::pin(async move {+ let name = payload.data["name"].as_str().ok_or_else(|| {+ anyhow::anyhow!("decision_api.decision requires a child name")+ })?;+ let mut replies = replies+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if payload.data["close"] == true {+ replies.remove(name);+ Ok(Value::Null)+ } else {+ Ok(replies+ .entry(name.to_string())+ .or_default()+ .take()+ .unwrap_or(Value::Null))+ }+ })+ }),+ );register_agent_message_host_handlers(sender, &mut handlers);register_agent_observe_host_handlers(observer, &mut handlers);self.register_bash_notice_host_handlers(&mut handlers);@@ -814,7 +843,7 @@ impl AgentSessionEngine {})}- async fn build_session(&self, model: &Model) -> anyhow::Result<CoreSessionEngine> {+ pub(super) async fn build_session(&self, model: &Model) -> anyhow::Result<CoreSessionEngine> {let agent_model =json_round_trip(model).ok_or_else(|| anyhow::anyhow!("model conversion failed"))?;// The live queue-delivery modes: read under a scoped lock (a std@@ -872,6 +901,7 @@ impl AgentSessionEngine {}None => pa_core::session::manager::SessionManager::in_memory(&cwd),};+if let Some(children) = &self.children {children.set_model(format!("{}/{}", model.provider, model.id));}@@ -1000,3 +1030,90 @@ impl AgentSessionEngine {})}}++#[cfg(test)]+mod decision_reply_tests {+ use super::*;+ use crate::worker::{Worker, WorkerConfig};+ use pa_core::kernel::shared::HostRequestPayload;+ use serde_json::json;++ #[tokio::test]+ async fn child_decision_replies_reach_the_loop_without_queuing_a_parent_turn() {+ let dir = tempfile::tempdir().unwrap();+ let worker = Worker::new(+ WorkerConfig {+ socket_path: dir.path().join("worker.sock"),+ supervisor_socket_path: dir.path().join("supervisor.sock"),+ token: "token".into(),+ worker_instance_id: String::new(),+ active_session_id: "parent".into(),+ agent_dir: dir.path().join("agent"),+ recovery_journal_path: dir.path().join("recovery.jsonl"),+ telemetry_disabled: Some(true),+ script: None,+ decision_child: false,+ },+ /*registration*/ None,+ );+ let created = worker+ .dispatch("create", &json!({"noSession":true,"cwd":dir.path()}))+ .await;+ assert!(created.success);+ let handlers = worker+ .agent_engine+ .as_ref()+ .unwrap()+ .extra_host_handlers()+ .unwrap();+ let poll = handlers+ .get("decision_api.decision")+ .expect("decision route registered");+ let call = |data| {+ poll(HostRequestPayload {+ data,+ cell_source_code: None,+ })+ };+ assert_eq!(+ call(json!({"name":"system-1-test"})).await.unwrap(),+ Value::Null+ );+ let decision = json!({+ "type":"decision_api.decision","seq":0,+ "decision":{"action":"left","confidence":0.9}+ });+ let mut delivery = json!({"message":decision.to_string(),"sender":{+ "activeSessionId":"child","sessionName":"system-1-test",+ "parentActiveSessionId":"parent","runtimeKind":"subagent"+ }});+ worker.core.lock().unwrap().busy = true;+ assert!(worker.handle_worker_deliver_message(&delivery).success);+ assert_eq!(+ call(json!({"name":"system-1-test"})).await.unwrap(),+ decision+ );+ assert_eq!(+ call(json!({"name":"system-1-test"})).await.unwrap(),+ Value::Null+ );+ assert!(worker.core.lock().unwrap().steering.is_empty());+ assert!(worker.core.lock().unwrap().follow_up.is_empty());+ worker.core.lock().unwrap().busy = false;+ call(json!({"name":"system-1-test","close":true}))+ .await+ .unwrap();+ assert!(worker.handle_worker_deliver_message(&delivery).success);+ assert!(+ worker.core.lock().unwrap().steering.is_empty(),+ "a closed decision child must not wake the parent"+ );+ delivery["sender"]["parentActiveSessionId"] = json!("another-parent");+ assert!(worker.handle_worker_deliver_message(&delivery).success);+ assert_eq!(+ worker.core.lock().unwrap().steering.len(),+ 1,+ "other agents retain normal routing"+ );+ }+}diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex 8c6f774cbe..f5d51ffa2b 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -9,9 +9,37 @@ use super::{ParentIdentity, PromptRequest, ProviderTarget, SessionEngine, SideQuestionOutcome,SideQuestionRequest, StartupScope, TurnPrompt, Value, DEFAULT_RLM_MAX_DEPTH,};+use pa_core::session_engine::agent_messaging::AgentFamilyRelationship;impl SessionEngine for AgentSessionEngine {- /// Withdraw the queued minted goal-context turns so a state change leaves nothing stale to run.+ fn route_decision_api_event(+ &self,+ relationship: Option<AgentFamilyRelationship>,+ sender_name: &str,+ message: &str,+ ) -> bool {+ if relationship != Some(AgentFamilyRelationship::Child) {+ return false;+ }+ let Ok(decision) = serde_json::from_str::<Value>(message) else {+ return false;+ };+ if decision["type"] != "decision_api.decision" {+ return false;+ }+ if let Some(slot) = self+ .decision_replies+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .get_mut(sender_name)+ {+ *slot = Some(decision);+ }+ true+ }+ /// TS `_clearQueuedGoalContexts`: the worker-installed purge withdraws+ /// the queued minted goal-context turns (pause/clear/start must not+ /// leave a stale continuation to run after the state change). /// Withdraw the queued minted goal-context turns so a state change leaves nothing stale to run.fn purge_queued_goal_contexts(&self) {let purge = self.goal_queue_purgediff --git a/crates/pa-daemon/src/agent_engine/tests/session.rs b/crates/pa-daemon/src/agent_engine/tests/session.rsindex e74aae2ffd..2e3e199c46 100644--- a/crates/pa-daemon/src/agent_engine/tests/session.rs+++ b/crates/pa-daemon/src/agent_engine/tests/session.rs@@ -2,6 +2,56 @@use super::*;use crate::engine::PromptBatchRow;+#[test]+fn constructor_reordering_keeps_completed_goals_after_later_errors() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("completed.jsonl");+ let mut store = crate::session_store::SessionFile::create("/tmp", None, 0);+ store.set_path(path.clone());+ let completed = pa_core::goals::GoalState {+ status: pa_core::goals::GoalStatus::Complete,+ objective: Some("finished".to_string()),+ ..pa_core::goals::empty_goal_state()+ };+ store.append_entry(+ "custom",+ json!({"customType":pa_core::goals::GOAL_STATE_CUSTOM_TYPE,"data":completed}),+ );+ let mut kept = String::new();+ for i in 0..12 {+ let id = store+ .append_message(&json!({"role":"user","content":format!("message {i}"),"timestamp":i}));+ if i == 8 {+ kept = id;+ }+ }+ store.append_entry(+ "compaction",+ json!({"summary":"summary","firstKeptEntryId":kept,"tokensBefore":1000}),+ );+ store.append_message(+ &json!({"role":"assistant","provider":"test","model":"test","api":"openai-completions",+ "content":[],"stopReason":"error","errorMessage":"later failure","timestamp":1}),+ );+ store.rewrite().unwrap();+ let engine = bare_engine(dir.path());+ *engine.session_file.lock().unwrap() = Some(path);+ let model: pa_types::ai::Model = serde_json::from_value(json!({+ "id":"test","name":"test","api":"openai-completions","provider":"test",+ "baseUrl":"http://127.0.0.1:9","reasoning":false,"input":["text"],+ "cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0},+ "contextWindow":1000,"maxTokens":100,+ }))+ .unwrap();+ engine+ .runtime+ .block_on(engine.ensure_core_session_async(&model))+ .unwrap();+ let restored: pa_core::goals::GoalState =+ serde_json::from_value(engine.goal_state_value()).unwrap();+ assert_eq!(restored, completed);+}+/// `get_commands` enumerates the session's skills as `skill:<name>`/// commands, including before the first prompt (the read seam demand-builds/// the core session). The faux provider registers under `FAUX_TEST_LOCK`diff --git a/crates/pa-daemon/src/agent_message_ingest.rs b/crates/pa-daemon/src/agent_message_ingest.rsindex 61217409a3..f0f1846c11 100644--- a/crates/pa-daemon/src/agent_message_ingest.rs+++ b/crates/pa-daemon/src/agent_message_ingest.rs@@ -173,6 +173,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/decision_engine.rs b/crates/pa-daemon/src/decision_engine.rsnew file mode 100644index 0000000000..5d443bb835--- /dev/null+++ b/crates/pa-daemon/src/decision_engine.rs@@ -0,0 +1,449 @@+//! The Decision API child engine (`rlm.spawn kind="decision"`): a spawned+//! session whose every message is one decision request, answered by a+//! single decision model call — the registry-resolved+//! `decisionApi.systemOneModel` model through the ordinary provider+//! transports. The parent's tagged goal messages route into the engine's+//! goal input (the newest seq wins; an older goal never overwrites a newer+//! one), and each answer returns to the parent as a tagged+//! `decision_api.decision` message the loop awaits.++use std::path::PathBuf;+use std::sync::{Arc, Mutex, PoisonError};++use anyhow::anyhow;+use serde_json::{json, Value};++use crate::agent_messaging::LinkAgentMessageController;+use crate::async_safe_runtime::AsyncSafeRuntime;+use crate::engine::{+ AssistantSnapshot, BranchSummaryOutcome, BranchSummaryRequest, CompactionOutcome,+ CompactionRequest, EngineEvent, PromptRequest, SessionEngine, SideQuestionOutcome,+ SideQuestionRequest,+};+use pa_core::session_engine::agent_messaging::{+ AgentFamilyRelationship, AgentMessageController, AgentMessageSendInput,+};+use pa_core::session_engine::side_question::SideQuestionSink;++/// One stored goal: the seq contract lives in the routing seam — a goal with+/// an older seq than the stored one loses.+#[derive(Debug, Clone)]+struct StoredGoal {+ seq: i64,+ goal: Option<String>,+}++impl Default for StoredGoal {+ fn default() -> Self {+ Self {+ seq: i64::MIN,+ goal: None,+ }+ }+}++/// The decision child's engine.+pub struct DecisionEngine {+ cwd: PathBuf,+ agent_dir: PathBuf,+ /// The latest goal message; shared with the worker's routing seam.+ goals: Arc<Mutex<StoredGoal>>,+ /// The spawn's protocol prompt (the child's decision instructions).+ protocol: Mutex<Option<String>>,+ /// The tagged-reply sender over the supervisor link.+ sender: Arc<LinkAgentMessageController>,+ /// The sender's identity source: the worker's session summary.+ own_summary: Arc<Mutex<Option<Value>>>,+ /// The engine's own runtime: the decision call and the reply send are+ /// async, `run_prompt` is not.+ runtime: AsyncSafeRuntime,+}++impl DecisionEngine {+ /// Build the engine over the worker's supervisor link; the worker's+ /// session summary (pushed through `set_session_summary`) becomes the+ /// sender identity.+ ///+ /// # Panics+ ///+ /// Panics when the engine runtime cannot start.+ pub fn new(+ cwd: PathBuf,+ agent_dir: PathBuf,+ link: Arc<crate::supervisor_link::SupervisorLink>,+ active_session_id: String,+ worker_token: String,+ ) -> Self {+ let own_summary: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));+ let sender = Arc::new(LinkAgentMessageController::new(+ link,+ active_session_id,+ worker_token,+ Arc::clone(&own_summary),+ None,+ ));+ Self {+ own_summary,+ cwd,+ agent_dir,+ goals: Arc::new(Mutex::new(StoredGoal::default())),+ protocol: Mutex::new(None),+ sender,+ runtime: AsyncSafeRuntime::new_multi_thread().expect("decision engine runtime"),+ }+ }++ /// The routing seam's goal contract: a `decision_api.goal` message is+ /// consumed without a turn, and a goal with an older-or-equal seq than+ /// the stored one loses — only a newer goal updates the input.+ fn accept_goal(&self, message: &str) -> bool {+ let Ok(goal) = serde_json::from_str::<Value>(message) else {+ return false;+ };+ if goal["type"] != "decision_api.goal" {+ return false;+ }+ let Some(seq) = goal["seq"].as_i64() else {+ // A malformed goal still carries the tag: consume, never a turn.+ return true;+ };+ let goal = goal.get("goal").and_then(Value::as_str).map(str::to_string);+ let mut stored = self.goals.lock().unwrap_or_else(PoisonError::into_inner);+ if seq > stored.seq {+ *stored = StoredGoal { seq, goal };+ }+ true+ }++ /// The latest goal text (the `decide()` call reads it into the state).+ fn latest_goal(&self) -> Option<String> {+ let stored = self.goals.lock().unwrap_or_else(PoisonError::into_inner);+ stored.goal.clone().filter(|goal| !goal.is_empty())+ }++ /// The raw delivered body: the agent-message row carries it in+ /// `details.message`; a plain prompt is its own body.+ fn raw_message(request: &PromptRequest) -> &str {+ request+ .custom_message+ .as_ref()+ .and_then(|row| row.get("details"))+ .and_then(|details| details.get("message"))+ .and_then(Value::as_str)+ .unwrap_or(&request.message)+ }++ /// Send one tagged reply to the parent through the supervisor link.+ fn send_reply(&self, message: &Value) -> anyhow::Result<()> {+ let sender = Arc::clone(&self.sender);+ let message = message.to_string();+ self.runtime.block_on(async move {+ let family = sender.family().await?;+ let parent = family+ .into_iter()+ .find(|member| member.relationship == AgentFamilyRelationship::Parent)+ .ok_or_else(|| anyhow!("the decision child has no parent in its family roster"))?;+ sender+ .send_agent_message(AgentMessageSendInput {+ target: parent.id,+ message,+ receiver_role: Some(AgentFamilyRelationship::Parent),+ })+ .await+ .map(|_| ())+ })+ }++ /// Serve one decision request message: inject the latest goal into the+ /// state, then run the shared decision path (the registry resolution+ /// and one provider completion).+ fn serve(&self, mut request: Value) -> anyhow::Result<Value> {+ if let Some(goal) = self.latest_goal() {+ if let Some(state) = request.get_mut("state").and_then(Value::as_object_mut) {+ state.insert("goal".to_string(), json!(goal));+ }+ }+ let cwd = self.cwd.clone();+ let agent_dir = self.agent_dir.clone();+ self.runtime.block_on(async move {+ pa_core::session_engine::decision_api::serve_decision_request(request, &cwd, &agent_dir)+ .await+ })+ }++ /// The child's resolved model label (the transcript rows).+ fn model_label(&self) -> String {+ pa_core::session_engine::decision_api::decision_model_selector(&self.cwd, &self.agent_dir)+ .unwrap_or_default()+ }++ /// The transcript row pair for an answer: the assistant update and the+ /// final message.+ fn answer_rows(provider: &str, model: &str, text: &str) -> (EngineEvent, EngineEvent) {+ let now = crate::util::now_ms();+ (+ EngineEvent::AssistantUpdate {+ message: AssistantSnapshot::Wire(json!({+ "role": "assistant", "content": "",+ "provider": provider, "model": model,+ "timestamp": now,+ })),+ stream_event: None,+ },+ EngineEvent::AssistantMessage(json!({+ "role": "assistant", "content": text,+ "provider": provider, "model": model,+ "timestamp": now,+ })),+ )+ }+}++impl SessionEngine for DecisionEngine {+ /// Consume the parent's tagged goal messages: no turn, newest seq wins.+ fn route_decision_api_event(+ &self,+ _relationship: Option<AgentFamilyRelationship>,+ _sender_name: &str,+ message: &str,+ ) -> bool {+ self.accept_goal(message)+ }++ /// The worker's live session summary: the sender identity block of the+ /// tagged replies.+ fn set_session_summary(&self, summary: Value) {+ *self+ .own_summary+ .lock()+ .unwrap_or_else(PoisonError::into_inner) = Some(summary);+ }++ fn run_side_question(+ &self,+ _request: SideQuestionRequest,+ _signal: &pa_agent::abort::AbortSignal,+ _sink: &SideQuestionSink,+ ) -> SideQuestionOutcome {+ SideQuestionOutcome::Failed {+ answer: String::new(),+ error: "a decision child answers decision requests only".to_string(),+ }+ }++ fn run_compaction(+ &self,+ _request: CompactionRequest,+ _signal: &pa_agent::abort::AbortSignal,+ ) -> CompactionOutcome {+ CompactionOutcome::Failed {+ error: "a decision child has no conversation to compact".to_string(),+ }+ }++ fn run_branch_summary(+ &self,+ _request: BranchSummaryRequest,+ _signal: &pa_agent::abort::AbortSignal,+ ) -> BranchSummaryOutcome {+ BranchSummaryOutcome::Failed {+ error: "a decision child has no branches to summarize".to_string(),+ }+ }++ fn rebuild_session_context(+ &self,+ _branch_entries: Vec<pa_types::session::FileEntry>,+ _goal_reload: pa_core::session_engine::goal_driver::GoalBranchReload,+ ) -> anyhow::Result<()> {+ Ok(())+ }++ fn run_prompt(+ &self,+ _prompt_index: usize,+ request: PromptRequest,+ aborted: &dyn Fn() -> bool,+ emit: &mut dyn FnMut(EngineEvent) -> bool,+ ) {+ let cancelled = || EngineEvent::Done(Err("prompt cancelled".to_string()));+ // The accepted row: the injected agent-message row, or the plain prompt.+ let accepted_row = match &request.custom_message {+ Some(custom) => custom.clone(),+ None => json!({+ "role": "user",+ "content": request.message.clone(),+ "timestamp": crate::util::now_ms(),+ }),+ };+ let accepted = match &request.custom_message {+ Some(_) => EngineEvent::CustomMessage(accepted_row.clone()),+ None => EngineEvent::UserMessage(accepted_row.clone()),+ };+ if !emit(accepted) {+ emit(cancelled());+ return;+ }+ if aborted() {+ emit(cancelled());+ return;+ }+ let raw = Self::raw_message(&request).to_string();+ // A decision request carries "questions"; anything else is the+ // spawn's protocol prompt (the child's decision instructions).+ let parsed: Option<Value> = serde_json::from_str(&raw).ok();+ let is_request = parsed+ .as_ref()+ .is_some_and(|value| value.get("questions").is_some());+ if !is_request {+ *self.protocol.lock().unwrap_or_else(PoisonError::into_inner) = Some(raw);+ let (update, message) =+ Self::answer_rows("decision", "system-1", "Decision child ready.");+ for event in [update, message] {+ if !emit(event) {+ emit(cancelled());+ return;+ }+ }+ emit(EngineEvent::Done(Ok(())));+ return;+ }+ let mut body = parsed.expect("checked above");+ let Some(seq) = body.get("seq").and_then(Value::as_i64) else {+ emit(EngineEvent::Done(Err(+ "a decision request must carry an integer \"seq\" for its reply".to_string(),+ )));+ return;+ };+ if let Some(body) = body.as_object_mut() {+ body.remove("seq");+ }+ let model_label = self.model_label();+ let (provider, model) = model_label.split_once('/').map_or_else(+ || ("decision".to_string(), "system-1".to_string()),+ |(provider, model)| (provider.to_string(), model.to_string()),+ );+ match self.serve(body) {+ Ok(envelope) => {+ let reply = json!({+ "type": "decision_api.decision",+ "seq": seq,+ "model": envelope.get("model").cloned().unwrap_or(json!(model_label)),+ "decision": envelope["answers"]["action"].clone(),+ });+ if let Err(error) = self.send_reply(&reply) {+ emit(EngineEvent::Done(Err(format!(+ "the decision reply could not reach the parent: {error:#}"+ ))));+ return;+ }+ let text = envelope["answers"].to_string();+ let (update, final_message) = Self::answer_rows(&provider, &model, &text);+ for event in [update, final_message.clone()] {+ if !emit(event) {+ emit(cancelled());+ return;+ }+ }+ let EngineEvent::AssistantMessage(turn_message) = final_message else {+ unreachable!("answer_rows returns an AssistantMessage");+ };+ if !emit(EngineEvent::TurnEnd {+ message: turn_message,+ tool_results: Vec::new(),+ }) {+ emit(cancelled());+ return;+ }+ if !emit(EngineEvent::AgentEnd {+ messages: vec![accepted_row],+ }) {+ emit(cancelled());+ return;+ }+ emit(EngineEvent::Done(Ok(())));+ }+ Err(error) => {+ // The failure reaches the loop as a tagged error reply, so+ // its await fails fast instead of timing out.+ let reply = json!({+ "type": "decision_api.decision",+ "seq": seq,+ "error": format!("{error:#}"),+ });+ let _ = self.send_reply(&reply);+ emit(EngineEvent::Done(Err(format!(+ "the decision failed: {error:#}"+ ))));+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn engine(dir: &std::path::Path) -> DecisionEngine {+ let link = Arc::new(crate::supervisor_link::SupervisorLink::new(+ std::path::PathBuf::new(),+ ));+ DecisionEngine::new(+ dir.to_path_buf(),+ dir.to_path_buf(),+ link,+ "decision-child".to_string(),+ "token".to_string(),+ )+ }++ /// The seq contract, pinned: an old goal arriving after a newer one+ /// loses — the routing seam keeps the newest seq.+ #[test]+ fn an_older_goal_never_overwrites_a_newer_one() {+ let dir = tempfile::tempdir().unwrap();+ let engine = engine(dir.path());+ let goal = |seq: i64, text: &str| {+ json!({"type":"decision_api.goal","seq":seq,"goal":text}).to_string()+ };+ assert!(engine.accept_goal(&goal(3, "first")));+ assert_eq!(engine.latest_goal().as_deref(), Some("first"));+ // An older goal arrives late: it loses, and it still starts no turn.+ assert!(engine.accept_goal(&goal(1, "stale")));+ assert_eq!(engine.latest_goal().as_deref(), Some("first"));+ // A newer goal wins.+ assert!(engine.accept_goal(&goal(4, "second")));+ assert_eq!(engine.latest_goal().as_deref(), Some("second"));+ // A goal without a goal field clears the guidance but consumes the message.+ assert!(engine.accept_goal(&json!({"type":"decision_api.goal","seq":5}).to_string()));+ assert_eq!(engine.latest_goal(), None);+ // Untagged messages are not consumed; neither are the reply tags.+ assert!(!engine.accept_goal("ordinary message"));+ assert!(!engine.accept_goal(&json!({"type":"decision_api.decision","seq":9}).to_string()));+ }++ /// The intake parse: the request must carry an integer seq, and the+ /// message-sourced goal reaches the state through the seam.+ #[test]+ fn a_decision_request_reads_the_message_sourced_goal() {+ let dir = tempfile::tempdir().unwrap();+ let engine = engine(dir.path());+ let request = json!({+ "seq": 7,+ "state": {"observation": 1},+ "questions": {"action": {+ "type": "choice", "criteria": {"left": "go left", "right": "go right"}+ }}+ });+ assert!(engine.accept_goal(+ &json!({+ "type":"decision_api.goal","seq":2,"goal":"follow the target"+ })+ .to_string()+ ));+ // The goal flows through latest_goal into the served state; the+ // request itself stays untouched until the serve call.+ assert_eq!(engine.latest_goal().as_deref(), Some("follow the target"));+ assert_eq!(request["seq"], json!(7));+ }+}diff --git a/crates/pa-daemon/src/descriptor.rs b/crates/pa-daemon/src/descriptor.rsindex 5761a1d65c..7ecdb40bab 100644--- a/crates/pa-daemon/src/descriptor.rs+++ b/crates/pa-daemon/src/descriptor.rs@@ -100,6 +100,18 @@ pub fn worker_launch_env(if let Some(script) = script {env.insert(crate::worker::WORKER_SCRIPT_ENV.to_string(), script);}+ if descriptor+ .create_command+ .rest+ .get("decisionChild")+ .and_then(Value::as_bool)+ == Some(true)+ {+ env.insert(+ crate::worker::WORKER_DECISION_CHILD_ENV.to_string(),+ "1".to_string(),+ );+ }if let Some(dir) = &descriptor.session_dir {env.insert(crate::paths::SESSION_DIR_ENV.to_string(), dir.clone());}diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rsindex a8b7a9f7c9..f6abd6ade5 100644--- a/crates/pa-daemon/src/engine.rs+++ b/crates/pa-daemon/src/engine.rs@@ -7,6 +7,7 @@ use std::sync::Arc;use anyhow::Result;use pa_agent::abort::AbortSignal;+use pa_core::session_engine::agent_messaging::AgentFamilyRelationship;use pa_core::session_engine::provider_adapter::json_round_trip;use pa_core::session_engine::provider_retry::{ProviderRetryPolicy, UNBOUNDED_BACKOFF_MS};use pa_core::session_engine::side_question::{SideQuestionSink, SideQuestionTurn};@@ -29,7 +30,26 @@ mod scripted;/// The turn behavior a worker session runs.pub trait SessionEngine: Send + Sync {- /// The session's shared MCP manager, when the engine owns one: the+ /// Consume one tagged Decision API message without starting a turn: the+ /// parent's engine consumes its decision child's `decision_api.decision`+ /// replies into its per-child slots, and the decision child consumes the+ /// parent's `decision_api.goal` messages into its goal input. Engines+ /// without decision loops use normal message routing. `relationship` is+ /// the sender's edge to this session (`None` for a parent or an+ /// unaffiliated sender — the deliver path computes child edges only).+ fn route_decision_api_event(+ &self,+ _relationship: Option<AgentFamilyRelationship>,+ _sender_name: &str,+ _message: &str,+ ) -> bool {+ false+ }+ /// The session's shared MCP manager, when the engine owns one (the+ /// real agent engine does; scripted harness engines do not). The+ /// `replace_acp_mcp_servers` command writes through it so+ /// ACP-admitted servers reach the prompt's MCP gating — the same+ /// store the core engine gates with. /// The session's shared MCP manager, when the engine owns one: the/// `replace_acp_mcp_servers` command writes through it.fn acp_mcp_manager(&self,diff --git a/crates/pa-daemon/src/lib.rs b/crates/pa-daemon/src/lib.rsindex 05686a3c22..c8ecfa2874 100644--- a/crates/pa-daemon/src/lib.rs+++ b/crates/pa-daemon/src/lib.rs@@ -43,6 +43,7 @@ pub(crate) mod compaction_supervision;pub(crate) mod context_tree_cache;pub(crate) mod context_tree_children;pub(crate) mod create_reuse;+pub(crate) mod decision_engine;pub mod descriptor;pub mod engine;pub(crate) mod factory_activity;diff --git a/crates/pa-daemon/src/model_catalog.rs b/crates/pa-daemon/src/model_catalog.rsindex 40d2fb6660..f199a27373 100644--- a/crates/pa-daemon/src/model_catalog.rs+++ b/crates/pa-daemon/src/model_catalog.rs@@ -431,6 +431,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let events = worker.events.subscribe();diff --git a/crates/pa-daemon/src/model_switch.rs b/crates/pa-daemon/src/model_switch.rsindex b8fdc7743e..26b9652d8a 100644--- a/crates/pa-daemon/src/model_switch.rs+++ b/crates/pa-daemon/src/model_switch.rs@@ -261,6 +261,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,}}diff --git a/crates/pa-daemon/src/queue_commands.rs b/crates/pa-daemon/src/queue_commands.rsindex 136a42f239..9b52484e6e 100644--- a/crates/pa-daemon/src/queue_commands.rs+++ b/crates/pa-daemon/src/queue_commands.rs@@ -248,6 +248,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/registration.rs b/crates/pa-daemon/src/registration.rsindex a131b20d3e..52dda613f9 100644--- a/crates/pa-daemon/src/registration.rs+++ b/crates/pa-daemon/src/registration.rs@@ -349,6 +349,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: None,+ decision_child: false,}}diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rsindex 35c1b0113e..5618be236a 100644--- a/crates/pa-daemon/src/rlm_children/host.rs+++ b/crates/pa-daemon/src/rlm_children/host.rs@@ -86,19 +86,45 @@ impl RlmSubagentHost for SupervisorChildSessions {let admission = async {this.assert_name_available(&name, identity.rlm_depth + 1).await?;- let model = resolve_child_model_allowlisted(- &this,- request.model.as_deref(),- "spawn",- "subagent",- )- .await?;+ let cwd_path = identity+ .cwd+ .clone()+ .unwrap_or_else(|| "/".to_string())+ .clone();+ let cwd = cwd_path.clone();+ // A decision child runs the settings decision model: the+ // spawn refuses with the same actionable message decide()+ // serves while the setting is unset or unresolvable, then+ // resolves through the ordinary child-model path so the+ // allowlist still gates the selector.+ let model = if request.decision_child {+ let selector = pa_core::session_engine::decision_api::decision_model_selector(+ std::path::Path::new(&cwd_path),+ &this.agent_dir,+ )+ .map_err(anyhow::Error::msg)?;+ let selector = resolve_child_model_allowlisted(+ &this,+ Some(&selector),+ "spawn",+ "subagent",+ )+ .await?;+ selector+ } else {+ resolve_child_model_allowlisted(+ &this,+ request.model.as_deref(),+ "spawn",+ "subagent",+ )+ .await?+ };assert_thinking_supported(&this.agent_dir, request.thinking.as_deref(), &model)?;let thinking = request.thinking.as_deref().or(identity.thinking.as_deref());let child_dir = this.child_session_dir(&child_id, &identity)?;- let cwd = identity.cwd.clone().unwrap_or_else(|| "/".to_string());let runtime_metadata = json!({- "kind": "subagent",+ "kind": if request.decision_child { "decision" } else { "subagent" },"rlmChildId": child_id,"parentActiveSessionId": this.parent_active_session_id,"rlmDepth": identity.rlm_depth + 1,diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rsindex f3572a0dc2..531705922b 100644--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs@@ -80,6 +80,17 @@ impl SupervisorChildSessionsInner {"rlmDepth": depth,"rlmMaxDepth": identity.rlm_max_depth,});+ // The decision child's runtime kind reaches the worker through the+ // create config: it builds the decision engine instead of the agent+ // engine.+ if runtime_metadata+ .as_ref()+ .and_then(|metadata| metadata.get("kind"))+ .and_then(Value::as_str)+ == Some("decision")+ {+ config["decisionChild"] = json!(true);+ }if let Some((provider, id)) = model.split_once('/') {config["provider"] = json!(provider);config["model"] = json!(id);diff --git a/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs b/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rsindex e2e02570ca..05e3b46873 100644--- a/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs+++ b/crates/pa-daemon/src/rlm_children/spawn_name_reservation_tests.rs@@ -161,6 +161,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}}diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rsindex 732ee81508..d53abc6df2 100644--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs@@ -301,6 +301,7 @@ async fn spawn_child(sessions: &SupervisorChildSessions) -> RlmSpawnHandle {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}).await.expect("spawn must succeed against the fake supervisor")diff --git a/crates/pa-daemon/src/rlm_surface.rs b/crates/pa-daemon/src/rlm_surface.rsindex a230bd3776..bdea3fad43 100644--- a/crates/pa-daemon/src/rlm_surface.rs+++ b/crates/pa-daemon/src/rlm_surface.rs@@ -116,6 +116,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/scheduled_jobs/tests.rs b/crates/pa-daemon/src/scheduled_jobs/tests.rsindex 0ab120ffc9..28df228401 100644--- a/crates/pa-daemon/src/scheduled_jobs/tests.rs+++ b/crates/pa-daemon/src/scheduled_jobs/tests.rs@@ -15,6 +15,7 @@ fn persisted_worker_config(dir: &std::path::Path) -> crate::worker::WorkerConfigrecovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(serde_json::json!({ "responses": ["ack", "ack", "ack", "ack"] })),+ decision_child: false,}}diff --git a/crates/pa-daemon/src/session_custom.rs b/crates/pa-daemon/src/session_custom.rsindex 9b23136955..062be54f99 100644--- a/crates/pa-daemon/src/session_custom.rs+++ b/crates/pa-daemon/src/session_custom.rs@@ -368,6 +368,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let mut create = json!({ "noSession": true, "cwd": "/tmp" });diff --git a/crates/pa-daemon/src/session_input_pause.rs b/crates/pa-daemon/src/session_input_pause.rsindex 35f91f4107..c31423b99b 100644--- a/crates/pa-daemon/src/session_input_pause.rs+++ b/crates/pa-daemon/src/session_input_pause.rs@@ -221,6 +221,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/session_navigation.rs b/crates/pa-daemon/src/session_navigation.rsindex 965c071c3a..0f730dd416 100644--- a/crates/pa-daemon/src/session_navigation.rs+++ b/crates/pa-daemon/src/session_navigation.rs@@ -461,6 +461,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = worker@@ -534,6 +535,7 @@ mod tests {"engine": "faux","responses": [{ "text": "one" }, { "text": "two" }],})),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = worker@@ -739,6 +741,7 @@ mod tests {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = worker@@ -855,6 +858,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(crate::worker::Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/setting_switches.rs b/crates/pa-daemon/src/setting_switches.rsindex 20e1523a56..ca060a2485 100644--- a/crates/pa-daemon/src/setting_switches.rs+++ b/crates/pa-daemon/src/setting_switches.rs@@ -591,6 +591,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,}}diff --git a/crates/pa-daemon/src/state_getters/state_getters_tests.rs b/crates/pa-daemon/src/state_getters/state_getters_tests.rsindex 57f8c2cfba..cd1b9543ba 100644--- a/crates/pa-daemon/src/state_getters/state_getters_tests.rs+++ b/crates/pa-daemon/src/state_getters/state_getters_tests.rs@@ -20,6 +20,7 @@ async fn created_worker_at(root: &std::path::Path, session_file: &std::path::Patrecovery_journal_path: root.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = worker@@ -49,6 +50,7 @@ async fn created_worker() -> Arc<Worker> {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = worker@@ -716,6 +718,7 @@ async fn model_catalog_and_available_models_match_the_ts_shapes() {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex ff3247db20..a87241304e 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -230,6 +230,9 @@ impl Supervisor {"rlmMaxDepth","parentSessionPath","models",+ // The Decision API child's engine choice: a dropped key respawns+ // the decision child as a regular agent session.+ "decisionChild",// The scripted-parent verification seam: a dropped key leaves// spawned children scriptless."childScript",diff --git a/crates/pa-daemon/src/update_restore.rs b/crates/pa-daemon/src/update_restore.rsindex 1f4f6af900..244eb419e2 100644--- a/crates/pa-daemon/src/update_restore.rs+++ b/crates/pa-daemon/src/update_restore.rs@@ -1115,6 +1115,7 @@ mod tests {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,},None,);@@ -1177,6 +1178,7 @@ mod tests {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({ "responses": ["ack", "done"] })),+ decision_child: false,},None,);diff --git a/crates/pa-daemon/src/user_bash.rs b/crates/pa-daemon/src/user_bash.rsindex 0bd56a7443..6182bdba58 100644--- a/crates/pa-daemon/src/user_bash.rs+++ b/crates/pa-daemon/src/user_bash.rs@@ -836,6 +836,7 @@ mod tests {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 04db62b0de..8f4a80840e 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -47,9 +47,9 @@ use turn::TurnRunner;mod commands;pub use env::{- WORKER_ACTIVE_SESSION_ID_ENV, WORKER_CWD_ENV, WORKER_INSTANCE_ID_ENV,- WORKER_RECOVERY_JOURNAL_ENV, WORKER_ROLE_ENV, WORKER_SCRIPT_ENV, WORKER_SOCKET_ENV,- WORKER_SUPERVISOR_LOST_EXIT_MS_ENV, WORKER_SUPERVISOR_SOCKET_ENV,+ WORKER_ACTIVE_SESSION_ID_ENV, WORKER_CWD_ENV, WORKER_DECISION_CHILD_ENV,+ WORKER_INSTANCE_ID_ENV, WORKER_RECOVERY_JOURNAL_ENV, WORKER_ROLE_ENV, WORKER_SCRIPT_ENV,+ WORKER_SOCKET_ENV, WORKER_SUPERVISOR_LOST_EXIT_MS_ENV, WORKER_SUPERVISOR_SOCKET_ENV,WORKER_TELEMETRY_DISABLED_ENV, WORKER_TOKEN_ENV,};use serde_json::Map;@@ -317,6 +317,7 @@ impl Worker {active_action: None,running_tool_calls: std::collections::HashSet::new(),running_admission_ids: std::collections::HashSet::new(),+ decision_child: false,};let active_session_id = config.active_session_id.clone();let script = config.script.clone();@@ -371,109 +372,200 @@ impl Worker {Arc::clone(&events),Arc::clone(&recovery),));+ // The turn runner's passivation context: shared by both engine+ // branches below (each moves the worker token into its engine).+ let passivation = crate::worker::turn::PassivationContext {+ agent_dir: config.agent_dir.clone(),+ link: Arc::clone(&roster_link),+ worker_token: worker_token.clone(),+ };let (engine, agent_engine, roster_pushes): (std::sync::Arc<dyn SessionEngine>,Option<std::sync::Arc<crate::agent_engine::AgentSessionEngine>>,crate::roster_activity::RosterPushQueue,) = {- // Scripted sessions serve the integration harness; sessions- // without a script run the real agent engine.- let mut agent_engine: Option<std::sync::Arc<crate::agent_engine::AgentSessionEngine>> =- None;- let engine: std::sync::Arc<dyn SessionEngine> = match &script {- // A `{"engine": "faux", ...}` script drives the real agent- // engine over the scripted faux provider (verification only).- Some(script) if script.get("engine") == Some(&serde_json::json!("faux")) => {- let cwd =- std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));- match AgentSessionEngine::new(AgentEngineConfig {- cwd,- agent_dir: config.agent_dir.clone(),- provider: None,- model: None,- api_key: None,- thinking: None,- session_dir: None,- session_file: None,- faux_script: Some(script.to_string()),- supervisor_link: Some(supervisor_link_config(&config)),- telemetry_disabled: config.telemetry_disabled,- cron_store: Some(kernel_cron_wiring(&scheduled)),- queued_steering_probe: queued_steering_probe.clone(),- }) {- Ok(engine) => {- let concrete = std::sync::Arc::new(engine);- agent_engine = Some(std::sync::Arc::clone(&concrete));- concrete+ // The Decision API child runs the decision engine; every other+ // session (scripted or not) runs the agent engine family.+ if config.decision_child {+ let engine: std::sync::Arc<dyn SessionEngine> =+ std::sync::Arc::new(crate::decision_engine::DecisionEngine::new(+ std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),+ config.agent_dir.clone(),+ std::sync::Arc::clone(&roster_link),+ config.active_session_id.clone(),+ worker_token,+ ));+ (+ engine,+ None,+ crate::roster_activity::RosterPushQueue::disabled(),+ )+ } else {+ // Scripted sessions serve the integration harness; sessions+ // without a script run the real agent engine.+ let mut agent_engine: Option<+ std::sync::Arc<crate::agent_engine::AgentSessionEngine>,+ > = None;+ let engine: std::sync::Arc<dyn SessionEngine> = match &script {+ // A `{"engine": "faux", ...}` script drives the real agent+ // engine over the scripted faux provider (verification only).+ Some(script) if script.get("engine") == Some(&serde_json::json!("faux")) => {+ let cwd = std::env::current_dir()+ .unwrap_or_else(|_| std::path::PathBuf::from("."));+ match AgentSessionEngine::new(AgentEngineConfig {+ cwd,+ agent_dir: config.agent_dir.clone(),+ provider: None,+ model: None,+ api_key: None,+ thinking: None,+ session_dir: None,+ session_file: None,+ faux_script: Some(script.to_string()),+ supervisor_link: Some(supervisor_link_config(&config)),+ telemetry_disabled: config.telemetry_disabled,+ cron_store: Some(kernel_cron_wiring(&scheduled)),+ queued_steering_probe: queued_steering_probe.clone(),+ }) {+ Ok(engine) => {+ let concrete = std::sync::Arc::new(engine);+ agent_engine = Some(std::sync::Arc::clone(&concrete));+ concrete+ }+ // Runtime construction failed: degrade to the echo engine.+ Err(_) => std::sync::Arc::new(ScriptedEngine::default()),}- // Runtime construction failed: degrade to the echo engine.- Err(_) => std::sync::Arc::new(ScriptedEngine::default()),}- }- Some(script) => {- std::sync::Arc::new(ScriptedEngine::from_value(script).unwrap_or_default())- }- None => {- let cwd =- std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));- match AgentSessionEngine::new(AgentEngineConfig {- cwd,- agent_dir: config.agent_dir.clone(),- provider: std::env::var("PRIME_AGENT_MODEL_PROVIDER").ok(),- model: std::env::var("PRIME_AGENT_MODEL").ok(),- api_key: None,- thinking: None,- session_dir: None,- session_file: None,- faux_script: None,- supervisor_link: Some(supervisor_link_config(&config)),- telemetry_disabled: config.telemetry_disabled,- cron_store: Some(kernel_cron_wiring(&scheduled)),- queued_steering_probe: queued_steering_probe.clone(),- }) {- Ok(engine) => {- let concrete = std::sync::Arc::new(engine);- agent_engine = Some(std::sync::Arc::clone(&concrete));- concrete+ Some(script) => {+ std::sync::Arc::new(ScriptedEngine::from_value(script).unwrap_or_default())+ }+ None => {+ let cwd = std::env::current_dir()+ .unwrap_or_else(|_| std::path::PathBuf::from("."));+ match AgentSessionEngine::new(AgentEngineConfig {+ cwd,+ agent_dir: config.agent_dir.clone(),+ provider: std::env::var("PRIME_AGENT_MODEL_PROVIDER").ok(),+ model: std::env::var("PRIME_AGENT_MODEL").ok(),+ api_key: None,+ thinking: None,+ session_dir: None,+ session_file: None,+ faux_script: None,+ supervisor_link: Some(supervisor_link_config(&config)),+ telemetry_disabled: config.telemetry_disabled,+ cron_store: Some(kernel_cron_wiring(&scheduled)),+ queued_steering_probe: queued_steering_probe.clone(),+ }) {+ Ok(engine) => {+ let concrete = std::sync::Arc::new(engine);+ agent_engine = Some(std::sync::Arc::clone(&concrete));+ concrete+ }+ // Runtime construction failed: degrade to the echo engine.+ Err(_) => std::sync::Arc::new(ScriptedEngine::default()),}- // Runtime construction failed: degrade to the echo engine.- Err(_) => std::sync::Arc::new(ScriptedEngine::default()),}- }- };- // The goal continuation seam (TS `getContinuationMessages`):- // the worker owns the queue and gates, the engine owns the mint.- if let Some(concrete) = agent_engine.as_ref() {- // The in-run autonomous continuation seam: the hook holds- // itself weakly through the registered arc.- concrete.register_arc();- let sink_core = Arc::clone(&core);- let sink_notify = Arc::clone(&work_notify);- let autonomous_sink: crate::agent_engine::AutonomousAdmission = {- let sink_core = Arc::clone(&sink_core);- let sink_notify = Arc::clone(&sink_notify);- let sink_recovery = Arc::clone(&recovery);- std::sync::Arc::new(move |text| {- admit_autonomous_follow_up(&sink_recovery, &sink_core, &sink_notify, text);- })};- concrete.set_autonomous_admission(autonomous_sink);- let purge_core = Arc::clone(&core);- let purge_recovery = Arc::clone(&recovery);- let autonomous_purge: std::sync::Arc<dyn Fn() + Send + Sync> =- std::sync::Arc::new(move || {+ // The goal continuation seam (TS `getContinuationMessages`):+ // the worker owns the queue and gates, the engine owns the mint.+ if let Some(concrete) = agent_engine.as_ref() {+ // The in-run autonomous continuation seam: the hook holds+ // itself weakly through the registered arc.+ concrete.register_arc();+ let sink_core = Arc::clone(&core);+ let sink_notify = Arc::clone(&work_notify);+ let autonomous_sink: crate::agent_engine::AutonomousAdmission = {+ let sink_core = Arc::clone(&sink_core);+ let sink_notify = Arc::clone(&sink_notify);+ let sink_recovery = Arc::clone(&recovery);+ std::sync::Arc::new(move |text| {+ admit_autonomous_follow_up(+ &sink_recovery,+ &sink_core,+ &sink_notify,+ text,+ );+ })+ };+ concrete.set_autonomous_admission(autonomous_sink);+ let purge_core = Arc::clone(&core);+ let purge_recovery = Arc::clone(&recovery);+ let autonomous_purge: std::sync::Arc<dyn Fn() + Send + Sync> =+ std::sync::Arc::new(move || {+ {+ let mut core = purge_core.lock().unwrap();+ core.follow_up.retain(|item| {+ item.queue_key.as_deref() != Some(AUTONOMOUS_QUEUE_KEY)+ });+ core.steering.retain(|item| {+ item.queue_key.as_deref() != Some(AUTONOMOUS_QUEUE_KEY)+ });+ }+ // The withdraw settles the rows: dropping the last+ // queued row must not leave busy=true promising a+ // revive (mid-turn stays busy until its own `turn_end`).+ checkpoint_queue_recovery(+ &purge_recovery,+ &purge_core,+ QueueCheckpoint::Settle {+ operation: "queue_purged",+ },+ );+ });+ concrete.set_autonomous_queue_purge(autonomous_purge);+ let probe_core = Arc::clone(&core);+ let probe: crate::engine::SessionInputProbe = Arc::new(move || {+ let core = probe_core.lock().unwrap();+ core.queued_input_suspended+ || !core.steering.is_empty()+ || !core.follow_up.is_empty()+ });+ let sink_core = Arc::clone(&core);+ let sink_events = events.clone();+ let sink_notify = Arc::clone(&work_notify);+ let sink_recovery = Arc::clone(&recovery);+ // Weak engine reference: the engine holds this sink, so a+ // strong one would pin it forever.+ let sink_engine = std::sync::Arc::downgrade(concrete);+ let sink: crate::engine::GoalAdmissionSink = Arc::new(move |work| {+ // The item's OWN pending handle, cloned before the+ // admission: the release touches exactly this mint's+ // guard, never the mutable mirror a rebuilt core re-swaps.+ let pending_handle = match &work {+ crate::engine::GoalTurnEndWork::Continuation(item)+ | crate::engine::GoalTurnEndWork::BudgetLimitSteer(item) => {+ item.pending_handle.clone()+ }+ };+ admit_goal_follow_up(+ &sink_recovery,+ &sink_core,+ &sink_events,+ &sink_notify,+ work,+ );+ if sink_engine.upgrade().is_none() {+ return;+ }+ // The queue admitted the minted continuation: the guard+ // releases now, so the next boundary may mint again.+ AgentSessionEngine::release_goal_continuation_handle(+ pending_handle.as_ref(),+ );+ });+ // TS `_clearQueuedGoalContexts`: withdraw queued minted+ // goal-context turns.+ let purge_core = Arc::clone(&core);+ let purge_recovery = Arc::clone(&recovery);+ let queue_purge: std::sync::Arc<dyn Fn() + Send + Sync> = Arc::new(move || {{let mut core = purge_core.lock().unwrap();- core.follow_up.retain(|item| {- item.queue_key.as_deref() != Some(AUTONOMOUS_QUEUE_KEY)- });- core.steering.retain(|item| {- item.queue_key.as_deref() != Some(AUTONOMOUS_QUEUE_KEY)- });+ core.steering.retain(|item| !is_goal_context_item(item));+ core.follow_up.retain(|item| !is_goal_context_item(item));}- // The withdraw settles the rows: dropping the last- // queued row must not leave busy=true promising a- // revive (mid-turn stays busy until its own `turn_end`).+ // Same settle as the autonomous withdraw: a pause/clear+ // cannot leave busy=true.checkpoint_queue_recovery(&purge_recovery,&purge_core,@@ -482,197 +574,144 @@ impl Worker {},);});- concrete.set_autonomous_queue_purge(autonomous_purge);- let probe_core = Arc::clone(&core);- let probe: crate::engine::SessionInputProbe = Arc::new(move || {- let core = probe_core.lock().unwrap();- core.queued_input_suspended- || !core.steering.is_empty()- || !core.follow_up.is_empty()- });- let sink_core = Arc::clone(&core);- let sink_events = events.clone();- let sink_notify = Arc::clone(&work_notify);- let sink_recovery = Arc::clone(&recovery);- // Weak engine reference: the engine holds this sink, so a- // strong one would pin it forever.- let sink_engine = std::sync::Arc::downgrade(concrete);- let sink: crate::engine::GoalAdmissionSink = Arc::new(move |work| {- // The item's OWN pending handle, cloned before the- // admission: the release touches exactly this mint's- // guard, never the mutable mirror a rebuilt core re-swaps.- let pending_handle = match &work {- crate::engine::GoalTurnEndWork::Continuation(item)- | crate::engine::GoalTurnEndWork::BudgetLimitSteer(item) => {- item.pending_handle.clone()- }- };- admit_goal_follow_up(- &sink_recovery,- &sink_core,- &sink_events,- &sink_notify,- work,- );- if sink_engine.upgrade().is_none() {- return;- }- // The queue admitted the minted continuation: the guard- // releases now, so the next boundary may mint again.- AgentSessionEngine::release_goal_continuation_handle(pending_handle.as_ref());- });- // TS `_clearQueuedGoalContexts`: withdraw queued minted- // goal-context turns.- let purge_core = Arc::clone(&core);- let purge_recovery = Arc::clone(&recovery);- let queue_purge: std::sync::Arc<dyn Fn() + Send + Sync> = Arc::new(move || {- {- let mut core = purge_core.lock().unwrap();- core.steering.retain(|item| !is_goal_context_item(item));- core.follow_up.retain(|item| !is_goal_context_item(item));- }- // Same settle as the autonomous withdraw: a pause/clear- // cannot leave busy=true.- checkpoint_queue_recovery(- &purge_recovery,- &purge_core,- QueueCheckpoint::Settle {- operation: "queue_purged",+ concrete.set_goal_admission(probe, sink, queue_purge);+ let late_core = Arc::clone(&core);+ let late_events = Arc::clone(&events);+ concrete.set_late_agent_message_sink(std::sync::Arc::new(+ move |tool_call_id, message| {+ let wire = pa_core::sent_agent_message_json(&message);+ crate::user_bash::emit_session_event_frame(+ &late_core,+ &late_events,+ serde_json::json!({+ "type": "ipython_sent_agent_message",+ "toolCallId": tool_call_id,+ "message": wire,+ }),+ );},- );- });- concrete.set_goal_admission(probe, sink, queue_purge);- let late_core = Arc::clone(&core);- let late_events = Arc::clone(&events);- concrete.set_late_agent_message_sink(std::sync::Arc::new(- move |tool_call_id, message| {- let wire = pa_core::sent_agent_message_json(&message);- crate::user_bash::emit_session_event_frame(- &late_core,- &late_events,- serde_json::json!({- "type": "ipython_sent_agent_message",- "toolCallId": tool_call_id,- "message": wire,- }),+ ));+ // The settled-child kernel release's registered-jobs gate+ // (TS #2483's `canPassivateSettledSession`+ // `hasRegisteredCronJob`): the release defers while this+ // session still owns an active or paused scheduled job+ // (a cron or heartbeat run must not lose its kernel).+ let jobs_core = Arc::clone(&core);+ let jobs_store = std::sync::Arc::clone(scheduled.store());+ concrete.set_registered_jobs_probe(std::sync::Arc::new(move || {+ let active_session_id = {+ jobs_core+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .active_session_id+ .clone()+ };+ jobs_store.list().into_iter().any(|job| {+ job.active_session_id == active_session_id+ && matches!(+ job.status,+ pa_core::cron::JobStatus::Active+ | pa_core::cron::JobStatus::Paused+ )+ })+ }));+ // The live compaction summary-delta sink: every summarizer+ // text delta reaches clients as one ephemeral frame (never+ // persisted, never a roster trigger).+ let summary_core = Arc::clone(&core);+ let summary_events = events.clone();+ let summary_sink: pa_core::session_engine::compaction_exec::SummaryDeltaSink =+ Arc::new(move |delta| {+ emit_worker_event_with(+ &summary_core,+ &summary_events,+ crate::compaction::compaction_summary_delta_event(delta),+ );+ });+ concrete.set_compaction_summary_sink(summary_sink);+ // The bash-completion wake seam (TS `_promptInjectedMessage`+ // for `bash.completed`): the handler validates, the sink+ // admits/withdraws through the queue lanes.+ let notice_engine = std::sync::Arc::downgrade(concrete);+ let notice_core = Arc::clone(&core);+ let notice_notify = Arc::clone(&work_notify);+ let notice_recovery = Arc::clone(&recovery);+ let completion: crate::engine::BashCompletionSink = Arc::new(move |notice| {+ let Some(engine) = notice_engine.upgrade() else {+ return;+ };+ if engine.session_is_closed() {+ return;+ }+ admit_bash_completion_notice(+ ¬ice_recovery,+ ¬ice_core,+ ¬ice_notify,+ ¬ice,+ // Revalidated inside the admission's lock section: the+ // close paths mark the session BEFORE clearing the lanes.+ || engine.session_is_closed(),);- },- ));- // The settled-child kernel release's registered-jobs gate- // (TS #2483's `canPassivateSettledSession`- // `hasRegisteredCronJob`): the release defers while this- // session still owns an active or paused scheduled job- // (a cron or heartbeat run must not lose its kernel).- let jobs_core = Arc::clone(&core);- let jobs_store = std::sync::Arc::clone(scheduled.store());- concrete.set_registered_jobs_probe(std::sync::Arc::new(move || {- let active_session_id = {- jobs_core- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .active_session_id- .clone()- };- jobs_store.list().into_iter().any(|job| {- job.active_session_id == active_session_id- && matches!(- job.status,- pa_core::cron::JobStatus::Active | pa_core::cron::JobStatus::Paused- )- })- }));- // The live compaction summary-delta sink: every summarizer- // text delta reaches clients as one ephemeral frame (never- // persisted, never a roster trigger).- let summary_core = Arc::clone(&core);- let summary_events = events.clone();- let summary_sink: pa_core::session_engine::compaction_exec::SummaryDeltaSink =- Arc::new(move |delta| {- emit_worker_event_with(- &summary_core,- &summary_events,- crate::compaction::compaction_summary_delta_event(delta),+ });+ let withdraw_core = Arc::clone(&core);+ let withdraw_recovery = Arc::clone(&recovery);+ let consumed: crate::engine::BashConsumedSink = Arc::new(move |notice| {+ withdraw_bash_completion_notice(+ &withdraw_recovery,+ &withdraw_core,+ ¬ice,);});- concrete.set_compaction_summary_sink(summary_sink);- // The bash-completion wake seam (TS `_promptInjectedMessage`- // for `bash.completed`): the handler validates, the sink- // admits/withdraws through the queue lanes.- let notice_engine = std::sync::Arc::downgrade(concrete);- let notice_core = Arc::clone(&core);- let notice_notify = Arc::clone(&work_notify);- let notice_recovery = Arc::clone(&recovery);- let completion: crate::engine::BashCompletionSink = Arc::new(move |notice| {- let Some(engine) = notice_engine.upgrade() else {- return;- };- if engine.session_is_closed() {- return;- }- admit_bash_completion_notice(- ¬ice_recovery,- ¬ice_core,- ¬ice_notify,- ¬ice,- // Revalidated inside the admission's lock section: the- // close paths mark the session BEFORE clearing the lanes.- || engine.session_is_closed(),- );- });- let withdraw_core = Arc::clone(&core);- let withdraw_recovery = Arc::clone(&recovery);- let consumed: crate::engine::BashConsumedSink = Arc::new(move |notice| {- withdraw_bash_completion_notice(&withdraw_recovery, &withdraw_core, ¬ice);- });- concrete.set_bash_notice_sinks(completion, consumed);- }- // The live roster activity feed (TS `observeRosterEvent`): busy- // flips and trigger events coalesce into `worker_roster_delta`- // pushes.- let roster_pushes =- crate::roster_activity::RosterPushQueue::spawn(crate::worker::RosterPushContext {- core: Arc::clone(&core),- engine: std::sync::Arc::clone(&engine),- user_bash: std::sync::Arc::clone(&user_bash),- roster_link: Arc::clone(&roster_link),- worker_token: worker_token.clone(),- worker_instance_id: config.worker_instance_id.clone(),- roster_delta_sequence: std::sync::Arc::clone(&roster_delta_sequence),- });- crate::roster_activity::spawn_roster_activity_watch(&events, roster_pushes.clone());- if let Some(children) = agent_engine- .as_ref()- .and_then(|engine| engine.children.as_ref())- {- crate::roster_activity::spawn_running_children_watch(- children,- roster_pushes.clone(),+ concrete.set_bash_notice_sinks(completion, consumed);+ }+ // The live roster activity feed (TS `observeRosterEvent`): busy+ // flips and trigger events coalesce into `worker_roster_delta`+ // pushes.+ let roster_pushes = crate::roster_activity::RosterPushQueue::spawn(+ crate::worker::RosterPushContext {+ core: Arc::clone(&core),+ engine: std::sync::Arc::clone(&engine),+ user_bash: std::sync::Arc::clone(&user_bash),+ roster_link: Arc::clone(&roster_link),+ worker_token,+ worker_instance_id: config.worker_instance_id.clone(),+ roster_delta_sequence: std::sync::Arc::clone(&roster_delta_sequence),+ },);+ crate::roster_activity::spawn_roster_activity_watch(&events, roster_pushes.clone());+ if let Some(children) = agent_engine+ .as_ref()+ .and_then(|engine| engine.children.as_ref())+ {+ crate::roster_activity::spawn_running_children_watch(+ children,+ roster_pushes.clone(),+ );+ }+ (engine, agent_engine, roster_pushes)}- let runner = TurnRunner {- recovery: Arc::clone(&recovery),- core: Arc::clone(&core),- input_pauses: input_pauses.clone(),- prompt_admissions: prompt_admissions.clone(),- work_notify: Arc::clone(&work_notify),- idle_notify: Arc::clone(&idle_notify),- events: events.clone(),- engine: std::sync::Arc::clone(&engine),- active_session_id,- roster_pushes: roster_pushes.clone(),- user_bash: std::sync::Arc::clone(&user_bash),- passivation: crate::worker::turn::PassivationContext {- agent_dir: config.agent_dir.clone(),- link: Arc::clone(&roster_link),- worker_token,- },- herdr: std::sync::Arc::clone(&herdr_slot),- };- tokio::spawn(async move {- runner.run().await;- });- (engine, agent_engine, roster_pushes)};+ // The turn runner drives the engine's queued prompts; every engine+ // needs it — a decision child without a runner never dequeues its+ // first prompt.+ let runner = TurnRunner {+ recovery: Arc::clone(&recovery),+ core: Arc::clone(&core),+ input_pauses: input_pauses.clone(),+ prompt_admissions: prompt_admissions.clone(),+ work_notify: Arc::clone(&work_notify),+ idle_notify: Arc::clone(&idle_notify),+ events: events.clone(),+ engine: std::sync::Arc::clone(&engine),+ active_session_id,+ roster_pushes: roster_pushes.clone(),+ user_bash: std::sync::Arc::clone(&user_bash),+ passivation,+ herdr: std::sync::Arc::clone(&herdr_slot),+ };+ tokio::spawn(async move {+ runner.run().await;+ });let side_questions = crate::side_question::SideQuestionManager::new(std::sync::Arc::clone(&engine),events.clone(),diff --git a/crates/pa-daemon/src/worker/agent_message_tests.rs b/crates/pa-daemon/src/worker/agent_message_tests.rsindex 97ace33bd0..69882c0329 100644--- a/crates/pa-daemon/src/worker/agent_message_tests.rs+++ b/crates/pa-daemon/src/worker/agent_message_tests.rs@@ -14,6 +14,7 @@ fn test_worker() -> Arc<Worker> {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};Arc::new(Worker::new(config, None))}diff --git a/crates/pa-daemon/src/worker/compaction_admission_tests.rs b/crates/pa-daemon/src/worker/compaction_admission_tests.rsindex bc5b33cc3f..499dd5c81b 100644--- a/crates/pa-daemon/src/worker/compaction_admission_tests.rs+++ b/crates/pa-daemon/src/worker/compaction_admission_tests.rs@@ -26,6 +26,7 @@ async fn compaction_admission_worker(compaction: Value) -> Arc<Worker> {"responses": ["steer reply"],"compaction": compaction,})),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/config.rs b/crates/pa-daemon/src/worker/config.rsindex 02568c318e..3ff3a004eb 100644--- a/crates/pa-daemon/src/worker/config.rs+++ b/crates/pa-daemon/src/worker/config.rs@@ -23,6 +23,8 @@ pub struct WorkerConfig {pub agent_dir: PathBuf,pub recovery_journal_path: PathBuf,pub script: Option<Value>,+ /// The Decision API child flag (`rlm.spawn kind="decision"`).+ pub decision_child: bool,/// Telemetry opt-out inherited from the create command ("1" = disabled;/// absent/other = enabled). Sessions created on this worker install no/// telemetry subscriber.@@ -65,6 +67,8 @@ impl WorkerConfig {let content = std::fs::read_to_string(path).ok()?;serde_json::from_str::<Value>(&content).ok()});+ let decision_child = std::env::var_os(crate::worker::WORKER_DECISION_CHILD_ENV)+ .is_some_and(|value| value == "1");let telemetry_disabled =std::env::var_os(WORKER_TELEMETRY_DISABLED_ENV).map(|value| value == "1");Ok(WorkerConfig {@@ -76,6 +80,7 @@ impl WorkerConfig {agent_dir,recovery_journal_path,script,+ decision_child,telemetry_disabled,})}diff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rsindex 35675d675d..bea876a09d 100644--- a/crates/pa-daemon/src/worker/create.rs+++ b/crates/pa-daemon/src/worker/create.rs@@ -189,6 +189,12 @@ impl Worker {.get("childScript").and_then(Value::as_str).map(str::to_string);+ // The Decision API child flag (`rlm.spawn kind="decision"`): the+ // worker runs the decision engine instead of the agent engine.+ let decision_child = payload+ .get("decisionChild")+ .and_then(Value::as_bool)+ .unwrap_or(false);// Set by the fresh-path arm when the name landed in its single rewrite:// the shared name persist must not append a second `session_info` line.@@ -569,6 +575,7 @@ impl Worker {core.parent_active_session_id = parent_active_session_id;core.parent_session_id = parent_session_id;core.child_script.clone_from(&child_script);+ core.decision_child = decision_child;(self.summary_locked(&core, inputs), rlm_depth)};// The engine's agent-level queues drain per the same modes thediff --git a/crates/pa-daemon/src/worker/create_collapse_tests.rs b/crates/pa-daemon/src/worker/create_collapse_tests.rsindex e412af30d1..6ff52abd04 100644--- a/crates/pa-daemon/src/worker/create_collapse_tests.rs+++ b/crates/pa-daemon/src/worker/create_collapse_tests.rs@@ -67,6 +67,7 @@ fn worker_in(dir: &std::path::Path, session_id: &str) -> Worker {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({"responses":[]})),+ decision_child: false,},None,);diff --git a/crates/pa-daemon/src/worker/env.rs b/crates/pa-daemon/src/worker/env.rsindex 1315864fd2..0cf60d0271 100644--- a/crates/pa-daemon/src/worker/env.rs+++ b/crates/pa-daemon/src/worker/env.rs@@ -57,6 +57,8 @@ pub const WORKER_SUPERVISOR_SOCKET_ENV: &str = "PRIME_AGENT_INTERNAL_DAEMON_SUPEpub const WORKER_RECOVERY_JOURNAL_ENV: &str = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_RECOVERY_JOURNAL";/// Scripted-engine script file for faux sessions (integration harness).pub const WORKER_SCRIPT_ENV: &str = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_SCRIPT";+/// The Decision API child flag: the worker builds the decision engine.+pub const WORKER_DECISION_CHILD_ENV: &str = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_DECISION_CHILD";/// Worker socket path (supervisor passes it explicitly).pub const WORKER_SOCKET_ENV: &str = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_SOCKET";/// Telemetry opt-out (supervisor passes the create's `telemetryDisabled`, TS parity).diff --git a/crates/pa-daemon/src/worker/input.rs b/crates/pa-daemon/src/worker/input.rsindex 3575a9fb26..f8d3343624 100644--- a/crates/pa-daemon/src/worker/input.rs+++ b/crates/pa-daemon/src/worker/input.rs@@ -303,6 +303,33 @@ impl Worker {.unwrap_or_else(std::sync::PoisonError::into_inner);sender_is_child_of(&sender, &core).then_some(AgentFamilyRelationship::Child)};+ if from_relationship != Some(AgentFamilyRelationship::Sibling)+ && self+ .engine+ .route_decision_api_event(from_relationship, &sender_name, message)+ {+ let (core, inputs) = self.summary_inputs();+ let summary = self.summary_locked(&core, inputs);+ return response_success(+ None,+ "worker_deliver_message",+ Some(json!({+ "id": pa_core::session_engine::agent_messaging::create_agent_session_message_id(),+ "source": AGENT_MESSAGE_SOURCE,+ "target": {+ "activeSessionId": summary.active_session_id,+ "sessionId": summary.session_id,+ "sessionName": summary.session_name,+ "runtimeKind": summary.runtime_kind,+ },+ "from": sender,+ "message": message,+ "deliveryMode": "steer",+ "deliveryStatus": "delivered",+ "deliveredAt": crate::util::now_iso(),+ })),+ );+ }let prompt = pa_core::session_engine::agent_messaging::create_agent_session_message_prompt(&AgentMessagePromptPayload {message: message.to_string(),diff --git a/crates/pa-daemon/src/worker/prompt_image_tests.rs b/crates/pa-daemon/src/worker/prompt_image_tests.rsindex 4fde703ebf..176fc03873 100644--- a/crates/pa-daemon/src/worker/prompt_image_tests.rs+++ b/crates/pa-daemon/src/worker/prompt_image_tests.rs@@ -39,6 +39,7 @@ fn test_worker() -> Arc<Worker> {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};Arc::new(Worker::new(config, None))}diff --git a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs b/crates/pa-daemon/src/worker/recovery_verdict_tests.rsindex 63dadbbd1b..85d8a1ea65 100644--- a/crates/pa-daemon/src/worker/recovery_verdict_tests.rs+++ b/crates/pa-daemon/src/worker/recovery_verdict_tests.rs@@ -14,6 +14,7 @@ fn worker_with_journal() -> Arc<Worker> {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));// The journal is opened in `serve()`; tests open it directly so thediff --git a/crates/pa-daemon/src/worker/replacement_gate_tests.rs b/crates/pa-daemon/src/worker/replacement_gate_tests.rsindex 0df9bb7ba8..68c973a37a 100644--- a/crates/pa-daemon/src/worker/replacement_gate_tests.rs+++ b/crates/pa-daemon/src/worker/replacement_gate_tests.rs@@ -87,6 +87,7 @@ fn recording_worker(dir: &Path, events: std::sync::Arc<std::sync::Mutex<Vec<Strirecovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let mut worker = Worker::new(config, None);let engine: std::sync::Arc<dyn SessionEngine> = std::sync::Arc::new(RecordingEngine { events });diff --git a/crates/pa-daemon/src/worker/session_core.rs b/crates/pa-daemon/src/worker/session_core.rsindex ae8e014344..835ab7b0d0 100644--- a/crates/pa-daemon/src/worker/session_core.rs+++ b/crates/pa-daemon/src/worker/session_core.rs@@ -56,6 +56,9 @@ pub(crate) struct SessionCore {/// The create command's harness `childScript` (kept across the runtime swap/// so a replacement's children stay scripted); `None` for product sessions.pub(crate) child_script: Option<String>,+ /// The Decision API child flag (`rlm.spawn kind="decision"`): the worker+ /// runs the decision engine instead of the agent engine.+ pub(crate) decision_child: bool,/// The session's service-tier preference (TS `_serviceTierPreference`,/// `None` = "auto"): clamps `priority` to `default` without fast mode.pub(crate) service_tier: Option<pa_types::ai::ServiceTier>,@@ -142,6 +145,7 @@ impl SessionCore {queued_input_suspended: false,pending_next_turn: Vec::new(),active_action: None,+ decision_child: false,}}}diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rsindex f7fe594c46..1a2c7542a5 100644--- a/crates/pa-daemon/src/worker/tests.rs+++ b/crates/pa-daemon/src/worker/tests.rs@@ -15,6 +15,7 @@ async fn created_dispatch_worker() -> std::sync::Arc<Worker> {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -64,6 +65,7 @@ async fn background_refinement_event_is_fenced_to_its_review_session() {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": [] })),+ decision_child: false,},None,);diff --git a/crates/pa-daemon/src/worker/tests/abort_boundary_tests.rs b/crates/pa-daemon/src/worker/tests/abort_boundary_tests.rsindex fe42266670..546c3684f2 100644--- a/crates/pa-daemon/src/worker/tests/abort_boundary_tests.rs+++ b/crates/pa-daemon/src/worker/tests/abort_boundary_tests.rs@@ -112,6 +112,7 @@ async fn abort_and_send_queued_delivers_the_parked_queue_at_the_boundary() {"follow-up reply",],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -297,6 +298,7 @@ async fn abort_and_send_queued_with_only_follow_ups_starts_the_oldest() {"follow-up two reply",],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -510,6 +512,7 @@ async fn cancel_owned_admission_aborts_the_running_prompt() {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": [{ "text": "held reply", "delayMs": 60000 }] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/tests/connection_state_tests.rs b/crates/pa-daemon/src/worker/tests/connection_state_tests.rsindex 449113795e..7c71a1e78c 100644--- a/crates/pa-daemon/src/worker/tests/connection_state_tests.rs+++ b/crates/pa-daemon/src/worker/tests/connection_state_tests.rs@@ -147,6 +147,7 @@ async fn summary_retry_resolves_the_selection_that_owns_the_locked_core() {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": [] })),+ decision_child: false,},None,);@@ -203,6 +204,7 @@ async fn the_attach_state_carries_the_stats_context_usage() {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({"responses":[]})),+ decision_child: false,},None,);@@ -249,6 +251,7 @@ async fn the_attach_state_carries_the_stats_context_usage() {recovery_journal_path: dir.path().join("recovery2.jsonl"),telemetry_disabled: None,script: Some(json!({"responses":[]})),+ decision_child: false,},None,);diff --git a/crates/pa-daemon/src/worker/tests/goal_tests.rs b/crates/pa-daemon/src/worker/tests/goal_tests.rsindex 5c2b026d10..7f3aa22c80 100644--- a/crates/pa-daemon/src/worker/tests/goal_tests.rs+++ b/crates/pa-daemon/src/worker/tests/goal_tests.rs@@ -18,6 +18,7 @@ async fn goal_dispatch_worker(goal: serde_json::Value) -> std::sync::Arc<Worker>"responses": ["ack"],"goal": goal,})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -216,6 +217,7 @@ async fn goal_turn_end_loop_runs_to_completion() {"after the loop settled",],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -340,6 +342,7 @@ async fn goal_pause_withdraws_the_queued_continuation() {"one continuation turn at most",],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -399,6 +402,7 @@ async fn goal_dispatch_worker_with_store("responses": ["ack"],"goal": goal,})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/tests/kill_broadcast_tests.rs b/crates/pa-daemon/src/worker/tests/kill_broadcast_tests.rsindex f564b241a2..5c6bb808f8 100644--- a/crates/pa-daemon/src/worker/tests/kill_broadcast_tests.rs+++ b/crates/pa-daemon/src/worker/tests/kill_broadcast_tests.rs@@ -27,6 +27,7 @@ async fn aborted_turn_row_broadcasts_and_persists_through_the_worker_gate() {{ "text": "held reply", "delayMs": 60000 },],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -197,6 +198,7 @@ async fn kill_cancels_the_sessions_scheduled_jobs() {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "engine": "faux", "responses": [] })),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -276,6 +278,7 @@ async fn kill_cancels_a_mid_provider_wait_turn_and_surfaces_the_aborted_row() {{ "text": "held reply", "delayMs": 60000 },],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -420,6 +423,7 @@ async fn compact_interrupt_swallows_the_aborted_row() {"engine": "faux","responses": [{ "text": "held reply", "delayMs": 60000 }],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/tests/warning_marker_tests.rs b/crates/pa-daemon/src/worker/tests/warning_marker_tests.rsindex e38c922000..f22cb2427a 100644--- a/crates/pa-daemon/src/worker/tests/warning_marker_tests.rs+++ b/crates/pa-daemon/src/worker/tests/warning_marker_tests.rs@@ -63,6 +63,7 @@ fn worker_in(dir: &std::path::Path, session_id: &str) -> Worker {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({"responses":[]})),+ decision_child: false,},None,);diff --git a/crates/pa-daemon/src/worker/turn_stream_tests.rs b/crates/pa-daemon/src/worker/turn_stream_tests.rsindex ba610ab6f9..76bf0449f7 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests.rs@@ -53,6 +53,7 @@ fn burst_runner(engine: Arc<dyn SessionEngine>) -> TurnRunner {active_action: None,running_tool_calls: std::collections::HashSet::new(),running_admission_ids: std::collections::HashSet::new(),+ decision_child: false,}));TurnRunner {core,diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rs b/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rsindex ab15b0d6b8..f61f80e489 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rs@@ -131,6 +131,7 @@ async fn abort_and_send_idle_race_rate_harness() {"follow-up reply"],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rs b/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rsindex f796e98670..4a975b9006 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/broadcast.rs@@ -157,6 +157,7 @@ async fn a_delivered_agent_message_turn_emits_the_custom_row() {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = worker@@ -346,6 +347,7 @@ async fn a_retried_turn_broadcasts_one_agent_end_per_run() {{ "text": "recovered reply" },],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/turn_stream_tests/interleave.rs b/crates/pa-daemon/src/worker/turn_stream_tests/interleave.rsindex 83207ea2ee..d0d1fd992d 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/interleave.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/interleave.rs@@ -585,6 +585,7 @@ async fn interleave_worker() -> (Arc<Worker>, tempfile::TempDir) {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": [] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rsindex b55ef96f12..a75caeab37 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs@@ -435,6 +435,7 @@ async fn abort_and_send_queued_delivers_the_steering_batch_then_the_follow_ups()"follow-up reply"],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = worker@@ -626,6 +627,7 @@ async fn abort_and_send_queued_acks_before_the_follow_up_delivery() {{ "text": "follow-up reply", "delayMs": 60000 },],})),+ decision_child: false,};let worker = std::sync::Arc::new(Worker::new(config, None));let created = workerdiff --git a/crates/pa-daemon/src/worker/update_snapshot_tests.rs b/crates/pa-daemon/src/worker/update_snapshot_tests.rsindex d4c58300f3..47541a488c 100644--- a/crates/pa-daemon/src/worker/update_snapshot_tests.rs+++ b/crates/pa-daemon/src/worker/update_snapshot_tests.rs@@ -14,6 +14,7 @@ async fn snapshot_after_create() -> (Arc<Worker>, DaemonResponse) {recovery_journal_path: dir.join("recovery.jsonl"),telemetry_disabled: None,script: Some(json!({ "responses": ["ack"] })),+ decision_child: false,};let worker = Arc::new(Worker::new(config, None));// The journal is opened in `serve()`; tests open it directly so thediff --git a/crates/pa-daemon/src/worker_resume_settings_tests.rs b/crates/pa-daemon/src/worker_resume_settings_tests.rsindex 45fa87bde9..0ef5150f5a 100644--- a/crates/pa-daemon/src/worker_resume_settings_tests.rs+++ b/crates/pa-daemon/src/worker_resume_settings_tests.rs@@ -108,6 +108,7 @@ mod resume_settings_tests {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({"responses":[]})),+ decision_child: false,},None,);@@ -208,6 +209,7 @@ mod resume_settings_tests {recovery_journal_path: dir.path().join("recovery.jsonl"),telemetry_disabled: Some(true),script: Some(json!({"responses":[]})),+ decision_child: false,},None,);diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rsindex c67f4bc752..aab2099de5 100644--- a/crates/pa-daemon/tests/agent_family_e2e.rs+++ b/crates/pa-daemon/tests/agent_family_e2e.rs@@ -424,6 +424,7 @@ async fn parent_child_agent_message_round_trip_end_to_end() {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}).await.expect("spawn the child");@@ -753,6 +754,7 @@ async fn family_edges_never_cross_families_end_to_end() {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}).await.expect("spawn the child");@@ -893,6 +895,7 @@ async fn family_edges_never_cross_families_end_to_end() {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}).await.expect("spawn the grandchild");@@ -1202,6 +1205,7 @@ async fn parent_renames_a_child_end_to_end() {thinking: None,spawned_by_request_id: None,cell_source_code: None,+ decision_child: false,}).await.expect("spawn the child");diff --git a/crates/pa-daemon/tests/agents_view_roster_e2e.rs b/crates/pa-daemon/tests/agents_view_roster_e2e.rsindex 9ea32980da..f1c6acf1fa 100644--- a/crates/pa-daemon/tests/agents_view_roster_e2e.rs+++ b/crates/pa-daemon/tests/agents_view_roster_e2e.rs@@ -423,6 +423,7 @@ async fn rlm_children_key_the_roster_by_parent_path_and_child_id() {name: Some("child-a".to_string()),model: None,thinking: None,+ decision_child: false,cell_source_code: None,spawned_by_request_id: None,})diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rsindex b408bd7163..5803e3487d 100644--- a/crates/pa-daemon/tests/idle_passivation_e2e.rs+++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs@@ -295,6 +295,7 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_agent_message(thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}).await.expect("spawn the child");@@ -613,6 +614,7 @@ async fn a_parent_rename_after_a_revival_and_second_passivation_reaches_the_chilthinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}).await.expect("spawn the child");diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rsindex d35b3e3e96..1c85f1482f 100644--- a/crates/pa-daemon/tests/rlm_children_e2e.rs+++ b/crates/pa-daemon/tests/rlm_children_e2e.rs@@ -233,6 +233,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {thinking: None,cell_source_code: None,spawned_by_request_id: None,+ decision_child: false,}}@@ -499,6 +500,123 @@ async fn rlm_children_spawn_roster_collect_delete_end_to_end() {assert_ne!(live[0].status, "cancelled");}+/// A decision child (`rlm.spawn kind="decision"`) spawns through the real+/// supervisor on the settings decision model and runs the decision engine:+/// the protocol prompt settles as the engine's ready answer, never an+/// agent turn. Regression: the durable create command must ride the+/// `decisionChild` flag to the worker's launch env — a dropped flag+/// respawns the decision child as a regular agent session whose turn+/// fails on the decision model.+#[tokio::test]+async fn a_decision_child_spawn_runs_the_decision_engine_end_to_end() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ // The settings gate, the registry recipe, and the stored login (the+ // clef live test's fixture shape, on an unreachable endpoint: the+ // protocol prompt makes no model call).+ std::fs::write(+ agent_dir.join("settings.json"),+ json!({ "decisionApi": { "systemOneModel": "decision-fixture/clef" } }).to_string(),+ )+ .expect("write settings");+ std::fs::write(+ agent_dir.join("models.json"),+ json!({ "providers": { "decision-fixture": {+ "baseUrl": "http://127.0.0.1:1/api/v1",+ "apiKey": "DECISION_FIXTURE_KEY",+ "api": "systemone",+ "models": [ { "id": "clef", "input": ["text"] } ],+ } } })+ .to_string(),+ )+ .expect("write models");+ std::fs::write(+ agent_dir.join("auth.json"),+ json!({ "decision-fixture": { "type": "api_key", "key": "fixture-key" } }).to_string(),+ )+ .expect("write auth");+ let _daemon = spawn_daemon(&socket, &agent_dir);+ let (mut client, hello) = Client::connect(&socket);+ assert_eq!(hello["type"], "daemon_hello");+ // The children registry without a child script: the decision child is+ // an engine choice, never a scripted child.+ let children = {+ let sessions = SupervisorChildSessions::new(+ Arc::new(SupervisorLink::new(socket.clone())),+ agent_dir.clone(),+ "parent-active-id".to_string(),+ std::sync::Arc::new(pa_daemon::model_allowlist::ModelRefusalTelemetry::new(+ agent_dir.clone(),+ /*telemetry_disabled*/ true,+ )),+ );+ sessions.set_identity(ParentIdentity {+ rlm_depth: 0,+ rlm_max_depth: 2,+ model: Some("scripted/faux-1".to_string()),+ cwd: Some(agent_dir.to_string_lossy().to_string()),+ session_id: Some("parent-session-uuid".to_string()),+ session_file: Some(agent_dir.join("parent.jsonl").to_string_lossy().to_string()),+ thinking: None,+ child_script: None,+ });+ sessions+ };+ let handle = children+ .spawn(RlmSpawnRequest {+ prompt: "You are System 1, the decision child of a real-time control loop.".to_string(),+ name: Some("system-1".to_string()),+ model: None,+ thinking: None,+ cell_source_code: None,+ spawned_by_request_id: None,+ decision_child: true,+ })+ .await+ .expect("spawn the decision child");+ children.notify_turn_done();+ // The spawn seam resolves the settings decision model, not the parent's.+ assert_eq!(handle.model, "decision-fixture/clef", "{handle:?}");+ // The child settles with the decision engine's protocol answer — an+ // agent-engine child instead fails its turn on the unreachable model.+ let entries = {+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ let entries = children.list_subagents().await.expect("list subagents");+ if entries+ .iter()+ .any(|entry| entry.answer_preview.as_deref() == Some("Decision child ready."))+ {+ break entries;+ }+ assert!(+ Instant::now() < deadline,+ "decision child never settled ready: {entries:?}"+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ };+ assert_eq!(entries.len(), 1, "one child in the roster");+ assert_eq!(entries[0].session_name, "system-1");+ // The supervisor roster carries the same settled decision child.+ let roster_summary = wait_until(Duration::from_secs(10), || {+ client.send_command("l1", &json!({ "type": "list" }));+ let list = client.read_response("l1");+ list["data"]["sessions"].as_array().and_then(|sessions| {+ sessions+ .iter()+ .find(|summary| summary["sessionName"] == "system-1")+ .cloned()+ })+ });+ assert_eq!(roster_summary["rlmDepth"], 1);+ // The decision engine serves the trait-default session summary, whose+ // runtimeKind stays the top-level default — the engine choice is under+ // test here, not the summary metadata.+}+#[tokio::test]async fn rlm_create_session_spawns_a_prompted_depth_zero_session() {let dir = tempfile::TempDir::new().expect("temp dir");diff --git a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rsindex 663b2cb342..cb2eee7ce7 100644--- a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs+++ b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs@@ -357,6 +357,7 @@ async fn subscribe_after_spawn_then_shutdown_seeds_the_passive_child() {name: Some("worker-a".to_string()),model: None,thinking: None,+ decision_child: false,cell_source_code: None,spawned_by_request_id: None,})diff --git a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rsindex 58dd98ff16..1150c9120f 100644--- a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs+++ b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs@@ -230,6 +230,7 @@ fn spawn_request(name: &str, prompt: &str) -> RlmSpawnRequest {name: Some(name.to_string()),model: None,thinking: None,+ decision_child: false,cell_source_code: None,spawned_by_request_id: None,}diff --git a/crates/pa-tui/README.md b/crates/pa-tui/README.mdindex b327fd0ab5..c57e7aae54 100644--- a/crates/pa-tui/README.md+++ b/crates/pa-tui/README.md@@ -25,6 +25,13 @@ list; rows carry their session's `◷ N` heartbeat count from the## Non-goalsNo session logic, no providers, no loop policy. The interactive UI renders daemon events and sends user intents (prompts, abort, switch) as daemon commands; the session loop itself lives in the pa-daemon worker. It never computes agent behavior and never spawns the supervisor (launch semantics live in pa-cli).+The `/decision-api` switch is a daemon session command; the TUI only+submits it. `chrome::ChromeState::decision_api` and+`snapshot::Reconstructed::decision_api` extend the existing rendering/snapshot+data with the session's enabled flag (seeded from the attach state, kept live+by its `decision_api_status` rows); the footer component itself remains+crate-internal.+The client commands of the clipboard/auth/update group: `/copy` (the last assistant text through the platform clipboard tool chain with the OSC 52 fallback — `clipboard.rs` + `osc52.rs`, the same emitter the selection-copy work can reuse; the daemon `get_last_assistant_text` supplies the text), `/import` (the path argument parse, the TS confirm, the typed error surfaces — the missing file, the missing session cwd with its fallback-cwd retry — and the post-import transcript rebuild through the daemon's `import_jsonl`), `/login` + `/logout` (the TS providers selector — `provider_auth.rs`, the panel `showConfigurationMenu("providers")` mounts: the tab bar, the search, the status indicators, the in-panel API-key prompt — over the composition root's auth flows), `/traces` (the TS status block and settings writes; the upload subsystem stays unported, its arms keep the TS state shapes and report the unavailability), and `/update` (the TS busy guard, the split-CLI child mapping — packages then the binary — and the self-update relaunch through the composition root's hook).## Public APIdiff --git a/crates/pa-tui/src/choice_picker.rs b/crates/pa-tui/src/choice_picker.rsnew file mode 100644index 0000000000..b879ba2c37--- /dev/null+++ b/crates/pa-tui/src/choice_picker.rs@@ -0,0 +1,182 @@+//! The inline single-choice picker the `/effort` command opens: one list+//! rendered through the inline-picker component+//! (TS `ThinkingSelectorComponent` reduced to this seam - list, select,+//! apply; Esc cancels). Enter applies the picked row through the caller,+//! which dispatches on the picker's purpose; the picker owns only list state.++use crate::config_selector::{ConfigSelector, SelectorAction, SelectorKind, SelectorRow};+use crate::effort_picker::level_description;+use crate::keybindings::KeybindingsManager;+use crate::theme::Theme;+use crate::Line;++/// What the picked row applies to.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ChoicePurpose {+ /// `/effort`: the row key is a thinking level.+ Effort,+}++/// One key press while the picker is open.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum ChoicePickerAction {+ /// Enter or Space on a row: the caller applies its key.+ Apply { purpose: ChoicePurpose, key: String },+ /// Esc or Ctrl+C: close without applying.+ Cancel,+ /// Navigation or filter editing only.+ None,+}++/// One single-choice picker. Rows carry their key as the identity; the+/// selector owns filtering, navigation, and rendering.+#[derive(Debug)]+pub(crate) struct ChoicePicker {+ selector: ConfigSelector,+ purpose: ChoicePurpose,+ keys: Vec<String>,+}++impl ChoicePicker {+ /// The `/effort` picker: one row per level (label = level, description+ /// as the secondary filter field), the current level checked.+ #[must_use]+ pub fn effort(levels: &[String], current: Option<&str>) -> Self {+ let rows = levels+ .iter()+ .map(|level| (level.clone(), level.clone(), level_description(level)))+ .collect();+ Self::new(ChoicePurpose::Effort, rows, current)+ }++ fn new(+ purpose: ChoicePurpose,+ rows: Vec<(String, String, &str)>,+ current: Option<&str>,+ ) -> Self {+ let kind = match purpose {+ ChoicePurpose::Effort => SelectorKind::Effort,+ };+ let keys: Vec<String> = rows.iter().map(|(key, _, _)| key.clone()).collect();+ let rows = rows+ .into_iter()+ .map(|(key, label, description)| SelectorRow::Item {+ checked: current == Some(key.as_str()),+ key,+ label,+ type_label: description.to_string(),+ path: String::new(),+ })+ .collect();+ let selector = ConfigSelector::with_kind(rows, kind);+ ChoicePicker {+ selector,+ purpose,+ keys,+ }+ }++ /// One bracketed paste into the search (the config selector's own+ /// paste path).+ pub fn paste(&mut self, text: &str) {+ self.selector.paste(text);+ }++ /// The checked state of one row.+ #[cfg(test)]+ #[must_use]+ pub fn checked(&self, key: &str) -> Option<bool> {+ self.selector.checked(key)+ }++ /// One key id. Cancel keys close without applying; Enter/Space apply+ /// the row at the selection (single-select).+ pub fn handle_key(&mut self, key: &str, kb: &KeybindingsManager) -> ChoicePickerAction {+ if key == "ctrl+c" {+ return ChoicePickerAction::Cancel;+ }+ match self.selector.handle_key(key, kb) {+ Some(SelectorAction::Close | SelectorAction::Exit) => ChoicePickerAction::Cancel,+ Some(SelectorAction::Toggle { key, .. }) => {+ if self.keys.contains(&key) {+ ChoicePickerAction::Apply {+ purpose: self.purpose,+ key,+ }+ } else {+ ChoicePickerAction::None+ }+ }+ None => ChoicePickerAction::None,+ }+ }++ /// The picker's rendered frame (the shared menu-panel grammar).+ #[must_use]+ pub fn render(&self, theme: &Theme, width: usize, kb: &KeybindingsManager) -> Vec<Line> {+ self.selector.render(theme, width, kb)+ }++ /// The rows the picker's list window renders (the click surface's+ /// item-row span).+ #[must_use]+ pub fn visible_window(&self) -> (usize, usize) {+ self.selector.visible_window()+ }++ /// Move the selection to one filtered row (the click grammar's row+ /// select - the arrow keys' exact movement, no apply).+ pub fn select_position(&mut self, position: usize) {+ self.selector.select_position(position);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::theme::{ColorMode, Theme};++ fn kb() -> KeybindingsManager {+ KeybindingsManager::new()+ }++ fn frame_text(picker: &ChoicePicker) -> Vec<String> {+ let theme = Theme::builtin("prime", ColorMode::TrueColor);+ picker+ .render(&theme, 60, &kb())+ .iter()+ .map(|line| line.iter().map(|span| span.content.as_str()).collect())+ .collect()+ }++ fn levels() -> Vec<String> {+ ["off", "low", "medium", "high"]+ .iter()+ .map(ToString::to_string)+ .collect()+ }++ #[test]+ fn enter_applies_the_selected_level_and_escape_cancels() {+ let mut picker = ChoicePicker::effort(&levels(), None);+ assert_eq!(picker.handle_key("down", &kb()), ChoicePickerAction::None);+ assert_eq!(+ picker.handle_key("enter", &kb()),+ ChoicePickerAction::Apply {+ purpose: ChoicePurpose::Effort,+ key: "low".to_string()+ }+ );+ assert_eq!(+ picker.handle_key("escape", &kb()),+ ChoicePickerAction::Cancel+ );+ }++ #[test]+ fn the_effort_frame_lists_levels_and_their_descriptions() {+ let text = frame_text(&ChoicePicker::effort(&levels(), None));+ assert!(text.iter().any(|row| row.contains("Thinking Level")));+ assert!(text.iter().any(|row| row.contains("Moderate reasoning")));+ }+}diff --git a/crates/pa-tui/src/click_dispatch.rs b/crates/pa-tui/src/click_dispatch.rsindex 301aac5449..3c80596699 100644--- a/crates/pa-tui/src/click_dispatch.rs+++ b/crates/pa-tui/src/click_dispatch.rs@@ -68,8 +68,8 @@ impl SessionUi {self.dirty = true;}}- ClickAction::SelectEffortRow(position) => {- if let Some(picker) = view.effort_picker.as_mut() {+ ClickAction::SelectChoiceRow(position) => {+ if let Some(picker) = view.choice_picker.as_mut() {self.track_click("picker");picker.select_position(position);self.dirty = true;diff --git a/crates/pa-tui/src/effort_picker.rs b/crates/pa-tui/src/effort_picker.rsindex 5f4f98441c..b8ea049ea4 100644--- a/crates/pa-tui/src/effort_picker.rs+++ b/crates/pa-tui/src/effort_picker.rs@@ -1,11 +1,7 @@-//! The `/effort` inline picker: the session's thinking levels rendered-//! through the inline-picker component. Enter applies the picked level-//! through the caller; the picker itself owns only list state.+//! The `/effort` command dispatch: the session's thinking levels and their+//! descriptions, opened in the shared [`ChoicePicker`] or applied directly.-use crate::config_selector::{ConfigSelector, SelectorAction, SelectorKind, SelectorRow};-use crate::keybindings::KeybindingsManager;-use crate::theme::Theme;-use crate::Line;+use crate::choice_picker::ChoicePicker;/// The reasoning-level descriptions the TS selector lists under each level.#[must_use]@@ -22,22 +18,11 @@ pub fn level_description(level: &str) -> &'static str {}}-/// One key press while the picker is open.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum EffortPickerAction {- /// Enter or Space on a level: the caller applies it.- Apply { level: String },- /// Esc or Ctrl+C: close without applying.- Cancel,- /// Navigation or filter editing only.- None,-}-/// The outcome of dispatching `/effort [level]`.#[derive(Debug)]pub(crate) enum EffortCommandOutcome {/// Open the picker over the session's levels.- Open(EffortPicker),+ Open(ChoicePicker),/// The model cannot think: the TS status note.Unsupported,/// The requested level is not one of the model's: the TS error.@@ -62,7 +47,7 @@ pub(crate) fn effort_command(}let requested = arg.trim().to_lowercase();if requested.is_empty() {- return EffortCommandOutcome::Open(EffortPicker::new(levels, current));+ return EffortCommandOutcome::Open(ChoicePicker::effort(levels, current));}if !levels.iter().any(|level| level == &requested) {return EffortCommandOutcome::Unknown {@@ -73,104 +58,9 @@ pub(crate) fn effort_command(EffortCommandOutcome::Apply { level: requested }}-/// One picker over the session's thinking levels; the selector owns-/// filtering, navigation, and rendering.-#[derive(Debug)]-pub struct EffortPicker {- selector: ConfigSelector,- levels: Vec<String>,-}--impl EffortPicker {- /// Build the picker: one item row per level (label = level, description- /// as the secondary filter field), the current level checked.- #[must_use]- pub fn new(levels: &[String], current: Option<&str>) -> Self {- let rows = levels- .iter()- .map(|level| SelectorRow::Item {- key: level.clone(),- label: level.clone(),- checked: current == Some(level.as_str()),- type_label: level_description(level).to_string(),- path: String::new(),- })- .collect();- EffortPicker {- selector: ConfigSelector::with_kind(rows, SelectorKind::Effort),- levels: levels.to_vec(),- }- }-- /// One bracketed paste into the search (the config selector's own- /// paste path).- pub fn paste(&mut self, text: &str) {- self.selector.paste(text);- }-- /// The session's levels the picker was built over.- #[must_use]- pub fn levels(&self) -> &[String] {- &self.levels- }-- /// The checked state of one level's row.- #[must_use]- pub fn checked(&self, level: &str) -> Option<bool> {- self.selector.checked(level)- }-- /// One key id. Cancel keys close without applying; Enter/Space apply- /// the level at the selection (single-select).- pub fn handle_key(&mut self, key: &str, kb: &KeybindingsManager) -> EffortPickerAction {- if key == "ctrl+c" {- return EffortPickerAction::Cancel;- }- match self.selector.handle_key(key, kb) {- Some(SelectorAction::Close | SelectorAction::Exit) => EffortPickerAction::Cancel,- Some(SelectorAction::Toggle { key, .. }) => {- if self.levels.contains(&key) {- EffortPickerAction::Apply { level: key }- } else {- EffortPickerAction::None- }- }- None => EffortPickerAction::None,- }- }-- /// The picker's rendered frame (the shared menu-panel grammar).- #[must_use]- pub fn render(&self, theme: &Theme, width: usize, kb: &KeybindingsManager) -> Vec<Line> {- self.selector.render(theme, width, kb)- }-- /// The level rows the picker's list window renders (the click- /// surface's item-row span).- #[must_use]- pub fn visible_window(&self) -> (usize, usize) {- self.selector.visible_window()- }-- /// Move the selection to one filtered row (the click grammar's row- /// select — the arrow keys' exact movement, no apply).- pub fn select_position(&mut self, position: usize) {- self.selector.select_position(position);- }-}-#[cfg(test)]mod tests {use super::*;- use crate::theme::{ColorMode, Theme};-- fn kb() -> KeybindingsManager {- KeybindingsManager::new()- }-- fn theme() -> Theme {- Theme::builtin("prime", ColorMode::TrueColor)- }fn levels() -> Vec<String> {["off", "low", "medium", "high"]@@ -216,32 +106,4 @@ mod tests {outcome => panic!("expected unknown, got {outcome:?}"),}}-- #[test]- fn enter_applies_the_selected_level_and_escape_cancels() {- let mut picker = EffortPicker::new(&levels(), None);- assert_eq!(picker.handle_key("down", &kb()), EffortPickerAction::None);- assert_eq!(- picker.handle_key("enter", &kb()),- EffortPickerAction::Apply {- level: "low".to_string()- }- );- assert_eq!(- picker.handle_key("escape", &kb()),- EffortPickerAction::Cancel- );- }-- #[test]- fn the_frame_lists_levels_and_their_descriptions() {- let picker = EffortPicker::new(&levels(), None);- let frame = picker.render(&theme(), 60, &kb());- let text: Vec<String> = frame- .iter()- .map(|line| line.iter().map(|span| span.content.as_str()).collect())- .collect();- assert!(text.iter().any(|row| row.contains("Thinking Level")));- assert!(text.iter().any(|row| row.contains("medium")));- }}diff --git a/crates/pa-tui/src/lib.rs b/crates/pa-tui/src/lib.rsindex 9f42983e0d..4c02b052ce 100644--- a/crates/pa-tui/src/lib.rs+++ b/crates/pa-tui/src/lib.rs@@ -39,6 +39,7 @@ pub(crate) mod branch;pub(crate) mod browser;pub mod chat;pub mod chat_slash;+mod choice_picker;pub mod chrome;mod click_dispatch;pub mod client_auth;diff --git a/crates/pa-tui/src/session_ui.rs b/crates/pa-tui/src/session_ui.rsindex bf400f7579..55de7d07f4 100644--- a/crates/pa-tui/src/session_ui.rs+++ b/crates/pa-tui/src/session_ui.rs@@ -64,10 +64,11 @@ use crate::chat::{ChatEntry, CompactionReason, CompactionState, MessageBlock, RetryState, StatusKind,ToolResultView, WorkingState,};+use crate::choice_picker::{ChoicePickerAction, ChoicePurpose};use crate::click_dispatch::PressedClick;use crate::daemon_client::{DaemonClient, DaemonClientEvent};use crate::daemon_reconnect::RecoveryKind;-use crate::effort_picker::{self, EffortPickerAction};+use crate::effort_picker;use crate::export_share::{self, GhAuthStatus, GistOutcome};use crate::goal_surface::{format_goal_status, tray_goal_label, GoalPanel, GoalView};use crate::heartbeats_picker::{diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rsindex 7551bce61e..1d782679a6 100644--- a/crates/pa-tui/src/session_ui/commands.rs+++ b/crates/pa-tui/src/session_ui/commands.rs@@ -193,7 +193,7 @@ impl SessionUi {.map(str::to_string);match effort_picker::effort_command(&levels, current.as_deref(), &resolved.args) {effort_picker::EffortCommandOutcome::Open(picker) => {- view.effort_picker = Some(picker);+ view.choice_picker = Some(picker);self.track_feature_outcome("effort", "initiated", None);}effort_picker::EffortCommandOutcome::Unsupported => {diff --git a/crates/pa-tui/src/session_ui/keys.rs b/crates/pa-tui/src/session_ui/keys.rsindex 2126d57035..de389240fd 100644--- a/crates/pa-tui/src/session_ui/keys.rs+++ b/crates/pa-tui/src/session_ui/keys.rs@@ -1,9 +1,9 @@//! The terminal input grammar: key dispatch, mouse reports, paste,//! selection/auto-scroll, and the input-state seams.use super::{- key_event_to_id, AgentView, ChatEntry, DaemonCommand, DockFocusSource, Duration,- EffortPickerAction, Instant, KeyEvent, Map, QueueBrowseDirection, QueueLane, Result, SessionUi,- StatusKind, SubmitBehavior,+ key_event_to_id, AgentView, ChatEntry, ChoicePickerAction, ChoicePurpose, DaemonCommand,+ DockFocusSource, Duration, Instant, KeyEvent, Map, QueueBrowseDirection, QueueLane, Result,+ SessionUi, StatusKind, SubmitBehavior,};/// How long the Ctrl+C exit hint arms the second-press exit.@@ -85,7 +85,7 @@ impl SessionUi {return;}let overlay_focused = view.model_picker.is_some()- || view.effort_picker.is_some()+ || view.choice_picker.is_some()|| view.heartbeats_picker.is_some()|| view.goal_panel.is_some()|| view.bash_view.is_some()@@ -291,7 +291,9 @@ impl SessionUi {let _ = view.editor.handle_paste(text);}- async fn handle_effort_picker_key(+ /// One key press while the `/effort` picker is open: Esc/Ctrl+C close it+ /// without applying; Enter applies the picked row.+ async fn handle_choice_picker_key(&mut self,key: KeyEvent,view: &mut AgentView,@@ -305,18 +307,21 @@ impl SessionUi {self.exit_guard.note_ctrl_c_handled();}let action = view- .effort_picker+ .choice_picker.as_mut().map(|picker| picker.handle_key(&id, view.editor.keybindings()));match action {- Some(EffortPickerAction::None) | None => {}- Some(EffortPickerAction::Cancel) => {- view.effort_picker = None;+ Some(ChoicePickerAction::None) | None => {}+ Some(ChoicePickerAction::Cancel) => {+ view.choice_picker = None;self.dirty = true;}- Some(EffortPickerAction::Apply { level }) => {- view.effort_picker = None;- self.apply_thinking_level(&level, view).await;+ Some(ChoicePickerAction::Apply { purpose, key }) => {+ view.choice_picker = None;+ self.dirty = true;+ match purpose {+ ChoicePurpose::Effort => self.apply_thinking_level(&key, view).await,+ }}}Ok(())@@ -338,8 +343,9 @@ impl SessionUi {if view.model_picker.is_some() {return self.handle_model_picker_key(key, view).await;}- if view.effort_picker.is_some() {- return self.handle_effort_picker_key(key, view).await;+ // The `/effort` picker owns the frame the same way.+ if view.choice_picker.is_some() {+ return self.handle_choice_picker_key(key, view).await;}if view.mcp_view.is_some() {return self.handle_mcp_view_key(key, view);diff --git a/crates/pa-tui/src/snapshot/decoder.rs b/crates/pa-tui/src/snapshot/decoder.rsindex 91964218e8..7d8440929a 100644--- a/crates/pa-tui/src/snapshot/decoder.rs+++ b/crates/pa-tui/src/snapshot/decoder.rs@@ -426,7 +426,7 @@ pub fn working_message_from_update(partial: &Value) -> Option<String> {.filter(|text| !text.is_empty())}-/// Decode one `custom`-role message into its transcript update: the+/// Decode one `custom`-role wire message into its transcript update: the/// session-command echo/result rows render; an invalid payload renders/// the malformed notice; everything else renders nothing.fn custom_row_update(message: &Value) -> Option<TurnUpdate> {diff --git a/crates/pa-tui/src/view.rs b/crates/pa-tui/src/view.rsindex f721b5fbe9..c43ab5e5c7 100644--- a/crates/pa-tui/src/view.rs+++ b/crates/pa-tui/src/view.rs@@ -85,7 +85,10 @@ pub struct AgentView {pub provider_auth: Option<crate::provider_auth::ProviderAuthSelector>,pub auth_panel: Option<crate::auth_panel::AuthPanel>,pub fork_selector: Option<crate::user_message_selector::UserMessageSelector>,- pub effort_picker: Option<crate::effort_picker::EffortPicker>,+ /// The `/effort` inline picker (TS+ /// `ThinkingSelectorComponent` seam): while set, it owns the whole frame+ /// like the model picker.+ pub(crate) choice_picker: Option<crate::choice_picker::ChoicePicker>,pub mcp_view: Option<crate::mcp_view::McpView>,/// The factory page: while set, it owns the editor dock like the/// inline pickers (one panel per live factory run) — the activity@@ -233,7 +236,7 @@ impl AgentView {picker.paste(text);return true;}- if let Some(picker) = self.effort_picker.as_mut() {+ if let Some(picker) = self.choice_picker.as_mut() {picker.paste(text);return true;}@@ -300,7 +303,7 @@ impl AgentView {provider_auth: None,auth_panel: None,fork_selector: None,- effort_picker: None,+ choice_picker: None,mcp_view: None,factory_view: None,heartbeats_picker: None,diff --git a/crates/pa-tui/src/view/click.rs b/crates/pa-tui/src/view/click.rsindex 4ba41fd393..6499134f17 100644--- a/crates/pa-tui/src/view/click.rs+++ b/crates/pa-tui/src/view/click.rs@@ -21,8 +21,9 @@ pub(crate) enum ClickAction {},/// Move the `/model` picker's selection to the clicked filtered row.SelectModelRow(usize),- /// Move the `/effort` picker's selection to the clicked filtered row.- SelectEffortRow(usize),+ /// Move the `/effort` picker's selection to the+ /// clicked filtered row.+ SelectChoiceRow(usize),/// Open the activity dock group the click landed on (operator/// directive 2026-09-29). The target spans one group's segment.OpenDockGroup(crate::chrome::ActivityGroup),@@ -83,16 +84,16 @@ pub(crate) struct PickerClickSurface {#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum PickerKind {Model,- Effort,+ Choice,}/// The `/model` picker's chrome rows: the bordered search field/// renders exactly three rows.pub(crate) const MODEL_PICKER_CHROME_ROWS: usize = 3;-/// The `/effort` picker's chrome rows: the config selector's header-/// block plus the bordered search field.-pub(crate) const EFFORT_PICKER_CHROME_ROWS: usize = 6;+/// The `/effort` picker's chrome rows: the config+/// selector's header block plus the bordered search field.+pub(crate) const CHOICE_PICKER_CHROME_ROWS: usize = 6;/// The last composed frame's clickable geometry; the inline compose/// clears it.@@ -192,7 +193,7 @@ impl AgentView {.filter(|item| *item < visible)?;return Some(match picker.kind {PickerKind::Model => ClickAction::SelectModelRow(picker.items.0 + item),- PickerKind::Effort => ClickAction::SelectEffortRow(picker.items.0 + item),+ PickerKind::Choice => ClickAction::SelectChoiceRow(picker.items.0 + item),});}// The dock's chrome rows resolve before the editor: their rowsdiff --git a/crates/pa-tui/src/view/frame.rs b/crates/pa-tui/src/view/frame.rsindex 41af8faded..cb7b3e7d41 100644--- a/crates/pa-tui/src/view/frame.rs+++ b/crates/pa-tui/src/view/frame.rs@@ -3,7 +3,7 @@//! cursor query, and the compose free helpers.use super::click::{- self, PickerClickSurface, PickerKind, EFFORT_PICKER_CHROME_ROWS, MODEL_PICKER_CHROME_ROWS,+ self, PickerClickSurface, PickerKind, CHOICE_PICKER_CHROME_ROWS, MODEL_PICKER_CHROME_ROWS,};use super::AgentView;use super::FULLSCREEN_MIN_TRANSCRIPT_ROWS;@@ -59,14 +59,14 @@ impl AgentView {kind: PickerKind::Model,});Some(dock)- } else if let Some(picker) = &self.effort_picker {+ } else if let Some(picker) = &self.choice_picker {let mut dock = prompt_context;dock.extend(picker.render(&self.theme, width, self.editor.keybindings()));self.click.record_picker(PickerClickSurface {dock_row: pane_row,- chrome_rows: EFFORT_PICKER_CHROME_ROWS,+ chrome_rows: CHOICE_PICKER_CHROME_ROWS,items: picker.visible_window(),- kind: PickerKind::Effort,+ kind: PickerKind::Choice,});Some(dock)} else if let Some(mcp_view) = self.mcp_view.as_mut() {@@ -280,7 +280,7 @@ impl AgentView {pub fn frame_cursor(&self) -> Option<(usize, usize)> {if self.onboarding.is_some()|| self.model_picker.is_some()- || self.effort_picker.is_some()+ || self.choice_picker.is_some()|| self.heartbeats_picker.is_some()|| self.goal_panel.is_some()|| self.bash_view.is_some()diff --git a/crates/pa-tui/src/view/tests.rs b/crates/pa-tui/src/view/tests.rsindex d9845749bf..b5433007ef 100644--- a/crates/pa-tui/src/view/tests.rs+++ b/crates/pa-tui/src/view/tests.rs@@ -44,7 +44,7 @@ fn a_paste_never_reaches_the_editor_behind_an_overlay() {let editor_text = |view: &AgentView| view.editor.get_lines().join("\n");// The /effort picker takes it into its search.let mut v = view();- v.effort_picker = Some(crate::effort_picker::EffortPicker::new(+ v.choice_picker = Some(crate::choice_picker::ChoicePicker::effort(&["high".to_string()],None,));diff --git a/crates/pa-types/README.md b/crates/pa-types/README.mdindex 8670957008..1985632611 100644--- a/crates/pa-types/README.md+++ b/crates/pa-types/README.md@@ -18,6 +18,10 @@ Daemon wire mechanics shared by the serving side (pa-daemon) and clients (pa-tui(the TUI dispatch + autocomplete, the session engine's command admission,CLI suggestion help) plus its pure parse/suggestion helpers — the TSproduct keeps the same single table in core and imports it from its TUI.+ `DECISION_API_STATUS_CUSTOM_TYPE` is imported directly from this crate by+ consumers; higher crates do not re-export it. The durable row's+ `details.provider` is `jev`, `clef`, or null (off). Selected-branch metadata,+ rather than the compacted prompt transcript, determines restoration.- `incident`: the daemon incident classifier shared by the incident CLI(pa-cli's `prime-agent incident`, TS `src/cli/incident.ts`) and theagents-view incident notice (pa-tui's `incident_notices`, TSdiff --git a/crates/pa-types/src/platform/transport.rs b/crates/pa-types/src/platform/transport.rsindex 3607489101..9335fdb031 100644--- a/crates/pa-types/src/platform/transport.rs+++ b/crates/pa-types/src/platform/transport.rs@@ -178,7 +178,7 @@ pub fn unix_listener_definitely_closed(path: &Path) -> bool {#[cfg(not(target_os = "linux"))]{let _ = path;- return false;+ false}#[cfg(target_os = "linux")]{diff --git a/crates/pa-types/src/slash_commands.rs b/crates/pa-types/src/slash_commands.rsindex 5240fbbca3..cddab2721e 100644--- a/crates/pa-types/src/slash_commands.rs+++ b/crates/pa-types/src/slash_commands.rs@@ -11,7 +11,6 @@ pub const SESSION_SLASH_COMMAND_NAMES: [&str; 4] = ["compact", "refine", "goal",/// result, persisted in sessions and rendered by every surface.pub const SESSION_SLASH_COMMAND_CUSTOM_TYPE: &str = "session_slash_command";pub const SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE: &str = "session_slash_command_result";-#[must_use]pub fn is_session_slash_command_name(value: &str) -> bool {SESSION_SLASH_COMMAND_NAMES.contains(&value)diff --git a/docs/decision-api.md b/docs/decision-api.mdnew file mode 100644index 0000000000..c42ca1c781--- /dev/null+++ b/docs/decision-api.md@@ -0,0 +1,103 @@+# Decision API setup and verification++The Decision API is experimental and off by default. It runs the+`decision-api` skill's System 1 / System 2 control loop, with System 1+serving one fast decision per observation.++Configure the decision model in settings.json. The canonical test target+is Prime Inference's hosted clef (baseUrl+https://api.pinference.ai/api/v1, the stored login's team header):++```json+{ "decisionApi": { "systemOneModel": "prime-inference/cloudflare/clef" } }+```++The value is a registry model reference (`"provider/model-id"` or a bare id)+resolved exactly like `imageModel`: it must match an available, authenticated+model in the model registry. Requests then ride the model's normal provider+transport (the Anthropic / OpenAI-compatible request paths) with the+credentials the registry resolves for it — the Decision API has no transport+or credential store of its own. A vision-capable model there also serves+decision images.++While the setting is unset, the feature stays off: the system prompt omits+the `decision-api` skill and every decision request refuses with a message+naming the setting. Setting it to a resolvable reference turns the feature+on for new sessions and kernels (the prompt inclusion and the kernel's+pre-import of the `decision_api` module are gated at session and kernel+start; an existing kernel pre-imports it only after a restart). Stopping an+active control loop before changing the setting avoids half-learned state.++The loop runs System 1 as a spawned decision child+(`rlm.spawn(..., kind="decision")`): the child's model is the setting's+reference, its every message is one decision request served by one model+call, and it lives exactly as long as the loop. Goals flow to it as tagged+`decision_api.goal` agent messages (an older goal never overwrites a newer+one), and its answers return to the loop as tagged `decision_api.decision`+messages.++The decision models ride two transports, chosen by the model's api: the+System One structured-decision protocol (`"api": "systemone"`, Prime+Inference's hosted clef — the request body POSTs to the model's baseUrl ++`/systemone` and the reply envelope carries the answers), or the ordinary+chat-completion transports, where decide() renders the decision prompt+and parses the model's JSON answer. The systemone transport rides the+request body verbatim, so the protocol's full contract holds — clef's+joint schema head: one state plus a schema of typed questions, answered+with a probability for every allowed option of every question in a single+forward pass (no free-form generation, no output parsing; images read as+state). decide() composes the single `action` question today; the+transport carries a multi-question schema unchanged. The model registry recipe for the+hosted clef (the pinned Prime Inference deployment):++```json+{ "providers": { "prime-inference": {+ "baseUrl": "https://api.pinference.ai/api/v1",+ "apiKey": "ENV_VAR_NAME",+ "api": "systemone",+ "models": [ { "id": "cloudflare/clef", "input": ["text", "image"] } ]+} } }+```++The live round trip is `PA_DECISION_LIVE=1` with+`PA_DECISION_LIVE_API_KEY` (and `PA_DECISION_LIVE_TEAM_ID`) set:+`cargo test -p pa-core --test decision_api_live`.++## Opt-in live smoke checks++These checks make billed provider requests. Run them only when intentionally+verifying live access with your own credentials. Normal Rust and Python tests+use synthetic fixtures and do not establish current production availability or+latency. No live call is required merely to store the setting.++In a Prime Agent session with the setting configured, wait for a Python cell+to run in the persistent REPL (restart the kernel if it predates the+configuration change). Execute one text decision:++```python+result = await decision_api.decide(+ {"target_direction": "left"},+ {"left": "Move toward a target on the left", "right": "Move toward a target on the right"},+ goal="Move toward the target",+)+assert result["action"] in {"left", "right"}, result+assert 0 <= result["confidence"] <= 1, result+print(result)+```++With a vision-capable model, additionally pass+`images=[png_data_url]` using a real, small PNG, JPEG, or WebP data URL+relevant to the observation. Use up to four images; avoid degenerate+single-pixel images. Keep the request synthetic and record the returned+`model`, action, confidence, and `latency_ms` without credentials. Do not+demand an exact probability or latency from a nondeterministic live service.++Clearing the setting hides the skill again on the next session build. If you+explicitly import it in an unconfigured session, `decide` must refuse with+the host's message naming the setting before contacting any provider.++The [skill guide](../skills/decision-api/SKILL.md) covers loop design and+System 2 operation. A provider smoke check verifies a single host call; it+does not prove a live System 2 child, a full control loop, or environment+cleanup. Record those checks separately with the runtime and environment+used.diff --git a/examples/catch/.gitignore b/examples/catch/.gitignorenew file mode 100644index 0000000000..a1e03960fb--- /dev/null+++ b/examples/catch/.gitignore@@ -0,0 +1 @@+runs/diff --git a/examples/catch/README.md b/examples/catch/README.mdnew file mode 100644index 0000000000..c22bb63d2d--- /dev/null+++ b/examples/catch/README.md@@ -0,0 +1,63 @@+# Catch++Catch is a small Gym-style environment for the Decision API skill. Install+[uv](https://docs.astral.sh/uv/) and use Python 3.11 or newer. `uv run` installs+the game's declared pygame dependency. Install ffmpeg on PATH to record MP4;+use `record=False` when recording is unnecessary. `headless=True` runs without+a display. Each run writes into its own `examples/catch/runs/catch-*` directory.++In Prime Agent, set `decisionApi.systemOneModel` in settings.json to a+registry model reference (vision-capable for image-based observations) and+restart the session or kernel; the `decision-api` skill appears once the+setting resolves. Run this in the persistent Python REPL with the skill+enabled, substituting the repository path:++```python+import sys+sys.path.insert(0, "<repo>/examples/catch")+import env++catch = await env.CatchEnv.make(seconds=60, seed=1, record=False, headless=True)+loop = None+try:+ observation, info = await catch.reset()++ async def observe():+ return None if observation.get("done") or observation.get("truncated") else observation++ async def act(action):+ global observation+ observation, reward, terminated, truncated, info = await catch.step(action)+ if terminated or truncated:+ observation = {**observation, "done": True}++ loop = decision_api.Loop(observe, act, catch.actions, objective="Catch the falling circles", tick=0.1)+ # A vision-capable System 1 reads the compact text state and sees the+ # rendered frame; drop these two lines for a text-only model.+ loop.state = env.observation_state+ loop.images = env.observation_images+ loop.start()+ while (await loop.wait(timeout=10))["running"]:+ print(loop.status(), loop.errors[-3:])+ print(await catch.close())+finally:+ if loop is not None:+ await loop.stop()+ await catch.close()+```++The first `reset()` starts the episode clock. `step(action)` returns+`(observation, reward, terminated, truncated, info)`; reward is catches minus+drops since the previous step. `close()` returns the final score and optional+recording path and is safe to call again. The session agent designs the loop;+the environment supplies observations and applies actions.++Each observation is the text state (`picture`, `bowl`, `caught`, `missed`,+`done`) plus the rendered frame as a 360x360 PNG data URL (`image`). For a+vision-capable System 1, wire the split into the loop: `loop.state =+env.observation_state` keeps the data URL out of the text, and `loop.images =+env.observation_images` rides the frame as the decision request's image+block. Both helpers accept the observation as the loop passes it.++Run startup/artifact regression tests with+`python3 -m unittest discover -s examples/catch -p 'test_*.py' -v`.diff --git a/examples/catch/env.py b/examples/catch/env.pynew file mode 100644index 0000000000..31a2f413ab--- /dev/null+++ b/examples/catch/env.py@@ -0,0 +1,198 @@+"""Catch as an environment. The session agent writes the decision-api loop.++ import sys; sys.path.insert(0, "<repo>/examples/catch")+ import env+ catch = await env.CatchEnv.make(seconds=60, seed=1)+ observation, info = await catch.reset()+ observation, reward, terminated, truncated, info = await catch.step("wait")+ result = await catch.close()++Each observation carries the text state (`picture`, `bowl`, `caught`,+`missed`, `done`) and the rendered frame as a PNG data URL (`image`).+`observation_state` and `observation_images` split it for the decision-api+loop: System 1 reads the compact text state and sees the frame as an image+block (vision-capable models only).+"""++from __future__ import annotations++import asyncio+import json+import tempfile+from pathlib import Path+from typing import Any++HERE = Path(__file__).resolve().parent+# What an action does to the bowl. When to take it is the agent's decision.+ACTIONS = {+ "wait": "Leave the bowl in its current column",+ "goto_far_left": "Move the bowl to the far left column",+ "goto_left": "Move the bowl to the left column",+ "goto_middle": "Move the bowl to the middle column",+ "goto_right": "Move the bowl to the right column",+ "goto_far_right": "Move the bowl to the far right column",+}+++def observation_state(+ observation: dict[str, Any], goal: str = "", history: list[dict[str, Any]] | None = None+) -> dict[str, Any]:+ """The compact text half of an observation for the loop's `state`+ callback: every field but the rendered frame. `observation_images`+ sends the frame as an image block, so the data URL never rides the+ text state too."""+ state: dict[str, Any] = {+ "observation": {key: value for key, value in observation.items() if key != "image"}+ }+ if history:+ state["recent_actions"] = history+ return state+++def observation_images(observation: dict[str, Any]) -> list[str] | None:+ """The observation's rendered frame as decision images for the loop's+ `images` callback: one PNG data URL, or None when there is no frame."""+ image = observation.get("image")+ if isinstance(image, str) and image.startswith("data:image/"):+ return [image]+ return None+++class CatchEnv:+ """One episode of Catch. `make` launches the window; `reset` starts the clock.++ `step` applies one action and returns the next observation, the reward+ (catches minus drops since the previous step), and whether the episode+ ended because time ran out (`terminated`) or the game process stopped+ early (`truncated`).+ """++ actions = ACTIONS++ def __init__(+ self,+ process: asyncio.subprocess.Process,+ reader: asyncio.StreamReader,+ writer: asyncio.StreamWriter,+ recording: Path | None,+ summary: Path,+ ) -> None:+ self.process = process+ self.reader = reader+ self.writer = writer+ self.recording = recording+ self.summary_path = summary+ self._lock = asyncio.Lock()+ self._caught = 0+ self._missed = 0+ self._started = False+ self._terminated = False+ self._closed = False+ self._result: dict[str, Any] | None = None++ @classmethod+ async def make(+ cls,+ seconds: float = 120,+ *,+ record: bool = True,+ headless: bool = False,+ seed: int | None = None,+ ) -> CatchEnv:+ runs = HERE / "runs"+ runs.mkdir(exist_ok=True)+ run = Path(tempfile.mkdtemp(prefix="catch-", dir=runs))+ recording = run / "recording.mp4" if record else None+ summary = run / "summary.json"+ command = ["uv", "run", "--quiet", str(HERE / "game.py"), "--seconds", str(seconds), "--summary", str(summary)]+ if recording:+ command += ["--record", str(recording)]+ if headless:+ command.append("--headless")+ if seed is not None:+ command += ["--seed", str(seed)]+ process = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.PIPE)+ writer = None+ try:+ assert process.stdout is not None+ line = await asyncio.wait_for(process.stdout.readline(), timeout=120)+ if not line.startswith(b"PORT "):+ raise RuntimeError(f"the game did not start (exit code {process.returncode})")+ reader, writer = await asyncio.open_connection("127.0.0.1", int(line.split()[1]))+ return cls(process, reader, writer, recording, summary)+ except BaseException:+ if writer is not None:+ writer.close()+ if process.returncode is None:+ try:+ process.terminate()+ except ProcessLookupError:+ pass+ try:+ await asyncio.wait_for(process.wait(), timeout=5)+ except TimeoutError:+ process.kill()+ await process.wait()+ raise++ async def reset(self) -> tuple[dict[str, Any], dict[str, int]]:+ """Start the episode and return the first observation."""+ if self._closed:+ raise RuntimeError("environment is closed")+ if self._started:+ raise RuntimeError("this environment runs one episode; make a new one to reset")+ observation = await self._request(op="observe")+ self._started = True+ self._caught = int(observation.get("caught", 0))+ self._missed = int(observation.get("missed", 0))+ return observation, {"caught": self._caught, "missed": self._missed}++ async def step(self, action: str) -> tuple[dict[str, Any], float, bool, bool, dict[str, int]]:+ """Apply `action` and return `(observation, reward, terminated, truncated, info)`."""+ if self._closed:+ raise RuntimeError("environment is closed")+ if not self._started:+ raise RuntimeError("call reset() before step()")+ if action not in ACTIONS:+ raise ValueError(f"unknown action {action!r}; actions are {', '.join(ACTIONS)}")+ acted = await self._request(op="act", action=action)+ if acted.get("ok") is False:+ raise ValueError(acted.get("error"))+ observation = await self._request(op="observe")+ if observation.get("truncated"):+ info = {"caught": self._caught, "missed": self._missed}+ return observation, 0.0, False, True, info+ caught = int(observation.get("caught", self._caught))+ missed = int(observation.get("missed", self._missed))+ reward = float((caught - self._caught) - (missed - self._missed))+ self._caught, self._missed = caught, missed+ terminated = bool(observation.get("done"))+ self._terminated = self._terminated or terminated+ return observation, reward, terminated, False, {"caught": caught, "missed": missed}++ async def render(self, *, system1: dict[str, Any] | None = None, system2: dict[str, Any] | None = None) -> None:+ """Show status on the game's side panel. The agent decides what to send."""+ await self._request(op="overlay", system1=system1 or {}, system2=system2 or {})++ async def close(self) -> dict[str, Any]:+ """Stop the game if it is still running and return the score and recording path."""+ if self._result is not None:+ return self._result+ self._closed = True+ self.writer.close()+ if self.process.returncode is None and not self._terminated:+ self.process.terminate()+ await self.process.wait()+ await self.writer.wait_closed()+ score = json.loads(self.summary_path.read_text()) if self.summary_path.exists() else None+ self._result = {"score": score, "recording": str(self.recording) if self.recording else None}+ return self._result++ async def _request(self, **request: Any) -> dict[str, Any]:+ async with self._lock:+ self.writer.write((json.dumps(request) + "\n").encode())+ await self.writer.drain()+ line = await self.reader.readline()+ if not line:+ return {"truncated": True}+ return json.loads(line)diff --git a/examples/catch/game.py b/examples/catch/game.pynew file mode 100644index 0000000000..77cce45362--- /dev/null+++ b/examples/catch/game.py@@ -0,0 +1,461 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["pygame-ce>=2.5"]+# ///+"""Catch: white circles fall in five columns; the bowl at the bottom catches them.++The game serves JSON lines on localhost for the decision-api loop:+ {"op": "observe"} -> game state as text plus the rendered frame (System 1's input)+ {"op": "act", "action": "wait" | "goto_far_left" | "goto_left" | "goto_middle" | "goto_right" | "goto_far_right"}+ {"op": "overlay", "system1": {...}, "system2": {...}}+It prints "PORT <n>" once listening. The clock starts on the first observe.+"""++from __future__ import annotations++import argparse+import base64+import io+import json+import math+import os+import random+import socketserver+import subprocess+import sys+import threading+import time+from dataclasses import dataclass+from pathlib import Path++GAME_W, H, PANEL_W = 720, 720, 400+W = GAME_W + PANEL_W+POSITIONS = ["far_left", "left", "middle", "right", "far_right"]+COLUMNS = len(POSITIONS)+COL_W = GAME_W / COLUMNS+GOTO = {f"goto_{name}": col for col, name in enumerate(POSITIONS, start=1)}+RIM_Y = 596+BOWL_W, BOWL_DEPTH = 104, 30+RADIUS = 15+FALL_SPEED = 300 # px/s for every circle: about 2 s from the top to the line+MOVE_SPEED = 4 * COL_W / 0.01 # px/s: column 1 to 5 within 10 ms, so a single frame+TRAIL_S = 0.12 # how long the afterimage of a move lingers+PICTURE_ROWS = 8+FRAME_SIDE = 360 # the rendered frame's width and height in the observation+FPS, VIDEO_FPS = 60, 30+MIN_GAP_S = 0.3+RATE_MIN, RATE_MAX = 0.3, 1 / MIN_GAP_S+SLIDER_Y = H - 52++WHITE = (255, 255, 255)+MUTED = (120, 120, 120)+FAINT = (40, 40, 40)+BLACK = (0, 0, 0)++# The compact brand butterfly from the TUI splash (pa-tui `PRIME_COMPACT_BUTTERFLY_LOGO`).+LOGO = [+ " ▗▄▄█▀",+ " ███▄ ▗▄███▀",+ " ▗█▛▐█▙ ▗▄█▀▗█▀",+ " ▗█▛ ▟██▙▄██▛ ▟▛",+ " ▗▟▌ ▐███▛▘▗▄█▖",+ "▟███▄ ▄▄▟███▀",+ "▜█▛▀▘ ▜█▛▀▘",+]+# Quadrants per block character: upper-left, upper-right, lower-left, lower-right.+QUADRANTS = {+ "▗": "0001", "▖": "0010", "▘": "1000", "▝": "0100", "▄": "0011", "▀": "1100",+ "▌": "1010", "▐": "0101", "█": "1111", "▛": "1110", "▜": "1101", "▙": "1011", "▟": "0111",+}+++def col_center(col: int) -> float:+ return (col - 0.5) * COL_W+++@dataclass+class Circle:+ col: int+ y: float+ done: bool = False+++class Game:+ def __init__(self, seconds: float, seed: int | None) -> None:+ self.rng = random.Random(seed)+ self.seconds = seconds+ self.lock = threading.Lock()+ self.started = False+ self.finished = False+ self.elapsed = 0.0+ self.circles: list[Circle] = []+ self.effects: list[tuple[str, float, float, float]] = []+ self.bowl_x = col_center(3)+ self.trail: list[tuple[float, float]] = []+ self.target_col = 3+ self.caught = self.missed = 0+ self.rate = 2.0+ self.next_spawn = 0.6+ self.system1: dict = {}+ self.system2: dict = {}+ self.frame: str | None = None+ self.latencies: list[float] = []+ self.goal_changed_at: float | None = None++ def bowl_col(self) -> int:+ return min(COLUMNS, max(1, int(self.bowl_x // COL_W) + 1))++ def handle(self, request: dict) -> dict:+ op = request.get("op")+ if op == "observe":+ self.started = True+ return self.observe()+ if op == "act":+ action = str(request.get("action"))+ if action in GOTO:+ self.target_col = GOTO[action]+ elif action != "wait":+ return {"ok": False, "error": f"unknown action {action!r}"}+ return {"ok": True}+ if op == "overlay":+ self.system1 = request.get("system1") or {}+ goal = (request.get("system2") or {}).get("goal")+ if goal != self.system2.get("goal"):+ self.goal_changed_at = time.monotonic()+ self.system2 = request.get("system2") or {}+ if isinstance(self.system1.get("latency_ms"), (int, float)):+ self.latencies = (self.latencies + [float(self.system1["latency_ms"])])[-90:]+ return {"ok": True}+ return {"ok": False, "error": f"unknown op {op!r}"}++ def observe(self) -> dict:+ rows = [["."] * COLUMNS for _ in range(PICTURE_ROWS)]+ for c in self.circles:+ if not c.done and 0 <= c.y <= RIM_Y:+ rows[min(PICTURE_ROWS - 1, int(c.y / (RIM_Y / PICTURE_ROWS)))][c.col - 1] = "o"+ bowl_row = ["."] * COLUMNS+ bowl_row[self.bowl_col() - 1] = "U"+ return {+ "picture": ["".join(row) for row in rows] + ["".join(bowl_row)],+ "bowl": POSITIONS[self.bowl_col() - 1],+ "caught": self.caught,+ "missed": self.missed,+ "done": self.finished,+ "image": self.frame,+ }++ def update(self, dt: float) -> None:+ now = time.monotonic()+ limit = MOVE_SPEED * dt+ self.bowl_x += max(-limit, min(limit, col_center(self.target_col) - self.bowl_x))+ self.trail = [p for p in self.trail if now - p[1] < TRAIL_S] + [(self.bowl_x, now)]+ self.effects = [e for e in self.effects if now - e[3] < 1.0]+ if not self.started or self.finished:+ return+ self.elapsed += dt+ if self.elapsed >= self.seconds:+ self.finished = True+ return+ self.next_spawn -= dt+ if self.next_spawn <= 0:+ self.circles.append(Circle(self.rng.randint(1, COLUMNS), -RADIUS))+ self.next_spawn = max(MIN_GAP_S, self.rng.uniform(0.8, 1.2) / self.rate)+ for c in self.circles:+ if c.done:+ continue+ c.y += FALL_SPEED * dt+ if c.y + RADIUS < RIM_Y:+ continue+ c.done = True+ x = col_center(c.col)+ if c.col == self.bowl_col():+ self.caught += 1+ self.effects.append(("catch", x, RIM_Y, now))+ else:+ self.missed += 1+ self.effects.append(("miss", x, RIM_Y, now))+ self.circles = [c for c in self.circles if not c.done]++ def set_rate(self, rate: float) -> None:+ self.rate = max(RATE_MIN, min(RATE_MAX, rate))+ self.next_spawn = min(self.next_spawn, max(MIN_GAP_S, 1.2 / self.rate))+++def slider_rate(x: float) -> float:+ left, right = GAME_W + 36, W - 36+ return RATE_MIN + (RATE_MAX - RATE_MIN) * max(0.0, min(1.0, (x - left) / (right - left)))+++def serve(game: Game) -> int:+ class Handler(socketserver.StreamRequestHandler):+ def handle(self) -> None:+ for line in self.rfile:+ try:+ request = json.loads(line)+ with game.lock:+ response = game.handle(request)+ except ValueError as error:+ response = {"ok": False, "error": str(error)}+ self.wfile.write((json.dumps(response) + "\n").encode())+ self.wfile.flush()++ class Server(socketserver.ThreadingTCPServer):+ allow_reuse_address = True+ daemon_threads = True++ server = Server(("127.0.0.1", 0), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ return server.server_address[1]+++class Renderer:+ def __init__(self, pygame) -> None:+ self.pg = pygame+ from pygame import gfxdraw++ self.gfx = gfxdraw+ self.screen = pygame.display.set_mode((W, H))+ from pygame._sdl2.video import Window++ Window.from_display_module().focus()+ self.ghosts = pygame.Surface((GAME_W, H))+ self.ghost_rect = pygame.Rect(0, RIM_Y - 20, GAME_W, H - RIM_Y + 20)+ pygame.display.set_caption("Catch - Prime Agent decision api")+ sans = "/System/Library/Fonts/HelveticaNeue.ttc"+ mono = "/System/Library/Fonts/SFNSMono.ttf"++ def font(path: str, size: int):+ return pygame.font.Font(path if os.path.exists(path) else None, size)++ self.f_time = font(sans, 34)+ self.f_small = font(sans, 15)+ self.f_label = font(sans, 12)+ self.f_action = font(mono, 28)+ self.f_value = font(mono, 15)+ self.f_goal = font(sans, 17)+ self.f_brand = font(sans, 22)++ def frame_data_url(self) -> str:+ """The play area (never the side panel) as one downscaled PNG data+ URL: the observation's image for vision-capable decision models."""+ play = self.screen.subsurface(self.pg.Rect(0, 0, GAME_W, H))+ small = self.pg.transform.smoothscale(play, (FRAME_SIDE, FRAME_SIDE))+ buffer = io.BytesIO()+ self.pg.image.save(small, buffer, ".png")+ return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()++ def text(self, font, value: str, color, pos, anchor: str = "topleft") -> None:+ surface = font.render(value, True, color)+ self.screen.blit(surface, surface.get_rect(**{anchor: pos}))++ def label(self, value: str, pos) -> None:+ x, y = pos+ for char in value:+ surface = self.f_label.render(char, True, MUTED)+ self.screen.blit(surface, (x, y))+ x += surface.get_width() + 2++ def circle(self, x: float, y: float, r: int, color, surface=None) -> None:+ surface = surface or self.screen+ self.gfx.filled_circle(surface, int(x), int(y), r, color)+ self.gfx.aacircle(surface, int(x), int(y), r, color)++ def figure(self, x: float, color=WHITE, surface=None) -> None:+ surface = surface or self.screen+ xi = int(round(x))+ bowl = [(xi + math.cos(math.pi * i / 32) * BOWL_W / 2, RIM_Y + math.sin(math.pi * i / 32) * BOWL_DEPTH) for i in range(33)]+ self.gfx.filled_polygon(surface, bowl, color)+ self.gfx.aapolygon(surface, bowl, color)+ line = self.pg.draw.line+ line(surface, color, (xi - 28, RIM_Y + 20), (xi - 14, 670), 3)+ line(surface, color, (xi + 28, RIM_Y + 20), (xi + 14, 670), 3)+ self.circle(xi, 650, 9, color, surface)+ line(surface, color, (xi, 662), (xi, 698), 3)+ line(surface, color, (xi, 698), (xi - 10, 716), 3)+ line(surface, color, (xi, 698), (xi + 10, 716), 3)++ def afterimage(self, game: Game, now: float) -> None:+ trail = game.trail+ if max((abs(x - game.bowl_x) for x, _ in trail), default=0.0) < 1:+ return+ self.ghosts.fill(BLACK, self.ghost_rect)+ for (x0, t0), (x1, t1) in zip(trail, trail[1:]):+ steps = max(1, int(abs(x1 - x0) / 10))+ for i in range(steps):+ f = i / steps+ fade = 1 - (now - (t0 + (t1 - t0) * f)) / TRAIL_S+ if fade > 0:+ self.figure(x0 + (x1 - x0) * f, (int(110 * fade * fade),) * 3, self.ghosts)+ blurred = self.pg.transform.gaussian_blur(self.ghosts.subsurface(self.ghost_rect), 5)+ self.screen.blit(blurred, self.ghost_rect.topleft, special_flags=self.pg.BLEND_ADD)++ def logo(self, x0: int, y0: int, quadrant: int = 2) -> None:+ # Terminal cells are twice as tall as wide, so each quadrant is 1:2.+ for row, chars in enumerate(LOGO):+ for col, char in enumerate(chars):+ for i, bit in enumerate(QUADRANTS.get(char, "0000")):+ if bit == "1":+ x = x0 + (col * 2 + i % 2) * quadrant+ y = y0 + (row * 2 + i // 2) * quadrant * 2+ self.pg.draw.rect(self.screen, WHITE, (x, y, quadrant, quadrant * 2))++ def wrap(self, value: str, font, width: int) -> list[str]:+ lines, current = [], ""+ for word in value.split():+ candidate = f"{current} {word}".strip()+ if font.size(candidate)[0] <= width:+ current = candidate+ else:+ lines.append(current)+ current = word+ return lines + ([current] if current else [])++ def draw(self, game: Game) -> None:+ screen, now = self.screen, time.monotonic()+ screen.fill(BLACK)+ for x in range(5, GAME_W, 14):+ self.pg.draw.rect(screen, MUTED, (x, RIM_Y - 1, 4, 2))+ for c in game.circles:+ self.circle(col_center(c.col), c.y, RADIUS, WHITE)+ for kind, x, y, t0 in game.effects:+ t = (now - t0) / (0.5 if kind == "catch" else 1.0)+ if t < 1:+ shade = int(255 * (1 - t))+ if kind == "catch":+ self.gfx.aacircle(screen, int(x), int(y), int(RADIUS + 34 * t), (shade,) * 3)+ else:+ self.pg.draw.line(screen, (shade,) * 3, (x - 14, y), (x + 14, y), 2)+ self.afterimage(game, now)+ self.figure(game.bowl_x)++ left = max(0.0, game.seconds - game.elapsed)+ self.text(self.f_time, f"{int(left) // 60}:{int(left) % 60:02d}", WHITE, (GAME_W // 2, 24), "midtop")+ self.text(self.f_small, f"{game.caught} caught {game.missed} dropped", MUTED, (GAME_W // 2, 66), "midtop")+ if not game.started:+ self.text(self.f_small, "waiting for agent", MUTED, (GAME_W // 2, H // 2), "center")+ if game.finished:+ self.text(self.f_time, f"{game.caught} / {game.caught + game.missed}", WHITE, (GAME_W // 2, H // 2 - 30), "center")+ self.text(self.f_small, "caught", MUTED, (GAME_W // 2, H // 2 + 6), "center")++ x0 = GAME_W + 36+ self.pg.draw.line(screen, FAINT, (GAME_W, 0), (GAME_W, H))+ self.logo(x0, 40)+ self.text(self.f_brand, "prime agent", WHITE, (x0 + 104, 50))+ self.text(self.f_label, "decision api", MUTED, (x0 + 105, 80))++ s1, s2 = game.system1, game.system2+ self.label("SYSTEM 1", (x0, 150))+ self.text(self.f_label, str(s1.get("model") or "-"), MUTED, (W - 36, 150), "topright")+ action = str(s1.get("action") or "-")+ label = POSITIONS[GOTO[action] - 1].replace("_", "-") if action in GOTO else action+ self.text(self.f_action, label, WHITE, (x0, 176))+ confidence = s1.get("confidence")+ if isinstance(confidence, (int, float)):+ self.text(self.f_value, f"{confidence:.2f}", MUTED, (W - 36, 186), "topright")+ latency = s1.get("latency_ms")+ self.text(self.f_label, "latency", MUTED, (x0, 230))+ self.text(self.f_value, f"{latency:.0f} ms" if isinstance(latency, (int, float)) else "-", WHITE, (W - 36, 227), "topright")+ if len(game.latencies) > 1:+ top = max(400.0, max(game.latencies))+ span = PANEL_W - 72+ points = [+ (x0 + span * i / (len(game.latencies) - 1), 300 - 44 * value / top)+ for i, value in enumerate(game.latencies)+ ]+ self.pg.draw.aalines(screen, WHITE, False, points)+ self.pg.draw.line(screen, FAINT, (x0, 300), (W - 36, 300))++ self.pg.draw.line(screen, FAINT, (x0, 336), (W - 36, 336))+ self.label("SYSTEM 2", (x0, 362))+ self.text(self.f_label, str(s2.get("model") or "-"), MUTED, (W - 36, 362), "topright")+ lines = self.wrap(str(s2.get("goal") or "-"), self.f_goal, PANEL_W - 72)[:8]+ for i, line in enumerate(lines):+ self.text(self.f_goal, line, WHITE, (x0, 392 + i * 25))+ if game.goal_changed_at is not None:+ self.text(self.f_label, f"updated {now - game.goal_changed_at:.0f} s ago", MUTED, (x0, 400 + len(lines) * 25))++ right = W - 36+ self.pg.draw.line(screen, FAINT, (x0, SLIDER_Y - 50), (right, SLIDER_Y - 50))+ self.label("CIRCLES", (x0, SLIDER_Y - 30))+ self.text(self.f_value, f"{game.rate:.1f} / s", WHITE, (right, SLIDER_Y - 33), "topright")+ knob = x0 + (right - x0) * (game.rate - RATE_MIN) / (RATE_MAX - RATE_MIN)+ self.pg.draw.line(screen, FAINT, (x0, SLIDER_Y), (right, SLIDER_Y), 2)+ self.pg.draw.line(screen, WHITE, (x0, SLIDER_Y), (knob, SLIDER_Y), 2)+ self.circle(knob, SLIDER_Y, 7, WHITE)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--seconds", type=float, default=120)+ parser.add_argument("--record", type=Path, help="write an mp4 of the run (needs ffmpeg)")+ parser.add_argument("--summary", type=Path, help="write the final score as json")+ parser.add_argument("--seed", type=int)+ parser.add_argument("--headless", action="store_true")+ args = parser.parse_args()+ if args.headless:+ os.environ["SDL_VIDEODRIVER"] = "dummy"+ os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")+ import pygame++ pygame.init()+ game = Game(args.seconds, args.seed)+ renderer = Renderer(pygame)+ renderer.draw(game)+ game.frame = renderer.frame_data_url()+ print(f"PORT {serve(game)}", flush=True)++ video = None+ frames = 0+ record_start = 0.0+ finished_at = None+ clock = pygame.time.Clock()+ last = time.monotonic()+ dragging = False+ while True:+ for event in pygame.event.get():+ if event.type == pygame.QUIT:+ finished_at = finished_at or 0.0+ elif event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > GAME_W and abs(event.pos[1] - SLIDER_Y) < 18:+ dragging = True+ elif event.type == pygame.MOUSEBUTTONUP:+ dragging = False+ if dragging and event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEMOTION):+ with game.lock:+ game.set_rate(slider_rate(event.pos[0]))+ now = time.monotonic()+ with game.lock:+ game.update(min(0.05, now - last))+ renderer.draw(game)+ game.frame = renderer.frame_data_url()+ started, finished = game.started, game.finished+ last = now+ pygame.display.flip()+ if args.record and started and video is None:+ video = subprocess.Popen(+ ["ffmpeg", "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}",+ "-r", str(VIDEO_FPS), "-i", "-", "-c:v", "libx264", "-preset", "veryfast", "-crf", "18",+ "-pix_fmt", "yuv420p", str(args.record)],+ stdin=subprocess.PIPE,+ )+ record_start = now+ if video is not None:+ frame = pygame.image.tobytes(renderer.screen, "RGB")+ while frames < int((now - record_start) * VIDEO_FPS):+ video.stdin.write(frame)+ frames += 1+ if finished and finished_at is None:+ finished_at = now+ if finished_at is not None and (finished_at == 0.0 or now - finished_at > 3):+ break+ clock.tick(FPS)+ if video is not None:+ video.stdin.close()+ video.wait()+ if args.summary:+ args.summary.write_text(json.dumps({"caught": game.caught, "missed": game.missed, "seconds": game.elapsed}))+ pygame.quit()+ sys.exit(0)+++if __name__ == "__main__":+ main()diff --git a/examples/catch/test_env.py b/examples/catch/test_env.pynew file mode 100644index 0000000000..2a6c605425--- /dev/null+++ b/examples/catch/test_env.py@@ -0,0 +1,165 @@+"""Catch startup owns its subprocess, including failed and cancelled startup.+The observation helpers split the rendered frame from the text state."""++import asyncio+import base64+import shutil+import struct+import tempfile+import unittest+from pathlib import Path+from unittest.mock import AsyncMock, patch++import env+++class Process:+ def __init__(self, line=b"PORT 12345\n"):+ self.stdout = type("Stdout", (), {"readline": AsyncMock(return_value=line)})()+ self.returncode = None+ self.reaped = False++ def terminate(self):+ self.returncode = -15++ def kill(self):+ self.returncode = -9++ async def wait(self):+ self.reaped = True+ return self.returncode+++class CatchTests(unittest.IsolatedAsyncioTestCase):+ async def asyncSetUp(self):+ self.directory = tempfile.TemporaryDirectory()+ self.addCleanup(self.directory.cleanup)+ self.here = patch.object(env, "HERE", Path(self.directory.name))+ self.here.start()+ self.addCleanup(self.here.stop)++ async def test_concurrent_runs_have_independent_artifacts(self):+ processes = [Process(), Process()]+ writer = type("Writer", (), {"close": lambda _self: None, "wait_closed": AsyncMock()})()+ with (+ patch.object(asyncio, "create_subprocess_exec", AsyncMock(side_effect=processes)),+ patch.object(asyncio, "open_connection", AsyncMock(return_value=(None, writer))),+ ):+ first, second = await asyncio.gather(env.CatchEnv.make(), env.CatchEnv.make())+ self.assertNotEqual(first.summary_path, second.summary_path)+ self.assertNotEqual(first.recording, second.recording)+ self.assertNotEqual(first.summary_path.parent, second.summary_path.parent)+ await asyncio.gather(first.close(), second.close())+ self.assertTrue(all(process.reaped for process in processes))++ async def test_failed_startup_terminates_and_reaps_process(self):+ for line, failure in ((b"bad startup\n", RuntimeError), (b"PORT invalid\n", ValueError)):+ process = Process(line)+ with patch.object(asyncio, "create_subprocess_exec", AsyncMock(return_value=process)):+ with self.assertRaises(failure):+ await env.CatchEnv.make(record=False)+ self.assertEqual(process.returncode, -15)+ self.assertTrue(process.reaped)++ async def test_connection_failure_terminates_and_reaps_process(self):+ process = Process()+ with (+ patch.object(asyncio, "create_subprocess_exec", AsyncMock(return_value=process)),+ patch.object(asyncio, "open_connection", AsyncMock(side_effect=ConnectionRefusedError)),+ ):+ with self.assertRaises(ConnectionRefusedError):+ await env.CatchEnv.make(record=False)+ self.assertEqual(process.returncode, -15)+ self.assertTrue(process.reaped)++ async def test_cancelled_startup_terminates_and_reaps_process(self):+ process = Process()+ process.stdout.readline.side_effect = asyncio.CancelledError+ with patch.object(asyncio, "create_subprocess_exec", AsyncMock(return_value=process)):+ with self.assertRaises(asyncio.CancelledError):+ await env.CatchEnv.make(record=False)+ self.assertEqual(process.returncode, -15)+ self.assertTrue(process.reaped)+++class ObservationHelperTests(unittest.TestCase):+ def observation(self, image="data:image/png;base64,aGVsbG8="):+ return {+ "picture": [".....", "..U.."],+ "bowl": "middle",+ "caught": 3,+ "missed": 4,+ "done": False,+ "image": image,+ }++ def test_state_keeps_the_text_and_drops_the_frame(self):+ state = env.observation_state(self.observation())+ self.assertEqual(+ state["observation"],+ {"picture": [".....", "..U.."], "bowl": "middle", "caught": 3, "missed": 4, "done": False},+ )++ def test_state_keeps_the_text_when_there_is_no_frame(self):+ observation = self.observation(image=None)+ state = env.observation_state(observation)+ self.assertNotIn("image", state["observation"])+ self.assertEqual(state["observation"]["caught"], 3)++ def test_state_carries_recent_actions(self):+ history = [{"step": 0, "action": "wait", "confidence": 0.5, "latency_ms": 1.0}]+ state = env.observation_state(self.observation(), history=history)+ self.assertEqual(state["recent_actions"], history)++ def test_images_pass_the_frame_through_as_a_data_url(self):+ self.assertEqual(env.observation_images(self.observation()), ["data:image/png;base64,aGVsbG8="])+ self.assertIsNone(env.observation_images(self.observation(image=None)))+ self.assertIsNone(env.observation_images(self.observation(image="not-a-data-url")))+++class LiveObservationFrameTests(unittest.IsolatedAsyncioTestCase):+ """The game serves a real rendered frame: a decodable PNG of the play+ area. Skipped when `uv` cannot run the game (its declared pygame+ dependency resolves through uv)."""++ @classmethod+ def setUpClass(cls):+ if shutil.which("uv") is None:+ raise unittest.SkipTest("uv is not on PATH; the game cannot start")++ async def asyncSetUp(self):+ self.environment = await env.CatchEnv.make(seconds=5, seed=1, record=False, headless=True)++ def assert_play_area_png(self, url):+ prefix, _, data = url.partition(",")+ self.assertEqual(prefix, "data:image/png;base64")+ png = base64.b64decode(data, validate=True)+ self.assertEqual(png[:8], b"\x89PNG\r\n\x1a\n")+ width, height = struct.unpack(">II", png[16:24])+ self.assertEqual((width, height), (360, 360))++ async def test_the_observation_carries_a_play_area_png(self):+ observation, _ = await self.environment.reset()+ self.assertIn("picture", observation)+ self.assertIn("bowl", observation)+ self.assert_play_area_png(observation["image"])++ async def test_the_frame_tracks_the_game(self):+ observation, _ = await self.environment.reset()+ first = observation["image"]+ # The seeded first circle spawns at 0.6 s and is mid-fall here, so+ # the frame must move with the game, not stay the opening render.+ await asyncio.sleep(0.8)+ observation, _, terminated, truncated, _ = await self.environment.step("wait")+ self.assertFalse(terminated or truncated)+ second = observation["image"]+ self.assert_play_area_png(second)+ self.assertNotEqual(first, second)++ async def asyncTearDown(self):+ await self.environment.close()+ shutil.rmtree(self.environment.summary_path.parent, ignore_errors=True)+++if __name__ == "__main__":+ unittest.main()diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex a90756641d..94169486d0 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -173,6 +173,7 @@ async def spawn(name: str,model: str | None = None,thinking: str | None = None,+ kind: str | None = None,) -> RLMSpawnHandle:"""Spawn a recursive Prime Agent child and return once its task is admitted.@@ -180,14 +181,20 @@ async def spawn(``model`` selects a child with an exact ``provider/model`` selector.``thinking`` sets the child reasoning level (e.g. 'off', 'low', 'medium', 'high');defaults to the parent level; levels invalid for the resolved model fail the spawn.+ ``kind`` selects a dedicated child kind; ``"decision"`` spawns the Decision API+ child (the model comes from the decisionApi.systemOneModel setting)."""if not isinstance(prompt, str):raise TypeError(f"prompt must be str, got {type(prompt).__name__}")+ if kind is not None and kind != "decision":+ raise TypeError(f"kind must be 'decision' or None, got {kind!r}")kwargs: dict[str, Any] = {"name": name}if model is not None:kwargs["model"] = modelif thinking is not None:kwargs["thinking"] = thinking+ if kind is not None:+ kwargs["kind"] = kind# Wire type stays "rlm.run" so kernels and hosts of different versions stay compatible.payload = await host_request("rlm.run", {"prompt": prompt, "kwargs": kwargs})return _spawn_handle_from_payload(payload)@@ -629,8 +636,9 @@ class _RLMNamespace:name: str,model: str | None = None,thinking: str | None = None,+ kind: str | None = None,) -> RLMSpawnHandle:- return await spawn(prompt, name=name, model=model, thinking=thinking)+ return await spawn(prompt, name=name, model=model, thinking=thinking, kind=kind)async def create_session(self,diff --git a/skills/decision-api/SKILL.md b/skills/decision-api/SKILL.mdnew file mode 100644index 0000000000..7f1f93db4f--- /dev/null+++ b/skills/decision-api/SKILL.md@@ -0,0 +1,130 @@+---+name: decision-api+description: Experimental System 1 / System 2 loop for real-time, low-latency tasks. System 1 is the model named by the decisionApi.systemOneModel setting, served by a spawned decision child that picks every action from observations; System 2 is you, the parent, routing goals to it as messages. You design, measure, and optimize the whole loop. Requires the decisionApi.systemOneModel setting.+---++# Decision API (System 1 / System 2)++Use this for real-time control tasks where every step is one choice from an+action set (a game, a device, a UI) and a full agent turn per step is too slow.++- **System 1** is the decision model the user configured: the+ `decisionApi.systemOneModel` setting names it. The canonical target is+ Prime Inference's hosted structured-decision clef+ (`prime-inference/cloudflare/clef`, served at+ https://api.pinference.ai/api/v1 with the stored login's team header);+ any registry model reference that resolves can serve the role, and a+ resolvable reference turns the feature on. `Loop` spawns it as a decision child (`rlm.spawn(kind="decision")`)+ whose every message is one decision request: each observation becomes one+ model call that returns the chosen action and its confidence. The child+ lives exactly as long as the loop. `loop.status()["system1_model"]`+ reports the model that served each decision.+- **System 2** is you, the parent running the loop. `loop.set_goal("...")`+ routes updated goals to the child as tagged agent messages, and every+ decision the child serves reads the latest goal. Goals are one or two+ sentences of strategy, never an action name or a step-by-step command.++## Your role: optimize the whole loop++You own the loop's design and performance:+- what System 1 sees (`state`, and `images` with a vision-capable model);+- how its question reads (`instructions` and the action descriptions);+- its `history_size`, `tick`, and `decide_timeout`;+- the goals you route with `set_goal` and the `objective` they refine.++Writing the task's strategy into System 1's instructions and action+descriptions is loop design, not goal routing.++Diagnose from the outcome before changing anything. The task's own result+(score, success rate) is the measure; `loop.history` confidences and+`loop.goal_updates` explain it.+- **System 1 problems:** low confidence, actions flipping between options,+ or failures while the goal stays the same. Give `state` the information+ the decision needs, sharpen `instructions`, or make the action descriptions+ easier to tell apart.+- **Goal problems:** goals that are wrong, churn, or lag the situation.+ Update the goal only when the situation genuinely needs a new direction;+ `loop.goal` starts as the `objective`.+- **No goals needed:** for pure reflexes or one fixed strategy, never call+ `set_goal`; the objective alone is enough.++Change one thing at a time and compare runs under the same conditions (same+seed or scenario, same duration), keeping what measurably helps. Make changes+through the loop's settings or the task's own code, never by editing this+skill's package. Do the analysis yourself rather than delegating it to extra+subagents.++You never steer the live loop by hand:+- Do not choose actions from observations yourself.+- Do not message the decision child directly; `set_goal` is the route.+- `loop.goal` is yours (it starts as the `objective`): `set_goal` updates+ it live.++## Setup++The Decision API is off until configured: the user sets+`decisionApi.systemOneModel` in settings.json to a registry model reference+(`"provider/model-id"` or a bare id) and restarts the session or kernel. The+host resolves the model and its credentials through the model registry — the+same path any other model call takes — and makes every provider call. If a+call reports the setting is unset or unresolvable, ask the user to fix the+setting. Do not ask for keys yourself.++## Usage++Write `observe` and `act` for the environment (sync or async), start the loop+in the background, then watch and adjust it from later cells:++```python+actions = {+ "left": "Move left when the target is to the left",+ "right": "Move right when the target is to the right",+ "wait": "Do nothing when already aligned",+}+loop = decision_api.Loop(observe, act, actions, objective="Keep the paddle under the ball", tick=0.3)+loop.start()++status = await loop.wait(timeout=20) # returns early if the loop ends+print(status, loop.history[-5:], loop.goal_updates[-3:], loop.errors[-3:])+```++Every attribute is read again each step, so assignments take effect live:++```python+loop.actions["fire"] = "Fire when an enemy is straight ahead" # or a function (observation) -> dict+loop.instructions = "..."; loop.tick = 0.2+loop.state = lambda observation, goal, history: {...} # exactly what System 1 sees+loop.images = lambda observation: [png_data_url] # vision models: up to 4 images per step+loop.on_error = "skip" # "stop" (default), "skip", or (error, observation) -> action+loop.on_step = lambda record, observation: ... # log or render; return "stop" to end the loop+loop.set_goal("Prioritize catching the ball over waiting") # System 2: route a new goal to the child+loop.objective = "..." # the goal's fallback; set_goal overrides it+loop.decide_timeout = 30.0 # bound one decision round trip+loop.pause(); loop.resume()+final = await loop.stop() # also removes the decision child+```++Construction accepts the same settings as keywords (`decide_timeout=10`,+`max_steps=500`, `history_size=10`, ...); `help(decision_api.Loop)` lists all+of them. `await loop.run()` runs to completion in one cell instead.++Each step sends one decision request to the child and awaits its tagged+reply. Spawn and delivery failures appear in `loop.errors` (spawn retries in+the background); a decision that overruns `decide_timeout` fails the step and+follows `on_error`. Stopping removes the child. Python 3.11 or newer is+required.++Stay in your turn while a loop runs: poll with `loop.wait(timeout=...)`, read+`history`, `goal_updates`, and `errors`, adjust, and stop it when done. The+loop keeps running between cells, but nothing wakes you once your turn ends.++For a single System 1 decision without a loop, `await+decision_api.decide(observation, actions, goal="...", images=None)` returns+`action`, `confidence`, `probabilities`, `latency_ms`, and `model` — the+same host call the child serves.++Images (vision-capable models only): at most 4 per decision, each a data URL+string such as `f"data:image/png;base64,{base64.b64encode(png_bytes).decode()}"`+(not bytes, paths, or dicts); PNG, JPEG, or WebP, up to 4 MiB and 16+megapixels each and 8 MiB in total. Small, cropped images keep latency low; degenerate ones (a 1x1 pixel)+fail with a server error.diff --git a/skills/decision-api/pyproject.toml b/skills/decision-api/pyproject.tomlnew file mode 100644index 0000000000..0511e0ea84--- /dev/null+++ b/skills/decision-api/pyproject.toml@@ -0,0 +1,13 @@+[project]+name = "prime-agent-skill-decision-api"+version = "0.1.0"+description = "Experimental System 1 / System 2 loop for Prime Agent (a configured decision model + a System 2 subagent)."+requires-python = ">=3.11"+dependencies = []++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["src/decision_api"]diff --git a/skills/decision-api/src/decision_api/__init__.py b/skills/decision-api/src/decision_api/__init__.pynew file mode 100644index 0000000000..f3a8d83740--- /dev/null+++ b/skills/decision-api/src/decision_api/__init__.py@@ -0,0 +1,422 @@+"""Prime Agent decision-api skill: an experimental System 1 / System 2 loop.++System 1 is the session's decision model: the model the user named in the+decisionApi.systemOneModel setting. `decide()` calls it once for a single+decision; `Loop` runs the control loop: it spawns a decision child+(`rlm.spawn(..., kind="decision")`) whose every message is one decision+request, so each observation becomes one model call. System 2 is the+parent — you, the calling agent: goals flow to the child as tagged+agent-to-agent messages, and every decision the child serves reads the+latest goal. You design, measure, and adjust the loop live.+"""++from __future__ import annotations++import asyncio+import inspect+import json+import time+import uuid+from dataclasses import dataclass+from typing import Any, Callable++import agent_message+import rlm++DEFAULT_INSTRUCTIONS = "Choose the next action that best advances the goal given the observation."+# One decision request's wall-clock bound (the child transport waits up to+# this long for the child's reply before recording the step's error).+DECIDE_TIMEOUT = 30.0+# One spawned decision child's admission bound.+SPAWN_TIMEOUT = 30.0+# The child-deletion bound at loop teardown.+CHILD_CLEANUP_TIMEOUT = 5.0+# The poll interval while awaiting the child's reply.+_REPLY_POLL_SECONDS = 0.05+_OBSERVATION_CHARS = 6000+_MAX_ERRORS = 50+++def _default_state(observation: Any, goal: str, history: list[dict[str, Any]]) -> dict[str, Any]:+ """What System 1 sees by default: the observation and recent actions."""+ state: dict[str, Any] = {"observation": observation}+ if history:+ state["recent_actions"] = history+ return state+++async def _ask_system1(+ state: Any,+ actions: dict[str, str],+ *,+ instructions: str = DEFAULT_INSTRUCTIONS,+ images: list[str] | None = None,+) -> dict[str, Any]:+ """One System 1 decision for an arbitrary `state`. The host serves the+ request with the decisionApi.systemOneModel model through the normal+ provider transports; no key ever enters this kernel. `images`+ (vision models only, at most 4) are data URL strings+ (`data:image/png;base64,...`).+ Returns `action`, `confidence`, `probabilities`, `latency_ms`, and `model`."""+ question = {"type": "choice", "instructions": instructions, "criteria": actions}+ request: dict[str, Any] = {"state": state, "questions": {"action": question}}+ if images:+ bad = [+ repr(image)[:40] for image in images if not (isinstance(image, str) and image.startswith("data:image/"))+ ]+ if bad:+ raise TypeError(f"images must be data URL strings like 'data:image/png;base64,...', got {bad}")+ request["images"] = list(images)+ started = time.perf_counter()+ body = await rlm.host_request("decision_api.decide", {"request": request})+ answer = body["answers"]["action"]+ return {+ "action": answer["choice"],+ "confidence": answer["confidence"],+ "probabilities": answer["probabilities"],+ "latency_ms": round((time.perf_counter() - started) * 1000, 1),+ "model": body.get("model"),+ }+++async def decide(+ observation: Any,+ actions: dict[str, str],+ *,+ goal: str = "",+ history: list[dict[str, Any]] | None = None,+ instructions: str = DEFAULT_INSTRUCTIONS,+ images: list[str] | None = None,+) -> dict[str, Any]:+ """A single System 1 decision with the default state."""+ state = _default_state(observation, goal, history or [])+ if goal:+ state["goal"] = goal+ return await _ask_system1(state, actions, instructions=instructions, images=images)+++async def _call(fn: Callable[..., Any], *args: Any) -> Any:+ result = fn(*args)+ return await result if inspect.isawaitable(result) else result+++def _spawn_prompt(objective: str, instructions: str) -> str:+ """The decision child's protocol prompt, composed from this skill's+ material: the child answers every message with one decision."""+ return (+ "You are System 1, the decision child of a real-time control loop.\n"+ f"Objective: {objective}\n"+ f"Decision instructions: {instructions}\n"+ "Every later message is one decision request; your replies carry its "+ "answer back to the parent."+ )+++class Loop:+ """A live System 1 / System 2 control loop.++ System 1 is a spawned decision child (`rlm.spawn(kind="decision")`):+ each observation becomes one request to the child, one decision model+ call, and one reply back here. The child lives exactly as long as the+ loop. System 2 is the parent — you: `set_goal` routes updated goals to+ the child as tagged messages, and every decision reads the latest goal.++ Every attribute is read afresh each step, so assigning one on a running+ loop changes the next step. `goal` is yours: it starts as `objective`+ and `set_goal` updates it.++ - `observe()` returns an observation, or None to end the loop.+ - `act(action)` applies an action. Both may be sync or async.+ - `actions`: action name -> when it applies, or `(observation) -> dict`.+ - `objective`: the overall task.+ - `state`: `(observation, goal, history) -> Any`, what System 1 sees.+ - `images`: None, or `(observation) -> list` of data URL strings System 1 sees+ next to `state` (vision-capable models; see `decide`).+ - `instructions`: System 1's question instructions.+ - `system1`: None for the spawned decision child, or `(observation,+ actions, goal, history) -> action name or dict with "action"` to+ replace System 1 entirely.+ - `decide_timeout`: maximum seconds one decision round trip may take.+ - `tick`: minimum seconds per step (None runs as fast as decisions come).+ - `max_steps`: stop after this many steps (None runs until observe ends it).+ - `history_size`: recent actions shown to System 1.+ - `on_step`: `(record, observation)` after each step; returning "stop" ends the loop.+ - `on_error`: when System 1 fails, "stop", "skip", or `(error, observation)+ -> action name or None`.+ """++ def __init__(+ self,+ observe: Callable[[], Any],+ act: Callable[[str], Any],+ actions: dict[str, str] | Callable[[Any], dict[str, str]],+ *,+ objective: str,+ **settings: Any,+ ) -> None:+ self.observe = observe+ self.act = act+ self.actions = actions+ self.objective = objective+ self.state: Callable[..., Any] = _default_state+ self.images: Callable[[Any], list[str] | None] | None = None+ self.instructions = DEFAULT_INSTRUCTIONS+ self.system1: Callable[..., Any] | None = None+ self.decide_timeout: float = DECIDE_TIMEOUT+ self.tick: float | None = None+ self.max_steps: int | None = None+ self.history_size = 20+ self.on_step: Callable[..., Any] | None = None+ self.on_error: str | Callable[..., Any] = "stop"+ for name, value in settings.items():+ if not hasattr(self, name):+ raise TypeError(f"Loop has no setting {name!r}")+ setattr(self, name, value)+ self.history: list[dict[str, Any]] = []+ self.goal_updates: list[dict[str, Any]] = []+ self.errors: list[dict[str, Any]] = []+ self.error: str | None = None+ self.step = 0+ self._loop_id = uuid.uuid4().hex+ self._goal: str | None = None+ self._child_name: str | None = None+ self._child_model: str | None = None+ self._child_ready = asyncio.Event()+ self._resume = asyncio.Event()+ self._resume.set()+ self._stopping = False+ self._task: asyncio.Task[None] | None = None+ self._spawn_task: asyncio.Task[None] | None = None++ @property+ def goal(self) -> str:+ return self.objective if self._goal is None else self._goal++ def set_goal(self, goal: str) -> None:+ """Route an updated goal to the decision child (System 2 = the+ parent): fire-and-forget; every later decision reads it."""+ if not isinstance(goal, str) or not goal.strip():+ raise TypeError("goal must be a non-empty string")+ self._goal = goal+ self.goal_updates.append({"step": self.step, "goal": goal})+ if self._child_name is not None:+ message = json.dumps({"type": "decision_api.goal", "seq": self.step, "goal": goal})+ asyncio.get_running_loop().create_task(+ agent_message.send(message, receiver_role="child", receiver_name=self._child_name)+ )++ def start(self) -> "Loop":+ """Run the loop as a background task and return immediately."""+ if self._task is not None:+ raise RuntimeError("This loop was already started")+ self._spawn_task = asyncio.get_running_loop().create_task(self._spawn_child())+ self._task = asyncio.get_running_loop().create_task(self._run())+ return self++ def pause(self) -> None:+ self._resume.clear()++ def resume(self) -> None:+ self._resume.set()++ async def wait(self, timeout: float | None = None) -> dict[str, Any]:+ """Wait up to `timeout` seconds for the loop to end; return its status."""+ if self._task is None:+ raise RuntimeError("Start the loop first")+ try:+ await asyncio.wait_for(asyncio.shield(self._task), timeout)+ except TimeoutError:+ pass+ except asyncio.CancelledError:+ if not self._task.cancelled():+ raise+ return self.status()++ async def stop(self) -> dict[str, Any]:+ """End the loop after the current step, remove the child, return the status."""+ self._stopping = True+ self._resume.set()+ return await self.wait()++ async def run(self) -> dict[str, Any]:+ """Run to completion in the current cell."""+ return await self.start().wait()++ def status(self) -> dict[str, Any]:+ recent = self.history[-self.history_size :]+ latencies = [r["latency_ms"] for r in recent if r.get("latency_ms") is not None]+ return {+ "running": self._task is not None and not self._task.done(),+ "paused": not self._resume.is_set(),+ "step": self.step,+ "objective": self.objective,+ "goal": self.goal,+ "system1_model": self._child_model,+ "last": self.history[-1] if self.history else None,+ "mean_latency_ms": round(sum(latencies) / len(latencies), 1) if latencies else None,+ "errors": len(self.errors),+ "error": self.error,+ }++ def _record_error(self, where: str, error: BaseException) -> None:+ self.errors.append({"step": self.step, "where": where, "error": f"{type(error).__name__}: {error}"})+ del self.errors[:-_MAX_ERRORS]++ async def _spawn_child(self) -> None:+ """Spawn the decision child with bounded retries; failures surface in+ `loop.errors` and retry in the background while the loop waits."""+ failures = 0+ while not self._stopping and self._child_name is None:+ try:+ name = f"system-1-{self._loop_id}"+ handle = await asyncio.wait_for(+ rlm.spawn(+ _spawn_prompt(self.objective, self.instructions),+ name=name,+ kind="decision",+ ),+ SPAWN_TIMEOUT,+ )+ self._child_name = handle.name+ self._child_model = handle.model+ self._child_ready.set()+ except Exception as error:+ self._record_error("spawn", error)+ failures += 1+ await asyncio.sleep(min(5.0, 0.25 * 2 ** min(failures - 1, 5)))++ async def _run(self) -> None:+ try:+ while not self._stopping and (self.max_steps is None or self.step < self.max_steps):+ await self._resume.wait()+ if self._stopping:+ break+ started = time.perf_counter()+ if await self._step() == "stop":+ break+ if self.tick is not None:+ await asyncio.sleep(max(0.0, self.tick - (time.perf_counter() - started)))+ else:+ # Synchronous callbacks must not starve the transport tasks.+ await asyncio.sleep(0)+ except asyncio.CancelledError:+ self.error = "cancelled"+ raise+ except Exception as error:+ self.error = f"{type(error).__name__}: {error}"+ finally:+ self._stopping = True+ await self._remove_child()++ async def _step(self) -> str | None:+ observation = await _call(self.observe)+ if observation is None:+ return "stop"+ actions = self.actions(observation) if callable(self.actions) else self.actions+ history = self.history[-self.history_size :]+ try:+ if self.system1 is not None:+ started = time.perf_counter()+ choice = await _call(self.system1, observation, actions, self.goal, history)+ decision = dict(choice) if isinstance(choice, dict) else {"action": choice}+ decision.setdefault("latency_ms", round((time.perf_counter() - started) * 1000, 1))+ if decision.get("model"):+ self._child_model = decision["model"]+ else:+ decision = await self._decide(observation, actions, history)+ except Exception as error:+ self._record_error("system1", error)+ if self.on_error == "stop":+ raise+ fallback = None if self.on_error == "skip" else await _call(self.on_error, error, observation)+ if fallback is None:+ self.step += 1+ return None+ decision = {"action": fallback, "confidence": None, "latency_ms": None, "fallback": True}+ if decision.get("model"):+ self._child_model = decision["model"]+ await _call(self.act, decision["action"])+ record = {+ "step": self.step,+ "action": decision["action"],+ "confidence": decision.get("confidence"),+ "latency_ms": decision.get("latency_ms"),+ }+ if decision.get("fallback"):+ record["fallback"] = True+ self.history.append(record)+ self.step += 1+ if self.on_step is not None:+ return await _call(self.on_step, record, observation)+ return None++ async def _decide(+ self, observation: Any, actions: dict[str, str], history: list[dict[str, Any]]+ ) -> dict[str, Any]:+ """One decision through the child: send the request, await the reply.+ The child injects the latest goal (message-sourced) into the state."""+ await asyncio.wait_for(self._child_ready.wait(), self.decide_timeout)+ name = self._child_name+ assert name is not None+ state = self.state(observation, self.goal, history)+ images = None if self.images is None else await _call(self.images, observation)+ if images:+ bad = [+ repr(image)[:40] for image in images if not (isinstance(image, str) and image.startswith("data:image/"))+ ]+ if bad:+ raise TypeError(f"images must be data URL strings like 'data:image/png;base64,...', got {bad}")+ request: dict[str, Any] = {+ "seq": self.step,+ "state": state,+ "questions": {+ "action": {+ "type": "choice",+ "instructions": self.instructions,+ "criteria": actions,+ }+ },+ }+ if images:+ request["images"] = list(images)+ started = time.perf_counter()+ await agent_message.send(+ json.dumps(request), receiver_role="child", receiver_name=name+ )+ # Await the tagged reply: the parent's decision slot holds it.+ deadline = time.monotonic() + self.decide_timeout+ while time.monotonic() < deadline:+ reply = await rlm.host_request("decision_api.decision", {"name": name})+ if reply is not None and reply.get("seq") == self.step:+ if reply.get("error") is not None:+ raise RuntimeError(f"the decision child failed: {reply['error']}")+ answer = reply["decision"]+ return {+ "action": answer["choice"],+ "confidence": answer.get("confidence"),+ "probabilities": answer.get("probabilities"),+ "latency_ms": round((time.perf_counter() - started) * 1000, 1),+ "model": reply.get("model"),+ }+ await asyncio.sleep(_REPLY_POLL_SECONDS)+ raise TimeoutError(+ f"the decision child did not answer within {self.decide_timeout} s"+ )++ async def _remove_child(self) -> None:+ """Teardown: drop the parent's reply slot and delete the child."""+ name = self._child_name+ if name is None:+ return+ self._child_name = None+ try:+ await asyncio.wait_for(+ rlm.host_request("decision_api.decision", {"name": name, "close": True}),+ CHILD_CLEANUP_TIMEOUT,+ )+ except Exception as error:+ self._record_error("cleanup", error)+ try:+ await asyncio.wait_for(rlm.delete_subagent(name), CHILD_CLEANUP_TIMEOUT)+ except Exception as error:+ self._record_error("cleanup", error)diff --git a/skills/decision-api/tests/test_loop.py b/skills/decision-api/tests/test_loop.pynew file mode 100644index 0000000000..51a7b803eb--- /dev/null+++ b/skills/decision-api/tests/test_loop.py@@ -0,0 +1,377 @@+"""The decision-api loop against a stand-in host.++Covers the decision child transport (spawn + request + tagged reply), goal+routing, step control, and the direct `decide` path. `rlm` and+`agent_message` are installed before the skill imports.+"""++import asyncio+import json+import sys+import types+import unittest++host_calls = []+sent = []+++async def host_request(kind, payload):+ host_calls.append((kind, payload))+ if kind == "decision_api.decide":+ return {+ "answers": {+ "action": {+ "choice": "left",+ "confidence": 0.9,+ "probabilities": {"left": 0.9},+ }+ },+ "model": "fixture/model",+ }+ return None+++class _Handle:+ def __init__(self, name: str) -> None:+ self.name = name+ self.model = "fixture/system-1"+++async def spawn(prompt, *, name, kind=None, model=None, thinking=None):+ if kind != "decision":+ raise TypeError("the loop spawns a decision child")+ assert "You are System 1" in prompt+ return _Handle(name)+++async def send(text, *, receiver_role, receiver_name):+ sent.append({"text": text, "role": receiver_role, "name": receiver_name})+++async def delete_subagent(name):+ sent.append({"deleted": name})+++def _install_stubs():+ rlm = types.ModuleType("rlm")+ rlm.host_request = host_request+ rlm.spawn = spawn+ rlm.delete_subagent = delete_subagent+ agent_message = types.ModuleType("agent_message")+ agent_message.send = send+ sys.modules["rlm"] = rlm+ sys.modules["agent_message"] = agent_message+++_install_stubs()++from decision_api import DEFAULT_INSTRUCTIONS, Loop, decide # noqa: E402+++class DecideTests(unittest.TestCase):+ def setUp(self):+ host_calls.clear()++ def test_images_must_be_data_url_strings(self):+ async def check():+ for images in (+ [{"content_type": "image/png", "base64": "AA=="}],+ [b"png"],+ ["frame.png"],+ ):+ with self.assertRaises(TypeError) as raised:+ await decide({"x": 1}, {"left": "go left"}, images=images)+ self.assertIn("data:image/png;base64", str(raised.exception))+ self.assertEqual(host_calls, [])++ result = await decide(+ {"x": 1},+ {"left": "go left"},+ images=["data:image/png;base64,AA=="],+ )+ self.assertEqual(result["action"], "left")+ self.assertEqual(result["confidence"], 0.9)+ self.assertEqual(result["model"], "fixture/model")+ self.assertIsInstance(result["latency_ms"], float)++ kind, payload = host_calls[0]+ request = payload["request"]+ self.assertEqual(kind, "decision_api.decide")+ self.assertEqual(request["state"], {"observation": {"x": 1}})+ self.assertEqual(request["images"], ["data:image/png;base64,AA=="])+ self.assertNotIn("model", request)+ self.assertEqual(+ request["questions"]["action"],+ {+ "type": "choice",+ "instructions": DEFAULT_INSTRUCTIONS,+ "criteria": {"left": "go left"},+ },+ )++ asyncio.run(check())+++class LoopTests(unittest.TestCase):+ def setUp(self):+ host_calls.clear()+ sent.clear()++ def test_steps_skip_a_system1_error_and_stop_when_observe_ends(self):+ seen = []++ def observe():+ observe.n += 1+ if observe.n > 3:+ return None+ return {"n": observe.n}++ observe.n = 0++ def system1(_observation, _actions, _goal, _history):+ if observe.n == 2:+ raise RuntimeError("blip")+ return "left"++ async def run():+ loop = Loop(+ observe,+ seen.append,+ {"left": "go left"},+ objective="stay under it",+ system1=system1,+ on_error="skip",+ )+ status = await loop.run()+ self.assertEqual(seen, ["left", "left"])+ self.assertEqual(loop.step, 3)+ self.assertEqual(len(loop.errors), 1)+ self.assertIn("blip", loop.errors[0]["error"])+ self.assertEqual(+ {+ key: status[key]+ for key in (+ "running",+ "paused",+ "step",+ "objective",+ "goal",+ "errors",+ "error",+ )+ },+ {+ "running": False,+ "paused": False,+ "step": 3,+ "objective": "stay under it",+ "goal": "stay under it",+ "errors": 1,+ "error": None,+ },+ )++ asyncio.run(run())++ def test_the_loop_spawns_one_child_and_awaits_its_replies(self):+ taken = []+ replies = {}+ spawns = []++ async def stub_spawn(prompt, *, name, kind=None, model=None, thinking=None):+ spawns.append(name)+ return _Handle(name)++ async def stub_send(text, *, receiver_role, receiver_name):+ message = json.loads(text)+ sent.append({"message": message, "role": receiver_role, "name": receiver_name})+ # The child's answer routes back through the decision slot.+ replies[receiver_name] = {+ "type": "decision_api.decision",+ "seq": message["seq"],+ "model": "fixture/model",+ "decision": {"choice": "left", "confidence": 0.9},+ }++ async def stub_host_request(kind, payload):+ host_calls.append((kind, payload))+ if kind == "decision_api.decision":+ if payload.get("close"):+ replies.pop(payload["name"], None)+ return None+ return replies.get(payload["name"])++ def observe():+ observe.n += 1+ if observe.n > 2:+ return None+ return {"frame": observe.n}++ observe.n = 0++ import decision_api++ decision_api.rlm.spawn = stub_spawn+ decision_api.rlm.host_request = stub_host_request+ decision_api.agent_message.send = stub_send++ async def run():+ loop = decision_api.Loop(+ observe,+ taken.append,+ {"left": "go left", "right": "go right"},+ objective="fixture objective",+ decide_timeout=5.0,+ )+ status = await loop.run()+ self.assertEqual(taken, ["left", "left"])+ self.assertEqual(len(spawns), 1, "one child for the loop's lifetime")+ self.assertEqual(loop._child_model, "fixture/model")+ self.assertEqual(spawns[0].split("-")[2], loop._loop_id)+ self.assertEqual(loop.status()["system1_model"], "fixture/model")+ self.assertEqual(loop.errors, [], loop.errors)+ self.assertFalse(status["running"])+ # The requests carry the step seq and the decision instructions.+ requests = [+ entry["message"] for entry in sent if entry.get("role") == "child"+ ]+ self.assertEqual([request["seq"] for request in requests], [0, 1])+ for request in requests:+ self.assertEqual(request["questions"]["action"]["type"], "choice")+ self.assertEqual(+ request["questions"]["action"]["criteria"],+ {"left": "go left", "right": "go right"},+ )+ self.assertNotIn("goal", request["state"], "the goal rides tagged messages, not the state")++ asyncio.run(run())++ def test_goal_updates_route_to_the_child(self):+ taken = []+ goals = []+ replies = {}+ decided = []++ async def stub_spawn(prompt, *, name, kind=None, model=None, thinking=None):+ return _Handle(name)++ async def stub_send(text, *, receiver_role, receiver_name):+ message = json.loads(text)+ sent.append(message)+ if message.get("type") == "decision_api.goal":+ goals.append(message)+ else:+ # The child injects the latest goal into the state it serves.+ decided.append(message["seq"])+ replies[receiver_name] = {+ "type": "decision_api.decision",+ "seq": message["seq"],+ "model": "fixture/model",+ "decision": {"choice": "left", "confidence": 0.9},+ }++ async def stub_host_request(kind, payload):+ if kind == "decision_api.decision":+ if payload.get("close"):+ return None+ return replies.get(payload["name"])++ def observe():+ observe.n += 1+ if observe.n > 2:+ return None+ return {}++ observe.n = 0++ import decision_api++ decision_api.rlm.spawn = stub_spawn+ decision_api.rlm.host_request = stub_host_request+ decision_api.agent_message.send = stub_send++ async def run():+ loop = decision_api.Loop(+ observe,+ taken.append,+ {"left": "go left"},+ objective="fixture objective",+ on_step=lambda record, observation: (+ loop.set_goal("follow the target") if record["step"] == 0 else None+ ),+ decide_timeout=5.0,+ )+ await loop.run()+ self.assertEqual(taken, ["left", "left"])+ self.assertEqual(loop.goal, "follow the target")+ self.assertEqual(loop.goal_updates[-1]["goal"], "follow the target")+ # The goal message is tagged and routed to the child.+ self.assertEqual(+ [entry["type"] for entry in goals],+ ["decision_api.goal"],+ goals,+ )+ self.assertEqual(goals[0]["goal"], "follow the target")+ # set_goal of an empty goal is a contract error.+ with self.assertRaises(TypeError):+ loop.set_goal("")++ asyncio.run(run())++ def test_a_child_error_reply_fails_the_step_and_the_removal_closes_the_slot(self):+ taken = []+ replies = {}+ closed = []++ async def stub_spawn(prompt, *, name, kind=None, model=None, thinking=None):+ return _Handle(name)++ async def stub_send(text, *, receiver_role, receiver_name):+ message = json.loads(text)+ replies[receiver_name] = {+ "type": "decision_api.decision",+ "seq": message["seq"],+ "error": "the decision model refused",+ }++ async def stub_host_request(kind, payload):+ if kind == "decision_api.decision":+ if payload.get("close"):+ closed.append(payload["name"])+ return None+ return replies.get(payload["name"])++ def observe():+ observe.n += 1+ if observe.n > 1:+ return None+ return {}++ observe.n = 0++ import decision_api++ decision_api.rlm.spawn = stub_spawn+ decision_api.rlm.host_request = stub_host_request+ decision_api.agent_message.send = stub_send++ async def run():+ loop = decision_api.Loop(+ observe,+ taken.append,+ {"left": "go left"},+ objective="fixture objective",+ decide_timeout=5.0,+ on_error="skip",+ )+ await loop.run()+ self.assertEqual(taken, [])+ self.assertEqual(len(loop.errors), 1)+ self.assertIn("the decision model refused", loop.errors[0]["error"])+ self.assertEqual(closed, ["system-1-" + loop._loop_id])++ asyncio.run(run())+++if __name__ == "__main__":+ unittest.main()