CI: remove k8s stages, fix the Docker-level pipeline green
Survey + fixes so the pipeline passes at the Docker level (no k8s).
- Remove k8s: drop the `sandbox-k8s` job (kind/Calico/--features k8s-tests) and the
"Helm chart lints" gate step. release.yml was already k8s-clean.
- Rust job:
- `cargo fmt --all` — fix pre-existing formatting drift (fmt --check was failing).
- clippy -D warnings: fix 3 lib warnings (cm-brain sort_by_key→Reverse, cm-api
fleet.rs doc list indentation, node_rules map_or→is_none_or).
- Regenerate the .sqlx offline cache (was missing the cm-runtime run_loop test
query → offline compile failed). DB-backed tests use testcontainers at runtime.
- Set SQLX_OFFLINE=true on the rust + e2e jobs so query! macros compile against
the committed cache deterministically (no DB needed at compile time).
- Frontend job:
- Fix the 1 ESLint error (useAgentTelemetry: no setState-synchronously-in-effect;
tag the slice with agentId + derive null on mismatch).
- Fix 2 stale panel-params tests (`terminal` is a valid app id now; assert the
current APP_IDS + use a genuinely-unknown id for the reject case).
Verified locally: fmt clean, clippy --all-targets -D warnings clean (offline),
frontend lint 0 errors, tsc clean, 86/86 frontend tests pass, build OK.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
a36b2c87ac
commit
3554a3aaf2
@@ -34,12 +34,23 @@ pub async fn connect(
|
||||
json!({ "ok": false, "error": "hubUrl, username and password are required" }),
|
||||
));
|
||||
}
|
||||
let conn = BeszelConn { hub_url: hub.clone(), username: username.clone(), password: req.password.clone() };
|
||||
let conn = BeszelConn {
|
||||
hub_url: hub.clone(),
|
||||
username: username.clone(),
|
||||
password: req.password.clone(),
|
||||
};
|
||||
// Verify the credentials authenticate before persisting.
|
||||
if let Err(e) = beszel::authenticate(&reqwest::Client::new(), &conn).await {
|
||||
return Ok(Json(json!({ "ok": false, "error": e })));
|
||||
}
|
||||
fleet_beszel::set(&state.pool, user.workspace_id, &hub, &username, &req.password).await?;
|
||||
fleet_beszel::set(
|
||||
&state.pool,
|
||||
user.workspace_id,
|
||||
&hub,
|
||||
&username,
|
||||
&req.password,
|
||||
)
|
||||
.await?;
|
||||
Ok(Json(json!({ "ok": true, "hubUrl": hub })))
|
||||
}
|
||||
|
||||
@@ -49,7 +60,9 @@ pub async fn status(
|
||||
Authed(user): Authed,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let conn = fleet_beszel::get(&state.pool, user.workspace_id).await?;
|
||||
Ok(Json(json!({ "connected": conn.is_some(), "hubUrl": conn.map(|c| c.hub_url) })))
|
||||
Ok(Json(
|
||||
json!({ "connected": conn.is_some(), "hubUrl": conn.map(|c| c.hub_url) }),
|
||||
))
|
||||
}
|
||||
|
||||
/// `DELETE /api/fleet/beszel` — disconnect.
|
||||
@@ -74,9 +87,10 @@ pub async fn node_metrics_get(
|
||||
.ok_or(ApiError::NotFound)?;
|
||||
let latest = node_metrics::latest(&state.pool, node_id).await?;
|
||||
let mut history = json!([]);
|
||||
if let (Some(latest_v), Some(conn)) =
|
||||
(&latest, fleet_beszel::get(&state.pool, user.workspace_id).await?)
|
||||
{
|
||||
if let (Some(latest_v), Some(conn)) = (
|
||||
&latest,
|
||||
fleet_beszel::get(&state.pool, user.workspace_id).await?,
|
||||
) {
|
||||
if let Some(sysid) = latest_v.get("beszelSystemId").and_then(Value::as_str) {
|
||||
let client = reqwest::Client::new();
|
||||
if let Ok(token) = beszel::authenticate(&client, &conn).await {
|
||||
@@ -91,7 +105,9 @@ pub async fn node_metrics_get(
|
||||
|
||||
// ── Fleet automation rules ──────────────────────────────────────────────────
|
||||
|
||||
const METRICS: [&str; 6] = ["cpu_pct", "mem_pct", "disk_pct", "gpu_pct", "temp_max", "load1"];
|
||||
const METRICS: [&str; 6] = [
|
||||
"cpu_pct", "mem_pct", "disk_pct", "gpu_pct", "temp_max", "load1",
|
||||
];
|
||||
const OPS: [&str; 4] = [">", "<", ">=", "<="];
|
||||
|
||||
fn rule_json(r: &node_rules::NodeRule) -> Value {
|
||||
@@ -115,7 +131,9 @@ pub async fn rules_list(
|
||||
Authed(user): Authed,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let rules = node_rules::list(&state.pool, user.workspace_id).await?;
|
||||
Ok(Json(json!({ "rules": rules.iter().map(rule_json).collect::<Vec<_>>() })))
|
||||
Ok(Json(
|
||||
json!({ "rules": rules.iter().map(rule_json).collect::<Vec<_>>() }),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -138,7 +156,9 @@ pub async fn rules_create(
|
||||
Json(req): Json<RuleReq>,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
if !METRICS.contains(&req.metric.as_str()) || !OPS.contains(&req.op.as_str()) {
|
||||
return Ok(Json(json!({ "ok": false, "error": "invalid metric or operator" })));
|
||||
return Ok(Json(
|
||||
json!({ "ok": false, "error": "invalid metric or operator" }),
|
||||
));
|
||||
}
|
||||
let node_id = match req.node_id.as_deref() {
|
||||
Some(s) if !s.is_empty() && s != "all" => {
|
||||
|
||||
@@ -2,11 +2,11 @@ use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use axum::Json;
|
||||
use std::convert::Infallible;
|
||||
use cm_db::repo::audit::Actor;
|
||||
use cm_domain::{AccessPolicy, Agent, AgentId, AgentStatus};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::convert::Infallible;
|
||||
|
||||
use crate::runtime_provision::provider_alias_for;
|
||||
use crate::{ApiError, AppState, Authed};
|
||||
@@ -241,7 +241,14 @@ pub async fn edit_brain(
|
||||
// system_prompt stays authoritative in Postgres.
|
||||
if let Some(sp) = req.system_prompt.as_ref() {
|
||||
let _ = cm_db::repo::agents::update_profile(
|
||||
&state.pool, agent.id, None, None, Some(sp.trim()), None, None, None,
|
||||
&state.pool,
|
||||
agent.id,
|
||||
None,
|
||||
None,
|
||||
Some(sp.trim()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -292,7 +299,10 @@ pub struct EnhanceRequest {
|
||||
/// fences, and trailing commentary (balanced-brace scan from the first `{`).
|
||||
pub(crate) fn extract_json(s: &str) -> Option<Value> {
|
||||
let t = s.trim();
|
||||
let t = t.strip_prefix("```json").or_else(|| t.strip_prefix("```")).unwrap_or(t);
|
||||
let t = t
|
||||
.strip_prefix("```json")
|
||||
.or_else(|| t.strip_prefix("```"))
|
||||
.unwrap_or(t);
|
||||
let t = t.strip_suffix("```").unwrap_or(t).trim();
|
||||
if let Ok(v) = serde_json::from_str::<Value>(t) {
|
||||
return Some(v);
|
||||
@@ -448,54 +458,110 @@ pub(crate) async fn enhance_and_publish(
|
||||
reference: &str,
|
||||
role_context: &str,
|
||||
) -> Result<String, String> {
|
||||
let safe: String = reference.chars().map(|c| if c == '/' || c == ':' { '_' } else { c }).collect();
|
||||
let safe: String = reference
|
||||
.chars()
|
||||
.map(|c| if c == '/' || c == ':' { '_' } else { c })
|
||||
.collect();
|
||||
let path = brain_dir().join(format!("scaffold_{safe}.h5"));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let pulled = cm_brain::hub::pull(reference, &path).await.map_err(|e| e.to_string())?;
|
||||
let pulled = cm_brain::hub::pull(reference, &path)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let (sp, agent_md, persona, skills) = {
|
||||
let b = cm_brain::ClawBrain::open_or_create(&path, reference).map_err(|e| e.to_string())?;
|
||||
(
|
||||
b.system_prompt().unwrap_or_default(),
|
||||
b.agent_md().unwrap_or_default(),
|
||||
b.personality().unwrap_or_default(),
|
||||
b.skills().into_iter().map(|(n, bd)| format!("## {n}\n{bd}")).collect::<Vec<_>>().join("\n\n"),
|
||||
b.skills()
|
||||
.into_iter()
|
||||
.map(|(n, bd)| format!("## {n}\n{bd}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n"),
|
||||
)
|
||||
};
|
||||
let user_prompt = format!(
|
||||
"ROLE CONTEXT: {role_context}\n\nBRAIN: {reference}\n\n=== SYSTEM PROMPT ===\n{sp}\n\n=== AGENTS.md ===\n{agent_md}\n\n=== PERSONA ===\n{persona}\n\n=== SKILLS ===\n{skills}"
|
||||
);
|
||||
let raw = runtime.complete(ENHANCE_SYSTEM, &user_prompt, "claude-opus-4-8", 16000, true).await?;
|
||||
let raw = runtime
|
||||
.complete(ENHANCE_SYSTEM, &user_prompt, "claude-opus-4-8", 16000, true)
|
||||
.await?;
|
||||
let v = extract_json(&raw).ok_or_else(|| "unparseable enhance output".to_string())?;
|
||||
let enh = v.get("enhanced").cloned().unwrap_or(Value::Null);
|
||||
let field = |k: &str| enh.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string();
|
||||
{
|
||||
let mut b = cm_brain::ClawBrain::open_or_create(&path, reference).map_err(|e| e.to_string())?;
|
||||
if !field("system_prompt").trim().is_empty() { let _ = b.set_system_prompt(&field("system_prompt")); }
|
||||
if !field("agent_md").trim().is_empty() { let _ = b.set_agent_md(&field("agent_md")); }
|
||||
if !field("persona").trim().is_empty() { let _ = b.set_personality(&field("persona")); }
|
||||
if !field("skills_md").trim().is_empty() { let _ = b.set_skills_md(&field("skills_md")); }
|
||||
}
|
||||
let owner = cm_brain::hub::whoami().await.unwrap_or_else(|_| "me".to_string());
|
||||
let on = pulled.meta.reference.rsplit_once(':').map(|(o, _)| o).unwrap_or(&pulled.meta.reference);
|
||||
let name = on.rsplit_once('/').map(|(_, n)| n.to_string()).unwrap_or_else(|| on.to_string());
|
||||
let cur_ver = pulled.meta.reference.rsplit_once(':').map(|(_, vv)| vv.to_string()).unwrap_or_else(|| "1.0.0".to_string());
|
||||
let new_ref = format!("{owner}/{name}:{}", bump_version(&cur_ver));
|
||||
let result = match cm_brain::hub::push(&new_ref, &path, "Refined by Master Planner (Opus 4.8)", &[]).await {
|
||||
Ok(()) => new_ref,
|
||||
Err(_) => reference.to_string(),
|
||||
let field = |k: &str| {
|
||||
enh.get(k)
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
};
|
||||
{
|
||||
let mut b =
|
||||
cm_brain::ClawBrain::open_or_create(&path, reference).map_err(|e| e.to_string())?;
|
||||
if !field("system_prompt").trim().is_empty() {
|
||||
let _ = b.set_system_prompt(&field("system_prompt"));
|
||||
}
|
||||
if !field("agent_md").trim().is_empty() {
|
||||
let _ = b.set_agent_md(&field("agent_md"));
|
||||
}
|
||||
if !field("persona").trim().is_empty() {
|
||||
let _ = b.set_personality(&field("persona"));
|
||||
}
|
||||
if !field("skills_md").trim().is_empty() {
|
||||
let _ = b.set_skills_md(&field("skills_md"));
|
||||
}
|
||||
}
|
||||
let owner = cm_brain::hub::whoami()
|
||||
.await
|
||||
.unwrap_or_else(|_| "me".to_string());
|
||||
let on = pulled
|
||||
.meta
|
||||
.reference
|
||||
.rsplit_once(':')
|
||||
.map(|(o, _)| o)
|
||||
.unwrap_or(&pulled.meta.reference);
|
||||
let name = on
|
||||
.rsplit_once('/')
|
||||
.map(|(_, n)| n.to_string())
|
||||
.unwrap_or_else(|| on.to_string());
|
||||
let cur_ver = pulled
|
||||
.meta
|
||||
.reference
|
||||
.rsplit_once(':')
|
||||
.map(|(_, vv)| vv.to_string())
|
||||
.unwrap_or_else(|| "1.0.0".to_string());
|
||||
let new_ref = format!("{owner}/{name}:{}", bump_version(&cur_ver));
|
||||
let result =
|
||||
match cm_brain::hub::push(&new_ref, &path, "Refined by Master Planner (Opus 4.8)", &[])
|
||||
.await
|
||||
{
|
||||
Ok(()) => new_ref,
|
||||
Err(_) => reference.to_string(),
|
||||
};
|
||||
let _ = std::fs::remove_file(&path);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Attach a brain reference to a freshly-created claw (merge + set its
|
||||
/// authoritative system prompt). Used by the Master Planner scaffold.
|
||||
pub(crate) async fn apply_reference_to_claw(state: &AppState, id: AgentId, reference: &str) -> Result<(), String> {
|
||||
pub(crate) async fn apply_reference_to_claw(
|
||||
state: &AppState,
|
||||
id: AgentId,
|
||||
reference: &str,
|
||||
) -> Result<(), String> {
|
||||
let path = brain_dir().join(format!("claw_{id}.h5"));
|
||||
let pulled = cm_brain::hub::pull_merge(reference, &path).await.map_err(|e| e.to_string())?;
|
||||
let pulled = cm_brain::hub::pull_merge(reference, &path)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !pulled.system_prompt.trim().is_empty() {
|
||||
let _ = cm_db::repo::agents::update_profile(
|
||||
&state.pool, id, None, None, Some(pulled.system_prompt.trim()), None, None, None,
|
||||
&state.pool,
|
||||
id,
|
||||
None,
|
||||
None,
|
||||
Some(pulled.system_prompt.trim()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -539,14 +605,20 @@ pub async fn pull_brain(
|
||||
let agent = Agent {
|
||||
id,
|
||||
workspace_id: user.workspace_id,
|
||||
name: body.name.filter(|s| !s.trim().is_empty()).unwrap_or(pulled.name),
|
||||
name: body
|
||||
.name
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or(pulled.name),
|
||||
job_title: body
|
||||
.job_title
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "Pulled from ClawBrainHub".into()),
|
||||
system_prompt: pulled.system_prompt,
|
||||
avatar: String::new(),
|
||||
accent: body.accent.filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "#ff6f61".into()),
|
||||
accent: body
|
||||
.accent
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| "#ff6f61".into()),
|
||||
wallpaper: String::new(),
|
||||
managed_by: user.user_id,
|
||||
status: AgentStatus::Online,
|
||||
@@ -627,7 +699,9 @@ pub async fn brainhub_search(
|
||||
Authed(_user): Authed,
|
||||
Query(query): Query<BrainSearchQuery>,
|
||||
) -> Result<Json<Vec<cm_brain::hub::BrainListing>>, ApiError> {
|
||||
Ok(Json(cm_brain::hub::list(&query.q).await.unwrap_or_default()))
|
||||
Ok(Json(
|
||||
cm_brain::hub::list(&query.q).await.unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
/// `GET /api/brainhub/preview?ref=owner/name` — overview of a brain's contents
|
||||
@@ -647,10 +721,13 @@ pub async fn brainhub_preview(
|
||||
if reference.is_empty() || !reference.contains('/') {
|
||||
return Err(ApiError::BadRequest);
|
||||
}
|
||||
cm_brain::hub::preview(reference).await.map(Json).map_err(|e| {
|
||||
eprintln!("cm-api: brain preview failed for {reference}: {e}");
|
||||
ApiError::BadRequest
|
||||
})
|
||||
cm_brain::hub::preview(reference)
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|e| {
|
||||
eprintln!("cm-api: brain preview failed for {reference}: {e}");
|
||||
ApiError::BadRequest
|
||||
})
|
||||
}
|
||||
|
||||
/// `POST /api/claws/{id}/brain/apply` — pull a brain and inject its contents
|
||||
@@ -673,10 +750,12 @@ pub async fn apply_brain(
|
||||
return Err(ApiError::BadRequest);
|
||||
}
|
||||
let path = brain_dir().join(format!("claw_{id}.h5"));
|
||||
let pulled = cm_brain::hub::pull_merge(reference, &path).await.map_err(|e| {
|
||||
eprintln!("cm-api: brain apply failed for {reference}: {e}");
|
||||
ApiError::BadRequest
|
||||
})?;
|
||||
let pulled = cm_brain::hub::pull_merge(reference, &path)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("cm-api: brain apply failed for {reference}: {e}");
|
||||
ApiError::BadRequest
|
||||
})?;
|
||||
// The assembled identity becomes the agent's authoritative system prompt
|
||||
// (safe replace — the chat path is raw‑API for every provider).
|
||||
if !pulled.system_prompt.trim().is_empty() {
|
||||
@@ -749,13 +828,25 @@ pub async fn brain_rollback(
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
workspace_agent(&state, &user, id).await?;
|
||||
let path = brain_dir().join(format!("claw_{id}.h5"));
|
||||
let b = cm_brain::ClawBrain::open_or_create(&path, &id.to_string()).map_err(|_| ApiError::Internal)?;
|
||||
b.rollback(body.revision).map_err(|_| ApiError::BadRequest)?;
|
||||
let b = cm_brain::ClawBrain::open_or_create(&path, &id.to_string())
|
||||
.map_err(|_| ApiError::Internal)?;
|
||||
b.rollback(body.revision)
|
||||
.map_err(|_| ApiError::BadRequest)?;
|
||||
// Re-open the rolled-back brain and restore its identity as the live prompt.
|
||||
if let Ok(reb) = cm_brain::ClawBrain::open_or_create(&path, &id.to_string()) {
|
||||
let sp = reb.assembled_identity();
|
||||
if !sp.trim().is_empty() {
|
||||
let _ = cm_db::repo::agents::update_profile(&state.pool, id, None, None, Some(sp.trim()), None, None, None).await;
|
||||
let _ = cm_db::repo::agents::update_profile(
|
||||
&state.pool,
|
||||
id,
|
||||
None,
|
||||
None,
|
||||
Some(sp.trim()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
cm_db::repo::audit::append(
|
||||
|
||||
@@ -136,7 +136,12 @@ pub async fn patch_company(
|
||||
.collect();
|
||||
let n = by_node.len();
|
||||
let roles: Vec<String> = (0..n)
|
||||
.map(|i| by_node.get(&format!("n{i}")).map(|(_, r)| r.clone()).unwrap_or_else(|| "team".into()))
|
||||
.map(|i| {
|
||||
by_node
|
||||
.get(&format!("n{i}"))
|
||||
.map(|(_, r)| r.clone())
|
||||
.unwrap_or_else(|| "team".into())
|
||||
})
|
||||
.collect();
|
||||
let role_refs: Vec<&str> = roles.iter().map(String::as_str).collect();
|
||||
let mut graph = build(kind, &role_refs).map_err(|_| ApiError::BadRequest)?;
|
||||
@@ -147,7 +152,14 @@ pub async fn patch_company(
|
||||
}
|
||||
}
|
||||
let graph_json = serde_json::to_value(&graph).map_err(|_| ApiError::Internal)?;
|
||||
cm_db::repo::companies::set_topology(&state.pool, company.id, user.workspace_id, kind.as_str(), &graph_json).await?;
|
||||
cm_db::repo::companies::set_topology(
|
||||
&state.pool,
|
||||
company.id,
|
||||
user.workspace_id,
|
||||
kind.as_str(),
|
||||
&graph_json,
|
||||
)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,9 @@ fn walk_files<'a>(
|
||||
};
|
||||
while let Ok(Some(entry)) = rd.next_entry().await {
|
||||
let path = entry.path();
|
||||
let Ok(ft) = entry.file_type().await else { continue };
|
||||
let Ok(ft) = entry.file_type().await else {
|
||||
continue;
|
||||
};
|
||||
if ft.is_dir() {
|
||||
walk_files(path, base.clone(), out).await;
|
||||
} else if ft.is_file() {
|
||||
@@ -54,7 +56,12 @@ async fn reconcile_drive(
|
||||
};
|
||||
let dir = root.join(format!("{ws}/{}/{scope}", drive.as_str()));
|
||||
let mut disk = HashMap::new();
|
||||
walk_files(dir, root.join(format!("{ws}/{}/{scope}", drive.as_str())), &mut disk).await;
|
||||
walk_files(
|
||||
dir,
|
||||
root.join(format!("{ws}/{}/{scope}", drive.as_str())),
|
||||
&mut disk,
|
||||
)
|
||||
.await;
|
||||
|
||||
let db = match cm_db::repo::files::list(pool, ws, drive, agent).await {
|
||||
Ok(d) => d,
|
||||
@@ -171,7 +178,14 @@ pub async fn shared_files(
|
||||
) -> Result<Json<Vec<FileNode>>, ApiError> {
|
||||
let agent = workspace_agent(&state, &user, query.claw_id).await?;
|
||||
if let Some(root) = &state.file_root {
|
||||
reconcile_drive(&state.pool, root, user.workspace_id, FileDrive::Shared, agent.id).await;
|
||||
reconcile_drive(
|
||||
&state.pool,
|
||||
root,
|
||||
user.workspace_id,
|
||||
FileDrive::Shared,
|
||||
agent.id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let nodes =
|
||||
cm_db::repo::files::list(&state.pool, user.workspace_id, FileDrive::Shared, agent.id)
|
||||
|
||||
@@ -7,8 +7,6 @@ pub mod browser;
|
||||
pub mod claw_chat;
|
||||
pub mod claws;
|
||||
pub mod companies;
|
||||
pub mod planner;
|
||||
pub mod webhooks;
|
||||
pub mod files;
|
||||
pub mod gateway;
|
||||
pub mod health;
|
||||
@@ -16,6 +14,7 @@ pub mod identity;
|
||||
pub mod nodes;
|
||||
pub mod oauth;
|
||||
pub mod orgs;
|
||||
pub mod planner;
|
||||
pub mod routines;
|
||||
pub mod sessions;
|
||||
pub mod skills;
|
||||
@@ -26,4 +25,5 @@ pub mod team;
|
||||
pub mod teams;
|
||||
pub mod terminal;
|
||||
pub mod topology;
|
||||
pub mod webhooks;
|
||||
pub mod world;
|
||||
|
||||
@@ -83,7 +83,9 @@ pub async fn list(
|
||||
Authed(user): Authed,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let rows = nodes::list(&state.pool, user.workspace_id).await?;
|
||||
Ok(Json(json!({ "nodes": rows.iter().map(node_json).collect::<Vec<_>>() })))
|
||||
Ok(Json(
|
||||
json!({ "nodes": rows.iter().map(node_json).collect::<Vec<_>>() }),
|
||||
))
|
||||
}
|
||||
|
||||
/// `GET /api/nodes/live` — SSE stream of the node list + health (2s poll).
|
||||
@@ -116,7 +118,9 @@ pub async fn exec_test(
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound)?;
|
||||
match state.node_hub.verify(node_id).await {
|
||||
Ok(out) => Ok(Json(json!({ "ok": out.ok, "output": out.output, "node": node.name }))),
|
||||
Ok(out) => Ok(Json(
|
||||
json!({ "ok": out.ok, "output": out.output, "node": node.name }),
|
||||
)),
|
||||
Err(e) => Ok(Json(json!({ "ok": false, "output": e, "node": node.name }))),
|
||||
}
|
||||
}
|
||||
@@ -184,7 +188,9 @@ pub async fn terminal_ticket(
|
||||
if !state.node_hub.is_online(node_id).await {
|
||||
return Ok(Json(json!({ "error": "node is offline" })));
|
||||
}
|
||||
Ok(Json(json!({ "ticket": state.node_hub.mint_ticket(node_id).await })))
|
||||
Ok(Json(
|
||||
json!({ "ticket": state.node_hub.mint_ticket(node_id).await }),
|
||||
))
|
||||
}
|
||||
|
||||
/// `GET /api/nodes/{id}/terminal/ws?ticket=…` — bridge a browser xterm to a host
|
||||
@@ -261,8 +267,14 @@ async fn bridge_terminal(hub: Arc<NodeHub>, node_id: NodeId, socket: WebSocket)
|
||||
// Host shell (no container) — the Infra node terminal.
|
||||
"fallback" => hub.open_pty(node_id, sid, cols, rows, None, None).await,
|
||||
"webrtc_offer" => {
|
||||
hub.webrtc_offer(node_id, sid, c.sdp.as_deref().unwrap_or(""), None, None)
|
||||
.await
|
||||
hub.webrtc_offer(
|
||||
node_id,
|
||||
sid,
|
||||
c.sdp.as_deref().unwrap_or(""),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
"webrtc_ice" => {
|
||||
hub.webrtc_ice(
|
||||
|
||||
@@ -61,7 +61,8 @@ brain_query to a concrete domain brain keyword (e.g. 'rust-2024', 'react-native'
|
||||
const SCHEDULED_NOTE: &str = "\n\nMODE: Scheduled. Include a schedule in the proposal. Recurring: \
|
||||
{\"cron\":\"<5-field>\",\"prompt\":\"<mission run each cycle>\"}. One-time: \
|
||||
{\"one_shot_at\":\"<RFC3339 UTC datetime>\",\"prompt\":\"<mission>\"}.";
|
||||
const TRIGGERED_NOTE: &str = "\n\nMODE: Triggered. The team will be fired by a webhook on demand. Set the \
|
||||
const TRIGGERED_NOTE: &str =
|
||||
"\n\nMODE: Triggered. The team will be fired by a webhook on demand. Set the \
|
||||
schedule field to {\"prompt\":\"<the default task the webhook runs>\"} (NO cron / one_shot_at).";
|
||||
const SWARM_SYSTEM: &str = "You are the planner for a self-verifying agent SWARM (Opus plans + verifies, a worker \
|
||||
swarm executes, the loop repeats until every output passes). The user describes a job; you turn it into a swarm \
|
||||
|
||||
@@ -62,7 +62,9 @@ pub async fn connect(
|
||||
let api_key = req.api_key.trim();
|
||||
let tailnet = req.tailnet.trim();
|
||||
if api_key.is_empty() || tailnet.is_empty() {
|
||||
return Ok(Json(json!({ "ok": false, "error": "apiKey and tailnet are required" })));
|
||||
return Ok(Json(
|
||||
json!({ "ok": false, "error": "apiKey and tailnet are required" }),
|
||||
));
|
||||
}
|
||||
fleet_tailscale::set(&state.pool, user.workspace_id, api_key, tailnet).await?;
|
||||
Ok(Json(json!({ "ok": true, "tailnet": tailnet })))
|
||||
@@ -74,7 +76,9 @@ pub async fn status(
|
||||
Authed(user): Authed,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let conn = fleet_tailscale::get(&state.pool, user.workspace_id).await?;
|
||||
Ok(Json(json!({ "connected": conn.is_some(), "tailnet": conn.map(|(_, t)| t) })))
|
||||
Ok(Json(
|
||||
json!({ "connected": conn.is_some(), "tailnet": conn.map(|(_, t)| t) }),
|
||||
))
|
||||
}
|
||||
|
||||
/// `DELETE /api/fleet/tailscale` — disconnect Tailscale.
|
||||
@@ -92,11 +96,16 @@ pub async fn devices(
|
||||
State(state): State<AppState>,
|
||||
Authed(user): Authed,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let Some((api_key, tailnet)) = fleet_tailscale::get(&state.pool, user.workspace_id).await? else {
|
||||
let Some((api_key, tailnet)) = fleet_tailscale::get(&state.pool, user.workspace_id).await?
|
||||
else {
|
||||
return Ok(Json(json!({ "connected": false, "devices": [] })));
|
||||
};
|
||||
let url = format!("https://api.tailscale.com/api/v2/tailnet/{tailnet}/devices");
|
||||
let resp = reqwest::Client::new().get(&url).bearer_auth(&api_key).send().await;
|
||||
let resp = reqwest::Client::new()
|
||||
.get(&url)
|
||||
.bearer_auth(&api_key)
|
||||
.send()
|
||||
.await;
|
||||
let body = match resp {
|
||||
Ok(r) if r.status().is_success() => r.json::<Value>().await.unwrap_or_else(|_| json!({})),
|
||||
Ok(r) => {
|
||||
@@ -127,5 +136,7 @@ pub async fn devices(
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Ok(Json(json!({ "connected": true, "tailnet": tailnet, "devices": devices })))
|
||||
Ok(Json(
|
||||
json!({ "connected": true, "tailnet": tailnet, "devices": devices }),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -79,10 +79,13 @@ pub(crate) async fn build_team(
|
||||
};
|
||||
cm_db::repo::agents::insert(&state.pool, &agent, &AccessPolicy::default()).await?;
|
||||
let claw_id = agent.id.as_uuid();
|
||||
provisioner.provision_claw(claw_id, &m.model).await.map_err(|e| {
|
||||
eprintln!("teams: provision claw {claw_id} failed: {e}");
|
||||
ApiError::Internal
|
||||
})?;
|
||||
provisioner
|
||||
.provision_claw(claw_id, &m.model)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("teams: provision claw {claw_id} failed: {e}");
|
||||
ApiError::Internal
|
||||
})?;
|
||||
cm_db::repo::agents::set_model_binding(&state.pool, agent.id, &m.model).await?;
|
||||
claw_ids.push(claw_id);
|
||||
}
|
||||
@@ -98,10 +101,19 @@ pub(crate) async fn build_team(
|
||||
|
||||
let team_id = Uuid::now_v7();
|
||||
let graph_json = serde_json::to_value(&graph).map_err(|_| ApiError::Internal)?;
|
||||
cm_db::repo::teams::insert_team(&state.pool, team_id, workspace_id, name, kind.as_str(), &graph_json).await?;
|
||||
cm_db::repo::teams::insert_team(
|
||||
&state.pool,
|
||||
team_id,
|
||||
workspace_id,
|
||||
name,
|
||||
kind.as_str(),
|
||||
&graph_json,
|
||||
)
|
||||
.await?;
|
||||
for (i, node) in graph.nodes.iter().enumerate() {
|
||||
if let Some(cid) = claw_ids.get(i) {
|
||||
cm_db::repo::teams::add_member(&state.pool, team_id, &node.id, *cid, &node.role).await?;
|
||||
cm_db::repo::teams::add_member(&state.pool, team_id, &node.id, *cid, &node.role)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok((team_id, claw_ids))
|
||||
@@ -122,7 +134,12 @@ pub async fn create_team(
|
||||
&body.members,
|
||||
)
|
||||
.await?;
|
||||
Ok((StatusCode::CREATED, Json(TeamCreated { team_id: team_id.to_string() })))
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(TeamCreated {
|
||||
team_id: team_id.to_string(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -146,12 +163,17 @@ pub async fn create_team_from_claws(
|
||||
if body.claw_ids.is_empty() {
|
||||
return Err(ApiError::BadRequest);
|
||||
}
|
||||
let kind = parse_kind(if body.kind.is_empty() { "hub_spoke" } else { &body.kind })?;
|
||||
let kind = parse_kind(if body.kind.is_empty() {
|
||||
"hub_spoke"
|
||||
} else {
|
||||
&body.kind
|
||||
})?;
|
||||
|
||||
// Resolve + authorize each claw, collecting its role for the topology.
|
||||
let mut roles: Vec<String> = Vec::with_capacity(body.claw_ids.len());
|
||||
for cid in &body.claw_ids {
|
||||
let agent = crate::routes::claws::workspace_agent(&state, &user, AgentId::from(*cid)).await?;
|
||||
let agent =
|
||||
crate::routes::claws::workspace_agent(&state, &user, AgentId::from(*cid)).await?;
|
||||
roles.push(if agent.job_title.is_empty() {
|
||||
"claw".into()
|
||||
} else {
|
||||
@@ -291,7 +313,12 @@ pub async fn patch_team(
|
||||
.collect();
|
||||
let n = by_node.len();
|
||||
let roles: Vec<String> = (0..n)
|
||||
.map(|i| by_node.get(&format!("n{i}")).map(|(_, r)| r.clone()).unwrap_or_else(|| "claw".into()))
|
||||
.map(|i| {
|
||||
by_node
|
||||
.get(&format!("n{i}"))
|
||||
.map(|(_, r)| r.clone())
|
||||
.unwrap_or_else(|| "claw".into())
|
||||
})
|
||||
.collect();
|
||||
let role_refs: Vec<&str> = roles.iter().map(String::as_str).collect();
|
||||
let mut graph = build(kind, &role_refs).map_err(|_| ApiError::BadRequest)?;
|
||||
@@ -302,7 +329,14 @@ pub async fn patch_team(
|
||||
}
|
||||
}
|
||||
let graph_json = serde_json::to_value(&graph).map_err(|_| ApiError::Internal)?;
|
||||
cm_db::repo::teams::set_topology(&state.pool, team.id, user.workspace_id, kind.as_str(), &graph_json).await?;
|
||||
cm_db::repo::teams::set_topology(
|
||||
&state.pool,
|
||||
team.id,
|
||||
user.workspace_id,
|
||||
kind.as_str(),
|
||||
&graph_json,
|
||||
)
|
||||
.await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -197,11 +197,21 @@ pub async fn run_swarm(
|
||||
"task_count": req.task_count,
|
||||
"worker_model": req.worker_model,
|
||||
});
|
||||
cm_db::repo::topology_runs::enqueue_run_tier(&state.pool, id, user.workspace_id, &req.goal, &config, "swarm")
|
||||
.await?;
|
||||
cm_db::repo::topology_runs::enqueue_run_tier(
|
||||
&state.pool,
|
||||
id,
|
||||
user.workspace_id,
|
||||
&req.goal,
|
||||
&config,
|
||||
"swarm",
|
||||
)
|
||||
.await?;
|
||||
Ok((
|
||||
StatusCode::ACCEPTED,
|
||||
Json(RunAccepted { run_id: id.to_string(), status: "queued".into() }),
|
||||
Json(RunAccepted {
|
||||
run_id: id.to_string(),
|
||||
status: "queued".into(),
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,9 @@ pub async fn create_webhook(
|
||||
.execute(&state.pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Internal)?;
|
||||
Ok(Json(json!({ "token": token.to_string(), "url": format!("/api/hooks/{token}") })))
|
||||
Ok(Json(
|
||||
json!({ "token": token.to_string(), "url": format!("/api/hooks/{token}") }),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
|
||||
@@ -74,33 +74,60 @@ fn summarize_input(input: &Value) -> String {
|
||||
/// Normalize one durable `run_events` row into taxonomy events — the Rust twin of
|
||||
/// the handoff bridge's normalize(). The runner already journals these, so the
|
||||
/// live view shows REAL reasoning, tool-convergence and doors with no runner edit.
|
||||
fn normalize_run_event(agent_id: &str, event_type: &str, payload: &Value) -> Vec<(&'static str, Value)> {
|
||||
fn normalize_run_event(
|
||||
agent_id: &str,
|
||||
event_type: &str,
|
||||
payload: &Value,
|
||||
) -> Vec<(&'static str, Value)> {
|
||||
let mut out = Vec::new();
|
||||
match event_type {
|
||||
"text_delta" => {
|
||||
if let Some(delta) = payload.get("delta").and_then(|v| v.as_str()) {
|
||||
out.push(("agent.reasoning.delta", json!({ "agentId": agent_id, "text": delta })));
|
||||
out.push((
|
||||
"agent.reasoning.delta",
|
||||
json!({ "agentId": agent_id, "text": delta }),
|
||||
));
|
||||
}
|
||||
}
|
||||
"step_started" => {
|
||||
let tool = payload.get("tool").and_then(|v| v.as_str()).unwrap_or("tool");
|
||||
let tool = payload
|
||||
.get("tool")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("tool");
|
||||
let node_id = format!("tool:{tool}");
|
||||
let target = payload.get("input").map(summarize_input).unwrap_or_default();
|
||||
let target = payload
|
||||
.get("input")
|
||||
.map(summarize_input)
|
||||
.unwrap_or_default();
|
||||
// File/project I/O gets an explosive burst (high touch weight).
|
||||
let lower = tool.to_lowercase();
|
||||
let file_op = ["file", "read", "write", "drive", "vault", "obsidian", "edit", "fs", "save"]
|
||||
.iter()
|
||||
.any(|k| lower.contains(k));
|
||||
let file_op = [
|
||||
"file", "read", "write", "drive", "vault", "obsidian", "edit", "fs", "save",
|
||||
]
|
||||
.iter()
|
||||
.any(|k| lower.contains(k));
|
||||
let weight = if file_op { 1.0 } else { 0.4 };
|
||||
out.push(("agent.tool.call", json!({ "agentId": agent_id, "tool": tool, "target": target })));
|
||||
out.push((
|
||||
"agent.tool.call",
|
||||
json!({ "agentId": agent_id, "tool": tool, "target": target }),
|
||||
));
|
||||
out.push(("node.activity", json!({ "nodeId": node_id, "label": tool, "kind": "service", "heat": if file_op { 1.0 } else { 0.9 } })));
|
||||
// the agent converges on the tool it's using (the Gource beam)
|
||||
out.push(("world.touch", json!({ "agentId": agent_id, "nodeId": node_id, "kind": "service", "weight": weight })));
|
||||
}
|
||||
"approval_required" => {
|
||||
let action = payload.get("action_type").and_then(|v| v.as_str()).unwrap_or("action");
|
||||
let category = payload.get("category").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let door_id = payload.get("approval_id").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let action = payload
|
||||
.get("action_type")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("action");
|
||||
let category = payload
|
||||
.get("category")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let door_id = payload
|
||||
.get("approval_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
out.push((
|
||||
"door.request",
|
||||
json!({ "doorId": door_id, "agentId": agent_id, "action": action, "target": category, "summary": action }),
|
||||
@@ -134,7 +161,10 @@ struct AgentTele {
|
||||
/// Per-agent telemetry for every agent in the workspace, in 4 grouped queries
|
||||
/// (not N×4): tokens over the last minute, credits over the last hour, active
|
||||
/// routines, and pending approvals — all keyed by agent id.
|
||||
async fn agent_telemetry(pool: &PgPool, ws: WorkspaceId) -> std::collections::HashMap<String, AgentTele> {
|
||||
async fn agent_telemetry(
|
||||
pool: &PgPool,
|
||||
ws: WorkspaceId,
|
||||
) -> std::collections::HashMap<String, AgentTele> {
|
||||
let mut m: std::collections::HashMap<String, AgentTele> = std::collections::HashMap::new();
|
||||
let id_of = |r: &sqlx::postgres::PgRow| r.get::<uuid::Uuid, _>("agent_id").to_string();
|
||||
|
||||
@@ -347,7 +377,9 @@ pub async fn world_replay(
|
||||
events.push(json!({ "t": started, "type": "node.activity", "data": { "nodeId": node_id, "label": "run", "kind": "event", "heat": 0.85 }}));
|
||||
events.push(json!({ "t": started, "type": "world.touch", "data": { "agentId": agent_id, "nodeId": node_id, "kind": "event" }}));
|
||||
}
|
||||
Ok(Json(json!({ "events": events, "hours": hours, "count": rows.len() })))
|
||||
Ok(Json(
|
||||
json!({ "events": events, "hours": hours, "count": rows.len() }),
|
||||
))
|
||||
}
|
||||
|
||||
// THE NORMALIZE SEAM (future) -------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user