text
stringlengths
14
100k
source
stringclasses
1 value
repo
stringclasses
810 values
language
stringclasses
13 values
<|fim_prefix|>//! Interactive hardware onboarding wizard UI. //! //! Provides [`run_setup`] — the hardware step of the ZeroClaw onboarding //! wizard. The function is intended to be registered as //! `WizardCallbacks::hardware_setup` from the binary crate. use anyhow::Result; use console::style; use dialoguer::{Confir...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! ACP session persistence. //! //! Storage shape: //! //! ```text //! acp_sessions //! ├── acp_messages (FK by integer id) //! │ └── acp_tool_calls (FK by integer id, two rows per call: //! │ one event_kind='in', one 'out') //! └── acp_session_events //! ``` //! //! ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>await.unwrap(), "hi alice"); assert_eq!(rx_b.await.unwrap(), "hi bob"); } } <|fim_prefix|>//! Inbound message debouncing for rapid senders. //! //! When users type fast and send multiple messages in quick succession, each //! message would normally trigger a separate LLM call. [`MessageDebounc...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> #[test] fn make_session_backend_unknown_value_falls_back_to_sqlite() { let tmp = TempDir::new().unwrap(); let backend = make_session_backend(tmp.path(), "totally-not-a-backend").unwrap(); backend.append("k1", &user_msg("hello-fallback")).unwrap(); let db = tmp.path(...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Trait abstraction for session persistence backends. //! //! Backends store per-sender conversation histories. The trait is intentionally //! minimal — load, append, remove_last, clear_messages, list — so that JSONL //! and SQLite (and future backends) share a common interface. use chrono::{DateTime, ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Per-session actor queue for serializing concurrent access. //! //! Each session gets at most one concurrent turn. Additional requests queue up //! (bounded by `max_queue_depth`) and proceed in FIFO order. This prevents //! SQLite history corruption from overlapping writes and ensures consistent //! se...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>k(); let old_time = (Utc::now() - Duration::seconds(600)).to_rfc3339(); conn.execute( "UPDATE session_metadata SET state = 'running', turn_id = 'old', turn_started_at = ?1 WHERE session_key = 's1'", params![old_time], ).unwrap(); ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! JSONL-based session persistence for channel conversations. //! //! Each session (keyed by `channel_sender` or `channel_thread_sender`) is stored //! as an append-only JSONL file in `{workspace}/sessions/`. Messages are appended //! one-per-line as JSON, never modifying old lines. On daemon restart, se...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>doesn't immediately // fire. self.touch(); let last_event = Arc::clone(&self.last_event); let timeout = self.timeout_secs; let poll_interval = std::time::Duration::from_secs((timeout / 2).max(1)); let handle = zeroclaw_spawn::spawn!(async move { ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> room_id: Some("changed-room"), sender_id: None, }, ) .expect("second call"); let after = conn .query_row( "SELECT channel_id, room_id, sender_id FROM session_metadata WHERE session_key = ?1", rusqlite::params!...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> let value = rx.recv().await.unwrap(); assert_eq!(value["ping"], true); let _guard = HOOK_TEST_LOCK.lock(); clear_broadcast_hook(); assert!(current_broadcast_hook().is_none()); } } <|fim_prefix|>//! Process-wide broadcast channel for the canonical log stream. //! //! ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>r); assert!(s.contains("processing turn")); assert!(s.contains("failed to dial provider")); assert!(s.contains("connection refused")); } } <|fim_prefix|>//! Anyhow error-chain rendering helper. //! //! Centralizes the `format!("{err:#}")` invocation so future evolution //! (e.g...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>ed_policy_respects_denylist() { let mut c = make_config(); c.log_tool_io_denylist = vec!["memory_recall_personal".to_string()]; let p = ResolvedPolicy::from_config(&c, std::path::Path::new("/")); assert!(p.is_tool_denylisted("memory_recall_personal")); assert!(!p.is...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Canonical event schema. OTel logs data model + ECS attribute //! conventions, with a `zeroclaw.*` namespace for the alias-bound //! domain attribution fields. //! //! On-disk JSON shape is the canonical contract — third-party tail //! consumers parse `serde_json::Value` and walk the keys. This struct ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>unwrap_or(false) { let zc = value.get("zeroclaw").expect("zeroclaw block present"); assert_eq!( zc.get("channel").and_then(|v| v.as_str()), Some("telegram.clamps"), ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>o a role. pub use ::tracing::{debug_span, error_span, info_span, trace_span, warn_span}; /// Span field helpers (e.g. [`field::Empty`] for fields that get /// recorded later via `span.record(...)`). pub mod field { pub use ::tracing::field::{Empty, FieldSet}; } pub use migrate::migrate_legacy_jsonl_...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>event.duration_ms_or_zero(), zc_file = %file!(), zc_line = %line!(), message = %$msg, ); }}; } /// Open an attribution span for the given `Attributable` thing. Every /// `record!` emitted while the returned span is entered inherits the /// thing's role + al...
fim
zeroclaw-labs/zeroclaw
rust
//! One-shot, streaming, in-place migration from schema_version 1 rows //! to schema_version 2. //! //! RAM contract: pure streaming. Read one line, parse, convert, write //! one line to a temp file. Bounded by a single line's allocation //! regardless of file size. Atomic rename at the end. use std::fs::{self, File, ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>der, model, messages_count, channel, agent_alias, turn_id, } => { assert_eq!(model_provider, "anthropic"); assert_eq!(model, "claude-sonnet-4-6"); assert_eq!(*message...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> } <|fim_prefix|>//! Paginated stream reader for the JSONL log file. //! //! RAM contract: at any moment, in-memory state is bounded by `limit` //! (the number of events the caller asked for) plus a single-line read //! buffer. We do NOT slurp the whole file into a `String`. //! //! The pagination model i...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> attribution .get("agent_alias") .or_else(|| attribution.get("channel")) .map(str::to_string) }) }) }) .unwrap_or_else(|| "system...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> break; } acc.push(ch); } Some(ToolIoCapture { text: acc, original_bytes, truncated: true, }) } } } } #[allow(dea...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! JSONL append-only writer + rolling rotation. //! //! RAM contract: a single event lands in two allocations (the JSON line //! that goes to disk + the `serde_json::Value` clone that goes to the //! broadcast hook). Rolling rotation streams through `BufReader::lines` //! into a temp file rather than slu...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Runtime memory wrapper bound to one agent. //! //! Each agent holds its own per-agent backend instance (selected at //! agent creation via `[agents.<alias>.memory.backend]`, immutable //! thereafter). The wrapper sits directly on top of that instance and: //! //! - Stamps the bound agent's UUID on eve...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Cross-agent path-walk variant for Markdown-backed agents. //! //! The generic [`AgentScopedMemory`](crate::agent_scoped::AgentScopedMemory) //! relies on the inner backend filtering rows by `agent_id` at the //! storage layer. Markdown has no shared store: each agent's //! attribution IS its on-disk p...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Audit trail for memory operations. //! //! Provides a decorator `AuditedMemory<M>` that wraps any `Memory` backend //! and logs all operations to a `memory_audit` table. Opt-in via //! `[memory] audit_enabled = true`. use super::traits::{Memory, MemoryCategory, MemoryEntry, ProceduralMessage}; use as...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>#[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum MemoryBackendKind { Sqlite, Lucid, Postgres, Qdrant, Markdown, None, Unknown, } #[allow(clippy::struct_excessive_bools)] #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct MemoryBackendProfile { pub key: &'static s...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>Chunk too long: {} chars", chunk.content.len() ); } } #[test] fn preserves_heading_in_split_sections() { let mut text = String::from("## Big Section\n"); for i in 0..100 { use std::fmt::Write; let _ = write!(text, "Li...
fim
zeroclaw-labs/zeroclaw
rust
//! Conflict resolution for memory entries. //! //! Before storing Core memories, performs a semantic similarity check against //! existing entries. If cosine similarity exceeds a threshold but content //! differs, the old entry is marked as superseded. use super::traits::{Memory, MemoryCategory, MemoryEntry}; /// Ch...
fim
zeroclaw-labs/zeroclaw
rust
//! LLM-driven memory consolidation. //! //! After each conversation turn, extracts structured information: //! - `history_entry`: A timestamped summary for the daily conversation log. //! - `memory_update`: New facts, preferences, or decisions worth remembering //! long-term (or `null` if nothing new was learned). /...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> (decayed - 0.25).abs() < 0.05, "score after two half-lives should be ~0.25, got {decayed}" ); } #[test] fn no_score_entry_is_unchanged() { let mut entries = vec![make_entry( MemoryCategory::Conversation, None, &days_ago...
fim
zeroclaw-labs/zeroclaw
rust
use async_trait::async_trait; /// Trait for embedding model_providers — convert text to vectors #[async_trait] pub trait EmbeddingProvider: Send + Sync { /// ModelProvider name fn name(&self) -> &str; /// Embedding dimensions fn dimensions(&self) -> usize; /// Embed a batch of texts into vectors ...
fim
zeroclaw-labs/zeroclaw
rust
use crate::policy::PolicyEnforcer; use anyhow::Result; use chrono::{DateTime, Duration, Local, NaiveDate, Utc}; use rusqlite::{Connection, params}; use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; use std::time::{Duration as StdDuration, SystemTime}; use zeroclaw_config::schema::MemoryC...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Heuristic importance scorer for non-LLM paths. //! //! Assigns importance scores (0.0–1.0) based on memory category and keyword //! signals. Used when LLM-based consolidation is unavailable or as a fast //! first-pass scorer. use super::traits::MemoryCategory; /// Base importance by category. fn cat...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>son, "L1", "C1", &[], None) .unwrap(); graph .add_node(NodeType::Lesson, "L2", "C2", &[], None) .unwrap(); let err = graph .add_node(NodeType::Lesson, "L3", "C3", &[], None) .unwrap_err(); assert!(err.to_string().contains(...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> ERROR, ::zeroclaw_log::Event::new(module_path!(), ::zeroclaw_log::Action::Fail) .with_outcome(::zeroclaw_log::EventOutcome::Failure), "pg knowledge graph thread terminated unexpectedly" ); anyhow::Error::msg("pg knowledge graph thread terminated...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>nfig { embedding_provider: "none".into(), embedding_model: "hint:semantic".into(), embedding_dimensions: 1536, ..MemoryConfig::default() }; let routes = vec![EmbeddingRouteConfig { hint: "semantic".into(), model_provid...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>read_to_string(&marker).await.unwrap_or_default(); assert_eq!(calls.lines().count(), 1); } } impl ::zeroclaw_api::attribution::Attributable for LucidMemory { fn role(&self) -> ::zeroclaw_api::attribution::Role { ::zeroclaw_api::attribution::Role::Memory(::zeroclaw_api::attribution...
fim
zeroclaw-labs/zeroclaw
rust
use super::traits::{Memory, MemoryCategory, MemoryEntry, is_recent_recall_query}; use async_trait::async_trait; use chrono::{DateTime, FixedOffset, Local, NaiveDate}; use std::path::{Path, PathBuf}; use tokio::fs; /// Decide whether a markdown entry's `timestamp` stem falls inside the /// recall `[since, until]` windo...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>orget("k").await.unwrap()); assert_eq!(memory.count().await.unwrap(), 0); assert!(memory.health_check().await); } } <|fim_prefix|>use super::traits::{Memory, MemoryCategory, MemoryEntry}; use async_trait::async_trait; /// Explicit no-op memory backend. /// /// This backend is used whe...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Policy engine for memory operations. //! //! Validates operations against configurable rules before they reach the //! backend. Enforces namespace quotas, category limits, read-only namespaces, //! and per-category retention rules. use super::traits::MemoryCategory; use zeroclaw_config::schema::Memor...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>_api::attribution::Attributable for PostgresMemory { fn role(&self) -> ::zeroclaw_api::attribution::Role { ::zeroclaw_api::attribution::Role::Memory(::zeroclaw_api::attribution::MemoryKind::Postgres) } fn alias(&self) -> &str { &self.alias } } #[cfg(test)] mod tests { ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use super::embeddings::EmbeddingProvider; use super::traits::{Memory, MemoryCategory, MemoryEntry, is_recent_recall_query}; use anyhow::{Context, Result}; use async_trait::async_trait; use chrono::Utc; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::sync::Arc; use tokio::sync:...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>esult.as_deref(), Some("answer v2")); let (count, _, _) = cache.stats().unwrap(); assert_eq!(count, 1); } #[test] fn unicode_prompt_handling() { let (_tmp, cache) = temp_cache(60); let key = ResponseCache::cache_key("gpt-4", None, "日本語のテスト 🦀"); cache...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Multi-stage retrieval pipeline. //! //! Wraps a `Memory` trait object with staged retrieval: //! - **Stage 1 (Hot cache):** In-memory LRU of recent recall results. //! - **Stage 2 (FTS):** FTS5 keyword search with optional early-return. //! - **Stage 3 (Vector):** Vector similarity search + hybrid mer...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>t: i64 = conn .query_row("SELECT COUNT(*) FROM memories", [], |row| row.get(0)) .unwrap(); assert_eq!(count, 2); let identity: String = conn .query_row( "SELECT content FROM memories WHERE key = 'identity'", [], ...
fim
zeroclaw-labs/zeroclaw
rust
pub use zeroclaw_api::memory_traits::*; <|endoftext|>
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>vectors() { let a = vec![0.0, 0.0]; let b = vec![0.0, 0.0]; assert!(cosine_similarity(&a, &b).abs() < f32::EPSILON); } // ── Edge cases: vec↔bytes serialization ────────────────────── #[test] fn bytes_to_vec_non_aligned_truncates() { // 5 bytes → only firs...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Integration tests for the SQLite multi-agent DB migration. //! //! Each test exercises the real `SqliteMemory::new` init path against a //! fresh `tempfile::TempDir`, which is what the runtime walks in //! production. The tests cover: //! //! - Fresh install: agents table created, default agent insert...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Plugin error types. use thiserror::Error; #[derive(Debug, Error)] pub enum PluginError { #[error("plugin not found: {0}")] NotFound(String), #[error("invalid manifest: {0}")] InvalidManifest(String), #[error("failed to load WASM module: {0}")] LoadFailed(String), #[err...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Plugin host: discovery, loading, lifecycle management. use super::error::PluginError; use super::signature::{self, SignatureMode, VerificationResult}; use super::{PluginCapability, PluginInfo, PluginManifest}; use std::collections::HashMap; use std::path::{Path, PathBuf}; /// Subdirectory inside a s...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>ath: Option<PathBuf>, pub loaded: bool, } <|fim_prefix|>//! WASM plugin system for ZeroClaw. //! //! Plugins are WebAssembly modules loaded via Extism that can extend //! ZeroClaw with custom tools and channels. Enable with `--features plugins-wasm`. pub mod error; pub mod host; pub mod runtime; pub ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Extism-based WASM execution bridge. //! //! Creates Extism plugin instances with permission-gated host functions //! (`zc_http_request`, `zc_env_read`) and calls plugin-exported functions //! (`tool_metadata`, `execute`). use crate::PluginPermission; use anyhow::{Context, Result}; use extism::*; use ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Ed25519 plugin signature verification. //! //! Uses `ring` (already a dependency) for Ed25519 signing and verification. //! Plugin manifests may include a base64url-encoded Ed25519 signature over //! the canonical manifest bytes (TOML content without the `signature` field). //! Publisher public keys a...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>ssage: &SendMessage) -> anyhow::Result<()> { // TODO: Wire to WASM plugin send function ::zeroclaw_log::record!( WARN, ::zeroclaw_log::Event::new(module_path!(), ::zeroclaw_log::Action::Note) .with_outcome(::zeroclaw_log::EventOutcome::Unknown), ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Bridge between WASM plugins and the Tool trait. use crate::PluginPermission; use crate::runtime; use async_trait::async_trait; use serde_json::Value; use std::path::PathBuf; use zeroclaw_api::attribution::ToolKind; use zeroclaw_api::tool::{Tool, ToolResult}; use zeroclaw_api::tool_attribution; tool_...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>et kind = detect_auth_kind("sk-ant-api-123", None); assert_eq!(kind, AnthropicAuthKind::ApiKey); } } <|fim_prefix|>use serde::{Deserialize, Serialize}; /// How Anthropic credentials should be sent. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "keba...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>/// Generic OAuth2 device-code flow and token refresh for IMAP email channels. /// /// Endpoint URLs and client IDs are supplied by the caller (via /// `[channels.email.<alias>.oauth2]` config) — this module contains no /// provider-specific constants. Microsoft Outlook and Google Workspace /// are both ...
fim
zeroclaw-labs/zeroclaw
rust
//! Google/Gemini OAuth2 authentication flow. //! //! Supports: //! - Authorization code flow with PKCE (loopback redirect) //! - Device code flow for headless environments //! //! Uses the same client credentials as Gemini CLI for compatibility. use crate::auth::oauth_common::{parse_query_params, url_decode, url_enco...
fim
zeroclaw-labs/zeroclaw
rust
pub mod anthropic_token; pub mod email_oauth2; pub mod gemini_oauth; pub mod oauth_common; pub mod openai_oauth; pub mod profiles; use crate::auth::openai_oauth::refresh_access_token; use crate::auth::profiles::{ AuthProfile, AuthProfileKind, AuthProfilesData, AuthProfilesStore, TokenSet, profile_id, }; use anyhow...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>3Dd"); } #[test] fn url_decode_basic() { assert_eq!(url_decode("hello"), "hello"); assert_eq!(url_decode("hello%20world"), "hello world"); assert_eq!(url_decode("hello+world"), "hello world"); assert_eq!(url_decode("a%3Db%26c%3Dd"), "a=b&c=d"); } #[tes...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use crate::auth::oauth_common::{parse_query_params, url_encode}; use crate::auth::profiles::TokenSet; use anyhow::{Context, Result}; use base64::Engine; use chrono::Utc; use reqwest::Client; use serde::Deserialize; use std::collections::BTreeMap; use std::time::{Duration, Instant}; use tokio::io::{AsyncR...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> p.refresh_token = Some(value); migrated = true; } if let Some(value) = id_migrated { p.id_token = Some(value); migrated = true; } if let Some(value) = token_migrated { p.token = Some(value); ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> _model: &str, temperature: Option<f64>, ) -> anyhow::Result<ProviderChatResponse> { let credential = self.credential.as_ref().ok_or_else(|| { ::zeroclaw_log::record!( ERROR, ::zeroclaw_log::Event::new(module_path!(), ::zeroclaw_log::...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! AWS Bedrock model_provider using the Converse API. //! //! Authentication: supports three methods: //! - **Bearer token**: set `BEDROCK_API_KEY` env var (takes precedence). //! - **SigV4 signing**: AWS AKSK (Access Key ID + Secret Access Key) //! via environment variables, `credential_process` in `~...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Per-family catalog source table. //! //! Reaches the model catalog for any provider family without constructing //! a live `ModelProvider` (which would require typed runtime context like //! Azure's `resource`/`deployment` or Bedrock's `region`). Used by the //! gateway's `/api/config/catalog/models` ...
fim
zeroclaw-labs/zeroclaw
rust
//! GitHub Copilot model_provider with OAuth device-flow authentication. //! //! Authenticates via GitHub's device code flow (same as VS Code Copilot), //! then exchanges the OAuth token for short-lived Copilot API keys. //! Tokens are cached to disk and auto-refreshed. //! //! **Note:** This uses VS Code's OAuth clien...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>er should build"); assert_eq!( zai.chat_with_system(None, "hello", "glm-5-turbo", Some(0.7)) .await .expect("zai chat should use overridden URL"), "ok" ); let glm_url = format!("{base_url}/glm/api/paas/v4"); let glm =...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>═════════════════════════════════════════════════════════════════════════════ #[derive(Debug, Serialize, Clone)] struct GenerateContentRequest { contents: Vec<Content>, #[serde(rename = "systemInstruction", skip_serializing_if = "Option::is_none")] system_instruction: Option<Content>, #[s...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>Self::supports_temperature(temperature) { anyhow::bail!( "temperature unsupported by Gemini CLI: {temperature}. \ Supported values: 0.7 or 1.0" ); } Ok(()) } fn redact_stderr(stderr: &[u8]) -> String { let text = Str...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Zhipu GLM model_provider with JWT authentication. //! The GLM API requires JWT tokens generated from the `id.secret` API key format //! with a custom `sign_type: "SIGN"` header, and uses `/v4/chat/completions`. use crate::traits::{ChatMessage, ModelProvider}; use async_trait::async_trait; use reqwest...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>lt.unwrap_err().to_string(); assert!( msg.contains("Failed to spawn KiloCLI binary"), "unexpected error message: {msg}" ); } } <|fim_prefix|>//! KiloCLI subprocess model_provider. //! //! Integrates with the KiloCLI tool, spawning the `kilo` binary //! as a subp...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> &self.alias } } <|fim_prefix|>use super::ModelProvider; use super::traits::{ ChatMessage, ChatRequest, ChatResponse, StreamChunk, StreamEvent, StreamOptions, StreamResult, }; use async_trait::async_trait; use futures_util::stream::BoxStream; pub struct ModelPinnedProvider { alias: String,...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>lter a parsed catalog for a model_provider key. Sorted, deduped. /// Pure — separated from the live fetch so it can be unit-tested. pub(crate) fn filter_models(catalog: &Catalog, provider_key: &str) -> Result<Vec<String>> { let entry = catalog.get(provider_key).ok_or_else(|| { ::zeroclaw_log::...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use base64::{Engine as _, engine::general_purpose::STANDARD}; use reqwest::Client; use std::collections::{HashMap, HashSet}; use std::path::Path; use zeroclaw_api::model_provider::ChatMessage; use zeroclaw_config::schema::{MultimodalConfig, build_runtime_proxy_client_with_timeouts}; const IMAGE_MARKER_PR...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> .and_then(serde_json::Value::as_str) .is_some_and(|content| { content.contains("## Tool Use Protocol") && content.contains("file_read") && content.contains("\"path\"") ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use crate::openai_codex::{ ResponsesStreamApiError, ResponsesStreamState, ResponsesToolSpec, append_utf8_stream_chunk, build_responses_input, convert_tools, first_nonempty, process_sse_chunk, }; use crate::stream_guard::AbortOnDrop; use crate::traits::{ ChatMessage, ChatRequest as ProviderChat...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use crate::ModelProviderRuntimeOptions; use crate::auth::AuthService; use crate::auth::openai_oauth::extract_account_id_from_jwt; use crate::multimodal; use crate::stream_guard::AbortOnDrop; use crate::traits::{ ChatMessage, ChatRequest as ProviderChatRequest, ChatResponse as ProviderChatResponse, ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> }, ToolSpec { name: "another-valid".into(), description: "Also valid".into(), parameters: serde_json::json!({"type": "object"}), }, ]; let result = OpenRouterModelProvider::convert_tools(Some(&tools)).unwrap(); ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Cross-vendor model catalog via OpenRouter's public `/api/v1/models` endpoint. //! //! Fallback for compat providers that don't have a `models.dev` entry and //! can't reach their native `/models` endpoint without a credential. Each //! OpenRouter model id is `<vendor>/<slug>`; we filter by vendor pref...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use super::ModelProvider; use super::traits::{ ChatMessage, ChatRequest, ChatResponse, StreamChunk, StreamEvent, StreamOptions, StreamResult, }; use async_trait::async_trait; use futures_util::stream::BoxStream; use std::collections::HashMap; /// Score a model against a user-keyed pricing map. Sums a...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Ties a spawned streaming-parser task's lifetime to the stream the consumer //! holds, so dropping the stream (turn cancel, timeout, client disconnect) //! aborts the task and releases its socket instead of leaking it. /// Aborts the wrapped task wh<|fim_suffix|> pub(crate) struct AbortOnDrop(tokio::t...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>on<&str>) -> Self { let resolved_key = resolve_telnyx_api_key(api_key); Self { alias: alias.to_string(), api_key: resolved_key, client: Client::builder() .timeout(std::time::Duration::from_secs(120)) .connect_timeout(std::...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>rovider::*; <|fim_prefix|>pub use zero<|fim_middle|>claw_api::model_p<|endoftext|>
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use zeroclaw_config::schema::QueryClassificationConfig; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClassificationDecision { pub hint: String, pub priority: i32, } /// Classify a user message against the configured rules and return the /// matching hint string, if any. /// /// Returns `Non...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use std::collections::HashSet; use zeroclaw_api::model_provider::ChatMessage; /// Signals extracted from conversation context to guide tool filtering. #[derive(Debug, Clone)] pub struct ContextS<|fim_suffix|> make_message("user", "hello"), make_message("assistant", "sure"), ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> maximum context length is 128000 tokens. However, your messages resulted in 150000 tokens."; assert_eq!(parse_context_limit_from_error(msg), Some(128_000)); } #[test] fn test_parse_context_limit_llamacpp() { let msg = "request (8968 tokens) exceeds the available context size ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>edup contract can be unit-tested with a caller-owned set instead of the /// process-static one. fn missing_pricing_first_sighting( seen: &Mutex<HashSet<(String, String)>>, model_provider: &str, model: &str, ) -> bool { seen.lock() .insert((model_provider.to_string(), model.to_strin...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use super::history::canonicalize_tool_result_media_markers; use crate::tools::{Tool, ToolSpec}; use serde_json::Value; use std::fmt::Write; use zeroclaw_providers::{ChatMessage, ChatResponse, ConversationMessage, ToolResultMessage}; #[derive(Debug, Clone)] pub struct ParsedToolCall { pub name: String...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>pub use zeroclaw_config::scattered_types::{AutoClassifyConfig, EvalConfig}; // ── Complexity estimation ─────────────────────────────────────── /// Coarse complexity tier for a user message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ComplexityTier { /// Short, simple query (greetings, ye...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use crate::agent::history_pruner::remove_orphaned_tool_messages; use anyhow::Result; use regex::Regex; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::LazyLock; use zeroclaw_providers::ChatMessage; /// Default trigger for auto-compaction when non-system message count exceeds this...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use zeroclaw_api::model_provider::ChatMessage; pub use zeroclaw_config::scattered_types::HistoryPrunerConfig; // --------------------------------------------------------------------------- // Stats // --------------------------------------------------------------------------- #[derive(Debug, Clone, Par...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>//! Loop detection guardrail for the agent tool-call loop. //! //! Monitors a sliding window of recent tool calls and their results to detect //! three repetitive patterns that indicate the agent is stuck: //! //! 1. **Exact repeat** — same tool + args called 3+ times consecutively. //! 2. **Ping-pong** —...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use async_trait::async_trait; use std::fmt::Write; use zeroclaw_memory::{self, MEMORY_CONTEXT_CLOSE, MEMORY_CONTEXT_OPEN, Memory, decay}; #[async_trait] pub trait MemoryLoader: Send + Sync { async fn load_context( &self, memory: &dyn Memory, user_message: &str, session...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use std::sync::Arc; use zeroclaw_api::memory_traits::{Memory, MemoryStrategy}; use zeroclaw_api::model_provider::ModelProvider; use crate::agent::memory_loader::{DefaultMemoryLoader, MemoryLoader}; /// Default memory strategy that delegates to existing implementations. /// /// Phase 1: This is a thin wr...
fim
zeroclaw-labs/zeroclaw
rust
#[allow(clippy::module_inception)] pub mod agent; pub mod classifier; pub mod context_analyzer; pub mod context_compressor; pub mod cost; pub mod dispatcher; pub mod eval; pub mod history; pub mod history_pruner; pub mod loop_; pub mod loop_detector; pub mod memory_loader; pub mod memory_strategy; pub mod personality; ...
fim
zeroclaw-labs/zeroclaw
rust
//! Personality system — loads workspace identity files (SOUL.md, IDENTITY.md, //! USER.md) and injects them into the system prompt pipeline. //! //! Ported from RustyClaw `src/agent/personality.rs`. The loader reads markdown //! files from the workspace root, validates size limits, and produces a //! [`PersonalityPro...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|> `None` when /// the filename is outside the editable allowlist (or when MEMORY.md /// is requested with `include_memory = false`). /// /// `BOOTSTRAP.md` is intentionally not rendered — it's a first-run /// scaffold the agent reads once and deletes; the dashboard editor /// doesn't expose it. The origina...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_prefix|>use crate::agent::personality; use crate::identity; use crate::security::AutonomyLevel; use crate::skills::Skill; use crate::tools::Tool; use anyhow::Result; use chrono::{Datelike, Local}; use std::fmt::Write; use std::path::Path; use zeroclaw_config::schema::IdentityConfig; pub struct PromptContext<'a> ...
fim
zeroclaw-labs/zeroclaw
rust
<|fim_suffix|>mary"), "unexpected response: {}", outcome.response ); let last_chat = outcome .new_messages .iter() .rev() .find_map(|m| match m { ConversationMessage::Chat(c) => Some(c), _ => None, }) .expect("new_messages m...
fim
zeroclaw-labs/zeroclaw
rust