text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_suffix|>n<invoke name=\"shell\">\n<parameter name=\"command\">sed -n '1,5p' file.rs";
assert_eq!(strip_tool_call_tags(msg), "Here's the result:");
// Envelope-only (no prose) -> empty.
let only = "<function_calls>\n<invoke name=\"shell\">\n<parameter name=\"command\">date";
assert... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>::json!({"error": format!("{}", e)})),
"Voice webhook server error"
);
anyhow::Error::msg(format!("Voice webhook server error: {e}"))
})?;
Ok(())
}
async fn health_check(&self) -> bool {
// Check we can reach the model_provider API
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Voice Wake Word detection channel.
//!
//! Listens on the default microphone via `cpal`, detects a configurable wake
//! word using energy-based VAD followed by transcription-based keyword matching,
//! then captures the subsequent utterance and dispatches it as a channel message.
//!
//! Gated behind... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use async_trait::async_trait;
use std::sync::Arc;
use uuid::Uuid;
use zeroclaw_api::channel::{Channel, ChannelMessage, SendMessage};
const MAX_WATI_AUDIO_BYTES: u64 = 25 * 1024 * 1024;
/// WATI WhatsApp Business API channel.
///
/// This channel operates in webhook mode (push-based) rather than polling.... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>r")
}
#[tokio::test]
async fn send_happy_path_returns_ok() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let mock = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/cb"))
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use async_trait::async_trait;
use std::sync::Arc;
use zeroclaw_api::channel::{Channel, ChannelMessage, SendMessage};
/// WeCom (WeChat Enterprise) Bot Webhook channel.
///
/// Sends messages via the WeCom Bot Webhook API. Incoming messages are received
/// through a configurable callback URL that WeCom p... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>est]
fn whatsapp_group_mention_dm_passes_through_without_match() {
// group_mention_patterns configured but DMs should pass through
let ch = WhatsAppChannel::new(
"test-token".into(),
"123456789".into(),
"verify-me".into(),
"whatsapp_test... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Custom wa-rs storage backend using ZeroClaw's rusqlite
//!
//! This module implements all 4 wa-rs storage traits using rusqlite directly,
//! avoiding the Diesel/libsqlite3-sys dependency conflict from wa-rs-sqlite-storage.
//!
//! # Traits Implemented
//!
//! - [`SignalStore`]: Signal protocol crypto... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Replays captured `card.action.trigger` fixtures (collected from a live
//! Lark/Feishu tenant via `RUST_LOG=info,zeroclaw_log_event=debug`) through
//! the exact JSON-pointer logic used by `LarkChannel::handle_card_action_event`,
//! and asserts t<|fim_suffix|>ehaviors/0/value β drift here means produ... | fim | zeroclaw-labs/zeroclaw | rust |
//! Integration coverage for `reply_min_interval_secs` + bounded queue
//! against the recipient shapes used by Telegram and WhatsApp Web β the
//! two channels #6345 calls out by name.
//!
//! These tests live at the pacing layer rather than inside each channel's
//! HTTP/WS protocol mocks because pacing is a `PacedCh... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Proof that the orchestrator's composition of channel_id / room_id /
//! sender_id from a real `ChannelMessage` produces the values that land
//! in `session_metadata`. The orchestrator's full
//! `handle_channel_message` requires a fully-built runtime context which
//! is heavy to fixture; this test e... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Structured error type for the gateway HTTP CRUD surface and its CLI peer.
//!
//! Every fallible operation against the new per-property endpoints (`/api/config/prop`,
//! `/api/config/list`, `OPTIONS /api/config*`, `PATCH /api/config`) and the matching
//! `zeroclaw config` CLI subcommands returns thi... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> of reachable targets is
/// determined by shared risk profile at the call site β this only gates
/// whether delegation is permitted at all.
pub fn permits(&self) -> bool {
matches!(self.mode, DelegationMode::Allow)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Shared TOML comment-writing helpers used by both the gateway HTTP CRUD
//! handlers and the CLI `zeroclaw config set --comment` / `zeroclaw config patch`
//! flow. Walks a `toml_edit::DocumentMut` to a leaf key by dotted path and
//! decorates its leading whitespace with `# {comment}\n`. Empty comment... | fim | zeroclaw-labs/zeroclaw | rust |
pub mod tracker;
pub mod types;
pub use tracker::CostTracker;
pub use types::*;
<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use super::types::{
AgentCostStats, BudgetCheck, CostRecord, CostSummary, ModelStats, TokenUsage, UsagePeriod,
};
use crate::schema::CostConfig;
use anyhow::{Context, Result};
use chrono::{DateTime, Datelike, NaiveDate, Utc};
use parking_lot::{Mutex, MutexGuard};
use std::collections::HashMap;
use std... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>current_usd: f64,
limit_usd: f64,
period: UsagePeriod,
},
/// Budget exceeded, request blocked
Exceeded {
current_usd: f64,
limit_usd: f64,
period: UsagePeriod,
},
}
/// Cost summary for reporting.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>her = DomainMatcher::new(&[] as &[String], &["banking".to_string()]).unwrap();
assert!(matcher.is_gated("login.paypal.com"));
assert!(matcher.is_gated("api.coinbase.com"));
assert!(!matcher.is_gated("developer.mozilla.org"));
}
#[test]
fn non_matching_domain_returns_fa... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> Some("**** (encrypted)"),
"must not corrupt the field with the display mask",
);
}
#[tokio::test]
async fn schema_version_override_rejected() {
let _guard = super::env_test_lock().await;
let _v = EnvVarGuard::set("ZEROCLAW_schema_version", "99");
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> let ex = memory_backend_excludes("qdrant");
assert!(!ex.contains(&"qdrant."));
assert!(ex.contains(&"postgres."));
assert!(ex.contains(&"sqlite-open-timeout-secs"));
assert!(ex.contains(&"conversation-retention-days"));
}
#[test]
fn excluded_paths_for_m... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Property helpers used by the `Configurable` derive macro and the `zeroclaw config` CLI.
use crate::traits::{ConfigTab, CredentialSurfaceClass, PropFieldInfo, PropKind};
/// For a `#[nested] HashMap<String, T>` field, parse a `get_prop`/`set_prop`
/// path of the form `<my_prefix>.<field_name>.<hm_ke... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>crets;
pub mod sections;
pub mod skill_bundles;
pub mod traits;
pub mod typed_value;
pub mod validation_warnings;
/// Shim module so `Configurable` derive macro's generated `crate::config::*` paths resolve.
/// The macro was written assuming it runs inside the root crate where `mod config` exists.
pub mo... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use anyhow::{Context, Result};
use std::path::Path;
use crate::schema::Config;
use crate::schema::v1::V1Config;
use crate::schema::v2::V2Config;
/// The schema version this binary writes and expects on disk.
pub const CURRENT_SCHEMA_VERSION: u32 = 3;
/// Top-level TOML keys that legacy schema versions ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>\"none\""),
(MemoryBackendKind::Sqlite, "\"sqlite\""),
(MemoryBackendKind::Postgres, "\"postgres\""),
(MemoryBackendKind::Qdrant, "\"qdrant\""),
(MemoryBackendKind::Markdown, "\"markdown\""),
(MemoryBackendKind::Lucid, "\"lucid\""),
];
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>// Gateway pairing mode β first-connect authentication.
//
// On startup the gateway generates a one-time pairing code printed to the
// terminal. The first client must present this code via `X-Pairing-Code`
// header on a `POST /pair` request. The server responds with a bearer token
// that must be sent ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> resolve_under(root, "skills//coding/").unwrap(),
root.join("skills/coding"),
);
}
}
<|fim_prefix|>//! Shared path helpers used by both schema-tier validation and the
//! scoped file browser. Single source of truth for "lexically normalize a
//! path" and "resolve a relative inp... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use crate::schema::DockerRuntimeConfig;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use zeroclaw_api::runtime_traits::RuntimeAdapter;
/// Docker runtime with lightweight container isolation.
#[derive(Debug, Clone)]
pub struct DockerRuntime {
config: DockerRuntimeConfig,
}
impl Doc... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub mod docker;
pub mod native;
pub use docker::DockerRuntime;
pub use native::NativeRuntime;
pub use zeroclaw_api::runtime_traits::RuntimeAdapter;
use crate::schema::RuntimeConfig;
pub fn create_runtime(config: &RuntimeConfig) -> anyhow::Result<Box<dyn RuntimeAdapter>> {
match config.kind.as_str()... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use std::path::{Path, PathBuf};
use zeroclaw_api::runtime_traits::RuntimeAdapter;
/// Native runtime β full access, runs on Mac/Linux/Windows/Docker/Raspberry Pi
pub struct NativeRuntime;
impl Default for NativeRuntime {
fn default() -> Self {
Self::new()
}
}
impl NativeRuntime {
pu... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Quickstart preset tables and submission shape.
//!
//! Two preset tables β [`RISK_PRESETS`] and [`RUNTIME_PRESETS`] β give
//! the Quickstart UI a fixed-shape menu of named, opinionated profile
//! defaults the user can pick from. Each preset carries:
//!
//! - `preset_name` β the alias key written t... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>me("qianfan")
} else if is_doubao_alias(name) {
Some("doubao")
} else if is_bailian_alias(name) {
Some("bailian")
} else {
None
}
}
/// Whether a canonical provider family honors the `wire_api` config field.
///
/// Mirrors the provider factory in `zeroclaw-provide... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> )
.chain(self.edge.iter().map(|(a, c)| ("edge", a.as_str(), &c.base)))
.chain(
self.piper
.iter()
.map(|(a, c)| ("piper", a.as_str(), &c.base)),
),
)
}
/// Iterate every T... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Config types that were originally defined in their home modules (agent, channels, tools, trust)
//! but are needed by the config schema. Moved here to break circular dependencies.
use crate::traits::{ChannelConfig, HasPropKind, PropKind};
use serde::{Deserialize, Serialize};
use std::collections::Has... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::migration::fo<|fim_suffix|> providers.insert("models".to_string(), toml::Value::Table(models_table));
}
if !model_routes.is_empty() {
providers.insert("model_routes".to_string()... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ping Markdown, not raw HTML table cells, so
// mdbook-i18n-helpers extracts the prose (field description and the
// tab guidance) for translation. Everything that must stay verbatim
// (field name, dotted path, `config set` command, env-var name) is in
// inline `code` span... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>").unwrap();
let key1 = store1.load_or_create_key().unwrap();
// Encrypt with store1's key
let plaintext = "secret-for-store1";
let ciphertext = xor_cipher(plaintext.as_bytes(), &key1);
let legacy_value = format!("enc:{}", hex_encode(&ciphertext));
// Decr... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Curated sections surface β a flat ordered set of [`Section`]s the
//! operator walks (new install) or scans (returning user) to configure
//! a working ZeroClaw deployment.
//!
//! Every fact about a section (its enum variant, its on-the-wire key,
//! its UI shape, its help blurb, its canonical positi... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Skill-bundle directory rules and helpers.
//!
//! Single source of truth for:
//! - the `shared/skills/<alias>/` default
//! - the inside-`shared/` containment rule
//! - the per-config uniqueness rule
//!
//! Lives in `zeroclaw-config` (not `zeroclaw-runtime/skills/bundle.rs`) so
//! [`crate::schema:... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>/// Sentinel rendered for unset / `None` / empty config values during display.
/// Never a valid stored value: the write path rejects it so it cannot round-trip
/// into persisted config.
pub const UNSET_DISPLAY: &str = "<unset>";
/// Describes a single secret field discovered via `#[derive(Configurable)... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> coerce_for_set_prop(&serde_json::Value::Null, k).unwrap(),
""
);
}
}
#[test]
fn string_array_rejects_non_array() {
let err = coerce_for_set_prop(
&serde_json::Value::String("a,b".into()),
Some(PropKind::StringArray),
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> user
//! with no indication their config would fail at runtime.
//!
//! Each warning carries:
//! - a stable `code` (machine-friendly, matches across releases for a
//! given check)
//! - a human-readable `message` (suitable for direct display to operators)
//! - the dotted property `path` the warning ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>erun-if-changed before any early return so cargo registers
// the dependency. Without it, source edits don't re-invoke the
// script and stale dist/ stays served against changed web/src.
println!(
"cargo:rerun-if-changed={}",
web_dir.join("package.json").display()
);
pr... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>module_path!(), ::zeroclaw_log::Action::Note),
"ACP WebSocket closed without handshake"
);
} else {
::zeroclaw_log::record!(
WARN,
::zeroclaw_log::Event::new(module_path!(), ::ze... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! HTTP adapter over `zeroclaw_runtime::browse::list_directory`.
//!
//! `GET /api/browse?path=<relative-to-shared>` returns one level of
//! children. All walking, containment, and sorting lives in the runtime
//! browse module; this is request shape β service call β response shape.
use axum::{
Jso... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Per-property CRUD endpoints for `/api/config/*`.
//!
//! These endpoints expose the same `Config::get_prop` / `set_prop` core that
//! `zeroclaw config get/set/list/init/migrate` uses on the CLI. Both are thin
//! frontends over the same mutation primitive.
//!
//! Returns structured `ConfigApiError` ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>("outcome"),
severity_min,
trace_id: take("trace_id"),
q: take("q"),
hide_internal,
field_eq,
};
let LogPage {
events,
next_cursor,
at_end,
} = match zeroclaw_log::load_page(&path, &filter, limit) {
Ok(page) => page,
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>.lock();
pending.retain(|p| p.expires_at > Utc::now());
pending.len()
}
}
fn extract_bearer(headers: &HeaderMap) -> Option<&str> {
headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|auth| auth.strip_prefix("Bearer "))
}
fn requir... | fim | zeroclaw-labs/zeroclaw | rust |
//! Read/write endpoints for per-agent personality markdown files
//! (`SOUL.md`, `IDENTITY.md`, `USER.md`, `AGENTS.md`, `TOOLS.md`,
//! `HEARTBEAT.md`, `BOOTSTRAP.md`, `MEMORY.md`).
//!
//! The runtime injects these into the system prompt at request time
//! (see `zeroclaw_runtime::agent::personality::load_personality... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Plugin management API routes (requires `plugins-wasm` feature).
#[cfg(feature = "plugins-wasm")]
pub mod plugin_routes {
use axum::{
extract::State,
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Json},
};
use super::super::AppState;
/// `GET... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> };
(StatusCode::OK, Json(body)).into_response()
}
/// Signal the in-place daemon reload using the same `reload_tx` watch
/// channel `/admin/reload` uses. The daemon supervisor reacts by
/// draining the current gateway/channels/scheduler and bringing them
/// back up against the new in-memory conf... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Curated config-section endpoints. Used by the `/config` page in the
//! web dashboard to navigate the schema by curated section rather than
//! raw prop paths. OpenAPI is authoritative for the exact route set.
use axum::{
extract::{Query, State},
http::HeaderMap,
response::{IntoResponse, ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>).to_string(),
frontmatter: s.frontmatter,
})
.collect(),
})
.into_response(),
Err(e) => service_error_response(e),
}
}
/// `POST /api/skills/bundles/:alias/skills`
pub async fn handle_create_skill(
State(state): State<Ap... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>, &body.response)
{
Ok(()) => Json(serde_json::json!({"status": "authenticated"})).into_response(),
Err(e) => (
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({"error": format!("{}", e)})),
)
.into_response(),
}
}
/// GET /api/webauthn... | fim | zeroclaw-labs/zeroclaw | rust |
//! Sliding-window rate limiter for authentication attempts.
//!
//! Protects pairing and bearer-token validation endpoints against
//! brute-force attacks. Tracks per-IP attempt timestamps and enforces
//! a lockout period after too many failures within the sliding window.
use parking_lot::Mutex;
use std::collection... | fim | zeroclaw-labs/zeroclaw | rust |
//! Live Canvas gateway routes β REST + WebSocket for real-time canvas updates.
//!
//! - `GET /api/canvas/:id` β get current canvas content (JSON)
//! - `POST /api/canvas/:id` β push content programmatically
//! - `GET /api/canvas` β list all active canvases
//! - `WS /ws/canvas/:id` β real-time canvas update... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ββββββββββ
#[derive(Debug, Serialize)]
struct HardwareContextResponse {
hardware_md: String,
devices: std::collections::HashMap<String, String>,
}
/// `GET /api/hardware/context` β return all current hardware context file contents.
pub async fn handle_hardware_context_get(
State(state): Stat... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Wraps a node capability as a zeroclaw [`Tool`] so it can be dispatched
//! through the existing tool registry and agent loop.
//!
//! Tool names are prefixed with the node ID: `node:<node_id>:<capability_name>`.
use std::sync::Arc;
use async_trait::async_trait;
use tokio::time::Duration;
use crate:... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>t = check_node_auth(&cfg, &make_pairing(false), &empty_headers(), None);
assert_eq!(result.map(|(s, _)| s), Some(StatusCode::UNAUTHORIZED));
}
/// nodes.auth_token set, correct token β auth passes (None = proceed to upgrade).
#[test]
fn nodes_auth_token_correct_token_passes() {
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Runtime-generated OpenAPI 3.1 document for the new `/api/config/*` surface.
//!
//! Built from the same `schemars::JsonSchema` derives the request/response
//! types carry. The generator does not introspect the axum router β instead it
//! walks a hand-maintained `(method, path, request_type, response... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Re-export from zeroclaw-infra<|fim_suffix|>ateway imports keep working.
pub use zeroclaw_infra::session_queue::*;
<|fim_middle|> so existing g<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>], "shell");
assert_eq!(value["success"], true);
let snap = buffer.snapshot();
assert_eq!(snap.len(), 1);
assert_eq!(snap[0]["type"], "tool_call");
}
#[test]
fn tool_call_start_event_is_broadcast() {
let (obs, mut rx, _buffer) = make_broadcast();
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Static file serving for the web dashboard.
//!
//! Serves the compiled `web/dist/` directory from the filesystem at runtime.
//! The directory path is configured via `gateway.web_dist_dir`.
use axum::{
Json,
extract::State,
http::{StatusCode, Uri, header},
response::{IntoResponse, Res... | fim | zeroclaw-labs/zeroclaw | rust |
//! TLS and mutual TLS (mTLS) support for the gateway server.
//!
//! Builds a [`rustls::ServerConfig`] from the gateway TLS configuration,
//! optionally requiring client certificates verified against a trusted CA
//! with optional certificate pinning (SHA-256 fingerprint matching).
use anyhow::{Context, Result};
use... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>art;
let json = serde_json::to_string(&event).unwrap();
assert_eq!(json, "{\"type\":\"speech_start\"}");
}
#[test]
fn voice_event_speech_end_roundtrip() {
let json = r#"{"type":"speech_end","transcript":"hello"}"#;
let event: VoiceEvent = serde_json::from_str(j... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ere β separate from the gateway boot-time seeding.
let ch = agent.channel_handles();
let channel_names = zeroclaw_channels::orchestrator::register_channels_for_tools(
&config,
&ch.ask_user,
&Some(ch.reaction.clone()),
&ch.poll,
&ch.escalate,
);
if !c... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>hrough to
// auto-deny per ApprovalManager policy.
self.pending.lock().remove(&request_id);
return Ok(None);
}
match tokio::time::timeout(self.timeout, rx).await {
Ok(Ok(decision)) => Ok(Some(decision)),
Ok(Err(_)) => {
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> Some(Err(_)) => break,
_ => {}
}
}
}
}
}
<|fim_prefix|>//! ESP32 simulator β speaks the same JSON-over-serial protocol as
//! `firmware/esp32/src/main.rs`, so a host ZeroClaw daemon can drive virtual
//! GPIO pins without any real hardw... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! AardvarkTransport β implements the Transport trait for Total Phase Aardvark USB adapters.
//!
//! The Aardvark is NOT a microcontroller firmware target; it is a USB bridge
//! that speaks I2C / SPI / GPIO directly. Unlike [`HardwareSerialTransport`],
//! this transport interprets [`ZcCommand`] locall... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>::new(),
error: Some(
resp.error
.unwrap_or_else(|| "gpio_aardvark: device returned ok:false".to_string()),
),
}),
Err(e) => Ok(ToolResult {
success: false,
output: String::n... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Canonical hardware tool-name and capability catalog.
//!
//! Single source of truth for the names the agent sees and the docs render.
//! `fn name()` impls and the mdBook hardware snippets both read these constants
//! so a rename lands in one place and the rendered tables follow on the next
//! docs ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Datasheet management for industry devices connected via Aardvark.
//!
//! When a user identifies a new device (e.g. "I have an LM75 temperature
//! sensor"), the [`DatasheetTool`] calls [`DatasheetManager`] to:
//!
//! 1. **search** β query the web for the device datasheet PDF URL.
//! 2. **download**... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Device types and registry β stable aliases for discovered hardware.
//!
//! The LLM always refers to devices by alias (`"pico0"`, `"arduino0"`), never
//! by raw `/dev/` paths. The `DeviceRegistry` assigns these aliases at startup
//! and provides lookup + context building for tool execution.
use sup... | fim | zeroclaw-labs/zeroclaw | rust |
//! USB device discovery β enumerate devices and enrich with board registry.
//!
//! USB enumeration via `nusb` is only supported on Linux, macOS, and Windows.
//! On Android (Termux) and other unsupported platforms this module is excluded
//! from compilation; callers in `hardware/mod.rs` fall back to an empty result.... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! GPIO tools β `gpio_read` and `gpio_write` for LLM-driven hardware control.
//!
//! These are the first built-in hardware tools. They implement the standard
//! [`Tool`] trait so the LLM can call them via function
//! calling, and dispatch commands to physical devices via the
//! `Transport` layer.
//!... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Device introspection β correlate serial path with USB device info.
use super::discover;
use super::registry;
use anyhow::Result;
/// Result of introspecting a device by path.
#[derive(Debug, Clone)]
pub struct IntrospectResult {
pub path: String,
pub vid: Option<u16>,
pub pid: Option<u16... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>path().join("devices").join("pico0.md"),
"# pico0\nPort: /dev/cu.usbmodem1101",
);
let result = load_hardware_context_from_dir(tmp.path(), &["pico0"]);
assert!(result.contains("/dev/cu.usbmodem1101"), "got: {result}");
}
#[test]
fn device_profile_skipped_fo... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>sh"),
"#!/bin/sh\necho '{\"success\":true,\"output\":\"ok\",\"error\":null}'\n",
)
.unwrap();
}
#[test]
fn load_one_plugin_succeeds_for_valid_manifest() {
let dir = tempfile::tempdir().unwrap();
write_valid_manifest(dir.path());
let manifes... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>/// When present, ZeroClaw will prefer the named transport kind
/// and can enforce device presence before calling the tool.
#[derive(Debug, Deserialize)]
pub struct TransportConfig {
/// Preferred transport kind: `"serial"` | `"swd"` | `"native"` | `"any"`.
pub preferred: String,
/// Whether ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> (e.g. /dev/cu.usbmodem* on macOS).",
stderr
);
}
println!("ZeroClaw firmware flashed successfully.");
println!("The Arduino now supports: capabilities, gpio_read, gpio_write.");
Ok(())
}
/// Resolve port from config or path. Returns the path to use for flashing.
pub ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Arduino upload tool β agent generates code, uploads via arduino-cli.
//!
//! When user says "make a heart on the LED grid", the agent generates Arduino
//! sketch code and calls this tool. ZeroClaw compiles and uploads it β no
//! manual IDE or file editing.
use async_trait::async_trait;
use serde_js... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Hardware capabilities tool β Phase C: query device for reported GPIO pins.
use super::serial::SerialTransport;
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
use zeroclaw_api::attribution::ToolKind;
use zeroclaw_api::tool::{Tool, ToolResult};
use zeroclaw_api::tool_attributio... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>oards: vec![],
datasheet_dir: None,
};
let tools = create_peripheral_tools(&config).await.unwrap();
assert!(
tools.is_empty(),
"disabled peripherals should produce no tools"
);
}
}
<|fim_prefix|>//! Hardware peripherals β STM32, RPi G... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Flash ZeroClaw Nucleo-F401RE firmware via probe-rs.
//!
//! Builds the Embassy firmware and flashes via ST-Link (built into Nucleo).
//! Requires: cargo install probe-rs-tools --locked
use anyhow::{Context, Result};
use std::path::PathBuf;
use std::process::Command;
const CHIP: &str = "STM32F401RETx... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Raspberry Pi GPIO peripheral β native rppal access.
//!
//! Only compiled when `peripheral-rpi` feature is enabled and target is Linux.
//! Uses BCM pin numbering (e.g. GPIO 17, 27).
use crate::peripherals::Peripheral;
use async_trait::async_trait;
use serde_json::{Value, json};
use zeroclaw_api::att... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Serial peripheral β STM32 and similar boards over USB CDC/serial.
//!
//! Protocol: newline-delimited JSON.
//! Request: {"id":"1","cmd":"gpio_write","args":{"pin":13,"value":1}}
//! Response: {"id":"1","ok":true,"result":"done"}
use crate::peripherals::Peripheral;
#[cfg(unix)]
use crate::util::shou... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! High-level smart-room device tools for ESP32 boards.
//!
//! Provides `set_device` and `read_device` tools that let the LLM
//! reason in terms of named devices (e.g. "reading_lamp", "fan")
//! instead of raw pin numbers. This eliminates the common failure mode
//! where the model guesses the wrong pi... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub use zeroclaw_a<|fim_suffix|>erals_traits::*;
<|fim_middle|>pi::periph<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> success: false,
output: format!("Bridge error: {}", e),
error: Some(e.to_string()),
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use zeroclaw_api::tool::Tool;
// ββ UnoQGpioReadTool βββββββββββββββββββββββββββββββββββββββββββββ... | fim | zeroclaw-labs/zeroclaw | rust |
//! Deploy ZeroClaw Bridge app to Arduino Uno Q.
use anyhow::{Context, Result};
use std::process::Command;
const BRIDGE_APP_NAME: &str = "uno-q-bridge";
/// Deploy the Bridge app. If host is Some, scp from repo and ssh to start.
/// If host is None, assume we're ON the Uno Q β use embedded files and start.
pub fn se... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Phase 7 β Dynamic code tools: `device_read_code`, `device_write_code`, `device_exec`.
//!
//! These tools let the LLM read, write, and execute code on any connected
//! hardware device. The `DeviceRuntime` on each device determines which
//! host-side tooling is used:
//!
//! - **MicroPython / Circui... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>sync fn execute_missing_confirm_returns_error() {
let result = tool().execute(serde_json::json!({})).await.unwrap();
assert!(!result.success);
}
#[tokio::test]
async fn execute_with_confirm_true_but_no_pico_returns_error() {
// In CI there's no Pico attached β the tool... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>Value::Null,
error: Some(message.into()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn zc_command_serialization_roundtrip() {
let cmd = ZcCommand::new("gpio_write", json!({"pin": 25, "value": 1}));
let json = serde_... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Board registry β maps USB VID/PID to known board names and archit<|fim_suffix|>ture: Some("USB-UART bridge"),
},
BoardInfo {
vid: 0x10c4,
pid: 0xea70,
name: "cp2102n",
architecture: Some("USB-UART bridge"),
},
// ESP32 dev boards often use CH340 USB-UART... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Raspberry Pi self-discovery and native GPIO tools.
//!
//! Only compiled on Linux with the `peripheral-rpi` feature enabled.
//!
//! Provides two capabilities:
//!
//! 1. **Board detection** β `RpiModel` / `RpiSystemContext` detect which Pi model
//! is running, its IP address, temperature, and GPI... | fim | zeroclaw-labs/zeroclaw | rust |
//! Hardware serial transport β newline-delimited JSON over USB CDC.
//!
//! Implements the [`Transport`] trait with **lazy port opening**: the port is
//! opened for each `send()` call and closed immediately after the response is
//! received. This means multiple tools can use the same device path without
//! one hold... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ore = "slow: waits SUBPROCESS_TIMEOUT_SECS (~10 s) to elapse β run manually"]
async fn execute_timeout_kills_process_and_returns_error() {
// Script sleeps forever β SubprocessTool should kill it and return a
// "timed out" error once SUBPROCESS_TIMEOUT_SECS elapses.
let dir = ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>et tool = self
.tools
.get(name)
.ok_or_else(|| ToolError::UnknownTool(name.to_string()))?;
tool.execute(args)
.await
.map_err(|e| ToolError::ExecutionFailed(e.to_string()))
}
/// List all registered tool names (sorted, for logg... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>el error (malformed JSON, id mismatch, etc.).
#[error("protocol error: {0}")]
Protocol(String),
/// Underlying I/O error.
#[error("transport I/O error: {0}")]
Io(#[from] std::io::Error),
/// Catch-all for transport-specific errors.
#[error("{0}")]
Other(String),
}
/// Tr... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! UF2 flashing support β detect BOOTSEL-mode Pico and deploy firmware.
//!
//! # Workflow
//! 1. [`find_rpi_rp2_mount`] β check well-known mount points for the RPI-RP2 volume
//! that appears when a Pico is held in BOOTSEL mode.
//! 2. [`ensure_firmware_dir`] β extract the bundled UF2 to
//! `~/.z... | fim | zeroclaw-labs/zeroclaw | rust |
const SERIAL_ALLOWED_PATH_PREFIXES: &[&str] = &[
"/dev/ttyACM",
"/dev/ttyUSB",
"/dev/tty.usbmodem",
"/dev/cu.usbmodem",
"/dev/tty.usbserial",
"/dev/cu.usbserial",
"COM",
#[cfg(feature = "dev-sim")]
DEV_SIM_SERIAL_PATH_PREFIX,
];
#[cfg(feature = "dev-sim")]
const DEV_SIM_SERIAL_PATH_... | fim | zeroclaw-labs/zeroclaw | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.