text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_prefix|>//! System prompt construction for the agent loop and channel subsystem.
//!
//! These functions were originally in `channels/mod.rs` but live here to
//! break a circular dependency between the channels and agent modules.
use crate::identity;
use crate::security::AutonomyLevel;
use crate::skills::Skill;... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>dModelProvider::new(vec![
tool_response(vec![ToolCall {
id: "tc1".into(),
name: "echo".into(),
arguments: r#"{"message": "hello from tool"}"#.into(),
extra_content: None,
}]),
text_response("I ran the tool"),
]));
let mut age... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Thinking/Reasoning Level Control
//!
//! Allows users to control how deeply the model reasons per message,
//! trading speed for depth. Levels range from `Off` (fastest, most concise)
//! to `Max` (deepest reasoning, slowest).
//!
//! Users can set the level via:
//! - Inline directive: `/think:high` ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>(activated_arc.as_deref()) else {
let reason = format!("Unknown tool: {call_name}");
let duration = start.elapsed();
let scrubbed_reason = scrub_credentials(&reason);
observer.record_event(&ObserverEvent::ToolCall {
tool: call_name.to_string(),
tool_... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>;
let args_real = serde_json::json!({"command": "date"});
let args_fake = serde_json::json!({"command": "rm -rf /"});
let receipt = receipt_gen.generate("shell", &args_real, "Mon Mar 27", 1_711_547_700);
assert!(!receipt_gen.verify(&receipt, "shell", &args_fake, "Mon Mar 27... | fim | zeroclaw-labs/zeroclaw | rust |
//! The per-tool-call approval gate: CLI prompt, channel inline approval, or
//! auto-deny, plus decision recording.
use super::context::TurnCtx;
use super::events::StreamDelta;
use super::redact::scrub_credentials;
use crate::agent::tool_execution::ToolExecutionOutcome;
use crate::approval::{ApprovalRequest, Approval... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! The per-call preparation loop: `before_tool_call` hook, delivery defaults,
//! the approval gate, the duplicate-call gate, and start logging — producing
//! the executable subset of this round's tool calls.
use super::approval_gate::{ApprovalGateOutcome, gate_tool_approval};
use super::context::TurnC... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>p calls (RUN_SHEET
/// `turn.context.TurnCtx`).
///
/// Fields the orchestrator threads to steps as explicit arguments
/// (`model_provider`, `tools_registry`, vision/tool config, receipts, …)
/// are NOT carried here — only the values steps actually read off `ctx`.
pub(crate) struct TurnCtx<'a> {
pub... | fim | zeroclaw-labs/zeroclaw | rust |
//! LLM-failure recording and in-loop context-overflow recovery.
use super::outcome::is_tool_loop_cancelled;
use crate::agent::history::{emergency_history_trim, fast_trim_tool_results};
use crate::observability::{Observer, ObserverEvent};
use std::time::Instant;
use zeroclaw_providers::ChatMessage;
/// Record a faile... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Channel delivery-default injection for cron_add tool calls.
const AUTO_DELIVERY_DEFAULT_CHANNELS: &[&str] = &[
"telegram",
"discord",
"slack",
"mattermost",
"matrix",
"dingtalk",
"lark",
"feishu",
];
pub(crate) fn maybe_inject_channel_delivery_defaults(
tool_name:... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ll(|id| !id.is_empty()),
"synthesized ids must be non-empty: {ids:?}"
);
assert_eq!(
ids[0], ids[1],
"ToolCall/ToolResult of one pair must share the id"
);
assert_eq!(ids[2], ids[3], "second pair must share its id");
assert_ne!(id... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>n each result's own id instead.
for (idx, (tool_call_id, result)) in individual_results.iter().enumerate() {
let resolved_id = tool_call_id
.clone()
.or_else(|| native_tool_calls.get(idx).map(|call| call.id.clone()));
let tool_msg = serde_jso... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Pre-iteration history maintenance: preemptive token-budget trimming,
//! orphaned tool-message removal, and system-message normalization.
use crate::agent::history::{
estimate_history_tokens, fast_trim_tool_results, normalize_system_messages,
};
use zeroclaw_providers::ChatMessage;
pub(crate) fn... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Per-caller loop behaviour knobs (#7415 consolidation).
//!
//! Every divergence between the historical turn engines that survives the
//! consolidation is an explicit field here, set per caller. `Default`
//! preserves today's channel/CLI behaviour.
/// How to handle max-tool-iteration exhaustion.
#[... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> (step_timeout_secs)")
}
SummaryCall::Done(Err(e)) => {
::zeroclaw_log::record!(
ERROR,
::zeroclaw_log::Event::new(module_path!(), ::zeroclaw_log::Action::Fail)
.with_outcome(::zeroclaw_log::EventOutcome::Failure)
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>teration": iteration})),
"Shared iteration budget exhausted at iteration "
);
break;
}
budget.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
preflight_history_maintenance(history, context_token_budget, iter... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"model switch requested to {} {}",
self.model_provider, self.model
)
}
}
impl std::error::Error for ModelSwitchRequested {}
pub fn is_model_switch_requested(err: &anyhow::Error) -> O... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>| {
"streaming text guard suppressed an internal tool protocol envelope".to_string()
})
})
};
if let Some(ref issue) = parse_issue {
::zeroclaw_log::record!(
WARN,
::zeroclaw_log::Event::new(module_path!(), ::zeroclaw_log::Action:... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>) {
for ((idx, call), outcome) in executable_indices
.iter()
.zip(executable_calls.iter())
.zip(executed_outcomes)
{
if let Some(tx) = ctx.event_tx {
super::events::emit_tool_call_pair(tx, call, &outcome).await;
}
::zeroclaw_log::record!... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Heuristics for detecting tool-protocol fragments in streamed model text.
use std::collections::HashSet;
use zeroclaw_tool_call_parser::{
ParsedToolCall, ToolProtocolEnvelopeKind, classify_tool_protocol_envelope,
contains_tool_protocol_tag_call, looks_like_malformed_tool_protocol_envelope,
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ng config to catch hung model responses.
use ::zeroclaw_log::Instrument;
let provider_span = ::zeroclaw_log::attribution_span!(active_model_provider);
let chat_future = ::zeroclaw_log::scope!(
model: active_model,
=>
active_model_provider.chat(
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>h.contains(':') {
if full_match.contains('"') {
format!("\"{}\": \"{}*[REDACTED]\"", key, prefix)
} else {
format!("{}: {}*[REDACTED]", key, prefix)
}
} else if full_match.contains('=') {
if... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> );
result_output = format!("{result_output}\n\n[receipt: {receipt}]");
if let Some(store) = collected_receipts
&& let Ok(mut v) = store.lock()
{
v.push(format!("{tool_name}: {receipt}"));
}
}
individual_resu... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Mid-turn steering: non-blocking drain of caller-pushed messages between
//! loop iterations (and between wrapper rounds)<|fim_suffix|><|fim_middle|>.
/// Drain any steering messages the caller pushed since the last round.
pub fn drain_steering_messages(
steering_rx: &mut Option<&mut tokio::sync::... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>hunk,
}
} else {
provider_stream.next().await
};
let Some(event_result) = next_chunk else {
break;
};
let event = match event_result {
Ok(event) => event,
Err(err) => {
::zeroclaw_log::rec... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Streaming-text guards: protocol-fragment buffering and <think> tag stripping.
use super::protocol_detect::{
complete_json_fence_protocol_state, complete_non_protocol_json,
find_embedded_protocol_cand<|fim_suffix|> }
if let Some(start) = find_incomplete_protocol_candidate_start(ch... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Per-iteration tool-spec assembly for the turn engine.
use crate::tools::{ActivatedToolSet, Tool, ToolSpec};
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use zeroclaw_providers::ModelProvider;
/// Tool specs assembled for one loop iteration.
pub(crate) struct IterationToolSpecs {
p... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>);
assert!(first.contains_images);
assert_eq!(cache.len(), 1, "image cached after the first prep");
// A later iteration/turn re-walks the same history; the cache serves it
// without growing (no second disk read + encode).
let _second = prepare_messages_for_iterat... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Interactive approval workflow for supervised mode.
//!
//! Provides a pre-execution hook that prompts the user before tool calls,
//! with session-scoped "Always" allowlists and audit logging.
use crate::security::AutonomyLevel;
use chrono::Utc;
use parking_lot::Mutex;
use serde::{Deserialize, Serial... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> from_trimmed
} else {
to_trimmed
}
)));
}
let root = agent_root(config, agent_alias);
let src: PathBuf = resolve_under(&root, from)?;
let dst: PathBuf = resolve_under(&root, to)?;
if !src.exists() {
return Err(BrowseError::No... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use anyhow::{Result, bail};
use std::io::{BufRead, Write};
#[derive(Debug, Clone, Default)]
pub struct Input {
prompt: String,
default: Option<String>,
allow_empty: bool,
}
impl Input {
#[must_use]
pub fn new() -> Self {
Self {
prompt: String::new(),
d... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>}
<|fim_prefix|>pub use zeroclaw_config::cost::*;
pub mod types {
pub use zeroclaw_config::cost::types::*;<|fim_middle|>
<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use crate::security::SecurityPolicy;
use anyhow::{Result, bail};
use zeroclaw_config::schema::Config;
mod schedule;
mod store;
mod types;
pub mod scheduler;
#[allow(unused_imports)]
pub use schedule::{
next_run_for_schedule, normalize_expression, schedule_cron_expression, validate_schedule,
};
#[al... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>seconds={})",
now.to_rfc3339(),
now.with_timezone(&chrono::Local).to_rfc3339(),
at.to_rfc3339(),
at.with_timezone(&chrono::Local).to_rfc3339(),
(*at - now).num_seconds()
);
}
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use crate::cron::store::{RunCompletionAction, persist_run_completion_state, persist_run_result};
use crate::cron::{
CronJob, DeliveryConfig, JobType, Schedule, SessionTarget, all_overdue_jobs, due_jobs,
next_run_for_schedule, skip_missed_run, sync_declarative_jobs,
};
use crate::security::Security... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>not create the cron directory"
);
assert!(
!cron_db(&config).exists(),
"empty declarative sync should not create jobs.db"
);
}
#[test]
fn read_existing_old_schema_db_migrates_before_querying_new_columns() {
let tmp = TempDir::new().unwra... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// Try to deserialize a `serde_json::Value` as `T`. If the value is a JSON
/// string that looks like an object (i.e. the LLM double-serialized it), parse
/// the inner string first and then deserialize the resulting object. This
/// pr... | fim | zeroclaw-labs/zeroclaw | rust |
use anyhow::Result;
use chrono::Utc;
use std::path::PathBuf;
use tokio::task::JoinHandle;
use tokio::time::Duration;
use zeroclaw_config::schema::Config;
use zeroclaw_memory::{MEMORY_CONTEXT_CLOSE, MEMORY_CONTEXT_OPEN};
mod registry;
pub use registry::DaemonRegistry;
const STATUS_FLUSH_SECONDS: u64 = 5;
/// Why the ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use anyhow::Result;
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use tokio::sync::{broadcast, watch};
use tokio_util::sync::CancellationToken;
use zeroclaw_config::schema::{Config, MqttConfig};
use crate::rpc::context::RpcConte... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use anyhow::Result;
use chrono::{DateTime, Utc};
use std::io::Write;
use std::path::Path;
use zeroclaw_config::schema::Config;
const DAEMON_STALE_SECONDS: i64 = 30;
const SCHEDULER_STALE_SECONDS: i64 = 120;
const CHANNEL_STALE_SECONDS: i64 = 300;
const COMMAND_VERSION_PREVIEW_CHARS: usize = 60;
// ── Di... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>dashboard can implement "since daemon start"
/// log queries without drift.
pub fn daemon_started_at() -> String {
registry().started_at_wall.to_rfc3339()
}
fn now_rfc3339() -> String {
Utc::now().to_rfc3339()
}
fn upsert_component<F>(component: &str, update: F)
where
F: FnOnce(&mut Componen... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>[0].status, TaskStatus::Active);
}
#[test]
fn parse_task_with_low_paused() {
let content = "- [low|paused] Review old PRs";
let tasks = HeartbeatEngine::parse_tasks(content);
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].text, "Review old PRs");
asser... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub mod engine;
pub mod store;
#[cfg(test)]
mod tests {
use crate::heartbeat::engine::HeartbeatEngine;
use crate::observability::NoopObserver;
use std::sync::Arc;
use zeroclaw_config::schema::HeartbeatConfig;
#[test]
fn heartbeat_engine_is_constru<|fim_suffix|> let heartbeat_p... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! SQLite persistence for heartbeat task execution history.
//!
//! Mirrors the `cron/store.rs` pattern: fresh connection per call, schema
//! auto-created, output truncated, history pruned to a configurable limit.
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use rusqlite::{Connection, pa... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use async_trait::async_trait;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::hooks::traits::HookHandler;
use zeroclaw_api::tool::ToolResult;
/// Logs tool calls for auditing.
pub struct CommandLoggerHook {
log: Arc<Mutex<Vec<String>>>,
}
impl Default for CommandLoggerHook {
fn... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>udit;
pub use command_logger::CommandLoggerHook;
pub use webhook_audit::WebhookAuditHook;
<|fim_prefix|>pub mod co<|fim_middle|>mmand_logger;
pub mod webhook_a<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::hooks::traits::{HookHandler, HookResult};
use zeroclaw_api::tool::ToolResult;
use zeroclaw_config::schema::WebhookAuditConfig;
/// Va... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub mod builtin;
mo<|fim_suffix|>{HookHandler, HookResult};
<|fim_middle|>d runner;
mod traits;
pub use runner::HookRunner;
// HookHandler and HookResult are part of the crate's public hook API surface.
// They may appear unused internally but are intentionally re-exported for
// external integrations an... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use std::time::Duration;
use futures_util::{FutureExt, future::join_all};
use serde_json::Value;
use std::panic::AssertUnwindSafe;
use zeroclaw_api::channel::ChannelMessage;
use zeroclaw_api::model_provider::{ChatMessage, ChatResponse};
use zeroclaw_api::tool::ToolResult;
use super::traits::{HookHandle... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub use zerocla<|fim_suffix|>k::*;
<|fim_middle|>w_api::hoo<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>e.home_dir().join(".zeroclaw/config.toml"));
candidates.push(base.config_dir().join("zeroclaw/config.toml"));
}
for path in &candidates {
if let Ok(contents) = std::fs::read_to_string(path) {
return contents.parse().ok();
}
}
None
}
fn locale_from_confi... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>or hobby in hobbies {
let _ = writeln!(prompt, "- {}", hobby);
}
}
if let Some(ref favorites) = interests.favorites
&& !favorites.is_empty()
{
prompt.push_str("\n**Favorites:**\n");
let mut sorted_keys: Vec<_> = favor... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub mod platform;
pub mod registry;
use anyhow::Result;
use zeroclaw_config::schema::Config;
/// Integration status
///
/// Two states only: an integration is either configured (`Active`) or it
/// exists in the schema but isn't configured (`Available`). There is no
/// "coming soon" state — if it is no... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Compile-time platform availability constants.
//!
//! The integrations registry iterates `PLATFORMS` to surface the
//! "Platforms" category. Each row is `(display_name, available)` where
//! `available` is computed from `cfg!(target_os = ...)`. There is no
//! schema for which OSes Rust can target — ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> assert!(
!entry.description.is_empty(),
"channel {:?} missing description text",
info.name,
);
}
}
#[test]
fn telegram_active_when_configured() {
let mut config = Config::default();
config.channels.telegram.... | fim | zeroclaw-labs/zeroclaw | rust |
#![allow(
clippy::to_string_in_format_args,
clippy::useless_format,
clippy::manual_inspect
)]
//! Agent runtime — orchestration, security, observability, cron, SOP, skills, hardware, and more.
pub mod cli_input;
pub mod identity;
pub mod migration;
pub mod util;
pub mod agent;
pub mod approval;
pub mod br... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>();
assert_eq!(target_mem.count().await.unwrap(), 0);
}
#[test]
fn migration_target_rejects_none_backend() {
let target = TempDir::new().unwrap();
let mut config = test_config(target.path());
config.memory.backend = "none".to_string();
let err = target... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ransport::NodeTransport;
<|fim_prefix|>pub mod trans<|fim_middle|>port;
pub use t<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>/ Sends authenticated HTTPS requests to peer nodes.
///
/// Every outgoing request carries three custom headers:
/// - `X-ZeroClaw-Timestamp` — unix epoch seconds
/// - `X-ZeroClaw-Nonce` — random UUID v4
/// - `X-ZeroClaw-Signature` — HMAC-SHA256 hex digest
///
/// Incoming requests are verified with the... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>)
.collect();
let mttr = if recoveries_in_window.is_empty() {
None
} else {
let count = u32::try_from(recoveries_in_window.len()).unwrap_or(u32::MAX);
let total: Duration = recoveries_in_window.iter().map(|r| r.duration).sum();
So... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use super::traits::{Observer, ObserverEvent, ObserverMetric};
use std::any::Any;
/// Log-based observer — uses tracing, zero external deps
pub struct LogObserver;
impl Default for LogObserver {
fn default() -> Self {
Self::new()
}
}
impl LogObserver {
pub fn new() -> Self {
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub mod dora;
pub mod log;
pub mod multi;
pub mod noop;
#[cfg(feature = "observability-otel")]
pub mod otel;
#[cfg(feature = "observability-prometheus")]
pub mod prometheus;
pub mod runtime_trace;
pub mod traits;
pub mod verbose;
#[allow(unused_imports)]
pub use self::log::LogObserver;
#[allow(unused_imp... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use super::traits::{Observer, ObserverEvent, ObserverMetric};
use std::any::Any;
/// Combine multiple <|fim_suffix|>e std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
/// Test observer that counts calls
struct CountingObserver {
event_count... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> agent_alias: None,
turn_id: None,
});
obs.record_event(&ObserverEvent::AgentEnd {
model_provider: "test".into(),
model: "test".into(),
duration: Duration::from_millis(100),
tokens_used: None,
cost_usd: Some(0.001),
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> turn_id,
} => {
let parent_cx = self.parent_cx_for(turn_id.as_deref());
let mut span = tracer.build_with_context(
opentelemetry::trace::SpanBuilder::from_name("llm.request")
.with_kind(SpanKind::Client)
... | fim | zeroclaw-labs/zeroclaw | rust |
use super::traits::{Observer, ObserverEvent, ObserverMetric};
use prometheus::{
Encoder, GaugeVec, Histogram, HistogramOpts, HistogramVec, IntCounterVec, Registry, TextEncoder,
};
use std::sync::{Arc, OnceLock};
/// Prometheus-backed observer — exposes metrics for scraping via `/metrics`.
pub struct PrometheusObse... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>rom_config(&to_log_config(config), workspace_dir);
}
/// Resolve the configured log path (used by the doctor command).
pub fn resolve_trace_path(
config: &zeroclaw_config::schema::ObservabilityConfig,
workspace_dir: &Path,
) -> std::path::PathBuf {
let policy = zeroclaw_log::ResolvedPolicy::f... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ic = metric.clone();
assert!(matches!(cloned_event, ObserverEvent::ToolCall { .. }));
assert!(matches!(cloned_metric, ObserverMetric::RequestLatency(_)));
}
}
<|fim_prefix|>pub use zeroclaw_api::observability_traits::*;
#[allow(unused_imports)]
pub use async_trait::async_trait;
#[cf... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>use super::traits::{Observer, ObserverEvent, ObserverMetric};
use std::any::Any;
/// Human-readable progress observer for interactive CLI sessions.
///
/// This observer prints compact `>` / `<` progress lines without exposing
/// prompt contents. It is intended to be opt-in (e.g. `--verbose`).
pub struc... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Peer-group runtime resolution.
//!
//! Given a `Config` and an `agent_alias`, produces the effective set
//! of peers that agent should accept inbound messages from on its
//! configured channels. The schema-side primitive is the
//! `[peer_groups.<name>]` block in `zeroclaw-config::multi_agent`;
//! ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub use zeroclaw_config::platform::*;
#[cfg(test)]
mod tests {
use super::*;
use zeroclaw_config::schema::RuntimeConfig;
#[test]
fn factory_native() {
let cfg = RuntimeConfig {
kind: "native".into(),
..RuntimeConfig::default()
};
let rt = c... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>n default_memory_budget_is_zero() {
let runtime = DummyRuntime;
assert_eq!(runtime.memory_budget(), 0);
}
#[test]
fn runtime_reports_capabilities() {
let runtime = DummyRuntime;
assert_eq!(runtime.name(), "dummy-runtime");
assert!(runtime.has_shell_acc... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! WASM sandbox runtime — in-process tool isolation via `wasmi`.
//!
//! Provides capability-based sandboxing without Docker or external runtimes.
//! Each WASM module runs with:
//! - **Fuel limits**: prevents infinite loops (each instruction costs 1 fuel)
//! - **Memory caps**: configurable per-module ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> fn cpu_percent_filled_on_second_sample() {
let _ = sample();
std::thread::sleep(std::time::Duration::from_millis(20));
for _ in 0..10_000 {
std::hint::black_box(0u64);
}
let s2 = sample();
assert!(
s2.cpu_percent.is_some(),
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Quickstart apply path.
//!
//! Single entry point both surfaces (web gateway, zerocode RPC, CLI)
//! call to land a [`BuilderSubmission`] into the live [`Config`]. The
//! runtime never enumerates channel types, provider types, or storage
//! backends itself — every write goes through `Config::set_pro... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! RAG pipeline for hardware datasheet retrieval.
//!
//! Supports:
//! - Markdown and text datasheets (always)
//! - PDF ingestion (with `rag-pdf` feature)
//! - Pin/alias tables (e.g. `red_led: 13`) for explicit lookup
//! - Keyword retrieval (default) or semantic search via embeddings (optional)
use ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Routines engine — event-triggered automation with pattern matching and
//! cooldown enforcement.
//!
//! A **routine** is a lightweight automation rule: when an event matches one of
//! its patterns, the associated action fires (provided cooldown has elapsed).
//! The engine bridges channel messages, ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Event pattern matching for the routines engine.
//!
//! Supports three match strategies: exact, glob, and regex. Each routine
//! declares one or more [`EventPattern`]s; an incoming [`RoutineEvent`] fires
//! the routine when **any** pattern matches.
use serde::{Deserialize, Serialize};
/// How a p... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>n jobs). Each routine supports per-routine cooldown
//! to prevent rapid re-triggering.
//!
//! ## Loading
//!
//! Routines are defined in `routines.toml` in the workspace root:
//!
//! ```toml
//! [[routines]]
//! name = "deploy-notify"
//! description = "Notify Slack on deploy webhook"
//! cooldown_sec... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>t_eq!(v["method"], "session/update");
assert_eq!(v["params"]["type"], "approval_request");
assert_eq!(v["params"]["session_id"], "sess-1");
assert_eq!(v["params"]["tool_name"], "shell");
let request_id = v["params"]["request_id"].as_str().unwrap().to_string();
pend... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> clipboard_image() {
use base64::{Engine, engine::general_purpose::STANDARD};
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path().to_string_lossy().to_string();
let store = setup_store(&ws).await;
let png_bytes = b"fake-png-data";
let entry = FileE... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>e,
reload_tx: None,
approval_pending: Arc::new(ApprovalPendingMap::default()),
tui_registry: Arc::new(TuiRegistry::new_unsigned()),
acp_session_store,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::oneshot;
use zerocl... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Filesystem RPC methods for remote directory browsing (WSS ACP CWD picker).
//!
//! These methods are only available to authe<|fim_suffix|>ta = match entry.metadata() {
Ok(m) => m,
Err(_) => continue,
};
let name = entry.file_name().to_string_lossy().to_string();... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>ead_info(&wt).unwrap();
assert_eq!(info.branch.as_deref(), Some("feature"));
assert_eq!(info.hash.as_deref(), Some("4a8f597"));
}
#[test]
fn no_git_returns_none() {
let td = TempDir::new().unwrap();
assert_eq!(branch_for(td.path()), None);
}
#[test]
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>kio::net::UnixStream::connect(&sock_path).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
assert_eq!(count.load(Ordering::Relaxed), 2);
drop(s1);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
assert_eq!(count.load(O... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Locale RPC methods: serve the in-memory locale registry and fetch
//! translated FTL catalogues from upstream.
//!
//! `locales/list` returns the build's embedded `locales.toml` registry — no
//! file read, no network. `locales/fetch` downloads catalogue bytes from the
//! upstream repository (URL bui... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Transport-agnostic JSON-RPC 2.0 dispatch for the runtime. See #6837.
pub mod appro<|fim_suffix|> dispatch;
pub mod fs;
pub mod git;
pub mod local;
pub mod locales;
pub mod session;
pub mod transport;
pub mod tui_identity;
pub mod turn;
pub mod types;
pub mod wss;
<|fim_middle|>val_channel;
pub mod at... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> ids.sort();
assert_eq!(ids, vec!["a", "b"]);
}
#[tokio::test]
async fn touch_updates_last_active() {
let store = make_store(4);
store
.insert(
"s1".into(),
RpcSession::new(make_agent(), "a", ".", crate::rpc::types::ChatMod... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>sport: Send + 'static {
fn writer(&self) -> mpsc::Sender<String>;
async fn next_frame(&mut self) -> Option<String>;
fn peer_label(&self) -> String;
}
<|fim_prefix|>//! Trans<|fim_middle|>port trait for RPC connections.
use async_trait::async_trait;
use tokio::sync::mpsc;
#[async_trait]
pub t... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! TUI session identity — UID generation, HMAC signing, and live
//! connection registry.
//!
//! **Source of truth** for connected TUI state. The `TuiRegistry` lives
//! on [`super::context::RpcContext`] and is the single canonical location
//! for "which TUIs are connected right now." Nothing else stor... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Shared turn execution. Single source of truth for spawn-drain-cancel.
use crate::agent::agent::{Agent, StreamedTurnError, StreamedTurnSuccess, TurnEvent};
use crate::agent::loop_::is_tool_loop_cancelled;
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use tokio_util::sync::CancellationToken;
use ... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> bundle: String,
pub name: String,
}
}
rpc_type! {
/// Consolidates gateway `SkillReadResponse`.
pub struct SkillsReadResult {
pub bundle: String,
pub name: String,
pub frontmatter: SkillFrontmatter,
pub body: String,
}
}
rpc_type! {
pub struct... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! WebSocket Secure (WSS) transport for the RPC layer.
//!
//! Mirrors the Unix socket transport (`unix.rs`) but uses TLS-encrypted
//! WebSocket connections, enabling remote TUI-to-daemon connectivity.
use super::context::RpcContext;
use super::dispatch::RpcDispatcher;
use super::transport::RpcTranspor... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Audit logging for security events
//!
//! Each audit entry is chained via a Merkle hash: `entry_hash = SHA-256(prev_hash || canonical_json)`.
//! This makes the trail tamper-evident — modifying any entry invalidates all subsequent hashes.
use anyhow::{Result, bail};
use chrono::{DateTime, Utc};
use p... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|> // `cargo`) can find the ELF interpreter and shared libraries inside the
// sandbox.
let sandbox = BubblewrapSandbox;
let mut cmd = Command::new("echo");
sandbox.wrap_command(&mut cmd).unwrap();
let args: Vec<String> = cmd
.get_args()
.... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_suffix|>);
}
#[test]
fn auto_mode_detects_something() {
let sandbox_cfg = SandboxConfig {
enabled: None, // Auto-detect
backend: SandboxBackend::Auto,
firejail_args: Vec::new(),
};
let sandbox = create_sandbox(&sandbox_cfg, "", None);
... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Docker sandbox (<|fim_suffix|>)),
"must include -v bind-mount flag when workspace is configured"
);
let ws_str = ws.to_string_lossy();
let expected = format!("{ws_str}:{ws_str}:ro");
assert!(
args.contains(&expected),
"bind-mount spec... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>pub u<|fim_suffix|>::domain_matcher::*;
<|fim_middle|>se zeroclaw_config<|endoftext|> | fim | zeroclaw-labs/zeroclaw | rust |
use crate::security::domain_matcher::DomainMatcher;
use crate::security::otp::OtpValidator;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use zeroclaw_config::schema::EstopConfig;
#[derive(Debug, Clone, PartialE... | fim | zeroclaw-labs/zeroclaw | rust |
<|fim_prefix|>//! Firejail sandbox (Linux user-space sandboxing)
//!
//! Firejail is a SUID sandbox program that Linux applications use to sandbox themselves.
use crate::security::traits::Sandbox;
use std::process::Command;
/// Firejail sandbox backend for Linux
#[derive(Debug, Clone, Default)]
pub struct FirejailSan... | 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.