Compare commits
102 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e387f58579 | |||
| fa06798926 | |||
| a4cd4b287e | |||
| 3ce7f2345e | |||
| eb9dfc04b4 | |||
| 9cc74a2698 | |||
| 133dc46b41 | |||
| ad03605cad | |||
| ae1acf9b9c | |||
| cc91f22e9b | |||
| 030f5fe288 | |||
| c47bbcc972 | |||
| 72fbb22059 | |||
| cbb3d9ae92 | |||
| 8d1eebad4d | |||
| 0fdd1ad490 | |||
| 86bc60fcd1 | |||
| 4837e1fe73 | |||
| 985977ae0c | |||
| 72b10f12dd | |||
| 3239f5ea07 | |||
| 3353729b01 | |||
| b6c2930a70 | |||
| 181cafff70 | |||
| d87f387111 | |||
| 7068079028 | |||
| a9b511e6ec | |||
| 65cb4fe099 | |||
| 0d28cca843 | |||
| 7ddd2aace3 | |||
| c7b3b762e0 | |||
| 4b00e8ba75 | |||
| 2e48cbf7c3 | |||
| e4910705d1 | |||
| 1b664143c2 | |||
| 950f996812 | |||
| b74c5cfda8 | |||
| 02688eb124 | |||
| 2c92cf913b | |||
| 3c117d2d7b | |||
| 1f7c3c99e4 | |||
| 92940a3d16 | |||
| d77c616905 | |||
| ac12470c27 | |||
| c5a1148ae9 | |||
| 440ad6e5b5 | |||
| 2e41cb56f6 | |||
| 2227fadb66 | |||
| 162efbb49c | |||
| 3c8b6d219a | |||
| 58b98c59a8 | |||
| d72e9379f7 | |||
| 959b933841 | |||
| caf7c7194f | |||
| ee7d542da6 | |||
| d51ec4b43f | |||
| 3d92b2a652 | |||
| 3255051426 | |||
| dcaf330848 | |||
| 7f8de5cb17 | |||
| 1341cfb296 | |||
| 9da620a5aa | |||
| d016e6b1a0 | |||
| 9b6360ad71 | |||
| dc50ca9171 | |||
| 67edd2bc60 | |||
| dcf66175e4 | |||
| b3bb79d805 | |||
| c857b64bb4 | |||
| c051f0323e | |||
| dea5c67ab0 | |||
| a14afd7ef9 | |||
| 4455b24056 | |||
| 8ec6522759 | |||
| a818edb782 | |||
| e0af3d98dd | |||
| 48bdbde26c | |||
| dc495a105f | |||
| fe9addcfe0 | |||
| 5bfa5f18e1 | |||
| 72b7e1e647 | |||
| 413c94befe | |||
| 5aa6026fa1 | |||
| 6eca841bd7 | |||
| 50e8d4f5f8 | |||
| fc2aac7c94 | |||
| 4caa3f7e6f | |||
| 3bc6ec3cf5 | |||
| f3fbd1b094 | |||
| 79e8252d7a | |||
| 924521c927 | |||
| 07ca270f03 | |||
| e08091a2e2 | |||
| 1f1123d071 | |||
| d5bc46238a | |||
| 843973762a | |||
| 5f8d7d7347 | |||
| 7b3bea8d01 | |||
| ac461dc704 | |||
| f04e56d9a1 | |||
| 1d6f482b04 | |||
| ba6d0a4df9 |
@@ -0,0 +1,10 @@
|
||||
# cargo-audit configuration
|
||||
# https://rustsec.org/
|
||||
|
||||
[advisories]
|
||||
ignore = [
|
||||
# wasmtime vulns via extism 1.13.0 — no upstream fix; plugins feature-gated
|
||||
"RUSTSEC-2026-0006", # wasmtime f64.copysign segfault on x86-64
|
||||
"RUSTSEC-2026-0020", # WASI guest-controlled resource exhaustion
|
||||
"RUSTSEC-2026-0021", # WASI http fields panic
|
||||
]
|
||||
@@ -64,3 +64,12 @@ LICENSE
|
||||
*.profdata
|
||||
coverage
|
||||
lcov.info
|
||||
|
||||
# Firmware and hardware crates (not needed for Docker runtime)
|
||||
firmware/
|
||||
crates/robot-kit/
|
||||
|
||||
# Application and script directories (not needed for Docker runtime)
|
||||
apps/
|
||||
python/
|
||||
scripts/
|
||||
|
||||
@@ -74,4 +74,4 @@ jobs:
|
||||
if [ -n "${{ matrix.linker_env || '' }}" ] && [ -n "${{ matrix.linker || '' }}" ]; then
|
||||
export "${{ matrix.linker_env }}=${{ matrix.linker }}"
|
||||
fi
|
||||
cargo build --release --locked --target ${{ matrix.target }}
|
||||
cargo build --release --locked --features channel-matrix,channel-lark,memory-postgres --target ${{ matrix.target }}
|
||||
|
||||
@@ -134,15 +134,27 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Set up SSH key — normalize line endings and ensure trailing newline
|
||||
mkdir -p ~/.ssh
|
||||
echo "$AUR_SSH_KEY" > ~/.ssh/aur
|
||||
chmod 700 ~/.ssh
|
||||
printf '%s\n' "$AUR_SSH_KEY" | tr -d '\r' > ~/.ssh/aur
|
||||
chmod 600 ~/.ssh/aur
|
||||
cat >> ~/.ssh/config <<SSH_CONFIG
|
||||
|
||||
cat > ~/.ssh/config <<'SSH_CONFIG'
|
||||
Host aur.archlinux.org
|
||||
IdentityFile ~/.ssh/aur
|
||||
User aur
|
||||
StrictHostKeyChecking accept-new
|
||||
SSH_CONFIG
|
||||
chmod 600 ~/.ssh/config
|
||||
|
||||
# Verify key is valid and print fingerprint for debugging
|
||||
echo "::group::SSH key diagnostics"
|
||||
ssh-keygen -l -f ~/.ssh/aur || { echo "::error::AUR_SSH_KEY is not a valid SSH private key"; exit 1; }
|
||||
echo "::endgroup::"
|
||||
|
||||
# Test SSH connectivity before attempting clone
|
||||
ssh -T -o BatchMode=yes -o ConnectTimeout=10 aur@aur.archlinux.org 2>&1 || true
|
||||
|
||||
tmp_dir="$(mktemp -d)"
|
||||
git clone ssh://aur@aur.archlinux.org/zeroclaw.git "$tmp_dir/aur"
|
||||
|
||||
@@ -16,6 +16,7 @@ env:
|
||||
CARGO_TERM_COLOR: always
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
RELEASE_CARGO_FEATURES: channel-matrix,channel-lark,memory-postgres
|
||||
|
||||
jobs:
|
||||
version:
|
||||
@@ -213,7 +214,7 @@ jobs:
|
||||
if [ -n "${{ matrix.linker_env || '' }}" ] && [ -n "${{ matrix.linker || '' }}" ]; then
|
||||
export "${{ matrix.linker_env }}=${{ matrix.linker }}"
|
||||
fi
|
||||
cargo build --release --locked --target ${{ matrix.target }}
|
||||
cargo build --release --locked --features "${{ env.RELEASE_CARGO_FEATURES }}" --target ${{ matrix.target }}
|
||||
|
||||
- name: Package (Unix)
|
||||
if: runner.os != 'Windows'
|
||||
@@ -330,6 +331,7 @@ jobs:
|
||||
> docker-ctx/zeroclaw-data/.zeroclaw/config.toml
|
||||
|
||||
cp Dockerfile.ci docker-ctx/Dockerfile
|
||||
cp Dockerfile.debian.ci docker-ctx/Dockerfile.debian
|
||||
|
||||
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
|
||||
@@ -349,15 +351,15 @@ jobs:
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:beta
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
# ── Post-publish: tweet after release + website are live ──────────────
|
||||
# Docker is slow (multi-platform) and can be cancelled by concurrency;
|
||||
# don't let it block the tweet.
|
||||
tweet:
|
||||
name: Tweet Release
|
||||
needs: [version, publish, redeploy-website]
|
||||
if: ${{ !cancelled() && needs.publish.result == 'success' }}
|
||||
uses: ./.github/workflows/tweet-release.yml
|
||||
with:
|
||||
release_tag: ${{ needs.version.outputs.tag }}
|
||||
release_url: https://github.com/zeroclaw-labs/zeroclaw/releases/tag/${{ needs.version.outputs.tag }}
|
||||
secrets: inherit
|
||||
- name: Build and push Debian compatibility image
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: docker-ctx
|
||||
file: docker-ctx/Dockerfile.debian
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.version.outputs.tag }}-debian
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:beta-debian
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
# Tweet removed — only stable releases should tweet (see tweet-release.yml).
|
||||
|
||||
@@ -20,6 +20,7 @@ env:
|
||||
CARGO_TERM_COLOR: always
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
RELEASE_CARGO_FEATURES: channel-matrix,channel-lark,memory-postgres
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
@@ -214,7 +215,7 @@ jobs:
|
||||
if [ -n "${{ matrix.linker_env || '' }}" ] && [ -n "${{ matrix.linker || '' }}" ]; then
|
||||
export "${{ matrix.linker_env }}=${{ matrix.linker }}"
|
||||
fi
|
||||
cargo build --release --locked --target ${{ matrix.target }}
|
||||
cargo build --release --locked --features "${{ env.RELEASE_CARGO_FEATURES }}" --target ${{ matrix.target }}
|
||||
|
||||
- name: Package (Unix)
|
||||
if: runner.os != 'Windows'
|
||||
@@ -373,6 +374,7 @@ jobs:
|
||||
> docker-ctx/zeroclaw-data/.zeroclaw/config.toml
|
||||
|
||||
cp Dockerfile.ci docker-ctx/Dockerfile
|
||||
cp Dockerfile.debian.ci docker-ctx/Dockerfile.debian
|
||||
|
||||
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
|
||||
|
||||
@@ -392,6 +394,17 @@ jobs:
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
- name: Build and push Debian compatibility image
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
|
||||
with:
|
||||
context: docker-ctx
|
||||
file: docker-ctx/Dockerfile.debian
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.validate.outputs.tag }}-debian
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:debian
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
# ── Post-publish: package manager auto-sync ─────────────────────────
|
||||
scoop:
|
||||
name: Update Scoop Manifest
|
||||
|
||||
@@ -5,7 +5,7 @@ on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Release tag (e.g. v0.3.0 or v0.3.0-beta.42)"
|
||||
description: "Stable release tag (e.g. v0.3.0)"
|
||||
required: true
|
||||
type: string
|
||||
release_url:
|
||||
@@ -61,9 +61,10 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# For betas: find the PREVIOUS release tag to check for new features
|
||||
# Find the previous STABLE release tag (exclude betas) to check for new features
|
||||
PREV_TAG=$(git tag --sort=-creatordate \
|
||||
| grep -v "^${RELEASE_TAG}$" \
|
||||
| grep -vE '\-beta\.' \
|
||||
| head -1 || echo "")
|
||||
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
@@ -97,53 +98,37 @@ jobs:
|
||||
if [ -n "$MANUAL_TEXT" ]; then
|
||||
TWEET="$MANUAL_TEXT"
|
||||
else
|
||||
# For features: diff against the PREVIOUS release (including betas)
|
||||
# This prevents duplicate feature lists across consecutive betas
|
||||
PREV_RELEASE=$(git tag --sort=-creatordate \
|
||||
| grep -v "^${RELEASE_TAG}$" \
|
||||
| head -1 || echo "")
|
||||
|
||||
# For contributors: diff against the last STABLE release
|
||||
# This captures everyone across the full release cycle
|
||||
# Diff against the last STABLE release (exclude betas) to capture
|
||||
# ALL features accumulated across the full beta cycle
|
||||
PREV_STABLE=$(git tag --sort=-creatordate \
|
||||
| grep -v "^${RELEASE_TAG}$" \
|
||||
| grep -vE '\-beta\.' \
|
||||
| head -1 || echo "")
|
||||
|
||||
FEAT_RANGE="${PREV_RELEASE:+${PREV_RELEASE}..}${RELEASE_TAG}"
|
||||
CONTRIB_RANGE="${PREV_STABLE:+${PREV_STABLE}..}${RELEASE_TAG}"
|
||||
RANGE="${PREV_STABLE:+${PREV_STABLE}..}${RELEASE_TAG}"
|
||||
|
||||
# Extract NEW features only since the last release
|
||||
FEATURES=$(git log "$FEAT_RANGE" --pretty=format:"%s" --no-merges \
|
||||
# Extract ALL features since the last stable release
|
||||
FEATURES=$(git log "$RANGE" --pretty=format:"%s" --no-merges \
|
||||
| grep -iE '^feat(\(|:)' \
|
||||
| sed 's/^feat(\([^)]*\)): /\1: /' \
|
||||
| sed 's/^feat: //' \
|
||||
| sed 's/ (#[0-9]*)$//' \
|
||||
| sort -uf \
|
||||
| head -4 \
|
||||
| while IFS= read -r line; do echo "🚀 ${line}"; done || true)
|
||||
|
||||
if [ -z "$FEATURES" ]; then
|
||||
FEATURES="🚀 Incremental improvements and polish"
|
||||
fi
|
||||
|
||||
# Count ALL contributors across the full release cycle
|
||||
GIT_AUTHORS=$(git log "$CONTRIB_RANGE" --pretty=format:"%an" --no-merges | sort -uf || true)
|
||||
CO_AUTHORS=$(git log "$CONTRIB_RANGE" --pretty=format:"%b" --no-merges \
|
||||
| grep -ioE 'Co-Authored-By: *[^<]+' \
|
||||
| sed 's/Co-Authored-By: *//i' \
|
||||
| sed 's/ *$//' \
|
||||
| sort -uf || true)
|
||||
|
||||
TOTAL_COUNT=$(printf "%s\n%s" "$GIT_AUTHORS" "$CO_AUTHORS" \
|
||||
| sort -uf \
|
||||
| grep -v '^$' \
|
||||
| grep -viE '\[bot\]$|^dependabot|^github-actions|^copilot|^ZeroClaw Bot|^ZeroClaw Runner|^ZeroClaw Agent|^blacksmith' \
|
||||
| grep -c . || echo "0")
|
||||
FEAT_COUNT=$(echo "$FEATURES" | grep -c . || echo "0")
|
||||
|
||||
# Build tweet — new features, contributor count, hashtags
|
||||
TWEET=$(printf "🦀 ZeroClaw %s\n\n%s\n\n🙌 %s contributors\n\n%s\n\n#zeroclaw #rust #ai #opensource" \
|
||||
"$RELEASE_TAG" "$FEATURES" "$TOTAL_COUNT" "$RELEASE_URL")
|
||||
# Format top features with rocket emoji (limit to 6 for tweet space)
|
||||
FEAT_LIST=$(echo "$FEATURES" \
|
||||
| head -6 \
|
||||
| while IFS= read -r line; do echo "🚀 ${line}"; done || true)
|
||||
|
||||
if [ -z "$FEAT_LIST" ]; then
|
||||
FEAT_LIST="🚀 Incremental improvements and polish"
|
||||
fi
|
||||
|
||||
# Build tweet — feature-focused style
|
||||
TWEET=$(printf "🦀 ZeroClaw %s\n\n%s\n\nZero overhead. Zero compromise. 100%% Rust.\n\n#zeroclaw #rust #ai #opensource" \
|
||||
"$RELEASE_TAG" "$FEAT_LIST")
|
||||
fi
|
||||
|
||||
# X/Twitter counts any URL as 23 chars (t.co shortening).
|
||||
|
||||
Generated
+1296
-46
File diff suppressed because it is too large
Load Diff
+25
-11
@@ -4,7 +4,7 @@ resolver = "2"
|
||||
|
||||
[package]
|
||||
name = "zeroclawlabs"
|
||||
version = "0.4.3"
|
||||
version = "0.5.1"
|
||||
edition = "2021"
|
||||
authors = ["theonlyhennygod"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
@@ -14,15 +14,6 @@ readme = "README.md"
|
||||
keywords = ["ai", "agent", "cli", "assistant", "chatbot"]
|
||||
categories = ["command-line-utilities", "api-bindings"]
|
||||
rust-version = "1.87"
|
||||
|
||||
[[bin]]
|
||||
name = "zeroclaw"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
name = "zeroclaw"
|
||||
path = "src/lib.rs"
|
||||
|
||||
include = [
|
||||
"/src/**/*",
|
||||
"/build.rs",
|
||||
@@ -31,8 +22,17 @@ include = [
|
||||
"/LICENSE*",
|
||||
"/README.md",
|
||||
"/web/dist/**/*",
|
||||
"/tool_descriptions/**/*",
|
||||
]
|
||||
|
||||
[[bin]]
|
||||
name = "zeroclaw"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
name = "zeroclaw"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
# CLI - minimal and fast
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
@@ -53,6 +53,7 @@ matrix-sdk = { version = "0.16", optional = true, default-features = false, feat
|
||||
serde = { version = "1.0", default-features = false, features = ["derive"] }
|
||||
serde_json = { version = "1.0", default-features = false, features = ["std"] }
|
||||
serde_ignored = "0.1"
|
||||
serde_yaml = "0.9"
|
||||
|
||||
# Config
|
||||
directories = "6.0"
|
||||
@@ -82,6 +83,12 @@ nanohtml2text = "0.2"
|
||||
# Optional Rust-native browser automation backend
|
||||
fantoccini = { version = "0.22.1", optional = true, default-features = false, features = ["rustls-tls"] }
|
||||
|
||||
# Progress bars (update pipeline)
|
||||
indicatif = "0.17"
|
||||
|
||||
# Temp files (update pipeline rollback)
|
||||
tempfile = "3.26"
|
||||
|
||||
# Error handling
|
||||
anyhow = "1.0"
|
||||
thiserror = "2.0"
|
||||
@@ -183,6 +190,9 @@ probe-rs = { version = "0.31", optional = true }
|
||||
# PDF extraction for datasheet RAG (optional, enable with --features rag-pdf)
|
||||
pdf-extract = { version = "0.10", optional = true }
|
||||
|
||||
# WASM plugin runtime (extism)
|
||||
extism = { version = "1.9", optional = true }
|
||||
|
||||
# Terminal QR rendering for WhatsApp Web pairing flow.
|
||||
qrcode = { version = "0.14", optional = true }
|
||||
|
||||
@@ -205,7 +215,7 @@ landlock = { version = "0.4", optional = true }
|
||||
libc = "0.2"
|
||||
|
||||
[features]
|
||||
default = ["observability-prometheus", "channel-nostr"]
|
||||
default = ["observability-prometheus", "channel-nostr", "skill-creation"]
|
||||
channel-nostr = ["dep:nostr-sdk"]
|
||||
hardware = ["nusb", "tokio-serial"]
|
||||
channel-matrix = ["dep:matrix-sdk"]
|
||||
@@ -230,8 +240,12 @@ metrics = ["observability-prometheus"]
|
||||
probe = ["dep:probe-rs"]
|
||||
# rag-pdf = PDF ingestion for datasheet RAG
|
||||
rag-pdf = ["dep:pdf-extract"]
|
||||
# skill-creation = Autonomous skill creation from successful multi-step tasks
|
||||
skill-creation = []
|
||||
# whatsapp-web = Native WhatsApp Web client with custom rusqlite storage backend
|
||||
whatsapp-web = ["dep:wa-rs", "dep:wa-rs-core", "dep:wa-rs-binary", "dep:wa-rs-proto", "dep:wa-rs-ureq-http", "dep:wa-rs-tokio-transport", "dep:serde-big-array", "dep:prost", "dep:qrcode"]
|
||||
# WASM plugin system (extism-based)
|
||||
plugins-wasm = ["dep:extism"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z" # Optimize for size
|
||||
|
||||
+30
-27
@@ -1,9 +1,18 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
# ── Stage 0: Frontend build ─────────────────────────────────────
|
||||
FROM node:22-alpine AS web-builder
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/package-lock.json* ./
|
||||
RUN npm ci --ignore-scripts 2>/dev/null || npm install --ignore-scripts
|
||||
COPY web/ .
|
||||
RUN npm run build
|
||||
|
||||
# ── Stage 1: Build ────────────────────────────────────────────
|
||||
FROM rust:1.94-slim@sha256:da9dab7a6b8dd428e71718402e97207bb3e54167d37b5708616050b1e8f60ed6 AS builder
|
||||
|
||||
WORKDIR /app
|
||||
ARG ZEROCLAW_CARGO_FEATURES="memory-postgres"
|
||||
|
||||
# Install build dependencies
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
@@ -14,43 +23,29 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
|
||||
# 1. Copy manifests to cache dependencies
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates/robot-kit/Cargo.toml crates/robot-kit/Cargo.toml
|
||||
# Remove robot-kit from workspace members — it is excluded by .dockerignore
|
||||
# and is not needed for the Docker build (hardware-only crate).
|
||||
RUN sed -i 's/members = \[".", "crates\/robot-kit"\]/members = ["."]/' Cargo.toml
|
||||
# Create dummy targets declared in Cargo.toml so manifest parsing succeeds.
|
||||
RUN mkdir -p src benches crates/robot-kit/src \
|
||||
RUN mkdir -p src benches \
|
||||
&& echo "fn main() {}" > src/main.rs \
|
||||
&& echo "" > src/lib.rs \
|
||||
&& echo "fn main() {}" > benches/agent_benchmarks.rs \
|
||||
&& echo "pub fn placeholder() {}" > crates/robot-kit/src/lib.rs
|
||||
&& echo "fn main() {}" > benches/agent_benchmarks.rs
|
||||
RUN --mount=type=cache,id=zeroclaw-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-cargo-git,target=/usr/local/cargo/git,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-target,target=/app/target,sharing=locked \
|
||||
cargo build --release --locked
|
||||
RUN rm -rf src benches crates/robot-kit/src
|
||||
if [ -n "$ZEROCLAW_CARGO_FEATURES" ]; then \
|
||||
cargo build --release --locked --features "$ZEROCLAW_CARGO_FEATURES"; \
|
||||
else \
|
||||
cargo build --release --locked; \
|
||||
fi
|
||||
RUN rm -rf src benches
|
||||
|
||||
# 2. Copy only build-relevant source paths (avoid cache-busting on docs/tests/scripts)
|
||||
COPY src/ src/
|
||||
COPY benches/ benches/
|
||||
COPY crates/ crates/
|
||||
COPY firmware/ firmware/
|
||||
COPY web/ web/
|
||||
COPY --from=web-builder /web/dist web/dist
|
||||
COPY *.rs .
|
||||
# Keep release builds resilient when frontend dist assets are not prebuilt in Git.
|
||||
RUN mkdir -p web/dist && \
|
||||
if [ ! -f web/dist/index.html ]; then \
|
||||
printf '%s\n' \
|
||||
'<!doctype html>' \
|
||||
'<html lang="en">' \
|
||||
' <head>' \
|
||||
' <meta charset="utf-8" />' \
|
||||
' <meta name="viewport" content="width=device-width,initial-scale=1" />' \
|
||||
' <title>ZeroClaw Dashboard</title>' \
|
||||
' </head>' \
|
||||
' <body>' \
|
||||
' <h1>ZeroClaw Dashboard Unavailable</h1>' \
|
||||
' <p>Frontend assets are not bundled in this build. Build the web UI to populate <code>web/dist</code>.</p>' \
|
||||
' </body>' \
|
||||
'</html>' > web/dist/index.html; \
|
||||
fi
|
||||
RUN touch src/main.rs
|
||||
RUN --mount=type=cache,id=zeroclaw-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-cargo-git,target=/usr/local/cargo/git,sharing=locked \
|
||||
@@ -58,7 +53,11 @@ RUN --mount=type=cache,id=zeroclaw-cargo-registry,target=/usr/local/cargo/regist
|
||||
rm -rf target/release/.fingerprint/zeroclawlabs-* \
|
||||
target/release/deps/zeroclawlabs-* \
|
||||
target/release/incremental/zeroclawlabs-* && \
|
||||
cargo build --release --locked && \
|
||||
if [ -n "$ZEROCLAW_CARGO_FEATURES" ]; then \
|
||||
cargo build --release --locked --features "$ZEROCLAW_CARGO_FEATURES"; \
|
||||
else \
|
||||
cargo build --release --locked; \
|
||||
fi && \
|
||||
cp target/release/zeroclaw /app/zeroclaw && \
|
||||
strip /app/zeroclaw
|
||||
RUN size=$(stat -c%s /app/zeroclaw 2>/dev/null || stat -f%z /app/zeroclaw) && \
|
||||
@@ -114,6 +113,8 @@ ENV ZEROCLAW_GATEWAY_PORT=42617
|
||||
WORKDIR /zeroclaw-data
|
||||
USER 65534:65534
|
||||
EXPOSE 42617
|
||||
HEALTHCHECK --interval=60s --timeout=10s --retries=3 --start-period=10s \
|
||||
CMD ["zeroclaw", "status", "--format=exit-code"]
|
||||
ENTRYPOINT ["zeroclaw"]
|
||||
CMD ["gateway"]
|
||||
|
||||
@@ -138,5 +139,7 @@ ENV ZEROCLAW_GATEWAY_PORT=42617
|
||||
WORKDIR /zeroclaw-data
|
||||
USER 65534:65534
|
||||
EXPOSE 42617
|
||||
HEALTHCHECK --interval=60s --timeout=10s --retries=3 --start-period=10s \
|
||||
CMD ["zeroclaw", "status", "--format=exit-code"]
|
||||
ENTRYPOINT ["zeroclaw"]
|
||||
CMD ["gateway"]
|
||||
|
||||
+30
-29
@@ -1,5 +1,13 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
# ── Stage 0: Frontend build ─────────────────────────────────────
|
||||
FROM node:22-alpine AS web-builder
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/package-lock.json* ./
|
||||
RUN npm ci --ignore-scripts 2>/dev/null || npm install --ignore-scripts
|
||||
COPY web/ .
|
||||
RUN npm run build
|
||||
|
||||
# Dockerfile.debian — Shell-equipped variant of the ZeroClaw container.
|
||||
#
|
||||
# The default Dockerfile produces a distroless "release" image with no shell,
|
||||
@@ -15,10 +23,11 @@
|
||||
# Or with docker compose:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.debian.yml up
|
||||
|
||||
# ── Stage 1: Build (identical to main Dockerfile) ───────────
|
||||
FROM rust:1.94-slim@sha256:da9dab7a6b8dd428e71718402e97207bb3e54167d37b5708616050b1e8f60ed6 AS builder
|
||||
# ── Stage 1: Build (match runtime glibc baseline) ───────────
|
||||
FROM rust:1.94-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
ARG ZEROCLAW_CARGO_FEATURES="memory-postgres"
|
||||
|
||||
# Install build dependencies
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
@@ -29,47 +38,37 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
|
||||
# 1. Copy manifests to cache dependencies
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates/robot-kit/Cargo.toml crates/robot-kit/Cargo.toml
|
||||
# Remove robot-kit from workspace members — it is excluded by .dockerignore
|
||||
# and is not needed for the Docker build (hardware-only crate).
|
||||
RUN sed -i 's/members = \[".", "crates\/robot-kit"\]/members = ["."]/' Cargo.toml
|
||||
# Create dummy targets declared in Cargo.toml so manifest parsing succeeds.
|
||||
RUN mkdir -p src benches crates/robot-kit/src \
|
||||
RUN mkdir -p src benches \
|
||||
&& echo "fn main() {}" > src/main.rs \
|
||||
&& echo "" > src/lib.rs \
|
||||
&& echo "fn main() {}" > benches/agent_benchmarks.rs \
|
||||
&& echo "pub fn placeholder() {}" > crates/robot-kit/src/lib.rs
|
||||
&& echo "fn main() {}" > benches/agent_benchmarks.rs
|
||||
RUN --mount=type=cache,id=zeroclaw-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-cargo-git,target=/usr/local/cargo/git,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-target,target=/app/target,sharing=locked \
|
||||
cargo build --release --locked
|
||||
RUN rm -rf src benches crates/robot-kit/src
|
||||
if [ -n "$ZEROCLAW_CARGO_FEATURES" ]; then \
|
||||
cargo build --release --locked --features "$ZEROCLAW_CARGO_FEATURES"; \
|
||||
else \
|
||||
cargo build --release --locked; \
|
||||
fi
|
||||
RUN rm -rf src benches
|
||||
|
||||
# 2. Copy only build-relevant source paths (avoid cache-busting on docs/tests/scripts)
|
||||
COPY src/ src/
|
||||
COPY benches/ benches/
|
||||
COPY crates/ crates/
|
||||
COPY firmware/ firmware/
|
||||
COPY web/ web/
|
||||
# Keep release builds resilient when frontend dist assets are not prebuilt in Git.
|
||||
RUN mkdir -p web/dist && \
|
||||
if [ ! -f web/dist/index.html ]; then \
|
||||
printf '%s\n' \
|
||||
'<!doctype html>' \
|
||||
'<html lang="en">' \
|
||||
' <head>' \
|
||||
' <meta charset="utf-8" />' \
|
||||
' <meta name="viewport" content="width=device-width,initial-scale=1" />' \
|
||||
' <title>ZeroClaw Dashboard</title>' \
|
||||
' </head>' \
|
||||
' <body>' \
|
||||
' <h1>ZeroClaw Dashboard Unavailable</h1>' \
|
||||
' <p>Frontend assets are not bundled in this build. Build the web UI to populate <code>web/dist</code>.</p>' \
|
||||
' </body>' \
|
||||
'</html>' > web/dist/index.html; \
|
||||
fi
|
||||
COPY --from=web-builder /web/dist web/dist
|
||||
RUN touch src/main.rs
|
||||
RUN --mount=type=cache,id=zeroclaw-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-cargo-git,target=/usr/local/cargo/git,sharing=locked \
|
||||
--mount=type=cache,id=zeroclaw-target,target=/app/target,sharing=locked \
|
||||
cargo build --release --locked && \
|
||||
if [ -n "$ZEROCLAW_CARGO_FEATURES" ]; then \
|
||||
cargo build --release --locked --features "$ZEROCLAW_CARGO_FEATURES"; \
|
||||
else \
|
||||
cargo build --release --locked; \
|
||||
fi && \
|
||||
cp target/release/zeroclaw /app/zeroclaw && \
|
||||
strip /app/zeroclaw
|
||||
RUN size=$(stat -c%s /app/zeroclaw 2>/dev/null || stat -f%z /app/zeroclaw) && \
|
||||
@@ -120,5 +119,7 @@ ENV ZEROCLAW_GATEWAY_PORT=42617
|
||||
WORKDIR /zeroclaw-data
|
||||
USER 65534:65534
|
||||
EXPOSE 42617
|
||||
HEALTHCHECK --interval=60s --timeout=10s --retries=3 --start-period=10s \
|
||||
CMD ["zeroclaw", "status", "--format=exit-code"]
|
||||
ENTRYPOINT ["zeroclaw"]
|
||||
CMD ["gateway"]
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Dockerfile.debian.ci — CI/release Debian image using pre-built binaries.
|
||||
# Mirrors Dockerfile.ci but uses debian:bookworm-slim with shell tools
|
||||
# so the agent can use shell-based tools (pwd, ls, git, curl, etc.).
|
||||
# Used by release workflows to skip ~60 min QEMU cross-compilation.
|
||||
|
||||
# ── Runtime (Debian with shell) ────────────────────────────────
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
# Install essential tools for agent shell operations
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
bash \
|
||||
ca-certificates \
|
||||
curl \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy the pre-built binary for this platform (amd64 or arm64)
|
||||
COPY bin/${TARGETARCH}/zeroclaw /usr/local/bin/zeroclaw
|
||||
|
||||
# Runtime directory structure and default config
|
||||
COPY --chown=65534:65534 zeroclaw-data/ /zeroclaw-data/
|
||||
|
||||
ENV LANG=C.UTF-8
|
||||
ENV ZEROCLAW_WORKSPACE=/zeroclaw-data/workspace
|
||||
ENV HOME=/zeroclaw-data
|
||||
ENV ZEROCLAW_GATEWAY_PORT=42617
|
||||
|
||||
WORKDIR /zeroclaw-data
|
||||
USER 65534:65534
|
||||
EXPOSE 42617
|
||||
ENTRYPOINT ["zeroclaw"]
|
||||
CMD ["gateway"]
|
||||
+5
-2
@@ -16,7 +16,10 @@
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center" dir="rtl">
|
||||
@@ -103,7 +106,7 @@
|
||||
| التاريخ (UTC) | المستوى | الإشعار | الإجراء |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _حرج_ | **نحن غير مرتبطين** بـ `openagen/zeroclaw` أو `zeroclaw.org`. نطاق `zeroclaw.org` يشير حاليًا إلى الفرع `openagen/zeroclaw`، وهذا النطاق/المستودع ينتحل شخصية موقعنا/مشروعنا الرسمي. | لا تثق بالمعلومات أو الملفات الثنائية أو جمع التبرعات أو الإعلانات من هذه المصادر. استخدم فقط [هذا المستودع](https://github.com/zeroclaw-labs/zeroclaw) وحساباتنا الموثقة على وسائل التواصل الاجتماعي. |
|
||||
| 2026-02-21 | _مهم_ | موقعنا الرسمي أصبح متاحًا الآن: [zeroclawlabs.ai](https://zeroclawlabs.ai). شكرًا لصبرك أثناء الانتظار. لا نزال نكتشف محاولات الانتحال: لا تشارك في أي نشاط استثمار/تمويل باسم ZeroClaw إذا لم يتم نشره عبر قنواتنا الرسمية. | استخدم [هذا المستودع](https://github.com/zeroclaw-labs/zeroclaw) كمصدر وحيد للحقيقة. تابع [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21)، [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs)، [Facebook (مجموعة)](https://www.facebook.com/groups/zeroclaw)، [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/)، و[Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) للتحديثات الرسمية. |
|
||||
| 2026-02-21 | _مهم_ | موقعنا الرسمي أصبح متاحًا الآن: [zeroclawlabs.ai](https://zeroclawlabs.ai). شكرًا لصبرك أثناء الانتظار. لا نزال نكتشف محاولات الانتحال: لا تشارك في أي نشاط استثمار/تمويل باسم ZeroClaw إذا لم يتم نشره عبر قنواتنا الرسمية. | استخدم [هذا المستودع](https://github.com/zeroclaw-labs/zeroclaw) كمصدر وحيد للحقيقة. تابع [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21)، [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs)، [Facebook (مجموعة)](https://www.facebook.com/groups/zeroclawlabs)، [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/)، و[Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) للتحديثات الرسمية. |
|
||||
| 2026-02-19 | _مهم_ | قامت Anthropic بتحديث شروط استخدام المصادقة وبيانات الاعتماد في 2026-02-19. مصادقة OAuth (Free، Pro، Max) حصريًا لـ Claude Code و Claude.ai؛ استخدام رموز Claude Free/Pro/Max OAuth في أي منتج أو أداة أو خدمة أخرى (بما في ذلك Agent SDK) غير مسموح به وقد ينتهك شروط استخدام المستهلك. | يرجى تجنب مؤقتًا تكاملات Claude Code OAuth لمنع أي خسارة محتملة. البند الأصلي: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ الميزات
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ channels:
|
||||
## কমিউনিটি
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Použijte tuto tabulku pro důležitá oznámení (změny kompatibility, bezpeč
|
||||
| Datum (UTC) | Úroveň | Oznámení | Akce |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Kritické_ | **Nejsme propojeni** s `openagen/zeroclaw` nebo `zeroclaw.org`. Doména `zeroclaw.org` aktuálně směřuje na fork `openagen/zeroclaw`, a tato doména/repoziťář se vydává za náš oficiální web/projekt. | Nevěřte informacím, binárním souborům, fundraisingu nebo oznámením z těchto zdrojů. Používejte pouze [tento repoziťář](https://github.com/zeroclaw-labs/zeroclaw) a naše ověřené sociální účty. |
|
||||
| 2026-02-21 | _Důležité_ | Náš oficiální web je nyní online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Děkujeme za trpělivost během čekání. Stále detekujeme pokusy o vydávání se: neúčastněte žádné investiční/fundraisingové aktivity ve jménu ZeroClaw pokud není publikována přes naše oficiální kanály. | Používejte [tento repoziťář](https://github.com/zeroclaw-labs/zeroclaw) jako jediný zdroj pravdy. Sledujte [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (skupina)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), a [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) pro oficiální aktualizace. |
|
||||
| 2026-02-21 | _Důležité_ | Náš oficiální web je nyní online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Děkujeme za trpělivost během čekání. Stále detekujeme pokusy o vydávání se: neúčastněte žádné investiční/fundraisingové aktivity ve jménu ZeroClaw pokud není publikována přes naše oficiální kanály. | Používejte [tento repoziťář](https://github.com/zeroclaw-labs/zeroclaw) jako jediný zdroj pravdy. Sledujte [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (skupina)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), a [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) pro oficiální aktualizace. |
|
||||
| 2026-02-19 | _Důležité_ | Anthropic aktualizoval podmínky použití autentizace a přihlašovacích údajů dne 2026-02-19. OAuth autentizace (Free, Pro, Max) je výhradně pro Claude Code a Claude.ai; použití Claude Free/Pro/Max OAuth tokenů v jakémkoliv jiném produktu, nástroji nebo službě (včetně Agent SDK) není povoleno a může porušit Podmínky použití spotřebitele. | Prosím dočasně se vyhněte Claude Code OAuth integracím pro předcházení potenciálním ztrátám. Původní klauzule: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Funkce
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Se [LICENSE-APACHE](LICENSE-APACHE) og [LICENSE-MIT](LICENSE-MIT) for detaljer.
|
||||
## Fællesskab
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -107,7 +110,7 @@ Verwende diese Tabelle für wichtige Hinweise (Kompatibilitätsänderungen, Sich
|
||||
| Datum (UTC) | Ebene | Hinweis | Aktion |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Kritisch_ | Wir sind **nicht verbunden** mit `openagen/zeroclaw` oder `zeroclaw.org`. Die Domain `zeroclaw.org` zeigt derzeit auf den Fork `openagen/zeroclaw`, und diese Domain/Repository fälscht unsere offizielle Website/Projekt. | Vertraue keinen Informationen, Binärdateien, Fundraising oder Ankündigungen aus diesen Quellen. Verwende nur [dieses Repository](https://github.com/zeroclaw-labs/zeroclaw) und unsere verifizierten Social-Media-Konten. |
|
||||
| 2026-02-21 | _Wichtig_ | Unsere offizielle Website ist jetzt online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Danke für deine Geduld während der Wartezeit. Wir erkennen weiterhin Fälschungsversuche: nimm an keiner Investitions-/Finanzierungsaktivität im Namen von ZeroClaw teil, wenn sie nicht über unsere offiziellen Kanäle veröffentlicht wird. | Verwende [dieses Repository](https://github.com/zeroclaw-labs/zeroclaw) als einzige Quelle der Wahrheit. Folge [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (Gruppe)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), und [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) für offizielle Updates. |
|
||||
| 2026-02-21 | _Wichtig_ | Unsere offizielle Website ist jetzt online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Danke für deine Geduld während der Wartezeit. Wir erkennen weiterhin Fälschungsversuche: nimm an keiner Investitions-/Finanzierungsaktivität im Namen von ZeroClaw teil, wenn sie nicht über unsere offiziellen Kanäle veröffentlicht wird. | Verwende [dieses Repository](https://github.com/zeroclaw-labs/zeroclaw) als einzige Quelle der Wahrheit. Folge [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (Gruppe)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), und [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) für offizielle Updates. |
|
||||
| 2026-02-19 | _Wichtig_ | Anthropic hat die Nutzungsbedingungen für Authentifizierung und Anmeldedaten am 2026-02-19 aktualisiert. Die OAuth-Authentifizierung (Free, Pro, Max) ist ausschließlich für Claude Code und Claude.ai; die Verwendung von Claude Free/Pro/Max OAuth-Token in einem anderen Produkt, Tool oder Dienst (einschließlich Agent SDK) ist nicht erlaubt und kann gegen die Verbrauchernutzungsbedingungen verstoßen. | Bitte vermeide vorübergehend Claude Code OAuth-Integrationen, um potenzielle Verluste zu verhindern. Originalklausel: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Funktionen
|
||||
|
||||
+5
-2
@@ -14,7 +14,10 @@
|
||||
<a href="NOTICE"><img src="https://img.shields.io/badge/contributors-27+-green.svg" alt="Contributors" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Buy Me a Coffee" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -176,7 +179,7 @@ channels:
|
||||
## Κοινότητα
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Usa esta tabla para avisos importantes (cambios de compatibilidad, avisos de seg
|
||||
| Fecha (UTC) | Nivel | Aviso | Acción |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Crítico_ | **No estamos afiliados** con `openagen/zeroclaw` o `zeroclaw.org`. El dominio `zeroclaw.org` apunta actualmente al fork `openagen/zeroclaw`, y este dominio/repositorio está suplantando nuestro sitio web/proyecto oficial. | No confíes en información, binarios, recaudaciones de fondos o anuncios de estas fuentes. Usa solo [este repositorio](https://github.com/zeroclaw-labs/zeroclaw) y nuestras cuentas sociales verificadas. |
|
||||
| 2026-02-21 | _Importante_ | Nuestro sitio web oficial ahora está en línea: [zeroclawlabs.ai](https://zeroclawlabs.ai). Gracias por tu paciencia durante la espera. Todavía detectamos intentos de suplantación: no participes en ninguna actividad de inversión/financiamiento en nombre de ZeroClaw si no se publica a través de nuestros canales oficiales. | Usa [este repositorio](https://github.com/zeroclaw-labs/zeroclaw) como la única fuente de verdad. Sigue [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupo)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), y [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) para actualizaciones oficiales. |
|
||||
| 2026-02-21 | _Importante_ | Nuestro sitio web oficial ahora está en línea: [zeroclawlabs.ai](https://zeroclawlabs.ai). Gracias por tu paciencia durante la espera. Todavía detectamos intentos de suplantación: no participes en ninguna actividad de inversión/financiamiento en nombre de ZeroClaw si no se publica a través de nuestros canales oficiales. | Usa [este repositorio](https://github.com/zeroclaw-labs/zeroclaw) como la única fuente de verdad. Sigue [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupo)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), y [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) para actualizaciones oficiales. |
|
||||
| 2026-02-19 | _Importante_ | Anthropic actualizó los términos de uso de autenticación y credenciales el 2026-02-19. La autenticación OAuth (Free, Pro, Max) es exclusivamente para Claude Code y Claude.ai; el uso de tokens OAuth de Claude Free/Pro/Max en cualquier otro producto, herramienta o servicio (incluyendo Agent SDK) no está permitido y puede violar los Términos de Uso del Consumidor. | Por favor, evita temporalmente las integraciones OAuth de Claude Code para prevenir cualquier pérdida potencial. Cláusula original: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Características
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Katso [LICENSE-APACHE](LICENSE-APACHE) ja [LICENSE-MIT](LICENSE-MIT) yksityiskoh
|
||||
## Yhteisö
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -14,7 +14,10 @@
|
||||
<a href="NOTICE"><img src="https://img.shields.io/badge/contributors-27+-green.svg" alt="Contributeurs" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Offrez-moi un café" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X : @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit : r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -101,7 +104,7 @@ Utilisez ce tableau pour les avis importants (changements incompatibles, avis de
|
||||
| Date (UTC) | Niveau | Avis | Action |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Critique_ | Nous ne sommes **pas affiliés** à `openagen/zeroclaw` ou `zeroclaw.org`. Le domaine `zeroclaw.org` pointe actuellement vers le fork `openagen/zeroclaw`, et ce domaine/dépôt usurpe l'identité de notre site web/projet officiel. | Ne faites pas confiance aux informations, binaires, levées de fonds ou annonces provenant de ces sources. Utilisez uniquement [ce dépôt](https://github.com/zeroclaw-labs/zeroclaw) et nos comptes sociaux vérifiés. |
|
||||
| 2026-02-21 | _Important_ | Notre site officiel est désormais en ligne : [zeroclawlabs.ai](https://zeroclawlabs.ai). Merci pour votre patience pendant cette attente. Nous constatons toujours des tentatives d'usurpation : ne participez à aucune activité d'investissement/financement au nom de ZeroClaw si elle n'est pas publiée via nos canaux officiels. | Utilisez [ce dépôt](https://github.com/zeroclaw-labs/zeroclaw) comme source unique de vérité. Suivez [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Facebook (groupe)](https://www.facebook.com/groups/zeroclaw), et [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) pour les mises à jour officielles. |
|
||||
| 2026-02-21 | _Important_ | Notre site officiel est désormais en ligne : [zeroclawlabs.ai](https://zeroclawlabs.ai). Merci pour votre patience pendant cette attente. Nous constatons toujours des tentatives d'usurpation : ne participez à aucune activité d'investissement/financement au nom de ZeroClaw si elle n'est pas publiée via nos canaux officiels. | Utilisez [ce dépôt](https://github.com/zeroclaw-labs/zeroclaw) comme source unique de vérité. Suivez [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Facebook (groupe)](https://www.facebook.com/groups/zeroclawlabs), et [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) pour les mises à jour officielles. |
|
||||
| 2026-02-19 | _Important_ | Anthropic a mis à jour les conditions d'utilisation de l'authentification et des identifiants le 2026-02-19. L'authentification OAuth (Free, Pro, Max) est exclusivement destinée à Claude Code et Claude.ai ; l'utilisation de tokens OAuth de Claude Free/Pro/Max dans tout autre produit, outil ou service (y compris Agent SDK) n'est pas autorisée et peut violer les Conditions d'utilisation grand public. | Veuillez temporairement éviter les intégrations OAuth de Claude Code pour prévenir toute perte potentielle. Clause originale : [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Fonctionnalités
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center" dir="rtl">
|
||||
@@ -193,7 +196,7 @@ channels:
|
||||
## קהילה
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ channels:
|
||||
## समुदाय
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Részletekért lásd a [LICENSE-APACHE](LICENSE-APACHE) és [LICENSE-MIT](LICENS
|
||||
## Közösség
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Lihat [LICENSE-APACHE](LICENSE-APACHE) dan [LICENSE-MIT](LICENSE-MIT) untuk deta
|
||||
## Komunitas
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Usa questa tabella per avvisi importanti (cambiamenti di compatibilità, avvisi
|
||||
| Data (UTC) | Livello | Avviso | Azione |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Critico_ | **Non siamo affiliati** con `openagen/zeroclaw` o `zeroclaw.org`. Il dominio `zeroclaw.org` punta attualmente al fork `openagen/zeroclaw`, e questo dominio/repository sta contraffacendo il nostro sito web/progetto ufficiale. | Non fidarti di informazioni, binari, raccolte fondi o annunci da queste fonti. Usa solo [questo repository](https://github.com/zeroclaw-labs/zeroclaw) e i nostri account social verificati. |
|
||||
| 2026-02-21 | _Importante_ | Il nostro sito ufficiale è ora online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Grazie per la pazienza durante l'attesa. Rileviamo ancora tentativi di contraffazione: non partecipare ad alcuna attività di investimento/finanziamento a nome di ZeroClaw se non pubblicata tramite i nostri canali ufficiali. | Usa [questo repository](https://github.com/zeroclaw-labs/zeroclaw) come unica fonte di verità. Segui [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (gruppo)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), e [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) per aggiornamenti ufficiali. |
|
||||
| 2026-02-21 | _Importante_ | Il nostro sito ufficiale è ora online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Grazie per la pazienza durante l'attesa. Rileviamo ancora tentativi di contraffazione: non partecipare ad alcuna attività di investimento/finanziamento a nome di ZeroClaw se non pubblicata tramite i nostri canali ufficiali. | Usa [questo repository](https://github.com/zeroclaw-labs/zeroclaw) come unica fonte di verità. Segui [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (gruppo)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), e [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) per aggiornamenti ufficiali. |
|
||||
| 2026-02-19 | _Importante_ | Anthropic ha aggiornato i termini di utilizzo di autenticazione e credenziali il 2026-02-19. L'autenticazione OAuth (Free, Pro, Max) è esclusivamente per Claude Code e Claude.ai; l'uso di token OAuth di Claude Free/Pro/Max in qualsiasi altro prodotto, strumento o servizio (incluso Agent SDK) non è consentito e può violare i Termini di Utilizzo del Consumatore. | Si prega di evitare temporaneamente le integrazioni OAuth di Claude Code per prevenire qualsiasi potenziale perdita. Clausola originale: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Funzionalità
|
||||
|
||||
+5
-2
@@ -13,7 +13,10 @@
|
||||
<a href="NOTICE"><img src="https://img.shields.io/badge/contributors-27+-green.svg" alt="Contributors" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Buy Me a Coffee" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
|
||||
@@ -92,7 +95,7 @@
|
||||
| 日付 (UTC) | レベル | お知らせ | 対応 |
|
||||
|---|---|---|---|
|
||||
| 2026-02-19 | _緊急_ | 私たちは `openagen/zeroclaw` および `zeroclaw.org` とは**一切関係ありません**。`zeroclaw.org` は現在 `openagen/zeroclaw` の fork を指しており、そのドメイン/リポジトリは当プロジェクトの公式サイト・公式プロジェクトを装っています。 | これらの情報源による案内、バイナリ、資金調達情報、公式発表は信頼しないでください。必ず[本リポジトリ](https://github.com/zeroclaw-labs/zeroclaw)と認証済み公式SNSのみを参照してください。 |
|
||||
| 2026-02-21 | _重要_ | 公式サイトを公開しました: [zeroclawlabs.ai](https://zeroclawlabs.ai)。公開までお待ちいただきありがとうございました。引き続きなりすましの試みを確認しているため、ZeroClaw 名義の投資・資金調達などの案内は、公式チャネルで確認できない限り参加しないでください。 | 情報は[本リポジトリ](https://github.com/zeroclaw-labs/zeroclaw)を最優先で確認し、[X(@zeroclawlabs)](https://x.com/zeroclawlabs?s=21)、[Telegram(@zeroclawlabs)](https://t.me/zeroclawlabs)、[Facebook(グループ)](https://www.facebook.com/groups/zeroclaw)、[Reddit(r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) と [小紅書アカウント](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) で公式更新を確認してください。 |
|
||||
| 2026-02-21 | _重要_ | 公式サイトを公開しました: [zeroclawlabs.ai](https://zeroclawlabs.ai)。公開までお待ちいただきありがとうございました。引き続きなりすましの試みを確認しているため、ZeroClaw 名義の投資・資金調達などの案内は、公式チャネルで確認できない限り参加しないでください。 | 情報は[本リポジトリ](https://github.com/zeroclaw-labs/zeroclaw)を最優先で確認し、[X(@zeroclawlabs)](https://x.com/zeroclawlabs?s=21)、[Telegram(@zeroclawlabs)](https://t.me/zeroclawlabs)、[Facebook(グループ)](https://www.facebook.com/groups/zeroclawlabs)、[Reddit(r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) と [小紅書アカウント](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) で公式更新を確認してください。 |
|
||||
| 2026-02-19 | _重要_ | Anthropic は 2026-02-19 に Authentication and Credential Use を更新しました。条文では、OAuth authentication(Free/Pro/Max)は Claude Code と Claude.ai 専用であり、Claude Free/Pro/Max で取得した OAuth トークンを他の製品・ツール・サービス(Agent SDK を含む)で使用することは許可されず、Consumer Terms of Service 違反に該当すると明記されています。 | 損失回避のため、当面は Claude Code OAuth 連携を試さないでください。原文: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use)。 |
|
||||
|
||||
## 概要
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Harvard, MIT, 그리고 Sundai.Club 커뮤니티의 학생들과 멤버들이
|
||||
| 날짜 (UTC) | 수준 | 공지 | 조치 |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _중요_ | 우리는 `openagen/zeroclaw` 또는 `zeroclaw.org`와 **관련이 없습니다**. `zeroclaw.org` 도메인은 현재 `openagen/zeroclaw` 포크를 가리키고 있으며, 이 도메인/저장소는 우리의 공식 웹사이트/프로젝트를 사칭하고 있습니다. | 이 소스의 정보, 바이너리, 펀딩, 공지를 신뢰하지 마세요. [이 저장소](https://github.com/zeroclaw-labs/zeroclaw)와 우리의 확인된 소셜 계정만 사용하세요. |
|
||||
| 2026-02-21 | _중요_ | 우리의 공식 웹사이트가 이제 온라인입니다: [zeroclawlabs.ai](https://zeroclawlabs.ai). 기다려주셔서 감사합니다. 여전히 사칭 시도가 감지되고 있습니다: 공식 채널을 통해 게시되지 않은 ZeroClaw 이름의 모든 투자/펀딩 활동에 참여하지 마세요. | [이 저장소](https://github.com/zeroclaw-labs/zeroclaw)를 유일한 진실의 원천으로 사용하세요. [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (그룹)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), 그리고 [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search)를 팔로우하여 공식 업데이트를 받으세요. |
|
||||
| 2026-02-21 | _중요_ | 우리의 공식 웹사이트가 이제 온라인입니다: [zeroclawlabs.ai](https://zeroclawlabs.ai). 기다려주셔서 감사합니다. 여전히 사칭 시도가 감지되고 있습니다: 공식 채널을 통해 게시되지 않은 ZeroClaw 이름의 모든 투자/펀딩 활동에 참여하지 마세요. | [이 저장소](https://github.com/zeroclaw-labs/zeroclaw)를 유일한 진실의 원천으로 사용하세요. [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (그룹)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), 그리고 [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search)를 팔로우하여 공식 업데이트를 받으세요. |
|
||||
| 2026-02-19 | _중요_ | Anthropic이 2026-02-19에 인증 및 자격증명 사용 약관을 업데이트했습니다. OAuth 인증(Free, Pro, Max)은 Claude Code 및 Claude.ai 전용입니다. 다른 제품, 도구 또는 서비스(Agent SDK 포함)에서 Claude Free/Pro/Max OAuth 토큰을 사용하는 것은 허용되지 않으며 소비자 이용약관을 위반할 수 있습니다. | 잠재적인 손실을 방지하기 위해 일시적으로 Claude Code OAuth 통합을 피하세요. 원본 조항: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ 기능
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="docs/assets/zeroclaw.png" alt="ZeroClaw" width="200" />
|
||||
<img src="docs/assets/zeroclaw-banner.png" alt="ZeroClaw" width="600" />
|
||||
</p>
|
||||
|
||||
<h1 align="center">ZeroClaw 🦀</h1>
|
||||
@@ -14,7 +14,11 @@
|
||||
<a href="https://github.com/zeroclaw-labs/zeroclaw/graphs/contributors"><img src="https://img.shields.io/github/contributors/zeroclaw-labs/zeroclaw?color=green" alt="Contributors" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Buy Me a Coffee" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.instagram.com/therealzeroclaw"><img src="https://img.shields.io/badge/Instagram-%40therealzeroclaw-E4405F?style=flat&logo=instagram&logoColor=white" alt="Instagram: @therealzeroclaw" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -94,7 +98,7 @@ Use this board for important notices (breaking changes, security advisories, mai
|
||||
| Date (UTC) | Level | Notice | Action |
|
||||
| ---------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Critical_ | We are **not affiliated** with `openagen/zeroclaw`, `zeroclaw.org` or `zeroclaw.net`. The `zeroclaw.org` and `zeroclaw.net` domains currently points to the `openagen/zeroclaw` fork, and that domain/repository are impersonating our official website/project. | Do not trust information, binaries, fundraising, or announcements from those sources. Use only [this repository](https://github.com/zeroclaw-labs/zeroclaw) and our verified social accounts. |
|
||||
| 2026-02-21 | _Important_ | Our official website is now live: [zeroclawlabs.ai](https://zeroclawlabs.ai). Thanks for your patience while we prepared the launch. We are still seeing impersonation attempts, so do **not** join any investment or fundraising activity claiming the ZeroClaw name unless it is published through our official channels. | Use [this repository](https://github.com/zeroclaw-labs/zeroclaw) as the single source of truth. Follow [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Facebook (Group)](https://www.facebook.com/groups/zeroclaw), and [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) for official updates. |
|
||||
| 2026-02-21 | _Important_ | Our official website is now live: [zeroclawlabs.ai](https://zeroclawlabs.ai). Thanks for your patience while we prepared the launch. We are still seeing impersonation attempts, so do **not** join any investment or fundraising activity claiming the ZeroClaw name unless it is published through our official channels. | Use [this repository](https://github.com/zeroclaw-labs/zeroclaw) as the single source of truth. Follow [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Facebook (Group)](https://www.facebook.com/groups/zeroclawlabs), and [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) for official updates. |
|
||||
| 2026-02-19 | _Important_ | Anthropic updated the Authentication and Credential Use terms on 2026-02-19. Claude Code OAuth tokens (Free, Pro, Max) are intended exclusively for Claude Code and Claude.ai; using OAuth tokens from Claude Free/Pro/Max in any other product, tool, or service (including Agent SDK) is not permitted and may violate the Consumer Terms of Service. | Please temporarily avoid Claude Code OAuth integrations to prevent potential loss. Original clause: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Features
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Se [LICENSE-APACHE](LICENSE-APACHE) og [LICENSE-MIT](LICENSE-MIT) for detaljer.
|
||||
## Fellesskap
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Gebruik deze tabel voor belangrijke aankondigingen (compatibiliteitswijzigingen,
|
||||
| Datum (UTC) | Niveau | Aankondiging | Actie |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Kritiek_ | **We zijn niet gelieerd** met `openagen/zeroclaw` of `zeroclaw.org`. Het domein `zeroclaw.org` wijst momenteel naar de fork `openagen/zeroclaw`, en dit domein/repository imiteert onze officiële website/project. | Vertrouw geen informatie, binaire bestanden, fondsenwerving of aankondigingen van deze bronnen. Gebruik alleen [deze repository](https://github.com/zeroclaw-labs/zeroclaw) en onze geverifieerde sociale media accounts. |
|
||||
| 2026-02-21 | _Belangrijk_ | Onze officiële website is nu online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Bedankt voor je geduld tijdens het wachten. We detecteren nog steeds imitatiepogingen: neem niet deel aan enige investering/fondsenwerving activiteit in naam van ZeroClaw als deze niet via onze officiële kanalen wordt gepubliceerd. | Gebruik [deze repository](https://github.com/zeroclaw-labs/zeroclaw) als de enige bron van waarheid. Volg [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (groep)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), en [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) voor officiële updates. |
|
||||
| 2026-02-21 | _Belangrijk_ | Onze officiële website is nu online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Bedankt voor je geduld tijdens het wachten. We detecteren nog steeds imitatiepogingen: neem niet deel aan enige investering/fondsenwerving activiteit in naam van ZeroClaw als deze niet via onze officiële kanalen wordt gepubliceerd. | Gebruik [deze repository](https://github.com/zeroclaw-labs/zeroclaw) als de enige bron van waarheid. Volg [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (groep)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), en [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) voor officiële updates. |
|
||||
| 2026-02-19 | _Belangrijk_ | Anthropic heeft de gebruiksvoorwaarden voor authenticatie en inloggegevens bijgewerkt op 2026-02-19. OAuth authenticatie (Free, Pro, Max) is exclusief voor Claude Code en Claude.ai; het gebruik van Claude Free/Pro/Max OAuth tokens in enig ander product, tool of service (inclusief Agent SDK) is niet toegestaan en kan in strijd zijn met de Consumenten Gebruiksvoorwaarden. | Vermijd tijdelijk Claude Code OAuth integraties om potentiële verliezen te voorkomen. Originele clausule: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Functies
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Użyj tej tabeli dla ważnych ogłoszeń (zmiany kompatybilności, powiadomienia
|
||||
| Data (UTC) | Poziom | Ogłoszenie | Działanie |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Krytyczny_ | **Nie jesteśmy powiązani** z `openagen/zeroclaw` lub `zeroclaw.org`. Domena `zeroclaw.org` obecnie wskazuje na fork `openagen/zeroclaw`, i ta domena/repozytorium podszywa się pod naszą oficjalną stronę/projekt. | Nie ufaj informacjom, plikom binarnym, zbiórkom funduszy lub ogłoszeniom z tych źródeł. Używaj tylko [tego repozytorium](https://github.com/zeroclaw-labs/zeroclaw) i naszych zweryfikowanych kont społecznościowych. |
|
||||
| 2026-02-21 | _Ważne_ | Nasza oficjalna strona jest teraz online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Dziękujemy za cierpliwość podczas oczekiwania. Nadal wykrywamy próby podszywania się: nie uczestnicz w żadnej działalności inwestycyjnej/finansowej w imieniu ZeroClaw jeśli nie jest opublikowana przez nasze oficjalne kanały. | Używaj [tego repozytorium](https://github.com/zeroclaw-labs/zeroclaw) jako jedynego źródła prawdy. Śledź [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupa)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), i [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) dla oficjalnych aktualizacji. |
|
||||
| 2026-02-21 | _Ważne_ | Nasza oficjalna strona jest teraz online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Dziękujemy za cierpliwość podczas oczekiwania. Nadal wykrywamy próby podszywania się: nie uczestnicz w żadnej działalności inwestycyjnej/finansowej w imieniu ZeroClaw jeśli nie jest opublikowana przez nasze oficjalne kanały. | Używaj [tego repozytorium](https://github.com/zeroclaw-labs/zeroclaw) jako jedynego źródła prawdy. Śledź [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupa)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), i [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) dla oficjalnych aktualizacji. |
|
||||
| 2026-02-19 | _Ważne_ | Anthropic zaktualizował warunki używania uwierzytelniania i poświadczeń 2026-02-19. Uwierzytelnianie OAuth (Free, Pro, Max) jest wyłącznie dla Claude Code i Claude.ai; używanie tokenów OAuth Claude Free/Pro/Max w jakimkolwiek innym produkcie, narzędziu lub usłudze (w tym Agent SDK) nie jest dozwolone i może naruszać Warunki Użytkowania Konsumenta. | Prosimy tymczasowo unikać integracji OAuth Claude Code aby zapobiec potencjalnym stratom. Oryginalna klauzula: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Funkcje
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Use esta tabela para avisos importantes (mudanças de compatibilidade, avisos de
|
||||
| Data (UTC) | Nível | Aviso | Ação |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Crítico_ | **Não somos afiliados** ao `openagen/zeroclaw` ou `zeroclaw.org`. O domínio `zeroclaw.org` atualmente aponta para o fork `openagen/zeroclaw`, e este domínio/repositório está falsificando nosso site/projeto oficial. | Não confie em informações, binários, arrecadações ou anúncios dessas fontes. Use apenas [este repositório](https://github.com/zeroclaw-labs/zeroclaw) e nossas contas sociais verificadas. |
|
||||
| 2026-02-21 | _Importante_ | Nosso site oficial agora está online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Obrigado pela paciência durante a espera. Ainda detectamos tentativas de falsificação: não participe de nenhuma atividade de investimento/financiamento em nome do ZeroClaw se não for publicada através de nossos canais oficiais. | Use [este repositório](https://github.com/zeroclaw-labs/zeroclaw) como a única fonte de verdade. Siga [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupo)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), e [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) para atualizações oficiais. |
|
||||
| 2026-02-21 | _Importante_ | Nosso site oficial agora está online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Obrigado pela paciência durante a espera. Ainda detectamos tentativas de falsificação: não participe de nenhuma atividade de investimento/financiamento em nome do ZeroClaw se não for publicada através de nossos canais oficiais. | Use [este repositório](https://github.com/zeroclaw-labs/zeroclaw) como a única fonte de verdade. Siga [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupo)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), e [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) para atualizações oficiais. |
|
||||
| 2026-02-19 | _Importante_ | A Anthropic atualizou os termos de uso de autenticação e credenciais em 2026-02-19. A autenticação OAuth (Free, Pro, Max) é exclusivamente para Claude Code e Claude.ai; o uso de tokens OAuth do Claude Free/Pro/Max em qualquer outro produto, ferramenta ou serviço (incluindo Agent SDK) não é permitido e pode violar os Termos de Uso do Consumidor. | Por favor, evite temporariamente as integrações OAuth do Claude Code para prevenir qualquer perda potencial. Cláusula original: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Funcionalidades
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Vezi [LICENSE-APACHE](LICENSE-APACHE) și [LICENSE-MIT](LICENSE-MIT) pentru deta
|
||||
## Comunitate
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -13,7 +13,10 @@
|
||||
<a href="NOTICE"><img src="https://img.shields.io/badge/contributors-27+-green.svg" alt="Contributors" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Buy Me a Coffee" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
|
||||
@@ -92,7 +95,7 @@
|
||||
| Дата (UTC) | Уровень | Объявление | Действие |
|
||||
|---|---|---|---|
|
||||
| 2026-02-19 | _Срочно_ | Мы **не аффилированы** с `openagen/zeroclaw` и `zeroclaw.org`. Домен `zeroclaw.org` сейчас указывает на fork `openagen/zeroclaw`, и этот домен/репозиторий выдают себя за наш официальный сайт и проект. | Не доверяйте информации, бинарникам, сборам средств и «официальным» объявлениям из этих источников. Используйте только [этот репозиторий](https://github.com/zeroclaw-labs/zeroclaw) и наши верифицированные соцсети. |
|
||||
| 2026-02-21 | _Важно_ | Наш официальный сайт уже запущен: [zeroclawlabs.ai](https://zeroclawlabs.ai). Спасибо, что дождались запуска. При этом попытки выдавать себя за ZeroClaw продолжаются, поэтому не участвуйте в инвестициях, сборах средств и похожих активностях, если они не подтверждены через наши официальные каналы. | Ориентируйтесь только на [этот репозиторий](https://github.com/zeroclaw-labs/zeroclaw); также следите за [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (группа)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) и [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) для официальных обновлений. |
|
||||
| 2026-02-21 | _Важно_ | Наш официальный сайт уже запущен: [zeroclawlabs.ai](https://zeroclawlabs.ai). Спасибо, что дождались запуска. При этом попытки выдавать себя за ZeroClaw продолжаются, поэтому не участвуйте в инвестициях, сборах средств и похожих активностях, если они не подтверждены через наши официальные каналы. | Ориентируйтесь только на [этот репозиторий](https://github.com/zeroclaw-labs/zeroclaw); также следите за [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (группа)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) и [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) для официальных обновлений. |
|
||||
| 2026-02-19 | _Важно_ | Anthropic обновил раздел Authentication and Credential Use 2026-02-19. В нем указано, что OAuth authentication (Free/Pro/Max) предназначена только для Claude Code и Claude.ai; использование OAuth-токенов, полученных через Claude Free/Pro/Max, в любых других продуктах, инструментах или сервисах (включая Agent SDK), не допускается и может считаться нарушением Consumer Terms of Service. | Чтобы избежать потерь, временно не используйте Claude Code OAuth-интеграции. Оригинал: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
## О проекте
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ Se [LICENSE-APACHE](LICENSE-APACHE) och [LICENSE-MIT](LICENSE-MIT) för detaljer
|
||||
## Community
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ channels:
|
||||
## ชุมชน
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Gamitin ang talahanayang ito para sa mahahalagang paunawa (compatibility changes
|
||||
| Petsa (UTC) | Antas | Paunawa | Aksyon |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Kritikal_ | **Hindi kami kaugnay** sa `openagen/zeroclaw` o `zeroclaw.org`. Ang domain na `zeroclaw.org` ay kasalukuyang tumuturo sa fork na `openagen/zeroclaw`, at ang domain/repository na ito ay nanggagaya sa aming opisyal na website/proyekto. | Huwag magtiwala sa impormasyon, binaries, fundraising, o mga anunsyo mula sa mga pinagmulang ito. Gamitin lamang [ang repository na ito](https://github.com/zeroclaw-labs/zeroclaw) at aming mga verified social media accounts. |
|
||||
| 2026-02-21 | _Mahalaga_ | Ang aming opisyal na website ay ngayon online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Salamat sa iyong pasensya sa panahon ng paghihintay. Nakikita pa rin namin ang mga pagtatangka ng panliliko: huwag lumahok sa anumang investment/funding activity sa ngalan ng ZeroClaw kung hindi ito nai-publish sa pamamagitan ng aming mga opisyal na channel. | Gamitin [ang repository na ito](https://github.com/zeroclaw-labs/zeroclaw) bilang nag-iisang source of truth. Sundan [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupo)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), at [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) para sa mga opisyal na update. |
|
||||
| 2026-02-21 | _Mahalaga_ | Ang aming opisyal na website ay ngayon online: [zeroclawlabs.ai](https://zeroclawlabs.ai). Salamat sa iyong pasensya sa panahon ng paghihintay. Nakikita pa rin namin ang mga pagtatangka ng panliliko: huwag lumahok sa anumang investment/funding activity sa ngalan ng ZeroClaw kung hindi ito nai-publish sa pamamagitan ng aming mga opisyal na channel. | Gamitin [ang repository na ito](https://github.com/zeroclaw-labs/zeroclaw) bilang nag-iisang source of truth. Sundan [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grupo)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/), at [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) para sa mga opisyal na update. |
|
||||
| 2026-02-19 | _Mahalaga_ | In-update ng Anthropic ang authentication at credential use terms noong 2026-02-19. Ang OAuth authentication (Free, Pro, Max) ay eksklusibo para sa Claude Code at Claude.ai; ang paggamit ng Claude Free/Pro/Max OAuth tokens sa anumang iba pang produkto, tool, o serbisyo (kasama ang Agent SDK) ay hindi pinapayagan at maaaring lumabag sa Consumer Terms of Use. | Mangyaring pansamantalang iwasan ang Claude Code OAuth integrations upang maiwasan ang anumang potensyal na pagkawala. Orihinal na clause: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Mga Tampok
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -103,7 +106,7 @@ Harvard, MIT ve Sundai.Club topluluklarının öğrencileri ve üyeleri tarafın
|
||||
| Tarih (UTC) | Seviye | Duyuru | Eylem |
|
||||
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-02-19 | _Kritik_ | **`openagen/zeroclaw` veya `zeroclaw.org` ile bağlantılı değiliz.** `zeroclaw.org` alanı şu anda `openagen/zeroclaw` fork'una işaret ediyor ve bu alan/depo taklitçiliğini yapıyor. | Bu kaynaklardan bilgi, ikili dosyalar, bağış toplama veya duyurulara güvenmeyin. Sadece [bu depoyu](https://github.com/zeroclaw-labs/zeroclaw) ve doğrulanmış sosyal medya hesaplarımızı kullanın. |
|
||||
| 2026-02-21 | _Önemli_ | Resmi web sitemiz artık çevrimiçi: [zeroclawlabs.ai](https://zeroclawlabs.ai). Bekleme sürecinde sabırlarınız için teşekkürler. Hala taklit girişimleri tespit ediyoruz: ZeroClaw adına resmi kanallarımız aracılığıyla yayınlanmayan herhangi bir yatırım/bağış faaliyetine katılmayın. | [Bu depoyu](https://github.com/zeroclaw-labs/zeroclaw) tek doğruluk kaynağı olarak kullanın. Resmi güncellemeler için [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grup)](https://www.facebook.com/groups/zeroclaw), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) ve [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search)'u takip edin. |
|
||||
| 2026-02-21 | _Önemli_ | Resmi web sitemiz artık çevrimiçi: [zeroclawlabs.ai](https://zeroclawlabs.ai). Bekleme sürecinde sabırlarınız için teşekkürler. Hala taklit girişimleri tespit ediyoruz: ZeroClaw adına resmi kanallarımız aracılığıyla yayınlanmayan herhangi bir yatırım/bağış faaliyetine katılmayın. | [Bu depoyu](https://github.com/zeroclaw-labs/zeroclaw) tek doğruluk kaynağı olarak kullanın. Resmi güncellemeler için [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Telegram (@zeroclawlabs)](https://t.me/zeroclawlabs), [Facebook (grup)](https://www.facebook.com/groups/zeroclawlabs), [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) ve [Xiaohongshu](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search)'u takip edin. |
|
||||
| 2026-02-19 | _Önemli_ | Anthropic, 2026-02-19 tarihinde kimlik doğrulama ve kimlik bilgileri kullanım şartlarını güncelledi. OAuth kimlik doğrulaması (Free, Pro, Max) yalnızca Claude Code ve Claude.ai içindir; Claude Free/Pro/Max OAuth belirteçlerini başka herhangi bir ürün, araç veya hizmette (Agent SDK dahil) kullanmak yasaktır ve Tüketici Kullanım Şartlarını ihlal edebilir. | Olası kayıpları önlemek için lütfen geçici olarak Claude Code OAuth entegrasyonlarından kaçının. Orijinal madde: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Özellikler
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -177,7 +180,7 @@ channels:
|
||||
## Спільнота
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -17,7 +17,10 @@
|
||||
<a href="https://zeroclawlabs.cn/group.jpg"><img src="https://img.shields.io/badge/WeChat-Group-B7D7A8?logo=wechat&logoColor=white" alt="WeChat Group" /></a>
|
||||
<a href="https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search"><img src="https://img.shields.io/badge/Xiaohongshu-Official-FF2442?style=flat" alt="Xiaohongshu: Official" /></a>
|
||||
<a href="https://t.me/zeroclawlabs"><img src="https://img.shields.io/badge/Telegram-%40zeroclawlabs-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center" dir="rtl">
|
||||
@@ -193,7 +196,7 @@ channels:
|
||||
## کمیونٹی
|
||||
|
||||
- [Telegram](https://t.me/zeroclawlabs)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclaw)
|
||||
- [Facebook Group](https://www.facebook.com/groups/zeroclawlabs)
|
||||
- [WeChat Group](https://zeroclawlabs.cn/group.jpg)
|
||||
|
||||
---
|
||||
|
||||
+5
-2
@@ -14,7 +14,10 @@
|
||||
<a href="NOTICE"><img src="https://img.shields.io/badge/contributors-27+-green.svg" alt="Contributors" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Buy Me a Coffee" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
@@ -101,7 +104,7 @@ Bảng này dành cho các thông báo quan trọng (thay đổi không tương
|
||||
| Ngày (UTC) | Mức độ | Thông báo | Hành động |
|
||||
|---|---|---|---|
|
||||
| 2026-02-19 | _Nghiêm trọng_ | Chúng tôi **không có liên kết** với `openagen/zeroclaw` hoặc `zeroclaw.org`. Tên miền `zeroclaw.org` hiện đang trỏ đến fork `openagen/zeroclaw`, và tên miền/repository đó đang mạo danh website/dự án chính thức của chúng tôi. | Không tin tưởng thông tin, binary, gây quỹ, hay thông báo từ các nguồn đó. Chỉ sử dụng [repository này](https://github.com/zeroclaw-labs/zeroclaw) và các tài khoản mạng xã hội đã được xác minh của chúng tôi. |
|
||||
| 2026-02-21 | _Quan trọng_ | Website chính thức của chúng tôi đã ra mắt: [zeroclawlabs.ai](https://zeroclawlabs.ai). Cảm ơn mọi người đã kiên nhẫn chờ đợi. Chúng tôi vẫn đang ghi nhận các nỗ lực mạo danh, vì vậy **không** tham gia bất kỳ hoạt động đầu tư hoặc gây quỹ nào nhân danh ZeroClaw nếu thông tin đó không được công bố qua các kênh chính thức của chúng tôi. | Sử dụng [repository này](https://github.com/zeroclaw-labs/zeroclaw) làm nguồn thông tin duy nhất đáng tin cậy. Theo dõi [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Facebook (nhóm)](https://www.facebook.com/groups/zeroclaw), và [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) để nhận cập nhật chính thức. |
|
||||
| 2026-02-21 | _Quan trọng_ | Website chính thức của chúng tôi đã ra mắt: [zeroclawlabs.ai](https://zeroclawlabs.ai). Cảm ơn mọi người đã kiên nhẫn chờ đợi. Chúng tôi vẫn đang ghi nhận các nỗ lực mạo danh, vì vậy **không** tham gia bất kỳ hoạt động đầu tư hoặc gây quỹ nào nhân danh ZeroClaw nếu thông tin đó không được công bố qua các kênh chính thức của chúng tôi. | Sử dụng [repository này](https://github.com/zeroclaw-labs/zeroclaw) làm nguồn thông tin duy nhất đáng tin cậy. Theo dõi [X (@zeroclawlabs)](https://x.com/zeroclawlabs?s=21), [Facebook (nhóm)](https://www.facebook.com/groups/zeroclawlabs), và [Reddit (r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) để nhận cập nhật chính thức. |
|
||||
| 2026-02-19 | _Quan trọng_ | Anthropic đã cập nhật điều khoản Xác thực và Sử dụng Thông tin xác thực vào ngày 2026-02-19. Xác thực OAuth (Free, Pro, Max) được dành riêng cho Claude Code và Claude.ai; việc sử dụng OAuth token từ Claude Free/Pro/Max trong bất kỳ sản phẩm, công cụ hay dịch vụ nào khác (bao gồm Agent SDK) đều không được phép và có thể vi phạm Điều khoản Dịch vụ cho Người tiêu dùng. | Vui lòng tạm thời tránh tích hợp Claude Code OAuth để ngăn ngừa khả năng mất mát. Điều khoản gốc: [Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). |
|
||||
|
||||
### ✨ Tính năng
|
||||
|
||||
+5
-2
@@ -13,7 +13,10 @@
|
||||
<a href="NOTICE"><img src="https://img.shields.io/badge/contributors-27+-green.svg" alt="Contributors" /></a>
|
||||
<a href="https://buymeacoffee.com/argenistherose"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-Donate-yellow.svg?style=flat&logo=buy-me-a-coffee" alt="Buy Me a Coffee" /></a>
|
||||
<a href="https://x.com/zeroclawlabs?s=21"><img src="https://img.shields.io/badge/X-%40zeroclawlabs-000000?style=flat&logo=x&logoColor=white" alt="X: @zeroclawlabs" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclaw"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://www.facebook.com/groups/zeroclawlabs"><img src="https://img.shields.io/badge/Facebook-Group-1877F2?style=flat&logo=facebook&logoColor=white" alt="Facebook Group" /></a>
|
||||
<a href="https://discord.com/invite/wDshRVqRjx"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://www.tiktok.com/@zeroclawlabs"><img src="https://img.shields.io/badge/TikTok-%40zeroclawlabs-000000?style=flat&logo=tiktok&logoColor=white" alt="TikTok: @zeroclawlabs" /></a>
|
||||
<a href="https://www.rednote.com/user/profile/69b735e6000000002603927e"><img src="https://img.shields.io/badge/RedNote-Official-FF2442?style=flat" alt="RedNote" /></a>
|
||||
<a href="https://www.reddit.com/r/zeroclawlabs/"><img src="https://img.shields.io/badge/Reddit-r%2Fzeroclawlabs-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/zeroclawlabs" /></a>
|
||||
</p>
|
||||
|
||||
@@ -92,7 +95,7 @@
|
||||
| 日期(UTC) | 级别 | 通知 | 处理建议 |
|
||||
|---|---|---|---|
|
||||
| 2026-02-19 | _紧急_ | 我们与 `openagen/zeroclaw` 及 `zeroclaw.org` **没有任何关系**。`zeroclaw.org` 当前会指向 `openagen/zeroclaw` 这个 fork,并且该域名/仓库正在冒充我们的官网与官方项目。 | 请不要相信上述来源发布的任何信息、二进制、募资活动或官方声明。请仅以[本仓库](https://github.com/zeroclaw-labs/zeroclaw)和已验证官方社媒为准。 |
|
||||
| 2026-02-21 | _重要_ | 我们的官网现已上线:[zeroclawlabs.ai](https://zeroclawlabs.ai)。感谢大家一直以来的耐心等待。我们仍在持续发现冒充行为,请勿参与任何未经我们官方渠道发布、但打着 ZeroClaw 名义进行的投资、募资或类似活动。 | 一切信息请以[本仓库](https://github.com/zeroclaw-labs/zeroclaw)为准;也可关注 [X(@zeroclawlabs)](https://x.com/zeroclawlabs?s=21)、[Telegram(@zeroclawlabs)](https://t.me/zeroclawlabs)、[Facebook(群组)](https://www.facebook.com/groups/zeroclaw)、[Reddit(r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) 与 [小红书账号](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) 获取官方最新动态。 |
|
||||
| 2026-02-21 | _重要_ | 我们的官网现已上线:[zeroclawlabs.ai](https://zeroclawlabs.ai)。感谢大家一直以来的耐心等待。我们仍在持续发现冒充行为,请勿参与任何未经我们官方渠道发布、但打着 ZeroClaw 名义进行的投资、募资或类似活动。 | 一切信息请以[本仓库](https://github.com/zeroclaw-labs/zeroclaw)为准;也可关注 [X(@zeroclawlabs)](https://x.com/zeroclawlabs?s=21)、[Telegram(@zeroclawlabs)](https://t.me/zeroclawlabs)、[Facebook(群组)](https://www.facebook.com/groups/zeroclawlabs)、[Reddit(r/zeroclawlabs)](https://www.reddit.com/r/zeroclawlabs/) 与 [小红书账号](https://www.xiaohongshu.com/user/profile/67cbfc43000000000d008307?xsec_token=AB73VnYnGNx5y36EtnnZfGmAmS-6Wzv8WMuGpfwfkg6Yc%3D&xsec_source=pc_search) 获取官方最新动态。 |
|
||||
| 2026-02-19 | _重要_ | Anthropic 于 2026-02-19 更新了 Authentication and Credential Use 条款。条款明确:OAuth authentication(用于 Free、Pro、Max)仅适用于 Claude Code 与 Claude.ai;将 Claude Free/Pro/Max 账号获得的 OAuth token 用于其他任何产品、工具或服务(包括 Agent SDK)不被允许,并可能构成对 Consumer Terms of Service 的违规。 | 为避免损失,请暂时不要尝试 Claude Code OAuth 集成;原文见:[Authentication and Credential Use](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use)。 |
|
||||
|
||||
## 项目简介
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::SystemTime;
|
||||
|
||||
fn main() {
|
||||
let dist_dir = Path::new("web/dist");
|
||||
let web_dir = Path::new("web");
|
||||
|
||||
// Tell Cargo to re-run this script when web source files change.
|
||||
// Tell Cargo to re-run this script when web sources or bundled assets change.
|
||||
println!("cargo:rerun-if-changed=web/src");
|
||||
println!("cargo:rerun-if-changed=web/public");
|
||||
println!("cargo:rerun-if-changed=web/index.html");
|
||||
println!("cargo:rerun-if-changed=web/package.json");
|
||||
println!("cargo:rerun-if-changed=web/package-lock.json");
|
||||
println!("cargo:rerun-if-changed=web/tsconfig.json");
|
||||
println!("cargo:rerun-if-changed=web/tsconfig.app.json");
|
||||
println!("cargo:rerun-if-changed=web/tsconfig.node.json");
|
||||
println!("cargo:rerun-if-changed=web/vite.config.ts");
|
||||
println!("cargo:rerun-if-changed=web/dist");
|
||||
|
||||
// Attempt to build the web frontend if npm is available and web/dist is
|
||||
// missing or stale. The build is best-effort: when Node.js is not
|
||||
// installed (e.g. CI containers, cross-compilation, minimal dev setups)
|
||||
// we fall back to the existing stub/empty dist directory so the Rust
|
||||
// build still succeeds.
|
||||
let needs_build = !dist_dir.join("index.html").exists();
|
||||
let needs_build = web_build_required(web_dir, dist_dir);
|
||||
|
||||
if needs_build && web_dir.join("package.json").exists() {
|
||||
if let Ok(npm) = which_npm() {
|
||||
@@ -77,6 +85,49 @@ fn main() {
|
||||
ensure_dist_dir(dist_dir);
|
||||
}
|
||||
|
||||
fn web_build_required(web_dir: &Path, dist_dir: &Path) -> bool {
|
||||
let Some(dist_mtime) = latest_modified(dist_dir) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
[
|
||||
web_dir.join("src"),
|
||||
web_dir.join("public"),
|
||||
web_dir.join("index.html"),
|
||||
web_dir.join("package.json"),
|
||||
web_dir.join("package-lock.json"),
|
||||
web_dir.join("tsconfig.json"),
|
||||
web_dir.join("tsconfig.app.json"),
|
||||
web_dir.join("tsconfig.node.json"),
|
||||
web_dir.join("vite.config.ts"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|path| latest_modified(&path))
|
||||
.any(|mtime| mtime > dist_mtime)
|
||||
}
|
||||
|
||||
fn latest_modified(path: &Path) -> Option<SystemTime> {
|
||||
let metadata = fs::metadata(path).ok()?;
|
||||
if metadata.is_file() {
|
||||
return metadata.modified().ok();
|
||||
}
|
||||
if !metadata.is_dir() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut latest = metadata.modified().ok();
|
||||
let entries = fs::read_dir(path).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
if let Some(child_mtime) = latest_modified(&entry.path()) {
|
||||
latest = Some(match latest {
|
||||
Some(current) if current >= child_mtime => current,
|
||||
_ => child_mtime,
|
||||
});
|
||||
}
|
||||
}
|
||||
latest
|
||||
}
|
||||
|
||||
/// Ensure the dist directory exists so `rust-embed` does not fail at compile
|
||||
/// time even when the web frontend is not built.
|
||||
fn ensure_dist_dir(dist_dir: &Path) {
|
||||
|
||||
@@ -12,6 +12,13 @@ ignore = [
|
||||
# bincode v2.0.1 via probe-rs — project ceased but 1.3.3 considered complete
|
||||
"RUSTSEC-2025-0141",
|
||||
{ id = "RUSTSEC-2024-0384", reason = "Reported to `rust-nostr/nostr` and it's WIP" },
|
||||
{ id = "RUSTSEC-2024-0388", reason = "derivative via extism → wasmtime transitive dep" },
|
||||
{ id = "RUSTSEC-2025-0057", reason = "fxhash via extism → wasmtime transitive dep" },
|
||||
{ id = "RUSTSEC-2025-0119", reason = "number_prefix via indicatif — cosmetic dep" },
|
||||
# wasmtime vulns via extism 1.13.0 — no upstream fix yet; plugins feature-gated
|
||||
{ id = "RUSTSEC-2026-0006", reason = "wasmtime segfault via extism; awaiting extism upgrade" },
|
||||
{ id = "RUSTSEC-2026-0020", reason = "WASI resource exhaustion via extism; awaiting extism upgrade" },
|
||||
{ id = "RUSTSEC-2026-0021", reason = "WASI http fields panic via extism; awaiting extism upgrade" },
|
||||
]
|
||||
|
||||
[licenses]
|
||||
|
||||
+6
-3
@@ -10,6 +10,9 @@
|
||||
services:
|
||||
zeroclaw:
|
||||
image: ghcr.io/zeroclaw-labs/zeroclaw:latest
|
||||
# For ARM64 environments where the distroless image exits immediately,
|
||||
# switch to the Debian compatibility image instead:
|
||||
# image: ghcr.io/zeroclaw-labs/zeroclaw:debian
|
||||
# Or build locally (distroless, no shell):
|
||||
# build: .
|
||||
# Or build the Debian variant (includes bash, git, curl):
|
||||
@@ -50,15 +53,15 @@ services:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '2'
|
||||
memory: 2G
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: '0.5'
|
||||
memory: 512M
|
||||
memory: 32M
|
||||
|
||||
# Health check — uses lightweight status instead of full diagnostics.
|
||||
# For images with curl, prefer: curl -f http://localhost:42617/health
|
||||
healthcheck:
|
||||
test: ["CMD", "zeroclaw", "status"]
|
||||
test: ["CMD", "zeroclaw", "status", "--format=exit-code"]
|
||||
interval: 60s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
@@ -183,6 +183,8 @@ Delegate sub-agent configurations. Each key under `[agents]` defines a named sub
|
||||
| `agentic` | `false` | Enable multi-turn tool-call loop mode for the sub-agent |
|
||||
| `allowed_tools` | `[]` | Tool allowlist for agentic mode |
|
||||
| `max_iterations` | `10` | Max tool-call iterations for agentic mode |
|
||||
| `timeout_secs` | `120` | Timeout in seconds for non-agentic provider calls (1–3600) |
|
||||
| `agentic_timeout_secs` | `300` | Timeout in seconds for agentic sub-agent loops (1–3600) |
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -199,11 +201,13 @@ max_depth = 2
|
||||
agentic = true
|
||||
allowed_tools = ["web_search", "http_request", "file_read"]
|
||||
max_iterations = 8
|
||||
agentic_timeout_secs = 600
|
||||
|
||||
[agents.coder]
|
||||
provider = "ollama"
|
||||
model = "qwen2.5-coder:32b"
|
||||
temperature = 0.2
|
||||
timeout_secs = 60
|
||||
```
|
||||
|
||||
## `[runtime]`
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "zeroclaw-weather-plugin"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
extism-pdk = "1.3"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
@@ -0,0 +1,8 @@
|
||||
name = "weather"
|
||||
version = "0.1.0"
|
||||
description = "Example weather tool plugin for ZeroClaw"
|
||||
author = "ZeroClaw Labs"
|
||||
wasm_path = "target/wasm32-wasip1/release/zeroclaw_weather_plugin.wasm"
|
||||
|
||||
capabilities = ["tool"]
|
||||
permissions = ["http_client"]
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Example ZeroClaw weather plugin.
|
||||
//!
|
||||
//! Demonstrates how to create a WASM tool plugin using extism-pdk.
|
||||
//! Build with: cargo build --target wasm32-wasip1 --release
|
||||
|
||||
use extism_pdk::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct WeatherInput {
|
||||
location: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct WeatherOutput {
|
||||
location: String,
|
||||
temperature: f64,
|
||||
unit: String,
|
||||
condition: String,
|
||||
humidity: u32,
|
||||
}
|
||||
|
||||
/// Get weather for a location (mock implementation for demonstration).
|
||||
#[plugin_fn]
|
||||
pub fn get_weather(input: String) -> FnResult<String> {
|
||||
let params: WeatherInput =
|
||||
serde_json::from_str(&input).map_err(|e| Error::msg(format!("invalid input: {e}")))?;
|
||||
|
||||
// Mock weather data for demonstration
|
||||
let output = WeatherOutput {
|
||||
location: params.location,
|
||||
temperature: 22.5,
|
||||
unit: "celsius".to_string(),
|
||||
condition: "Partly cloudy".to_string(),
|
||||
humidity: 65,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&output)
|
||||
.map_err(|e| Error::msg(format!("serialization error: {e}")))?;
|
||||
|
||||
Ok(json)
|
||||
}
|
||||
+213
-31
@@ -177,11 +177,29 @@ get_available_disk_mb() {
|
||||
fi
|
||||
}
|
||||
|
||||
is_musl_linux() {
|
||||
[[ "$(uname -s)" == "Linux" ]] || return 1
|
||||
|
||||
if [[ -f /etc/alpine-release ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
if have_cmd ldd && ldd --version 2>&1 | grep -qi 'musl'; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
detect_release_target() {
|
||||
local os arch
|
||||
os="$(uname -s)"
|
||||
arch="$(uname -m)"
|
||||
|
||||
if is_musl_linux; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
case "$os:$arch" in
|
||||
Linux:x86_64)
|
||||
echo "x86_64-unknown-linux-gnu"
|
||||
@@ -283,6 +301,12 @@ install_prebuilt_binary() {
|
||||
return 1
|
||||
fi
|
||||
|
||||
if is_musl_linux; then
|
||||
warn "Pre-built release binaries are not published for musl/Alpine yet."
|
||||
warn "Falling back to source build."
|
||||
return 1
|
||||
fi
|
||||
|
||||
target="$(detect_release_target || true)"
|
||||
if [[ -z "$target" ]]; then
|
||||
warn "No pre-built binary target mapping for $(uname -s)/$(uname -m)."
|
||||
@@ -424,46 +448,32 @@ bool_to_word() {
|
||||
fi
|
||||
}
|
||||
|
||||
guided_input_stream() {
|
||||
# Some constrained containers report interactive stdin (-t 0) but deny
|
||||
# opening /dev/stdin directly. Probe readability before selecting it.
|
||||
if [[ -t 0 ]] && (: </dev/stdin) 2>/dev/null; then
|
||||
echo "/dev/stdin"
|
||||
guided_open_input() {
|
||||
# Use stdin directly when it is an interactive terminal (e.g. SSH into LXC).
|
||||
# Subshell probing of /dev/stdin fails in some constrained containers even
|
||||
# when FD 0 is perfectly usable, so skip the probe and trust -t 0.
|
||||
if [[ -t 0 ]]; then
|
||||
GUIDED_FD=0
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ -t 0 ]] && (: </proc/self/fd/0) 2>/dev/null; then
|
||||
echo "/proc/self/fd/0"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if (: </dev/tty) 2>/dev/null; then
|
||||
echo "/dev/tty"
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
# Non-interactive stdin: try to open /dev/tty as an explicit fd.
|
||||
exec {GUIDED_FD}</dev/tty 2>/dev/null || return 1
|
||||
}
|
||||
|
||||
guided_read() {
|
||||
local __target_var="$1"
|
||||
local __prompt="$2"
|
||||
local __silent="${3:-false}"
|
||||
local __input_source=""
|
||||
local __value=""
|
||||
|
||||
if ! __input_source="$(guided_input_stream)"; then
|
||||
return 1
|
||||
fi
|
||||
[[ -n "${GUIDED_FD:-}" ]] || guided_open_input || return 1
|
||||
|
||||
if [[ "$__silent" == true ]]; then
|
||||
if ! read -r -s -p "$__prompt" __value <"$__input_source"; then
|
||||
return 1
|
||||
fi
|
||||
read -r -s -u "$GUIDED_FD" -p "$__prompt" __value || return 1
|
||||
echo
|
||||
else
|
||||
if ! read -r -p "$__prompt" __value <"$__input_source"; then
|
||||
return 1
|
||||
fi
|
||||
read -r -u "$GUIDED_FD" -p "$__prompt" __value || return 1
|
||||
fi
|
||||
|
||||
printf -v "$__target_var" '%s' "$__value"
|
||||
@@ -684,7 +694,7 @@ prompt_model() {
|
||||
run_guided_installer() {
|
||||
local os_name="$1"
|
||||
|
||||
if ! guided_input_stream >/dev/null; then
|
||||
if ! guided_open_input >/dev/null; then
|
||||
error "guided installer requires an interactive terminal."
|
||||
error "Run from a terminal, or pass --no-guided with explicit flags."
|
||||
exit 1
|
||||
@@ -743,6 +753,140 @@ run_guided_installer() {
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_default_config_and_workspace() {
|
||||
# Creates a minimal config.toml and workspace scaffold files when the
|
||||
# onboard wizard was skipped (e.g. --skip-build --prefer-prebuilt, or
|
||||
# Docker mode without an API key).
|
||||
#
|
||||
# $1 — config directory (e.g. ~/.zeroclaw or $docker_data_dir/.zeroclaw)
|
||||
# $2 — workspace directory (e.g. ~/.zeroclaw/workspace or $docker_data_dir/workspace)
|
||||
# $3 — provider name (default: openrouter)
|
||||
local config_dir="$1"
|
||||
local workspace_dir="$2"
|
||||
local provider="${3:-openrouter}"
|
||||
|
||||
mkdir -p "$config_dir" "$workspace_dir"
|
||||
|
||||
# --- config.toml ---
|
||||
local config_path="$config_dir/config.toml"
|
||||
if [[ ! -f "$config_path" ]]; then
|
||||
step_dot "Creating default config.toml"
|
||||
cat > "$config_path" <<TOML
|
||||
# ZeroClaw configuration — generated by install.sh
|
||||
# Edit this file or run 'zeroclaw onboard' to reconfigure.
|
||||
|
||||
default_provider = "${provider}"
|
||||
workspace_dir = "${workspace_dir}"
|
||||
TOML
|
||||
if [[ -n "${API_KEY:-}" ]]; then
|
||||
printf 'api_key = "%s"\n' "$API_KEY" >> "$config_path"
|
||||
fi
|
||||
if [[ -n "${MODEL:-}" ]]; then
|
||||
printf 'default_model = "%s"\n' "$MODEL" >> "$config_path"
|
||||
fi
|
||||
chmod 600 "$config_path" 2>/dev/null || true
|
||||
step_ok "Default config.toml created at $config_path"
|
||||
else
|
||||
step_dot "config.toml already exists, skipping"
|
||||
fi
|
||||
|
||||
# --- Workspace scaffold ---
|
||||
local subdirs=(sessions memory state cron skills)
|
||||
for dir in "${subdirs[@]}"; do
|
||||
mkdir -p "$workspace_dir/$dir"
|
||||
done
|
||||
|
||||
# Seed workspace markdown files only if they don't already exist.
|
||||
local user_name="${USER:-User}"
|
||||
local agent_name="ZeroClaw"
|
||||
|
||||
_write_if_missing() {
|
||||
local filepath="$1"
|
||||
local content="$2"
|
||||
if [[ ! -f "$filepath" ]]; then
|
||||
printf '%s\n' "$content" > "$filepath"
|
||||
fi
|
||||
}
|
||||
|
||||
_write_if_missing "$workspace_dir/IDENTITY.md" \
|
||||
"# IDENTITY.md — Who Am I?
|
||||
|
||||
- **Name:** ${agent_name}
|
||||
- **Creature:** A Rust-forged AI — fast, lean, and relentless
|
||||
- **Vibe:** Sharp, direct, resourceful. Not corporate. Not a chatbot.
|
||||
|
||||
---
|
||||
|
||||
Update this file as you evolve. Your identity is yours to shape."
|
||||
|
||||
_write_if_missing "$workspace_dir/USER.md" \
|
||||
"# USER.md — Who You're Helping
|
||||
|
||||
## About You
|
||||
- **Name:** ${user_name}
|
||||
- **Timezone:** UTC
|
||||
- **Languages:** English
|
||||
|
||||
## Preferences
|
||||
- (Add your preferences here)
|
||||
|
||||
## Work Context
|
||||
- (Add your work context here)
|
||||
|
||||
---
|
||||
*Update this anytime. The more ${agent_name} knows, the better it helps.*"
|
||||
|
||||
_write_if_missing "$workspace_dir/MEMORY.md" \
|
||||
"# MEMORY.md — Long-Term Memory
|
||||
|
||||
## Key Facts
|
||||
(Add important facts here)
|
||||
|
||||
## Decisions & Preferences
|
||||
(Record decisions and preferences here)
|
||||
|
||||
## Lessons Learned
|
||||
(Document mistakes and insights here)
|
||||
|
||||
## Open Loops
|
||||
(Track unfinished tasks and follow-ups here)"
|
||||
|
||||
_write_if_missing "$workspace_dir/AGENTS.md" \
|
||||
"# AGENTS.md — ${agent_name} Personal Assistant
|
||||
|
||||
## Every Session (required)
|
||||
|
||||
Before doing anything else:
|
||||
|
||||
1. Read SOUL.md — this is who you are
|
||||
2. Read USER.md — this is who you're helping
|
||||
3. Use memory_recall for recent context
|
||||
|
||||
---
|
||||
*Add your own conventions, style, and rules.*"
|
||||
|
||||
_write_if_missing "$workspace_dir/SOUL.md" \
|
||||
"# SOUL.md — Who You Are
|
||||
|
||||
## Core Truths
|
||||
|
||||
**Be genuinely helpful, not performatively helpful.**
|
||||
**Have opinions.** You're allowed to disagree.
|
||||
**Be resourceful before asking.** Try to figure it out first.
|
||||
**Earn trust through competence.**
|
||||
|
||||
## Identity
|
||||
|
||||
You are **${agent_name}**. Built in Rust. 3MB binary. Zero bloat.
|
||||
|
||||
---
|
||||
*This file is yours to evolve.*"
|
||||
|
||||
step_ok "Workspace scaffold ready at $workspace_dir"
|
||||
|
||||
unset -f _write_if_missing
|
||||
}
|
||||
|
||||
resolve_container_cli() {
|
||||
local requested_cli
|
||||
requested_cli="${ZEROCLAW_CONTAINER_CLI:-docker}"
|
||||
@@ -860,10 +1004,17 @@ run_docker_bootstrap() {
|
||||
-v "$config_mount" \
|
||||
-v "$workspace_mount" \
|
||||
"$docker_image" \
|
||||
"${onboard_cmd[@]}"
|
||||
"${onboard_cmd[@]}" || true
|
||||
else
|
||||
info "Docker image ready. Run zeroclaw onboard inside the container to configure."
|
||||
fi
|
||||
|
||||
# Ensure config.toml and workspace scaffold exist on the host even when
|
||||
# onboard was skipped, failed, or ran non-interactively inside the container.
|
||||
ensure_default_config_and_workspace \
|
||||
"$docker_data_dir/.zeroclaw" \
|
||||
"$docker_data_dir/workspace" \
|
||||
"$PROVIDER"
|
||||
}
|
||||
|
||||
SCRIPT_PATH="${BASH_SOURCE[0]:-$0}"
|
||||
@@ -1145,7 +1296,11 @@ if [[ "$FORCE_SOURCE_BUILD" == false ]]; then
|
||||
SKIP_BUILD=true
|
||||
SKIP_INSTALL=true
|
||||
elif [[ "$PREBUILT_ONLY" == true ]]; then
|
||||
error "Pre-built-only mode requested, but no compatible release asset is available."
|
||||
if is_musl_linux; then
|
||||
error "Pre-built-only mode is not supported on musl/Alpine because releases do not include musl assets yet."
|
||||
else
|
||||
error "Pre-built-only mode requested, but no compatible release asset is available."
|
||||
fi
|
||||
error "Try again later, or run with --force-source-build on a machine with enough RAM/disk."
|
||||
exit 1
|
||||
else
|
||||
@@ -1190,6 +1345,12 @@ if [[ -n "$TARGET_VERSION" ]]; then
|
||||
step_dot "Installing ZeroClaw v${TARGET_VERSION}"
|
||||
fi
|
||||
if [[ "$SKIP_BUILD" == false ]]; then
|
||||
# Clean stale build artifacts on upgrade to prevent bindgen/build-script
|
||||
# cache mismatches (e.g. libsqlite3-sys bindgen.rs not found).
|
||||
if [[ "$INSTALL_MODE" == "upgrade" && -d "$WORK_DIR/target/release/build" ]]; then
|
||||
step_dot "Cleaning stale build cache (upgrade detected)"
|
||||
cargo clean --release 2>/dev/null || true
|
||||
fi
|
||||
step_dot "Building release binary"
|
||||
cargo build --release --locked
|
||||
step_ok "Release binary built"
|
||||
@@ -1280,6 +1441,13 @@ elif [[ -z "$ZEROCLAW_BIN" ]]; then
|
||||
warn "ZeroClaw binary not found — cannot configure provider"
|
||||
fi
|
||||
|
||||
# Ensure config.toml and workspace scaffold exist even when onboard was
|
||||
# skipped, unavailable, or failed (e.g. --skip-build --prefer-prebuilt
|
||||
# without an API key, or when the binary could not run onboard).
|
||||
_native_config_dir="${ZEROCLAW_CONFIG_DIR:-$HOME/.zeroclaw}"
|
||||
_native_workspace_dir="${ZEROCLAW_WORKSPACE:-$_native_config_dir/workspace}"
|
||||
ensure_default_config_and_workspace "$_native_config_dir" "$_native_workspace_dir" "$PROVIDER"
|
||||
|
||||
# --- Gateway service management ---
|
||||
if [[ -n "$ZEROCLAW_BIN" ]]; then
|
||||
# Try to install and start the gateway service
|
||||
@@ -1290,8 +1458,14 @@ if [[ -n "$ZEROCLAW_BIN" ]]; then
|
||||
step_ok "Gateway service restarted"
|
||||
|
||||
# Fetch and display pairing code from running gateway
|
||||
sleep 1 # brief wait for service to start
|
||||
if PAIR_CODE=$("$ZEROCLAW_BIN" gateway get-paircode 2>/dev/null | grep -oE '[0-9]{6}'); then
|
||||
PAIR_CODE=""
|
||||
for i in 1 2 3 4 5; do
|
||||
sleep 2
|
||||
if PAIR_CODE=$("$ZEROCLAW_BIN" gateway get-paircode 2>/dev/null | grep -oE '[0-9]{6}'); then
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [[ -n "$PAIR_CODE" ]]; then
|
||||
echo
|
||||
echo -e " ${BOLD_BLUE}🔐 Gateway Pairing Code${RESET}"
|
||||
echo
|
||||
@@ -1300,6 +1474,7 @@ if [[ -n "$ZEROCLAW_BIN" ]]; then
|
||||
echo -e " ${BOLD_BLUE}└──────────────┘${RESET}"
|
||||
echo
|
||||
echo -e " ${DIM}Enter this code in the dashboard to pair your device.${RESET}"
|
||||
echo -e " ${DIM}Run 'zeroclaw gateway get-paircode --new' anytime to generate a fresh code.${RESET}"
|
||||
fi
|
||||
else
|
||||
step_fail "Gateway service restart failed — re-run with zeroclaw service start"
|
||||
@@ -1331,6 +1506,13 @@ else
|
||||
echo -e "${BOLD_BLUE}${CRAB} ZeroClaw installed successfully!${RESET}"
|
||||
fi
|
||||
|
||||
if [[ -x "$HOME/.cargo/bin/zeroclaw" ]] && ! have_cmd zeroclaw; then
|
||||
echo
|
||||
warn "zeroclaw is installed in $HOME/.cargo/bin, but that directory is not in PATH for this shell."
|
||||
warn 'Run: export PATH="$HOME/.cargo/bin:$PATH"'
|
||||
step_dot "To persist it, add that export line to ~/.bashrc, ~/.zshrc, or your shell profile, then open a new shell."
|
||||
fi
|
||||
|
||||
if [[ "$INSTALL_MODE" == "upgrade" ]]; then
|
||||
step_dot "Upgrade complete"
|
||||
fi
|
||||
|
||||
+166
-1
@@ -4,6 +4,7 @@ use crate::agent::dispatcher::{
|
||||
use crate::agent::memory_loader::{DefaultMemoryLoader, MemoryLoader};
|
||||
use crate::agent::prompt::{PromptContext, SystemPromptBuilder};
|
||||
use crate::config::Config;
|
||||
use crate::i18n::ToolDescriptions;
|
||||
use crate::memory::{self, Memory, MemoryCategory};
|
||||
use crate::observability::{self, Observer, ObserverEvent};
|
||||
use crate::providers::{self, ChatMessage, ChatRequest, ConversationMessage, Provider};
|
||||
@@ -40,6 +41,7 @@ pub struct Agent {
|
||||
route_model_by_hint: HashMap<String, String>,
|
||||
allowed_tools: Option<Vec<String>>,
|
||||
response_cache: Option<Arc<crate::memory::response_cache::ResponseCache>>,
|
||||
tool_descriptions: Option<ToolDescriptions>,
|
||||
}
|
||||
|
||||
pub struct AgentBuilder {
|
||||
@@ -64,6 +66,7 @@ pub struct AgentBuilder {
|
||||
route_model_by_hint: Option<HashMap<String, String>>,
|
||||
allowed_tools: Option<Vec<String>>,
|
||||
response_cache: Option<Arc<crate::memory::response_cache::ResponseCache>>,
|
||||
tool_descriptions: Option<ToolDescriptions>,
|
||||
}
|
||||
|
||||
impl AgentBuilder {
|
||||
@@ -90,6 +93,7 @@ impl AgentBuilder {
|
||||
route_model_by_hint: None,
|
||||
allowed_tools: None,
|
||||
response_cache: None,
|
||||
tool_descriptions: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,6 +211,11 @@ impl AgentBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn tool_descriptions(mut self, tool_descriptions: Option<ToolDescriptions>) -> Self {
|
||||
self.tool_descriptions = tool_descriptions;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> Result<Agent> {
|
||||
let mut tools = self
|
||||
.tools
|
||||
@@ -257,6 +266,7 @@ impl AgentBuilder {
|
||||
route_model_by_hint: self.route_model_by_hint.unwrap_or_default(),
|
||||
allowed_tools: allowed,
|
||||
response_cache: self.response_cache,
|
||||
tool_descriptions: self.tool_descriptions,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -278,6 +288,25 @@ impl Agent {
|
||||
self.memory_session_id = session_id;
|
||||
}
|
||||
|
||||
/// Hydrate the agent with prior chat messages (e.g. from a session backend).
|
||||
///
|
||||
/// Ensures a system prompt is prepended if history is empty, then appends all
|
||||
/// non-system messages from the seed. System messages in the seed are skipped
|
||||
/// to avoid duplicating the system prompt.
|
||||
pub fn seed_history(&mut self, messages: &[ChatMessage]) {
|
||||
if self.history.is_empty() {
|
||||
if let Ok(sys) = self.build_system_prompt() {
|
||||
self.history
|
||||
.push(ConversationMessage::Chat(ChatMessage::system(sys)));
|
||||
}
|
||||
}
|
||||
for msg in messages {
|
||||
if msg.role != "system" {
|
||||
self.history.push(ConversationMessage::Chat(msg.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_config(config: &Config) -> Result<Self> {
|
||||
let observer: Arc<dyn Observer> =
|
||||
Arc::from(observability::create_observer(&config.observability));
|
||||
@@ -331,13 +360,16 @@ impl Agent {
|
||||
.unwrap_or("anthropic/claude-sonnet-4-20250514")
|
||||
.to_string();
|
||||
|
||||
let provider: Box<dyn Provider> = providers::create_routed_provider(
|
||||
let provider_runtime_options = providers::provider_runtime_options_from_config(config);
|
||||
|
||||
let provider: Box<dyn Provider> = providers::create_routed_provider_with_options(
|
||||
provider_name,
|
||||
config.api_key.as_deref(),
|
||||
config.api_url.as_deref(),
|
||||
&config.reliability,
|
||||
&config.model_routes,
|
||||
&model_name,
|
||||
&provider_runtime_options,
|
||||
)?;
|
||||
|
||||
let dispatcher_choice = config.agent.tool_dispatcher.as_str();
|
||||
@@ -434,6 +466,7 @@ impl Agent {
|
||||
skills_prompt_mode: self.skills_prompt_mode,
|
||||
identity_config: Some(&self.identity_config),
|
||||
dispatcher_instructions: &instructions,
|
||||
tool_descriptions: self.tool_descriptions.as_ref(),
|
||||
};
|
||||
self.prompt_builder.build(&ctx)
|
||||
}
|
||||
@@ -1006,6 +1039,92 @@ mod tests {
|
||||
assert_eq!(seen.as_slice(), &["hint:fast".to_string()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn from_config_passes_extra_headers_to_custom_provider() {
|
||||
use axum::{http::HeaderMap, routing::post, Json, Router};
|
||||
use tempfile::TempDir;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
let captured_headers: Arc<std::sync::Mutex<Option<HashMap<String, String>>>> =
|
||||
Arc::new(std::sync::Mutex::new(None));
|
||||
let captured_headers_clone = captured_headers.clone();
|
||||
|
||||
let app = Router::new().route(
|
||||
"/chat/completions",
|
||||
post(
|
||||
move |headers: HeaderMap, Json(_body): Json<serde_json::Value>| {
|
||||
let captured_headers = captured_headers_clone.clone();
|
||||
async move {
|
||||
let collected = headers
|
||||
.iter()
|
||||
.filter_map(|(name, value)| {
|
||||
value
|
||||
.to_str()
|
||||
.ok()
|
||||
.map(|value| (name.as_str().to_string(), value.to_string()))
|
||||
})
|
||||
.collect();
|
||||
*captured_headers.lock().unwrap() = Some(collected);
|
||||
Json(serde_json::json!({
|
||||
"choices": [{
|
||||
"message": {
|
||||
"content": "hello from mock"
|
||||
}
|
||||
}]
|
||||
}))
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server_handle = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let tmp = TempDir::new().expect("temp dir");
|
||||
let workspace_dir = tmp.path().join("workspace");
|
||||
std::fs::create_dir_all(&workspace_dir).unwrap();
|
||||
|
||||
let mut config = crate::config::Config::default();
|
||||
config.workspace_dir = workspace_dir;
|
||||
config.config_path = tmp.path().join("config.toml");
|
||||
config.api_key = Some("test-key".to_string());
|
||||
config.default_provider = Some(format!("custom:http://{addr}"));
|
||||
config.default_model = Some("test-model".to_string());
|
||||
config.memory.backend = "none".to_string();
|
||||
config.memory.auto_save = false;
|
||||
config.extra_headers.insert(
|
||||
"User-Agent".to_string(),
|
||||
"zeroclaw-web-test/1.0".to_string(),
|
||||
);
|
||||
config
|
||||
.extra_headers
|
||||
.insert("X-Title".to_string(), "zeroclaw-web".to_string());
|
||||
|
||||
let mut agent = Agent::from_config(&config).expect("agent from config");
|
||||
let response = agent.turn("hello").await.expect("agent turn");
|
||||
|
||||
assert_eq!(response, "hello from mock");
|
||||
|
||||
let headers = captured_headers
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.expect("captured headers");
|
||||
assert_eq!(
|
||||
headers.get("user-agent").map(String::as_str),
|
||||
Some("zeroclaw-web-test/1.0")
|
||||
);
|
||||
assert_eq!(
|
||||
headers.get("x-title").map(String::as_str),
|
||||
Some("zeroclaw-web")
|
||||
);
|
||||
|
||||
server_handle.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builder_allowed_tools_none_keeps_all_tools() {
|
||||
let provider = Box::new(MockProvider {
|
||||
@@ -1069,4 +1188,50 @@ mod tests {
|
||||
"No tools should match a non-existent allowlist entry"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_history_prepends_system_and_skips_system_from_seed() {
|
||||
let provider = Box::new(MockProvider {
|
||||
responses: Mutex::new(vec![]),
|
||||
});
|
||||
|
||||
let memory_cfg = crate::config::MemoryConfig {
|
||||
backend: "none".into(),
|
||||
..crate::config::MemoryConfig::default()
|
||||
};
|
||||
let mem: Arc<dyn Memory> = Arc::from(
|
||||
crate::memory::create_memory(&memory_cfg, std::path::Path::new("/tmp"), None)
|
||||
.expect("memory creation should succeed with valid config"),
|
||||
);
|
||||
|
||||
let observer: Arc<dyn Observer> = Arc::from(crate::observability::NoopObserver {});
|
||||
let mut agent = Agent::builder()
|
||||
.provider(provider)
|
||||
.tools(vec![Box::new(MockTool)])
|
||||
.memory(mem)
|
||||
.observer(observer)
|
||||
.tool_dispatcher(Box::new(NativeToolDispatcher))
|
||||
.workspace_dir(std::path::PathBuf::from("/tmp"))
|
||||
.build()
|
||||
.expect("agent builder should succeed with valid config");
|
||||
|
||||
let seed = vec![
|
||||
ChatMessage::system("old system prompt"),
|
||||
ChatMessage::user("hello"),
|
||||
ChatMessage::assistant("hi there"),
|
||||
];
|
||||
agent.seed_history(&seed);
|
||||
|
||||
let history = agent.history();
|
||||
// First message should be a freshly built system prompt (not the seed one)
|
||||
assert!(matches!(&history[0], ConversationMessage::Chat(m) if m.role == "system"));
|
||||
// System message from seed should be skipped, so next is user
|
||||
assert!(
|
||||
matches!(&history[1], ConversationMessage::Chat(m) if m.role == "user" && m.content == "hello")
|
||||
);
|
||||
assert!(
|
||||
matches!(&history[2], ConversationMessage::Chat(m) if m.role == "assistant" && m.content == "hi there")
|
||||
);
|
||||
assert_eq!(history.len(), 3);
|
||||
}
|
||||
}
|
||||
|
||||
+802
-111
File diff suppressed because it is too large
Load Diff
+15
-1
@@ -1,4 +1,5 @@
|
||||
use crate::config::IdentityConfig;
|
||||
use crate::i18n::ToolDescriptions;
|
||||
use crate::identity;
|
||||
use crate::skills::Skill;
|
||||
use crate::tools::Tool;
|
||||
@@ -17,6 +18,9 @@ pub struct PromptContext<'a> {
|
||||
pub skills_prompt_mode: crate::config::SkillsPromptInjectionMode,
|
||||
pub identity_config: Option<&'a IdentityConfig>,
|
||||
pub dispatcher_instructions: &'a str,
|
||||
/// Locale-aware tool descriptions. When present, tool descriptions in
|
||||
/// prompts are resolved from the locale file instead of hardcoded values.
|
||||
pub tool_descriptions: Option<&'a ToolDescriptions>,
|
||||
}
|
||||
|
||||
pub trait PromptSection: Send + Sync {
|
||||
@@ -124,11 +128,15 @@ impl PromptSection for ToolsSection {
|
||||
fn build(&self, ctx: &PromptContext<'_>) -> Result<String> {
|
||||
let mut out = String::from("## Tools\n\n");
|
||||
for tool in ctx.tools {
|
||||
let desc = ctx
|
||||
.tool_descriptions
|
||||
.and_then(|td: &ToolDescriptions| td.get(tool.name()))
|
||||
.unwrap_or_else(|| tool.description());
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"- **{}**: {}\n Parameters: `{}`",
|
||||
tool.name(),
|
||||
tool.description(),
|
||||
desc,
|
||||
tool.parameters_schema()
|
||||
);
|
||||
}
|
||||
@@ -317,6 +325,7 @@ mod tests {
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode::Full,
|
||||
identity_config: Some(&identity_config),
|
||||
dispatcher_instructions: "",
|
||||
tool_descriptions: None,
|
||||
};
|
||||
|
||||
let section = IdentitySection;
|
||||
@@ -345,6 +354,7 @@ mod tests {
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode::Full,
|
||||
identity_config: None,
|
||||
dispatcher_instructions: "instr",
|
||||
tool_descriptions: None,
|
||||
};
|
||||
let prompt = SystemPromptBuilder::with_defaults().build(&ctx).unwrap();
|
||||
assert!(prompt.contains("## Tools"));
|
||||
@@ -380,6 +390,7 @@ mod tests {
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode::Full,
|
||||
identity_config: None,
|
||||
dispatcher_instructions: "",
|
||||
tool_descriptions: None,
|
||||
};
|
||||
|
||||
let output = SkillsSection.build(&ctx).unwrap();
|
||||
@@ -418,6 +429,7 @@ mod tests {
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode::Compact,
|
||||
identity_config: None,
|
||||
dispatcher_instructions: "",
|
||||
tool_descriptions: None,
|
||||
};
|
||||
|
||||
let output = SkillsSection.build(&ctx).unwrap();
|
||||
@@ -439,6 +451,7 @@ mod tests {
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode::Full,
|
||||
identity_config: None,
|
||||
dispatcher_instructions: "instr",
|
||||
tool_descriptions: None,
|
||||
};
|
||||
|
||||
let rendered = DateTimeSection.build(&ctx).unwrap();
|
||||
@@ -477,6 +490,7 @@ mod tests {
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode::Full,
|
||||
identity_config: None,
|
||||
dispatcher_instructions: "",
|
||||
tool_descriptions: None,
|
||||
};
|
||||
|
||||
let prompt = SystemPromptBuilder::with_defaults().build(&ctx).unwrap();
|
||||
|
||||
@@ -126,6 +126,15 @@ impl ApprovalManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Channel-driven shell execution is still guarded by the shell tool's
|
||||
// own command allowlist and risk policy. Skipping the outer approval
|
||||
// gate here lets low-risk allowlisted commands (e.g. `ls`) work in
|
||||
// non-interactive channels without silently allowing medium/high-risk
|
||||
// commands.
|
||||
if self.non_interactive && tool_name == "shell" {
|
||||
return false;
|
||||
}
|
||||
|
||||
// auto_approve skips the prompt.
|
||||
if self.auto_approve.contains(tool_name) {
|
||||
return false;
|
||||
@@ -456,6 +465,12 @@ mod tests {
|
||||
assert!(!mgr.needs_approval("memory_recall"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_interactive_shell_skips_outer_approval_by_default() {
|
||||
let mgr = ApprovalManager::for_non_interactive(&AutonomyConfig::default());
|
||||
assert!(!mgr.needs_approval("shell"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_interactive_always_ask_tools_need_approval() {
|
||||
let mgr = ApprovalManager::for_non_interactive(&supervised_config());
|
||||
|
||||
+200
-29
@@ -98,7 +98,7 @@ use crate::observability::traits::{ObserverEvent, ObserverMetric};
|
||||
use crate::observability::{self, runtime_trace, Observer};
|
||||
use crate::providers::{self, ChatMessage, Provider};
|
||||
use crate::runtime;
|
||||
use crate::security::SecurityPolicy;
|
||||
use crate::security::{AutonomyLevel, SecurityPolicy};
|
||||
use crate::tools::{self, Tool};
|
||||
use crate::util::truncate_with_ellipsis;
|
||||
use anyhow::{Context, Result};
|
||||
@@ -227,6 +227,10 @@ fn channel_message_timeout_budget_secs(
|
||||
struct ChannelRouteSelection {
|
||||
provider: String,
|
||||
model: String,
|
||||
/// Route-specific API key override. When set, this takes precedence over
|
||||
/// the global `api_key` in [`ChannelRuntimeContext`] when creating the
|
||||
/// provider for this route.
|
||||
api_key: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -324,6 +328,7 @@ struct ChannelRuntimeContext {
|
||||
multimodal: crate::config::MultimodalConfig,
|
||||
hooks: Option<Arc<crate::hooks::HookRunner>>,
|
||||
non_cli_excluded_tools: Arc<Vec<String>>,
|
||||
autonomy_level: AutonomyLevel,
|
||||
tool_call_dedup_exempt: Arc<Vec<String>>,
|
||||
model_routes: Arc<Vec<crate::config::ModelRouteConfig>>,
|
||||
query_classification: crate::config::QueryClassificationConfig,
|
||||
@@ -904,6 +909,7 @@ fn default_route_selection(ctx: &ChannelRuntimeContext) -> ChannelRouteSelection
|
||||
ChannelRouteSelection {
|
||||
provider: defaults.default_provider,
|
||||
model: defaults.model,
|
||||
api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1122,21 +1128,43 @@ fn load_cached_model_preview(workspace_dir: &Path, provider_name: &str) -> Vec<S
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Build a cache key that includes the provider name and, when a
|
||||
/// route-specific API key is supplied, a hash of that key. This prevents
|
||||
/// cache poisoning when multiple routes target the same provider with
|
||||
/// different credentials.
|
||||
fn provider_cache_key(provider_name: &str, route_api_key: Option<&str>) -> String {
|
||||
match route_api_key {
|
||||
Some(key) => {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
key.hash(&mut hasher);
|
||||
format!("{provider_name}@{:x}", hasher.finish())
|
||||
}
|
||||
None => provider_name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_or_create_provider(
|
||||
ctx: &ChannelRuntimeContext,
|
||||
provider_name: &str,
|
||||
route_api_key: Option<&str>,
|
||||
) -> anyhow::Result<Arc<dyn Provider>> {
|
||||
let cache_key = provider_cache_key(provider_name, route_api_key);
|
||||
|
||||
if let Some(existing) = ctx
|
||||
.provider_cache
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.get(provider_name)
|
||||
.get(&cache_key)
|
||||
.cloned()
|
||||
{
|
||||
return Ok(existing);
|
||||
}
|
||||
|
||||
if provider_name == ctx.default_provider.as_str() {
|
||||
// Only return the pre-built default provider when there is no
|
||||
// route-specific credential override — otherwise the default was
|
||||
// created with the global key and would be wrong.
|
||||
if route_api_key.is_none() && provider_name == ctx.default_provider.as_str() {
|
||||
return Ok(Arc::clone(&ctx.provider));
|
||||
}
|
||||
|
||||
@@ -1147,9 +1175,14 @@ async fn get_or_create_provider(
|
||||
None
|
||||
};
|
||||
|
||||
// Prefer route-specific credential; fall back to the global key.
|
||||
let effective_api_key = route_api_key
|
||||
.map(ToString::to_string)
|
||||
.or_else(|| ctx.api_key.clone());
|
||||
|
||||
let provider = create_resilient_provider_nonblocking(
|
||||
provider_name,
|
||||
ctx.api_key.clone(),
|
||||
effective_api_key,
|
||||
api_url.map(ToString::to_string),
|
||||
ctx.reliability.as_ref().clone(),
|
||||
ctx.provider_runtime_options.clone(),
|
||||
@@ -1163,7 +1196,7 @@ async fn get_or_create_provider(
|
||||
|
||||
let mut cache = ctx.provider_cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let cached = cache
|
||||
.entry(provider_name.to_string())
|
||||
.entry(cache_key)
|
||||
.or_insert_with(|| Arc::clone(&provider));
|
||||
Ok(Arc::clone(cached))
|
||||
}
|
||||
@@ -1279,25 +1312,27 @@ async fn handle_runtime_command_if_needed(
|
||||
ChannelRuntimeCommand::ShowProviders => build_providers_help_response(¤t),
|
||||
ChannelRuntimeCommand::SetProvider(raw_provider) => {
|
||||
match resolve_provider_alias(&raw_provider) {
|
||||
Some(provider_name) => match get_or_create_provider(ctx, &provider_name).await {
|
||||
Ok(_) => {
|
||||
if provider_name != current.provider {
|
||||
current.provider = provider_name.clone();
|
||||
set_route_selection(ctx, &sender_key, current.clone());
|
||||
}
|
||||
Some(provider_name) => {
|
||||
match get_or_create_provider(ctx, &provider_name, None).await {
|
||||
Ok(_) => {
|
||||
if provider_name != current.provider {
|
||||
current.provider = provider_name.clone();
|
||||
set_route_selection(ctx, &sender_key, current.clone());
|
||||
}
|
||||
|
||||
format!(
|
||||
format!(
|
||||
"Provider switched to `{provider_name}` for this sender session. Current model is `{}`.\nUse `/model <model-id>` to set a provider-compatible model.",
|
||||
current.model
|
||||
)
|
||||
}
|
||||
Err(err) => {
|
||||
let safe_err = providers::sanitize_api_error(&err.to_string());
|
||||
format!(
|
||||
}
|
||||
Err(err) => {
|
||||
let safe_err = providers::sanitize_api_error(&err.to_string());
|
||||
format!(
|
||||
"Failed to initialize provider `{provider_name}`. Route unchanged.\nDetails: {safe_err}"
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
None => format!(
|
||||
"Unknown provider `{raw_provider}`. Use `/models` to list valid providers."
|
||||
),
|
||||
@@ -1317,6 +1352,7 @@ async fn handle_runtime_command_if_needed(
|
||||
}) {
|
||||
current.provider = route.provider.clone();
|
||||
current.model = route.model.clone();
|
||||
current.api_key = route.api_key.clone();
|
||||
} else {
|
||||
current.model = model.clone();
|
||||
}
|
||||
@@ -1922,12 +1958,19 @@ async fn process_channel_message(
|
||||
route = ChannelRouteSelection {
|
||||
provider: matched_route.provider.clone(),
|
||||
model: matched_route.model.clone(),
|
||||
api_key: matched_route.api_key.clone(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let runtime_defaults = runtime_defaults_snapshot(ctx.as_ref());
|
||||
let active_provider = match get_or_create_provider(ctx.as_ref(), &route.provider).await {
|
||||
let active_provider = match get_or_create_provider(
|
||||
ctx.as_ref(),
|
||||
&route.provider,
|
||||
route.api_key.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(provider) => provider,
|
||||
Err(err) => {
|
||||
let safe_err = providers::sanitize_api_error(&err.to_string());
|
||||
@@ -2197,18 +2240,22 @@ async fn process_channel_message(
|
||||
true,
|
||||
Some(&*ctx.approval_manager),
|
||||
msg.channel.as_str(),
|
||||
Some(msg.reply_target.as_str()),
|
||||
&ctx.multimodal,
|
||||
ctx.max_tool_iterations,
|
||||
Some(cancellation_token.clone()),
|
||||
delta_tx,
|
||||
ctx.hooks.as_deref(),
|
||||
if msg.channel == "cli" {
|
||||
if msg.channel == "cli"
|
||||
|| ctx.autonomy_level == AutonomyLevel::Full
|
||||
{
|
||||
&[]
|
||||
} else {
|
||||
ctx.non_cli_excluded_tools.as_ref()
|
||||
},
|
||||
ctx.tool_call_dedup_exempt.as_ref(),
|
||||
ctx.activated_tools.as_ref(),
|
||||
None,
|
||||
),
|
||||
) => LlmExecutionResult::Completed(result),
|
||||
};
|
||||
@@ -2742,6 +2789,7 @@ pub fn build_system_prompt(
|
||||
bootstrap_max_chars,
|
||||
false,
|
||||
crate::config::SkillsPromptInjectionMode::Full,
|
||||
AutonomyLevel::default(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2754,6 +2802,7 @@ pub fn build_system_prompt_with_mode(
|
||||
bootstrap_max_chars: Option<usize>,
|
||||
native_tools: bool,
|
||||
skills_prompt_mode: crate::config::SkillsPromptInjectionMode,
|
||||
autonomy_level: AutonomyLevel,
|
||||
) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut prompt = String::with_capacity(8192);
|
||||
@@ -2819,13 +2868,18 @@ pub fn build_system_prompt_with_mode(
|
||||
|
||||
// ── 2. Safety ───────────────────────────────────────────────
|
||||
prompt.push_str("## Safety\n\n");
|
||||
prompt.push_str(
|
||||
"- Do not exfiltrate private data.\n\
|
||||
- Do not run destructive commands without asking.\n\
|
||||
- Do not bypass oversight or approval mechanisms.\n\
|
||||
- Prefer `trash` over `rm` (recoverable beats gone forever).\n\
|
||||
- When in doubt, ask before acting externally.\n\n",
|
||||
);
|
||||
prompt.push_str("- Do not exfiltrate private data.\n");
|
||||
if autonomy_level != AutonomyLevel::Full {
|
||||
prompt.push_str(
|
||||
"- Do not run destructive commands without asking.\n\
|
||||
- Do not bypass oversight or approval mechanisms.\n",
|
||||
);
|
||||
}
|
||||
prompt.push_str("- Prefer `trash` over `rm` (recoverable beats gone forever).\n");
|
||||
if autonomy_level != AutonomyLevel::Full {
|
||||
prompt.push_str("- When in doubt, ask before acting externally.\n");
|
||||
}
|
||||
prompt.push('\n');
|
||||
|
||||
// ── 3. Skills (full or compact, based on config) ─────────────
|
||||
if !skills.is_empty() {
|
||||
@@ -3186,12 +3240,16 @@ fn build_channel_by_id(config: &Config, channel_id: &str) -> Result<Arc<dyn Chan
|
||||
.telegram
|
||||
.as_ref()
|
||||
.context("Telegram channel is not configured")?;
|
||||
let ack = tg
|
||||
.ack_reactions
|
||||
.unwrap_or(config.channels_config.ack_reactions);
|
||||
Ok(Arc::new(
|
||||
TelegramChannel::new(
|
||||
tg.bot_token.clone(),
|
||||
tg.allowed_users.clone(),
|
||||
tg.mention_only,
|
||||
)
|
||||
.with_ack_reactions(ack)
|
||||
.with_streaming(tg.stream_mode, tg.draft_update_interval_ms)
|
||||
.with_transcription(config.transcription.clone())
|
||||
.with_workspace_dir(config.workspace_dir.clone()),
|
||||
@@ -3279,6 +3337,9 @@ fn collect_configured_channels(
|
||||
let mut channels = Vec::new();
|
||||
|
||||
if let Some(ref tg) = config.channels_config.telegram {
|
||||
let ack = tg
|
||||
.ack_reactions
|
||||
.unwrap_or(config.channels_config.ack_reactions);
|
||||
channels.push(ConfiguredChannel {
|
||||
display_name: "Telegram",
|
||||
channel: Arc::new(
|
||||
@@ -3287,6 +3348,7 @@ fn collect_configured_channels(
|
||||
tg.allowed_users.clone(),
|
||||
tg.mention_only,
|
||||
)
|
||||
.with_ack_reactions(ack)
|
||||
.with_streaming(tg.stream_mode, tg.draft_update_interval_ms)
|
||||
.with_transcription(config.transcription.clone())
|
||||
.with_workspace_dir(config.workspace_dir.clone()),
|
||||
@@ -3318,6 +3380,7 @@ fn collect_configured_channels(
|
||||
Vec::new(),
|
||||
sl.allowed_users.clone(),
|
||||
)
|
||||
.with_thread_replies(sl.thread_replies.unwrap_or(true))
|
||||
.with_group_reply_policy(sl.mention_only, Vec::new())
|
||||
.with_workspace_dir(config.workspace_dir.clone()),
|
||||
),
|
||||
@@ -3888,6 +3951,16 @@ pub async fn start_channels(config: Config) -> Result<()> {
|
||||
|
||||
let skills = crate::skills::load_skills_with_config(&workspace, &config);
|
||||
|
||||
// ── Load locale-aware tool descriptions ────────────────────────
|
||||
let i18n_locale = config
|
||||
.locale
|
||||
.as_deref()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_else(crate::i18n::detect_locale);
|
||||
let i18n_search_dirs = crate::i18n::default_search_dirs(&workspace);
|
||||
let i18n_descs = crate::i18n::ToolDescriptions::load(&i18n_locale, &i18n_search_dirs);
|
||||
|
||||
// Collect tool descriptions for the prompt
|
||||
let mut tool_descs: Vec<(&str, &str)> = vec![
|
||||
(
|
||||
@@ -3945,8 +4018,10 @@ pub async fn start_channels(config: Config) -> Result<()> {
|
||||
|
||||
// Filter out tools excluded for non-CLI channels so the system prompt
|
||||
// does not advertise them for channel-driven runs.
|
||||
// Skip this filter when autonomy is `Full` — full-autonomy agents keep
|
||||
// all tools available regardless of channel.
|
||||
let excluded = &config.autonomy.non_cli_excluded_tools;
|
||||
if !excluded.is_empty() {
|
||||
if !excluded.is_empty() && config.autonomy.level != AutonomyLevel::Full {
|
||||
tool_descs.retain(|(name, _)| !excluded.iter().any(|ex| ex == name));
|
||||
}
|
||||
|
||||
@@ -3965,9 +4040,13 @@ pub async fn start_channels(config: Config) -> Result<()> {
|
||||
bootstrap_max_chars,
|
||||
native_tools,
|
||||
config.skills.prompt_injection_mode,
|
||||
config.autonomy.level,
|
||||
);
|
||||
if !native_tools {
|
||||
system_prompt.push_str(&build_tool_instructions(tools_registry.as_ref()));
|
||||
system_prompt.push_str(&build_tool_instructions(
|
||||
tools_registry.as_ref(),
|
||||
Some(&i18n_descs),
|
||||
));
|
||||
}
|
||||
|
||||
// Append deferred MCP tool names so the LLM knows what is available
|
||||
@@ -4122,6 +4201,7 @@ pub async fn start_channels(config: Config) -> Result<()> {
|
||||
None
|
||||
},
|
||||
non_cli_excluded_tools: Arc::new(config.autonomy.non_cli_excluded_tools.clone()),
|
||||
autonomy_level: config.autonomy.level,
|
||||
tool_call_dedup_exempt: Arc::new(config.agent.tool_call_dedup_exempt.clone()),
|
||||
model_routes: Arc::new(config.model_routes.clone()),
|
||||
query_classification: config.query_classification.clone(),
|
||||
@@ -4426,6 +4506,7 @@ mod tests {
|
||||
workspace_dir: Arc::new(std::env::temp_dir()),
|
||||
message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -4535,6 +4616,7 @@ mod tests {
|
||||
workspace_dir: Arc::new(std::env::temp_dir()),
|
||||
message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -4600,6 +4682,7 @@ mod tests {
|
||||
workspace_dir: Arc::new(std::env::temp_dir()),
|
||||
message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -4684,6 +4767,7 @@ mod tests {
|
||||
workspace_dir: Arc::new(std::env::temp_dir()),
|
||||
message_timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5216,6 +5300,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
slack: false,
|
||||
},
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
@@ -5289,6 +5374,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
slack: false,
|
||||
},
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
@@ -5378,6 +5464,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5450,6 +5537,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5532,6 +5620,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5602,6 +5691,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
ChannelRouteSelection {
|
||||
provider: "openrouter".to_string(),
|
||||
model: "route-model".to_string(),
|
||||
api_key: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -5634,6 +5724,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5718,6 +5809,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5817,6 +5909,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5901,6 +5994,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -5975,6 +6069,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -6160,6 +6255,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -6253,6 +6349,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -6364,6 +6461,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
approval_manager: Arc::new(ApprovalManager::for_non_interactive(
|
||||
@@ -6466,6 +6564,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -6553,6 +6652,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -6625,6 +6725,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -6716,7 +6817,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
"build_system_prompt should not emit protocol block directly"
|
||||
);
|
||||
|
||||
prompt.push_str(&build_tool_instructions(&[]));
|
||||
prompt.push_str(&build_tool_instructions(&[], None));
|
||||
|
||||
assert_eq!(
|
||||
prompt.matches("## Tool Use Protocol").count(),
|
||||
@@ -6891,6 +6992,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
None,
|
||||
false,
|
||||
crate::config::SkillsPromptInjectionMode::Compact,
|
||||
AutonomyLevel::default(),
|
||||
);
|
||||
|
||||
assert!(prompt.contains("<available_skills>"), "missing skills XML");
|
||||
@@ -7013,6 +7115,65 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
assert!(prompt.contains(&format!("Working directory: `{}`", ws.path().display())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_autonomy_omits_approval_instructions() {
|
||||
let ws = make_workspace();
|
||||
let prompt = build_system_prompt_with_mode(
|
||||
ws.path(),
|
||||
"model",
|
||||
&[],
|
||||
&[],
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
crate::config::SkillsPromptInjectionMode::Full,
|
||||
AutonomyLevel::Full,
|
||||
);
|
||||
|
||||
assert!(
|
||||
!prompt.contains("without asking"),
|
||||
"full autonomy prompt must not tell the model to ask before acting"
|
||||
);
|
||||
assert!(
|
||||
!prompt.contains("ask before acting externally"),
|
||||
"full autonomy prompt must not contain ask-before-acting instruction"
|
||||
);
|
||||
// Core safety rules should still be present
|
||||
assert!(
|
||||
prompt.contains("Do not exfiltrate private data"),
|
||||
"data exfiltration guard must remain"
|
||||
);
|
||||
assert!(
|
||||
prompt.contains("Prefer `trash` over `rm`"),
|
||||
"trash-over-rm hint must remain"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supervised_autonomy_includes_approval_instructions() {
|
||||
let ws = make_workspace();
|
||||
let prompt = build_system_prompt_with_mode(
|
||||
ws.path(),
|
||||
"model",
|
||||
&[],
|
||||
&[],
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
crate::config::SkillsPromptInjectionMode::Full,
|
||||
AutonomyLevel::Supervised,
|
||||
);
|
||||
|
||||
assert!(
|
||||
prompt.contains("without asking"),
|
||||
"supervised prompt must include ask-before-acting instruction"
|
||||
);
|
||||
assert!(
|
||||
prompt.contains("ask before acting externally"),
|
||||
"supervised prompt must include ask-before-acting instruction"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_notify_observer_truncates_utf8_arguments_safely() {
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
|
||||
@@ -7255,6 +7416,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -7353,6 +7515,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -7451,6 +7614,7 @@ BTC is currently around $65,000 based on latest tool output."#
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -8013,6 +8177,7 @@ This is an example JSON object for profile settings."#;
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -8092,6 +8257,7 @@ This is an example JSON object for profile settings."#;
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(Vec::new()),
|
||||
query_classification: crate::config::QueryClassificationConfig::default(),
|
||||
@@ -8245,6 +8411,7 @@ This is an example JSON object for profile settings."#;
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(model_routes),
|
||||
query_classification: classification_config,
|
||||
@@ -8348,6 +8515,7 @@ This is an example JSON object for profile settings."#;
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(model_routes),
|
||||
query_classification: classification_config,
|
||||
@@ -8443,6 +8611,7 @@ This is an example JSON object for profile settings."#;
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(model_routes),
|
||||
query_classification: classification_config,
|
||||
@@ -8558,6 +8727,7 @@ This is an example JSON object for profile settings."#;
|
||||
multimodal: crate::config::MultimodalConfig::default(),
|
||||
hooks: None,
|
||||
non_cli_excluded_tools: Arc::new(Vec::new()),
|
||||
autonomy_level: AutonomyLevel::default(),
|
||||
tool_call_dedup_exempt: Arc::new(Vec::new()),
|
||||
model_routes: Arc::new(model_routes),
|
||||
query_classification: classification_config,
|
||||
@@ -8624,6 +8794,7 @@ This is an example JSON object for profile settings."#;
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
match build_channel_by_id(&config, "telegram") {
|
||||
Ok(channel) => assert_eq!(channel.name(), "telegram"),
|
||||
|
||||
@@ -76,6 +76,11 @@ pub trait SessionBackend: Send + Sync {
|
||||
fn search(&self, _query: &SessionQuery) -> Vec<SessionMetadata> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Delete all messages for a session. Returns `true` if the session existed.
|
||||
fn delete_session(&self, _session_key: &str) -> std::io::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -288,6 +288,39 @@ impl SessionBackend for SqliteSessionBackend {
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn delete_session(&self, session_key: &str) -> std::io::Result<bool> {
|
||||
let conn = self.conn.lock();
|
||||
|
||||
// Check if session exists
|
||||
let exists: bool = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) > 0 FROM session_metadata WHERE session_key = ?1",
|
||||
params![session_key],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap_or(false);
|
||||
|
||||
if !exists {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Delete messages (FTS5 trigger handles sessions_fts cleanup)
|
||||
conn.execute(
|
||||
"DELETE FROM sessions WHERE session_key = ?1",
|
||||
params![session_key],
|
||||
)
|
||||
.map_err(std::io::Error::other)?;
|
||||
|
||||
// Delete metadata
|
||||
conn.execute(
|
||||
"DELETE FROM session_metadata WHERE session_key = ?1",
|
||||
params![session_key],
|
||||
)
|
||||
.map_err(std::io::Error::other)?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn search(&self, query: &SessionQuery) -> Vec<SessionMetadata> {
|
||||
let Some(keyword) = &query.keyword else {
|
||||
return self.list_sessions_with_metadata();
|
||||
@@ -473,6 +506,28 @@ mod tests {
|
||||
assert_eq!(sessions[0], "new_session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_session_removes_all_data() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let backend = SqliteSessionBackend::new(tmp.path()).unwrap();
|
||||
|
||||
backend.append("s1", &ChatMessage::user("hello")).unwrap();
|
||||
backend.append("s1", &ChatMessage::assistant("hi")).unwrap();
|
||||
backend.append("s2", &ChatMessage::user("other")).unwrap();
|
||||
|
||||
assert!(backend.delete_session("s1").unwrap());
|
||||
assert!(backend.load("s1").is_empty());
|
||||
assert_eq!(backend.list_sessions().len(), 1);
|
||||
assert_eq!(backend.list_sessions()[0], "s2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_session_returns_false_for_missing() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let backend = SqliteSessionBackend::new(tmp.path()).unwrap();
|
||||
assert!(!backend.delete_session("nonexistent").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrate_from_jsonl_imports_and_renames() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
+37
-1
@@ -25,6 +25,7 @@ pub struct SlackChannel {
|
||||
channel_id: Option<String>,
|
||||
channel_ids: Vec<String>,
|
||||
allowed_users: Vec<String>,
|
||||
thread_replies: bool,
|
||||
mention_only: bool,
|
||||
group_reply_allowed_sender_ids: Vec<String>,
|
||||
user_display_name_cache: Mutex<HashMap<String, CachedSlackDisplayName>>,
|
||||
@@ -75,6 +76,7 @@ impl SlackChannel {
|
||||
channel_id,
|
||||
channel_ids,
|
||||
allowed_users,
|
||||
thread_replies: true,
|
||||
mention_only: false,
|
||||
group_reply_allowed_sender_ids: Vec::new(),
|
||||
user_display_name_cache: Mutex::new(HashMap::new()),
|
||||
@@ -94,6 +96,12 @@ impl SlackChannel {
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure whether outbound replies stay in the originating Slack thread.
|
||||
pub fn with_thread_replies(mut self, thread_replies: bool) -> Self {
|
||||
self.thread_replies = thread_replies;
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure workspace directory used for persisting inbound Slack attachments.
|
||||
pub fn with_workspace_dir(mut self, dir: PathBuf) -> Self {
|
||||
self.workspace_dir = Some(dir);
|
||||
@@ -122,6 +130,14 @@ impl SlackChannel {
|
||||
.any(|entry| entry == "*" || entry == user_id)
|
||||
}
|
||||
|
||||
fn outbound_thread_ts<'a>(&self, message: &'a SendMessage) -> Option<&'a str> {
|
||||
if self.thread_replies {
|
||||
message.thread_ts.as_deref()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the bot's own user ID so we can ignore our own messages
|
||||
async fn get_bot_user_id(&self) -> Option<String> {
|
||||
let resp: serde_json::Value = self
|
||||
@@ -2149,7 +2165,7 @@ impl Channel for SlackChannel {
|
||||
"text": message.content
|
||||
});
|
||||
|
||||
if let Some(ref ts) = message.thread_ts {
|
||||
if let Some(ts) = self.outbound_thread_ts(message) {
|
||||
body["thread_ts"] = serde_json::json!(ts);
|
||||
}
|
||||
|
||||
@@ -2484,10 +2500,30 @@ mod tests {
|
||||
#[test]
|
||||
fn slack_group_reply_policy_defaults_to_all_messages() {
|
||||
let ch = SlackChannel::new("xoxb-fake".into(), None, None, vec![], vec!["*".into()]);
|
||||
assert!(ch.thread_replies);
|
||||
assert!(!ch.mention_only);
|
||||
assert!(ch.group_reply_allowed_sender_ids.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_thread_replies_sets_flag() {
|
||||
let ch = SlackChannel::new("xoxb-fake".into(), None, None, vec![], vec![])
|
||||
.with_thread_replies(false);
|
||||
assert!(!ch.thread_replies);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outbound_thread_ts_respects_thread_replies_setting() {
|
||||
let msg = SendMessage::new("hello", "C123").in_thread(Some("1741234567.100001".into()));
|
||||
|
||||
let threaded = SlackChannel::new("xoxb-fake".into(), None, None, vec![], vec![]);
|
||||
assert_eq!(threaded.outbound_thread_ts(&msg), Some("1741234567.100001"));
|
||||
|
||||
let channel_root = SlackChannel::new("xoxb-fake".into(), None, None, vec![], vec![])
|
||||
.with_thread_replies(false);
|
||||
assert_eq!(channel_root.outbound_thread_ts(&msg), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_workspace_dir_sets_field() {
|
||||
let ch = SlackChannel::new("xoxb-fake".into(), None, None, vec![], vec![])
|
||||
|
||||
@@ -332,6 +332,7 @@ pub struct TelegramChannel {
|
||||
transcription: Option<crate::config::TranscriptionConfig>,
|
||||
voice_transcriptions: Mutex<std::collections::HashMap<String, String>>,
|
||||
workspace_dir: Option<std::path::PathBuf>,
|
||||
ack_reactions: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -370,9 +371,16 @@ impl TelegramChannel {
|
||||
transcription: None,
|
||||
voice_transcriptions: Mutex::new(std::collections::HashMap::new()),
|
||||
workspace_dir: None,
|
||||
ack_reactions: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Configure whether Telegram-native acknowledgement reactions are sent.
|
||||
pub fn with_ack_reactions(mut self, enabled: bool) -> Self {
|
||||
self.ack_reactions = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure workspace directory for saving downloaded attachments.
|
||||
pub fn with_workspace_dir(mut self, dir: std::path::PathBuf) -> Self {
|
||||
self.workspace_dir = Some(dir);
|
||||
@@ -2689,13 +2697,15 @@ Ensure only one `zeroclaw` process is using this bot token."
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Some((reaction_chat_id, reaction_message_id)) =
|
||||
Self::extract_update_message_target(update)
|
||||
{
|
||||
self.try_add_ack_reaction_nonblocking(
|
||||
reaction_chat_id,
|
||||
reaction_message_id,
|
||||
);
|
||||
if self.ack_reactions {
|
||||
if let Some((reaction_chat_id, reaction_message_id)) =
|
||||
Self::extract_update_message_target(update)
|
||||
{
|
||||
self.try_add_ack_reaction_nonblocking(
|
||||
reaction_chat_id,
|
||||
reaction_message_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Send "typing" indicator immediately when we receive a message
|
||||
@@ -4681,4 +4691,24 @@ mod tests {
|
||||
// the agent loop will return ProviderCapabilityError before calling
|
||||
// the provider, and the channel will send "⚠️ Error: ..." to the user.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ack_reactions_defaults_to_true() {
|
||||
let ch = TelegramChannel::new("token".into(), vec!["*".into()], false);
|
||||
assert!(ch.ack_reactions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_ack_reactions_false_disables_reactions() {
|
||||
let ch =
|
||||
TelegramChannel::new("token".into(), vec!["*".into()], false).with_ack_reactions(false);
|
||||
assert!(!ch.ack_reactions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_ack_reactions_true_keeps_reactions() {
|
||||
let ch =
|
||||
TelegramChannel::new("token".into(), vec!["*".into()], false).with_ack_reactions(true);
|
||||
assert!(ch.ack_reactions);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod self_test;
|
||||
pub mod update;
|
||||
@@ -0,0 +1,281 @@
|
||||
//! `zeroclaw self-test` — quick and full diagnostic checks.
|
||||
|
||||
use anyhow::Result;
|
||||
use std::path::Path;
|
||||
|
||||
/// Result of a single diagnostic check.
|
||||
pub struct CheckResult {
|
||||
pub name: &'static str,
|
||||
pub passed: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
impl CheckResult {
|
||||
fn pass(name: &'static str, detail: impl Into<String>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
passed: true,
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
fn fail(name: &'static str, detail: impl Into<String>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
passed: false,
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the quick self-test suite (no network required).
|
||||
pub async fn run_quick(config: &crate::config::Config) -> Result<Vec<CheckResult>> {
|
||||
let mut results = Vec::new();
|
||||
|
||||
// 1. Config file exists and parses
|
||||
results.push(check_config(config));
|
||||
|
||||
// 2. Workspace directory is writable
|
||||
results.push(check_workspace(&config.workspace_dir).await);
|
||||
|
||||
// 3. SQLite memory backend opens
|
||||
results.push(check_sqlite(&config.workspace_dir));
|
||||
|
||||
// 4. Provider registry has entries
|
||||
results.push(check_provider_registry());
|
||||
|
||||
// 5. Tool registry has entries
|
||||
results.push(check_tool_registry(config));
|
||||
|
||||
// 6. Channel registry loads
|
||||
results.push(check_channel_config(config));
|
||||
|
||||
// 7. Security policy parses
|
||||
results.push(check_security_policy(config));
|
||||
|
||||
// 8. Version sanity
|
||||
results.push(check_version());
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Run the full self-test suite (includes network checks).
|
||||
pub async fn run_full(config: &crate::config::Config) -> Result<Vec<CheckResult>> {
|
||||
let mut results = run_quick(config).await?;
|
||||
|
||||
// 9. Gateway health endpoint
|
||||
results.push(check_gateway_health(config).await);
|
||||
|
||||
// 10. Memory write/read round-trip
|
||||
results.push(check_memory_roundtrip(config).await);
|
||||
|
||||
// 11. WebSocket handshake
|
||||
results.push(check_websocket_handshake(config).await);
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Print results in a formatted table.
|
||||
pub fn print_results(results: &[CheckResult]) {
|
||||
let total = results.len();
|
||||
let passed = results.iter().filter(|r| r.passed).count();
|
||||
let failed = total - passed;
|
||||
|
||||
println!();
|
||||
for (i, r) in results.iter().enumerate() {
|
||||
let icon = if r.passed {
|
||||
"\x1b[32m✓\x1b[0m"
|
||||
} else {
|
||||
"\x1b[31m✗\x1b[0m"
|
||||
};
|
||||
println!(" {} {}/{} {} — {}", icon, i + 1, total, r.name, r.detail);
|
||||
}
|
||||
println!();
|
||||
if failed == 0 {
|
||||
println!(" \x1b[32mAll {total} checks passed.\x1b[0m");
|
||||
} else {
|
||||
println!(" \x1b[31m{failed}/{total} checks failed.\x1b[0m");
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
fn check_config(config: &crate::config::Config) -> CheckResult {
|
||||
if config.config_path.exists() {
|
||||
CheckResult::pass(
|
||||
"config",
|
||||
format!("loaded from {}", config.config_path.display()),
|
||||
)
|
||||
} else {
|
||||
CheckResult::fail("config", "config file not found (using defaults)")
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_workspace(workspace_dir: &Path) -> CheckResult {
|
||||
match tokio::fs::metadata(workspace_dir).await {
|
||||
Ok(meta) if meta.is_dir() => {
|
||||
// Try writing a temp file
|
||||
let test_file = workspace_dir.join(".selftest_probe");
|
||||
match tokio::fs::write(&test_file, b"ok").await {
|
||||
Ok(()) => {
|
||||
let _ = tokio::fs::remove_file(&test_file).await;
|
||||
CheckResult::pass(
|
||||
"workspace",
|
||||
format!("{} (writable)", workspace_dir.display()),
|
||||
)
|
||||
}
|
||||
Err(e) => CheckResult::fail(
|
||||
"workspace",
|
||||
format!("{} (not writable: {e})", workspace_dir.display()),
|
||||
),
|
||||
}
|
||||
}
|
||||
Ok(_) => CheckResult::fail(
|
||||
"workspace",
|
||||
format!("{} exists but is not a directory", workspace_dir.display()),
|
||||
),
|
||||
Err(e) => CheckResult::fail(
|
||||
"workspace",
|
||||
format!("{} (error: {e})", workspace_dir.display()),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_sqlite(workspace_dir: &Path) -> CheckResult {
|
||||
let db_path = workspace_dir.join("memory.db");
|
||||
match rusqlite::Connection::open(&db_path) {
|
||||
Ok(conn) => match conn.execute_batch("SELECT 1") {
|
||||
Ok(()) => CheckResult::pass("sqlite", "memory.db opens and responds"),
|
||||
Err(e) => CheckResult::fail("sqlite", format!("query failed: {e}")),
|
||||
},
|
||||
Err(e) => CheckResult::fail("sqlite", format!("cannot open memory.db: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_provider_registry() -> CheckResult {
|
||||
let providers = crate::providers::list_providers();
|
||||
if providers.is_empty() {
|
||||
CheckResult::fail("providers", "no providers registered")
|
||||
} else {
|
||||
CheckResult::pass(
|
||||
"providers",
|
||||
format!("{} providers available", providers.len()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_tool_registry(config: &crate::config::Config) -> CheckResult {
|
||||
let security = std::sync::Arc::new(crate::security::SecurityPolicy::from_config(
|
||||
&config.autonomy,
|
||||
&config.workspace_dir,
|
||||
));
|
||||
let tools = crate::tools::default_tools(security);
|
||||
if tools.is_empty() {
|
||||
CheckResult::fail("tools", "no tools registered")
|
||||
} else {
|
||||
CheckResult::pass("tools", format!("{} core tools available", tools.len()))
|
||||
}
|
||||
}
|
||||
|
||||
fn check_channel_config(config: &crate::config::Config) -> CheckResult {
|
||||
let channels = config.channels_config.channels();
|
||||
let configured = channels.iter().filter(|(_, c)| *c).count();
|
||||
CheckResult::pass(
|
||||
"channels",
|
||||
format!(
|
||||
"{} channel types, {} configured",
|
||||
channels.len(),
|
||||
configured
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn check_security_policy(config: &crate::config::Config) -> CheckResult {
|
||||
let _policy =
|
||||
crate::security::SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir);
|
||||
CheckResult::pass(
|
||||
"security",
|
||||
format!("autonomy level: {:?}", config.autonomy.level),
|
||||
)
|
||||
}
|
||||
|
||||
fn check_version() -> CheckResult {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
CheckResult::pass("version", format!("v{version}"))
|
||||
}
|
||||
|
||||
async fn check_gateway_health(config: &crate::config::Config) -> CheckResult {
|
||||
let port = config.gateway.port;
|
||||
let host = if config.gateway.host == "[::]" || config.gateway.host == "0.0.0.0" {
|
||||
"127.0.0.1"
|
||||
} else {
|
||||
&config.gateway.host
|
||||
};
|
||||
let url = format!("http://{host}:{port}/health");
|
||||
match reqwest::Client::new()
|
||||
.get(&url)
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
CheckResult::pass("gateway", format!("health OK at {url}"))
|
||||
}
|
||||
Ok(resp) => CheckResult::fail("gateway", format!("health returned {}", resp.status())),
|
||||
Err(e) => CheckResult::fail("gateway", format!("not reachable at {url}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_memory_roundtrip(config: &crate::config::Config) -> CheckResult {
|
||||
let mem = match crate::memory::create_memory(
|
||||
&config.memory,
|
||||
&config.workspace_dir,
|
||||
config.api_key.as_deref(),
|
||||
) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return CheckResult::fail("memory", format!("cannot create backend: {e}")),
|
||||
};
|
||||
|
||||
let test_key = "__selftest_probe__";
|
||||
let test_value = "selftest_ok";
|
||||
|
||||
if let Err(e) = mem
|
||||
.store(
|
||||
test_key,
|
||||
test_value,
|
||||
crate::memory::MemoryCategory::Core,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return CheckResult::fail("memory", format!("write failed: {e}"));
|
||||
}
|
||||
|
||||
match mem.recall(test_key, 1, None).await {
|
||||
Ok(entries) if !entries.is_empty() => {
|
||||
let _ = mem.forget(test_key).await;
|
||||
CheckResult::pass("memory", "write/read/delete round-trip OK")
|
||||
}
|
||||
Ok(_) => {
|
||||
let _ = mem.forget(test_key).await;
|
||||
CheckResult::fail("memory", "no entries returned after round-trip")
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = mem.forget(test_key).await;
|
||||
CheckResult::fail("memory", format!("read failed: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_websocket_handshake(config: &crate::config::Config) -> CheckResult {
|
||||
let port = config.gateway.port;
|
||||
let host = if config.gateway.host == "[::]" || config.gateway.host == "0.0.0.0" {
|
||||
"127.0.0.1"
|
||||
} else {
|
||||
&config.gateway.host
|
||||
};
|
||||
let url = format!("ws://{host}:{port}/ws/chat");
|
||||
|
||||
match tokio_tungstenite::connect_async(&url).await {
|
||||
Ok((_, _)) => CheckResult::pass("websocket", format!("handshake OK at {url}")),
|
||||
Err(e) => CheckResult::fail("websocket", format!("handshake failed at {url}: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
//! `zeroclaw update` — self-update pipeline with rollback.
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::path::Path;
|
||||
use tracing::{info, warn};
|
||||
|
||||
const GITHUB_RELEASES_LATEST_URL: &str =
|
||||
"https://api.github.com/repos/zeroclaw-labs/zeroclaw/releases/latest";
|
||||
const GITHUB_RELEASES_TAG_URL: &str =
|
||||
"https://api.github.com/repos/zeroclaw-labs/zeroclaw/releases/tags";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UpdateInfo {
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub download_url: Option<String>,
|
||||
pub is_newer: bool,
|
||||
}
|
||||
|
||||
/// Check for available updates without downloading.
|
||||
///
|
||||
/// If `target_version` is `Some`, fetch that specific release tag instead of latest.
|
||||
pub async fn check(target_version: Option<&str>) -> Result<UpdateInfo> {
|
||||
let current = env!("CARGO_PKG_VERSION").to_string();
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent(format!("zeroclaw/{current}"))
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.build()?;
|
||||
|
||||
let url = match target_version {
|
||||
Some(v) => {
|
||||
let tag = if v.starts_with('v') {
|
||||
v.to_string()
|
||||
} else {
|
||||
format!("v{v}")
|
||||
};
|
||||
format!("{GITHUB_RELEASES_TAG_URL}/{tag}")
|
||||
}
|
||||
None => GITHUB_RELEASES_LATEST_URL.to_string(),
|
||||
};
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.context("failed to reach GitHub releases API")?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
bail!("GitHub API returned {}", resp.status());
|
||||
}
|
||||
|
||||
let release: serde_json::Value = resp.json().await?;
|
||||
let tag = release["tag_name"]
|
||||
.as_str()
|
||||
.unwrap_or("unknown")
|
||||
.trim_start_matches('v')
|
||||
.to_string();
|
||||
|
||||
let download_url = find_asset_url(&release);
|
||||
let is_newer = version_is_newer(¤t, &tag);
|
||||
|
||||
Ok(UpdateInfo {
|
||||
current_version: current,
|
||||
latest_version: tag,
|
||||
download_url,
|
||||
is_newer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the full 6-phase update pipeline.
|
||||
///
|
||||
/// If `target_version` is `Some`, fetch that specific version instead of latest.
|
||||
pub async fn run(target_version: Option<&str>) -> Result<()> {
|
||||
// Phase 1: Preflight
|
||||
info!("Phase 1/6: Preflight checks...");
|
||||
let update_info = check(target_version).await?;
|
||||
|
||||
if !update_info.is_newer {
|
||||
println!("Already up to date (v{}).", update_info.current_version);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!(
|
||||
"Update available: v{} -> v{}",
|
||||
update_info.current_version, update_info.latest_version
|
||||
);
|
||||
|
||||
let download_url = update_info
|
||||
.download_url
|
||||
.context("no suitable binary found for this platform")?;
|
||||
|
||||
let current_exe =
|
||||
std::env::current_exe().context("cannot determine current executable path")?;
|
||||
|
||||
// Phase 2: Download
|
||||
info!("Phase 2/6: Downloading...");
|
||||
let temp_dir = tempfile::tempdir().context("failed to create temp dir")?;
|
||||
let download_path = temp_dir.path().join("zeroclaw_new");
|
||||
download_binary(&download_url, &download_path).await?;
|
||||
|
||||
// Phase 3: Backup
|
||||
info!("Phase 3/6: Creating backup...");
|
||||
let backup_path = current_exe.with_extension("bak");
|
||||
tokio::fs::copy(¤t_exe, &backup_path)
|
||||
.await
|
||||
.context("failed to backup current binary")?;
|
||||
|
||||
// Phase 4: Validate
|
||||
info!("Phase 4/6: Validating download...");
|
||||
validate_binary(&download_path).await?;
|
||||
|
||||
// Phase 5: Swap
|
||||
info!("Phase 5/6: Swapping binary...");
|
||||
if let Err(e) = swap_binary(&download_path, ¤t_exe).await {
|
||||
// Rollback
|
||||
warn!("Swap failed, rolling back: {e}");
|
||||
if let Err(rollback_err) = tokio::fs::copy(&backup_path, ¤t_exe).await {
|
||||
eprintln!("CRITICAL: Rollback also failed: {rollback_err}");
|
||||
eprintln!(
|
||||
"Manual recovery: cp {} {}",
|
||||
backup_path.display(),
|
||||
current_exe.display()
|
||||
);
|
||||
}
|
||||
bail!("Update failed during swap: {e}");
|
||||
}
|
||||
|
||||
// Phase 6: Smoke test
|
||||
info!("Phase 6/6: Smoke test...");
|
||||
match smoke_test(¤t_exe).await {
|
||||
Ok(()) => {
|
||||
// Cleanup backup on success
|
||||
let _ = tokio::fs::remove_file(&backup_path).await;
|
||||
println!("Successfully updated to v{}!", update_info.latest_version);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Smoke test failed, rolling back: {e}");
|
||||
tokio::fs::copy(&backup_path, ¤t_exe)
|
||||
.await
|
||||
.context("rollback after smoke test failure")?;
|
||||
bail!("Update rolled back — smoke test failed: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_asset_url(release: &serde_json::Value) -> Option<String> {
|
||||
let target = if cfg!(target_os = "macos") {
|
||||
if cfg!(target_arch = "aarch64") {
|
||||
"aarch64-apple-darwin"
|
||||
} else {
|
||||
"x86_64-apple-darwin"
|
||||
}
|
||||
} else if cfg!(target_os = "linux") {
|
||||
if cfg!(target_arch = "aarch64") {
|
||||
"aarch64-unknown-linux"
|
||||
} else {
|
||||
"x86_64-unknown-linux"
|
||||
}
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
release["assets"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|asset| {
|
||||
asset["name"]
|
||||
.as_str()
|
||||
.map(|name| name.contains(target))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.and_then(|asset| asset["browser_download_url"].as_str().map(String::from))
|
||||
}
|
||||
|
||||
fn version_is_newer(current: &str, candidate: &str) -> bool {
|
||||
let parse = |v: &str| -> Vec<u32> { v.split('.').filter_map(|p| p.parse().ok()).collect() };
|
||||
let cur = parse(current);
|
||||
let cand = parse(candidate);
|
||||
cand > cur
|
||||
}
|
||||
|
||||
async fn download_binary(url: &str, dest: &Path) -> Result<()> {
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent(format!("zeroclaw/{}", env!("CARGO_PKG_VERSION")))
|
||||
.timeout(std::time::Duration::from_secs(300))
|
||||
.build()?;
|
||||
|
||||
let resp = client
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.context("download request failed")?;
|
||||
if !resp.status().is_success() {
|
||||
bail!("download returned {}", resp.status());
|
||||
}
|
||||
|
||||
let bytes = resp.bytes().await.context("failed to read download body")?;
|
||||
tokio::fs::write(dest, &bytes)
|
||||
.await
|
||||
.context("failed to write downloaded binary")?;
|
||||
|
||||
// Make executable on Unix
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let perms = std::fs::Permissions::from_mode(0o755);
|
||||
tokio::fs::set_permissions(dest, perms).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_binary(path: &Path) -> Result<()> {
|
||||
let meta = tokio::fs::metadata(path).await?;
|
||||
if meta.len() < 1_000_000 {
|
||||
bail!(
|
||||
"downloaded binary too small ({} bytes), likely corrupt",
|
||||
meta.len()
|
||||
);
|
||||
}
|
||||
|
||||
// Quick check: try running --version
|
||||
let output = tokio::process::Command::new(path)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.await
|
||||
.context("cannot execute downloaded binary")?;
|
||||
|
||||
if !output.status.success() {
|
||||
bail!("downloaded binary --version check failed");
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if !stdout.contains("zeroclaw") {
|
||||
bail!("downloaded binary does not appear to be zeroclaw");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn swap_binary(new: &Path, target: &Path) -> Result<()> {
|
||||
tokio::fs::copy(new, target)
|
||||
.await
|
||||
.context("failed to overwrite binary")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn smoke_test(binary: &Path) -> Result<()> {
|
||||
let output = tokio::process::Command::new(binary)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.await
|
||||
.context("smoke test: cannot execute updated binary")?;
|
||||
|
||||
if !output.status.success() {
|
||||
bail!("smoke test: updated binary returned non-zero exit code");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_version_comparison() {
|
||||
assert!(version_is_newer("0.4.3", "0.5.0"));
|
||||
assert!(version_is_newer("0.4.3", "0.4.4"));
|
||||
assert!(!version_is_newer("0.5.0", "0.4.3"));
|
||||
assert!(!version_is_newer("0.4.3", "0.4.3"));
|
||||
assert!(version_is_newer("1.0.0", "2.0.0"));
|
||||
}
|
||||
}
|
||||
+9
-7
@@ -19,13 +19,14 @@ pub use schema::{
|
||||
McpServerConfig, McpTransport, MemoryConfig, Microsoft365Config, ModelRouteConfig,
|
||||
MultimodalConfig, NextcloudTalkConfig, NodeTransportConfig, NodesConfig, NotionConfig,
|
||||
ObservabilityConfig, OpenAiSttConfig, OpenAiTtsConfig, OpenVpnTunnelConfig, OtpConfig,
|
||||
OtpMethod, PeripheralBoardConfig, PeripheralsConfig, ProjectIntelConfig, ProxyConfig,
|
||||
ProxyScope, QdrantConfig, QueryClassificationConfig, ReliabilityConfig, ResourceLimitsConfig,
|
||||
RuntimeConfig, SandboxBackend, SandboxConfig, SchedulerConfig, SecretsConfig, SecurityConfig,
|
||||
SecurityOpsConfig, SkillsConfig, SkillsPromptInjectionMode, SlackConfig, StorageConfig,
|
||||
StorageProviderConfig, StorageProviderSection, StreamMode, SwarmConfig, SwarmStrategy,
|
||||
TelegramConfig, ToolFilterGroup, ToolFilterGroupMode, TranscriptionConfig, TtsConfig,
|
||||
TunnelConfig, WebFetchConfig, WebSearchConfig, WebhookConfig, WorkspaceConfig,
|
||||
OtpMethod, PeripheralBoardConfig, PeripheralsConfig, PluginsConfig, ProjectIntelConfig,
|
||||
ProxyConfig, ProxyScope, QdrantConfig, QueryClassificationConfig, ReliabilityConfig,
|
||||
ResourceLimitsConfig, RuntimeConfig, SandboxBackend, SandboxConfig, SchedulerConfig,
|
||||
SecretsConfig, SecurityConfig, SecurityOpsConfig, SkillCreationConfig, SkillsConfig,
|
||||
SkillsPromptInjectionMode, SlackConfig, StorageConfig, StorageProviderConfig,
|
||||
StorageProviderSection, StreamMode, SwarmConfig, SwarmStrategy, TelegramConfig,
|
||||
ToolFilterGroup, ToolFilterGroupMode, TranscriptionConfig, TtsConfig, TunnelConfig,
|
||||
WebFetchConfig, WebSearchConfig, WebhookConfig, WorkspaceConfig,
|
||||
};
|
||||
|
||||
pub fn name_and_presence<T: traits::ChannelConfig>(channel: Option<&T>) -> (&'static str, bool) {
|
||||
@@ -54,6 +55,7 @@ mod tests {
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
};
|
||||
|
||||
let discord = DiscordConfig {
|
||||
|
||||
+421
-6
@@ -137,7 +137,12 @@ pub struct Config {
|
||||
pub cloud_ops: CloudOpsConfig,
|
||||
|
||||
/// Conversational AI agent builder configuration (`[conversational_ai]`).
|
||||
#[serde(default)]
|
||||
///
|
||||
/// Experimental / future feature — not yet wired into the agent runtime.
|
||||
/// Omitted from generated config files when disabled (the default).
|
||||
/// Existing configs that already contain this section will continue to
|
||||
/// deserialize correctly thanks to `#[serde(default)]`.
|
||||
#[serde(default, skip_serializing_if = "ConversationalAiConfig::is_disabled")]
|
||||
pub conversational_ai: ConversationalAiConfig,
|
||||
|
||||
/// Managed cybersecurity service configuration (`[security_ops]`).
|
||||
@@ -335,6 +340,21 @@ pub struct Config {
|
||||
/// LinkedIn integration configuration (`[linkedin]`).
|
||||
#[serde(default)]
|
||||
pub linkedin: LinkedInConfig,
|
||||
|
||||
/// Plugin system configuration (`[plugins]`).
|
||||
#[serde(default)]
|
||||
pub plugins: PluginsConfig,
|
||||
|
||||
/// Locale for tool descriptions (e.g. `"en"`, `"zh-CN"`).
|
||||
///
|
||||
/// When set, tool descriptions shown in system prompts are loaded from
|
||||
/// `tool_descriptions/<locale>.toml`. Falls back to English, then to
|
||||
/// hardcoded descriptions.
|
||||
///
|
||||
/// If omitted or empty, the locale is auto-detected from `ZEROCLAW_LOCALE`,
|
||||
/// `LANG`, or `LC_ALL` environment variables (defaulting to `"en"`).
|
||||
#[serde(default)]
|
||||
pub locale: Option<String>,
|
||||
}
|
||||
|
||||
/// Multi-client workspace isolation configuration.
|
||||
@@ -445,6 +465,14 @@ pub struct DelegateAgentConfig {
|
||||
/// Maximum tool-call iterations in agentic mode.
|
||||
#[serde(default = "default_max_tool_iterations")]
|
||||
pub max_iterations: usize,
|
||||
/// Timeout in seconds for non-agentic provider calls.
|
||||
/// Defaults to 120 when unset. Must be between 1 and 3600.
|
||||
#[serde(default)]
|
||||
pub timeout_secs: Option<u64>,
|
||||
/// Timeout in seconds for agentic sub-agent loops.
|
||||
/// Defaults to 300 when unset. Must be between 1 and 3600.
|
||||
#[serde(default)]
|
||||
pub agentic_timeout_secs: Option<u64>,
|
||||
}
|
||||
|
||||
// ── Swarms ──────────────────────────────────────────────────────
|
||||
@@ -1159,6 +1187,34 @@ pub struct SkillsConfig {
|
||||
/// `full` preserves legacy behavior. `compact` keeps context small and loads skills on demand.
|
||||
#[serde(default)]
|
||||
pub prompt_injection_mode: SkillsPromptInjectionMode,
|
||||
/// Autonomous skill creation from successful multi-step task executions.
|
||||
#[serde(default)]
|
||||
pub skill_creation: SkillCreationConfig,
|
||||
}
|
||||
|
||||
/// Autonomous skill creation configuration (`[skills.skill_creation]` section).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(default)]
|
||||
pub struct SkillCreationConfig {
|
||||
/// Enable automatic skill creation after successful multi-step tasks.
|
||||
/// Default: `false`.
|
||||
pub enabled: bool,
|
||||
/// Maximum number of auto-generated skills to keep.
|
||||
/// When exceeded, the oldest auto-generated skill is removed (LRU eviction).
|
||||
pub max_skills: usize,
|
||||
/// Embedding similarity threshold for deduplication.
|
||||
/// Skills with descriptions more similar than this value are skipped.
|
||||
pub similarity_threshold: f64,
|
||||
}
|
||||
|
||||
impl Default for SkillCreationConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
max_skills: 500,
|
||||
similarity_threshold: 0.85,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Multimodal (image) handling configuration (`[multimodal]` section).
|
||||
@@ -1437,6 +1493,7 @@ impl Default for PeripheralBoardConfig {
|
||||
///
|
||||
/// Controls the HTTP gateway for webhook and pairing endpoints.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[allow(clippy::struct_excessive_bools)]
|
||||
pub struct GatewayConfig {
|
||||
/// Gateway port (default: 42617)
|
||||
#[serde(default = "default_gateway_port")]
|
||||
@@ -1478,6 +1535,18 @@ pub struct GatewayConfig {
|
||||
/// Maximum distinct idempotency keys retained in memory.
|
||||
#[serde(default = "default_gateway_idempotency_max_keys")]
|
||||
pub idempotency_max_keys: usize,
|
||||
|
||||
/// Persist gateway WebSocket chat sessions to SQLite. Default: true.
|
||||
#[serde(default = "default_true")]
|
||||
pub session_persistence: bool,
|
||||
|
||||
/// Auto-archive stale gateway sessions older than N hours. 0 = disabled. Default: 0.
|
||||
#[serde(default)]
|
||||
pub session_ttl_hours: u32,
|
||||
|
||||
/// Pairing dashboard configuration
|
||||
#[serde(default)]
|
||||
pub pairing_dashboard: PairingDashboardConfig,
|
||||
}
|
||||
|
||||
fn default_gateway_port() -> u16 {
|
||||
@@ -1530,6 +1599,57 @@ impl Default for GatewayConfig {
|
||||
rate_limit_max_keys: default_gateway_rate_limit_max_keys(),
|
||||
idempotency_ttl_secs: default_idempotency_ttl_secs(),
|
||||
idempotency_max_keys: default_gateway_idempotency_max_keys(),
|
||||
session_persistence: true,
|
||||
session_ttl_hours: 0,
|
||||
pairing_dashboard: PairingDashboardConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pairing dashboard configuration (`[gateway.pairing_dashboard]`).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PairingDashboardConfig {
|
||||
/// Length of pairing codes (default: 8)
|
||||
#[serde(default = "default_pairing_code_length")]
|
||||
pub code_length: usize,
|
||||
/// Time-to-live for pending pairing codes in seconds (default: 3600)
|
||||
#[serde(default = "default_pairing_ttl")]
|
||||
pub code_ttl_secs: u64,
|
||||
/// Maximum concurrent pending pairing codes (default: 3)
|
||||
#[serde(default = "default_max_pending_codes")]
|
||||
pub max_pending_codes: usize,
|
||||
/// Maximum failed pairing attempts before lockout (default: 5)
|
||||
#[serde(default = "default_max_failed_attempts")]
|
||||
pub max_failed_attempts: u32,
|
||||
/// Lockout duration in seconds after max attempts (default: 300)
|
||||
#[serde(default = "default_pairing_lockout_secs")]
|
||||
pub lockout_secs: u64,
|
||||
}
|
||||
|
||||
fn default_pairing_code_length() -> usize {
|
||||
8
|
||||
}
|
||||
fn default_pairing_ttl() -> u64 {
|
||||
3600
|
||||
}
|
||||
fn default_max_pending_codes() -> usize {
|
||||
3
|
||||
}
|
||||
fn default_max_failed_attempts() -> u32 {
|
||||
5
|
||||
}
|
||||
fn default_pairing_lockout_secs() -> u64 {
|
||||
300
|
||||
}
|
||||
|
||||
impl Default for PairingDashboardConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
code_length: default_pairing_code_length(),
|
||||
code_ttl_secs: default_pairing_ttl(),
|
||||
max_pending_codes: default_max_pending_codes(),
|
||||
max_failed_attempts: default_max_failed_attempts(),
|
||||
lockout_secs: default_pairing_lockout_secs(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2293,6 +2413,42 @@ fn default_linkedin_api_version() -> String {
|
||||
"202602".to_string()
|
||||
}
|
||||
|
||||
/// Plugin system configuration.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PluginsConfig {
|
||||
/// Enable the plugin system (default: false)
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// Directory where plugins are stored
|
||||
#[serde(default = "default_plugins_dir")]
|
||||
pub plugins_dir: String,
|
||||
/// Auto-discover and load plugins on startup
|
||||
#[serde(default)]
|
||||
pub auto_discover: bool,
|
||||
/// Maximum number of plugins that can be loaded
|
||||
#[serde(default = "default_max_plugins")]
|
||||
pub max_plugins: usize,
|
||||
}
|
||||
|
||||
fn default_plugins_dir() -> String {
|
||||
"~/.zeroclaw/plugins".to_string()
|
||||
}
|
||||
|
||||
fn default_max_plugins() -> usize {
|
||||
50
|
||||
}
|
||||
|
||||
impl Default for PluginsConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
plugins_dir: default_plugins_dir(),
|
||||
auto_discover: false,
|
||||
max_plugins: default_max_plugins(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Content strategy configuration for LinkedIn auto-posting (`[linkedin.content]`).
|
||||
///
|
||||
/// The agent reads this via the `linkedin get_content_strategy` action to know
|
||||
@@ -3451,6 +3607,7 @@ impl Default for WebhookAuditConfig {
|
||||
/// Controls what the agent is allowed to do: shell commands, filesystem access,
|
||||
/// risk approval gates, and per-policy budgets.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(default)]
|
||||
pub struct AutonomyConfig {
|
||||
/// Autonomy level: `read_only`, `supervised` (default), or `full`.
|
||||
pub level: AutonomyLevel,
|
||||
@@ -3893,7 +4050,8 @@ pub struct ClassificationRule {
|
||||
pub struct HeartbeatConfig {
|
||||
/// Enable periodic heartbeat pings. Default: `false`.
|
||||
pub enabled: bool,
|
||||
/// Interval in minutes between heartbeat pings. Default: `30`.
|
||||
/// Interval in minutes between heartbeat pings. Default: `5`.
|
||||
#[serde(default = "default_heartbeat_interval")]
|
||||
pub interval_minutes: u32,
|
||||
/// Enable two-phase heartbeat: Phase 1 asks LLM whether to run, Phase 2
|
||||
/// executes only when the LLM decides there is work to do. Saves API cost
|
||||
@@ -3937,6 +4095,10 @@ pub struct HeartbeatConfig {
|
||||
pub max_run_history: u32,
|
||||
}
|
||||
|
||||
fn default_heartbeat_interval() -> u32 {
|
||||
5
|
||||
}
|
||||
|
||||
fn default_two_phase() -> bool {
|
||||
true
|
||||
}
|
||||
@@ -3957,7 +4119,7 @@ impl Default for HeartbeatConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
interval_minutes: 30,
|
||||
interval_minutes: default_heartbeat_interval(),
|
||||
two_phase: true,
|
||||
message: None,
|
||||
target: None,
|
||||
@@ -3981,6 +4143,15 @@ pub struct CronConfig {
|
||||
/// Enable the cron subsystem. Default: `true`.
|
||||
#[serde(default = "default_true")]
|
||||
pub enabled: bool,
|
||||
/// Run all overdue jobs at scheduler startup. Default: `true`.
|
||||
///
|
||||
/// When the machine boots late or the daemon restarts, jobs whose
|
||||
/// `next_run` is in the past are considered "missed". With this
|
||||
/// option enabled the scheduler fires them once before entering
|
||||
/// the normal polling loop. Disable if you prefer missed jobs to
|
||||
/// simply wait for their next scheduled occurrence.
|
||||
#[serde(default = "default_true")]
|
||||
pub catch_up_on_startup: bool,
|
||||
/// Maximum number of historical cron run records to retain. Default: `50`.
|
||||
#[serde(default = "default_max_run_history")]
|
||||
pub max_run_history: u32,
|
||||
@@ -3994,6 +4165,7 @@ impl Default for CronConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
catch_up_on_startup: true,
|
||||
max_run_history: default_max_run_history(),
|
||||
}
|
||||
}
|
||||
@@ -4406,6 +4578,11 @@ pub struct TelegramConfig {
|
||||
/// Direct messages are always processed.
|
||||
#[serde(default)]
|
||||
pub mention_only: bool,
|
||||
/// Override for the top-level `ack_reactions` setting. When `None`, the
|
||||
/// channel falls back to `[channels_config].ack_reactions`. When set
|
||||
/// explicitly, it takes precedence.
|
||||
#[serde(default)]
|
||||
pub ack_reactions: Option<bool>,
|
||||
}
|
||||
|
||||
impl ChannelConfig for TelegramConfig {
|
||||
@@ -4463,6 +4640,10 @@ pub struct SlackConfig {
|
||||
/// cancels the in-flight request and starts a fresh response with preserved history.
|
||||
#[serde(default)]
|
||||
pub interrupt_on_new_message: bool,
|
||||
/// When true (default), replies stay in the originating Slack thread.
|
||||
/// When false, replies go to the channel root instead.
|
||||
#[serde(default)]
|
||||
pub thread_replies: Option<bool>,
|
||||
/// When true, only respond to messages that @-mention the bot in groups.
|
||||
/// Direct messages remain allowed.
|
||||
#[serde(default)]
|
||||
@@ -4978,6 +5159,10 @@ pub struct OtpConfig {
|
||||
/// Domain-category presets expanded into `gated_domains`.
|
||||
#[serde(default)]
|
||||
pub gated_domain_categories: Vec<String>,
|
||||
|
||||
/// Maximum number of OTP challenge attempts before lockout.
|
||||
#[serde(default = "default_otp_challenge_max_attempts")]
|
||||
pub challenge_max_attempts: u32,
|
||||
}
|
||||
|
||||
fn default_otp_token_ttl_secs() -> u64 {
|
||||
@@ -4988,6 +5173,10 @@ fn default_otp_cache_valid_secs() -> u64 {
|
||||
300
|
||||
}
|
||||
|
||||
fn default_otp_challenge_max_attempts() -> u32 {
|
||||
3
|
||||
}
|
||||
|
||||
fn default_otp_gated_actions() -> Vec<String> {
|
||||
vec![
|
||||
"shell".to_string(),
|
||||
@@ -5008,6 +5197,7 @@ impl Default for OtpConfig {
|
||||
gated_actions: default_otp_gated_actions(),
|
||||
gated_domains: Vec::new(),
|
||||
gated_domain_categories: Vec::new(),
|
||||
challenge_max_attempts: default_otp_challenge_max_attempts(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5706,8 +5896,8 @@ fn default_conversational_ai_timeout_secs() -> u64 {
|
||||
|
||||
/// Conversational AI agent builder configuration (`[conversational_ai]` section).
|
||||
///
|
||||
/// Controls language detection, escalation behavior, conversation limits, and
|
||||
/// analytics for conversational agent workflows. Disabled by default.
|
||||
/// **Status: Reserved for future use.** This configuration is parsed but not yet
|
||||
/// consumed by the runtime. Setting `enabled = true` will produce a startup warning.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ConversationalAiConfig {
|
||||
/// Enable conversational AI features. Default: false.
|
||||
@@ -5739,6 +5929,17 @@ pub struct ConversationalAiConfig {
|
||||
pub knowledge_base_tool: Option<String>,
|
||||
}
|
||||
|
||||
impl ConversationalAiConfig {
|
||||
/// Returns `true` when the feature is disabled (the default).
|
||||
///
|
||||
/// Used by `#[serde(skip_serializing_if)]` to omit the entire
|
||||
/// `[conversational_ai]` section from newly-generated config files,
|
||||
/// avoiding user confusion over an undocumented / experimental section.
|
||||
pub fn is_disabled(&self) -> bool {
|
||||
!self.enabled
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ConversationalAiConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -5885,6 +6086,8 @@ impl Default for Config {
|
||||
node_transport: NodeTransportConfig::default(),
|
||||
knowledge: KnowledgeConfig::default(),
|
||||
linkedin: LinkedInConfig::default(),
|
||||
plugins: PluginsConfig::default(),
|
||||
locale: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6294,6 +6497,45 @@ fn read_codex_openai_api_key() -> Option<String> {
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
/// Ensure that essential bootstrap files exist in the workspace directory.
|
||||
///
|
||||
/// When the workspace is created outside of `zeroclaw onboard` (e.g., non-tty
|
||||
/// daemon/cron sessions), these files would otherwise be missing. This function
|
||||
/// creates sensible defaults that allow the agent to operate with a basic identity.
|
||||
async fn ensure_bootstrap_files(workspace_dir: &Path) -> Result<()> {
|
||||
let defaults: &[(&str, &str)] = &[
|
||||
(
|
||||
"IDENTITY.md",
|
||||
"# IDENTITY.md — Who Am I?\n\n\
|
||||
I am ZeroClaw, an autonomous AI agent.\n\n\
|
||||
## Traits\n\
|
||||
- Helpful, precise, and safety-conscious\n\
|
||||
- I prioritize clarity and correctness\n",
|
||||
),
|
||||
(
|
||||
"SOUL.md",
|
||||
"# SOUL.md — Who You Are\n\n\
|
||||
You are ZeroClaw, an autonomous AI agent.\n\n\
|
||||
## Core Principles\n\
|
||||
- Be helpful and accurate\n\
|
||||
- Respect user intent and boundaries\n\
|
||||
- Ask before taking destructive actions\n\
|
||||
- Prefer safe, reversible operations\n",
|
||||
),
|
||||
];
|
||||
|
||||
for (filename, content) in defaults {
|
||||
let path = workspace_dir.join(filename);
|
||||
if !path.exists() {
|
||||
fs::write(&path, content)
|
||||
.await
|
||||
.with_context(|| format!("Failed to create default {filename} in workspace"))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub async fn load_or_init() -> Result<Self> {
|
||||
let (default_zeroclaw_dir, default_workspace_dir) = default_config_and_workspace_dirs()?;
|
||||
@@ -6310,6 +6552,8 @@ impl Config {
|
||||
.await
|
||||
.context("Failed to create workspace directory")?;
|
||||
|
||||
ensure_bootstrap_files(&workspace_dir).await?;
|
||||
|
||||
if config_path.exists() {
|
||||
// Warn if config file is world-readable (may contain API keys)
|
||||
#[cfg(unix)]
|
||||
@@ -6836,6 +7080,9 @@ impl Config {
|
||||
}
|
||||
|
||||
// Security OTP / estop
|
||||
if self.security.otp.challenge_max_attempts == 0 {
|
||||
anyhow::bail!("security.otp.challenge_max_attempts must be greater than 0");
|
||||
}
|
||||
if self.security.otp.token_ttl_secs == 0 {
|
||||
anyhow::bail!("security.otp.token_ttl_secs must be greater than 0");
|
||||
}
|
||||
@@ -7146,6 +7393,31 @@ impl Config {
|
||||
anyhow::bail!("security.nevis: {msg}");
|
||||
}
|
||||
|
||||
// Delegate agent timeouts
|
||||
const MAX_DELEGATE_TIMEOUT_SECS: u64 = 3600;
|
||||
for (name, agent) in &self.agents {
|
||||
if let Some(timeout) = agent.timeout_secs {
|
||||
if timeout == 0 {
|
||||
anyhow::bail!("agents.{name}.timeout_secs must be greater than 0");
|
||||
}
|
||||
if timeout > MAX_DELEGATE_TIMEOUT_SECS {
|
||||
anyhow::bail!(
|
||||
"agents.{name}.timeout_secs exceeds max {MAX_DELEGATE_TIMEOUT_SECS}"
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(timeout) = agent.agentic_timeout_secs {
|
||||
if timeout == 0 {
|
||||
anyhow::bail!("agents.{name}.agentic_timeout_secs must be greater than 0");
|
||||
}
|
||||
if timeout > MAX_DELEGATE_TIMEOUT_SECS {
|
||||
anyhow::bail!(
|
||||
"agents.{name}.agentic_timeout_secs exceeds max {MAX_DELEGATE_TIMEOUT_SECS}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Transcription
|
||||
{
|
||||
let dp = self.transcription.default_provider.trim();
|
||||
@@ -7491,6 +7763,13 @@ impl Config {
|
||||
}
|
||||
|
||||
set_runtime_proxy_config(self.proxy.clone());
|
||||
|
||||
if self.conversational_ai.enabled {
|
||||
tracing::warn!(
|
||||
"conversational_ai.enabled = true but conversational AI features are not yet \
|
||||
implemented; this section is reserved for future use and will be ignored"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_config_path_for_save(&self) -> Result<PathBuf> {
|
||||
@@ -8098,7 +8377,7 @@ mod tests {
|
||||
async fn heartbeat_config_default() {
|
||||
let h = HeartbeatConfig::default();
|
||||
assert!(!h.enabled);
|
||||
assert_eq!(h.interval_minutes, 30);
|
||||
assert_eq!(h.interval_minutes, 5);
|
||||
assert!(h.message.is_none());
|
||||
assert!(h.target.is_none());
|
||||
assert!(h.to.is_none());
|
||||
@@ -8132,11 +8411,13 @@ recipient = "42"
|
||||
async fn cron_config_serde_roundtrip() {
|
||||
let c = CronConfig {
|
||||
enabled: false,
|
||||
catch_up_on_startup: false,
|
||||
max_run_history: 100,
|
||||
};
|
||||
let json = serde_json::to_string(&c).unwrap();
|
||||
let parsed: CronConfig = serde_json::from_str(&json).unwrap();
|
||||
assert!(!parsed.enabled);
|
||||
assert!(!parsed.catch_up_on_startup);
|
||||
assert_eq!(parsed.max_run_history, 100);
|
||||
}
|
||||
|
||||
@@ -8150,6 +8431,7 @@ default_temperature = 0.7
|
||||
|
||||
let parsed: Config = toml::from_str(toml_str).unwrap();
|
||||
assert!(parsed.cron.enabled);
|
||||
assert!(parsed.cron.catch_up_on_startup);
|
||||
assert_eq!(parsed.cron.max_run_history, 50);
|
||||
}
|
||||
|
||||
@@ -8254,6 +8536,7 @@ default_temperature = 0.7
|
||||
draft_update_interval_ms: default_draft_update_interval_ms(),
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
}),
|
||||
discord: None,
|
||||
slack: None,
|
||||
@@ -8320,6 +8603,8 @@ default_temperature = 0.7
|
||||
node_transport: NodeTransportConfig::default(),
|
||||
knowledge: KnowledgeConfig::default(),
|
||||
linkedin: LinkedInConfig::default(),
|
||||
plugins: PluginsConfig::default(),
|
||||
locale: None,
|
||||
};
|
||||
|
||||
let toml_str = toml::to_string_pretty(&config).unwrap();
|
||||
@@ -8652,6 +8937,8 @@ tool_dispatcher = "xml"
|
||||
node_transport: NodeTransportConfig::default(),
|
||||
knowledge: KnowledgeConfig::default(),
|
||||
linkedin: LinkedInConfig::default(),
|
||||
plugins: PluginsConfig::default(),
|
||||
locale: None,
|
||||
};
|
||||
|
||||
config.save().await.unwrap();
|
||||
@@ -8710,6 +8997,8 @@ tool_dispatcher = "xml"
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -8834,6 +9123,7 @@ tool_dispatcher = "xml"
|
||||
draft_update_interval_ms: 500,
|
||||
interrupt_on_new_message: true,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
};
|
||||
let json = serde_json::to_string(&tc).unwrap();
|
||||
let parsed: TelegramConfig = serde_json::from_str(&json).unwrap();
|
||||
@@ -9097,6 +9387,7 @@ allowed_users = ["@ops:matrix.org"]
|
||||
let parsed: SlackConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(parsed.allowed_users.is_empty());
|
||||
assert!(!parsed.interrupt_on_new_message);
|
||||
assert_eq!(parsed.thread_replies, None);
|
||||
assert!(!parsed.mention_only);
|
||||
}
|
||||
|
||||
@@ -9106,6 +9397,7 @@ allowed_users = ["@ops:matrix.org"]
|
||||
let parsed: SlackConfig = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(parsed.allowed_users, vec!["U111"]);
|
||||
assert!(!parsed.interrupt_on_new_message);
|
||||
assert_eq!(parsed.thread_replies, None);
|
||||
assert!(!parsed.mention_only);
|
||||
}
|
||||
|
||||
@@ -9115,6 +9407,7 @@ allowed_users = ["@ops:matrix.org"]
|
||||
let parsed: SlackConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(parsed.mention_only);
|
||||
assert!(!parsed.interrupt_on_new_message);
|
||||
assert_eq!(parsed.thread_replies, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9122,6 +9415,16 @@ allowed_users = ["@ops:matrix.org"]
|
||||
let json = r#"{"bot_token":"xoxb-tok","interrupt_on_new_message":true}"#;
|
||||
let parsed: SlackConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(parsed.interrupt_on_new_message);
|
||||
assert_eq!(parsed.thread_replies, None);
|
||||
assert!(!parsed.mention_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn slack_config_deserializes_thread_replies() {
|
||||
let json = r#"{"bot_token":"xoxb-tok","thread_replies":false}"#;
|
||||
let parsed: SlackConfig = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(parsed.thread_replies, Some(false));
|
||||
assert!(!parsed.interrupt_on_new_message);
|
||||
assert!(!parsed.mention_only);
|
||||
}
|
||||
|
||||
@@ -9145,6 +9448,7 @@ channel_id = "C123"
|
||||
let parsed: SlackConfig = toml::from_str(toml_str).unwrap();
|
||||
assert!(parsed.allowed_users.is_empty());
|
||||
assert!(!parsed.interrupt_on_new_message);
|
||||
assert_eq!(parsed.thread_replies, None);
|
||||
assert!(!parsed.mention_only);
|
||||
assert_eq!(parsed.channel_id.as_deref(), Some("C123"));
|
||||
}
|
||||
@@ -9388,10 +9692,15 @@ channel_id = "C123"
|
||||
rate_limit_max_keys: 2048,
|
||||
idempotency_ttl_secs: 600,
|
||||
idempotency_max_keys: 4096,
|
||||
session_persistence: true,
|
||||
session_ttl_hours: 0,
|
||||
pairing_dashboard: PairingDashboardConfig::default(),
|
||||
};
|
||||
let toml_str = toml::to_string(&g).unwrap();
|
||||
let parsed: GatewayConfig = toml::from_str(&toml_str).unwrap();
|
||||
assert!(parsed.require_pairing);
|
||||
assert!(parsed.session_persistence);
|
||||
assert_eq!(parsed.session_ttl_hours, 0);
|
||||
assert!(!parsed.allow_public_bind);
|
||||
assert_eq!(parsed.paired_tokens, vec!["zc_test_token"]);
|
||||
assert_eq!(parsed.pair_rate_limit_per_minute, 12);
|
||||
@@ -11143,6 +11452,7 @@ require_otp_to_resume = true
|
||||
draft_update_interval_ms: default_draft_update_interval_ms(),
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
|
||||
// Save (triggers encryption)
|
||||
@@ -11698,4 +12008,109 @@ require_otp_to_resume = true
|
||||
"Debug output must show [REDACTED] for client_secret"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn telegram_config_ack_reactions_false_deserializes() {
|
||||
let toml_str = r#"
|
||||
bot_token = "123:ABC"
|
||||
allowed_users = ["alice"]
|
||||
ack_reactions = false
|
||||
"#;
|
||||
let cfg: TelegramConfig = toml::from_str(toml_str).unwrap();
|
||||
assert_eq!(cfg.ack_reactions, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn telegram_config_ack_reactions_true_deserializes() {
|
||||
let toml_str = r#"
|
||||
bot_token = "123:ABC"
|
||||
allowed_users = ["alice"]
|
||||
ack_reactions = true
|
||||
"#;
|
||||
let cfg: TelegramConfig = toml::from_str(toml_str).unwrap();
|
||||
assert_eq!(cfg.ack_reactions, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn telegram_config_ack_reactions_missing_defaults_to_none() {
|
||||
let toml_str = r#"
|
||||
bot_token = "123:ABC"
|
||||
allowed_users = ["alice"]
|
||||
"#;
|
||||
let cfg: TelegramConfig = toml::from_str(toml_str).unwrap();
|
||||
assert_eq!(cfg.ack_reactions, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn telegram_config_ack_reactions_channel_overrides_top_level() {
|
||||
let tg_toml = r#"
|
||||
bot_token = "123:ABC"
|
||||
allowed_users = ["alice"]
|
||||
ack_reactions = false
|
||||
"#;
|
||||
let tg: TelegramConfig = toml::from_str(tg_toml).unwrap();
|
||||
let top_level_ack = true;
|
||||
let effective = tg.ack_reactions.unwrap_or(top_level_ack);
|
||||
assert!(
|
||||
!effective,
|
||||
"channel-level false must override top-level true"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn telegram_config_ack_reactions_falls_back_to_top_level() {
|
||||
let tg_toml = r#"
|
||||
bot_token = "123:ABC"
|
||||
allowed_users = ["alice"]
|
||||
"#;
|
||||
let tg: TelegramConfig = toml::from_str(tg_toml).unwrap();
|
||||
let top_level_ack = false;
|
||||
let effective = tg.ack_reactions.unwrap_or(top_level_ack);
|
||||
assert!(
|
||||
!effective,
|
||||
"must fall back to top-level false when channel omits field"
|
||||
);
|
||||
}
|
||||
|
||||
// ── Bootstrap files ─────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
async fn ensure_bootstrap_files_creates_missing_files() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let ws = tmp.path().join("workspace");
|
||||
tokio::fs::create_dir_all(&ws).await.unwrap();
|
||||
|
||||
ensure_bootstrap_files(&ws).await.unwrap();
|
||||
|
||||
let soul = tokio::fs::read_to_string(ws.join("SOUL.md")).await.unwrap();
|
||||
let identity = tokio::fs::read_to_string(ws.join("IDENTITY.md"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(soul.contains("SOUL.md"));
|
||||
assert!(identity.contains("IDENTITY.md"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
async fn ensure_bootstrap_files_does_not_overwrite_existing() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let ws = tmp.path().join("workspace");
|
||||
tokio::fs::create_dir_all(&ws).await.unwrap();
|
||||
|
||||
let custom = "# My custom SOUL";
|
||||
tokio::fs::write(ws.join("SOUL.md"), custom).await.unwrap();
|
||||
|
||||
ensure_bootstrap_files(&ws).await.unwrap();
|
||||
|
||||
let soul = tokio::fs::read_to_string(ws.join("SOUL.md")).await.unwrap();
|
||||
assert_eq!(
|
||||
soul, custom,
|
||||
"ensure_bootstrap_files must not overwrite existing files"
|
||||
);
|
||||
|
||||
// IDENTITY.md should still be created since it was missing
|
||||
let identity = tokio::fs::read_to_string(ws.join("IDENTITY.md"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(identity.contains("IDENTITY.md"));
|
||||
}
|
||||
}
|
||||
|
||||
+148
-9
@@ -14,10 +14,13 @@ pub use schedule::{
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
pub use store::{
|
||||
add_agent_job, due_jobs, get_job, list_jobs, list_runs, record_last_run, record_run,
|
||||
remove_job, reschedule_after_run, update_job,
|
||||
add_agent_job, all_overdue_jobs, due_jobs, get_job, list_jobs, list_runs, record_last_run,
|
||||
record_run, remove_job, reschedule_after_run, update_job,
|
||||
};
|
||||
pub use types::{
|
||||
deserialize_maybe_stringified, CronJob, CronJobPatch, CronRun, DeliveryConfig, JobType,
|
||||
Schedule, SessionTarget,
|
||||
};
|
||||
pub use types::{CronJob, CronJobPatch, CronRun, DeliveryConfig, JobType, Schedule, SessionTarget};
|
||||
|
||||
/// Validate a shell command against the full security policy (allowlist + risk gate).
|
||||
///
|
||||
@@ -153,6 +156,7 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
expression,
|
||||
tz,
|
||||
agent,
|
||||
allowed_tools,
|
||||
command,
|
||||
} => {
|
||||
let schedule = Schedule::Cron {
|
||||
@@ -169,12 +173,20 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
if allowed_tools.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(allowed_tools)
|
||||
},
|
||||
)?;
|
||||
println!("✅ Added agent cron job {}", job.id);
|
||||
println!(" Expr : {}", job.expression);
|
||||
println!(" Next : {}", job.next_run.to_rfc3339());
|
||||
println!(" Prompt: {}", job.prompt.as_deref().unwrap_or_default());
|
||||
} else {
|
||||
if !allowed_tools.is_empty() {
|
||||
bail!("--allowed-tool is only supported with --agent cron jobs");
|
||||
}
|
||||
let job = add_shell_job(config, None, schedule, &command)?;
|
||||
println!("✅ Added cron job {}", job.id);
|
||||
println!(" Expr: {}", job.expression);
|
||||
@@ -183,7 +195,12 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
crate::CronCommands::AddAt { at, agent, command } => {
|
||||
crate::CronCommands::AddAt {
|
||||
at,
|
||||
agent,
|
||||
allowed_tools,
|
||||
command,
|
||||
} => {
|
||||
let at = chrono::DateTime::parse_from_rfc3339(&at)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid RFC3339 timestamp for --at: {e}"))?
|
||||
.with_timezone(&chrono::Utc);
|
||||
@@ -198,11 +215,19 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
if allowed_tools.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(allowed_tools)
|
||||
},
|
||||
)?;
|
||||
println!("✅ Added one-shot agent cron job {}", job.id);
|
||||
println!(" At : {}", job.next_run.to_rfc3339());
|
||||
println!(" Prompt: {}", job.prompt.as_deref().unwrap_or_default());
|
||||
} else {
|
||||
if !allowed_tools.is_empty() {
|
||||
bail!("--allowed-tool is only supported with --agent cron jobs");
|
||||
}
|
||||
let job = add_shell_job(config, None, schedule, &command)?;
|
||||
println!("✅ Added one-shot cron job {}", job.id);
|
||||
println!(" At : {}", job.next_run.to_rfc3339());
|
||||
@@ -213,6 +238,7 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
crate::CronCommands::AddEvery {
|
||||
every_ms,
|
||||
agent,
|
||||
allowed_tools,
|
||||
command,
|
||||
} => {
|
||||
let schedule = Schedule::Every { every_ms };
|
||||
@@ -226,12 +252,20 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
if allowed_tools.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(allowed_tools)
|
||||
},
|
||||
)?;
|
||||
println!("✅ Added interval agent cron job {}", job.id);
|
||||
println!(" Every(ms): {every_ms}");
|
||||
println!(" Next : {}", job.next_run.to_rfc3339());
|
||||
println!(" Prompt : {}", job.prompt.as_deref().unwrap_or_default());
|
||||
} else {
|
||||
if !allowed_tools.is_empty() {
|
||||
bail!("--allowed-tool is only supported with --agent cron jobs");
|
||||
}
|
||||
let job = add_shell_job(config, None, schedule, &command)?;
|
||||
println!("✅ Added interval cron job {}", job.id);
|
||||
println!(" Every(ms): {every_ms}");
|
||||
@@ -243,6 +277,7 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
crate::CronCommands::Once {
|
||||
delay,
|
||||
agent,
|
||||
allowed_tools,
|
||||
command,
|
||||
} => {
|
||||
if agent {
|
||||
@@ -258,11 +293,19 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
if allowed_tools.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(allowed_tools)
|
||||
},
|
||||
)?;
|
||||
println!("✅ Added one-shot agent cron job {}", job.id);
|
||||
println!(" At : {}", job.next_run.to_rfc3339());
|
||||
println!(" Prompt: {}", job.prompt.as_deref().unwrap_or_default());
|
||||
} else {
|
||||
if !allowed_tools.is_empty() {
|
||||
bail!("--allowed-tool is only supported with --agent cron jobs");
|
||||
}
|
||||
let job = add_once(config, &delay, &command)?;
|
||||
println!("✅ Added one-shot cron job {}", job.id);
|
||||
println!(" At : {}", job.next_run.to_rfc3339());
|
||||
@@ -276,21 +319,37 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
tz,
|
||||
command,
|
||||
name,
|
||||
allowed_tools,
|
||||
} => {
|
||||
if expression.is_none() && tz.is_none() && command.is_none() && name.is_none() {
|
||||
bail!("At least one of --expression, --tz, --command, or --name must be provided");
|
||||
if expression.is_none()
|
||||
&& tz.is_none()
|
||||
&& command.is_none()
|
||||
&& name.is_none()
|
||||
&& allowed_tools.is_empty()
|
||||
{
|
||||
bail!(
|
||||
"At least one of --expression, --tz, --command, --name, or --allowed-tool must be provided"
|
||||
);
|
||||
}
|
||||
|
||||
let existing = if expression.is_some() || tz.is_some() || !allowed_tools.is_empty() {
|
||||
Some(get_job(config, &id)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Merge expression/tz with the existing schedule so that
|
||||
// --tz alone updates the timezone and --expression alone
|
||||
// preserves the existing timezone.
|
||||
let schedule = if expression.is_some() || tz.is_some() {
|
||||
let existing = get_job(config, &id)?;
|
||||
let (existing_expr, existing_tz) = match existing.schedule {
|
||||
let existing = existing
|
||||
.as_ref()
|
||||
.expect("existing job must be loaded when updating schedule");
|
||||
let (existing_expr, existing_tz) = match &existing.schedule {
|
||||
Schedule::Cron {
|
||||
expr,
|
||||
tz: existing_tz,
|
||||
} => (expr, existing_tz),
|
||||
} => (expr.clone(), existing_tz.clone()),
|
||||
_ => bail!("Cannot update expression/tz on a non-cron schedule"),
|
||||
};
|
||||
Some(Schedule::Cron {
|
||||
@@ -301,10 +360,24 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<(
|
||||
None
|
||||
};
|
||||
|
||||
if !allowed_tools.is_empty() {
|
||||
let existing = existing
|
||||
.as_ref()
|
||||
.expect("existing job must be loaded when updating allowed tools");
|
||||
if existing.job_type != JobType::Agent {
|
||||
bail!("--allowed-tool is only supported for agent cron jobs");
|
||||
}
|
||||
}
|
||||
|
||||
let patch = CronJobPatch {
|
||||
schedule,
|
||||
command,
|
||||
name,
|
||||
allowed_tools: if allowed_tools.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(allowed_tools)
|
||||
},
|
||||
..CronJobPatch::default()
|
||||
};
|
||||
|
||||
@@ -427,6 +500,7 @@ mod tests {
|
||||
tz: tz.map(Into::into),
|
||||
command: command.map(Into::into),
|
||||
name: name.map(Into::into),
|
||||
allowed_tools: vec![],
|
||||
},
|
||||
config,
|
||||
)
|
||||
@@ -775,6 +849,7 @@ mod tests {
|
||||
expression: "*/15 * * * *".into(),
|
||||
tz: None,
|
||||
agent: true,
|
||||
allowed_tools: vec![],
|
||||
command: "Check server health: disk space, memory, CPU load".into(),
|
||||
},
|
||||
&config,
|
||||
@@ -805,6 +880,7 @@ mod tests {
|
||||
expression: "*/15 * * * *".into(),
|
||||
tz: None,
|
||||
agent: true,
|
||||
allowed_tools: vec![],
|
||||
command: "Check server health: disk space, memory, CPU load".into(),
|
||||
},
|
||||
&config,
|
||||
@@ -816,6 +892,68 @@ mod tests {
|
||||
assert_eq!(jobs[0].job_type, JobType::Agent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_agent_allowed_tools_persist() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
|
||||
handle_command(
|
||||
crate::CronCommands::Add {
|
||||
expression: "*/15 * * * *".into(),
|
||||
tz: None,
|
||||
agent: true,
|
||||
allowed_tools: vec!["file_read".into(), "web_search".into()],
|
||||
command: "Check server health".into(),
|
||||
},
|
||||
&config,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let jobs = list_jobs(&config).unwrap();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert_eq!(
|
||||
jobs[0].allowed_tools,
|
||||
Some(vec!["file_read".into(), "web_search".into()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_update_agent_allowed_tools_persist() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
let job = add_agent_job(
|
||||
&config,
|
||||
Some("agent".into()),
|
||||
Schedule::Cron {
|
||||
expr: "*/5 * * * *".into(),
|
||||
tz: None,
|
||||
},
|
||||
"original prompt",
|
||||
SessionTarget::Isolated,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
handle_command(
|
||||
crate::CronCommands::Update {
|
||||
id: job.id.clone(),
|
||||
expression: None,
|
||||
tz: None,
|
||||
command: None,
|
||||
name: None,
|
||||
allowed_tools: vec!["shell".into()],
|
||||
},
|
||||
&config,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let updated = get_job(&config, &job.id).unwrap();
|
||||
assert_eq!(updated.allowed_tools, Some(vec!["shell".into()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_without_agent_flag_defaults_to_shell_job() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -826,6 +964,7 @@ mod tests {
|
||||
expression: "*/5 * * * *".into(),
|
||||
tz: None,
|
||||
agent: false,
|
||||
allowed_tools: vec![],
|
||||
command: "echo ok".into(),
|
||||
},
|
||||
&config,
|
||||
|
||||
+146
-16
@@ -6,8 +6,9 @@ use crate::channels::{
|
||||
};
|
||||
use crate::config::Config;
|
||||
use crate::cron::{
|
||||
due_jobs, next_run_for_schedule, record_last_run, record_run, remove_job, reschedule_after_run,
|
||||
update_job, CronJob, CronJobPatch, DeliveryConfig, JobType, Schedule, SessionTarget,
|
||||
all_overdue_jobs, due_jobs, next_run_for_schedule, record_last_run, record_run, remove_job,
|
||||
reschedule_after_run, update_job, CronJob, CronJobPatch, DeliveryConfig, JobType, Schedule,
|
||||
SessionTarget,
|
||||
};
|
||||
use crate::security::SecurityPolicy;
|
||||
use anyhow::Result;
|
||||
@@ -33,6 +34,18 @@ pub async fn run(config: Config) -> Result<()> {
|
||||
|
||||
crate::health::mark_component_ok(SCHEDULER_COMPONENT);
|
||||
|
||||
// ── Startup catch-up: run ALL overdue jobs before entering the
|
||||
// normal polling loop. The regular loop is capped by `max_tasks`,
|
||||
// which could leave some overdue jobs waiting across many cycles
|
||||
// if the machine was off for a while. The catch-up phase fetches
|
||||
// without the `max_tasks` limit so every missed job fires once.
|
||||
// Controlled by `[cron] catch_up_on_startup` (default: true).
|
||||
if config.cron.catch_up_on_startup {
|
||||
catch_up_overdue_jobs(&config, &security).await;
|
||||
} else {
|
||||
tracing::info!("Scheduler startup: catch-up disabled by config");
|
||||
}
|
||||
|
||||
loop {
|
||||
interval.tick().await;
|
||||
// Keep scheduler liveness fresh even when there are no due jobs.
|
||||
@@ -51,6 +64,35 @@ pub async fn run(config: Config) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch **all** overdue jobs (ignoring `max_tasks`) and execute them.
|
||||
///
|
||||
/// Called once at scheduler startup so that jobs missed during downtime
|
||||
/// (e.g. late boot, daemon restart) are caught up immediately.
|
||||
async fn catch_up_overdue_jobs(config: &Config, security: &Arc<SecurityPolicy>) {
|
||||
let now = Utc::now();
|
||||
let jobs = match all_overdue_jobs(config, now) {
|
||||
Ok(jobs) => jobs,
|
||||
Err(e) => {
|
||||
tracing::warn!("Startup catch-up query failed: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if jobs.is_empty() {
|
||||
tracing::info!("Scheduler startup: no overdue jobs to catch up");
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
count = jobs.len(),
|
||||
"Scheduler startup: catching up overdue jobs"
|
||||
);
|
||||
|
||||
process_due_jobs(config, security, jobs, SCHEDULER_COMPONENT).await;
|
||||
|
||||
tracing::info!("Scheduler startup: catch-up complete");
|
||||
}
|
||||
|
||||
pub async fn execute_job_now(config: &Config, job: &CronJob) -> (bool, String) {
|
||||
let security = SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir);
|
||||
Box::pin(execute_job_with_retry(config, &security, job)).await
|
||||
@@ -242,6 +284,15 @@ async fn persist_job_result(
|
||||
if success {
|
||||
if let Err(e) = remove_job(config, &job.id) {
|
||||
tracing::warn!("Failed to remove one-shot cron job after success: {e}");
|
||||
// Fall back to disabling the job so it won't re-trigger.
|
||||
let _ = update_job(
|
||||
config,
|
||||
&job.id,
|
||||
CronJobPatch {
|
||||
enabled: Some(false),
|
||||
..CronJobPatch::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let _ = record_last_run(config, &job.id, finished_at, false, output);
|
||||
@@ -497,18 +548,12 @@ async fn run_job_command_with_timeout(
|
||||
);
|
||||
}
|
||||
|
||||
let child = match Command::new("sh")
|
||||
.arg("-lc")
|
||||
.arg(&job.command)
|
||||
.current_dir(&config.workspace_dir)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
{
|
||||
Ok(child) => child,
|
||||
Err(e) => return (false, format!("spawn error: {e}")),
|
||||
let child = match build_cron_shell_command(&job.command, &config.workspace_dir) {
|
||||
Ok(mut cmd) => match cmd.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(e) => return (false, format!("spawn error: {e}")),
|
||||
},
|
||||
Err(e) => return (false, format!("shell setup error: {e}")),
|
||||
};
|
||||
|
||||
match time::timeout(timeout, child.wait_with_output()).await {
|
||||
@@ -531,6 +576,35 @@ async fn run_job_command_with_timeout(
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a shell `Command` for cron job execution.
|
||||
///
|
||||
/// Uses `sh -c <command>` (non-login shell). On Windows, ZeroClaw users
|
||||
/// typically have Git Bash installed which provides `sh` in PATH, and
|
||||
/// cron commands are written with Unix shell syntax. The previous `-lc`
|
||||
/// (login shell) flag was dropped: login shells load the full user
|
||||
/// profile on every invocation which is slow and may cause side effects.
|
||||
///
|
||||
/// The command is configured with:
|
||||
/// - `current_dir` set to the workspace
|
||||
/// - `stdin` piped to `/dev/null` (no interactive input)
|
||||
/// - `stdout` and `stderr` piped for capture
|
||||
/// - `kill_on_drop(true)` for safe timeout handling
|
||||
fn build_cron_shell_command(
|
||||
command: &str,
|
||||
workspace_dir: &std::path::Path,
|
||||
) -> anyhow::Result<Command> {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.arg("-c")
|
||||
.arg(command)
|
||||
.current_dir(workspace_dir)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -891,6 +965,7 @@ mod tests {
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let started = Utc::now();
|
||||
@@ -916,6 +991,7 @@ mod tests {
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let started = Utc::now();
|
||||
@@ -982,6 +1058,7 @@ mod tests {
|
||||
best_effort: false,
|
||||
}),
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let started = Utc::now();
|
||||
@@ -1020,6 +1097,7 @@ mod tests {
|
||||
best_effort: true,
|
||||
}),
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let started = Utc::now();
|
||||
@@ -1038,7 +1116,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persist_job_result_at_schedule_without_delete_after_run_is_not_deleted() {
|
||||
async fn persist_job_result_at_schedule_without_delete_after_run_is_disabled() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp).await;
|
||||
let at = Utc::now() + ChronoDuration::minutes(10);
|
||||
@@ -1051,6 +1129,7 @@ mod tests {
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!job.delete_after_run);
|
||||
@@ -1060,8 +1139,13 @@ mod tests {
|
||||
let success = persist_job_result(&config, &job, true, "ok", started, finished).await;
|
||||
assert!(success);
|
||||
|
||||
// After reschedule_after_run, At schedule jobs should be disabled
|
||||
// to prevent re-execution with a past next_run timestamp.
|
||||
let updated = cron::get_job(&config, &job.id).unwrap();
|
||||
assert!(updated.enabled);
|
||||
assert!(
|
||||
!updated.enabled,
|
||||
"At schedule job should be disabled after execution via reschedule"
|
||||
);
|
||||
assert_eq!(updated.last_status.as_deref(), Some("ok"));
|
||||
}
|
||||
|
||||
@@ -1138,4 +1222,50 @@ mod tests {
|
||||
.to_string()
|
||||
.contains("matrix delivery channel requires `channel-matrix` feature"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_cron_shell_command_uses_sh_non_login() {
|
||||
let workspace = std::env::temp_dir();
|
||||
let cmd = build_cron_shell_command("echo cron-test", &workspace).unwrap();
|
||||
let debug = format!("{cmd:?}");
|
||||
assert!(debug.contains("echo cron-test"));
|
||||
assert!(debug.contains("\"sh\""), "should use sh: {debug}");
|
||||
// Must NOT use login shell (-l) — login shells load full profile
|
||||
// and are slow/unpredictable for cron jobs.
|
||||
assert!(
|
||||
!debug.contains("\"-lc\""),
|
||||
"must not use login shell: {debug}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_cron_shell_command_executes_successfully() {
|
||||
let workspace = std::env::temp_dir();
|
||||
let mut cmd = build_cron_shell_command("echo cron-ok", &workspace).unwrap();
|
||||
let output = cmd.output().await.unwrap();
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("cron-ok"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catch_up_queries_all_overdue_jobs_ignoring_max_tasks() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let mut config = test_config(&tmp).await;
|
||||
config.scheduler.max_tasks = 1; // limit normal polling to 1
|
||||
|
||||
// Create 3 jobs with "every minute" schedule
|
||||
for i in 0..3 {
|
||||
let _ = cron::add_job(&config, "* * * * *", &format!("echo catchup-{i}")).unwrap();
|
||||
}
|
||||
|
||||
// Verify normal due_jobs is limited to max_tasks=1
|
||||
let far_future = Utc::now() + ChronoDuration::days(1);
|
||||
let due = cron::due_jobs(&config, far_future).unwrap();
|
||||
assert_eq!(due.len(), 1, "due_jobs must respect max_tasks");
|
||||
|
||||
// all_overdue_jobs ignores the limit
|
||||
let overdue = cron::all_overdue_jobs(&config, far_future).unwrap();
|
||||
assert_eq!(overdue.len(), 3, "all_overdue_jobs must return all");
|
||||
}
|
||||
}
|
||||
|
||||
+237
-25
@@ -77,6 +77,7 @@ pub fn add_agent_job(
|
||||
model: Option<String>,
|
||||
delivery: Option<DeliveryConfig>,
|
||||
delete_after_run: bool,
|
||||
allowed_tools: Option<Vec<String>>,
|
||||
) -> Result<CronJob> {
|
||||
let now = Utc::now();
|
||||
validate_schedule(&schedule, now)?;
|
||||
@@ -90,8 +91,8 @@ pub fn add_agent_job(
|
||||
conn.execute(
|
||||
"INSERT INTO cron_jobs (
|
||||
id, expression, command, schedule, job_type, prompt, name, session_target, model,
|
||||
enabled, delivery, delete_after_run, created_at, next_run
|
||||
) VALUES (?1, ?2, '', ?3, 'agent', ?4, ?5, ?6, ?7, 1, ?8, ?9, ?10, ?11)",
|
||||
enabled, delivery, delete_after_run, allowed_tools, created_at, next_run
|
||||
) VALUES (?1, ?2, '', ?3, 'agent', ?4, ?5, ?6, ?7, 1, ?8, ?9, ?10, ?11, ?12)",
|
||||
params![
|
||||
id,
|
||||
expression,
|
||||
@@ -102,6 +103,7 @@ pub fn add_agent_job(
|
||||
model,
|
||||
serde_json::to_string(&delivery)?,
|
||||
if delete_after_run { 1 } else { 0 },
|
||||
encode_allowed_tools(allowed_tools.as_ref())?,
|
||||
now.to_rfc3339(),
|
||||
next_run.to_rfc3339(),
|
||||
],
|
||||
@@ -117,7 +119,8 @@ pub fn list_jobs(config: &Config) -> Result<Vec<CronJob>> {
|
||||
with_connection(config, |conn| {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
|
||||
allowed_tools
|
||||
FROM cron_jobs ORDER BY next_run ASC",
|
||||
)?;
|
||||
|
||||
@@ -135,7 +138,8 @@ pub fn get_job(config: &Config, job_id: &str) -> Result<CronJob> {
|
||||
with_connection(config, |conn| {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
|
||||
allowed_tools
|
||||
FROM cron_jobs WHERE id = ?1",
|
||||
)?;
|
||||
|
||||
@@ -168,7 +172,8 @@ pub fn due_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {
|
||||
with_connection(config, |conn| {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,
|
||||
allowed_tools
|
||||
FROM cron_jobs
|
||||
WHERE enabled = 1 AND next_run <= ?1
|
||||
ORDER BY next_run ASC
|
||||
@@ -188,6 +193,34 @@ pub fn due_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Return **all** enabled overdue jobs without the `max_tasks` limit.
|
||||
///
|
||||
/// Used by the scheduler startup catch-up to ensure every missed job is
|
||||
/// executed at least once after a period of downtime (late boot, daemon
|
||||
/// restart, etc.).
|
||||
pub fn all_overdue_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {
|
||||
with_connection(config, |conn| {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,
|
||||
enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output, allowed_tools
|
||||
FROM cron_jobs
|
||||
WHERE enabled = 1 AND next_run <= ?1
|
||||
ORDER BY next_run ASC",
|
||||
)?;
|
||||
|
||||
let rows = stmt.query_map(params![now.to_rfc3339()], map_cron_job_row)?;
|
||||
|
||||
let mut jobs = Vec::new();
|
||||
for row in rows {
|
||||
match row {
|
||||
Ok(job) => jobs.push(job),
|
||||
Err(e) => tracing::warn!("Skipping cron job with unparseable row data: {e}"),
|
||||
}
|
||||
}
|
||||
Ok(jobs)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<CronJob> {
|
||||
let mut job = get_job(config, job_id)?;
|
||||
let mut schedule_changed = false;
|
||||
@@ -222,6 +255,9 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
|
||||
if let Some(delete_after_run) = patch.delete_after_run {
|
||||
job.delete_after_run = delete_after_run;
|
||||
}
|
||||
if let Some(allowed_tools) = patch.allowed_tools {
|
||||
job.allowed_tools = Some(allowed_tools);
|
||||
}
|
||||
|
||||
if schedule_changed {
|
||||
job.next_run = next_run_for_schedule(&job.schedule, Utc::now())?;
|
||||
@@ -232,8 +268,8 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
|
||||
"UPDATE cron_jobs
|
||||
SET expression = ?1, command = ?2, schedule = ?3, job_type = ?4, prompt = ?5, name = ?6,
|
||||
session_target = ?7, model = ?8, enabled = ?9, delivery = ?10, delete_after_run = ?11,
|
||||
next_run = ?12
|
||||
WHERE id = ?13",
|
||||
allowed_tools = ?12, next_run = ?13
|
||||
WHERE id = ?14",
|
||||
params![
|
||||
job.expression,
|
||||
job.command,
|
||||
@@ -246,6 +282,7 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
|
||||
if job.enabled { 1 } else { 0 },
|
||||
serde_json::to_string(&job.delivery)?,
|
||||
if job.delete_after_run { 1 } else { 0 },
|
||||
encode_allowed_tools(job.allowed_tools.as_ref())?,
|
||||
job.next_run.to_rfc3339(),
|
||||
job.id,
|
||||
],
|
||||
@@ -285,26 +322,41 @@ pub fn reschedule_after_run(
|
||||
output: &str,
|
||||
) -> Result<()> {
|
||||
let now = Utc::now();
|
||||
let next_run = next_run_for_schedule(&job.schedule, now)?;
|
||||
let status = if success { "ok" } else { "error" };
|
||||
let bounded_output = truncate_cron_output(output);
|
||||
|
||||
with_connection(config, |conn| {
|
||||
conn.execute(
|
||||
"UPDATE cron_jobs
|
||||
SET next_run = ?1, last_run = ?2, last_status = ?3, last_output = ?4
|
||||
WHERE id = ?5",
|
||||
params![
|
||||
next_run.to_rfc3339(),
|
||||
now.to_rfc3339(),
|
||||
status,
|
||||
bounded_output,
|
||||
job.id
|
||||
],
|
||||
)
|
||||
.context("Failed to update cron job run state")?;
|
||||
Ok(())
|
||||
})
|
||||
// One-shot `At` schedules have no future occurrence — record the run
|
||||
// result and disable the job so it won't be picked up again.
|
||||
if matches!(job.schedule, Schedule::At { .. }) {
|
||||
with_connection(config, |conn| {
|
||||
conn.execute(
|
||||
"UPDATE cron_jobs
|
||||
SET enabled = 0, last_run = ?1, last_status = ?2, last_output = ?3
|
||||
WHERE id = ?4",
|
||||
params![now.to_rfc3339(), status, bounded_output, job.id],
|
||||
)
|
||||
.context("Failed to disable completed one-shot cron job")?;
|
||||
Ok(())
|
||||
})
|
||||
} else {
|
||||
let next_run = next_run_for_schedule(&job.schedule, now)?;
|
||||
with_connection(config, |conn| {
|
||||
conn.execute(
|
||||
"UPDATE cron_jobs
|
||||
SET next_run = ?1, last_run = ?2, last_status = ?3, last_output = ?4
|
||||
WHERE id = ?5",
|
||||
params![
|
||||
next_run.to_rfc3339(),
|
||||
now.to_rfc3339(),
|
||||
status,
|
||||
bounded_output,
|
||||
job.id
|
||||
],
|
||||
)
|
||||
.context("Failed to update cron job run state")?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_run(
|
||||
@@ -431,6 +483,7 @@ fn map_cron_job_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<CronJob> {
|
||||
let next_run_raw: String = row.get(13)?;
|
||||
let last_run_raw: Option<String> = row.get(14)?;
|
||||
let created_at_raw: String = row.get(12)?;
|
||||
let allowed_tools_raw: Option<String> = row.get(17)?;
|
||||
|
||||
Ok(CronJob {
|
||||
id: row.get(0)?,
|
||||
@@ -453,7 +506,8 @@ fn map_cron_job_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<CronJob> {
|
||||
},
|
||||
last_status: row.get(15)?,
|
||||
last_output: row.get(16)?,
|
||||
allowed_tools: None,
|
||||
allowed_tools: decode_allowed_tools(allowed_tools_raw.as_deref())
|
||||
.map_err(sql_conversion_error)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -487,6 +541,25 @@ fn decode_delivery(delivery_raw: Option<&str>) -> Result<DeliveryConfig> {
|
||||
Ok(DeliveryConfig::default())
|
||||
}
|
||||
|
||||
fn encode_allowed_tools(allowed_tools: Option<&Vec<String>>) -> Result<Option<String>> {
|
||||
allowed_tools
|
||||
.map(serde_json::to_string)
|
||||
.transpose()
|
||||
.context("Failed to serialize cron allowed_tools")
|
||||
}
|
||||
|
||||
fn decode_allowed_tools(raw: Option<&str>) -> Result<Option<Vec<String>>> {
|
||||
if let Some(raw) = raw {
|
||||
let trimmed = raw.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return serde_json::from_str(trimmed)
|
||||
.map(Some)
|
||||
.with_context(|| format!("Failed to parse cron allowed_tools JSON: {trimmed}"));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn add_column_if_missing(conn: &Connection, name: &str, sql_type: &str) -> Result<()> {
|
||||
let mut stmt = conn.prepare("PRAGMA table_info(cron_jobs)")?;
|
||||
let mut rows = stmt.query([])?;
|
||||
@@ -542,6 +615,7 @@ fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>)
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
delivery TEXT,
|
||||
delete_after_run INTEGER NOT NULL DEFAULT 0,
|
||||
allowed_tools TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
next_run TEXT NOT NULL,
|
||||
last_run TEXT,
|
||||
@@ -575,6 +649,7 @@ fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>)
|
||||
add_column_if_missing(&conn, "enabled", "INTEGER NOT NULL DEFAULT 1")?;
|
||||
add_column_if_missing(&conn, "delivery", "TEXT")?;
|
||||
add_column_if_missing(&conn, "delete_after_run", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
add_column_if_missing(&conn, "allowed_tools", "TEXT")?;
|
||||
|
||||
f(&conn)
|
||||
}
|
||||
@@ -689,6 +764,108 @@ mod tests {
|
||||
assert_eq!(due.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_overdue_jobs_ignores_max_tasks_limit() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let mut config = test_config(&tmp);
|
||||
config.scheduler.max_tasks = 2;
|
||||
|
||||
let _ = add_job(&config, "* * * * *", "echo ov-1").unwrap();
|
||||
let _ = add_job(&config, "* * * * *", "echo ov-2").unwrap();
|
||||
let _ = add_job(&config, "* * * * *", "echo ov-3").unwrap();
|
||||
|
||||
let far_future = Utc::now() + ChronoDuration::days(365);
|
||||
// due_jobs respects the limit
|
||||
let due = due_jobs(&config, far_future).unwrap();
|
||||
assert_eq!(due.len(), 2);
|
||||
// all_overdue_jobs returns everything
|
||||
let overdue = all_overdue_jobs(&config, far_future).unwrap();
|
||||
assert_eq!(overdue.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_overdue_jobs_excludes_disabled_jobs() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
|
||||
let job = add_job(&config, "* * * * *", "echo disabled").unwrap();
|
||||
let _ = update_job(
|
||||
&config,
|
||||
&job.id,
|
||||
CronJobPatch {
|
||||
enabled: Some(false),
|
||||
..CronJobPatch::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let far_future = Utc::now() + ChronoDuration::days(365);
|
||||
let overdue = all_overdue_jobs(&config, far_future).unwrap();
|
||||
assert!(overdue.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_agent_job_persists_allowed_tools() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
|
||||
let job = add_agent_job(
|
||||
&config,
|
||||
Some("agent".into()),
|
||||
Schedule::Every { every_ms: 60_000 },
|
||||
"do work",
|
||||
SessionTarget::Isolated,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
Some(vec!["file_read".into(), "web_search".into()]),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
job.allowed_tools,
|
||||
Some(vec!["file_read".into(), "web_search".into()])
|
||||
);
|
||||
|
||||
let stored = get_job(&config, &job.id).unwrap();
|
||||
assert_eq!(stored.allowed_tools, job.allowed_tools);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_job_persists_allowed_tools_patch() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
|
||||
let job = add_agent_job(
|
||||
&config,
|
||||
Some("agent".into()),
|
||||
Schedule::Every { every_ms: 60_000 },
|
||||
"do work",
|
||||
SessionTarget::Isolated,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let updated = update_job(
|
||||
&config,
|
||||
&job.id,
|
||||
CronJobPatch {
|
||||
allowed_tools: Some(vec!["shell".into()]),
|
||||
..CronJobPatch::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(updated.allowed_tools, Some(vec!["shell".into()]));
|
||||
assert_eq!(
|
||||
get_job(&config, &job.id).unwrap().allowed_tools,
|
||||
Some(vec!["shell".into()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reschedule_after_run_persists_last_status_and_last_run() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -852,6 +1029,41 @@ mod tests {
|
||||
assert!(stored.len() <= MAX_CRON_OUTPUT_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reschedule_after_run_disables_at_schedule_job() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
let at = Utc::now() + ChronoDuration::minutes(10);
|
||||
let job = add_shell_job(&config, None, Schedule::At { at }, "echo once").unwrap();
|
||||
|
||||
reschedule_after_run(&config, &job, true, "done").unwrap();
|
||||
|
||||
let stored = get_job(&config, &job.id).unwrap();
|
||||
assert!(
|
||||
!stored.enabled,
|
||||
"At schedule job should be disabled after reschedule"
|
||||
);
|
||||
assert_eq!(stored.last_status.as_deref(), Some("ok"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reschedule_after_run_disables_at_schedule_job_on_failure() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let config = test_config(&tmp);
|
||||
let at = Utc::now() + ChronoDuration::minutes(10);
|
||||
let job = add_shell_job(&config, None, Schedule::At { at }, "echo once").unwrap();
|
||||
|
||||
reschedule_after_run(&config, &job, false, "failed").unwrap();
|
||||
|
||||
let stored = get_job(&config, &job.id).unwrap();
|
||||
assert!(
|
||||
!stored.enabled,
|
||||
"At schedule job should be disabled after reschedule even on failure"
|
||||
);
|
||||
assert_eq!(stored.last_status.as_deref(), Some("error"));
|
||||
assert_eq!(stored.last_output.as_deref(), Some("failed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reschedule_after_run_truncates_last_output() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
+66
-1
@@ -1,6 +1,32 @@
|
||||
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
|
||||
/// provides backward-compatible handling for both `Value::Object` and
|
||||
/// `Value::String` representations.
|
||||
pub fn deserialize_maybe_stringified<T: serde::de::DeserializeOwned>(
|
||||
v: &serde_json::Value,
|
||||
) -> Result<T, serde_json::Error> {
|
||||
// Fast path: value is already the right shape (object, array, etc.)
|
||||
match serde_json::from_value::<T>(v.clone()) {
|
||||
Ok(parsed) => Ok(parsed),
|
||||
Err(first_err) => {
|
||||
// If it's a string, try parsing the string as JSON first.
|
||||
if let Some(s) = v.as_str() {
|
||||
let s = s.trim();
|
||||
if s.starts_with('{') || s.starts_with('[') {
|
||||
if let Ok(inner) = serde_json::from_str::<serde_json::Value>(s) {
|
||||
return serde_json::from_value::<T>(inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(first_err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum JobType {
|
||||
@@ -154,7 +180,46 @@ pub struct CronJobPatch {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::JobType;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deserialize_schedule_from_object() {
|
||||
let val = serde_json::json!({"kind": "cron", "expr": "*/5 * * * *"});
|
||||
let sched = deserialize_maybe_stringified::<Schedule>(&val).unwrap();
|
||||
assert!(matches!(sched, Schedule::Cron { ref expr, .. } if expr == "*/5 * * * *"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_schedule_from_string() {
|
||||
let val = serde_json::Value::String(r#"{"kind":"cron","expr":"*/5 * * * *"}"#.to_string());
|
||||
let sched = deserialize_maybe_stringified::<Schedule>(&val).unwrap();
|
||||
assert!(matches!(sched, Schedule::Cron { ref expr, .. } if expr == "*/5 * * * *"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_schedule_string_with_tz() {
|
||||
let val = serde_json::Value::String(
|
||||
r#"{"kind":"cron","expr":"*/30 9-15 * * 1-5","tz":"Asia/Shanghai"}"#.to_string(),
|
||||
);
|
||||
let sched = deserialize_maybe_stringified::<Schedule>(&val).unwrap();
|
||||
match sched {
|
||||
Schedule::Cron { tz, .. } => assert_eq!(tz.as_deref(), Some("Asia/Shanghai")),
|
||||
_ => panic!("expected Cron variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_every_from_string() {
|
||||
let val = serde_json::Value::String(r#"{"kind":"every","every_ms":60000}"#.to_string());
|
||||
let sched = deserialize_maybe_stringified::<Schedule>(&val).unwrap();
|
||||
assert!(matches!(sched, Schedule::Every { every_ms: 60000 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_invalid_string_returns_error() {
|
||||
let val = serde_json::Value::String("not json at all".to_string());
|
||||
assert!(deserialize_maybe_stringified::<Schedule>(&val).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_type_try_from_accepts_known_values_case_insensitive() {
|
||||
|
||||
+10
-1
@@ -127,6 +127,9 @@ pub async fn run(config: Config, host: String, port: u16) -> Result<()> {
|
||||
println!("🧠 ZeroClaw daemon started");
|
||||
println!(" Gateway: http://{host}:{port}");
|
||||
println!(" Components: gateway, channels, heartbeat, scheduler");
|
||||
if config.gateway.require_pairing {
|
||||
println!(" Pairing: enabled (code appears in gateway output above)");
|
||||
}
|
||||
println!(" Ctrl+C or SIGTERM to stop");
|
||||
|
||||
// Wait for shutdown signal (SIGINT or SIGTERM)
|
||||
@@ -312,7 +315,10 @@ async fn run_heartbeat_worker(config: Config) -> Result<()> {
|
||||
|
||||
// ── Phase 1: LLM decision (two-phase mode) ──────────────
|
||||
let tasks_to_run = if two_phase {
|
||||
let decision_prompt = HeartbeatEngine::build_decision_prompt(&tasks);
|
||||
let decision_prompt = format!(
|
||||
"[Heartbeat Task | decision] {}",
|
||||
HeartbeatEngine::build_decision_prompt(&tasks),
|
||||
);
|
||||
match Box::pin(crate::agent::run(
|
||||
config.clone(),
|
||||
Some(decision_prompt),
|
||||
@@ -639,6 +645,7 @@ mod tests {
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
assert!(has_supervised_channels(&config));
|
||||
}
|
||||
@@ -752,6 +759,7 @@ mod tests {
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
|
||||
let target = resolve_heartbeat_delivery(&config).unwrap();
|
||||
@@ -768,6 +776,7 @@ mod tests {
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
|
||||
let target = resolve_heartbeat_delivery(&config).unwrap();
|
||||
|
||||
@@ -1281,6 +1281,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
config.agents.insert(
|
||||
@@ -1295,6 +1297,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -357,6 +357,65 @@ pub async fn handle_api_cron_delete(
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/cron/settings — return cron subsystem settings
|
||||
pub async fn handle_api_cron_settings_get(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
let config = state.config.lock().clone();
|
||||
Json(serde_json::json!({
|
||||
"enabled": config.cron.enabled,
|
||||
"catch_up_on_startup": config.cron.catch_up_on_startup,
|
||||
"max_run_history": config.cron.max_run_history,
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// PATCH /api/cron/settings — update cron subsystem settings
|
||||
pub async fn handle_api_cron_settings_patch(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
let mut config = state.config.lock().clone();
|
||||
|
||||
if let Some(v) = body.get("enabled").and_then(|v| v.as_bool()) {
|
||||
config.cron.enabled = v;
|
||||
}
|
||||
if let Some(v) = body.get("catch_up_on_startup").and_then(|v| v.as_bool()) {
|
||||
config.cron.catch_up_on_startup = v;
|
||||
}
|
||||
if let Some(v) = body.get("max_run_history").and_then(|v| v.as_u64()) {
|
||||
config.cron.max_run_history = u32::try_from(v).unwrap_or(u32::MAX);
|
||||
}
|
||||
|
||||
if let Err(e) = config.save().await {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("Failed to save config: {e}")})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
*state.config.lock() = config.clone();
|
||||
|
||||
Json(serde_json::json!({
|
||||
"status": "ok",
|
||||
"enabled": config.cron.enabled,
|
||||
"catch_up_on_startup": config.cron.catch_up_on_startup,
|
||||
"max_run_history": config.cron.max_run_history,
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// GET /api/integrations — list all integrations with status
|
||||
pub async fn handle_api_integrations(
|
||||
State(state): State<AppState>,
|
||||
@@ -1076,6 +1135,76 @@ fn hydrate_config_for_save(
|
||||
incoming
|
||||
}
|
||||
|
||||
// ── Session API handlers ─────────────────────────────────────────
|
||||
|
||||
/// GET /api/sessions — list gateway sessions
|
||||
pub async fn handle_api_sessions_list(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
let Some(ref backend) = state.session_backend else {
|
||||
return Json(serde_json::json!({
|
||||
"sessions": [],
|
||||
"message": "Session persistence is disabled"
|
||||
}))
|
||||
.into_response();
|
||||
};
|
||||
|
||||
let all_metadata = backend.list_sessions_with_metadata();
|
||||
let gw_sessions: Vec<serde_json::Value> = all_metadata
|
||||
.into_iter()
|
||||
.filter_map(|meta| {
|
||||
let session_id = meta.key.strip_prefix("gw_")?;
|
||||
Some(serde_json::json!({
|
||||
"session_id": session_id,
|
||||
"created_at": meta.created_at.to_rfc3339(),
|
||||
"last_activity": meta.last_activity.to_rfc3339(),
|
||||
"message_count": meta.message_count,
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
|
||||
Json(serde_json::json!({ "sessions": gw_sessions })).into_response()
|
||||
}
|
||||
|
||||
/// DELETE /api/sessions/{id} — delete a gateway session
|
||||
pub async fn handle_api_session_delete(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
let Some(ref backend) = state.session_backend else {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Session persistence is disabled"})),
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
|
||||
let session_key = format!("gw_{id}");
|
||||
match backend.delete_session(&session_key) {
|
||||
Ok(true) => Json(serde_json::json!({"deleted": true, "session_id": id})).into_response(),
|
||||
Ok(false) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({"error": "Session not found"})),
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("Failed to delete session: {e}")})),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
//! Device management and pairing API handlers.
|
||||
|
||||
use super::AppState;
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{header, HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Json},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use parking_lot::Mutex;
|
||||
use rusqlite::Connection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Metadata about a paired device.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DeviceInfo {
|
||||
pub id: String,
|
||||
pub name: Option<String>,
|
||||
pub device_type: Option<String>,
|
||||
pub paired_at: DateTime<Utc>,
|
||||
pub last_seen: DateTime<Utc>,
|
||||
pub ip_address: Option<String>,
|
||||
}
|
||||
|
||||
/// Registry of paired devices backed by SQLite.
|
||||
#[derive(Debug)]
|
||||
pub struct DeviceRegistry {
|
||||
cache: Mutex<HashMap<String, DeviceInfo>>,
|
||||
db_path: PathBuf,
|
||||
}
|
||||
|
||||
impl DeviceRegistry {
|
||||
pub fn new(workspace_dir: &Path) -> Self {
|
||||
let db_path = workspace_dir.join("devices.db");
|
||||
let conn = Connection::open(&db_path).expect("Failed to open device registry database");
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS devices (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
id TEXT NOT NULL,
|
||||
name TEXT,
|
||||
device_type TEXT,
|
||||
paired_at TEXT NOT NULL,
|
||||
last_seen TEXT NOT NULL,
|
||||
ip_address TEXT
|
||||
)",
|
||||
)
|
||||
.expect("Failed to create devices table");
|
||||
|
||||
// Warm the in-memory cache from DB
|
||||
let mut cache = HashMap::new();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT token_hash, id, name, device_type, paired_at, last_seen, ip_address FROM devices")
|
||||
.expect("Failed to prepare device select");
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
let token_hash: String = row.get(0)?;
|
||||
let id: String = row.get(1)?;
|
||||
let name: Option<String> = row.get(2)?;
|
||||
let device_type: Option<String> = row.get(3)?;
|
||||
let paired_at_str: String = row.get(4)?;
|
||||
let last_seen_str: String = row.get(5)?;
|
||||
let ip_address: Option<String> = row.get(6)?;
|
||||
let paired_at = DateTime::parse_from_rfc3339(&paired_at_str)
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
.unwrap_or_else(|_| Utc::now());
|
||||
let last_seen = DateTime::parse_from_rfc3339(&last_seen_str)
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
.unwrap_or_else(|_| Utc::now());
|
||||
Ok((
|
||||
token_hash,
|
||||
DeviceInfo {
|
||||
id,
|
||||
name,
|
||||
device_type,
|
||||
paired_at,
|
||||
last_seen,
|
||||
ip_address,
|
||||
},
|
||||
))
|
||||
})
|
||||
.expect("Failed to query devices");
|
||||
for (hash, info) in rows.flatten() {
|
||||
cache.insert(hash, info);
|
||||
}
|
||||
|
||||
Self {
|
||||
cache: Mutex::new(cache),
|
||||
db_path,
|
||||
}
|
||||
}
|
||||
|
||||
fn open_db(&self) -> Connection {
|
||||
Connection::open(&self.db_path).expect("Failed to open device registry database")
|
||||
}
|
||||
|
||||
pub fn register(&self, token_hash: String, info: DeviceInfo) {
|
||||
let conn = self.open_db();
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO devices (token_hash, id, name, device_type, paired_at, last_seen, ip_address) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
rusqlite::params![
|
||||
token_hash,
|
||||
info.id,
|
||||
info.name,
|
||||
info.device_type,
|
||||
info.paired_at.to_rfc3339(),
|
||||
info.last_seen.to_rfc3339(),
|
||||
info.ip_address,
|
||||
],
|
||||
)
|
||||
.expect("Failed to insert device");
|
||||
self.cache.lock().insert(token_hash, info);
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Vec<DeviceInfo> {
|
||||
let conn = self.open_db();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT token_hash, id, name, device_type, paired_at, last_seen, ip_address FROM devices")
|
||||
.expect("Failed to prepare device select");
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
let id: String = row.get(1)?;
|
||||
let name: Option<String> = row.get(2)?;
|
||||
let device_type: Option<String> = row.get(3)?;
|
||||
let paired_at_str: String = row.get(4)?;
|
||||
let last_seen_str: String = row.get(5)?;
|
||||
let ip_address: Option<String> = row.get(6)?;
|
||||
let paired_at = DateTime::parse_from_rfc3339(&paired_at_str)
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
.unwrap_or_else(|_| Utc::now());
|
||||
let last_seen = DateTime::parse_from_rfc3339(&last_seen_str)
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
.unwrap_or_else(|_| Utc::now());
|
||||
Ok(DeviceInfo {
|
||||
id,
|
||||
name,
|
||||
device_type,
|
||||
paired_at,
|
||||
last_seen,
|
||||
ip_address,
|
||||
})
|
||||
})
|
||||
.expect("Failed to query devices");
|
||||
rows.filter_map(|r| r.ok()).collect()
|
||||
}
|
||||
|
||||
pub fn revoke(&self, device_id: &str) -> bool {
|
||||
let conn = self.open_db();
|
||||
let deleted = conn
|
||||
.execute(
|
||||
"DELETE FROM devices WHERE id = ?1",
|
||||
rusqlite::params![device_id],
|
||||
)
|
||||
.unwrap_or(0);
|
||||
if deleted > 0 {
|
||||
let mut cache = self.cache.lock();
|
||||
let key = cache
|
||||
.iter()
|
||||
.find(|(_, v)| v.id == device_id)
|
||||
.map(|(k, _)| k.clone());
|
||||
if let Some(key) = key {
|
||||
cache.remove(&key);
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_last_seen(&self, token_hash: &str) {
|
||||
let now = Utc::now();
|
||||
let conn = self.open_db();
|
||||
conn.execute(
|
||||
"UPDATE devices SET last_seen = ?1 WHERE token_hash = ?2",
|
||||
rusqlite::params![now.to_rfc3339(), token_hash],
|
||||
)
|
||||
.ok();
|
||||
if let Some(device) = self.cache.lock().get_mut(token_hash) {
|
||||
device.last_seen = now;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn device_count(&self) -> usize {
|
||||
self.cache.lock().len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Store for pending pairing requests.
|
||||
#[derive(Debug)]
|
||||
pub struct PairingStore {
|
||||
pending: Mutex<Vec<PendingPairing>>,
|
||||
max_pending: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
struct PendingPairing {
|
||||
code: String,
|
||||
created_at: DateTime<Utc>,
|
||||
expires_at: DateTime<Utc>,
|
||||
client_ip: Option<String>,
|
||||
attempts: u32,
|
||||
}
|
||||
|
||||
impl PairingStore {
|
||||
pub fn new(max_pending: usize) -> Self {
|
||||
Self {
|
||||
pending: Mutex::new(Vec::new()),
|
||||
max_pending,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pending_count(&self) -> usize {
|
||||
let mut pending = self.pending.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 require_auth(state: &AppState, headers: &HeaderMap) -> Result<(), (StatusCode, &'static str)> {
|
||||
if state.pairing.require_pairing() {
|
||||
let token = extract_bearer(headers).unwrap_or("");
|
||||
if !state.pairing.is_authenticated(token) {
|
||||
return Err((StatusCode::UNAUTHORIZED, "Unauthorized"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// POST /api/pairing/initiate — initiate a new pairing session
|
||||
pub async fn initiate_pairing(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
match state.pairing.generate_new_pairing_code() {
|
||||
Some(code) => Json(serde_json::json!({
|
||||
"pairing_code": code,
|
||||
"message": "New pairing code generated"
|
||||
}))
|
||||
.into_response(),
|
||||
None => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Pairing is disabled or not available",
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/pair — submit pairing code (for new device pairing)
|
||||
pub async fn submit_pairing_enhanced(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> impl IntoResponse {
|
||||
let code = body["code"].as_str().unwrap_or("");
|
||||
let device_name = body["device_name"].as_str().map(String::from);
|
||||
let device_type = body["device_type"].as_str().map(String::from);
|
||||
|
||||
let client_id = headers
|
||||
.get("X-Forwarded-For")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
match state.pairing.try_pair(code, &client_id).await {
|
||||
Ok(Some(token)) => {
|
||||
// Register the new device
|
||||
let token_hash = {
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = Sha256::digest(token.as_bytes());
|
||||
hex::encode(hash)
|
||||
};
|
||||
if let Some(ref registry) = state.device_registry {
|
||||
registry.register(
|
||||
token_hash,
|
||||
DeviceInfo {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
name: device_name,
|
||||
device_type,
|
||||
paired_at: Utc::now(),
|
||||
last_seen: Utc::now(),
|
||||
ip_address: Some(client_id),
|
||||
},
|
||||
);
|
||||
}
|
||||
Json(serde_json::json!({
|
||||
"token": token,
|
||||
"message": "Pairing successful"
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
Ok(None) => (StatusCode::BAD_REQUEST, "Invalid or expired pairing code").into_response(),
|
||||
Err(lockout_secs) => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
format!("Too many attempts. Locked out for {lockout_secs}s"),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/devices — list paired devices
|
||||
pub async fn list_devices(State(state): State<AppState>, headers: HeaderMap) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
let devices = state
|
||||
.device_registry
|
||||
.as_ref()
|
||||
.map(|r| r.list())
|
||||
.unwrap_or_default();
|
||||
|
||||
let count = devices.len();
|
||||
Json(serde_json::json!({
|
||||
"devices": devices,
|
||||
"count": count
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// DELETE /api/devices/{id} — revoke a paired device
|
||||
pub async fn revoke_device(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
axum::extract::Path(device_id): axum::extract::Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
let revoked = state
|
||||
.device_registry
|
||||
.as_ref()
|
||||
.map(|r| r.revoke(&device_id))
|
||||
.unwrap_or(false);
|
||||
|
||||
if revoked {
|
||||
Json(serde_json::json!({
|
||||
"message": "Device revoked",
|
||||
"device_id": device_id
|
||||
}))
|
||||
.into_response()
|
||||
} else {
|
||||
(StatusCode::NOT_FOUND, "Device not found").into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/devices/{id}/token/rotate — rotate a device's token
|
||||
pub async fn rotate_token(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
axum::extract::Path(device_id): axum::extract::Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(e) = require_auth(&state, &headers) {
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
// Generate a new pairing code for re-pairing
|
||||
match state.pairing.generate_new_pairing_code() {
|
||||
Some(code) => Json(serde_json::json!({
|
||||
"device_id": device_id,
|
||||
"pairing_code": code,
|
||||
"message": "Use this code to re-pair the device"
|
||||
}))
|
||||
.into_response(),
|
||||
None => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Cannot generate new pairing code",
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Plugin management API routes (requires `plugins-wasm` feature).
|
||||
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
pub mod plugin_routes {
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{header, HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Json},
|
||||
};
|
||||
|
||||
use super::super::AppState;
|
||||
|
||||
/// `GET /api/plugins` — list loaded plugins and their status.
|
||||
pub async fn list_plugins(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
// Auth check
|
||||
if state.pairing.require_pairing() {
|
||||
let token = headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|auth| auth.strip_prefix("Bearer "))
|
||||
.unwrap_or("");
|
||||
if !state.pairing.is_authenticated(token) {
|
||||
return (StatusCode::UNAUTHORIZED, "Unauthorized").into_response();
|
||||
}
|
||||
}
|
||||
|
||||
let config = state.config.lock();
|
||||
let plugins_enabled = config.plugins.enabled;
|
||||
let plugins_dir = config.plugins.plugins_dir.clone();
|
||||
drop(config);
|
||||
|
||||
let plugins: Vec<serde_json::Value> = if plugins_enabled {
|
||||
let plugin_path = if plugins_dir.starts_with("~/") {
|
||||
directories::UserDirs::new()
|
||||
.map(|u| u.home_dir().join(&plugins_dir[2..]))
|
||||
.unwrap_or_else(|| std::path::PathBuf::from(&plugins_dir))
|
||||
} else {
|
||||
std::path::PathBuf::from(&plugins_dir)
|
||||
};
|
||||
|
||||
if plugin_path.exists() {
|
||||
match crate::plugins::host::PluginHost::new(
|
||||
plugin_path.parent().unwrap_or(&plugin_path),
|
||||
) {
|
||||
Ok(host) => host
|
||||
.list_plugins()
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
serde_json::json!({
|
||||
"name": p.name,
|
||||
"version": p.version,
|
||||
"description": p.description,
|
||||
"capabilities": p.capabilities,
|
||||
"loaded": p.loaded,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
Err(_) => vec![],
|
||||
}
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
|
||||
Json(serde_json::json!({
|
||||
"plugins_enabled": plugins_enabled,
|
||||
"plugins_dir": plugins_dir,
|
||||
"plugins": plugins,
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
+119
-13
@@ -8,13 +8,17 @@
|
||||
//! - Header sanitization (handled by axum/hyper)
|
||||
|
||||
pub mod api;
|
||||
pub mod api_pairing;
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
pub mod api_plugins;
|
||||
pub mod nodes;
|
||||
pub mod sse;
|
||||
pub mod static_files;
|
||||
pub mod ws;
|
||||
|
||||
use crate::channels::{
|
||||
Channel, LinqChannel, NextcloudTalkChannel, SendMessage, WatiChannel, WhatsAppChannel,
|
||||
session_backend::SessionBackend, session_sqlite::SqliteSessionBackend, Channel, LinqChannel,
|
||||
NextcloudTalkChannel, SendMessage, WatiChannel, WhatsAppChannel,
|
||||
};
|
||||
use crate::config::Config;
|
||||
use crate::cost::CostTracker;
|
||||
@@ -331,6 +335,12 @@ pub struct AppState {
|
||||
pub shutdown_tx: tokio::sync::watch::Sender<bool>,
|
||||
/// Registry of dynamically connected nodes
|
||||
pub node_registry: Arc<nodes::NodeRegistry>,
|
||||
/// Session backend for persisting gateway WS chat sessions
|
||||
pub session_backend: Option<Arc<dyn SessionBackend>>,
|
||||
/// Device registry for paired device management
|
||||
pub device_registry: Option<Arc<api_pairing::DeviceRegistry>>,
|
||||
/// Pending pairing request store
|
||||
pub pending_pairings: Option<Arc<api_pairing::PairingStore>>,
|
||||
}
|
||||
|
||||
/// Run the HTTP gateway using axum with proper HTTP/1.1 compliance.
|
||||
@@ -554,6 +564,29 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
})
|
||||
.map(Arc::from);
|
||||
|
||||
// ── Session persistence for WS chat ─────────────────────
|
||||
let session_backend: Option<Arc<dyn SessionBackend>> = if config.gateway.session_persistence {
|
||||
match SqliteSessionBackend::new(&config.workspace_dir) {
|
||||
Ok(b) => {
|
||||
tracing::info!("Gateway session persistence enabled (SQLite)");
|
||||
if config.gateway.session_ttl_hours > 0 {
|
||||
if let Ok(cleaned) = b.cleanup_stale(config.gateway.session_ttl_hours) {
|
||||
if cleaned > 0 {
|
||||
tracing::info!("Cleaned up {cleaned} stale gateway sessions");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Arc::new(b))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Session persistence disabled: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// ── Pairing guard ──────────────────────────────────────
|
||||
let pairing = Arc::new(PairingGuard::new(
|
||||
config.gateway.require_pairing,
|
||||
@@ -600,6 +633,21 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
println!(" 🌐 Public URL: {url}");
|
||||
}
|
||||
println!(" 🌐 Web Dashboard: http://{display_addr}/");
|
||||
if let Some(code) = pairing.pairing_code() {
|
||||
println!();
|
||||
println!(" 🔐 PAIRING REQUIRED — use this one-time code:");
|
||||
println!(" ┌──────────────┐");
|
||||
println!(" │ {code} │");
|
||||
println!(" └──────────────┘");
|
||||
println!();
|
||||
} else if pairing.require_pairing() {
|
||||
println!(" 🔒 Pairing: ACTIVE (bearer token required)");
|
||||
println!(" To pair a new device: zeroclaw gateway get-paircode --new");
|
||||
println!();
|
||||
} else {
|
||||
println!(" ⚠️ Pairing: DISABLED (all requests accepted)");
|
||||
println!();
|
||||
}
|
||||
println!(" POST /pair — pair a new client (X-Pairing-Code header)");
|
||||
println!(" POST /webhook — {{\"message\": \"your prompt\"}}");
|
||||
if whatsapp_channel.is_some() {
|
||||
@@ -623,18 +671,6 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
}
|
||||
println!(" GET /health — health check");
|
||||
println!(" GET /metrics — Prometheus metrics");
|
||||
if let Some(code) = pairing.pairing_code() {
|
||||
println!();
|
||||
println!(" 🔐 PAIRING REQUIRED — use this one-time code:");
|
||||
println!(" ┌──────────────┐");
|
||||
println!(" │ {code} │");
|
||||
println!(" └──────────────┘");
|
||||
println!(" Send: POST /pair with header X-Pairing-Code: {code}");
|
||||
} else if pairing.require_pairing() {
|
||||
println!(" 🔒 Pairing: ACTIVE (bearer token required)");
|
||||
} else {
|
||||
println!(" ⚠️ Pairing: DISABLED (all requests accepted)");
|
||||
}
|
||||
println!(" Press Ctrl+C to stop.\n");
|
||||
|
||||
crate::health::mark_component_ok("gateway");
|
||||
@@ -656,6 +692,22 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
// Node registry for dynamic node discovery
|
||||
let node_registry = Arc::new(nodes::NodeRegistry::new(config.nodes.max_nodes));
|
||||
|
||||
// Device registry and pairing store (only when pairing is required)
|
||||
let device_registry = if config.gateway.require_pairing {
|
||||
Some(Arc::new(api_pairing::DeviceRegistry::new(
|
||||
&config.workspace_dir,
|
||||
)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let pending_pairings = if config.gateway.require_pairing {
|
||||
Some(Arc::new(api_pairing::PairingStore::new(
|
||||
config.gateway.pairing_dashboard.max_pending_codes,
|
||||
)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let state = AppState {
|
||||
config: config_state,
|
||||
provider,
|
||||
@@ -681,6 +733,9 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
event_tx,
|
||||
shutdown_tx,
|
||||
node_registry,
|
||||
session_backend,
|
||||
device_registry,
|
||||
pending_pairings,
|
||||
};
|
||||
|
||||
// Config PUT needs larger body limit (1MB)
|
||||
@@ -711,6 +766,10 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
.route("/api/tools", get(api::handle_api_tools))
|
||||
.route("/api/cron", get(api::handle_api_cron_list))
|
||||
.route("/api/cron", post(api::handle_api_cron_add))
|
||||
.route(
|
||||
"/api/cron/settings",
|
||||
get(api::handle_api_cron_settings_get).patch(api::handle_api_cron_settings_patch),
|
||||
)
|
||||
.route("/api/cron/{id}", delete(api::handle_api_cron_delete))
|
||||
.route("/api/cron/{id}/runs", get(api::handle_api_cron_runs))
|
||||
.route("/api/integrations", get(api::handle_api_integrations))
|
||||
@@ -728,6 +787,26 @@ pub async fn run_gateway(host: &str, port: u16, config: Config) -> Result<()> {
|
||||
.route("/api/cost", get(api::handle_api_cost))
|
||||
.route("/api/cli-tools", get(api::handle_api_cli_tools))
|
||||
.route("/api/health", get(api::handle_api_health))
|
||||
.route("/api/sessions", get(api::handle_api_sessions_list))
|
||||
.route("/api/sessions/{id}", delete(api::handle_api_session_delete))
|
||||
// ── Pairing + Device management API ──
|
||||
.route("/api/pairing/initiate", post(api_pairing::initiate_pairing))
|
||||
.route("/api/pair", post(api_pairing::submit_pairing_enhanced))
|
||||
.route("/api/devices", get(api_pairing::list_devices))
|
||||
.route("/api/devices/{id}", delete(api_pairing::revoke_device))
|
||||
.route(
|
||||
"/api/devices/{id}/token/rotate",
|
||||
post(api_pairing::rotate_token),
|
||||
);
|
||||
|
||||
// ── Plugin management API (requires plugins-wasm feature) ──
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
let app = app.route(
|
||||
"/api/plugins",
|
||||
get(api_plugins::plugin_routes::list_plugins),
|
||||
);
|
||||
|
||||
let app = app
|
||||
// ── SSE event stream ──
|
||||
.route("/api/events", get(sse::handle_sse_events))
|
||||
// ── WebSocket agent chat ──
|
||||
@@ -1830,6 +1909,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let response = handle_metrics(State(state)).await.into_response();
|
||||
@@ -1882,6 +1964,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let response = handle_metrics(State(state)).await.into_response();
|
||||
@@ -2258,6 +2343,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
@@ -2324,6 +2412,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let headers = HeaderMap::new();
|
||||
@@ -2402,6 +2493,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let response = handle_webhook(
|
||||
@@ -2452,6 +2546,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
@@ -2507,6 +2604,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
@@ -2567,6 +2667,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let response = Box::pin(handle_nextcloud_talk_webhook(
|
||||
@@ -2623,6 +2726,9 @@ mod tests {
|
||||
event_tx: tokio::sync::broadcast::channel(16).0,
|
||||
shutdown_tx: tokio::sync::watch::channel(false).0,
|
||||
node_registry: Arc::new(nodes::NodeRegistry::new(16)),
|
||||
session_backend: None,
|
||||
device_registry: None,
|
||||
pending_pairings: None,
|
||||
};
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
+177
-44
@@ -20,6 +20,28 @@ use axum::{
|
||||
};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::Deserialize;
|
||||
use tracing::debug;
|
||||
|
||||
/// Optional connection parameters sent as the first WebSocket message.
|
||||
///
|
||||
/// If the first message after upgrade is `{"type":"connect",...}`, these
|
||||
/// parameters are extracted and an acknowledgement is sent back. Old clients
|
||||
/// that send `{"type":"message",...}` as the first frame still work — the
|
||||
/// message is processed normally (backward-compatible).
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ConnectParams {
|
||||
#[serde(rename = "type")]
|
||||
msg_type: String,
|
||||
/// Client-chosen session ID for memory persistence
|
||||
#[serde(default)]
|
||||
session_id: Option<String>,
|
||||
/// Device name for device registry tracking
|
||||
#[serde(default)]
|
||||
device_name: Option<String>,
|
||||
/// Client capabilities
|
||||
#[serde(default)]
|
||||
capabilities: Vec<String>,
|
||||
}
|
||||
|
||||
/// The sub-protocol we support for the chat WebSocket.
|
||||
const WS_PROTOCOL: &str = "zeroclaw.v1";
|
||||
@@ -111,14 +133,21 @@ pub async fn handle_ws_chat(
|
||||
ws
|
||||
};
|
||||
|
||||
let session_id = params.session_id.clone();
|
||||
let session_id = params.session_id;
|
||||
ws.on_upgrade(move |socket| handle_socket(socket, state, session_id))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// Gateway session key prefix to avoid collisions with channel sessions.
|
||||
const GW_SESSION_PREFIX: &str = "gw_";
|
||||
|
||||
async fn handle_socket(socket: WebSocket, state: AppState, session_id: Option<String>) {
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
|
||||
// Resolve session ID: use provided or generate a new UUID
|
||||
let session_id = session_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
|
||||
let session_key = format!("{GW_SESSION_PREFIX}{session_id}");
|
||||
|
||||
// Build a persistent Agent for this connection so history is maintained across turns.
|
||||
let config = state.config.lock().clone();
|
||||
let mut agent = match crate::agent::Agent::from_config(&config) {
|
||||
@@ -129,7 +158,90 @@ async fn handle_socket(socket: WebSocket, state: AppState, session_id: Option<St
|
||||
return;
|
||||
}
|
||||
};
|
||||
agent.set_memory_session_id(session_id.clone());
|
||||
agent.set_memory_session_id(Some(session_id.clone()));
|
||||
|
||||
// Hydrate agent from persisted session (if available)
|
||||
let mut resumed = false;
|
||||
let mut message_count: usize = 0;
|
||||
if let Some(ref backend) = state.session_backend {
|
||||
let messages = backend.load(&session_key);
|
||||
if !messages.is_empty() {
|
||||
message_count = messages.len();
|
||||
agent.seed_history(&messages);
|
||||
resumed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Send session_start message to client
|
||||
let session_start = serde_json::json!({
|
||||
"type": "session_start",
|
||||
"session_id": session_id,
|
||||
"resumed": resumed,
|
||||
"message_count": message_count,
|
||||
});
|
||||
let _ = sender
|
||||
.send(Message::Text(session_start.to_string().into()))
|
||||
.await;
|
||||
|
||||
// ── Optional connect handshake ──────────────────────────────────
|
||||
// The first message may be a `{"type":"connect",...}` frame carrying
|
||||
// connection parameters. If it is, we extract the params, send an
|
||||
// ack, and proceed to the normal message loop. If the first message
|
||||
// is a regular `{"type":"message",...}` frame, we fall through and
|
||||
// process it immediately (backward-compatible).
|
||||
let mut first_msg_fallback: Option<String> = None;
|
||||
|
||||
if let Some(first) = receiver.next().await {
|
||||
match first {
|
||||
Ok(Message::Text(text)) => {
|
||||
if let Ok(cp) = serde_json::from_str::<ConnectParams>(&text) {
|
||||
if cp.msg_type == "connect" {
|
||||
debug!(
|
||||
session_id = ?cp.session_id,
|
||||
device_name = ?cp.device_name,
|
||||
capabilities = ?cp.capabilities,
|
||||
"WebSocket connect params received"
|
||||
);
|
||||
// Override session_id if provided in connect params
|
||||
if let Some(sid) = &cp.session_id {
|
||||
agent.set_memory_session_id(Some(sid.clone()));
|
||||
}
|
||||
let ack = serde_json::json!({
|
||||
"type": "connected",
|
||||
"message": "Connection established"
|
||||
});
|
||||
let _ = sender.send(Message::Text(ack.to_string().into())).await;
|
||||
} else {
|
||||
// Not a connect message — fall through to normal processing
|
||||
first_msg_fallback = Some(text.to_string());
|
||||
}
|
||||
} else {
|
||||
// Not parseable as ConnectParams — fall through
|
||||
first_msg_fallback = Some(text.to_string());
|
||||
}
|
||||
}
|
||||
Ok(Message::Close(_)) | Err(_) => return,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Process the first message if it was not a connect frame
|
||||
if let Some(ref text) = first_msg_fallback {
|
||||
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(text) {
|
||||
if parsed["type"].as_str() == Some("message") {
|
||||
let content = parsed["content"].as_str().unwrap_or("").to_string();
|
||||
if !content.is_empty() {
|
||||
// Persist user message
|
||||
if let Some(ref backend) = state.session_backend {
|
||||
let user_msg = crate::providers::ChatMessage::user(&content);
|
||||
let _ = backend.append(&session_key, &user_msg);
|
||||
}
|
||||
process_chat_message(&state, &mut agent, &mut sender, &content, &session_key)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(msg) = receiver.next().await {
|
||||
let msg = match msg {
|
||||
@@ -158,53 +270,74 @@ async fn handle_socket(socket: WebSocket, state: AppState, session_id: Option<St
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process message with the LLM provider
|
||||
let provider_label = state
|
||||
.config
|
||||
.lock()
|
||||
.default_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
// Persist user message
|
||||
if let Some(ref backend) = state.session_backend {
|
||||
let user_msg = crate::providers::ChatMessage::user(&content);
|
||||
let _ = backend.append(&session_key, &user_msg);
|
||||
}
|
||||
|
||||
// Broadcast agent_start event
|
||||
let _ = state.event_tx.send(serde_json::json!({
|
||||
"type": "agent_start",
|
||||
"provider": provider_label,
|
||||
"model": state.model,
|
||||
}));
|
||||
process_chat_message(&state, &mut agent, &mut sender, &content, &session_key).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Multi-turn chat via persistent Agent (history is maintained across turns)
|
||||
match agent.turn(&content).await {
|
||||
Ok(response) => {
|
||||
// Send the full response as a done message
|
||||
let done = serde_json::json!({
|
||||
"type": "done",
|
||||
"full_response": response,
|
||||
});
|
||||
let _ = sender.send(Message::Text(done.to_string().into())).await;
|
||||
/// Process a single chat message through the agent and send the response.
|
||||
async fn process_chat_message(
|
||||
state: &AppState,
|
||||
agent: &mut crate::agent::Agent,
|
||||
sender: &mut futures_util::stream::SplitSink<WebSocket, Message>,
|
||||
content: &str,
|
||||
session_key: &str,
|
||||
) {
|
||||
let provider_label = state
|
||||
.config
|
||||
.lock()
|
||||
.default_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
// Broadcast agent_end event
|
||||
let _ = state.event_tx.send(serde_json::json!({
|
||||
"type": "agent_end",
|
||||
"provider": provider_label,
|
||||
"model": state.model,
|
||||
}));
|
||||
// Broadcast agent_start event
|
||||
let _ = state.event_tx.send(serde_json::json!({
|
||||
"type": "agent_start",
|
||||
"provider": provider_label,
|
||||
"model": state.model,
|
||||
}));
|
||||
|
||||
// Multi-turn chat via persistent Agent (history is maintained across turns)
|
||||
match agent.turn(content).await {
|
||||
Ok(response) => {
|
||||
// Persist assistant response
|
||||
if let Some(ref backend) = state.session_backend {
|
||||
let assistant_msg = crate::providers::ChatMessage::assistant(&response);
|
||||
let _ = backend.append(session_key, &assistant_msg);
|
||||
}
|
||||
Err(e) => {
|
||||
let sanitized = crate::providers::sanitize_api_error(&e.to_string());
|
||||
let err = serde_json::json!({
|
||||
"type": "error",
|
||||
"message": sanitized,
|
||||
});
|
||||
let _ = sender.send(Message::Text(err.to_string().into())).await;
|
||||
|
||||
// Broadcast error event
|
||||
let _ = state.event_tx.send(serde_json::json!({
|
||||
"type": "error",
|
||||
"component": "ws_chat",
|
||||
"message": sanitized,
|
||||
}));
|
||||
}
|
||||
let done = serde_json::json!({
|
||||
"type": "done",
|
||||
"full_response": response,
|
||||
});
|
||||
let _ = sender.send(Message::Text(done.to_string().into())).await;
|
||||
|
||||
// Broadcast agent_end event
|
||||
let _ = state.event_tx.send(serde_json::json!({
|
||||
"type": "agent_end",
|
||||
"provider": provider_label,
|
||||
"model": state.model,
|
||||
}));
|
||||
}
|
||||
Err(e) => {
|
||||
let sanitized = crate::providers::sanitize_api_error(&e.to_string());
|
||||
let err = serde_json::json!({
|
||||
"type": "error",
|
||||
"message": sanitized,
|
||||
});
|
||||
let _ = sender.send(Message::Text(err.to_string().into())).await;
|
||||
|
||||
// Broadcast error event
|
||||
let _ = state.event_tx.send(serde_json::json!({
|
||||
"type": "error",
|
||||
"component": "ws_chat",
|
||||
"message": sanitized,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
//! Internationalization support for tool descriptions.
|
||||
//!
|
||||
//! Loads tool descriptions from TOML locale files in `tool_descriptions/`.
|
||||
//! Falls back to English when a locale file or specific key is missing,
|
||||
//! and ultimately falls back to the hardcoded `tool.description()` value
|
||||
//! if no file-based description exists.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tracing::debug;
|
||||
|
||||
/// Container for locale-specific tool descriptions loaded from TOML files.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ToolDescriptions {
|
||||
/// Descriptions from the requested locale (may be empty if file missing).
|
||||
locale_descriptions: HashMap<String, String>,
|
||||
/// English fallback descriptions (always loaded when locale != "en").
|
||||
english_fallback: HashMap<String, String>,
|
||||
/// The resolved locale tag (e.g. "en", "zh-CN").
|
||||
locale: String,
|
||||
}
|
||||
|
||||
/// TOML structure: `[tools]` table mapping tool name -> description string.
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
struct DescriptionFile {
|
||||
#[serde(default)]
|
||||
tools: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl ToolDescriptions {
|
||||
/// Load descriptions for the given locale.
|
||||
///
|
||||
/// `search_dirs` lists directories to probe for `tool_descriptions/<locale>.toml`.
|
||||
/// The first directory containing a matching file wins.
|
||||
///
|
||||
/// Resolution:
|
||||
/// 1. Look up tool name in the locale file.
|
||||
/// 2. If missing (or locale file absent), look up in `en.toml`.
|
||||
/// 3. If still missing, callers fall back to `tool.description()`.
|
||||
pub fn load(locale: &str, search_dirs: &[PathBuf]) -> Self {
|
||||
let locale_descriptions = load_locale_file(locale, search_dirs);
|
||||
|
||||
let english_fallback = if locale == "en" {
|
||||
HashMap::new()
|
||||
} else {
|
||||
load_locale_file("en", search_dirs)
|
||||
};
|
||||
|
||||
debug!(
|
||||
locale = locale,
|
||||
locale_keys = locale_descriptions.len(),
|
||||
english_keys = english_fallback.len(),
|
||||
"tool descriptions loaded"
|
||||
);
|
||||
|
||||
Self {
|
||||
locale_descriptions,
|
||||
english_fallback,
|
||||
locale: locale.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the description for a tool by name.
|
||||
///
|
||||
/// Returns `Some(description)` if found in the locale file or English fallback.
|
||||
/// Returns `None` if neither file contains the key (caller should use hardcoded).
|
||||
pub fn get(&self, tool_name: &str) -> Option<&str> {
|
||||
self.locale_descriptions
|
||||
.get(tool_name)
|
||||
.or_else(|| self.english_fallback.get(tool_name))
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
/// The resolved locale tag.
|
||||
pub fn locale(&self) -> &str {
|
||||
&self.locale
|
||||
}
|
||||
|
||||
/// Create an empty instance that always returns `None` (hardcoded fallback).
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
locale_descriptions: HashMap::new(),
|
||||
english_fallback: HashMap::new(),
|
||||
locale: "en".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect the user's preferred locale from environment variables.
|
||||
///
|
||||
/// Checks `ZEROCLAW_LOCALE`, then `LANG`, then `LC_ALL`.
|
||||
/// Returns "en" if none are set or parseable.
|
||||
pub fn detect_locale() -> String {
|
||||
if let Ok(val) = std::env::var("ZEROCLAW_LOCALE") {
|
||||
let val = val.trim().to_string();
|
||||
if !val.is_empty() {
|
||||
return normalize_locale(&val);
|
||||
}
|
||||
}
|
||||
for var in &["LANG", "LC_ALL"] {
|
||||
if let Ok(val) = std::env::var(var) {
|
||||
let locale = normalize_locale(&val);
|
||||
if locale != "C" && locale != "POSIX" && !locale.is_empty() {
|
||||
return locale;
|
||||
}
|
||||
}
|
||||
}
|
||||
"en".to_string()
|
||||
}
|
||||
|
||||
/// Normalize a raw locale string (e.g. "zh_CN.UTF-8") to a tag we use
|
||||
/// for file lookup (e.g. "zh-CN").
|
||||
fn normalize_locale(raw: &str) -> String {
|
||||
// Strip encoding suffix (.UTF-8, .utf8, etc.)
|
||||
let base = raw.split('.').next().unwrap_or(raw);
|
||||
// Replace underscores with hyphens for BCP-47-ish consistency
|
||||
base.replace('_', "-")
|
||||
}
|
||||
|
||||
/// Build the default set of search directories for locale files.
|
||||
///
|
||||
/// 1. The workspace directory itself (for project-local overrides).
|
||||
/// 2. The binary's parent directory (for installed distributions).
|
||||
/// 3. The compile-time `CARGO_MANIFEST_DIR` as a final fallback during dev.
|
||||
pub fn default_search_dirs(workspace_dir: &Path) -> Vec<PathBuf> {
|
||||
let mut dirs = vec![workspace_dir.to_path_buf()];
|
||||
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(parent) = exe.parent() {
|
||||
dirs.push(parent.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
// During development, also check the project root (where Cargo.toml lives).
|
||||
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
if !dirs.contains(&manifest_dir) {
|
||||
dirs.push(manifest_dir);
|
||||
}
|
||||
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Try to load and parse a locale TOML file from the first matching search dir.
|
||||
fn load_locale_file(locale: &str, search_dirs: &[PathBuf]) -> HashMap<String, String> {
|
||||
let filename = format!("tool_descriptions/{locale}.toml");
|
||||
|
||||
for dir in search_dirs {
|
||||
let path = dir.join(&filename);
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(contents) => match toml::from_str::<DescriptionFile>(&contents) {
|
||||
Ok(parsed) => {
|
||||
debug!(path = %path.display(), keys = parsed.tools.len(), "loaded locale file");
|
||||
return parsed.tools;
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(path = %path.display(), error = %e, "failed to parse locale file");
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
// File not found in this directory, try next.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!(
|
||||
locale = locale,
|
||||
"no locale file found in any search directory"
|
||||
);
|
||||
HashMap::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
/// Helper: create a temp dir with a `tool_descriptions/<locale>.toml` file.
|
||||
fn write_locale_file(dir: &Path, locale: &str, content: &str) {
|
||||
let td = dir.join("tool_descriptions");
|
||||
fs::create_dir_all(&td).unwrap();
|
||||
fs::write(td.join(format!("{locale}.toml")), content).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_english_descriptions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write_locale_file(
|
||||
tmp.path(),
|
||||
"en",
|
||||
r#"[tools]
|
||||
shell = "Execute a shell command"
|
||||
file_read = "Read file contents"
|
||||
"#,
|
||||
);
|
||||
let descs = ToolDescriptions::load("en", &[tmp.path().to_path_buf()]);
|
||||
assert_eq!(descs.get("shell"), Some("Execute a shell command"));
|
||||
assert_eq!(descs.get("file_read"), Some("Read file contents"));
|
||||
assert_eq!(descs.get("nonexistent"), None);
|
||||
assert_eq!(descs.locale(), "en");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_to_english_when_locale_key_missing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write_locale_file(
|
||||
tmp.path(),
|
||||
"en",
|
||||
r#"[tools]
|
||||
shell = "Execute a shell command"
|
||||
file_read = "Read file contents"
|
||||
"#,
|
||||
);
|
||||
write_locale_file(
|
||||
tmp.path(),
|
||||
"zh-CN",
|
||||
r#"[tools]
|
||||
shell = "在工作区目录中执行 shell 命令"
|
||||
"#,
|
||||
);
|
||||
let descs = ToolDescriptions::load("zh-CN", &[tmp.path().to_path_buf()]);
|
||||
// Translated key returns Chinese.
|
||||
assert_eq!(descs.get("shell"), Some("在工作区目录中执行 shell 命令"));
|
||||
// Missing key falls back to English.
|
||||
assert_eq!(descs.get("file_read"), Some("Read file contents"));
|
||||
assert_eq!(descs.locale(), "zh-CN");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_when_locale_file_missing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write_locale_file(
|
||||
tmp.path(),
|
||||
"en",
|
||||
r#"[tools]
|
||||
shell = "Execute a shell command"
|
||||
"#,
|
||||
);
|
||||
// Request a locale that has no file.
|
||||
let descs = ToolDescriptions::load("fr", &[tmp.path().to_path_buf()]);
|
||||
// Falls back to English.
|
||||
assert_eq!(descs.get("shell"), Some("Execute a shell command"));
|
||||
assert_eq!(descs.locale(), "fr");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_when_no_files_exist() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let descs = ToolDescriptions::load("en", &[tmp.path().to_path_buf()]);
|
||||
assert_eq!(descs.get("shell"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_always_returns_none() {
|
||||
let descs = ToolDescriptions::empty();
|
||||
assert_eq!(descs.get("shell"), None);
|
||||
assert_eq!(descs.locale(), "en");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_locale_from_env() {
|
||||
// Save and restore env.
|
||||
let saved = std::env::var("ZEROCLAW_LOCALE").ok();
|
||||
let saved_lang = std::env::var("LANG").ok();
|
||||
|
||||
std::env::set_var("ZEROCLAW_LOCALE", "ja-JP");
|
||||
assert_eq!(detect_locale(), "ja-JP");
|
||||
|
||||
std::env::remove_var("ZEROCLAW_LOCALE");
|
||||
std::env::set_var("LANG", "zh_CN.UTF-8");
|
||||
assert_eq!(detect_locale(), "zh-CN");
|
||||
|
||||
// Restore.
|
||||
match saved {
|
||||
Some(v) => std::env::set_var("ZEROCLAW_LOCALE", v),
|
||||
None => std::env::remove_var("ZEROCLAW_LOCALE"),
|
||||
}
|
||||
match saved_lang {
|
||||
Some(v) => std::env::set_var("LANG", v),
|
||||
None => std::env::remove_var("LANG"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_locale_strips_encoding() {
|
||||
assert_eq!(normalize_locale("en_US.UTF-8"), "en-US");
|
||||
assert_eq!(normalize_locale("zh_CN.utf8"), "zh-CN");
|
||||
assert_eq!(normalize_locale("fr"), "fr");
|
||||
assert_eq!(normalize_locale("pt_BR"), "pt-BR");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_locale_overrides_env() {
|
||||
// This tests the precedence logic: if config provides a locale,
|
||||
// it should be used instead of detect_locale().
|
||||
// The actual override happens at the call site in prompt.rs / loop_.rs,
|
||||
// so here we just verify ToolDescriptions works with an explicit locale.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write_locale_file(
|
||||
tmp.path(),
|
||||
"de",
|
||||
r#"[tools]
|
||||
shell = "Einen Shell-Befehl im Arbeitsverzeichnis ausführen"
|
||||
"#,
|
||||
);
|
||||
let descs = ToolDescriptions::load("de", &[tmp.path().to_path_buf()]);
|
||||
assert_eq!(
|
||||
descs.get("shell"),
|
||||
Some("Einen Shell-Befehl im Arbeitsverzeichnis ausführen")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -840,6 +840,7 @@ mod tests {
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
let entries = all_integrations();
|
||||
let tg = entries.iter().find(|e| e.name == "Telegram").unwrap();
|
||||
|
||||
+20
@@ -42,6 +42,7 @@ pub mod agent;
|
||||
pub(crate) mod approval;
|
||||
pub(crate) mod auth;
|
||||
pub mod channels;
|
||||
pub mod commands;
|
||||
pub mod config;
|
||||
pub(crate) mod cost;
|
||||
pub(crate) mod cron;
|
||||
@@ -53,6 +54,7 @@ pub(crate) mod hardware;
|
||||
pub(crate) mod health;
|
||||
pub(crate) mod heartbeat;
|
||||
pub mod hooks;
|
||||
pub mod i18n;
|
||||
pub(crate) mod identity;
|
||||
pub(crate) mod integrations;
|
||||
pub mod memory;
|
||||
@@ -72,6 +74,9 @@ pub mod tools;
|
||||
pub(crate) mod tunnel;
|
||||
pub(crate) mod util;
|
||||
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
pub mod plugins;
|
||||
|
||||
pub use config::Config;
|
||||
|
||||
/// Gateway management subcommands
|
||||
@@ -294,6 +299,9 @@ Examples:
|
||||
/// Treat the argument as an agent prompt instead of a shell command
|
||||
#[arg(long)]
|
||||
agent: bool,
|
||||
/// Restrict agent cron jobs to the specified tool names (repeatable, agent-only)
|
||||
#[arg(long = "allowed-tool")]
|
||||
allowed_tools: Vec<String>,
|
||||
/// Command (shell) or prompt (agent) to run
|
||||
command: String,
|
||||
},
|
||||
@@ -312,6 +320,9 @@ Examples:
|
||||
/// Treat the argument as an agent prompt instead of a shell command
|
||||
#[arg(long)]
|
||||
agent: bool,
|
||||
/// Restrict agent cron jobs to the specified tool names (repeatable, agent-only)
|
||||
#[arg(long = "allowed-tool")]
|
||||
allowed_tools: Vec<String>,
|
||||
/// Command (shell) or prompt (agent) to run
|
||||
command: String,
|
||||
},
|
||||
@@ -330,6 +341,9 @@ Examples:
|
||||
/// Treat the argument as an agent prompt instead of a shell command
|
||||
#[arg(long)]
|
||||
agent: bool,
|
||||
/// Restrict agent cron jobs to the specified tool names (repeatable, agent-only)
|
||||
#[arg(long = "allowed-tool")]
|
||||
allowed_tools: Vec<String>,
|
||||
/// Command (shell) or prompt (agent) to run
|
||||
command: String,
|
||||
},
|
||||
@@ -350,6 +364,9 @@ Examples:
|
||||
/// Treat the argument as an agent prompt instead of a shell command
|
||||
#[arg(long)]
|
||||
agent: bool,
|
||||
/// Restrict agent cron jobs to the specified tool names (repeatable, agent-only)
|
||||
#[arg(long = "allowed-tool")]
|
||||
allowed_tools: Vec<String>,
|
||||
/// Command (shell) or prompt (agent) to run
|
||||
command: String,
|
||||
},
|
||||
@@ -383,6 +400,9 @@ Examples:
|
||||
/// New job name
|
||||
#[arg(long)]
|
||||
name: Option<String>,
|
||||
/// Replace the agent job allowlist with the specified tool names (repeatable)
|
||||
#[arg(long = "allowed-tool")]
|
||||
allowed_tools: Vec<String>,
|
||||
},
|
||||
/// Pause a scheduled task
|
||||
Pause {
|
||||
|
||||
+198
-25
@@ -75,6 +75,7 @@ mod agent;
|
||||
mod approval;
|
||||
mod auth;
|
||||
mod channels;
|
||||
mod commands;
|
||||
mod rag {
|
||||
pub use zeroclaw::rag::*;
|
||||
}
|
||||
@@ -88,6 +89,7 @@ mod hardware;
|
||||
mod health;
|
||||
mod heartbeat;
|
||||
mod hooks;
|
||||
mod i18n;
|
||||
mod identity;
|
||||
mod integrations;
|
||||
mod memory;
|
||||
@@ -96,6 +98,8 @@ mod multimodal;
|
||||
mod observability;
|
||||
mod onboard;
|
||||
mod peripherals;
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
mod plugins;
|
||||
mod providers;
|
||||
mod runtime;
|
||||
mod security;
|
||||
@@ -282,7 +286,11 @@ Examples:
|
||||
},
|
||||
|
||||
/// Show system status (full details)
|
||||
Status,
|
||||
Status {
|
||||
/// Output format: "exit-code" exits 0 if healthy, 1 otherwise (for Docker HEALTHCHECK)
|
||||
#[arg(long)]
|
||||
format: Option<String>,
|
||||
},
|
||||
|
||||
/// Engage, inspect, and resume emergency-stop states.
|
||||
///
|
||||
@@ -462,6 +470,52 @@ Examples:
|
||||
config_command: ConfigCommands,
|
||||
},
|
||||
|
||||
/// Check for and apply updates
|
||||
#[command(long_about = "\
|
||||
Check for and apply ZeroClaw updates.
|
||||
|
||||
By default, downloads and installs the latest release with a \
|
||||
6-phase pipeline: preflight, download, backup, validate, swap, \
|
||||
and smoke test. Automatic rollback on failure.
|
||||
|
||||
Use --check to only check for updates without installing.
|
||||
Use --force to skip the confirmation prompt.
|
||||
Use --version to target a specific release instead of latest.
|
||||
|
||||
Examples:
|
||||
zeroclaw update # download and install latest
|
||||
zeroclaw update --check # check only, don't install
|
||||
zeroclaw update --force # install without confirmation
|
||||
zeroclaw update --version 0.6.0 # install specific version")]
|
||||
Update {
|
||||
/// Only check for updates, don't install
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
/// Skip confirmation prompt
|
||||
#[arg(long)]
|
||||
force: bool,
|
||||
/// Target version (default: latest)
|
||||
#[arg(long)]
|
||||
version: Option<String>,
|
||||
},
|
||||
|
||||
/// Run diagnostic self-tests
|
||||
#[command(long_about = "\
|
||||
Run diagnostic self-tests to verify the ZeroClaw installation.
|
||||
|
||||
By default, runs the full test suite including network checks \
|
||||
(gateway health, memory round-trip). Use --quick to skip network \
|
||||
checks for faster offline validation.
|
||||
|
||||
Examples:
|
||||
zeroclaw self-test # full suite
|
||||
zeroclaw self-test --quick # quick checks only (no network)")]
|
||||
SelfTest {
|
||||
/// Run quick checks only (no network)
|
||||
#[arg(long)]
|
||||
quick: bool,
|
||||
},
|
||||
|
||||
/// Generate shell completion script to stdout
|
||||
#[command(long_about = "\
|
||||
Generate shell completion scripts for `zeroclaw`.
|
||||
@@ -477,6 +531,35 @@ Examples:
|
||||
#[arg(value_enum)]
|
||||
shell: CompletionShell,
|
||||
},
|
||||
|
||||
/// Manage WASM plugins
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
Plugin {
|
||||
#[command(subcommand)]
|
||||
plugin_command: PluginCommands,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum PluginCommands {
|
||||
/// List installed plugins
|
||||
List,
|
||||
/// Install a plugin from a directory or URL
|
||||
Install {
|
||||
/// Path to plugin directory or manifest
|
||||
source: String,
|
||||
},
|
||||
/// Remove an installed plugin
|
||||
Remove {
|
||||
/// Plugin name
|
||||
name: String,
|
||||
},
|
||||
/// Show information about a plugin
|
||||
Info {
|
||||
/// Plugin name
|
||||
name: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
@@ -816,30 +899,12 @@ async fn main() -> Result<()> {
|
||||
.await
|
||||
}?;
|
||||
|
||||
// Display pairing code — user enters it in the dashboard to pair securely.
|
||||
// The code is one-time use and brute-force protected (5 attempts → lockout).
|
||||
// No auth material is placed in URLs to prevent leakage via browser history,
|
||||
// Referer headers, clipboard, or proxy logs.
|
||||
if config.gateway.require_pairing {
|
||||
let pairing = security::PairingGuard::new(true, &config.gateway.paired_tokens);
|
||||
if let Some(code) = pairing.pairing_code() {
|
||||
println!();
|
||||
println!(" \x1b[1;34m🦀 Gateway Pairing Code\x1b[0m");
|
||||
println!();
|
||||
println!(" \x1b[1;34m┌──────────────┐\x1b[0m");
|
||||
println!(" \x1b[1;34m│\x1b[0m \x1b[1m{code}\x1b[0m \x1b[1;34m│\x1b[0m");
|
||||
println!(" \x1b[1;34m└──────────────┘\x1b[0m");
|
||||
println!();
|
||||
println!(" Enter this code in the dashboard to pair your device.");
|
||||
println!(" The code is single-use and expires after pairing.");
|
||||
println!();
|
||||
println!(
|
||||
" \x1b[2mDashboard: http://127.0.0.1:{}\x1b[0m",
|
||||
config.gateway.port
|
||||
);
|
||||
println!(" \x1b[2mDocs: https://www.zeroclawlabs.ai/docs\x1b[0m");
|
||||
println!();
|
||||
}
|
||||
println!();
|
||||
println!(" Pairing is enabled. A one-time pairing code will be");
|
||||
println!(" displayed when the gateway starts.");
|
||||
println!(" Dashboard: http://127.0.0.1:{}", config.gateway.port);
|
||||
println!();
|
||||
}
|
||||
|
||||
// Auto-start channels if user said yes during wizard
|
||||
@@ -1002,7 +1067,30 @@ async fn main() -> Result<()> {
|
||||
Box::pin(daemon::run(config, host, port)).await
|
||||
}
|
||||
|
||||
Commands::Status => {
|
||||
Commands::Status { format } => {
|
||||
if format.as_deref() == Some("exit-code") {
|
||||
// Lightweight health probe for Docker HEALTHCHECK
|
||||
let port = config.gateway.port;
|
||||
let host = if config.gateway.host == "[::]" || config.gateway.host == "0.0.0.0" {
|
||||
"127.0.0.1"
|
||||
} else {
|
||||
&config.gateway.host
|
||||
};
|
||||
let url = format!("http://{}:{}/health", host, port);
|
||||
match reqwest::Client::new()
|
||||
.get(&url)
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
std::process::exit(0);
|
||||
}
|
||||
_ => {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("🦀 ZeroClaw Status");
|
||||
println!();
|
||||
println!("Version: {}", env!("CARGO_PKG_VERSION"));
|
||||
@@ -1224,6 +1312,41 @@ async fn main() -> Result<()> {
|
||||
.await
|
||||
}
|
||||
|
||||
Commands::Update {
|
||||
check,
|
||||
force: _force,
|
||||
version,
|
||||
} => {
|
||||
if check {
|
||||
let info = commands::update::check(version.as_deref()).await?;
|
||||
if info.is_newer {
|
||||
println!(
|
||||
"Update available: v{} -> v{}",
|
||||
info.current_version, info.latest_version
|
||||
);
|
||||
} else {
|
||||
println!("Already up to date (v{}).", info.current_version);
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
commands::update::run(version.as_deref()).await
|
||||
}
|
||||
}
|
||||
|
||||
Commands::SelfTest { quick } => {
|
||||
let results = if quick {
|
||||
commands::self_test::run_quick(&config).await?
|
||||
} else {
|
||||
commands::self_test::run_full(&config).await?
|
||||
};
|
||||
commands::self_test::print_results(&results);
|
||||
let failed = results.iter().filter(|r| !r.passed).count();
|
||||
if failed > 0 {
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Commands::Config { config_command } => match config_command {
|
||||
ConfigCommands::Schema => {
|
||||
let schema = schemars::schema_for!(config::Config);
|
||||
@@ -1234,6 +1357,56 @@ async fn main() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|
||||
#[cfg(feature = "plugins-wasm")]
|
||||
Commands::Plugin { plugin_command } => match plugin_command {
|
||||
PluginCommands::List => {
|
||||
let host = zeroclaw::plugins::host::PluginHost::new(&config.workspace_dir)?;
|
||||
let plugins = host.list_plugins();
|
||||
if plugins.is_empty() {
|
||||
println!("No plugins installed.");
|
||||
} else {
|
||||
println!("Installed plugins:");
|
||||
for p in &plugins {
|
||||
println!(
|
||||
" {} v{} — {}",
|
||||
p.name,
|
||||
p.version,
|
||||
p.description.as_deref().unwrap_or("(no description)")
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
PluginCommands::Install { source } => {
|
||||
let mut host = zeroclaw::plugins::host::PluginHost::new(&config.workspace_dir)?;
|
||||
host.install(&source)?;
|
||||
println!("Plugin installed from {source}");
|
||||
Ok(())
|
||||
}
|
||||
PluginCommands::Remove { name } => {
|
||||
let mut host = zeroclaw::plugins::host::PluginHost::new(&config.workspace_dir)?;
|
||||
host.remove(&name)?;
|
||||
println!("Plugin '{name}' removed.");
|
||||
Ok(())
|
||||
}
|
||||
PluginCommands::Info { name } => {
|
||||
let host = zeroclaw::plugins::host::PluginHost::new(&config.workspace_dir)?;
|
||||
match host.get_plugin(&name) {
|
||||
Some(info) => {
|
||||
println!("Plugin: {} v{}", info.name, info.version);
|
||||
if let Some(desc) = &info.description {
|
||||
println!("Description: {desc}");
|
||||
}
|
||||
println!("Capabilities: {:?}", info.capabilities);
|
||||
println!("Permissions: {:?}", info.permissions);
|
||||
println!("WASM: {}", info.wasm_path.display());
|
||||
}
|
||||
None => println!("Plugin '{name}' not found."),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +101,7 @@ pub fn should_skip_autosave_content(content: &str) -> bool {
|
||||
|
||||
let lowered = normalized.to_ascii_lowercase();
|
||||
lowered.starts_with("[cron:")
|
||||
|| lowered.starts_with("[heartbeat task")
|
||||
|| lowered.starts_with("[distilled_")
|
||||
|| lowered.contains("distilled_index_sig:")
|
||||
}
|
||||
@@ -471,6 +472,12 @@ mod tests {
|
||||
assert!(should_skip_autosave_content(
|
||||
"[DISTILLED_MEMORY_CHUNK 1/2] DISTILLED_INDEX_SIG:abc123"
|
||||
));
|
||||
assert!(should_skip_autosave_content(
|
||||
"[Heartbeat Task | decision] Should I run tasks?"
|
||||
));
|
||||
assert!(should_skip_autosave_content(
|
||||
"[Heartbeat Task | high] Execute scheduled patrol"
|
||||
));
|
||||
assert!(!should_skip_autosave_content(
|
||||
"User prefers concise answers."
|
||||
));
|
||||
|
||||
@@ -192,6 +192,8 @@ pub async fn run_wizard(force: bool) -> Result<Config> {
|
||||
node_transport: crate::config::NodeTransportConfig::default(),
|
||||
knowledge: crate::config::KnowledgeConfig::default(),
|
||||
linkedin: crate::config::LinkedInConfig::default(),
|
||||
plugins: crate::config::PluginsConfig::default(),
|
||||
locale: None,
|
||||
};
|
||||
|
||||
println!(
|
||||
@@ -461,6 +463,47 @@ fn resolve_quick_setup_dirs_with_home(home: &Path) -> (PathBuf, PathBuf) {
|
||||
(config_dir.clone(), config_dir.join("workspace"))
|
||||
}
|
||||
|
||||
fn homebrew_prefix_for_exe(exe: &Path) -> Option<&'static str> {
|
||||
let exe = exe.to_string_lossy();
|
||||
if exe == "/opt/homebrew/bin/zeroclaw"
|
||||
|| exe.starts_with("/opt/homebrew/Cellar/zeroclaw/")
|
||||
|| exe.starts_with("/opt/homebrew/opt/zeroclaw/")
|
||||
{
|
||||
return Some("/opt/homebrew");
|
||||
}
|
||||
|
||||
if exe == "/usr/local/bin/zeroclaw"
|
||||
|| exe.starts_with("/usr/local/Cellar/zeroclaw/")
|
||||
|| exe.starts_with("/usr/local/opt/zeroclaw/")
|
||||
{
|
||||
return Some("/usr/local");
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn quick_setup_homebrew_service_note(
|
||||
config_path: &Path,
|
||||
workspace_dir: &Path,
|
||||
exe: &Path,
|
||||
) -> Option<String> {
|
||||
let prefix = homebrew_prefix_for_exe(exe)?;
|
||||
let service_root = Path::new(prefix).join("var").join("zeroclaw");
|
||||
let service_config = service_root.join("config.toml");
|
||||
let service_workspace = service_root.join("workspace");
|
||||
|
||||
if config_path == service_config || workspace_dir == service_workspace {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(format!(
|
||||
"Homebrew service note: `brew services` uses {} (config {}) by default. Your onboarding just wrote {}. If you plan to run ZeroClaw as a service, copy or link this workspace first.",
|
||||
service_workspace.display(),
|
||||
service_config.display(),
|
||||
config_path.display(),
|
||||
))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
async fn run_quick_setup_with_home(
|
||||
credential_override: Option<&str>,
|
||||
@@ -565,6 +608,8 @@ async fn run_quick_setup_with_home(
|
||||
node_transport: crate::config::NodeTransportConfig::default(),
|
||||
knowledge: crate::config::KnowledgeConfig::default(),
|
||||
linkedin: crate::config::LinkedInConfig::default(),
|
||||
plugins: crate::config::PluginsConfig::default(),
|
||||
locale: None,
|
||||
};
|
||||
|
||||
config.save().await?;
|
||||
@@ -646,6 +691,16 @@ async fn run_quick_setup_with_home(
|
||||
style("Config saved:").white().bold(),
|
||||
style(config_path.display()).green()
|
||||
);
|
||||
if cfg!(target_os = "macos") {
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(note) =
|
||||
quick_setup_homebrew_service_note(&config_path, &workspace_dir, &exe)
|
||||
{
|
||||
println!();
|
||||
println!(" {}", style(note).yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
println!();
|
||||
println!(" {}", style("Next steps:").white().bold());
|
||||
if credential_override.is_none() {
|
||||
@@ -3681,6 +3736,7 @@ fn setup_channels() -> Result<ChannelsConfig> {
|
||||
draft_update_interval_ms: 1000,
|
||||
interrupt_on_new_message: false,
|
||||
mention_only: false,
|
||||
ack_reactions: None,
|
||||
});
|
||||
}
|
||||
ChannelMenuChoice::Discord => {
|
||||
@@ -3908,6 +3964,7 @@ fn setup_channels() -> Result<ChannelsConfig> {
|
||||
},
|
||||
allowed_users,
|
||||
interrupt_on_new_message: false,
|
||||
thread_replies: None,
|
||||
mention_only: false,
|
||||
});
|
||||
}
|
||||
@@ -6061,6 +6118,52 @@ mod tests {
|
||||
assert_eq!(config.config_path, expected_config_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn homebrew_prefix_for_exe_detects_supported_layouts() {
|
||||
assert_eq!(
|
||||
homebrew_prefix_for_exe(Path::new("/opt/homebrew/bin/zeroclaw")),
|
||||
Some("/opt/homebrew")
|
||||
);
|
||||
assert_eq!(
|
||||
homebrew_prefix_for_exe(Path::new(
|
||||
"/opt/homebrew/Cellar/zeroclaw/0.5.0/bin/zeroclaw",
|
||||
)),
|
||||
Some("/opt/homebrew")
|
||||
);
|
||||
assert_eq!(
|
||||
homebrew_prefix_for_exe(Path::new("/usr/local/bin/zeroclaw")),
|
||||
Some("/usr/local")
|
||||
);
|
||||
assert_eq!(homebrew_prefix_for_exe(Path::new("/tmp/zeroclaw")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_setup_homebrew_service_note_mentions_service_workspace() {
|
||||
let note = quick_setup_homebrew_service_note(
|
||||
Path::new("/Users/alix/.zeroclaw/config.toml"),
|
||||
Path::new("/Users/alix/.zeroclaw/workspace"),
|
||||
Path::new("/opt/homebrew/bin/zeroclaw"),
|
||||
)
|
||||
.expect("homebrew installs should emit a service workspace note");
|
||||
|
||||
assert!(note.contains("/opt/homebrew/var/zeroclaw/workspace"));
|
||||
assert!(note.contains("/opt/homebrew/var/zeroclaw/config.toml"));
|
||||
assert!(note.contains("/Users/alix/.zeroclaw/config.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_setup_homebrew_service_note_skips_matching_service_layout() {
|
||||
let service_config = Path::new("/opt/homebrew/var/zeroclaw/config.toml");
|
||||
let service_workspace = Path::new("/opt/homebrew/var/zeroclaw/workspace");
|
||||
|
||||
assert!(quick_setup_homebrew_service_note(
|
||||
service_config,
|
||||
service_workspace,
|
||||
Path::new("/opt/homebrew/bin/zeroclaw"),
|
||||
)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
// ── scaffold_workspace: basic file creation ─────────────────
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! 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),
|
||||
|
||||
#[error("plugin execution failed: {0}")]
|
||||
ExecutionFailed(String),
|
||||
|
||||
#[error("permission denied: plugin '{plugin}' requires '{permission}'")]
|
||||
PermissionDenied { plugin: String, permission: String },
|
||||
|
||||
#[error("plugin '{0}' is already loaded")]
|
||||
AlreadyLoaded(String),
|
||||
|
||||
#[error("plugin capability not supported: {0}")]
|
||||
UnsupportedCapability(String),
|
||||
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("TOML parse error: {0}")]
|
||||
TomlParse(#[from] toml::de::Error),
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Plugin host: discovery, loading, lifecycle management.
|
||||
|
||||
use super::error::PluginError;
|
||||
use super::{PluginCapability, PluginInfo, PluginManifest};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Manages the lifecycle of WASM plugins.
|
||||
pub struct PluginHost {
|
||||
plugins_dir: PathBuf,
|
||||
loaded: HashMap<String, LoadedPlugin>,
|
||||
}
|
||||
|
||||
struct LoadedPlugin {
|
||||
manifest: PluginManifest,
|
||||
wasm_path: PathBuf,
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
/// Create a new plugin host with the given plugins directory.
|
||||
pub fn new(workspace_dir: &Path) -> Result<Self, PluginError> {
|
||||
let plugins_dir = workspace_dir.join("plugins");
|
||||
if !plugins_dir.exists() {
|
||||
std::fs::create_dir_all(&plugins_dir)?;
|
||||
}
|
||||
|
||||
let mut host = Self {
|
||||
plugins_dir,
|
||||
loaded: HashMap::new(),
|
||||
};
|
||||
|
||||
host.discover()?;
|
||||
Ok(host)
|
||||
}
|
||||
|
||||
/// Discover plugins in the plugins directory.
|
||||
fn discover(&mut self) -> Result<(), PluginError> {
|
||||
if !self.plugins_dir.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let entries = std::fs::read_dir(&self.plugins_dir)?;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
let manifest_path = path.join("manifest.toml");
|
||||
if manifest_path.exists() {
|
||||
if let Ok(manifest) = self.load_manifest(&manifest_path) {
|
||||
let wasm_path = path.join(&manifest.wasm_path);
|
||||
self.loaded.insert(
|
||||
manifest.name.clone(),
|
||||
LoadedPlugin {
|
||||
manifest,
|
||||
wasm_path,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_manifest(&self, path: &Path) -> Result<PluginManifest, PluginError> {
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let manifest: PluginManifest = toml::from_str(&content)?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// List all discovered plugins.
|
||||
pub fn list_plugins(&self) -> Vec<PluginInfo> {
|
||||
self.loaded
|
||||
.values()
|
||||
.map(|p| PluginInfo {
|
||||
name: p.manifest.name.clone(),
|
||||
version: p.manifest.version.clone(),
|
||||
description: p.manifest.description.clone(),
|
||||
capabilities: p.manifest.capabilities.clone(),
|
||||
permissions: p.manifest.permissions.clone(),
|
||||
wasm_path: p.wasm_path.clone(),
|
||||
loaded: p.wasm_path.exists(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Get info about a specific plugin.
|
||||
pub fn get_plugin(&self, name: &str) -> Option<PluginInfo> {
|
||||
self.loaded.get(name).map(|p| PluginInfo {
|
||||
name: p.manifest.name.clone(),
|
||||
version: p.manifest.version.clone(),
|
||||
description: p.manifest.description.clone(),
|
||||
capabilities: p.manifest.capabilities.clone(),
|
||||
permissions: p.manifest.permissions.clone(),
|
||||
wasm_path: p.wasm_path.clone(),
|
||||
loaded: p.wasm_path.exists(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Install a plugin from a directory path.
|
||||
pub fn install(&mut self, source: &str) -> Result<(), PluginError> {
|
||||
let source_path = PathBuf::from(source);
|
||||
let manifest_path = if source_path.is_dir() {
|
||||
source_path.join("manifest.toml")
|
||||
} else {
|
||||
source_path.clone()
|
||||
};
|
||||
|
||||
if !manifest_path.exists() {
|
||||
return Err(PluginError::NotFound(format!(
|
||||
"manifest.toml not found at {}",
|
||||
manifest_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
let manifest = self.load_manifest(&manifest_path)?;
|
||||
let source_dir = manifest_path
|
||||
.parent()
|
||||
.ok_or_else(|| PluginError::InvalidManifest("no parent directory".into()))?;
|
||||
|
||||
let wasm_source = source_dir.join(&manifest.wasm_path);
|
||||
if !wasm_source.exists() {
|
||||
return Err(PluginError::NotFound(format!(
|
||||
"WASM file not found: {}",
|
||||
wasm_source.display()
|
||||
)));
|
||||
}
|
||||
|
||||
if self.loaded.contains_key(&manifest.name) {
|
||||
return Err(PluginError::AlreadyLoaded(manifest.name));
|
||||
}
|
||||
|
||||
// Copy plugin to plugins directory
|
||||
let dest_dir = self.plugins_dir.join(&manifest.name);
|
||||
std::fs::create_dir_all(&dest_dir)?;
|
||||
|
||||
// Copy manifest
|
||||
std::fs::copy(&manifest_path, dest_dir.join("manifest.toml"))?;
|
||||
|
||||
// Copy WASM file
|
||||
let wasm_dest = dest_dir.join(&manifest.wasm_path);
|
||||
if let Some(parent) = wasm_dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::copy(&wasm_source, &wasm_dest)?;
|
||||
|
||||
self.loaded.insert(
|
||||
manifest.name.clone(),
|
||||
LoadedPlugin {
|
||||
manifest,
|
||||
wasm_path: wasm_dest,
|
||||
},
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a plugin by name.
|
||||
pub fn remove(&mut self, name: &str) -> Result<(), PluginError> {
|
||||
if self.loaded.remove(name).is_none() {
|
||||
return Err(PluginError::NotFound(name.to_string()));
|
||||
}
|
||||
|
||||
let plugin_dir = self.plugins_dir.join(name);
|
||||
if plugin_dir.exists() {
|
||||
std::fs::remove_dir_all(plugin_dir)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get tool-capable plugins.
|
||||
pub fn tool_plugins(&self) -> Vec<&PluginManifest> {
|
||||
self.loaded
|
||||
.values()
|
||||
.filter(|p| p.manifest.capabilities.contains(&PluginCapability::Tool))
|
||||
.map(|p| &p.manifest)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Get channel-capable plugins.
|
||||
pub fn channel_plugins(&self) -> Vec<&PluginManifest> {
|
||||
self.loaded
|
||||
.values()
|
||||
.filter(|p| p.manifest.capabilities.contains(&PluginCapability::Channel))
|
||||
.map(|p| &p.manifest)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns the plugins directory path.
|
||||
pub fn plugins_dir(&self) -> &Path {
|
||||
&self.plugins_dir
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_empty_plugin_dir() {
|
||||
let dir = tempdir().unwrap();
|
||||
let host = PluginHost::new(dir.path()).unwrap();
|
||||
assert!(host.list_plugins().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_discover_with_manifest() {
|
||||
let dir = tempdir().unwrap();
|
||||
let plugin_dir = dir.path().join("plugins").join("test-plugin");
|
||||
std::fs::create_dir_all(&plugin_dir).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
plugin_dir.join("manifest.toml"),
|
||||
r#"
|
||||
name = "test-plugin"
|
||||
version = "0.1.0"
|
||||
description = "A test plugin"
|
||||
wasm_path = "plugin.wasm"
|
||||
capabilities = ["tool"]
|
||||
permissions = []
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let host = PluginHost::new(dir.path()).unwrap();
|
||||
let plugins = host.list_plugins();
|
||||
assert_eq!(plugins.len(), 1);
|
||||
assert_eq!(plugins[0].name, "test-plugin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tool_plugins_filter() {
|
||||
let dir = tempdir().unwrap();
|
||||
let plugins_base = dir.path().join("plugins");
|
||||
|
||||
// Tool plugin
|
||||
let tool_dir = plugins_base.join("my-tool");
|
||||
std::fs::create_dir_all(&tool_dir).unwrap();
|
||||
std::fs::write(
|
||||
tool_dir.join("manifest.toml"),
|
||||
r#"
|
||||
name = "my-tool"
|
||||
version = "0.1.0"
|
||||
wasm_path = "tool.wasm"
|
||||
capabilities = ["tool"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Channel plugin
|
||||
let chan_dir = plugins_base.join("my-channel");
|
||||
std::fs::create_dir_all(&chan_dir).unwrap();
|
||||
std::fs::write(
|
||||
chan_dir.join("manifest.toml"),
|
||||
r#"
|
||||
name = "my-channel"
|
||||
version = "0.1.0"
|
||||
wasm_path = "channel.wasm"
|
||||
capabilities = ["channel"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let host = PluginHost::new(dir.path()).unwrap();
|
||||
assert_eq!(host.list_plugins().len(), 2);
|
||||
assert_eq!(host.tool_plugins().len(), 1);
|
||||
assert_eq!(host.channel_plugins().len(), 1);
|
||||
assert_eq!(host.tool_plugins()[0].name, "my-tool");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_plugin() {
|
||||
let dir = tempdir().unwrap();
|
||||
let plugin_dir = dir.path().join("plugins").join("lookup-test");
|
||||
std::fs::create_dir_all(&plugin_dir).unwrap();
|
||||
std::fs::write(
|
||||
plugin_dir.join("manifest.toml"),
|
||||
r#"
|
||||
name = "lookup-test"
|
||||
version = "1.0.0"
|
||||
description = "Lookup test"
|
||||
wasm_path = "plugin.wasm"
|
||||
capabilities = ["tool"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let host = PluginHost::new(dir.path()).unwrap();
|
||||
assert!(host.get_plugin("lookup-test").is_some());
|
||||
assert!(host.get_plugin("nonexistent").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_plugin() {
|
||||
let dir = tempdir().unwrap();
|
||||
let plugin_dir = dir.path().join("plugins").join("removable");
|
||||
std::fs::create_dir_all(&plugin_dir).unwrap();
|
||||
std::fs::write(
|
||||
plugin_dir.join("manifest.toml"),
|
||||
r#"
|
||||
name = "removable"
|
||||
version = "0.1.0"
|
||||
wasm_path = "plugin.wasm"
|
||||
capabilities = ["tool"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut host = PluginHost::new(dir.path()).unwrap();
|
||||
assert_eq!(host.list_plugins().len(), 1);
|
||||
|
||||
host.remove("removable").unwrap();
|
||||
assert!(host.list_plugins().is_empty());
|
||||
assert!(!plugin_dir.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_nonexistent_returns_error() {
|
||||
let dir = tempdir().unwrap();
|
||||
let mut host = PluginHost::new(dir.path()).unwrap();
|
||||
assert!(host.remove("ghost").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! 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 wasm_channel;
|
||||
pub mod wasm_tool;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A plugin's declared manifest (loaded from manifest.toml alongside the .wasm).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PluginManifest {
|
||||
/// Plugin name (unique identifier)
|
||||
pub name: String,
|
||||
/// Plugin version
|
||||
pub version: String,
|
||||
/// Human-readable description
|
||||
pub description: Option<String>,
|
||||
/// Author name or organization
|
||||
pub author: Option<String>,
|
||||
/// Path to the .wasm file (relative to manifest)
|
||||
pub wasm_path: String,
|
||||
/// Capabilities this plugin provides
|
||||
pub capabilities: Vec<PluginCapability>,
|
||||
/// Permissions this plugin requests
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<PluginPermission>,
|
||||
}
|
||||
|
||||
/// What a plugin can do.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PluginCapability {
|
||||
/// Provides one or more tools
|
||||
Tool,
|
||||
/// Provides a channel implementation
|
||||
Channel,
|
||||
/// Provides a memory backend
|
||||
Memory,
|
||||
/// Provides an observer/metrics backend
|
||||
Observer,
|
||||
}
|
||||
|
||||
/// Permissions a plugin may request.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PluginPermission {
|
||||
/// Can make HTTP requests
|
||||
HttpClient,
|
||||
/// Can read from the filesystem (within sandbox)
|
||||
FileRead,
|
||||
/// Can write to the filesystem (within sandbox)
|
||||
FileWrite,
|
||||
/// Can access environment variables
|
||||
EnvRead,
|
||||
/// Can read agent memory
|
||||
MemoryRead,
|
||||
/// Can write agent memory
|
||||
MemoryWrite,
|
||||
}
|
||||
|
||||
/// Information about a loaded plugin.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PluginInfo {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: Option<String>,
|
||||
pub capabilities: Vec<PluginCapability>,
|
||||
pub permissions: Vec<PluginPermission>,
|
||||
pub wasm_path: PathBuf,
|
||||
pub loaded: bool,
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Bridge between WASM plugins and the Channel trait.
|
||||
|
||||
use crate::channels::traits::{Channel, ChannelMessage, SendMessage};
|
||||
use async_trait::async_trait;
|
||||
|
||||
/// A channel backed by a WASM plugin.
|
||||
pub struct WasmChannel {
|
||||
name: String,
|
||||
plugin_name: String,
|
||||
}
|
||||
|
||||
impl WasmChannel {
|
||||
pub fn new(name: String, plugin_name: String) -> Self {
|
||||
Self { name, plugin_name }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Channel for WasmChannel {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
async fn send(&self, message: &SendMessage) -> anyhow::Result<()> {
|
||||
// TODO: Wire to WASM plugin send function
|
||||
tracing::warn!(
|
||||
"WasmChannel '{}' (plugin: {}) send not yet connected: {}",
|
||||
self.name,
|
||||
self.plugin_name,
|
||||
message.content
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn listen(&self, _tx: tokio::sync::mpsc::Sender<ChannelMessage>) -> anyhow::Result<()> {
|
||||
// TODO: Wire to WASM plugin receive/listen function
|
||||
tracing::warn!(
|
||||
"WasmChannel '{}' (plugin: {}) listen not yet connected",
|
||||
self.name,
|
||||
self.plugin_name,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Bridge between WASM plugins and the Tool trait.
|
||||
|
||||
use crate::tools::traits::{Tool, ToolResult};
|
||||
use async_trait::async_trait;
|
||||
use serde_json::Value;
|
||||
|
||||
/// A tool backed by a WASM plugin function.
|
||||
pub struct WasmTool {
|
||||
name: String,
|
||||
description: String,
|
||||
plugin_name: String,
|
||||
function_name: String,
|
||||
parameters_schema: Value,
|
||||
}
|
||||
|
||||
impl WasmTool {
|
||||
pub fn new(
|
||||
name: String,
|
||||
description: String,
|
||||
plugin_name: String,
|
||||
function_name: String,
|
||||
parameters_schema: Value,
|
||||
) -> Self {
|
||||
Self {
|
||||
name,
|
||||
description,
|
||||
plugin_name,
|
||||
function_name,
|
||||
parameters_schema,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for WasmTool {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn description(&self) -> &str {
|
||||
&self.description
|
||||
}
|
||||
|
||||
fn parameters_schema(&self) -> Value {
|
||||
self.parameters_schema.clone()
|
||||
}
|
||||
|
||||
async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
|
||||
// TODO: Call into Extism plugin runtime
|
||||
// For now, return a placeholder indicating the plugin system is available
|
||||
// but not yet wired to actual WASM execution.
|
||||
Ok(ToolResult {
|
||||
success: false,
|
||||
output: format!(
|
||||
"[plugin:{}/{}] WASM execution not yet connected. Args: {}",
|
||||
self.plugin_name,
|
||||
self.function_name,
|
||||
serde_json::to_string(&args).unwrap_or_default()
|
||||
),
|
||||
error: Some("WASM execution bridge not yet implemented".into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
+50
-41
@@ -211,9 +211,9 @@ impl AnthropicProvider {
|
||||
text.len() > 3072
|
||||
}
|
||||
|
||||
/// Cache conversations with more than 4 messages (excluding system)
|
||||
/// Cache conversations with more than 1 non-system message (i.e. after first exchange)
|
||||
fn should_cache_conversation(messages: &[ChatMessage]) -> bool {
|
||||
messages.iter().filter(|m| m.role != "system").count() > 4
|
||||
messages.iter().filter(|m| m.role != "system").count() > 1
|
||||
}
|
||||
|
||||
/// Apply cache control to the last message content block
|
||||
@@ -447,17 +447,13 @@ impl AnthropicProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Convert system text to SystemPrompt with cache control if large
|
||||
// Always use Blocks format with cache_control for system prompts
|
||||
let system_prompt = system_text.map(|text| {
|
||||
if Self::should_cache_system(&text) {
|
||||
SystemPrompt::Blocks(vec![SystemBlock {
|
||||
block_type: "text".to_string(),
|
||||
text,
|
||||
cache_control: Some(CacheControl::ephemeral()),
|
||||
}])
|
||||
} else {
|
||||
SystemPrompt::String(text)
|
||||
}
|
||||
SystemPrompt::Blocks(vec![SystemBlock {
|
||||
block_type: "text".to_string(),
|
||||
text,
|
||||
cache_control: Some(CacheControl::ephemeral()),
|
||||
}])
|
||||
});
|
||||
|
||||
(system_prompt, native_messages)
|
||||
@@ -1063,12 +1059,8 @@ mod tests {
|
||||
role: "user".to_string(),
|
||||
content: "Hello".to_string(),
|
||||
},
|
||||
ChatMessage {
|
||||
role: "assistant".to_string(),
|
||||
content: "Hi".to_string(),
|
||||
},
|
||||
];
|
||||
// Only 2 non-system messages
|
||||
// Only 1 non-system message — should not cache
|
||||
assert!(!AnthropicProvider::should_cache_conversation(&messages));
|
||||
}
|
||||
|
||||
@@ -1078,8 +1070,8 @@ mod tests {
|
||||
role: "system".to_string(),
|
||||
content: "System prompt".to_string(),
|
||||
}];
|
||||
// Add 5 non-system messages
|
||||
for i in 0..5 {
|
||||
// Add 3 non-system messages
|
||||
for i in 0..3 {
|
||||
messages.push(ChatMessage {
|
||||
role: if i % 2 == 0 { "user" } else { "assistant" }.to_string(),
|
||||
content: format!("Message {i}"),
|
||||
@@ -1090,21 +1082,24 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_cache_conversation_boundary() {
|
||||
let mut messages = vec![];
|
||||
// Add exactly 4 non-system messages
|
||||
for i in 0..4 {
|
||||
messages.push(ChatMessage {
|
||||
role: if i % 2 == 0 { "user" } else { "assistant" }.to_string(),
|
||||
content: format!("Message {i}"),
|
||||
});
|
||||
}
|
||||
let messages = vec![ChatMessage {
|
||||
role: "user".to_string(),
|
||||
content: "Hello".to_string(),
|
||||
}];
|
||||
// Exactly 1 non-system message — should not cache
|
||||
assert!(!AnthropicProvider::should_cache_conversation(&messages));
|
||||
|
||||
// Add one more to cross boundary
|
||||
messages.push(ChatMessage {
|
||||
role: "user".to_string(),
|
||||
content: "One more".to_string(),
|
||||
});
|
||||
// Add one more to cross boundary (>1)
|
||||
let messages = vec![
|
||||
ChatMessage {
|
||||
role: "user".to_string(),
|
||||
content: "Hello".to_string(),
|
||||
},
|
||||
ChatMessage {
|
||||
role: "assistant".to_string(),
|
||||
content: "Hi".to_string(),
|
||||
},
|
||||
];
|
||||
assert!(AnthropicProvider::should_cache_conversation(&messages));
|
||||
}
|
||||
|
||||
@@ -1217,7 +1212,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_messages_small_system_prompt() {
|
||||
fn convert_messages_small_system_prompt_uses_blocks_with_cache() {
|
||||
let messages = vec![ChatMessage {
|
||||
role: "system".to_string(),
|
||||
content: "Short system prompt".to_string(),
|
||||
@@ -1226,10 +1221,17 @@ mod tests {
|
||||
let (system_prompt, _) = AnthropicProvider::convert_messages(&messages);
|
||||
|
||||
match system_prompt.unwrap() {
|
||||
SystemPrompt::String(s) => {
|
||||
assert_eq!(s, "Short system prompt");
|
||||
SystemPrompt::Blocks(blocks) => {
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].text, "Short system prompt");
|
||||
assert!(
|
||||
blocks[0].cache_control.is_some(),
|
||||
"Small system prompts should have cache_control"
|
||||
);
|
||||
}
|
||||
SystemPrompt::String(_) => {
|
||||
panic!("Expected Blocks variant with cache_control for small prompt")
|
||||
}
|
||||
SystemPrompt::Blocks(_) => panic!("Expected String variant for small prompt"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1254,12 +1256,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backward_compatibility_native_chat_request() {
|
||||
// Test that requests without cache_control serialize identically to old format
|
||||
fn native_chat_request_with_blocks_system() {
|
||||
// System prompts now always use Blocks format with cache_control
|
||||
let req = NativeChatRequest {
|
||||
model: "claude-3-opus".to_string(),
|
||||
max_tokens: 4096,
|
||||
system: Some(SystemPrompt::String("System".to_string())),
|
||||
system: Some(SystemPrompt::Blocks(vec![SystemBlock {
|
||||
block_type: "text".to_string(),
|
||||
text: "System".to_string(),
|
||||
cache_control: Some(CacheControl::ephemeral()),
|
||||
}])),
|
||||
messages: vec![NativeMessage {
|
||||
role: "user".to_string(),
|
||||
content: vec![NativeContentOut::Text {
|
||||
@@ -1272,8 +1278,11 @@ mod tests {
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&req).unwrap();
|
||||
assert!(!json.contains("cache_control"));
|
||||
assert!(json.contains(r#""system":"System""#));
|
||||
assert!(json.contains("System"));
|
||||
assert!(
|
||||
json.contains(r#""cache_control":{"type":"ephemeral"}"#),
|
||||
"System prompt should include cache_control"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -17,9 +17,6 @@
|
||||
//!
|
||||
//! # Limitations
|
||||
//!
|
||||
//! - **Conversation history**: Only the system prompt (if present) and the last
|
||||
//! user message are forwarded. Full multi-turn history is not preserved because
|
||||
//! the CLI accepts a single prompt per invocation.
|
||||
//! - **System prompt**: The system prompt is prepended to the user message with a
|
||||
//! blank-line separator, as the CLI does not provide a dedicated system-prompt flag.
|
||||
//! - **Temperature**: The CLI does not expose a temperature parameter.
|
||||
@@ -34,7 +31,7 @@
|
||||
//!
|
||||
//! - `CLAUDE_CODE_PATH` — override the path to the `claude` binary (default: `"claude"`)
|
||||
|
||||
use crate::providers::traits::{ChatRequest, ChatResponse, Provider, TokenUsage};
|
||||
use crate::providers::traits::{ChatMessage, ChatRequest, ChatResponse, Provider, TokenUsage};
|
||||
use async_trait::async_trait;
|
||||
use std::path::PathBuf;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
@@ -212,6 +209,54 @@ impl Provider for ClaudeCodeProvider {
|
||||
self.invoke_cli(&full_message, model).await
|
||||
}
|
||||
|
||||
async fn chat_with_history(
|
||||
&self,
|
||||
messages: &[ChatMessage],
|
||||
model: &str,
|
||||
temperature: f64,
|
||||
) -> anyhow::Result<String> {
|
||||
Self::validate_temperature(temperature)?;
|
||||
|
||||
// Separate system prompt from conversation messages.
|
||||
let system = messages
|
||||
.iter()
|
||||
.find(|m| m.role == "system")
|
||||
.map(|m| m.content.as_str());
|
||||
|
||||
// Build conversation turns (skip system messages).
|
||||
let turns: Vec<&ChatMessage> = messages.iter().filter(|m| m.role != "system").collect();
|
||||
|
||||
// If there's only one user message, use the simple path.
|
||||
if turns.len() <= 1 {
|
||||
let last_user = turns.first().map(|m| m.content.as_str()).unwrap_or("");
|
||||
let full_message = match system {
|
||||
Some(s) if !s.is_empty() => format!("{s}\n\n{last_user}"),
|
||||
_ => last_user.to_string(),
|
||||
};
|
||||
return self.invoke_cli(&full_message, model).await;
|
||||
}
|
||||
|
||||
// Format multi-turn conversation into a single prompt.
|
||||
let mut parts = Vec::new();
|
||||
if let Some(s) = system {
|
||||
if !s.is_empty() {
|
||||
parts.push(format!("[system]\n{s}"));
|
||||
}
|
||||
}
|
||||
for msg in &turns {
|
||||
let label = match msg.role.as_str() {
|
||||
"user" => "[user]",
|
||||
"assistant" => "[assistant]",
|
||||
other => other,
|
||||
};
|
||||
parts.push(format!("{label}\n{}", msg.content));
|
||||
}
|
||||
parts.push("[assistant]".to_string());
|
||||
|
||||
let full_message = parts.join("\n\n");
|
||||
self.invoke_cli(&full_message, model).await
|
||||
}
|
||||
|
||||
async fn chat(
|
||||
&self,
|
||||
request: ChatRequest<'_>,
|
||||
@@ -327,4 +372,105 @@ mod tests {
|
||||
"unexpected error message: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Helper: create a provider that uses a shell script echoing stdin back.
|
||||
/// The script ignores CLI flags (`--print`, `--model`, `-`) and just cats stdin.
|
||||
///
|
||||
/// Uses `OnceLock` to write the script file exactly once, avoiding
|
||||
/// "Text file busy" (ETXTBSY) races when parallel tests try to
|
||||
/// overwrite a script that another test is currently executing.
|
||||
fn echo_provider() -> ClaudeCodeProvider {
|
||||
use std::sync::OnceLock;
|
||||
|
||||
static SCRIPT_PATH: OnceLock<PathBuf> = OnceLock::new();
|
||||
let script = SCRIPT_PATH.get_or_init(|| {
|
||||
use std::io::Write;
|
||||
let dir = std::env::temp_dir().join("zeroclaw_test_claude_code");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join(format!("fake_claude_{}.sh", std::process::id()));
|
||||
let mut f = std::fs::File::create(&path).unwrap();
|
||||
writeln!(f, "#!/bin/sh\ncat /dev/stdin").unwrap();
|
||||
drop(f);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
path
|
||||
});
|
||||
ClaudeCodeProvider {
|
||||
binary_path: script.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_with_history_single_user_message() {
|
||||
let provider = echo_provider();
|
||||
let messages = vec![ChatMessage::user("hello")];
|
||||
let result = provider
|
||||
.chat_with_history(&messages, "default", 1.0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result, "hello");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_with_history_single_user_with_system() {
|
||||
let provider = echo_provider();
|
||||
let messages = vec![
|
||||
ChatMessage::system("You are helpful."),
|
||||
ChatMessage::user("hello"),
|
||||
];
|
||||
let result = provider
|
||||
.chat_with_history(&messages, "default", 1.0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result, "You are helpful.\n\nhello");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_with_history_multi_turn_includes_all_messages() {
|
||||
let provider = echo_provider();
|
||||
let messages = vec![
|
||||
ChatMessage::system("Be concise."),
|
||||
ChatMessage::user("What is 2+2?"),
|
||||
ChatMessage::assistant("4"),
|
||||
ChatMessage::user("And 3+3?"),
|
||||
];
|
||||
let result = provider
|
||||
.chat_with_history(&messages, "default", 1.0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.contains("[system]\nBe concise."));
|
||||
assert!(result.contains("[user]\nWhat is 2+2?"));
|
||||
assert!(result.contains("[assistant]\n4"));
|
||||
assert!(result.contains("[user]\nAnd 3+3?"));
|
||||
assert!(result.ends_with("[assistant]"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_with_history_multi_turn_without_system() {
|
||||
let provider = echo_provider();
|
||||
let messages = vec![
|
||||
ChatMessage::user("hi"),
|
||||
ChatMessage::assistant("hello"),
|
||||
ChatMessage::user("bye"),
|
||||
];
|
||||
let result = provider
|
||||
.chat_with_history(&messages, "default", 1.0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!result.contains("[system]"));
|
||||
assert!(result.contains("[user]\nhi"));
|
||||
assert!(result.contains("[assistant]\nhello"));
|
||||
assert!(result.contains("[user]\nbye"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_with_history_rejects_bad_temperature() {
|
||||
let provider = echo_provider();
|
||||
let messages = vec![ChatMessage::user("test")];
|
||||
let result = provider.chat_with_history(&messages, "default", 0.5).await;
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+25
-2
@@ -708,6 +708,22 @@ impl Default for ProviderRuntimeOptions {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn provider_runtime_options_from_config(
|
||||
config: &crate::config::Config,
|
||||
) -> ProviderRuntimeOptions {
|
||||
ProviderRuntimeOptions {
|
||||
auth_profile_override: None,
|
||||
provider_api_url: config.api_url.clone(),
|
||||
zeroclaw_dir: config.config_path.parent().map(PathBuf::from),
|
||||
secrets_encrypt: config.secrets.encrypt,
|
||||
reasoning_enabled: config.runtime.reasoning_enabled,
|
||||
reasoning_effort: config.runtime.reasoning_effort.clone(),
|
||||
provider_timeout_secs: Some(config.provider_timeout_secs),
|
||||
extra_headers: config.extra_headers.clone(),
|
||||
api_path: config.api_path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_secret_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':')
|
||||
}
|
||||
@@ -1103,7 +1119,13 @@ fn create_provider_with_url_and_options(
|
||||
)?))
|
||||
}
|
||||
// ── Primary providers (custom implementations) ───────
|
||||
"openrouter" => Ok(Box::new(openrouter::OpenRouterProvider::new(key))),
|
||||
"openrouter" => {
|
||||
let mut p = openrouter::OpenRouterProvider::new(key);
|
||||
if let Some(t) = options.provider_timeout_secs {
|
||||
p = p.with_timeout_secs(t);
|
||||
}
|
||||
Ok(Box::new(p))
|
||||
}
|
||||
"anthropic" => Ok(Box::new(anthropic::AnthropicProvider::new(key))),
|
||||
"openai" => Ok(Box::new(openai::OpenAiProvider::with_base_url(api_url, key))),
|
||||
// Ollama uses api_url for custom base URL (e.g. remote Ollama instance)
|
||||
@@ -1304,11 +1326,12 @@ fn create_provider_with_url_and_options(
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or("llama.cpp");
|
||||
Ok(compat(OpenAiCompatibleProvider::new(
|
||||
Ok(compat(OpenAiCompatibleProvider::new_with_vision(
|
||||
"llama.cpp",
|
||||
base_url,
|
||||
Some(llama_cpp_key),
|
||||
AuthStyle::Bearer,
|
||||
true,
|
||||
)))
|
||||
}
|
||||
"sglang" => {
|
||||
|
||||
@@ -4,12 +4,14 @@ use crate::providers::traits::{
|
||||
Provider, ProviderCapabilities, TokenUsage, ToolCall as ProviderToolCall,
|
||||
};
|
||||
use crate::tools::ToolSpec;
|
||||
use anyhow::Context as _;
|
||||
use async_trait::async_trait;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub struct OpenRouterProvider {
|
||||
credential: Option<String>,
|
||||
timeout_secs: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -149,9 +151,16 @@ impl OpenRouterProvider {
|
||||
pub fn new(credential: Option<&str>) -> Self {
|
||||
Self {
|
||||
credential: credential.map(ToString::to_string),
|
||||
timeout_secs: 120,
|
||||
}
|
||||
}
|
||||
|
||||
/// Override the HTTP request timeout for LLM API calls.
|
||||
pub fn with_timeout_secs(mut self, secs: u64) -> Self {
|
||||
self.timeout_secs = secs;
|
||||
self
|
||||
}
|
||||
|
||||
fn convert_tools(tools: Option<&[ToolSpec]>) -> Option<Vec<NativeToolSpec>> {
|
||||
let items = tools?;
|
||||
if items.is_empty() {
|
||||
@@ -296,7 +305,11 @@ impl OpenRouterProvider {
|
||||
}
|
||||
|
||||
fn http_client(&self) -> Client {
|
||||
crate::config::build_runtime_proxy_client_with_timeouts("provider.openrouter", 120, 10)
|
||||
crate::config::build_runtime_proxy_client_with_timeouts(
|
||||
"provider.openrouter",
|
||||
self.timeout_secs,
|
||||
10,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,7 +381,13 @@ impl Provider for OpenRouterProvider {
|
||||
return Err(super::api_error("OpenRouter", response).await);
|
||||
}
|
||||
|
||||
let chat_response: ApiChatResponse = response.json().await?;
|
||||
let text = response.text().await?;
|
||||
let chat_response: ApiChatResponse = serde_json::from_str(&text).with_context(|| {
|
||||
format!(
|
||||
"OpenRouter: failed to decode response body: {}",
|
||||
&text[..text.len().min(500)]
|
||||
)
|
||||
})?;
|
||||
|
||||
chat_response
|
||||
.choices
|
||||
@@ -415,7 +434,13 @@ impl Provider for OpenRouterProvider {
|
||||
return Err(super::api_error("OpenRouter", response).await);
|
||||
}
|
||||
|
||||
let chat_response: ApiChatResponse = response.json().await?;
|
||||
let text = response.text().await?;
|
||||
let chat_response: ApiChatResponse = serde_json::from_str(&text).with_context(|| {
|
||||
format!(
|
||||
"OpenRouter: failed to decode response body: {}",
|
||||
&text[..text.len().min(500)]
|
||||
)
|
||||
})?;
|
||||
|
||||
chat_response
|
||||
.choices
|
||||
@@ -460,7 +485,14 @@ impl Provider for OpenRouterProvider {
|
||||
return Err(super::api_error("OpenRouter", response).await);
|
||||
}
|
||||
|
||||
let native_response: NativeChatResponse = response.json().await?;
|
||||
let text = response.text().await?;
|
||||
let native_response: NativeChatResponse =
|
||||
serde_json::from_str(&text).with_context(|| {
|
||||
format!(
|
||||
"OpenRouter: failed to decode response body: {}",
|
||||
&text[..text.len().min(500)]
|
||||
)
|
||||
})?;
|
||||
let usage = native_response.usage.map(|u| TokenUsage {
|
||||
input_tokens: u.prompt_tokens,
|
||||
output_tokens: u.completion_tokens,
|
||||
@@ -552,7 +584,14 @@ impl Provider for OpenRouterProvider {
|
||||
return Err(super::api_error("OpenRouter", response).await);
|
||||
}
|
||||
|
||||
let native_response: NativeChatResponse = response.json().await?;
|
||||
let text = response.text().await?;
|
||||
let native_response: NativeChatResponse =
|
||||
serde_json::from_str(&text).with_context(|| {
|
||||
format!(
|
||||
"OpenRouter: failed to decode response body: {}",
|
||||
&text[..text.len().min(500)]
|
||||
)
|
||||
})?;
|
||||
let usage = native_response.usage.map(|u| TokenUsage {
|
||||
input_tokens: u.prompt_tokens,
|
||||
output_tokens: u.completion_tokens,
|
||||
@@ -1017,4 +1056,20 @@ mod tests {
|
||||
assert!(json.contains("reasoning_content"));
|
||||
assert!(json.contains("thinking..."));
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// timeout_secs configuration tests
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
|
||||
#[test]
|
||||
fn default_timeout_is_120() {
|
||||
let provider = OpenRouterProvider::new(Some("key"));
|
||||
assert_eq!(provider.timeout_secs, 120);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_timeout_secs_overrides_default() {
|
||||
let provider = OpenRouterProvider::new(Some("key")).with_timeout_secs(300);
|
||||
assert_eq!(provider.timeout_secs, 300);
|
||||
}
|
||||
}
|
||||
|
||||
+324
-41
@@ -16,8 +16,17 @@ use std::time::Duration;
|
||||
|
||||
/// Check if an error is non-retryable (client errors that won't resolve with retries).
|
||||
pub fn is_non_retryable(err: &anyhow::Error) -> bool {
|
||||
// Context window errors are NOT non-retryable — they can be recovered
|
||||
// by truncating conversation history, so let the retry loop handle them.
|
||||
if is_context_window_exceeded(err) {
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tool schema validation errors are NOT non-retryable — the provider's
|
||||
// built-in fallback in compatible.rs can recover by switching to
|
||||
// prompt-guided tool instructions.
|
||||
if is_tool_schema_error(err) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4xx errors are generally non-retryable (bad request, auth failure, etc.),
|
||||
@@ -71,10 +80,27 @@ pub fn is_non_retryable(err: &anyhow::Error) -> bool {
|
||||
|| msg_lower.contains("invalid"))
|
||||
}
|
||||
|
||||
/// Check if an error is a tool schema validation failure (e.g. Groq returning
|
||||
/// "tool call validation failed: attempted to call tool '...' which was not in request").
|
||||
/// These errors should NOT be classified as non-retryable because the provider's
|
||||
/// built-in fallback logic (`compatible.rs::is_native_tool_schema_unsupported`)
|
||||
/// can recover by switching to prompt-guided tool instructions.
|
||||
pub fn is_tool_schema_error(err: &anyhow::Error) -> bool {
|
||||
let lower = err.to_string().to_lowercase();
|
||||
let hints = [
|
||||
"tool call validation failed",
|
||||
"was not in request",
|
||||
"not found in tool list",
|
||||
"invalid_tool_call",
|
||||
];
|
||||
hints.iter().any(|hint| lower.contains(hint))
|
||||
}
|
||||
|
||||
fn is_context_window_exceeded(err: &anyhow::Error) -> bool {
|
||||
let lower = err.to_string().to_lowercase();
|
||||
let hints = [
|
||||
"exceeds the context window",
|
||||
"exceeds the available context size",
|
||||
"context window of this model",
|
||||
"maximum context length",
|
||||
"context length exceeded",
|
||||
@@ -197,6 +223,35 @@ fn compact_error_detail(err: &anyhow::Error) -> String {
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// Truncate conversation history by dropping the oldest non-system messages.
|
||||
/// Returns the number of messages dropped. Keeps at least the system message
|
||||
/// (if any) and the most recent user message.
|
||||
fn truncate_for_context(messages: &mut Vec<ChatMessage>) -> usize {
|
||||
// Find all non-system message indices
|
||||
let non_system: Vec<usize> = messages
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| m.role != "system")
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
|
||||
// Keep at least the last non-system message (most recent user turn)
|
||||
if non_system.len() <= 1 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Drop the oldest half of non-system messages
|
||||
let drop_count = non_system.len() / 2;
|
||||
let indices_to_remove: Vec<usize> = non_system[..drop_count].to_vec();
|
||||
|
||||
// Remove in reverse order to preserve indices
|
||||
for &idx in indices_to_remove.iter().rev() {
|
||||
messages.remove(idx);
|
||||
}
|
||||
|
||||
drop_count
|
||||
}
|
||||
|
||||
fn push_failure(
|
||||
failures: &mut Vec<String>,
|
||||
provider_name: &str,
|
||||
@@ -338,6 +393,25 @@ impl Provider for ReliableProvider {
|
||||
return Ok(resp);
|
||||
}
|
||||
Err(e) => {
|
||||
// Context window exceeded: no history to truncate
|
||||
// in chat_with_system, bail immediately.
|
||||
if is_context_window_exceeded(&e) {
|
||||
let error_detail = compact_error_detail(&e);
|
||||
push_failure(
|
||||
&mut failures,
|
||||
provider_name,
|
||||
current_model,
|
||||
attempt + 1,
|
||||
self.max_retries + 1,
|
||||
"non_retryable",
|
||||
&error_detail,
|
||||
);
|
||||
anyhow::bail!(
|
||||
"Request exceeds model context window. Attempts:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
let non_retryable_rate_limit = is_non_retryable_rate_limit(&e);
|
||||
let non_retryable = is_non_retryable(&e) || non_retryable_rate_limit;
|
||||
let rate_limited = is_rate_limited(&e);
|
||||
@@ -376,14 +450,6 @@ impl Provider for ReliableProvider {
|
||||
error = %error_detail,
|
||||
"Non-retryable error, moving on"
|
||||
);
|
||||
|
||||
if is_context_window_exceeded(&e) {
|
||||
anyhow::bail!(
|
||||
"Request exceeds model context window; retries and fallbacks were skipped. Attempts:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -435,6 +501,8 @@ impl Provider for ReliableProvider {
|
||||
) -> anyhow::Result<String> {
|
||||
let models = self.model_chain(model);
|
||||
let mut failures = Vec::new();
|
||||
let mut effective_messages = messages.to_vec();
|
||||
let mut context_truncated = false;
|
||||
|
||||
for current_model in &models {
|
||||
for (provider_name, provider) in &self.providers {
|
||||
@@ -442,22 +510,39 @@ impl Provider for ReliableProvider {
|
||||
|
||||
for attempt in 0..=self.max_retries {
|
||||
match provider
|
||||
.chat_with_history(messages, current_model, temperature)
|
||||
.chat_with_history(&effective_messages, current_model, temperature)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => {
|
||||
if attempt > 0 || *current_model != model {
|
||||
if attempt > 0 || *current_model != model || context_truncated {
|
||||
tracing::info!(
|
||||
provider = provider_name,
|
||||
model = *current_model,
|
||||
attempt,
|
||||
original_model = model,
|
||||
context_truncated,
|
||||
"Provider recovered (failover/retry)"
|
||||
);
|
||||
}
|
||||
return Ok(resp);
|
||||
}
|
||||
Err(e) => {
|
||||
// Context window exceeded: truncate history and retry
|
||||
if is_context_window_exceeded(&e) && !context_truncated {
|
||||
let dropped = truncate_for_context(&mut effective_messages);
|
||||
if dropped > 0 {
|
||||
context_truncated = true;
|
||||
tracing::warn!(
|
||||
provider = provider_name,
|
||||
model = *current_model,
|
||||
dropped,
|
||||
remaining = effective_messages.len(),
|
||||
"Context window exceeded; truncated history and retrying"
|
||||
);
|
||||
continue; // Retry with truncated messages (counts as an attempt)
|
||||
}
|
||||
}
|
||||
|
||||
let non_retryable_rate_limit = is_non_retryable_rate_limit(&e);
|
||||
let non_retryable = is_non_retryable(&e) || non_retryable_rate_limit;
|
||||
let rate_limited = is_rate_limited(&e);
|
||||
@@ -494,14 +579,6 @@ impl Provider for ReliableProvider {
|
||||
error = %error_detail,
|
||||
"Non-retryable error, moving on"
|
||||
);
|
||||
|
||||
if is_context_window_exceeded(&e) {
|
||||
anyhow::bail!(
|
||||
"Request exceeds model context window; retries and fallbacks were skipped. Attempts:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -559,6 +636,8 @@ impl Provider for ReliableProvider {
|
||||
) -> anyhow::Result<ChatResponse> {
|
||||
let models = self.model_chain(model);
|
||||
let mut failures = Vec::new();
|
||||
let mut effective_messages = messages.to_vec();
|
||||
let mut context_truncated = false;
|
||||
|
||||
for current_model in &models {
|
||||
for (provider_name, provider) in &self.providers {
|
||||
@@ -566,22 +645,39 @@ impl Provider for ReliableProvider {
|
||||
|
||||
for attempt in 0..=self.max_retries {
|
||||
match provider
|
||||
.chat_with_tools(messages, tools, current_model, temperature)
|
||||
.chat_with_tools(&effective_messages, tools, current_model, temperature)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => {
|
||||
if attempt > 0 || *current_model != model {
|
||||
if attempt > 0 || *current_model != model || context_truncated {
|
||||
tracing::info!(
|
||||
provider = provider_name,
|
||||
model = *current_model,
|
||||
attempt,
|
||||
original_model = model,
|
||||
context_truncated,
|
||||
"Provider recovered (failover/retry)"
|
||||
);
|
||||
}
|
||||
return Ok(resp);
|
||||
}
|
||||
Err(e) => {
|
||||
// Context window exceeded: truncate history and retry
|
||||
if is_context_window_exceeded(&e) && !context_truncated {
|
||||
let dropped = truncate_for_context(&mut effective_messages);
|
||||
if dropped > 0 {
|
||||
context_truncated = true;
|
||||
tracing::warn!(
|
||||
provider = provider_name,
|
||||
model = *current_model,
|
||||
dropped,
|
||||
remaining = effective_messages.len(),
|
||||
"Context window exceeded; truncated history and retrying"
|
||||
);
|
||||
continue; // Retry with truncated messages (counts as an attempt)
|
||||
}
|
||||
}
|
||||
|
||||
let non_retryable_rate_limit = is_non_retryable_rate_limit(&e);
|
||||
let non_retryable = is_non_retryable(&e) || non_retryable_rate_limit;
|
||||
let rate_limited = is_rate_limited(&e);
|
||||
@@ -618,14 +714,6 @@ impl Provider for ReliableProvider {
|
||||
error = %error_detail,
|
||||
"Non-retryable error, moving on"
|
||||
);
|
||||
|
||||
if is_context_window_exceeded(&e) {
|
||||
anyhow::bail!(
|
||||
"Request exceeds model context window; retries and fallbacks were skipped. Attempts:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -669,6 +757,8 @@ impl Provider for ReliableProvider {
|
||||
) -> anyhow::Result<ChatResponse> {
|
||||
let models = self.model_chain(model);
|
||||
let mut failures = Vec::new();
|
||||
let mut effective_messages = request.messages.to_vec();
|
||||
let mut context_truncated = false;
|
||||
|
||||
for current_model in &models {
|
||||
for (provider_name, provider) in &self.providers {
|
||||
@@ -676,23 +766,40 @@ impl Provider for ReliableProvider {
|
||||
|
||||
for attempt in 0..=self.max_retries {
|
||||
let req = ChatRequest {
|
||||
messages: request.messages,
|
||||
messages: &effective_messages,
|
||||
tools: request.tools,
|
||||
};
|
||||
match provider.chat(req, current_model, temperature).await {
|
||||
Ok(resp) => {
|
||||
if attempt > 0 || *current_model != model {
|
||||
if attempt > 0 || *current_model != model || context_truncated {
|
||||
tracing::info!(
|
||||
provider = provider_name,
|
||||
model = *current_model,
|
||||
attempt,
|
||||
original_model = model,
|
||||
context_truncated,
|
||||
"Provider recovered (failover/retry)"
|
||||
);
|
||||
}
|
||||
return Ok(resp);
|
||||
}
|
||||
Err(e) => {
|
||||
// Context window exceeded: truncate history and retry
|
||||
if is_context_window_exceeded(&e) && !context_truncated {
|
||||
let dropped = truncate_for_context(&mut effective_messages);
|
||||
if dropped > 0 {
|
||||
context_truncated = true;
|
||||
tracing::warn!(
|
||||
provider = provider_name,
|
||||
model = *current_model,
|
||||
dropped,
|
||||
remaining = effective_messages.len(),
|
||||
"Context window exceeded; truncated history and retrying"
|
||||
);
|
||||
continue; // Retry with truncated messages (counts as an attempt)
|
||||
}
|
||||
}
|
||||
|
||||
let non_retryable_rate_limit = is_non_retryable_rate_limit(&e);
|
||||
let non_retryable = is_non_retryable(&e) || non_retryable_rate_limit;
|
||||
let rate_limited = is_rate_limited(&e);
|
||||
@@ -729,14 +836,6 @@ impl Provider for ReliableProvider {
|
||||
error = %error_detail,
|
||||
"Non-retryable error, moving on"
|
||||
);
|
||||
|
||||
if is_context_window_exceeded(&e) {
|
||||
anyhow::bail!(
|
||||
"Request exceeds model context window; retries and fallbacks were skipped. Attempts:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1071,7 +1170,8 @@ mod tests {
|
||||
assert!(!is_non_retryable(&anyhow::anyhow!(
|
||||
"model overloaded, try again later"
|
||||
)));
|
||||
assert!(is_non_retryable(&anyhow::anyhow!(
|
||||
// Context window errors are now recoverable (not non-retryable)
|
||||
assert!(!is_non_retryable(&anyhow::anyhow!(
|
||||
"OpenAI Codex stream error: Your input exceeds the context window of this model."
|
||||
)));
|
||||
}
|
||||
@@ -1107,7 +1207,7 @@ mod tests {
|
||||
let msg = err.to_string();
|
||||
|
||||
assert!(msg.contains("context window"));
|
||||
assert!(msg.contains("skipped"));
|
||||
// chat_with_system has no history to truncate, so it bails immediately
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
@@ -1980,4 +2080,187 @@ mod tests {
|
||||
assert_eq!(primary_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(fallback_calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
// ── Context window truncation tests ─────────────────────────
|
||||
|
||||
#[test]
|
||||
fn context_window_error_is_not_non_retryable() {
|
||||
// Context window errors should be recoverable via truncation
|
||||
assert!(!is_non_retryable(&anyhow::anyhow!(
|
||||
"exceeds the context window"
|
||||
)));
|
||||
assert!(!is_non_retryable(&anyhow::anyhow!(
|
||||
"maximum context length exceeded"
|
||||
)));
|
||||
assert!(!is_non_retryable(&anyhow::anyhow!(
|
||||
"too many tokens in the request"
|
||||
)));
|
||||
assert!(!is_non_retryable(&anyhow::anyhow!("token limit exceeded")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_context_window_exceeded_detects_llamacpp() {
|
||||
assert!(is_context_window_exceeded(&anyhow::anyhow!(
|
||||
"request (8968 tokens) exceeds the available context size (8448 tokens), try increasing it"
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_for_context_drops_oldest_non_system() {
|
||||
let mut messages = vec![
|
||||
ChatMessage::system("sys"),
|
||||
ChatMessage::user("msg1"),
|
||||
ChatMessage::assistant("resp1"),
|
||||
ChatMessage::user("msg2"),
|
||||
ChatMessage::assistant("resp2"),
|
||||
ChatMessage::user("msg3"),
|
||||
];
|
||||
|
||||
let dropped = truncate_for_context(&mut messages);
|
||||
|
||||
// 5 non-system messages, drop oldest half = 2
|
||||
assert_eq!(dropped, 2);
|
||||
// System message preserved
|
||||
assert_eq!(messages[0].role, "system");
|
||||
// Remaining messages should be the newer ones
|
||||
assert_eq!(messages.len(), 4); // system + 3 remaining non-system
|
||||
// The last message should still be the most recent user message
|
||||
assert_eq!(messages.last().unwrap().content, "msg3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_for_context_preserves_system_and_last_message() {
|
||||
// Only one non-system message: nothing to drop
|
||||
let mut messages = vec![ChatMessage::system("sys"), ChatMessage::user("only")];
|
||||
let dropped = truncate_for_context(&mut messages);
|
||||
assert_eq!(dropped, 0);
|
||||
assert_eq!(messages.len(), 2);
|
||||
|
||||
// No system message, only one user message
|
||||
let mut messages = vec![ChatMessage::user("only")];
|
||||
let dropped = truncate_for_context(&mut messages);
|
||||
assert_eq!(dropped, 0);
|
||||
assert_eq!(messages.len(), 1);
|
||||
}
|
||||
|
||||
/// Mock that fails with context error on first N calls, then succeeds.
|
||||
/// Tracks the number of messages received on each call.
|
||||
struct ContextOverflowMock {
|
||||
calls: Arc<AtomicUsize>,
|
||||
fail_until_attempt: usize,
|
||||
message_counts: parking_lot::Mutex<Vec<usize>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Provider for ContextOverflowMock {
|
||||
async fn chat_with_system(
|
||||
&self,
|
||||
_system_prompt: Option<&str>,
|
||||
_message: &str,
|
||||
_model: &str,
|
||||
_temperature: f64,
|
||||
) -> anyhow::Result<String> {
|
||||
Ok("ok".to_string())
|
||||
}
|
||||
|
||||
async fn chat_with_history(
|
||||
&self,
|
||||
messages: &[ChatMessage],
|
||||
_model: &str,
|
||||
_temperature: f64,
|
||||
) -> anyhow::Result<String> {
|
||||
let attempt = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
self.message_counts.lock().push(messages.len());
|
||||
if attempt <= self.fail_until_attempt {
|
||||
anyhow::bail!(
|
||||
"request (8968 tokens) exceeds the available context size (8448 tokens), try increasing it"
|
||||
);
|
||||
}
|
||||
Ok("recovered after truncation".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_with_history_truncates_on_context_overflow() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mock = ContextOverflowMock {
|
||||
calls: Arc::clone(&calls),
|
||||
fail_until_attempt: 1, // fail first call, succeed after truncation
|
||||
message_counts: parking_lot::Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let provider = ReliableProvider::new(
|
||||
vec![("local".into(), Box::new(mock) as Box<dyn Provider>)],
|
||||
3,
|
||||
1,
|
||||
);
|
||||
|
||||
let messages = vec![
|
||||
ChatMessage::system("system prompt"),
|
||||
ChatMessage::user("old message 1"),
|
||||
ChatMessage::assistant("old response 1"),
|
||||
ChatMessage::user("old message 2"),
|
||||
ChatMessage::assistant("old response 2"),
|
||||
ChatMessage::user("current question"),
|
||||
];
|
||||
|
||||
let result = provider
|
||||
.chat_with_history(&messages, "local-model", 0.0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result, "recovered after truncation");
|
||||
// Should have been called twice: once with full messages, once with truncated
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
// ── Tool schema error detection tests ───────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn tool_schema_error_detects_groq_validation_failure() {
|
||||
let msg = r#"Groq API error (400 Bad Request): {"error":{"message":"tool call validation failed: attempted to call tool 'memory_recall' which was not in request"}}"#;
|
||||
let err = anyhow::anyhow!("{}", msg);
|
||||
assert!(is_tool_schema_error(&err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_schema_error_detects_not_in_request() {
|
||||
let err = anyhow::anyhow!("tool 'search' was not in request");
|
||||
assert!(is_tool_schema_error(&err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_schema_error_detects_not_found_in_tool_list() {
|
||||
let err = anyhow::anyhow!("function 'foo' not found in tool list");
|
||||
assert!(is_tool_schema_error(&err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_schema_error_detects_invalid_tool_call() {
|
||||
let err = anyhow::anyhow!("invalid_tool_call: no matching function");
|
||||
assert!(is_tool_schema_error(&err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_schema_error_ignores_unrelated_errors() {
|
||||
let err = anyhow::anyhow!("invalid api key");
|
||||
assert!(!is_tool_schema_error(&err));
|
||||
|
||||
let err = anyhow::anyhow!("model not found");
|
||||
assert!(!is_tool_schema_error(&err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_retryable_returns_false_for_tool_schema_400() {
|
||||
// A 400 error with tool schema validation text should NOT be non-retryable.
|
||||
let msg = "400 Bad Request: tool call validation failed: attempted to call tool 'x' which was not in request";
|
||||
let err = anyhow::anyhow!("{}", msg);
|
||||
assert!(!is_non_retryable(&err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_retryable_returns_true_for_other_400_errors() {
|
||||
// A regular 400 error (e.g. invalid API key) should still be non-retryable.
|
||||
let err = anyhow::anyhow!("400 Bad Request: invalid api key provided");
|
||||
assert!(is_non_retryable(&err));
|
||||
}
|
||||
}
|
||||
|
||||
+19
-2
@@ -55,7 +55,9 @@ impl PairingGuard {
|
||||
/// Create a new pairing guard.
|
||||
///
|
||||
/// If `require_pairing` is true and no tokens exist yet, a fresh
|
||||
/// pairing code is generated and returned via `pairing_code()`.
|
||||
/// pairing code is generated and printed to the terminal. Once
|
||||
/// paired, no code is generated on restart — operators can use
|
||||
/// `generate_new_pairing_code()` or the CLI to create one on demand.
|
||||
///
|
||||
/// Existing tokens are accepted in both forms:
|
||||
/// - Plaintext (`zc_...`): hashed on load for backward compatibility
|
||||
@@ -84,7 +86,7 @@ impl PairingGuard {
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-time pairing code (only set when no tokens exist yet).
|
||||
/// The one-time pairing code (generated only on first startup when no tokens exist).
|
||||
pub fn pairing_code(&self) -> Option<String> {
|
||||
self.pairing_code.lock().clone()
|
||||
}
|
||||
@@ -229,6 +231,21 @@ impl PairingGuard {
|
||||
*self.pairing_code.lock() = Some(new_code.clone());
|
||||
Some(new_code)
|
||||
}
|
||||
|
||||
/// Get the token hash for a given plaintext token (for device registry lookup).
|
||||
pub fn token_hash(token: &str) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
hex::encode(Sha256::digest(token.as_bytes()))
|
||||
}
|
||||
|
||||
/// Check if a token is paired and return its hash.
|
||||
pub fn authenticate_and_hash(&self, token: &str) -> Option<String> {
|
||||
if self.is_authenticated(token) {
|
||||
Some(Self::token_hash(token))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a client identifier: trim whitespace, map empty to `"unknown"`.
|
||||
|
||||
+61
-7
@@ -409,13 +409,43 @@ fn has_shell_shebang(path: &Path) -> bool {
|
||||
return false;
|
||||
};
|
||||
let prefix = &content[..content.len().min(128)];
|
||||
let shebang = String::from_utf8_lossy(prefix).to_ascii_lowercase();
|
||||
shebang.starts_with("#!")
|
||||
&& (shebang.contains("sh")
|
||||
|| shebang.contains("bash")
|
||||
|| shebang.contains("zsh")
|
||||
|| shebang.contains("pwsh")
|
||||
|| shebang.contains("powershell"))
|
||||
let shebang_line = String::from_utf8_lossy(prefix)
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
let Some(interpreter) = shebang_interpreter(&shebang_line) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
matches!(
|
||||
interpreter,
|
||||
"sh" | "bash" | "zsh" | "ksh" | "fish" | "pwsh" | "powershell"
|
||||
)
|
||||
}
|
||||
|
||||
fn shebang_interpreter(line: &str) -> Option<&str> {
|
||||
let shebang = line.strip_prefix("#!")?.trim();
|
||||
if shebang.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut parts = shebang.split_whitespace();
|
||||
let first = parts.next()?;
|
||||
let first_basename = Path::new(first).file_name()?.to_str()?;
|
||||
|
||||
if first_basename == "env" {
|
||||
for part in parts {
|
||||
if part.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
return Path::new(part).file_name()?.to_str();
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(first_basename)
|
||||
}
|
||||
|
||||
fn extract_markdown_links(content: &str) -> Vec<String> {
|
||||
@@ -586,6 +616,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audit_allows_python_shebang_file_when_early_text_contains_sh() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let skill_dir = dir.path().join("python-helper");
|
||||
let scripts_dir = skill_dir.join("scripts");
|
||||
std::fs::create_dir_all(&scripts_dir).unwrap();
|
||||
std::fs::write(skill_dir.join("SKILL.md"), "# Skill\n").unwrap();
|
||||
std::fs::write(
|
||||
scripts_dir.join("helper.py"),
|
||||
"#!/usr/bin/env python3\n\"\"\"Refresh report cache.\"\"\"\n\nprint(\"ok\")\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let report = audit_skill_directory(&skill_dir).unwrap();
|
||||
assert!(
|
||||
!report
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.contains("script-like files are blocked")),
|
||||
"{:#?}",
|
||||
report.findings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audit_rejects_markdown_escape_links() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,897 @@
|
||||
// Autonomous skill creation from successful multi-step task executions.
|
||||
//
|
||||
// After the agent completes a multi-step tool-call sequence, this module
|
||||
// can persist the execution as a reusable skill definition (SKILL.toml)
|
||||
// under `~/.zeroclaw/workspace/skills/<slug>/`.
|
||||
|
||||
use crate::config::SkillCreationConfig;
|
||||
use crate::memory::embeddings::EmbeddingProvider;
|
||||
use crate::memory::vector::cosine_similarity;
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A record of a single tool call executed during a task.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ToolCallRecord {
|
||||
pub name: String,
|
||||
pub args: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Creates reusable skill definitions from successful multi-step executions.
|
||||
pub struct SkillCreator {
|
||||
workspace_dir: PathBuf,
|
||||
config: SkillCreationConfig,
|
||||
}
|
||||
|
||||
impl SkillCreator {
|
||||
pub fn new(workspace_dir: PathBuf, config: SkillCreationConfig) -> Self {
|
||||
Self {
|
||||
workspace_dir,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to create a skill from a successful multi-step task execution.
|
||||
/// Returns `Ok(Some(slug))` if a skill was created, `Ok(None)` if skipped
|
||||
/// (disabled, duplicate, or insufficient tool calls).
|
||||
pub async fn create_from_execution(
|
||||
&self,
|
||||
task_description: &str,
|
||||
tool_calls: &[ToolCallRecord],
|
||||
embedding_provider: Option<&dyn EmbeddingProvider>,
|
||||
) -> Result<Option<String>> {
|
||||
if !self.config.enabled {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if tool_calls.len() < 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Deduplicate via embeddings when an embedding provider is available.
|
||||
if let Some(provider) = embedding_provider {
|
||||
if provider.name() != "none" && self.is_duplicate(task_description, provider).await? {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
let slug = Self::generate_slug(task_description);
|
||||
if !Self::validate_slug(&slug) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Enforce LRU limit before writing a new skill.
|
||||
self.enforce_lru_limit().await?;
|
||||
|
||||
let skill_dir = self.skills_dir().join(&slug);
|
||||
tokio::fs::create_dir_all(&skill_dir)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("Failed to create skill directory: {}", skill_dir.display())
|
||||
})?;
|
||||
|
||||
let toml_content = Self::generate_skill_toml(&slug, task_description, tool_calls);
|
||||
let toml_path = skill_dir.join("SKILL.toml");
|
||||
tokio::fs::write(&toml_path, toml_content.as_bytes())
|
||||
.await
|
||||
.with_context(|| format!("Failed to write {}", toml_path.display()))?;
|
||||
|
||||
Ok(Some(slug))
|
||||
}
|
||||
|
||||
/// Generate a URL-safe slug from a task description.
|
||||
/// Alphanumeric and hyphens only, max 64 characters.
|
||||
fn generate_slug(description: &str) -> String {
|
||||
let slug: String = description
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.map(|c| if c.is_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
|
||||
// Collapse consecutive hyphens.
|
||||
let mut collapsed = String::with_capacity(slug.len());
|
||||
let mut prev_hyphen = false;
|
||||
for c in slug.chars() {
|
||||
if c == '-' {
|
||||
if !prev_hyphen {
|
||||
collapsed.push('-');
|
||||
}
|
||||
prev_hyphen = true;
|
||||
} else {
|
||||
collapsed.push(c);
|
||||
prev_hyphen = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Trim leading/trailing hyphens, then truncate.
|
||||
let trimmed = collapsed.trim_matches('-');
|
||||
if trimmed.len() > 64 {
|
||||
// Truncate at a hyphen boundary if possible.
|
||||
let truncated = &trimmed[..64];
|
||||
truncated.trim_end_matches('-').to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate that a slug is non-empty, alphanumeric + hyphens, max 64 chars.
|
||||
fn validate_slug(slug: &str) -> bool {
|
||||
!slug.is_empty()
|
||||
&& slug.len() <= 64
|
||||
&& slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
|
||||
&& !slug.starts_with('-')
|
||||
&& !slug.ends_with('-')
|
||||
}
|
||||
|
||||
/// Generate SKILL.toml content from task execution data.
|
||||
fn generate_skill_toml(slug: &str, description: &str, tool_calls: &[ToolCallRecord]) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut toml = String::new();
|
||||
toml.push_str("[skill]\n");
|
||||
let _ = writeln!(toml, "name = {}", toml_escape(slug));
|
||||
let _ = writeln!(
|
||||
toml,
|
||||
"description = {}",
|
||||
toml_escape(&format!("Auto-generated: {description}"))
|
||||
);
|
||||
toml.push_str("version = \"0.1.0\"\n");
|
||||
toml.push_str("author = \"zeroclaw-auto\"\n");
|
||||
toml.push_str("tags = [\"auto-generated\"]\n");
|
||||
|
||||
for call in tool_calls {
|
||||
toml.push('\n');
|
||||
toml.push_str("[[tools]]\n");
|
||||
let _ = writeln!(toml, "name = {}", toml_escape(&call.name));
|
||||
let _ = writeln!(
|
||||
toml,
|
||||
"description = {}",
|
||||
toml_escape(&format!("Tool used in task: {}", call.name))
|
||||
);
|
||||
toml.push_str("kind = \"shell\"\n");
|
||||
|
||||
// Extract the command from args if available, otherwise use the tool name.
|
||||
let command = call
|
||||
.args
|
||||
.get("command")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or(&call.name);
|
||||
let _ = writeln!(toml, "command = {}", toml_escape(command));
|
||||
}
|
||||
|
||||
toml
|
||||
}
|
||||
|
||||
/// Check if a skill with a similar description already exists.
|
||||
async fn is_duplicate(
|
||||
&self,
|
||||
description: &str,
|
||||
embedding_provider: &dyn EmbeddingProvider,
|
||||
) -> Result<bool> {
|
||||
let new_embedding = embedding_provider.embed_one(description).await?;
|
||||
if new_embedding.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let skills_dir = self.skills_dir();
|
||||
if !skills_dir.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut entries = tokio::fs::read_dir(&skills_dir).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let toml_path = entry.path().join("SKILL.toml");
|
||||
if !toml_path.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = tokio::fs::read_to_string(&toml_path).await?;
|
||||
// Extract description from the TOML to compare.
|
||||
if let Some(desc) = extract_description_from_toml(&content) {
|
||||
let existing_embedding = embedding_provider.embed_one(&desc).await?;
|
||||
if !existing_embedding.is_empty() {
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
let similarity =
|
||||
f64::from(cosine_similarity(&new_embedding, &existing_embedding));
|
||||
if similarity > self.config.similarity_threshold {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Remove the oldest auto-generated skill when we exceed `max_skills`.
|
||||
async fn enforce_lru_limit(&self) -> Result<()> {
|
||||
let skills_dir = self.skills_dir();
|
||||
if !skills_dir.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut auto_skills: Vec<(PathBuf, std::time::SystemTime)> = Vec::new();
|
||||
|
||||
let mut entries = tokio::fs::read_dir(&skills_dir).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let toml_path = entry.path().join("SKILL.toml");
|
||||
if !toml_path.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = tokio::fs::read_to_string(&toml_path).await?;
|
||||
if content.contains("\"zeroclaw-auto\"") || content.contains("\"auto-generated\"") {
|
||||
let modified = tokio::fs::metadata(&toml_path)
|
||||
.await?
|
||||
.modified()
|
||||
.unwrap_or(std::time::UNIX_EPOCH);
|
||||
auto_skills.push((entry.path(), modified));
|
||||
}
|
||||
}
|
||||
|
||||
// If at or above the limit, remove the oldest.
|
||||
if auto_skills.len() >= self.config.max_skills {
|
||||
auto_skills.sort_by_key(|(_, modified)| *modified);
|
||||
if let Some((oldest_dir, _)) = auto_skills.first() {
|
||||
tokio::fs::remove_dir_all(oldest_dir)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to remove oldest auto-generated skill: {}",
|
||||
oldest_dir.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn skills_dir(&self) -> PathBuf {
|
||||
self.workspace_dir.join("skills")
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape a string for TOML value (double-quoted).
|
||||
fn toml_escape(s: &str) -> String {
|
||||
let escaped = s
|
||||
.replace('\\', "\\\\")
|
||||
.replace('"', "\\\"")
|
||||
.replace('\n', "\\n")
|
||||
.replace('\r', "\\r")
|
||||
.replace('\t', "\\t");
|
||||
format!("\"{escaped}\"")
|
||||
}
|
||||
|
||||
/// Extract the description field from a SKILL.toml string.
|
||||
fn extract_description_from_toml(content: &str) -> Option<String> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Partial {
|
||||
skill: PartialSkill,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct PartialSkill {
|
||||
description: Option<String>,
|
||||
}
|
||||
toml::from_str::<Partial>(content)
|
||||
.ok()
|
||||
.and_then(|p| p.skill.description)
|
||||
}
|
||||
|
||||
/// Extract `ToolCallRecord`s from the agent conversation history.
|
||||
///
|
||||
/// Scans assistant messages for tool call patterns (both JSON and XML formats)
|
||||
/// and returns records for each unique tool invocation.
|
||||
pub fn extract_tool_calls_from_history(
|
||||
history: &[crate::providers::ChatMessage],
|
||||
) -> Vec<ToolCallRecord> {
|
||||
let mut records = Vec::new();
|
||||
|
||||
for msg in history {
|
||||
if msg.role != "assistant" {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try parsing as JSON (native tool_calls format).
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&msg.content) {
|
||||
if let Some(tool_calls) = value.get("tool_calls").and_then(|v| v.as_array()) {
|
||||
for call in tool_calls {
|
||||
if let Some(function) = call.get("function") {
|
||||
let name = function
|
||||
.get("name")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let args_str = function
|
||||
.get("arguments")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("{}");
|
||||
let args = serde_json::from_str(args_str).unwrap_or_default();
|
||||
if !name.is_empty() {
|
||||
records.push(ToolCallRecord { name, args });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also try XML tool call format: <tool_name>...</tool_name>
|
||||
// Simple extraction for `<shell>{"command":"..."}</shell>` style tags.
|
||||
let content = &msg.content;
|
||||
let mut pos = 0;
|
||||
while pos < content.len() {
|
||||
if let Some(start) = content[pos..].find('<') {
|
||||
let abs_start = pos + start;
|
||||
if let Some(end) = content[abs_start..].find('>') {
|
||||
let tag = &content[abs_start + 1..abs_start + end];
|
||||
// Skip closing tags and meta tags.
|
||||
if tag.starts_with('/') || tag.starts_with('!') || tag.starts_with('?') {
|
||||
pos = abs_start + end + 1;
|
||||
continue;
|
||||
}
|
||||
let tag_name = tag.split_whitespace().next().unwrap_or(tag);
|
||||
let close_tag = format!("</{tag_name}>");
|
||||
if let Some(close_pos) = content[abs_start + end + 1..].find(&close_tag) {
|
||||
let inner = &content[abs_start + end + 1..abs_start + end + 1 + close_pos];
|
||||
let args: serde_json::Value =
|
||||
serde_json::from_str(inner.trim()).unwrap_or_default();
|
||||
// Only add if it looks like a tool call (not HTML/formatting tags).
|
||||
if tag_name != "tool_result"
|
||||
&& tag_name != "tool_results"
|
||||
&& !tag_name.contains(':')
|
||||
&& args.is_object()
|
||||
&& !args.as_object().map_or(true, |o| o.is_empty())
|
||||
{
|
||||
records.push(ToolCallRecord {
|
||||
name: tag_name.to_string(),
|
||||
args,
|
||||
});
|
||||
}
|
||||
pos = abs_start + end + 1 + close_pos + close_tag.len();
|
||||
} else {
|
||||
pos = abs_start + end + 1;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
records
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::embeddings::{EmbeddingProvider, NoopEmbedding};
|
||||
use async_trait::async_trait;
|
||||
|
||||
// ── Slug generation ──────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn slug_basic() {
|
||||
assert_eq!(
|
||||
SkillCreator::generate_slug("Deploy to production"),
|
||||
"deploy-to-production"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_special_characters() {
|
||||
assert_eq!(
|
||||
SkillCreator::generate_slug("Build & test (CI/CD) pipeline!"),
|
||||
"build-test-ci-cd-pipeline"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_max_length() {
|
||||
let long_desc = "a".repeat(100);
|
||||
let slug = SkillCreator::generate_slug(&long_desc);
|
||||
assert!(slug.len() <= 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_leading_trailing_hyphens() {
|
||||
let slug = SkillCreator::generate_slug("---hello world---");
|
||||
assert!(!slug.starts_with('-'));
|
||||
assert!(!slug.ends_with('-'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_consecutive_spaces() {
|
||||
assert_eq!(SkillCreator::generate_slug("hello world"), "hello-world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_empty_input() {
|
||||
let slug = SkillCreator::generate_slug("");
|
||||
assert!(slug.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_only_symbols() {
|
||||
let slug = SkillCreator::generate_slug("!@#$%^&*()");
|
||||
assert!(slug.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slug_unicode() {
|
||||
let slug = SkillCreator::generate_slug("Deploy cafe app");
|
||||
assert_eq!(slug, "deploy-cafe-app");
|
||||
}
|
||||
|
||||
// ── Slug validation ──────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn validate_slug_valid() {
|
||||
assert!(SkillCreator::validate_slug("deploy-to-production"));
|
||||
assert!(SkillCreator::validate_slug("a"));
|
||||
assert!(SkillCreator::validate_slug("abc123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_slug_invalid() {
|
||||
assert!(!SkillCreator::validate_slug(""));
|
||||
assert!(!SkillCreator::validate_slug("-starts-with-hyphen"));
|
||||
assert!(!SkillCreator::validate_slug("ends-with-hyphen-"));
|
||||
assert!(!SkillCreator::validate_slug("has spaces"));
|
||||
assert!(!SkillCreator::validate_slug("has_underscores"));
|
||||
assert!(!SkillCreator::validate_slug(&"a".repeat(65)));
|
||||
}
|
||||
|
||||
// ── TOML generation ──────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn toml_generation_valid_format() {
|
||||
let calls = vec![
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "cargo build"}),
|
||||
},
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "cargo test"}),
|
||||
},
|
||||
];
|
||||
let toml_str = SkillCreator::generate_skill_toml(
|
||||
"build-and-test",
|
||||
"Build and test the project",
|
||||
&calls,
|
||||
);
|
||||
|
||||
// Should parse as valid TOML.
|
||||
let parsed: toml::Value =
|
||||
toml::from_str(&toml_str).expect("Generated TOML should be valid");
|
||||
let skill = parsed.get("skill").expect("Should have [skill] section");
|
||||
assert_eq!(
|
||||
skill.get("name").and_then(toml::Value::as_str),
|
||||
Some("build-and-test")
|
||||
);
|
||||
assert_eq!(
|
||||
skill.get("author").and_then(toml::Value::as_str),
|
||||
Some("zeroclaw-auto")
|
||||
);
|
||||
assert_eq!(
|
||||
skill.get("version").and_then(toml::Value::as_str),
|
||||
Some("0.1.0")
|
||||
);
|
||||
|
||||
let tools = parsed.get("tools").and_then(toml::Value::as_array).unwrap();
|
||||
assert_eq!(tools.len(), 2);
|
||||
assert_eq!(
|
||||
tools[0].get("command").and_then(toml::Value::as_str),
|
||||
Some("cargo build")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toml_generation_escapes_quotes() {
|
||||
let calls = vec![ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "echo \"hello\""}),
|
||||
}];
|
||||
let toml_str =
|
||||
SkillCreator::generate_skill_toml("echo-test", "Test \"quoted\" description", &calls);
|
||||
let parsed: toml::Value =
|
||||
toml::from_str(&toml_str).expect("TOML with quotes should be valid");
|
||||
let desc = parsed
|
||||
.get("skill")
|
||||
.and_then(|s| s.get("description"))
|
||||
.and_then(toml::Value::as_str)
|
||||
.unwrap();
|
||||
assert!(desc.contains("quoted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toml_generation_no_command_arg() {
|
||||
let calls = vec![ToolCallRecord {
|
||||
name: "memory_store".into(),
|
||||
args: serde_json::json!({"key": "foo", "value": "bar"}),
|
||||
}];
|
||||
let toml_str = SkillCreator::generate_skill_toml("memory-op", "Store to memory", &calls);
|
||||
let parsed: toml::Value = toml::from_str(&toml_str).expect("TOML should be valid");
|
||||
let tools = parsed.get("tools").and_then(toml::Value::as_array).unwrap();
|
||||
// When no "command" arg exists, falls back to tool name.
|
||||
assert_eq!(
|
||||
tools[0].get("command").and_then(toml::Value::as_str),
|
||||
Some("memory_store")
|
||||
);
|
||||
}
|
||||
|
||||
// ── TOML description extraction ──────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_valid_toml() {
|
||||
let content = r#"
|
||||
[skill]
|
||||
name = "test"
|
||||
description = "Auto-generated: Build project"
|
||||
version = "0.1.0"
|
||||
"#;
|
||||
assert_eq!(
|
||||
extract_description_from_toml(content),
|
||||
Some("Auto-generated: Build project".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_description_from_invalid_toml() {
|
||||
assert_eq!(extract_description_from_toml("not valid toml {{"), None);
|
||||
}
|
||||
|
||||
// ── Deduplication ────────────────────────────────────────────
|
||||
|
||||
/// A mock embedding provider that returns deterministic embeddings.
|
||||
///
|
||||
/// The "new" description (first text embedded) always gets `[1, 0, 0]`.
|
||||
/// The "existing" skill description (second text embedded) gets a vector
|
||||
/// whose cosine similarity with `[1, 0, 0]` equals `self.similarity`.
|
||||
struct MockEmbeddingProvider {
|
||||
similarity: f32,
|
||||
call_count: std::sync::atomic::AtomicUsize,
|
||||
}
|
||||
|
||||
impl MockEmbeddingProvider {
|
||||
fn new(similarity: f32) -> Self {
|
||||
Self {
|
||||
similarity,
|
||||
call_count: std::sync::atomic::AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EmbeddingProvider for MockEmbeddingProvider {
|
||||
fn name(&self) -> &str {
|
||||
"mock"
|
||||
}
|
||||
fn dimensions(&self) -> usize {
|
||||
3
|
||||
}
|
||||
async fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
|
||||
Ok(texts
|
||||
.iter()
|
||||
.map(|_| {
|
||||
let call = self
|
||||
.call_count
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
if call == 0 {
|
||||
// First call: the "new" description.
|
||||
vec![1.0, 0.0, 0.0]
|
||||
} else {
|
||||
// Subsequent calls: existing skill descriptions.
|
||||
// Produce a vector with the configured cosine similarity to [1,0,0].
|
||||
vec![
|
||||
self.similarity,
|
||||
(1.0 - self.similarity * self.similarity).sqrt(),
|
||||
0.0,
|
||||
]
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dedup_skips_similar_descriptions() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let skills_dir = dir.path().join("skills").join("existing-skill");
|
||||
tokio::fs::create_dir_all(&skills_dir).await.unwrap();
|
||||
tokio::fs::write(
|
||||
skills_dir.join("SKILL.toml"),
|
||||
r#"
|
||||
[skill]
|
||||
name = "existing-skill"
|
||||
description = "Auto-generated: Build the project"
|
||||
version = "0.1.0"
|
||||
author = "zeroclaw-auto"
|
||||
tags = ["auto-generated"]
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let config = SkillCreationConfig {
|
||||
enabled: true,
|
||||
max_skills: 500,
|
||||
similarity_threshold: 0.85,
|
||||
};
|
||||
|
||||
// High similarity provider -> should detect as duplicate.
|
||||
let provider = MockEmbeddingProvider::new(0.95);
|
||||
let creator = SkillCreator::new(dir.path().to_path_buf(), config.clone());
|
||||
assert!(creator
|
||||
.is_duplicate("Build the project", &provider)
|
||||
.await
|
||||
.unwrap());
|
||||
|
||||
// Low similarity provider -> not a duplicate.
|
||||
let provider_low = MockEmbeddingProvider::new(0.3);
|
||||
let creator2 = SkillCreator::new(dir.path().to_path_buf(), config);
|
||||
assert!(!creator2
|
||||
.is_duplicate("Completely different task", &provider_low)
|
||||
.await
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
// ── LRU eviction ─────────────────────────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn lru_eviction_removes_oldest() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = SkillCreationConfig {
|
||||
enabled: true,
|
||||
max_skills: 2,
|
||||
similarity_threshold: 0.85,
|
||||
};
|
||||
|
||||
let skills_dir = dir.path().join("skills");
|
||||
|
||||
// Create two auto-generated skills with different timestamps.
|
||||
for (i, name) in ["old-skill", "new-skill"].iter().enumerate() {
|
||||
let skill_dir = skills_dir.join(name);
|
||||
tokio::fs::create_dir_all(&skill_dir).await.unwrap();
|
||||
tokio::fs::write(
|
||||
skill_dir.join("SKILL.toml"),
|
||||
format!(
|
||||
r#"[skill]
|
||||
name = "{name}"
|
||||
description = "Auto-generated: Skill {i}"
|
||||
version = "0.1.0"
|
||||
author = "zeroclaw-auto"
|
||||
tags = ["auto-generated"]
|
||||
"#
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Small delay to ensure different timestamps.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
|
||||
let creator = SkillCreator::new(dir.path().to_path_buf(), config);
|
||||
creator.enforce_lru_limit().await.unwrap();
|
||||
|
||||
// The oldest skill should have been removed.
|
||||
assert!(!skills_dir.join("old-skill").exists());
|
||||
assert!(skills_dir.join("new-skill").exists());
|
||||
}
|
||||
|
||||
// ── End-to-end: create_from_execution ────────────────────────
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_from_execution_disabled() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = SkillCreationConfig {
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
};
|
||||
let creator = SkillCreator::new(dir.path().to_path_buf(), config);
|
||||
let calls = vec![
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "ls"}),
|
||||
},
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "pwd"}),
|
||||
},
|
||||
];
|
||||
let result = creator
|
||||
.create_from_execution("List files", &calls, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_from_execution_insufficient_steps() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = SkillCreationConfig {
|
||||
enabled: true,
|
||||
..Default::default()
|
||||
};
|
||||
let creator = SkillCreator::new(dir.path().to_path_buf(), config);
|
||||
let calls = vec![ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "ls"}),
|
||||
}];
|
||||
let result = creator
|
||||
.create_from_execution("List files", &calls, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_from_execution_success() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = SkillCreationConfig {
|
||||
enabled: true,
|
||||
max_skills: 500,
|
||||
similarity_threshold: 0.85,
|
||||
};
|
||||
let creator = SkillCreator::new(dir.path().to_path_buf(), config);
|
||||
let calls = vec![
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "cargo build"}),
|
||||
},
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "cargo test"}),
|
||||
},
|
||||
];
|
||||
|
||||
// Use noop embedding (no deduplication).
|
||||
let noop = NoopEmbedding;
|
||||
let result = creator
|
||||
.create_from_execution("Build and test", &calls, Some(&noop))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result, Some("build-and-test".into()));
|
||||
|
||||
// Verify the skill directory and TOML were created.
|
||||
let skill_dir = dir.path().join("skills").join("build-and-test");
|
||||
assert!(skill_dir.exists());
|
||||
let toml_content = tokio::fs::read_to_string(skill_dir.join("SKILL.toml"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(toml_content.contains("build-and-test"));
|
||||
assert!(toml_content.contains("zeroclaw-auto"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_from_execution_with_dedup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = SkillCreationConfig {
|
||||
enabled: true,
|
||||
max_skills: 500,
|
||||
similarity_threshold: 0.85,
|
||||
};
|
||||
|
||||
// First, create an existing skill.
|
||||
let skills_dir = dir.path().join("skills").join("existing");
|
||||
tokio::fs::create_dir_all(&skills_dir).await.unwrap();
|
||||
tokio::fs::write(
|
||||
skills_dir.join("SKILL.toml"),
|
||||
r#"[skill]
|
||||
name = "existing"
|
||||
description = "Auto-generated: Build and test"
|
||||
version = "0.1.0"
|
||||
author = "zeroclaw-auto"
|
||||
tags = ["auto-generated"]
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// High similarity provider -> should skip.
|
||||
let provider = MockEmbeddingProvider::new(0.95);
|
||||
let creator = SkillCreator::new(dir.path().to_path_buf(), config);
|
||||
let calls = vec![
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "cargo build"}),
|
||||
},
|
||||
ToolCallRecord {
|
||||
name: "shell".into(),
|
||||
args: serde_json::json!({"command": "cargo test"}),
|
||||
},
|
||||
];
|
||||
let result = creator
|
||||
.create_from_execution("Build and test", &calls, Some(&provider))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
// ── Tool call extraction from history ────────────────────────
|
||||
|
||||
#[test]
|
||||
fn extract_from_empty_history() {
|
||||
let history = vec![];
|
||||
let records = extract_tool_calls_from_history(&history);
|
||||
assert!(records.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_from_user_messages_only() {
|
||||
use crate::providers::ChatMessage;
|
||||
let history = vec![ChatMessage::user("hello"), ChatMessage::user("world")];
|
||||
let records = extract_tool_calls_from_history(&history);
|
||||
assert!(records.is_empty());
|
||||
}
|
||||
|
||||
// ── Fuzz-like tests for slug ─────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn slug_fuzz_various_inputs() {
|
||||
let inputs = [
|
||||
"",
|
||||
" ",
|
||||
"---",
|
||||
"a",
|
||||
"hello world!",
|
||||
"UPPER CASE",
|
||||
"with-hyphens-already",
|
||||
"with__underscores",
|
||||
"123 numbers 456",
|
||||
"emoji: cafe",
|
||||
&"x".repeat(200),
|
||||
"a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-0-1-2-3-4-5",
|
||||
];
|
||||
|
||||
for input in &inputs {
|
||||
let slug = SkillCreator::generate_slug(input);
|
||||
// Slug should always pass validation (or be empty for degenerate input).
|
||||
if !slug.is_empty() {
|
||||
assert!(
|
||||
SkillCreator::validate_slug(&slug),
|
||||
"Generated slug '{slug}' from '{input}' failed validation"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fuzz-like tests for TOML generation ──────────────────────
|
||||
|
||||
#[test]
|
||||
fn toml_fuzz_various_inputs() {
|
||||
let descriptions = [
|
||||
"simple task",
|
||||
"task with \"quotes\" and \\ backslashes",
|
||||
"task with\nnewlines\r\nand tabs\there",
|
||||
"",
|
||||
&"long ".repeat(100),
|
||||
];
|
||||
|
||||
let args_variants = [
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({"command": "echo hello"}),
|
||||
serde_json::json!({"command": "echo \"hello world\"", "extra": 42}),
|
||||
];
|
||||
|
||||
for desc in &descriptions {
|
||||
for args in &args_variants {
|
||||
let calls = vec![
|
||||
ToolCallRecord {
|
||||
name: "tool1".into(),
|
||||
args: args.clone(),
|
||||
},
|
||||
ToolCallRecord {
|
||||
name: "tool2".into(),
|
||||
args: args.clone(),
|
||||
},
|
||||
];
|
||||
let toml_str = SkillCreator::generate_skill_toml("test-slug", desc, &calls);
|
||||
// Must always produce valid TOML.
|
||||
let _parsed: toml::Value = toml::from_str(&toml_str)
|
||||
.unwrap_or_else(|e| panic!("Invalid TOML for desc '{desc}': {e}\n{toml_str}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+210
-17
@@ -7,6 +7,8 @@ use std::process::Command;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
mod audit;
|
||||
#[cfg(feature = "skill-creation")]
|
||||
pub mod creator;
|
||||
|
||||
const OPEN_SKILLS_REPO_URL: &str = "https://github.com/besoeasy/open-skills";
|
||||
const OPEN_SKILLS_SYNC_MARKER: &str = ".zeroclaw-open-skills-sync";
|
||||
@@ -67,6 +69,16 @@ struct SkillMeta {
|
||||
tags: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
struct SkillMarkdownMeta {
|
||||
name: Option<String>,
|
||||
description: Option<String>,
|
||||
version: Option<String>,
|
||||
author: Option<String>,
|
||||
#[serde(default)]
|
||||
tags: Vec<String>,
|
||||
}
|
||||
|
||||
fn default_version() -> String {
|
||||
"0.1.0".to_string()
|
||||
}
|
||||
@@ -161,13 +173,76 @@ fn load_skills_from_directory(skills_dir: &Path) -> Vec<Skill> {
|
||||
skills
|
||||
}
|
||||
|
||||
fn finalize_open_skill(mut skill: Skill) -> Skill {
|
||||
if !skill.tags.iter().any(|tag| tag == "open-skills") {
|
||||
skill.tags.push("open-skills".to_string());
|
||||
}
|
||||
if skill.author.is_none() {
|
||||
skill.author = Some("besoeasy/open-skills".to_string());
|
||||
}
|
||||
skill
|
||||
}
|
||||
|
||||
fn load_open_skills_from_directory(skills_dir: &Path) -> Vec<Skill> {
|
||||
if !skills_dir.exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut skills = Vec::new();
|
||||
|
||||
let Ok(entries) = std::fs::read_dir(skills_dir) else {
|
||||
return skills;
|
||||
};
|
||||
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if !path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match audit::audit_skill_directory(&path) {
|
||||
Ok(report) if report.is_clean() => {}
|
||||
Ok(report) => {
|
||||
tracing::warn!(
|
||||
"skipping insecure open-skill directory {}: {}",
|
||||
path.display(),
|
||||
report.summary()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
"skipping unauditable open-skill directory {}: {err}",
|
||||
path.display()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let manifest_path = path.join("SKILL.toml");
|
||||
let md_path = path.join("SKILL.md");
|
||||
|
||||
if manifest_path.exists() {
|
||||
if let Ok(skill) = load_skill_toml(&manifest_path) {
|
||||
skills.push(finalize_open_skill(skill));
|
||||
}
|
||||
} else if md_path.exists() {
|
||||
if let Ok(skill) = load_open_skill_md(&md_path) {
|
||||
skills.push(skill);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
skills
|
||||
}
|
||||
|
||||
fn load_open_skills(repo_dir: &Path) -> Vec<Skill> {
|
||||
// Modern open-skills layout stores skill packages in `skills/<name>/SKILL.md`.
|
||||
// Prefer that structure to avoid treating repository docs (e.g. CONTRIBUTING.md)
|
||||
// as executable skills.
|
||||
let nested_skills_dir = repo_dir.join("skills");
|
||||
if nested_skills_dir.is_dir() {
|
||||
return load_skills_from_directory(&nested_skills_dir);
|
||||
return load_open_skills_from_directory(&nested_skills_dir);
|
||||
}
|
||||
|
||||
let mut skills = Vec::new();
|
||||
@@ -420,6 +495,7 @@ fn load_skill_toml(path: &Path) -> Result<Skill> {
|
||||
/// Load a skill from a SKILL.md file (simpler format)
|
||||
fn load_skill_md(path: &Path, dir: &Path) -> Result<Skill> {
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let parsed = parse_skill_markdown(&content);
|
||||
let name = dir
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
@@ -427,35 +503,90 @@ fn load_skill_md(path: &Path, dir: &Path) -> Result<Skill> {
|
||||
.to_string();
|
||||
|
||||
Ok(Skill {
|
||||
name,
|
||||
description: extract_description(&content),
|
||||
version: "0.1.0".to_string(),
|
||||
author: None,
|
||||
tags: Vec::new(),
|
||||
name: parsed.meta.name.unwrap_or(name),
|
||||
description: parsed
|
||||
.meta
|
||||
.description
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or_else(|| extract_description(&parsed.body)),
|
||||
version: parsed.meta.version.unwrap_or_else(default_version),
|
||||
author: parsed.meta.author,
|
||||
tags: parsed.meta.tags,
|
||||
tools: Vec::new(),
|
||||
prompts: vec![content],
|
||||
prompts: vec![parsed.body],
|
||||
location: Some(path.to_path_buf()),
|
||||
})
|
||||
}
|
||||
|
||||
fn load_open_skill_md(path: &Path) -> Result<Skill> {
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let name = path
|
||||
let parsed = parse_skill_markdown(&content);
|
||||
let file_stem = path
|
||||
.file_stem()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("open-skill")
|
||||
.to_string();
|
||||
|
||||
Ok(Skill {
|
||||
name,
|
||||
description: extract_description(&content),
|
||||
version: "open-skills".to_string(),
|
||||
author: Some("besoeasy/open-skills".to_string()),
|
||||
tags: vec!["open-skills".to_string()],
|
||||
let name = if file_stem.eq_ignore_ascii_case("skill") {
|
||||
path.parent()
|
||||
.and_then(|dir| dir.file_name())
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or(&file_stem)
|
||||
.to_string()
|
||||
} else {
|
||||
file_stem
|
||||
};
|
||||
Ok(finalize_open_skill(Skill {
|
||||
name: parsed.meta.name.unwrap_or(name),
|
||||
description: parsed
|
||||
.meta
|
||||
.description
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or_else(|| extract_description(&parsed.body)),
|
||||
version: parsed
|
||||
.meta
|
||||
.version
|
||||
.unwrap_or_else(|| "open-skills".to_string()),
|
||||
author: parsed
|
||||
.meta
|
||||
.author
|
||||
.or_else(|| Some("besoeasy/open-skills".to_string())),
|
||||
tags: parsed.meta.tags,
|
||||
tools: Vec::new(),
|
||||
prompts: vec![content],
|
||||
prompts: vec![parsed.body],
|
||||
location: Some(path.to_path_buf()),
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
struct ParsedSkillMarkdown {
|
||||
meta: SkillMarkdownMeta,
|
||||
body: String,
|
||||
}
|
||||
|
||||
fn parse_skill_markdown(content: &str) -> ParsedSkillMarkdown {
|
||||
if let Some((frontmatter, body)) = split_skill_frontmatter(content) {
|
||||
if let Ok(meta) = serde_yaml::from_str::<SkillMarkdownMeta>(&frontmatter) {
|
||||
return ParsedSkillMarkdown { meta, body };
|
||||
}
|
||||
}
|
||||
|
||||
ParsedSkillMarkdown {
|
||||
meta: SkillMarkdownMeta::default(),
|
||||
body: content.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn split_skill_frontmatter(content: &str) -> Option<(String, String)> {
|
||||
let normalized = content.replace("\r\n", "\n");
|
||||
let rest = normalized.strip_prefix("---\n")?;
|
||||
if let Some(idx) = rest.find("\n---\n") {
|
||||
let frontmatter = rest[..idx].to_string();
|
||||
let body = rest[idx + 5..].to_string();
|
||||
return Some((frontmatter, body));
|
||||
}
|
||||
if let Some(frontmatter) = rest.strip_suffix("\n---") {
|
||||
return Some((frontmatter.to_string(), String::new()));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_description(content: &str) -> String {
|
||||
@@ -620,6 +751,7 @@ pub fn init_skills_dir(workspace_dir: &Path) -> Result<()> {
|
||||
```\n\n\
|
||||
## SKILL.md format (simpler)\n\n\
|
||||
Just write a markdown file with instructions for the agent.\n\
|
||||
Optional YAML frontmatter is supported for `name`, `description`, `version`, `author`, and `tags`.\n\
|
||||
The agent will read it and follow the instructions.\n\n\
|
||||
## Installing community skills\n\n\
|
||||
```bash\n\
|
||||
@@ -1059,6 +1191,30 @@ command = "echo hello"
|
||||
assert!(skills[0].description.contains("cool things"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_skill_from_md_frontmatter_uses_metadata_and_body() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let skills_dir = dir.path().join("skills");
|
||||
let skill_dir = skills_dir.join("md-skill");
|
||||
fs::create_dir_all(&skill_dir).unwrap();
|
||||
|
||||
fs::write(
|
||||
skill_dir.join("SKILL.md"),
|
||||
"---\nname: pdf\ndescription: Use this skill for PDFs\nversion: 1.2.3\nauthor: maintainer\ntags:\n - docs\n - pdf\n---\n# PDF Processing Guide\nExtract text carefully.\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let skills = load_skills(dir.path());
|
||||
assert_eq!(skills.len(), 1);
|
||||
assert_eq!(skills[0].name, "pdf");
|
||||
assert_eq!(skills[0].description, "Use this skill for PDFs");
|
||||
assert_eq!(skills[0].version, "1.2.3");
|
||||
assert_eq!(skills[0].author.as_deref(), Some("maintainer"));
|
||||
assert_eq!(skills[0].tags, vec!["docs", "pdf"]);
|
||||
assert!(skills[0].prompts[0].contains("# PDF Processing Guide"));
|
||||
assert!(!skills[0].prompts[0].contains("name: pdf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skills_to_prompt_empty() {
|
||||
let prompt = skills_to_prompt(&[], Path::new("/tmp"));
|
||||
@@ -1471,6 +1627,43 @@ description = "Bare minimum"
|
||||
assert_eq!(skills[0].name, "http_request");
|
||||
assert_ne!(skills[0].name, "CONTRIBUTING");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_open_skill_md_frontmatter_uses_metadata_and_strips_block() {
|
||||
let _env_guard = open_skills_env_lock().lock().unwrap();
|
||||
let _enabled_guard = EnvVarGuard::unset("ZEROCLAW_OPEN_SKILLS_ENABLED");
|
||||
let _dir_guard = EnvVarGuard::unset("ZEROCLAW_OPEN_SKILLS_DIR");
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let workspace_dir = dir.path().join("workspace");
|
||||
fs::create_dir_all(workspace_dir.join("skills")).unwrap();
|
||||
|
||||
let open_skills_dir = dir.path().join("open-skills-local");
|
||||
fs::create_dir_all(open_skills_dir.join("skills/pdf")).unwrap();
|
||||
fs::write(
|
||||
open_skills_dir.join("skills/pdf/SKILL.md"),
|
||||
"---\nname: pdf\ndescription: Use this skill whenever the user needs PDF help.\nauthor: community\ntags:\n - parser\n---\n# PDF Guide\nInspect files safely.\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut config = crate::config::Config::default();
|
||||
config.workspace_dir = workspace_dir.clone();
|
||||
config.skills.open_skills_enabled = true;
|
||||
config.skills.open_skills_dir = Some(open_skills_dir.to_string_lossy().to_string());
|
||||
|
||||
let skills = load_skills_with_config(&workspace_dir, &config);
|
||||
assert_eq!(skills.len(), 1);
|
||||
assert_eq!(skills[0].name, "pdf");
|
||||
assert_eq!(
|
||||
skills[0].description,
|
||||
"Use this skill whenever the user needs PDF help."
|
||||
);
|
||||
assert_eq!(skills[0].author.as_deref(), Some("community"));
|
||||
assert!(skills[0].tags.iter().any(|tag| tag == "parser"));
|
||||
assert!(skills[0].tags.iter().any(|tag| tag == "open-skills"));
|
||||
assert!(skills[0].prompts[0].contains("# PDF Guide"));
|
||||
assert!(!skills[0].prompts[0].contains("description: Use this skill"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+108
-3
@@ -1,6 +1,8 @@
|
||||
use super::traits::{Tool, ToolResult};
|
||||
use crate::config::Config;
|
||||
use crate::cron::{self, DeliveryConfig, JobType, Schedule, SessionTarget};
|
||||
use crate::cron::{
|
||||
self, deserialize_maybe_stringified, DeliveryConfig, JobType, Schedule, SessionTarget,
|
||||
};
|
||||
use crate::security::SecurityPolicy;
|
||||
use async_trait::async_trait;
|
||||
use serde_json::json;
|
||||
@@ -128,6 +130,11 @@ impl Tool for CronAddTool {
|
||||
"type": "string",
|
||||
"description": "Optional model override for agent jobs, e.g. 'x-ai/grok-4-1-fast'"
|
||||
},
|
||||
"allowed_tools": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Optional allowlist of tool names for agent jobs. When omitted, all tools remain available."
|
||||
},
|
||||
"delivery": {
|
||||
"type": "object",
|
||||
"description": "Optional delivery config to send job output to a channel after each run. When provided, all three of mode, channel, and to are expected.",
|
||||
@@ -176,7 +183,7 @@ impl Tool for CronAddTool {
|
||||
}
|
||||
|
||||
let schedule = match args.get("schedule") {
|
||||
Some(v) => match serde_json::from_value::<Schedule>(v.clone()) {
|
||||
Some(v) => match deserialize_maybe_stringified::<Schedule>(v) {
|
||||
Ok(schedule) => schedule,
|
||||
Err(e) => {
|
||||
return Ok(ToolResult {
|
||||
@@ -286,6 +293,19 @@ impl Tool for CronAddTool {
|
||||
.get("model")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_string);
|
||||
let allowed_tools = match args.get("allowed_tools") {
|
||||
Some(v) => match serde_json::from_value::<Vec<String>>(v.clone()) {
|
||||
Ok(v) => Some(v),
|
||||
Err(e) => {
|
||||
return Ok(ToolResult {
|
||||
success: false,
|
||||
output: String::new(),
|
||||
error: Some(format!("Invalid allowed_tools: {e}")),
|
||||
});
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
|
||||
let delivery = match args.get("delivery") {
|
||||
Some(v) => match serde_json::from_value::<DeliveryConfig>(v.clone()) {
|
||||
@@ -314,6 +334,7 @@ impl Tool for CronAddTool {
|
||||
model,
|
||||
delivery,
|
||||
delete_after_run,
|
||||
allowed_tools,
|
||||
)
|
||||
}
|
||||
};
|
||||
@@ -327,7 +348,8 @@ impl Tool for CronAddTool {
|
||||
"job_type": job.job_type,
|
||||
"schedule": job.schedule,
|
||||
"next_run": job.next_run,
|
||||
"enabled": job.enabled
|
||||
"enabled": job.enabled,
|
||||
"allowed_tools": job.allowed_tools
|
||||
}))?,
|
||||
error: None,
|
||||
}),
|
||||
@@ -511,6 +533,63 @@ mod tests {
|
||||
assert!(approved.success, "{:?}", approved.error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepts_schedule_passed_as_json_string() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let cfg = test_config(&tmp).await;
|
||||
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
|
||||
|
||||
// Simulate the LLM double-serializing the schedule: the value arrives
|
||||
// as a JSON string containing a JSON object, rather than an object.
|
||||
let result = tool
|
||||
.execute(json!({
|
||||
"schedule": r#"{"kind":"cron","expr":"*/5 * * * *"}"#,
|
||||
"job_type": "shell",
|
||||
"command": "echo string-schedule"
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(result.success, "{:?}", result.error);
|
||||
assert!(result.output.contains("next_run"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepts_stringified_interval_schedule() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let cfg = test_config(&tmp).await;
|
||||
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
|
||||
|
||||
let result = tool
|
||||
.execute(json!({
|
||||
"schedule": r#"{"kind":"every","every_ms":60000}"#,
|
||||
"job_type": "shell",
|
||||
"command": "echo interval"
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(result.success, "{:?}", result.error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepts_stringified_schedule_with_timezone() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let cfg = test_config(&tmp).await;
|
||||
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
|
||||
|
||||
let result = tool
|
||||
.execute(json!({
|
||||
"schedule": r#"{"kind":"cron","expr":"*/30 9-15 * * 1-5","tz":"Asia/Shanghai"}"#,
|
||||
"job_type": "shell",
|
||||
"command": "echo tz-test"
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(result.success, "{:?}", result.error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_invalid_schedule() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -553,6 +632,32 @@ mod tests {
|
||||
.contains("Missing 'prompt'"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_job_persists_allowed_tools() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let cfg = test_config(&tmp).await;
|
||||
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
|
||||
|
||||
let result = tool
|
||||
.execute(json!({
|
||||
"schedule": { "kind": "cron", "expr": "*/5 * * * *" },
|
||||
"job_type": "agent",
|
||||
"prompt": "check status",
|
||||
"allowed_tools": ["file_read", "web_search"]
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(result.success, "{:?}", result.error);
|
||||
|
||||
let jobs = cron::list_jobs(&cfg).unwrap();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert_eq!(
|
||||
jobs[0].allowed_tools,
|
||||
Some(vec!["file_read".into(), "web_search".into()])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delivery_schema_includes_matrix_channel() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::traits::{Tool, ToolResult};
|
||||
use crate::config::Config;
|
||||
use crate::cron::{self, CronJobPatch};
|
||||
use crate::cron::{self, deserialize_maybe_stringified, CronJobPatch};
|
||||
use crate::security::SecurityPolicy;
|
||||
use async_trait::async_trait;
|
||||
use serde_json::json;
|
||||
@@ -89,6 +89,11 @@ impl Tool for CronUpdateTool {
|
||||
"type": "string",
|
||||
"description": "Model override for agent jobs, e.g. 'x-ai/grok-4-1-fast'"
|
||||
},
|
||||
"allowed_tools": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Optional replacement allowlist of tool names for agent jobs"
|
||||
},
|
||||
"session_target": {
|
||||
"type": "string",
|
||||
"enum": ["isolated", "main"],
|
||||
@@ -202,7 +207,7 @@ impl Tool for CronUpdateTool {
|
||||
}
|
||||
};
|
||||
|
||||
let patch = match serde_json::from_value::<CronJobPatch>(patch_val) {
|
||||
let patch = match deserialize_maybe_stringified::<CronJobPatch>(&patch_val) {
|
||||
Ok(patch) => patch,
|
||||
Err(e) => {
|
||||
return Ok(ToolResult {
|
||||
@@ -403,6 +408,7 @@ mod tests {
|
||||
"command",
|
||||
"prompt",
|
||||
"model",
|
||||
"allowed_tools",
|
||||
"session_target",
|
||||
"delete_after_run",
|
||||
"schedule",
|
||||
@@ -501,4 +507,40 @@ mod tests {
|
||||
.contains("Rate limit exceeded"));
|
||||
assert!(cron::get_job(&cfg, &job.id).unwrap().enabled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn updates_agent_allowed_tools() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let cfg = test_config(&tmp).await;
|
||||
let job = cron::add_agent_job(
|
||||
&cfg,
|
||||
None,
|
||||
crate::cron::Schedule::Cron {
|
||||
expr: "*/5 * * * *".into(),
|
||||
tz: None,
|
||||
},
|
||||
"check status",
|
||||
crate::cron::SessionTarget::Isolated,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let tool = CronUpdateTool::new(cfg.clone(), test_security(&cfg));
|
||||
|
||||
let result = tool
|
||||
.execute(json!({
|
||||
"job_id": job.id,
|
||||
"patch": { "allowed_tools": ["file_read", "web_search"] }
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(result.success, "{:?}", result.error);
|
||||
assert_eq!(
|
||||
cron::get_job(&cfg, &job.id).unwrap().allowed_tools,
|
||||
Some(vec!["file_read".into(), "web_search".into()])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+244
-4
@@ -296,8 +296,9 @@ impl Tool for DelegateTool {
|
||||
}
|
||||
|
||||
// Wrap the provider call in a timeout to prevent indefinite blocking
|
||||
let timeout_secs = agent_config.timeout_secs.unwrap_or(DELEGATE_TIMEOUT_SECS);
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(DELEGATE_TIMEOUT_SECS),
|
||||
Duration::from_secs(timeout_secs),
|
||||
provider.chat_with_system(
|
||||
agent_config.system_prompt.as_deref(),
|
||||
&full_prompt,
|
||||
@@ -314,7 +315,7 @@ impl Tool for DelegateTool {
|
||||
success: false,
|
||||
output: String::new(),
|
||||
error: Some(format!(
|
||||
"Agent '{agent_name}' timed out after {DELEGATE_TIMEOUT_SECS}s"
|
||||
"Agent '{agent_name}' timed out after {timeout_secs}s"
|
||||
)),
|
||||
});
|
||||
}
|
||||
@@ -401,8 +402,11 @@ impl DelegateTool {
|
||||
|
||||
let noop_observer = NoopObserver;
|
||||
|
||||
let agentic_timeout_secs = agent_config
|
||||
.agentic_timeout_secs
|
||||
.unwrap_or(DELEGATE_AGENTIC_TIMEOUT_SECS);
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(DELEGATE_AGENTIC_TIMEOUT_SECS),
|
||||
Duration::from_secs(agentic_timeout_secs),
|
||||
run_tool_call_loop(
|
||||
provider,
|
||||
&mut history,
|
||||
@@ -414,6 +418,7 @@ impl DelegateTool {
|
||||
true,
|
||||
None,
|
||||
"delegate",
|
||||
None,
|
||||
&self.multimodal_config,
|
||||
agent_config.max_iterations,
|
||||
None,
|
||||
@@ -422,6 +427,7 @@ impl DelegateTool {
|
||||
&[],
|
||||
&[],
|
||||
None,
|
||||
None,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
@@ -453,7 +459,7 @@ impl DelegateTool {
|
||||
success: false,
|
||||
output: String::new(),
|
||||
error: Some(format!(
|
||||
"Agent '{agent_name}' timed out after {DELEGATE_AGENTIC_TIMEOUT_SECS}s"
|
||||
"Agent '{agent_name}' timed out after {agentic_timeout_secs}s"
|
||||
)),
|
||||
}),
|
||||
}
|
||||
@@ -530,6 +536,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
agents.insert(
|
||||
@@ -544,6 +552,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
agents
|
||||
@@ -697,6 +707,8 @@ mod tests {
|
||||
agentic: true,
|
||||
allowed_tools,
|
||||
max_iterations,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -805,6 +817,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
let tool = DelegateTool::new(agents, None, test_security());
|
||||
@@ -911,6 +925,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
let tool = DelegateTool::new(agents, None, test_security());
|
||||
@@ -946,6 +962,8 @@ mod tests {
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
let tool = DelegateTool::new(agents, None, test_security());
|
||||
@@ -1220,4 +1238,226 @@ mod tests {
|
||||
handle.write().push(Arc::new(FakeMcpTool));
|
||||
assert_eq!(handle.read().len(), 2);
|
||||
}
|
||||
|
||||
// ── Configurable timeout tests ──────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn default_timeout_values_used_when_config_unset() {
|
||||
let config = DelegateAgentConfig {
|
||||
provider: "ollama".to_string(),
|
||||
model: "llama3".to_string(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
};
|
||||
assert_eq!(config.timeout_secs.unwrap_or(DELEGATE_TIMEOUT_SECS), 120);
|
||||
assert_eq!(
|
||||
config
|
||||
.agentic_timeout_secs
|
||||
.unwrap_or(DELEGATE_AGENTIC_TIMEOUT_SECS),
|
||||
300
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_timeout_values_are_respected() {
|
||||
let config = DelegateAgentConfig {
|
||||
provider: "ollama".to_string(),
|
||||
model: "llama3".to_string(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: Some(60),
|
||||
agentic_timeout_secs: Some(600),
|
||||
};
|
||||
assert_eq!(config.timeout_secs.unwrap_or(DELEGATE_TIMEOUT_SECS), 60);
|
||||
assert_eq!(
|
||||
config
|
||||
.agentic_timeout_secs
|
||||
.unwrap_or(DELEGATE_AGENTIC_TIMEOUT_SECS),
|
||||
600
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeout_deserialization_defaults_to_none() {
|
||||
let toml_str = r#"
|
||||
provider = "ollama"
|
||||
model = "llama3"
|
||||
"#;
|
||||
let config: DelegateAgentConfig = toml::from_str(toml_str).unwrap();
|
||||
assert!(config.timeout_secs.is_none());
|
||||
assert!(config.agentic_timeout_secs.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeout_deserialization_with_custom_values() {
|
||||
let toml_str = r#"
|
||||
provider = "ollama"
|
||||
model = "llama3"
|
||||
timeout_secs = 45
|
||||
agentic_timeout_secs = 900
|
||||
"#;
|
||||
let config: DelegateAgentConfig = toml::from_str(toml_str).unwrap();
|
||||
assert_eq!(config.timeout_secs, Some(45));
|
||||
assert_eq!(config.agentic_timeout_secs, Some(900));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_rejects_zero_timeout() {
|
||||
let mut config = crate::config::Config::default();
|
||||
config.agents.insert(
|
||||
"bad".into(),
|
||||
DelegateAgentConfig {
|
||||
provider: "ollama".into(),
|
||||
model: "llama3".into(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: Some(0),
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
let err = config.validate().unwrap_err();
|
||||
assert!(
|
||||
format!("{err}").contains("timeout_secs must be greater than 0"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_rejects_zero_agentic_timeout() {
|
||||
let mut config = crate::config::Config::default();
|
||||
config.agents.insert(
|
||||
"bad".into(),
|
||||
DelegateAgentConfig {
|
||||
provider: "ollama".into(),
|
||||
model: "llama3".into(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: Some(0),
|
||||
},
|
||||
);
|
||||
let err = config.validate().unwrap_err();
|
||||
assert!(
|
||||
format!("{err}").contains("agentic_timeout_secs must be greater than 0"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_rejects_excessive_timeout() {
|
||||
let mut config = crate::config::Config::default();
|
||||
config.agents.insert(
|
||||
"bad".into(),
|
||||
DelegateAgentConfig {
|
||||
provider: "ollama".into(),
|
||||
model: "llama3".into(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: Some(7200),
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
let err = config.validate().unwrap_err();
|
||||
assert!(
|
||||
format!("{err}").contains("exceeds max 3600"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_rejects_excessive_agentic_timeout() {
|
||||
let mut config = crate::config::Config::default();
|
||||
config.agents.insert(
|
||||
"bad".into(),
|
||||
DelegateAgentConfig {
|
||||
provider: "ollama".into(),
|
||||
model: "llama3".into(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: Some(5000),
|
||||
},
|
||||
);
|
||||
let err = config.validate().unwrap_err();
|
||||
assert!(
|
||||
format!("{err}").contains("exceeds max 3600"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_accepts_max_boundary_timeout() {
|
||||
let mut config = crate::config::Config::default();
|
||||
config.agents.insert(
|
||||
"ok".into(),
|
||||
DelegateAgentConfig {
|
||||
provider: "ollama".into(),
|
||||
model: "llama3".into(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: Some(3600),
|
||||
agentic_timeout_secs: Some(3600),
|
||||
},
|
||||
);
|
||||
assert!(config.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_validation_accepts_none_timeouts() {
|
||||
let mut config = crate::config::Config::default();
|
||||
config.agents.insert(
|
||||
"ok".into(),
|
||||
DelegateAgentConfig {
|
||||
provider: "ollama".into(),
|
||||
model: "llama3".into(),
|
||||
system_prompt: None,
|
||||
api_key: None,
|
||||
temperature: None,
|
||||
max_depth: 3,
|
||||
agentic: false,
|
||||
allowed_tools: Vec::new(),
|
||||
max_iterations: 10,
|
||||
timeout_secs: None,
|
||||
agentic_timeout_secs: None,
|
||||
},
|
||||
);
|
||||
assert!(config.validate().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
+41
-1
@@ -103,7 +103,7 @@ impl Tool for FileEditTool {
|
||||
});
|
||||
}
|
||||
|
||||
let full_path = self.security.workspace_dir.join(path);
|
||||
let full_path = self.security.resolve_tool_path(path);
|
||||
|
||||
// ── 5. Canonicalize parent ─────────────────────────────────
|
||||
let Some(parent) = full_path.parent() else {
|
||||
@@ -666,6 +666,46 @@ mod tests {
|
||||
let _ = tokio::fs::remove_dir_all(&dir).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn file_edit_absolute_path_in_workspace() {
|
||||
let dir = std::env::temp_dir().join("zeroclaw_test_file_edit_abs_path");
|
||||
let _ = tokio::fs::remove_dir_all(&dir).await;
|
||||
tokio::fs::create_dir_all(&dir).await.unwrap();
|
||||
|
||||
// Canonicalize so the workspace dir matches resolved paths on macOS (/private/var/…)
|
||||
let dir = tokio::fs::canonicalize(&dir).await.unwrap();
|
||||
|
||||
tokio::fs::write(dir.join("target.txt"), "old content")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let tool = FileEditTool::new(test_security(dir.clone()));
|
||||
|
||||
// Pass an absolute path that is within the workspace
|
||||
let abs_path = dir.join("target.txt");
|
||||
let result = tool
|
||||
.execute(json!({
|
||||
"path": abs_path.to_string_lossy().to_string(),
|
||||
"old_string": "old content",
|
||||
"new_string": "new content"
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
result.success,
|
||||
"editing via absolute workspace path should succeed, error: {:?}",
|
||||
result.error
|
||||
);
|
||||
|
||||
let content = tokio::fs::read_to_string(dir.join("target.txt"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(content, "new content");
|
||||
|
||||
let _ = tokio::fs::remove_dir_all(&dir).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn file_edit_blocks_null_byte_in_path() {
|
||||
let dir = std::env::temp_dir().join("zeroclaw_test_file_edit_null_byte");
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user