mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-25 14:53:34 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bece7ec47 | ||
|
|
3c4095c7a1 | ||
|
|
7e2ad874bd | ||
|
|
26b1c5b493 | ||
|
|
e0e530e646 | ||
|
|
93c27fa053 | ||
|
|
a8e83210ff | ||
|
|
6d9dbbb3b9 | ||
|
|
8a320ae9db | ||
|
|
fd41bdf4be | ||
|
|
de5a1c7b0d | ||
|
|
9ce3a9fc53 | ||
|
|
9bb19a98f7 | ||
|
|
0b33ca9926 | ||
|
|
9ba10eac35 | ||
|
|
27e8d6f8dd | ||
|
|
f49f368355 | ||
|
|
8f8cb7f7b1 | ||
|
|
2f4eb08613 | ||
|
|
30db07c58e | ||
|
|
7234700c78 | ||
|
|
9c5ba43ccd | ||
|
|
45cd6682d3 |
@@ -5,7 +5,7 @@ argument-hint: <event_name> [description]
|
||||
model: opus
|
||||
---
|
||||
|
||||
Add a new SSE event called `$ARGUMENTS` to the IronClaw web gateway. This involves changes across 5 files in a specific order. Follow each step exactly.
|
||||
Add a new SSE event called `$ARGUMENTS` to the OptimClaw web gateway. This involves changes across 5 files in a specific order. Follow each step exactly.
|
||||
|
||||
## Step 1: Add `StatusUpdate` variant
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ argument-hint: <tool_name> [description]
|
||||
model: opus
|
||||
---
|
||||
|
||||
Scaffold a new tool called `$ARGUMENTS` for the IronClaw agent. First, determine the tool type and then follow the appropriate path.
|
||||
Scaffold a new tool called `$ARGUMENTS` for the OptimClaw agent. First, determine the tool type and then follow the appropriate path.
|
||||
|
||||
## Step 0: Determine tool type
|
||||
|
||||
@@ -43,7 +43,7 @@ Follow this exact pattern (adjust name and description):
|
||||
name = "<name>-tool"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "<Description> tool for IronClaw (WASM component)"
|
||||
description = "<Description> tool for OptimClaw (WASM component)"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ Enter planning mode to design the implementation. The plan MUST cover:
|
||||
- Happy path (expected input produces expected output)
|
||||
- Error paths (invalid input, missing data, permission denied)
|
||||
- Edge cases (empty collections, boundary values, concurrent access)
|
||||
5. **IronClaw-specific concerns**:
|
||||
5. **OptimClaw-specific concerns**:
|
||||
- If the change touches persistence, both database backends must be updated (`postgres.rs` and `libsql_backend.rs`)
|
||||
- New `Database` trait methods need implementations in both backends
|
||||
- No `.unwrap()` or `.expect()` in production code
|
||||
@@ -80,7 +80,7 @@ After the plan is approved:
|
||||
|
||||
1. Implement each change from the plan.
|
||||
2. Write all planned tests.
|
||||
3. Run IronClaw's full quality gate:
|
||||
3. Run OptimClaw's full quality gate:
|
||||
- `cargo fmt`
|
||||
- `cargo clippy --all --benches --tests --examples --all-features` (zero warnings)
|
||||
- `cargo test --lib` (all tests pass)
|
||||
|
||||
@@ -96,7 +96,7 @@ Wait for user confirmation (unless `--fix` flag set), then proceed to Phase 3.
|
||||
|
||||
Read EVERY changed file in full (not just diff hunks). For PRs touching >20 files, prioritize: service logic > handlers > types > tests > docs. Batch reads in parallel via Agent tool.
|
||||
|
||||
### IronClaw-specific checks (always)
|
||||
### OptimClaw-specific checks (always)
|
||||
- No `.unwrap()` or `.expect()` in production code
|
||||
- Prefer `crate::` for cross-module imports (`super::` OK in tests/intra-module)
|
||||
- Error types use `thiserror`
|
||||
@@ -167,7 +167,7 @@ gh pr checkout {number}
|
||||
1. All approved review comment fixes (from Phase 2a)
|
||||
2. All approved review findings (from Phase 2b)
|
||||
|
||||
Follow IronClaw conventions:
|
||||
Follow OptimClaw conventions:
|
||||
- `thiserror` for errors
|
||||
- `crate::` imports
|
||||
- No `.unwrap()` in production
|
||||
@@ -180,7 +180,7 @@ After all fixes implemented, proceed to Phase 4.
|
||||
|
||||
## Phase 4: Quality Gate
|
||||
|
||||
Run the full IronClaw shipping checklist:
|
||||
Run the full OptimClaw shipping checklist:
|
||||
|
||||
```bash
|
||||
cargo fmt
|
||||
|
||||
@@ -60,7 +60,7 @@ Wait for user confirmation before proceeding to implementation.
|
||||
After user confirms:
|
||||
|
||||
1. Implement each fix in the plan.
|
||||
2. Run IronClaw's quality gate to verify nothing breaks:
|
||||
2. Run OptimClaw's quality gate to verify nothing breaks:
|
||||
- `cargo fmt`
|
||||
- `cargo clippy --all --benches --tests --examples --all-features`
|
||||
- `cargo test --lib`
|
||||
@@ -77,5 +77,5 @@ For each comment addressed, reply on the PR with a short message stating what wa
|
||||
- Group duplicate comments (same issue reported by multiple bots) and reply to all of them.
|
||||
- Do not make changes beyond what the review comments ask for. Stay focused.
|
||||
- If a comment suggests a change you disagree with, present your reasoning to the user during the planning phase rather than silently ignoring it.
|
||||
- Follow IronClaw conventions: no `.unwrap()` in production code, use `crate::` imports, `thiserror` errors.
|
||||
- Follow OptimClaw conventions: no `.unwrap()` in production code, use `crate::` imports, `thiserror` errors.
|
||||
- If changes touch persistence, verify both database backends are updated.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: Deep audit of the IronClaw crate for vulnerabilities, bugs, unfinished work, inconsistencies, and oversights
|
||||
description: Deep audit of the OptimClaw crate for vulnerabilities, bugs, unfinished work, inconsistencies, and oversights
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash(cargo fmt:*), Bash(cargo clippy:*), Bash(cargo test:*), Bash(cargo audit:*), Bash(git diff:*), Bash(git log:*), Bash(git show:*), Bash(wc:*), Read, Grep, Glob, Task
|
||||
argument-hint: "[path/to/crate]"
|
||||
@@ -93,7 +93,7 @@ Search for `.unwrap()`, `.expect(`, `panic!`, `unreachable!` in non-test code. F
|
||||
- Is there a code path that reaches this with None/Err?
|
||||
- Should it be replaced with proper error handling (`?`, `.ok()`, `.unwrap_or_default()`)?
|
||||
|
||||
IronClaw convention: `.unwrap()` and `.expect()` are banned in production code. Any occurrence outside `#[cfg(test)]` blocks is a **High severity** finding.
|
||||
OptimClaw convention: `.unwrap()` and `.expect()` are banned in production code. Any occurrence outside `#[cfg(test)]` blocks is a **High severity** finding.
|
||||
|
||||
### 5c. SQL and injection vectors
|
||||
|
||||
@@ -102,7 +102,7 @@ Search for string formatting used in SQL queries, shell commands, or HTML:
|
||||
- String interpolation in query construction vs parameterized queries
|
||||
- User input flowing into file paths (`Path::new`, `std::fs::`)
|
||||
|
||||
IronClaw has two database backends (PostgreSQL and libSQL). Check both for injection vectors.
|
||||
OptimClaw has two database backends (PostgreSQL and libSQL). Check both for injection vectors.
|
||||
|
||||
### 5d. Cryptographic issues
|
||||
|
||||
@@ -125,7 +125,7 @@ If the crate uses crypto:
|
||||
- Are errors swallowed silently? (`let _ = ...`, `.ok()` discarding errors that matter)
|
||||
- Do error types carry enough context to debug in production?
|
||||
- Are there error type mismatches? (returning generic `anyhow::Error` where a typed error would prevent confusion)
|
||||
- Is `thiserror` used consistently for error types (IronClaw convention)?
|
||||
- Is `thiserror` used consistently for error types (OptimClaw convention)?
|
||||
|
||||
## Step 6: Check for inconsistencies
|
||||
|
||||
@@ -156,7 +156,7 @@ Look for:
|
||||
|
||||
### 6e. Import style
|
||||
|
||||
IronClaw convention: use `crate::` imports, not `super::`. Flag any `super::` imports in non-test code.
|
||||
OptimClaw convention: use `crate::` imports, not `super::`. Flag any `super::` imports in non-test code.
|
||||
|
||||
## Step 7: Inspect for change oversights
|
||||
|
||||
@@ -172,7 +172,7 @@ IronClaw convention: use `crate::` imports, not `super::`. Flag any `super::` im
|
||||
- Are there `impl` blocks that look incomplete?
|
||||
- Are `Default` implementations sensible?
|
||||
|
||||
IronClaw key traits: `Database` (~60 methods), `Channel`, `Tool`, `LlmProvider`, `SuccessEvaluator`, `EmbeddingProvider`. If any new methods were added to `Database`, verify both `postgres.rs` and `libsql_backend.rs` implement them.
|
||||
OptimClaw key traits: `Database` (~60 methods), `Channel`, `Tool`, `LlmProvider`, `SuccessEvaluator`, `EmbeddingProvider`. If any new methods were added to `Database`, verify both `postgres.rs` and `libsql_backend.rs` implement them.
|
||||
|
||||
### 7c. Test coverage gaps
|
||||
|
||||
|
||||
@@ -49,9 +49,9 @@ If the PR touches more than 20 files, still read all of them, but process in thi
|
||||
|
||||
Go through the changes with each of these lenses. For every finding, note the file, line range, severity, and a concrete description.
|
||||
|
||||
### IronClaw-specific checks
|
||||
### OptimClaw-specific checks
|
||||
|
||||
In addition to the general lenses below, check IronClaw conventions (see CLAUDE.md):
|
||||
In addition to the general lenses below, check OptimClaw conventions (see CLAUDE.md):
|
||||
- No `.unwrap()` or `.expect()` in production code (tests are fine)
|
||||
- Use `crate::` imports, not `super::`
|
||||
- Error types use `thiserror` in `error.rs`
|
||||
|
||||
@@ -3,7 +3,7 @@ description: Run the full Rust quality gate (fmt, clippy, tests) before shipping
|
||||
allowed-tools: Bash(cargo fmt:*), Bash(cargo clippy:*), Bash(cargo test:*)
|
||||
---
|
||||
|
||||
Run the IronClaw shipping checklist. This is the mandatory quality gate before any change is considered done.
|
||||
Run the OptimClaw shipping checklist. This is the mandatory quality gate before any change is considered done.
|
||||
|
||||
## Steps
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
---
|
||||
description: Trace a data flow or bug through the IronClaw codebase end-to-end
|
||||
description: Trace a data flow or bug through the OptimClaw codebase end-to-end
|
||||
allowed-tools: Read, Glob, Grep, Bash(cargo test:*)
|
||||
argument-hint: <symptom or feature name>
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
Trace the flow of `$ARGUMENTS` through the IronClaw codebase. Your job is to map every file and function involved, identify where data transforms or could break, and report the full chain.
|
||||
Trace the flow of `$ARGUMENTS` through the OptimClaw codebase. Your job is to map every file and function involved, identify where data transforms or could break, and report the full chain.
|
||||
|
||||
## Architecture Reference
|
||||
|
||||
IronClaw has three main data flow paths. Identify which one(s) are relevant and trace through them:
|
||||
OptimClaw has three main data flow paths. Identify which one(s) are relevant and trace through them:
|
||||
|
||||
### Message Flow (user input to LLM response)
|
||||
```
|
||||
|
||||
@@ -11,8 +11,8 @@ SKILL.md files extend the agent's prompt with domain-specific instructions. Each
|
||||
|
||||
| Trust Level | Source | Tool Access |
|
||||
|-------------|--------|-------------|
|
||||
| **Trusted** | User-placed in `~/.ironclaw/skills/` or workspace `skills/` | All tools available to the agent |
|
||||
| **Installed** | Downloaded from ClawHub registry (`~/.ironclaw/installed_skills/`) | Read-only tools only (no shell, file write, HTTP) |
|
||||
| **Trusted** | User-placed in `~/.optimclaw/skills/` or workspace `skills/` | All tools available to the agent |
|
||||
| **Installed** | Downloaded from ClawHub registry (`~/.optimclaw/installed_skills/`) | Read-only tools only (no shell, file write, HTTP) |
|
||||
|
||||
## SKILL.md Format
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ paths:
|
||||
|
||||
**Keep tool-specific logic out of the main agent codebase.** The main agent provides generic infrastructure; tools are self-contained units that declare requirements through `<name>.capabilities.json` sidecar files (in dev mode: `tools-src/<name>/<name>-tool.capabilities.json`).
|
||||
|
||||
Tools can be WASM (sandboxed, credential-injected, single binary) or MCP servers (ecosystem, any language, no sandbox). Both are first-class via `ironclaw tool install`.
|
||||
Tools can be WASM (sandboxed, credential-injected, single binary) or MCP servers (ecosystem, any language, no sandbox). Both are first-class via `optimclaw tool install`.
|
||||
|
||||
See `src/tools/README.md` for full architecture, adding new tools, auth JSON examples, and WASM vs MCP decision guide.
|
||||
|
||||
|
||||
+15
-15
@@ -1,5 +1,5 @@
|
||||
# Database Configuration
|
||||
DATABASE_URL=postgres://localhost/ironclaw
|
||||
DATABASE_URL=postgres://localhost/optimclaw
|
||||
DATABASE_POOL_SIZE=10
|
||||
|
||||
# LLM Provider
|
||||
@@ -26,19 +26,19 @@ DATABASE_POOL_SIZE=10
|
||||
|
||||
# === GitHub Copilot ===
|
||||
# Uses the OAuth token from your Copilot IDE sign-in (for example
|
||||
# ~/.config/github-copilot/apps.json on Linux/macOS), or run `ironclaw onboard`
|
||||
# ~/.config/github-copilot/apps.json on Linux/macOS), or run `optimclaw onboard`
|
||||
# and choose the GitHub device login flow.
|
||||
# LLM_BACKEND=github_copilot
|
||||
# GITHUB_COPILOT_TOKEN=gho_...
|
||||
# GITHUB_COPILOT_MODEL=gpt-4o
|
||||
# IronClaw injects standard VS Code Copilot headers automatically.
|
||||
# OptimClaw injects standard VS Code Copilot headers automatically.
|
||||
# Optional advanced headers for custom overrides:
|
||||
# GITHUB_COPILOT_EXTRA_HEADERS=Copilot-Integration-Id:vscode-chat
|
||||
|
||||
# === NEAR AI (Chat Completions API) ===
|
||||
# Two auth modes:
|
||||
# 1. Session token (default): Uses browser OAuth (GitHub/Google) on first run.
|
||||
# Session token stored in ~/.ironclaw/session.json automatically.
|
||||
# Session token stored in ~/.optimclaw/session.json automatically.
|
||||
# Base URL defaults to https://private.near.ai
|
||||
# 2. API key: Set NEARAI_API_KEY to use API key auth from cloud.near.ai.
|
||||
# Base URL defaults to https://cloud-api.near.ai
|
||||
@@ -46,7 +46,7 @@ NEARAI_MODEL=Qwen/Qwen3.5-122B-A10B
|
||||
NEARAI_BASE_URL=https://private.near.ai
|
||||
NEARAI_AUTH_URL=https://private.near.ai
|
||||
# NEARAI_SESSION_TOKEN=sess_... # hosting providers: set this
|
||||
# NEARAI_SESSION_PATH=~/.ironclaw/session.json # optional, default shown
|
||||
# NEARAI_SESSION_PATH=~/.optimclaw/session.json # optional, default shown
|
||||
# NEARAI_API_KEY=... # API key from cloud.near.ai
|
||||
|
||||
# Local LLM Providers (Ollama, LM Studio, vLLM, LiteLLM)
|
||||
@@ -63,7 +63,7 @@ NEARAI_AUTH_URL=https://private.near.ai
|
||||
# LLM_API_KEY=sk-... # optional for local servers
|
||||
# Custom HTTP headers for OpenAI-compatible providers
|
||||
# Format: comma-separated key:value pairs
|
||||
# LLM_EXTRA_HEADERS=HTTP-Referer:https://github.com/nearai/ironclaw,X-Title:ironclaw
|
||||
# LLM_EXTRA_HEADERS=HTTP-Referer:https://github.com/nearai/optimclaw,X-Title:optimclaw
|
||||
|
||||
# === OpenRouter (300+ models via OpenAI-compatible) ===
|
||||
# LLM_MODEL=anthropic/claude-sonnet-4 # see openrouter.ai/models for IDs
|
||||
@@ -145,7 +145,7 @@ HTTP_HOST=0.0.0.0
|
||||
HTTP_PORT=8080
|
||||
HTTP_WEBHOOK_SECRET=your-webhook-secret
|
||||
# Webhook authentication uses HMAC-SHA256 signature verification.
|
||||
# Callers must send an X-IronClaw-Signature header with format: sha256=<hex_digest>
|
||||
# Callers must send an X-OptimClaw-Signature header with format: sha256=<hex_digest>
|
||||
# where the digest is HMAC-SHA256(HTTP_WEBHOOK_SECRET, raw_request_body) in lowercase hex.
|
||||
#
|
||||
# Example (bash):
|
||||
@@ -153,7 +153,7 @@ HTTP_WEBHOOK_SECRET=your-webhook-secret
|
||||
# SIG=$(echo -n "$BODY" | openssl dgst -sha256 -hmac "$HTTP_WEBHOOK_SECRET" | cut -d' ' -f2)
|
||||
# curl -X POST http://localhost:8080/webhook \
|
||||
# -H "Content-Type: application/json" \
|
||||
# -H "X-IronClaw-Signature: sha256=$SIG" \
|
||||
# -H "X-OptimClaw-Signature: sha256=$SIG" \
|
||||
# -d "$BODY"
|
||||
#
|
||||
# DEPRECATED: Passing "secret" in the JSON body still works but will be removed in a future release.
|
||||
@@ -170,7 +170,7 @@ HTTP_WEBHOOK_SECRET=your-webhook-secret
|
||||
# SIGNAL_IGNORE_STORIES=true
|
||||
|
||||
# Agent Settings
|
||||
AGENT_NAME=ironclaw
|
||||
AGENT_NAME=optimclaw
|
||||
AGENT_MAX_PARALLEL_JOBS=5
|
||||
AGENT_JOB_TIMEOUT_SECS=3600
|
||||
AGENT_STUCK_THRESHOLD_SECS=300
|
||||
@@ -205,7 +205,7 @@ HEARTBEAT_NOTIFY_USER=default
|
||||
# # commands directly on the host. Without this
|
||||
# # set to "true", full_access is downgraded to
|
||||
# # workspace_write.
|
||||
# SANDBOX_IMAGE=ironclaw-worker:latest
|
||||
# SANDBOX_IMAGE=optimclaw-worker:latest
|
||||
# SANDBOX_TIMEOUT_SECS=120
|
||||
# SANDBOX_MEMORY_LIMIT_MB=2048
|
||||
|
||||
@@ -214,11 +214,11 @@ SAFETY_MAX_OUTPUT_LENGTH=100000
|
||||
SAFETY_INJECTION_CHECK_ENABLED=true
|
||||
|
||||
# Restart Feature (Docker containers only)
|
||||
# Set IRONCLAW_IN_DOCKER=true in the container entrypoint to enable the restart feature.
|
||||
# Set OPTIMCLAW_IN_DOCKER=true in the container entrypoint to enable the restart feature.
|
||||
# Without this, the restart tool and /restart command will be disabled.
|
||||
# IRONCLAW_IN_DOCKER=false
|
||||
# IRONCLAW_RESTART_DELAY=5 # default wait before exit (seconds, range: 1-30)
|
||||
# IRONCLAW_MAX_FAILURES=10 # max consecutive failures before container exits
|
||||
# OPTIMCLAW_IN_DOCKER=false
|
||||
# OPTIMCLAW_RESTART_DELAY=5 # default wait before exit (seconds, range: 1-30)
|
||||
# OPTIMCLAW_MAX_FAILURES=10 # max consecutive failures before container exits
|
||||
|
||||
# Logging
|
||||
RUST_LOG=ironclaw=debug,tower_http=debug
|
||||
RUST_LOG=optimclaw=debug,tower_http=debug
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
## Change Type
|
||||
|
||||
<!-- Check one -->
|
||||
<!-- Check all that apply. Refactor-only PRs are for core team or maintainer-requested work. -->
|
||||
|
||||
- [ ] Bug fix
|
||||
- [ ] New feature
|
||||
@@ -18,16 +18,19 @@
|
||||
|
||||
## Linked Issue
|
||||
|
||||
<!-- Closes #N, or "None" -->
|
||||
<!-- Closes #N, Fixes #N, Related #N, or "None". New feature PRs must link an approved issue. -->
|
||||
|
||||
## Validation
|
||||
|
||||
<!-- How did you verify this works? -->
|
||||
|
||||
- [ ] `cargo fmt`
|
||||
- [ ] `cargo clippy --all --benches --tests --examples --all-features`
|
||||
- [ ] `cargo fmt --all -- --check`
|
||||
- [ ] `cargo clippy --all --benches --tests --examples --all-features -- -D warnings`
|
||||
- [ ] `cargo build`
|
||||
- [ ] Relevant tests pass: <!-- list specific tests -->
|
||||
- [ ] `cargo test --features integration` if database-backed or integration behavior changed
|
||||
- [ ] Manual testing: <!-- describe what you tested -->
|
||||
- [ ] If a coding agent was used and supports it, `review-pr` or `pr-shepherd --fix` was run before requesting review
|
||||
|
||||
## Security Impact
|
||||
|
||||
@@ -45,6 +48,10 @@
|
||||
|
||||
<!-- How to revert if this causes problems? For Track C changes, this is mandatory. -->
|
||||
|
||||
## Review Follow-Through
|
||||
|
||||
<!-- Review conversations are author-owned. Summarize any known follow-up or areas where reviewer judgment is still needed. -->
|
||||
|
||||
---
|
||||
|
||||
**Review track**: <!-- A (docs/tests/chore) | B (feature/refactor) | C (security/runtime/DB/CI) -->
|
||||
**Review track**: <!-- A (docs/tests/chore) | B (feature/maintainer-requested refactor) | C (security/runtime/DB/CI) -->
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
allowed_bots: "ironclaw-ci[bot]"
|
||||
allowed_bots: "optimclaw-ci[bot]"
|
||||
claude_args: "--max-turns 50 --model claude-haiku-4-5-20251001 --allowedTools 'Read,Glob,Grep,Agent,Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr list:*),Bash(gh issue view:*),Bash(gh issue list:*),Bash(gh search:*),Bash(git blame:*),Bash(git log:*),Bash(git diff:*)'"
|
||||
prompt: |
|
||||
Code review this pull request. Follow these steps precisely:
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
# What it does:
|
||||
# - Runs unit and integration tests with coverage instrumentation
|
||||
# - Runs E2E tests with coverage instrumentation
|
||||
# - Uploads coverage reports to Codecov (https://codecov.io/gh/nearai/ironclaw)
|
||||
# - Uploads coverage reports to Codecov (https://codecov.io/gh/nearai/optimclaw)
|
||||
#
|
||||
# Viewing coverage reports:
|
||||
# - PRs automatically get coverage comments showing changes in coverage
|
||||
# - Visit https://codecov.io/gh/nearai/ironclaw for detailed coverage reports
|
||||
# - Visit https://codecov.io/gh/nearai/optimclaw for detailed coverage reports
|
||||
# - Coverage reports are generated for three configurations:
|
||||
# 1. all-features: Full feature set
|
||||
# 2. default: Default features
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
env:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: ironclaw_test
|
||||
POSTGRES_DB: optimclaw_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
@@ -103,11 +103,11 @@ jobs:
|
||||
PGHOST: localhost
|
||||
PGUSER: postgres
|
||||
PGPASSWORD: postgres
|
||||
PGDATABASE: ironclaw_test
|
||||
PGDATABASE: optimclaw_test
|
||||
|
||||
- name: Set DATABASE_URL for postgres configs
|
||||
if: matrix.has_postgres
|
||||
run: echo "DATABASE_URL=postgres://postgres:postgres@localhost/ironclaw_test" >> "$GITHUB_ENV"
|
||||
run: echo "DATABASE_URL=postgres://postgres:postgres@localhost/optimclaw_test" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Generate coverage
|
||||
run: cargo llvm-cov ${{ matrix.flags }} --workspace --lcov --output-path lcov.info
|
||||
@@ -176,7 +176,7 @@ jobs:
|
||||
run: |
|
||||
pytest tests/e2e/ -v --timeout=120
|
||||
env:
|
||||
RUST_LOG: ironclaw=info
|
||||
RUST_LOG: optimclaw=info
|
||||
RUST_BACKTRACE: "1"
|
||||
|
||||
- name: Verify profraw files exist
|
||||
|
||||
@@ -14,7 +14,7 @@ on:
|
||||
jobs:
|
||||
# ── Step 1: compile once ──────────────────────────────────────────────────
|
||||
build:
|
||||
name: Build ironclaw (libsql)
|
||||
name: Build optimclaw (libsql)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
@@ -35,8 +35,8 @@ jobs:
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ironclaw-e2e-binary
|
||||
path: target/debug/ironclaw
|
||||
name: optimclaw-e2e-binary
|
||||
path: target/debug/optimclaw
|
||||
retention-days: 1
|
||||
|
||||
# ── Step 2: run test slices in parallel ───────────────────────────────────
|
||||
@@ -63,11 +63,11 @@ jobs:
|
||||
- name: Download binary
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ironclaw-e2e-binary
|
||||
name: optimclaw-e2e-binary
|
||||
path: target/debug/
|
||||
|
||||
- name: Make binary executable
|
||||
run: chmod +x target/debug/ironclaw
|
||||
run: chmod +x target/debug/optimclaw
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
"src/agent/self_repair.rs"
|
||||
"src/agent/agentic_loop.rs"
|
||||
"src/tools/execute.rs"
|
||||
"crates/ironclaw_safety/src/"
|
||||
"crates/optimclaw_safety/src/"
|
||||
)
|
||||
|
||||
for pattern in "${HIGH_RISK_PATTERNS[@]}"; do
|
||||
|
||||
@@ -166,7 +166,7 @@ jobs:
|
||||
continue
|
||||
fi
|
||||
name=$(echo "$filename" | sed "s/^${kind}-//" | sed 's/-[0-9].*-wasm32-wasip2\.tar\.gz$//')
|
||||
url="https://github.com/nearai/ironclaw/releases/download/${RELEASE_TAG}/${filename}"
|
||||
url="https://github.com/nearai/optimclaw/releases/download/${RELEASE_TAG}/${filename}"
|
||||
|
||||
manifest="registry/${kind}s/${name}.json"
|
||||
if [ -f "$manifest" ]; then
|
||||
@@ -496,7 +496,7 @@ jobs:
|
||||
continue
|
||||
fi
|
||||
name=$(echo "$filename" | sed "s/^${kind}-//" | sed 's/-[0-9].*-wasm32-wasip2\.tar\.gz$//')
|
||||
url="https://github.com/nearai/ironclaw/releases/download/${RELEASE_TAG}/${filename}"
|
||||
url="https://github.com/nearai/optimclaw/releases/download/${RELEASE_TAG}/${filename}"
|
||||
|
||||
manifest="registry/${kind}s/${name}.json"
|
||||
if [ -f "$manifest" ]; then
|
||||
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
- name: Build Docker image
|
||||
run: docker build -t ironclaw-test:ci .
|
||||
run: docker build -t optimclaw-test:ci .
|
||||
|
||||
version-check:
|
||||
name: Version Bump Check
|
||||
|
||||
+520
-520
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
# IronClaw Development Guide
|
||||
# OptimClaw Development Guide
|
||||
|
||||
**IronClaw** is a secure personal AI assistant — user-first security, self-expanding tools, defense in depth, multi-channel access with proactive background execution.
|
||||
**OptimClaw** is a secure personal AI assistant — user-first security, self-expanding tools, defense in depth, multi-channel access with proactive background execution.
|
||||
|
||||
## Build & Test
|
||||
|
||||
@@ -9,7 +9,7 @@ cargo fmt # format
|
||||
cargo clippy --all --benches --tests --examples --all-features # lint (zero warnings)
|
||||
cargo test # unit tests
|
||||
cargo test --features integration # + PostgreSQL tests
|
||||
RUST_LOG=ironclaw=debug cargo run # run with logging
|
||||
RUST_LOG=optimclaw=debug cargo run # run with logging
|
||||
```
|
||||
|
||||
E2E tests: see `tests/e2e/CLAUDE.md`.
|
||||
@@ -35,20 +35,20 @@ All I/O is async with tokio. Use `Arc<T>` for shared state, `RwLock` for concurr
|
||||
|
||||
## Extracted Crates
|
||||
|
||||
Safety logic lives in `crates/ironclaw_safety/`. The `src/safety/mod.rs` shim re-exports everything for backward compatibility, but **new code should import from `ironclaw_safety` directly** (e.g. `use ironclaw_safety::SafetyLayer`). When touching a file that still uses `crate::safety::*`, migrate its imports to `ironclaw_safety::*`.
|
||||
Safety logic lives in `crates/optimclaw_safety/`. The `src/safety/mod.rs` shim re-exports everything for backward compatibility, but **new code should import from `optimclaw_safety` directly** (e.g. `use optimclaw_safety::SafetyLayer`). When touching a file that still uses `crate::safety::*`, migrate its imports to `optimclaw_safety::*`.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
crates/
|
||||
└── ironclaw_safety/ # Extracted: prompt injection, validation, leak detection, policy
|
||||
└── optimclaw_safety/ # Extracted: prompt injection, validation, leak detection, policy
|
||||
|
||||
src/
|
||||
├── lib.rs # Library root, module declarations
|
||||
├── main.rs # Entry point, CLI args, startup
|
||||
├── app.rs # App startup orchestration (channel wiring, DB init)
|
||||
├── bootstrap.rs # Base directory resolution (~/.ironclaw), early .env loading
|
||||
├── settings.rs # User settings persistence (~/.ironclaw/settings.json)
|
||||
├── bootstrap.rs # Base directory resolution (~/.optimclaw), early .env loading
|
||||
├── settings.rs # User settings persistence (~/.optimclaw/settings.json)
|
||||
├── service.rs # OS service management (launchd/systemd daemon install)
|
||||
├── tracing_fmt.rs # Custom tracing formatter
|
||||
├── util.rs # Shared utilities
|
||||
@@ -111,7 +111,7 @@ src/
|
||||
│ ├── claude_bridge.rs # Claude Code bridge (spawns claude CLI)
|
||||
│ └── proxy_llm.rs # LlmProvider that proxies through orchestrator
|
||||
│
|
||||
├── safety/ # Re-export shim for crates/ironclaw_safety (see Extracted Crates)
|
||||
├── safety/ # Re-export shim for crates/optimclaw_safety (see Extracted Crates)
|
||||
│
|
||||
├── llm/ # Multi-provider LLM integration — see src/llm/CLAUDE.md
|
||||
│
|
||||
@@ -206,7 +206,7 @@ Pending -> InProgress -> Completed -> Submitted -> Accepted
|
||||
|
||||
SKILL.md files extend the agent's prompt with domain-specific instructions. See `.claude/rules/skills.md` for full details.
|
||||
|
||||
- **Trust model**: Trusted (user-placed in `~/.ironclaw/skills/` or workspace `skills/`, full tool access) vs Installed (registry, read-only tools)
|
||||
- **Trust model**: Trusted (user-placed in `~/.optimclaw/skills/` or workspace `skills/`, full tool access) vs Installed (registry, read-only tools)
|
||||
- **Selection pipeline**: gating (check bin/env/config requirements) -> scoring (keywords/patterns/tags) -> budget (fit within `SKILLS_MAX_TOKENS`) -> attenuation (trust-based tool ceiling)
|
||||
- **Skill tools**: `skill_list`, `skill_search`, `skill_install`, `skill_remove`
|
||||
|
||||
@@ -228,9 +228,9 @@ Persistent memory with hybrid search (FTS + vector via RRF). Four tools: `memory
|
||||
## Debugging
|
||||
|
||||
```bash
|
||||
RUST_LOG=ironclaw=trace cargo run # verbose
|
||||
RUST_LOG=ironclaw::agent=debug cargo run # agent module only
|
||||
RUST_LOG=ironclaw=debug,tower_http=debug cargo run # + HTTP request logging
|
||||
RUST_LOG=optimclaw=trace cargo run # verbose
|
||||
RUST_LOG=optimclaw::agent=debug cargo run # agent module only
|
||||
RUST_LOG=optimclaw=debug,tower_http=debug cargo run # + HTTP request logging
|
||||
```
|
||||
|
||||
## Current Limitations
|
||||
|
||||
+79
-4
@@ -3,13 +3,49 @@
|
||||
## Getting Started
|
||||
|
||||
```bash
|
||||
git clone https://github.com/nearai/ironclaw.git
|
||||
cd ironclaw
|
||||
git clone https://github.com/nearai/optimclaw.git
|
||||
cd optimclaw
|
||||
./scripts/dev-setup.sh
|
||||
```
|
||||
|
||||
This installs the Rust toolchain, WASM targets, git hooks, and runs initial checks.
|
||||
|
||||
## How to Contribute
|
||||
|
||||
- Bug fixes, docs improvements, and focused cleanup tied to a concrete problem are welcome.
|
||||
- Search existing issues and PRs before opening a new one to avoid duplicates.
|
||||
- Keep changes scoped. One bug, one feature, or one documentation improvement per PR.
|
||||
|
||||
### Creating Issues
|
||||
|
||||
Open an issue when you are reporting a bug, proposing a feature, or documenting a gap in behavior.
|
||||
|
||||
For bug reports, include:
|
||||
|
||||
- What you expected to happen
|
||||
- What actually happened
|
||||
- Clear reproduction steps
|
||||
- Relevant logs, screenshots, or error output
|
||||
- Environment details when they matter (OS, database backend, feature flags, commit/branch)
|
||||
|
||||
For feature requests:
|
||||
|
||||
- Open an issue first before writing code
|
||||
- Explain the problem being solved, not just the implementation idea
|
||||
- Wait for maintainer feedback before investing in a large PR
|
||||
|
||||
We require an issue for new features so maintainers can prioritize the work and confirm it fits the roadmap before anyone spends time implementing it.
|
||||
|
||||
### Fixing Bugs
|
||||
|
||||
- Small, targeted bug-fix PRs are welcome
|
||||
- If there is already an issue, link it in your PR
|
||||
- If the bug is non-trivial, security-sensitive, or changes behavior across subsystems, open or confirm an issue first so the approach can be aligned before implementation
|
||||
|
||||
### Refactor-Only PRs
|
||||
|
||||
Refactor-only PRs are not accepted from contributors outside the core team. If a refactor is necessary to land a bug fix or approved feature, keep it minimal and clearly tied to that change.
|
||||
|
||||
## Development Workflow
|
||||
|
||||
```bash
|
||||
@@ -19,6 +55,45 @@ cargo test # unit tests
|
||||
cargo test --features integration # + PostgreSQL tests
|
||||
```
|
||||
|
||||
These commands are for day-to-day iteration while you are developing locally. The pre-submission checks below are intentionally stricter and use CI-style flags so you can catch formatting drift and clippy warnings before requesting review.
|
||||
|
||||
## Before You Open a PR
|
||||
|
||||
Run the local validation checks required before requesting a review. These are stricter than the commands for iterative development:
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --all --benches --tests --examples --all-features -- -D warnings
|
||||
cargo build
|
||||
cargo test
|
||||
```
|
||||
|
||||
Also run this when your change touches database-backed or integration behavior:
|
||||
|
||||
```bash
|
||||
cargo test --features integration
|
||||
```
|
||||
|
||||
Before asking for review:
|
||||
|
||||
- Build and exercise the changed path locally, not just the narrowest unit test
|
||||
- Keep the PR focused and avoid mixing unrelated concerns
|
||||
- Fill out the PR template with a clear summary, validation notes, and impact assessment
|
||||
- If your change affects tracked behavior, update `FEATURE_PARITY.md` in the same branch
|
||||
- If onboarding or setup behavior changes, update the relevant setup docs in the same branch
|
||||
- If you are using a coding agent and it supports them, run `review-pr` or `pr-shepherd --fix` before opening or updating the PR
|
||||
- `codex review --base origin/main` is also encouraged before requesting review
|
||||
|
||||
## Review Follow-Through
|
||||
|
||||
Review conversations are author-owned.
|
||||
|
||||
- Address each review comment with a code change or a clear explanation
|
||||
- Resolve conversations you have handled; leave them open only when reviewer judgment is still needed
|
||||
- Do not leave review cleanup for maintainers when the follow-through belongs to the author
|
||||
|
||||
If a PR is stale for more than 48 hours after review feedback is posted, maintainers may take over the follow-up work and land the changes needed to accomplish the original PR or issue intent.
|
||||
|
||||
## Code Style
|
||||
|
||||
- Zero clippy warnings policy
|
||||
@@ -46,14 +121,14 @@ All PRs follow a risk-based review process:
|
||||
| Track | Scope | Requirements |
|
||||
|-------|-------|-------------|
|
||||
| **A** | Docs, tests, chore, dependency bumps | 1 approval + CI green |
|
||||
| **B** | Features, refactors, new tools/channels | 1 approval + CI green + test evidence |
|
||||
| **B** | Features, maintainer-requested refactors, new tools/channels | 1 approval + CI green + test evidence |
|
||||
| **C** | Security (`src/safety/`, `src/secrets/`), runtime (`src/agent/`, `src/worker/`), database schema, CI workflows | 2 approvals + rollback plan documented |
|
||||
|
||||
Select the appropriate track in the PR template based on what your changes touch.
|
||||
|
||||
## Database Changes
|
||||
|
||||
IronClaw uses dual-backend persistence (PostgreSQL + libSQL). All new persistence features must support both backends. See `src/db/CLAUDE.md`.
|
||||
OptimClaw uses dual-backend persistence (PostgreSQL + libSQL). All new persistence features must support both backends. See `src/db/CLAUDE.md`.
|
||||
|
||||
## Adding Dependencies
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# IronClaw Coverage Plan: 63.3% to 95%
|
||||
# OptimClaw Coverage Plan: 63.3% to 95%
|
||||
|
||||
> Generated 2025-03-06 from [Codecov](https://app.codecov.io/gh/nearai/ironclaw/tree/main/src)
|
||||
> Generated 2025-03-06 from [Codecov](https://app.codecov.io/gh/nearai/optimclaw/tree/main/src)
|
||||
|
||||
## Current State
|
||||
|
||||
|
||||
Generated
+235
-247
@@ -121,15 +121,6 @@ version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
|
||||
|
||||
[[package]]
|
||||
name = "ansi_term"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "0.6.21"
|
||||
@@ -401,17 +392,6 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "atty"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
|
||||
dependencies = [
|
||||
"hermit-abi 0.1.19",
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.0"
|
||||
@@ -961,29 +941,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.59.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bd2a9a458e8f4304c52c43ebb0cfbd520289f8379a52e329a38afda99bf8eb8"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"clap 2.34.0",
|
||||
"env_logger",
|
||||
"lazy_static",
|
||||
"lazycell",
|
||||
"log",
|
||||
"peeking_take_while",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"rustc-hash 1.1.0",
|
||||
"shlex",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.66.1"
|
||||
@@ -1403,21 +1360,6 @@ dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "2.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
|
||||
dependencies = [
|
||||
"ansi_term",
|
||||
"atty",
|
||||
"bitflags 1.3.2",
|
||||
"strsim 0.8.0",
|
||||
"textwrap",
|
||||
"unicode-width 0.1.14",
|
||||
"vec_map",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.60"
|
||||
@@ -1437,7 +1379,7 @@ dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim 0.11.1",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1446,7 +1388,7 @@ version = "4.5.66"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c757a3b7e39161a4e56f9365141ada2a6c915a8622c408ab6bb4b5d047371031"
|
||||
dependencies = [
|
||||
"clap 4.5.60",
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1755,7 +1697,7 @@ dependencies = [
|
||||
"anes",
|
||||
"cast",
|
||||
"ciborium",
|
||||
"clap 4.5.60",
|
||||
"clap",
|
||||
"criterion-plot",
|
||||
"is-terminal",
|
||||
"itertools 0.10.5",
|
||||
@@ -1998,7 +1940,7 @@ dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim 0.11.1",
|
||||
"strsim",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
@@ -2368,19 +2310,6 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"humantime",
|
||||
"log",
|
||||
"regex",
|
||||
"termcolor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -2919,15 +2848,6 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.1.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.2"
|
||||
@@ -2967,6 +2887,17 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hostname"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "html-escape"
|
||||
version = "0.2.13"
|
||||
@@ -3088,12 +3019,6 @@ version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "humantime"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "0.14.32"
|
||||
@@ -3474,126 +3399,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironclaw"
|
||||
version = "0.22.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
"aho-corasick",
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"aws-config",
|
||||
"aws-sdk-bedrockruntime",
|
||||
"aws-smithy-types",
|
||||
"axum 0.8.8",
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"bollard",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"clap 4.5.60",
|
||||
"clap_complete",
|
||||
"criterion",
|
||||
"cron",
|
||||
"crossterm",
|
||||
"deadpool-postgres",
|
||||
"dirs 6.0.0",
|
||||
"dotenvy",
|
||||
"ed25519-dalek",
|
||||
"eventsource-stream",
|
||||
"flate2",
|
||||
"fs4",
|
||||
"futures",
|
||||
"hex",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"html-to-markdown-rs",
|
||||
"http-body-util",
|
||||
"hyper 1.8.1",
|
||||
"hyper-util",
|
||||
"iana-time-zone",
|
||||
"insta",
|
||||
"ironclaw_common",
|
||||
"ironclaw_safety",
|
||||
"json5",
|
||||
"libsql",
|
||||
"lru",
|
||||
"mime_guess",
|
||||
"open",
|
||||
"pdf-extract",
|
||||
"pgvector",
|
||||
"postgres-types",
|
||||
"pretty_assertions",
|
||||
"rand 0.8.5",
|
||||
"readabilityrs",
|
||||
"refinery",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"rig-core",
|
||||
"rust_decimal",
|
||||
"rust_decimal_macros",
|
||||
"rustls 0.23.37",
|
||||
"rustls-native-certs 0.8.3",
|
||||
"rustyline",
|
||||
"secrecy",
|
||||
"secret-service",
|
||||
"security-framework 3.7.0",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yml",
|
||||
"sha2",
|
||||
"silk-rs",
|
||||
"subtle",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"termimad",
|
||||
"testcontainers-modules",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-postgres",
|
||||
"tokio-postgres-rustls",
|
||||
"tokio-stream",
|
||||
"tokio-test",
|
||||
"tokio-tungstenite 0.26.2",
|
||||
"toml",
|
||||
"tower 0.5.3",
|
||||
"tower-http 0.6.8",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tracing-test",
|
||||
"url",
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
"wasmparser 0.220.1",
|
||||
"wasmtime",
|
||||
"wasmtime-wasi",
|
||||
"zbus",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironclaw_common"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironclaw_safety"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-docker"
|
||||
version = "0.2.0"
|
||||
@@ -3609,7 +3414,7 @@ version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi 0.5.2",
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -3845,7 +3650,7 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f2a50a585a1184a43621a9133b7702ba5cb7a87ca5e704056b19d8005de6faf"
|
||||
dependencies = [
|
||||
"bindgen 0.66.1",
|
||||
"bindgen",
|
||||
"cc",
|
||||
]
|
||||
|
||||
@@ -4319,7 +4124,7 @@ version = "1.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
|
||||
dependencies = [
|
||||
"hermit-abi 0.5.2",
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -4409,6 +4214,132 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "optimclaw"
|
||||
version = "0.22.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"aho-corasick",
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"aws-config",
|
||||
"aws-sdk-bedrockruntime",
|
||||
"aws-smithy-types",
|
||||
"axum 0.8.8",
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"bollard",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"criterion",
|
||||
"cron",
|
||||
"crossterm",
|
||||
"deadpool-postgres",
|
||||
"dirs 6.0.0",
|
||||
"dotenvy",
|
||||
"ed25519-dalek",
|
||||
"eventsource-stream",
|
||||
"flate2",
|
||||
"fs4",
|
||||
"futures",
|
||||
"hex",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"hostname",
|
||||
"html-to-markdown-rs",
|
||||
"http-body-util",
|
||||
"hyper 1.8.1",
|
||||
"hyper-util",
|
||||
"iana-time-zone",
|
||||
"insta",
|
||||
"json5",
|
||||
"libsql",
|
||||
"lru",
|
||||
"mime_guess",
|
||||
"open",
|
||||
"optimclaw_common",
|
||||
"optimclaw_safety",
|
||||
"pdf-extract",
|
||||
"pgvector",
|
||||
"postgres-types",
|
||||
"pqcrypto-kyber",
|
||||
"pqcrypto-traits",
|
||||
"pretty_assertions",
|
||||
"pty-process",
|
||||
"quinn",
|
||||
"rand 0.8.5",
|
||||
"rcgen",
|
||||
"readabilityrs",
|
||||
"refinery",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"rig-core",
|
||||
"rust_decimal",
|
||||
"rust_decimal_macros",
|
||||
"rustls 0.23.37",
|
||||
"rustls-native-certs 0.8.3",
|
||||
"rustyline",
|
||||
"secrecy",
|
||||
"secret-service",
|
||||
"security-framework 3.7.0",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yml",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"sys-info",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"termimad",
|
||||
"testcontainers-modules",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-postgres",
|
||||
"tokio-postgres-rustls",
|
||||
"tokio-stream",
|
||||
"tokio-test",
|
||||
"tokio-tungstenite 0.26.2",
|
||||
"toml",
|
||||
"tower 0.5.3",
|
||||
"tower-http 0.6.8",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tracing-test",
|
||||
"url",
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
"wasmparser 0.220.1",
|
||||
"wasmtime",
|
||||
"wasmtime-wasi",
|
||||
"webpki-roots 0.26.11",
|
||||
"zbus",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "optimclaw_common"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "optimclaw_safety"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
@@ -4527,6 +4458,16 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -4797,7 +4738,7 @@ checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"concurrent-queue",
|
||||
"hermit-abi 0.5.2",
|
||||
"hermit-abi",
|
||||
"pin-project-lite",
|
||||
"rustix 1.1.4",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -4896,6 +4837,37 @@ dependencies = [
|
||||
"zerocopy 0.8.42",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pqcrypto-internals"
|
||||
version = "0.2.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4a326caf27cbf2ac291ca7fd56300497ba9e76a8cc6a7d95b7a18b57f22b61d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"dunce",
|
||||
"getrandom 0.3.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pqcrypto-kyber"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15c00293cf898859d0c771455388054fd69ab712263c73fdc7f287a39b1ba000"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"glob",
|
||||
"libc",
|
||||
"pqcrypto-internals",
|
||||
"pqcrypto-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pqcrypto-traits"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94e851c7654eed9e68d7d27164c454961a616cf8c203d500607ef22c737b51bb"
|
||||
|
||||
[[package]]
|
||||
name = "precomputed-hash"
|
||||
version = "0.1.1"
|
||||
@@ -4993,6 +4965,16 @@ dependencies = [
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pty-process"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71cec9e2670207c5ebb9e477763c74436af3b9091dd550b9fb3c1bec7f3ea266"
|
||||
dependencies = [
|
||||
"rustix 1.1.4",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulley-interpreter"
|
||||
version = "28.0.1"
|
||||
@@ -5181,6 +5163,19 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rcgen"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2"
|
||||
dependencies = [
|
||||
"pem",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"time",
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "readabilityrs"
|
||||
version = "0.1.2"
|
||||
@@ -6195,18 +6190,6 @@ dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "silk-rs"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "014e6619f35a385ff848570e73a0b8c36b31031e0ee11cac70192b50097b1cfe"
|
||||
dependencies = [
|
||||
"bindgen 0.59.2",
|
||||
"bytes",
|
||||
"cc",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.8"
|
||||
@@ -6335,12 +6318,6 @@ dependencies = [
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
@@ -6424,6 +6401,16 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sys-info"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b3a0d0aba8bf96a0e1ddfdc352fc53b3df7f39318c71854910c3c4b024ae52c"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration"
|
||||
version = "0.7.0"
|
||||
@@ -6581,15 +6568,6 @@ dependencies = [
|
||||
"testcontainers",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textwrap"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
|
||||
dependencies = [
|
||||
"unicode-width 0.1.14",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.69"
|
||||
@@ -6892,7 +6870,11 @@ checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
"rustls 0.23.37",
|
||||
"rustls-native-certs 0.8.3",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls 0.26.4",
|
||||
"tungstenite 0.26.2",
|
||||
]
|
||||
|
||||
@@ -7106,6 +7088,7 @@ dependencies = [
|
||||
"futures-util",
|
||||
"http 1.4.0",
|
||||
"http-body 1.0.1",
|
||||
"http-body-util",
|
||||
"iri-string",
|
||||
"pin-project-lite",
|
||||
"tower 0.5.3",
|
||||
@@ -7252,6 +7235,8 @@ dependencies = [
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.9.2",
|
||||
"rustls 0.23.37",
|
||||
"rustls-pki-types",
|
||||
"sha1",
|
||||
"thiserror 2.0.18",
|
||||
"utf-8",
|
||||
@@ -7456,12 +7441,6 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "vec_map"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -8682,6 +8661,15 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
|
||||
|
||||
[[package]]
|
||||
name = "yasna"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
|
||||
dependencies = [
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.1"
|
||||
|
||||
+25
-13
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = [".", "crates/ironclaw_common", "crates/ironclaw_safety"]
|
||||
members = [".", "crates/optimclaw_common", "crates/optimclaw_safety"]
|
||||
exclude = [
|
||||
"channels-src/discord",
|
||||
"channels-src/telegram",
|
||||
@@ -15,19 +15,19 @@ exclude = [
|
||||
"tools-src/slack",
|
||||
"tools-src/telegram",
|
||||
"fuzz",
|
||||
"crates/ironclaw_safety/fuzz",
|
||||
"crates/optimclaw_safety/fuzz",
|
||||
]
|
||||
|
||||
[package]
|
||||
name = "ironclaw"
|
||||
name = "optimclaw"
|
||||
version = "0.22.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.92"
|
||||
description = "Secure personal AI assistant that protects your data and expands its capabilities on the fly"
|
||||
authors = ["NEAR AI <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
homepage = "https://github.com/nearai/ironclaw"
|
||||
repository = "https://github.com/nearai/ironclaw"
|
||||
homepage = "https://github.com/nearai/optimclaw"
|
||||
repository = "https://github.com/nearai/optimclaw"
|
||||
|
||||
[package.metadata.wix]
|
||||
upgrade-guid = "D0156E61-BA37-451E-8AB9-1A2ECCCFA48F"
|
||||
@@ -40,6 +40,7 @@ eula = false
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-stream = { version = "0.1", features = ["sync"] }
|
||||
futures = "0.3"
|
||||
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-native-roots"] }
|
||||
eventsource-stream = "0.2"
|
||||
|
||||
# HTTP client
|
||||
@@ -57,6 +58,7 @@ refinery = { version = "0.8", features = ["tokio-postgres"], optional = true }
|
||||
tokio-postgres-rustls = { version = "0.13", optional = true }
|
||||
rustls = { version = "0.23", optional = true, default-features = false }
|
||||
rustls-native-certs = { version = "0.8", optional = true }
|
||||
webpki-roots = { version = "0.26", optional = true }
|
||||
|
||||
# Database - libSQL/Turso (optional embedded database)
|
||||
libsql = { version = "0.6", optional = true, default-features = false, features = ["core", "replication", "remote", "tls"] }
|
||||
@@ -95,16 +97,16 @@ termimad = "0.34"
|
||||
# Channel integrations
|
||||
axum = { version = "0.8", features = ["ws"] }
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = ["trace", "cors", "set-header"] }
|
||||
tower-http = { version = "0.6", features = ["trace", "cors", "set-header", "catch-panic"] }
|
||||
|
||||
# Cron scheduling for routines
|
||||
cron = "0.13"
|
||||
|
||||
# Shared types
|
||||
ironclaw_common = { path = "crates/ironclaw_common", version = "0.1.0" }
|
||||
optimclaw_common = { path = "crates/optimclaw_common", version = "0.1.0" }
|
||||
|
||||
# Safety/sanitization
|
||||
ironclaw_safety = { path = "crates/ironclaw_safety", version = "0.2.0" }
|
||||
optimclaw_safety = { path = "crates/optimclaw_safety", version = "0.2.0" }
|
||||
regex = "1"
|
||||
aho-corasick = "1"
|
||||
|
||||
@@ -138,7 +140,6 @@ wasmtime-wasi = "28" # WASI support for component model
|
||||
wasmparser = "0.220" # WASM binary parsing for validation
|
||||
|
||||
# Cryptography for secrets management
|
||||
aes = "0.8"
|
||||
aes-gcm = "0.10"
|
||||
hkdf = "0.12"
|
||||
hmac = "0.12"
|
||||
@@ -175,7 +176,6 @@ base64 = "0.22.1"
|
||||
mime_guess = "2.0.5"
|
||||
clap_complete = "4.5.0"
|
||||
lru = "0.16.3"
|
||||
silk-rs = "0.2.0"
|
||||
|
||||
# HTML to Markdown conversion (feature gated)
|
||||
html-to-markdown-rs = { version = "2.3", optional = true }
|
||||
@@ -186,10 +186,22 @@ hex = "0.4.3"
|
||||
# OpenClaw import (feature gated)
|
||||
json5 = { version = "0.4", optional = true }
|
||||
|
||||
# Mesh cluster (feature gated)
|
||||
pqcrypto-kyber = { version = "0.8", optional = true }
|
||||
pqcrypto-traits = { version = "0.3", optional = true }
|
||||
sys-info = { version = "0.9", optional = true }
|
||||
hostname = { version = "0.4", optional = true }
|
||||
quinn = { version = "0.11", default-features = false, features = ["runtime-tokio", "rustls-ring"], optional = true }
|
||||
rcgen = { version = "0.13", optional = true }
|
||||
|
||||
# macOS keychain
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
security-framework = "3"
|
||||
|
||||
# PTY allocation for Claude CLI stdout buffering fix (Unix only)
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
pty-process = { version = "0.5", features = ["async"] }
|
||||
|
||||
# Linux secret-service (GNOME Keyring, KWallet)
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
secret-service = { version = "4", features = ["rt-tokio-crypto-rust"] }
|
||||
@@ -198,7 +210,6 @@ zbus = "4"
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4"
|
||||
tracing-test = "0.2"
|
||||
tokio-tungstenite = "0.26"
|
||||
testcontainers-modules = { version = "0.11", features = ["postgres"] }
|
||||
pretty_assertions = "1"
|
||||
tempfile = "3"
|
||||
@@ -221,6 +232,7 @@ postgres = [
|
||||
"dep:tokio-postgres-rustls",
|
||||
"dep:rustls",
|
||||
"dep:rustls-native-certs",
|
||||
"dep:webpki-roots",
|
||||
"dep:postgres-types",
|
||||
"dep:refinery",
|
||||
"dep:pgvector",
|
||||
@@ -233,6 +245,7 @@ integration = []
|
||||
html-to-markdown = ["dep:html-to-markdown-rs", "dep:readabilityrs"]
|
||||
bedrock = ["dep:aws-config", "dep:aws-sdk-bedrockruntime", "dep:aws-smithy-types"]
|
||||
import = ["dep:json5", "libsql"]
|
||||
cluster = ["dep:pqcrypto-kyber", "dep:pqcrypto-traits", "dep:sys-info", "dep:hostname", "dep:quinn", "dep:rcgen", "dep:rustls"]
|
||||
|
||||
[[test]]
|
||||
name = "e2e_thread_scheduling"
|
||||
@@ -248,8 +261,7 @@ strip = true # Remove debug symbols from release binaries
|
||||
# The profile that 'cargo dist' will build with
|
||||
[profile.dist]
|
||||
inherits = "release"
|
||||
lto = "fat" # Full cross-crate LTO (slow build, better codegen)
|
||||
codegen-units = 1 # Single codegen unit for maximum optimization
|
||||
lto = "thin"
|
||||
|
||||
# Config for 'dist'
|
||||
[workspace.metadata.dist]
|
||||
|
||||
+34
-8
@@ -1,45 +1,71 @@
|
||||
# Multi-stage Dockerfile for the IronClaw agent (cloud deployment).
|
||||
#
|
||||
# Uses cargo-chef for dependency caching — only rebuilds deps when
|
||||
# Cargo.toml/Cargo.lock change, not on every source edit.
|
||||
#
|
||||
# Build:
|
||||
# docker build --platform linux/amd64 -t ironclaw:latest .
|
||||
#
|
||||
# Run:
|
||||
# docker run --env-file .env -p 3000:3000 ironclaw:latest
|
||||
|
||||
# Stage 1: Build
|
||||
FROM rust:1.92-slim-bookworm AS builder
|
||||
# Stage 1: Install cargo-chef
|
||||
FROM rust:1.92-slim-bookworm AS chef
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
pkg-config libssl-dev cmake gcc g++ \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& rustup target add wasm32-wasip2 \
|
||||
&& cargo install wasm-tools
|
||||
&& cargo install cargo-chef wasm-tools
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy manifests first for layer caching
|
||||
# Stage 2: Generate the dependency recipe (changes only when Cargo.toml/lock change)
|
||||
FROM chef AS planner
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates/ crates/
|
||||
|
||||
# Copy source, build script, tests, and supporting directories
|
||||
COPY build.rs build.rs
|
||||
COPY src/ src/
|
||||
COPY tests/ tests/
|
||||
COPY benches/ benches/
|
||||
COPY migrations/ migrations/
|
||||
COPY registry/ registry/
|
||||
COPY channels-src/ channels-src/
|
||||
COPY wit/ wit/
|
||||
COPY providers.json providers.json
|
||||
# [[bench]] entries in Cargo.toml require bench sources to exist for cargo to parse the manifest
|
||||
|
||||
RUN cargo chef prepare --recipe-path recipe.json
|
||||
|
||||
# Stage 3: Build dependencies (cached unless Cargo.toml/lock change)
|
||||
FROM chef AS deps
|
||||
|
||||
COPY --from=planner /app/recipe.json recipe.json
|
||||
RUN cargo chef cook --release --recipe-path recipe.json
|
||||
|
||||
# Stage 4: Build the actual binary (only recompiles ironclaw source)
|
||||
FROM deps AS builder
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY crates/ crates/
|
||||
COPY build.rs build.rs
|
||||
COPY src/ src/
|
||||
COPY tests/ tests/
|
||||
COPY benches/ benches/
|
||||
COPY migrations/ migrations/
|
||||
COPY registry/ registry/
|
||||
COPY channels-src/ channels-src/
|
||||
COPY wit/ wit/
|
||||
COPY providers.json providers.json
|
||||
|
||||
RUN cargo build --release --bin ironclaw
|
||||
|
||||
# Stage 2: Runtime
|
||||
# Stage 5: Runtime
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates libssl3 \
|
||||
&& update-ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /app/target/release/ironclaw /usr/local/bin/ironclaw
|
||||
|
||||
+38
-39
@@ -1,6 +1,6 @@
|
||||
# IronClaw ↔ OpenClaw Feature Parity Matrix
|
||||
# OptimClaw ↔ OpenClaw Feature Parity Matrix
|
||||
|
||||
This document tracks feature parity between IronClaw (Rust implementation) and OpenClaw (TypeScript reference implementation). Use this to coordinate work across developers.
|
||||
This document tracks feature parity between OptimClaw (Rust implementation) and OpenClaw (TypeScript reference implementation). Use this to coordinate work across developers.
|
||||
|
||||
**Legend:**
|
||||
|
||||
@@ -17,7 +17,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 1. Architecture
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Hub-and-spoke architecture | ✅ | ✅ | Web gateway as central hub |
|
||||
| WebSocket control plane | ✅ | ✅ | Gateway with WebSocket + SSE |
|
||||
@@ -32,7 +32,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 2. Gateway System
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Gateway control plane | ✅ | ✅ | Web gateway with 40+ API endpoints |
|
||||
| HTTP endpoints for Control UI | ✅ | ✅ | Web dashboard with chat, memory, jobs, logs, extensions |
|
||||
@@ -62,22 +62,21 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 3. Messaging Channels
|
||||
|
||||
| Channel | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Channel | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| CLI/TUI | ✅ | ✅ | - | Ratatui-based TUI |
|
||||
| HTTP webhook | ✅ | ✅ | - | axum with secret validation |
|
||||
| REPL (simple) | ✅ | ✅ | - | For testing |
|
||||
| WASM channels | ❌ | ✅ | - | IronClaw innovation; host resolves owner scope vs sender identity |
|
||||
| WASM channels | ❌ | ✅ | - | OptimClaw innovation; host resolves owner scope vs sender identity |
|
||||
| WhatsApp | ✅ | ❌ | P1 | Baileys (Web), same-phone mode with echo detection |
|
||||
| Telegram | ✅ | ✅ | - | WASM channel(MTProto), DM pairing, caption, /start, bot_username, DM topics, setup-time owner auto-verification, owner-scoped persistence |
|
||||
| Discord | ✅ | ❌ | P2 | discord.js, thread parent binding inheritance |
|
||||
| Discord | ✅ | 🚧 | P2 | Gateway `MESSAGE_CREATE` intake restored via websocket queue + WASM poll; Gateway DMs now respect pairing; thread parent binding inheritance and reply/thread parity still incomplete |
|
||||
| Signal | ✅ | ✅ | P2 | signal-cli daemonPC, SSE listener HTTP/JSON-R, user/group allowlists, DM pairing |
|
||||
| Slack | ✅ | ✅ | - | WASM tool |
|
||||
| iMessage | ✅ | ❌ | P3 | BlueBubbles or Linq recommended |
|
||||
| Linq | ✅ | ❌ | P3 | Real iMessage via API, no Mac required |
|
||||
| Feishu/Lark | ✅ | 🚧 | P3 | WASM channel with Event Subscription v2.0; Bitable/Docx tools planned |
|
||||
| LINE | ✅ | ❌ | P3 | |
|
||||
| WeChat (iLink bot) | ✅ | 🚧 | P2 | Extension-first channel (`channels-src/wechat`), single-account DM flow with QR login, typing, image send/receive, inbound file extraction, and inbound voice handling with SILK-to-WAV fallback; multi-account plus video and outbound file parity follow-up |
|
||||
| WebChat | ✅ | ✅ | - | Web gateway chat |
|
||||
| Matrix | ✅ | ❌ | P3 | E2EE support |
|
||||
| Mattermost | ✅ | ❌ | P3 | Emoji reactions, interactive buttons, model picker |
|
||||
@@ -89,7 +88,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
### Telegram-Specific Features (since Feb 2025)
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Forum topic creation | ✅ | ❌ | Create topics in forum groups |
|
||||
| channel_post support | ✅ | ❌ | Bot-to-bot communication |
|
||||
@@ -101,7 +100,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
### Discord-Specific Features (since Feb 2025)
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Forwarded attachment downloads | ✅ | ❌ | Fetch media from forwarded messages |
|
||||
| Faster reaction state machine | ✅ | ❌ | Watchdog + debounce |
|
||||
@@ -109,7 +108,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
### Slack-Specific Features (since Feb 2025)
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Streaming draft replies | ✅ | ❌ | Partial replies via draft message updates |
|
||||
| Configurable stream modes | ✅ | ❌ | Per-channel stream behavior |
|
||||
@@ -118,23 +117,23 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
### Mattermost-Specific Features (since Mar 2026)
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Interactive buttons | ✅ | ❌ | Clickable message buttons with signed callback flow |
|
||||
| Interactive model picker | ✅ | ❌ | In-channel provider/model chooser |
|
||||
|
||||
### Feishu/Lark-Specific Features (since Mar 2026)
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Doc/table actions | ✅ | ❌ | `feishu_doc` supports tables, positional insert, color_text, image upload, and file upload |
|
||||
| Rich-text embedded media extraction | ✅ | ❌ | Pull video/media attachments from post messages |
|
||||
|
||||
### Channel Features
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| DM pairing codes | ✅ | ✅ | `ironclaw pairing list/approve`, host APIs |
|
||||
| DM pairing codes | ✅ | ✅ | `optimclaw pairing list/approve`, host APIs |
|
||||
| Allowlist/blocklist | ✅ | 🚧 | `allow_from` + pairing store + hardened command/group allowlists |
|
||||
| Self-message bypass | ✅ | ❌ | Own messages skip pairing |
|
||||
| Mention-based activation | ✅ | ✅ | bot_username + respond_to_all_group_messages |
|
||||
@@ -152,7 +151,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 4. CLI Commands
|
||||
|
||||
| Command | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Command | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| `run` (agent) | ✅ | ✅ | - | Default command |
|
||||
| `tool install/list/remove` | ✅ | ✅ | - | WASM tools |
|
||||
@@ -190,9 +189,9 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 5. Agent System
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Pi agent runtime | ✅ | ➖ | IronClaw uses custom runtime |
|
||||
| Pi agent runtime | ✅ | ➖ | OptimClaw uses custom runtime |
|
||||
| RPC-based execution | ✅ | ✅ | Orchestrator/worker pattern |
|
||||
| Multi-provider failover | ✅ | ✅ | `FailoverProvider` tries providers sequentially on retryable errors |
|
||||
| Per-sender sessions | ✅ | ✅ | |
|
||||
@@ -233,7 +232,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 6. Model & Provider Support
|
||||
|
||||
| Provider | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Provider | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|----------|----------|----------|----------|-------|
|
||||
| NEAR AI | ✅ | ✅ | - | Primary provider |
|
||||
| Anthropic (Claude) | ✅ | 🚧 | - | Via NEAR AI proxy; Opus 4.5, Sonnet 4, Sonnet 4.6, adaptive thinking default |
|
||||
@@ -246,7 +245,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
| Cloudflare Workers AI | ✅ | ✅ | P3 | Via `cloudflare` adapter |
|
||||
| NVIDIA API | ✅ | ✅ | P3 | Via `nvidia` adapter and `providers.json` |
|
||||
| OpenRouter | ✅ | ✅ | - | Via OpenAI-compatible provider (RigAdapter) |
|
||||
| Tinfoil | ❌ | ✅ | - | Private inference provider (IronClaw-only) |
|
||||
| Tinfoil | ❌ | ✅ | - | Private inference provider (OptimClaw-only) |
|
||||
| OpenAI-compatible | ❌ | ✅ | - | Generic OpenAI-compatible endpoint (RigAdapter) |
|
||||
| GitHub Copilot | ✅ | ✅ | - | Dedicated provider with OAuth token exchange (`GithubCopilotProvider`) |
|
||||
| Ollama (local) | ✅ | ✅ | - | via `rig::providers::ollama` (full support) |
|
||||
@@ -258,7 +257,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
### Model Features
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Auto-discovery | ✅ | ❌ | |
|
||||
| Failover chains | ✅ | ✅ | `FailoverProvider` with configurable `fallback_model` |
|
||||
@@ -274,7 +273,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 7. Media Handling
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| Image processing (Sharp) | ✅ | ❌ | P2 | Resize, format convert |
|
||||
| Configurable image resize dims | ✅ | ❌ | P2 | Per-agent dimension config |
|
||||
@@ -297,12 +296,12 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 8. Plugin & Extension System
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Dynamic loading | ✅ | ✅ | WASM modules |
|
||||
| Manifest validation | ✅ | ✅ | WASM metadata |
|
||||
| HTTP path registration | ✅ | ❌ | Plugin routes |
|
||||
| Workspace-relative install | ✅ | ✅ | ~/.ironclaw/tools/ |
|
||||
| Workspace-relative install | ✅ | ✅ | ~/.optimclaw/tools/ |
|
||||
| Channel plugins | ✅ | ✅ | WASM channels |
|
||||
| Auth plugins | ✅ | ❌ | |
|
||||
| Memory plugins | ✅ | ❌ | Custom backends + selectable memory slot |
|
||||
@@ -322,7 +321,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 9. Configuration System
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Primary config file | ✅ `~/.openclaw/openclaw.json` | ✅ `.env` | Different formats |
|
||||
| JSON5 support | ✅ | ❌ | Comments, trailing commas |
|
||||
@@ -331,7 +330,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
| Config validation/schema | ✅ | ✅ | Type-safe Config struct + `openclaw config validate` |
|
||||
| Hot-reload | ✅ | ❌ | |
|
||||
| Legacy migration | ✅ | ➖ | |
|
||||
| State directory | ✅ `~/.openclaw-state/` | ✅ `~/.ironclaw/` | |
|
||||
| State directory | ✅ `~/.openclaw-state/` | ✅ `~/.optimclaw/` | |
|
||||
| Credentials directory | ✅ | ✅ | Session files |
|
||||
| Full model compat fields in schema | ✅ | ❌ | pi-ai model compat exposed in config |
|
||||
|
||||
@@ -341,7 +340,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 10. Memory & Knowledge System
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Vector memory | ✅ | ✅ | pgvector |
|
||||
| Session-based memory | ✅ | ✅ | |
|
||||
@@ -352,7 +351,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
| OpenAI embeddings | ✅ | ✅ | |
|
||||
| Gemini embeddings | ✅ | ❌ | |
|
||||
| Local embeddings | ✅ | ❌ | |
|
||||
| SQLite-vec backend | ✅ | ❌ | IronClaw uses PostgreSQL |
|
||||
| SQLite-vec backend | ✅ | ❌ | OptimClaw uses PostgreSQL |
|
||||
| LanceDB backend | ✅ | ❌ | Configurable auto-capture max length |
|
||||
| QMD backend | ✅ | ❌ | |
|
||||
| Atomic reindexing | ✅ | ✅ | |
|
||||
@@ -370,7 +369,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 11. Mobile Apps
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| iOS app (SwiftUI) | ✅ | 🚫 | - | Out of scope initially |
|
||||
| Android app (Kotlin) | ✅ | 🚫 | - | Out of scope initially |
|
||||
@@ -391,7 +390,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 12. macOS App
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| SwiftUI native app | ✅ | 🚫 | - | Out of scope |
|
||||
| Menu bar presence | ✅ | 🚫 | - | Animated menubar icon |
|
||||
@@ -412,7 +411,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 13. Web Interface
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| Control UI Dashboard | ✅ | ✅ | - | Web gateway with chat, memory, jobs, logs, extensions |
|
||||
| Channel status view | ✅ | 🚧 | P2 | Gateway status widget, full channel view pending |
|
||||
@@ -432,7 +431,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 14. Automation
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Priority | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Priority | Notes |
|
||||
|---------|----------|----------|----------|-------|
|
||||
| Cron jobs | ✅ | ✅ | - | Routines with cron trigger |
|
||||
| Per-job model fallback override | ✅ | ❌ | P2 | `payload.fallbacks` overrides agent-level fallbacks |
|
||||
@@ -466,14 +465,14 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 15. Security Features
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Gateway token auth | ✅ | ✅ | Bearer token auth on web gateway |
|
||||
| Device pairing | ✅ | ❌ | |
|
||||
| Tailscale identity | ✅ | ❌ | |
|
||||
| Trusted-proxy auth | ✅ | ❌ | Header-based reverse proxy auth |
|
||||
| OAuth flows | ✅ | 🚧 | NEAR AI OAuth + Gemini OAuth (PKCE, S256) + hosted extension/MCP OAuth broker; external auth-proxy rollout still pending |
|
||||
| DM pairing verification | ✅ | ✅ | ironclaw pairing approve, host APIs |
|
||||
| DM pairing verification | ✅ | ✅ | optimclaw pairing approve, host APIs |
|
||||
| Allowlist/blocklist | ✅ | 🚧 | allow_from + pairing store |
|
||||
| Per-group tool policies | ✅ | ❌ | |
|
||||
| Exec approvals | ✅ | ✅ | TUI overlay |
|
||||
@@ -484,7 +483,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
| Loopback-first | ✅ | 🚧 | HTTP binds 0.0.0.0 |
|
||||
| Docker sandbox | ✅ | ✅ | Orchestrator/worker containers |
|
||||
| Podman support | ✅ | ❌ | Alternative to Docker |
|
||||
| WASM sandbox | ❌ | ✅ | IronClaw innovation |
|
||||
| WASM sandbox | ❌ | ✅ | OptimClaw innovation |
|
||||
| Sandbox env sanitization | ✅ | 🚧 | Shell tool scrubs env vars (secret detection); docker container env sanitization partial |
|
||||
| Tool policies | ✅ | ✅ | |
|
||||
| Elevated mode | ✅ | ❌ | |
|
||||
@@ -506,7 +505,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## 16. Development & Build System
|
||||
|
||||
| Feature | OpenClaw | IronClaw | Notes |
|
||||
| Feature | OpenClaw | OptimClaw | Notes |
|
||||
|---------|----------|----------|-------|
|
||||
| Primary language | TypeScript | Rust | Different ecosystems |
|
||||
| Build tool | tsdown | cargo | |
|
||||
@@ -532,7 +531,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
- ✅ TUI channel with approval overlays
|
||||
- ✅ HTTP webhook channel
|
||||
- ✅ DM pairing (ironclaw pairing list/approve, host APIs)
|
||||
- ✅ DM pairing (optimclaw pairing list/approve, host APIs)
|
||||
- ✅ WASM tool sandbox
|
||||
- ✅ Workspace/memory with hybrid search + embeddings batching
|
||||
- ✅ Prompt injection defense
|
||||
@@ -606,7 +605,7 @@ This document tracks feature parity between IronClaw (Rust implementation) and O
|
||||
|
||||
## Deviations from OpenClaw
|
||||
|
||||
IronClaw intentionally differs from OpenClaw in these ways:
|
||||
OptimClaw intentionally differs from OpenClaw in these ways:
|
||||
|
||||
1. **Rust vs TypeScript**: Native performance, memory safety, single binary distribution
|
||||
2. **WASM sandbox vs Docker**: Lighter weight, faster startup, capability-based security
|
||||
@@ -614,7 +613,7 @@ IronClaw intentionally differs from OpenClaw in these ways:
|
||||
4. **NEAR AI focus**: Primary provider with session-based auth
|
||||
5. **No mobile/desktop apps**: Focus on server-side and CLI initially
|
||||
6. **WASM channels**: Novel extension mechanism not in OpenClaw
|
||||
7. **Tinfoil private inference**: IronClaw-only provider for private/encrypted inference
|
||||
7. **Tinfoil private inference**: OptimClaw-only provider for private/encrypted inference
|
||||
8. **GitHub WASM tool**: Native GitHub integration as WASM tool
|
||||
9. **Prompt-based skills**: Different approach than OpenClaw capability bundles (trust gating, attenuation)
|
||||
|
||||
|
||||
+26
-26
@@ -1,8 +1,8 @@
|
||||
<p align="center">
|
||||
<img src="ironclaw.png?v=2" alt="IronClaw" width="200"/>
|
||||
<img src="optimclaw.png?v=2" alt="OptimClaw" width="200"/>
|
||||
</p>
|
||||
|
||||
<h1 align="center">IronClaw</h1>
|
||||
<h1 align="center">OptimClaw</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>あなたの味方になる、安全なパーソナルAIアシスタント</strong>
|
||||
@@ -10,8 +10,8 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache%202.0-blue.svg" alt="License: MIT OR Apache-2.0" /></a>
|
||||
<a href="https://t.me/ironclawAI"><img src="https://img.shields.io/badge/Telegram-%40ironclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @ironclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/ironclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FironclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/ironclawAI" /></a>
|
||||
<a href="https://t.me/optimclawAI"><img src="https://img.shields.io/badge/Telegram-%40optimclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @optimclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/optimclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FoptimclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/optimclawAI" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -34,16 +34,16 @@
|
||||
|
||||
## フィロソフィー
|
||||
|
||||
IronClawはシンプルな原則に基づいて構築されています:**あなたのAIアシスタントは、あなたのために働くべきであり、あなたに不利益をもたらすべきではありません。**
|
||||
OptimClawはシンプルな原則に基づいて構築されています:**あなたのAIアシスタントは、あなたのために働くべきであり、あなたに不利益をもたらすべきではありません。**
|
||||
|
||||
AIシステムがデータの取り扱いについて不透明になり、企業の利益に沿って調整されることが増えている世界で、IronClawは異なるアプローチを取ります:
|
||||
AIシステムがデータの取り扱いについて不透明になり、企業の利益に沿って調整されることが増えている世界で、OptimClawは異なるアプローチを取ります:
|
||||
|
||||
- **あなたのデータはあなたのもの** - すべての情報はローカルに保存・暗号化され、あなたの管理下から離れることはありません
|
||||
- **設計段階からの透明性** - オープンソース、監査可能、隠れたテレメトリやデータ収集なし
|
||||
- **自己拡張する能力** - ベンダーのアップデートを待たずに、新しいツールをその場で構築
|
||||
- **多層防御** - 複数のセキュリティレイヤーがプロンプトインジェクションやデータ流出から保護
|
||||
|
||||
IronClawは、個人生活にも仕事にも本当に信頼できるAIアシスタントです。
|
||||
OptimClawは、個人生活にも仕事にも本当に信頼できるAIアシスタントです。
|
||||
|
||||
## 機能
|
||||
|
||||
@@ -66,7 +66,7 @@ IronClawは、個人生活にも仕事にも本当に信頼できるAIアシス
|
||||
|
||||
### 自己拡張
|
||||
|
||||
- **動的ツール構築** - 必要なものを説明すると、IronClawがWASMツールとして構築
|
||||
- **動的ツール構築** - 必要なものを説明すると、OptimClawがWASMツールとして構築
|
||||
- **MCPプロトコル** - Model Context Protocolサーバーに接続して追加機能を利用
|
||||
- **プラグインアーキテクチャ** - 再起動なしで新しいWASMツールやチャネルを追加
|
||||
|
||||
@@ -86,12 +86,12 @@ IronClawは、個人生活にも仕事にも本当に信頼できるAIアシス
|
||||
|
||||
## ダウンロードまたはビルド
|
||||
|
||||
最新のアップデートは[リリースページ](https://github.com/nearai/ironclaw/releases/)をご覧ください。
|
||||
最新のアップデートは[リリースページ](https://github.com/nearai/optimclaw/releases/)をご覧ください。
|
||||
|
||||
<details>
|
||||
<summary>Windowsインストーラーでインストール(Windows)</summary>
|
||||
|
||||
[Windowsインストーラー](https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-x86_64-pc-windows-msvc.msi)をダウンロードして実行してください。
|
||||
[Windowsインストーラー](https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-x86_64-pc-windows-msvc.msi)をダウンロードして実行してください。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -99,7 +99,7 @@ IronClawは、個人生活にも仕事にも本当に信頼できるAIアシス
|
||||
<summary>PowerShellスクリプトでインストール(Windows)</summary>
|
||||
|
||||
```sh
|
||||
irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.ps1 | iex
|
||||
irm https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.ps1 | iex
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -108,7 +108,7 @@ irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-install
|
||||
<summary>シェルスクリプトでインストール(macOS、Linux、Windows/WSL)</summary>
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.sh | sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.sh | sh
|
||||
```
|
||||
</details>
|
||||
|
||||
@@ -116,7 +116,7 @@ curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/release
|
||||
<summary>Homebrewでインストール(macOS/Linux)</summary>
|
||||
|
||||
```sh
|
||||
brew install ironclaw
|
||||
brew install optimclaw
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -128,8 +128,8 @@ brew install ironclaw
|
||||
|
||||
```bash
|
||||
# リポジトリをクローン
|
||||
git clone https://github.com/nearai/ironclaw.git
|
||||
cd ironclaw
|
||||
git clone https://github.com/nearai/optimclaw.git
|
||||
cd optimclaw
|
||||
|
||||
# ビルド
|
||||
cargo build --release
|
||||
@@ -146,25 +146,25 @@ cargo test
|
||||
|
||||
```bash
|
||||
# データベースを作成
|
||||
createdb ironclaw
|
||||
createdb optimclaw
|
||||
|
||||
# pgvectorを有効化
|
||||
psql ironclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
psql optimclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
```
|
||||
|
||||
## 設定
|
||||
|
||||
セットアップウィザードを実行してIronClawを設定します:
|
||||
セットアップウィザードを実行してOptimClawを設定します:
|
||||
|
||||
```bash
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
```
|
||||
|
||||
ウィザードは、データベース接続、NEAR AI認証(ブラウザOAuth経由)、シークレットの暗号化(システムキーチェーンを使用)を処理します。設定は接続されたデータベースに永続化されます。ブートストラップ変数(例:`DATABASE_URL`、`LLM_BACKEND`)は、データベース接続前に利用できるよう`~/.ironclaw/.env`に書き込まれます。
|
||||
ウィザードは、データベース接続、NEAR AI認証(ブラウザOAuth経由)、シークレットの暗号化(システムキーチェーンを使用)を処理します。設定は接続されたデータベースに永続化されます。ブートストラップ変数(例:`DATABASE_URL`、`LLM_BACKEND`)は、データベース接続前に利用できるよう`~/.optimclaw/.env`に書き込まれます。
|
||||
|
||||
### 代替LLMプロバイダー
|
||||
|
||||
IronClawはデフォルトでNEAR AIを使用しますが、多くのLLMプロバイダーをすぐに利用できます。組み込みプロバイダーには**Anthropic**、**OpenAI**、**Google Gemini**、**MiniMax**、**Mistral**、**Ollama**(ローカル)が含まれます。**OpenRouter**(300以上のモデル)、**Together AI**、**Fireworks AI**、セルフホストサーバー(**vLLM**、**LiteLLM**)などのOpenAI互換サービスもサポートされています。
|
||||
OptimClawはデフォルトでNEAR AIを使用しますが、多くのLLMプロバイダーをすぐに利用できます。組み込みプロバイダーには**Anthropic**、**OpenAI**、**Google Gemini**、**MiniMax**、**Mistral**、**Ollama**(ローカル)が含まれます。**OpenRouter**(300以上のモデル)、**Together AI**、**Fireworks AI**、セルフホストサーバー(**vLLM**、**LiteLLM**)などのOpenAI互換サービスもサポートされています。
|
||||
|
||||
ウィザードでプロバイダーを選択するか、環境変数を直接設定してください:
|
||||
|
||||
@@ -184,7 +184,7 @@ LLM_MODEL=anthropic/claude-sonnet-4
|
||||
|
||||
## セキュリティ
|
||||
|
||||
IronClawは、データを保護し悪用を防ぐために多層防御を実装しています。
|
||||
OptimClawは、データを保護し悪用を防ぐために多層防御を実装しています。
|
||||
|
||||
### WASMサンドボックス
|
||||
|
||||
@@ -280,13 +280,13 @@ WASM ──► 許可リスト ──► リーク ──► 認証情報 ─
|
||||
|
||||
```bash
|
||||
# 初回セットアップ(データベース、認証などを設定)
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
|
||||
# インタラクティブREPLを起動
|
||||
cargo run
|
||||
|
||||
# デバッグログ付き
|
||||
RUST_LOG=ironclaw=debug cargo run
|
||||
RUST_LOG=optimclaw=debug cargo run
|
||||
```
|
||||
|
||||
## 開発
|
||||
@@ -299,7 +299,7 @@ cargo fmt
|
||||
cargo clippy --all --benches --tests --examples --all-features
|
||||
|
||||
# テスト実行
|
||||
createdb ironclaw_test
|
||||
createdb optimclaw_test
|
||||
cargo test
|
||||
|
||||
# 特定のテストを実行
|
||||
@@ -311,7 +311,7 @@ cargo test test_name
|
||||
|
||||
## OpenClawの系譜
|
||||
|
||||
IronClawは[OpenClaw](https://github.com/openclaw/openclaw)にインスパイアされたRust再実装です。完全な対応表は[FEATURE_PARITY.md](FEATURE_PARITY.md)をご覧ください。
|
||||
OptimClawは[OpenClaw](https://github.com/openclaw/openclaw)にインスパイアされたRust再実装です。完全な対応表は[FEATURE_PARITY.md](FEATURE_PARITY.md)をご覧ください。
|
||||
|
||||
主な違い:
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<p align="center">
|
||||
<img src="ironclaw.png?v=2" alt="IronClaw" width="200"/>
|
||||
<img src="optimclaw.png?v=2" alt="OptimClaw" width="200"/>
|
||||
</p>
|
||||
|
||||
<h1 align="center">IronClaw</h1>
|
||||
<h1 align="center">OptimClaw</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>Your secure personal AI assistant, always on your side</strong>
|
||||
@@ -10,10 +10,10 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache%202.0-blue.svg" alt="License: MIT OR Apache-2.0" /></a>
|
||||
<a href="https://t.me/ironclawAI"><img src="https://img.shields.io/badge/Telegram-%40ironclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @ironclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/ironclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FironclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/ironclawAI" /></a>
|
||||
<a href="https://gitcgr.com/nearai/ironclaw">
|
||||
<img src="https://gitcgr.com/badge/nearai/ironclaw.svg" alt="gitcgr" />
|
||||
<a href="https://t.me/optimclawAI"><img src="https://img.shields.io/badge/Telegram-%40optimclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @optimclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/optimclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FoptimclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/optimclawAI" /></a>
|
||||
<a href="https://gitcgr.com/nearai/optimclaw">
|
||||
<img src="https://gitcgr.com/badge/nearai/optimclaw.svg" alt="gitcgr" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
<p align="center">
|
||||
<a href="#philosophy">Philosophy</a> •
|
||||
<a href="#features">Features</a> •
|
||||
<a href="#mesh-cluster">Mesh Cluster</a> •
|
||||
<a href="#lazy-tools">Lazy Tools</a> •
|
||||
<a href="#installation">Installation</a> •
|
||||
<a href="#configuration">Configuration</a> •
|
||||
<a href="#security">Security</a> •
|
||||
@@ -37,16 +39,16 @@
|
||||
|
||||
## Philosophy
|
||||
|
||||
IronClaw is built on a simple principle: **your AI assistant should work for you, not against you**.
|
||||
OptimClaw is built on a simple principle: **your AI assistant should work for you, not against you**.
|
||||
|
||||
In a world where AI systems are increasingly opaque about data handling and aligned with corporate interests, IronClaw takes a different approach:
|
||||
In a world where AI systems are increasingly opaque about data handling and aligned with corporate interests, OptimClaw takes a different approach:
|
||||
|
||||
- **Your data stays yours** - All information is stored locally, encrypted, and never leaves your control
|
||||
- **Transparency by design** - Open source, auditable, no hidden telemetry or data harvesting
|
||||
- **Self-expanding capabilities** - Build new tools on the fly without waiting for vendor updates
|
||||
- **Defense in depth** - Multiple security layers protect against prompt injection and data exfiltration
|
||||
|
||||
IronClaw is the AI assistant you can actually trust with your personal and professional life.
|
||||
OptimClaw is the AI assistant you can actually trust with your personal and professional life.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -69,7 +71,7 @@ IronClaw is the AI assistant you can actually trust with your personal and profe
|
||||
|
||||
### Self-Expanding
|
||||
|
||||
- **Dynamic Tool Building** - Describe what you need, and IronClaw builds it as a WASM tool
|
||||
- **Dynamic Tool Building** - Describe what you need, and OptimClaw builds it as a WASM tool
|
||||
- **MCP Protocol** - Connect to Model Context Protocol servers for additional capabilities
|
||||
- **Plugin Architecture** - Drop in new WASM tools and channels without restarting
|
||||
|
||||
@@ -79,6 +81,50 @@ IronClaw is the AI assistant you can actually trust with your personal and profe
|
||||
- **Workspace Filesystem** - Flexible path-based storage for notes, logs, and context
|
||||
- **Identity Files** - Maintain consistent personality and preferences across sessions
|
||||
|
||||
## Mesh Cluster
|
||||
|
||||
OptimClaw instances can form an **autonomous AI mesh network** where nodes discover each other automatically, coordinate via a gossip protocol, and route tasks intelligently across the cluster.
|
||||
|
||||
Key highlights:
|
||||
|
||||
- **Zero-config discovery** -- UDP beacon broadcast finds peers on the local network automatically
|
||||
- **Post-quantum encryption** -- ML-KEM-768 key exchange with AES-256-GCM authenticated encryption protects all inter-node traffic against both classical and quantum adversaries
|
||||
- **SWIM gossip membership** -- Reliable failure detection and cluster state convergence in O(log N) rounds
|
||||
- **Intelligent task routing** -- A scoring algorithm balances load, latency, capability match, session affinity, and region locality to pick the best node for each task
|
||||
- **Graceful degradation** -- Nodes operate independently if connectivity is lost; no split-brain data corruption
|
||||
|
||||
Quick start (two nodes on one machine):
|
||||
|
||||
```bash
|
||||
# Terminal 1
|
||||
export CLUSTER_ENABLED=true CLUSTER_SECRET="your-32-char-secret-here-change-me" CLUSTER_NODE_ID=node-a
|
||||
cargo run
|
||||
|
||||
# Terminal 2
|
||||
export CLUSTER_ENABLED=true CLUSTER_SECRET="your-32-char-secret-here-change-me" CLUSTER_NODE_ID=node-b CLUSTER_BIND_PORT=9410
|
||||
cargo run
|
||||
```
|
||||
|
||||
Monitor via `GET /api/mesh/status` and `GET /api/mesh/nodes`.
|
||||
|
||||
See [docs/MESH_CLUSTER.md](docs/MESH_CLUSTER.md) for the full guide covering architecture, configuration reference, security model, and troubleshooting.
|
||||
|
||||
## Lazy Tools
|
||||
|
||||
Lazy tool loading reduces the system prompt from approximately 13,000 tokens to approximately 4,000 tokens by deferring tool schemas that are not immediately needed.
|
||||
|
||||
Enable it with:
|
||||
|
||||
```bash
|
||||
export OPTIMCLAW_LAZY_TOOLS=1
|
||||
```
|
||||
|
||||
When enabled, 12 core tools (echo, time, json, http, web_fetch, file_read, file_write, shell, memory_search, memory_write, message, tool_info) are loaded eagerly. All other tools -- including MCP, WASM, and skill tools -- are listed by name only. The LLM calls `tool_info` to load the full schema for any additional tool on demand.
|
||||
|
||||
This is recommended for production deployments and cost-sensitive usage with expensive models.
|
||||
|
||||
See [docs/LAZY_TOOLS.md](docs/LAZY_TOOLS.md) for the full guide.
|
||||
|
||||
## Installation
|
||||
|
||||
### Prerequisites
|
||||
@@ -89,12 +135,12 @@ IronClaw is the AI assistant you can actually trust with your personal and profe
|
||||
|
||||
## Download or Build
|
||||
|
||||
Visit [Releases page](https://github.com/nearai/ironclaw/releases/) to see the latest updates.
|
||||
Visit [Releases page](https://github.com/nearai/optimclaw/releases/) to see the latest updates.
|
||||
|
||||
<details>
|
||||
<summary>Install via Windows Installer (Windows)</summary>
|
||||
|
||||
Download the [Windows Installer](https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-x86_64-pc-windows-msvc.msi) and run it.
|
||||
Download the [Windows Installer](https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-x86_64-pc-windows-msvc.msi) and run it.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -102,7 +148,7 @@ Download the [Windows Installer](https://github.com/nearai/ironclaw/releases/lat
|
||||
<summary>Install via powershell script (Windows)</summary>
|
||||
|
||||
```sh
|
||||
irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.ps1 | iex
|
||||
irm https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.ps1 | iex
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -111,7 +157,7 @@ irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-install
|
||||
<summary>Install via shell script (macOS, Linux, Windows/WSL)</summary>
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.sh | sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.sh | sh
|
||||
```
|
||||
</details>
|
||||
|
||||
@@ -119,7 +165,7 @@ curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/release
|
||||
<summary>Install via Homebrew (macOS/Linux)</summary>
|
||||
|
||||
```sh
|
||||
brew install ironclaw
|
||||
brew install optimclaw
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -131,8 +177,8 @@ Install it with `cargo`, just make sure you have [Rust](https://rustup.rs) insta
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/nearai/ironclaw.git
|
||||
cd ironclaw
|
||||
git clone https://github.com/nearai/optimclaw.git
|
||||
cd optimclaw
|
||||
|
||||
# Build
|
||||
cargo build --release
|
||||
@@ -149,28 +195,28 @@ For **full release** (after modifying channel sources), run `./scripts/build-all
|
||||
|
||||
```bash
|
||||
# Create database
|
||||
createdb ironclaw
|
||||
createdb optimclaw
|
||||
|
||||
# Enable pgvector
|
||||
psql ironclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
psql optimclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Run the setup wizard to configure IronClaw:
|
||||
Run the setup wizard to configure OptimClaw:
|
||||
|
||||
```bash
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
```
|
||||
|
||||
The wizard handles database connection, NEAR AI authentication (via browser OAuth),
|
||||
and secrets encryption (using your system keychain). Settings are persisted in the
|
||||
connected database; bootstrap variables (e.g. `DATABASE_URL`, `LLM_BACKEND`) are
|
||||
written to `~/.ironclaw/.env` so they are available before the database connects.
|
||||
written to `~/.optimclaw/.env` so they are available before the database connects.
|
||||
|
||||
### Alternative LLM Providers
|
||||
|
||||
IronClaw defaults to NEAR AI but supports many LLM providers out of the box.
|
||||
OptimClaw defaults to NEAR AI but supports many LLM providers out of the box.
|
||||
Built-in providers include **Anthropic**, **OpenAI**, **GitHub Copilot**, **Google Gemini**, **MiniMax**,
|
||||
**Mistral**, and **Ollama** (local). OpenAI-compatible services like **OpenRouter**
|
||||
(300+ models), **Together AI**, **Fireworks AI**, and self-hosted servers (**vLLM**,
|
||||
@@ -194,7 +240,7 @@ See [docs/LLM_PROVIDERS.md](docs/LLM_PROVIDERS.md) for a full provider guide.
|
||||
|
||||
## Security
|
||||
|
||||
IronClaw implements defense in depth to protect your data and prevent misuse.
|
||||
OptimClaw implements defense in depth to protect your data and prevent misuse.
|
||||
|
||||
### WASM Sandbox
|
||||
|
||||
@@ -287,13 +333,13 @@ External content passes through multiple security layers:
|
||||
|
||||
```bash
|
||||
# First-time setup (configures database, auth, etc.)
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
|
||||
# Start interactive REPL
|
||||
cargo run
|
||||
|
||||
# With debug logging
|
||||
RUST_LOG=ironclaw=debug cargo run
|
||||
RUST_LOG=optimclaw=debug cargo run
|
||||
```
|
||||
|
||||
## Development
|
||||
@@ -306,7 +352,7 @@ cargo fmt
|
||||
cargo clippy --all --benches --tests --examples --all-features
|
||||
|
||||
# Run tests
|
||||
createdb ironclaw_test
|
||||
createdb optimclaw_test
|
||||
cargo test
|
||||
|
||||
# Run specific test
|
||||
@@ -318,7 +364,7 @@ cargo test test_name
|
||||
|
||||
## OpenClaw Heritage
|
||||
|
||||
IronClaw is a Rust reimplementation inspired by [OpenClaw](https://github.com/openclaw/openclaw). See [FEATURE_PARITY.md](FEATURE_PARITY.md) for the complete tracking matrix.
|
||||
OptimClaw is a Rust reimplementation inspired by [OpenClaw](https://github.com/openclaw/openclaw). See [FEATURE_PARITY.md](FEATURE_PARITY.md) for the complete tracking matrix.
|
||||
|
||||
Key differences:
|
||||
|
||||
|
||||
+26
-26
@@ -1,8 +1,8 @@
|
||||
<p align="center">
|
||||
<img src="ironclaw.png?v=2" alt="IronClaw" width="200"/>
|
||||
<img src="optimclaw.png?v=2" alt="OptimClaw" width="200"/>
|
||||
</p>
|
||||
|
||||
<h1 align="center">IronClaw</h1>
|
||||
<h1 align="center">OptimClaw</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>Ваш защищенный персональный AI-ассистент, всегда на вашей стороне</strong>
|
||||
@@ -10,8 +10,8 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache%202.0-blue.svg" alt="Лицензия: MIT OR Apache-2.0" /></a>
|
||||
<a href="https://t.me/ironclawAI"><img src="https://img.shields.io/badge/Telegram-%40ironclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @ironclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/ironclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FironclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/ironclawAI" /></a>
|
||||
<a href="https://t.me/optimclawAI"><img src="https://img.shields.io/badge/Telegram-%40optimclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @optimclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/optimclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FoptimclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/optimclawAI" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -34,16 +34,16 @@
|
||||
|
||||
## Философия
|
||||
|
||||
IronClaw построен на простом принципе: **ваш AI-ассистент должен работать на вас, а не против вас**.
|
||||
OptimClaw построен на простом принципе: **ваш AI-ассистент должен работать на вас, а не против вас**.
|
||||
|
||||
В мире, где системы ИИ становятся все более непрозрачными в вопросах обработки данных и ориентируются на корпоративные интересы, IronClaw выбирает другой путь:
|
||||
В мире, где системы ИИ становятся все более непрозрачными в вопросах обработки данных и ориентируются на корпоративные интересы, OptimClaw выбирает другой путь:
|
||||
|
||||
- **Ваши данные остаются вашими** — вся информация хранится локально, зашифрована и никогда не покидает ваш контроль.
|
||||
- **Прозрачность по умолчанию** — открытый исходный код, возможность аудита, отсутствие скрытой телеметрии или сбора данных.
|
||||
- **Саморасширяемые возможности** — создавайте новые инструменты «на лету», не дожидаясь обновлений от вендора.
|
||||
- **Глубокая защита** — несколько уровней безопасности защищают от инъекций промптов и утечки данных.
|
||||
|
||||
IronClaw — это AI-ассистент, которому вы действительно можете доверять в личной и профессиональной жизни.
|
||||
OptimClaw — это AI-ассистент, которому вы действительно можете доверять в личной и профессиональной жизни.
|
||||
|
||||
## Возможности
|
||||
|
||||
@@ -66,7 +66,7 @@ IronClaw — это AI-ассистент, которому вы действи
|
||||
|
||||
### Саморасширяемый
|
||||
|
||||
- **Динамическое создание инструментов** — опишите, что вам нужно, и IronClaw создаст это как инструмент WASM.
|
||||
- **Динамическое создание инструментов** — опишите, что вам нужно, и OptimClaw создаст это как инструмент WASM.
|
||||
- **Протокол MCP** — подключайтесь к серверам Model Context Protocol для получения дополнительных возможностей.
|
||||
- **Плагинная архитектура** — добавляйте новые инструменты WASM и каналы без перезагрузки системы.
|
||||
|
||||
@@ -86,12 +86,12 @@ IronClaw — это AI-ассистент, которому вы действи
|
||||
|
||||
## Загрузка и сборка
|
||||
|
||||
Посетите [страницу релизов](https://github.com/nearai/ironclaw/releases/), чтобы увидеть последние обновления.
|
||||
Посетите [страницу релизов](https://github.com/nearai/optimclaw/releases/), чтобы увидеть последние обновления.
|
||||
|
||||
<details>
|
||||
<summary>Установка через установщик Windows (Windows)</summary>
|
||||
|
||||
Загрузите [Windows Installer](https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-x86_64-pc-windows-msvc.msi) и запустите его.
|
||||
Загрузите [Windows Installer](https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-x86_64-pc-windows-msvc.msi) и запустите его.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -99,7 +99,7 @@ IronClaw — это AI-ассистент, которому вы действи
|
||||
<summary>Установка через powershell-скрипт (Windows)</summary>
|
||||
|
||||
```sh
|
||||
irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.ps1 | iex
|
||||
irm https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.ps1 | iex
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -108,7 +108,7 @@ irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-install
|
||||
<summary>Установка через shell-скрипт (macOS, Linux, Windows/WSL)</summary>
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.sh | sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.sh | sh
|
||||
```
|
||||
</details>
|
||||
|
||||
@@ -116,7 +116,7 @@ curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/release
|
||||
<summary>Установка через Homebrew (macOS/Linux)</summary>
|
||||
|
||||
```sh
|
||||
brew install ironclaw
|
||||
brew install optimclaw
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -128,8 +128,8 @@ brew install ironclaw
|
||||
|
||||
```bash
|
||||
# Клонируйте репозиторий
|
||||
git clone https://github.com/nearai/ironclaw.git
|
||||
cd ironclaw
|
||||
git clone https://github.com/nearai/optimclaw.git
|
||||
cd optimclaw
|
||||
|
||||
# Сборка
|
||||
cargo build --release
|
||||
@@ -146,25 +146,25 @@ cargo test
|
||||
|
||||
```bash
|
||||
# Создание базы данных
|
||||
createdb ironclaw
|
||||
createdb optimclaw
|
||||
|
||||
# Включение pgvector
|
||||
psql ironclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
psql optimclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
```
|
||||
|
||||
## Конфигурация
|
||||
|
||||
Запустите мастер настройки для конфигурации IronClaw:
|
||||
Запустите мастер настройки для конфигурации OptimClaw:
|
||||
|
||||
```bash
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
```
|
||||
|
||||
Мастер настройки поможет установить соединение с базой данных, пройти аутентификацию NEAR AI (через браузер OAuth) и настроить шифрование секретов (используя системную связку ключей). Настройки сохраняются в базе данных; базовые переменные (например, `DATABASE_URL`, `LLM_BACKEND`) записываются в `~/.ironclaw/.env`, чтобы они были доступны до подключения к БД.
|
||||
Мастер настройки поможет установить соединение с базой данных, пройти аутентификацию NEAR AI (через браузер OAuth) и настроить шифрование секретов (используя системную связку ключей). Настройки сохраняются в базе данных; базовые переменные (например, `DATABASE_URL`, `LLM_BACKEND`) записываются в `~/.optimclaw/.env`, чтобы они были доступны до подключения к БД.
|
||||
|
||||
### Альтернативные LLM-провайдеры
|
||||
|
||||
IronClaw по умолчанию использует NEAR AI, но поддерживает множество LLM-провайдеров из коробки.
|
||||
OptimClaw по умолчанию использует NEAR AI, но поддерживает множество LLM-провайдеров из коробки.
|
||||
Встроенные провайдеры включают **Anthropic**, **OpenAI**, **Google Gemini**, **MiniMax**,
|
||||
**Mistral** и **Ollama** (локально). Также поддерживаются OpenAI-совместимые сервисы:
|
||||
**OpenRouter** (300+ моделей), **Together AI**, **Fireworks AI** и собственные серверы
|
||||
@@ -188,7 +188,7 @@ LLM_MODEL=anthropic/claude-sonnet-4
|
||||
|
||||
## Безопасность
|
||||
|
||||
IronClaw реализует эшелонированную защиту для обеспечения безопасности ваших данных и предотвращения злоупотреблений.
|
||||
OptimClaw реализует эшелонированную защиту для обеспечения безопасности ваших данных и предотвращения злоупотреблений.
|
||||
|
||||
### Песочница WASM
|
||||
|
||||
@@ -282,13 +282,13 @@ WASM ──► Валидатор ──► Сканер ───► Инъек
|
||||
|
||||
```bash
|
||||
# Первоначальная настройка (БД, аутентификация и т.д.)
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
|
||||
# Запуск интерактивного REPL
|
||||
cargo run
|
||||
|
||||
# С отладочными логами
|
||||
RUST_LOG=ironclaw=debug cargo run
|
||||
RUST_LOG=optimclaw=debug cargo run
|
||||
```
|
||||
|
||||
## Разработка
|
||||
@@ -301,7 +301,7 @@ cargo fmt
|
||||
cargo clippy --all --benches --tests --examples --all-features
|
||||
|
||||
# Запуск тестов
|
||||
createdb ironclaw_test
|
||||
createdb optimclaw_test
|
||||
cargo test
|
||||
|
||||
# Запуск конкретного теста
|
||||
@@ -313,7 +313,7 @@ cargo test название_теста
|
||||
|
||||
## Наследие OpenClaw
|
||||
|
||||
IronClaw — это реализация на Rust, вдохновленная проектом [OpenClaw](https://github.com/openclaw/openclaw). Полную матрицу соответствия функций можно найти в [FEATURE_PARITY.md](FEATURE_PARITY.md).
|
||||
OptimClaw — это реализация на Rust, вдохновленная проектом [OpenClaw](https://github.com/openclaw/openclaw). Полную матрицу соответствия функций можно найти в [FEATURE_PARITY.md](FEATURE_PARITY.md).
|
||||
|
||||
Ключевые отличия:
|
||||
|
||||
|
||||
+26
-26
@@ -1,8 +1,8 @@
|
||||
<p align="center">
|
||||
<img src="ironclaw.png?v=2" alt="IronClaw" width="200"/>
|
||||
<img src="optimclaw.png?v=2" alt="OptimClaw" width="200"/>
|
||||
</p>
|
||||
|
||||
<h1 align="center">IronClaw</h1>
|
||||
<h1 align="center">OptimClaw</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>安全可靠的个人 AI 助手,始终站在你这边</strong>
|
||||
@@ -10,8 +10,8 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache%202.0-blue.svg" alt="License: MIT OR Apache-2.0" /></a>
|
||||
<a href="https://t.me/ironclawAI"><img src="https://img.shields.io/badge/Telegram-%40ironclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @ironclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/ironclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FironclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/ironclawAI" /></a>
|
||||
<a href="https://t.me/optimclawAI"><img src="https://img.shields.io/badge/Telegram-%40optimclawAI-26A5E4?style=flat&logo=telegram&logoColor=white" alt="Telegram: @optimclawAI" /></a>
|
||||
<a href="https://www.reddit.com/r/optimclawAI/"><img src="https://img.shields.io/badge/Reddit-r%2FoptimclawAI-FF4500?style=flat&logo=reddit&logoColor=white" alt="Reddit: r/optimclawAI" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -34,16 +34,16 @@
|
||||
|
||||
## 设计理念
|
||||
|
||||
IronClaw 基于一个简单的原则:**你的 AI 助手应该为你服务,而不是与你为敌。**
|
||||
OptimClaw 基于一个简单的原则:**你的 AI 助手应该为你服务,而不是与你为敌。**
|
||||
|
||||
在 AI 系统对数据处理日益不透明、与企业利益捆绑的今天,IronClaw 选择了一条不同的路:
|
||||
在 AI 系统对数据处理日益不透明、与企业利益捆绑的今天,OptimClaw 选择了一条不同的路:
|
||||
|
||||
- **数据归你所有** — 所有信息存储在本地,加密保护,始终在你掌控之下
|
||||
- **透明至上** — 完全开源,可审计,没有隐藏的遥测或数据收集
|
||||
- **自主扩展** — 随时构建新工具,无需等待供应商更新
|
||||
- **纵深防御** — 多层安全机制抵御提示注入和数据泄露
|
||||
|
||||
IronClaw 是一个你真正可以信赖的 AI 助手,无论是个人生活还是工作。
|
||||
OptimClaw 是一个你真正可以信赖的 AI 助手,无论是个人生活还是工作。
|
||||
|
||||
## 功能特性
|
||||
|
||||
@@ -66,7 +66,7 @@ IronClaw 是一个你真正可以信赖的 AI 助手,无论是个人生活还
|
||||
|
||||
### 自主扩展
|
||||
|
||||
- **动态工具构建** — 描述你的需求,IronClaw 会将其构建为 WASM 工具
|
||||
- **动态工具构建** — 描述你的需求,OptimClaw 会将其构建为 WASM 工具
|
||||
- **MCP 协议** — 连接模型上下文协议(Model Context Protocol)服务器以获取额外能力
|
||||
- **插件架构** — 无需重启即可加载新的 WASM 工具和渠道
|
||||
|
||||
@@ -86,12 +86,12 @@ IronClaw 是一个你真正可以信赖的 AI 助手,无论是个人生活还
|
||||
|
||||
## 下载或编译
|
||||
|
||||
访问 [Releases 页面](https://github.com/nearai/ironclaw/releases/) 查看最新版本。
|
||||
访问 [Releases 页面](https://github.com/nearai/optimclaw/releases/) 查看最新版本。
|
||||
|
||||
<details>
|
||||
<summary>通过 Windows 安装程序安装 (Windows)</summary>
|
||||
|
||||
下载 [Windows 安装程序](https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-x86_64-pc-windows-msvc.msi) 并运行。
|
||||
下载 [Windows 安装程序](https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-x86_64-pc-windows-msvc.msi) 并运行。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -99,7 +99,7 @@ IronClaw 是一个你真正可以信赖的 AI 助手,无论是个人生活还
|
||||
<summary>通过 PowerShell 脚本安装 (Windows)</summary>
|
||||
|
||||
```sh
|
||||
irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.ps1 | iex
|
||||
irm https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.ps1 | iex
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -108,7 +108,7 @@ irm https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-install
|
||||
<summary>通过 Shell 脚本安装 (macOS、Linux、Windows/WSL)</summary>
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/releases/latest/download/ironclaw-installer.sh | sh
|
||||
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/optimclaw/releases/latest/download/optimclaw-installer.sh | sh
|
||||
```
|
||||
</details>
|
||||
|
||||
@@ -116,7 +116,7 @@ curl --proto '=https' --tlsv1.2 -LsSf https://github.com/nearai/ironclaw/release
|
||||
<summary>通过 Homebrew 安装 (macOS/Linux)</summary>
|
||||
|
||||
```sh
|
||||
brew install ironclaw
|
||||
brew install optimclaw
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -128,8 +128,8 @@ brew install ironclaw
|
||||
|
||||
```bash
|
||||
# 克隆仓库
|
||||
git clone https://github.com/nearai/ironclaw.git
|
||||
cd ironclaw
|
||||
git clone https://github.com/nearai/optimclaw.git
|
||||
cd optimclaw
|
||||
|
||||
# 编译
|
||||
cargo build --release
|
||||
@@ -146,25 +146,25 @@ cargo test
|
||||
|
||||
```bash
|
||||
# 创建数据库
|
||||
createdb ironclaw
|
||||
createdb optimclaw
|
||||
|
||||
# 启用 pgvector 扩展
|
||||
psql ironclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
psql optimclaw -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||
```
|
||||
|
||||
## 配置
|
||||
|
||||
运行设置向导来配置 IronClaw:
|
||||
运行设置向导来配置 OptimClaw:
|
||||
|
||||
```bash
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
```
|
||||
|
||||
向导将引导你完成数据库连接、NEAR AI 身份验证(通过浏览器 OAuth)和密钥加密(使用系统钥匙串)。设置会保存在数据库中;引导变量(如 `DATABASE_URL`、`LLM_BACKEND`)写入 `~/.ironclaw/.env`,以便在数据库连接前可用。
|
||||
向导将引导你完成数据库连接、NEAR AI 身份验证(通过浏览器 OAuth)和密钥加密(使用系统钥匙串)。设置会保存在数据库中;引导变量(如 `DATABASE_URL`、`LLM_BACKEND`)写入 `~/.optimclaw/.env`,以便在数据库连接前可用。
|
||||
|
||||
### 替代 LLM 提供商
|
||||
|
||||
IronClaw 默认使用 NEAR AI,但开箱即用地支持多种 LLM 提供商。
|
||||
OptimClaw 默认使用 NEAR AI,但开箱即用地支持多种 LLM 提供商。
|
||||
内置提供商包括 **Anthropic**、**OpenAI**、**GitHub Copilot**、**Google Gemini**、**MiniMax**、**Mistral** 和 **Ollama**(本地部署)。同时也支持 OpenAI 兼容服务,如 **OpenRouter**(300+ 模型)、**Together AI**、**Fireworks AI** 以及自托管服务器(**vLLM**、**LiteLLM**)。
|
||||
|
||||
在向导中选择你的提供商,或直接设置环境变量:
|
||||
@@ -185,7 +185,7 @@ LLM_MODEL=anthropic/claude-sonnet-4
|
||||
|
||||
## 安全机制
|
||||
|
||||
IronClaw 实现了纵深防御策略来保护你的数据并防止滥用。
|
||||
OptimClaw 实现了纵深防御策略来保护你的数据并防止滥用。
|
||||
|
||||
### WASM 沙箱
|
||||
|
||||
@@ -278,13 +278,13 @@ WASM ──► 白名单 ──► 泄露扫描 ──► 凭据 ──► 执
|
||||
|
||||
```bash
|
||||
# 首次设置(配置数据库、认证等)
|
||||
ironclaw onboard
|
||||
optimclaw onboard
|
||||
|
||||
# 启动交互式 REPL
|
||||
cargo run
|
||||
|
||||
# 启用调试日志
|
||||
RUST_LOG=ironclaw=debug cargo run
|
||||
RUST_LOG=optimclaw=debug cargo run
|
||||
```
|
||||
|
||||
## 开发
|
||||
@@ -297,7 +297,7 @@ cargo fmt
|
||||
cargo clippy --all --benches --tests --examples --all-features
|
||||
|
||||
# 运行测试
|
||||
createdb ironclaw_test
|
||||
createdb optimclaw_test
|
||||
cargo test
|
||||
|
||||
# 运行指定测试
|
||||
@@ -309,7 +309,7 @@ cargo test test_name
|
||||
|
||||
## OpenClaw 传承
|
||||
|
||||
IronClaw 是受 [OpenClaw](https://github.com/openclaw/openclaw) 启发的 Rust 重新实现。参见 [FEATURE_PARITY.md](FEATURE_PARITY.md) 了解完整的功能追踪矩阵。
|
||||
OptimClaw 是受 [OpenClaw](https://github.com/openclaw/openclaw) 启发的 Rust 重新实现。参见 [FEATURE_PARITY.md](FEATURE_PARITY.md) 了解完整的功能追踪矩阵。
|
||||
|
||||
主要差异:
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
||||
use ironclaw::safety::{LeakDetector, Sanitizer, Validator};
|
||||
use optimclaw::safety::{LeakDetector, Sanitizer, Validator};
|
||||
|
||||
fn bench_sanitizer(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("sanitizer");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
||||
use ironclaw::config::SafetyConfig;
|
||||
use ironclaw::safety::{SafetyLayer, Validator};
|
||||
use optimclaw::config::SafetyConfig;
|
||||
use optimclaw::safety::{SafetyLayer, Validator};
|
||||
|
||||
fn bench_safety_layer_pipeline(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("safety_pipeline");
|
||||
|
||||
Generated
+11
-216
@@ -20,162 +20,33 @@ version = "1.0.102"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "discord-channel"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
dependencies = [
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
@@ -197,12 +68,6 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
@@ -223,9 +88,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.17"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "leb128"
|
||||
@@ -233,12 +98,6 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.182"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.29"
|
||||
@@ -253,19 +112,9 @@ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.3"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
@@ -288,22 +137,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.44"
|
||||
version = "1.0.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
|
||||
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.27"
|
||||
@@ -353,23 +193,6 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.1"
|
||||
@@ -385,22 +208,6 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.117"
|
||||
@@ -412,12 +219,6 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
@@ -575,30 +376,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.39"
|
||||
version = "0.8.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a"
|
||||
checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.39"
|
||||
version = "0.8.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517"
|
||||
checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.21"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
[package]
|
||||
name = "discord-channel"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
edition = "2021"
|
||||
description = "Discord channel for IronClaw"
|
||||
description = "Discord channel for OptimClaw"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
@@ -10,8 +10,6 @@ publish = false
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
wit-bindgen = "0.36"
|
||||
ed25519-dalek = { version = "2", default-features = false, features = ["alloc", "fast", "zeroize"] }
|
||||
hex = "0.4"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Discord Channel for IronClaw
|
||||
# Discord Channel for OptimClaw
|
||||
|
||||
WASM channel for Discord integration - handle slash commands and button interactions via webhooks.
|
||||
|
||||
@@ -13,12 +13,12 @@ WASM channel for Discord integration - handle slash commands and button interact
|
||||
|
||||
1. Create a Discord Application at <https://discord.com/developers/applications>
|
||||
2. Create a Bot and get the token
|
||||
3. Set up Interactions URL to point to your IronClaw instance
|
||||
3. Set up Interactions URL to point to your OptimClaw instance
|
||||
4. Copy the Application ID and Public Key
|
||||
5. Store in IronClaw secrets:
|
||||
5. Store in OptimClaw secrets:
|
||||
|
||||
```bash
|
||||
ironclaw secret set discord_bot_token YOUR_BOT_TOKEN
|
||||
optimclaw secret set discord_bot_token YOUR_BOT_TOKEN
|
||||
```
|
||||
|
||||
**Note:** The `discord_bot_token` secret is used for Discord REST API calls.
|
||||
@@ -51,7 +51,7 @@ curl -X POST \
|
||||
|
||||
In your Discord app settings, set:
|
||||
|
||||
- Interactions Endpoint URL: `https://your-ironclaw.com/webhook/discord`
|
||||
- Interactions Endpoint URL: `https://your-optimclaw.com/webhook/discord`
|
||||
|
||||
## Usage Examples
|
||||
|
||||
@@ -86,6 +86,24 @@ If an internal error occurs (e.g., metadata serialization failure), the tool att
|
||||
Check the host logs for detailed error information.
|
||||
|
||||
## Advanced Usage
|
||||
### Gateway Mode
|
||||
|
||||
The Discord channel now defaults to Discord Gateway transport for inbound message intake.
|
||||
The bundled identify payload requests intents `4609`, which expands to:
|
||||
|
||||
- `GUILDS` (`1`)
|
||||
- `GUILD_MESSAGES` (`512`)
|
||||
- `DIRECT_MESSAGES` (`4096`)
|
||||
|
||||
Gateway DMs now follow the same pairing policy as webhook DMs. Unpaired users receive a pairing
|
||||
instruction reply in the DM channel before the message is allowed through to the agent. If you
|
||||
want stricter access control than pairing, set `owner_id`; that lock still applies to both
|
||||
webhook and Gateway traffic.
|
||||
|
||||
Gateway presence simply reflects a successful authenticated Gateway connection and advertises
|
||||
`online`. Pairing still controls whether DMs are allowed through to the agent, but it no longer
|
||||
changes the visible Discord status.
|
||||
|
||||
### Mention Polling
|
||||
|
||||
The Discord channel can also poll configured channels for `@bot` mentions.
|
||||
@@ -110,6 +128,7 @@ Example channel config:
|
||||
- `owner_id`: when set, only that Discord user can interact with the bot.
|
||||
- `dm_policy`: `open` allows all DMs; `pairing` requires approval.
|
||||
- `allow_from`: allowlist entries for DM pairing checks (`*`, user id, or username).
|
||||
- Gateway DMs respect `dm_policy` and pairing just like webhook DMs.
|
||||
|
||||
### Embeds
|
||||
|
||||
@@ -127,7 +146,7 @@ To send embeds, include an `embeds` array in the `metadata_json` field of the ag
|
||||
|
||||
### "401 Unauthorized"
|
||||
|
||||
- Check that `discord_bot_token` is set correctly in IronClaw secrets.
|
||||
- Check that `discord_bot_token` is set correctly in OptimClaw secrets.
|
||||
- Ensure the bot is added to the server.
|
||||
|
||||
### "Interaction Failed"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.1",
|
||||
"wit_version": "0.3.0",
|
||||
"type": "channel",
|
||||
"name": "discord",
|
||||
@@ -22,7 +22,8 @@
|
||||
"capabilities": {
|
||||
"http": {
|
||||
"allowlist": [
|
||||
{ "host": "discord.com", "path_prefix": "/api/v10" }
|
||||
{ "host": "discord.com", "path_prefix": "/api/v10" },
|
||||
{ "host": "gateway.discord.gg", "path_prefix": "/", "methods": ["GET"] }
|
||||
],
|
||||
"credentials": {
|
||||
"discord_bot_token": {
|
||||
@@ -36,6 +37,20 @@
|
||||
"requests_per_hour": 3600
|
||||
}
|
||||
},
|
||||
"websocket": {
|
||||
"url": "wss://gateway.discord.gg/?v=10&encoding=json",
|
||||
"connect_on_start": true,
|
||||
"identify_secret_name": "discord_bot_token",
|
||||
"identify": {
|
||||
"_intents_doc": "GUILDS(1) + GUILD_MESSAGES(512) + DIRECT_MESSAGES(4096)",
|
||||
"intents": 4609,
|
||||
"properties": {
|
||||
"os": "linux",
|
||||
"browser": "ironclaw",
|
||||
"device": "ironclaw"
|
||||
}
|
||||
}
|
||||
},
|
||||
"secrets": {
|
||||
"allowed_names": ["discord_bot_token", "discord_*"]
|
||||
},
|
||||
|
||||
+1630
-972
File diff suppressed because it is too large
Load Diff
Generated
+7
@@ -44,6 +44,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"subtle",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
@@ -208,6 +209,12 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.117"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "feishu-channel"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Feishu/Lark Bot channel for IronClaw"
|
||||
description = "Feishu/Lark Bot channel for OptimClaw"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[lib]
|
||||
@@ -15,6 +15,7 @@ wit-bindgen = "0.36"
|
||||
# Serialization
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
subtle = "2.6"
|
||||
|
||||
# Exclude from parent workspace (this is a standalone WASM component)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"auth": {
|
||||
"secret_name": "feishu_app_id",
|
||||
"display_name": "Feishu / Lark",
|
||||
"instructions": "Create a bot at https://open.feishu.cn/app (Feishu) or https://open.larksuite.com/app (Lark). You need the App ID and App Secret. Note: IronClaw supports Event Subscription webhook delivery, but not Feishu's long-connection websocket mode.",
|
||||
"instructions": "Create a bot at https://open.feishu.cn/app (Feishu) or https://open.larksuite.com/app (Lark). You need the App ID and App Secret. Note: OptimClaw supports Event Subscription webhook delivery, but not Feishu's long-connection websocket mode.",
|
||||
"setup_url": "https://open.feishu.cn/app",
|
||||
"token_hint": "App ID looks like cli_XXXX, App Secret is a long alphanumeric string",
|
||||
"env_var": "FEISHU_APP_ID"
|
||||
@@ -27,7 +27,7 @@
|
||||
{
|
||||
"name": "feishu_verification_token",
|
||||
"prompt": "Enter your Feishu/Lark Verification Token (from Event Subscription webhook settings)",
|
||||
"optional": true
|
||||
"optional": false
|
||||
}
|
||||
],
|
||||
"setup_url": "https://open.feishu.cn/app"
|
||||
@@ -63,13 +63,15 @@
|
||||
},
|
||||
"webhook": {
|
||||
"secret_header": "X-Feishu-Verification-Token",
|
||||
"secret_name": "feishu_verification_token"
|
||||
"secret_name": "feishu_verification_token",
|
||||
"managed_by_host": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"app_id": null,
|
||||
"app_secret": null,
|
||||
"verification_token": null,
|
||||
"api_base": "https://open.feishu.cn",
|
||||
"owner_id": null,
|
||||
"dm_policy": "pairing",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// Feishu API types have fields reserved for future use.
|
||||
#![allow(dead_code)]
|
||||
|
||||
//! Feishu/Lark Bot channel for IronClaw.
|
||||
//! Feishu/Lark Bot channel for OptimClaw.
|
||||
//!
|
||||
//! This WASM component implements the channel interface for handling Feishu
|
||||
//! webhooks (Event Subscription v2.0) and sending messages back via the
|
||||
//! Feishu/Lark Bot API. IronClaw currently does not connect to Feishu's
|
||||
//! Feishu/Lark Bot API. OptimClaw currently does not connect to Feishu's
|
||||
//! long-connection websocket subscription mode; use Event Subscription
|
||||
//! webhooks for this channel.
|
||||
//!
|
||||
@@ -23,7 +23,8 @@
|
||||
//! - App credentials (app_id, app_secret) are injected by the host into
|
||||
//! the config JSON during startup for token exchange
|
||||
//! - Bearer token for API calls is obtained via token exchange and cached
|
||||
//! - Verification token validated by host for webhook requests
|
||||
//! - Webhook requests must be authenticated by the host or by a matching
|
||||
//! Feishu verification token in the request body
|
||||
|
||||
// Generate bindings from the WIT file
|
||||
wit_bindgen::generate!({
|
||||
@@ -32,6 +33,7 @@ wit_bindgen::generate!({
|
||||
});
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
// Re-export generated types
|
||||
use exports::near::agent::channel::{
|
||||
@@ -50,6 +52,7 @@ const ALLOW_FROM_PATH: &str = "allow_from";
|
||||
const API_BASE_PATH: &str = "api_base";
|
||||
const APP_ID_PATH: &str = "app_id";
|
||||
const APP_SECRET_PATH: &str = "app_secret";
|
||||
const VERIFICATION_TOKEN_PATH: &str = "verification_token";
|
||||
const TOKEN_PATH: &str = "tenant_access_token";
|
||||
const TOKEN_EXPIRY_PATH: &str = "token_expiry";
|
||||
|
||||
@@ -102,6 +105,10 @@ struct FeishuEventHeader {
|
||||
/// Tenant key.
|
||||
#[serde(default)]
|
||||
tenant_key: Option<String>,
|
||||
|
||||
/// Verification token for v2 event payloads.
|
||||
#[serde(default)]
|
||||
token: Option<String>,
|
||||
}
|
||||
|
||||
/// Message receive event payload (im.message.receive_v1).
|
||||
@@ -251,6 +258,9 @@ struct FeishuConfig {
|
||||
/// Feishu App Secret (for token exchange).
|
||||
app_secret: Option<String>,
|
||||
|
||||
/// Feishu Event Subscription verification token.
|
||||
verification_token: Option<String>,
|
||||
|
||||
/// API base URL. Defaults to "https://open.feishu.cn" (use
|
||||
/// "https://open.larksuite.com" for Lark international).
|
||||
#[serde(default = "default_api_base")]
|
||||
@@ -300,6 +310,9 @@ impl Guest for FeishuChannel {
|
||||
if let Some(ref app_secret) = config.app_secret {
|
||||
let _ = channel_host::workspace_write(APP_SECRET_PATH, app_secret);
|
||||
}
|
||||
if let Some(ref verification_token) = config.verification_token {
|
||||
let _ = channel_host::workspace_write(VERIFICATION_TOKEN_PATH, verification_token);
|
||||
}
|
||||
|
||||
if let Some(owner_id) = &config.owner_id {
|
||||
let _ = channel_host::workspace_write(OWNER_ID_PATH, owner_id);
|
||||
@@ -376,6 +389,23 @@ impl Guest for FeishuChannel {
|
||||
}
|
||||
};
|
||||
|
||||
let configured_token =
|
||||
channel_host::workspace_read(VERIFICATION_TOKEN_PATH).filter(|token| !token.is_empty());
|
||||
if !is_authenticated_webhook(
|
||||
req.secret_validated,
|
||||
configured_token.as_deref(),
|
||||
request_verification_token(&event),
|
||||
) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
"Rejecting unauthenticated Feishu webhook request",
|
||||
);
|
||||
return json_response(
|
||||
401,
|
||||
serde_json::json!({"error": "Webhook authentication failed"}),
|
||||
);
|
||||
}
|
||||
|
||||
// Handle URL verification challenge (initial webhook setup).
|
||||
if event.event_type.as_deref() == Some("url_verification") {
|
||||
if let Some(challenge) = &event.challenge {
|
||||
@@ -839,6 +869,31 @@ fn json_response(status: u16, body: serde_json::Value) -> OutgoingHttpResponse {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_authenticated_webhook(
|
||||
secret_validated: bool,
|
||||
configured_token: Option<&str>,
|
||||
request_token: Option<&str>,
|
||||
) -> bool {
|
||||
if secret_validated {
|
||||
return true;
|
||||
}
|
||||
|
||||
match (configured_token, request_token) {
|
||||
(Some(expected), Some(provided)) => {
|
||||
bool::from(expected.as_bytes().ct_eq(provided.as_bytes()))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn request_verification_token(event: &FeishuEvent) -> Option<&str> {
|
||||
event
|
||||
.header
|
||||
.as_ref()
|
||||
.and_then(|header| header.token.as_deref())
|
||||
.or(event.token.as_deref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -862,7 +917,10 @@ mod tests {
|
||||
fn parse_token_response_rejects_missing_token() {
|
||||
let json = r#"{"code": 0, "msg": "ok", "expire": 7200}"#;
|
||||
let result: Result<TenantAccessTokenResponse, _> = serde_json::from_str(json);
|
||||
assert!(result.is_err(), "should fail when tenant_access_token is missing");
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"should fail when tenant_access_token is missing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -894,4 +952,64 @@ mod tests {
|
||||
assert_eq!(resp.code, 10003);
|
||||
assert!(resp.tenant_access_token.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webhook_auth_requires_host_auth_or_matching_verification_token() {
|
||||
assert!(
|
||||
!is_authenticated_webhook(false, None, Some("token")),
|
||||
"requests without any configured verification mechanism must be rejected"
|
||||
);
|
||||
assert!(
|
||||
!is_authenticated_webhook(false, Some("expected"), None),
|
||||
"requests missing the Feishu token must be rejected when host auth did not pass"
|
||||
);
|
||||
assert!(
|
||||
!is_authenticated_webhook(false, Some("expected"), Some("wrong")),
|
||||
"requests with the wrong Feishu token must be rejected"
|
||||
);
|
||||
assert!(
|
||||
is_authenticated_webhook(false, Some("expected"), Some("expected")),
|
||||
"matching Feishu verification token should authenticate the request"
|
||||
);
|
||||
assert!(
|
||||
is_authenticated_webhook(true, None, None),
|
||||
"host-authenticated requests should still be accepted"
|
||||
);
|
||||
assert!(
|
||||
is_authenticated_webhook(true, Some("expected"), Some("wrong")),
|
||||
"host authentication should take precedence over body token checks"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_verification_token_prefers_v2_header_token() {
|
||||
let event: FeishuEvent = serde_json::from_str(
|
||||
r#"{
|
||||
"schema": "2.0",
|
||||
"header": {
|
||||
"event_id": "evt_123",
|
||||
"event_type": "im.message.receive_v1",
|
||||
"token": "header-token"
|
||||
},
|
||||
"event": {}
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(request_verification_token(&event), Some("header-token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_verification_token_falls_back_to_top_level_token() {
|
||||
let event: FeishuEvent = serde_json::from_str(
|
||||
r#"{
|
||||
"type": "url_verification",
|
||||
"challenge": "abc",
|
||||
"token": "top-level-token"
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(request_verification_token(&event), Some("top-level-token"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "slack-channel"
|
||||
version = "0.2.1"
|
||||
edition = "2021"
|
||||
description = "Slack Events API channel for IronClaw"
|
||||
description = "Slack Events API channel for OptimClaw"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Slack Events API channel for IronClaw.
|
||||
//! Slack Events API channel for OptimClaw.
|
||||
//!
|
||||
//! This WASM component implements the channel interface for handling Slack
|
||||
//! webhooks and sending messages back to Slack.
|
||||
@@ -650,7 +650,7 @@ fn send_pairing_reply(channel_id: &str, code: &str) -> Result<(), String> {
|
||||
let payload = serde_json::json!({
|
||||
"channel": channel_id,
|
||||
"text": format!(
|
||||
"To pair with this bot, run: `ironclaw pairing approve slack {}`",
|
||||
"To pair with this bot, run: `optimclaw pairing approve slack {}`",
|
||||
code
|
||||
),
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "telegram-channel"
|
||||
version = "0.2.1"
|
||||
edition = "2021"
|
||||
description = "Telegram Bot API channel for IronClaw"
|
||||
description = "Telegram Bot API channel for OptimClaw"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[lib]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Telegram API types have fields reserved for future use (entities, reply threading, etc.)
|
||||
#![allow(dead_code)]
|
||||
|
||||
//! Telegram Bot API channel for IronClaw.
|
||||
//! Telegram Bot API channel for OptimClaw.
|
||||
//!
|
||||
//! This WASM component implements the channel interface for handling Telegram
|
||||
//! webhooks and sending messages back via the Bot API.
|
||||
@@ -1170,7 +1170,7 @@ fn send_photo(
|
||||
);
|
||||
}
|
||||
|
||||
let boundary = format!("ironclaw-{}", channel_host::now_millis());
|
||||
let boundary = format!("optimclaw-{}", channel_host::now_millis());
|
||||
let mut body = Vec::new();
|
||||
|
||||
write_multipart_field(&mut body, &boundary, "chat_id", &chat_id.to_string());
|
||||
@@ -1235,7 +1235,7 @@ fn send_document(
|
||||
) -> Result<(), String> {
|
||||
let message_thread_id = normalize_thread_id(message_thread_id);
|
||||
|
||||
let boundary = format!("ironclaw-{}", channel_host::now_millis());
|
||||
let boundary = format!("optimclaw-{}", channel_host::now_millis());
|
||||
let mut body = Vec::new();
|
||||
|
||||
write_multipart_field(&mut body, &boundary, "chat_id", &chat_id.to_string());
|
||||
@@ -1552,7 +1552,7 @@ fn send_pairing_reply(chat_id: i64, code: &str) -> Result<(), String> {
|
||||
send_message(
|
||||
chat_id,
|
||||
&format!(
|
||||
"To pair with this bot, run: `ironclaw pairing approve telegram {}`",
|
||||
"To pair with this bot, run: `optimclaw pairing approve telegram {}`",
|
||||
code
|
||||
),
|
||||
None,
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
/target
|
||||
/*.wasm
|
||||
Generated
-568
@@ -1,568 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.102"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "id-arena"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.16.1",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "leb128"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.183"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.149"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
|
||||
|
||||
[[package]]
|
||||
name = "spdx"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3"
|
||||
dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.220.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e913f9242315ca39eff82aee0e19ee7a372155717ff0eb082c741e435ce25ed1"
|
||||
dependencies = [
|
||||
"leb128",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-metadata"
|
||||
version = "0.220.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "185dfcd27fa5db2e6a23906b54c28199935f71d9a27a1a27b3a88d6fee2afae7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"indexmap",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"spdx",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.220.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d07b6a3b550fefa1a914b6d54fc175dd11c3392da11eee604e6ffc759805d25"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bitflags",
|
||||
"hashbrown 0.14.5",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wechat-channel"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"base64",
|
||||
"cipher",
|
||||
"md-5",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a2b3e15cd6068f233926e7d8c7c588b2ec4fb7cc7bf3824115e7c7e2a8485a3"
|
||||
dependencies = [
|
||||
"wit-bindgen-rt",
|
||||
"wit-bindgen-rust-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-core"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b632a5a0fa2409489bd49c9e6d99fcc61bb3d4ce9d1907d44662e75a28c71172"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rt"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7947d0131c7c9da3f01dfde0ab8bd4c4cf3c5bd49b6dba0ae640f1fa752572ea"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4329de4186ee30e2ef30a0533f9b3c123c019a237a7c82d692807bf1b3ee2697"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"heck",
|
||||
"indexmap",
|
||||
"prettyplease",
|
||||
"syn",
|
||||
"wasm-metadata",
|
||||
"wit-bindgen-core",
|
||||
"wit-component",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen-rust-macro"
|
||||
version = "0.36.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "177fb7ee1484d113b4792cc480b1ba57664bbc951b42a4beebe573502135b1fc"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wit-bindgen-core",
|
||||
"wit-bindgen-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-component"
|
||||
version = "0.220.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b505603761ed400c90ed30261f44a768317348e49f1864e82ecdc3b2744e5627"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags",
|
||||
"indexmap",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-parser"
|
||||
version = "0.220.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae2a7999ed18efe59be8de2db9cb2b7f84d88b27818c79353dfc53131840fe1a"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"id-arena",
|
||||
"indexmap",
|
||||
"log",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"unicode-xid",
|
||||
"wasmparser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
|
||||
@@ -1,27 +0,0 @@
|
||||
[package]
|
||||
name = "wechat-channel"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "WeChat iLink Bot channel for IronClaw"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
wit-bindgen = "0.36"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
base64 = "0.22"
|
||||
aes = "0.8"
|
||||
cipher = "0.4"
|
||||
md-5 = "0.10"
|
||||
rand = "0.8"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
|
||||
[workspace]
|
||||
@@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
echo "Building WeChat channel WASM component..."
|
||||
|
||||
cargo build --release --target wasm32-wasip2
|
||||
|
||||
WASM_PATH="target/wasm32-wasip2/release/wechat_channel.wasm"
|
||||
|
||||
if [ -f "$WASM_PATH" ]; then
|
||||
if command -v wasm-tools >/dev/null 2>&1; then
|
||||
wasm-tools component new "$WASM_PATH" -o wechat.wasm 2>/dev/null || cp "$WASM_PATH" wechat.wasm
|
||||
wasm-tools strip wechat.wasm -o wechat.wasm
|
||||
else
|
||||
cp "$WASM_PATH" wechat.wasm
|
||||
echo "wasm-tools not found; copied raw wasm output without component conversion/strip"
|
||||
fi
|
||||
|
||||
echo "Built: wechat.wasm ($(du -h wechat.wasm | cut -f1))"
|
||||
echo ""
|
||||
echo "To install:"
|
||||
echo " mkdir -p ~/.ironclaw/channels"
|
||||
echo " cp wechat.wasm wechat.capabilities.json ~/.ironclaw/channels/"
|
||||
else
|
||||
echo "Error: WASM output not found at $WASM_PATH"
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,277 +0,0 @@
|
||||
use base64::Engine as _;
|
||||
|
||||
use crate::near::agent::channel_host;
|
||||
use crate::types::{
|
||||
BaseInfo, GetConfigRequest, GetConfigResponse, GetUpdatesRequest, GetUpdatesResponse,
|
||||
GetUploadUrlRequest, GetUploadUrlResponse, MessageItem, OutboundWechatMessage,
|
||||
SendMessageRequest, SendTypingRequest, SendTypingResponse, TextItem, WechatConfig,
|
||||
MESSAGE_ITEM_TEXT, MESSAGE_STATE_FINISH, MESSAGE_TYPE_BOT,
|
||||
};
|
||||
|
||||
pub fn base_info() -> BaseInfo {
|
||||
BaseInfo {
|
||||
channel_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_trailing_slash(base_url: &str) -> String {
|
||||
if base_url.ends_with('/') {
|
||||
base_url.to_string()
|
||||
} else {
|
||||
format!("{base_url}/")
|
||||
}
|
||||
}
|
||||
|
||||
fn random_wechat_uin() -> String {
|
||||
let seed = (channel_host::now_millis() % u32::MAX as u64) as u32;
|
||||
base64::engine::general_purpose::STANDARD.encode(seed.to_string())
|
||||
}
|
||||
|
||||
fn request_headers(body: &[u8]) -> String {
|
||||
serde_json::json!({
|
||||
"Content-Type": "application/json",
|
||||
"AuthorizationType": "ilink_bot_token",
|
||||
"Authorization": "Bearer {WECHAT_BOT_TOKEN}",
|
||||
"Content-Length": body.len().to_string(),
|
||||
"X-WECHAT-UIN": random_wechat_uin(),
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn summarize_body_preview(bytes: &[u8], limit: usize) -> String {
|
||||
let preview = String::from_utf8_lossy(&bytes[..bytes.len().min(limit)]);
|
||||
let normalized = preview.replace(['\n', '\r'], " ");
|
||||
if bytes.len() > limit {
|
||||
format!("{normalized}...")
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_updates(
|
||||
config: &WechatConfig,
|
||||
get_updates_buf: &str,
|
||||
) -> Result<GetUpdatesResponse, String> {
|
||||
get_updates_with_timeout(config, get_updates_buf, config.long_poll_timeout_ms)
|
||||
}
|
||||
|
||||
pub fn get_updates_with_timeout(
|
||||
config: &WechatConfig,
|
||||
get_updates_buf: &str,
|
||||
timeout_ms: u32,
|
||||
) -> Result<GetUpdatesResponse, String> {
|
||||
let body = serde_json::to_vec(&GetUpdatesRequest {
|
||||
get_updates_buf: get_updates_buf.to_string(),
|
||||
base_info: base_info(),
|
||||
})
|
||||
.map_err(|e| format!("Failed to encode getUpdates request: {e}"))?;
|
||||
let headers = request_headers(&body);
|
||||
let url = format!(
|
||||
"{}ilink/bot/getupdates",
|
||||
ensure_trailing_slash(&config.base_url)
|
||||
);
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Info,
|
||||
&format!(
|
||||
"WeChat getUpdates request: cursor_len={} timeout_ms={}",
|
||||
get_updates_buf.len(),
|
||||
config.long_poll_timeout_ms
|
||||
),
|
||||
);
|
||||
let response =
|
||||
channel_host::http_request("POST", &url, &headers, Some(&body), Some(timeout_ms))
|
||||
.map_err(|e| format!("getUpdates request failed: {e}"))?;
|
||||
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Info,
|
||||
&format!(
|
||||
"WeChat getUpdates response: status={} bytes={} has_image_marker={} has_aeskey_marker={} preview={}",
|
||||
response.status,
|
||||
response.body.len(),
|
||||
response
|
||||
.body
|
||||
.windows(b"image_item".len())
|
||||
.any(|window| window == b"image_item"),
|
||||
response
|
||||
.body
|
||||
.windows(b"aeskey".len())
|
||||
.any(|window| window == b"aeskey"),
|
||||
summarize_body_preview(&response.body, 160)
|
||||
),
|
||||
);
|
||||
|
||||
if response.status != 200 {
|
||||
let body = String::from_utf8_lossy(&response.body);
|
||||
return Err(format!("getUpdates returned {}: {}", response.status, body));
|
||||
}
|
||||
|
||||
let parsed: GetUpdatesResponse = serde_json::from_slice(&response.body)
|
||||
.map_err(|e| format!("Failed to parse getUpdates response: {e}"))?;
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Info,
|
||||
&format!(
|
||||
"WeChat getUpdates parsed: ret={:?} errcode={:?} msg_count={} next_cursor_len={}",
|
||||
parsed.ret,
|
||||
parsed.errcode,
|
||||
parsed.msgs.len(),
|
||||
parsed.get_updates_buf.as_deref().unwrap_or_default().len()
|
||||
),
|
||||
);
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
pub fn send_text_message(
|
||||
config: &WechatConfig,
|
||||
to_user_id: &str,
|
||||
text: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let message = SendMessageRequest {
|
||||
msg: OutboundWechatMessage {
|
||||
from_user_id: String::new(),
|
||||
to_user_id: to_user_id.to_string(),
|
||||
client_id: format!("wechat-{}", channel_host::now_millis()),
|
||||
message_type: MESSAGE_TYPE_BOT,
|
||||
message_state: MESSAGE_STATE_FINISH,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_TEXT),
|
||||
text_item: Some(TextItem {
|
||||
text: text.to_string(),
|
||||
}),
|
||||
image_item: None,
|
||||
voice_item: None,
|
||||
file_item: None,
|
||||
}],
|
||||
context_token: context_token.map(str::to_string),
|
||||
},
|
||||
base_info: base_info(),
|
||||
};
|
||||
|
||||
send_message_request(config, &message)
|
||||
}
|
||||
|
||||
pub fn send_message_request(
|
||||
config: &WechatConfig,
|
||||
message: &SendMessageRequest,
|
||||
) -> Result<(), String> {
|
||||
let body = serde_json::to_vec(message)
|
||||
.map_err(|e| format!("Failed to encode sendMessage request: {e}"))?;
|
||||
let headers = request_headers(&body);
|
||||
let url = format!(
|
||||
"{}ilink/bot/sendmessage",
|
||||
ensure_trailing_slash(&config.base_url)
|
||||
);
|
||||
|
||||
let response = channel_host::http_request("POST", &url, &headers, Some(&body), Some(15_000))
|
||||
.map_err(|e| format!("sendMessage request failed: {e}"))?;
|
||||
|
||||
if response.status != 200 {
|
||||
let body = String::from_utf8_lossy(&response.body);
|
||||
return Err(format!(
|
||||
"sendMessage returned {}: {}",
|
||||
response.status, body
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_upload_url(
|
||||
config: &WechatConfig,
|
||||
request: &GetUploadUrlRequest,
|
||||
) -> Result<GetUploadUrlResponse, String> {
|
||||
let body = serde_json::to_vec(request)
|
||||
.map_err(|e| format!("Failed to encode getUploadUrl request: {e}"))?;
|
||||
let headers = request_headers(&body);
|
||||
let url = format!(
|
||||
"{}ilink/bot/getuploadurl",
|
||||
ensure_trailing_slash(&config.base_url)
|
||||
);
|
||||
|
||||
let response = channel_host::http_request("POST", &url, &headers, Some(&body), Some(15_000))
|
||||
.map_err(|e| format!("getUploadUrl request failed: {e}"))?;
|
||||
|
||||
if response.status != 200 {
|
||||
let body = String::from_utf8_lossy(&response.body);
|
||||
return Err(format!(
|
||||
"getUploadUrl returned {}: {}",
|
||||
response.status, body
|
||||
));
|
||||
}
|
||||
|
||||
serde_json::from_slice(&response.body)
|
||||
.map_err(|e| format!("Failed to parse getUploadUrl response: {e}"))
|
||||
}
|
||||
|
||||
pub fn get_config(
|
||||
config: &WechatConfig,
|
||||
ilink_user_id: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<GetConfigResponse, String> {
|
||||
let body = serde_json::to_vec(&GetConfigRequest {
|
||||
ilink_user_id: ilink_user_id.to_string(),
|
||||
context_token: context_token.map(str::to_string),
|
||||
base_info: base_info(),
|
||||
})
|
||||
.map_err(|e| format!("Failed to encode getConfig request: {e}"))?;
|
||||
let headers = request_headers(&body);
|
||||
let url = format!(
|
||||
"{}ilink/bot/getconfig",
|
||||
ensure_trailing_slash(&config.base_url)
|
||||
);
|
||||
|
||||
let response = channel_host::http_request("POST", &url, &headers, Some(&body), Some(10_000))
|
||||
.map_err(|e| format!("getConfig request failed: {e}"))?;
|
||||
|
||||
if response.status != 200 {
|
||||
let body = String::from_utf8_lossy(&response.body);
|
||||
return Err(format!("getConfig returned {}: {}", response.status, body));
|
||||
}
|
||||
|
||||
serde_json::from_slice(&response.body)
|
||||
.map_err(|e| format!("Failed to parse getConfig response: {e}"))
|
||||
}
|
||||
|
||||
pub fn send_typing(
|
||||
config: &WechatConfig,
|
||||
ilink_user_id: &str,
|
||||
typing_ticket: &str,
|
||||
status: i32,
|
||||
) -> Result<(), String> {
|
||||
let body = serde_json::to_vec(&SendTypingRequest {
|
||||
ilink_user_id: ilink_user_id.to_string(),
|
||||
typing_ticket: typing_ticket.to_string(),
|
||||
status,
|
||||
base_info: base_info(),
|
||||
})
|
||||
.map_err(|e| format!("Failed to encode sendTyping request: {e}"))?;
|
||||
let headers = request_headers(&body);
|
||||
let url = format!(
|
||||
"{}ilink/bot/sendtyping",
|
||||
ensure_trailing_slash(&config.base_url)
|
||||
);
|
||||
|
||||
let response = channel_host::http_request("POST", &url, &headers, Some(&body), Some(10_000))
|
||||
.map_err(|e| format!("sendTyping request failed: {e}"))?;
|
||||
|
||||
if response.status != 200 {
|
||||
let body = String::from_utf8_lossy(&response.body);
|
||||
return Err(format!("sendTyping returned {}: {}", response.status, body));
|
||||
}
|
||||
|
||||
let parsed: SendTypingResponse = serde_json::from_slice(&response.body)
|
||||
.map_err(|e| format!("Failed to parse sendTyping response: {e}"))?;
|
||||
|
||||
if parsed.ret.unwrap_or(0) != 0 {
|
||||
let errmsg = parsed
|
||||
.errmsg
|
||||
.as_deref()
|
||||
.unwrap_or("unknown WeChat sendTyping error");
|
||||
return Err(format!(
|
||||
"sendTyping returned ret={} errmsg={errmsg}",
|
||||
parsed.ret.unwrap_or(-1)
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
pub const TOKEN_SECRET_NAME: &str = "wechat_bot_token";
|
||||
pub const CONFIG_PATH: &str = "config.json";
|
||||
pub const GET_UPDATES_BUF_PATH: &str = "state/get_updates_buf.json";
|
||||
pub const CONTEXT_TOKENS_PATH: &str = "state/context_tokens.json";
|
||||
pub const TYPING_TICKETS_PATH: &str = "state/typing_tickets.json";
|
||||
pub const PENDING_INBOUND_PATH: &str = "state/pending_inbound.json";
|
||||
@@ -1,942 +0,0 @@
|
||||
wit_bindgen::generate!({
|
||||
world: "sandboxed-channel",
|
||||
path: "../../wit/channel.wit",
|
||||
});
|
||||
|
||||
mod api;
|
||||
mod auth;
|
||||
mod media;
|
||||
mod state;
|
||||
mod types;
|
||||
|
||||
use exports::near::agent::channel::{
|
||||
AgentResponse, ChannelConfig, Guest, PollConfig, StatusType, StatusUpdate,
|
||||
};
|
||||
use near::agent::channel_host::{self, EmittedMessage};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::auth::TOKEN_SECRET_NAME;
|
||||
use crate::state::{
|
||||
load_config, load_context_tokens, load_get_updates_buf, load_pending_inbound_bundles,
|
||||
load_typing_tickets, persist_config, persist_context_tokens, persist_get_updates_buf,
|
||||
persist_pending_inbound_bundles, persist_typing_tickets, PendingInboundBundle,
|
||||
StoredInboundAttachment, TypingTicketEntry,
|
||||
};
|
||||
use crate::types::{
|
||||
OutboundMetadata, WechatConfig, WechatMessage, MESSAGE_ITEM_TEXT, MESSAGE_TYPE_USER,
|
||||
TYPING_STATUS_CANCEL, TYPING_STATUS_TYPING,
|
||||
};
|
||||
|
||||
const TYPING_TICKET_TTL_MS: u64 = 24 * 60 * 60 * 1000;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum WechatStatusAction {
|
||||
Typing,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
struct WechatChannel;
|
||||
|
||||
impl Guest for WechatChannel {
|
||||
fn on_start(config_json: String) -> Result<ChannelConfig, String> {
|
||||
let config = serde_json::from_str::<WechatConfig>(&config_json)
|
||||
.map_err(|e| format!("Failed to parse WeChat config: {e}"))?;
|
||||
persist_config(&config)?;
|
||||
|
||||
Ok(ChannelConfig {
|
||||
display_name: "WeChat".to_string(),
|
||||
http_endpoints: Vec::new(),
|
||||
poll: Some(PollConfig {
|
||||
interval_ms: config.poll_interval_ms.max(30_000),
|
||||
enabled: true,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn on_http_request(
|
||||
_req: exports::near::agent::channel::IncomingHttpRequest,
|
||||
) -> exports::near::agent::channel::OutgoingHttpResponse {
|
||||
exports::near::agent::channel::OutgoingHttpResponse {
|
||||
status: 404,
|
||||
headers_json: "{}".to_string(),
|
||||
body: b"{\"error\":\"wechat channel does not expose webhooks\"}".to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn on_poll() {
|
||||
if !channel_host::secret_exists(TOKEN_SECRET_NAME) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
"WeChat bot token is missing; skipping poll",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let config = load_config();
|
||||
let cursor = load_get_updates_buf();
|
||||
let mut current_cursor = cursor.clone();
|
||||
let mut context_tokens = load_context_tokens();
|
||||
let mut pending_inbound = match load_pending_inbound_bundles() {
|
||||
Ok(bundles) => bundles,
|
||||
Err(error) => {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Error,
|
||||
&format!("Failed to load WeChat pending inbound bundles: {error}"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut pending_inbound_changed = false;
|
||||
|
||||
for bundle in take_due_pending_bundles(&mut pending_inbound, channel_host::now_millis()) {
|
||||
pending_inbound_changed = true;
|
||||
emit_buffered_bundle(bundle);
|
||||
}
|
||||
|
||||
match api::get_updates(&config, ¤t_cursor) {
|
||||
Ok(response) => {
|
||||
if response.errcode == Some(-14) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Error,
|
||||
"WeChat getUpdates returned errcode=-14; reconnect the channel",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if response.ret.unwrap_or(0) != 0 {
|
||||
let errmsg = response
|
||||
.errmsg
|
||||
.as_deref()
|
||||
.unwrap_or("unknown WeChat polling error");
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!(
|
||||
"WeChat getUpdates returned ret={} errmsg={errmsg}",
|
||||
response.ret.unwrap_or(-1)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(next_cursor) = response.get_updates_buf.as_deref() {
|
||||
if next_cursor != current_cursor {
|
||||
current_cursor = next_cursor.to_string();
|
||||
if let Err(error) = persist_get_updates_buf(next_cursor) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!("Failed to persist WeChat polling cursor: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut context_tokens_changed = false;
|
||||
for message in response.msgs {
|
||||
if let Some(from_user_id) = message.from_user_id.as_deref() {
|
||||
if let Some(context_token) = message.context_token.as_deref() {
|
||||
let changed = context_tokens
|
||||
.insert(from_user_id.to_string(), context_token.to_string())
|
||||
.as_deref()
|
||||
!= Some(context_token);
|
||||
context_tokens_changed |= changed;
|
||||
}
|
||||
}
|
||||
match incoming_bundle_from_message(&config, message) {
|
||||
Ok(Some(bundle)) => {
|
||||
let emitted = process_incoming_bundle(
|
||||
&mut pending_inbound,
|
||||
bundle,
|
||||
&mut pending_inbound_changed,
|
||||
channel_host::now_millis(),
|
||||
u64::from(config.inbound_merge_window_ms),
|
||||
);
|
||||
for emitted_bundle in emitted {
|
||||
emit_buffered_bundle(emitted_bundle);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Error,
|
||||
&format!("Failed to map WeChat inbound message: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collect_follow_up_bundles(
|
||||
&config,
|
||||
&mut current_cursor,
|
||||
&mut context_tokens,
|
||||
&mut context_tokens_changed,
|
||||
&mut pending_inbound,
|
||||
&mut pending_inbound_changed,
|
||||
);
|
||||
|
||||
for bundle in
|
||||
take_due_pending_bundles(&mut pending_inbound, channel_host::now_millis())
|
||||
{
|
||||
pending_inbound_changed = true;
|
||||
emit_buffered_bundle(bundle);
|
||||
}
|
||||
|
||||
if context_tokens_changed {
|
||||
if let Err(error) = persist_context_tokens(&context_tokens) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!("Failed to persist WeChat context tokens: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if pending_inbound_changed {
|
||||
if let Err(error) = persist_pending_inbound_bundles(&pending_inbound) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!("Failed to persist WeChat pending inbound bundles: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Error,
|
||||
&format!("WeChat polling failed: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_respond(response: AgentResponse) -> Result<(), String> {
|
||||
let metadata = serde_json::from_str::<OutboundMetadata>(&response.metadata_json)
|
||||
.map_err(|e| format!("Invalid WeChat response metadata: {e}"))?;
|
||||
let config = load_config();
|
||||
let context_tokens = load_context_tokens();
|
||||
let context_token = metadata
|
||||
.context_token
|
||||
.clone()
|
||||
.or_else(|| context_tokens.get(&metadata.from_user_id).cloned());
|
||||
if let Err(error) = send_typing_indicator(
|
||||
&config,
|
||||
&metadata,
|
||||
context_token.as_deref(),
|
||||
TYPING_STATUS_CANCEL,
|
||||
false,
|
||||
) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Debug,
|
||||
&format!("Failed to cancel WeChat typing indicator before reply: {error}"),
|
||||
);
|
||||
}
|
||||
|
||||
send_response(&config, &metadata, &response, context_token.as_deref())
|
||||
}
|
||||
|
||||
fn on_status(update: StatusUpdate) {
|
||||
let Some(action) = classify_status_update(&update) else {
|
||||
return;
|
||||
};
|
||||
let metadata = match serde_json::from_str::<OutboundMetadata>(&update.metadata_json) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(_) => {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Debug,
|
||||
"on_status: no valid WeChat metadata, skipping typing update",
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let config = load_config();
|
||||
let context_tokens = load_context_tokens();
|
||||
let context_token = resolve_context_token(&metadata, &context_tokens);
|
||||
|
||||
let (typing_status, allow_ticket_fetch) = match action {
|
||||
WechatStatusAction::Typing => (TYPING_STATUS_TYPING, true),
|
||||
WechatStatusAction::Cancel => (TYPING_STATUS_CANCEL, false),
|
||||
};
|
||||
|
||||
if let Err(error) = send_typing_indicator(
|
||||
&config,
|
||||
&metadata,
|
||||
context_token.as_deref(),
|
||||
typing_status,
|
||||
allow_ticket_fetch,
|
||||
) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Debug,
|
||||
&format!("WeChat typing update failed: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn on_broadcast(_user_id: String, _response: AgentResponse) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_shutdown() {}
|
||||
}
|
||||
|
||||
fn incoming_bundle_from_message(
|
||||
config: &WechatConfig,
|
||||
message: WechatMessage,
|
||||
) -> Result<Option<PendingInboundBundle>, String> {
|
||||
if message.message_type != Some(MESSAGE_TYPE_USER) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let from_user_id = match message.from_user_id.as_deref() {
|
||||
Some(user_id) => user_id,
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let text = extract_text(&message);
|
||||
let attachments = media::extract_inbound_attachments(config, &message)?
|
||||
.into_iter()
|
||||
.map(StoredInboundAttachment::from)
|
||||
.collect::<Vec<_>>();
|
||||
if text.trim().is_empty() && attachments.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(Some(PendingInboundBundle {
|
||||
from_user_id: from_user_id.to_string(),
|
||||
to_user_id: message.to_user_id,
|
||||
session_id: message.session_id,
|
||||
context_token: message.context_token,
|
||||
message_id: message.message_id,
|
||||
flush_at_ms: 0,
|
||||
text,
|
||||
attachments,
|
||||
}))
|
||||
}
|
||||
|
||||
fn process_incoming_bundle(
|
||||
pending_inbound: &mut std::collections::HashMap<String, PendingInboundBundle>,
|
||||
mut bundle: PendingInboundBundle,
|
||||
pending_inbound_changed: &mut bool,
|
||||
now_ms: u64,
|
||||
inbound_merge_window_ms: u64,
|
||||
) -> Vec<PendingInboundBundle> {
|
||||
let key = bundle.from_user_id.clone();
|
||||
let bundle_has_text = !bundle.text.trim().is_empty();
|
||||
let bundle_has_attachments = !bundle.attachments.is_empty();
|
||||
|
||||
if let Some(mut pending) = pending_inbound.remove(&key) {
|
||||
*pending_inbound_changed = true;
|
||||
|
||||
if bundle_has_text {
|
||||
let incoming_metadata = bundle.clone();
|
||||
pending.text = merge_text(&pending.text, &bundle.text);
|
||||
pending.attachments.extend(bundle.attachments);
|
||||
merge_bundle_metadata(&mut pending, &incoming_metadata);
|
||||
return vec![pending];
|
||||
}
|
||||
|
||||
let incoming_metadata = bundle.clone();
|
||||
pending.attachments.extend(bundle.attachments);
|
||||
merge_bundle_metadata(&mut pending, &incoming_metadata);
|
||||
pending.flush_at_ms = next_flush_deadline(now_ms, inbound_merge_window_ms);
|
||||
pending_inbound.insert(key, pending);
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
if bundle_has_attachments && !bundle_has_text {
|
||||
*pending_inbound_changed = true;
|
||||
bundle.flush_at_ms = next_flush_deadline(now_ms, inbound_merge_window_ms);
|
||||
pending_inbound.insert(key, bundle);
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![bundle]
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_follow_up_bundles(
|
||||
config: &WechatConfig,
|
||||
current_cursor: &mut String,
|
||||
context_tokens: &mut std::collections::HashMap<String, String>,
|
||||
context_tokens_changed: &mut bool,
|
||||
pending_inbound: &mut std::collections::HashMap<String, PendingInboundBundle>,
|
||||
pending_inbound_changed: &mut bool,
|
||||
) {
|
||||
while !pending_inbound.is_empty() {
|
||||
let now_ms = channel_host::now_millis();
|
||||
let Some(timeout_ms) = next_follow_up_timeout_ms(pending_inbound, now_ms) else {
|
||||
break;
|
||||
};
|
||||
if timeout_ms == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
let timeout_ms_u32 = timeout_ms.min(u64::from(u32::MAX)) as u32;
|
||||
let response = match api::get_updates_with_timeout(config, current_cursor, timeout_ms_u32) {
|
||||
Ok(response) => response,
|
||||
Err(_) => break,
|
||||
};
|
||||
|
||||
if response.errcode == Some(-14) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Error,
|
||||
"WeChat getUpdates returned errcode=-14 during follow-up merge window; reconnect the channel",
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
if response.ret.unwrap_or(0) != 0 {
|
||||
let errmsg = response
|
||||
.errmsg
|
||||
.as_deref()
|
||||
.unwrap_or("unknown WeChat polling error");
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!(
|
||||
"WeChat getUpdates returned ret={} errmsg={errmsg} during follow-up merge window",
|
||||
response.ret.unwrap_or(-1)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(next_cursor) = response.get_updates_buf.as_deref() {
|
||||
if next_cursor != current_cursor {
|
||||
*current_cursor = next_cursor.to_string();
|
||||
if let Err(error) = persist_get_updates_buf(next_cursor) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!("Failed to persist WeChat polling cursor: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut saw_relevant_message = false;
|
||||
for message in response.msgs {
|
||||
if let Some(from_user_id) = message.from_user_id.as_deref() {
|
||||
if let Some(context_token) = message.context_token.as_deref() {
|
||||
let changed = context_tokens
|
||||
.insert(from_user_id.to_string(), context_token.to_string())
|
||||
.as_deref()
|
||||
!= Some(context_token);
|
||||
*context_tokens_changed |= changed;
|
||||
}
|
||||
}
|
||||
match incoming_bundle_from_message(config, message) {
|
||||
Ok(Some(bundle)) => {
|
||||
let emitted = process_incoming_bundle(
|
||||
pending_inbound,
|
||||
bundle,
|
||||
pending_inbound_changed,
|
||||
channel_host::now_millis(),
|
||||
u64::from(config.inbound_merge_window_ms),
|
||||
);
|
||||
for emitted_bundle in emitted {
|
||||
saw_relevant_message = true;
|
||||
emit_buffered_bundle(emitted_bundle);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Error,
|
||||
&format!("Failed to map WeChat inbound message: {error}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !saw_relevant_message && pending_inbound.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn next_flush_deadline(now_ms: u64, inbound_merge_window_ms: u64) -> u64 {
|
||||
now_ms.saturating_add(inbound_merge_window_ms)
|
||||
}
|
||||
|
||||
fn next_follow_up_timeout_ms(
|
||||
pending_inbound: &std::collections::HashMap<String, PendingInboundBundle>,
|
||||
now_ms: u64,
|
||||
) -> Option<u64> {
|
||||
pending_inbound
|
||||
.values()
|
||||
.map(|bundle| bundle.flush_at_ms.saturating_sub(now_ms))
|
||||
.min()
|
||||
}
|
||||
|
||||
fn take_due_pending_bundles(
|
||||
pending_inbound: &mut std::collections::HashMap<String, PendingInboundBundle>,
|
||||
now_ms: u64,
|
||||
) -> Vec<PendingInboundBundle> {
|
||||
let due_keys = pending_inbound
|
||||
.iter()
|
||||
.filter_map(|(key, bundle)| (bundle.flush_at_ms <= now_ms).then_some(key.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
due_keys
|
||||
.into_iter()
|
||||
.filter_map(|key| pending_inbound.remove(&key))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn emit_buffered_bundle(bundle: PendingInboundBundle) {
|
||||
let metadata = json!({
|
||||
"from_user_id": bundle.from_user_id,
|
||||
"to_user_id": bundle.to_user_id,
|
||||
"message_id": bundle.message_id,
|
||||
"session_id": bundle.session_id,
|
||||
"context_token": bundle.context_token,
|
||||
});
|
||||
|
||||
channel_host::emit_message(&EmittedMessage {
|
||||
user_id: bundle.from_user_id.clone(),
|
||||
user_name: None,
|
||||
content: bundle.text,
|
||||
thread_id: Some(format!("wechat:{}", bundle.from_user_id)),
|
||||
metadata_json: metadata.to_string(),
|
||||
attachments: bundle.attachments.into_iter().map(Into::into).collect(),
|
||||
});
|
||||
}
|
||||
|
||||
fn merge_bundle_metadata(target: &mut PendingInboundBundle, incoming: &PendingInboundBundle) {
|
||||
if incoming.to_user_id.is_some() {
|
||||
target.to_user_id = incoming.to_user_id.clone();
|
||||
}
|
||||
if incoming.session_id.is_some() {
|
||||
target.session_id = incoming.session_id.clone();
|
||||
}
|
||||
if incoming.context_token.is_some() {
|
||||
target.context_token = incoming.context_token.clone();
|
||||
}
|
||||
if incoming.message_id.is_some() {
|
||||
target.message_id = incoming.message_id;
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_text(existing: &str, incoming: &str) -> String {
|
||||
let existing = existing.trim();
|
||||
let incoming = incoming.trim();
|
||||
match (existing.is_empty(), incoming.is_empty()) {
|
||||
(true, true) => String::new(),
|
||||
(true, false) => incoming.to_string(),
|
||||
(false, true) => existing.to_string(),
|
||||
(false, false) => format!("{existing}\n\n{incoming}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn send_response(
|
||||
config: &WechatConfig,
|
||||
metadata: &OutboundMetadata,
|
||||
response: &AgentResponse,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let mut remaining_text = response.content.trim().to_string();
|
||||
let mut sent_attachment = false;
|
||||
|
||||
for attachment in &response.attachments {
|
||||
if !attachment.mime_type.starts_with("image/") {
|
||||
return Err(format!(
|
||||
"WeChat currently supports image attachments only, got {} ({})",
|
||||
attachment.filename, attachment.mime_type
|
||||
));
|
||||
}
|
||||
|
||||
let caption = if sent_attachment {
|
||||
""
|
||||
} else {
|
||||
remaining_text.as_str()
|
||||
};
|
||||
media::send_image_attachment(
|
||||
config,
|
||||
&metadata.from_user_id,
|
||||
attachment,
|
||||
context_token,
|
||||
caption,
|
||||
)?;
|
||||
sent_attachment = true;
|
||||
remaining_text.clear();
|
||||
}
|
||||
|
||||
if !remaining_text.is_empty() || !sent_attachment {
|
||||
api::send_text_message(
|
||||
config,
|
||||
&metadata.from_user_id,
|
||||
&remaining_text,
|
||||
context_token,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_text(message: &WechatMessage) -> String {
|
||||
message
|
||||
.item_list
|
||||
.iter()
|
||||
.find_map(|item| {
|
||||
if item.r#type == Some(MESSAGE_ITEM_TEXT) {
|
||||
item.text_item.as_ref().map(|item| item.text.clone())
|
||||
} else if item.r#type == Some(crate::types::MESSAGE_ITEM_VOICE) {
|
||||
item.voice_item
|
||||
.as_ref()
|
||||
.and_then(|item| item.text.as_ref())
|
||||
.cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn is_terminal_text_status(message: &str) -> bool {
|
||||
let trimmed = message.trim();
|
||||
trimmed.eq_ignore_ascii_case("done")
|
||||
|| trimmed.eq_ignore_ascii_case("interrupted")
|
||||
|| trimmed.eq_ignore_ascii_case("awaiting approval")
|
||||
|| trimmed.eq_ignore_ascii_case("rejected")
|
||||
}
|
||||
|
||||
fn classify_status_update(update: &StatusUpdate) -> Option<WechatStatusAction> {
|
||||
match update.status {
|
||||
StatusType::Thinking => Some(WechatStatusAction::Typing),
|
||||
StatusType::Done
|
||||
| StatusType::Interrupted
|
||||
| StatusType::ApprovalNeeded
|
||||
| StatusType::AuthRequired => Some(WechatStatusAction::Cancel),
|
||||
StatusType::Status if is_terminal_text_status(&update.message) => {
|
||||
Some(WechatStatusAction::Cancel)
|
||||
}
|
||||
StatusType::ToolStarted
|
||||
| StatusType::ToolCompleted
|
||||
| StatusType::ToolResult
|
||||
| StatusType::Status
|
||||
| StatusType::JobStarted
|
||||
| StatusType::AuthCompleted => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_context_token(
|
||||
metadata: &OutboundMetadata,
|
||||
context_tokens: &std::collections::HashMap<String, String>,
|
||||
) -> Option<String> {
|
||||
metadata
|
||||
.context_token
|
||||
.clone()
|
||||
.or_else(|| context_tokens.get(&metadata.from_user_id).cloned())
|
||||
}
|
||||
|
||||
fn cached_typing_ticket(user_id: &str) -> Option<String> {
|
||||
let tickets = load_typing_tickets();
|
||||
let ticket = tickets.get(user_id)?;
|
||||
let trimmed = ticket.ticket.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let age_ms = channel_host::now_millis().saturating_sub(ticket.fetched_at_ms);
|
||||
if age_ms >= TYPING_TICKET_TTL_MS {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
fn persist_typing_ticket(user_id: &str, ticket: &str) -> Result<(), String> {
|
||||
let mut tickets = load_typing_tickets();
|
||||
tickets.insert(
|
||||
user_id.to_string(),
|
||||
TypingTicketEntry {
|
||||
ticket: ticket.to_string(),
|
||||
fetched_at_ms: channel_host::now_millis(),
|
||||
},
|
||||
);
|
||||
persist_typing_tickets(&tickets)
|
||||
}
|
||||
|
||||
fn clear_typing_ticket(user_id: &str) -> Result<(), String> {
|
||||
let mut tickets = load_typing_tickets();
|
||||
if tickets.remove(user_id).is_some() {
|
||||
persist_typing_tickets(&tickets)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_typing_ticket(
|
||||
config: &WechatConfig,
|
||||
user_id: &str,
|
||||
context_token: Option<&str>,
|
||||
) -> Result<Option<String>, String> {
|
||||
if let Some(ticket) = cached_typing_ticket(user_id) {
|
||||
return Ok(Some(ticket));
|
||||
}
|
||||
|
||||
let response = api::get_config(config, user_id, context_token)?;
|
||||
if response.ret.unwrap_or(0) != 0 {
|
||||
let errmsg = response
|
||||
.errmsg
|
||||
.as_deref()
|
||||
.unwrap_or("unknown WeChat getConfig error");
|
||||
return Err(format!(
|
||||
"WeChat getConfig returned ret={} errmsg={errmsg}",
|
||||
response.ret.unwrap_or(-1)
|
||||
));
|
||||
}
|
||||
|
||||
let Some(ticket) = response
|
||||
.typing_ticket
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|ticket| !ticket.is_empty())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if let Err(error) = persist_typing_ticket(user_id, ticket) {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Warn,
|
||||
&format!("Failed to persist WeChat typing ticket: {error}"),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Some(ticket.to_string()))
|
||||
}
|
||||
|
||||
fn send_typing_indicator(
|
||||
config: &WechatConfig,
|
||||
metadata: &OutboundMetadata,
|
||||
context_token: Option<&str>,
|
||||
status: i32,
|
||||
allow_ticket_fetch: bool,
|
||||
) -> Result<(), String> {
|
||||
let ticket = if allow_ticket_fetch {
|
||||
resolve_typing_ticket(config, &metadata.from_user_id, context_token)?
|
||||
} else {
|
||||
cached_typing_ticket(&metadata.from_user_id)
|
||||
};
|
||||
|
||||
let Some(ticket) = ticket else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if let Err(error) = api::send_typing(config, &metadata.from_user_id, &ticket, status) {
|
||||
let _ = clear_typing_ticket(&metadata.from_user_id);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
export!(WechatChannel);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{
|
||||
classify_status_update, extract_text, merge_text, process_incoming_bundle,
|
||||
take_due_pending_bundles, PendingInboundBundle, StoredInboundAttachment,
|
||||
WechatStatusAction,
|
||||
};
|
||||
use crate::exports::near::agent::channel::{StatusType, StatusUpdate};
|
||||
use crate::types::{MessageItem, VoiceItem, WechatMessage, MESSAGE_ITEM_VOICE};
|
||||
|
||||
fn make_bundle(user_id: &str, text: &str, image_count: usize) -> PendingInboundBundle {
|
||||
PendingInboundBundle {
|
||||
from_user_id: user_id.to_string(),
|
||||
to_user_id: Some("bot".to_string()),
|
||||
session_id: Some("session-1".to_string()),
|
||||
context_token: Some("ctx-1".to_string()),
|
||||
message_id: Some(1),
|
||||
flush_at_ms: 0,
|
||||
text: text.to_string(),
|
||||
attachments: (0..image_count)
|
||||
.map(|index| StoredInboundAttachment {
|
||||
id: format!("att-{index}"),
|
||||
mime_type: "image/jpeg".to_string(),
|
||||
filename: Some(format!("photo-{index}.jpg")),
|
||||
size_bytes: Some(128),
|
||||
source_url: Some("https://example.com/image.jpg".to_string()),
|
||||
storage_key: None,
|
||||
extracted_text: None,
|
||||
extras_json: "{}".to_string(),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_status_update_thinking_starts_typing() {
|
||||
let update = StatusUpdate {
|
||||
status: StatusType::Thinking,
|
||||
message: "Thinking...".to_string(),
|
||||
metadata_json: "{}".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
classify_status_update(&update),
|
||||
Some(WechatStatusAction::Typing)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_status_update_done_cancels_typing() {
|
||||
let update = StatusUpdate {
|
||||
status: StatusType::Done,
|
||||
message: "Done".to_string(),
|
||||
metadata_json: "{}".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
classify_status_update(&update),
|
||||
Some(WechatStatusAction::Cancel)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_status_update_approval_needed_cancels_typing() {
|
||||
let update = StatusUpdate {
|
||||
status: StatusType::ApprovalNeeded,
|
||||
message: "Approval needed".to_string(),
|
||||
metadata_json: "{}".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
classify_status_update(&update),
|
||||
Some(WechatStatusAction::Cancel)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_status_update_tool_started_is_ignored() {
|
||||
let update = StatusUpdate {
|
||||
status: StatusType::ToolStarted,
|
||||
message: "Tool started".to_string(),
|
||||
metadata_json: "{}".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(classify_status_update(&update), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_status_update_terminal_text_status_cancels_typing() {
|
||||
let update = StatusUpdate {
|
||||
status: StatusType::Status,
|
||||
message: "Awaiting approval".to_string(),
|
||||
metadata_json: "{}".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
classify_status_update(&update),
|
||||
Some(WechatStatusAction::Cancel)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_status_update_progress_status_is_ignored() {
|
||||
let update = StatusUpdate {
|
||||
status: StatusType::Status,
|
||||
message: "Context compaction started".to_string(),
|
||||
metadata_json: "{}".to_string(),
|
||||
};
|
||||
|
||||
assert_eq!(classify_status_update(&update), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_text_joins_non_empty_segments() {
|
||||
assert_eq!(merge_text("", "hello"), "hello");
|
||||
assert_eq!(merge_text("look", "what is this"), "look\n\nwhat is this");
|
||||
assert_eq!(merge_text("look", ""), "look");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_text_uses_voice_transcript_when_present() {
|
||||
let message = WechatMessage {
|
||||
message_id: Some(1),
|
||||
from_user_id: Some("user-1".to_string()),
|
||||
to_user_id: Some("bot-1".to_string()),
|
||||
session_id: None,
|
||||
message_type: None,
|
||||
context_token: None,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_VOICE),
|
||||
text_item: None,
|
||||
image_item: None,
|
||||
voice_item: Some(VoiceItem {
|
||||
media: None,
|
||||
encode_type: Some(6),
|
||||
playtime: Some(1500),
|
||||
text: Some("voice transcript".to_string()),
|
||||
}),
|
||||
file_item: None,
|
||||
}],
|
||||
};
|
||||
|
||||
assert_eq!(extract_text(&message), "voice transcript");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_process_incoming_bundle_merges_buffered_image_with_follow_up_text() {
|
||||
let mut pending = HashMap::new();
|
||||
let mut changed = false;
|
||||
|
||||
let emitted = process_incoming_bundle(
|
||||
&mut pending,
|
||||
make_bundle("u1", "", 1),
|
||||
&mut changed,
|
||||
100,
|
||||
5_000,
|
||||
);
|
||||
assert!(emitted.is_empty());
|
||||
assert!(changed);
|
||||
assert_eq!(pending.len(), 1);
|
||||
assert_eq!(pending["u1"].flush_at_ms, 5100);
|
||||
|
||||
changed = false;
|
||||
let emitted = process_incoming_bundle(
|
||||
&mut pending,
|
||||
make_bundle("u1", "What is in this image?", 0),
|
||||
&mut changed,
|
||||
200,
|
||||
5_000,
|
||||
);
|
||||
assert!(changed);
|
||||
assert!(pending.is_empty());
|
||||
assert_eq!(emitted.len(), 1);
|
||||
assert_eq!(emitted[0].text, "What is in this image?");
|
||||
assert_eq!(emitted[0].attachments.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_process_incoming_bundle_emits_text_and_images_together_without_buffering() {
|
||||
let mut pending = HashMap::new();
|
||||
let mut changed = false;
|
||||
|
||||
let emitted = process_incoming_bundle(
|
||||
&mut pending,
|
||||
make_bundle("u1", "Look at this image", 1),
|
||||
&mut changed,
|
||||
100,
|
||||
5_000,
|
||||
);
|
||||
assert!(!changed);
|
||||
assert!(pending.is_empty());
|
||||
assert_eq!(emitted.len(), 1);
|
||||
assert_eq!(emitted[0].text, "Look at this image");
|
||||
assert_eq!(emitted[0].attachments.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_take_due_pending_bundles_emits_only_expired_entries() {
|
||||
let mut pending = HashMap::new();
|
||||
let mut expired = make_bundle("u1", "", 1);
|
||||
expired.flush_at_ms = 100;
|
||||
let mut fresh = make_bundle("u2", "", 1);
|
||||
fresh.flush_at_ms = 300;
|
||||
pending.insert(expired.from_user_id.clone(), expired);
|
||||
pending.insert(fresh.from_user_id.clone(), fresh);
|
||||
|
||||
let due = take_due_pending_bundles(&mut pending, 200);
|
||||
assert_eq!(due.len(), 1);
|
||||
assert_eq!(due[0].from_user_id, "u1");
|
||||
assert_eq!(pending.len(), 1);
|
||||
assert!(pending.contains_key("u2"));
|
||||
}
|
||||
}
|
||||
@@ -1,718 +0,0 @@
|
||||
use aes::cipher::{generic_array::GenericArray, BlockEncrypt, KeyInit};
|
||||
use aes::Aes128;
|
||||
use base64::Engine as _;
|
||||
use md5::{Digest, Md5};
|
||||
use rand::RngCore;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::exports::near::agent::channel::Attachment;
|
||||
use crate::near::agent::channel_host::{self, InboundAttachment};
|
||||
use crate::types::{
|
||||
CdnMedia, FileItem, ImageItem, MessageItem, SendMessageRequest, WechatConfig,
|
||||
MESSAGE_ITEM_FILE, MESSAGE_ITEM_IMAGE, MESSAGE_ITEM_VOICE, MESSAGE_STATE_FINISH,
|
||||
MESSAGE_TYPE_BOT, UPLOAD_MEDIA_TYPE_IMAGE,
|
||||
};
|
||||
|
||||
const AES_BLOCK_SIZE: usize = 16;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UploadImage {
|
||||
pub download_encrypted_query_param: String,
|
||||
pub aes_key_base64: String,
|
||||
pub file_size_ciphertext: u64,
|
||||
}
|
||||
|
||||
pub fn extract_inbound_attachments(
|
||||
config: &WechatConfig,
|
||||
message: &crate::types::WechatMessage,
|
||||
) -> Result<Vec<InboundAttachment>, String> {
|
||||
message
|
||||
.item_list
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
map_inbound_attachment(config, message, item, index).transpose()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn send_image_attachment(
|
||||
config: &WechatConfig,
|
||||
to_user_id: &str,
|
||||
attachment: &Attachment,
|
||||
context_token: Option<&str>,
|
||||
text: &str,
|
||||
) -> Result<(), String> {
|
||||
if attachment.data.is_empty() {
|
||||
return Err(format!(
|
||||
"WeChat image attachment '{}' has no data",
|
||||
attachment.filename
|
||||
));
|
||||
}
|
||||
|
||||
let upload = upload_image(config, to_user_id, attachment)?;
|
||||
if !text.trim().is_empty() {
|
||||
crate::api::send_text_message(config, to_user_id, text.trim(), context_token)?;
|
||||
}
|
||||
let request = SendMessageRequest {
|
||||
msg: crate::types::OutboundWechatMessage {
|
||||
from_user_id: String::new(),
|
||||
to_user_id: to_user_id.to_string(),
|
||||
client_id: format!("wechat-{}", channel_host::now_millis()),
|
||||
message_type: MESSAGE_TYPE_BOT,
|
||||
message_state: MESSAGE_STATE_FINISH,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_IMAGE),
|
||||
text_item: None,
|
||||
image_item: Some(ImageItem {
|
||||
media: Some(CdnMedia {
|
||||
encrypt_query_param: Some(upload.download_encrypted_query_param.clone()),
|
||||
aes_key: Some(upload.aes_key_base64.clone()),
|
||||
encrypt_type: Some(1),
|
||||
}),
|
||||
aeskey: None,
|
||||
mid_size: Some(upload.file_size_ciphertext),
|
||||
}),
|
||||
voice_item: None,
|
||||
file_item: None,
|
||||
}],
|
||||
context_token: context_token.map(str::to_string),
|
||||
},
|
||||
base_info: crate::api::base_info(),
|
||||
};
|
||||
|
||||
crate::api::send_message_request(config, &request)
|
||||
}
|
||||
|
||||
fn map_inbound_attachment(
|
||||
config: &WechatConfig,
|
||||
message: &crate::types::WechatMessage,
|
||||
item: &MessageItem,
|
||||
index: usize,
|
||||
) -> Result<Option<InboundAttachment>, String> {
|
||||
if item.r#type == Some(MESSAGE_ITEM_IMAGE) {
|
||||
return map_image_attachment(config, message, item, index);
|
||||
}
|
||||
if item.r#type == Some(MESSAGE_ITEM_VOICE) {
|
||||
return map_voice_attachment(config, message, item, index);
|
||||
}
|
||||
if item.r#type == Some(MESSAGE_ITEM_FILE) {
|
||||
return map_file_attachment(config, message, item, index);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn map_image_attachment(
|
||||
config: &WechatConfig,
|
||||
message: &crate::types::WechatMessage,
|
||||
item: &MessageItem,
|
||||
index: usize,
|
||||
) -> Result<Option<InboundAttachment>, String> {
|
||||
if item.r#type != Some(MESSAGE_ITEM_IMAGE) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let image = item.image_item.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat image message {:?} is missing image_item payload",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let media = image.media.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat image message {:?} is missing media payload",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let encrypt_query_param = media.encrypt_query_param.as_deref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat image message {:?} is missing encrypt_query_param",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let message_id = message
|
||||
.message_id
|
||||
.ok_or_else(|| "WeChat image message is missing message_id".to_string())?;
|
||||
let aes_key = preferred_image_aes_key(image, media).map(str::to_string);
|
||||
|
||||
Ok(Some(InboundAttachment {
|
||||
id: format!("wechat-image-{}-{}", message_id, index),
|
||||
mime_type: "image/jpeg".to_string(),
|
||||
filename: Some(format!("wechat-image-{}-{}.jpg", message_id, index)),
|
||||
size_bytes: image.mid_size,
|
||||
source_url: Some(build_cdn_download_url(
|
||||
&config.cdn_base_url,
|
||||
encrypt_query_param,
|
||||
)),
|
||||
storage_key: None,
|
||||
extracted_text: None,
|
||||
extras_json: json!({ "wechat_aes_key": aes_key }).to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn map_file_attachment(
|
||||
config: &WechatConfig,
|
||||
message: &crate::types::WechatMessage,
|
||||
item: &MessageItem,
|
||||
index: usize,
|
||||
) -> Result<Option<InboundAttachment>, String> {
|
||||
if item.r#type != Some(MESSAGE_ITEM_FILE) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let file = item.file_item.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat file message {:?} is missing file_item payload",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let media = file.media.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat file message {:?} is missing media payload",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let encrypt_query_param = media.encrypt_query_param.as_deref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat file message {:?} is missing encrypt_query_param",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let aes_key = media
|
||||
.aes_key
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat file message {:?} is missing aes_key",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let message_id = message
|
||||
.message_id
|
||||
.ok_or_else(|| "WeChat file message is missing message_id".to_string())?;
|
||||
let filename = inbound_file_name(file, message_id, index);
|
||||
let size_bytes = file.len.as_deref().and_then(parse_file_size);
|
||||
|
||||
Ok(Some(InboundAttachment {
|
||||
id: format!("wechat-file-{}-{}", message_id, index),
|
||||
mime_type: infer_file_mime_type(&filename),
|
||||
filename: Some(filename),
|
||||
size_bytes,
|
||||
source_url: Some(build_cdn_download_url(
|
||||
&config.cdn_base_url,
|
||||
encrypt_query_param,
|
||||
)),
|
||||
storage_key: None,
|
||||
extracted_text: None,
|
||||
extras_json: json!({ "wechat_aes_key": aes_key }).to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn map_voice_attachment(
|
||||
config: &WechatConfig,
|
||||
message: &crate::types::WechatMessage,
|
||||
item: &MessageItem,
|
||||
index: usize,
|
||||
) -> Result<Option<InboundAttachment>, String> {
|
||||
if item.r#type != Some(MESSAGE_ITEM_VOICE) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let voice = item.voice_item.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat voice message {:?} is missing voice_item payload",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let media = voice.media.as_ref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat voice message {:?} is missing media payload",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let encrypt_query_param = media.encrypt_query_param.as_deref().ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat voice message {:?} is missing encrypt_query_param",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let aes_key = media
|
||||
.aes_key
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"WeChat voice message {:?} is missing aes_key",
|
||||
message.message_id
|
||||
)
|
||||
})?;
|
||||
let message_id = message
|
||||
.message_id
|
||||
.ok_or_else(|| "WeChat voice message is missing message_id".to_string())?;
|
||||
let (mime_type, extension) = infer_voice_media_type(voice.encode_type);
|
||||
let duration_secs = voice.playtime.map(|millis| (millis / 1000) as u32);
|
||||
|
||||
Ok(Some(InboundAttachment {
|
||||
id: format!("wechat-voice-{}-{}", message_id, index),
|
||||
mime_type: mime_type.to_string(),
|
||||
filename: Some(format!(
|
||||
"wechat-voice-{}-{}.{}",
|
||||
message_id, index, extension
|
||||
)),
|
||||
size_bytes: None,
|
||||
source_url: Some(build_cdn_download_url(
|
||||
&config.cdn_base_url,
|
||||
encrypt_query_param,
|
||||
)),
|
||||
storage_key: None,
|
||||
extracted_text: voice
|
||||
.text
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_string),
|
||||
extras_json: build_voice_extras_json(aes_key, duration_secs),
|
||||
}))
|
||||
}
|
||||
|
||||
fn preferred_image_aes_key<'a>(image: &'a ImageItem, media: &'a CdnMedia) -> Option<&'a str> {
|
||||
image
|
||||
.aeskey
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| {
|
||||
media
|
||||
.aes_key
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn inbound_file_name(file: &FileItem, message_id: i64, index: usize) -> String {
|
||||
file.file_name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| format!("wechat-file-{}-{}.bin", message_id, index))
|
||||
}
|
||||
|
||||
fn parse_file_size(raw: &str) -> Option<u64> {
|
||||
raw.trim().parse::<u64>().ok()
|
||||
}
|
||||
|
||||
fn infer_voice_media_type(encode_type: Option<i32>) -> (&'static str, &'static str) {
|
||||
match encode_type {
|
||||
Some(7) => ("audio/mpeg", "mp3"),
|
||||
Some(8) => ("audio/ogg", "ogg"),
|
||||
Some(5) => ("audio/amr", "amr"),
|
||||
Some(6) => ("audio/silk", "silk"),
|
||||
_ => ("audio/silk", "silk"),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_voice_extras_json(aes_key: &str, duration_secs: Option<u32>) -> String {
|
||||
let mut extras = serde_json::Map::new();
|
||||
extras.insert("wechat_aes_key".to_string(), json!(aes_key));
|
||||
if let Some(duration_secs) = duration_secs {
|
||||
extras.insert("duration_secs".to_string(), json!(duration_secs));
|
||||
}
|
||||
serde_json::Value::Object(extras).to_string()
|
||||
}
|
||||
|
||||
fn infer_file_mime_type(filename: &str) -> String {
|
||||
let extension = filename
|
||||
.rsplit_once('.')
|
||||
.map(|(_, ext)| ext.trim().to_ascii_lowercase());
|
||||
|
||||
match extension.as_deref() {
|
||||
Some("pdf") => "application/pdf",
|
||||
Some("doc") => "application/msword",
|
||||
Some("docx") => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
Some("xls") => "application/vnd.ms-excel",
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
Some("ppt") => "application/vnd.ms-powerpoint",
|
||||
Some("pptx") => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
Some("txt") => "text/plain",
|
||||
Some("csv") => "text/csv",
|
||||
Some("json") => "application/json",
|
||||
Some("xml") => "application/xml",
|
||||
Some("md") => "text/markdown",
|
||||
Some("zip") => "application/zip",
|
||||
Some("tar") => "application/x-tar",
|
||||
Some("gz") => "application/gzip",
|
||||
Some("mp3") => "audio/mpeg",
|
||||
Some("ogg") => "audio/ogg",
|
||||
Some("wav") => "audio/wav",
|
||||
Some("mp4") => "video/mp4",
|
||||
Some("mov") => "video/quicktime",
|
||||
Some("webm") => "video/webm",
|
||||
Some("mkv") => "video/x-matroska",
|
||||
Some("avi") => "video/x-msvideo",
|
||||
Some("png") => "image/png",
|
||||
Some("jpg") | Some("jpeg") => "image/jpeg",
|
||||
Some("gif") => "image/gif",
|
||||
Some("webp") => "image/webp",
|
||||
Some("bmp") => "image/bmp",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn upload_image(
|
||||
config: &WechatConfig,
|
||||
to_user_id: &str,
|
||||
attachment: &Attachment,
|
||||
) -> Result<UploadImage, String> {
|
||||
let plaintext = &attachment.data;
|
||||
let raw_size = plaintext.len() as u64;
|
||||
let raw_md5 = hex_lower(md5_bytes(plaintext));
|
||||
let file_size_ciphertext = padded_size(raw_size);
|
||||
let filekey = hex_lower(random_bytes(16)?);
|
||||
let aes_key = random_bytes(16)?;
|
||||
let aes_key_hex = hex_lower(aes_key.clone());
|
||||
|
||||
let upload_url = crate::api::get_upload_url(
|
||||
config,
|
||||
&crate::types::GetUploadUrlRequest {
|
||||
filekey: filekey.clone(),
|
||||
media_type: UPLOAD_MEDIA_TYPE_IMAGE,
|
||||
to_user_id: to_user_id.to_string(),
|
||||
rawsize: raw_size,
|
||||
rawfilemd5: raw_md5,
|
||||
filesize: file_size_ciphertext,
|
||||
no_need_thumb: true,
|
||||
aeskey: aes_key_hex,
|
||||
base_info: crate::api::base_info(),
|
||||
},
|
||||
)?;
|
||||
|
||||
let upload_param = upload_url
|
||||
.upload_param
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| "WeChat getUploadUrl returned no upload_param".to_string())?;
|
||||
|
||||
if upload_url.thumb_upload_param.is_some() {
|
||||
channel_host::log(
|
||||
channel_host::LogLevel::Debug,
|
||||
"WeChat image upload returned thumb_upload_param; ignoring for single-image flow",
|
||||
);
|
||||
}
|
||||
|
||||
let ciphertext = encrypt_aes_ecb_pkcs7(plaintext, &aes_key)?;
|
||||
let upload_response = channel_host::http_request(
|
||||
"POST",
|
||||
&build_cdn_upload_url(&config.cdn_base_url, upload_param, &filekey),
|
||||
r#"{"Content-Type":"application/octet-stream"}"#,
|
||||
Some(&ciphertext),
|
||||
Some(15_000),
|
||||
)
|
||||
.map_err(|e| format!("WeChat CDN upload failed: {e}"))?;
|
||||
|
||||
if upload_response.status != 200 {
|
||||
let body = String::from_utf8_lossy(&upload_response.body);
|
||||
return Err(format!(
|
||||
"WeChat CDN upload returned {}: {}",
|
||||
upload_response.status, body
|
||||
));
|
||||
}
|
||||
|
||||
let headers: std::collections::HashMap<String, String> =
|
||||
serde_json::from_str(&upload_response.headers_json)
|
||||
.map_err(|e| format!("Failed to parse WeChat CDN upload headers: {e}"))?;
|
||||
let download_encrypted_query_param = headers
|
||||
.iter()
|
||||
.find_map(|(key, value)| {
|
||||
if key.eq_ignore_ascii_case("x-encrypted-param") {
|
||||
Some(value.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| "WeChat CDN upload response missing x-encrypted-param".to_string())?;
|
||||
|
||||
Ok(UploadImage {
|
||||
download_encrypted_query_param,
|
||||
aes_key_base64: base64::engine::general_purpose::STANDARD.encode(aes_key),
|
||||
file_size_ciphertext,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_cdn_download_url(cdn_base_url: &str, encrypted_query_param: &str) -> String {
|
||||
format!(
|
||||
"{}/download?encrypted_query_param={}",
|
||||
cdn_base_url.trim_end_matches('/'),
|
||||
percent_encode(encrypted_query_param)
|
||||
)
|
||||
}
|
||||
|
||||
fn build_cdn_upload_url(cdn_base_url: &str, upload_param: &str, filekey: &str) -> String {
|
||||
format!(
|
||||
"{}/upload?encrypted_query_param={}&filekey={}",
|
||||
cdn_base_url.trim_end_matches('/'),
|
||||
percent_encode(upload_param),
|
||||
percent_encode(filekey)
|
||||
)
|
||||
}
|
||||
|
||||
fn percent_encode(value: &str) -> String {
|
||||
let mut encoded = String::with_capacity(value.len());
|
||||
for byte in value.bytes() {
|
||||
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
|
||||
encoded.push(byte as char);
|
||||
} else {
|
||||
encoded.push('%');
|
||||
encoded.push(nibble_to_hex(byte >> 4));
|
||||
encoded.push(nibble_to_hex(byte & 0x0F));
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn nibble_to_hex(nibble: u8) -> char {
|
||||
match nibble {
|
||||
0..=9 => (b'0' + nibble) as char,
|
||||
10..=15 => (b'A' + (nibble - 10)) as char,
|
||||
_ => '0',
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_hex(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
out.push(nibble_to_hex(byte >> 4));
|
||||
out.push(nibble_to_hex(byte & 0x0F));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hex_lower(bytes: Vec<u8>) -> String {
|
||||
encode_hex(&bytes).to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn encrypt_aes_ecb_pkcs7(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let cipher = Aes128::new_from_slice(key).map_err(|e| format!("Invalid AES key: {e}"))?;
|
||||
let mut padded = plaintext.to_vec();
|
||||
let pad_len = AES_BLOCK_SIZE - (padded.len() % AES_BLOCK_SIZE);
|
||||
padded.extend(std::iter::repeat_n(pad_len as u8, pad_len));
|
||||
|
||||
for chunk in padded.chunks_exact_mut(AES_BLOCK_SIZE) {
|
||||
cipher.encrypt_block(GenericArray::from_mut_slice(chunk));
|
||||
}
|
||||
|
||||
Ok(padded)
|
||||
}
|
||||
|
||||
fn md5_bytes(bytes: &[u8]) -> Vec<u8> {
|
||||
Md5::digest(bytes).to_vec()
|
||||
}
|
||||
|
||||
fn random_bytes(len: usize) -> Result<Vec<u8>, String> {
|
||||
let mut bytes = vec![0u8; len];
|
||||
rand::rngs::OsRng.fill_bytes(&mut bytes);
|
||||
if bytes.iter().all(|byte| *byte == 0) {
|
||||
return Err("OS RNG returned all-zero bytes unexpectedly".to_string());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn padded_size(raw_size: u64) -> u64 {
|
||||
((raw_size / AES_BLOCK_SIZE as u64) + 1) * AES_BLOCK_SIZE as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
build_voice_extras_json, encode_hex, encrypt_aes_ecb_pkcs7, infer_file_mime_type,
|
||||
infer_voice_media_type, map_file_attachment, map_image_attachment, map_voice_attachment,
|
||||
AES_BLOCK_SIZE,
|
||||
};
|
||||
use crate::types::{
|
||||
CdnMedia, FileItem, ImageItem, MessageItem, VoiceItem, WechatConfig, WechatMessage,
|
||||
MESSAGE_ITEM_FILE, MESSAGE_ITEM_IMAGE, MESSAGE_ITEM_VOICE,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_encrypt_aes_ecb_pkcs7_is_block_aligned() {
|
||||
let key = [0x11u8; 16];
|
||||
let plaintext = b"wechat image payload".to_vec();
|
||||
let ciphertext = encrypt_aes_ecb_pkcs7(&plaintext, &key).unwrap();
|
||||
assert_eq!(ciphertext.len() % AES_BLOCK_SIZE, 0);
|
||||
assert_ne!(ciphertext, plaintext);
|
||||
assert_eq!(
|
||||
encode_hex(&ciphertext).to_ascii_lowercase(),
|
||||
"a7464c94a03fb2c5aa783597a1d2f5a461f1cd5d83a7bd92721e8ac1853f881f"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_image_attachment_errors_when_message_id_missing() {
|
||||
let config = WechatConfig::default();
|
||||
let message = WechatMessage {
|
||||
message_id: None,
|
||||
from_user_id: Some("user-1".to_string()),
|
||||
to_user_id: Some("bot-1".to_string()),
|
||||
session_id: None,
|
||||
message_type: None,
|
||||
context_token: None,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_IMAGE),
|
||||
text_item: None,
|
||||
image_item: Some(ImageItem {
|
||||
media: Some(CdnMedia {
|
||||
encrypt_query_param: Some("enc".to_string()),
|
||||
aes_key: Some("aes".to_string()),
|
||||
encrypt_type: Some(1),
|
||||
}),
|
||||
aeskey: None,
|
||||
mid_size: Some(128),
|
||||
}),
|
||||
voice_item: None,
|
||||
file_item: None,
|
||||
}],
|
||||
};
|
||||
|
||||
let error = map_image_attachment(&config, &message, &message.item_list[0], 0)
|
||||
.expect_err("missing message_id should error");
|
||||
assert!(error.contains("missing message_id"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_file_attachment_uses_filename_and_size_metadata() {
|
||||
let config = WechatConfig::default();
|
||||
let message = WechatMessage {
|
||||
message_id: Some(42),
|
||||
from_user_id: Some("user-1".to_string()),
|
||||
to_user_id: Some("bot-1".to_string()),
|
||||
session_id: None,
|
||||
message_type: None,
|
||||
context_token: None,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_FILE),
|
||||
text_item: None,
|
||||
image_item: None,
|
||||
voice_item: None,
|
||||
file_item: Some(FileItem {
|
||||
media: Some(CdnMedia {
|
||||
encrypt_query_param: Some("enc".to_string()),
|
||||
aes_key: Some("YWJjZGVmZ2hpamtsbW5vcA==".to_string()),
|
||||
encrypt_type: Some(1),
|
||||
}),
|
||||
file_name: Some("report.PDF".to_string()),
|
||||
len: Some("256".to_string()),
|
||||
}),
|
||||
}],
|
||||
};
|
||||
|
||||
let attachment = map_file_attachment(&config, &message, &message.item_list[0], 0)
|
||||
.expect("file attachment should map")
|
||||
.expect("file attachment should be present");
|
||||
assert_eq!(attachment.id, "wechat-file-42-0");
|
||||
assert_eq!(attachment.mime_type, "application/pdf");
|
||||
assert_eq!(attachment.filename.as_deref(), Some("report.PDF"));
|
||||
assert_eq!(attachment.size_bytes, Some(256));
|
||||
assert!(attachment.extras_json.contains("wechat_aes_key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_file_attachment_errors_when_message_id_missing() {
|
||||
let config = WechatConfig::default();
|
||||
let message = WechatMessage {
|
||||
message_id: None,
|
||||
from_user_id: Some("user-1".to_string()),
|
||||
to_user_id: Some("bot-1".to_string()),
|
||||
session_id: None,
|
||||
message_type: None,
|
||||
context_token: None,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_FILE),
|
||||
text_item: None,
|
||||
image_item: None,
|
||||
voice_item: None,
|
||||
file_item: Some(FileItem {
|
||||
media: Some(CdnMedia {
|
||||
encrypt_query_param: Some("enc".to_string()),
|
||||
aes_key: Some("aes".to_string()),
|
||||
encrypt_type: Some(1),
|
||||
}),
|
||||
file_name: Some("report.pdf".to_string()),
|
||||
len: Some("256".to_string()),
|
||||
}),
|
||||
}],
|
||||
};
|
||||
|
||||
let error = map_file_attachment(&config, &message, &message.item_list[0], 0)
|
||||
.expect_err("missing message_id should error");
|
||||
assert!(error.contains("missing message_id"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_infer_file_mime_type_defaults_to_octet_stream() {
|
||||
assert_eq!(
|
||||
infer_file_mime_type("archive.unknown"),
|
||||
"application/octet-stream"
|
||||
);
|
||||
assert_eq!(infer_file_mime_type("README"), "application/octet-stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_infer_voice_media_type_defaults_to_silk() {
|
||||
assert_eq!(infer_voice_media_type(Some(6)), ("audio/silk", "silk"));
|
||||
assert_eq!(infer_voice_media_type(Some(8)), ("audio/ogg", "ogg"));
|
||||
assert_eq!(infer_voice_media_type(None), ("audio/silk", "silk"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_voice_extras_json_includes_duration() {
|
||||
let extras = build_voice_extras_json("aes-key", Some(9));
|
||||
assert!(extras.contains("wechat_aes_key"));
|
||||
assert!(extras.contains("duration_secs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_voice_attachment_sets_audio_metadata() {
|
||||
let config = WechatConfig::default();
|
||||
let message = WechatMessage {
|
||||
message_id: Some(77),
|
||||
from_user_id: Some("user-1".to_string()),
|
||||
to_user_id: Some("bot-1".to_string()),
|
||||
session_id: None,
|
||||
message_type: None,
|
||||
context_token: None,
|
||||
item_list: vec![MessageItem {
|
||||
r#type: Some(MESSAGE_ITEM_VOICE),
|
||||
text_item: None,
|
||||
image_item: None,
|
||||
voice_item: Some(VoiceItem {
|
||||
media: Some(CdnMedia {
|
||||
encrypt_query_param: Some("enc".to_string()),
|
||||
aes_key: Some("YWJjZGVmZ2hpamtsbW5vcA==".to_string()),
|
||||
encrypt_type: Some(1),
|
||||
}),
|
||||
encode_type: Some(8),
|
||||
playtime: Some(4200),
|
||||
text: Some("hello from voice".to_string()),
|
||||
}),
|
||||
file_item: None,
|
||||
}],
|
||||
};
|
||||
|
||||
let attachment = map_voice_attachment(&config, &message, &message.item_list[0], 0)
|
||||
.expect("voice attachment should map")
|
||||
.expect("voice attachment should be present");
|
||||
assert_eq!(attachment.id, "wechat-voice-77-0");
|
||||
assert_eq!(attachment.mime_type, "audio/ogg");
|
||||
assert_eq!(
|
||||
attachment.filename.as_deref(),
|
||||
Some("wechat-voice-77-0.ogg")
|
||||
);
|
||||
assert_eq!(
|
||||
attachment.extracted_text.as_deref(),
|
||||
Some("hello from voice")
|
||||
);
|
||||
assert!(attachment.extras_json.contains("duration_secs"));
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::auth::{
|
||||
CONFIG_PATH, CONTEXT_TOKENS_PATH, GET_UPDATES_BUF_PATH, PENDING_INBOUND_PATH,
|
||||
TYPING_TICKETS_PATH,
|
||||
};
|
||||
use crate::near::agent::channel_host;
|
||||
use crate::types::WechatConfig;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct TypingTicketEntry {
|
||||
pub ticket: String,
|
||||
pub fetched_at_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct StoredInboundAttachment {
|
||||
pub id: String,
|
||||
pub mime_type: String,
|
||||
pub filename: Option<String>,
|
||||
pub size_bytes: Option<u64>,
|
||||
pub source_url: Option<String>,
|
||||
pub storage_key: Option<String>,
|
||||
pub extracted_text: Option<String>,
|
||||
pub extras_json: String,
|
||||
}
|
||||
|
||||
impl From<channel_host::InboundAttachment> for StoredInboundAttachment {
|
||||
fn from(value: channel_host::InboundAttachment) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
mime_type: value.mime_type,
|
||||
filename: value.filename,
|
||||
size_bytes: value.size_bytes,
|
||||
source_url: value.source_url,
|
||||
storage_key: value.storage_key,
|
||||
extracted_text: value.extracted_text,
|
||||
extras_json: value.extras_json,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StoredInboundAttachment> for channel_host::InboundAttachment {
|
||||
fn from(value: StoredInboundAttachment) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
mime_type: value.mime_type,
|
||||
filename: value.filename,
|
||||
size_bytes: value.size_bytes,
|
||||
source_url: value.source_url,
|
||||
storage_key: value.storage_key,
|
||||
extracted_text: value.extracted_text,
|
||||
extras_json: value.extras_json,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct PendingInboundBundle {
|
||||
pub from_user_id: String,
|
||||
pub to_user_id: Option<String>,
|
||||
pub session_id: Option<String>,
|
||||
pub context_token: Option<String>,
|
||||
pub message_id: Option<i64>,
|
||||
pub flush_at_ms: u64,
|
||||
pub text: String,
|
||||
pub attachments: Vec<StoredInboundAttachment>,
|
||||
}
|
||||
|
||||
pub fn load_config() -> WechatConfig {
|
||||
channel_host::workspace_read(CONFIG_PATH)
|
||||
.and_then(|raw| serde_json::from_str::<WechatConfig>(&raw).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn persist_config(config: &WechatConfig) -> Result<(), String> {
|
||||
let serialized =
|
||||
serde_json::to_string(config).map_err(|e| format!("Failed to serialize config: {e}"))?;
|
||||
channel_host::workspace_write(CONFIG_PATH, &serialized).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn load_get_updates_buf() -> String {
|
||||
channel_host::workspace_read(GET_UPDATES_BUF_PATH)
|
||||
.and_then(|raw| serde_json::from_str::<String>(&raw).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn persist_get_updates_buf(value: &str) -> Result<(), String> {
|
||||
let serialized =
|
||||
serde_json::to_string(value).map_err(|e| format!("Failed to serialize cursor: {e}"))?;
|
||||
channel_host::workspace_write(GET_UPDATES_BUF_PATH, &serialized).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn load_context_tokens() -> HashMap<String, String> {
|
||||
channel_host::workspace_read(CONTEXT_TOKENS_PATH)
|
||||
.and_then(|raw| serde_json::from_str::<HashMap<String, String>>(&raw).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn persist_context_tokens(tokens: &HashMap<String, String>) -> Result<(), String> {
|
||||
let serialized =
|
||||
serde_json::to_string(tokens).map_err(|e| format!("Failed to serialize tokens: {e}"))?;
|
||||
channel_host::workspace_write(CONTEXT_TOKENS_PATH, &serialized).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn load_typing_tickets() -> HashMap<String, TypingTicketEntry> {
|
||||
channel_host::workspace_read(TYPING_TICKETS_PATH)
|
||||
.and_then(|raw| serde_json::from_str::<HashMap<String, TypingTicketEntry>>(&raw).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn persist_typing_tickets(tickets: &HashMap<String, TypingTicketEntry>) -> Result<(), String> {
|
||||
let serialized =
|
||||
serde_json::to_string(tickets).map_err(|e| format!("Failed to serialize tickets: {e}"))?;
|
||||
channel_host::workspace_write(TYPING_TICKETS_PATH, &serialized).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn load_pending_inbound_bundles() -> Result<HashMap<String, PendingInboundBundle>, String> {
|
||||
parse_pending_inbound_bundles(channel_host::workspace_read(PENDING_INBOUND_PATH).as_deref())
|
||||
}
|
||||
|
||||
pub fn persist_pending_inbound_bundles(
|
||||
bundles: &HashMap<String, PendingInboundBundle>,
|
||||
) -> Result<(), String> {
|
||||
let serialized =
|
||||
serde_json::to_string(bundles).map_err(|e| format!("Failed to serialize bundles: {e}"))?;
|
||||
channel_host::workspace_write(PENDING_INBOUND_PATH, &serialized).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn parse_pending_inbound_bundles(
|
||||
raw: Option<&str>,
|
||||
) -> Result<HashMap<String, PendingInboundBundle>, String> {
|
||||
match raw {
|
||||
None => Ok(HashMap::new()),
|
||||
Some(raw) => serde_json::from_str(raw)
|
||||
.map_err(|e| format!("Failed to parse pending inbound bundles: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_pending_inbound_bundles_missing_file_returns_empty_map() {
|
||||
let bundles = parse_pending_inbound_bundles(None).expect("missing state should be empty");
|
||||
assert!(bundles.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_pending_inbound_bundles_invalid_json_returns_error() {
|
||||
let error =
|
||||
parse_pending_inbound_bundles(Some("{not json")).expect_err("invalid json should err");
|
||||
assert!(error.contains("Failed to parse pending inbound bundles"));
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct WechatConfig {
|
||||
#[serde(default = "default_base_url")]
|
||||
pub base_url: String,
|
||||
#[serde(default = "default_cdn_base_url")]
|
||||
pub cdn_base_url: String,
|
||||
#[serde(default = "default_bot_type")]
|
||||
pub bot_type: String,
|
||||
#[serde(default = "default_poll_interval_ms")]
|
||||
pub poll_interval_ms: u32,
|
||||
#[serde(default = "default_long_poll_timeout_ms")]
|
||||
pub long_poll_timeout_ms: u32,
|
||||
#[serde(default = "default_inbound_merge_window_ms")]
|
||||
pub inbound_merge_window_ms: u32,
|
||||
}
|
||||
|
||||
fn default_base_url() -> String {
|
||||
"https://ilinkai.weixin.qq.com".to_string()
|
||||
}
|
||||
|
||||
fn default_cdn_base_url() -> String {
|
||||
"https://novac2c.cdn.weixin.qq.com/c2c".to_string()
|
||||
}
|
||||
|
||||
fn default_bot_type() -> String {
|
||||
"3".to_string()
|
||||
}
|
||||
|
||||
fn default_poll_interval_ms() -> u32 {
|
||||
30_000
|
||||
}
|
||||
|
||||
fn default_long_poll_timeout_ms() -> u32 {
|
||||
35_000
|
||||
}
|
||||
|
||||
fn default_inbound_merge_window_ms() -> u32 {
|
||||
5_000
|
||||
}
|
||||
|
||||
impl Default for WechatConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
base_url: default_base_url(),
|
||||
cdn_base_url: default_cdn_base_url(),
|
||||
bot_type: default_bot_type(),
|
||||
poll_interval_ms: default_poll_interval_ms(),
|
||||
long_poll_timeout_ms: default_long_poll_timeout_ms(),
|
||||
inbound_merge_window_ms: default_inbound_merge_window_ms(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct BaseInfo {
|
||||
pub channel_version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct GetUploadUrlRequest {
|
||||
pub filekey: String,
|
||||
pub media_type: i32,
|
||||
pub to_user_id: String,
|
||||
pub rawsize: u64,
|
||||
pub rawfilemd5: String,
|
||||
pub filesize: u64,
|
||||
pub no_need_thumb: bool,
|
||||
pub aeskey: String,
|
||||
pub base_info: BaseInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct GetUpdatesRequest {
|
||||
pub get_updates_buf: String,
|
||||
pub base_info: BaseInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct GetConfigRequest {
|
||||
pub ilink_user_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context_token: Option<String>,
|
||||
pub base_info: BaseInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct GetUpdatesResponse {
|
||||
pub ret: Option<i32>,
|
||||
pub errcode: Option<i32>,
|
||||
pub errmsg: Option<String>,
|
||||
#[serde(default)]
|
||||
pub msgs: Vec<WechatMessage>,
|
||||
pub get_updates_buf: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct GetUploadUrlResponse {
|
||||
pub upload_param: Option<String>,
|
||||
pub thumb_upload_param: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct SendMessageRequest {
|
||||
pub msg: OutboundWechatMessage,
|
||||
pub base_info: BaseInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct SendTypingRequest {
|
||||
pub ilink_user_id: String,
|
||||
pub typing_ticket: String,
|
||||
pub status: i32,
|
||||
pub base_info: BaseInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct OutboundWechatMessage {
|
||||
pub from_user_id: String,
|
||||
pub to_user_id: String,
|
||||
pub client_id: String,
|
||||
pub message_type: i32,
|
||||
pub message_state: i32,
|
||||
pub item_list: Vec<MessageItem>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct WechatMessage {
|
||||
pub message_id: Option<i64>,
|
||||
pub from_user_id: Option<String>,
|
||||
pub to_user_id: Option<String>,
|
||||
pub session_id: Option<String>,
|
||||
pub message_type: Option<i32>,
|
||||
pub context_token: Option<String>,
|
||||
#[serde(default)]
|
||||
pub item_list: Vec<MessageItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct GetConfigResponse {
|
||||
pub ret: Option<i32>,
|
||||
pub errmsg: Option<String>,
|
||||
pub typing_ticket: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SendTypingResponse {
|
||||
pub ret: Option<i32>,
|
||||
pub errmsg: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct MessageItem {
|
||||
pub r#type: Option<i32>,
|
||||
pub text_item: Option<TextItem>,
|
||||
pub image_item: Option<ImageItem>,
|
||||
pub voice_item: Option<VoiceItem>,
|
||||
pub file_item: Option<FileItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct TextItem {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct CdnMedia {
|
||||
pub encrypt_query_param: Option<String>,
|
||||
pub aes_key: Option<String>,
|
||||
pub encrypt_type: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ImageItem {
|
||||
pub media: Option<CdnMedia>,
|
||||
pub aeskey: Option<String>,
|
||||
pub mid_size: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct VoiceItem {
|
||||
pub media: Option<CdnMedia>,
|
||||
pub encode_type: Option<i32>,
|
||||
pub playtime: Option<u64>,
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct FileItem {
|
||||
pub media: Option<CdnMedia>,
|
||||
pub file_name: Option<String>,
|
||||
pub len: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct OutboundMetadata {
|
||||
pub from_user_id: String,
|
||||
pub to_user_id: Option<String>,
|
||||
pub message_id: Option<i64>,
|
||||
pub session_id: Option<String>,
|
||||
pub context_token: Option<String>,
|
||||
}
|
||||
|
||||
pub const MESSAGE_TYPE_USER: i32 = 1;
|
||||
pub const MESSAGE_TYPE_BOT: i32 = 2;
|
||||
pub const MESSAGE_STATE_FINISH: i32 = 2;
|
||||
pub const MESSAGE_ITEM_TEXT: i32 = 1;
|
||||
pub const MESSAGE_ITEM_IMAGE: i32 = 2;
|
||||
pub const MESSAGE_ITEM_VOICE: i32 = 3;
|
||||
pub const MESSAGE_ITEM_FILE: i32 = 4;
|
||||
pub const TYPING_STATUS_TYPING: i32 = 1;
|
||||
pub const TYPING_STATUS_CANCEL: i32 = 2;
|
||||
pub const UPLOAD_MEDIA_TYPE_IMAGE: i32 = 1;
|
||||
@@ -1,51 +0,0 @@
|
||||
{
|
||||
"version": "0.1.0",
|
||||
"wit_version": "0.3.0",
|
||||
"type": "channel",
|
||||
"name": "wechat",
|
||||
"description": "WeChat iLink Bot channel for direct-message chat via long polling",
|
||||
"setup": {
|
||||
"required_secrets": [
|
||||
{
|
||||
"name": "wechat_bot_token",
|
||||
"prompt": "Connect this channel from the WeChat setup flow. IronClaw stores the bot token after QR login succeeds.",
|
||||
"optional": false
|
||||
}
|
||||
],
|
||||
"setup_url": "https://ilinkai.weixin.qq.com"
|
||||
},
|
||||
"capabilities": {
|
||||
"http": {
|
||||
"allowlist": [
|
||||
{ "host": "ilinkai.weixin.qq.com", "path_prefix": "/" },
|
||||
{ "host": "novac2c.cdn.weixin.qq.com", "path_prefix": "/c2c/" }
|
||||
],
|
||||
"rate_limit": {
|
||||
"requests_per_minute": 60,
|
||||
"requests_per_hour": 1200
|
||||
}
|
||||
},
|
||||
"secrets": {
|
||||
"allowed_names": ["wechat_*"]
|
||||
},
|
||||
"channel": {
|
||||
"allowed_paths": [],
|
||||
"allow_polling": true,
|
||||
"min_poll_interval_ms": 30000,
|
||||
"workspace_prefix": "channels/wechat/",
|
||||
"callback_timeout_secs": 45,
|
||||
"emit_rate_limit": {
|
||||
"messages_per_minute": 100,
|
||||
"messages_per_hour": 5000
|
||||
}
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"base_url": "https://ilinkai.weixin.qq.com",
|
||||
"cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",
|
||||
"bot_type": "3",
|
||||
"poll_interval_ms": 30000,
|
||||
"long_poll_timeout_ms": 35000,
|
||||
"inbound_merge_window_ms": 5000
|
||||
}
|
||||
}
|
||||
Generated
+1
-1
@@ -269,7 +269,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "whatsapp-channel"
|
||||
version = "0.2.0"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name = "whatsapp-channel"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
description = "WhatsApp Cloud API channel for IronClaw"
|
||||
description = "WhatsApp Cloud API channel for OptimClaw"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// WhatsApp API types have fields reserved for future use (contacts, statuses, etc.)
|
||||
#![allow(dead_code)]
|
||||
|
||||
//! WhatsApp Cloud API channel for IronClaw.
|
||||
//! WhatsApp Cloud API channel for OptimClaw.
|
||||
//!
|
||||
//! This WASM component implements the channel interface for handling WhatsApp
|
||||
//! webhooks and sending messages back via the Cloud API.
|
||||
@@ -910,7 +910,7 @@ fn send_pairing_reply(
|
||||
"text": {
|
||||
"preview_url": false,
|
||||
"body": format!(
|
||||
"To pair with this bot, run: ironclaw pairing approve whatsapp {}",
|
||||
"To pair with this bot, run: optimclaw pairing approve whatsapp {}",
|
||||
code
|
||||
)
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Complexity guardrails for AI-assisted development quality.
|
||||
# These thresholds prevent new violations while preserving existing code.
|
||||
# See: https://github.com/nearai/ironclaw/issues/338
|
||||
# See: https://github.com/nearai/optimclaw/issues/338
|
||||
|
||||
cognitive-complexity-threshold = 15 # default: 25 (only active when lint is enabled)
|
||||
too-many-lines-threshold = 100 # default: 100 (only active when lint is enabled)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "ironclaw_common"
|
||||
name = "optimclaw_common"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.92"
|
||||
description = "Shared types and utilities for the IronClaw workspace"
|
||||
description = "Shared types and utilities for the OptimClaw workspace"
|
||||
authors = ["NEAR AI <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
homepage = "https://github.com/nearai/ironclaw"
|
||||
repository = "https://github.com/nearai/ironclaw"
|
||||
homepage = "https://github.com/nearai/optimclaw"
|
||||
repository = "https://github.com/nearai/optimclaw"
|
||||
|
||||
[package.metadata.dist]
|
||||
dist = false
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Shared types and utilities for the IronClaw workspace.
|
||||
//! Shared types and utilities for the OptimClaw workspace.
|
||||
|
||||
mod event;
|
||||
mod util;
|
||||
@@ -1,13 +1,13 @@
|
||||
[package]
|
||||
name = "ironclaw_safety"
|
||||
name = "optimclaw_safety"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.92"
|
||||
description = "Prompt injection defense, input validation, secret leak detection, and safety policy enforcement"
|
||||
authors = ["NEAR AI <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
homepage = "https://github.com/nearai/ironclaw"
|
||||
repository = "https://github.com/nearai/ironclaw"
|
||||
homepage = "https://github.com/nearai/optimclaw"
|
||||
repository = "https://github.com/nearai/optimclaw"
|
||||
|
||||
[package.metadata.dist]
|
||||
dist = false
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "ironclaw-safety-fuzz"
|
||||
name = "optimclaw-safety-fuzz"
|
||||
version = "0.0.0"
|
||||
publish = false
|
||||
edition = "2021"
|
||||
@@ -11,7 +11,7 @@ cargo-fuzz = true
|
||||
libfuzzer-sys = "0.4"
|
||||
serde_json = "1"
|
||||
|
||||
[dependencies.ironclaw_safety]
|
||||
[dependencies.optimclaw_safety]
|
||||
path = ".."
|
||||
|
||||
[[bin]]
|
||||
@@ -1,6 +1,6 @@
|
||||
# ironclaw_safety Fuzz Targets
|
||||
# optimclaw_safety Fuzz Targets
|
||||
|
||||
Fuzz testing for the `ironclaw_safety` crate using [cargo-fuzz](https://github.com/rust-fuzz/cargo-fuzz) (libFuzzer).
|
||||
Fuzz testing for the `optimclaw_safety` crate using [cargo-fuzz](https://github.com/rust-fuzz/cargo-fuzz) (libFuzzer).
|
||||
|
||||
## Targets
|
||||
|
||||
@@ -22,7 +22,7 @@ rustup install nightly
|
||||
## Running
|
||||
|
||||
```bash
|
||||
cd crates/ironclaw_safety
|
||||
cd crates/optimclaw_safety
|
||||
|
||||
# Run a specific target (runs until stopped or crash found)
|
||||
cargo +nightly fuzz run fuzz_safety_sanitizer
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user