openclacky 1.5.25 → 1.5.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -0
  3. data/lib/clacky/agent/chunk_index.rb +2 -1
  4. data/lib/clacky/agent/message_compressor_helper.rb +20 -2
  5. data/lib/clacky/agent/session_serializer.rb +28 -1
  6. data/lib/clacky/agent/skill_manager.rb +2 -8
  7. data/lib/clacky/agent/time_machine.rb +108 -127
  8. data/lib/clacky/agent/tool_executor.rb +2 -11
  9. data/lib/clacky/agent.rb +15 -19
  10. data/lib/clacky/agent_config.rb +14 -4
  11. data/lib/clacky/billing/media_usage.rb +69 -0
  12. data/lib/clacky/billing/platform_billing.rb +5 -0
  13. data/lib/clacky/brand_config.rb +16 -215
  14. data/lib/clacky/default_extensions/ext-studio/agents/ext-developer/system_prompt.md +2 -80
  15. data/lib/clacky/default_extensions/ext-studio/panels/studio/view.js +1 -1
  16. data/lib/clacky/default_extensions/ext-studio/skills/ext-develop/SKILL.md +10 -96
  17. data/lib/clacky/default_extensions/git/panels/git/view.js +208 -69
  18. data/lib/clacky/default_extensions/knowledge/README.md +1 -1
  19. data/lib/clacky/default_extensions/knowledge/README.zh.md +1 -1
  20. data/lib/clacky/default_extensions/knowledge/lib/importer.rb +1 -1
  21. data/lib/clacky/default_extensions/knowledge/panels/kb/view.js +3 -3
  22. data/lib/clacky/default_extensions/meeting/api/handler.rb +23 -2
  23. data/lib/clacky/default_extensions/meeting/panels/meeting/view.js +194 -36
  24. data/lib/clacky/default_extensions/preview/icon.svg +3 -2
  25. data/lib/clacky/default_extensions/secretary/panels/work/view.js +108 -33
  26. data/lib/clacky/default_extensions/side-chat/README.md +40 -0
  27. data/lib/clacky/default_extensions/side-chat/README.zh.md +40 -0
  28. data/lib/clacky/default_extensions/side-chat/api/handler.rb +90 -0
  29. data/lib/clacky/default_extensions/side-chat/api/runtime.rb +411 -0
  30. data/lib/clacky/default_extensions/side-chat/ext.yml +16 -0
  31. data/lib/clacky/default_extensions/side-chat/icon.svg +14 -0
  32. data/lib/clacky/default_extensions/side-chat/panels/side-chat/view.js +779 -0
  33. data/lib/clacky/default_extensions/terminal/README.md +36 -0
  34. data/lib/clacky/default_extensions/terminal/README.zh.md +36 -0
  35. data/lib/clacky/default_extensions/terminal/api/handler.rb +121 -0
  36. data/lib/clacky/default_extensions/terminal/api/runtime.rb +397 -0
  37. data/lib/clacky/default_extensions/terminal/ext.yml +16 -0
  38. data/lib/clacky/default_extensions/terminal/icon.svg +13 -0
  39. data/lib/clacky/default_extensions/terminal/panels/terminal/view.js +351 -0
  40. data/lib/clacky/default_extensions/terminal/vendor/LICENSE +21 -0
  41. data/lib/clacky/default_extensions/terminal/vendor/addon-fit.js +2 -0
  42. data/lib/clacky/default_extensions/terminal/vendor/xterm.css +218 -0
  43. data/lib/clacky/default_extensions/terminal/vendor/xterm.js +2 -0
  44. data/lib/clacky/default_skills/media-gen/SKILL.md +30 -9
  45. data/lib/clacky/extension/api_extension.rb +12 -0
  46. data/lib/clacky/locales/en.rb +14 -11
  47. data/lib/clacky/locales/i18n.rb +25 -0
  48. data/lib/clacky/locales/zh.rb +14 -11
  49. data/lib/clacky/media/base.rb +11 -1
  50. data/lib/clacky/media/openai_compat.rb +271 -3
  51. data/lib/clacky/message_format/open_ai.rb +17 -0
  52. data/lib/clacky/prompts/base.md +3 -0
  53. data/lib/clacky/providers.rb +33 -20
  54. data/lib/clacky/reasoning_levels.rb +75 -0
  55. data/lib/clacky/server/channel/channel_ui_controller.rb +12 -5
  56. data/lib/clacky/server/git_panel.rb +40 -18
  57. data/lib/clacky/server/http_server.rb +62 -71
  58. data/lib/clacky/server/session_registry.rb +3 -0
  59. data/lib/clacky/ui2/markdown_renderer.rb +153 -0
  60. data/lib/clacky/ui2/strings_cjk_patch.rb +134 -124
  61. data/lib/clacky/utils/file_link_normalizer.rb +30 -3
  62. data/lib/clacky/utils/frontmatter.rb +63 -0
  63. data/lib/clacky/utils/model_pricing.rb +67 -9
  64. data/lib/clacky/version.rb +1 -1
  65. data/lib/clacky/web/app.css +722 -274
  66. data/lib/clacky/web/app.js +2 -0
  67. data/lib/clacky/web/components/chat-composer.js +504 -0
  68. data/lib/clacky/web/components/chat-navigator.js +1 -1
  69. data/lib/clacky/web/components/model-picker.js +319 -20
  70. data/lib/clacky/web/components/quote-select.js +97 -39
  71. data/lib/clacky/web/core/aside.js +137 -27
  72. data/lib/clacky/web/core/ext.js +658 -81
  73. data/lib/clacky/web/features/brand/store.js +0 -4
  74. data/lib/clacky/web/features/brand/view.js +2 -99
  75. data/lib/clacky/web/features/extensions/store.js +3 -1
  76. data/lib/clacky/web/features/extensions/view.js +14 -15
  77. data/lib/clacky/web/features/new-session/store.js +4 -0
  78. data/lib/clacky/web/features/new-session/view.js +27 -4
  79. data/lib/clacky/web/features/skills/store.js +7 -5
  80. data/lib/clacky/web/features/skills/view.js +65 -16
  81. data/lib/clacky/web/features/version/view.js +1 -1
  82. data/lib/clacky/web/features/workspace/store.js +7 -3
  83. data/lib/clacky/web/features/workspace/view.js +46 -5
  84. data/lib/clacky/web/i18n.js +104 -58
  85. data/lib/clacky/web/index.html +21 -22
  86. data/lib/clacky/web/lib/box-diagram.js +239 -0
  87. data/lib/clacky/web/sessions.js +117 -151
  88. data/lib/clacky/web/settings.js +23 -16
  89. data/lib/clacky/web/ws-dispatcher.js +4 -1
  90. data/lib/clacky.rb +2 -0
  91. metadata +24 -1
@@ -530,11 +530,26 @@ Ambient audio includes rain, ocean waves, wind, and café background
530
530
  sounds. Generate it programmatically, verify the audio, and provide
531
531
  it for playback or download.
532
532
 
533
- ## Generating speech (Gemini TTS)
533
+ ## Generating speech
534
534
 
535
535
  The same `/api/media/` namespace serves text-to-speech. The user must
536
- configure a `type=audio` model in settings (recommended:
537
- `or-tts-gemini-2-5-flash`, the cheap+fast default).
536
+ configure a `type=audio` model in settings:
537
+
538
+ | Model | Voices | Limits | Notes |
539
+ |-------|--------|--------|-------|
540
+ | `dsk-deepseek-tts` (default) | `stella` (female), `tide` (male) only | ~5,000 CJK chars (see below) | Fastest (~6x realtime). Priced per character: ~$0.088 for 1,000 CJK chars, about 1.5x Gemini Flash. No style cues; unknown voices fall back to `stella` |
541
+ | `or-tts-gemini-2-5-flash` | ~40, e.g. `Kore`, `Puck`, `Charon`, `Fenrir`, `Aoede` | none in practice | Cheapest per minute (~$0.058 for the same 1,000 CJK chars), but much slower. Style cues work: "Say cheerfully: …" |
542
+ | `or-tts-gemini-2-5-pro` | same as Flash | none | Best quality, costs more |
543
+
544
+ Check which one is active with `GET /api/media/types` (`audio.model`). The
545
+ per-request cap on `dsk-deepseek-tts` depends on the route: through the
546
+ openclacky gateway it relays up to 10,000 billing characters (~5,000 hanzi,
547
+ about 15 minutes of audio), while an audio model pointed straight at
548
+ `api.deepseek.com` stops at 2,000 (~1,000 hanzi, about 3 minutes). A CJK
549
+ character bills as two. Going over rejects the request with
550
+ `invalid_argument` — for a longer script, synthesize paragraph by paragraph
551
+ and concatenate. Do that well before the cap anyway: the clip comes back
552
+ base64-wrapped, so a full 15-minute request is already a ~12 MB response.
538
553
 
539
554
  ### Endpoint
540
555
 
@@ -552,7 +567,7 @@ curl -s -X POST http://${CLACKY_SERVER_HOST}:${CLACKY_SERVER_PORT}/api/media/aud
552
567
  -H "Content-Type: application/json" \
553
568
  -d '{
554
569
  "input": "Hello and welcome to openclacky. Today we will explore...",
555
- "voice": "Kore",
570
+ "voice": "stella",
556
571
  "output_dir": "'"$(pwd)"'/assets/generated",
557
572
  "session_id": "<%= session_id %>"
558
573
  }'
@@ -561,7 +576,7 @@ curl -s -X POST http://${CLACKY_SERVER_HOST}:${CLACKY_SERVER_PORT}/api/media/aud
561
576
  | Field | Required | Values | Notes |
562
577
  |--------------|----------|---------------------------------|-------|
563
578
  | `input` | yes | string | The text to speak. Plain prose works best; you can prefix with style cues like "Say cheerfully:" or "In a calm tone:". |
564
- | `voice` | no | string voice name | Defaults to `Kore`. Common Gemini voices: `Kore`, `Puck`, `Charon`, `Fenrir`, `Aoede`. |
579
+ | `voice` | no | string voice name | Defaults to `Kore` on Gemini, `stella` on DeepSeek. See the model table above; a voice the active model doesn't know is mapped to its default rather than rejected. |
565
580
  | `output_dir` | no | absolute path | The exact directory the file is written to — nothing is appended. Use the directory the user asked for; otherwise `$(pwd)/assets/generated` as shown in the example. |
566
581
  | `session_id` | yes | string | Current Clacky session ID. Always pass the rendered value shown in the request example. |
567
582
 
@@ -574,16 +589,22 @@ blocks until the WAV is ready.
574
589
  {
575
590
  "success": true,
576
591
  "audio": "/abs/path/to/working_dir/assets/generated/tts_20260615_233522_4ff02705.wav",
577
- "model": "or-tts-gemini-2-5-flash",
592
+ "model": "dsk-deepseek-tts",
578
593
  "provider": "openclacky",
579
594
  "input": "Hello and welcome to openclacky...",
580
- "voice": "Kore",
595
+ "voice": "stella",
581
596
  "mime_type": "audio/wav",
582
- "usage": { "prompt_tokens": 13, "completion_tokens": 122, "total_tokens": 135 },
583
- "cost_usd": 0.000259
597
+ "usage": { "characters": 135, "audio_seconds": 12.4 },
598
+ "cost_usd": 0.000056
584
599
  }
585
600
  ```
586
601
 
602
+ Both engines report what they bill on: DeepSeek returns `characters` (a CJK
603
+ character counts as two) plus `audio_seconds`, Gemini returns token counts
604
+ (`prompt_tokens` / `completion_tokens`). If the audio model points straight
605
+ at `api.deepseek.com` rather than at the gateway, the response also carries
606
+ `"cost_source": "estimated"`, because DeepSeek itself reports no usage block.
607
+
587
608
  The `audio` field is an absolute path on disk. Output is mono 16-bit PCM at
588
609
  24 kHz wrapped in a standard WAV container — playable by any browser, OS
589
610
  player, or `<audio>` tag without conversion.
@@ -69,6 +69,18 @@ module Clacky
69
69
  registry[ext_id] = klass
70
70
  end
71
71
 
72
+ # `ext.<name>.<event>` frames resolve back to the extension that owns them.
73
+ # `<name>` is free-form, so a client commonly writes an id with underscores
74
+ # while ext.yml declares it with hyphens (`side-chat` vs `ext.side_chat.send`);
75
+ # accept both spellings instead of dropping the frame as unknown.
76
+ def ws_extension_for(type)
77
+ match = /\Aext\.([^.]+)\..+\z/.match(type.to_s)
78
+ return nil unless match
79
+
80
+ name = match[1]
81
+ registry[name] || registry[name.tr("_", "-")] || registry[name.tr("-", "_")]
82
+ end
83
+
72
84
  def reset_registry!
73
85
  @registry = {}
74
86
  @pending_subclasses = []
@@ -19,6 +19,20 @@ module Clacky
19
19
 
20
20
  "phase.skill_evolution" => "Reflecting on this task",
21
21
  "phase.memory_update" => "Updating long-term memory",
22
+ "progress.compressing" => "Compressing message history...",
23
+ "progress.compressing_idle" => "Idle detected. Compressing conversation to optimize costs...",
24
+ "progress.tool.browser" => "Executing browser...",
25
+ "progress.tool.edit" => "Editing a file...",
26
+ "progress.tool.file_reader" => "Reading a file...",
27
+ "progress.tool.glob" => "Finding files...",
28
+ "progress.tool.grep" => "Searching files...",
29
+ "progress.tool.invoke_skill" => "Using a skill...",
30
+ "progress.tool.terminal" => "Running command...",
31
+ "progress.tool.todo_manager" => "Updating the task plan...",
32
+ "progress.tool.web_fetch" => "Fetching web page...",
33
+ "progress.tool.web_search" => "Searching web...",
34
+ "progress.tool.write" => "Writing a file...",
35
+ "progress.tool.generic" => "Executing %<name>s...",
22
36
  "llm.error.insufficient_credit" => "Insufficient credit, please top up your account to continue",
23
37
  "llm.error.rate_limit_400" => "Too many requests or model temporarily unavailable. Please switch to another model and retry",
24
38
  "llm.error.invalid_api_key" => "API key is invalid or expired, please update it in Settings",
@@ -67,17 +81,6 @@ module Clacky
67
81
  "channel.questions.incomplete" => "Please answer every question first.",
68
82
  "channel.progress.thinking" => "Thinking...",
69
83
  "channel.progress.working" => "Working...",
70
- "channel.progress.tool.browser" => "Using the browser...",
71
- "channel.progress.tool.edit" => "Editing a file...",
72
- "channel.progress.tool.file_reader" => "Reading a file...",
73
- "channel.progress.tool.glob" => "Finding files...",
74
- "channel.progress.tool.grep" => "Searching files...",
75
- "channel.progress.tool.invoke_skill" => "Using a skill...",
76
- "channel.progress.tool.terminal" => "Running a command...",
77
- "channel.progress.tool.todo_manager" => "Updating the task plan...",
78
- "channel.progress.tool.web_fetch" => "Reading a web page...",
79
- "channel.progress.tool.web_search" => "Searching the web...",
80
- "channel.progress.tool.write" => "Writing a file...",
81
84
  "channel.progress.task_interrupted" => "Task interrupted.",
82
85
  "channel.progress.waiting_response" => "Waiting for your response.",
83
86
  "channel.progress.step" => "%<count>d step",
@@ -11,10 +11,35 @@ module Clacky
11
11
  }.freeze
12
12
  DEFAULT_LOCALE = "en"
13
13
 
14
+ # Tools that have a dedicated progress phrase. Anything else falls back to
15
+ # "Executing <tool>..." so a newly added tool still says something sensible.
16
+ PROGRESS_TOOLS = %w[
17
+ browser edit file_reader glob grep invoke_skill terminal todo_manager
18
+ web_fetch web_search write
19
+ ].freeze
20
+
14
21
  def self.t(key, **vars)
15
22
  translate(locale, key, **vars)
16
23
  end
17
24
 
25
+ # Progress line shown while a tool runs (TUI spinner, Web UI status pill,
26
+ # IM channel card), localized to the active thread locale.
27
+ def self.tool_progress(tool)
28
+ translate(locale, tool_progress_key(tool), name: tool.to_s)
29
+ end
30
+
31
+ # Same phrase in every locale, for surfaces that render all translations
32
+ # at once (IM cards).
33
+ def self.tool_progress_translations(tool)
34
+ translations(tool_progress_key(tool), name: tool.to_s)
35
+ end
36
+
37
+ def self.tool_progress_key(tool)
38
+ name = tool.to_s.downcase
39
+ PROGRESS_TOOLS.include?(name) ? "progress.tool.#{name}" : "progress.tool.generic"
40
+ end
41
+ private_class_method :tool_progress_key
42
+
18
43
  def self.translate(code, key, **vars)
19
44
  table = LOCALES[code] || LOCALES[DEFAULT_LOCALE]
20
45
  msg = table[key] || LOCALES[DEFAULT_LOCALE][key] || key
@@ -19,6 +19,20 @@ module Clacky
19
19
 
20
20
  "phase.skill_evolution" => "正在复盘本次任务",
21
21
  "phase.memory_update" => "正在更新长期记忆",
22
+ "progress.compressing" => "正在压缩对话历史...",
23
+ "progress.compressing_idle" => "检测到空闲,正在压缩对话以优化成本...",
24
+ "progress.tool.browser" => "正在使用浏览器...",
25
+ "progress.tool.edit" => "正在编辑文件...",
26
+ "progress.tool.file_reader" => "正在读取文件...",
27
+ "progress.tool.glob" => "正在查找文件...",
28
+ "progress.tool.grep" => "正在搜索文件内容...",
29
+ "progress.tool.invoke_skill" => "正在使用技能...",
30
+ "progress.tool.terminal" => "正在执行命令...",
31
+ "progress.tool.todo_manager" => "正在更新任务计划...",
32
+ "progress.tool.web_fetch" => "正在读取网页...",
33
+ "progress.tool.web_search" => "正在联网搜索...",
34
+ "progress.tool.write" => "正在写入文件...",
35
+ "progress.tool.generic" => "正在执行 %<name>s...",
22
36
  "llm.error.insufficient_credit" => "API Key 账户余额不足,请前往控制台充值后继续使用",
23
37
  "llm.error.rate_limit_400" => "请求频率过高或模型暂时不可用,请暂时切换其他模型重试",
24
38
  "llm.error.invalid_api_key" => "API Key 无效或已过期,请到设置中重新配置",
@@ -67,17 +81,6 @@ module Clacky
67
81
  "channel.questions.incomplete" => "请先完成所有问题。",
68
82
  "channel.progress.thinking" => "思考中...",
69
83
  "channel.progress.working" => "处理中...",
70
- "channel.progress.tool.browser" => "正在使用浏览器...",
71
- "channel.progress.tool.edit" => "正在编辑文件...",
72
- "channel.progress.tool.file_reader" => "正在读取文件...",
73
- "channel.progress.tool.glob" => "正在查找文件...",
74
- "channel.progress.tool.grep" => "正在搜索文件内容...",
75
- "channel.progress.tool.invoke_skill" => "正在使用技能...",
76
- "channel.progress.tool.terminal" => "正在执行命令...",
77
- "channel.progress.tool.todo_manager" => "正在更新任务计划...",
78
- "channel.progress.tool.web_fetch" => "正在读取网页...",
79
- "channel.progress.tool.web_search" => "正在联网搜索...",
80
- "channel.progress.tool.write" => "正在写入文件...",
81
84
  "channel.progress.task_interrupted" => "任务已中断。",
82
85
  "channel.progress.waiting_response" => "等待你的回复。",
83
86
  "channel.progress.step" => "%<count>d 步",
@@ -44,7 +44,7 @@ module Clacky
44
44
  # @return [Hash] either audio_success_response(...) or audio_error_response(...)
45
45
  def generate_speech(input:, voice: nil, output_dir: nil, **_kwargs)
46
46
  audio_error_response(
47
- error: "Speech synthesis is not supported by #{self.class.name.split("::").last}. Use the openclacky gateway with a TTS model such as or-tts-gemini-2-5-flash.",
47
+ error: "Speech synthesis is not supported by #{self.class.name.split("::").last}. Use the openclacky gateway with a TTS model such as dsk-deepseek-tts.",
48
48
  error_type: "not_implemented",
49
49
  provider: "",
50
50
  input: input
@@ -104,6 +104,16 @@ module Clacky
104
104
  path
105
105
  end
106
106
 
107
+ private def save_audio_bytes(bytes, output_dir:, prefix: "tts", extension: "wav")
108
+ target_dir = media_output_dir(output_dir)
109
+ FileUtils.mkdir_p(target_dir)
110
+ ts = Time.now.strftime("%Y%m%d_%H%M%S")
111
+ short = SecureRandom.hex(4)
112
+ path = File.join(target_dir, "#{prefix}_#{ts}_#{short}.#{extension}")
113
+ File.binwrite(path, bytes)
114
+ path
115
+ end
116
+
107
117
  # Download a remote image URL and persist it under output_dir,
108
118
  # mirroring save_b64_image so providers that return URLs (e.g.
109
119
  # DashScope, whose links expire after 24h) land local files at the same
@@ -4,6 +4,7 @@ require "faraday"
4
4
  require "json"
5
5
  require "base64"
6
6
  require "securerandom"
7
+ require "uri"
7
8
  require_relative "base"
8
9
 
9
10
  module Clacky
@@ -30,6 +31,30 @@ module Clacky
30
31
  VIDEO_ASPECTS = %w[landscape portrait].freeze
31
32
  DEFAULT_VIDEO_DURATION = 8
32
33
 
34
+ # DeepSeek's standalone ASR endpoint lives at /v1/tools/asr, bills by
35
+ # audio duration, and decodes only 16 kHz PCM WAV and Ogg Opus. Browsers
36
+ # record webm/opus (Chrome) or mp4/aac (Safari), so callers either
37
+ # transcode first or fall back to a Gemini STT alias.
38
+ DEEPSEEK_ASR_ALIASES = %w[dsk-deepseek-asr deepseek-asr].freeze
39
+ # List price, not the running 50% promo: the discount has no published
40
+ # end date, so booking it would silently understate cost once withdrawn.
41
+ DEEPSEEK_ASR_RMB_PER_AUDIO_HOUR = 0.78
42
+ RMB_PER_USD = 7.2
43
+ DEEPSEEK_ASR_MIME_TYPES = %w[
44
+ audio/wav audio/x-wav audio/wave audio/ogg audio/opus application/ogg
45
+ ].freeze
46
+
47
+ # DeepSeek's TTS endpoint (/v1/tools/tts) answers with raw WAV bytes and
48
+ # no usage block, bills per character (¥3 / 10,000, CJK counts twice),
49
+ # and offers exactly two voices. A relay of 24 kHz mono audio runs
50
+ # ~48 KB/s, and the response is base64-wrapped by the caller, so a long
51
+ # script turns into an unusable payload — hence the cap.
52
+ DEEPSEEK_TTS_ALIASES = %w[dsk-deepseek-tts deepseek-tts].freeze
53
+ DEEPSEEK_TTS_RMB_PER_KCHAR = 0.30
54
+ DEEPSEEK_TTS_VOICES = %w[stella tide].freeze
55
+ DEEPSEEK_TTS_DEFAULT_VOICE = "stella"
56
+ DEEPSEEK_TTS_MAX_BILLING_CHARS = 2000
57
+
33
58
  def generate_image(prompt:, aspect_ratio: DEFAULT_ASPECT, output_dir: nil, n: 1, image: nil, images: nil, **_kwargs)
34
59
  provider_id = Clacky::Providers.find_by_base_url(@base_url) || "custom"
35
60
  aspect = ASPECT_TO_SIZE.key?(aspect_ratio) ? aspect_ratio : DEFAULT_ASPECT
@@ -280,6 +305,10 @@ module Clacky
280
305
  )
281
306
  end
282
307
 
308
+ return deepseek_speech(
309
+ input: input, voice: voice, output_dir: output_dir, provider_id: provider_id
310
+ ) if deepseek_direct?
311
+
283
312
  payload = { model: @model, input: input }
284
313
  payload[:voice] = voice if voice && !voice.to_s.strip.empty?
285
314
 
@@ -344,7 +373,25 @@ module Clacky
344
373
  )
345
374
  end
346
375
 
347
- ext = mime_type.split(";").first.split("/").last.then { |e| e == "mpeg" ? "mp3" : e }
376
+ base_mime = mime_type.to_s.split(";").first.to_s.strip.downcase
377
+ ext = base_mime.split("/").last.to_s.then { |e| e == "mpeg" ? "mp3" : e }
378
+
379
+ return deepseek_transcription(audio_base64: audio_base64, mime_type: base_mime, provider_id: provider_id) if deepseek_direct?
380
+
381
+ model = @model.to_s
382
+ if deepseek_asr_model?(model) && !DEEPSEEK_ASR_MIME_TYPES.include?(base_mime)
383
+ # The gateway answers dsk- aliases from the mainland, and DeepSeek
384
+ # rejects every container the browser records natively. Prefer a
385
+ # slower success over a hard failure.
386
+ fallback = Clacky::Providers.stt_models(provider_id).find { |m| !deepseek_asr_model?(m) }
387
+ if fallback.nil?
388
+ return transcription_error_response(
389
+ error: "DeepSeek ASR accepts only 16 kHz PCM WAV or Ogg Opus audio (got #{base_mime})",
390
+ error_type: "unsupported_audio_format", provider: provider_id
391
+ )
392
+ end
393
+ model = fallback
394
+ end
348
395
 
349
396
  # OpenRouter caps multipart uploads at 25 MB and redirects larger files
350
397
  # to base64 JSON via input_audio. Plain OpenAI-compatible providers keep
@@ -354,7 +401,7 @@ module Clacky
354
401
  if provider_id == Clacky::Providers::OPENROUTER_ID
355
402
  ext = "m4a" if ext == "mp4" # OpenRouter wants the audio format, not the container
356
403
  payload = {
357
- model: @model,
404
+ model: model,
358
405
  input_audio: {
359
406
  data: audio_base64, # raw base64 bytes, NOT a data URI
360
407
  format: ext
@@ -388,7 +435,7 @@ module Clacky
388
435
  body << audio_data.b
389
436
  body << "\r\n--#{boundary}\r\n".b
390
437
  body << "Content-Disposition: form-data; name=\"model\"\r\n\r\n".b
391
- body << @model.to_s.b
438
+ body << model.b
392
439
  unless prompt.to_s.strip.empty?
393
440
  body << "\r\n--#{boundary}\r\n".b
394
441
  body << "Content-Disposition: form-data; name=\"prompt\"\r\n\r\n".b
@@ -429,12 +476,233 @@ module Clacky
429
476
  text: parsed["text"].to_s.strip,
430
477
  provider: provider_id,
431
478
  extra: {
479
+ "model" => model,
432
480
  "usage" => parsed["usage"],
433
481
  "cost_usd" => parsed["cost_usd"]
434
482
  }.compact
435
483
  )
436
484
  end
437
485
 
486
+ # DeepSeek's standalone speech endpoint is not OpenAI-shaped: it lives on
487
+ # /v1/tools/asr, takes only the file part, and bills by audio duration.
488
+ private def deepseek_transcription(audio_base64:, mime_type:, provider_id:)
489
+ unless DEEPSEEK_ASR_MIME_TYPES.include?(mime_type)
490
+ return transcription_error_response(
491
+ error: "DeepSeek ASR accepts only 16 kHz PCM WAV or Ogg Opus audio (got #{mime_type})",
492
+ error_type: "unsupported_audio_format", provider: provider_id
493
+ )
494
+ end
495
+
496
+ ext = mime_type.include?("ogg") ? "ogg" : "wav"
497
+ audio_data = Base64.decode64(audio_base64)
498
+ boundary = "----FormBoundary#{SecureRandom.hex(8)}"
499
+ body = "".b
500
+ body << "--#{boundary}\r\n".b
501
+ body << "Content-Disposition: form-data; name=\"file\"; filename=\"chunk.#{ext}\"\r\n".b
502
+ body << "Content-Type: #{mime_type}\r\n\r\n".b
503
+ body << audio_data.b
504
+ body << "\r\n--#{boundary}--\r\n".b
505
+
506
+ begin
507
+ response = stt_connection.post(deepseek_asr_path) do |req|
508
+ req.headers["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
509
+ req.headers["Authorization"] = "Bearer #{@api_key}"
510
+ req.body = body
511
+ end
512
+ rescue Faraday::Error => e
513
+ return transcription_error_response(
514
+ error: "HTTP request failed: #{e.message}",
515
+ error_type: "network_error", provider: provider_id
516
+ )
517
+ end
518
+
519
+ unless response.success?
520
+ return transcription_error_response(
521
+ error: "Upstream #{response.status}: #{truncate(response.body, 500)}",
522
+ error_type: "api_error", provider: provider_id
523
+ )
524
+ end
525
+
526
+ parsed = parse_json(response.body)
527
+ unless parsed.is_a?(Hash)
528
+ return transcription_error_response(
529
+ error: "Invalid JSON response from upstream",
530
+ error_type: "invalid_response", provider: provider_id
531
+ )
532
+ end
533
+
534
+ transcription_success_response(
535
+ text: parsed["text"].to_s.strip,
536
+ provider: provider_id,
537
+ extra: deepseek_transcription_billing(@model, parsed["duration_ms"])
538
+ )
539
+ end
540
+
541
+ # A BYO DeepSeek key is billed by audio duration, and the upstream body
542
+ # carries only duration_ms — nothing to read a cost from, so it is
543
+ # estimated locally from the list price. Callers keep the row as
544
+ # :estimated instead of pretending it is an API-confirmed amount.
545
+ private def deepseek_transcription_billing(model, duration_ms)
546
+ duration = duration_ms.to_i
547
+ extra = { "model" => model, "duration_ms" => duration_ms }.compact
548
+ return extra unless duration > 0
549
+
550
+ extra.merge(
551
+ "usage" => { "audio_seconds" => duration / 1000.0, "duration_ms" => duration },
552
+ "cost_usd" => duration / 3_600_000.0 * DEEPSEEK_ASR_RMB_PER_AUDIO_HOUR / RMB_PER_USD,
553
+ "cost_source" => "estimated"
554
+ )
555
+ end
556
+
557
+ # DeepSeek's TTS endpoint answers with raw WAV bytes instead of a JSON
558
+ # envelope, reports no usage, and streams a WAV whose two size fields are
559
+ # 0xFFFFFFFF placeholders. Everything specific to that contract stays
560
+ # here so the OpenAI-shaped callers never see it.
561
+ private def deepseek_speech(input:, voice:, output_dir:, provider_id:)
562
+ billing_chars = deepseek_tts_billing_chars(input)
563
+ if billing_chars > DEEPSEEK_TTS_MAX_BILLING_CHARS
564
+ return audio_error_response(
565
+ error: "input is #{billing_chars} billing characters (a CJK character counts as 2); " \
566
+ "DeepSeek TTS accepts up to #{DEEPSEEK_TTS_MAX_BILLING_CHARS} per request — " \
567
+ "split the script into paragraphs and synthesize them one at a time",
568
+ error_type: "invalid_argument", provider: provider_id, input: input, voice: voice.to_s
569
+ )
570
+ end
571
+
572
+ voice_id = deepseek_tts_voice(voice)
573
+ payload = {
574
+ text: input.to_s,
575
+ voice_id: voice_id,
576
+ format: "wav",
577
+ filter_markdown: true
578
+ }
579
+
580
+ begin
581
+ response = audio_connection.post(deepseek_tts_path) do |req|
582
+ req.headers["Content-Type"] = "application/json"
583
+ req.headers["Authorization"] = "Bearer #{@api_key}"
584
+ req.body = JSON.generate(payload)
585
+ end
586
+ rescue Faraday::Error => e
587
+ return audio_error_response(
588
+ error: "HTTP request failed: #{e.message}",
589
+ error_type: "network_error", provider: provider_id, input: input, voice: voice_id
590
+ )
591
+ end
592
+
593
+ unless response.success?
594
+ return audio_error_response(
595
+ error: "Upstream #{response.status}: #{truncate(response.body, 500)}",
596
+ error_type: "api_error", provider: provider_id, input: input, voice: voice_id
597
+ )
598
+ end
599
+
600
+ wav = repair_wav_sizes(response.body)
601
+ if wav.bytesize < 44
602
+ return audio_error_response(
603
+ error: "Upstream returned #{wav.bytesize} bytes, too short to be a WAV file",
604
+ error_type: "empty_response", provider: provider_id, input: input, voice: voice_id
605
+ )
606
+ end
607
+
608
+ path = save_audio_bytes(wav, output_dir: output_dir, prefix: "tts", extension: "wav")
609
+ audio_success_response(
610
+ audio: path, input: input, voice: voice_id, provider: provider_id,
611
+ extra: {
612
+ "mime_type" => "audio/wav",
613
+ "usage" => {
614
+ "characters" => billing_chars,
615
+ "audio_seconds" => wav_duration_seconds(wav)
616
+ },
617
+ "cost_usd" => billing_chars / 1000.0 * DEEPSEEK_TTS_RMB_PER_KCHAR / RMB_PER_USD,
618
+ "cost_source" => "estimated"
619
+ }
620
+ )
621
+ end
622
+
623
+ # DeepSeek ships two voices and ignores unknown names, but the `voice`
624
+ # field is free-form for OpenAI-shaped callers, so a Gemini voice name
625
+ # must degrade to the default instead of failing.
626
+ private def deepseek_tts_voice(voice)
627
+ candidate = voice.to_s.strip.downcase
628
+ DEEPSEEK_TTS_VOICES.include?(candidate) ? candidate : DEEPSEEK_TTS_DEFAULT_VOICE
629
+ end
630
+
631
+ # DeepSeek counts a CJK character as two billing characters; every
632
+ # multi-byte rune is treated the same way so the estimate never
633
+ # understates a mixed-language script.
634
+ private def deepseek_tts_billing_chars(text)
635
+ text.to_s.each_char.sum { |ch| ch.bytesize > 1 ? 2 : 1 }
636
+ end
637
+
638
+ private def deepseek_tts_path
639
+ @base_url.to_s.chomp("/").end_with?("/v1") ? "tools/tts" : "v1/tools/tts"
640
+ end
641
+
642
+ # Rewrites the two size fields DeepSeek leaves as placeholders. Without
643
+ # this a browser reports a bogus duration and refuses to seek.
644
+ private def repair_wav_sizes(wav)
645
+ data = wav.to_s.dup.force_encoding(Encoding::BINARY)
646
+ return data if data.bytesize < 44
647
+ return data unless data.byteslice(0, 4) == "RIFF" && data.byteslice(8, 4) == "WAVE"
648
+
649
+ data[4, 4] = [data.bytesize - 8].pack("V")
650
+ offset = 12
651
+ while offset + 8 <= data.bytesize
652
+ chunk_id = data.byteslice(offset, 4)
653
+ size = data.byteslice(offset + 4, 4).unpack1("V")
654
+ if chunk_id == "data"
655
+ data[offset + 4, 4] = [data.bytesize - (offset + 8)].pack("V")
656
+ break
657
+ end
658
+ break if size <= 0 || size > data.bytesize - (offset + 8)
659
+
660
+ offset += 8 + size + (size % 2)
661
+ end
662
+ data
663
+ end
664
+
665
+ private def wav_duration_seconds(wav)
666
+ byte_rate = 0
667
+ data_len = 0
668
+ offset = 12
669
+ while offset + 8 <= wav.bytesize
670
+ chunk_id = wav.byteslice(offset, 4)
671
+ size = wav.byteslice(offset + 4, 4).unpack1("V")
672
+ case chunk_id
673
+ when "fmt "
674
+ byte_rate = wav.byteslice(offset + 16, 4).unpack1("V") if size >= 12
675
+ when "data"
676
+ data_len = size
677
+ available = wav.bytesize - (offset + 8)
678
+ data_len = available if data_len > available
679
+ break
680
+ end
681
+ break if size <= 0 || size > wav.bytesize - (offset + 8)
682
+
683
+ offset += 8 + size + (size % 2)
684
+ end
685
+ return 0.0 if byte_rate <= 0 || data_len <= 0
686
+
687
+ data_len.to_f / byte_rate
688
+ end
689
+
690
+ private def deepseek_direct?
691
+ URI.parse(@base_url.to_s).host.to_s.end_with?("deepseek.com")
692
+ rescue URI::InvalidURIError
693
+ false
694
+ end
695
+
696
+ private def deepseek_asr_model?(model)
697
+ DEEPSEEK_ASR_ALIASES.include?(model.to_s)
698
+ end
699
+
700
+ # A custom provider may point at either https://api.deepseek.com or the
701
+ # /v1 form; only one of them needs the version segment.
702
+ private def deepseek_asr_path
703
+ @base_url.to_s.chomp("/").end_with?("/v1") ? "tools/asr" : "v1/tools/asr"
704
+ end
705
+
438
706
  def understand_video(video_base64:, mime_type:, prompt: nil, **_kwargs)
439
707
  provider_id = Clacky::Providers.find_by_base_url(@base_url) || "custom"
440
708
  prompt = "Describe what you see in this frame." if prompt.to_s.strip.empty?
@@ -345,6 +345,23 @@ module Clacky
345
345
  elsif !effort_str.empty?
346
346
  body[:thinking] = { type: "adaptive" }
347
347
  end
348
+ elsif model.to_s.match?(/gemini-4-/i)
349
+ # Gemini 4 always thinks — there is no off switch — and Google's
350
+ # OpenAI shim maps reasoning_effort onto thinkingLevel verbatim
351
+ # (minimal/low→low, medium, high, xhigh on Hydrogen only). Argon
352
+ # caps at high, so anything above is clamped there rather than sent
353
+ # upstream and rejected.
354
+ ceiling = model.to_s.match?(/gemini-4-hydrogen/i) ? "xhigh" : "high"
355
+ effort =
356
+ if OFF_EFFORT_VALUES.include?(effort_str)
357
+ "low"
358
+ else
359
+ case effort_str
360
+ when "max", "xhigh" then ceiling
361
+ else effort_str
362
+ end
363
+ end
364
+ assign_effort(body, effort, responses_api) if %w[low medium high xhigh].include?(effort)
348
365
  elsif model.to_s.match?(/deepseek/i)
349
366
  # DeepSeek V4 reasoning_effort only accepts low/high/max.
350
367
  # xhigh is not recognized — map it to max. Off-like values are not
@@ -18,6 +18,9 @@
18
18
  - Don't narrate your internal deliberation. User-facing text should be relevant communication, not a running commentary.
19
19
  - Don't summarize what you just did at the end of every response. The user can read the diff.
20
20
  - Only use emojis if the user explicitly requests it. Avoid emojis in all communication unless asked.
21
+ - Prefer markdown tables and indented trees over ASCII box art. If you must draw box art,
22
+ pad by display width (a CJK character is 2 columns), keep annotations on their own lines
23
+ below the frame, and avoid symbols whose width varies between terminals (`③`, `⨯`, `←`).
21
24
 
22
25
  ## Task Tracking
23
26