Class: Clacky::Server::HttpServer
- Inherits:
-
Object
- Object
- Clacky::Server::HttpServer
- Defined in:
- lib/clacky/server/http_server.rb
Overview
HttpServer runs an embedded WEBrick HTTP server with WebSocket support.
Routes:
GET /ws → WebSocket upgrade (all real-time communication)
* /api/* → JSON REST API (sessions, tasks, schedules)
GET /** → static files served from lib/clacky/web/ directory
Defined Under Namespace
Classes: WebSocketConnection
Constant Summary collapse
- WEB_ROOT =
File.("../web", __dir__)
- DEFAULT_SOUL_MD =
Default SOUL.md written when the user skips the onboard conversation. A richer version is created by the Agent during the soul_setup phase.
<<~MD.freeze # Clacky — Agent Soul You are Clacky, a friendly and capable AI coding assistant and technical co-founder. You are sharp, concise, and proactive. You speak plainly and avoid unnecessary formality. You love helping people ship great software. ## Personality - Warm and encouraging, but direct and honest - Think step-by-step before acting; explain your reasoning briefly - Prefer doing over talking — use tools, write code, ship results - Adapt your language and tone to match the user's style ## Strengths - Full-stack software development (Ruby, Python, JS, and more) - Architectural thinking and code review - Debugging tricky problems with patience and creativity - Breaking big goals into small, executable steps MD
- DEFAULT_SOUL_MD_ZH =
Default SOUL.md for Chinese-language users.
<<~MD.freeze # Clacky — 助手灵魂 你是 Clacky,一位友好、能干的 AI 编程助手和技术联合创始人。 你思维敏锐、言简意赅、主动积极。你说话直接,不喜欢过度客套。 你热爱帮助用户打造优秀的软件产品。 **重要:始终用中文回复用户。** ## 性格特点 - 热情鼓励,但直接诚实 - 行动前先思考;简要说明你的推理过程 - 重行动而非空谈 —— 善用工具,写代码,交付结果 - 根据用户的风格调整语气和表达方式 ## 核心能力 - 全栈软件开发(Ruby、Python、JS 等) - 架构设计与代码审查 - 耐心细致地调试复杂问题 - 将大目标拆解为可执行的小步骤 MD
Instance Method Summary collapse
- #_dispatch_rest(req, res) ⇒ Object
-
#api_brand_activate(req, res) ⇒ Object
POST /api/brand/activate Body: { license_key: “XXXX-XXXX-XXXX-XXXX-XXXX” } Activates the license and persists the result to brand.yml.
-
#api_brand_info(res) ⇒ Object
GET /api/brand Returns brand metadata consumed by the WebUI on boot to dynamically replace branding strings.
-
#api_brand_skill_install(slug, req, res) ⇒ Object
POST /api/brand/skills/:name/install Downloads and installs (or updates) the given brand skill.
-
#api_brand_skills(res) ⇒ Object
POST /api/store/skills/:slug/install.
-
#api_brand_status(res) ⇒ Object
GET /api/brand/status Returns whether brand activation is needed.
-
#api_browser_configure(req, res) ⇒ Object
POST /api/browser/configure Called by browser-setup skill to write browser.yml and hot-reload the daemon.
-
#api_browser_reload(res) ⇒ Object
POST /api/browser/reload Called by browser-setup skill after writing browser.yml.
-
#api_browser_status(res) ⇒ Object
GET /api/browser/status Returns real daemon liveness from BrowserManager (not just yml read).
-
#api_browser_toggle(res) ⇒ Object
POST /api/browser/toggle.
- #api_change_session_working_dir(session_id, req, res) ⇒ Object
-
#api_create_cron_task(req, res) ⇒ Object
POST /api/cron-tasks — create task file + schedule in one step Body: { name, content, cron, enabled? }.
- #api_create_session(req, res) ⇒ Object
-
#api_delete_channel(platform, res) ⇒ Object
DELETE /api/channels/:platform Disables the platform (keeps credentials, sets enabled: false).
-
#api_delete_cron_task(name, res) ⇒ Object
DELETE /api/cron-tasks/:name — remove task file + schedule.
- #api_delete_session(session_id, res) ⇒ Object
-
#api_get_config(res) ⇒ Object
GET /api/config — return current model configurations.
-
#api_get_version(res) ⇒ Object
GET /api/version Returns current version and latest version from RubyGems (cached for 1 hour).
- #api_list_channels(res) ⇒ Object
-
#api_list_cron_tasks(res) ⇒ Object
GET /api/cron-tasks.
-
#api_list_providers(res) ⇒ Object
GET /api/providers — return built-in provider presets for quick setup.
-
#api_list_sessions(req, res) ⇒ Object
── REST API ──────────────────────────────────────────────────────────────.
-
#api_list_skills(res) ⇒ Object
GET /api/skills — list all loaded skills with metadata.
-
#api_onboard_complete(req, res) ⇒ Object
POST /api/onboard/complete Called after key setup is done (soul_setup is optional/skipped).
-
#api_onboard_skip_soul(req, res) ⇒ Object
POST /api/onboard/skip-soul Writes a minimal SOUL.md so the soul_setup phase is not re-triggered on the next server start when the user chooses to skip the conversation.
-
#api_onboard_status(res) ⇒ Object
GET /api/onboard/status Phase “key_setup” → no API key configured yet Phase “soul_setup” → key configured, but ~/.clacky/agents/SOUL.md missing needs_onboard: false → fully set up.
- #api_rename_session(session_id, req, res) ⇒ Object
-
#api_restart(req, res) ⇒ Object
POST /api/restart Re-execs the current process so the newly installed gem version is loaded.
-
#api_run_cron_task(name, res) ⇒ Object
POST /api/cron-tasks/:name/run — execute immediately.
-
#api_save_channel(platform, req, res) ⇒ Object
POST /api/channels/:platform Body: { fields… } (platform-specific credential fields) Saves credentials and optionally (re)starts the adapter.
-
#api_save_config(req, res) ⇒ Object
POST /api/config — save updated model list Body: { models: [ { index, model, base_url, api_key, anthropic_format, type } ] } api_key may be masked (“sk-ab12****…5678”) — keep existing key in that case.
-
#api_session_messages(session_id, req, res) ⇒ Object
GET /api/sessions/:id/messages?limit=20&before=1709123456.789 Replays conversation history for a session via the agent’s replay_history method.
-
#api_session_skills(session_id, res) ⇒ Object
GET /api/sessions/:id/skills — list user-invocable skills for a session, filtered by the session’s agent profile.
-
#api_store_skills(res) ⇒ Object
GET /api/brand/skills Fetches the brand skills list from the cloud, enriched with local installed version.
- #api_switch_session_model(session_id, req, res) ⇒ Object
-
#api_test_channel(platform, req, res) ⇒ Object
POST /api/channels/:platform/test Body: { fields… } (credentials to test — NOT saved) Tests connectivity using the provided credentials without persisting.
-
#api_test_config(req, res) ⇒ Object
POST /api/config/test — test connection for a single model config Body: { model, base_url, api_key, anthropic_format }.
-
#api_toggle_skill(name, req, res) ⇒ Object
PATCH /api/skills/:name/toggle — enable or disable a skill Body: { enabled: true/false }.
-
#api_tool_browser(req, res) ⇒ Object
GET /api/channels Returns current config and running status for all supported platforms.
-
#api_update_cron_task(name, req, res) ⇒ Object
PATCH /api/cron-tasks/:name — update content and/or cron/enabled Body: { content?, cron?, enabled? }.
-
#api_upgrade_version(req, res) ⇒ Object
POST /api/version/upgrade Upgrades openclacky in a background thread, streaming output via WebSocket broadcast.
-
#api_upload_file(req, res) ⇒ Object
POST /api/upload Accepts a multipart/form-data file upload (field name: “file”).
-
#broadcast(session_id, event) ⇒ Object
Broadcast an event to all clients subscribed to a session.
-
#broadcast_all(event) ⇒ Object
Broadcast an event to every connected client (regardless of session subscription).
-
#broadcast_session_update(session_id) ⇒ Object
Broadcast a session_update event to all clients so they can patch their local session list without needing a full session_list refresh.
-
#build_session(name:, working_dir:, permission_mode: :confirm_all, profile: "general", source: :manual, model_override: nil) ⇒ Object
Create a session in the registry and wire up Agent + WebUIController.
-
#build_session_from_data(session_data, permission_mode: :confirm_all) ⇒ Object
Restore a persisted session from saved session_data (from SessionManager).
-
#create_default_session ⇒ Object
Auto-restore persisted sessions (or create a fresh default) when the server starts.
-
#default_working_dir ⇒ Object
── Helpers ───────────────────────────────────────────────────────────────.
- #deliver_confirmation(session_id, conf_id, result) ⇒ Object
-
#dispatch(req, res) ⇒ Object
── Router ────────────────────────────────────────────────────────────────.
-
#handle_user_message(session_id, content, files = []) ⇒ Object
── Session actions ───────────────────────────────────────────────────────.
-
#handle_websocket(req, res) ⇒ Object
Hijacks the TCP socket from WEBrick and upgrades it to WebSocket.
-
#initialize(host: "127.0.0.1", port: 7070, agent_config:, client_factory:, brand_test: false, sessions_dir: nil, socket: nil, master_pid: nil) ⇒ HttpServer
constructor
A new instance of HttpServer.
- #interrupt_session(session_id) ⇒ Object
- #json_response(res, status, data) ⇒ Object
-
#mask_api_key(key) ⇒ Object
Mask API key for display: show first 8 + last 4 chars, middle replaced with ****.
- #not_found(res) ⇒ Object
- #on_ws_close(conn) ⇒ Object
- #on_ws_message(conn, raw) ⇒ Object
- #on_ws_open(conn) ⇒ Object
- #parse_json_body(req) ⇒ Object
- #start ⇒ Object
-
#start_pending_task(session_id) ⇒ Object
Start the pending task for a session.
-
#subscribe(session_id, conn) ⇒ Object
── WebSocket subscription management ─────────────────────────────────────.
- #unsubscribe(conn) ⇒ Object
- #unsubscribe_all(session_id) ⇒ Object
-
#websocket_upgrade?(req) ⇒ Boolean
── WebSocket ─────────────────────────────────────────────────────────────.
Constructor Details
#initialize(host: "127.0.0.1", port: 7070, agent_config:, client_factory:, brand_test: false, sessions_dir: nil, socket: nil, master_pid: nil) ⇒ HttpServer
Returns a new instance of HttpServer.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/clacky/server/http_server.rb', line 147 def initialize(host: "127.0.0.1", port: 7070, agent_config:, client_factory:, brand_test: false, sessions_dir: nil, socket: nil, master_pid: nil) @host = host @port = port @agent_config = agent_config @client_factory = client_factory # callable: -> { Clacky::Client.new(...) } @brand_test = brand_test # when true, skip remote API calls for license activation @inherited_socket = socket # TCPServer socket passed from Master (nil = standalone mode) @master_pid = master_pid # Master PID so we can send USR1 on upgrade/restart # Capture the absolute path of the entry script and original ARGV at startup, # so api_restart can re-exec the correct binary even if cwd changes later. @restart_script = File.($0) @restart_argv = ARGV.dup @session_manager = Clacky::SessionManager.new(sessions_dir: sessions_dir) @registry = SessionRegistry.new( session_manager: @session_manager, session_restorer: method(:build_session_from_data) ) @ws_clients = {} # session_id => [WebSocketConnection, ...] @all_ws_conns = [] # every connected WS client, regardless of session subscription @ws_mutex = Mutex.new # Version cache: { latest: "x.y.z", checked_at: Time } @version_cache = nil @version_mutex = Mutex.new @scheduler = Scheduler.new( session_registry: @registry, session_builder: method(:build_session) ) @channel_manager = Clacky::Channel::ChannelManager.new( session_registry: @registry, session_builder: method(:build_session), run_agent_task: method(:run_agent_task), interrupt_session: method(:interrupt_session), channel_config: Clacky::ChannelConfig.load ) @browser_manager = Clacky::BrowserManager.instance @skill_loader = Clacky::SkillLoader.new(working_dir: nil, brand_config: Clacky::BrandConfig.load) end |
Instance Method Details
#_dispatch_rest(req, res) ⇒ Object
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/clacky/server/http_server.rb', line 354 def _dispatch_rest(req, res) path = req.path method = req.request_method case [method, path] when ["GET", "/api/sessions"] then api_list_sessions(req, res) when ["POST", "/api/sessions"] then api_create_session(req, res) when ["GET", "/api/cron-tasks"] then api_list_cron_tasks(res) when ["POST", "/api/cron-tasks"] then api_create_cron_task(req, res) when ["GET", "/api/skills"] then api_list_skills(res) when ["GET", "/api/config"] then api_get_config(res) when ["POST", "/api/config"] then api_save_config(req, res) when ["POST", "/api/config/test"] then api_test_config(req, res) when ["GET", "/api/providers"] then api_list_providers(res) when ["GET", "/api/onboard/status"] then api_onboard_status(res) when ["GET", "/api/browser/status"] then api_browser_status(res) when ["POST", "/api/browser/configure"] then api_browser_configure(req, res) when ["POST", "/api/browser/reload"] then api_browser_reload(res) when ["POST", "/api/browser/toggle"] then api_browser_toggle(res) when ["POST", "/api/onboard/complete"] then api_onboard_complete(req, res) when ["POST", "/api/onboard/skip-soul"] then api_onboard_skip_soul(req, res) when ["GET", "/api/store/skills"] then api_store_skills(res) when ["GET", "/api/brand/status"] then api_brand_status(res) when ["POST", "/api/brand/activate"] then api_brand_activate(req, res) when ["DELETE", "/api/brand/license"] then api_brand_deactivate(res) when ["GET", "/api/brand/skills"] then api_brand_skills(res) when ["GET", "/api/brand"] then api_brand_info(res) when ["GET", "/api/creator/skills"] then api_creator_skills(res) when ["GET", "/api/channels"] then api_list_channels(res) when ["POST", "/api/tool/browser"] then api_tool_browser(req, res) when ["POST", "/api/upload"] then api_upload_file(req, res) when ["GET", "/api/version"] then api_get_version(res) when ["POST", "/api/version/upgrade"] then api_upgrade_version(req, res) when ["POST", "/api/restart"] then api_restart(req, res) when ["PATCH", "/api/sessions/:id/model"] then api_switch_session_model(req, res) when ["PATCH", "/api/sessions/:id/working_dir"] then api_change_session_working_dir(req, res) else if method == "POST" && path.match?(%r{^/api/channels/[^/]+/test$}) platform = path.sub("/api/channels/", "").sub("/test", "") api_test_channel(platform, req, res) elsif method == "POST" && path.start_with?("/api/channels/") platform = path.sub("/api/channels/", "") api_save_channel(platform, req, res) elsif method == "DELETE" && path.start_with?("/api/channels/") platform = path.sub("/api/channels/", "") api_delete_channel(platform, res) elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/skills$}) session_id = path.sub("/api/sessions/", "").sub("/skills", "") api_session_skills(session_id, res) elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/messages$}) session_id = path.sub("/api/sessions/", "").sub("/messages", "") (session_id, req, res) elsif method == "PATCH" && path.match?(%r{^/api/sessions/[^/]+$}) session_id = path.sub("/api/sessions/", "") api_rename_session(session_id, req, res) elsif method == "PATCH" && path.match?(%r{^/api/sessions/[^/]+/model$}) session_id = path.sub("/api/sessions/", "").sub("/model", "") api_switch_session_model(session_id, req, res) elsif method == "PATCH" && path.match?(%r{^/api/sessions/[^/]+/working_dir$}) session_id = path.sub("/api/sessions/", "").sub("/working_dir", "") api_change_session_working_dir(session_id, req, res) elsif method == "DELETE" && path.start_with?("/api/sessions/") session_id = path.sub("/api/sessions/", "") api_delete_session(session_id, res) elsif method == "POST" && path.match?(%r{^/api/cron-tasks/[^/]+/run$}) name = URI.decode_www_form_component(path.sub("/api/cron-tasks/", "").sub("/run", "")) api_run_cron_task(name, res) elsif method == "PATCH" && path.match?(%r{^/api/cron-tasks/[^/]+$}) name = URI.decode_www_form_component(path.sub("/api/cron-tasks/", "")) api_update_cron_task(name, req, res) elsif method == "DELETE" && path.match?(%r{^/api/cron-tasks/[^/]+$}) name = URI.decode_www_form_component(path.sub("/api/cron-tasks/", "")) api_delete_cron_task(name, res) elsif method == "PATCH" && path.match?(%r{^/api/skills/[^/]+/toggle$}) name = URI.decode_www_form_component(path.sub("/api/skills/", "").sub("/toggle", "")) api_toggle_skill(name, req, res) elsif method == "POST" && path.match?(%r{^/api/brand/skills/[^/]+/install$}) slug = URI.decode_www_form_component(path.sub("/api/brand/skills/", "").sub("/install", "")) api_brand_skill_install(slug, req, res) elsif method == "POST" && path.match?(%r{^/api/my-skills/[^/]+/publish$}) name = URI.decode_www_form_component(path.sub("/api/my-skills/", "").sub("/publish", "")) api_publish_my_skill(name, req, res) else not_found(res) end end end |
#api_brand_activate(req, res) ⇒ Object
POST /api/brand/activate Body: { license_key: “XXXX-XXXX-XXXX-XXXX-XXXX” } Activates the license and persists the result to brand.yml.
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 |
# File 'lib/clacky/server/http_server.rb', line 665 def api_brand_activate(req, res) body = parse_json_body(req) key = body["license_key"].to_s.strip if key.empty? json_response(res, 422, { ok: false, error: "license_key is required" }) return end brand = Clacky::BrandConfig.load result = @brand_test ? brand.activate_mock!(key) : brand.activate!(key) if result[:success] # Refresh skill_loader with the now-activated brand config so brand # skills are loadable from this point forward (e.g. after sync). @skill_loader = Clacky::SkillLoader.new(working_dir: nil, brand_config: brand) json_response(res, 200, { ok: true, product_name: result[:product_name] || brand.product_name, user_id: result[:user_id] || brand.license_user_id, user_licensed: brand.user_licensed? }) else json_response(res, 422, { ok: false, error: result[:message] }) end end |
#api_brand_info(res) ⇒ Object
GET /api/brand Returns brand metadata consumed by the WebUI on boot to dynamically replace branding strings.
817 818 819 820 |
# File 'lib/clacky/server/http_server.rb', line 817 def api_brand_info(res) brand = Clacky::BrandConfig.load json_response(res, 200, brand.to_h) end |
#api_brand_skill_install(slug, req, res) ⇒ Object
POST /api/brand/skills/:name/install Downloads and installs (or updates) the given brand skill. Body may optionally contain { skill_info: … } from the frontend cache; otherwise we re-fetch to get the download_url.
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 |
# File 'lib/clacky/server/http_server.rb', line 772 def api_brand_skill_install(slug, req, res) brand = Clacky::BrandConfig.load unless brand.activated? json_response(res, 403, { ok: false, error: "License not activated" }) return end # Re-fetch the skills list to get the authoritative download_url if @brand_test all_skills = mock_brand_skills(brand)[:skills] else fetch_result = brand.fetch_brand_skills! unless fetch_result[:success] json_response(res, 422, { ok: false, error: fetch_result[:error] }) return end all_skills = fetch_result[:skills] end skill_info = all_skills.find { |s| s["name"] == slug } unless skill_info json_response(res, 404, { ok: false, error: "Skill '#{slug}' not found in license" }) return end # In brand-test mode use the mock installer which writes a real .enc file # so the full decrypt → load → invoke code-path is exercised end-to-end. result = @brand_test ? brand.install_mock_brand_skill!(skill_info) : brand.install_brand_skill!(skill_info) if result[:success] # Reload skills so the Agent can pick up the new skill immediately. # Re-create the loader with the current brand_config so brand skills are decryptable. @skill_loader = Clacky::SkillLoader.new(working_dir: nil, brand_config: brand) json_response(res, 200, { ok: true, name: result[:name], version: result[:version] }) else json_response(res, 422, { ok: false, error: result[:error] }) end rescue StandardError, ScriptError => e json_response(res, 500, { ok: false, error: e. }) end |
#api_brand_skills(res) ⇒ Object
POST /api/store/skills/:slug/install
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 |
# File 'lib/clacky/server/http_server.rb', line 729 def api_brand_skills(res) brand = Clacky::BrandConfig.load unless brand.activated? json_response(res, 403, { ok: false, error: "License not activated" }) return end if @brand_test # Return mock skills in brand-test mode instead of calling the remote API result = mock_brand_skills(brand) else result = brand.fetch_brand_skills! end if result[:success] json_response(res, 200, { ok: true, skills: result[:skills], expires_at: result[:expires_at] }) else # Remote API failed — fall back to locally installed skills so the user # can still see and use what they already have. Surface a soft warning. local_skills = brand.installed_brand_skills.map do |name, | { "name" => ["name"] || name, "name_zh" => ["name_zh"].to_s, # Use locally cached description so it renders correctly offline "description" => ["description"].to_s, "description_zh" => ["description_zh"].to_s, "installed_version" => ["version"], "needs_update" => false } end json_response(res, 200, { ok: true, skills: local_skills, warning: "Could not reach the license server. Showing locally installed skills only." }) end end |
#api_brand_status(res) ⇒ Object
GET /api/brand/status Returns whether brand activation is needed. Mirrors the onboard/status pattern so the frontend can gate on it.
Response:
{ branded: false } → no brand, nothing to do
{ branded: true, needs_activation: true,
product_name: "JohnAI" } → license key required
{ branded: true, needs_activation: false,
product_name: "JohnAI", warning: "..." } → activated, possible warning
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 |
# File 'lib/clacky/server/http_server.rb', line 602 def api_brand_status(res) brand = Clacky::BrandConfig.load unless brand.branded? json_response(res, 200, { branded: false }) return end unless brand.activated? json_response(res, 200, { branded: true, needs_activation: true, product_name: brand.product_name, test_mode: @brand_test }) return end # Send heartbeat if interval has elapsed (once per day) if brand.heartbeat_due? Clacky::Logger.info("[Brand] api_brand_status: heartbeat due, sending...") result = brand.heartbeat! if result[:success] Clacky::Logger.info("[Brand] api_brand_status: heartbeat OK") else Clacky::Logger.warn("[Brand] api_brand_status: heartbeat failed — #{result[:message]}") end # Reload after heartbeat to pick up updated expires_at / last_heartbeat brand = Clacky::BrandConfig.load else Clacky::Logger.debug("[Brand] api_brand_status: heartbeat not due yet") end Clacky::Logger.debug("[Brand] api_brand_status: expired=#{brand.expired?} grace_exceeded=#{brand.grace_period_exceeded?} expires_at=#{brand.license_expires_at&.iso8601 || "nil"}") warning = nil if brand.expired? warning = "Your #{brand.product_name} license has expired. Please renew to continue." elsif brand.grace_period_exceeded? warning = "License server unreachable for more than 3 days. Please check your connection." elsif brand.license_expires_at && !brand.expired? days_remaining = ((brand.license_expires_at - Time.now.utc) / 86_400).ceil if days_remaining <= 7 warning = "Your #{brand.product_name} license expires in #{days_remaining} day#{"s" if days_remaining != 1}. Please renew soon." end end Clacky::Logger.debug("[Brand] api_brand_status: warning=#{warning.inspect}") json_response(res, 200, { branded: true, needs_activation: false, product_name: brand.product_name, warning: warning, test_mode: @brand_test, user_licensed: brand.user_licensed?, license_user_id: brand.license_user_id }) end |
#api_browser_configure(req, res) ⇒ Object
POST /api/browser/configure Called by browser-setup skill to write browser.yml and hot-reload the daemon. Body: { chrome_version: “146” }
535 536 537 538 539 540 541 542 543 544 |
# File 'lib/clacky/server/http_server.rb', line 535 def api_browser_configure(req, res) body = JSON.parse(req.body.to_s) rescue {} chrome_version = body["chrome_version"].to_s.strip return json_response(res, 422, { ok: false, error: "chrome_version is required" }) if chrome_version.empty? @browser_manager.configure(chrome_version: chrome_version) json_response(res, 200, { ok: true }) rescue StandardError => e json_response(res, 500, { ok: false, error: e. }) end |
#api_browser_reload(res) ⇒ Object
POST /api/browser/reload Called by browser-setup skill after writing browser.yml. Hot-reloads the MCP daemon with the new configuration.
549 550 551 552 553 554 |
# File 'lib/clacky/server/http_server.rb', line 549 def api_browser_reload(res) @browser_manager.reload json_response(res, 200, { ok: true }) rescue StandardError => e json_response(res, 500, { ok: false, error: e. }) end |
#api_browser_status(res) ⇒ Object
GET /api/browser/status Returns real daemon liveness from BrowserManager (not just yml read).
528 529 530 |
# File 'lib/clacky/server/http_server.rb', line 528 def api_browser_status(res) json_response(res, 200, @browser_manager.status) end |
#api_browser_toggle(res) ⇒ Object
POST /api/browser/toggle
557 558 559 560 561 562 |
# File 'lib/clacky/server/http_server.rb', line 557 def api_browser_toggle(res) enabled = @browser_manager.toggle json_response(res, 200, { ok: true, enabled: enabled }) rescue StandardError => e json_response(res, 500, { ok: false, error: e. }) end |
#api_change_session_working_dir(session_id, req, res) ⇒ Object
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 |
# File 'lib/clacky/server/http_server.rb', line 1894 def api_change_session_working_dir(session_id, req, res) body = parse_json_body(req) new_dir = body["working_dir"].to_s.strip return json_response(res, 400, { error: "working_dir is required" }) if new_dir.empty? return json_response(res, 404, { error: "Session not found" }) unless @registry.ensure(session_id) # Expand ~ to home directory = File.(new_dir) # Validate directory exists unless Dir.exist?() return json_response(res, 400, { error: "Directory does not exist: #{}" }) end agent = nil @registry.with_session(session_id) { |s| agent = s[:agent] } # Change the agent's working directory agent.change_working_dir() # Persist the change @session_manager.save(agent.to_session_data) # Broadcast update to all clients broadcast_session_update(session_id) json_response(res, 200, { ok: true, working_dir: }) rescue => e json_response(res, 500, { error: e. }) end |
#api_create_cron_task(req, res) ⇒ Object
POST /api/cron-tasks — create task file + schedule in one step Body: { name, content, cron, enabled? }
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 |
# File 'lib/clacky/server/http_server.rb', line 1331 def api_create_cron_task(req, res) body = parse_json_body(req) name = body["name"].to_s.strip content = body["content"].to_s cron = body["cron"].to_s.strip enabled = body.key?("enabled") ? body["enabled"] : true return json_response(res, 422, { error: "name is required" }) if name.empty? return json_response(res, 422, { error: "content is required" }) if content.empty? return json_response(res, 422, { error: "cron is required" }) if cron.empty? fields = cron.strip.split(/\s+/) unless fields.size == 5 return json_response(res, 422, { error: "cron must have 5 fields (min hour dom month dow)" }) end @scheduler.create_cron_task(name: name, content: content, cron: cron, enabled: enabled) json_response(res, 201, { ok: true, name: name }) end |
#api_create_session(req, res) ⇒ Object
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
# File 'lib/clacky/server/http_server.rb', line 461 def api_create_session(req, res) body = parse_json_body(req) name = body["name"] return json_response(res, 400, { error: "name is required" }) if name.nil? || name.strip.empty? # Optional agent_profile; defaults to "general" if omitted or invalid profile = body["agent_profile"].to_s.strip profile = "general" if profile.empty? # Optional source; defaults to :manual. Accept "system" for skill-launched sessions # (e.g. /onboard, /browser-setup, /channel-setup). raw_source = body["source"].to_s.strip source = %w[manual cron channel setup].include?(raw_source) ? raw_source.to_sym : :manual raw_dir = body["working_dir"].to_s.strip working_dir = raw_dir.empty? ? default_working_dir : File.(raw_dir) # Optional model override model_override = body["model"].to_s.strip model_override = nil if model_override.empty? # Create working directory if it doesn't exist # Allow multiple sessions in the same directory FileUtils.mkdir_p(working_dir) session_id = build_session(name: name, working_dir: working_dir, profile: profile, source: source, model_override: model_override) broadcast_session_update(session_id) json_response(res, 201, { session: @registry.session_summary(session_id) }) end |
#api_delete_channel(platform, res) ⇒ Object
DELETE /api/channels/:platform Disables the platform (keeps credentials, sets enabled: false).
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 |
# File 'lib/clacky/server/http_server.rb', line 1194 def api_delete_channel(platform, res) platform = platform.to_sym config = Clacky::ChannelConfig.load config.disable_platform(platform) config.save @channel_manager.reload_platform(platform, config) json_response(res, 200, { ok: true }) rescue StandardError => e json_response(res, 422, { ok: false, error: e. }) end |
#api_delete_cron_task(name, res) ⇒ Object
DELETE /api/cron-tasks/:name — remove task file + schedule
1370 1371 1372 1373 1374 1375 1376 |
# File 'lib/clacky/server/http_server.rb', line 1370 def api_delete_cron_task(name, res) if @scheduler.delete_cron_task(name) json_response(res, 200, { ok: true }) else json_response(res, 404, { error: "Cron task not found: #{name}" }) end end |
#api_delete_session(session_id, res) ⇒ Object
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 |
# File 'lib/clacky/server/http_server.rb', line 1926 def api_delete_session(session_id, res) if @registry.delete(session_id) # Also remove the persisted session file from disk @session_manager.delete(session_id) # Notify connected clients the session is gone broadcast(session_id, { type: "session_deleted", session_id: session_id }) unsubscribe_all(session_id) json_response(res, 200, { ok: true }) else json_response(res, 404, { error: "Session not found" }) end end |
#api_get_config(res) ⇒ Object
GET /api/config — return current model configurations
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 |
# File 'lib/clacky/server/http_server.rb', line 1681 def api_get_config(res) models = @agent_config.models.map.with_index do |m, i| { index: i, model: m["model"], base_url: m["base_url"], api_key_masked: mask_api_key(m["api_key"]), anthropic_format: m["anthropic_format"] || false, type: m["type"] } end json_response(res, 200, { models: models, current_index: @agent_config.current_model_index }) end |
#api_get_version(res) ⇒ Object
GET /api/version Returns current version and latest version from RubyGems (cached for 1 hour).
826 827 828 829 830 831 832 833 834 |
# File 'lib/clacky/server/http_server.rb', line 826 def api_get_version(res) current = Clacky::VERSION latest = fetch_latest_version_cached json_response(res, 200, { current: current, latest: latest, needs_update: latest ? version_older?(current, latest) : false }) end |
#api_list_channels(res) ⇒ Object
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 |
# File 'lib/clacky/server/http_server.rb', line 1115 def api_list_channels(res) config = Clacky::ChannelConfig.load running = @channel_manager.running_platforms platforms = Clacky::Channel::Adapters.all.map do |klass| platform = klass.platform_id raw = config.instance_variable_get(:@channels)[platform.to_s] || {} { platform: platform, enabled: !!raw["enabled"], running: running.include?(platform), has_config: !config.platform_config(platform).nil? }.merge(platform_safe_fields(platform, config)) end json_response(res, 200, { channels: platforms }) end |
#api_list_cron_tasks(res) ⇒ Object
GET /api/cron-tasks
1325 1326 1327 |
# File 'lib/clacky/server/http_server.rb', line 1325 def api_list_cron_tasks(res) json_response(res, 200, { cron_tasks: @scheduler.list_cron_tasks }) end |
#api_list_providers(res) ⇒ Object
GET /api/providers — return built-in provider presets for quick setup
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 |
# File 'lib/clacky/server/http_server.rb', line 1775 def api_list_providers(res) providers = Clacky::Providers::PRESETS.map do |id, preset| { id: id, name: preset["name"], base_url: preset["base_url"], default_model: preset["default_model"], models: preset["models"] || [], website_url: preset["website_url"] } end json_response(res, 200, { providers: providers }) end |
#api_list_sessions(req, res) ⇒ Object
── REST API ──────────────────────────────────────────────────────────────
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
# File 'lib/clacky/server/http_server.rb', line 444 def api_list_sessions(req, res) query = URI.decode_www_form(req.query_string.to_s).to_h limit = [query["limit"].to_i.then { |n| n > 0 ? n : 20 }, 50].min before = query["before"].to_s.strip.then { |v| v.empty? ? nil : v } q = query["q"].to_s.strip.then { |v| v.empty? ? nil : v } date = query["date"].to_s.strip.then { |v| v.empty? ? nil : v } type = query["type"].to_s.strip.then { |v| v.empty? ? nil : v } # Backward-compat: ?source=<x> and ?profile=coding → type type ||= query["profile"].to_s.strip.then { |v| v.empty? ? nil : v } type ||= query["source"].to_s.strip.then { |v| v.empty? ? nil : v } # Fetch one extra to detect has_more without a separate count query sessions = @registry.list(limit: limit + 1, before: before, q: q, date: date, type: type) has_more = sessions.size > limit sessions = sessions.first(limit) json_response(res, 200, { sessions: sessions, has_more: has_more }) end |
#api_list_skills(res) ⇒ Object
GET /api/skills — list all loaded skills with metadata
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 |
# File 'lib/clacky/server/http_server.rb', line 1400 def api_list_skills(res) @skill_loader.load_all # refresh from disk on each request = Clacky::BrandConfig. shadowed = @skill_loader.shadowed_by_local skills = @skill_loader.all_skills.reject(&:brand_skill).map do |skill| source = @skill_loader.loaded_from[skill.identifier] = [skill.identifier] || {} # Compute local modification time of SKILL.md for "has local changes" indicator skill_md_path = File.join(skill.directory.to_s, "SKILL.md") local_modified_at = File.exist?(skill_md_path) ? File.mtime(skill_md_path).utc.iso8601 : nil entry = { name: skill.identifier, name_zh: skill.name_zh, description: skill.context_description, description_zh: skill.description_zh, source: source, enabled: !skill.disabled?, invalid: skill.invalid?, warnings: skill.warnings, platform_version: ["platform_version"], uploaded_at: ["uploaded_at"], local_modified_at: local_modified_at, # true when this local skill is shadowing a same-named brand skill shadowing_brand: shadowed.key?(skill.identifier) } entry[:invalid_reason] = skill.invalid_reason if skill.invalid? entry end json_response(res, 200, { skills: skills }) end |
#api_onboard_complete(req, res) ⇒ Object
POST /api/onboard/complete Called after key setup is done (soul_setup is optional/skipped). Creates the default session if none exists yet, returns it.
567 568 569 570 571 |
# File 'lib/clacky/server/http_server.rb', line 567 def api_onboard_complete(req, res) create_default_session if @registry.list(limit: 1).empty? first_session = @registry.list(limit: 1).first json_response(res, 200, { ok: true, session: first_session }) end |
#api_onboard_skip_soul(req, res) ⇒ Object
POST /api/onboard/skip-soul Writes a minimal SOUL.md so the soul_setup phase is not re-triggered on the next server start when the user chooses to skip the conversation.
576 577 578 579 580 581 582 583 584 585 586 587 588 |
# File 'lib/clacky/server/http_server.rb', line 576 def api_onboard_skip_soul(req, res) body = parse_json_body(req) lang = body["lang"].to_s.strip soul_content = lang == "zh" ? DEFAULT_SOUL_MD_ZH : DEFAULT_SOUL_MD agents_dir = File.("~/.clacky/agents") FileUtils.mkdir_p(agents_dir) soul_path = File.join(agents_dir, "SOUL.md") unless File.exist?(soul_path) File.write(soul_path, soul_content) end json_response(res, 200, { ok: true }) end |
#api_onboard_status(res) ⇒ Object
GET /api/onboard/status Phase “key_setup” → no API key configured yet Phase “soul_setup” → key configured, but ~/.clacky/agents/SOUL.md missing needs_onboard: false → fully set up
518 519 520 521 522 523 524 |
# File 'lib/clacky/server/http_server.rb', line 518 def api_onboard_status(res) if !@agent_config.models_configured? json_response(res, 200, { needs_onboard: true, phase: "key_setup" }) else json_response(res, 200, { needs_onboard: false }) end end |
#api_rename_session(session_id, req, res) ⇒ Object
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 |
# File 'lib/clacky/server/http_server.rb', line 1819 def api_rename_session(session_id, req, res) body = parse_json_body(req) new_name = body["name"]&.to_s&.strip pinned = body["pinned"] return json_response(res, 404, { error: "Session not found" }) unless @registry.ensure(session_id) agent = nil @registry.with_session(session_id) { |s| agent = s[:agent] } # Update name if provided if new_name && !new_name.empty? agent.rename(new_name) end # Save session data session_data = agent.to_session_data # Update pinned field if provided (not stored in agent, only in session file) if !pinned.nil? session_data[:pinned] = pinned end @session_manager.save(session_data) # Broadcast update event update_data = { type: "session_updated", session_id: session_id } update_data[:name] = new_name if new_name && !new_name.empty? update_data[:pinned] = pinned unless pinned.nil? broadcast(session_id, update_data) response_data = { ok: true } response_data[:name] = new_name if new_name && !new_name.empty? response_data[:pinned] = pinned unless pinned.nil? json_response(res, 200, response_data) rescue => e json_response(res, 500, { error: e. }) end |
#api_restart(req, res) ⇒ Object
POST /api/restart Re-execs the current process so the newly installed gem version is loaded. Uses the absolute script path captured at startup to avoid relative-path issues. Responds 200 first, then waits briefly for WEBrick to flush the response before exec.
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 |
# File 'lib/clacky/server/http_server.rb', line 984 def api_restart(req, res) json_response(res, 200, { ok: true, message: "Restarting…" }) Thread.new do sleep 0.5 # Let WEBrick flush the HTTP response if @master_pid # Worker mode: tell master to hot-restart, then exit cleanly. Clacky::Logger.info("[Restart] Sending USR1 to master (PID=#{@master_pid})") begin Process.kill("USR1", @master_pid) rescue Errno::ESRCH Clacky::Logger.warn("[Restart] Master PID=#{@master_pid} not found, falling back to exec.") standalone_exec_restart end exit(0) else # Standalone mode (no master): fall back to the original exec approach. standalone_exec_restart end end end |
#api_run_cron_task(name, res) ⇒ Object
POST /api/cron-tasks/:name/run — execute immediately
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 |
# File 'lib/clacky/server/http_server.rb', line 1379 def api_run_cron_task(name, res) unless @scheduler.list_tasks.include?(name) return json_response(res, 404, { error: "Cron task not found: #{name}" }) end prompt = @scheduler.read_task(name) session_name = "▶ #{name} #{Time.now.strftime("%H:%M")}" working_dir = File.("~/clacky_workspace") FileUtils.mkdir_p(working_dir) session_id = build_session(name: session_name, working_dir: working_dir, permission_mode: :auto_approve) @registry.update(session_id, pending_task: prompt, pending_working_dir: working_dir) json_response(res, 202, { ok: true, session: @registry.session_summary(session_id) }) rescue => e json_response(res, 422, { error: e. }) end |
#api_save_channel(platform, req, res) ⇒ Object
POST /api/channels/:platform Body: { fields… } (platform-specific credential fields) Saves credentials and optionally (re)starts the adapter.
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 |
# File 'lib/clacky/server/http_server.rb', line 1157 def api_save_channel(platform, req, res) platform = platform.to_sym body = parse_json_body(req) config = Clacky::ChannelConfig.load fields = body.transform_keys(&:to_sym).reject { |k, _| k == :platform } fields = fields.transform_values { |v| v.is_a?(String) ? v.strip : v } # Record when the token was last updated so clients can detect re-login fields[:token_updated_at] = Time.now.to_i if platform == :weixin && fields.key?(:token) # Validate credentials against live API before persisting. # Merge with existing config so partial updates (e.g. allowed_users only) still validate correctly. klass = Clacky::Channel::Adapters.find(platform) if klass && klass.respond_to?(:test_connection) existing = config.platform_config(platform) || {} merged = existing.merge(fields) result = klass.test_connection(merged) unless result[:ok] json_response(res, 422, { ok: false, error: result[:error] || "Credential validation failed" }) return end end config.set_platform(platform, **fields) config.save # Hot-reload: stop existing adapter for this platform (if running) and restart @channel_manager.reload_platform(platform, config) json_response(res, 200, { ok: true }) rescue StandardError => e json_response(res, 422, { ok: false, error: e. }) end |
#api_save_config(req, res) ⇒ Object
POST /api/config — save updated model list Body: { models: [ { index, model, base_url, api_key, anthropic_format, type } ] } api_key may be masked (“sk-ab12****…5678”) — keep existing key in that case
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 |
# File 'lib/clacky/server/http_server.rb', line 1698 def api_save_config(req, res) body = parse_json_body(req) return json_response(res, 400, { error: "Invalid JSON" }) unless body incoming = body["models"] return json_response(res, 400, { error: "models array required" }) unless incoming.is_a?(Array) incoming.each_with_index do |m, i| existing = @agent_config.models[i] # Resolve api_key: if masked placeholder, keep the stored key api_key = if m["api_key"].to_s.include?("****") existing&.dig("api_key") else m["api_key"] end if existing existing["model"] = m["model"] if m.key?("model") existing["base_url"] = m["base_url"] if m.key?("base_url") existing["api_key"] = api_key if api_key existing["anthropic_format"] = m["anthropic_format"] if m.key?("anthropic_format") existing["type"] = m["type"] if m.key?("type") else @agent_config.add_model( model: m["model"].to_s, api_key: api_key.to_s, base_url: m["base_url"].to_s, anthropic_format: m["anthropic_format"] || false, type: m["type"] ) end end # Remove models that are no longer present (trim to incoming length) while @agent_config.models.length > incoming.length @agent_config.models.pop end @agent_config.save json_response(res, 200, { ok: true }) rescue => e json_response(res, 422, { error: e. }) end |
#api_session_messages(session_id, req, res) ⇒ Object
GET /api/sessions/:id/messages?limit=20&before=1709123456.789 Replays conversation history for a session via the agent’s replay_history method. Returns a list of UI events (same format as WS events) for the frontend to render.
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 |
# File 'lib/clacky/server/http_server.rb', line 1792 def (session_id, req, res) unless @registry.ensure(session_id) Clacky::Logger.warn("[messages] registry.ensure failed", session_id: session_id) return json_response(res, 404, { error: "Session not found" }) end # Parse query params query = URI.decode_www_form(req.query_string.to_s).to_h limit = [query["limit"].to_i.then { |n| n > 0 ? n : 20 }, 100].min before = query["before"]&.to_f agent = nil @registry.with_session(session_id) { |s| agent = s[:agent] } unless agent Clacky::Logger.warn("[messages] agent is nil", session_id: session_id) return json_response(res, 200, { events: [], has_more: false }) end # Collect events emitted by replay_history via a lightweight collector UI collected = [] collector = HistoryCollector.new(session_id, collected) result = agent.replay_history(collector, limit: limit, before: before) json_response(res, 200, { events: collected, has_more: result[:has_more] }) end |
#api_session_skills(session_id, res) ⇒ Object
GET /api/sessions/:id/skills — list user-invocable skills for a session, filtered by the session’s agent profile. Used by the frontend slash-command autocomplete so only skills valid for the current profile are suggested.
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 |
# File 'lib/clacky/server/http_server.rb', line 1437 def api_session_skills(session_id, res) unless @registry.ensure(session_id) json_response(res, 404, { error: "Session not found" }) return end session = @registry.get(session_id) unless session json_response(res, 404, { error: "Session not found" }) return end agent = session[:agent] unless agent json_response(res, 404, { error: "Agent not found" }) return end agent.skill_loader.load_all profile = agent.agent_profile skills = agent.skill_loader.user_invocable_skills skills = skills.select { |s| s.allowed_for_agent?(profile.name) } if profile loader = agent.skill_loader loaded_from = loader.loaded_from skill_data = skills.map do |skill| source_type = loaded_from[skill.identifier] { name: skill.identifier, name_zh: skill.name_zh, description: skill.description || skill.context_description, description_zh: skill.description_zh, encrypted: skill.encrypted?, source_type: source_type } end json_response(res, 200, { skills: skill_data }) end |
#api_store_skills(res) ⇒ Object
GET /api/brand/skills Fetches the brand skills list from the cloud, enriched with local installed version. Returns 200 with skill list, or 403 when license is not activated. If the remote API call fails, falls back to locally installed skills with a warning. GET /api/store/skills Returns the public skill store catalog from the OpenClacky Cloud API. Requires an activated license — uses HMAC auth with scope: “store” to fetch platform-wide published public skills (not filtered by the user’s own skills). Falls back to the hardcoded catalog when license is not activated or API is unavailable.
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 |
# File 'lib/clacky/server/http_server.rb', line 712 def api_store_skills(res) brand = Clacky::BrandConfig.load result = brand.fetch_store_skills! if result[:success] json_response(res, 200, { ok: true, skills: result[:skills] }) else # License not activated or remote API unavailable — return empty list json_response(res, 200, { ok: true, skills: [], warning: result[:error] || "Could not reach the skill store." }) end end |
#api_switch_session_model(session_id, req, res) ⇒ Object
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 |
# File 'lib/clacky/server/http_server.rb', line 1858 def api_switch_session_model(session_id, req, res) body = parse_json_body(req) new_model_name = body["model"].to_s.strip return json_response(res, 400, { error: "model is required" }) if new_model_name.empty? return json_response(res, 404, { error: "Session not found" }) unless @registry.ensure(session_id) agent = nil @registry.with_session(session_id) { |s| agent = s[:agent] } # Find the model configuration index by model name (use global config) model_index = @agent_config.models.find_index { |m| m["model"] == new_model_name } if model_index.nil? return json_response(res, 400, { error: "Model '#{new_model_name}' not found in configuration" }) end # Switch to the model by index (unified interface with CLI) # This handles: config.switch_model + client rebuild + message_compressor rebuild success = agent.switch_model(model_index) unless success return json_response(res, 500, { error: "Failed to switch model" }) end # Persist the change (saves to session file, NOT global config.yml) @session_manager.save(agent.to_session_data) # Broadcast update to all clients broadcast_session_update(session_id) json_response(res, 200, { ok: true, model: new_model_name }) rescue => e json_response(res, 500, { error: e. }) end |
#api_test_channel(platform, req, res) ⇒ Object
POST /api/channels/:platform/test Body: { fields… } (credentials to test — NOT saved) Tests connectivity using the provided credentials without persisting.
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 |
# File 'lib/clacky/server/http_server.rb', line 1210 def api_test_channel(platform, req, res) platform = platform.to_sym body = parse_json_body(req) fields = body.transform_keys(&:to_sym).reject { |k, _| k == :platform } klass = Clacky::Channel::Adapters.find(platform) unless klass json_response(res, 404, { ok: false, error: "Unknown platform: #{platform}" }) return end result = klass.test_connection(fields) json_response(res, 200, result) rescue StandardError => e json_response(res, 200, { ok: false, error: e. }) end |
#api_test_config(req, res) ⇒ Object
POST /api/config/test — test connection for a single model config Body: { model, base_url, api_key, anthropic_format }
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 |
# File 'lib/clacky/server/http_server.rb', line 1744 def api_test_config(req, res) body = parse_json_body(req) return json_response(res, 400, { error: "Invalid JSON" }) unless body api_key = body["api_key"].to_s # If masked, use the stored key from the matching model (by index or current) if api_key.include?("****") idx = body["index"]&.to_i || @agent_config.current_model_index api_key = @agent_config.models.dig(idx, "api_key").to_s end begin model = body["model"].to_s test_client = Clacky::Client.new( api_key, base_url: body["base_url"].to_s, model: model, anthropic_format: body["anthropic_format"] || false ) result = test_client.test_connection(model: model) if result[:success] json_response(res, 200, { ok: true, message: "Connected successfully" }) else json_response(res, 200, { ok: false, message: result[:error].to_s }) end rescue => e json_response(res, 200, { ok: false, message: e. }) end end |
#api_toggle_skill(name, req, res) ⇒ Object
PATCH /api/skills/:name/toggle — enable or disable a skill Body: { enabled: true/false }
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 |
# File 'lib/clacky/server/http_server.rb', line 1480 def api_toggle_skill(name, req, res) body = parse_json_body(req) enabled = body["enabled"] if enabled.nil? json_response(res, 422, { error: "enabled field required" }) return end skill = @skill_loader.toggle_skill(name, enabled: enabled) json_response(res, 200, { ok: true, name: skill.identifier, enabled: !skill.disabled? }) rescue Clacky::AgentError => e json_response(res, 422, { error: e. }) end |
#api_tool_browser(req, res) ⇒ Object
GET /api/channels Returns current config and running status for all supported platforms. POST /api/tool/browser Executes a browser tool action via the shared BrowserManager daemon. Used by skill scripts (e.g. feishu_setup.rb) to reuse the server’s existing Chrome connection without spawning a second MCP daemon.
Request body: JSON with same params as the browser tool
{ "action": "snapshot", "interactive": true, ... }
Response: JSON result from the browser tool
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 |
# File 'lib/clacky/server/http_server.rb', line 1102 def api_tool_browser(req, res) params = parse_json_body(req) action = params["action"] return json_response(res, 400, { error: "action is required" }) if action.nil? || action.empty? tool = Clacky::Tools::Browser.new result = tool.execute(**params.transform_keys(&:to_sym)) json_response(res, 200, result) rescue StandardError => e json_response(res, 500, { error: e. }) end |
#api_update_cron_task(name, req, res) ⇒ Object
PATCH /api/cron-tasks/:name — update content and/or cron/enabled Body: { content?, cron?, enabled? }
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 |
# File 'lib/clacky/server/http_server.rb', line 1353 def api_update_cron_task(name, req, res) body = parse_json_body(req) content = body["content"] cron = body["cron"]&.to_s&.strip enabled = body["enabled"] if cron && cron.split(/\s+/).size != 5 return json_response(res, 422, { error: "cron must have 5 fields (min hour dom month dow)" }) end @scheduler.update_cron_task(name, content: content, cron: cron, enabled: enabled) json_response(res, 200, { ok: true, name: name }) rescue => e json_response(res, 404, { error: e. }) end |
#api_upgrade_version(req, res) ⇒ Object
POST /api/version/upgrade Upgrades openclacky in a background thread, streaming output via WebSocket broadcast. If the user’s gem source is the official RubyGems, use ‘gem update`. Otherwise (e.g. Aliyun mirror) download the .gem from OSS CDN to bypass mirror lag.
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 |
# File 'lib/clacky/server/http_server.rb', line 840 def api_upgrade_version(req, res) json_response(res, 202, { ok: true, message: "Upgrade started" }) Thread.new do begin if official_gem_source? upgrade_via_gem_update else upgrade_via_oss_cdn end rescue StandardError => e Clacky::Logger.error("[Upgrade] Exception: #{e.class}: #{e.}\n#{e.backtrace.first(5).join("\n")}") broadcast_all(type: "upgrade_log", line: "\n✗ Error during upgrade: #{e.}\n") broadcast_all(type: "upgrade_complete", success: false) end end end |
#api_upload_file(req, res) ⇒ Object
POST /api/upload Accepts a multipart/form-data file upload (field name: “file”). Runs the file through FileProcessor: saves original + generates structured preview (Markdown) for Office/ZIP files so the agent can read them directly.
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 |
# File 'lib/clacky/server/http_server.rb', line 1137 def api_upload_file(req, res) upload = parse_multipart_upload(req, "file") unless upload json_response(res, 400, { ok: false, error: "No file field found in multipart body" }) return end saved = Clacky::Utils::FileProcessor.save( body: upload[:data], filename: upload[:filename].to_s ) json_response(res, 200, { ok: true, name: saved[:name], path: saved[:path] }) rescue => e json_response(res, 500, { ok: false, error: e. }) end |
#broadcast(session_id, event) ⇒ Object
Broadcast an event to all clients subscribed to a session. Dead connections (broken pipe / closed socket) are removed automatically.
2212 2213 2214 2215 2216 2217 2218 2219 2220 |
# File 'lib/clacky/server/http_server.rb', line 2212 def broadcast(session_id, event) clients = @ws_mutex.synchronize { (@ws_clients[session_id] || []).dup } dead = clients.reject { |conn| conn.send_json(event) } return if dead.empty? @ws_mutex.synchronize do (@ws_clients[session_id] || []).reject! { |conn| dead.include?(conn) } end end |
#broadcast_all(event) ⇒ Object
Broadcast an event to every connected client (regardless of session subscription). Dead connections are removed automatically.
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 |
# File 'lib/clacky/server/http_server.rb', line 2224 def broadcast_all(event) clients = @ws_mutex.synchronize { @all_ws_conns.dup } dead = clients.reject { |conn| conn.send_json(event) } return if dead.empty? @ws_mutex.synchronize do @all_ws_conns.reject! { |conn| dead.include?(conn) } @ws_clients.each_value { |list| list.reject! { |conn| dead.include?(conn) } } end end |
#broadcast_session_update(session_id) ⇒ Object
Broadcast a session_update event to all clients so they can patch their local session list without needing a full session_list refresh.
2237 2238 2239 2240 2241 2242 |
# File 'lib/clacky/server/http_server.rb', line 2237 def broadcast_session_update(session_id) session = @registry.list(limit: 200).find { |s| s[:id] == session_id } return unless session broadcast_all(type: "session_update", session: session) end |
#build_session(name:, working_dir:, permission_mode: :confirm_all, profile: "general", source: :manual, model_override: nil) ⇒ Object
Create a session in the registry and wire up Agent + WebUIController. Returns the new session_id. Build a new agent session.
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 |
# File 'lib/clacky/server/http_server.rb', line 2257 def build_session(name:, working_dir:, permission_mode: :confirm_all, profile: "general", source: :manual, model_override: nil) session_id = Clacky::SessionManager.generate_id @registry.create(session_id: session_id) client = @client_factory.call config = @agent_config.deep_copy config. = # Apply model override if provided if model_override && config.current_model config.current_model["model"] = model_override end broadcaster = method(:broadcast) ui = WebUIController.new(session_id, broadcaster) agent = Clacky::Agent.new(client, config, working_dir: working_dir, ui: ui, profile: profile, session_id: session_id, source: source) agent.rename(name) unless name.nil? || name.empty? idle_timer = build_idle_timer(session_id, agent) @registry.with_session(session_id) do |s| s[:agent] = agent s[:ui] = ui s[:idle_timer] = idle_timer end # Persist an initial snapshot so the session is immediately visible in registry.list # (which reads from disk). Without this, new sessions only appear after their first task. @session_manager.save(agent.to_session_data) session_id end |
#build_session_from_data(session_data, permission_mode: :confirm_all) ⇒ Object
Restore a persisted session from saved session_data (from SessionManager). The agent keeps its original session_id so the frontend URL hash stays valid across server restarts.
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 |
# File 'lib/clacky/server/http_server.rb', line 2293 def build_session_from_data(session_data, permission_mode: :confirm_all) original_id = session_data[:session_id] client = @client_factory.call config = @agent_config.deep_copy config. = broadcaster = method(:broadcast) ui = WebUIController.new(original_id, broadcaster) # Restore the agent profile from the persisted session; fall back to "general" # for sessions saved before the agent_profile field was introduced. profile = session_data[:agent_profile].to_s profile = "general" if profile.empty? agent = Clacky::Agent.from_session(client, config, session_data, ui: ui, profile: profile) idle_timer = build_idle_timer(original_id, agent) # Register session atomically with a fully-built agent so no concurrent # caller ever sees agent=nil for this session. The duplicate-restore guard # is handled upstream by SessionRegistry#ensure via @restoring. @registry.create(session_id: original_id) @registry.with_session(original_id) do |s| s[:agent] = agent s[:ui] = ui s[:idle_timer] = idle_timer end original_id end |
#create_default_session ⇒ Object
Auto-restore persisted sessions (or create a fresh default) when the server starts. Skipped when no API key is configured (onboard flow will handle it).
Strategy: load the most recent sessions from ~/.clacky/sessions/ for the current working directory and restore them into @registry so their IDs are stable across restarts (frontend hash stays valid). If no persisted sessions exist, fall back to creating a brand-new default session.
498 499 500 501 502 503 504 505 506 507 508 509 510 |
# File 'lib/clacky/server/http_server.rb', line 498 def create_default_session return unless @agent_config.models_configured? # Restore up to 5 sessions per source type from disk into the registry. @registry.restore_from_disk(n: 5) # If nothing was restored (no persisted sessions), create a fresh default. unless @registry.list(limit: 1).any? working_dir = default_working_dir FileUtils.mkdir_p(working_dir) unless Dir.exist?(working_dir) build_session(name: "Session 1", working_dir: working_dir) end end |
#default_working_dir ⇒ Object
── Helpers ───────────────────────────────────────────────────────────────
2246 2247 2248 |
# File 'lib/clacky/server/http_server.rb', line 2246 def default_working_dir File.("~/clacky_workspace") end |
#deliver_confirmation(session_id, conf_id, result) ⇒ Object
2117 2118 2119 2120 2121 |
# File 'lib/clacky/server/http_server.rb', line 2117 def deliver_confirmation(session_id, conf_id, result) ui = nil @registry.with_session(session_id) { |s| ui = s[:ui] } ui&.deliver_confirmation(conf_id, result) end |
#dispatch(req, res) ⇒ Object
── Router ────────────────────────────────────────────────────────────────
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# File 'lib/clacky/server/http_server.rb', line 317 def dispatch(req, res) path = req.path method = req.request_method # WebSocket upgrade — no timeout applied (long-lived connection) if websocket_upgrade?(req) handle_websocket(req, res) return end # Wrap all REST handlers in a timeout so a hung handler (e.g. infinite # recursion in chunk parsing) returns a proper 503 instead of an empty 200. # # Brand/license endpoints call PlatformHttpClient which retries across two # hosts with OPEN_TIMEOUT=8s per attempt × 2 attempts = up to ~16s on the # primary alone, before failing over to the fallback domain. Give them a # generous 90s so retry + failover can complete without being cut short. timeout_sec = if path.start_with?("/api/brand") 90 elsif path == "/api/tool/browser" 30 else 10 end Timeout.timeout(timeout_sec) do _dispatch_rest(req, res) end rescue Timeout::Error Clacky::Logger.warn("[HTTP 503] #{method} #{path} timed out after #{timeout_sec}s") json_response(res, 503, { error: "Request timed out" }) rescue => e Clacky::Logger.warn("[HTTP 500] #{e.class}: #{e.}\n#{e.backtrace.first(5).join("\n")}") json_response(res, 500, { error: e. }) end |
#handle_user_message(session_id, content, files = []) ⇒ Object
── Session actions ───────────────────────────────────────────────────────
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 |
# File 'lib/clacky/server/http_server.rb', line 2087 def (session_id, content, files = []) return unless @registry.exist?(session_id) session = @registry.get(session_id) return if session[:status] == :running agent = nil @registry.with_session(session_id) { |s| agent = s[:agent] } return unless agent # Auto-name the session from the first user message (before agent starts running). # Check messages.empty? only — agent.name may already hold a default placeholder # like "Session 1" assigned at creation time, so it's not a reliable signal. if agent.history.empty? auto_name = content.gsub(/\s+/, " ").strip[0, 30] auto_name += "…" if content.strip.length > 30 agent.rename(auto_name) broadcast(session_id, { type: "session_renamed", session_id: session_id, name: auto_name }) end # Broadcast user message through web_ui so channel subscribers (飞书/企微) receive it. web_ui = nil @registry.with_session(session_id) { |s| web_ui = s[:ui] } web_ui&.(content, source: :web) # File references are now handled inside agent.run — injected as a system_injected # message after the user message, so replay_history skips them automatically. run_agent_task(session_id, agent) { agent.run(content, files: files) } end |
#handle_websocket(req, res) ⇒ Object
Hijacks the TCP socket from WEBrick and upgrades it to WebSocket.
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 |
# File 'lib/clacky/server/http_server.rb', line 1946 def handle_websocket(req, res) socket = req.instance_variable_get(:@socket) # Server handshake — parse the upgrade request handshake = WebSocket::Handshake::Server.new handshake << build_handshake_request(req) unless handshake.finished? && handshake.valid? Clacky::Logger.warn("WebSocket handshake invalid") return end # Send the 101 Switching Protocols response socket.write(handshake.to_s) version = handshake.version incoming = WebSocket::Frame::Incoming::Server.new(version: version) conn = WebSocketConnection.new(socket, version) on_ws_open(conn) begin buf = String.new("", encoding: "BINARY") loop do chunk = socket.read_nonblock(4096, buf, exception: false) case chunk when :wait_readable IO.select([socket], nil, nil, 30) when nil break # EOF else incoming << chunk.dup while (frame = incoming.next) case frame.type when :text (conn, frame.data) when :binary (conn, frame.data) when :ping conn.send_raw(:pong, frame.data) when :close conn.send_raw(:close, "") break end end end end rescue IOError, Errno::ECONNRESET, Errno::EPIPE, Errno::EBADF # Client disconnected or socket became invalid ensure on_ws_close(conn) socket.close rescue nil end # Tell WEBrick not to send any response (we handled everything) res.instance_variable_set(:@header, {}) res.status = -1 rescue => e Clacky::Logger.error("WebSocket handler error: #{e.class}: #{e.}") end |
#interrupt_session(session_id) ⇒ Object
2123 2124 2125 2126 2127 2128 |
# File 'lib/clacky/server/http_server.rb', line 2123 def interrupt_session(session_id) @registry.with_session(session_id) do |s| s[:idle_timer]&.cancel s[:thread]&.raise(Clacky::AgentInterrupted, "Interrupted by user") end end |
#json_response(res, status, data) ⇒ Object
2339 2340 2341 2342 2343 2344 |
# File 'lib/clacky/server/http_server.rb', line 2339 def json_response(res, status, data) res.status = status res.content_type = "application/json; charset=utf-8" res["Access-Control-Allow-Origin"] = "*" res.body = JSON.generate(data) end |
#mask_api_key(key) ⇒ Object
Mask API key for display: show first 8 + last 4 chars, middle replaced with ****
2333 2334 2335 2336 2337 |
# File 'lib/clacky/server/http_server.rb', line 2333 def mask_api_key(key) return "" if key.nil? || key.empty? return key if key.length <= 12 "#{key[0..7]}****#{key[-4..]}" end |
#not_found(res) ⇒ Object
2402 2403 2404 2405 |
# File 'lib/clacky/server/http_server.rb', line 2402 def not_found(res) res.status = 404 res.body = "Not Found" end |
#on_ws_close(conn) ⇒ Object
2080 2081 2082 2083 |
# File 'lib/clacky/server/http_server.rb', line 2080 def on_ws_close(conn) @ws_mutex.synchronize { @all_ws_conns.delete(conn) } unsubscribe(conn) end |
#on_ws_message(conn, raw) ⇒ Object
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 |
# File 'lib/clacky/server/http_server.rb', line 2019 def (conn, raw) msg = JSON.parse(raw) type = msg["type"] case type when "subscribe" session_id = msg["session_id"] if @registry.ensure(session_id) conn.session_id = session_id subscribe(session_id, conn) conn.send_json(type: "subscribed", session_id: session_id) # If a shell command is still running, replay progress + buffered stdout # to the newly subscribed tab so it sees the live state it may have missed. @registry.with_session(session_id) { |s| s[:ui]&.replay_live_state } else conn.send_json(type: "error", message: "Session not found: #{session_id}") end when "message" session_id = msg["session_id"] || conn.session_id # Merge legacy images array into files as { data_url:, name:, mime_type: } entries raw_images = (msg["images"] || []).map do |data_url| { "data_url" => data_url, "name" => "image.jpg", "mime_type" => "image/jpeg" } end (session_id, msg["content"].to_s, (msg["files"] || []) + raw_images) when "confirmation" session_id = msg["session_id"] || conn.session_id deliver_confirmation(session_id, msg["id"], msg["result"]) when "interrupt" session_id = msg["session_id"] || conn.session_id interrupt_session(session_id) when "list_sessions" # Initial load: newest 20 sessions regardless of source/profile. # Single unified query — frontend shows all in one time-sorted list. page = @registry.list(limit: 21) has_more = page.size > 20 all_sessions = page.first(20) conn.send_json(type: "session_list", sessions: all_sessions, has_more: has_more) when "run_task" # Client sends this after subscribing to guarantee it's ready to receive # broadcasts before the agent starts executing. session_id = msg["session_id"] || conn.session_id start_pending_task(session_id) when "ping" conn.send_json(type: "pong") else conn.send_json(type: "error", message: "Unknown message type: #{type}") end rescue JSON::ParserError => e conn.send_json(type: "error", message: "Invalid JSON: #{e.}") rescue => e Clacky::Logger.error("[on_ws_message] #{e.class}: #{e.}\n#{e.backtrace.first(10).join("\n")}") conn.send_json(type: "error", message: e.) end |
#on_ws_open(conn) ⇒ Object
2014 2015 2016 2017 |
# File 'lib/clacky/server/http_server.rb', line 2014 def on_ws_open(conn) @ws_mutex.synchronize { @all_ws_conns << conn } # Client will send a "subscribe" message to bind to a session end |
#parse_json_body(req) ⇒ Object
2346 2347 2348 2349 2350 2351 2352 |
# File 'lib/clacky/server/http_server.rb', line 2346 def parse_json_body(req) return {} if req.body.nil? || req.body.empty? JSON.parse(req.body) rescue JSON::ParserError {} end |
#start ⇒ Object
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/clacky/server/http_server.rb', line 185 def start # Enable console logging for the server process so log lines are visible in the terminal. Clacky::Logger.console = true Clacky::Logger.info("[HttpServer PID=#{Process.pid}] start() mode=#{@inherited_socket ? 'worker' : 'standalone'} inherited_socket=#{@inherited_socket.inspect} master_pid=#{@master_pid.inspect}") # In standalone mode (no master), kill any stale server and manage our own PID file. # In worker mode the master owns the PID file; we just skip this block. if @inherited_socket.nil? kill_existing_server(@port) pid_file = File.join(Dir.tmpdir, "clacky-server-#{@port}.pid") File.write(pid_file, Process.pid.to_s) at_exit { File.delete(pid_file) if File.exist?(pid_file) } end # Expose server address and brand name to all child processes (skill scripts, shell commands, etc.) # so they can call back into the server without hardcoding the port, # and use the correct product name without re-reading brand.yml. ENV["CLACKY_SERVER_PORT"] = @port.to_s ENV["CLACKY_SERVER_HOST"] = (@host == "0.0.0.0" ? "127.0.0.1" : @host) product_name = Clacky::BrandConfig.load.product_name ENV["CLACKY_PRODUCT_NAME"] = (product_name.nil? || product_name.strip.empty?) ? "OpenClacky" : product_name # Override WEBrick's built-in signal traps via StartCallback, # which fires after WEBrick sets its own INT/TERM handlers. # This ensures Ctrl-C always exits immediately. # # When running as a worker under Master, DoNotListen: true prevents WEBrick # from calling bind() on its own — we inject the inherited socket instead. webrick_opts = { BindAddress: @host, Port: @port, Logger: WEBrick::Log.new(File::NULL), AccessLog: [], StartCallback: proc { } # signal traps set below, after `server` is created } webrick_opts[:DoNotListen] = true if @inherited_socket Clacky::Logger.info("[HttpServer PID=#{Process.pid}] WEBrick DoNotListen=#{webrick_opts[:DoNotListen].inspect}") server = WEBrick::HTTPServer.new(**webrick_opts) # Override WEBrick's signal traps now that `server` is available. # On INT/TERM: call server.shutdown (graceful), with a 1s hard-kill fallback. # Also stop BrowserManager so the chrome-devtools-mcp node process is killed # before this worker exits — otherwise it becomes an orphan and holds port 7070. shutdown_once = false shutdown_proc = proc do next if shutdown_once shutdown_once = true Thread.new do sleep 2 Clacky::Logger.warn("[HttpServer] Forced exit after graceful shutdown timeout.") exit!(0) end # Stop channel and browser managers in parallel to minimize shutdown time. t1 = Thread.new { @channel_manager.stop rescue nil } t2 = Thread.new { Clacky::BrowserManager.instance.stop rescue nil } t1.join(1.5) t2.join(1.5) server.shutdown rescue nil end trap("INT") { shutdown_proc.call } trap("TERM") { shutdown_proc.call } if @inherited_socket server.listeners << @inherited_socket Clacky::Logger.info("[HttpServer PID=#{Process.pid}] injected inherited fd=#{@inherited_socket.fileno} listeners=#{server.listeners.map(&:fileno).inspect}") else Clacky::Logger.info("[HttpServer PID=#{Process.pid}] standalone, WEBrick listeners=#{server.listeners.map(&:fileno).inspect}") end # Mount API + WebSocket handler (takes priority). # Use a custom Servlet so that DELETE/PUT/PATCH requests are not rejected # by WEBrick's default method whitelist before reaching our dispatcher. dispatcher = self servlet_class = Class.new(WEBrick::HTTPServlet::AbstractServlet) do define_method(:do_GET) { |req, res| dispatcher.send(:dispatch, req, res) } define_method(:do_POST) { |req, res| dispatcher.send(:dispatch, req, res) } define_method(:do_PUT) { |req, res| dispatcher.send(:dispatch, req, res) } define_method(:do_DELETE) { |req, res| dispatcher.send(:dispatch, req, res) } define_method(:do_PATCH) { |req, res| dispatcher.send(:dispatch, req, res) } define_method(:do_OPTIONS) { |req, res| dispatcher.send(:dispatch, req, res) } end server.mount("/api", servlet_class) server.mount("/ws", servlet_class) # Mount static file handler for the entire web directory. # Use mount_proc so we can inject no-cache headers on every response, # preventing stale JS/CSS from being served after a gem update. # # Special case: GET / and GET /index.html are served with server-side # rendering — the {{BRAND_NAME}} placeholder is replaced before delivery # so the correct brand name appears on first paint with no JS flash. file_handler = WEBrick::HTTPServlet::FileHandler.new(server, WEB_ROOT, FancyIndexing: false) index_html_path = File.join(WEB_ROOT, "index.html") server.mount_proc("/") do |req, res| if req.path == "/" || req.path == "/index.html" product_name = Clacky::BrandConfig.load.product_name || "OpenClacky" html = File.read(index_html_path).gsub("{{BRAND_NAME}}", product_name) res.status = 200 res["Content-Type"] = "text/html; charset=utf-8" res["Cache-Control"] = "no-store" res["Pragma"] = "no-cache" res.body = html else file_handler.service(req, res) res["Cache-Control"] = "no-store" res["Pragma"] = "no-cache" end end # Auto-create a default session on startup create_default_session # Start the background scheduler @scheduler.start puts " Scheduler: #{@scheduler.schedules.size} task(s) loaded" # Start IM channel adapters (non-blocking — each platform runs in its own thread) @channel_manager.start # Start browser MCP daemon if browser.yml is configured (non-blocking) @browser_manager.start server.start end |
#start_pending_task(session_id) ⇒ Object
Start the pending task for a session. Called when the client sends “run_task” over WS — by that point the client has already subscribed, so every broadcast will be delivered.
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 |
# File 'lib/clacky/server/http_server.rb', line 2133 def start_pending_task(session_id) return unless @registry.exist?(session_id) session = @registry.get(session_id) prompt = session[:pending_task] working_dir = session[:pending_working_dir] return unless prompt # nothing pending # Clear the pending fields so a re-connect doesn't re-run @registry.update(session_id, pending_task: nil, pending_working_dir: nil) agent = nil @registry.with_session(session_id) { |s| agent = s[:agent] } return unless agent run_agent_task(session_id, agent) { agent.run(prompt) } end |
#subscribe(session_id, conn) ⇒ Object
── WebSocket subscription management ─────────────────────────────────────
2190 2191 2192 2193 2194 2195 2196 2197 2198 |
# File 'lib/clacky/server/http_server.rb', line 2190 def subscribe(session_id, conn) @ws_mutex.synchronize do # Remove conn from any previous session subscription first, # so switching sessions never results in duplicate delivery. @ws_clients.each_value { |list| list.delete(conn) } @ws_clients[session_id] ||= [] @ws_clients[session_id] << conn unless @ws_clients[session_id].include?(conn) end end |
#unsubscribe(conn) ⇒ Object
2200 2201 2202 2203 2204 |
# File 'lib/clacky/server/http_server.rb', line 2200 def unsubscribe(conn) @ws_mutex.synchronize do @ws_clients.each_value { |list| list.delete(conn) } end end |
#unsubscribe_all(session_id) ⇒ Object
2206 2207 2208 |
# File 'lib/clacky/server/http_server.rb', line 2206 def unsubscribe_all(session_id) @ws_mutex.synchronize { @ws_clients.delete(session_id) } end |
#websocket_upgrade?(req) ⇒ Boolean
── WebSocket ─────────────────────────────────────────────────────────────
1941 1942 1943 |
# File 'lib/clacky/server/http_server.rb', line 1941 def websocket_upgrade?(req) req["Upgrade"]&.downcase == "websocket" end |