Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ Cyber Code has working features in each area below, but it is not at full featur
Other limits to consider:

- **Acceptance is ongoing:** the full local-model baseline, Windows enforcement and several P1 migration, memory and code-intelligence paths remain open.
- **Automation has edges:** [reserved budgets](docs/reserved-budgets.md) currently support bounded official OpenAI Responses requests; ChatGPT/Copilot subscription models use soft token/time controls. Finished-agent transcript retention and persistent scheduling are separate roadmap items; agent teams and the project hub are experimental.
- **Automation has edges:** [reserved budgets](docs/reserved-budgets.md) currently support bounded official OpenAI Responses requests; ChatGPT/Copilot subscription models use soft token/time controls. Finished-agent transcript retention is a separate roadmap item; persistent schedules (`cyber loops`) run only while the Cyber service runs, which has no launchd/systemd unit yet; agent teams and the project hub are experimental.
- **The native Gemini adapter is experimental:** off until `features.gemini` is set; tested against recorded protocol shapes only. A live tool-loop run with a key, the live coding baseline, Vertex AI and stored Gemini keys (`cyber providers login google`) remain.
- **Native computer use is experimental:** macOS 14+ only, off by default; controlled capture, input and Stop passed. Other layouts, live OS revocation and release signing remain unverified.
- **Remote access is private:** physical-device certificate trust is an operator check. Relay, paired Devices and mobile apps remain roadmap work.
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ The [current inventory](docs/implementation/spec-doc-reconciliation.md) contains
1. **M2.1 Workflow runtime:** QuickJS sandbox, `agent()/parallel()/pipeline()/phase()`, determinism guards, event-sourced resume, budgets, model tiers (`fast` / `smart` / `verify`). *Status: implemented and accepted end to end with the real binary and a scripted local provider, including the gaps (`ask()`, direct read-only tools, prompt-cache warm-up, `exec --workflow`, `/tasks`, the Workflow library over HTTP, Save); reserved budgets are implemented for bounded official OpenAI Responses requests ([limits and owner reconciliation](docs/reserved-budgets.md)); finished-transcript retention remains (Session export includes run summaries); see [P2 evidence](docs/implementation/p2-status.md).*
2. **M2.2 Verified workflow library:** *Status: the five original bundled Workflows and the `solve` candidate/check/judge protocol are implemented; solve has scripted real-binary acceptance and green platform CI in PR #23.* The bundled review, audit (find → verify), migrate (fan-out with worktrees), research (cross-checked) and plan-from-angles ship in the binary (change `implement-m2-2-bundled-workflows`) with library listing, `show`/`eject`, args validation, host preparation, `/review` and `cyber review` routed to `review`, and the `/workflows` Library tab; each runs end to end on the real binary against a scripted model (`crates/cyber-cli/tests/bundled_workflows.rs`). Open: TUI pty/PNG captures, a live-model run and the archive; see [P2 evidence](docs/implementation/p2-status.md#m22-bundled-workflows-2026-10-22). The `solve` workflow adds 2–4 independent model attempts in worktrees → host-run checks tied to exact source revisions → an independent judge → an evidence report and optional recommendation; no automatic merge. Default soft budget: 5 USD / 30 minutes. See [solve acceptance](docs/measurements/verified-solve-acceptance.md) and the [archived change](openspec/changes/archive/2026-10-23-add-verified-solve-workflow/proposal.md).
3. **M2.3 Goals:** active goal + goal queue, evaluator verdicts, `check` commands, budgets, `exec --goal` exit codes. **Status: implemented** (change `implement-m2-3-goals`): `/goal` with queue, pause/resume/skip/clear/edit and reorder, the evaluator after each Turn with continuation and completion, checks, budgets, blocking-error pauses, deferred evaluation during background work, restore after restart, `core/goal` context, notifications, hooks, HTTP routes, the TUI panel, footer and sidebar, `exec --goal`, templates, `/goal fork` into a worktree Session, goals on subagents and workflow `agent()`, the model `goal` tool and unattended-ask pauses. The live end-to-end acceptance on the real binary remains.
4. **M2.4 Loops & cron:** `/loop` fixed and self-paced, in-session cron, daemon-backed persistent loops. **Status: Session loops implemented** (change `implement-m2-4-loops`): fixed-interval and self-paced `/loop` with `schedule_wakeup`, queued delivery with overlap skip/coalesce, noop collapsing, `--max`/`--for`/`--until`/budget stops, restore after restart, HTTP routes and the TUI. In-session cron tools, persistent `cyber loops` schedules, jitter, notifications, loop hooks and `--until-goal` remain.
4. **M2.4 Loops & cron:** `/loop` fixed and self-paced, in-session cron, daemon-backed persistent loops. **Status: implemented** (changes `implement-m2-4-loops`, `implement-m2-4-schedules`): fixed-interval and self-paced `/loop` with `schedule_wakeup`, queued delivery with overlap skip/coalesce, noop collapsing, `--max`/`--for`/`--until`/`--until-goal`/budget stops, restore after restart with the missed-run policy, the model's `cron_create`/`cron_list`/`cron_delete` tasks, loop notifications (`--notify`), the `LoopIteration` hook, HTTP routes and the TUI; persistent `cyber loops add|list|show|pause|resume|run|rm` schedules run by the service with no client open, in `dont-ask` by default (`bypass` only with `loops.allow_bypass` from user or managed config), only in trusted directories, with deterministic jitter, Session and desktop notifications, budgets across runs, `schedule.run.1` and the `ScheduleRun` hook. Live runs against a real model, a launchd/systemd unit for the service and `cyber loops promote` (P3) remain.
5. **M2.5 Agent view & teams:** `cyber agents` dashboard; experimental lead/teammates with a shared task list. **Status: agent teams implemented, behind the experimental `teams` feature** (change `implement-agent-teams`, sections 1–9): definitions, spawning with worktree isolation and the lead's Mode ceiling and deny rules, the shared task board with dependencies and atomic claims, team messaging and idle notices, file ownership, `team_merge` that leaves the lead's checkout unchanged on conflicts, team budgets, stop/resume with restart recovery, HTTP/SDK/CLI and the TUI team view; accepted by hand on 2026-10-20 with the real binary and a scripted local provider (15 scenarios, [evidence](docs/implementation/p2-status.md#agent-teams-2026-10-20)). The `cyber agents` dashboard (agent view), an automated end-to-end suite, Windows runs and the archive remain; distributed teammates are P3.

**Direct peers (`cross-session-messaging`, P2, not owned by an M2.x milestone): Status: implemented** (change `add-messaging-direct-peers`; [guide](docs/peers.md)). Pairing with pinned TLS fingerprints and hashed grant tokens, `name@machine` sends held on the receiver, polled outcomes, listing and watches, revocation, `cyber attach <session>@<peer>` and opt-in mDNS discovery have production-path tests and were accepted by hand on 2026-10-19 with two real servers on one macOS host. Open: OS keyring evidence (mocked with `--token-env`), two-way pairing with a reply, the SSH-tunnel flow, a two-host run, Linux and Windows CI on this work, and the archive; see [P2 evidence](docs/implementation/p2-status.md#cross-session-messaging-direct-peers-2026-10-19).
Expand Down
91 changes: 91 additions & 0 deletions crates/cyber-app/src/desktop_notifier.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! The OS desktop notifier of scheduled runs (`loops-scheduling` → Completion
//! notifications): a scheduled run usually has no client attached to show its
//! notification, so the service shows it. macOS uses `osascript`, Linux `notify-send`;
//! other platforms have none. Title and body are passed as arguments, never inlined in a
//! script or a shell command line. Best effort: a missing tool or a failure is ignored,
//! and a notifier that hangs is killed after a few seconds.

use std::process::Stdio;
use std::time::Duration;

use cyber_server::runtime::schedules::DesktopNotifier;

/// How long a notifier process may run.
const TIMEOUT: Duration = Duration::from_secs(5);
/// Longest title and body passed on.
const MAX_TITLE: usize = 120;
const MAX_BODY: usize = 400;

pub struct OsNotifier;

/// The program and arguments that show `title` and `body`, or `None` on a platform
/// without a notifier.
pub fn command(title: &str, body: &str) -> Option<(&'static str, Vec<String>)> {
let title: String = title.chars().take(MAX_TITLE).collect();
let body: String = body.chars().take(MAX_BODY).collect();
if cfg!(target_os = "macos") {
// The text arrives as `argv`, so no quoting can turn it into AppleScript.
let script = [
"-e",
"on run argv",
"-e",
"display notification (item 2 of argv) with title (item 1 of argv)",
"-e",
"end run",
];
let mut args: Vec<String> = script.iter().map(|s| (*s).to_owned()).collect();
args.extend([title, body]);
return Some(("osascript", args));
}
if cfg!(target_os = "linux") {
return Some(("notify-send", vec!["--".into(), title, body]));
}
None
}

impl DesktopNotifier for OsNotifier {
fn notify(&self, title: &str, body: &str) {
let Some((program, args)) = command(title, body) else {
return;
};
let Ok(handle) = tokio::runtime::Handle::try_current() else {
return;
};
handle.spawn(async move {
let child = tokio::process::Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn();
if let Ok(mut child) = child {
let _ = tokio::time::timeout(TIMEOUT, child.wait()).await;
}
});
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn text_is_passed_as_arguments_only() {
let hostile = "\" & do shell script \"touch /tmp/x\" & \"";
let Some((program, args)) = command("Schedule nightly", hostile) else {
return;
};
assert!(matches!(program, "osascript" | "notify-send"));
assert_eq!(args.last().map(String::as_str), Some(hostile));
assert!(
args.iter()
.filter(|a| a.as_str() != hostile)
.all(|a| !a.contains("touch")),
"{args:?}"
);
let long = "x".repeat(1000);
let (_, args) = command(&long, &long).unwrap();
assert!(args.iter().all(|a| a.chars().count() <= MAX_BODY));
}
}
7 changes: 7 additions & 0 deletions crates/cyber-app/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@ impl ToolHost for AppHost {
self.builtin.loop_settings(directory)
}

fn schedule_policy(
&self,
directory: &str,
) -> Result<cyber_server::runtime::schedules::SchedulePolicy, String> {
self.builtin.schedule_policy(directory)
}

fn check(
&self,
directory: &str,
Expand Down
28 changes: 24 additions & 4 deletions crates/cyber-app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
pub mod account;
pub mod backup;
pub mod collaboration;
pub mod desktop_notifier;
pub mod git_text;
mod host;
pub mod peer_discovery;
Expand Down Expand Up @@ -208,6 +209,28 @@ fn peer_names(global: Arc<services::GlobalConfigFn>) -> Arc<host::PeerNames> {
Arc::new(move || peer_tokens::enabled_names(&global()?))
}

/// Session loops: end iterations a stopped server cut off, apply the missed-run policy,
/// then admit due iterations every 5 s (`loops-scheduling`). Persistent schedules run only
/// in the service (`loops-scheduling` → Persistent local schedules): end runs a stopped
/// service cut off, apply the missed-run policy, then start due runs every 5 s, notifying
/// on the desktop.
async fn recover_loops_and_schedules(
runtime: &cyber_server::runtime::Runtime,
served: bool,
) -> Result<(), String> {
runtime.recover_loops().await.map_err(|e| e.to_string())?;
runtime.spawn_loop_sweep();
if served {
runtime.set_desktop_notifier(Arc::new(desktop_notifier::OsNotifier));
runtime
.recover_schedules()
.await
.map_err(|e| e.to_string())?;
runtime.spawn_schedule_sweep();
}
Ok(())
}

pub fn config_loader(paths: Paths, home: PathBuf) -> Arc<ConfigFn> {
let resolved = hook_config_loader(paths, home);
Arc::new(move |location| resolved(location).map(|resolved| (resolved.value, resolved.sources)))
Expand Down Expand Up @@ -450,10 +473,7 @@ impl App {
// teams a restart left stopping finish stopping (`agent-teams` → Idle
// notifications, Shutdown and resume).
runtime.recover_teams().await.map_err(|e| e.to_string())?;
// Session loops: end iterations a stopped server cut off, apply the missed-run
// policy, then admit due iterations every 5 s (`loops-scheduling`).
runtime.recover_loops().await.map_err(|e| e.to_string())?;
runtime.spawn_loop_sweep();
recover_loops_and_schedules(&runtime, served).await?;
// Outcomes of messages held on peers, polled from the times the store keeps, so
// polling resumes after a restart (`cross-session-messaging` → Peer outcome
// tracking).
Expand Down
102 changes: 102 additions & 0 deletions crates/cyber-app/tests/loops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,105 @@ async fn until_runs_a_real_check_through_the_app_host() {
assert_eq!(ended["status"], "until_met", "{ended}");
assert_eq!(ended["iterations"], 0);
}

/// `loops-scheduling` → In-session cron tools: the real tools, offered to a root
/// Session; `cron_delete` cannot reach a `/loop` the user started.
#[tokio::test]
async fn the_model_manages_scheduled_tasks_with_the_cron_tools() {
let app = ModeApp::start(Setup::default()).await;
let id = session(&app).await;
let at = (chrono::Utc::now() + chrono::Duration::hours(2)).to_rfc3339();
app.run(
&id,
&format!(r#"TOOL<<cron_create>>{{"at": "{at}", "prompt": "summarize overnight CI"}}"#),
)
.await;
let outputs = app.outputs(&id).await;
let created: Value = serde_json::from_str(&outputs[0]).unwrap_or(Value::Null);
let task_id = created["id"]
.as_str()
.unwrap_or_else(|| panic!("{outputs:?}"))
.to_owned();
assert!(task_id.starts_with("cron_"), "{created}");
assert!(created["next_run"].is_string(), "{created}");
let requests = app.model.requests();
let turn = requests.iter().find(|r| !offered(r).is_empty()).unwrap();
for tool in ["cron_create", "cron_list", "cron_delete"] {
assert!(offered(turn).contains(&tool.to_string()), "{tool}");
}

let (_, listed) = app
.send("GET", &format!("/sessions/{id}/loops"), None)
.await;
let task = &listed["data"][0];
assert_eq!(
(task["kind"].as_str(), task["loop_id"].as_str()),
(Some("cron"), Some(task_id.as_str()))
);
assert!(task["at_ms"].is_i64(), "{task}");

// A `/loop` of the user (here one whose check already passed) is not a task.
let user_loop = create(&app, &id, r#"1h --until "test -d .git" check the deploy"#).await;
let loop_id = user_loop["loop_id"].as_str().unwrap().to_owned();
app.run(&id, &format!(r#"TOOL<<cron_delete>>{{"id": "{loop_id}"}}"#))
.await;
assert_output(&app, &id, &format!("Unknown scheduled task {loop_id}")).await;
app.run(&id, "TOOL<<cron_list>>{}").await;
assert_output(&app, &id, "\"tasks\":[{\"id\":\"cron_").await;
app.run(&id, &format!(r#"TOOL<<cron_delete>>{{"id": "{task_id}"}}"#))
.await;
let ended = wait_loop(&app, &id, &task_id, |l| l["status"] != "active").await;
assert_eq!(ended["status"], "stopped");
}

/// `loops-scheduling` → Loop events and hooks: `LoopIteration` receives the loop and the
/// iteration on stdin after `loop.iteration.ended.1` commits.
#[tokio::test]
async fn loop_iteration_hook_receives_the_iteration() {
let app = ModeApp::start(Setup {
config: json!({"hooks": {"LoopIteration": [{"hooks": [
{"type": "command", "command": "cat > iteration.json"}]}]}}),
..Setup::default()
})
.await;
let id = session(&app).await;
let created = create(&app, &id, "5m --max 1 check the deploy").await;
let loop_id = created["loop_id"].as_str().unwrap();
wait_loop(&app, &id, loop_id, |l| l["status"] != "active").await;
let path = app.repo.join("iteration.json");
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
let written = loop {
if let Ok(text) = std::fs::read_to_string(&path)
&& let Ok(value) = serde_json::from_str::<Value>(&text)
{
break value;
}
assert!(tokio::time::Instant::now() < deadline, "the hook never ran");
tokio::time::sleep(Duration::from_millis(50)).await;
};
assert_eq!(
written["hook_event_name"]
.as_str()
.or(written["event"].as_str()),
Some("LoopIteration"),
"{written}"
);
assert_eq!(written["loop"]["loop_id"], loop_id, "{written}");
assert_eq!(written["iteration"]["n"], 1);
assert_eq!(written["iteration"]["outcome"], "completed");
assert_eq!(written["iteration"]["noop"], false);
let kinds: Vec<String> = app.events(&id).into_iter().map(|e| e.kind).collect();
assert!(
kinds.iter().any(|k| k == "loop.iteration.ended.1"),
"{kinds:?}"
);
}

/// Some settled call of the Session returned output containing `needle`.
async fn assert_output(app: &ModeApp, id: &str, needle: &str) {
let outputs = app.outputs(id).await;
assert!(
outputs.iter().any(|o| o.contains(needle)),
"{needle}: {outputs:?}"
);
}
Loading
Loading