Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): /goal slash command — keep working until a condition is met

tikikun122f36b279ee
diff --git a/jan-agent.sh b/jan-agent.sh
new file mode 100755
index 000000000..71fbaf2bb
--- /dev/null
+++ b/jan-agent.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# Convenience launcher for the locally-built Jan agent binary.
+# Usage:
+# ./jan-agent.sh -> opens the interactive agent UI
+# ./jan-agent.sh agent status -> forwards any args straight to `jan`
+# ./jan-agent.sh agent run "..." -> run a task headlessly
+
+set -euo pipefail
+
+DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+JAN_BIN="$DIR/src-tauri/resources/bin/jan"
+
+if [ ! -x "$JAN_BIN" ]; then
+ echo "error: jan binary not found or not executable at $JAN_BIN" >&2
+ exit 1
+fi
+
+cd "$DIR/src-tauri"
+
+if [ "$#" -eq 0 ]; then
+ exec "$JAN_BIN" agent ui
+else
+ exec "$JAN_BIN" "$@"
+fi
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 52f5c0056..5c8b02133 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -15,6 +15,7 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.
# .jan/agent/agent.toml [provider] section.
#
# default_model = "gpt-4o" # used when no --model / agent.toml model is set
+# smol_model = "gpt-4o-mini" # fast model for the `smol` role (/goal evaluation)
#
# [providers.openai]
# api_key = "sk-..."
@@ -32,6 +33,10 @@ struct GlobalConfigToml {
/// flag nor `agent.toml` names one. Takes precedence over any derived guess.
#[serde(default, skip_serializing_if = "Option::is_none")]
default_model: Option<String>,
+ /// Fast, cheap model for the `smol` role: goal evaluation and other
+ /// lightweight side calls. Falls back to `default_model` when unset.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ smol_model: Option<String>,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
@@ -122,6 +127,14 @@ pub(crate) fn default_model() -> Result<Option<String>, String> {
.find_map(|(_, entry)| entry.models.into_iter().next()))
}
+/// Resolve the `smol` role model from `~/.jan/config.toml`: the explicit
+/// `smol_model` key if set. `None` when unset (callers fall back to the
+/// session's main model). Errors only on a malformed file.
+pub(crate) fn smol_model() -> Result<Option<String>, String> {
+ let config = load_raw()?;
+ Ok(config.smol_model.filter(|m| !m.trim().is_empty()))
+}
+
/// Read `~/.jan/config.toml` into the raw TOML struct for editing. Missing file
/// -> default (empty); malformed file -> error, so a set never silently drops an
/// unparseable file's contents.
diff --git a/src-tauri/src/core/agent/goal.rs b/src-tauri/src/core/agent/goal.rs
new file mode 100644
index 000000000..4d595e93b
--- /dev/null
+++ b/src-tauri/src/core/agent/goal.rs
@@ -0,0 +1,396 @@
+//! `/goal` support: keep the agent working across turns until a completion
+//! condition is met. A goal stores a user-supplied condition; after each
+//! assistant turn a fast, stateless evaluator (the session's `smol` role model)
+//! reads the condition plus the conversation and returns yes/no + a short
+//! reason. "no" surfaces the reason as guidance and starts the next turn
+//! automatically; "yes" marks the goal achieved and returns control to the
+//! user. The evaluator calls no tools and has no side effects.
+
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use tokio::sync::mpsc;
+
+use crate::core::agent::r#loop::ModelInvoker;
+use crate::core::agent::upstream::extract_choice_message;
+
+/// Hard cap on a goal condition, per the spec ("up to 4k chars").
+pub(crate) const MAX_CONDITION_CHARS: usize = 4096;
+
+/// Lifecycle of an active goal.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum GoalStatus {
+ /// The loop is running: turns fire until the evaluator says the goal is met.
+ Active,
+ /// The evaluator judged the condition satisfied; control is back with the user.
+ Achieved,
+}
+
+/// A session-scoped goal, serialized with the thread so it survives restart and
+/// `/resume`. Times are Unix epoch seconds so they round-trip through JSON
+/// without pulling in a datetime dependency.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub(crate) struct GoalState {
+ /// The completion condition the evaluator checks after every turn.
+ pub condition: String,
+ /// Turns run since the goal was set (each assistant turn increments this).
+ #[serde(default)]
+ pub turns: u32,
+ /// When the goal was set, Unix epoch seconds.
+ #[serde(default)]
+ pub started_at: u64,
+ /// The evaluator's most recent short reason ("" until the first evaluation).
+ #[serde(default)]
+ pub last_reason: String,
+ /// Current lifecycle state.
+ #[serde(default = "default_status")]
+ pub status: GoalStatus,
+}
+
+fn default_status() -> GoalStatus {
+ GoalStatus::Active
+}
+
+impl GoalState {
+ /// Start a fresh, active goal for `condition` (trimmed and length-capped).
+ pub fn new(condition: &str) -> Self {
+ Self {
+ condition: clamp_condition(condition),
+ turns: 0,
+ started_at: now_secs(),
+ last_reason: String::new(),
+ status: GoalStatus::Active,
+ }
+ }
+
+ /// Whether the loop should keep firing turns.
+ pub fn is_active(&self) -> bool {
+ self.status == GoalStatus::Active
+ }
+
+ /// Seconds elapsed since the goal was set (saturating; robust to clock skew).
+ pub fn elapsed_secs(&self) -> u64 {
+ now_secs().saturating_sub(self.started_at)
+ }
+}
+
+/// Trim and cap a condition to [`MAX_CONDITION_CHARS`] (char-safe).
+pub(crate) fn clamp_condition(condition: &str) -> String {
+ let trimmed = condition.trim();
+ if trimmed.chars().count() <= MAX_CONDITION_CHARS {
+ return trimmed.to_string();
+ }
+ trimmed.chars().take(MAX_CONDITION_CHARS).collect()
+}
+
+fn now_secs() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+/// The evaluator's verdict for one turn.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct GoalVerdict {
+ /// True when the condition is satisfied.
+ pub met: bool,
+ /// A short human-readable reason (guidance when `met` is false).
+ pub reason: String,
+}
+
+const EVALUATOR_SYSTEM_PROMPT: &str = "You are a strict completion evaluator for an autonomous \
+coding agent. You are given a GOAL (a condition that should become true) and a TRANSCRIPT of the \
+agent's work so far. Decide whether the goal is now satisfied based ONLY on evidence in the \
+transcript. Do not run tools, do not assume work that is not shown, and do not give the agent the \
+benefit of the doubt. If the evidence is missing or ambiguous, the goal is NOT met.\n\n\
+Reply with a single line of JSON and nothing else, in exactly this shape:\n\
+{\"met\": true|false, \"reason\": \"<one concise sentence>\"}\n\
+When \"met\" is false, the reason must state what still needs to happen so the agent can continue.";
+
+/// Render the conversation into a plain-text transcript for the evaluator,
+/// capped so a long session cannot itself overflow the evaluator's context.
+/// The most recent content is kept when truncating.
+fn serialize_transcript(messages: &[Value]) -> String {
+ const MAX_CHARS: usize = 60_000;
+ let mut lines: Vec<String> = Vec::with_capacity(messages.len());
+ for msg in messages {
+ let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
+ // Skip system prompts: they describe capabilities, not progress.
+ if role == "system" {
+ continue;
+ }
+ let content = match msg.get("content") {
+ Some(Value::String(s)) => s.clone(),
+ Some(Value::Null) | None => String::new(),
+ Some(other) => other.to_string(),
+ };
+ let mut line = format!("{role}: {content}");
+ if let Some(calls) = msg.get("tool_calls").and_then(|v| v.as_array()) {
+ let names: Vec<&str> = calls
+ .iter()
+ .filter_map(|c| {
+ c.get("function")
+ .and_then(|f| f.get("name"))
+ .and_then(|n| n.as_str())
+ })
+ .collect();
+ if !names.is_empty() {
+ line.push_str(&format!(" [tool_calls: {}]", names.join(", ")));
+ }
+ }
+ lines.push(line);
+ }
+ let joined = lines.join("\n");
+ if joined.len() > MAX_CHARS {
+ let start = joined.len() - MAX_CHARS;
+ let start = (start..joined.len())
+ .find(|i| joined.is_char_boundary(*i))
+ .unwrap_or(joined.len());
+ format!("[...older content truncated...]\n{}", &joined[start..])
+ } else {
+ joined
+ }
+}
+
+/// Build the stateless evaluator request body (no tools, no streaming needed).
+pub(crate) fn build_evaluator_request(
+ model_id: &str,
+ condition: &str,
+ messages: &[Value],
+) -> Value {
+ let user = format!(
+ "GOAL:\n{condition}\n\nTRANSCRIPT:\n{}",
+ serialize_transcript(messages)
+ );
+ json!({
+ "model": model_id,
+ "messages": [
+ { "role": "system", "content": EVALUATOR_SYSTEM_PROMPT },
+ { "role": "user", "content": user },
+ ],
+ // Deterministic judging: no creativity wanted.
+ "temperature": 0,
+ })
+}
+
+/// Parse the evaluator's reply. Accepts a bare JSON object, JSON embedded in
+/// prose, or a plain yes/no line as a fallback so a non-conforming smol model
+/// still yields a usable verdict.
+pub(crate) fn parse_verdict(reply: &str) -> GoalVerdict {
+ let trimmed = reply.trim();
+
+ // Preferred path: a JSON object somewhere in the reply.
+ if let Some(obj) = extract_json_object(trimmed) {
+ let met = obj.get("met").and_then(Value::as_bool);
+ let reason = obj
+ .get("reason")
+ .and_then(|r| r.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ if let Some(met) = met {
+ return GoalVerdict {
+ met,
+ reason: reason.unwrap_or_else(|| {
+ if met {
+ "condition satisfied".to_string()
+ } else {
+ "condition not yet satisfied".to_string()
+ }
+ }),
+ };
+ }
+ }
+
+ // Fallback: sniff an affirmative/negative from the leading text.
+ let lower = trimmed.to_lowercase();
+ let met = lower.starts_with("yes")
+ || lower.starts_with("true")
+ || lower.contains("\"met\": true")
+ || lower.contains("goal met")
+ || lower.contains("condition met");
+ GoalVerdict {
+ met,
+ reason: if trimmed.is_empty() {
+ "evaluator returned no reason".to_string()
+ } else {
+ first_line(trimmed).to_string()
+ },
+ }
+}
+
+/// Extract the first balanced `{...}` JSON object from `s`, if it parses.
+fn extract_json_object(s: &str) -> Option<Value> {
+ let start = s.find('{')?;
+ let mut depth = 0usize;
+ let mut in_str = false;
+ let mut escaped = false;
+ for (i, ch) in s[start..].char_indices() {
+ if in_str {
+ if escaped {
+ escaped = false;
+ } else if ch == '\\' {
+ escaped = true;
+ } else if ch == '"' {
+ in_str = false;
+ }
+ continue;
+ }
+ match ch {
+ '"' => in_str = true,
+ '{' => depth += 1,
+ '}' => {
+ depth -= 1;
+ if depth == 0 {
+ let end = start + i + 1;
+ return serde_json::from_str(&s[start..end]).ok();
+ }
+ }
+ _ => {}
+ }
+ }
+ None
+}
+
+fn first_line(s: &str) -> &str {
+ s.lines().next().unwrap_or(s).trim()
+}
+
+/// Run one stateless evaluation. Errors from the model call are surfaced to the
+/// caller so it can decide whether to keep looping; a malformed reply degrades
+/// to a best-effort verdict via [`parse_verdict`].
+pub(crate) async fn evaluate(
+ model_id: &str,
+ condition: &str,
+ messages: &[Value],
+ model: &dyn ModelInvoker,
+) -> Result<GoalVerdict, String> {
+ let request = build_evaluator_request(model_id, condition, messages);
+ // The evaluator's tokens are internal: a dropped receiver keeps them off the
+ // user-facing stream.
+ let (sink, _rx) = mpsc::unbounded_channel();
+ let completion = model.invoke(&request, &sink).await?;
+ let reply = extract_choice_message(&completion)
+ .and_then(|m| m.get("content").cloned())
+ .and_then(|c| c.as_str().map(str::to_string))
+ .unwrap_or_default();
+ Ok(parse_verdict(&reply))
+}
+
+/// The guidance message injected as the next user turn when the goal is unmet.
+/// Phrased as a continuation so the agent keeps working rather than re-asking.
+pub(crate) fn continuation_prompt(condition: &str, reason: &str) -> String {
+ format!(
+ "Continue working toward this goal: {condition}\n\n\
+The goal is not yet met: {reason}\n\n\
+Keep going until it is satisfied. Do not stop to ask for confirmation."
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::events::StreamEvent;
+ use async_trait::async_trait;
+
+ struct StubModel {
+ reply: String,
+ }
+ #[async_trait]
+ impl ModelInvoker for StubModel {
+ async fn invoke(
+ &self,
+ _request: &Value,
+ _events: &mpsc::UnboundedSender<StreamEvent>,
+ ) -> Result<Value, String> {
+ Ok(json!({ "choices": [{ "message": { "content": self.reply.clone() } }] }))
+ }
+ }
+
+ #[test]
+ fn clamp_trims_and_caps() {
+ assert_eq!(clamp_condition(" hi "), "hi");
+ let long = "x".repeat(MAX_CONDITION_CHARS + 500);
+ assert_eq!(clamp_condition(&long).chars().count(), MAX_CONDITION_CHARS);
+ }
+
+ #[test]
+ fn new_goal_is_active() {
+ let g = GoalState::new("all tests pass");
+ assert!(g.is_active());
+ assert_eq!(g.turns, 0);
+ assert_eq!(g.condition, "all tests pass");
+ }
+
+ #[test]
+ fn parses_clean_json_verdict() {
+ let v = parse_verdict(r#"{"met": true, "reason": "all tests green"}"#);
+ assert!(v.met);
+ assert_eq!(v.reason, "all tests green");
+
+ let v = parse_verdict(r#"{"met": false, "reason": "3 tests still failing"}"#);
+ assert!(!v.met);
+ assert_eq!(v.reason, "3 tests still failing");
+ }
+
+ #[test]
+ fn parses_json_embedded_in_prose() {
+ let v = parse_verdict(
+ "Here is my judgment:\n{\"met\": false, \"reason\": \"not done\"}\nThanks",
+ );
+ assert!(!v.met);
+ assert_eq!(v.reason, "not done");
+ }
+
+ #[test]
+ fn parses_json_with_nested_braces_in_reason() {
+ let v = parse_verdict(r#"{"met": true, "reason": "the {x} block compiles"}"#);
+ assert!(v.met);
+ assert_eq!(v.reason, "the {x} block compiles");
+ }
+
+ #[test]
+ fn falls_back_to_yes_no_sniffing() {
+ assert!(parse_verdict("Yes, the condition is met.").met);
+ assert!(!parse_verdict("No, still work to do.").met);
+ }
+
+ #[test]
+ fn empty_reply_is_not_met() {
+ let v = parse_verdict("");
+ assert!(!v.met);
+ assert!(!v.reason.is_empty());
+ }
+
+ #[test]
+ fn transcript_omits_system_messages() {
+ let msgs = vec![
+ json!({ "role": "system", "content": "you are an agent" }),
+ json!({ "role": "user", "content": "do the thing" }),
+ json!({ "role": "assistant", "content": "done" }),
+ ];
+ let t = serialize_transcript(&msgs);
+ assert!(!t.contains("you are an agent"));
+ assert!(t.contains("do the thing"));
+ assert!(t.contains("done"));
+ }
+
+ #[tokio::test]
+ async fn evaluate_returns_met_verdict() {
+ let model = StubModel {
+ reply: r#"{"met": true, "reason": "ok"}"#.into(),
+ };
+ let msgs = vec![json!({ "role": "user", "content": "hi" })];
+ let v = evaluate("smol", "cond", &msgs, &model).await.unwrap();
+ assert!(v.met);
+ assert_eq!(v.reason, "ok");
+ }
+
+ #[test]
+ fn continuation_prompt_includes_condition_and_reason() {
+ let p = continuation_prompt("tests pass", "2 failing");
+ assert!(p.contains("tests pass"));
+ assert!(p.contains("2 failing"));
+ }
+}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index a3c0343fd..61dc65da6 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -961,6 +961,31 @@ pub(crate) async fn compact_history(
.await)
}
+/// Run one stateless `/goal` evaluation against `smol_model_id` (the session's
+/// fast "smol" role). Mirrors [`compact_history`]: resolve the upstream for the
+/// evaluator model, then make a single tool-free model call that judges whether
+/// `condition` is satisfied by `messages`. No tools, no streaming to the user.
+pub(crate) async fn evaluate_goal(
+ args: &OrchestrationArgs,
+ smol_model_id: &str,
+ condition: &str,
+ messages: &[serde_json::Value],
+) -> Result<crate::core::agent::goal::GoalVerdict, String> {
+ let (upstream_url, api_keys) = resolve_upstream_for_model(
+ smol_model_id,
+ args.provider_configs.clone(),
+ args.llama_state.clone(),
+ args.mlx_sessions.clone(),
+ )
+ .await?;
+ let model = HttpModelInvoker {
+ client: args.client.clone(),
+ upstream_url,
+ api_keys,
+ };
+ crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await
+}
+
#[allow(clippy::too_many_arguments)]
async fn run_turn_cycle(
events: &mpsc::UnboundedSender<StreamEvent>,
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index b23b21881..9aa883855 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -5,6 +5,7 @@ pub mod commands;
pub mod compaction;
pub mod context;
pub mod events;
+pub mod goal;
#[cfg(feature = "cli")]
pub mod global_config;
#[cfg(feature = "cli")]
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 2fbe43271..34b164378 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1030,6 +1030,8 @@ pub(crate) struct AgentSession {
pub args: OrchestrationArgs,
pub permission_requests: PermissionRegistry,
pub model: String,
+ /// Fast model for the `smol` role (goal evaluation). Falls back to `model`.
+ pub smol_model: String,
pub max_turns: u32,
/// Background local-router startup, awaited before the first turn. `None`
/// for cloud models.
@@ -1094,6 +1096,13 @@ fn prepare_agent_session(
.or(cfg.agent.max_turns)
.unwrap_or(DEFAULT_MAX_TURNS);
+ // The `smol` role (used by /goal evaluation): an explicit smol_model in
+ // ~/.jan/config.toml, else reuse the main model so evaluation always works.
+ let smol_model = crate::core::agent::global_config::smol_model()
+ .ok()
+ .flatten()
+ .unwrap_or_else(|| model.clone());
+
let provider_configs = load_provider_configs(Some(&project_root), &overrides)?;
// A local llamacpp model needs its router started; cloud models are plain
@@ -1135,6 +1144,7 @@ fn prepare_agent_session(
args,
permission_requests,
model,
+ smol_model,
max_turns,
router_task,
mcp_servers,
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 329c6aade..c4f6d8961 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -31,7 +31,7 @@ use crate::core::agent::git;
use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};
use crate::core::agent::tools::gate::PermissionDecision;
-#[derive(PartialEq)]
+#[derive(Debug, PartialEq)]
enum Status {
Idle,
Running,
@@ -252,6 +252,16 @@ struct PendingImage {
struct App {
model: String,
+ /// Fast model for the `smol` role, used by `/goal` evaluation. Defaults to
+ /// `model` when no smol model is configured.
+ smol_model: String,
+ /// Active `/goal`, if any: the loop keeps firing turns until the evaluator
+ /// judges the condition met. Persisted with the thread so it survives
+ /// restart/resume. `None` = no goal.
+ goal: Option<crate::core::agent::goal::GoalState>,
+ /// Set after a turn finishes while a goal is active: the chat loop runs the
+ /// evaluator off the render loop, then auto-continues or returns control.
+ goal_eval_pending: bool,
/// Orchestration handle for out-of-run model calls (the `/compact` command).
/// `None` in unit tests, set by `run` for the live session.
args: Option<Arc<OrchestrationArgs>>,
@@ -428,7 +438,10 @@ impl App {
repo_root: Option<PathBuf>,
) -> Self {
Self {
+ smol_model: model.clone(),
model,
+ goal: None,
+ goal_eval_pending: false,
args: None,
max_turns,
repo_root,
@@ -518,6 +531,9 @@ impl App {
fn reset_session(&mut self) {
self.history.clear();
self.thread_id = None;
+ // A fresh session drops any active goal along with the conversation.
+ self.goal = None;
+ self.goal_eval_pending = false;
// Detach snapshots; the next submit arms a fresh base + thread id.
self.base_snapshot = None;
self.checkpoints.clear();
@@ -871,11 +887,23 @@ impl App {
/// per-turn checkpoints, so `/resume` can restore and rewind. `None` when
/// snapshots are inactive (keeps a plain `{}` metadata block).
fn thread_metadata(&self) -> Option<serde_json::Value> {
- let base = self.base_snapshot.as_ref()?;
- Some(serde_json::json!({
- "base_snapshot": base,
- "checkpoints": self.checkpoints,
- }))
+ // Persist metadata when either snapshots or a goal are present; a goal
+ // must survive restart/resume even in a non-git project (no snapshots).
+ if self.base_snapshot.is_none() && self.goal.is_none() {
+ return None;
+ }
+ let mut meta = serde_json::Map::new();
+ if let Some(base) = self.base_snapshot.as_ref() {
+ meta.insert("base_snapshot".to_string(), serde_json::json!(base));
+ meta.insert("checkpoints".to_string(), serde_json::json!(self.checkpoints));
+ }
+ if let Some(goal) = self.goal.as_ref() {
+ meta.insert(
+ "goal".to_string(),
+ serde_json::to_value(goal).unwrap_or(serde_json::Value::Null),
+ );
+ }
+ Some(serde_json::Value::Object(meta))
}
/// Queue a checkpoint of the working tree produced by the just-finished turn,
@@ -1223,6 +1251,17 @@ impl App {
self.push(Line::styled(msg, Style::new().yellow().bold()));
}
self.checkpoint_turn();
+ // A turn just completed under an active goal: count it and queue an
+ // evaluation. The chat loop runs the (stateless) evaluator off the
+ // render loop, then auto-continues or hands control back.
+ if let Some(goal) = self.goal.as_mut() {
+ if goal.is_active() {
+ goal.turns = goal.turns.saturating_add(1);
+ // Only evaluate on a normal completion; an early/no-answer finish
+ // is surfaced above and the user decides what to do next.
+ self.goal_eval_pending = normal && !no_answer;
+ }
+ }
self.persist();
}
@@ -1242,6 +1281,81 @@ impl App {
Style::new().red().bold(),
));
self.scrollback = 0;
+ // An errored turn halts the goal loop; the user decides how to recover.
+ self.goal_eval_pending = false;
+ if let Some(goal) = self.goal.as_ref() {
+ if goal.is_active() {
+ self.note("goal paused (turn errored); /goal to review, /goal clear to stop");
+ }
+ }
+ }
+
+ /// Run one goal evaluation and act on the verdict. Called by the chat loop
+ /// when a turn finished under an active goal (`goal_eval_pending`). Makes one
+ /// stateless `smol`-model call (no tools), then either auto-submits the next
+ /// turn (goal unmet) or marks the goal achieved and returns control (goal
+ /// met). Runs only while idle; blocks the loop for the single eval call.
+ async fn run_goal_evaluation(&mut self) {
+ self.goal_eval_pending = false;
+ let Some(goal) = self.goal.clone() else {
+ return;
+ };
+ if !goal.is_active() {
+ return;
+ }
+ let Some(args) = self.args.clone() else {
+ // No live session (e.g. tests): cannot evaluate. Leave control with
+ // the user rather than looping blindly.
+ return;
+ };
+ self.note("◎ evaluating goal...");
+ let verdict = crate::core::agent::r#loop::evaluate_goal(
+ &args,
+ &self.smol_model,
+ &goal.condition,
+ &self.history,
+ )
+ .await;
+
+ match verdict {
+ Ok(v) => {
+ if let Some(g) = self.goal.as_mut() {
+ g.last_reason = v.reason.clone();
+ }
+ if v.met {
+ if let Some(g) = self.goal.as_mut() {
+ g.status = crate::core::agent::goal::GoalStatus::Achieved;
+ }
+ let turns = self.goal.as_ref().map(|g| g.turns).unwrap_or(0);
+ let elapsed = self.goal.as_ref().map(|g| g.elapsed_secs()).unwrap_or(0);
+ self.gap(Kind::Meta);
+ self.push(Line::styled(
+ format!(
+ "◎ goal achieved in {turns} turn(s), {}",
+ fmt_duration(elapsed)
+ ),
+ Style::new().green().bold(),
+ ));
+ self.push(Line::styled(format!(" {}", v.reason), Style::new().dim()));
+ self.persist();
+ } else {
+ // Goal unmet: surface the reason as guidance and start the
+ // next turn automatically, no user prompt needed.
+ self.note(&format!("◎ goal not met: {} — continuing", v.reason));
+ let prompt =
+ crate::core::agent::goal::continuation_prompt(&goal.condition, &v.reason);
+ self.submit_user(prompt);
+ }
+ }
+ Err(e) => {
+ // Evaluation failed: don't loop blindly. Keep the goal so the
+ // user can retry, and hand control back.
+ self.note(&format!(
+ "◎ goal evaluation failed: {e} (goal kept; /goal clear to stop)"
+ ));
+ self.persist();
+ }
+ }
}
/// Cancel the in-flight run, keeping the conversation intact.
@@ -1261,6 +1375,9 @@ impl App {
self.scrollback = 0;
self.gap(Kind::Meta);
self.push(Line::styled("cancelled", Style::new().yellow()));
+ // A cancel stops the goal loop mid-flight; the goal itself is kept so
+ // the user can inspect it (/goal) or clear it (/goal clear).
+ self.goal_eval_pending = false;
self.persist();
}
}
@@ -1949,6 +2066,7 @@ pub async fn run(
args,
permission_requests,
model,
+ smol_model,
max_turns,
router_task,
mcp_servers,
@@ -1966,6 +2084,7 @@ pub async fn run(
// non-repo runs exactly as before with conversation-only rewind.
let repo_root = git::repo_root(&project_root);
let mut app = App::new(model, max_turns, agent_dir, project_root, repo_root);
+ app.smol_model = smol_model;
app.args = Some(args.clone());
if args.yolo {
app.note("--yolo: sandbox disabled, all tool calls auto-approved without prompting");
@@ -2040,6 +2159,14 @@ async fn chat_loop<B: Backend>(
}
}
+ // A turn finished under an active goal: run the (stateless) evaluator
+ // before anything else. It either auto-submits the next turn (setting
+ // want_start) or hands control back. Gated on an idle, run-free state so
+ // it never races an in-flight turn.
+ if app.goal_eval_pending && current.is_none() && !app.want_start {
+ app.run_goal_evaluation().await;
+ }
+
// Kick off a queued run once the previous one has cleared, the local
// model (if any) is loaded, and the base snapshot (if any) is captured.
// `submit_user` already flipped status to Running and reset the counter.
@@ -2509,6 +2636,11 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
hint: "",
description: "Summarize older turns to free up context",
},
+ SlashCommand {
+ name: "/goal",
+ hint: "[condition|clear]",
+ description: "Keep working until a condition is met (bare: status)",
+ },
SlashCommand {
name: "/threads",
hint: "",
@@ -2626,6 +2758,7 @@ async fn run_command(app: &mut App, line: &str) {
}
"mcp" => open_mcp_picker(app),
"config" => open_config_screen(app),
+ "goal" => goal_command(app, arg),
"quit" | "exit" => app.should_quit = true,
other => app.note(&format!("unknown command '/{other}' (try /help)")),
}
@@ -2651,6 +2784,98 @@ async fn compact_command(app: &mut App) {
}
}
+/// `/goal` dispatcher: `clear` removes an active goal, a bare command shows
+/// status, and any other argument sets a new goal and starts a turn toward it.
+/// Runs only while idle (the caller gates on `Status::Idle`).
+fn goal_command(app: &mut App, arg: &str) {
+ let arg = arg.trim();
+ match arg {
+ "clear" => {
+ if app.goal.take().is_some() {
+ app.goal_eval_pending = false;
+ app.persist();
+ app.note("goal cleared");
+ } else {
+ app.note("no active goal");
+ }
+ }
+ "" => show_goal_status(app),
+ condition => set_goal(app, condition),
+ }
+}
+
+/// Print the active goal's condition, turn count, duration, and the evaluator's
+/// latest reason. Notes when there is no goal.
+fn show_goal_status(app: &mut App) {
+ use crate::core::agent::goal::GoalStatus;
+ let Some(goal) = app.goal.clone() else {
+ app.note("no active goal (set one with /goal <condition>)");
+ return;
+ };
+ let state = match goal.status {
+ GoalStatus::Active => "active",
+ GoalStatus::Achieved => "achieved",
+ };
+ app.gap(Kind::Meta);
+ app.push(Line::styled(
+ format!("◎ goal [{state}]"),
+ Style::new().cyan().bold(),
+ ));
+ app.push(Line::styled(
+ format!(" condition: {}", goal.condition),
+ Style::new().dim(),
+ ));
+ app.push(Line::styled(
+ format!(
+ " turns: {} duration: {}",
+ goal.turns,
+ fmt_duration(goal.elapsed_secs())
+ ),
+ Style::new().dim(),
+ ));
+ let reason = if goal.last_reason.is_empty() {
+ "(not evaluated yet)"
+ } else {
+ &goal.last_reason
+ };
+ app.push(Line::styled(
+ format!(" evaluator: {reason}"),
+ Style::new().dim(),
+ ));
+}
+
+/// Set a new goal from `condition` and immediately start a turn toward it (the
+/// condition is the first prompt). Replaces any existing goal.
+fn set_goal(app: &mut App, condition: &str) {
+ use crate::core::agent::goal::GoalState;
+ if app.status != Status::Idle {
+ app.note("cannot set a goal while a turn is running");
+ return;
+ }
+ let goal = GoalState::new(condition);
+ let cond = goal.condition.clone();
+ app.goal = Some(goal);
+ app.goal_eval_pending = false;
+ app.note(&format!("◎ goal set: {cond}"));
+ // Start the first turn with the condition as the prompt; on_done triggers
+ // the evaluator, which drives the loop from there.
+ app.submit_user(cond);
+}
+
+/// Format a duration in whole seconds as `Nh Nm Ns` / `Nm Ns` / `Ns`.
+fn fmt_duration(secs: u64) -> String {
+ let h = secs / 3600;
+ let m = (secs % 3600) / 60;
+ let s = secs % 60;
+ if h > 0 {
+ format!("{h}h {m}m {s}s")
+ } else if m > 0 {
+ format!("{m}m {s}s")
+ } else {
+ format!("{s}s")
+ }
+}
+
/// Display name for a saved thread: its summarized `title` when present, else a
/// snippet of the last user message (so untitled threads still show content),
/// else `(untitled)`.
@@ -2878,6 +3103,23 @@ fn restore_snapshots(app: &mut App, metadata: Option<&serde_json::Value>) {
app.base_requested = true;
}
+/// Reload an active `/goal` for a resumed thread from its persisted metadata.
+/// An old thread with no goal (or a malformed one) simply clears the goal.
+fn restore_goal(app: &mut App, metadata: Option<&serde_json::Value>) {
+ app.goal = None;
+ app.goal_eval_pending = false;
+ let Some(meta) = metadata else { return };
+ if let Some(goal) = meta
+ .get("goal")
+ .and_then(|v| serde_json::from_value::<crate::core::agent::goal::GoalState>(v.clone()).ok())
+ {
+ if goal.is_active() {
+ app.note(&format!("resumed active goal: {}", goal.condition));
+ }
+ app.goal = Some(goal);
+ }
+}
+
/// Open the double-Esc rewind picker listing the conversation's user messages.
fn open_rewind_picker(app: &mut App) {
let mut items = Vec::new();
@@ -3053,6 +3295,7 @@ fn resume_thread(app: &mut App, id_arg: &str) {
app.tokens = 0;
app.scrollback = 0;
restore_snapshots(app, thread.get("metadata"));
+ restore_goal(app, thread.get("metadata"));
// Adopt the thread's model so continuation stays coherent.
if let Some(model) = thread
@@ -3671,15 +3914,29 @@ fn header(app: &App) -> Paragraph<'static> {
.run_started
.map(|t| format!(" {}", format_elapsed(t.elapsed().as_secs())))
.unwrap_or_default();
- Paragraph::new(Line::from(vec![
+ let mut spans = vec![
Span::styled(" jan agent ", Style::new().on_blue().white().bold()),
Span::raw(format!(" {} ", app.model)),
Span::styled(dir.to_string(), Style::new().dark_gray()),
Span::raw(format!(" {turn}tokens {}", app.tokens)),
Span::styled(elapsed, Style::new().dim()),
- Span::raw(" "),
- Span::styled(format!("[{status}]"), style),
- ]))
+ ];
+ // Active-goal indicator: `◎ /goal active <duration>` (cyan while running,
+ // green once achieved), so an unattended run shows the goal is still live.
+ if let Some(goal) = app.goal.as_ref() {
+ use crate::core::agent::goal::GoalStatus;
+ let (label, gstyle) = match goal.status {
+ GoalStatus::Active => (
+ format!(" ◎ /goal active {}", fmt_duration(goal.elapsed_secs())),
+ Style::new().cyan().bold(),
+ ),
+ GoalStatus::Achieved => (" ◎ /goal done".to_string(), Style::new().green()),
+ };
+ spans.push(Span::styled(label, gstyle));
+ }
+ spans.push(Span::raw(" "));
+ spans.push(Span::styled(format!("[{status}]"), style));
+ Paragraph::new(Line::from(spans))
}
/// Max content rows the input box grows to before it scrolls internally.
@@ -3853,10 +4110,10 @@ mod tests {
build_user_message, clipboard_path, diff_lines, group_activity, group_detail_lines,
group_summary, handle_key, handle_mouse, image_mime, input_content_lines, is_table_separator, load_image_file,
message_text, open_config_screen, parse_command, render_table, run_command,
- running_group_row, split_reasoning, subagent_activity, subagent_name_from_run_id,
- summarize_result, tool_activity, tool_finished, transcript_top_padding,
- user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind, SnapshotJob,
- DIFF_MAX_ROWS, SLASH_COMMANDS, SPINNER,
+ restore_goal, running_group_row, split_reasoning, subagent_activity,
+ subagent_name_from_run_id, summarize_result, tool_activity, tool_finished,
+ transcript_top_padding, user_content_parts, App, CurrentRun, Pending, PendingImage,
+ PickerKind, SnapshotJob, Status, DIFF_MAX_ROWS, SLASH_COMMANDS, SPINNER,
};
use ratatui::crossterm::event::{
KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
@@ -5841,6 +6098,134 @@ mod tests {
assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/compact"));
}
+ #[test]
+ fn goal_is_a_registered_command() {
+ assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/goal"));
+ }
+
+ #[tokio::test]
+ async fn goal_set_stores_condition_and_starts_a_turn() {
+ let mut app = test_app();
+ run_command(&mut app, "goal all tests in test/auth pass").await;
+ let goal = app.goal.as_ref().expect("goal should be set");
+ assert_eq!(goal.condition, "all tests in test/auth pass");
+ assert!(goal.is_active());
+ // Setting a goal starts the first turn with the condition as the prompt.
+ assert!(app.want_start, "a turn should be queued");
+ assert_eq!(app.status, Status::Running);
+ let last = app.history.last().expect("history has the condition prompt");
+ assert_eq!(
+ last.get("content").and_then(|c| c.as_str()),
+ Some("all tests in test/auth pass")
+ );
+ }
+
+ #[tokio::test]
+ async fn goal_clear_removes_active_goal() {
+ let mut app = test_app();
+ app.goal = Some(crate::core::agent::goal::GoalState::new("x"));
+ run_command(&mut app, "goal clear").await;
+ assert!(app.goal.is_none());
+ let text: String = app.transcript.iter().map(line_text).collect();
+ assert!(text.contains("goal cleared"), "missing note: {text}");
+ }
+
+ #[tokio::test]
+ async fn goal_clear_with_no_goal_notes() {
+ let mut app = test_app();
+ run_command(&mut app, "goal clear").await;
+ assert!(app.goal.is_none());
+ let text: String = app.transcript.iter().map(line_text).collect();
+ assert!(text.contains("no active goal"), "missing note: {text}");
+ }
+
+ #[tokio::test]
+ async fn goal_status_reports_active_goal() {
+ let mut app = test_app();
+ let mut goal = crate::core::agent::goal::GoalState::new("make git status clean");
+ goal.turns = 3;
+ goal.last_reason = "two files still modified".into();
+ app.goal = Some(goal);
+ run_command(&mut app, "goal").await;
+ let text: String = app.transcript.iter().map(line_text).collect();
+ assert!(text.contains("make git status clean"), "condition: {text}");
+ assert!(text.contains("turns: 3"), "turn count: {text}");
+ assert!(text.contains("two files still modified"), "reason: {text}");
+ }
+
+ #[tokio::test]
+ async fn goal_status_with_no_goal_notes() {
+ let mut app = test_app();
+ run_command(&mut app, "goal").await;
+ let text: String = app.transcript.iter().map(line_text).collect();
+ assert!(text.contains("no active goal"), "missing note: {text}");
+ }
+
+ #[test]
+ fn on_done_counts_turn_and_queues_eval_under_active_goal() {
+ let mut app = test_app();
+ app.goal = Some(crate::core::agent::goal::GoalState::new("cond"));
+ app.status = Status::Running;
+ app.apply(StreamEvent::Token {
+ text: "did some work".into(),
+ });
+ app.on_done("stop".into(), None);
+ assert_eq!(app.goal.as_ref().unwrap().turns, 1);
+ assert!(app.goal_eval_pending, "evaluation should be queued");
+ }
+
+ #[test]
+ fn on_done_without_goal_does_not_queue_eval() {
+ let mut app = test_app();
+ app.status = Status::Running;
+ app.apply(StreamEvent::Token { text: "done".into() });
+ app.on_done("stop".into(), None);
+ assert!(!app.goal_eval_pending);
+ }
+
+ #[test]
+ fn on_done_early_finish_does_not_queue_goal_eval() {
+ // An early/truncated finish under a goal counts the turn but leaves
+ // control with the user rather than auto-continuing.
+ let mut app = test_app();
+ app.goal = Some(crate::core::agent::goal::GoalState::new("cond"));
+ app.status = Status::Running;
+ app.apply(StreamEvent::Token { text: "partial".into() });
+ app.on_done("length".into(), None);
+ assert_eq!(app.goal.as_ref().unwrap().turns, 1);
+ assert!(!app.goal_eval_pending, "early finish should not auto-continue");
+ }
+
+ #[test]
+ fn cancel_run_stops_goal_eval_but_keeps_goal() {
+ let mut app = test_app();
+ app.goal = Some(crate::core::agent::goal::GoalState::new("cond"));
+ app.goal_eval_pending = true;
+ app.status = Status::Running;
+ app.cancel_run();
+ assert!(!app.goal_eval_pending, "cancel stops the loop");
+ assert!(app.goal.is_some(), "the goal itself is kept for inspection");
+ }
+
+ #[test]
+ fn goal_persists_and_restores_via_thread_metadata() {
+ let mut app = test_app();
+ let mut goal = crate::core::agent::goal::GoalState::new("tests pass");
+ goal.turns = 2;
+ goal.last_reason = "one failing".into();
+ app.goal = Some(goal);
+ let meta = app.thread_metadata().expect("metadata present with a goal");
+ assert!(meta.get("goal").is_some());
+
+ let mut restored = test_app();
+ restore_goal(&mut restored, Some(&meta));
+ let g = restored.goal.expect("goal restored");
+ assert_eq!(g.condition, "tests pass");
+ assert_eq!(g.turns, 2);
+ assert_eq!(g.last_reason, "one failing");
+ assert!(g.is_active());
+ }
+
#[tokio::test]
async fn new_command_resets_session() {
let mut app = test_app();