diff --git a/CHANGELOG.md b/CHANGELOG.md index d6953a7f..8acf1843 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to Cyber Code are recorded here. The format follows [Keep a - An isolated subagent's worktree now starts from the parent checkout's uncommitted work: staged, unstaged and untracked non-ignored files, deletions and renames are committed in the child's checkout as its base, so its result still shows only its own changes (and now reports `base`). Files the Session may not read (`.env` by default) and ignored files stay behind, `.worktreeinclude` is unchanged, and `worktrees.carry_limit_mb` (default 100, `0` off) caps the total. - Bundled skill `/grill-me `: before starting, the agent interviews you one question at a time with the `question` tool, recommending an answer for each, then summarizes the agreed scope and waits for your confirmation. - `title.command` in the global `tui.jsonc` sets the terminal window title from your own command: it receives the Session state as JSON on stdin and its first output line is the title. It runs at most every 300 ms, only when the state changed, with a one-second limit; a project `tui.jsonc` cannot set it. +- `/model ` in the TUI sends one prompt to another model; the Session's model answers the next prompt again. `POST /api/v1/sessions/{id}/prompt` accepts `model` for the same one-prompt override, and the prompt's inbox row reports it. - Computer use reports a platform-neutral capability report (schema version 2): a derived mode (`unsupported`, `capture_only`, `input_enabled`), stable reason codes, authority kind, honored selectors and the support evidence level, alongside the existing macOS fields. Receipts add platform, grant, target and frame references, a reason, cleanup state and timestamps; HTTP errors add a `reason` code. `cyber computer allow --preview --yes` confirms a printed review by its identifier. - `cyber exec --format stream-json --include-hook-events` adds a `hook_event` line for each hook that ran for the run's Session (hook ID, event, scope, outcome, decision, duration, and the tool call it guarded), before the line of what it gated. Hook input, output, reasons and environment are never included. The instance event stream carries the underlying `session.hook.receipt` summaries when asked with `include=hook_receipts`, and so does a Session's event stream (`/sessions/{id}/events`) for that Session's own receipts, which `--input-format stream-json` runs follow. - The `auto` reviewer can check context before deciding with read-only tools: `transcript_search` over the Session's history, and `read_file`/`grep_files` over the Location under the Session's own read rules (`.env`, `deny_read` globs, secret files and paths outside the Location stay unreadable). Results arrive as framed untrusted data; budgets are 8 calls, 16 KiB per result, 64 KiB per review and 5 s per call. A bare "yes"/"go ahead" reaches the reviewer together with the assistant question it answers. `permission.auto_decided.1` records `reviewer_tools` and `confirmation`; `cyber permissions auto show` adds `reviewer tool calls`. diff --git a/crates/cyber-cli/tests/review_command.rs b/crates/cyber-cli/tests/review_command.rs index 52a29273..af489b53 100644 --- a/crates/cyber-cli/tests/review_command.rs +++ b/crates/cyber-cli/tests/review_command.rs @@ -1034,16 +1034,23 @@ fn the_review_workflow_reports_target_errors_and_clean_trees_without_a_run() { /// A budget that stops the review run exits 4 and still prints its partial findings: /// the reviewer answers after the wall-clock budget, so no verifier starts. +/// +/// The budget must expire after the reviewer asked the provider and before it answers. +/// Its clock also covers the reviewer's start (admission, child Session, first request), +/// which took over 2 s on a loaded macOS runner: with a 2 s budget the run stopped +/// before the reviewer asked, with no findings. A 20 s budget leaves room for the +/// start, and holding the answer 25 s after the request puts it after the budget +/// whenever the request came in time. #[test] fn a_budget_stopped_review_workflow_exits_4_with_partial_findings() { let provider = Provider::start(Script { result: unsorted(), - delay: Duration::from_secs(4), + delay: Duration::from_secs(25), read_first: None, }); let env = Env::new(&provider); env.write("a.rs", "changed\n"); - let output = env.workflow_review(&["--format", "json", "--timeout", "2s"]); + let output = env.workflow_review(&["--format", "json", "--timeout", "20s"]); let detail = describe(&output, &provider); assert_eq!(output.status.code(), Some(4), "{detail}"); let result = result(&output, &detail); diff --git a/crates/cyber-server/src/http/peer/attach.rs b/crates/cyber-server/src/http/peer/attach.rs index e7a45527..644340ab 100644 --- a/crates/cyber-server/src/http/peer/attach.rs +++ b/crates/cyber-server/src/http/peer/attach.rs @@ -377,6 +377,7 @@ pub(super) async fn prompt( resume: true, source: None, format: None, + model: None, }; crate::http::sessions::submit_prompt(&peer.app, &id, prompt).await } diff --git a/crates/cyber-server/src/http/sessions.rs b/crates/cyber-server/src/http/sessions.rs index b0c54fc6..9c3d9ad4 100644 --- a/crates/cyber-server/src/http/sessions.rs +++ b/crates/cyber-server/src/http/sessions.rs @@ -200,6 +200,9 @@ pub struct PromptBody { pub source: Option, /// A structured answer for this root prompt (`session-runtime` → Structured output). pub format: Option, + /// `provider/model` that answers this prompt only; later prompts use the Session's + /// model again. + pub model: Option, } /// `{ type: "json_schema", schema }`: the answer is a JSON object the schema validates, @@ -820,6 +823,7 @@ pub(crate) async fn submit_prompt( output_schema: body .format .map(|PromptFormat::JsonSchema { schema }| schema), + model: body.model, }; let receipt: Receipt = match state .runtime @@ -1680,6 +1684,7 @@ mod tests { untrusted, output_schema: None, structured: None, + model: None, } } diff --git a/crates/cyber-server/src/runtime/auto_override.rs b/crates/cyber-server/src/runtime/auto_override.rs index cf670150..ecc81b9c 100644 --- a/crates/cyber-server/src/runtime/auto_override.rs +++ b/crates/cyber-server/src/runtime/auto_override.rs @@ -546,6 +546,7 @@ impl Inner { resources: Vec::new(), untrusted: None, output_schema: None, + model: None, }, ), event( diff --git a/crates/cyber-server/src/runtime/continuation.rs b/crates/cyber-server/src/runtime/continuation.rs index 4a4bb0d8..a0da705a 100644 --- a/crates/cyber-server/src/runtime/continuation.rs +++ b/crates/cyber-server/src/runtime/continuation.rs @@ -31,7 +31,7 @@ impl Runtime { files: Vec, ) -> Result { self.inner.ensure_admission_open(id)?; - self.check_output_schema(id, &admission).await?; + self.check_prompt_options(id, &admission).await?; let lifecycle = self.inner.open().await?; let handle = self.inner.handle(id).await?; let state = handle.state.lock().await.clone(); @@ -127,6 +127,7 @@ impl Runtime { resources: attachments.resources, untrusted: attachments.untrusted, output_schema: None, + model: admission.model, }, ), ], diff --git a/crates/cyber-server/src/runtime/drain.rs b/crates/cyber-server/src/runtime/drain.rs index 9f4d484d..8180127a 100644 --- a/crates/cyber-server/src/runtime/drain.rs +++ b/crates/cyber-server/src/runtime/drain.rs @@ -3484,6 +3484,7 @@ mod queue_head_tests { untrusted: None, output_schema: None, structured: None, + model: None, } } diff --git a/crates/cyber-server/src/runtime/events.rs b/crates/cyber-server/src/runtime/events.rs index 4622b4c2..a49f991b 100644 --- a/crates/cyber-server/src/runtime/events.rs +++ b/crates/cyber-server/src/runtime/events.rs @@ -187,6 +187,9 @@ pub struct Admitted { /// Structured output). #[serde(default, skip_serializing_if = "Option::is_none")] pub output_schema: Option, + /// `provider/model` for the Turn of this prompt only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/cyber-server/src/runtime/goals/run.rs b/crates/cyber-server/src/runtime/goals/run.rs index ac3c8fe5..bc8130ad 100644 --- a/crates/cyber-server/src/runtime/goals/run.rs +++ b/crates/cyber-server/src/runtime/goals/run.rs @@ -509,6 +509,7 @@ fn steer(goal: &Goal, text: String) -> NewEvent { resources: Vec::new(), untrusted: None, output_schema: None, + model: None, }; event(ADMITTED, &admitted) } diff --git a/crates/cyber-server/src/runtime/lifecycle.rs b/crates/cyber-server/src/runtime/lifecycle.rs index 2f9eaaf0..7385c4b5 100644 --- a/crates/cyber-server/src/runtime/lifecycle.rs +++ b/crates/cyber-server/src/runtime/lifecycle.rs @@ -142,6 +142,7 @@ impl Inner { resources: Vec::new(), untrusted: None, output_schema: None, + model: None, }; self.commit(handle, vec![event(ADMITTED, &admitted)]) .await?; diff --git a/crates/cyber-server/src/runtime/messaging/hops.rs b/crates/cyber-server/src/runtime/messaging/hops.rs index 823fd580..0a4ba58e 100644 --- a/crates/cyber-server/src/runtime/messaging/hops.rs +++ b/crates/cyber-server/src/runtime/messaging/hops.rs @@ -278,6 +278,7 @@ mod tests { untrusted: None, output_schema: None, structured: None, + model: None, }); if let Some(hops) = hops { let chain = MessageChain { diff --git a/crates/cyber-server/src/runtime/messaging/send.rs b/crates/cyber-server/src/runtime/messaging/send.rs index 39d4aedf..db6869ba 100644 --- a/crates/cyber-server/src/runtime/messaging/send.rs +++ b/crates/cyber-server/src/runtime/messaging/send.rs @@ -388,6 +388,7 @@ impl Outgoing { source: "session".into(), resume: true, output_schema: None, + model: None, } } diff --git a/crates/cyber-server/src/runtime/mod.rs b/crates/cyber-server/src/runtime/mod.rs index a0ec93bf..16dddae8 100644 --- a/crates/cyber-server/src/runtime/mod.rs +++ b/crates/cyber-server/src/runtime/mod.rs @@ -664,6 +664,7 @@ impl CommandPlan { source: self.source.into(), resume: true, output_schema: None, + model: None, } } } @@ -708,6 +709,8 @@ pub struct Admission { pub output_schema: Option, /// Bind this original input to a dedicated client; absent keeps legacy presence. pub input_client: Option, + /// `provider/model` for this prompt's Turn only; the Session's model is unchanged. + pub model: Option, } impl Admission { @@ -728,10 +731,14 @@ impl Admission { ), None => base, }; - // A retry with another schema is another prompt. - match &self.output_schema { + // A retry with another schema or model is another prompt. + let base = match &self.output_schema { Some(schema) => format!("{base}+schema:{:x}", Sha256::digest(schema.to_string())), None => base, + }; + match &self.model { + Some(model) => format!("{base}+model:{model}"), + None => base, } } @@ -746,6 +753,7 @@ impl Admission { source: "user".into(), resume: true, output_schema: None, + model: None, } } } @@ -1737,7 +1745,7 @@ impl Runtime { check: PromptCheck, extra: Vec, ) -> Result { - self.check_output_schema(session_id, &admission).await?; + self.check_prompt_options(session_id, &admission).await?; self.admit_recorded(session_id, admission, attempt, check, extra, None) .await } @@ -1768,7 +1776,26 @@ impl Runtime { /// A prompt's `output_schema` is for root Sessions and must pass the root schema /// bounds (`session-runtime` → Structured output). - pub(crate) async fn check_output_schema( + /// Refuse a prompt's `output_schema` or `model` before anything is admitted. + pub(crate) async fn check_prompt_options( + &self, + session_id: &str, + admission: &Admission, + ) -> Result<(), RuntimeError> { + self.check_output_schema(session_id, admission).await?; + let Some(model) = &admission.model else { + return Ok(()); + }; + cyber_llm::catalog::ModelRef::parse(model) + .map_err(|error| RuntimeError::Invalid(error.to_string()))?; + let handle = self.inner.handle(session_id).await?; + let info = handle.state.lock().await.info.clone(); + self.inner + .resolve_selection(&info, &selection::ModelSelection::explicit(model.clone())) + .map(drop) + } + + async fn check_output_schema( &self, session_id: &str, admission: &Admission, @@ -1866,6 +1893,7 @@ impl Runtime { resources: attachments.resources, untrusted: untrusted_input::merged([untrusted, attachments.untrusted]), output_schema: admission.output_schema, + model: admission.model, }; let mut events = Vec::new(); if let Some(attempt) = attempt { diff --git a/crates/cyber-server/src/runtime/model.rs b/crates/cyber-server/src/runtime/model.rs index 1cf2374e..b9974bd6 100644 --- a/crates/cyber-server/src/runtime/model.rs +++ b/crates/cyber-server/src/runtime/model.rs @@ -54,6 +54,19 @@ pub struct InboxRow { /// The structured result or error of a prompt with `output_schema`, once settled. #[serde(default, skip_serializing_if = "Option::is_none")] pub structured: Option, + /// `provider/model` for this prompt's Turn only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, +} + +impl InboxRow { + /// The model this row's Turn runs on instead of the Session's: the prompt's own + /// `model`, else its command's. + pub fn turn_model(&self) -> Option<&str> { + self.model + .as_deref() + .or_else(|| self.skill_command.as_ref()?.model.as_deref()) + } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] @@ -741,6 +754,15 @@ impl SessionState { .find(|row| row.message_id == message && row.skill_command.is_some()) } + /// The current user prompt's row when it names a model for its Turn: a prompt + /// `model` or a command's `model`. + fn current_model_row(&self) -> Option<&InboxRow> { + let message = self.current_user_message()?; + self.inbox + .iter() + .find(|row| row.message_id == message && row.turn_model().is_some()) + } + pub(crate) fn boundary_command_model(&self, continue_tools: bool) -> Option<&str> { let pending = self.pending(Delivery::Steer).last().or_else(|| { (!continue_tools) @@ -748,14 +770,15 @@ impl SessionState { .flatten() }); match pending { - Some(row) => row.skill_command.as_ref()?.model.as_deref(), + Some(row) => row.turn_model(), None => self.command_model(), } } - /// A command model applies through its tool loop, then expires at its final text reply. + /// A prompt or command model applies through its tool loop, then expires at its + /// final text reply. pub fn command_model(&self) -> Option<&str> { - let row = self.current_command_row()?; + let row = self.current_model_row()?; let user = self .entries .iter() @@ -772,7 +795,7 @@ impl SessionState { if last.is_some_and(|assistant| assistant.finished && assistant.calls.is_empty()) { return None; } - row.skill_command.as_ref()?.model.as_deref() + row.turn_model() } pub fn child_worktree_setup_pending(&self) -> bool { @@ -1336,6 +1359,7 @@ impl SessionState { untrusted: a.untrusted, output_schema: a.output_schema, structured: None, + model: a.model, }); } diff --git a/crates/cyber-server/src/runtime/rewind.rs b/crates/cyber-server/src/runtime/rewind.rs index 1e518f2e..69128758 100644 --- a/crates/cyber-server/src/runtime/rewind.rs +++ b/crates/cyber-server/src/runtime/rewind.rs @@ -293,6 +293,7 @@ impl Runtime { resources: Vec::new(), untrusted: None, output_schema: None, + model: None, }; let promoted = Promoted { message_id }; self.inner diff --git a/crates/cyber-server/tests/planner.rs b/crates/cyber-server/tests/planner.rs index acba6724..21902fd5 100644 --- a/crates/cyber-server/tests/planner.rs +++ b/crates/cyber-server/tests/planner.rs @@ -195,3 +195,30 @@ async fn sessions_with_a_parent_keep_their_own_model() { assert_eq!(steps(&h, &child), vec![("test/main".into(), None)]); assert!(h.models.requests("other/main").is_empty()); } + +/// A prompt's own `model` (`/model `) answers that prompt even in a plan +/// phase, without suspending the planner: the next plan-mode prompt is on the planner. +#[tokio::test] +async fn a_one_shot_prompt_model_in_plan_mode_keeps_the_planner() { + let h = Harness::new(planner_setup(vec![ + ("other/main", vec![text("plan one"), text("plan two")]), + ("spare/main", vec![text("second opinion")]), + ])); + let id = session_in(&h, "plan", None).await; + ask(&h, &id, "plan the migration").await; + let mut once = Admission::text("what would you change?", Delivery::Queue); + once.model = Some("spare/main".into()); + h.runtime.admit(&id, once).await.unwrap(); + h.settle(&id).await; + let state = h.state(&id).await; + assert_eq!(h.runtime.model_role(&state), Some(PLAN_ROLE)); + ask(&h, &id, "refine it").await; + assert_eq!( + steps(&h, &id), + vec![ + ("other/main".into(), Some("plan".into())), + ("spare/main".into(), None), + ("other/main".into(), Some("plan".into())), + ] + ); +} diff --git a/crates/cyber-tools/tests/skill_commands.rs b/crates/cyber-tools/tests/skill_commands.rs index e80ef0fd..b9f122c8 100644 --- a/crates/cyber-tools/tests/skill_commands.rs +++ b/crates/cyber-tools/tests/skill_commands.rs @@ -312,3 +312,44 @@ async fn unavailable_command_model_preserves_pending_input_without_using_the_bas assert!(flow.main.requests().is_empty()); flow.runtime.shutdown().await; } + +/// `session-runtime` → per-prompt model: a prompt's `model` answers that prompt, tool loop +/// included, and the next prompt runs on the Session's model again. +#[tokio::test] +async fn prompt_model_answers_one_prompt_then_the_session_model_returns() { + let flow = Flow::with_models( + support::Fixture::new(), + vec![text("base answer")], + false, + Arc::new(NoSnapshots), + vec![( + "other/once", + vec![ + call("read", "read", json!({"path":"notes.txt"})), + text("once answer"), + ], + )], + ); + flow.f.write("notes.txt", "notes"); + let id = flow.session("default").await; + let mut once = cyber_server::runtime::Admission::text("look", Delivery::Queue); + once.model = Some("other/once".into()); + flow.runtime.admit_user(&id, once).await.unwrap(); + flow.settle(&id).await; + let state = flow.runtime.state(&id).await.unwrap(); + assert!(format!("{:?}", state.entries).contains("once answer")); + assert_eq!(state.info.model, "test/main"); + assert!(flow.main.requests().is_empty()); + + let again = cyber_server::runtime::Admission::text("again", Delivery::Queue); + flow.runtime.admit_user(&id, again).await.unwrap(); + flow.settle(&id).await; + let entries = format!("{:?}", flow.runtime.state(&id).await.unwrap().entries); + assert!(entries.contains("base answer"), "{entries}"); + assert_eq!(flow.main.requests().len(), 1); + + let mut unknown = cyber_server::runtime::Admission::text("x", Delivery::Queue); + unknown.model = Some("missing/model".into()); + assert!(flow.runtime.admit_user(&id, unknown).await.is_err()); + flow.runtime.shutdown().await; +} diff --git a/crates/cyber-tui/src/app.rs b/crates/cyber-tui/src/app.rs index ee1ff132..c6b6e749 100644 --- a/crates/cyber-tui/src/app.rs +++ b/crates/cyber-tui/src/app.rs @@ -104,6 +104,13 @@ pub enum Action { /// The draft's chips whose labels are in `text`, in label order. chips: Vec, }, + /// `/model `: one prompt answered by `model`; the Session + /// keeps its own model. + ModelPrompt { + model: String, + text: String, + delivery: &'static str, + }, Shell(String), /// `& cmd`: start a user shell command as a background Job of the Session. BackgroundShell(String), @@ -1794,6 +1801,30 @@ impl App { }] } + /// `/model` opens the picker; `/model ` sends one prompt to + /// that model, and the Session's model answers the next one again. + fn model_command(&mut self, args: &str) -> Vec { + let Some((model, prompt)) = args.split_once(char::is_whitespace) else { + return vec![Action::LoadModels]; + }; + let prompt = prompt.trim(); + if !model.contains('/') || prompt.is_empty() { + self.toast("Usage: /model "); + return Vec::new(); + } + let delivery = if self.session.running { + "queue" + } else { + "steer" + }; + self.hide_recap(); + vec![Action::ModelPrompt { + model: model.to_string(), + text: prompt.to_string(), + delivery, + }] + } + /// `/memory [global]` opens the review panel; `/memory on|off|readonly` saves the /// toggle, which Sessions apply at their next Safe Boundary. fn memory_command(&mut self, args: &str) -> Vec { @@ -1886,7 +1917,7 @@ impl App { self.overlay = Overlay::ConfirmStopTasks; Vec::new() } - "model" | "models" => vec![Action::LoadModels], + "model" | "models" => self.model_command(args), "skills" => vec![Action::LoadSkills], "plugins" => vec![Action::LoadPlugins { reload: false }], "reload-plugins" => vec![Action::LoadPlugins { reload: true }, Action::LoadCommands], diff --git a/crates/cyber-tui/src/lib.rs b/crates/cyber-tui/src/lib.rs index d7c7f4ba..22d4c91e 100644 --- a/crates/cyber-tui/src/lib.rs +++ b/crates/cyber-tui/src/lib.rs @@ -102,6 +102,8 @@ mod screens_mcp; #[cfg(test)] mod screens_messages; #[cfg(test)] +mod screens_model_prompt; +#[cfg(test)] mod screens_mouse; #[cfg(test)] mod screens_output_styles; diff --git a/crates/cyber-tui/src/perform.rs b/crates/cyber-tui/src/perform.rs index a7affeae..870c7168 100644 --- a/crates/cyber-tui/src/perform.rs +++ b/crates/cyber-tui/src/perform.rs @@ -845,6 +845,27 @@ async fn submit_prompt( Ok(Msg::Done) } +/// `/model `: the prompt's `model` answers it alone. +async fn model_prompt( + client: &Client, + session: &Session, + model: &str, + text: &str, + delivery: &str, +) -> Result { + let id = session.id.as_str(); + let body = json!({ + "parts": parts(text, &session.directory, client.attached_session().is_none()), + "delivery": delivery, + "model": model, + }); + client + .post(&format!("/sessions/{id}/prompt"), body) + .await + .map_err(prompt_refusal)?; + Ok(Msg::Done) +} + /// A refused prompt as the server words it, without the error tag. fn prompt_refusal(e: cyber_client::ClientError) -> String { match e { @@ -1007,7 +1028,8 @@ pub async fn perform_owned( | Action::RepoMap(_) | Action::LoadUpdate | Action::ResumeAtReset - | Action::Export(_) => scheduled(client, session, action).await, + | Action::Export(_) + | Action::ModelPrompt { .. } => scheduled(client, session, action).await, Action::SaveTheme(_) | Action::SaveProjectTheme(_) | Action::SavePreference { .. } @@ -1028,9 +1050,11 @@ async fn scheduled(client: &Client, session: &Session, action: Action) -> Result Action::ComputerStatus | Action::ComputerStop => { crate::computer::perform(client, session, action).await } - Action::Branch(_) | Action::Export(_) | Action::LoadUpdate | Action::ResumeAtReset => { - session_requests(client, session, action).await - } + Action::Branch(_) + | Action::Export(_) + | Action::LoadUpdate + | Action::ResumeAtReset + | Action::ModelPrompt { .. } => session_requests(client, session, action).await, Action::Loop(request) => crate::loops::perform(client, request).await, Action::Team(request) => crate::team::perform(client, session, request).await, Action::Collaboration(request) => { @@ -1060,8 +1084,8 @@ async fn preferences(client: &Client, action: Action) -> Result { } } -/// The branch tree (`/tree`, `/label`), `/export`, the update check and -/// `/resume-at-reset`. +/// The branch tree (`/tree`, `/label`), `/export`, the update check, +/// `/resume-at-reset` and `/model `. async fn session_requests( client: &Client, session: &Session, @@ -1072,6 +1096,11 @@ async fn session_requests( Action::Export(request) => crate::export::perform(client, request).await, Action::LoadUpdate => crate::update::perform(client).await, Action::ResumeAtReset => crate::usage_wait::perform(client, &session.id).await, + Action::ModelPrompt { + model, + text, + delivery, + } => model_prompt(client, session, &model, &text, delivery).await, _ => Ok(Msg::Done), } } diff --git a/crates/cyber-tui/src/screens_model_prompt.rs b/crates/cyber-tui/src/screens_model_prompt.rs new file mode 100644 index 00000000..c26c8c92 --- /dev/null +++ b/crates/cyber-tui/src/screens_model_prompt.rs @@ -0,0 +1,91 @@ +//! `/model ` (`tui` → Model picker) against a production App and +//! server: the prompt is answered by the named model and the Session keeps its own. + +use std::time::Duration; + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use serde_json::json; + +use crate::app::{Action, App}; +use crate::screens::Server; + +fn typed(app: &mut App, text: &str) -> Vec { + for c in text.chars() { + app.on_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + app.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)) +} + +/// The provider model of every Turn request (one with tools, unlike title generation) +/// that carried `text`. +fn models_answering(server: &Server, text: &str) -> Vec { + server + .model + .requests() + .iter() + .filter(|request| { + request["tools"] + .as_array() + .is_some_and(|tools| !tools.is_empty()) + }) + .filter(|request| request["messages"].to_string().contains(text)) + .map(|request| request["model"].as_str().unwrap_or_default().to_owned()) + .collect() +} + +async fn wait_for(server: &Server, id: &str, text: &str) -> Vec { + for _ in 0..1000 { + let models = models_answering(server, text); + if !models.is_empty() && !server.host.runtime.is_running(id) { + return models; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("no request for {text:?}: {:?}", server.model.requests()); +} + +#[test] +fn model_command_keeps_the_picker_and_parses_a_one_shot_prompt() { + let mut app = App::new(crate::model::Session::default(), Vec::new(), "cyber"); + assert_eq!(typed(&mut app, "/model"), [Action::LoadModels]); + assert_eq!(typed(&mut app, "/model test/other"), [Action::LoadModels]); + assert!(typed(&mut app, "/model other explain").is_empty()); + assert_eq!( + app.toast.as_ref().unwrap().0, + "Usage: /model " + ); + assert_eq!( + typed(&mut app, "/model test/other explain fib "), + [Action::ModelPrompt { + model: "test/other".into(), + text: "explain fib".into(), + delivery: "steer", + }] + ); + app.session.running = true; + assert!(matches!( + typed(&mut app, "/model test/other again").as_slice(), + [Action::ModelPrompt { + delivery: "queue", + .. + }] + )); +} + +#[tokio::test] +async fn one_shot_model_prompt_then_the_session_model_answers_again() { + let server = Server::start_models(json!({"main": {}, "other": {}}), json!({}), false).await; + let id = server.session().await; + let mut app = server.load(&id).await; + let actions = typed(&mut app, "/model test/other explain fib"); + for action in actions { + let msg = crate::perform::perform(&server.client, &app.session, action).await; + crate::runner::apply(&mut app, msg, &mut Default::default()); + } + assert_eq!(wait_for(&server, &id, "explain fib").await, ["other"]); + let session = server.client.get(&format!("/sessions/{id}")).await.unwrap(); + assert_eq!(session["data"]["model"], "test/main"); + + server.prompt(&id, "and now").await; + assert_eq!(wait_for(&server, &id, "and now").await, ["main"]); +} diff --git a/docs/local-core-guide.md b/docs/local-core-guide.md index 5d32cb0c..3dc0bda8 100644 --- a/docs/local-core-guide.md +++ b/docs/local-core-guide.md @@ -1182,6 +1182,10 @@ Each finished run ends with a marker, `▣ Build · · 11.3s`, built fro `Ctrl+P` (or `/` then `Tab`) opens the command palette: UI actions (usage, theme, copy the last code block, reasoning, tool output, timestamps), the built-in commands, and the server's custom commands, skills and MCP prompts, each with its current key. Keys come from one table that `tui.keybinds` in `tui.jsonc` merges over: top-level names bind global actions (`command_palette`, `settings`, `model_list`, `session_list`, `session_new`, `theme_list` (`s`), `theme_cycle` (`t`), `session_fork`, `copy_code`, `help`, `reasoning_toggle`, `tool_details`, `leader`), and the `composer` (`history_previous` Up, `history_next` Down, `history_search` Ctrl+R, `newline` Ctrl+J, `editor` Ctrl+G), `palette`, `sidebar`, `settings` and `explorer` objects scope bindings to a context; any other context is reported as unknown. With `history_previous` set to `"none"`, Up only moves the cursor. `"none"` disables a binding, which then disappears from the footer, help and palette; a value that does not parse keeps the default and is reported. +### One prompt on another model + +`/model ` sends one prompt to another model: `/model anthropic/claude-sonnet explain this diff`. That model answers the prompt, including any tool calls it makes, and the Session's model answers the next prompt again. The footer, the Session's model and its switch history do not change. While the Session works, the prompt waits in the queue. `/model` alone, or with only a model name, opens the model picker as before. Over the API, send `"model": "provider/model"` with `POST /api/v1/sessions/{id}/prompt`; the prompt's inbox row reports it. A model that does not parse or resolve is refused before anything is admitted. + ### Searching past prompts Up and Down walk the project's last 500 prompts one at a time; Ctrl+R searches them. Type part of a prompt and the composer shows the newest prompt containing it, with each occurrence marked, while the info line reads `search: N/M` (or `no match`). Ctrl+R or Up moves to the next older match and Down to a newer one. The match ignores case unless the query has an uppercase letter, and a prompt sent several times is listed once. Enter (or Tab, Left, Right) puts the match in the composer for editing; nothing is sent until you press Enter again. Esc, Ctrl+G or Ctrl+C closes the search and gives back the draft you had, chips included. The search runs on the history already loaded and sends nothing to the server. Rebind it as `keybinds.composer.history_search`, or set it to `"none"`. diff --git a/openspec/changes/add-one-shot-model-prompt/proposal.md b/openspec/changes/add-one-shot-model-prompt/proposal.md new file mode 100644 index 00000000..0365bc27 --- /dev/null +++ b/openspec/changes/add-one-shot-model-prompt/proposal.md @@ -0,0 +1,14 @@ +## Why + +Sometimes one question should go to a different model (a stronger reasoner, a cheaper one) without changing the Session. Switching with `/model`, asking, and switching back takes three steps and is easy to forget. The runtime already runs a command's Turns on the command's `model` and then returns to the Session's model, but a plain prompt could not ask for that. + +## What Changes + +- `session-runtime` "Agent, model, and mode switching": `POST /sessions/{id}/prompt` accepts `model`. That prompt's Turns, tool loop included, run on it until the final text reply. The Session's model and its switch events are unchanged. An unparseable or unresolvable model is refused before admission, and the prompt's `model` takes precedence over a command's. The inbox row reports `model`, and the exact-retry digest includes it. +- `tui` "Model, variant and agent selection": `/model ` sends the prompt with that `model`, queued while the Session runs. `/model` and `/model ` open the picker as before. + +## Impact + +- `crates/cyber-server`: `PromptBody.model`, `Admission.model`, `Admitted.model`, `InboxRow.model`, and admission validation; the command-model selection generalized to `InboxRow::turn_model`. +- `crates/cyber-tui`: the `/model` arguments and `Action::ModelPrompt`. +- OpenAPI document and TypeScript SDK regenerated. diff --git a/openspec/changes/add-one-shot-model-prompt/specs/session-runtime/spec.md b/openspec/changes/add-one-shot-model-prompt/specs/session-runtime/spec.md new file mode 100644 index 00000000..0818574a --- /dev/null +++ b/openspec/changes/add-one-shot-model-prompt/specs/session-runtime/spec.md @@ -0,0 +1,20 @@ +## MODIFIED Requirements + +### Requirement: Agent, model, and mode switching +(P0) The system SHALL record agent, model/variant, mode and output style switches as durable events (`session.agent.switched.1`, `session.model.switched.1`, `session.mode.switched.1`, `session.output_style.switched.1`). They SHALL take effect at the next Turn and append history markers that are not sent to the model. Switching to the current selection SHALL be a no-op. A prompt MAY name a `model` (`provider/model[#variant]`) for itself alone: the Turns that answer it, tool calls included, SHALL run on that model until its final text reply, the Session's own model SHALL NOT change and no switch event SHALL be recorded, and the next prompt SHALL use the Session's model again. In a plan phase it SHALL take precedence over `model_roles.plan` for that prompt without suspending the planner, and its steps SHALL have no `model_role`. A prompt `model` that does not parse or resolve SHALL be refused before admission, and it SHALL take precedence over a command's `model`. The inbox row SHALL report the prompt's `model`, and an exact retry with another `model` SHALL be another prompt. An output style switch SHALL record the Session's own selection (`null` returns to the configured style) and SHALL be refused for Sessions with a parent. + +#### Scenario: Switch model mid-session +- **WHEN** the user switches from `openai/gpt-6` to `anthropic/claude-sonnet` during a Turn +- **THEN** the current Turn completes on `openai/gpt-6` and the next Turn uses `anthropic/claude-sonnet` + +#### Scenario: Output style survives a restart +- **WHEN** the user switches a Session to output style `concise` and the server restarts +- **THEN** the Session still reports `output_style: "concise"` and its next Turn uses that style + +#### Scenario: One prompt on another model +- **WHEN** a prompt on a `openai/gpt-6` Session names `model: "anthropic/claude-sonnet"` and its answer calls `read` +- **THEN** both Turns of that answer use `anthropic/claude-sonnet`, the Session still reports `openai/gpt-6`, and the next prompt runs on `openai/gpt-6` + +#### Scenario: Unknown prompt model +- **WHEN** a prompt names `model: "missing/model"` +- **THEN** it is refused and nothing is admitted diff --git a/openspec/changes/add-one-shot-model-prompt/specs/tui/spec.md b/openspec/changes/add-one-shot-model-prompt/specs/tui/spec.md new file mode 100644 index 00000000..3a915d54 --- /dev/null +++ b/openspec/changes/add-one-shot-model-prompt/specs/tui/spec.md @@ -0,0 +1,16 @@ +## MODIFIED Requirements + +### Requirement: Model, variant and agent selection +(P0) The system SHALL provide a model picker (`/model`, Ctrl+X M) listing available models grouped by provider, with Favorites and Recents sections at the top. It SHALL be persisted in `~/.local/state/cyber/model.json` (maximum 10 recents). Ctrl+T in the picker SHALL cycle reasoning variants. Tab SHALL cycle primary, non-hidden agents. Selecting a model or agent SHALL call the Session switch operations, so the change applies at the next Turn. `/model ` SHALL send `` with that `model` (`session-runtime` → Agent, model, and mode switching), so that model answers it and the Session's model answers the next prompt; it SHALL be queued while the Session runs. `/model` with no argument or a single argument SHALL open the picker as before, and a first argument without `/` followed by text SHALL show `Usage: /model `. + +#### Scenario: Unavailable model rejected +- **WHEN** a favorite model's provider has no credentials +- **THEN** the picker shows it dimmed with `not connected`, and selecting it opens the connect dialog instead of switching + +#### Scenario: Agent cycling +- **WHEN** the user presses Tab in the composer with primary agents `build` and `docs` available +- **THEN** the active agent switches from `build` to `docs` and the footer shows the agent's color and name + +#### Scenario: One-shot model prompt +- **WHEN** the user submits `/model anthropic/claude-sonnet explain this diff` in a Session on `openai/gpt-6` +- **THEN** `explain this diff` is answered by `anthropic/claude-sonnet`, the footer still shows `openai/gpt-6`, and the next prompt is answered by `openai/gpt-6` diff --git a/openspec/changes/add-one-shot-model-prompt/tasks.md b/openspec/changes/add-one-shot-model-prompt/tasks.md new file mode 100644 index 00000000..d1d97da4 --- /dev/null +++ b/openspec/changes/add-one-shot-model-prompt/tasks.md @@ -0,0 +1,7 @@ +## 1. Prompt model + +- [x] 1.1 `model` on prompt requests, admissions, admitted events and inbox rows; validation before admission; the retry digest. +- [x] 1.2 Turn model selection through `InboxRow::turn_model` (prompt model, then command model), expiring at the final text reply. +- [x] 1.3 Runtime test through the tool host: tool loop on the prompt model, Session model unchanged, next prompt on the Session model, unknown model refused. +- [x] 1.4 TUI `/model `; unit and real-server tests. +- [x] 1.5 OpenAPI, SDK, guide and CHANGELOG. diff --git a/openspec/specs/session-runtime/spec.md b/openspec/specs/session-runtime/spec.md index 03e23f36..ca5fe0ac 100644 --- a/openspec/specs/session-runtime/spec.md +++ b/openspec/specs/session-runtime/spec.md @@ -119,7 +119,7 @@ The session runtime records Sessions and their durable input inbox, then runs ad - **THEN** its next Turn has no tools and returns a summary to the parent ### Requirement: Agent, model, and mode switching -(P0) The system SHALL record agent, model/variant, mode and output style switches as durable events (`session.agent.switched.1`, `session.model.switched.1`, `session.mode.switched.1`, `session.output_style.switched.1`). They SHALL take effect at the next Turn and append history markers that are not sent to the model. Switching to the current selection SHALL be a no-op. An output style switch SHALL record the Session's own selection (`null` returns to the configured style) and SHALL be refused for Sessions with a parent. +(P0) The system SHALL record agent, model/variant, mode and output style switches as durable events (`session.agent.switched.1`, `session.model.switched.1`, `session.mode.switched.1`, `session.output_style.switched.1`). They SHALL take effect at the next Turn and append history markers that are not sent to the model. Switching to the current selection SHALL be a no-op. A prompt MAY name a `model` (`provider/model[#variant]`) for itself alone: the Turns that answer it, tool calls included, SHALL run on that model until its final text reply, the Session's own model SHALL NOT change and no switch event SHALL be recorded, and the next prompt SHALL use the Session's model again. In a plan phase it SHALL take precedence over `model_roles.plan` for that prompt without suspending the planner, and its steps SHALL have no `model_role`. A prompt `model` that does not parse or resolve SHALL be refused before admission, and it SHALL take precedence over a command's `model`. The inbox row SHALL report the prompt's `model`, and an exact retry with another `model` SHALL be another prompt. An output style switch SHALL record the Session's own selection (`null` returns to the configured style) and SHALL be refused for Sessions with a parent. #### Scenario: Switch model mid-session - **WHEN** the user switches from `openai/gpt-6` to `anthropic/claude-sonnet` during a Turn @@ -129,6 +129,14 @@ The session runtime records Sessions and their durable input inbox, then runs ad - **WHEN** the user switches a Session to output style `concise` and the server restarts - **THEN** the Session still reports `output_style: "concise"` and its next Turn uses that style +#### Scenario: One prompt on another model +- **WHEN** a prompt on a `openai/gpt-6` Session names `model: "anthropic/claude-sonnet"` and its answer calls `read` +- **THEN** both Turns of that answer use `anthropic/claude-sonnet`, the Session still reports `openai/gpt-6`, and the next prompt runs on `openai/gpt-6` + +#### Scenario: Unknown prompt model +- **WHEN** a prompt names `model: "missing/model"` +- **THEN** it is refused and nothing is admitted + ### Requirement: Reasoning lowering across models (P0) The system SHALL send historical reasoning and provider metadata (signatures, encrypted reasoning) natively only when the historical message's provider and model exactly match the Turn's model, and otherwise SHALL lower non-empty reasoning to plain assistant text and drop empty reasoning. diff --git a/openspec/specs/tui/spec.md b/openspec/specs/tui/spec.md index de43d583..beff703e 100644 --- a/openspec/specs/tui/spec.md +++ b/openspec/specs/tui/spec.md @@ -314,7 +314,7 @@ Esc SHALL dismiss the request, which halts the Drain as defined in `session-runt - **THEN** the TUI shows `bypass mode is disabled by your organization` and the mode is unchanged ### Requirement: Model, variant and agent selection -(P0) The system SHALL provide a model picker (`/model`, Ctrl+X M) listing available models grouped by provider, with Favorites and Recents sections at the top. It SHALL be persisted in `~/.local/state/cyber/model.json` (maximum 10 recents). Ctrl+T in the picker SHALL cycle reasoning variants. Tab SHALL cycle primary, non-hidden agents. Selecting a model or agent SHALL call the Session switch operations, so the change applies at the next Turn. +(P0) The system SHALL provide a model picker (`/model`, Ctrl+X M) listing available models grouped by provider, with Favorites and Recents sections at the top. It SHALL be persisted in `~/.local/state/cyber/model.json` (maximum 10 recents). Ctrl+T in the picker SHALL cycle reasoning variants. Tab SHALL cycle primary, non-hidden agents. Selecting a model or agent SHALL call the Session switch operations, so the change applies at the next Turn. `/model ` SHALL send `` with that `model` (`session-runtime` → Agent, model, and mode switching), so that model answers it and the Session's model answers the next prompt; it SHALL be queued while the Session runs. `/model` with no argument or a single argument SHALL open the picker as before, and a first argument without `/` followed by text SHALL show `Usage: /model `. #### Scenario: Unavailable model rejected - **WHEN** a favorite model's provider has no credentials @@ -324,6 +324,10 @@ Esc SHALL dismiss the request, which halts the Drain as defined in `session-runt - **WHEN** the user presses Tab in the composer with primary agents `build` and `docs` available - **THEN** the active agent switches from `build` to `docs` and the footer shows the agent's color and name +#### Scenario: One-shot model prompt +- **WHEN** the user submits `/model anthropic/claude-sonnet explain this diff` in a Session on `openai/gpt-6` +- **THEN** `explain this diff` is answered by `anthropic/claude-sonnet`, the footer still shows `openai/gpt-6`, and the next prompt is answered by `openai/gpt-6` + ### Requirement: Session picker and actions (P0) The system SHALL provide a Session picker (`/resume`, Ctrl+X L). It SHALL list root Sessions of the Location newest first, with fuzzy search over name and title and a preview of the last message. Child and forked Sessions SHALL show as an expandable tree. From the picker or the command palette the user SHALL be able to rename, fork (from the latest message or a chosen one), archive, delete (with confirmation), and export a Session. `/rename ` SHALL rename the current Session at once, and `/rename` without a title SHALL open a dialog prefilled with the current title (Enter saves, Esc cancels). `/rename` SHALL be listed in `/help` and in the command palette as **Rename session**, with the binding action `session_rename` (unbound by default). The header, the sidebar and the terminal window title SHALL show a new title when `session.renamed.1` or `session.title.generated.1` arrives, whichever client renamed it. diff --git a/sdk/openapi.json b/sdk/openapi.json index 43a3c7fa..d4c35d4d 100644 --- a/sdk/openapi.json +++ b/sdk/openapi.json @@ -7034,6 +7034,13 @@ } ], "description": "A structured answer for this root prompt (`session-runtime` → Structured output)." + }, + "model": { + "type": [ + "string", + "null" + ], + "description": "`provider/model` that answers this prompt only; later prompts use the Session's\nmodel again." } }, "required": [ @@ -10441,6 +10448,13 @@ } ], "description": "The structured result or error of a prompt with `output_schema`, once settled." + }, + "model": { + "type": [ + "string", + "null" + ], + "description": "`provider/model` for this prompt's Turn only." } }, "required": [ diff --git a/sdk/typescript/src/generated/types.ts b/sdk/typescript/src/generated/types.ts index 19fd6c67..f25a8b72 100644 --- a/sdk/typescript/src/generated/types.ts +++ b/sdk/typescript/src/generated/types.ts @@ -2721,6 +2721,8 @@ export type InboxRow = { output_schema?: unknown; /** The structured result or error of a prompt with `output_schema`, once settled. */ structured?: StructuredOutcome | null; + /** `provider/model` for this prompt's Turn only. */ + model?: string | null; }; /** An iteration that was admitted and has not ended. */ @@ -4314,6 +4316,11 @@ export type PromptBody = { source?: string | null; /** A structured answer for this root prompt (`session-runtime` → Structured output). */ format?: PromptFormat | null; + /** + * `provider/model` that answers this prompt only; later prompts use the Session's + * model again. + */ + model?: string | null; }; /**