Class: Clacky::Server::HttpServer

Inherits:
Object
  • Object
show all
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.expand_path("../web", __dir__)
AGENT_INTERRUPT_JOIN_SECONDS =

How long shutdown waits for each agent thread to unwind before falling back to a manual session save.

2
EXCHANGE_RATE_PRIMARY_BASE_URL =
"https://open.er-api.com/v6/latest"
EXCHANGE_RATE_FALLBACK_URL =
"https://api.frankfurter.app/latest"
OSS_CDN_BASE =
"https://oss.1024code.com/openclacky"
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
BRAND_HEARTBEAT_MUTEX =

Process-wide mutex guarding heartbeat trigger state. Used by #trigger_async_heartbeat! to ensure only one heartbeat Thread is in flight at a time, no matter how many concurrent /api/brand/status requests arrive from the Web UI poller.

Mutex.new
BRAND_DIST_REFRESH_MUTEX =

Mutex + inflight flag for async distribution refresh. Mirrors the heartbeat pattern above so the same guarantees hold: at most one refresh thread per process regardless of how many concurrent /api/brand/status polls arrive from the Web UI.

Mutex.new
INSTALL_JOB_TTL =

Install jobs can go stale in two ways:

- the client abandons the poll (tab closed, network drop) so a
finished job never gets picked up and deleted by the status endpoint
- the worker thread dies without ever updating the job hash (should
not happen given the rescue in api_store_extension_install, but a
hung Thread with no timeout upstream would otherwise pin memory
forever)

Sweep anything past its TTL. Must be called from inside

30 * 60
IGNORED_FILE_ENTRIES =

Lists one directory level inside the session's working_dir (lazy, per-layer). Path traversal outside working_dir is rejected. Noisy dirs are hidden.

%w[.git .svn .hg node_modules .DS_Store .bundle vendor/bundle tmp .sass-cache].freeze
WINDOWS_PROFILE_DIRS =

Windows "special" folders under C:Users that aren't real user profiles.

["Public", "Default", "Default User", "All Users"].freeze
PROFILE_USER_AGENTS_DIR =

── Profile API (USER.md / SOUL.md) ──────────────────────────────

User can override the built-in defaults by writing their own ~/.clacky/agents/USER.md and ~/.clacky/agents/SOUL.md. These endpoints let the Web UI read and edit those files.

File.expand_path("~/.clacky/agents").freeze
PROFILE_MAX_BYTES =

Hard limit; prevents runaway content.

50_000
MEMORIES_DIR =

── Memories API (~/.clacky/memories/*.md) ───────────────────────

Long-term memories are plain Markdown files with YAML frontmatter stored under ~/.clacky/memories/. These endpoints let the user inspect, edit, create, and delete them from the Web UI.

File.expand_path("~/.clacky/memories").freeze
MEMORY_MAX_BYTES =
50_000
@@brand_heartbeat_inflight =

Tracks whether a heartbeat Thread is currently running.

false
@@brand_dist_refresh_inflight =
false

Instance Method Summary collapse

Constructor Details

#initialize(host: "127.0.0.1", port: 7070, agent_config:, client_factory:, brand_test: false, sessions_dir: nil, projects_file: nil, socket: nil, master_pid: nil) ⇒ HttpServer

Returns a new instance of HttpServer.



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
# File 'lib/clacky/server/http_server.rb', line 222

def initialize(host: "127.0.0.1", port: 7070, agent_config:, client_factory:, brand_test: false, sessions_dir: nil, projects_file: 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.expand_path($0)
  @restart_argv   = ARGV.dup
  @session_manager = Clacky::SessionManager.new(sessions_dir: sessions_dir)
  @project_manager = Clacky::Server::ProjectManager.new(projects_file: projects_file)
  @registry        = SessionRegistry.new(
    session_manager:  @session_manager,
    session_restorer: method(:build_session_from_data),
    agent_config:     @agent_config
  )
  @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),
    task_runner:      method(:run_agent_task)
  )
  @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),
    # No updated_at: clearing a stale channel_info must not bump the session's
    # position in the newest-first list.
    persist_session:   ->(agent) { @session_manager.save(agent.to_session_data) },
    channel_config:    Clacky::ChannelConfig.load
  )
  @browser_manager = Clacky::BrowserManager.instance
  @skill_loader    = Clacky::SkillLoader.new(working_dir: nil, brand_config: Clacky::BrandConfig.load)
  # Lazy: process-wide MCP registry. Created on first /api/mcp/:name access
  # so test setups that override Dir.home in before-hooks still work.
  @mcp_registry_mutex = Mutex.new
  # Install jobs: job_id => { stage:, progress:, error:, done: }
  @install_jobs       = {}
  @install_jobs_mutex = Mutex.new
  # Access key authentication:
  # - localhost (127.0.0.1 / ::1) is always trusted; auth is skipped entirely.
  # - Any other bind address requires CLACKY_ACCESS_KEY env var.
  @localhost_only      = local_host?(@host)
  @access_key          = @localhost_only ? nil : resolve_access_key
  @auth_failures       = {}
  @auth_failures_mutex = Mutex.new
  if @localhost_only
    Clacky::Logger.info("[HttpServer] Localhost mode — authentication disabled")
  else
    Clacky::Logger.info("[HttpServer] Public mode — access key authentication ENABLED")
  end
end

Instance Method Details

#_dispatch_rest(req, res) ⇒ Object



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
661
662
663
664
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
767
768
769
770
771
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
# File 'lib/clacky/server/http_server.rb', line 634

def _dispatch_rest(req, res)
  path   = req.path
  method = req.request_method

  # HTTP API extensions declared in an ext.yml container mount at
  # /api/ext/<ext_id>/... Routed through a separate dispatcher so the
  # host's giant case table stays focused on built-in endpoints.
  if path.start_with?(Clacky::Server::ApiExtensionDispatcher::MOUNT_PREFIX)
    return if Clacky::Server::ApiExtensionDispatcher.handle(req, res, http_server: self)
  end

  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/projects"]      then api_list_projects(res)
  when ["POST",   "/api/projects"]      then api_create_project(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/agents"]         then api_list_agents(res)
  when ["GET",    "/api/config"]        then api_get_config(req, res)
  when ["GET",    "/api/model_prices"]  then json_response(res, 200, Clacky::Server::ModelPrices.build(req.query["models"]))
  when ["GET",    "/api/config/settings"]  then api_get_settings(res)
  when ["GET",    "/api/exchange-rate"]    then api_exchange_rate(req, res)
  when ["PATCH",  "/api/config/settings"]  then api_update_settings(req, res)
  when ["POST",   "/api/config/models"] then api_add_model(req, res)
  when ["POST",   "/api/config/test"]   then api_test_config(req, res)
  when ["POST",   "/api/config/media/test"] then api_test_media_config(req, res)
  when ["GET",    "/api/config/media"]  then api_get_media_config(res)
  when ["GET",    "/api/config/ocr"]    then api_get_ocr_config(res)
  when ["PATCH",  "/api/config/ocr"]    then api_update_ocr_config(req, res)
  when ["POST",   "/api/config/ocr/test"] then api_test_ocr_config(req, res)
  when ["GET",    "/api/config/search"] then api_get_search_config(res)
  when ["PATCH",  "/api/config/search"] then api_update_search_config(req, res)
  when ["POST",   "/api/config/search/test"] then api_test_search_config(req, res)
  when ["POST",   "/api/internal/ocr-image"] then api_internal_ocr_image(req, res)
  when ["GET",    "/api/providers"]     then api_list_providers(res)
  when ["GET",    "/api/onboard/status"]    then api_onboard_status(res)
  when ["POST",   "/api/onboard/device/start"] then api_onboard_device_start(req, res)
  when ["POST",   "/api/onboard/device/poll"]  then api_onboard_device_poll(req, 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 ["GET",    "/api/backup/status"]     then api_backup_status(res)
  when ["POST",   "/api/backup/run"]        then api_backup_run(res)
  when ["GET",    "/api/backup/download"]   then api_backup_download(res)
  when ["POST",   "/api/backup/restore"]    then api_backup_restore(req, res)
  when ["POST",   "/api/backup/open-folder"] then api_backup_open_folder(res)
  when ["PATCH",  "/api/backup/config"]     then api_backup_config(req, res)
  when ["POST",   "/api/telemetry"]        then api_telemetry(req, 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/store/extensions"]          then api_store_extensions(req, res)
  when ["GET",    "/api/store/extensions/brand"]   then api_store_extensions_brand(res)
  when ["GET",    "/api/store/extensions/system"]   then api_store_extensions_system(res)
  when ["GET",    "/api/store/extensions/installed"] then api_store_extensions_installed(res)
  when ["GET",    "/api/store/extension"]       then api_store_extension_detail(req, res)
  when ["POST",   "/api/store/extension/install"]  then api_store_extension_install(req, res)
  when ["POST",   "/api/store/extension/import"]   then api_store_extension_import(req, res)
  when ["GET",    "/api/store/extension/install/status"] then api_store_extension_install_status(req, res)
  when ["POST",   "/api/store/extension/disable"] then api_store_extension_disable(req, res)
  when ["POST",   "/api/store/extension/enable"]  then api_store_extension_enable(req, res)
  when ["DELETE", "/api/store/extension"]         then api_store_extension_uninstall(req, 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/trash"]     then api_trash(req, res)
  when ["POST",   "/api/trash/restore"] then api_trash_restore(req, res)
  when ["DELETE", "/api/trash"]     then api_trash_delete(req, res)
  when ["GET",    "/api/trash/sessions"]     then api_trash_sessions(req, res)
  when ["POST",   "/api/trash/sessions/restore"] then api_trash_session_restore(req, res)
  when ["DELETE", "/api/trash/sessions"]     then api_trash_sessions_delete(req, res)
  when ["GET",    "/api/profile"]   then api_profile_get(res)
  when ["PUT",    "/api/profile"]   then api_profile_put(req, res)
  when ["GET",    "/api/memories"]  then api_memories_list(res)
  when ["POST",   "/api/memories"]  then api_memories_create(req, res)
  when ["GET",    "/api/channels"]          then api_list_channels(res)
  when ["GET",    "/api/mcp"]               then api_mcp_list(res)
  when ["POST",   "/api/tool/browser"]      then api_tool_browser(req, res)
  when ["POST",   "/api/upload"]            then api_upload_file(req, res)
  when ["POST",   "/api/file-action"]       then api_file_action(req, res)
  when ["GET",    "/api/local-image"]       then api_serve_local_image(req, res)
  when ["POST",   "/api/media/image"]       then api_media_image(req, res)
  when ["POST",   "/api/media/video"]       then api_media_video(req, res)
  when ["GET",    "/api/media/video/status"] then api_media_video_status(req, res)
  when ["POST",   "/api/media/audio/speech"] then api_media_audio_speech(req, res)
  when ["POST",   "/api/media/audio/transcriptions"] then api_media_audio_transcriptions(req, res)
  when ["POST",   "/api/media/video/understand"]     then api_media_video_understand(req, res)
  when ["GET",    "/api/media/types"]       then api_media_types(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 ["GET",    "/api/billing/summary"]   then api_billing_summary(req, res)
  when ["GET",    "/api/billing/daily"]     then api_billing_daily(req, res)
  when ["GET",    "/api/billing/records"]   then api_billing_records(req, res)
  when ["GET",    "/api/billing/sessions"]  then api_billing_sessions(req, res)
  when ["DELETE", "/api/billing/clear"]     then api_billing_clear(req, res)
  when ["POST",   "/api/ui/open_aside"]       then api_ui_open_aside(req, res)
  when ["POST",   "/api/ui/show_ext_refresh"] then api_ui_show_ext_refresh(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/[^/]+/send$})
      platform = path.sub("/api/channels/", "").sub("/send", "")
      api_send_channel_message(platform, req, res)
    elsif method == "GET" && path.match?(%r{^/api/channels/group_history/})
      chat_id = URI.decode_www_form_component(path.sub("/api/channels/group_history/", ""))
      api_group_history(chat_id, res)
    elsif method == "GET" && path.match?(%r{^/api/channels/[^/]+/users$})
      platform = path.sub("/api/channels/", "").sub("/users", "")
      api_list_channel_users(platform, res)
    elsif method == "POST" && path.match?(%r{^/api/channels/[^/]+/test$})
      platform = path.sub("/api/channels/", "").sub("/test", "")
      api_test_channel(platform, req, res)
    elsif method == "PATCH" && path == "/api/channels/status_messages"
      api_channel_status_messages(req, res)
    elsif method == "PATCH" && path == "/api/channels/process_messages"
      api_channel_process_messages(req, res)
    elsif method == "PATCH" && path.match?(%r{^/api/channels/[^/]+/enabled$})
      platform = path.sub("/api/channels/", "").sub("/enabled", "")
      api_toggle_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 == "POST" && path.match?(%r{^/api/mcp/[^/]+/probe$})
      name = path.sub("/api/mcp/", "").sub("/probe", "")
      api_mcp_probe(name, res)
    elsif method == "GET" && path.match?(%r{^/api/mcp/[^/]+/tools$})
      name = path.sub("/api/mcp/", "").sub("/tools", "")
      api_mcp_tools(name, res)
    elsif method == "POST" && path.match?(%r{^/api/mcp/[^/]+/call$})
      name = path.sub("/api/mcp/", "").sub("/call", "")
      api_mcp_call(name, req, res)
    elsif method == "POST" && path == "/api/mcp"
      api_mcp_create(req, res)
    elsif method == "PATCH" && path.match?(%r{^/api/mcp/[^/]+/enabled$})
      name = path.sub("/api/mcp/", "").sub("/enabled", "")
      api_mcp_toggle(name, req, res)
    elsif method == "PUT" && path.match?(%r{^/api/mcp/[^/]+$})
      name = path.sub("/api/mcp/", "")
      api_mcp_update(name, req, res)
    elsif method == "DELETE" && path.match?(%r{^/api/mcp/[^/]+$})
      name = path.sub("/api/mcp/", "")
      api_mcp_delete(name, req, 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/agents/[^/]+/skills$})
      agent_id = path[%r{^/api/agents/([^/]+)/skills$}, 1]
      api_agent_skills(agent_id, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/git/[a-z]+$})
      session_id = path[%r{^/api/sessions/([^/]+)/git/}, 1]
      action     = path[%r{/git/([a-z]+)$}, 1]
      api_session_git(session_id, action, req, res)
    elsif method == "POST" && path.match?(%r{^/api/sessions/[^/]+/git/commit$})
      session_id = path[%r{^/api/sessions/([^/]+)/git/}, 1]
      api_session_git_commit(session_id, req, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/time_machine$})
      session_id = path.sub("/api/sessions/", "").sub("/time_machine", "")
      api_session_time_machine(session_id, res)
    elsif method == "POST" && path.match?(%r{^/api/sessions/[^/]+/time_machine/switch$})
      session_id = path[%r{^/api/sessions/([^/]+)/time_machine/}, 1]
      api_session_time_machine_switch(session_id, req, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/time_machine/\d+/diff$})
      session_id = path[%r{^/api/sessions/([^/]+)/time_machine/}, 1]
      task_id    = path[%r{/time_machine/(\d+)/diff$}, 1].to_i
      api_session_time_machine_diff(session_id, task_id, req, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/time_machine/\d+/restore_preview$})
      session_id = path[%r{^/api/sessions/([^/]+)/time_machine/}, 1]
      task_id    = path[%r{/time_machine/(\d+)/restore_preview$}, 1].to_i
      api_session_time_machine_restore_preview(session_id, task_id, res)
    elsif method == "GET" && path == "/api/dirs"
      api_browse_dirs(req, res)
    elsif method == "POST" && path == "/api/dirs/mkdir"
      api_dirs_mkdir(req, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/files$})
      session_id = path.sub("/api/sessions/", "").sub("/files", "")
      api_session_files(session_id, req, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/export$})
      session_id = path.sub("/api/sessions/", "").sub("/export", "")
      api_export_session(session_id, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+/messages$})
      session_id = path.sub("/api/sessions/", "").sub("/messages", "")
      api_session_messages(session_id, req, res)
    elsif method == "GET" && path.match?(%r{^/api/sessions/[^/]+$})
      session_id = path.sub("/api/sessions/", "")
      api_get_session(session_id, 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/[^/]+/project$})
      session_id = path.sub("/api/sessions/", "").sub("/project", "")
      api_update_session_project(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/[^/]+/reasoning_effort$})
      session_id = path.sub("/api/sessions/", "").sub("/reasoning_effort", "")
      api_switch_session_reasoning_effort(session_id, req, res)
    elsif method == "PATCH" && path.match?(%r{^/api/sessions/[^/]+/submodel$})
      session_id = path.sub("/api/sessions/", "").sub("/submodel", "")
      api_switch_session_submodel(session_id, req, res)
    elsif method == "POST" && path.match?(%r{^/api/sessions/[^/]+/benchmark$})
      session_id = path.sub("/api/sessions/", "").sub("/benchmark", "")
      api_benchmark_session_models(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 == "POST" && path.match?(%r{^/api/sessions/[^/]+/fork$})
      session_id = path.sub("/api/sessions/", "").sub("/fork", "")
      api_fork_session(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 == "DELETE" && path.match?(%r{^/api/trash/sessions/[^/]+$})
      session_id = path.sub("/api/trash/sessions/", "")
      api_trash_session_delete_one(session_id, res)
    elsif method == "POST" && path.match?(%r{^/api/config/models/[^/]+/default$})
      id = path.sub("/api/config/models/", "").sub("/default", "")
      api_set_default_model(id, res)
    elsif method == "PATCH" && path.match?(%r{^/api/config/models/[^/]+$})
      id = path.sub("/api/config/models/", "")
      api_update_model(id, req, res)
    elsif method == "DELETE" && path.match?(%r{^/api/config/models/[^/]+$})
      id = path.sub("/api/config/models/", "")
      api_delete_model(id, res)
    elsif method == "PATCH" && path.match?(%r{^/api/config/media/(image|video|audio|stt|video_understanding)$})
      kind = path.sub("/api/config/media/", "")
      api_update_media_config(kind, req, 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 == "GET" && path.match?(%r{^/api/skills/[^/]+/content$})
      name = URI.decode_www_form_component(path.sub("/api/skills/", "").sub("/content", ""))
      api_skill_content_get(name, res)
    elsif method == "PUT" && path.match?(%r{^/api/skills/[^/]+/content$})
      name = URI.decode_www_form_component(path.sub("/api/skills/", "").sub("/content", ""))
      api_skill_content_update(name, req, res)
    elsif method == "DELETE" && path.match?(%r{^/api/skills/[^/]+$})
      name = URI.decode_www_form_component(path.sub("/api/skills/", ""))
      api_delete_skill(name, res)
    elsif method == "DELETE" && path.match?(%r{^/api/brand/skills/[^/]+$})
      slug = URI.decode_www_form_component(path.sub("/api/brand/skills/", ""))
      api_delete_brand_skill(slug, 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)
    elsif method == "GET" && path.match?(%r{^/api/memories/[^/]+$})
      filename = URI.decode_www_form_component(path.sub("/api/memories/", ""))
      api_memories_get(filename, res)
    elsif method == "PUT" && path.match?(%r{^/api/memories/[^/]+$})
      filename = URI.decode_www_form_component(path.sub("/api/memories/", ""))
      api_memories_update(filename, req, res)
    elsif method == "DELETE" && path.match?(%r{^/api/memories/[^/]+$})
      filename = URI.decode_www_form_component(path.sub("/api/memories/", ""))
      api_memories_delete(filename, res)
    elsif method == "PATCH" && path.match?(%r{^/api/projects/[^/]+$})
      project_id = path.sub("/api/projects/", "")
      api_update_project(project_id, req, res)
    elsif method == "DELETE" && path.match?(%r{^/api/projects/[^/]+/sessions$})
      project_id = path.sub("/api/projects/", "").sub("/sessions", "")
      api_delete_project_sessions(project_id, res)
    elsif method == "DELETE" && path.match?(%r{^/api/projects/[^/]+$})
      project_id = path.sub("/api/projects/", "")
      api_delete_project(project_id, res)
    else
      not_found(res)
    end
  end
end

#api_add_model(req, res) ⇒ Object

POST /api/config/models Body: { model, base_url, api_key, anthropic_format, api_format?, type? } Creates a new model entry, returns { ok:true, id, index } so the frontend can record the new id without reloading the whole list.



6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
# File 'lib/clacky/server/http_server.rb', line 6394

def api_add_model(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  api_format = normalize_api_format(body["api_format"])
  return json_response(res, 422, { error: "invalid api_format" }) if api_format == :invalid

  model    = body["model"].to_s.strip
  base_url = body["base_url"].to_s.strip
  api_key  = body["api_key"].to_s
  # When duplicating, the frontend sends source_id so we can inherit the
  # real key without ever transmitting it back to the client.
  if api_key.empty? || api_key.include?("****")
    source_id = body["source_id"].to_s
    unless source_id.empty?
      source  = @agent_config.models.find { |m| m["id"] == source_id }
      api_key = source["api_key"].to_s if source
    end
  end
  if api_key.empty? || api_key.include?("****")
    return json_response(res, 422, { error: "api_key is required" })
  end

  entry = {
    "id"               => SecureRandom.uuid,
    "model"            => model,
    "base_url"         => base_url,
    "api_key"          => api_key,
    "anthropic_format" => body["anthropic_format"] || false,
    "provider_id"      => body["provider_id"].to_s.strip.then { |v| v.empty? ? nil : v }
  }
  caps = body["capabilities"]
  if caps.is_a?(Hash) && !caps.empty?
    entry["capabilities"] = caps.each_with_object({}) { |(k, v), h| h[k.to_s] = v == true }
  end
  remark = body["remark"].to_s.strip
  entry["remark"] = remark unless remark.empty?
  entry["api_format"] = api_format if api_format
  type = body["type"].to_s
  unless type.empty?
    # Preserve the single-slot "default" invariant.
    if type == "default"
      @agent_config.models.each { |m| m.delete("type") if m["type"] == "default" }
    end
    entry["type"] = type
  end

  @agent_config.models << entry
  # If this is the only model and no default marker exists yet,
  # adopt it as the default so downstream lookups resolve cleanly.
  if @agent_config.models.none? { |m| m["type"] == "default" }
    entry["type"] = "default"
    @agent_config.current_model_id    = entry["id"]
    @agent_config.current_model_index = @agent_config.models.length - 1
  elsif type == "default"
    # Re-anchor current_* to the newly-defaulted entry.
    @agent_config.current_model_id    = entry["id"]
    @agent_config.current_model_index = @agent_config.models.length - 1
  end

  @agent_config.save
  json_response(res, 200, {
    ok:    true,
    id:    entry["id"],
    index: @agent_config.models.length - 1
  })
rescue => e
  json_response(res, 422, { error: e.message })
end

#api_agent_skills(agent_id, res) ⇒ Object

GET /api/agents/:id/skills — like api_session_skills but keyed on an agent id rather than a live session. Used by the New Session page so the first-message composer can offer slash-command autocomplete before a session exists.



4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
# File 'lib/clacky/server/http_server.rb', line 4910

def api_agent_skills(agent_id, res)
  profile = begin
    Clacky::AgentProfile.load(agent_id)
  rescue StandardError
    nil
  end

  @skill_loader.load_all
  skills = @skill_loader.user_invocable_skills(profile)

  loaded_from = @skill_loader.loaded_from
  skill_data = skills.map do |skill|
    {
      name:           skill.identifier,
      name_zh:        skill.name_zh,
      description:    skill.description || skill.context_description,
      description_zh: skill.description_zh,
      encrypted:      skill.encrypted?,
      source_type:    loaded_from[skill.identifier],
      always_show:    skill.always_show
    }
  end

  json_response(res, 200, { skills: skill_data })
end

#api_backup_config(req, res) ⇒ Object

Body: { enabled?, cron?, dest_dir?, keep?, include_sessions? }



1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# File 'lib/clacky/server/http_server.rb', line 1672

def api_backup_config(req, res)
  body = parse_json_body(req) || {}
  cfg = BackupManager.update_config(
    enabled:          body.key?("enabled") ? body["enabled"] : nil,
    cron:             body["cron"],
    dest_dir:         body.key?("dest_dir") ? body["dest_dir"] : nil,
    keep:             body["keep"],
    include_sessions: body.key?("include_sessions") ? body["include_sessions"] : nil
  )
  json_response(res, 200, { ok: true, config: cfg, status: BackupManager.status })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_backup_download(res) ⇒ Object

GET /api/backup/download — build a one-off archive and stream it directly to the browser. Not written to dest_dir nor recorded.



1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
# File 'lib/clacky/server/http_server.rb', line 1659

def api_backup_download(res)
  result = BackupManager.build_download!
  res.status                = 200
  res["Content-Type"]       = "application/gzip"
  res["Content-Disposition"] = %(attachment; filename="#{result[:filename]}")
  res["Cache-Control"]      = "no-store"
  res.body                  = File.binread(result[:path])
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
ensure
  FileUtils.rm_f(result[:path]) if result && result[:path]
end

#api_backup_open_folder(res) ⇒ Object

POST /api/backup/open-folder — open the backup destination in Finder/Explorer



6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
# File 'lib/clacky/server/http_server.rb', line 6195

def api_backup_open_folder(res)
  dest = BackupManager.status["dest_dir"]
  FileUtils.mkdir_p(dest)
  host_os = RbConfig::CONFIG["host_os"]
  if host_os =~ /darwin/
    system("open", dest)
  elsif host_os =~ /linux/
    if File.exist?("/proc/version") && File.read("/proc/version").downcase.include?("microsoft")
      windows_path, = Open3.capture2("wslpath", "-w", dest)
      system("explorer.exe", windows_path.strip) unless windows_path.strip.empty?
    else
      system("xdg-open", dest)
    end
  end
  json_response(res, 200, { ok: true, dest_dir: dest })
rescue => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_backup_restore(req, res) ⇒ Object

POST /api/backup/restore — accept a tar.gz upload, extract over ~/.clacky, hot-restart



6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
# File 'lib/clacky/server/http_server.rb', line 6153

def api_backup_restore(req, res)
  body = req.body.to_s
  return json_response(res, 400, { error: "Empty body" }) if body.empty?

  clacky_dir = File.expand_path("~/.clacky")
  stamp      = Time.now.strftime("%Y%m%d-%H%M%S")
  tmp_archive = File.join(Dir.tmpdir, "clacky-restore-#{stamp}.tar.gz")
  tmp_backup  = File.join(Dir.tmpdir, "clacky-pre-restore-#{stamp}")

  File.binwrite(tmp_archive, body)

  FileUtils.cp_r(clacky_dir, tmp_backup)

  result = system("tar", "-xzf", tmp_archive, "-C", clacky_dir)
  unless result
    FileUtils.rm_rf(clacky_dir)
    FileUtils.cp_r(tmp_backup, clacky_dir)
    return json_response(res, 500, { error: "Failed to extract archive" })
  end

  json_response(res, 200, { ok: true })

  Clacky::ThreadRegistry.spawn(name: "exec-restart") do
    sleep 0.5
    if @master_pid
      begin
        Process.kill("USR1", @master_pid)
      rescue Errno::ESRCH
        standalone_exec_restart
      end
    else
      standalone_exec_restart
    end
  end
rescue => e
  json_response(res, 500, { ok: false, error: e.message })
ensure
  FileUtils.rm_f(tmp_archive) if tmp_archive
  FileUtils.rm_rf(tmp_backup) if tmp_backup && Dir.exist?(tmp_backup)
end

#api_backup_run(res) ⇒ Object

POST /api/backup/run — run a backup immediately.



1648
1649
1650
1651
1652
1653
1654
1655
# File 'lib/clacky/server/http_server.rb', line 1648

def api_backup_run(res)
  result = BackupManager.run!
  json_response(res, 200, { ok: true, archive: File.basename(result[:archive]),
                            size: result[:size], dest_dir: result[:dest_dir],
                            status: BackupManager.status })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_backup_status(res) ⇒ Object

GET /api/backup/status



1641
1642
1643
1644
1645
# File 'lib/clacky/server/http_server.rb', line 1641

def api_backup_status(res)
  json_response(res, 200, BackupManager.status)
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_benchmark_session_models(session_id, _req, res) ⇒ Object

POST /api/sessions/:id/benchmark

Speed-test every configured model in one shot so the user can pick the fastest available model for this session. We send a minimal one-token request to each model in parallel (one thread per model) and measure total HTTP duration — for non-streaming calls this equals the user's perceived time-to-first-token, so the field is named ttft_ms for forward-compatibility with a future streaming implementation.

Cost note: each request is max_tokens: 1 + a 2-byte prompt, so the total cost across a dozen models is well under one cent.

Response shape:

{
ok: true,
results: [
  { model_id: "...", model: "...", ttft_ms: 812, ok: true },
  { model_id: "...", model: "...", ok: false, error: "timeout" },
  ...
]
}


7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
# File 'lib/clacky/server/http_server.rb', line 7017

def api_benchmark_session_models(session_id, _req, res)
  return json_response(res, 404, { error: "Session not found" }) unless @registry.ensure(session_id)

  # Snapshot the models list — @agent_config.models is a shared reference
  # that the user might mutate from the settings panel during the test;
  # a shallow dup is enough since we only read string fields below.
  models = Array(@agent_config.models).dup
  return json_response(res, 200, { ok: true, results: [] }) if models.empty?

  # Kick off one thread per model. We deliberately cap per-request wall
  # time inside each thread via a Faraday timeout so a single dead model
  # can't block the response. The outer join uses a generous ceiling
  # (timeout + small buffer) as a last-resort safety net.
  per_model_timeout = 15
  threads = models.map do |m|
    Clacky::ThreadRegistry.spawn(name: "benchmark-model") do
      Thread.current.report_on_exception = false
      benchmark_single_model(m, per_model_timeout)
    end
  end

  results = threads.map do |t|
    if t.join(per_model_timeout + 3)
      t.value rescue { ok: false, error: "thread failed" }
    else
      t.kill
      { ok: false, error: "Request timed out" }
    end
  end

  json_response(res, 200, { ok: true, results: results })
rescue => e
  Clacky::Logger.error("[benchmark] #{e.class}: #{e.message}", error: e)
  json_response(res, 500, { error: e.message })
end

#api_billing_clear(req, res) ⇒ Object

DELETE /api/billing/clear # Clears billing records Query params: scope (today|all, default: today)



3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
# File 'lib/clacky/server/http_server.rb', line 3343

def api_billing_clear(req, res)
  require_relative "../billing/billing_store"

  query = URI.decode_www_form(req.query_string.to_s).to_h
  scope = query["scope"] || "today"

  store = Clacky::Billing::BillingStore.new
  deleted = store.clear(scope: scope.to_sym)

  json_response(res, 200, { ok: true, deleted: deleted, scope: scope })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_billing_daily(req, res) ⇒ Object

GET /api/billing/daily Returns daily cost breakdown Query params: days (default: 30), model (optional)



3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
# File 'lib/clacky/server/http_server.rb', line 3288

def api_billing_daily(req, res)
  require_relative "../billing/billing_store"

  query = URI.decode_www_form(req.query_string.to_s).to_h
  days  = [(query["days"] || "30").to_i, 90].min
  model = query["model"]

  store = Clacky::Billing::BillingStore.new
  daily = merged_billing_daily(store, days: days, model: model)

  json_response(res, 200, { days: daily })
end

#api_billing_records(req, res) ⇒ Object

GET /api/billing/records Returns recent billing records Query params: limit (default: 100), model, session_id



3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
# File 'lib/clacky/server/http_server.rb', line 3304

def api_billing_records(req, res)
  require_relative "../billing/billing_store"

  query      = URI.decode_www_form(req.query_string.to_s).to_h
  limit      = [(query["limit"] || "100").to_i, 500].min
  model      = query["model"]
  session_id = query["session_id"]

  store   = Clacky::Billing::BillingStore.new
  records = store.query(model: model, session_id: session_id, limit: limit)

  json_response(res, 200, {
    records: records.map(&:to_h),
    count: records.size
  })
end

#api_billing_sessions(req, res) ⇒ Object

GET /api/billing/sessions Returns session-level billing summary Query params: period (day|week|month|year|all, default: month), model, limit



3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
# File 'lib/clacky/server/http_server.rb', line 3324

def api_billing_sessions(req, res)
  require_relative "../billing/billing_store"

  query = URI.decode_www_form(req.query_string.to_s).to_h
  period = (query["period"] || "month").to_sym
  model = query["model"]
  limit = [(query["limit"] || "50").to_i, 200].min

  store = Clacky::Billing::BillingStore.new
  sessions = store.session_summary(period: period, model: model, limit: limit)

  json_response(res, 200, {
    sessions: sessions,
    count: sessions.size
  })
end

#api_billing_summary(req, res) ⇒ Object

GET /api/billing/summary Returns billing summary for a time period Query params: period (day|week|month|year|all, default: month), model (optional)



3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
# File 'lib/clacky/server/http_server.rb', line 3272

def api_billing_summary(req, res)
  require_relative "../billing/billing_store"

  query  = URI.decode_www_form(req.query_string.to_s).to_h
  period = (query["period"] || "month").to_sym
  model  = query["model"]

  store   = Clacky::Billing::BillingStore.new
  summary = merged_billing_summary(store, period: period, model: model)

  json_response(res, 200, summary)
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.



2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
# File 'lib/clacky/server/http_server.rb', line 2587

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)
    # Install all brand skills in the background on first activation so
    # they are available immediately without manual user action.
    brand.sync_brand_skills_async!(install_new: true)
    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?,
      theme_color:   brand.theme_color
    })
  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.



3260
3261
3262
3263
# File 'lib/clacky/server/http_server.rb', line 3260

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.



3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
# File 'lib/clacky/server/http_server.rb', line 3177

def api_brand_skill_install(slug, req, res)
  brand = Clacky::BrandConfig.load

  # Free-mode: branded but not activated. Fall back to the public free
  # skills endpoint and install with encrypted: false. Paid (encrypted)
  # skills still require activation and will return 404 here.
  unless brand.activated?
    fetch_result = brand.fetch_free_skills!
    unless fetch_result[:success]
      json_response(res, 422, { ok: false, error: fetch_result[:error] })
      return
    end

    skill_info = fetch_result[:skills].find { |s| s["name"] == slug }
    unless skill_info
      json_response(res, 404, { ok: false, error: "Skill '#{slug}' is not a free skill — activate your license to access it." })
      return
    end

    result = brand.install_free_skill!(skill_info)
    if result[:success]
      @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
    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.message })
end

#api_brand_skills(res) ⇒ Object

POST /api/store/skills/:slug/install



3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
# File 'lib/clacky/server/http_server.rb', line 3108

def api_brand_skills(res)
  brand = Clacky::BrandConfig.load

  unless brand.activated?
    # Free-mode: branded but no license. Return the unencrypted skills
    # available to anonymous installs so the Brand Skills tab is not
    # empty and the user can install/use them without a serial number.
    # Each skill is tagged is_free=true so the UI can show a "Free" badge.
    result = brand.fetch_free_skills!

    if result[:success]
      free_skills = result[:skills].map { |s| s.merge("is_free" => true) }
      json_response(res, 200, {
        ok:                true,
        skills:            free_skills,
        free_mode:         true,
        paid_skills_count: result[:paid_skills_count].to_i
      })
    else
      json_response(res, 200, {
        ok:                true,
        skills:            [],
        free_mode:         true,
        paid_skills_count: 0,
        warning_code:      "remote_unavailable",
        warning:           result[:error] || "Could not reach the license server."
      })
    end
    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, meta|
      {
        "name"              => meta["name"] || name,
        "name_zh"           => meta["name_zh"].to_s,
        # Use locally cached description so it renders correctly offline
        "description"       => meta["description"].to_s,
        "description_zh"    => meta["description_zh"].to_s,
        "installed_version" => meta["version"],
        "needs_update"      => false
      }
    end
    json_response(res, 200, {
      ok:           true,
      skills:       local_skills,
      # warning_code lets the frontend render a localized message.
      # `warning` is kept for back-compat and as an English fallback.
      warning_code: "remote_unavailable",
      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


2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
# File 'lib/clacky/server/http_server.rb', line 2490

def api_brand_status(res)
  brand = Clacky::BrandConfig.load

  unless brand.branded?
    refresh_pending = false
    if brand.distribution_refresh_due?
      trigger_async_distribution_refresh!
      refresh_pending = true
    end

    json_response(res, 200, {
      branded: false,
      distribution_refresh_pending: refresh_pending
    })
    return
  end

  unless brand.activated?
    # Refresh public brand assets (logo, theme, homepage_url, support_*)
    # if due. This catches the common case of `install.sh --brand-name=X`
    # which writes only product_name + package_name — without this poll
    # the user would never see the brand's logo/theme until activation.
    # Completely asynchronous: we do NOT wait for the network round-trip.
    #
    # `distribution_refresh_pending` lets the Web UI know a refresh is
    # in flight, so it can re-poll /api/brand shortly and apply the
    # logo/theme without requiring the user to activate or refresh the
    # page first.
    refresh_pending = false
    if brand.distribution_refresh_due?
      trigger_async_distribution_refresh!
      refresh_pending = true
    end

    json_response(res, 200, {
      branded:                       true,
      needs_activation:              true,
      product_name:                  brand.product_name,
      homepage_url:                  brand.homepage_url,
      logo_url:                      brand.logo_url,
      theme_color:                   brand.theme_color,
      test_mode:                     @brand_test,
      distribution_refresh_pending:  refresh_pending
    })
    return
  end

  # Send heartbeat asynchronously if interval has elapsed (once per day).
  #
  # We must NOT block this HTTP response on the heartbeat call: a slow or
  # unreachable license server would otherwise stall the Web UI's first
  # paint for up to ~92s (2 hosts × 2 attempts × 23s timeout). The fresh
  # expires_at / last_heartbeat will be picked up on the next /api/brand/status
  # poll, which is sufficient for a once-per-day check.
  if brand.heartbeat_due?
    trigger_async_heartbeat!
  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
  warning_type = nil
  if brand.expired?
    warning      = "Your #{brand.product_name} license has expired. Please renew to continue."
    warning_type = "expired"
  elsif brand.grace_period_exceeded?
    warning      = "License server unreachable for more than 3 days. Please check your connection."
    warning_type = "unreachable"
  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."
      warning_type = "expiring"
    end
  end

  Clacky::Logger.debug("[Brand] api_brand_status: warning=#{warning.inspect} warning_type=#{warning_type.inspect}")

  json_response(res, 200, {
    branded:          true,
    needs_activation: false,
    product_name:     brand.product_name,
    homepage_url:     brand.homepage_url,
    logo_url:         brand.logo_url,
    warning:          warning,
    warning_type:     warning_type,
    test_mode:        @brand_test,
    user_licensed:    brand.user_licensed?,
    license_user_id:  brand.license_user_id
  })
end

#api_browse_dirs(req, res) ⇒ Object

GET /api/dirs?path=<absolute-or-~-path> Session-independent directory browser used by the New Session modal, where no session (and thus no working_dir) exists yet. Always operates in absolute mode. Lists directories only by default; pass files=true to include files (used by the @ mention file picker on the new-session page).



5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
# File 'lib/clacky/server/http_server.rb', line 5221

def api_browse_dirs(req, res)
  query = URI.decode_www_form(req.query_string.to_s).to_h
  rel   = query["path"].to_s.strip
  show_hidden = query["show_hidden"] == "true"
  include_files = query["files"] == "true"
  rel   = Dir.home if rel.empty?
  target = File.expand_path(rel.start_with?("~") ? rel.sub(/\A~/, Dir.home) : rel)

  # The requested directory may not exist yet (e.g. the default
  # ~/clacky_workspace before any session created it). Instead of 404,
  # walk up to the nearest existing ancestor so the picker stays usable.
  until Dir.exist?(target)
    parent = File.dirname(target)
    break if parent == target
    target = parent
  end
  return json_response(res, 404, { error: "Directory not found" }) unless Dir.exist?(target)

  entries = Dir.children(target).reject do |name|
    IGNORED_FILE_ENTRIES.include?(name) || (!show_hidden && name.start_with?("."))
  end
  items = entries.filter_map do |name|
    full = File.join(target, name)
    next unless File.exist?(full)
    is_dir = File.directory?(full)
    next if !include_files && !is_dir
    { name: name, path: full, type: is_dir ? "dir" : "file",
      size: is_dir ? nil : (File.size(full) rescue nil) }
  rescue StandardError
    nil
  end
  items.sort_by! { |it| [it[:type] == "dir" ? 0 : 1, it[:name].downcase] }

  json_response(res, 200, { root: target, path: target, parent: File.dirname(target), home: Dir.home, default: default_working_dir, entries: items, places: dir_picker_places })
rescue StandardError => e
  json_response(res, 500, { error: e.message })
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" }



1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
# File 'lib/clacky/server/http_server.rb', line 1611

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.message })
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.



1625
1626
1627
1628
1629
1630
# File 'lib/clacky/server/http_server.rb', line 1625

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.message })
end

#api_browser_status(res) ⇒ Object



1604
1605
1606
# File 'lib/clacky/server/http_server.rb', line 1604

def api_browser_status(res)
  json_response(res, 200, @browser_manager.status)
end

#api_browser_toggle(res) ⇒ Object

POST /api/browser/toggle



1633
1634
1635
1636
1637
1638
# File 'lib/clacky/server/http_server.rb', line 1633

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.message })
end

#api_change_session_working_dir(session_id, req, res) ⇒ Object



7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
# File 'lib/clacky/server/http_server.rb', line 7093

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
  expanded_dir = File.expand_path(new_dir)

  # Auto-create the directory if it doesn't exist yet.
  FileUtils.mkdir_p(expanded_dir)

  agent = nil
  @registry.with_session(session_id) { |s| agent = s[:agent] }
  
  # Change the agent's working directory
  agent.change_working_dir(expanded_dir)
  
  # Persist the change
  @session_manager.save(agent.to_session_data(updated_at: Time.now))
  
  # Broadcast update to all clients
  broadcast_session_update(session_id)
  
  json_response(res, 200, { ok: true, working_dir: expanded_dir })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_channel_process_messages(req, res) ⇒ Object

PATCH /api/channels/process_messages Body: { process_messages: true|false } Global toggle for tool-call process messages (interim narration and file/shell previews) across all IM channels. Hot-applies without restarting adapters.



4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
# File 'lib/clacky/server/http_server.rb', line 4545

def api_channel_process_messages(req, res)
  enabled = parse_json_body(req)["process_messages"] == true
  config  = Clacky::ChannelConfig.load

  config.set_process_messages(enabled)
  config.save
  @channel_manager.update_config(config)

  json_response(res, 200, { ok: true, process_messages: config.process_messages_enabled? })
rescue StandardError => e
  json_response(res, 422, { ok: false, error: e.message })
end

#api_channel_status_messages(req, res) ⇒ Object

PATCH /api/channels/status_messages Body: { status_messages: true|false } Global toggle for process-status messages ("Thinking...", "Done" summary) across all IM channels. Hot-applies without restarting adapters.



4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
# File 'lib/clacky/server/http_server.rb', line 4527

def api_channel_status_messages(req, res)
  enabled = parse_json_body(req)["status_messages"] == true
  config  = Clacky::ChannelConfig.load

  config.set_status_messages(enabled)
  config.save
  @channel_manager.update_config(config)

  json_response(res, 200, { ok: true, status_messages: config.status_messages_enabled? })
rescue StandardError => e
  json_response(res, 422, { ok: false, error: e.message })
end

#api_create_cron_task(req, res) ⇒ Object

POST /api/cron-tasks — create task file + schedule in one step Body: { name, content, cron, enabled? }



4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
# File 'lib/clacky/server/http_server.rb', line 4728

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_project(req, res) ⇒ Object

POST /api/projects — create a new project Body: { name:, description:?, color:?, icon:?, working_dir:? }



6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
# File 'lib/clacky/server/http_server.rb', line 6742

def api_create_project(req, res)
  body        = parse_json_body(req)
  name        = body["name"].to_s.strip
  return json_response(res, 400, { error: "name is required" }) if name.empty?

  description = body["description"]
  color       = body["color"]
  icon        = body["icon"]
  working_dir = body["working_dir"].to_s.strip
  working_dir = working_dir.empty? ? nil : File.expand_path(working_dir)

  project = @project_manager.create(name: name, description: description, color: color, icon: icon, working_dir: working_dir)
  json_response(res, 201, { project: project })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_create_session(req, res) ⇒ Object



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'lib/clacky/server/http_server.rb', line 967

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-manager).
  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.expand_path(raw_dir)

  # Optional model override — passed as a stable model id (matches the
  # id returned by GET /api/config). Name-based override was removed:
  # a bare model name can't disambiguate between entries from different
  # providers (e.g. "deepseek-v4-pro" on DeepSeek direct vs its dsk-*
  # alias on OpenClacky/Bedrock), and mutating current_model["model"]
  # kept the wrong api_key / base_url / api format, producing
  # "unknown model" errors at the provider.
  model_id_override = body["model_id"].to_s.strip
  model_id_override = nil if model_id_override.empty?

  if model_id_override && !@agent_config.models.any? { |m| m["id"] == model_id_override }
    return json_response(res, 400, { error: "Model not found in configuration" })
  end

  # Optional project association — validate the project exists if provided
  project_id_override = body["project_id"].to_s.strip
  project_id_override = nil if project_id_override.empty?
  if project_id_override && @project_manager.find(project_id_override).nil?
    return json_response(res, 400, { error: "Project not found" })
  end

  # If no explicit working_dir was given but the project has one, inherit it.
  if raw_dir.empty? && project_id_override
    project = @project_manager.find(project_id_override)
    if project && project[:working_dir].to_s.strip != ""
      working_dir = File.expand_path(project[:working_dir])
    end
  end

  # 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_id: model_id_override)

  # Persist project_id into the session file right away if provided
  if project_id_override
    agent = nil
    @registry.with_session(session_id) { |s| agent = s[:agent] }
    if agent
      agent.project_id = project_id_override
      @session_manager.save(agent.to_session_data(updated_at: Time.now))
    end
  end

  broadcast_session_update(session_id)
  summary = @registry.session_summary(session_id)
  json_response(res, 201, { session: summary })
end

#api_delete_brand_skill(slug, res) ⇒ Object

DELETE /api/brand/skills/:slug Uninstalls a brand skill by removing its files and metadata.



3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
# File 'lib/clacky/server/http_server.rb', line 3242

def api_delete_brand_skill(slug, res)
  brand = Clacky::BrandConfig.load
  installed = brand.installed_brand_skills
  unless installed.key?(slug)
    json_response(res, 404, { ok: false, error: "Brand skill '#{slug}' is not installed" })
    return
  end

  brand.delete_brand_skill!(slug)
  @skill_loader = Clacky::SkillLoader.new(working_dir: nil, brand_config: brand)
  json_response(res, 200, { ok: true })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_delete_channel(platform, res) ⇒ Object

DELETE /api/channels/:platform Disables the platform (keeps credentials, sets enabled: false).



4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
# File 'lib/clacky/server/http_server.rb', line 4509

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.message })
end

#api_delete_cron_task(name, res) ⇒ Object

DELETE /api/cron-tasks/:name — remove task file + schedule



4767
4768
4769
4770
4771
4772
4773
# File 'lib/clacky/server/http_server.rb', line 4767

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_model(id, res) ⇒ Object

DELETE /api/config/models/:id



6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
# File 'lib/clacky/server/http_server.rb', line 6569

def api_delete_model(id, res)
  models = @agent_config.models
  return json_response(res, 404, { error: "model not found" }) unless models.any? { |m| m["id"] == id }
  return json_response(res, 422, { error: "cannot delete the last model" }) if models.length <= 1

  index = models.find_index { |m| m["id"] == id }
  removed = models.delete_at(index)

  # Re-anchor current_* if we just deleted the active model.
  if @agent_config.current_model_id == removed["id"]
    new_default = models.find { |m| m["type"] == "default" } || models.first
    # If the removed model was the default, promote the new current
    # model so the config always has exactly one default entry.
    if removed["type"] == "default" && new_default && new_default["type"] != "default"
      new_default["type"] = "default"
    end
    @agent_config.current_model_id    = new_default["id"]
    @agent_config.current_model_index = models.find_index { |m| m["id"] == new_default["id"] } || 0
  elsif @agent_config.current_model_index >= models.length
    @agent_config.current_model_index = models.length - 1
  end

  @agent_config.save
  json_response(res, 200, { ok: true })
rescue => e
  json_response(res, 422, { error: e.message })
end

#api_delete_project(project_id, res) ⇒ Object

DELETE /api/projects/:id — delete a project and all its sessions (soft-delete to trash)



6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
# File 'lib/clacky/server/http_server.rb', line 6790

def api_delete_project(project_id, res)
  return json_response(res, 404, { error: "Project not found" }) unless @project_manager.find(project_id)

  @project_manager.delete(project_id)
  _delete_project_sessions(project_id)

  json_response(res, 200, { ok: true })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_delete_project_sessions(project_id, res) ⇒ Object

DELETE /api/projects/:id/sessions - delete all sessions in a project but keep the project



6802
6803
6804
6805
6806
6807
6808
6809
# File 'lib/clacky/server/http_server.rb', line 6802

def api_delete_project_sessions(project_id, res)
  return json_response(res, 404, { error: "Project not found" }) unless @project_manager.find(project_id)

  deleted = _delete_project_sessions(project_id)
  json_response(res, 200, { ok: true, deleted: deleted })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_delete_session(session_id, res) ⇒ Object



7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
# File 'lib/clacky/server/http_server.rb', line 7132

def api_delete_session(session_id, res)
  # A session exists if it's either in the runtime registry OR on disk.
  # Old sessions that were never restored into memory this server run
  # (e.g. shown via "load more" in the WebUI list) are disk-only — we
  # must still be able to delete them. Previously this endpoint only
  # consulted @registry and returned 404 for disk-only sessions,
  # causing the "can't delete old sessions" bug.
  in_registry = @registry.exist?(session_id)
  on_disk     = !@session_manager.load(session_id).nil?

  unless in_registry || on_disk
    return json_response(res, 404, { error: "Session not found" })
  end

  # Registry delete is best-effort — only meaningful when the session
  # is actually live (cancels idle timer, interrupts the agent thread).
  # For disk-only sessions this is a no-op and returns false, which is
  # fine and no longer blocks the disk cleanup below.
  @registry.delete(session_id) if in_registry

  # Soft-delete: move session to trash instead of permanently destroying it.
  @session_manager.soft_delete(session_id) if on_disk

  # Notify any still-connected clients (mainly matters when the
  # session was live, but harmless otherwise).
  broadcast(session_id, { type: "session_deleted", session_id: session_id })
  unsubscribe_all(session_id)

  json_response(res, 200, { ok: true })
end

#api_dirs_mkdir(req, res) ⇒ Object

POST /api/dirs/mkdir Body: { parent: "/abs/parent", name: "New Folder" }



5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
# File 'lib/clacky/server/http_server.rb', line 5273

def api_dirs_mkdir(req, res)
  body   = parse_json_body(req)
  parent = body["parent"].to_s
  name   = body["name"].to_s.strip

  return json_response(res, 422, { error: "parent must be an absolute path" }) unless parent.start_with?("/")
  return json_response(res, 422, { error: "name is invalid" }) unless picker_valid_name?(name)

  parent = File.expand_path(parent)
  return json_response(res, 404, { error: "Parent directory not found" }) unless Dir.exist?(parent)

  target = File.join(parent, name)
  return json_response(res, 422, { error: "Already exists" }) if File.exist?(target)

  FileUtils.mkdir_p(target)
  json_response(res, 200, { ok: true, path: target, name: name })
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_exchange_rate(req, res) ⇒ Object

GET /api/exchange-rate?from=USD&to=CNY Fetches the latest exchange rate on demand. The browser still owns the saved preference in localStorage; this API is only a lightweight proxy that avoids CORS issues and normalizes provider responses.



1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/clacky/server/http_server.rb', line 1064

def api_exchange_rate(req, res)
  query = URI.decode_www_form(req.query_string.to_s).to_h
  from  = normalize_currency_code(query["from"], fallback: "USD")
  to    = normalize_currency_code(query["to"], fallback: "CNY")

  unless from && to
    return json_response(res, 400, { error: "from and to must be 3-letter currency codes" })
  end

  data = fetch_exchange_rate(from, to)
  json_response(res, 200, data)
rescue StandardError => e
  Clacky::Logger.warn("[ExchangeRate] failed: #{e.class}: #{e.message}")
  json_response(res, 502, { error: "Failed to fetch exchange rate" })
end

#api_export_session(session_id, res) ⇒ Object

Export a session bundle as a .zip download containing:

- session.json          (always)
- chunk-*.md            (0..N archived conversation chunks)
- logs/clacky-YYYY-MM-DD.log  (today's logger file, if present)

Useful for debugging — user clicks "download" in the WebUI status bar and we can ask them to attach the zip to a bug report.



7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
# File 'lib/clacky/server/http_server.rb', line 7169

def api_export_session(session_id, res)
  bundle = @session_manager.files_for(session_id)
  unless bundle
    return json_response(res, 404, { error: "Session not found" })
  end

  require "zip"

  short_id = bundle[:session][:session_id].to_s[0..7]
  # Build the zip entirely in memory — session files are small (< few MB).
  buffer = Zip::OutputStream.write_buffer do |zos|
    zos.put_next_entry("session.json")
    zos.write(File.binread(bundle[:json_path]))

    bundle[:chunks].each do |chunk_path|
      # Preserve original chunk filename so the ordering (chunk-1.md, chunk-2.md, ...) is clear.
      zos.put_next_entry(File.basename(chunk_path))
      zos.write(File.binread(chunk_path))
    end

    log_path = Clacky::Logger.current_log_file
    if log_path && File.exist?(log_path)
      zos.put_next_entry("logs/#{File.basename(log_path)}")
      zos.write(File.binread(log_path))
    end
  end
  buffer.rewind
  data = buffer.read

  filename = "clacky-session-#{short_id}.zip"
  res.status = 200
  res.content_type = "application/zip"
  res["Content-Disposition"] = %(attachment; filename="#{filename}")
  res["Access-Control-Allow-Origin"] = "*"
  # Force a fresh copy each time — debugging sessions get new chunks over time.
  res["Cache-Control"] = "no-store"
  res.body = data
rescue => e
  Clacky::Logger.error("Session export failed: #{e.message}") if defined?(Clacky::Logger)
  json_response(res, 500, { error: "Export failed: #{e.message}" })
end

#api_file_action(req, res) ⇒ Object

POST /api/file-action Unified file action endpoint — open locally or download. Body: { path: String, action: "open" | "download" | "save" } open: opens the file with the OS default handler (local deployments). download: returns the file as a download (remote deployments). save: writes content back to the file. Body must include { content: String }.



4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
# File 'lib/clacky/server/http_server.rb', line 4347

def api_file_action(req, res)
  body = parse_json_body(req)
  path = body["path"]
  action = body["action"] || "open"

  return json_response(res, 400, { error: "path is required" }) unless path && !path.empty?

  # Path arrives already percent-decoded by the click handler; normalize
  # Windows drive letters (WSL) BEFORE expand_path or the drive is treated
  # as relative and corrupted. No-op on macOS/Linux.
  linux_path = Utils::EnvironmentDetector.win_to_linux_path(path)
  linux_path = File.expand_path(linux_path)

  # For save action, the file may not exist yet — skip the existence check.
  unless action == "save"
    return json_response(res, 404, { error: "file not found" }) unless File.exist?(linux_path)
  end

  case action
  when "open"
    result = Utils::EnvironmentDetector.open_file(linux_path)
    return json_response(res, 501, { error: "unsupported OS" }) if result.nil?
    json_response(res, 200, { ok: true })
  when "reveal"
    Utils::EnvironmentDetector.reveal_file(linux_path)
    json_response(res, 200, { ok: true })
  when "download"
    serve_file_download(res, linux_path)
  when "display-path"
    display = Utils::EnvironmentDetector.linux_to_win_path(linux_path)
    json_response(res, 200, { ok: true, path: display })
  when "save"
    content = body["content"]
    return json_response(res, 400, { error: "content is required" }) if content.nil?
    FileUtils.mkdir_p(File.dirname(linux_path))
    File.write(linux_path, content, encoding: "UTF-8")
    json_response(res, 200, { ok: true })
  else
    json_response(res, 400, { error: "invalid action. Must be 'open', 'reveal', 'download', 'display-path' or 'save'" })
  end
rescue => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_fork_session(session_id, req, res) ⇒ Object



7123
7124
7125
7126
7127
7128
7129
7130
# File 'lib/clacky/server/http_server.rb', line 7123

def api_fork_session(session_id, req, res)
  fork_data = @session_manager.fork(session_id)
  return json_response(res, 404, { error: "Session not found" }) unless fork_data

  fork_id = fork_data[:session_id]
  broadcast_session_update(fork_id)
  json_response(res, 201, { session: @registry.snapshot(fork_id) })
end

#api_get_config(req, res) ⇒ Object

GET /api/config — return current model configurations



6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
# File 'lib/clacky/server/http_server.rb', line 6115

def api_get_config(req, res)
  models = @agent_config.models.map.with_index do |m, i|
    {
      id:               m["id"],   # Stable runtime id — use this for switching
      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,
      api_format:       m["api_format"],
      provider_id:      m["provider_id"],
      capabilities:     m["capabilities"],
      remark:           m["remark"],
      type:             m["type"]
    }
  end
  # Filter out auto-injected models (lite, derived media) AND media
  # entries (image/video/audio/ocr) — those are managed via the dedicated
  # media-config UI, not the chat-model card list.
  models.reject! do |m|
    raw = @agent_config.models[m[:index]]
    raw["auto_injected"] ||
      Clacky::Providers::MEDIA_KINDS.include?(raw["type"].to_s) ||
      raw["type"].to_s == "ocr"
  end
  # Capabilities follow the model the *session* is actually running on
  # (it may differ from the global default after a per-session switch).
  query   = URI.decode_www_form(req.query_string.to_s).to_h
  cfg     = config_for_session(query["session_id"]) || @agent_config
  json_response(res, 200, {
    models: models,
    current_index: @agent_config.current_model_index,
    current_id: @agent_config.current_model&.dig("id"),
    media_capabilities: media_capabilities_payload(cfg)
  })
end

#api_get_media_config(res) ⇒ Object

GET /api/config/media Used by the Settings UI to render the tri-state media controls. Per-kind payload mirrors AgentConfig#media_state.



1944
1945
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
# File 'lib/clacky/server/http_server.rb', line 1944

def api_get_media_config(res)
  out = {}
  Clacky::Providers::MEDIA_KINDS.each do |t|
    state = @agent_config.media_state(t)
    entry = @agent_config.find_model_by_type(t)
    out[t] = {
      source:     state["source"],
      model:      state["model"],
      base_url:   state["base_url"],
      api_key_masked: entry ? mask_api_key(entry["api_key"]) : nil,
      provider:   state["provider"],
      available:  state["available"],
      aliases:    state["aliases"] || {},
      stale:      state["stale"] || false,
      requested_model: state["requested_model"],
      configured: state["configured"]
    }
    if entry && entry["base_url"] && state["source"] != "custom"
      out[t][:saved_custom] = { model: entry["model"], base_url: entry["base_url"] }
    end
  end

  # Surface what the current default model can offer, even when the
  # user is currently in "off" — the UI uses this to render the
  # auto-mode preview ("Auto would use X").
  default = @agent_config.find_model_by_type("default")
  provider_id = default && @agent_config.provider_id_for(default)
  defaults = {}
  Clacky::Providers::MEDIA_KINDS.each do |t|
    defaults[t] = {
      provider:  provider_id,
      model:     provider_id ? Clacky::Providers.default_media_model(provider_id, t) : nil,
      available: provider_id ? Clacky::Providers.media_models(provider_id, t) : [],
      aliases:   provider_id ? Clacky::Providers.media_model_aliases(provider_id, t) : {}
    }
  end

  json_response(res, 200, { media: out, default_provider: defaults })
end

#api_get_ocr_config(res) ⇒ Object

GET /api/config/ocr Returns the OCR sidecar state for the Settings UI. Mirrors media_state in shape so the UI can render OCR with the same row component.



2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
# File 'lib/clacky/server/http_server.rb', line 2154

def api_get_ocr_config(res)
  state = @agent_config.ocr_state
  entry = @agent_config.find_model_by_type("ocr")

  out = {
    source:         state["source"],
    model:          state["model"],
    base_url:       state["base_url"],
    api_key_masked: entry ? mask_api_key(entry["api_key"]) : nil,
    provider:       state["provider"],
    available:      state["available"],
    stale:          state["stale"] || false,
    requested_model: state["requested_model"],
    configured:     state["configured"],
    primary:        state["primary"] || false
  }
  if entry && entry["base_url"] && state["source"] != "custom"
    out[:saved_custom] = { model: entry["model"], base_url: entry["base_url"] }
  end

  # Auto-mode preview: surface what the OCR sidecar *would* be if the
  # user flipped to "auto" — derived from the same provider as the
  # current default model.
  default = @agent_config.find_model_by_type("default")
  provider_id = default && @agent_config.provider_id_for(default)
  default_preview = {
    provider:  provider_id,
    model:     provider_id ? Clacky::Providers.default_ocr_model(provider_id) : nil,
    available: provider_id ? Clacky::Providers.ocr_models(provider_id) : []
  }

  json_response(res, 200, { ocr: out, default_provider: default_preview })
end

#api_get_search_config(res) ⇒ Object

GET /api/config/search Lists installed searchers so the UI can offer whatever the user dropped into ~/.clacky/searchers/, not just the bundled ones.



2221
2222
2223
2224
2225
2226
2227
2228
2229
# File 'lib/clacky/server/http_server.rb', line 2221

def api_get_search_config(res)
  config = Clacky::SearchConfig.load
  json_response(res, 200, {
    ok: true,
    provider: config["provider"],
    key_masked: config["key"].empty? ? nil : mask_api_key(config["key"]),
    available: Clacky::Utils::SearcherManager.available
  })
end

#api_get_session(session_id, res) ⇒ Object

GET /api/sessions/:id — fetch a single session by id (memory + disk merged). Used by the frontend Router when navigating to a session that isn't in the paged sidebar list (search results, URL deep links, share links, browser back/forward, external notifications, etc.).



961
962
963
964
965
# File 'lib/clacky/server/http_server.rb', line 961

def api_get_session(session_id, res)
  row = @registry.snapshot(session_id)
  return json_response(res, 404, { error: "Session not found" }) unless row
  json_response(res, 200, { session: row })
end

#api_get_settings(res) ⇒ Object

GET /api/config/settings — return advanced settings



6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
# File 'lib/clacky/server/http_server.rb', line 6247

def api_get_settings(res)
  json_response(res, 200, {
    ok: true,
    enable_compression: @agent_config.enable_compression,
    enable_idle_compression: @agent_config.enable_idle_compression,
    enable_prompt_caching: @agent_config.enable_prompt_caching,
    memory_update_enabled: @agent_config.memory_update_enabled,
    proxy_url: @agent_config.proxy_url.to_s,
    clacky_license_server: effective_clacky_license_server
  })
end

#api_get_version(res) ⇒ Object

GET /api/version Returns current version and latest version from RubyGems (cached for 1 hour).



3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
# File 'lib/clacky/server/http_server.rb', line 3506

def api_get_version(res)
  current = Clacky::VERSION
  latest  = fetch_latest_version_cached
  brand   = Clacky::BrandConfig.load
  cli_cmd = brand.branded? && brand.package_name && !brand.package_name.empty? ? brand.package_name : "openclacky"
  json_response(res, 200, {
    current:      current,
    latest:       latest,
    needs_update: latest ? version_older?(current, latest) : false,
    launcher:     ENV["CLACKY_LAUNCHER"] || "cli",
    cli_command:  cli_cmd
  })
end

#api_group_history(chat_id, res) ⇒ Object



4313
4314
4315
4316
4317
4318
# File 'lib/clacky/server/http_server.rb', line 4313

def api_group_history(chat_id, res)
  messages = @channel_manager.group_history(chat_id)
  json_response(res, 200, { chat_id: chat_id, messages: messages })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_internal_ocr_image(req, res) ⇒ Object

POST /api/internal/ocr-image Internal endpoint used by parser scripts (e.g. pdf_parser_vlm.py) to transcribe a single image via the configured OCR sidecar. Localhost- only by virtue of the standard auth path: when the server binds to 127.0.0.1 (@localhost_only), check_access_key returns true without requiring a token, so parsers running on the same host can call this endpoint with no extra wiring.

Request: multipart/form-data with field "image" (binary), optional "prompt" OR JSON body { "data_url": "data:image/png;base64,...", "prompt": "..." } Response: { ok: true, text: "..." } or { ok: false, message: "..." }



2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
# File 'lib/clacky/server/http_server.rb', line 2303

def api_internal_ocr_image(req, res)
  entry = @agent_config.find_model_by_type("ocr")
  unless entry
    return json_response(res, 503, { ok: false, message: "OCR sidecar not configured" })
  end

  prompt   = nil
  data_url = nil
  bytes    = nil
  mime     = "image/png"

  ctype = req.content_type.to_s
  if ctype.start_with?("multipart/form-data")
    parts = req.query
    if (img = parts["image"])
      bytes = img.respond_to?(:read) ? img.read : img.to_s
      mime  = (img.respond_to?(:[]) ? img["content-type"].to_s : nil)
      mime  = "image/png" if mime.nil? || mime.empty?
    end
    prompt = parts["prompt"].to_s if parts["prompt"]
  else
    body = parse_json_body(req) || {}
    data_url = body["data_url"].to_s
    prompt   = body["prompt"].to_s if body["prompt"]
  end

  image =
    if bytes && !bytes.empty?
      { bytes: bytes, mime_type: mime }
    elsif data_url && !data_url.empty?
      { data_url: data_url }
    else
      return json_response(res, 400, { ok: false, message: "image or data_url required" })
    end

  text = Clacky::Vision::Resolver.new(entry).describe(image, prompt: prompt)
  if text && !text.strip.empty?
    json_response(res, 200, { ok: true, text: text })
  else
    json_response(res, 200, { ok: false, message: "OCR returned empty result" })
  end
rescue => e
  json_response(res, 500, { ok: false, message: e.message })
end

#api_list_agents(res) ⇒ Object

GET /api/agents — list all available agent profiles (default + user override + ext). Each entry carries { id, title, title_zh, description, description_zh, source, order, layer, author }. Extensions can supply title_zh / description_zh / author in their ext.yml so the New Session cards read naturally and credit their author. Third-party extension agents are ordered by most-recently-used (derived from session history) so the ones the user actually uses float to the front of that group.



4843
4844
4845
4846
4847
# File 'lib/clacky/server/http_server.rb', line 4843

def api_list_agents(res)
  recency = agent_last_used_recency
  agents = Clacky::AgentProfile.all(recency: recency)
  json_response(res, 200, { agents: agents })
end

#api_list_channel_users(platform, res) ⇒ Object

GET /api/channels/:platform/users Returns the list of known user IDs for the given platform. These are users who have sent at least one message to the bot in this server session.

For Weixin: returns users with a cached context_token (required for proactive messaging). For Feishu / WeCom: returns user IDs extracted from channel session bindings.

Response:

200 { users: ["uid1", "uid2", ...] }


4305
4306
4307
4308
4309
4310
4311
# File 'lib/clacky/server/http_server.rb', line 4305

def api_list_channel_users(platform, res)
  platform = platform.to_sym
  users    = @channel_manager.known_users(platform)
  json_response(res, 200, { platform: platform, users: users })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_list_channels(res) ⇒ Object



3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
# File 'lib/clacky/server/http_server.rb', line 3955

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, status_messages: config.status_messages_enabled?, process_messages: config.process_messages_enabled? })
end

#api_list_cron_tasks(res) ⇒ Object

GET /api/cron-tasks



4722
4723
4724
# File 'lib/clacky/server/http_server.rb', line 4722

def api_list_cron_tasks(res)
  json_response(res, 200, { cron_tasks: @scheduler.list_cron_tasks })
end

#api_list_projects(res) ⇒ Object

GET /api/projects — list all projects



6735
6736
6737
6738
# File 'lib/clacky/server/http_server.rb', line 6735

def api_list_projects(res)
  projects = @project_manager.all
  json_response(res, 200, { projects: projects })
end

#api_list_providers(res) ⇒ Object

GET /api/providers — return built-in provider presets for quick setup



6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
# File 'lib/clacky/server/http_server.rb', line 6678

def api_list_providers(res)
  providers = Clacky::Providers::PRESETS.map do |id, preset|
    {
      id:                id,
      name:              preset["name"],
      # Optional i18n key for the display name (localised per UI language);
      # frontend falls back to `name` when absent or untranslated.
      name_key:          preset["name_key"],
      base_url:          preset["base_url"],
      default_model:     preset["default_model"],
      # Preset transport protocol; the frontend shows this as the
      # "auto" resolution target in the API format dropdown (issue #466).
      api:               preset["api"],
      models:            preset["models"] || [],
      # Frontend uses this to render a Base URL dropdown (regional /
      # billing-plan variants) when present. Absent for single-endpoint
      # providers — UI renders a plain text input in that case.
      endpoint_variants: preset["endpoint_variants"],
      website_url:       preset["website_url"]
    }
  end
  json_response(res, 200, { providers: providers })
end

#api_list_sessions(req, res) ⇒ Object

── REST API ──────────────────────────────────────────────────────────────



927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
# File 'lib/clacky/server/http_server.rb', line 927

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 : 15 }, 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 }
  q_scope      = query["q_scope"].to_s.strip.then { |v| %w[name content].include?(v) ? v : "name" }
  date         = query["date"].to_s.strip.then    { |v| v.empty? ? nil : v }
  type         = query["type"].to_s.strip.then    { |v| v.empty? ? nil : v }
  exclude_type = query["exclude_type"].to_s.split(",").map(&:strip).reject(&:empty?).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 }

  # Paginated "load more" (before set) only fills the regular session list;
  # project sessions already arrive via the first-page WS payload and render
  # in the project section, so they must not eat into this page's quota.
  # Search (no before) keeps the original semantics: without a type filter
  # it may still match project sessions.
  exclude_project = before ? true : !!type
  sessions = @registry.list(limit: limit + 1, before: before, q: q, q_scope: q_scope, date: date, type: type, exclude_type: exclude_type, exclude_project: exclude_project)

  pinned_part, non_pinned_part = sessions.partition { |s| s[:pinned] }
  has_more = non_pinned_part.size > limit
  non_pinned_part = non_pinned_part.first(limit)
  sessions = pinned_part + non_pinned_part

  json_response(res, 200, { sessions: sessions, has_more: has_more,
                            groups: @registry.group_stats_all })
end

#api_list_skills(res) ⇒ Object

GET /api/skills — list all loaded skills with metadata



4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
# File 'lib/clacky/server/http_server.rb', line 4797

def api_list_skills(res)
  @skill_loader.load_all  # refresh from disk on each request
  upload_meta = Clacky::BrandConfig.load_upload_meta
  shadowed    = @skill_loader.shadowed_by_local

  skills = @skill_loader.all_skills.reject(&:brand_skill).reject do |skill|
    # Third-party extension skills (installed/local) are managed from the
    # extension panel, not the skills panel.
    @skill_loader.loaded_from[skill.identifier] == :extension
  end.map do |skill|
    source = @skill_loader.loaded_from[skill.identifier]
    meta   = upload_meta[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,
      always_show:       skill.always_show,
      enabled:           !skill.disabled?,
      invalid:           skill.invalid?,
      warnings:          skill.warnings,
      platform_version:  meta["platform_version"],
      uploaded_at:       meta["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_mcp_call(name, req, res) ⇒ Object

POST /api/mcp/:name/call body: { tool: "...", arguments: ... } Forwards a tools/call to the configured MCP server and returns its raw result. Subagents call this from their shell tool via curl — there is no Ruby-side bridge tool anymore.



4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
# File 'lib/clacky/server/http_server.rb', line 4063

def api_mcp_call(name, req, res)
  unless mcp_registry.configured?(name)
    json_response(res, 404, { ok: false, error: "MCP server '#{name}' not found in mcp.json" })
    return
  end

  body = parse_json_body(req) || {}
  tool = body["tool"] || body[:tool]
  arguments = body["arguments"] || body[:arguments] || {}

  if tool.nil? || tool.to_s.strip.empty?
    json_response(res, 400, { ok: false, error: "missing required field: tool" })
    return
  end

  result = mcp_registry.call_tool(name, tool, arguments)
  json_response(res, 200, { ok: true, result: result })
rescue Clacky::Mcp::Client::McpError, Clacky::Mcp::Client::TransportError => e
  json_response(res, 502, { ok: false, error: e.message })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_mcp_create(req, res) ⇒ Object

POST /api/mcp { name, command, args, env{}, cwd?, description? }



4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
# File 'lib/clacky/server/http_server.rb', line 4148

def api_mcp_create(req, res)
  return unless mcp_localhost_only(req, res)

  body = parse_json_body(req)
  name, spec, err = mcp_validate_spec(body)
  if err
    json_response(res, 400, { ok: false, error: err })
    return
  end

  data = mcp_load_raw_config
  if data["mcpServers"].key?(name)
    json_response(res, 409, { ok: false, error: "MCP server '#{name}' already exists. Use PUT to update." })
    return
  end

  data["mcpServers"][name] = spec
  mcp_write_raw_config(data)
  @mcp_registry_mutex.synchronize { @mcp_registry&.reload }
  json_response(res, 200, { ok: true, name: name, config_path: mcp_config_path })
end

#api_mcp_delete(name, req, res) ⇒ Object

DELETE /api/mcp/:name



4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
# File 'lib/clacky/server/http_server.rb', line 4195

def api_mcp_delete(name, req, res)
  return unless mcp_localhost_only(req, res)

  data = mcp_load_raw_config
  unless data["mcpServers"].key?(name)
    json_response(res, 404, { ok: false, error: "MCP server '#{name}' not found" })
    return
  end

  data["mcpServers"].delete(name)
  mcp_write_raw_config(data)
  @mcp_registry_mutex.synchronize { @mcp_registry&.reload }
  json_response(res, 200, { ok: true, name: name })
end

#api_mcp_list(res) ⇒ Object

GET /api/mcp Lists configured MCP servers without spawning any subprocess. Honors both ~/.clacky/mcp.json (global) and project-level overrides.



3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
# File 'lib/clacky/server/http_server.rb', line 3976

def api_mcp_list(res)
  data = mcp_load_raw_config
  servers = (data["mcpServers"] || {}).map do |name, spec|
    next nil unless spec.is_a?(Hash)

    type = (spec["type"] || (spec["url"] ? "http" : "stdio")).to_s
    {
      name:        name.to_s,
      type:        type,
      description: spec["description"] || "",
      command:     spec["command"],
      args:        Array(spec["args"]),
      url:         spec["url"],
      disabled:    spec["disabled"] == true,
      has_env:     spec["env"].is_a?(Hash) && !spec["env"].empty?,
      has_headers: spec["headers"].is_a?(Hash) && !spec["headers"].empty?,
    }
  end.compact

  json_response(res, 200, {
    configured:    !servers.empty?,
    config_path:   mcp_config_path,
    config_exists: File.exist?(mcp_config_path),
    servers:       servers,
  })
end

#api_mcp_probe(name, res) ⇒ Object

POST /api/mcp/:name/probe Spawns the MCP server briefly to fetch its tool catalog, then shuts it down. Used by the WebUI to display each server's tool list on demand. No state survives the request — the next agent run does its own lazy spawn.



4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
# File 'lib/clacky/server/http_server.rb', line 4007

def api_mcp_probe(name, res)
  registry = Clacky::Mcp::Registry.new(idle_timeout: 0)
  unless registry.configured?(name)
    json_response(res, 404, { ok: false, error: "MCP server '#{name}' not found in mcp.json" })
    return
  end

  tools = registry.tool_definitions(name).map do |defn|
    fn = defn[:function] || defn["function"] || {}
    {
      name:         fn[:name] || fn["name"],
      description:  fn[:description] || fn["description"] || "",
      input_schema: fn[:parameters] || fn["parameters"] || {},
    }
  end

  json_response(res, 200, { ok: true, name: name, tools: tools, tool_count: tools.length })
rescue Clacky::Mcp::Client::McpError, Clacky::Mcp::Client::TransportError => e
  json_response(res, 502, { ok: false, error: e.message })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
ensure
  registry&.shutdown
end

#api_mcp_toggle(name, req, res) ⇒ Object

PATCH /api/mcp/:name/enabled body: { enabled: true|false }



4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
# File 'lib/clacky/server/http_server.rb', line 4211

def api_mcp_toggle(name, req, res)
  return unless mcp_localhost_only(req, res)

  body = parse_json_body(req) || {}
  enabled = body["enabled"]
  if enabled.nil? || ![true, false].include?(enabled)
    json_response(res, 400, { ok: false, error: "enabled (boolean) is required" })
    return
  end

  data = mcp_load_raw_config
  spec = data["mcpServers"][name]
  unless spec.is_a?(Hash)
    json_response(res, 404, { ok: false, error: "MCP server '#{name}' not found" })
    return
  end

  if enabled
    spec.delete("disabled")
  else
    spec["disabled"] = true
  end
  mcp_write_raw_config(data)

  @mcp_registry_mutex.synchronize { @mcp_registry&.reload }

  json_response(res, 200, { ok: true, name: name, disabled: spec["disabled"] == true })
end

#api_mcp_tools(name, res) ⇒ Object

GET /api/mcp/:name/tools Returns the live tool catalog for an MCP server, using the process-wide registry. The first call cold-starts the server; later calls hit cache. Subagents use this as a discovery endpoint, replacing the deleted mcp_call tool's hidden tool list.



4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
# File 'lib/clacky/server/http_server.rb', line 4037

def api_mcp_tools(name, res)
  unless mcp_registry.configured?(name)
    json_response(res, 404, { ok: false, error: "MCP server '#{name}' not found in mcp.json" })
    return
  end

  tools = mcp_registry.tool_definitions(name).map do |defn|
    fn = defn[:function] || defn["function"] || {}
    {
      name:         fn[:name] || fn["name"],
      description:  fn[:description] || fn["description"] || "",
      input_schema: fn[:parameters] || fn["parameters"] || {},
    }
  end

  json_response(res, 200, { ok: true, name: name, tools: tools, tool_count: tools.length })
rescue Clacky::Mcp::Client::McpError, Clacky::Mcp::Client::TransportError => e
  json_response(res, 502, { ok: false, error: e.message })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_mcp_update(name, req, res) ⇒ Object

PUT /api/mcp/:name { command, args, env{}, cwd?, description? } Replaces the entire spec. Path :name wins over body name.



4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
# File 'lib/clacky/server/http_server.rb', line 4172

def api_mcp_update(name, req, res)
  return unless mcp_localhost_only(req, res)

  body = parse_json_body(req).merge("name" => name)
  _, spec, err = mcp_validate_spec(body)
  if err
    json_response(res, 400, { ok: false, error: err })
    return
  end

  data = mcp_load_raw_config
  unless data["mcpServers"].key?(name)
    json_response(res, 404, { ok: false, error: "MCP server '#{name}' not found" })
    return
  end

  data["mcpServers"][name] = spec
  mcp_write_raw_config(data)
  @mcp_registry_mutex.synchronize { @mcp_registry&.reload }
  json_response(res, 200, { ok: true, name: name })
end

#api_media_audio_speech(req, res) ⇒ Object



1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
# File 'lib/clacky/server/http_server.rb', line 1797

def api_media_audio_speech(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  input = body["input"].to_s
  if input.strip.empty?
    return json_response(res, 422, { error: "input is required" })
  end

  voice      = body["voice"]
  output_dir = body["output_dir"].to_s
  output_dir = @agent_config.default_working_dir || Dir.pwd if output_dir.empty?

  session_id = body["session_id"].to_s
  session_id = nil if session_id.empty?

  result = Clacky::Media::Generator.new(@agent_config).generate_speech(
    input: input,
    voice: voice,
    output_dir: output_dir
  )
  if result["success"]
    log_media_usage(result, prompt: input, session_id: session_id)
  end
  status = result["success"] ? 200 : 422
  json_response(res, status, result)
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_media_audio_transcriptions(req, res) ⇒ Object



1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
# File 'lib/clacky/server/http_server.rb', line 1827

def api_media_audio_transcriptions(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  audio_b64 = body["audio_base64"].to_s
  if audio_b64.empty?
    return json_response(res, 422, { error: "audio_base64 is required" })
  end

  mime_type = body["mime_type"].to_s
  mime_type = "audio/webm" if mime_type.empty?

  result = Clacky::Media::Generator.new(@agent_config).generate_transcription(
    audio_base64: audio_b64,
    mime_type: mime_type
  )
  if result["success"]
    Clacky::Logger.info("[Media] stt generated model=#{result["model"]} provider=#{result["provider"]} cost_usd=#{result["cost_usd"].to_f}")
  end
  status = result["success"] ? 200 : 422
  json_response(res, status, result)
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_media_image(req, res) ⇒ Object

POST /api/media/image Body: { "prompt": "...", "aspect_ratio": "landscape|square|portrait", "output_dir": "<absolute path, optional>" } Routes to the model configured with type=image in agent_config.



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
# File 'lib/clacky/server/http_server.rb', line 1701

def api_media_image(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  prompt = body["prompt"].to_s
  if prompt.strip.empty?
    return json_response(res, 422, { error: "prompt is required" })
  end

  aspect_ratio = body["aspect_ratio"].to_s
  aspect_ratio = "landscape" if aspect_ratio.empty?
  output_dir   = body["output_dir"].to_s
  output_dir   = @agent_config.default_working_dir || Dir.pwd if output_dir.empty?

  session_id = body["session_id"].to_s
  session_id = nil if session_id.empty?

  result = Clacky::Media::Generator.new(@agent_config).generate_image(
    prompt: prompt,
    aspect_ratio: aspect_ratio,
    output_dir: output_dir,
    image: body["image"],
    images: body["images"]
  )
  if result["success"]
    log_media_usage(result, prompt: prompt, session_id: session_id)
  end
  status = result["success"] ? 200 : 422
  json_response(res, status, result)
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_media_types(res) ⇒ Object

GET /api/media/types Returns which media types are configured in agent_config.models. Used by the media-gen skill to decide whether to surface generation capabilities to the user.



1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
# File 'lib/clacky/server/http_server.rb', line 1922

def api_media_types(res)
  out = {}
  Clacky::Providers::MEDIA_KINDS.each do |t|
    state = @agent_config.media_state(t)
    out[t] =
      if state["configured"]
        {
          configured: true,
          model:      state["model"],
          base_url:   state["base_url"],
          source:     state["source"]
        }
      else
        { configured: false, source: "off" }
      end
  end
  json_response(res, 200, out)
end

#api_media_video(req, res) ⇒ Object



1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
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
1773
1774
1775
1776
# File 'lib/clacky/server/http_server.rb', line 1734

def api_media_video(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  prompt = body["prompt"].to_s
  if prompt.strip.empty?
    return json_response(res, 422, { error: "prompt is required" })
  end

  aspect_ratio = body["aspect_ratio"].to_s
  aspect_ratio = "landscape" if aspect_ratio.empty?
  duration     = body["duration_seconds"]
  image        = body["image"]
  output_dir   = body["output_dir"].to_s
  output_dir   = @agent_config.default_working_dir || Dir.pwd if output_dir.empty?

  session_id = body["session_id"].to_s
  session_id = nil if session_id.empty?

  result = Clacky::Media::Generator.new(@agent_config).generate_video(
    prompt: prompt,
    aspect_ratio: aspect_ratio,
    duration_seconds: duration,
    output_dir: output_dir,
    image: image,
    first_frame: body["first_frame"],
    last_frame: body["last_frame"],
    reference_images: body["reference_images"],
    reference_videos: body["reference_videos"],
    reference_audios: body["reference_audios"],
    resolution: body["resolution"],
    generate_audio: body["generate_audio"],
    watermark: body["watermark"],
    seed: body["seed"]
  )
  if result["success"]
    log_media_usage(result, prompt: prompt, session_id: session_id)
  end
  status = result["success"] ? 200 : 422
  json_response(res, status, result)
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_media_video_status(req, res) ⇒ Object



1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
# File 'lib/clacky/server/http_server.rb', line 1778

def api_media_video_status(req, res)
  query   = URI.decode_www_form(req.query_string.to_s).to_h
  task_id = query["task_id"].to_s
  if task_id.strip.empty?
    return json_response(res, 422, { error: "task_id is required" })
  end

  output_dir = query["output_dir"].to_s
  output_dir = @agent_config.default_working_dir || Dir.pwd if output_dir.empty?

  result = Clacky::Media::Generator.new(@agent_config).video_status(
    task_id: task_id,
    output_dir: output_dir
  )
  json_response(res, 200, result)
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_media_video_understand(req, res) ⇒ Object



1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
# File 'lib/clacky/server/http_server.rb', line 1852

def api_media_video_understand(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  video_b64 = body["video_base64"].to_s
  if video_b64.empty?
    return json_response(res, 422, { error: "video_base64 is required" })
  end

  mime_type = body["mime_type"].to_s
  mime_type = "image/png" if mime_type.empty?

  prompt = body["prompt"].to_s

  result = Clacky::Media::Generator.new(@agent_config).understand_video(
    video_base64: video_b64,
    mime_type: mime_type,
    prompt: prompt
  )
  if result["success"]
    Clacky::Logger.info("[Media] video_understanding generated model=#{result["model"]} provider=#{result["provider"]} cost_usd=#{result["cost_usd"].to_f}")
  end
  status = result["success"] ? 200 : 422
  json_response(res, status, result)
rescue StandardError => e
  json_response(res, 500, { error: e.message })
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.



2351
2352
2353
2354
2355
# File 'lib/clacky/server/http_server.rb', line 2351

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_device_poll(req, res) ⇒ Object

POST /api/onboard/device/poll { device_code } Polls the platform once. While pending, returns { status: "pending" }. On approval, persists the issued key into agent_config and returns { status: "approved" } so the frontend can proceed to the onboard session.



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
# File 'lib/clacky/server/http_server.rb', line 1203

def api_onboard_device_poll(req, res)
  body        = parse_json_body(req) || {}
  device_code = body["device_code"].to_s
  if device_code.empty?
    return json_response(res, 422, { ok: false, error: "device_code is required" })
  end

  client = Clacky::PlatformHttpClient.new
  result = client.post("/api/v1/device/token", { device_code: device_code })
  data   = result[:data] || {}
  status = data["status"]

  if result[:success] && status == "approved"
    persist_onboard_model(
      api_key:  data["api_key"],
      base_url: data["base_url"],
      model:    data["default_model"]
    ) if data["api_key"]
    if data["device_token"]
      Clacky::Identity.load.bind!(
        device_token: data["device_token"],
        user_id:      data["user_id"]
      )
    end
    json_response(res, 200, {
      ok:            true,
      status:        "approved",
      default_model: data["default_model"]
    })
  elsif status == "pending"
    json_response(res, 200, { ok: true, status: "pending" })
  else
    # denied / expired / consumed / network error — surface to the client.
    json_response(res, 200, {
      ok:     false,
      status: status || "error",
      error:  result[:error]
    })
  end
end

#api_onboard_device_start(req, res) ⇒ Object

POST /api/onboard/device/start Kicks off a device-authorization flow against the platform. Returns the device_code (held by the client for polling) plus the user-facing verification URL the browser should open.



1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'lib/clacky/server/http_server.rb', line 1177

def api_onboard_device_start(req, res)
  client = Clacky::PlatformHttpClient.new
  result = client.post("/api/v1/device/authorize", {
    device_id:   onboard_device_id,
    device_info: { os: RUBY_PLATFORM, hostname: Socket.gethostname, app_version: Clacky::VERSION }
  })

  if result[:success]
    data = result[:data]
    json_response(res, 200, {
      ok:                        true,
      device_code:               data["device_code"],
      user_code:                 data["user_code"],
      verification_uri:          data["verification_uri"],
      verification_uri_complete: data["verification_uri_complete"],
      interval:                  data["interval"] || 5
    })
  else
    json_response(res, 502, { ok: false, error: result[:error] })
  end
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.



2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
# File 'lib/clacky/server/http_server.rb', line 2360

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.expand_path("~/.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 branded: true → running under a brand; hide the OpenClacky AI Keys block



1164
1165
1166
1167
1168
1169
1170
1171
# File 'lib/clacky/server/http_server.rb', line 1164

def api_onboard_status(res)
  branded = Clacky::BrandConfig.load.branded?
  if !@agent_config.models_configured?
    json_response(res, 200, { needs_onboard: true, phase: "key_setup", branded: branded })
  else
    json_response(res, 200, { needs_onboard: false, branded: branded })
  end
end

#api_rename_session(session_id, req, res) ⇒ Object



6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
# File 'lib/clacky/server/http_server.rb', line 6858

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
  
  # Update pinned status if provided
  if !pinned.nil?
    agent.pinned = pinned
  end
  
  # Save session data
  @session_manager.save(agent.to_session_data(updated_at: Time.now))
  
  # 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.message })
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.



3808
3809
3810
3811
# File 'lib/clacky/server/http_server.rb', line 3808

def api_restart(req, res)
  json_response(res, 200, { ok: true, message: "Restarting…" })
  schedule_restart
end

#api_run_cron_task(name, res) ⇒ Object

POST /api/cron-tasks/:name/run — execute immediately



4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
# File 'lib/clacky/server/http_server.rb', line 4776

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.expand_path("~/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.message })
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.



4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
# File 'lib/clacky/server/http_server.rb', line 4471

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)
  fields[:token_updated_at] = Time.now.to_i if platform == :discord && fields.key?(:bot_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.message })
end

#api_send_channel_message(platform, req, res) ⇒ Object

POST /api/channels/:platform/send Proactively send a message to a user via the given IM platform.

Body:

{ "message": "hello",            # required
"user_id": "some_user_id" }    # optional — defaults to most-recently active user

Response:

200 { ok: true }
400 { ok: false, error: "..." }  — missing/invalid params or platform not running
503 { ok: false, error: "..." }  — no known users (nobody has messaged the bot yet)

Constraints:

- The platform adapter must be running (channel must be enabled + connected).
- For Weixin (iLink protocol), a context_token is required per message. This is
automatically looked up from the in-memory cache populated by inbound messages.
If no token exists for the target user (i.e. the user has never messaged the bot
in this server session), the message cannot be delivered.


4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
# File 'lib/clacky/server/http_server.rb', line 4258

def api_send_channel_message(platform, req, res)
  platform = platform.to_sym
  body     = parse_json_body(req)
  message  = body["message"].to_s.strip

  if message.empty?
    json_response(res, 400, { ok: false, error: "message is required" })
    return
  end

  # Resolve target user_id
  user_id = body["user_id"].to_s.strip
  if user_id.empty?
    # Default to the most-recently active user for this platform
    known = @channel_manager.known_users(platform)
    if known.empty?
      json_response(res, 503, {
        ok:    false,
        error: "No known users for :#{platform}. The user must send a message to the bot first."
      })
      return
    end
    user_id = known.last
  end

  result = @channel_manager.send_to_user(platform, user_id, message)
  if result.nil?
    json_response(res, 400, {
      ok:    false,
      error: "Failed to send message. The :#{platform} adapter may not be running, or no context_token is available for user #{user_id}."
    })
  else
    json_response(res, 200, { ok: true, platform: platform, user_id: user_id })
  end
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_serve_local_image(req, res) ⇒ Object

GET /api/local-image?path=file:///path/to/image.png GET /api/local-image?path=/path/to/image.png

Serves a local image file with the correct Content-Type. Used by the Web UI to render local images that would otherwise be blocked by the browser's security policy (file:// from http:// origin).



4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
# File 'lib/clacky/server/http_server.rb', line 4412

def api_serve_local_image(req, res)
  raw_path = URI.decode_www_form(req.query_string.to_s).to_h["path"].to_s
  return json_response(res, 400, { error: "path is required" }) if raw_path.empty?

  # Strip file://, decode, WSL drive-letter normalize, then expand — in
  # this order (normalize must precede expand_path). No-op on macOS/Linux.
  path = Utils::EnvironmentDetector.resolve_local_path(raw_path)

  # Security: only serve media files (images + videos)
  ext = File.extname(path).downcase
  unless Utils::FileProcessor::LOCAL_MEDIA_EXTENSIONS.include?(ext)
    return json_response(res, 403, { error: "not a supported media file" })
  end

  return json_response(res, 404, { error: "file not found" }) unless File.exist?(path)

  file_size = File.size(path)
  mime = Utils::FileProcessor::MIME_TYPES[ext] || "application/octet-stream"

  # ETag from mtime+size so an overwritten same-name file invalidates the
  # browser cache. Use no-cache (revalidate every time) rather than
  # max-age: unchanged files return 304 (no body), changed files return
  # the new bytes.
  stat = File.stat(path)
  etag = %(W/"#{stat.mtime.to_i}-#{stat.size}")
  res["Cache-Control"] = "private, no-cache"
  res["ETag"] = etag
  if req["If-None-Match"] == etag
    res.status = 304
    res.body = ""
    return
  end

  # Support HTTP Range requests for video seeking
  range_header = req["Range"]
  if range_header && range_header =~ /\Abytes=(\d*)-(\d*)\z/
    start_byte = ($1.empty? ? 0 : $1.to_i)
    end_byte   = ($2.empty? ? file_size - 1 : $2.to_i)
    end_byte   = [end_byte, file_size - 1].min

    res.status = 206
    res["Content-Type"]  = mime
    res["Content-Range"] = "bytes #{start_byte}-#{end_byte}/#{file_size}"
    res["Accept-Ranges"] = "bytes"
    res["Content-Length"] = (end_byte - start_byte + 1).to_s
    IO.binread(path, end_byte - start_byte + 1, start_byte).then { |data| res.body = data }
  else
    res.status         = 200
    res["Content-Type"] = mime
    res["Accept-Ranges"] = "bytes"
    res.body = File.binread(path)
  end
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_session_files(session_id, req, res) ⇒ Object



5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
# File 'lib/clacky/server/http_server.rb', line 5155

def api_session_files(session_id, req, res)
  unless @registry.ensure(session_id)
    return json_response(res, 404, { error: "Session not found" })
  end
  session = @registry.get(session_id)
  agent   = session && session[:agent]
  return json_response(res, 404, { error: "Session not found" }) unless agent

  root = File.expand_path(agent.working_dir.to_s)
  return json_response(res, 404, { error: "Working directory not found" }) unless Dir.exist?(root)

  query = URI.decode_www_form(req.query_string.to_s).to_h
  rel = query["path"].to_s
  absolute_mode = query["absolute"] == "true"
  show_hidden = query["show_hidden"] == "true"

  # Absolute mode: allow browsing outside working directory (e.g., root "/")
  if absolute_mode
    target = File.expand_path(rel.empty? ? "/" : rel)
    display_root = target
    # Normalize rel for API response
    rel = target
  else
    rel = rel.sub(%r{\A/+}, "").strip
    target = File.expand_path(File.join(root, rel))
    display_root = root

    # Reject traversal outside the working directory.
    unless target == root || target.start_with?("#{root}/")
      return json_response(res, 403, { error: "Path outside working directory" })
    end
  end

  return json_response(res, 404, { error: "Directory not found" }) unless Dir.exist?(target)
  entries = Dir.children(target).reject do |name|
    IGNORED_FILE_ENTRIES.include?(name) || (!show_hidden && name.start_with?("."))
  end

  items = entries.filter_map do |name|
    full = File.join(target, name)
    is_dir = File.directory?(full)
    # Skip symlinks pointing outside the root, and anything unreadable.
    next unless File.exist?(full)
    {
      name:  name,
      path:  "#{rel}/#{name}".gsub(%r{/+}, "/"),
      type:  is_dir ? "dir" : "file",
      size:  is_dir ? nil : (File.size(full) rescue nil)
    }
  rescue StandardError
    nil
  end

  # Directories first, then files; both case-insensitive alphabetical.
  items.sort_by! { |it| [it[:type] == "dir" ? 0 : 1, it[:name].downcase] }

  json_response(res, 200, { root: display_root, path: rel, home: Dir.home, default: default_working_dir, entries: items, places: dir_picker_places })
rescue StandardError => e
  json_response(res, 500, { error: e.message })
end

#api_session_git(session_id, action, req, res) ⇒ Object

working_dir. action ∈ status|diff|log|branches. diff accepts ?file=, log accepts ?limit=.



4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
# File 'lib/clacky/server/http_server.rb', line 4937

def api_session_git(session_id, action, req, res)
  dir = git_session_dir(session_id, res)
  return unless dir

  unless Clacky::Server::GitPanel.repo?(dir)
    return json_response(res, 200, { repo: false })
  end

  query = URI.decode_www_form(req.query_string.to_s).to_h
  case action
  when "status"
    json_response(res, 200, { repo: true }.merge(Clacky::Server::GitPanel.status(dir)))
  when "diff"
    json_response(res, 200, { repo: true, diff: Clacky::Server::GitPanel.diff(dir, file: query["file"]) })
  when "log"
    json_response(res, 200, { repo: true, commits: Clacky::Server::GitPanel.log(dir, limit: query["limit"] || 50) })
  when "branches"
    json_response(res, 200, { repo: true, branches: Clacky::Server::GitPanel.branches(dir) })
  else
    json_response(res, 404, { error: "Unknown git action" })
  end
end

#api_session_git_commit(session_id, req, res) ⇒ Object

POST /api/sessions/:id/git/commit — body: { message:, files: [..] }.



4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
# File 'lib/clacky/server/http_server.rb', line 4961

def api_session_git_commit(session_id, req, res)
  dir = git_session_dir(session_id, res)
  return unless dir

  unless Clacky::Server::GitPanel.repo?(dir)
    return json_response(res, 400, { error: "Not a git repository" })
  end

  body = parse_json_body(req)
  result = Clacky::Server::GitPanel.commit(dir, message: body["message"], files: body["files"])
  if result[:ok]
    json_response(res, 200, result)
  else
    json_response(res, 422, { error: result[:error] })
  end
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.



6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
# File 'lib/clacky/server/http_server.rb', line 6705

def api_session_messages(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.



4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
# File 'lib/clacky/server/http_server.rb', line 4867

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
  skills = agent.skill_loader.user_invocable_skills(agent.agent_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,
      always_show:    skill.always_show
    }
  end

  json_response(res, 200, { skills: skill_data })
end

#api_session_time_machine(session_id, res) ⇒ Object

GET /api/sessions/:id/time_machine — task history for the Time Machine panel. Mirrors the CLI menu: each entry carries id, summary, status (current/past/undone) and whether it branches.



4981
4982
4983
4984
4985
4986
4987
# File 'lib/clacky/server/http_server.rb', line 4981

def api_session_time_machine(session_id, res)
  agent = time_machine_agent(session_id, res)
  return unless agent

  history = agent.get_task_history(limit: 20)
  json_response(res, 200, { tasks: history })
end

#api_session_time_machine_diff(session_id, task_id, req, res) ⇒ Object

GET /api/sessions/:id/time_machine/:task_id/diff Without ?path: returns the file list this task touched. With ?path=: returns the unified diff of that file.



5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
# File 'lib/clacky/server/http_server.rb', line 5010

def api_session_time_machine_diff(session_id, task_id, req, res)
  agent = time_machine_agent(session_id, res)
  return unless agent

  rel = req.query["path"].to_s
  if rel.empty?
    json_response(res, 200, { ok: true, task_id: task_id, files: agent.task_diff_files(task_id) })
  else
    diff = agent.task_file_diff(task_id, rel)
    if diff.nil?
      json_response(res, 404, { ok: false, error: "No diff for #{rel}" })
    else
      json_response(res, 200, { ok: true, task_id: task_id }.merge(diff))
    end
  end
end

#api_session_time_machine_restore_preview(session_id, task_id, res) ⇒ Object

GET /api/sessions/:id/time_machine/:task_id/restore_preview Returns the file-level effect of switching back to this task without actually performing the switch. Lets the UI render an honest confirmation listing the files that would be overwritten/created/deleted.



5031
5032
5033
5034
5035
5036
5037
# File 'lib/clacky/server/http_server.rb', line 5031

def api_session_time_machine_restore_preview(session_id, task_id, res)
  agent = time_machine_agent(session_id, res)
  return unless agent

  changes = agent.preview_restore_to_task(task_id)
  json_response(res, 200, { ok: true, task_id: task_id, changes: changes })
end

#api_session_time_machine_switch(session_id, req, res) ⇒ Object

POST /api/sessions/:id/time_machine/switch — body: { task_id: }. Restores the working tree to the end-of-task state of task_id.



4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
# File 'lib/clacky/server/http_server.rb', line 4991

def api_session_time_machine_switch(session_id, req, res)
  agent = time_machine_agent(session_id, res)
  return unless agent

  body = parse_json_body(req)
  task_id = body["task_id"].to_i
  result = agent.switch_to_task(task_id)
  if result[:success]
    @session_manager.save(agent.to_session_data(status: :success, updated_at: Time.now))
    broadcast_session_update(session_id)
    json_response(res, 200, { ok: true, message: result[:message], task_id: result[:task_id] })
  else
    json_response(res, 422, { ok: false, error: result[:message] })
  end
end

#api_set_default_model(id, res) ⇒ Object

POST /api/config/models/:id/default Makes the identified model the new "default" (global initial model for new sessions AND current model for this server instance).



6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
# File 'lib/clacky/server/http_server.rb', line 6600

def api_set_default_model(id, res)
  ok = @agent_config.set_default_model_by_id(id)
  return json_response(res, 404, { error: "model not found" }) unless ok

  @agent_config.current_model_id    = id
  @agent_config.current_model_index = @agent_config.models.find_index { |m| m["id"] == id } || 0
  @agent_config.save
  json_response(res, 200, { ok: true })
rescue => e
  json_response(res, 422, { error: e.message })
end

#api_store_extension_detail(req, res) ⇒ Object

GET /api/store/extension?id=[&source=brand]

Detail for a single extension. Pass source=brand to query brand-private extensions via the license-gated API; omit (or any other value) for the public marketplace API.



2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
# File 'lib/clacky/server/http_server.rb', line 2882

def api_store_extension_detail(req, res)
  id = req.query["id"].to_s
  if id.strip.empty?
    json_response(res, 400, { ok: false, error: "Missing id." })
    return
  end

  brand  = Clacky::BrandConfig.load
  result = if req.query["source"] == "brand"
    brand.brand_extension_detail!(id)
  else
    brand.extension_detail!(id)
  end

  if result[:success] && result[:extension]
    ext  = result[:extension]
    slug = ext["name"] || ext[:name] || ext["slug"] || ext[:slug]
    container = extension_container(slug)
    ext  = ext.merge(
      "slug"              => slug,
      "installed"         => !container.nil?,
      "installed_version" => container&.dig(:version),
      "removable"         => container && container[:layer] == :installed,
      "disabled"          => container ? container[:disabled] == true : false,
    )
    json_response(res, 200, { ok: true, extension: ext })
  else
    container = extension_container(id)
    if container && container[:layer] == :installed
      market = fetch_batch_market_data([id])[id]
      # Fall back to local ext.yml for self-authored extensions.
      local_name   = container[:name].to_s.then { |n| n.empty? ? id : n }
      local_desc   = container.dig(:raw, "description").to_s
      local_author = container[:author].to_s
      local_units  = units_from_container(container)
      ext = {
        "id"                => id,
        "name"              => market ? (market["name"] || id) : local_name,
        "name_zh"           => market&.dig("name_zh"),
        "name_en"           => market&.dig("name_en"),
        "slug"              => id,
        "version"           => market ? (market["version"] || container[:version]) : container[:version],
        "installed_version" => container[:version],
        "description"       => market ? market["description"] : local_desc,
        "author"            => market ? market["author"] : local_author,
        "icon_url"          => market&.dig("icon_url"),
        "units"             => market ? market["units"] : local_units,
        "homepage"          => market ? (market["homepage"] || "") : container[:homepage].to_s,
        "origin"            => market ? (market["origin"] || container[:origin]) : container[:origin],
        "hub_active"        => market&.dig("hub_active"),
        "unlisted"          => market.nil? || market["unlisted"] == true,
        "installed"         => true,
        "removable"         => true,
        "disabled"          => container[:disabled] == true,
      }
      json_response(res, 200, { ok: true, extension: ext })
    else
      json_response(res, 404, { ok: false, error: result[:error] || "Not found" })
    end
  end
end

#api_store_extension_disable(req, res) ⇒ Object

POST /api/store/extension/disable body: { id: }



2955
2956
2957
# File 'lib/clacky/server/http_server.rb', line 2955

def api_store_extension_disable(req, res)
  toggle_extension(req, res, :disable)
end

#api_store_extension_enable(req, res) ⇒ Object

POST /api/store/extension/enable body: { id: }



2960
2961
2962
# File 'lib/clacky/server/http_server.rb', line 2960

def api_store_extension_enable(req, res)
  toggle_extension(req, res, :enable)
end

#api_store_extension_import(req, res) ⇒ Object

POST /api/store/extension/import multipart/form-data: file= Imports a locally uploaded .zip package. Same async job/poll flow as install; the import work itself lives in ExtensionPackager.install_bytes.



3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
# File 'lib/clacky/server/http_server.rb', line 3002

def api_store_extension_import(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

  job_id = spawn_extension_job("extracting") do |on_progress|
    Clacky::ExtensionPackager.install_bytes(upload[:data], filename: upload[:filename], force: true, on_progress: on_progress)
  end

  json_response(res, 200, { ok: true, job_id: job_id })
end

#api_store_extension_install(req, res) ⇒ Object

POST /api/store/extension/install body: { download_url:, name: } Starts an async install job and returns immediately with a job_id. Poll GET /api/store/extension/install/status?job_id=xxx for progress.



2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
# File 'lib/clacky/server/http_server.rb', line 2981

def api_store_extension_install(req, res)
  body         = parse_json_body(req)
  download_url = body["download_url"].to_s.strip
  name         = body["name"].to_s.strip

  if download_url.empty?
    json_response(res, 400, { ok: false, error: "Missing download_url." })
    return
  end

  job_id = spawn_extension_job("downloading") do |on_progress|
    Clacky::ExtensionPackager.install(download_url, force: true, on_progress: on_progress)
    Clacky::Telemetry.extension_install!(name) unless name.empty?
  end

  json_response(res, 200, { ok: true, job_id: job_id })
end

#api_store_extension_install_status(req, res) ⇒ Object

GET /api/store/extension/install/status?job_id=xxx



3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
# File 'lib/clacky/server/http_server.rb', line 3049

def api_store_extension_install_status(req, res)
  job_id = req.query["job_id"].to_s.strip
  if job_id.empty?
    json_response(res, 400, { ok: false, error: "Missing job_id." })
    return
  end
  job = @install_jobs_mutex.synchronize do
    sweep_stale_install_jobs!
    @install_jobs[job_id]
  end
  if job.nil?
    json_response(res, 404, { ok: false, error: "Job not found." })
    return
  end
  # Clean up finished jobs after they are read as done
  if job[:done]
    @install_jobs_mutex.synchronize { @install_jobs.delete(job_id) }
  end
  json_response(res, 200, { ok: true }.merge(job))
end

#api_store_extension_uninstall(req, res) ⇒ Object



3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
# File 'lib/clacky/server/http_server.rb', line 3086

def api_store_extension_uninstall(req, res)
  body = parse_json_body(req)
  id = body["id"].to_s
  purge_data = body["purge_data"] == true
  container = extension_container(id)
  if container.nil?
    json_response(res, 404, { ok: false, error: "Not installed." })
    return
  end
  unless container[:layer] == :installed
    json_response(res, 422, { ok: false, error: "Only marketplace-installed extensions can be removed." })
    return
  end

  if Clacky::ExtensionLoader.uninstall!(id, purge_data: purge_data)
    json_response(res, 200, { ok: true, id: id })
  else
    json_response(res, 404, { ok: false, error: "Not installed." })
  end
end

#api_store_extensions(req, res) ⇒ Object

GET /api/store/extensions?q=&sort=

Public extension marketplace catalog — always returns the full public catalog regardless of brand status. Both brand and non-brand users see the same public marketplace here.



2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
# File 'lib/clacky/server/http_server.rb', line 2664

def api_store_extensions(req, res)
  brand  = Clacky::BrandConfig.load
  result = brand.search_extensions!(query: req.query["q"], sort: req.query["sort"], page: req.query["page"], per_page: req.query["per_page"])

  if result[:success]
    installed = installed_extension_containers
    extensions = Array(result[:extensions]).map do |ext|
      slug      = ext["name"] || ext[:name] || ext["slug"] || ext[:slug]
      container = installed[slug]
      ext.merge(
        "installed"         => !container.nil?,
        "installed_version" => container&.dig(:version)
      )
    end
    json_response(res, 200, { ok: true, extensions: extensions, meta: result[:meta] })
  else
    json_response(res, 200, {
      ok:         true,
      extensions: [],
      warning:    result[:error] || "Could not reach the extension store."
    })
  end
end

#api_store_extensions_brand(res) ⇒ Object

GET /api/store/extensions/brand

Brand-private extension catalog — only available to users with an activated brand license. Returns extensions belonging to this brand via BrandConfig#fetch_brand_extensions!. Returns 403 when the license is not activated.



2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
# File 'lib/clacky/server/http_server.rb', line 2694

def api_store_extensions_brand(res)
  brand = Clacky::BrandConfig.load

  unless brand.activated?
    json_response(res, 403, { ok: false, error: "Brand license not activated." })
    return
  end

  result = brand.fetch_brand_extensions!

  if result[:success]
    installed = installed_extension_containers
    extensions = Array(result[:extensions]).map do |ext|
      slug      = ext["name"] || ext[:name] || ext["slug"] || ext[:slug]
      container = installed[slug]
      # Merge local container data (e.g. emoji) for self-authored extensions.
      local_overrides = {}
      if container && ext["emoji"].to_s.empty?
        local_emoji = container.dig(:raw, "emoji") || container[:emoji]
        local_overrides["emoji"] = local_emoji if local_emoji.to_s.strip != ""
      end
      ext.merge(
        "installed"         => !ext["installed_version"].nil?,
        "installed_version" => ext["installed_version"],
        **local_overrides
      )
    end
    json_response(res, 200, { ok: true, extensions: extensions })
  else
    json_response(res, 200, {
      ok:         true,
      extensions: [],
      warning:    result[:error] || "Could not reach the extension store."
    })
  end
end

#api_store_extensions_installed(res) ⇒ Object

GET /api/store/extensions/installed

Returns all locally installed extensions (all layers: builtin, installed, local) regardless of whether they are still listed on the marketplace.



2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
# File 'lib/clacky/server/http_server.rb', line 2776

def api_store_extensions_installed(res)
  result   = Clacky::ExtensionLoader.load_all
  disabled = Clacky::ExtensionLoader.disabled_ids

  local_entries = Array(result&.containers).filter_map do |ext_id, container|
    next unless container[:layer] == :installed

    [ext_id, container]
  end.to_h

  market_by_slug = fetch_batch_market_data(local_entries.keys)

  extensions = local_entries.map do |ext_id, container|
    market = market_by_slug[ext_id]
    # For self-authored (origin: self) extensions market is nil.
    # Fall back to local ext.yml data so name/description/author are populated.
    local_name   = container[:name].to_s.then { |n| n.empty? ? ext_id : n }
    local_desc   = container.dig(:raw, "description").to_s
    local_author = container[:author].to_s
    local_units  = units_from_container(container)
    {
      "id"                => ext_id,
      "name"              => market ? (market["name"] || ext_id) : local_name,
      "display_name"      => market&.dig("display_name"),
      "display_name_zh"   => market&.dig("display_name_zh"),
      "name_zh"           => market&.dig("name_zh"),
      "name_en"           => market&.dig("name_en"),
      "slug"              => ext_id,
      "version"           => market ? (market["version"] || container[:version]) : container[:version],
      "installed_version" => container[:version],
      "description"       => market ? market["description"] : local_desc,
      "author"            => market ? market["author"] : local_author,
      "icon_url"          => market&.dig("icon_url"),
      "units"             => market ? market["units"] : local_units,
      "homepage"          => market ? (market["homepage"] || "") : container[:homepage].to_s,
      "origin"            => market ? (market["origin"] || container[:origin]) : container[:origin],
      "hub_active"        => market&.dig("hub_active"),
      "download_count"    => market&.dig("download_count").to_i,
      # Mark as unlisted when:
      # - market is nil (extension no longer exists on the platform), OR
      # - platform batch API explicitly returned unlisted:true (brand-private
      #   extension removed from all distributions but not yet soft-deleted).
      "unlisted"          => market.nil? || market["unlisted"] == true,
      "layer"             => container[:layer].to_s,
      "installed"         => true,
      "removable"         => true,
      "disabled"          => disabled.include?(ext_id),
    }
  end

  json_response(res, 200, { ok: true, extensions: extensions })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#api_store_extensions_system(res) ⇒ Object

GET /api/store/extensions/system

Returns only the builtin (system) extensions shipped with the gem.



2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
# File 'lib/clacky/server/http_server.rb', line 2734

def api_store_extensions_system(res)
  result   = Clacky::ExtensionLoader.load_all
  disabled = Clacky::ExtensionLoader.disabled_ids

  hidden = %w[coding general ext-studio].to_set

  extensions = Array(result&.containers).filter_map do |ext_id, container|
    next unless container[:layer] == :builtin
    next if hidden.include?(ext_id)

    local_name   = container[:name].to_s.then { |n| n.empty? ? ext_id : n }
    local_desc   = container.dig(:raw, "description").to_s
    local_desc_zh = container.dig(:raw, "description_zh").to_s
    local_author = container[:author].to_s
    local_units  = units_from_container(container)
    {
      "id"              => ext_id,
      "name"            => local_name,
      "display_name"    => container.dig(:raw, "display_name") || local_name,
      "display_name_zh" => container.dig(:raw, "display_name_zh"),
      "slug"            => ext_id,
      "version"         => container[:version],
      "description"     => local_desc,
      "description_zh"  => local_desc_zh,
      "author"          => local_author,
      "units"           => local_units,
      "layer"           => "builtin",
      "installed"       => true,
      "removable"       => false,
      "disabled"        => disabled.include?(ext_id),
    }
  end

  json_response(res, 200, { ok: true, extensions: extensions })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
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.



2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
# File 'lib/clacky/server/http_server.rb', line 2643

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



6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
# File 'lib/clacky/server/http_server.rb', line 6895

def api_switch_session_model(session_id, req, res)
  body = parse_json_body(req)
  model_id = body["model_id"].to_s.strip

  return json_response(res, 400, { error: "model_id is required" }) if model_id.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] }

  # With Plan B (shared @models reference), every session's AgentConfig
  # points at the same @models array as the global @agent_config. So
  # resolving the model by stable id here and in agent.switch_model_by_id
  # will always agree — no more index divergence after add/delete.
  target_model = @agent_config.models.find { |m| m["id"] == model_id }
  if target_model.nil?
    return json_response(res, 400, { error: "Model not found in configuration" })
  end

  # Switch to the model by id (unified interface with CLI)
  # Handles: config.switch_model_by_id + client rebuild + message_compressor rebuild
  success = agent.switch_model_by_id(model_id)

  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(updated_at: Time.now))

  # Broadcast update to all clients
  broadcast_session_update(session_id)

  json_response(res, 200, { ok: true, model_id: model_id, model: target_model["model"] })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_switch_session_reasoning_effort(session_id, req, res) ⇒ Object

PATCH /api/sessions/:id/reasoning_effort Body: { "reasoning_effort": "off" | "low" | "medium" | "high" | "xhigh" | "max" }



6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
# File 'lib/clacky/server/http_server.rb', line 6935

def api_switch_session_reasoning_effort(session_id, req, res)
  body = parse_json_body(req)
  raw = body["reasoning_effort"]
  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] }
  return json_response(res, 404, { error: "Session not found" }) unless agent

  agent.reasoning_effort = raw
  @session_manager.save(agent.to_session_data(updated_at: Time.now))
  broadcast_session_update(session_id)

  json_response(res, 200, { ok: true, reasoning_effort: agent.reasoning_effort })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_switch_session_submodel(session_id, req, res) ⇒ Object

PATCH /api/sessions/:id/submodel Body: { "model_name": "dsk-deepseek-v4-pro" | null }

Pin this session to a sub-model under its current card without touching credentials or the global @models. Pass null/empty to clear and fall back to the card default. The name must appear in the provider preset's "models" list — anything else is rejected.



6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
# File 'lib/clacky/server/http_server.rb', line 6960

def api_switch_session_submodel(session_id, req, res)
  body = parse_json_body(req)
  raw = body["model_name"]
  model_name = raw.is_a?(String) ? raw.strip : nil

  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] }
  return json_response(res, 404, { error: "Session not found" }) unless agent

  if model_name && !model_name.empty?
    info = agent.current_model_info
    # Prefer explicitly saved provider_id, fall back to base_url lookup
    provider_id = info&.dig(:provider_id).to_s.strip.then { |v| v.empty? ? nil : v }
    provider_id ||= (info && Clacky::Providers.find_by_base_url(info[:base_url]))
    allowed = provider_id ? Clacky::Providers.models(provider_id) : []
    if allowed.empty?
      return json_response(res, 400, { error: "Current model has no provider preset; sub-model switching unavailable" })
    end
    unless allowed.include?(model_name)
      return json_response(res, 400, { error: "Sub-model '#{model_name}' not listed under provider '#{provider_id}'" })
    end
  else
    model_name = nil
  end

  agent.set_session_sub_model(model_name)
  @session_manager.save(agent.to_session_data(updated_at: Time.now))
  broadcast_session_update(session_id)

  json_response(res, 200, { ok: true, sub_model: agent.current_model_info[:sub_model] })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_telemetry(req, res) ⇒ Object

POST /api/telemetry Body: { "event": "share_open" | "share_download", ... } Fire-and-forget telemetry from the WebUI frontend.



1689
1690
1691
1692
1693
1694
1695
# File 'lib/clacky/server/http_server.rb', line 1689

def api_telemetry(req, res)
  body = parse_json_body(req) || {}
  Clacky::Telemetry.share!(event: body["event"], extra: body["extra"])
  json_response(res, 200, { ok: true })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
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.



4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
# File 'lib/clacky/server/http_server.rb', line 4589

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.message })
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 }



6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
# File 'lib/clacky/server/http_server.rb', line 6614

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 api_key.include?("****")
    model_id = body["id"].to_s
    entry = nil
    if !model_id.empty?
      entry = @agent_config.models.find { |m| m["id"] == model_id }
    end
    if entry.nil? && body.key?("index")
      entry = @agent_config.models[body["index"].to_i]
    end
    entry ||= @agent_config.models[@agent_config.current_model_index]
    api_key = entry ? entry["api_key"].to_s : ""
  end

  model            = body["model"].to_s
  base_url         = body["base_url"].to_s
  anthropic_format = body["anthropic_format"] || false
  api_format       = normalize_api_format(body["api_format"])
  return json_response(res, 422, { error: "invalid api_format" }) if api_format == :invalid

  result, used_base_url = try_test_with_base_url(api_key, base_url, model, anthropic_format, api_format)

  if result[:success] && used_base_url != base_url
    json_response(res, 200, {
      ok:                  true,
      message:             "Connected (auto-corrected base_url to add /v1)",
      effective_base_url:  used_base_url
    })
  elsif result[:success]
    json_response(res, 200, { ok: true, message: "Connected successfully" })
  else
    json_response(res, 200, { ok: false, message: result[:error].to_s, error_code: result[:error_code] })
  end
rescue => e
  json_response(res, 200, { ok: false, message: e.message })
end

#api_test_media_config(req, res) ⇒ Object

PATCH /api/config/media/:kind Body: { source: "off"|"auto"|"custom", model?, base_url?, api_key?, anthropic_format? } off / auto — remove any custom entry; "auto" lets the virtual derivation in AgentConfig#find_model_by_type take over. custom — replace any existing custom entry with the supplied fields. POST /api/config/media/test Body: { kind, source, model, base_url, api_key } Lightweight preflight: GET <base_url>/models to verify connectivity, auth, and that the requested model is exposed by the endpoint. No image is generated — zero cost, sub-second.



1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
# File 'lib/clacky/server/http_server.rb', line 1995

def api_test_media_config(req, res)
  body = parse_json_body(req) || {}
  kind = body["kind"].to_s
  return json_response(res, 422, { error: "invalid kind" }) unless %w[image video audio].include?(kind)
  return json_response(res, 422, { error: "only image kind supported" }) unless kind == "image"

  api_key = body["api_key"].to_s
  if api_key.empty? || api_key.include?("****")
    existing = @agent_config.find_model_by_type(kind) || {}
    api_key = existing["api_key"].to_s
  end

  model    = body["model"].to_s.strip
  base_url = body["base_url"].to_s.strip

  if model.empty? || base_url.empty? || api_key.empty?
    return json_response(res, 200, { ok: false, message: "model, base_url, api_key are required" })
  end

  result = preflight_media_endpoint(base_url: base_url, api_key: api_key, model: model)
  json_response(res, 200, result)
rescue => e
  json_response(res, 200, { ok: false, message: e.message })
end

#api_test_ocr_config(req, res) ⇒ Object

POST /api/config/ocr/test Reuses the media preflight (GET /models) — same connectivity check.



2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
# File 'lib/clacky/server/http_server.rb', line 2197

def api_test_ocr_config(req, res)
  body = parse_json_body(req) || {}
  api_key = body["api_key"].to_s
  if api_key.empty? || api_key.include?("****")
    existing = @agent_config.find_model_by_type("ocr") || {}
    api_key = existing["api_key"].to_s
  end

  model    = body["model"].to_s.strip
  base_url = body["base_url"].to_s.strip

  if model.empty? || base_url.empty? || api_key.empty?
    return json_response(res, 200, { ok: false, message: "model, base_url, api_key are required" })
  end

  result = preflight_media_endpoint(base_url: base_url, api_key: api_key, model: model)
  json_response(res, 200, result)
rescue => e
  json_response(res, 200, { ok: false, message: e.message })
end

#api_test_search_config(req, res) ⇒ Object

POST /api/config/search/test Runs the searcher with a fixed query so the user gets a definitive answer before saving, rather than discovering a bad key mid-task.



2254
2255
2256
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
2289
2290
# File 'lib/clacky/server/http_server.rb', line 2254

def api_test_search_config(req, res)
  body = parse_json_body(req) || {}
  provider = body["provider"].to_s.strip
  return json_response(res, 200, { ok: false, message: "provider is required" }) if provider.empty?

  script = Clacky::Utils::SearcherManager.path_for(provider)
  return json_response(res, 200, { ok: false, message: "searcher not found: #{provider}" }) unless script

  key = body["key"].to_s
  key = Clacky::SearchConfig.key if key.empty? || key.include?("****")

  stdout, stderr, status = Clacky::Utils::ParserManager.capture3_with_timeout(
    { "CLACKY_SEARCH_KEY" => key },
    Clacky::Utils::SearcherManager.interpreter_for(script),
    script, "openclacky", "1",
    timeout: 30
  )

  if status == :timeout
    return json_response(res, 200, { ok: false, message: "searcher timed out" })
  end

  unless status.success?
    message = stderr.to_s.strip
    return json_response(res, 200, { ok: false, message: message.empty? ? "searcher failed" : message })
  end

  count = begin
    JSON.parse(stdout.to_s).size
  rescue StandardError
    return json_response(res, 200, { ok: false, message: "searcher did not output a JSON array" })
  end

  json_response(res, 200, { ok: true, message: "Returned #{count} result(s)" })
rescue => e
  json_response(res, 200, { ok: false, message: e.message })
end

#api_toggle_channel(platform, req, res) ⇒ Object

PATCH /api/channels/:platform/enabled Body: { enabled: true|false } Toggles the platform on/off without touching credentials. Enabling requires the platform to already be configured.



4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
# File 'lib/clacky/server/http_server.rb', line 4562

def api_toggle_channel(platform, req, res)
  platform = platform.to_sym
  enabled  = parse_json_body(req)["enabled"] == true

  config = Clacky::ChannelConfig.load

  if enabled
    unless config.platform_config(platform)
      json_response(res, 422, { ok: false, error: "Platform is not configured yet" })
      return
    end
    config.enable_platform(platform)
  else
    config.disable_platform(platform)
  end

  config.save
  @channel_manager.reload_platform(platform, config)

  json_response(res, 200, { ok: true, enabled: config.enabled?(platform) })
rescue StandardError => e
  json_response(res, 422, { ok: false, error: e.message })
end

#api_toggle_skill(name, req, res) ⇒ Object

Body: { enabled: true/false }



5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
# File 'lib/clacky/server/http_server.rb', line 5305

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.message })
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 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



3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
# File 'lib/clacky/server/http_server.rb', line 3942

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.message })
end

#api_ui_open_aside(req, res) ⇒ Object

POST /api/ui/open_aside Broadcasts an open_aside event to the specified session's WebSocket clients, causing the browser to open the right-side panel. Body: { session_id: "..." }



3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
# File 'lib/clacky/server/http_server.rb', line 3473

def api_ui_open_aside(req, res)
  body = parse_json_body(req) || {}
  session_id = body["session_id"].to_s.strip
  if session_id.empty?
    json_response(res, 400, { error: "session_id is required" })
    return
  end
  broadcast(session_id, { type: "open_aside" })
  json_response(res, 200, { ok: true })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_ui_show_ext_refresh(req, res) ⇒ Object

POST /api/ui/show_ext_refresh Broadcasts a show_ext_refresh event to the specified session's WebSocket clients, causing the browser to display a one-click "reload extensions" button. Called by the AI after editing extension files so the user knows to reload. Body: { session_id: "..." }



3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
# File 'lib/clacky/server/http_server.rb', line 3491

def api_ui_show_ext_refresh(req, res)
  body = parse_json_body(req) || {}
  session_id = body["session_id"].to_s.strip
  if session_id.empty?
    json_response(res, 400, { error: "session_id is required" })
    return
  end
  broadcast(session_id, { type: "show_ext_refresh" })
  json_response(res, 200, { ok: true })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_update_cron_task(name, req, res) ⇒ Object

PATCH /api/cron-tasks/:name — update content and/or cron/enabled Body: { content?, cron?, enabled? }



4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
# File 'lib/clacky/server/http_server.rb', line 4750

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.message })
end

#api_update_media_config(kind, req, res) ⇒ Object



2069
2070
2071
# File 'lib/clacky/server/http_server.rb', line 2069

def api_update_media_config(kind, req, res)
  update_sidecar_config(res, kind, parse_json_body(req) || {})
end

#api_update_model(id, req, res) ⇒ Object

PATCH /api/config/models/:id Body: any subset of { model, base_url, api_key, anthropic_format, type } provider_id, capabilities, remark } Rules (the whole reason we moved off bulk save):

- Missing key  → field untouched
- api_key with "****" (masked display value) → IGNORED (never overwrites)
- api_key empty string → IGNORED (defensive; treat as "not changed")
- api_key real non-masked value → stored
- api_format null/empty → cleared (back to auto)
- api_format unsupported value → 422
- type="default" transparently clears the marker on other models
- capabilities is a hash like { vision: false }; empty hash clears it
- Unknown id → 404


6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
# File 'lib/clacky/server/http_server.rb', line 6477

def api_update_model(id, req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  target = @agent_config.models.find { |m| m["id"] == id }
  return json_response(res, 404, { error: "model not found" }) unless target

  # Validate before any mutation: target is a live reference inside
  # @agent_config.models, so an early 422 return after partial writes
  # would leave the in-memory config poisoned until the next save.
  api_format = nil
  if body.key?("api_format")
    api_format = normalize_api_format(body["api_format"])
    return json_response(res, 422, { error: "invalid api_format" }) if api_format == :invalid
  end

  if body.key?("model")
    v = body["model"].to_s.strip
    target["model"] = v unless v.empty?
  end
  if body.key?("base_url")
    v = body["base_url"].to_s.strip
    target["base_url"] = v unless v.empty?
  end
  if body.key?("anthropic_format")
    target["anthropic_format"] = !!body["anthropic_format"]
  end
  if body.key?("api_format")
    if api_format.nil?
      target.delete("api_format")
    else
      target["api_format"] = api_format
    end
  end
  if body.key?("provider_id")
    v = body["provider_id"].to_s.strip
    if v.empty?
      target.delete("provider_id")
    else
      target["provider_id"] = v
    end
  end
  if body.key?("capabilities")
    caps = body["capabilities"]
    if caps.is_a?(Hash) && !caps.empty?
      target["capabilities"] = caps.each_with_object({}) { |(k, v), h| h[k.to_s] = v == true }
    else
      target.delete("capabilities")
    end
  end
  if body.key?("remark")
    v = body["remark"].to_s.strip
    if v.empty?
      target.delete("remark")
    else
      target["remark"] = v
    end
  end
  if body.key?("api_key")
    new_key = body["api_key"].to_s
    # Only store a real, unmasked, non-empty value. This is the
    # single place the "api_key disappeared" bug can no longer
    # happen — there is no path that writes "" into api_key.
    if !new_key.empty? && !new_key.include?("****")
      target["api_key"] = new_key
    end
  end
  if body.key?("type")
    new_type = body["type"]
    new_type = nil if new_type.is_a?(String) && new_type.strip.empty?
    if new_type == "default"
      @agent_config.models.each do |m|
        next if m["id"] == id
        m.delete("type") if m["type"] == "default"
      end
      target["type"] = "default"
      @agent_config.current_model_id    = target["id"]
      @agent_config.current_model_index = @agent_config.models.find_index { |m| m["id"] == id } || 0
    elsif new_type.nil?
      target.delete("type")
    else
      target["type"] = new_type
    end
  end

  @agent_config.save
  json_response(res, 200, { ok: true })
rescue => e
  json_response(res, 422, { error: e.message })
end

#api_update_ocr_config(req, res) ⇒ Object

PATCH /api/config/ocr Body: { source: "off"|"auto"|"custom", model?, base_url?, api_key?, anthropic_format? }



2191
2192
2193
# File 'lib/clacky/server/http_server.rb', line 2191

def api_update_ocr_config(req, res)
  update_sidecar_config(res, "ocr", parse_json_body(req) || {})
end

#api_update_project(project_id, req, res) ⇒ Object

PATCH /api/projects/:id - update a project Body: { name:?, description:?, color:?, working_dir:?, pinned:? } - only provided fields are changed



6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
# File 'lib/clacky/server/http_server.rb', line 6761

def api_update_project(project_id, req, res)
  body = parse_json_body(req)
  return json_response(res, 404, { error: "Project not found" }) if @project_manager.find(project_id).nil?

  kwargs = {}
  kwargs[:name]        = body["name"]        if body.key?("name")
  kwargs[:description] = body["description"] if body.key?("description")
  kwargs[:color]       = body["color"]        if body.key?("color")
  kwargs[:icon]        = body["icon"]         if body.key?("icon")
  if body.key?("pinned")
    return json_response(res, 400, { error: "pinned must be true or false" }) unless body["pinned"] == true || body["pinned"] == false
    kwargs[:pinned] = body["pinned"]
  end
  if body.key?("working_dir")
    raw_wd = body["working_dir"].to_s.strip
    kwargs[:working_dir] = raw_wd.empty? ? nil : File.expand_path(raw_wd)
  end

  project = @project_manager.update(project_id, **kwargs)
  return json_response(res, 404, { error: "Project not found" }) unless project

  json_response(res, 200, { project: project })
rescue ArgumentError => e
  json_response(res, 400, { error: e.message })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_update_search_config(req, res) ⇒ Object

PATCH /api/config/search Body: { provider: "tavily"|"", key?: "..." }



2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
# File 'lib/clacky/server/http_server.rb', line 2233

def api_update_search_config(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  provider = body["provider"].to_s.strip
  unless provider.empty? || Clacky::Utils::SearcherManager.path_for(provider)
    return json_response(res, 422, { error: "Unknown search provider: #{provider}" })
  end

  key = body["key"].to_s
  key = Clacky::SearchConfig.key if key.include?("****")

  Clacky::SearchConfig.save(provider: provider, key: key)
  json_response(res, 200, { ok: true, provider: provider })
rescue => e
  json_response(res, 422, { error: e.message })
end

#api_update_session_project(session_id, req, res) ⇒ Object

PATCH /api/sessions/:id/project — move a session into or out of a project Body: { project_id: "" } to assign, { project_id: null } to remove



6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
# File 'lib/clacky/server/http_server.rb', line 6832

def api_update_session_project(session_id, req, res)
  body       = parse_json_body(req)
  new_pid    = body.key?("project_id") ? body["project_id"] : :__unset

  return json_response(res, 400, { error: "project_id key is required" }) if new_pid == :__unset

  # Validate the target project exists (skip when clearing)
  if new_pid && @project_manager.find(new_pid.to_s).nil?
    return json_response(res, 400, { error: "Project not found" })
  end

  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] }
  return json_response(res, 404, { error: "Session not found" }) unless agent

  agent.project_id = new_pid ? new_pid.to_s : nil
  @session_manager.save(agent.to_session_data(updated_at: Time.now))
  broadcast_session_update(session_id)

  json_response(res, 200, { ok: true, project_id: agent.project_id })
rescue => e
  json_response(res, 500, { error: e.message })
end

#api_update_settings(req, res) ⇒ Object

PATCH /api/config/settings — update advanced settings



6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
# File 'lib/clacky/server/http_server.rb', line 6260

def api_update_settings(req, res)
  body = parse_json_body(req)
  return json_response(res, 400, { error: "Invalid JSON" }) unless body

  source_requested = body.key?("clacky_license_server")
  normalized_source = nil
  if source_requested
    begin
      normalized_source = normalize_http_origin(body["clacky_license_server"])
    rescue ArgumentError => e
      return json_response(res, 422, { ok: false, error: e.message })
    end
  end

  if body.key?("enable_compression")
    @agent_config.enable_compression = !!body["enable_compression"]
  end
  if body.key?("enable_idle_compression")
    @agent_config.enable_idle_compression = !!body["enable_idle_compression"]
  end
  if body.key?("enable_prompt_caching")
    @agent_config.enable_prompt_caching = !!body["enable_prompt_caching"]
  end
  if body.key?("memory_update_enabled")
    @agent_config.memory_update_enabled = !!body["memory_update_enabled"]
  end
  if body.key?("proxy_url")
    raw = body["proxy_url"].to_s.strip
    if raw.empty?
      @agent_config.proxy_url = nil
    else
      begin
        uri = URI.parse(raw)
        unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty?
          return json_response(res, 422, { error: "proxy_url must be a valid http(s) URL" })
        end
      rescue URI::InvalidURIError
        return json_response(res, 422, { error: "proxy_url is not a valid URL" })
      end
      @agent_config.proxy_url = raw
    end
  end

  source_changed = source_requested &&
                   normalized_source != effective_clacky_license_server
  deactivate_brand! if source_changed
  @agent_config.clacky_license_server = normalized_source if source_requested

  @agent_config.save
  payload = { ok: true }
  if source_requested
    payload.merge!(
      clacky_license_server: normalized_source,
      source_changed: source_changed,
      restarting: source_changed
    )
  end
  json_response(res, 200, payload)
  schedule_restart if source_changed
rescue => e
  json_response(res, 422, { error: e.message })
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.



3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
# File 'lib/clacky/server/http_server.rb', line 3524

def api_upgrade_version(req, res)
  json_response(res, 202, { ok: true, message: "Upgrade started" })

  Clacky::ThreadRegistry.spawn(name: "upgrade") 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.message}\n#{e.backtrace.first(5).join("\n")}")
      broadcast_all(type: "upgrade_log", line: "\n✗ Error during upgrade: #{e.message}\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.



4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
# File 'lib/clacky/server/http_server.rb', line 4324

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.message })
end

#broadcast(session_id, event) ⇒ Object

Broadcast an event to all clients subscribed to a session. Dead connections (broken pipe / closed socket / deadline exceeded) are removed automatically. Connections already marked closed are skipped upfront so one sluggish client can't delay delivery to healthy ones.



7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
# File 'lib/clacky/server/http_server.rb', line 7729

def broadcast(session_id, event)
  # Drop events emitted by a superseded agent thread. A thread carrying a
  # :task_epoch only gets through while it still owns the session; an
  # interrupted-but-unwinding old thread (e.g. a late show_progress
  # "done" from an ensure block) is silently dropped so it can't disturb
  # the new task's UI. Threads without :task_epoch (HTTP handlers, the
  # task supervisor itself) are never affected.
  my_epoch = Thread.current[:task_epoch]
  return if my_epoch && @registry.current_epoch(session_id) != my_epoch

  clients = @ws_mutex.synchronize { (@ws_clients[session_id] || []).dup }
  dead = []
  clients.each do |conn|
    if conn.closed?
      dead << conn
      next
    end
    dead << conn unless conn.send_json(event)
  end
  return if dead.empty?

  @ws_mutex.synchronize do
    (@ws_clients[session_id] || []).reject! { |conn| dead.include?(conn) }
    @all_ws_conns.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.



7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
# File 'lib/clacky/server/http_server.rb', line 7758

def broadcast_all(event)
  clients = @ws_mutex.synchronize { @all_ws_conns.dup }
  dead = []
  clients.each do |conn|
    if conn.closed?
      dead << conn
      next
    end
    dead << conn unless conn.send_json(event)
  end
  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.



7778
7779
7780
7781
7782
7783
# File 'lib/clacky/server/http_server.rb', line 7778

def broadcast_session_update(session_id)
  session = @registry.snapshot(session_id)
  return unless session

  broadcast_all(type: "session_update", session: session)
end

#build_session(name:, working_dir: nil, permission_mode: :confirm_all, profile: "general", source: :manual, model_id: nil) ⇒ Object

Create a session in the registry and wire up Agent + WebUIController. Returns the new session_id. Build a new agent session.

Parameters:

  • name (String)

    display name for the session

  • working_dir (String) (defaults to: nil)

    working directory for the agent

  • permission_mode (Symbol) (defaults to: :confirm_all)

    :confirm_all (default, human present) or :auto_approve (unattended — suppresses ask_user waits)



7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
# File 'lib/clacky/server/http_server.rb', line 7798

def build_session(name:, working_dir: nil, permission_mode: :confirm_all, profile: "general", source: :manual, model_id: nil)
  working_dir ||= default_working_dir
  FileUtils.mkdir_p(working_dir) unless Dir.exist?(working_dir)
  session_id = Clacky::SessionManager.generate_id
  @registry.create(session_id: session_id)

  config = @agent_config.deep_copy
  config.permission_mode = permission_mode

  # Apply model override BEFORE creating the client — otherwise the
  # client is built from the default model entry and may route through
  # the wrong provider (e.g. sending a deepseek-v4-pro request to the
  # Bedrock-format OpenClacky endpoint, which replies "unknown model").
  #
  # We use switch_model_by_id (not a name-based rewrite of
  # current_model["model"]) because:
  #   1. Ids uniquely identify an entry across providers; names can
  #      collide between entries (deepseek vs dsk-deepseek aliases).
  #   2. switch_model_by_id only flips per-session @current_model_id
  #      in the dup'd config — it never mutates the shared @models
  #      array (see AgentConfig#deep_copy's shared-ref contract).
  #      A name rewrite would have leaked into every live session
  #      AND corrupted the on-disk config at next save.
  config.switch_model_by_id(model_id) if model_id

  # Build client from the (possibly overridden) config so api format
  # detection (Bedrock vs OpenAI vs Anthropic) uses the correct model.
  client = Clacky::Client.new(
    config.api_key,
    base_url: config.base_url,
    model: config.model_name,
    anthropic_format: config.anthropic_format?,
    api_format: config.api_format
  )

  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(updated_at: Time.now))

  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.



7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
# File 'lib/clacky/server/http_server.rb', line 7856

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.permission_mode = permission_mode
  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

#config_for_session(session_id) ⇒ Object

Resolve the AgentConfig for a given session, falling back to nil when the session isn't live so callers can use the global config instead.



6216
6217
6218
6219
6220
6221
6222
6223
# File 'lib/clacky/server/http_server.rb', line 6216

def config_for_session(session_id)
  return nil if session_id.to_s.strip.empty?
  return nil unless @registry.ensure(session_id)

  agent = nil
  @registry.with_session(session_id) { |s| agent = s[:agent] }
  agent&.config
end

#create_default_sessionObject

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.



1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
# File 'lib/clacky/server/http_server.rb', line 1041

def create_default_session
  return unless @agent_config.models_configured?

  # Restore up to 2 sessions per source type from disk. Earlier this was
  # 5/source (≤20 sessions), which exceeded max_idle_agents=10 and caused
  # the first user message after a restart to spend several seconds in
  # evict_excess_idle! serializing 10+ sessions back to disk. 2/source
  # keeps the most-recent items hot for fast switch without blowing the
  # idle budget.
  @registry.restore_from_disk(n: 2)

  # 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_dirObject

── Helpers ───────────────────────────────────────────────────────────────



7787
7788
7789
# File 'lib/clacky/server/http_server.rb', line 7787

def default_working_dir
  @agent_config&.default_working_dir || File.expand_path("~/clacky_workspace")
end

#deliver_confirmation(session_id, conf_id, result) ⇒ Object



7492
7493
7494
7495
7496
# File 'lib/clacky/server/http_server.rb', line 7492

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 ────────────────────────────────────────────────────────────────



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
# File 'lib/clacky/server/http_server.rb', line 545

def dispatch(req, res)
  path   = req.path
  method = req.request_method

  Thread.current[:lang] = req["X-Lang"].to_s.strip.then { |l| l.empty? ? nil : l }

  # CORS preflight — must run BEFORE the access-key guard because a
  # browser preflight carries no credentials (only the
  # Access-Control-Request-* headers). Returning 204 with the allow
  # headers lets cross-origin clients (container behind a domain,
  # third-party UIs) pass the preflight and reach the real request.
  if method == "OPTIONS"
    return handle_cors_preflight(req, res)
  end

  # Access key guard (skip for WebSocket upgrades)
  return unless check_access_key(req, res)

  # 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.start_with?(Clacky::Server::ApiExtensionDispatcher::MOUNT_PREFIX)
    # api_ext dispatcher applies its own per-route timeout (capped at
    # ApiExtension::MAX_TIMEOUT). Use the upper bound here so the outer
    # guard never cuts a long-running custom handler short.
    Clacky::ApiExtension::MAX_TIMEOUT + 30
  elsif path == "/api/tool/browser"
    30
  elsif path == "/api/exchange-rate"
    20
  elsif path.end_with?("/benchmark")
    20
  elsif path == "/api/media/image"
    # Image generation routes through OpenRouter (chat completions
    # with modalities:["image"]); end-to-end latency is commonly
    # 20-60s and can exceed 2 minutes for or-gpt-image-2 under load.
    300
  elsif path == "/api/media/video/status"
    # Single upstream task lookup; returns in well under a second.
    30
  elsif path == "/api/media/video"
    # Video generation (Veo via the gateway) runs an async submit+poll
    # cycle that routinely takes 1-3 minutes and can approach the
    # gateway's 8-minute ceiling. Give the local handler headroom.
    600
  elsif path == "/api/media/audio/speech"
    120
  elsif path == "/api/media/audio/transcriptions"
    30
  elsif path == "/api/media/video/understand"
    60
  elsif path.start_with?("/api/backup/download") || path == "/api/backup/run" || path == "/api/backup/restore"
    # Building/extracting a tar.gz of ~/.clacky can take a while.
    120
  elsif path == "/api/store/extension/install"
    10  # now async — just spawns a thread and returns job_id immediately
  elsif path == "/api/store/extension/import"
    # The handler reads the whole zip body synchronously (up to 80MB via
    # parse_multipart_upload) before spawning the worker thread, so this
    # must cover the network read, not just the cheap job handoff.
    60
  elsif path == "/api/store/extension/install/status"
    10
  else
    30
  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.message}\n#{e.backtrace.first(5).join("\n")}")
  json_response(res, 500, { error: e.message })
end

#extension_container(slug) ⇒ Object

Locate an installed container by slug/id (nil when not installed).



2945
2946
2947
2948
2949
2950
2951
2952
# File 'lib/clacky/server/http_server.rb', line 2945

def extension_container(slug)
  return nil if slug.to_s.strip.empty?

  result = Clacky::ExtensionLoader.load_all
  Array(result&.containers).to_h[slug.to_s]
rescue StandardError
  nil
end

#fetch_exchange_rate(from, to) ⇒ Object



1086
1087
1088
1089
1090
1091
# File 'lib/clacky/server/http_server.rb', line 1086

def fetch_exchange_rate(from, to)
  fetch_open_exchange_rate(from, to)
rescue StandardError => primary_error
  Clacky::Logger.warn("[ExchangeRate] primary source failed: #{primary_error.message}")
  fetch_frankfurter_exchange_rate(from, to)
end

#fetch_exchange_rate_json(url) ⇒ Object



1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
# File 'lib/clacky/server/http_server.rb', line 1128

def fetch_exchange_rate_json(url)
  uri = URI(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.open_timeout = 5
  http.read_timeout = 8

  req = Net::HTTP::Get.new(uri.request_uri, "Accept" => "application/json")
  response = http.request(req)
  raise "HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)

  JSON.parse(response.body.to_s)
end

#fetch_frankfurter_exchange_rate(from, to) ⇒ Object



1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
# File 'lib/clacky/server/http_server.rb', line 1111

def fetch_frankfurter_exchange_rate(from, to)
  query = URI.encode_www_form("from" => from, "to" => to)
  data  = fetch_exchange_rate_json("#{EXCHANGE_RATE_FALLBACK_URL}?#{query}")

  rate = positive_float(data.dig("rates", to))
  raise "frankfurter.app missing #{to} rate" unless rate

  {
    from: from,
    to: to,
    rate: rate,
    date: data["date"].to_s,
    updated_at: data["date"].to_s,
    source: "frankfurter.app"
  }
end

#fetch_open_exchange_rate(from, to) ⇒ Object



1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# File 'lib/clacky/server/http_server.rb', line 1093

def fetch_open_exchange_rate(from, to)
  data = fetch_exchange_rate_json("#{EXCHANGE_RATE_PRIMARY_BASE_URL}/#{URI.encode_www_form_component(from)}")
  raise "open.er-api.com returned #{data["result"] || "unknown"}" unless data["result"] == "success"

  rate = positive_float(data.dig("rates", to))
  raise "open.er-api.com missing #{to} rate" unless rate

  updated_at = data["time_last_update_utc"].to_s
  {
    from: from,
    to: to,
    rate: rate,
    date: parse_exchange_rate_date(updated_at),
    updated_at: updated_at,
    source: "open.er-api.com"
  }
end

#handle_cors_preflight(req, res) ⇒ Object

CORS preflight (OPTIONS) — respond with 204 + allow headers before any auth/routing logic so cross-origin browsers can proceed with the real request. Headers are echoed from the request where sensible.



7923
7924
7925
7926
7927
7928
7929
7930
7931
# File 'lib/clacky/server/http_server.rb', line 7923

def handle_cors_preflight(req, res)
  res.status = 204
  res["Access-Control-Allow-Origin"]  = req["Origin"] || "*"
  res["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
  res["Access-Control-Allow-Headers"] = req["Access-Control-Request-Headers"] ||
                                        "Content-Type, X-Lang, Authorization"
  res["Access-Control-Max-Age"]       = "86400"
  res.body = ""
end

#handle_edit_message(session_id, content, created_at) ⇒ Object

── Session actions ───────────────────────────────────────────────────────



7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
# File 'lib/clacky/server/http_server.rb', line 7386

def handle_edit_message(session_id, content, created_at)
  return unless @registry.exist?(session_id)

  agent = nil
  @registry.with_session(session_id) { |s| agent = s[:agent] }
  return unless agent

  if agent.history.respond_to?(:truncate_from_created_at) && !created_at.to_s.empty?
    agent.history.truncate_from_created_at(created_at)
  end

  handle_user_message(session_id, content)
end

#handle_user_message(session_id, content, files = [], references: []) ⇒ Object



7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
# File 'lib/clacky/server/http_server.rb', line 7400

def handle_user_message(session_id, content, files = [], references: [])
  return unless @registry.exist?(session_id)

  session = @registry.get(session_id)
  
  # If session is running, interrupt it first (mimics CLI behavior)
  if session[:status] == :running
    interrupt_session(session_id)

    # Give the old thread a short window to exit cleanly.
    # In the common case it returns within milliseconds (Thread#raise
    # lands on a tight loop or LLM read). If it can't be reached in
    # time (e.g. blocked in a slow subagent syscall), we proceed anyway:
    # the agent's check_stale! checkpoints will refuse to mutate
    # history once the new thread takes over.
    old_thread = nil
    @registry.with_session(session_id) { |s| old_thread = s[:thread] }
    old_thread&.join(2)
  end

  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).
  # Skip if the name looks like it was set by the user (not a system-generated "Session N").
  if agent.history.empty? && agent.name.match?(/\ASession \d+\z/)
    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.
  # created_at is shared with agent.run so the history entry and the bubble use the same value.
  msg_created_at = Time.now.to_f
  web_ui = nil
  @registry.with_session(session_id) { |s| web_ui = s[:ui] }
  # Resolve the slash command once here so the realtime broadcast carries the
  # confirmed skill name (matched against the authoritative skill registry).
  # agent.run re-resolves internally for dispatch; the broadcast only needs
  # the flag for the UI to highlight a valid /command. The display name is
  # resolved against the client's language (Thread.current[:lang], set from
  # the WS message's lang field) so a zh client gets the Chinese name.
  skill_command = agent.parse_skill_command(content)
  skill_command_display = if skill_command[:found] && skill_command[:skill]
                            skill_command[:skill].display_name(Thread.current[:lang])
                          end
  # Pass the uploaded files through to the realtime broadcast so images and
  # attachments render in the bubble immediately. agent.run later appends the
  # authoritative display_files to history — but only after vision/OCR
  # processing finishes, which can take seconds. Without the preview here, a
  # page refresh inside that window shows the message without its image (the
  # "need to refresh several times before the image appears" bug).
  web_ui&.show_user_message(content, created_at: msg_created_at, source: :web, files: Array(files),
                            skill_command: skill_command[:found] ? skill_command[:skill_name] : nil,
                            skill_command_display: skill_command_display)

  # File references are now handled inside agent.run — injected as a system_injected
  # message after the user message, so replay_history skips them automatically.
  reference_contexts = build_reference_contexts(references)
  run_agent_task(session_id, agent) { agent.run(content, files: files, reference_contexts: reference_contexts, created_at: msg_created_at, references_display: references) }
end

#handle_websocket(req, res) ⇒ Object

Hijacks the TCP socket from WEBrick and upgrades it to WebSocket.



7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
# File 'lib/clacky/server/http_server.rb', line 7218

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
            on_ws_message(conn, frame.data)
          when :binary
            on_ws_message(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.message}")
end

#installed_extension_containersObject



2855
2856
2857
2858
2859
2860
# File 'lib/clacky/server/http_server.rb', line 2855

def installed_extension_containers
  result = Clacky::ExtensionLoader.load_all
  Array(result&.containers).filter_map { |id, c| [id, c] if c[:layer] == :installed }.to_h
rescue StandardError
  {}
end

#installed_extension_slugsObject

Slugs of every extension container currently loaded (any layer), used to flag "installed" on the public marketplace catalog.



2848
2849
2850
2851
2852
2853
# File 'lib/clacky/server/http_server.rb', line 2848

def installed_extension_slugs
  result = Clacky::ExtensionLoader.load_all
  Array(result&.containers).map { |id, _c| id }.to_set
rescue StandardError
  Set.new
end

#interrupt_session(session_id) ⇒ Object

Interrupt a running agent session.

Thread#raise is best-effort: it unblocks most pure-Ruby waits and Faraday reads, but can't reach a thread stuck in a C-extension syscall until that syscall returns. We raise once and return immediately.

Correctness of the takeover does not depend on the old thread dying promptly: each new task claims a fresh epoch (see run_agent_task), and any status write or UI broadcast from a superseded thread is fenced off by that epoch. A stale thread that lingers in a syscall is harmless — it self-terminates at the next check_stale! checkpoint, or when the syscall returns; either way it can no longer touch the live session.



7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
# File 'lib/clacky/server/http_server.rb', line 7510

def interrupt_session(session_id)
  @registry.with_session(session_id) do |s|
    s[:idle_timer]&.cancel
    thread = s[:thread]
    next unless thread&.alive?

    Clacky::Logger.info("[interrupt] session=#{session_id} raise")
    begin
      thread.raise(Clacky::AgentInterrupted, "Interrupted by user")
    rescue ThreadError => e
      Clacky::Logger.warn("[interrupt] raise failed: #{e.message}")
    end
  end
end

#json_response(res, status, data) ⇒ Object



7913
7914
7915
7916
7917
7918
# File 'lib/clacky/server/http_server.rb', line 7913

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 **** Mask an api_key for safe display / transport to the browser.

Contract: the returned string MUST contain "****" so callers (incl. the frontend) can reliably detect "this is a display placeholder, not a real key" and refuse to treat it as input. The old behaviour of returning the raw value for short keys was a correctness bug — it leaked short keys in plaintext to GET /api/config, and it let short masked values slip past the frontend's mask-detection.



7904
7905
7906
7907
7908
7909
7910
7911
# File 'lib/clacky/server/http_server.rb', line 7904

def mask_api_key(key)
  return "" if key.nil? || key.empty?
  if key.length <= 12
    # Very short key — show the first char only, redact the rest.
    return "#{key[0]}****"
  end
  "#{key[0..7]}****#{key[-4..]}"
end

#media_capabilities_payload(cfg = @agent_config) ⇒ Object

Capability summary for the model dropdown's footer. vision — true when the current default model handles images itself OR a vision sidecar is configured (ocr_state covers both). image/video/audio — true only when a dedicated sidecar is configured; the chat model can never generate these on its own.



6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
# File 'lib/clacky/server/http_server.rb', line 6230

def media_capabilities_payload(cfg = @agent_config)
  ocr = cfg.ocr_state
  out = {
    vision: {
      configured: !!ocr["configured"],
      primary:    !!ocr["primary"],
      model:      ocr["model"]
    }
  }
  Clacky::Providers::MEDIA_KINDS.each do |t|
    state = cfg.media_state(t)
    out[t] = { configured: !!state["configured"], model: state["model"] }
  end
  out
end

#normalize_currency_code(value, fallback:) ⇒ Object



1080
1081
1082
1083
1084
# File 'lib/clacky/server/http_server.rb', line 1080

def normalize_currency_code(value, fallback:)
  code = value.to_s.strip.upcase
  code = fallback if code.empty?
  code.match?(/\A[A-Z]{3}\z/) ? code : nil
end

#not_found(res) ⇒ Object



7989
7990
7991
7992
7993
# File 'lib/clacky/server/http_server.rb', line 7989

def not_found(res)
  res.status = 404
  res["Access-Control-Allow-Origin"] = "*"
  res.body   = "Not Found"
end

#on_ws_close(conn) ⇒ Object



7379
7380
7381
7382
# File 'lib/clacky/server/http_server.rb', line 7379

def on_ws_close(conn)
  @ws_mutex.synchronize { @all_ws_conns.delete(conn) }
  unsubscribe(conn)
end

#on_ws_message(conn, raw) ⇒ Object



7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
# File 'lib/clacky/server/http_server.rb', line 7291

def on_ws_message(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)
      # Push a fresh snapshot so a reconnecting tab sees the true current
      # status (it may have missed session_update events while offline).
      if (snap = @registry.snapshot(session_id))
        conn.send_json(type: "session_update", session: snap)
      end
      # 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 "edit_message"
    session_id = msg["session_id"] || conn.session_id
    handle_edit_message(session_id, msg["content"].to_s, msg["created_at"].to_s)

  when "message"
    session_id = msg["session_id"] || conn.session_id
    Thread.current[:lang] = msg["lang"].to_s.strip.then { |l| l.empty? ? nil : l }
    # 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
    handle_user_message(session_id, msg["content"].to_s, (msg["files"] || []) + raw_images, references: msg["references"] || [])

  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"
    groups   = @registry.group_stats_all
    page     = @registry.list(limit: 11, exclude_type: SessionManager::GROUPED_SOURCES, exclude_project: true)
    # The sidebar's first page is capped at 10 rows total: pinned first,
    # non-pinned fill the remainder. Pinned sessions must never be
    # truncated — `page.first(10)` dropped the oldest pins once more than
    # 10 sessions were pinned.
    pinned_part, non_pinned_part = page.partition { |s| s[:pinned] }
    non_pinned_limit = [10 - pinned_part.size, 0].max
    has_more = non_pinned_part.size > non_pinned_limit
    all_sessions = pinned_part + non_pinned_part.first(non_pinned_limit)
    projects = @project_manager.all
    if projects.any?
      project_ids = projects.map { |p| p[:id] }
      project_sessions = project_ids.flat_map do |pid|
        @registry.list(project_id: pid)
      end
      # Deduplicate: project sessions that are already in the first page
      # will be replaced by the enriched version from `all_sessions`.
      paged_ids = all_sessions.map { |s| s[:id] }.to_set
      all_sessions += project_sessions.reject { |s| paged_ids.include?(s[:id]) }
    end
    conn.send_json(type: "session_list", sessions: all_sessions, has_more: has_more,
                   groups: groups, projects: projects)

  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.message}")
rescue => e
  Clacky::Logger.error("[on_ws_message] #{e.class}: #{e.message}\n#{e.backtrace.first(10).join("\n")}")
  conn.send_json(type: "error", message: e.message)
end

#on_ws_open(conn) ⇒ Object



7286
7287
7288
7289
# File 'lib/clacky/server/http_server.rb', line 7286

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_exchange_rate_date(value) ⇒ Object



1149
1150
1151
1152
1153
1154
1155
# File 'lib/clacky/server/http_server.rb', line 1149

def parse_exchange_rate_date(value)
  return "" if value.to_s.strip.empty?

  Date.parse(value.to_s).iso8601
rescue ArgumentError
  ""
end

#parse_json_body(req) ⇒ Object



7933
7934
7935
7936
7937
7938
7939
# File 'lib/clacky/server/http_server.rb', line 7933

def parse_json_body(req)
  return {} if req.body.nil? || req.body.empty?

  JSON.parse(req.body)
rescue JSON::ParserError
  {}
end

#positive_float(value) ⇒ Object



1142
1143
1144
1145
1146
1147
# File 'lib/clacky/server/http_server.rb', line 1142

def positive_float(value)
  rate = Float(value)
  rate.positive? ? rate : nil
rescue ArgumentError, TypeError
  nil
end

#run_session_task(session_id, prompt, display_message: nil) ⇒ Object

for the client to subscribe. The user bubble is persisted via display_text (Agent#run → history → replay_history), so the frontend only needs to navigate over and load history — no realtime broadcast, no subscribe-timing race. This is the stable entry point for programmatic "create session + run now" flows (spawn, extensions).



7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
# File 'lib/clacky/server/http_server.rb', line 7529

def run_session_task(session_id, prompt, display_message: nil)
  return unless @registry.exist?(session_id)

  agent = nil
  web_ui = nil
  @registry.with_session(session_id) do |s|
    agent = s[:agent]
    web_ui = s[:ui]
  end
  return unless agent

  web_ui&.show_user_message(display_message, source: :web) if display_message

  run_agent_task(session_id, agent) { agent.run(prompt, display_text: display_message) }
end

#serve_file_download(res, path) ⇒ Object

Stream a file to the client as a download. Content-Type is always application/octet-stream — the browser determines file type and handling from the filename extension in Content-Disposition.



4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
# File 'lib/clacky/server/http_server.rb', line 4394

def serve_file_download(res, path)
  filename = File.basename(path)

  res.status                  = 200
  res["Content-Type"]         = "application/octet-stream"
  res["Content-Disposition"]  = "attachment; filename=\"#{filename}\""
  res["Content-Length"]       = File.size(path).to_s
  res["Access-Control-Allow-Origin"] = "*"
  res.body = File.binread(path)
end

#startObject



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
313
314
315
316
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
353
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/clacky/server/http_server.rb', line 284

def start
  @start_time = Time.now
  # One-time migration: move legacy trash contents into file-trash/ subdirectory.
  Clacky::TrashDirectory.migrate_legacy_if_needed

  # Enable console logging for the server process so log lines are visible
  # in the terminal. Only echo when stderr is a real terminal — under a
  # LaunchAgent it's redirected to the log file, and echoing would write
  # every line twice (Logger already wrote it to that same file).
  Clacky::Logger.console = $stderr.isatty

  Clacky::Logger.info("[HttpServer PID=#{Process.pid}] start() mode=#{@inherited_socket ? 'worker' : 'standalone'} inherited_socket=#{@inherited_socket.inspect} master_pid=#{@master_pid.inspect}")

  # 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.
  # CLACKY_SERVER_HOST always points at 127.0.0.1 so child processes hit
  # the loopback listener (no access key required), regardless of bind.
  ENV["CLACKY_SERVER_PORT"]  = @port.to_s
  ENV["CLACKY_SERVER_HOST"]  = "127.0.0.1"
  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
    @draining = true
    # Flip the process-wide cooperative shutdown flag FIRST so agent
    # threads poll it at safe points (stream chunk callbacks, retry
    # loops, main loop) and exit cleanly instead of spinning.
    Clacky::Shutdown.request!(:signal)
    begin
      # Persist in-flight agent sessions BEFORE starting the forced-exit
      # timer, so any new messages added to @history since the last save
      # are on disk before the new worker reads them after a hot restart.
      interrupt_all_agents
      Clacky::Logger.info("[shutdown] step=agents_interrupted")

      # Close active WebSocket connections so their handler threads exit
      # promptly. WEBrick's shutdown does not touch established
      # connections, and a handler parked in IO.select(30) would keep
      # the process from exiting (Ruby waits for every thread after main
      # returns), tripping the master's KILL watchdog.
      @ws_mutex.synchronize do
        @all_ws_conns.each(&:force_close!)
      end
      Clacky::Logger.info("[shutdown] step=ws_closed")

      # Detach the inherited (shared) listen socket BEFORE WEBrick.shutdown
      # so that cleanup_listener does not call shutdown(SHUT_RDWR)+close on
      # it — that would propagate to every process sharing the underlying
      # kernel socket (Master + new worker), breaking subsequent accept()
      # on Linux. macOS's BSD stack tolerates this; Linux does not.
      if @inherited_socket && server.listeners.include?(@inherited_socket)
        server.listeners.delete(@inherited_socket)
        Clacky::Logger.info("[HttpServer PID=#{Process.pid}] detached inherited socket fd=#{@inherited_socket.fileno} before shutdown")
      end
      # Close the loopback listener we created in this worker so the port
      # is freed before the next worker starts (hot restart path).
      if @loopback_listener
        server.listeners.delete(@loopback_listener)
        @loopback_listener.close rescue nil
        @loopback_listener = nil
      end
      t1 = Clacky::ThreadRegistry.spawn(name: "shutdown-stopper-channel") { @channel_manager.stop rescue nil }
      t2 = Clacky::ThreadRegistry.spawn(name: "shutdown-stopper-browser") { Clacky::BrowserManager.instance.stop rescue nil }
      t3 = Clacky::ThreadRegistry.spawn(name: "shutdown-stopper-mcp") { @mcp_registry&.shutdown rescue nil }
      # Share one 1s budget across all three stoppers (parallel), so a
      # slow channel teardown no longer delays browser/MCP cleanup.
      deadline = Time.now + 1.0
      [t1, t2, t3].each { |t| t.join([deadline - Time.now, 0.01].max) }
      Clacky::Logger.info("[shutdown] step=stoppers_stopped")
      # Force-stop any managed thread that refused to exit cooperatively,
      # then report stragglers so stray Thread.new calls get traced.
      # Grace is short: agents were already interrupted+joined above, so
      # anything still alive here is stuck and should be killed promptly.
      Clacky::ThreadRegistry.force_stop!(grace: 0.5)
      Clacky::ThreadRegistry.report_leaks!
      Clacky::Logger.info("[shutdown] step=managed_threads_stopped")
    rescue => e
      Clacky::Logger.error("[shutdown] shutdown_proc raised #{e.class}: #{e.message}")
      Clacky::Logger.error("[shutdown] #{e.backtrace.first(5).join(' | ')}")
    ensure
      # WEBrick's start() joins every request thread (th[:WEBrickThread])
      # with an unbounded join after the accept loop exits. A keep-alive
      # HTTP or WS handler blocked on socket read would pin the main
      # thread — and the process — until the master's KILL fires, so kill
      # those threads right after shutdown to let server.start return.
      Clacky::Logger.info("[shutdown] calling server.shutdown")
      server.shutdown rescue nil
      Thread.list.each { |t| t.kill if t[:WEBrickThread] }
      Clacky::Logger.info("[shutdown] server.shutdown returned")
    end
  end
  # Ruby forbids Mutex#synchronize / Thread#join inside a trap handler
  # (ThreadError: can't be called from trap context), and interrupt_all_agents
  # needs both. So the trap only flips @draining (so /health answers
  # "draining" immediately) and hands the rest to a plain thread, where
  # session persistence and WEBrick shutdown can run normally. GVL makes
  # the shutdown_once check below atomic even if INT+TERM race.
  trap("INT")  { @draining = true; Thread.new { shutdown_proc.call } }
  trap("TERM") { @draining = true; Thread.new { 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

  # When bound to a specific non-loopback address (e.g. 192.168.x.x),
  # local skills using 127.0.0.1 cannot reach the server. Attach an
  # extra loopback listener so child processes (curl in skills, MCP, etc.)
  # can always talk to the server via 127.0.0.1 without an access key.
  # Skipped for 0.0.0.0 (already covers loopback) and for loopback binds.
  @loopback_listener = nil
  if !@localhost_only && @host.to_s != "0.0.0.0"
    begin
      @loopback_listener = TCPServer.new("127.0.0.1", @port)
      @loopback_listener.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
      server.listeners << @loopback_listener
      Clacky::Logger.info("[HttpServer PID=#{Process.pid}] added loopback listener fd=#{@loopback_listener.fileno} on 127.0.0.1:#{@port}")
    rescue Errno::EADDRINUSE, Errno::EACCES => e
      Clacky::Logger.warn("[HttpServer PID=#{Process.pid}] could not add loopback listener on 127.0.0.1:#{@port}: #{e.class}: #{e.message}")
      @loopback_listener = nil
    end
  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)

  # Health check endpoint — no auth, minimal overhead.
  # Docker / orchestrators can probe this to decide container health.
  # Status stays 200 while draining so liveness probes do not kill a worker
  # that is merely handing over; readers must check the status field.
  # pid lets a caller confirm a hot restart actually swapped the worker.
  server.mount_proc("/health") do |_req, res|
    res.status          = 200
    res["Content-Type"] = "application/json"
    state               = @draining ? "draining" : "ok"
    res.body            = %Q({"status":"#{state}","pid":#{Process.pid}})
  end

  # 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"
      brand        = Clacky::BrandConfig.load
      product_name = brand.product_name || "OpenClacky"
      logo_url     = brand.logo_url || "/logo_nav_dark.png"
      logo_hidden  = logo_url.start_with?("http://", "https://") ? 'style="display:none"' : ""
      pure         = req.query["pure"] == "true"
      html = File.read(index_html_path)
                 .gsub("{{BRAND_NAME}}", product_name)
                 .gsub("{{BRAND_LOGO_URL}}", logo_url)
                 .gsub("{{BRAND_LOGO_HIDDEN}}", logo_hidden)
                 .gsub("{{EXT_SCRIPTS}}", pure ? "" : self.send(:webui_ext_script_tags))
      res.status                = 200
      res["Content-Type"]       = "text/html; charset=utf-8"
      res["Cache-Control"]      = "no-store"
      res["Pragma"]             = "no-cache"
      res.body                  = html
    elsif req.path.start_with?("/agent_ui/")
      self.send(:serve_agent_ui, req, res)
    elsif req.path.start_with?("/agent_avatar/")
      self.send(:serve_agent_avatar, req, res)
    elsif req.path.start_with?("/ext_ui/")
      self.send(:serve_ext_ui, req, res)
    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

  # Load api backends contributed by ext.yml containers into the shared
  # ApiExtension registry. Each unit mounts at /api/ext/<ext_id>/. Done
  # here (not at gem load) so handlers can resolve session_manager and
  # other host helpers as soon as they are wired up.
  Clacky::ApiExtensionLoader.load_all

  # Static verification of every ext.yml container: unknown keys, bad
  # scopes, dangling agent→panel references, layer-shadow warnings.
  # Errors from the loader itself are already surfaced elsewhere; this
  # pass covers the whole-program checks an author needs to see at boot.
  report_extension_issues

  # Start the background scheduler
  @scheduler.start
  puts "   Scheduler: #{@scheduler.schedules.size} task(s) loaded"

  # Reclaim orphaned Time Machine snapshots (sessions deleted earlier
  # without snapshot cleanup). Runs off-thread so startup stays fast.
  Clacky::ThreadRegistry.spawn(name: "snapshot-cleanup") do
    begin
      n = Clacky::SessionManager.cleanup_orphan_snapshots
      puts "   Snapshots: reclaimed #{n} orphan dir(s)" if n.positive?
    rescue StandardError => e
      Clacky::Logger.error("snapshot_cleanup_error", error: e)
    end
  end

  # 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.



7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
# File 'lib/clacky/server/http_server.rb', line 7548

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]
  display_message = session[:pending_display_message]
  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, pending_display_message: nil)

  agent = nil
  @registry.with_session(session_id) { |s| agent = s[:agent] }
  return unless agent

  # Surface a user message on screen before the agent starts thinking, so
  # programmatically-submitted tasks (e.g. meeting summarization) don't
  # appear as a thinking spinner with no preceding message. When a short
  # display_message is provided we show that instead of the full prompt.
  if display_message
    web_ui = nil
    @registry.with_session(session_id) { |s| web_ui = s[:ui] }
    web_ui&.show_user_message(display_message, source: :web)
  end

  run_agent_task(session_id, agent) { agent.run(prompt, display_text: display_message) }
end

#subscribe(session_id, conn) ⇒ Object

── WebSocket subscription management ─────────────────────────────────────



7705
7706
7707
7708
7709
7710
7711
7712
7713
# File 'lib/clacky/server/http_server.rb', line 7705

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

#toggle_extension(req, res, action) ⇒ Object



2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
# File 'lib/clacky/server/http_server.rb', line 2964

def toggle_extension(req, res, action)
  id = parse_json_body(req)["id"].to_s
  container = extension_container(id)
  if container.nil?
    json_response(res, 404, { ok: false, error: "Not installed." })
    return
  end

  action == :disable ? Clacky::ExtensionLoader.disable!(id) : Clacky::ExtensionLoader.enable!(id)
  json_response(res, 200, { ok: true, id: id, disabled: action == :disable })
rescue StandardError => e
  json_response(res, 500, { ok: false, error: e.message })
end

#trigger_async_distribution_refresh!Object

Fire a public-distribution refresh in a background Thread.

Used for installs that have a package_name configured via install.sh but haven't activated a license yet — they would otherwise never see the brand logo / theme / homepage_url until activation. See BrandConfig#refresh_distribution! for the end-to-end flow.

Contract mirrors #trigger_async_heartbeat!:

* At most one refresh Thread in flight process-wide.
* Caller never waits — Web UI first paint is not blocked on network.
* All exceptions are swallowed; a refresh failure must not crash the
server or leak through the web stack.


2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
# File 'lib/clacky/server/http_server.rb', line 2441

def trigger_async_distribution_refresh!
  refresh_source = worker_clacky_license_server
  source_current = -> { effective_clacky_license_server == refresh_source }
  unless source_current.call
    Clacky::Logger.debug("[Brand] distribution refresh skipped — worker source is stale")
    return
  end

  BRAND_DIST_REFRESH_MUTEX.synchronize do
    if @@brand_dist_refresh_inflight
      Clacky::Logger.debug("[Brand] distribution refresh already in flight, skipping")
      return
    end
    @@brand_dist_refresh_inflight = true
  end

  Clacky::ThreadRegistry.spawn(name: "brand-dist-refresh") do
    Clacky::Logger.info("[Brand] async distribution refresh starting...")
    begin
      brand  = Clacky::BrandConfig.load
      result = brand.refresh_distribution!(&source_current)
      if result[:success]
        Clacky::Logger.info("[Brand] async distribution refresh OK")
      else
        Clacky::Logger.debug("[Brand] async distribution refresh skipped/failed — #{result[:message]}")
      end
      # Free-mode skill sync: branded + unactivated installs need their
      # creator's free skills auto-installed for the "no serial number" UX.
      brand.sync_free_skills_async! if source_current.call
    rescue StandardError => e
      Clacky::Logger.warn("[Brand] async distribution refresh raised: #{e.class}: #{e.message}")
    ensure
      BRAND_DIST_REFRESH_MUTEX.synchronize do
        @@brand_dist_refresh_inflight = false
      end
    end
  end
end

#trigger_async_heartbeat!Object

Fire a heartbeat in a background Thread without blocking the caller.

Contract:

* Only one heartbeat Thread may be running at any moment across the
whole process. If one is already in flight, this call is a no-op.
* The caller never waits: it returns immediately after (at most)
spawning the Thread.
* The Thread rescues everything so a network failure cannot kill the
server or leak an exception through the web stack.


2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
# File 'lib/clacky/server/http_server.rb', line 2400

def trigger_async_heartbeat!
  BRAND_HEARTBEAT_MUTEX.synchronize do
    if @@brand_heartbeat_inflight
      Clacky::Logger.debug("[Brand] heartbeat already in flight, skipping")
      return
    end
    @@brand_heartbeat_inflight = true
  end

  Clacky::ThreadRegistry.spawn(name: "brand-heartbeat") do
    Clacky::Logger.info("[Brand] async heartbeat starting...")
    begin
      brand  = Clacky::BrandConfig.load
      result = brand.heartbeat!
      if result[:success]
        Clacky::Logger.info("[Brand] async heartbeat OK")
      else
        Clacky::Logger.warn("[Brand] async heartbeat failed — #{result[:message]}")
      end
    rescue StandardError => e
      Clacky::Logger.warn("[Brand] async heartbeat raised: #{e.class}: #{e.message}")
    ensure
      BRAND_HEARTBEAT_MUTEX.synchronize do
        @@brand_heartbeat_inflight = false
      end
    end
  end
end

#unsubscribe(conn) ⇒ Object



7715
7716
7717
7718
7719
# File 'lib/clacky/server/http_server.rb', line 7715

def unsubscribe(conn)
  @ws_mutex.synchronize do
    @ws_clients.each_value { |list| list.delete(conn) }
  end
end

#unsubscribe_all(session_id) ⇒ Object



7721
7722
7723
# File 'lib/clacky/server/http_server.rb', line 7721

def unsubscribe_all(session_id)
  @ws_mutex.synchronize { @ws_clients.delete(session_id) }
end

#websocket_upgrade?(req) ⇒ Boolean

── WebSocket ─────────────────────────────────────────────────────────────

Returns:

  • (Boolean)


7213
7214
7215
# File 'lib/clacky/server/http_server.rb', line 7213

def websocket_upgrade?(req)
  req["Upgrade"]&.downcase == "websocket"
end