mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-26 15:40:18 +00:00
* feat: complete multi-tenant isolation — per-user budgets, model selection, heartbeat cycling Finishes the remaining isolation work from phases 2–4 of #59: Phase 2 (DB scoping): Fix /status and /list commands to use _for_user DB variants instead of global queries that leaked cross-user job data. Phase 3 (Runtime isolation): Per-user workspace in routine engine's spawn_fire so lightweight routines run in the correct user context. Per-user daily cost tracking in CostGuard with configurable budget via MAX_COST_PER_USER_PER_DAY_CENTS. Multi-user heartbeat that cycles through all users with routines, auto-detected from GATEWAY_USER_TOKENS. Phase 4 (Provider/tools): Per-user model selection via preferred_model setting — looked up from SettingsStore on first iteration, threaded through ReasoningContext.model_override to CompletionRequest. Works with providers that support per-request model overrides (NearAI). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: use selected_model setting key to match /model command persistence The dispatcher was reading "preferred_model" but the /model command (merged from staging) persists to "selected_model". Since set_setting is already per-user scoped, using the same key makes /model work as the per-user model override in multi-tenant mode. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: heartbeat hygiene, /model multi-tenant guard, RigAdapter model override Three follow-up fixes for multi-tenant isolation: 1. Multi-user heartbeat now runs memory hygiene per user before each heartbeat check, matching single-user heartbeat behavior. 2. /model command in multi-tenant mode only persists to per-user settings (selected_model) without calling set_model() on the shared LlmProvider. The per-request model_override in the dispatcher reads from the same setting. Added multi_tenant flag to AgentConfig (auto-detected from GATEWAY_USER_TOKENS). 3. RigAdapter now supports per-request model overrides by injecting the model name into rig-core's additional_params. OpenAI/Anthropic/Ollama API servers use last-key-wins for duplicate JSON keys, so the override takes effect via serde's flatten serialization order. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address PR review — cost model attribution, heartbeat concurrency, pruning Fixes from review comments on #1614: - Cost tracking now uses the override model name (not active_model_name) when a per-user model override is active, for accurate attribution. - Multi-user heartbeat runs per-user checks concurrently via JoinSet instead of sequentially, preventing one slow user from blocking others. - Per-user failure counts tracked independently; users exceeding max_failures are skipped (matching single-user semantics). - per_user_daily_cost HashMap pruned on day rollover to prevent unbounded growth in long-lived deployments. - Doc comment fixed: says "routines" not "active routines". Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: /status ownership, model persistence scoping, heartbeat robustness Addresses second round of PR review on #1614: - /status <job_id> DB path now validates job.user_id == requesting user before returning data (was missing ownership check, security fix). - persist_selected_model takes user_id param instead of owner_id, and skips .env/TOML writes in multi-tenant mode (these are shared global files). handle_system_command now receives user_id from caller. - JoinSet collection handles Err(JoinError) explicitly instead of silently dropping panicked tasks. - Notification forwarder extracts owner_id from response metadata in multi-tenant mode for per-user routing instead of broadcasting to the agent owner. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: cost pricing, fire_manual workspace, heartbeat concurrency cap Round 3 review fixes: - Cost tracking passes None for cost_per_token when model override is active, letting CostGuard look up pricing by model name instead of using the default provider's rates (serrrfirat). - fire_manual() now uses per-user workspace, matching spawn_fire() pattern (serrrfirat). - Removed MULTI_TENANT env var — multi-tenant mode is auto-detected solely from GATEWAY_USER_TOKENS presence (serrrfirat + Copilot). - Multi-user heartbeat capped at 8 concurrent tasks to avoid flooding the LLM provider (serrrfirat + Copilot). - Fixed inject_model_override doc comment accuracy (Copilot). - Added comment explaining multi-tenant notification routing priority (Copilot). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: user-scoped webhook endpoint for multi-tenant isolation Adds POST /api/webhooks/u/{user_id}/{path} — a user-scoped webhook endpoint that filters the routine lookup by user_id, preventing cross-user webhook triggering when paths collide. The existing /api/webhooks/{path} endpoint remains unchanged for backward compatibility in single-user deployments. Changes: - get_webhook_routine_by_path gains user_id: Option<&str> param - Both postgres and libsql implementations add AND user_id = ? filter when user_id is provided - New webhook_trigger_user_scoped_handler extracts (user_id, path) from URL and passes to shared fire_webhook_inner logic - Route registered on public router (webhooks are called by external services that can't send bearer tokens) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(db): add UserStore trait with users, api_tokens, invitations tables Foundation for DB-backed user management (#1605): - UserRecord, ApiTokenRecord, InvitationRecord types in db/mod.rs - UserStore sub-trait (17 methods) added to Database supertrait - PostgreSQL migration V14__users.sql (users, api_tokens, invitations) - libSQL schema + incremental migration V14 - Full implementations for both PgBackend (via Store delegation) and LibSqlBackend (direct SQL in libsql/users.rs) - authenticate_token JOINs api_tokens+users with active/non-revoked checks; has_any_users for bootstrap detection Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(web): DB-backed auth, user/token/invitation API handlers Adds the web gateway layer for DB-backed user management (#1605): Auth refactor: - CombinedAuthState wraps env-var tokens (MultiAuthState) + optional DbAuthenticator for DB-backed token lookup with LRU cache (60s TTL, 1024 max entries) - auth_middleware tries env-var tokens first, then DB fallback - From<MultiAuthState> impl for backward compatibility - main.rs wires with_db_auth when database is available API handlers (12 new endpoints): - /api/admin/users — CRUD: create, list, detail, update, suspend, activate - /api/tokens — create (returns plaintext once), list, revoke - /api/invitations — create, list, accept (creates user + first token) Token creation: 32 random bytes → hex plaintext, SHA-256 hash stored. Invitation accept: validates hash + pending + not expired, creates user record and first API token atomically. All test files updated for CombinedAuthState type change. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: startup env-var user migration + UserStore integration tests Completes the DB-backed user management feature (#1605): - Startup migration: when GATEWAY_USER_TOKENS is set and the users table is empty, inserts env-var users + hashed tokens into DB. Logs deprecation notice when DB already has users. - hash_token made pub for reuse in migration code. - 10 integration tests for UserStore (libsql file-backed): - has_any_users bootstrap detection - create/get/get_by_email/list/update user lifecycle - token create → authenticate → revoke → reject cycle - suspended user tokens rejected - wrong-user token revoke returns false - invitation create → accept → user created - record_login and record_token_usage timestamps - libSQL migration: removed FK constraints from V14 (incompatible with execute_batch inside transactions). Tables in both base SCHEMA and incremental migration for fresh and existing databases. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: remove GATEWAY_USER_TOKENS, fix review feedback GATEWAY_USER_TOKENS never went to production — replaced entirely by DB-backed user management via /api/admin/users and /api/tokens. Removed: - UserTokenConfig struct and GATEWAY_USER_TOKENS env var parsing - user_tokens field from GatewayConfig - GatewayChannel::new_multi_auth() constructor - Env-var user migration block in main.rs (~90 lines) - multi_tenant auto-detection from GATEWAY_USER_TOKENS (now runtime via db.has_any_users() in app.rs) Review fixes (zmanian): - User ID generation: UUID instead of display-name derivation (#1) - Invitation accept moved to public router (no auth needed) (#3) - libSQL get_invitation_by_hash aligned with postgres: filters status='pending' AND expires_at > now (#4) - UUID parse: returns DatabaseError::Serialization instead of unwrap_or_default (#7) - PostgreSQL SELECT * replaced with explicit column lists (#8) - Sort order aligned (both backends use DESC) (#6) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: add role-based access control (admin/member) Adds a `role` field (admin|member) to user management: Schema: - `role TEXT NOT NULL DEFAULT 'member'` added to users table in both PostgreSQL V14 migration and libSQL schema/incremental migration - UserRecord gains `role: String` field - UserIdentity gains `role: String` field, populated from DB in DbAuthenticator and defaulting to "admin" for single-user mode Access control: - AdminUser extractor: returns 403 Forbidden if role != "admin" - /api/admin/users/* handlers: require AdminUser (create, list, detail, update, suspend, activate) - POST /api/invitations: requires AdminUser (only admins can invite) - User creation accepts optional "role" param (defaults to "member") - Invitation acceptance creates users with "member" role Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat(web): add Users admin tab to web UI Adds a Users tab to the web gateway UI for managing users, tokens, and roles without needing direct API calls. Features: - User list table with ID, name, email, role, status, created date - Create user form with display name, email, role selector - Suspend/activate actions per user - Create API token for any user (shows plaintext once with copy button) - Role badges (admin highlighted, member muted) - Non-admin users see "Admin access required" message - Keyboard shortcut: Cmd/Ctrl+5 switches to Users tab CSS: - Reuses routines-table styles for the user list - Badge, token-display, btn-small, btn-danger, btn-primary components Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: move Users to Settings subtab, bootstrap admin user on first run - Moved Users from top-level tab to Settings sidebar subtab (under Skills, before Theme toggle) - On first startup with empty users table, automatically creates an admin user from GATEWAY_USER_ID config with a corresponding API token from GATEWAY_AUTH_TOKEN. This ensures the owner appears in the Users panel immediately. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: user creation shows token, + Token works, no password save popup Three UI/UX fixes: 1. Create user now generates an initial API token and shows it in a copy-able banner instead of triggering the browser's password save dialog. Uses autocomplete="off" and type="text" for email field. 2. "+ Token" button works: exposed createTokenForUser/suspendUser/ activateUser on window for inline onclick handlers in dynamically generated table rows. Token creation uses showTokenBanner helper. 3. Admin token creation: POST /api/tokens now accepts optional "user_id" field when the requesting user is admin, allowing token creation for other users from the Users panel. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: use event delegation for user action buttons (CSP compliance) Inline onclick handlers are blocked by the Content-Security-Policy (script-src 'self' without 'unsafe-inline'). Switched to data-action attributes with a delegated click listener on the users table. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: add i18n for Users subtab, show login link on user creation - Added 'settings.users' i18n key for English and Chinese - Token banner now shows a full login link (domain/?token=xxx) with a Copy Link button, plus the raw token below - Login link works automatically via existing ?token= auto-auth Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: token hash mismatch — hash hex string, not raw bytes Critical auth bug: token creation hashed the raw 32 bytes (hasher.update(token_bytes)) but authentication hashed the hex-encoded string (hash_token(candidate) where candidate is the hex string the user sends). This meant newly created tokens could never authenticate. Fixed all 4 token creation sites (users, tokens, invitations create, invitations accept) to use hash_token(&plaintext_token) which hashes the hex string consistently with the auth lookup path. Removed now-unused sha2::Digest imports from handlers. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: remove invitation system The invitation flow is redundant — admin create user already generates a token and shows a login link. Invitations add complexity without value until email integration exists. Removed: - InvitationRecord struct and 4 UserStore trait methods - invitations table from V14 migration (postgres + both libsql schemas) - PostgreSQL Store methods (create/get/accept/list invitations) - libSQL UserStore invitation methods + row_to_invitation helper - invitations.rs handler file (212 lines) - /api/invitations routes (create, list, accept) - test_invitation_lifecycle test Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: user deletion, self-service profile, per-user job limits, usage API Four multi-tenancy improvements: 1. User deletion cascade (DELETE /api/admin/users/{id}): Deletes user and all data across 11 user-scoped tables (settings, secrets, routines, memory, jobs, conversations, etc.). Admin only. 2. Self-service profile (GET/PATCH /api/profile): Users can read and update their own display_name and metadata without admin privileges. 3. Per-user job concurrency (MAX_JOBS_PER_USER env var): Scheduler checks active_jobs_for(user_id) before dispatch. Prevents one user from exhausting all job slots. 4. Usage reporting (GET /api/admin/usage?user_id=X&period=day|week|month): Aggregates LLM costs from llm_calls via agent_jobs.user_id. Returns per-user, per-model breakdown of calls, tokens, and cost. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: add TenantCtx for compile-time tenant isolation Implements zmanian's architectural proposal from #1614 review: two-tier scoped database access (TenantScope/AdminScope) so handler code cannot accidentally bypass tenant scoping. TenantScope (default): wraps user_id + Arc<dyn Database>, auto-binds user_id on every operation. ID-based lookups return None for cross- tenant resources. No escape hatch — forgetting to scope is a compile error. AdminScope (explicit opt-in): cross-tenant access for system-level components (heartbeat, routine engine, self-repair, scheduler, worker). TenantCtx bundles TenantScope + workspace + cost guard + per-user rate limiting. Constructed once per request in handle_message, threaded through all command handlers and ChatDelegate. Key changes: - New src/tenant.rs (~920 lines): TenantScope, AdminScope, TenantCtx, TenantRateState, TenantRateRegistry - All command handlers: user_id: &str → ctx: &TenantCtx - ChatDelegate: cost check/record/settings via self.tenant - System components: store field changed to AdminScope - Config: TENANT_MAX_LLM_CONCURRENT, TENANT_MAX_JOBS_CONCURRENT env vars - Fixes bug: /status <job_id> cross-tenant leak (now auto-filtered) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address PR #1626 review feedback — bounded LRU cache, admin auth, FK cleanup - Replace HashMap with lru::LruCache in DbAuthenticator so the token cache is hard-bounded at 1024 entries (evicts LRU, not just expired) - Gate admin user endpoints (list/detail/update/suspend/activate) with AdminUser extractor so members get 403 instead of full access - Add api_tokens to libSQL delete_user cleanup list to prevent orphaned tokens (libSQL has no FK cascade) - Add regression tests for all three fixes Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: update CA certificates in runtime Docker image Ensures the root certificate bundle is current so TLS handshakes to services like Supabase succeed on Railway. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: resolve CI failures — formatting, no-panics check - Run cargo fmt on test code - Replace .expect() with const NonZeroUsize in DbAuthenticator - Add // safety: comments for test-only code in multi_tenant.rs Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: switch PostgreSQL TLS from rustls to native-tls rustls with rustls-native-certs fails TLS handshake on Railway's slim container (empty or stale root cert store). native-tls delegates to OpenSSL on Linux which handles system certs more reliably. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * Adding user management api * feat: admin secrets provisioning API + API documentation - Add PUT/GET/DELETE /api/admin/users/{id}/secrets/{name} endpoints for application backends to provision per-user secrets (AES-256-GCM encrypted) - Add secrets_store field to GatewayState with builder wiring - Create docs/USER_MANAGEMENT_API.md with full API spec covering users, secrets, tokens, profile, and usage endpoints - Update web gateway CLAUDE.md route table Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: add CatchPanicLayer to capture handler panics Without this, panics in async handlers silently drop the connection and the edge proxy returns a generic 503. Now panics are caught, logged, and returned as 500 with the panic message. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address second-round review — transactional delete, overflow, error logging - C1: Wrap PostgreSQL delete_user() in a transaction so partial cleanup can't leave users in a half-deleted state - M2: Add job_events to delete cleanup (both backends) — FK to agent_jobs without CASCADE would cause FK violation - H1/M4: Cap expires_in_days to 36500 before i64 cast (tokens + secrets) - H2: Validate target user exists before creating admin token to prevent orphan tokens on libSQL - H3: Log DB errors in DbAuthenticator::authenticate() instead of silently swallowing them as 401 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: revert to rustls with webpki-roots fallback for PostgreSQL TLS native-tls/OpenSSL caused silent crashes (segfaults in C code) during DB writes on Railway containers. Switch back to rustls but add webpki-roots as a fallback when system certs are missing, which was the original TLS handshake failure on slim container images. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * chore: update Cargo.lock for rustls + webpki-roots Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * debug: add /api/debug/db-write endpoint to diagnose user insert failure Temporary diagnostic endpoint that tests DB INSERT to users table with full error logging. No auth required. Will be removed after debugging. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * perf: use cargo-chef in Dockerfile for dependency caching Splits the build into planner/deps/builder stages. Dependencies are only recompiled when Cargo.toml or Cargo.lock change. Source-only changes skip straight to the final build stage. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * debug: add tracing to users_create_handler Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: guard created_by FK in user creation handler The auth identity user_id (from owner_id scope) may not match any user row in the DB, causing a FK violation on the created_by column. Check that the referenced user exists before setting created_by. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * refactor: collapse GATEWAY_USER_ID into IRONCLAW_OWNER_ID Remove the separate GATEWAY_USER_ID config. The gateway now uses IRONCLAW_OWNER_ID (config.owner_id) directly for auth identity, bootstrap user creation, and workspace scoping. Previously, with_owner_scope() rebinds the auth identity to owner_id while keeping default_sender_id as the gateway user_id. This caused a FK constraint violation when creating users because the auth identity ("default") didn't match any user in the DB ("nearai"). Changes: - Remove GATEWAY_USER_ID env var and gateway_user_id from settings - Remove user_id field from GatewayConfig - Add owner_id parameter to GatewayChannel::new() - Remove with_owner_scope() method - Remove default_sender_id from GatewayState - Remove sender override logic in chat/approval handlers - Remove debug endpoint and tracing from prior debugging - Update all tests and E2E fixtures Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: hide Users tab for non-admins, remove auth hint text - Fetch /api/profile after login and hide the Users settings tab when the user's role is not admin - Remove the "Enter the GATEWAY_AUTH_TOKEN" hint from the login page since tokens are now managed via the admin panel, not .env files Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address review feedback (auth 503, token expiry, CORS PATCH) - DB auth errors now return 503 instead of 401 so outages are distinguishable from invalid tokens (serrrfirat H3) - Cap expires_in_days to 36500 before i64 cast to prevent negative duration from u64 overflow (serrrfirat H1) - Add PATCH to CORS allowed methods for profile/user update endpoints (Copilot) - Stop leaking panic details in CatchPanicLayer response body Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: harden multi-tenant isolation — review fixes from #1614 - Add conversation ownership checks in TenantScope: add_conversation_message, touch_conversation, list_conversation_messages (+ paginated), update_conversation_metadata_field, get_conversation_metadata now return NotFound for conversations not owned by the tenant (cross-tenant data leak) - Fix multi-user heartbeat: clear notify_user_id per runner so notifications persist to the correct user, not the shared config target - Move hygiene tasks into bounded JoinSet instead of unbounded tokio::spawn - Revert send_notification to private visibility (only used within module) - Use effective_model_name() for cost attribution in dispatcher so providers that ignore per-request model overrides report the actual model used - Fix inject_model_override doc comment; add 3 unit tests - Fix heartbeat doc comment ("routines" not "active routines") Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: add Jobs, Cost, Last Active columns to admin Users table Add UserSummaryStats struct and user_summary_stats() batch query to the UserStore trait (both PostgreSQL and libSQL backends). The admin users list endpoint now fetches per-user aggregates (job count, total LLM spend, most recent activity) in a single query and includes them inline in the response. The frontend Users table displays three new columns. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address review comments and CI formatting failures CI fixes: - cargo fmt fixes in cli/mod.rs and db/tls.rs Security/correctness (from Copilot + serrrfirat + pranavraja99 reviews): - Token create: reject expires_in_days > 36500 with 400 instead of silent clamp - Token create: return 404 when admin targets non-existent user - User create: map duplicate email constraint violations to 409 Conflict - User create: remove unnecessary DB roundtrip for created_by (use AdminUser directly) - DB auth: log warn on DB lookup failures instead of silently swallowing errors - libSQL: add FK constraints on users.created_by and api_tokens.user_id Config fixes: - agent.multi_tenant: resolve from AGENT_MULTI_TENANT env var instead of hardcoding false - heartbeat.multi_tenant: fix doc comment to match actual env-var-based behavior UI fix: - showTokenBanner: pass correct title ("Token created!" vs "User created!") Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address remaining review comments (round 2) - Secrets handlers: normalize name to lowercase before store operations, validate target user_id exists (returns 404 if not found) - libSQL: propagate cost parsing errors instead of unwrap_or_default() in both user_usage_stats and user_summary_stats - users_list_handler: propagate user_summary_stats DB errors (was silently swallowed with unwrap_or_default) - loadUsers: distinguish 401/403 (admin required) from other errors - Docs: fix users.id type (TEXT not UUID), remove "invitation flow" from V14 migration comment Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: i18n for Users tab, atomic user+token creation, transactional delete_user i18n: - Add 31 translation keys for all Users tab strings (en + zh-CN) - Wire data-i18n attributes on HTML elements (headings, buttons, inputs, table headers, empty state) - Replace all hard-coded strings in app.js with I18n.t() calls Atomic user+token creation: - Add create_user_with_token() to UserStore trait - PostgreSQL: wraps both INSERTs in conn.transaction() with auto-rollback - libSQL: wraps in explicit BEGIN/COMMIT with ROLLBACK on error - Handler uses single atomic call instead of two separate operations Transactional delete_user for libSQL: - Wrap multi-table DELETE cascade in BEGIN/COMMIT transaction - ROLLBACK on any error to prevent partial cleanup / inconsistent state - Matches the PostgreSQL implementation which already used transactions Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: revert V14 migration to match deployed checksum [skip-regression-check] Refinery checksums applied migrations — editing V14__users.sql after it was already applied causes deployment failures. Revert the cosmetic comment changes (added in df40b22f) to restore the original checksum. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: bootstrap onboarding flow for multi-tenant users The bootstrap greeting and workspace seeding only ran for the owner workspace at startup, so new users created via the admin API never received the welcome message or identity files (BOOTSTRAP.md, SOUL.md, AGENTS.md, USER.md, etc.). Three fixes: - tenant_ctx(): seed per-user workspace on first creation via seed_if_empty(), which writes identity files and sets bootstrap_pending when the workspace is truly fresh - handle_message(): check take_bootstrap_pending() on the tenant workspace (not the owner workspace) and persist the greeting to the user's own assistant conversation + broadcast via SSE - WorkspacePool: seed new per-user workspaces in the web gateway so memory tools also see identity files immediately The existing single-user bootstrap in Agent::run() is preserved for non-multi-tenant deployments. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address remaining PR review comments (round 3) - Docs: fix metadata description from "merge patch" to "full replacement" - Secrets: reject expires_in_days > 36500 with 400 (was silently clamped) - libSQL: CAST(SUM(cost) AS TEXT) in user_usage_stats and user_summary_stats to prevent SQLite numeric coercion from crashing get_text() — this was the root cause of the Copilot "SUM returns numeric type" comments - Add 3 regression tests: user_summary_stats (empty + with data) and user_usage_stats (multi-model aggregation) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * feat: add role change support for users (admin/member toggle) - Add update_user_role() to UserStore trait + both backends (PostgreSQL and libSQL) - Extend PATCH /api/admin/users/{id} to accept optional "role" field with validation (must be "admin" or "member") - Add "Make Admin" / "Make Member" toggle button in Users table actions - Add i18n keys for role change (en + zh-CN) - Update API docs to document the role field on PATCH - Fix test helpers to use fmt_ts() for timestamps (was using SQLite datetime('now') which produces incompatible format for string comparison) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: show live LLM spend in Users table instead of only DB-recorded costs [skip-regression-check] Chat turns record LLM cost in CostGuard (in-memory) but don't create agent_jobs/llm_calls DB rows — those are only written for background jobs. The Users table was querying only from DB, so it showed $0.00 for users who only chatted. Now supplements DB stats with CostGuard.daily_spend_for_user() — the same source displayed in the status bar token counter. Shows whichever is larger (DB historical total vs live daily spend). Also falls back to last_login_at for "Last Active" when no DB job activity exists. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: persist chat LLM calls to DB and fix usage stats query Two root causes for zero usage stats: 1. ChatDelegate only recorded LLM costs to CostGuard (in-memory) — never to the llm_calls DB table. Added DB persistence via TenantScope.record_llm_call() after each chat LLM call, with job_id=NULL and conversation_id=thread_id. 2. user_summary_stats query only joined agent_jobs→llm_calls, missing chat calls (which have job_id=NULL). Redesigned query to start from llm_calls and resolve user_id via COALESCE(agent_jobs.user_id, conversations.user_id) — covers both job and chat LLM calls. Both PostgreSQL and libSQL queries updated. TenantScope gets record_llm_call() method. Tests updated for new query semantics. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address review comments — input validation, cost semantics, panic safety [skip-regression-check] - Validate display_name: trim whitespace, reject empty strings (create + update) - Validate metadata: must be a JSON object, return 400 if not (admin + profile) - secrets_list_handler: verify target user_id exists before listing - Cost display: use DB total directly (chat calls now persist to DB), remove confusing max(db,live) CostGuard fallback - CatchPanicLayer: truncate panic payload to 200 chars in log to limit potential sensitive data exposure Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: address Copilot round 5 — docs, secrets consistency, token name, provider field [skip-regression-check] - Docs: users.id note updated to "typically UUID v4 strings (bootstrap admin may use a custom ID)" - secrets_list_handler: return 503 when DB store is None (was falling through to list secrets without user validation) - tokens_create: trim + reject empty token name (matching display_name pattern) - LlmCallRecord.provider: use llm_backend ("nearai","openai") instead of model_name() which returns the model identifier - user_summary_stats zero-LLM users: acceptable — handler already falls back to 0 cost and last_login_at for missing entries Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: DB auth returns 503 on outage, scheduler counts only blocking jobs From serrrfirat review: - DB auth: return Err(()) on database errors so middleware returns 503 instead of silently returning Ok(None) → 401 (auth miss) - Scheduler: add parallel_blocking_count_for() that uses is_parallel_blocking() (Pending/InProgress/Stuck) instead of is_active() for per-user concurrency — Completed/Submitted jobs no longer count against MAX_JOBS_PER_USER From Copilot: - CLAUDE.md: fix secrets route paths from {id} to {user_id} - token_hash: use .as_slice() instead of .to_vec() to avoid heap allocation on every token auth/creation call Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: immediate auth cache invalidation on security-critical actions (zmanian review #6) Add DbAuthenticator::invalidate_user() that evicts all cached entries for a user. Called after: - Suspend user (immediate lockout, was 60s delay) - Activate user (immediate access restoration) - Role change (admin↔member takes effect immediately) - Token revocation (revoked token can't be reused from cache) The DbAuthenticator is shared (via Clone, which Arc-clones the cache) between the auth middleware and GatewayState, so handlers can evict entries from the same cache the middleware reads. Also from zmanian's review: - Items 1-5, 7-11 were already resolved in prior commits - Item 12 (String→enum for status/role) is deferred as a broader refactor Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: last-admin protection, usage stats for chat calls, UTF-8 safe panic truncation Last-admin protection: - Suspend, delete, and role-demotion of the last active admin now return 409 Conflict instead of succeeding and locking out the admin API - Helper is_last_admin() checks active admin count before destructive ops Usage stats: - user_usage_stats() now includes chat LLM calls (job_id=NULL) by joining via conversations.user_id, matching user_summary_stats() - Both PostgreSQL and libSQL queries updated Panic handler: - Use floor_char_boundary(200) instead of byte-index [..200] to prevent panic on multi-byte UTF-8 characters in panic messages Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: workspace seed race, bootstrap atomicity, email trim, secrets upsert response [skip-regression-check] - WorkspacePool: await seed_if_empty() synchronously after inserting into cache (drop lock first to avoid blocking), so callers see identity files immediately instead of racing a background task - Bootstrap admin: use create_user_with_token() for atomic user+token creation, matching the admin create endpoint - Email: trim whitespace, treat empty as None to prevent " " being stored and breaking uniqueness - Secrets PUT: report "updated" vs "created" based on prior existence - Last token_hash.to_vec() → .as_slice() in authenticate_token Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: disable unscoped webhook endpoint in multi-tenant mode [skip-regression-check] The original /api/webhooks/{path} endpoint looks up routines across all users. In multi-tenant mode, anyone who knows the webhook path + secret could trigger another user's routine. Now returns 410 Gone with a message pointing to the scoped endpoint /api/webhooks/u/{user_id}/{path}. Detection uses state.db_auth.is_some() — present only when DB-backed auth is enabled (multi-tenant). Single-user deployments are unaffected. From: standardtoaster review comment Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix: webhook multi-tenant check, secrets error propagation, stale doc comment [skip-regression-check] - Webhook: use workspace_pool.is_some() instead of db_auth.is_some() for multi-tenant detection — db_auth is set for any DB deployment, workspace_pool is only set when has_any_users() was true at startup - Secrets: propagate exists() errors instead of unwrap_or(false) so backend outages surface as 500 rather than incorrect "created" status - Config: fix stale workspace_read_scopes comment referencing user_id Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
1215 lines
48 KiB
Rust
1215 lines
48 KiB
Rust
//! IronClaw - Main entry point.
|
|
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use clap::Parser;
|
|
|
|
use ironclaw::{
|
|
agent::{Agent, AgentDeps},
|
|
app::{AppBuilder, AppBuilderFlags},
|
|
channels::{
|
|
ChannelManager, GatewayChannel, HttpChannel, ReplChannel, SignalChannel, WebhookServer,
|
|
WebhookServerConfig,
|
|
wasm::{WasmChannelRouter, WasmChannelRuntime},
|
|
web::log_layer::LogBroadcaster,
|
|
},
|
|
cli::{
|
|
Cli, Command, run_mcp_command, run_pairing_command, run_service_command,
|
|
run_status_command, run_tool_command,
|
|
},
|
|
config::Config,
|
|
hooks::bootstrap_hooks,
|
|
llm::create_session_manager,
|
|
orchestrator::{ReaperConfig, SandboxReaper},
|
|
pairing::PairingStore,
|
|
tracing_fmt::{init_cli_tracing, init_worker_tracing},
|
|
webhooks::{self, ToolWebhookState},
|
|
};
|
|
|
|
#[cfg(unix)]
|
|
use ironclaw::channels::ChannelSecretUpdater;
|
|
#[cfg(any(feature = "postgres", feature = "libsql"))]
|
|
use ironclaw::setup::{SetupConfig, SetupWizard};
|
|
|
|
/// Synchronous entry point. Loads `.env` files before the Tokio runtime
|
|
/// starts so that `std::env::set_var` is safe (no worker threads yet).
|
|
fn main() -> anyhow::Result<()> {
|
|
let _ = dotenvy::dotenv();
|
|
ironclaw::bootstrap::load_ironclaw_env();
|
|
|
|
let result = tokio::runtime::Builder::new_multi_thread()
|
|
.enable_all()
|
|
.build()?
|
|
.block_on(async_main());
|
|
|
|
if let Err(ref e) = result {
|
|
format_top_level_error(e);
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Format a top-level error with color and recovery hints.
|
|
fn format_top_level_error(err: &anyhow::Error) {
|
|
use ironclaw::cli::fmt;
|
|
let msg = format!("{err:#}");
|
|
|
|
eprintln!();
|
|
eprintln!(" {}\u{2717}{} {}", fmt::error(), fmt::reset(), msg);
|
|
|
|
// Provide recovery hints for common errors
|
|
let lower = msg.to_ascii_lowercase();
|
|
let hint = if lower.contains("database_url")
|
|
|| lower.contains("database") && lower.contains("not set")
|
|
{
|
|
Some("run `ironclaw onboard` or set DATABASE_URL in .env")
|
|
} else if lower.contains("connection refused") || lower.contains("connect error") {
|
|
Some("check that the database server is running")
|
|
} else if lower.contains("session") && lower.contains("not found") {
|
|
Some("run `ironclaw onboard` to set up authentication")
|
|
} else if lower.contains("secrets_master_key") {
|
|
Some("run `ironclaw onboard` or set SECRETS_MASTER_KEY in .env")
|
|
} else if lower.contains("already running") {
|
|
Some("stop the other instance or remove the stale PID file")
|
|
} else if lower.contains("onboard") {
|
|
Some("run `ironclaw onboard` to complete setup")
|
|
} else {
|
|
None
|
|
};
|
|
|
|
if let Some(hint_text) = hint {
|
|
eprintln!(" {}hint:{} {}", fmt::dim(), fmt::reset(), hint_text,);
|
|
}
|
|
eprintln!();
|
|
}
|
|
|
|
async fn async_main() -> anyhow::Result<()> {
|
|
let cli = Cli::parse();
|
|
|
|
// Handle non-agent commands first (they don't need full setup)
|
|
match &cli.command {
|
|
Some(Command::Tool(tool_cmd)) => {
|
|
init_cli_tracing();
|
|
return run_tool_command(tool_cmd.clone()).await;
|
|
}
|
|
Some(Command::Config(config_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_config_command(config_cmd.clone()).await;
|
|
}
|
|
Some(Command::Registry(registry_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_registry_command(registry_cmd.clone()).await;
|
|
}
|
|
Some(Command::Channels(channels_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_channels_command(
|
|
channels_cmd.clone(),
|
|
cli.config.as_deref(),
|
|
)
|
|
.await;
|
|
}
|
|
Some(Command::Routines(routines_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_routines_cli(routines_cmd, cli.config.as_deref()).await;
|
|
}
|
|
Some(Command::Mcp(mcp_cmd)) => {
|
|
init_cli_tracing();
|
|
return run_mcp_command(*mcp_cmd.clone()).await;
|
|
}
|
|
Some(Command::Memory(mem_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_memory_command(mem_cmd).await;
|
|
}
|
|
Some(Command::Pairing(pairing_cmd)) => {
|
|
init_cli_tracing();
|
|
return run_pairing_command(pairing_cmd.clone()).map_err(|e| anyhow::anyhow!("{}", e));
|
|
}
|
|
Some(Command::Service(service_cmd)) => {
|
|
init_cli_tracing();
|
|
return run_service_command(service_cmd);
|
|
}
|
|
Some(Command::Skills(skills_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_skills_command(skills_cmd.clone(), cli.config.as_deref())
|
|
.await;
|
|
}
|
|
Some(Command::Hooks(hooks_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_hooks_command(hooks_cmd.clone(), cli.config.as_deref())
|
|
.await;
|
|
}
|
|
Some(Command::Logs(logs_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_logs_command(logs_cmd.clone(), cli.config.as_deref()).await;
|
|
}
|
|
Some(Command::Models(models_cmd)) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_models_command(models_cmd.clone(), cli.config.as_deref())
|
|
.await;
|
|
}
|
|
Some(Command::Doctor) => {
|
|
init_cli_tracing();
|
|
return ironclaw::cli::run_doctor_command().await;
|
|
}
|
|
Some(Command::Status) => {
|
|
init_cli_tracing();
|
|
return run_status_command().await;
|
|
}
|
|
Some(Command::Completion(completion)) => {
|
|
init_cli_tracing();
|
|
return completion.run();
|
|
}
|
|
#[cfg(feature = "import")]
|
|
Some(Command::Import(import_cmd)) => {
|
|
init_cli_tracing();
|
|
let config = ironclaw::config::Config::from_env().await?;
|
|
return ironclaw::cli::run_import_command(import_cmd, &config).await;
|
|
}
|
|
Some(Command::Worker {
|
|
job_id,
|
|
orchestrator_url,
|
|
max_iterations,
|
|
}) => {
|
|
init_worker_tracing();
|
|
return ironclaw::worker::run_worker(*job_id, orchestrator_url, *max_iterations).await;
|
|
}
|
|
Some(Command::ClaudeBridge {
|
|
job_id,
|
|
orchestrator_url,
|
|
max_turns,
|
|
model,
|
|
}) => {
|
|
init_worker_tracing();
|
|
return ironclaw::worker::run_claude_bridge(
|
|
*job_id,
|
|
orchestrator_url,
|
|
*max_turns,
|
|
model,
|
|
)
|
|
.await;
|
|
}
|
|
Some(Command::Login { openai_codex }) => {
|
|
init_cli_tracing();
|
|
if *openai_codex {
|
|
// Resolve codex config so OPENAI_CODEX_* env overrides are
|
|
// honoured even when LLM_BACKEND isn't set to openai_codex.
|
|
let codex_config = {
|
|
let config = Config::from_env()
|
|
.await
|
|
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
|
config.llm.openai_codex.unwrap_or_else(|| {
|
|
use ironclaw::llm::OpenAiCodexConfig;
|
|
let mut cfg = OpenAiCodexConfig::default();
|
|
if let Ok(v) = std::env::var("OPENAI_CODEX_AUTH_URL") {
|
|
cfg.auth_endpoint = v;
|
|
}
|
|
if let Ok(v) = std::env::var("OPENAI_CODEX_API_URL") {
|
|
cfg.api_base_url = v;
|
|
}
|
|
if let Ok(v) = std::env::var("OPENAI_CODEX_CLIENT_ID") {
|
|
cfg.client_id = v;
|
|
}
|
|
if let Ok(v) = std::env::var("OPENAI_CODEX_SESSION_PATH") {
|
|
cfg.session_path = std::path::PathBuf::from(v);
|
|
}
|
|
cfg
|
|
})
|
|
};
|
|
let mgr = ironclaw::llm::OpenAiCodexSessionManager::new(codex_config)
|
|
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
|
mgr.device_code_login()
|
|
.await
|
|
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
|
println!(
|
|
"OpenAI Codex authentication complete. Set LLM_BACKEND=openai_codex to use it."
|
|
);
|
|
} else {
|
|
println!("Specify a provider to authenticate with:");
|
|
println!(" ironclaw login --openai-codex (ChatGPT subscription)");
|
|
}
|
|
return Ok(());
|
|
}
|
|
Some(Command::Onboard {
|
|
skip_auth,
|
|
channels_only,
|
|
provider_only,
|
|
quick,
|
|
step,
|
|
}) => {
|
|
#[cfg(any(feature = "postgres", feature = "libsql"))]
|
|
{
|
|
let config = SetupConfig {
|
|
skip_auth: *skip_auth,
|
|
channels_only: *channels_only,
|
|
provider_only: *provider_only,
|
|
quick: *quick,
|
|
steps: step.clone(),
|
|
};
|
|
let mut wizard =
|
|
SetupWizard::try_with_config_and_toml(config, cli.config.as_deref())?;
|
|
wizard.run().await?;
|
|
}
|
|
#[cfg(not(any(feature = "postgres", feature = "libsql")))]
|
|
{
|
|
let _ = (skip_auth, channels_only, provider_only, quick, step);
|
|
eprintln!("Onboarding wizard requires the 'postgres' or 'libsql' feature.");
|
|
}
|
|
return Ok(());
|
|
}
|
|
None | Some(Command::Run) => {
|
|
// Continue to run agent
|
|
}
|
|
}
|
|
|
|
// ── PID lock (prevent multiple instances) ────────────────────────
|
|
let _pid_lock = match ironclaw::bootstrap::PidLock::acquire() {
|
|
Ok(lock) => Some(lock),
|
|
Err(ironclaw::bootstrap::PidLockError::AlreadyRunning { pid }) => {
|
|
anyhow::bail!(
|
|
"Another IronClaw instance is already running (PID {}). \
|
|
If this is incorrect, remove the stale PID file: {}",
|
|
pid,
|
|
ironclaw::bootstrap::pid_lock_path().display()
|
|
);
|
|
}
|
|
Err(e) => {
|
|
eprintln!("Warning: Could not acquire PID lock: {}", e);
|
|
eprintln!("Continuing without PID lock protection.");
|
|
None
|
|
}
|
|
};
|
|
|
|
let startup_start = std::time::Instant::now();
|
|
|
|
// ── Agent startup ──────────────────────────────────────────────────
|
|
|
|
// Enhanced first-run detection
|
|
#[cfg(any(feature = "postgres", feature = "libsql"))]
|
|
if !cli.no_onboard
|
|
&& let Some(reason) = ironclaw::setup::check_onboard_needed()
|
|
{
|
|
println!("Onboarding needed: {}", reason);
|
|
println!();
|
|
let mut wizard = SetupWizard::try_with_config_and_toml(
|
|
SetupConfig {
|
|
quick: true,
|
|
..Default::default()
|
|
},
|
|
cli.config.as_deref(),
|
|
)?;
|
|
wizard.run().await?;
|
|
}
|
|
|
|
// Load initial config from env + disk + optional TOML (before DB is available).
|
|
// Credentials may be missing at this point — that's fine. LlmConfig::resolve()
|
|
// defers gracefully, and AppBuilder::build_all() re-resolves after loading
|
|
// secrets from the encrypted DB.
|
|
let toml_path = cli.config.as_deref();
|
|
let config = match Config::from_env_with_toml(toml_path).await {
|
|
Ok(c) => c,
|
|
Err(ironclaw::error::ConfigError::MissingRequired { key, hint }) => {
|
|
anyhow::bail!(
|
|
"Configuration error: Missing required setting '{}'. {}. \
|
|
Run 'ironclaw onboard' to configure, or set the required environment variables.",
|
|
key,
|
|
hint
|
|
);
|
|
}
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
|
|
// Initialize session manager before channel setup
|
|
let session = create_session_manager(config.llm.session.clone()).await;
|
|
|
|
// Create log broadcaster before tracing init so the WebLogLayer can capture all events.
|
|
let log_broadcaster = Arc::new(LogBroadcaster::new());
|
|
|
|
// Initialize tracing with a reloadable EnvFilter so the gateway can switch
|
|
// log levels at runtime without restarting.
|
|
let log_level_handle =
|
|
ironclaw::channels::web::log_layer::init_tracing(Arc::clone(&log_broadcaster));
|
|
|
|
tracing::debug!("Starting IronClaw...");
|
|
tracing::debug!("Loaded configuration for agent: {}", config.agent.name);
|
|
tracing::debug!("LLM backend: {}", config.llm.backend);
|
|
|
|
// ── Phase 1-5: Build all core components via AppBuilder ────────────
|
|
|
|
let flags = AppBuilderFlags { no_db: cli.no_db };
|
|
let components = AppBuilder::new(
|
|
config,
|
|
flags,
|
|
toml_path.map(std::path::PathBuf::from),
|
|
session.clone(),
|
|
Arc::clone(&log_broadcaster),
|
|
)
|
|
.build_all()
|
|
.await?;
|
|
|
|
let config = components.config;
|
|
|
|
// ── Tunnel setup ───────────────────────────────────────────────────
|
|
|
|
let (config, active_tunnel) = ironclaw::tunnel::start_managed_tunnel(config).await;
|
|
|
|
// ── Orchestrator / container job manager ────────────────────────────
|
|
|
|
let orch = ironclaw::orchestrator::setup_orchestrator(
|
|
&config,
|
|
&components.llm,
|
|
components.db.as_ref(),
|
|
components.secrets_store.as_ref(),
|
|
)
|
|
.await;
|
|
let container_job_manager = orch.container_job_manager;
|
|
let job_event_tx = orch.job_event_tx;
|
|
let prompt_queue = orch.prompt_queue;
|
|
let docker_status = orch.docker_status;
|
|
|
|
// Derive user-facing warning from docker_status for channel notification
|
|
let docker_user_warning: Option<String> = match docker_status {
|
|
ironclaw::sandbox::DockerStatus::NotInstalled => Some(
|
|
"Sandbox is enabled but Docker is not installed -- \
|
|
full_job routines will fail until Docker is available."
|
|
.to_string(),
|
|
),
|
|
ironclaw::sandbox::DockerStatus::NotRunning => Some(
|
|
"Sandbox is enabled but Docker is not running -- \
|
|
full_job routines will fail until Docker is started."
|
|
.to_string(),
|
|
),
|
|
_ => None,
|
|
};
|
|
|
|
// ── Channel setup ──────────────────────────────────────────────────
|
|
|
|
let channels = ChannelManager::new();
|
|
let mut channel_names: Vec<String> = Vec::new();
|
|
let mut loaded_wasm_channel_names: Vec<String> = Vec::new();
|
|
#[allow(clippy::type_complexity)]
|
|
let mut wasm_channel_runtime_state: Option<(
|
|
Arc<WasmChannelRuntime>,
|
|
Arc<PairingStore>,
|
|
Arc<WasmChannelRouter>,
|
|
)> = None;
|
|
|
|
// Create CLI channel
|
|
let repl_channel = if let Some(ref msg) = cli.message {
|
|
Some(ReplChannel::with_message_for_user(
|
|
config.owner_id.clone(),
|
|
msg.clone(),
|
|
))
|
|
} else if config.channels.cli.enabled {
|
|
let repl = ReplChannel::with_user_id(config.owner_id.clone());
|
|
repl.suppress_banner();
|
|
Some(repl)
|
|
} else {
|
|
None
|
|
};
|
|
|
|
if let Some(repl) = repl_channel {
|
|
channels.add(Box::new(repl)).await;
|
|
if cli.message.is_some() {
|
|
tracing::debug!("Single message mode");
|
|
} else {
|
|
channel_names.push("repl".to_string());
|
|
tracing::debug!("REPL mode enabled");
|
|
}
|
|
}
|
|
|
|
// Shared routine engine slot for gateway + generic webhook ingress.
|
|
let shared_routine_engine_slot: ironclaw::channels::web::server::RoutineEngineSlot =
|
|
Arc::new(tokio::sync::RwLock::new(None));
|
|
|
|
// Collect webhook route fragments; a single WebhookServer hosts them all.
|
|
let mut webhook_routes: Vec<axum::Router> = Vec::new();
|
|
|
|
webhook_routes.push(webhooks::routes(ToolWebhookState {
|
|
tools: Arc::clone(&components.tools),
|
|
routine_engine: Arc::clone(&shared_routine_engine_slot),
|
|
user_id: config.owner_id.clone(),
|
|
secrets_store: components.secrets_store.clone(),
|
|
}));
|
|
|
|
// Load WASM channels and register their webhook routes.
|
|
// Ensure the channels directory exists so the WASM runtime initializes even when
|
|
// no channels are installed yet — hot-activation needs the runtime to be available.
|
|
if config.channels.wasm_channels_enabled
|
|
&& let Err(e) = std::fs::create_dir_all(&config.channels.wasm_channels_dir)
|
|
{
|
|
tracing::warn!(
|
|
path = %config.channels.wasm_channels_dir.display(),
|
|
error = %e,
|
|
"Failed to create WASM channels directory"
|
|
);
|
|
}
|
|
if config.channels.wasm_channels_enabled && config.channels.wasm_channels_dir.exists() {
|
|
let wasm_result = ironclaw::channels::wasm::setup_wasm_channels(
|
|
&config,
|
|
&components.secrets_store,
|
|
components.extension_manager.as_ref(),
|
|
components.db.as_ref(),
|
|
)
|
|
.await;
|
|
|
|
if let Some(result) = wasm_result {
|
|
loaded_wasm_channel_names = result.channel_names;
|
|
wasm_channel_runtime_state = Some((
|
|
result.wasm_channel_runtime,
|
|
result.pairing_store,
|
|
result.wasm_channel_router,
|
|
));
|
|
for (name, channel) in result.channels {
|
|
channel_names.push(name);
|
|
channels.add(channel).await;
|
|
}
|
|
if let Some(routes) = result.webhook_routes {
|
|
webhook_routes.push(routes);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Add Signal channel if configured and not CLI-only mode.
|
|
if !cli.cli_only
|
|
&& let Some(ref signal_config) = config.channels.signal
|
|
{
|
|
let signal_channel = SignalChannel::new(signal_config.clone())?;
|
|
channel_names.push("signal".to_string());
|
|
channels.add(Box::new(signal_channel)).await;
|
|
let safe_url = SignalChannel::redact_url(&signal_config.http_url);
|
|
tracing::debug!(
|
|
url = %safe_url,
|
|
"Signal channel enabled"
|
|
);
|
|
if signal_config.allow_from.is_empty() {
|
|
tracing::warn!(
|
|
"Signal channel has empty allow_from list - ALL messages will be DENIED."
|
|
);
|
|
}
|
|
}
|
|
|
|
// Add HTTP channel if configured and not CLI-only mode.
|
|
let mut webhook_server_addr: Option<std::net::SocketAddr> = None;
|
|
#[cfg(unix)]
|
|
let mut http_channel_state: Option<Arc<ironclaw::channels::HttpChannelState>> = None;
|
|
if !cli.cli_only
|
|
&& let Some(ref http_config) = config.channels.http
|
|
{
|
|
let http_channel = HttpChannel::new(http_config.clone());
|
|
#[cfg(unix)]
|
|
{
|
|
http_channel_state = Some(http_channel.shared_state());
|
|
}
|
|
webhook_routes.push(http_channel.routes());
|
|
let (host, port) = http_channel.addr();
|
|
webhook_server_addr = Some(
|
|
format!("{}:{}", host, port)
|
|
.parse()
|
|
.expect("HttpConfig host:port must be a valid SocketAddr"),
|
|
);
|
|
channel_names.push("http".to_string());
|
|
channels.add(Box::new(http_channel)).await;
|
|
tracing::debug!(
|
|
"HTTP channel enabled on {}:{}",
|
|
http_config.host,
|
|
http_config.port
|
|
);
|
|
}
|
|
|
|
// Start the unified webhook server if any routes were registered.
|
|
let webhook_server: Option<Arc<tokio::sync::Mutex<WebhookServer>>> = if !webhook_routes
|
|
.is_empty()
|
|
{
|
|
let addr =
|
|
webhook_server_addr.unwrap_or_else(|| std::net::SocketAddr::from(([0, 0, 0, 0], 8080)));
|
|
if addr.ip().is_unspecified() {
|
|
tracing::warn!(
|
|
"Webhook server is binding to {} — it will be reachable from all network interfaces. \
|
|
Set HTTP_HOST=127.0.0.1 to restrict to localhost.",
|
|
addr.ip()
|
|
);
|
|
}
|
|
let mut server = WebhookServer::new(WebhookServerConfig { addr });
|
|
for routes in webhook_routes {
|
|
server.add_routes(routes);
|
|
}
|
|
server.start().await?;
|
|
Some(Arc::new(tokio::sync::Mutex::new(server)))
|
|
} else {
|
|
None
|
|
};
|
|
|
|
// Register lifecycle hooks.
|
|
let active_tool_names = components.tools.list().await;
|
|
|
|
let hook_bootstrap = bootstrap_hooks(
|
|
&components.hooks,
|
|
components.workspace.as_ref(),
|
|
&config.wasm.tools_dir,
|
|
&config.channels.wasm_channels_dir,
|
|
&active_tool_names,
|
|
&loaded_wasm_channel_names,
|
|
&components.dev_loaded_tool_names,
|
|
)
|
|
.await;
|
|
tracing::debug!(
|
|
bundled = hook_bootstrap.bundled_hooks,
|
|
plugin = hook_bootstrap.plugin_hooks,
|
|
workspace = hook_bootstrap.workspace_hooks,
|
|
outbound_webhooks = hook_bootstrap.outbound_webhooks,
|
|
errors = hook_bootstrap.errors,
|
|
"Lifecycle hooks initialized"
|
|
);
|
|
|
|
// Reuse the shared agent session manager prepared by AppBuilder.
|
|
let session_manager = Arc::clone(&components.agent_session_manager);
|
|
|
|
// Lazy scheduler slot — filled after Agent::new creates the Scheduler.
|
|
// Allows CreateJobTool to dispatch local jobs via the Scheduler even though
|
|
// the Scheduler is created after tools are registered (chicken-and-egg).
|
|
let scheduler_slot: ironclaw::tools::builtin::SchedulerSlot =
|
|
Arc::new(tokio::sync::RwLock::new(None));
|
|
|
|
// Register job tools (sandbox deps auto-injected when container_job_manager is available)
|
|
components.tools.register_job_tools(
|
|
Arc::clone(&components.context_manager),
|
|
Some(scheduler_slot.clone()),
|
|
container_job_manager.clone(),
|
|
components.db.clone(),
|
|
job_event_tx.clone(),
|
|
Some(channels.inject_sender()),
|
|
if config.sandbox.enabled {
|
|
Some(Arc::clone(&prompt_queue))
|
|
} else {
|
|
None
|
|
},
|
|
components.secrets_store.clone(),
|
|
);
|
|
|
|
// ── Gateway channel ────────────────────────────────────────────────
|
|
|
|
let mut gateway_url: Option<String> = None;
|
|
let mut sse_manager: Option<std::sync::Arc<ironclaw::channels::web::sse::SseManager>> = None;
|
|
if let Some(ref gw_config) = config.channels.gateway {
|
|
let mut gw = GatewayChannel::new(gw_config.clone(), config.owner_id.clone());
|
|
gw = gw.with_llm_provider(Arc::clone(&components.llm));
|
|
if let Some(ref ws) = components.workspace {
|
|
gw = gw.with_workspace(Arc::clone(ws));
|
|
}
|
|
// Create per-user workspace pool for multi-user mode.
|
|
if let Some(ref db) = components.db {
|
|
let emb_cache_config = ironclaw::workspace::EmbeddingCacheConfig {
|
|
max_entries: config.embeddings.cache_size,
|
|
};
|
|
let pool = Arc::new(ironclaw::channels::web::server::WorkspacePool::new(
|
|
Arc::clone(db),
|
|
components.embeddings.clone(),
|
|
emb_cache_config,
|
|
config.search.clone(),
|
|
config.workspace.clone(),
|
|
));
|
|
gw = gw.with_workspace_pool(pool);
|
|
}
|
|
gw = gw.with_session_manager(Arc::clone(&session_manager));
|
|
gw = gw.with_log_broadcaster(Arc::clone(&log_broadcaster));
|
|
gw = gw.with_log_level_handle(Arc::clone(&log_level_handle));
|
|
gw = gw.with_tool_registry(Arc::clone(&components.tools));
|
|
if let Some(ref ext_mgr) = components.extension_manager {
|
|
// Enable gateway mode so MCP OAuth returns auth URLs to the frontend
|
|
// instead of calling open::that() on the server.
|
|
let gw_base = config
|
|
.tunnel
|
|
.public_url
|
|
.clone()
|
|
.unwrap_or_else(|| format!("http://{}:{}", gw_config.host, gw_config.port));
|
|
ext_mgr.enable_gateway_mode(gw_base).await;
|
|
gw = gw.with_extension_manager(Arc::clone(ext_mgr));
|
|
}
|
|
if !components.catalog_entries.is_empty() {
|
|
gw = gw.with_registry_entries(components.catalog_entries.clone());
|
|
}
|
|
if let Some(ref d) = components.db {
|
|
gw = gw.with_store(Arc::clone(d));
|
|
gw = gw.with_db_auth(Arc::clone(d));
|
|
if let Some(ref ss) = components.secrets_store {
|
|
gw = gw.with_secrets_store(Arc::clone(ss));
|
|
}
|
|
|
|
// Bootstrap: create the first admin user from single-user config
|
|
// so the owner appears in the Users admin panel immediately.
|
|
if let Ok(false) = d.has_any_users().await {
|
|
let now = chrono::Utc::now();
|
|
let user = ironclaw::db::UserRecord {
|
|
id: config.owner_id.clone(),
|
|
email: None,
|
|
display_name: config.owner_id.clone(),
|
|
status: "active".to_string(),
|
|
role: "admin".to_string(),
|
|
created_at: now,
|
|
updated_at: now,
|
|
last_login_at: None,
|
|
created_by: None,
|
|
metadata: serde_json::json!({"source": "bootstrap"}),
|
|
};
|
|
// Create admin user + bootstrap token atomically.
|
|
let auth_token = gw.auth_token();
|
|
if auth_token.is_empty() {
|
|
if let Err(e) = d.create_user(&user).await {
|
|
tracing::warn!("Failed to bootstrap admin user: {}", e);
|
|
}
|
|
} else {
|
|
use ironclaw::channels::web::auth::hash_token;
|
|
let hash = hash_token(auth_token);
|
|
let prefix = if auth_token.len() >= 8 {
|
|
&auth_token[..8]
|
|
} else {
|
|
auth_token
|
|
};
|
|
if let Err(e) = d
|
|
.create_user_with_token(&user, "bootstrap", &hash, prefix, None)
|
|
.await
|
|
{
|
|
tracing::warn!("Failed to bootstrap admin user: {}", e);
|
|
} else {
|
|
tracing::info!(
|
|
user_id = config.owner_id,
|
|
"Bootstrapped admin user from gateway config"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if let Some(ref jm) = container_job_manager {
|
|
gw = gw.with_job_manager(Arc::clone(jm));
|
|
}
|
|
gw = gw.with_scheduler(scheduler_slot.clone());
|
|
gw = gw.with_routine_engine_slot(Arc::clone(&shared_routine_engine_slot));
|
|
if let Some(ref sr) = components.skill_registry {
|
|
gw = gw.with_skill_registry(Arc::clone(sr));
|
|
}
|
|
if let Some(ref sc) = components.skill_catalog {
|
|
gw = gw.with_skill_catalog(Arc::clone(sc));
|
|
}
|
|
gw = gw.with_cost_guard(Arc::clone(&components.cost_guard));
|
|
{
|
|
let active_model = components.llm.model_name().to_string();
|
|
let mut enabled = channel_names.clone();
|
|
enabled.push("gateway".into());
|
|
gw = gw.with_active_config(ironclaw::channels::web::server::ActiveConfigSnapshot {
|
|
llm_backend: config.llm.backend.to_string(),
|
|
llm_model: active_model,
|
|
enabled_channels: enabled,
|
|
});
|
|
}
|
|
if config.sandbox.enabled {
|
|
gw = gw.with_prompt_queue(Arc::clone(&prompt_queue));
|
|
|
|
if let Some(ref tx) = job_event_tx {
|
|
let mut rx = tx.subscribe();
|
|
let gw_state = Arc::clone(gw.state());
|
|
tokio::spawn(async move {
|
|
while let Ok((_job_id, user_id, event)) = rx.recv().await {
|
|
if user_id.is_empty() {
|
|
gw_state.sse.broadcast(event);
|
|
} else {
|
|
gw_state.sse.broadcast_for_user(&user_id, event);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Persist auto-generated auth token so it survives restarts.
|
|
// Write to the "default" settings namespace, which is the namespace
|
|
// Config::from_db() reads from — NOT the gateway channel's user_id.
|
|
if gw_config.auth_token.is_none() {
|
|
let token_to_persist = gw.auth_token().to_string();
|
|
if let Some(ref db) = components.db {
|
|
let db = db.clone();
|
|
tokio::spawn(async move {
|
|
if let Err(e) = db
|
|
.set_setting(
|
|
"default",
|
|
"channels.gateway_auth_token",
|
|
&serde_json::Value::String(token_to_persist),
|
|
)
|
|
.await
|
|
{
|
|
tracing::warn!("Failed to persist auto-generated gateway auth token: {e}");
|
|
} else {
|
|
tracing::debug!("Persisted auto-generated gateway auth token to settings");
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
gateway_url = Some(format!(
|
|
"http://{}:{}/?token={}",
|
|
gw_config.host,
|
|
gw_config.port,
|
|
gw.auth_token()
|
|
));
|
|
|
|
tracing::debug!("Web UI: http://{}:{}/", gw_config.host, gw_config.port);
|
|
|
|
// Capture SSE sender and routine engine slot before moving gw into channels.
|
|
// IMPORTANT: This must come after all `with_*` calls since `rebuild_state`
|
|
// creates a new SseManager, which would orphan this sender.
|
|
sse_manager = Some(Arc::clone(&gw.state().sse));
|
|
channel_names.push("gateway".to_string());
|
|
channels.add(Box::new(gw)).await;
|
|
}
|
|
|
|
// ── Boot screen ────────────────────────────────────────────────────
|
|
|
|
let boot_tool_count = components.tools.count();
|
|
let boot_llm_model = components.llm.model_name().to_string();
|
|
let boot_cheap_model = components
|
|
.cheap_llm
|
|
.as_ref()
|
|
.map(|c| c.model_name().to_string());
|
|
|
|
if config.channels.cli.enabled && cli.message.is_none() {
|
|
let boot_info = ironclaw::boot_screen::BootInfo {
|
|
version: env!("CARGO_PKG_VERSION").to_string(),
|
|
agent_name: config.agent.name.clone(),
|
|
llm_backend: config.llm.backend.to_string(),
|
|
llm_model: boot_llm_model,
|
|
cheap_model: boot_cheap_model,
|
|
db_backend: if cli.no_db {
|
|
"none".to_string()
|
|
} else {
|
|
config.database.backend.to_string()
|
|
},
|
|
db_connected: !cli.no_db,
|
|
tool_count: boot_tool_count,
|
|
gateway_url,
|
|
embeddings_enabled: config.embeddings.enabled,
|
|
embeddings_provider: if config.embeddings.enabled {
|
|
Some(config.embeddings.provider.clone())
|
|
} else {
|
|
None
|
|
},
|
|
heartbeat_enabled: config.heartbeat.enabled,
|
|
heartbeat_interval_secs: config.heartbeat.interval_secs,
|
|
sandbox_enabled: config.sandbox.enabled,
|
|
docker_status,
|
|
claude_code_enabled: config.claude_code.enabled,
|
|
routines_enabled: config.routines.enabled,
|
|
skills_enabled: config.skills.enabled,
|
|
channels: channel_names,
|
|
tunnel_url: active_tunnel
|
|
.as_ref()
|
|
.and_then(|t| t.public_url())
|
|
.or_else(|| config.tunnel.public_url.clone()),
|
|
tunnel_provider: active_tunnel.as_ref().map(|t| t.name().to_string()),
|
|
startup_elapsed: Some(startup_start.elapsed()),
|
|
};
|
|
ironclaw::boot_screen::print_boot_screen(&boot_info);
|
|
}
|
|
|
|
// ── Run the agent ──────────────────────────────────────────────────
|
|
|
|
let channels = Arc::new(channels);
|
|
|
|
// Register message tool for sending messages to connected channels
|
|
components
|
|
.tools
|
|
.register_message_tools(Arc::clone(&channels), components.extension_manager.clone())
|
|
.await;
|
|
|
|
// Default user ID for extension operations (single-user mode).
|
|
let ext_user_id = config.owner_id.clone();
|
|
|
|
// Wire up channel runtime for hot-activation of WASM channels.
|
|
if let Some(ref ext_mgr) = components.extension_manager
|
|
&& let Some((rt, ps, router)) = wasm_channel_runtime_state.take()
|
|
{
|
|
let active_at_startup: std::collections::HashSet<String> =
|
|
loaded_wasm_channel_names.iter().cloned().collect();
|
|
ext_mgr.set_active_channels(loaded_wasm_channel_names).await;
|
|
ext_mgr
|
|
.set_channel_runtime(
|
|
Arc::clone(&channels),
|
|
rt,
|
|
ps,
|
|
router,
|
|
config.channels.wasm_channel_owner_ids.clone(),
|
|
)
|
|
.await;
|
|
tracing::debug!("Channel runtime wired into extension manager for hot-activation");
|
|
|
|
// Auto-activate WASM channels that were active in a previous session.
|
|
// Relay channels are handled separately below via restore_relay_channels().
|
|
let persisted = ext_mgr.load_persisted_active_channels(&ext_user_id).await;
|
|
for name in &persisted {
|
|
if active_at_startup.contains(name)
|
|
|| ext_mgr.is_relay_channel(name, &ext_user_id).await
|
|
{
|
|
continue;
|
|
}
|
|
match ext_mgr.activate(name, &ext_user_id).await {
|
|
Ok(result) => {
|
|
tracing::debug!(
|
|
channel = %name,
|
|
message = %result.message,
|
|
"Auto-activated persisted WASM channel"
|
|
);
|
|
}
|
|
Err(e) => {
|
|
tracing::warn!(
|
|
channel = %name,
|
|
error = %e,
|
|
"Failed to auto-activate persisted WASM channel"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Ensure the relay channel manager is always set (even without WASM runtime),
|
|
// then restore any persisted relay channels.
|
|
if let Some(ref ext_mgr) = components.extension_manager {
|
|
ext_mgr
|
|
.set_relay_channel_manager(Arc::clone(&channels))
|
|
.await;
|
|
ext_mgr.restore_relay_channels(&ext_user_id).await;
|
|
}
|
|
|
|
// Wire SSE sender into extension manager for broadcasting status events.
|
|
if let Some(ref ext_mgr) = components.extension_manager
|
|
&& let Some(ref sse) = sse_manager
|
|
{
|
|
ext_mgr.set_sse_sender(Arc::clone(sse)).await;
|
|
}
|
|
|
|
// Snapshot memory for trace recording before the agent starts
|
|
if let Some(ref recorder) = components.recording_handle
|
|
&& let Some(ref ws) = components.workspace
|
|
{
|
|
recorder.snapshot_memory(ws).await;
|
|
}
|
|
|
|
let http_interceptor = components
|
|
.recording_handle
|
|
.as_ref()
|
|
.map(|r| r.http_interceptor());
|
|
// Clone context_manager for the reaper before it's moved into Agent::new()
|
|
let reaper_context_manager = Arc::clone(&components.context_manager);
|
|
|
|
// Capture db reference for SIGHUP handler before it's moved into AgentDeps (Unix only)
|
|
#[cfg(unix)]
|
|
let sighup_settings_store: Option<Arc<dyn ironclaw::db::SettingsStore>> = components
|
|
.db
|
|
.as_ref()
|
|
.map(|db| Arc::clone(db) as Arc<dyn ironclaw::db::SettingsStore>);
|
|
|
|
let deps = AgentDeps {
|
|
owner_id: config.owner_id.clone(),
|
|
store: components.db,
|
|
llm: components.llm,
|
|
cheap_llm: components.cheap_llm,
|
|
safety: components.safety,
|
|
tools: components.tools,
|
|
workspace: components.workspace,
|
|
extension_manager: components.extension_manager,
|
|
skill_registry: components.skill_registry,
|
|
skill_catalog: components.skill_catalog,
|
|
skills_config: config.skills.clone(),
|
|
hooks: components.hooks,
|
|
cost_guard: components.cost_guard,
|
|
sse_tx: sse_manager,
|
|
http_interceptor,
|
|
transcription: config.transcription.create_provider().map(|p| {
|
|
Arc::new(ironclaw::llm::transcription::TranscriptionMiddleware::new(
|
|
p,
|
|
))
|
|
}),
|
|
document_extraction: Some(Arc::new(
|
|
ironclaw::document_extraction::DocumentExtractionMiddleware::new(),
|
|
)),
|
|
sandbox_readiness: if !config.sandbox.enabled {
|
|
ironclaw::agent::routine_engine::SandboxReadiness::DisabledByConfig
|
|
} else if docker_status.is_ok() {
|
|
ironclaw::agent::routine_engine::SandboxReadiness::Available
|
|
} else {
|
|
ironclaw::agent::routine_engine::SandboxReadiness::DockerUnavailable
|
|
},
|
|
builder: components.builder,
|
|
llm_backend: config.llm.backend.clone(),
|
|
tenant_rates: Arc::new(ironclaw::tenant::TenantRateRegistry::new(
|
|
config.agent.max_llm_concurrent_per_user.unwrap_or(4),
|
|
config.agent.max_jobs_concurrent_per_user.unwrap_or(3),
|
|
)),
|
|
};
|
|
|
|
let channels_for_warnings = Arc::clone(&channels);
|
|
let mut agent = Agent::new(
|
|
config.agent.clone(),
|
|
deps,
|
|
channels,
|
|
Some(config.heartbeat.clone()),
|
|
Some(config.hygiene.clone()),
|
|
Some(config.routines.clone()),
|
|
Some(components.context_manager),
|
|
Some(session_manager),
|
|
);
|
|
|
|
// Fill the scheduler slot now that Agent (and its Scheduler) exist.
|
|
*scheduler_slot.write().await = Some(agent.scheduler());
|
|
|
|
// Spawn sandbox reaper for orphaned container cleanup
|
|
if let Some(ref jm) = container_job_manager {
|
|
let reaper_jm = Arc::clone(jm);
|
|
let reaper_config = ReaperConfig {
|
|
scan_interval: Duration::from_secs(config.sandbox.reaper_interval_secs),
|
|
orphan_threshold: Duration::from_secs(config.sandbox.orphan_threshold_secs),
|
|
..ReaperConfig::default()
|
|
};
|
|
let reaper_ctx = Arc::clone(&reaper_context_manager);
|
|
tokio::spawn(async move {
|
|
match SandboxReaper::new(reaper_jm, reaper_ctx, reaper_config).await {
|
|
Ok(reaper) => reaper.run().await,
|
|
Err(e) => tracing::error!("Sandbox reaper failed to initialize: {}", e),
|
|
}
|
|
});
|
|
}
|
|
|
|
// Give the agent the routine engine slot so it can expose the engine to the gateway.
|
|
agent.set_routine_engine_slot(shared_routine_engine_slot);
|
|
|
|
// Prepare SIGHUP handler for hot-reloading HTTP webhook config
|
|
// Broadcast channel for clean shutdown of background tasks
|
|
let (shutdown_tx, _) = tokio::sync::broadcast::channel::<()>(1);
|
|
|
|
#[cfg(unix)]
|
|
{
|
|
// Collect all channels that support secret updates
|
|
let mut secret_updaters: Vec<Arc<dyn ChannelSecretUpdater>> = Vec::new();
|
|
if let Some(ref state) = http_channel_state {
|
|
secret_updaters.push(Arc::clone(state) as Arc<dyn ChannelSecretUpdater>);
|
|
}
|
|
|
|
let sighup_webhook_server = webhook_server.clone();
|
|
let sighup_settings_store_clone = sighup_settings_store.clone();
|
|
let sighup_secrets_store = components.secrets_store.clone();
|
|
let sighup_owner_id = config.owner_id.clone();
|
|
let mut shutdown_rx = shutdown_tx.subscribe();
|
|
|
|
tokio::spawn(async move {
|
|
use tokio::signal::unix::{SignalKind, signal};
|
|
let mut sighup = match signal(SignalKind::hangup()) {
|
|
Ok(s) => s,
|
|
Err(e) => {
|
|
tracing::warn!("Failed to register SIGHUP handler: {}", e);
|
|
return;
|
|
}
|
|
};
|
|
|
|
loop {
|
|
// Exit loop on shutdown signal or when SIGHUP is received
|
|
tokio::select! {
|
|
_ = shutdown_rx.recv() => {
|
|
tracing::debug!("SIGHUP handler shutting down");
|
|
break;
|
|
}
|
|
_ = sighup.recv() => {
|
|
// Handle SIGHUP signal
|
|
}
|
|
}
|
|
tracing::info!("SIGHUP received — reloading HTTP webhook config");
|
|
|
|
// Inject channel secrets from database into thread-safe overlay
|
|
// (similar to inject_llm_keys_from_secrets for LLM providers)
|
|
if let Some(ref secrets_store) = sighup_secrets_store {
|
|
// Inject HTTP webhook secret from encrypted store
|
|
if let Ok(webhook_secret) = secrets_store
|
|
.get_decrypted(&sighup_owner_id, "http_webhook_secret")
|
|
.await
|
|
{
|
|
// Thread-safe: Uses INJECTED_VARS mutex instead of unsafe std::env::set_var
|
|
// Config::from_env() will read from the overlay via optional_env()
|
|
ironclaw::config::inject_single_var(
|
|
"HTTP_WEBHOOK_SECRET",
|
|
webhook_secret.expose(),
|
|
);
|
|
tracing::debug!("Injected HTTP_WEBHOOK_SECRET from secrets store");
|
|
}
|
|
}
|
|
|
|
// Reload config (now with secrets injected into environment)
|
|
let new_config = match &sighup_settings_store_clone {
|
|
Some(store) => {
|
|
ironclaw::config::Config::from_db(store.as_ref(), &sighup_owner_id).await
|
|
}
|
|
None => ironclaw::config::Config::from_env().await,
|
|
};
|
|
|
|
let new_config = match new_config {
|
|
Ok(c) => c,
|
|
Err(e) => {
|
|
tracing::error!("SIGHUP config reload failed: {}", e);
|
|
continue;
|
|
}
|
|
};
|
|
|
|
let new_http = match new_config.channels.http {
|
|
Some(c) => c,
|
|
None => {
|
|
tracing::warn!("SIGHUP: HTTP channel no longer configured, skipping");
|
|
continue;
|
|
}
|
|
};
|
|
|
|
// Compute new socket addr
|
|
let new_addr: std::net::SocketAddr =
|
|
match format!("{}:{}", new_http.host, new_http.port).parse() {
|
|
Ok(a) => a,
|
|
Err(e) => {
|
|
tracing::error!("SIGHUP: invalid addr in config: {}", e);
|
|
continue;
|
|
}
|
|
};
|
|
|
|
// Restart listener if addr changed.
|
|
// Two-phase approach: bind outside the lock, then swap under lock.
|
|
let mut restart_failed = false;
|
|
if let Some(ref ws_arc) = sighup_webhook_server {
|
|
let (old_addr, router) = {
|
|
let ws = ws_arc.lock().await;
|
|
(ws.current_addr(), ws.merged_router_clone())
|
|
}; // Lock released here
|
|
|
|
if old_addr != new_addr {
|
|
tracing::info!(
|
|
"SIGHUP: HTTP addr {} -> {}, restarting listener",
|
|
old_addr,
|
|
new_addr
|
|
);
|
|
|
|
match router {
|
|
Some(app) => {
|
|
// Phase 1: Bind new listener WITHOUT holding the lock.
|
|
match tokio::net::TcpListener::bind(new_addr).await {
|
|
Ok(listener) => {
|
|
// Phase 2: Swap state under lock (no await inside).
|
|
let (old_tx, old_handle) = {
|
|
let mut ws = ws_arc.lock().await;
|
|
ws.install_listener(new_addr, listener, app)
|
|
}; // Lock released here
|
|
|
|
// Phase 3: Shut down old listener outside the lock.
|
|
if let Some(tx) = old_tx {
|
|
let _ = tx.send(());
|
|
}
|
|
if let Some(handle) = old_handle {
|
|
let _ = handle.await;
|
|
}
|
|
|
|
tracing::info!(
|
|
"SIGHUP: webhook server restarted on {}",
|
|
new_addr
|
|
);
|
|
}
|
|
Err(e) => {
|
|
tracing::error!(
|
|
"SIGHUP: failed to bind to {}: {}",
|
|
new_addr,
|
|
e
|
|
);
|
|
restart_failed = true;
|
|
}
|
|
}
|
|
}
|
|
None => {
|
|
tracing::error!(
|
|
"SIGHUP: cannot restart — server was never started"
|
|
);
|
|
restart_failed = true;
|
|
}
|
|
}
|
|
} else {
|
|
tracing::debug!("SIGHUP: addr unchanged ({})", old_addr);
|
|
}
|
|
}
|
|
|
|
// Update secrets in all configured channels (if restart succeeded or wasn't needed)
|
|
if !restart_failed {
|
|
use secrecy::{ExposeSecret, SecretString};
|
|
let new_secret = new_http
|
|
.webhook_secret
|
|
.as_ref()
|
|
.map(|s| SecretString::from(s.expose_secret().to_string()));
|
|
|
|
// Update all channels that support secret swapping
|
|
for updater in &secret_updaters {
|
|
updater.update_secret(new_secret.clone()).await;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// Notify user if sandbox is unavailable (Docker missing/not running)
|
|
if let Some(warning) = docker_user_warning {
|
|
let channels_ref = Arc::clone(&channels_for_warnings);
|
|
tokio::spawn(async move {
|
|
// Delay to let channels finish connecting before sending the warning.
|
|
// 5s is generous but avoids the message being lost on slow startups.
|
|
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
|
tracing::debug!("Sending sandbox-unavailable warning to connected channels");
|
|
let response = ironclaw::channels::OutgoingResponse {
|
|
content: format!("Warning: {warning}"),
|
|
thread_id: None,
|
|
attachments: Vec::new(),
|
|
metadata: serde_json::json!({
|
|
"source": "system",
|
|
"type": "warning",
|
|
}),
|
|
};
|
|
let _ = channels_ref.broadcast_all("default", response).await;
|
|
});
|
|
}
|
|
|
|
agent.run().await?;
|
|
|
|
// ── Shutdown ────────────────────────────────────────────────────────
|
|
|
|
// Signal background tasks (SIGHUP handler, etc.) to gracefully shut down
|
|
let _ = shutdown_tx.send(());
|
|
|
|
// Shut down all stdio MCP server child processes.
|
|
components.mcp_process_manager.shutdown_all().await;
|
|
|
|
// Flush LLM trace recording if enabled
|
|
if let Some(ref recorder) = components.recording_handle
|
|
&& let Err(e) = recorder.flush().await
|
|
{
|
|
tracing::warn!("Failed to write LLM trace: {}", e);
|
|
}
|
|
|
|
if let Some(ref ws_arc) = webhook_server {
|
|
let (shutdown_tx, handle) = {
|
|
let mut ws = ws_arc.lock().await;
|
|
ws.begin_shutdown()
|
|
};
|
|
if let Some(tx) = shutdown_tx {
|
|
let _ = tx.send(());
|
|
}
|
|
if let Some(handle) = handle {
|
|
let _ = handle.await;
|
|
}
|
|
}
|
|
|
|
if let Some(tunnel) = active_tunnel {
|
|
tracing::debug!("Stopping {} tunnel...", tunnel.name());
|
|
if let Err(e) = tunnel.stop().await {
|
|
tracing::warn!("Failed to stop tunnel cleanly: {}", e);
|
|
}
|
|
}
|
|
|
|
tracing::debug!("Agent shutdown complete");
|
|
|
|
Ok(())
|
|
}
|