Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Add live GUI JSON controls

Pranav P1fbce09b59a3
diff --git a/gui/src-tauri/src/runtime/simple.rs b/gui/src-tauri/src/runtime/simple.rs
index 0a7d0f35..60bc1a09 100644
--- a/gui/src-tauri/src/runtime/simple.rs
+++ b/gui/src-tauri/src/runtime/simple.rs
@@ -3,6 +3,8 @@ use crate::{
persistence::project_store::ProjectStore, terminal::TerminalManager,
};
use anyhow::{Context, Result};
+#[cfg(target_os = "macos")]
+use std::os::unix::fs::PermissionsExt;
use std::{
collections::HashMap,
path::{Path, PathBuf},
@@ -12,8 +14,6 @@ use std::{
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::Mutex;
use uuid::Uuid;
-#[cfg(target_os = "macos")]
-use std::os::unix::fs::PermissionsExt;
#[derive(Clone, Default)]
struct ConversationState {
@@ -22,6 +22,8 @@ struct ConversationState {
title: String,
messages: Vec<SessionMessageDto>,
active_request_ids: Vec<String>,
+ active_agent_id: Option<String>,
+ plan_mode: bool,
}
#[derive(Default)]
@@ -120,7 +122,10 @@ impl RuntimeManager {
let catalog = self.ensure_model_catalog().await;
let (selected_provider, selected_model) = {
let state = self.state.lock().await;
- (state.selected_provider.clone(), state.selected_model.clone())
+ (
+ state.selected_provider.clone(),
+ state.selected_model.clone(),
+ )
};
if catalog.is_empty() {
@@ -179,15 +184,28 @@ impl RuntimeManager {
})
}
- /// Persists the model selection; it takes effect when the next session spawns.
+ /// Persists the model selection and applies it to the live session when possible.
pub async fn update_prompt_settings(
&self,
input: UpdatePromptSettingsInput,
) -> Result<PromptSettingsDto> {
- {
+ let live_conversation_id = {
let mut state = self.state.lock().await;
state.selected_provider = Some(input.provider_id.clone());
state.selected_model = Some(input.model_id.clone());
+ state.active_conversation_id.clone()
+ };
+ if let Some(conversation_id) = live_conversation_id {
+ if self.session_exists(&conversation_id).await {
+ self.send_control(
+ &conversation_id,
+ serde_json::json!({
+ "type": "set_model",
+ "name": input.model_id,
+ }),
+ )
+ .await?;
+ }
}
self.get_prompt_settings(input.workspace_path).await
}
@@ -315,6 +333,7 @@ impl RuntimeManager {
.clone()
.unwrap_or_else(|| format!("chat-{}", Uuid::new_v4().simple()));
let request_id = format!("request-{}", Uuid::new_v4().simple());
+ let plan_mode = input.agent_id.as_deref() == Some("muse");
{
let mut state = self.state.lock().await;
set_active_workspace(&mut state, &input.workspace_path);
@@ -322,6 +341,7 @@ impl RuntimeManager {
state
.selected_by_workspace
.insert(input.workspace_path.clone(), conversation_id.clone());
+ let active_agent_id = state.active_agent_id.clone();
let conversation = state
.conversations
.entry(conversation_id.clone())
@@ -331,7 +351,10 @@ impl RuntimeManager {
title: title_from_prompt(&input.prompt),
messages: vec![],
active_request_ids: vec![],
+ active_agent_id,
+ plan_mode,
});
+ conversation.plan_mode = plan_mode;
conversation.messages.push(SessionMessageDto::User {
id: format!("{request_id}-user"),
request_id: request_id.clone(),
@@ -341,8 +364,24 @@ impl RuntimeManager {
}
self.emit().await?;
+ if self.session_exists(&conversation_id).await {
+ self.send_control(
+ &conversation_id,
+ serde_json::json!({
+ "type": "set_mode",
+ "mode": if plan_mode { "plan" } else { "normal" },
+ }),
+ )
+ .await?;
+ }
+
if let Err(error) = self
- .stream_turn(&conversation_id, &request_id, &input.workspace_path, &input.prompt)
+ .stream_turn(
+ &conversation_id,
+ &request_id,
+ &input.workspace_path,
+ &input.prompt,
+ )
.await
{
let message = format_error_chain(&error);
@@ -379,7 +418,9 @@ impl RuntimeManager {
workspace_path: &str,
prompt: &str,
) -> Result<()> {
- let mut io = self.acquire_session_io(conversation_id, workspace_path).await?;
+ let mut io = self
+ .acquire_session_io(conversation_id, workspace_path)
+ .await?;
let line = serde_json::json!({ "type": "user", "text": prompt }).to_string();
if let Err(error) = write_session_line(&mut io.stdin, &line).await {
@@ -402,8 +443,9 @@ impl RuntimeManager {
}
Err(error) => {
self.drop_session(conversation_id).await;
- return Err(anyhow::Error::new(error)
- .context("Failed reading graff session output"));
+ return Err(
+ anyhow::Error::new(error).context("Failed reading graff session output")
+ );
}
};
let trimmed = line.trim();
@@ -432,14 +474,17 @@ impl RuntimeManager {
let rid = request_id.to_string();
let delta = delta.to_string();
self.mutate_conversation(conversation_id, move |conversation| {
- let existing = conversation.messages.iter_mut().rev().find_map(|message| {
- match message {
- SessionMessageDto::Assistant { id: mid, text, .. } if *mid == id => {
- Some(text)
- }
- _ => None,
- }
- });
+ let existing =
+ conversation.messages.iter_mut().rev().find_map(
+ |message| match message {
+ SessionMessageDto::Assistant { id: mid, text, .. }
+ if *mid == id =>
+ {
+ Some(text)
+ }
+ _ => None,
+ },
+ );
match existing {
Some(text) => text.push_str(&delta),
None => conversation.messages.push(SessionMessageDto::Assistant {
@@ -541,6 +586,67 @@ impl RuntimeManager {
Ok(())
}
+ /// Sends one non-user control request to a live `graff --json` session and returns its ack event.
+ async fn send_control(
+ &self,
+ conversation_id: &str,
+ request: serde_json::Value,
+ ) -> Result<serde_json::Value> {
+ let mut sessions = self.sessions.lock().await;
+ let session = sessions
+ .get_mut(conversation_id)
+ .context("No live graff session for this conversation")?;
+ let mut io = session
+ .io
+ .take()
+ .context("a prompt is already running for this conversation")?;
+ drop(sessions);
+
+ if let Err(error) = write_session_line(&mut io.stdin, &request.to_string()).await {
+ self.drop_session(conversation_id).await;
+ return Err(anyhow::Error::new(error)
+ .context("Failed to send control request to graff session"));
+ }
+
+ let ack = loop {
+ let line = match io.reader.next_line().await {
+ Ok(Some(line)) => line,
+ Ok(None) => {
+ self.drop_session(conversation_id).await;
+ anyhow::bail!("graff session exited before acknowledging control request");
+ }
+ Err(error) => {
+ self.drop_session(conversation_id).await;
+ return Err(
+ anyhow::Error::new(error).context("Failed reading graff control response")
+ );
+ }
+ };
+ let trimmed = line.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ let Ok(event) = serde_json::from_str::<serde_json::Value>(trimmed) else {
+ continue;
+ };
+ match event.get("type").and_then(serde_json::Value::as_str) {
+ Some("model" | "compact" | "mode" | "agent") => break event,
+ Some("error") => {
+ let message = event
+ .get("message")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or("graff control request failed");
+ self.release_session_io(conversation_id, io).await;
+ anyhow::bail!(message.to_string());
+ }
+ _ => {}
+ }
+ };
+
+ self.release_session_io(conversation_id, io).await;
+ Ok(ack)
+ }
+
/// Builds the current snapshot and pushes it to the UI.
async fn emit(&self) -> Result<()> {
let snapshot = self.snapshot().await?;
@@ -562,6 +668,8 @@ impl RuntimeManager {
conversation_id: conversation.conversation_id.clone(),
title: conversation.title.clone(),
messages: conversation.messages.clone(),
+ active_agent_id: conversation.active_agent_id.clone(),
+ plan_mode: conversation.plan_mode,
})
.collect()
};
@@ -597,9 +705,37 @@ impl RuntimeManager {
) -> Result<GraffSessionIo> {
let mut sessions = self.sessions.lock().await;
if !sessions.contains_key(conversation_id) {
- let model = self.state.lock().await.selected_model.clone();
+ let (model, active_agent_id, plan_mode) = {
+ let state = self.state.lock().await;
+ let conversation = state.conversations.get(conversation_id);
+ (
+ state.selected_model.clone(),
+ conversation
+ .and_then(|conversation| conversation.active_agent_id.clone())
+ .or_else(|| state.active_agent_id.clone()),
+ conversation
+ .map(|conversation| conversation.plan_mode)
+ .unwrap_or(false),
+ )
+ };
let session = spawn_graff_session(workspace_path, model.as_deref())?;
sessions.insert(conversation_id.to_string(), session);
+ drop(sessions);
+ if let Some(agent_id) = active_agent_id.filter(|id| id != "forge") {
+ self.send_control(
+ conversation_id,
+ serde_json::json!({ "type": "set_agent", "id": agent_id }),
+ )
+ .await?;
+ }
+ if plan_mode {
+ self.send_control(
+ conversation_id,
+ serde_json::json!({ "type": "set_mode", "mode": "plan" }),
+ )
+ .await?;
+ }
+ sessions = self.sessions.lock().await;
}
let session = sessions
.get_mut(conversation_id)
@@ -626,6 +762,11 @@ impl RuntimeManager {
}
}
+ /// Returns whether a live session exists for the conversation.
+ async fn session_exists(&self, conversation_id: &str) -> bool {
+ self.sessions.lock().await.contains_key(conversation_id)
+ }
+
/// Runs an MVP slash command.
pub async fn run_command(
&self,
@@ -741,13 +882,37 @@ impl RuntimeManager {
draft.export_text
}
- /// Sets the active agent.
+ /// Sets the active agent and applies it to the live conversation when present.
pub async fn set_active_agent(
&self,
agent_id: String,
_: Option<String>,
) -> Result<AgentsPayloadDto> {
- self.state.lock().await.active_agent_id = Some(agent_id);
+ let conversation_id = {
+ let mut state = self.state.lock().await;
+ state.active_agent_id = Some(agent_id.clone());
+ let conversation_id = state.active_conversation_id.clone();
+ if let Some(conversation_id) = &conversation_id {
+ if let Some(conversation) = state.conversations.get_mut(conversation_id) {
+ conversation.active_agent_id = Some(agent_id.clone());
+ }
+ }
+ conversation_id
+ };
+ if let Some(conversation_id) = conversation_id {
+ if self.session_exists(&conversation_id).await {
+ let id = if agent_id == "forge" {
+ ""
+ } else {
+ agent_id.as_str()
+ };
+ self.send_control(
+ &conversation_id,
+ serde_json::json!({ "type": "set_agent", "id": id }),
+ )
+ .await?;
+ }
+ }
Ok(self.agents_payload().await)
}
@@ -772,10 +937,7 @@ impl RuntimeManager {
let incoming: serde_json::Value =
serde_json::from_str(&input.json).context("Invalid MCP config JSON")?;
// Accept either {"mcpServers": {...}} or a bare {name: {...}} map.
- let incoming = incoming
- .get("mcpServers")
- .cloned()
- .unwrap_or(incoming);
+ let incoming = incoming.get("mcpServers").cloned().unwrap_or(incoming);
let incoming = incoming
.as_object()
.context("MCP config must be an object of servers")?;
@@ -829,7 +991,9 @@ impl RuntimeManager {
/// MCP OAuth login — not applicable: graff runs stdio MCP servers only.
pub async fn login_mcp_server(&self, _: McpServerActionInput) -> Result<McpSettingsPayloadDto> {
- anyhow::bail!("graff runs stdio MCP servers (command/args) only; OAuth login does not apply")
+ anyhow::bail!(
+ "graff runs stdio MCP servers (command/args) only; OAuth login does not apply"
+ )
}
/// MCP OAuth logout — not applicable: graff runs stdio MCP servers only.
@@ -837,7 +1001,9 @@ impl RuntimeManager {
&self,
_: McpServerActionInput,
) -> Result<McpSettingsPayloadDto> {
- anyhow::bail!("graff runs stdio MCP servers (command/args) only; OAuth logout does not apply")
+ anyhow::bail!(
+ "graff runs stdio MCP servers (command/args) only; OAuth logout does not apply"
+ )
}
/// Resolves the workspace to act on: the argument if set, else the active one.
@@ -848,25 +1014,35 @@ impl RuntimeManager {
self.state.lock().await.active_workspace_path.clone()
}
- /// Compacts a conversation marker in local state.
+ /// Compacts the live conversation and records the real compaction result.
pub async fn compact_conversation(
&self,
workspace_path: String,
conversation_id: String,
) -> Result<SessionSnapshotDto> {
- let mut state = self.state.lock().await;
- set_active_workspace(&mut state, &workspace_path);
- if let Some(conversation) = state.conversations.get_mut(&conversation_id) {
+ {
+ let mut state = self.state.lock().await;
+ set_active_workspace(&mut state, &workspace_path);
+ }
+ let ack = self
+ .send_control(&conversation_id, serde_json::json!({ "type": "compact" }))
+ .await?;
+ let chars = ack
+ .get("chars")
+ .and_then(serde_json::Value::as_u64)
+ .unwrap_or(0);
+ self.mutate_conversation(&conversation_id, move |conversation| {
let request_id = format!("compact-{}", Uuid::new_v4().simple());
conversation
.messages
.push(SessionMessageDto::ContextCompacted {
id: request_id.clone(),
request_id,
- text: "Conversation compacted for the Zig-native GUI session.".into(),
+ text: format!("Conversation compacted to a {chars}-character summary."),
});
- }
- drop(state);
+ })
+ .await;
+ self.persist_conversations().await;
self.snapshot().await
}
@@ -927,6 +1103,8 @@ impl RuntimeManager {
title: "New chat".into(),
messages: vec![],
active_request_ids: vec![],
+ active_agent_id: None,
+ plan_mode: false,
},
);
drop(state);
@@ -1275,17 +1453,30 @@ fn workspace_text_search(
]);
if let Some(exts) = ends_with {
for ext in exts {
- command.arg("--glob").arg(format!("*.{}", ext.trim_start_matches('.')));
+ command
+ .arg("--glob")
+ .arg(format!("*.{}", ext.trim_start_matches('.')));
}
}
- command.arg("--").arg(query).arg(".").current_dir(workspace_path);
+ command
+ .arg("--")
+ .arg(query)
+ .arg(".")
+ .current_dir(workspace_path);
let stdout = match command.output() {
Ok(output) => String::from_utf8_lossy(&output.stdout).into_owned(),
// ripgrep absent: fall back to git grep (needs a git repo).
Err(_) => {
let output = Command::new("git")
- .args(["grep", "--line-number", "--fixed-strings", "-I", "-e", query])
+ .args([
+ "grep",
+ "--line-number",
+ "--fixed-strings",
+ "-I",
+ "-e",
+ query,
+ ])
.current_dir(workspace_path)
.output();
match output {
@@ -1338,12 +1529,18 @@ struct PersistedConversation {
conversation_id: String,
title: String,
messages: Vec<SessionMessageDto>,
+ active_agent_id: Option<String>,
+ #[serde(default)]
+ plan_mode: bool,
}
/// Path to the transcript store (`~/.codegraff-gui/conversations.json`).
fn conversations_store_path() -> Option<PathBuf> {
- std::env::var_os("HOME")
- .map(|home| PathBuf::from(home).join(".codegraff-gui").join("conversations.json"))
+ std::env::var_os("HOME").map(|home| {
+ PathBuf::from(home)
+ .join(".codegraff-gui")
+ .join("conversations.json")
+ })
}
/// Loads persisted transcripts so past chats survive a restart. Live `graff`
@@ -1370,6 +1567,8 @@ fn load_persisted_conversations() -> HashMap<String, ConversationState> {
title: conversation.title,
messages: conversation.messages,
active_request_ids: vec![],
+ active_agent_id: conversation.active_agent_id,
+ plan_mode: conversation.plan_mode,
},
)
})
@@ -1428,7 +1627,10 @@ fn spawn_graff_session(workspace_path: &str, model: Option<&str>) -> Result<Graf
.spawn()
.context("Failed to launch Zig-native codegraff --json session")?;
let stdin = child.stdin.take().context("graff session missing stdin")?;
- let stdout = child.stdout.take().context("graff session missing stdout")?;
+ let stdout = child
+ .stdout
+ .take()
+ .context("graff session missing stdout")?;
let reader = BufReader::new(stdout).lines();
Ok(GraffSession {
child,
@@ -1567,7 +1769,10 @@ fn tool_result_summary(text: &str) -> Option<String> {
}
const LIMIT: usize = 160;
if first_line.chars().count() > LIMIT {
- Some(format!("{}…", first_line.chars().take(LIMIT).collect::<String>()))
+ Some(format!(
+ "{}…",
+ first_line.chars().take(LIMIT).collect::<String>()
+ ))
} else {
Some(first_line.to_string())
}
@@ -1913,8 +2118,8 @@ fn remove_stored_credential(provider_id: &str) -> Result<()> {
.map(|object| object.remove(provider_id).is_some())
.unwrap_or(false);
if removed {
- let text = serde_json::to_string(&value)
- .context("Failed to serialize key store")?;
+ let text =
+ serde_json::to_string(&value).context("Failed to serialize key store")?;
std::fs::write(&path, text).context("Failed to update key store")?;
}
}
@@ -1966,8 +2171,8 @@ async fn launch_codegraff_login(login_target: Option<&str>) -> Result<()> {
command_line.push(' ');
command_line.push_str(&shell_single_quote(target));
}
- let script_path = std::env::temp_dir()
- .join(format!("graff-login-{}.command", Uuid::new_v4().simple()));
+ let script_path =
+ std::env::temp_dir().join(format!("graff-login-{}.command", Uuid::new_v4().simple()));
let script = format!("#!/bin/sh\n{command_line}\nrm -f \"$0\"\n");
std::fs::write(&script_path, script)
.context("Failed to write graff login launcher script")?;
diff --git a/src/main.zig b/src/main.zig
index bc60b318..3f206936 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -79,7 +79,7 @@ var unattended = false; // -p one-shot: no human to prompt; unapproved tool call
const schema_protocol_json =
\\{
\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",
- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"name\":\"provider|provider/model|model\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"} are live control requests acked by model/compact/mode/agent events. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
\\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to harness.trajectory.jsonl (the append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",
\\ "events": [
\\ {"type": "text", "text": "assistant text delta"},
@@ -87,6 +87,10 @@ const schema_protocol_json =
\\ {"type": "tool_result", "name": "tool", "is_error": false, "text": "..."},
\\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0},
\\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},
+ \\ {"type": "model", "ok": true, "id": "provider", "name": "model", "context": 0, "note": "context kept"},
+ \\ {"type": "compact", "ok": true, "chars": 0},
+ \\ {"type": "mode", "ok": true, "mode": "plan"},
+ \\ {"type": "agent", "ok": true, "id": "reviewer", "chars": 0},
\\ {"type": "score", "ok": true, "prompt_sha": "..."},
\\ {"type": "error", "message": "..."}
\\ ]
@@ -104,7 +108,7 @@ const schema_serve_json =
\\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},
\\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},
\\ {"method": "POST", "path": "/v1/sessions", "description": "create a session (a graff --json child); optional JSON body {\"model\",\"yolo\",\"system_prompt\",\"append_system_prompt\"} overrides serve-level defaults; responds {\"session_id\":\"<16 hex>\"}"},
- \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / set_system_prompt / score); response streams application/x-ndjson events until the request's terminal event (turn/error, or the system_prompt/score ack); one request in flight per session at a time"},
+ \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / set_system_prompt / set_model / compact / set_mode / set_agent / score); response streams application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); one request in flight per session at a time"},
\\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin"}
\\ ]
\\}
@@ -3921,6 +3925,68 @@ pub fn main(init: std.process.Init) !void {
(if (parsed.object.get("type")) |v| (if (v == .string) v.string else "") else "")
else
"";
+ if (std.mem.eql(u8, rtype, "set_model")) {
+ const name = if (parsed.object.get("name")) |v| (if (v == .string) v.string else "") else "";
+ if (name.len == 0) {
+ root.emit(.{ .type = "error", .message = "set_model needs a non-empty name" });
+ continue;
+ }
+ const provider = resolveProviderRequest(&keys, arena, name) catch |err| {
+ const message = switch (err) {
+ error.MissingKey => try std.fmt.allocPrint(arena, "no key/login for requested model '{s}'", .{name}),
+ error.InvalidModelRequest => "set_model needs a non-empty name",
+ else => try std.fmt.allocPrint(arena, "failed to switch model '{s}': {s}", .{ name, @errorName(err) }),
+ };
+ root.emit(.{ .type = "error", .message = message });
+ continue;
+ };
+ const note = applyProvider(&root, arena, provider);
+ root.emit(.{ .type = "model", .ok = true, .id = provider.id, .name = provider.model, .context = provider.context, .note = note });
+ continue;
+ }
+ if (std.mem.eql(u8, rtype, "compact")) {
+ const chars = root.compact() catch |err| {
+ const message = switch (err) {
+ error.EmptySummary => "compaction failed: empty summary, history unchanged",
+ else => try std.fmt.allocPrint(arena, "compaction failed: {s}", .{@errorName(err)}),
+ };
+ root.emit(.{ .type = "error", .message = message });
+ continue;
+ };
+ root.emit(.{ .type = "compact", .ok = true, .chars = chars });
+ continue;
+ }
+ if (std.mem.eql(u8, rtype, "set_mode")) {
+ const mode = if (parsed.object.get("mode")) |v| (if (v == .string) v.string else "") else "";
+ if (std.mem.eql(u8, mode, "plan")) {
+ plan_mode = true;
+ } else if (std.mem.eql(u8, mode, "normal")) {
+ plan_mode = false;
+ } else {
+ root.emit(.{ .type = "error", .message = "set_mode needs mode 'plan' or 'normal'" });
+ continue;
+ }
+ root.emit(.{ .type = "mode", .ok = true, .mode = mode });
+ continue;
+ }
+ if (std.mem.eql(u8, rtype, "set_agent")) {
+ const id = if (parsed.object.get("id")) |v| (if (v == .string) v.string else "") else "";
+ if (id.len == 0) {
+ root.sys_normal = sys_normal;
+ root.sys_strict = sys_strict;
+ root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = root.sys_normal.len });
+ continue;
+ }
+ const prompt = agentTypePrompt(id) orelse {
+ const message = try std.fmt.allocPrint(arena, "unknown agent '{s}' (see /agents)", .{id});
+ root.emit(.{ .type = "error", .message = message });
+ continue;
+ };
+ root.sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ sys_normal, prompt });
+ root.sys_strict = try std.fmt.allocPrint(arena, "{s}{s}", .{ root.sys_normal, strict_note });
+ root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = root.sys_normal.len });
+ continue;
+ }
if (std.mem.eql(u8, rtype, "score")) {
const sha = if (parsed.object.get("prompt_sha")) |v| (if (v == .string) v.string else "") else "";
const sc: f64 = if (parsed.object.get("score")) |v| switch (v) {
@@ -4115,7 +4181,7 @@ pub fn main(init: std.process.Init) !void {
}
if (root.last_context_tokens >= root.provider.compactAt()) {
- root.compact() catch |err| switch (err) {
+ _ = root.compact() catch |err| switch (err) {
error.ApiError => {},
else => |e| root.say("[compaction skipped: {t}]\n", .{e}) catch {},
};
@@ -4229,12 +4295,7 @@ fn translateHistory(arena: Allocator, msgs: *std.json.Array, to_kind: Provider.K
msgs.* = out;
}
-/// Switch the active provider/model. Within the same wire format
-/// (provider.kind) the conversation is kept verbatim. Across formats
-/// (OpenAI↔Anthropic↔Responses) the stored messages don't fit the new shape:
-/// with keep_context on (default) the dialogue is translated to a text-only
-/// history and carried over; off clears it.
-fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writer) !void {
+fn applyProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
const same_format = root.provider.kind == p.kind;
var note: []const u8 = "context kept";
if (!same_format) {
@@ -4250,6 +4311,40 @@ fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writer)
root.cap_new = false; // per-provider token-cap quirk; relearn on rejection
root.provider = p;
saveModel(root.io, root.home, p.id, p.model); // remember for next launch
+ return note;
+}
+
+fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Provider {
+ const arg = std.mem.trim(u8, query, " \t");
+ if (arg.len == 0) return error.InvalidModelRequest;
+
+ if (std.mem.indexOfAny(u8, arg, " /\t")) |i| {
+ const pid = arg[0..i];
+ const mdl = std.mem.trim(u8, arg[i + 1 ..], " \t");
+ for (provider_specs) |spec| {
+ if (!std.mem.eql(u8, spec.id, pid) or mdl.len == 0) continue;
+ const m = try arena.dupe(u8, mdl);
+ return keys.providerById(pid, m);
+ }
+ }
+
+ for (provider_specs) |spec| {
+ if (!std.mem.eql(u8, spec.id, arg)) continue;
+ return keys.providerById(spec.id, spec.default_model);
+ }
+
+ const resolved = resolveModelName(keys.*, arg);
+ const name = try arena.dupe(u8, resolved orelse arg);
+ return keys.providerFor(name);
+}
+
+/// Switch the active provider/model. Within the same wire format
+/// (provider.kind) the conversation is kept verbatim. Across formats
+/// (OpenAI↔Anthropic↔Responses) the stored messages don't fit the new shape:
+/// with keep_context on (default) the dialogue is translated to a text-only
+/// history and carried over; off clears it.
+fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writer) !void {
+ const note = applyProvider(root, arena, p);
try out.print("switched to {s} via {s} ({t} format, {d}k ctx) — {s}\n", .{
p.model, p.id, p.kind, p.context / 1000, note,
});
@@ -4886,7 +4981,7 @@ fn handleCommand(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return;
}
if (std.mem.eql(u8, line, "/compact")) {
- root.compact() catch |err| switch (err) {
+ _ = root.compact() catch |err| switch (err) {
error.ApiError => {},
else => |e| return e,
};
@@ -5950,7 +6045,9 @@ fn serveTerminalEvent(line: []const u8) bool {
}
}
return std.mem.eql(u8, t, "turn") or std.mem.eql(u8, t, "error") or
- std.mem.eql(u8, t, "system_prompt") or std.mem.eql(u8, t, "score");
+ std.mem.eql(u8, t, "system_prompt") or std.mem.eql(u8, t, "score") or
+ std.mem.eql(u8, t, "model") or std.mem.eql(u8, t, "compact") or
+ std.mem.eql(u8, t, "mode") or std.mem.eql(u8, t, "agent");
}
/// Remove a dead session and free it (child already gone or being killed).
@@ -7209,12 +7306,12 @@ const Agent = struct {
/// Ask the model for a context-handoff summary (no tools), then restart
/// history from that summary.
- fn compact(self: *Agent) anyerror!void {
+ fn compact(self: *Agent) anyerror!usize {
if (self.messages.items.len == 0) {
- try self.say("nothing to compact\n", .{});
- return;
+ if (!json_mode) try self.say("nothing to compact\n", .{});
+ return 0;
}
- try self.say("[compacting ~{d} tokens…]\n", .{self.last_context_tokens});
+ if (!json_mode) try self.say("[compacting ~{d} tokens…]\n", .{self.last_context_tokens});
try self.messages.append(try textMessage(self.arena, "user", compact_instruction));
errdefer _ = self.messages.pop();
@@ -7256,9 +7353,9 @@ const Agent = struct {
},
};
if (summary.len == 0) {
- try self.say("[compaction failed: empty summary, history unchanged]\n", .{});
+ if (!json_mode) try self.say("[compaction failed: empty summary, history unchanged]\n", .{});
_ = self.messages.pop();
- return;
+ return error.EmptySummary;
}
var fresh = std.json.Array.init(self.arena);
@@ -7273,7 +7370,8 @@ const Agent = struct {
try fresh.append(try textMessage(self.arena, "user", handoff));
self.messages = fresh;
self.last_context_tokens = 0;
- try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});
+ if (!json_mode) try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});
+ return summary.len;
}
fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bool, stream_usage: bool) ![]u8 {