@clipen/clipen-cli 1.0.0 → 1.0.2

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 (132) hide show
  1. package/README.md +56 -48
  2. package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
  3. package/apps/web/dist/index.html +1 -1
  4. package/bin/clipen.js +1 -1
  5. package/package.json +7 -6
  6. package/pyproject.toml +18 -2
  7. package/requirements/dev.txt +2 -0
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/__init__.py +7 -7
  10. package/src/clipen/analysis/artifacts.py +4 -10
  11. package/src/clipen/analysis/audio.py +10 -8
  12. package/src/clipen/analysis/evidence_service.py +345 -167
  13. package/src/clipen/analysis/image_similarity.py +5 -14
  14. package/src/clipen/analysis/keyframes.py +5 -17
  15. package/src/clipen/analysis/models.py +5 -7
  16. package/src/clipen/analysis/qwen_worker.py +19 -54
  17. package/src/clipen/analysis/resources.py +2 -1
  18. package/src/clipen/analysis/runtime.py +1 -3
  19. package/src/clipen/analysis/service.py +16 -48
  20. package/src/clipen/analysis/setup.py +11 -25
  21. package/src/clipen/analysis/setup_cli.py +5 -15
  22. package/src/clipen/analysis/storage.py +96 -278
  23. package/src/clipen/analysis/transcription.py +40 -82
  24. package/src/clipen/analysis/visual.py +109 -48
  25. package/src/clipen/annotations/__init__.py +5 -2
  26. package/src/clipen/annotations/models.py +1 -1
  27. package/src/clipen/annotations/storage.py +132 -84
  28. package/src/clipen/annotations/suggestions.py +3 -8
  29. package/src/clipen/asr_release.py +4 -11
  30. package/src/clipen/bootstrap.py +71 -61
  31. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  32. package/src/clipen/cli.py +4 -9
  33. package/src/clipen/controller/app.py +401 -214
  34. package/src/clipen/controller/server.py +28 -38
  35. package/src/clipen/domain/__init__.py +1 -1
  36. package/src/clipen/domain/media_time.py +3 -10
  37. package/src/clipen/domain/timeline.py +45 -47
  38. package/src/clipen/domain/validation.py +0 -1
  39. package/src/clipen/editing/__init__.py +1 -1
  40. package/src/clipen/editing/agent_models.py +4 -11
  41. package/src/clipen/editing/agent_repository.py +393 -172
  42. package/src/clipen/editing/agent_tools.py +180 -99
  43. package/src/clipen/editing/alignment.py +92 -52
  44. package/src/clipen/editing/alignment_setup.py +118 -70
  45. package/src/clipen/editing/alignment_worker.py +11 -9
  46. package/src/clipen/editing/change_report.py +95 -38
  47. package/src/clipen/editing/compiler.py +0 -1
  48. package/src/clipen/editing/component_looks.py +58 -34
  49. package/src/clipen/editing/component_review.py +34 -38
  50. package/src/clipen/editing/coordinator.py +213 -92
  51. package/src/clipen/editing/editorial_review.py +217 -95
  52. package/src/clipen/editing/evidence_jobs.py +457 -200
  53. package/src/clipen/editing/history_changes.py +129 -68
  54. package/src/clipen/editing/music_choices.py +8 -5
  55. package/src/clipen/editing/production_catalog.py +573 -136
  56. package/src/clipen/editing/production_limits.py +43 -17
  57. package/src/clipen/editing/production_media.py +376 -167
  58. package/src/clipen/editing/production_preview.py +322 -129
  59. package/src/clipen/editing/production_progress.py +164 -69
  60. package/src/clipen/editing/production_requirements.py +106 -39
  61. package/src/clipen/editing/production_tools.py +1064 -462
  62. package/src/clipen/editing/program_audio.py +211 -81
  63. package/src/clipen/editing/program_direction.py +59 -25
  64. package/src/clipen/editing/program_story.py +83 -45
  65. package/src/clipen/editing/program_subtitles.py +194 -96
  66. package/src/clipen/editing/programme_review.py +98 -50
  67. package/src/clipen/editing/prompt_history.py +64 -27
  68. package/src/clipen/editing/recut.py +65 -25
  69. package/src/clipen/editing/refinement_references.py +176 -86
  70. package/src/clipen/editing/resolve_export.py +449 -218
  71. package/src/clipen/editing/resolve_titles.py +162 -105
  72. package/src/clipen/editing/skill_tools.py +530 -154
  73. package/src/clipen/editing/source_dialogue.py +177 -67
  74. package/src/clipen/editing/speech_coverage.py +42 -22
  75. package/src/clipen/editing/speech_quality.py +6 -1
  76. package/src/clipen/editing/tool_receipts.py +78 -32
  77. package/src/clipen/editing/versions.py +122 -64
  78. package/src/clipen/editing/visual_preview.py +157 -61
  79. package/src/clipen/editing/workbench.py +104 -42
  80. package/src/clipen/finishing/audio.py +69 -30
  81. package/src/clipen/finishing/catalog.py +176 -93
  82. package/src/clipen/finishing/models.py +1 -1
  83. package/src/clipen/finishing/renderer.py +33 -14
  84. package/src/clipen/mcp_editing/__main__.py +3 -1
  85. package/src/clipen/mcp_editing/server.py +77 -34
  86. package/src/clipen/media/__init__.py +3 -3
  87. package/src/clipen/media/discovery.py +7 -20
  88. package/src/clipen/media/models.py +7 -18
  89. package/src/clipen/media/preview.py +14 -24
  90. package/src/clipen/media/probe.py +16 -44
  91. package/src/clipen/media/service.py +6 -19
  92. package/src/clipen/media/storage.py +33 -81
  93. package/src/clipen/music_vocabulary.py +33 -4
  94. package/src/clipen/power.py +8 -3
  95. package/src/clipen/projects/__init__.py +1 -1
  96. package/src/clipen/projects/deletion.py +19 -32
  97. package/src/clipen/projects/finishing_schema.py +3 -1
  98. package/src/clipen/projects/models.py +2 -5
  99. package/src/clipen/projects/picker.py +13 -37
  100. package/src/clipen/projects/service.py +8 -24
  101. package/src/clipen/projects/storage.py +226 -246
  102. package/src/clipen/provider_registry.py +9 -20
  103. package/src/clipen/providers/account.py +86 -35
  104. package/src/clipen/providers/claude.py +59 -25
  105. package/src/clipen/providers/claude_editing.py +14 -7
  106. package/src/clipen/providers/codex.py +73 -118
  107. package/src/clipen/providers/codex_editing.py +2 -2
  108. package/src/clipen/providers/editing_agent.py +19 -17
  109. package/src/clipen/providers/recovery.py +7 -8
  110. package/src/clipen/rendering/cover.py +18 -5
  111. package/src/clipen/rendering/custom_components.py +167 -79
  112. package/src/clipen/rendering/custom_render.py +62 -41
  113. package/src/clipen/rendering/production_effects.py +77 -45
  114. package/src/clipen/rendering/program_components.py +134 -73
  115. package/src/clipen/rendering/program_creator.py +432 -277
  116. package/src/clipen/rendering/program_identities.py +277 -182
  117. package/src/clipen/rendering/program_motion.py +140 -95
  118. package/src/clipen/rendering/program_studio.py +175 -116
  119. package/src/clipen/rendering/program_styles.py +231 -145
  120. package/src/clipen/rendering/program_subtitles.py +71 -34
  121. package/src/clipen/rendering/renderer.py +150 -121
  122. package/src/clipen/rendering/storage.py +9 -22
  123. package/src/clipen/rendering/titles.py +193 -86
  124. package/src/clipen/skills/__init__.py +1 -0
  125. package/src/clipen/skills/catalog.py +151 -55
  126. package/src/clipen/skills/library.py +13 -7
  127. package/src/clipen/skills/package.py +46 -23
  128. package/src/clipen/skills/visual_styles.py +29 -18
  129. package/src/clipen/workspace.py +15 -44
  130. package/install +0 -25
  131. package/src/clipen/planning/__init__.py +0 -9
  132. package/uninstall +0 -25
@@ -2,22 +2,22 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from contextlib import contextmanager
6
- from datetime import datetime, timezone
7
5
  import hashlib
8
6
  import json
9
7
  import os
10
- from pathlib import Path
11
8
  import platform
12
9
  import re
13
- import shutil
14
10
  import shlex
11
+ import shutil
15
12
  import stat
16
13
  import subprocess
17
14
  import sys
18
- from types import ModuleType
19
15
  import uuid
20
16
  import venv
17
+ from contextlib import contextmanager
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from types import ModuleType
21
21
  from typing import Iterator, Mapping, Sequence, TextIO
22
22
 
23
23
  from clipen.asr_release import (
@@ -25,11 +25,11 @@ from clipen.asr_release import (
25
25
  ASR_SOFTWARE_LICENSE_URL,
26
26
  DOWNLOAD_BYTES,
27
27
  INSTALLED_BYTES,
28
+ LICENSE_NOTICE,
28
29
  MODEL_NAME,
29
30
  MODEL_REPOSITORY,
30
31
  MODEL_REVISION,
31
32
  PROGRESS_RECORD_PREFIX,
32
- LICENSE_NOTICE,
33
33
  quick_release_is_ready,
34
34
  release_root,
35
35
  )
@@ -46,6 +46,7 @@ _SETUPTOOLS_VERSION = "84.0.0"
46
46
  _WHEEL_VERSION = "0.48.0"
47
47
  _PROFILE_START = "# >>> Clipen managed PATH >>>"
48
48
  _PROFILE_END = "# <<< Clipen managed PATH <<<"
49
+ # Installed commands carry this exact line and reinstalling checks for it, so it stays as first written.
49
50
  _COMMAND_MARKER = "# Managed by Clipen; rerun ./install or clipen install to update."
50
51
  _MANAGED_COMMAND_PREFIX = "# Managed by Clipen;"
51
52
  _REMOVABLE_DIRECTORIES = (
@@ -70,9 +71,7 @@ class BootstrapError(RuntimeError):
70
71
 
71
72
  def _require_posix_file_locking() -> ModuleType:
72
73
  if _fcntl is None:
73
- raise BootstrapError(
74
- "這個開發版本尚不支援 Windows;第一次設定需要 POSIX 檔案鎖"
75
- )
74
+ raise BootstrapError("這個開發版本尚不支援 Windows;第一次設定需要 POSIX 檔案鎖")
76
75
  return _fcntl
77
76
 
78
77
 
@@ -88,17 +87,17 @@ def _toml_multiline_string(line: bytes, quote: bytes | None) -> bytes | None:
88
87
  index = 0
89
88
  while index < len(line):
90
89
  if quote is not None:
91
- if quote.startswith(b'"') and line[index:index + 1] == b"\\":
90
+ if quote.startswith(b'"') and line[index : index + 1] == b"\\":
92
91
  index += 2
93
92
  elif line.startswith(quote, index):
94
93
  index += len(quote)
95
94
  quote = None
96
95
  else:
97
96
  index += 1
98
- elif line[index:index + 1] == b"#":
97
+ elif line[index : index + 1] == b"#":
99
98
  break
100
- elif line[index:index + 1] in (b'"', b"'"):
101
- character = line[index:index + 1]
99
+ elif line[index : index + 1] in (b'"', b"'"):
100
+ character = line[index : index + 1]
102
101
  quote = character * 3 if line.startswith(character * 3, index) else character
103
102
  index += len(quote)
104
103
  else:
@@ -120,7 +119,7 @@ def _replace_project_version(contents: bytes, version: bytes) -> bytes:
120
119
  line,
121
120
  )
122
121
  if match:
123
- line = line[:match.start(2)] + version + line[match.end(2):]
122
+ line = line[: match.start(2)] + version + line[match.end(2) :]
124
123
  multiline = _toml_multiline_string(line, multiline)
125
124
  result.append(line)
126
125
  return b"".join(result)
@@ -137,9 +136,7 @@ def _runtime_fingerprint(repo_root: Path, *, project_version: bytes | None) -> s
137
136
  digest.update(f"python={sys.version_info.major}.{sys.version_info.minor}\n".encode())
138
137
  digest.update(f"platform={platform.system()}-{platform.machine()}\n".encode())
139
138
  digest.update(f"repo={repo_root.resolve(strict=True)}\n".encode())
140
- digest.update(
141
- f"bootstrap-tools={_PIP_VERSION},{_SETUPTOOLS_VERSION},{_WHEEL_VERSION}\n".encode()
142
- )
139
+ digest.update(f"bootstrap-tools={_PIP_VERSION},{_SETUPTOOLS_VERSION},{_WHEEL_VERSION}\n".encode())
143
140
  for relative in (
144
141
  "pyproject.toml",
145
142
  "requirements/runtime.txt",
@@ -206,10 +203,11 @@ def _ready_runtime(root: Path, fingerprint: str, repo_root: Path) -> Path | None
206
203
  for metadata in sorted(packages.glob("clipen-*.dist-info")):
207
204
  if metadata.is_symlink() or not metadata.is_dir():
208
205
  continue
209
- version = metadata.name[len("clipen-"):-len(".dist-info")].encode()
210
- if re.fullmatch(rb"[A-Za-z0-9.!+_-]+", version) and _runtime_fingerprint(
211
- repo_root, project_version=version
212
- ) == candidate.name:
206
+ version = metadata.name[len("clipen-") : -len(".dist-info")].encode()
207
+ if (
208
+ re.fullmatch(rb"[A-Za-z0-9.!+_-]+", version)
209
+ and _runtime_fingerprint(repo_root, project_version=version) == candidate.name
210
+ ):
213
211
  return candidate
214
212
  return None
215
213
 
@@ -267,9 +265,44 @@ def _confirm_setup(
267
265
  return answer in {"", "y", "yes"}
268
266
 
269
267
 
268
+ # What the web UI is built from, inside apps/web.
269
+ _WEB_SOURCES = ("src", "public", "index.html", "package.json", "package-lock.json", "vite.config.ts", "tsconfig.json")
270
+
271
+
272
+ def _newest_web_source(web: Path) -> float:
273
+ newest = 0.0
274
+ for name in _WEB_SOURCES:
275
+ path = web / name
276
+ files = path.rglob("*") if path.is_dir() else [path]
277
+ newest = max([newest, *(item.stat().st_mtime for item in files if item.is_file())])
278
+ return newest
279
+
280
+
281
+ def ensure_web_build(repo_root: Path, stream: TextIO = sys.stdout) -> None:
282
+ """A source checkout builds its web UI when it is missing or older than its sources.
283
+
284
+ The npm package ships the UI already built and carries no web sources, so it skips this.
285
+ """
286
+ web = repo_root / "apps" / "web"
287
+ if not (web / "package.json").is_file():
288
+ return
289
+ built = web / "dist" / "index.html"
290
+ if built.is_file() and built.stat().st_mtime >= _newest_web_source(web):
291
+ return
292
+ npm = shutil.which("npm")
293
+ if npm is None:
294
+ raise BootstrapError("從原始碼執行 Clipen 需要 Node.js 18 以上來建立操作介面:https://nodejs.org")
295
+ print("正在建立 Clipen 操作介面…", file=stream)
296
+ quiet = {"cwd": web, "check": True, "stdout": subprocess.DEVNULL}
297
+ if not (web / "node_modules").is_dir():
298
+ subprocess.run([npm, "ci", "--no-audit", "--no-fund"], **quiet)
299
+ subprocess.run([npm, "run", "build"], **quiet)
300
+ print("✓ 操作介面建立完成", file=stream)
301
+
302
+
270
303
  def _install_hint(repo_root: Path) -> str:
271
304
  """How this copy of Clipen is set up again: from npm (npx) or from a source checkout."""
272
- return "npx @clipen/clipen-cli install" if (repo_root / ".clipen-npm").is_file() else "./install"
305
+ return "npx @clipen/clipen-cli install" if (repo_root / ".clipen-npm").is_file() else "./clipen install"
273
306
 
274
307
 
275
308
  def _chrome_ready(home: Path) -> bool:
@@ -295,7 +328,7 @@ def _command_script(repo_root: Path) -> str:
295
328
  raise BootstrapError("Repo 內的 clipen launcher 不存在或不可執行")
296
329
  # Run the launcher with the Python that set Clipen up: a Mac's own python3 is too old.
297
330
  python = Path(sys.executable).resolve()
298
- return f"#!/bin/sh\n{_COMMAND_MARKER}\nexec {shlex.quote(str(python))} {shlex.quote(str(launcher))} \"$@\"\n"
331
+ return f'#!/bin/sh\n{_COMMAND_MARKER}\nexec {shlex.quote(str(python))} {shlex.quote(str(launcher))} "$@"\n'
299
332
 
300
333
 
301
334
  def _shell_profile(home: Path, environment: Mapping[str, str]) -> Path:
@@ -304,17 +337,11 @@ def _shell_profile(home: Path, environment: Mapping[str, str]) -> Path:
304
337
  return home / ".zshrc"
305
338
  if shell == "bash":
306
339
  return home / (".bash_profile" if sys.platform == "darwin" else ".bashrc")
307
- raise BootstrapError(
308
- "目前只能自動設定 zsh 或 bash;請將 Clipen 的 bin 目錄手動加入 PATH"
309
- )
340
+ raise BootstrapError("目前只能自動設定 zsh 或 bash;請將 Clipen 的 bin 目錄手動加入 PATH")
310
341
 
311
342
 
312
343
  def _profile_block(bin_root: Path) -> str:
313
- return (
314
- f"{_PROFILE_START}\n"
315
- f"export PATH={shlex.quote(str(bin_root))}:\"$PATH\"\n"
316
- f"{_PROFILE_END}"
317
- )
344
+ return f'{_PROFILE_START}\nexport PATH={shlex.quote(str(bin_root))}:"$PATH"\n{_PROFILE_END}'
318
345
 
319
346
 
320
347
  def _replace_profile_block(contents: str, block: str) -> str:
@@ -563,11 +590,7 @@ def _install_asr_bundle(
563
590
  process.terminate()
564
591
  raise BootstrapError("語音辨識設定輸出超過安全上限")
565
592
  is_progress = line.startswith(PROGRESS_RECORD_PREFIX)
566
- visible_line = (
567
- line[len(PROGRESS_RECORD_PREFIX) :].rstrip("\r\n")
568
- if is_progress
569
- else line
570
- )
593
+ visible_line = line[len(PROGRESS_RECORD_PREFIX) :].rstrip("\r\n") if is_progress else line
571
594
  log.write(f"{visible_line}\n" if is_progress else visible_line)
572
595
  log.flush()
573
596
  if is_progress and stdout.isatty():
@@ -624,9 +647,7 @@ def ensure_runtime(
624
647
  if ready is not None:
625
648
  return ready
626
649
  if runtime.exists():
627
- raise BootstrapError(
628
- f"Clipen runtime 不完整,請先保留此目錄並回報問題:{runtime}"
629
- )
650
+ raise BootstrapError(f"Clipen runtime 不完整,請先保留此目錄並回報問題:{runtime}")
630
651
  if not confirmed and not _confirm_setup(runtime, stdin, stdout):
631
652
  print("已取消,沒有建立 Clipen runtime。", file=stdout)
632
653
  return None
@@ -669,9 +690,7 @@ def ensure_installation(
669
690
  asr_requirements = repo_root / "requirements" / "asr-runtime.txt"
670
691
  runtime_ready = ready is not None
671
692
  asr_ready = quick_release_is_ready(selected_data_root, asr_requirements)
672
- command_ready = _command_is_ready(
673
- repo_root, selected_data_root, selected_home, selected_environment
674
- )
693
+ command_ready = _command_is_ready(repo_root, selected_data_root, selected_home, selected_environment)
675
694
 
676
695
  if not runtime_ready or not asr_ready:
677
696
  command_path = selected_data_root / "bin" / "clipen"
@@ -759,9 +778,7 @@ def completed_runtime(repo_root: Path, *, data_root: Path | None = None) -> Path
759
778
  fingerprint = runtime_fingerprint(repo_root)
760
779
  runtime = _ready_runtime(selected_data_root / "runtimes", fingerprint, repo_root)
761
780
  requirements = repo_root / "requirements" / "asr-runtime.txt"
762
- if runtime is None or not quick_release_is_ready(
763
- selected_data_root, requirements
764
- ):
781
+ if runtime is None or not quick_release_is_ready(selected_data_root, requirements):
765
782
  raise BootstrapError(
766
783
  f"Clipen 尚未完成安裝;第一次請執行 {_install_hint(repo_root)},"
767
784
  "已有 clipen 指令時可執行 clipen install 修復"
@@ -867,21 +884,14 @@ def uninstall_installation(
867
884
  if command_path.is_symlink() or not command_path.is_file():
868
885
  raise BootstrapError("clipen 指令位置不是安全的實體檔案,未進行移除")
869
886
  command = command_path.read_text(encoding="utf-8")
870
- if not any(
871
- line.startswith(_MANAGED_COMMAND_PREFIX)
872
- for line in command.splitlines()[:3]
873
- ):
887
+ if not any(line.startswith(_MANAGED_COMMAND_PREFIX) for line in command.splitlines()[:3]):
874
888
  raise BootstrapError("clipen 指令不是由 Clipen 管理,未進行移除")
875
889
 
876
890
  if selected_data_root.exists():
877
891
  for name in _REMOVABLE_DIRECTORIES:
878
- _validate_removable_path(
879
- resolved_data_root / name, resolved_data_root, directory=True
880
- )
892
+ _validate_removable_path(resolved_data_root / name, resolved_data_root, directory=True)
881
893
  for name in _REMOVABLE_FILES:
882
- _validate_removable_path(
883
- resolved_data_root / name, resolved_data_root, directory=False
884
- )
894
+ _validate_removable_path(resolved_data_root / name, resolved_data_root, directory=False)
885
895
 
886
896
  if selected_data_root.exists():
887
897
  for name in _REMOVABLE_DIRECTORIES:
@@ -906,26 +916,25 @@ def uninstall_installation(
906
916
 
907
917
  def _print_usage(stream: TextIO, repo_root: Path | None = None) -> None:
908
918
  npm = repo_root is not None and (repo_root / ".clipen-npm").is_file()
909
- print(f"第一次安裝:{'npx @clipen/clipen-cli' if npm else './install'}", file=stream)
919
+ print(f"第一次安裝:{'npx @clipen/clipen-cli' if npm else './clipen install'}", file=stream)
910
920
  print("啟動 Clipen:clipen codex 或 clipen claude", file=stream)
911
- print(f"移除 Clipen:{'clipen uninstall' if npm else './uninstall'}", file=stream)
921
+ print(f"移除 Clipen:{'clipen uninstall' if npm else './clipen uninstall'}", file=stream)
912
922
 
913
923
 
914
924
  def main(repo_root: Path, arguments: Sequence[str]) -> int:
915
925
  if list(arguments) in (["--help"], ["-h"]):
916
926
  _print_usage(sys.stdout, repo_root)
917
927
  return 0
918
- from clipen.provider_registry import PROVIDERS, implemented_providers
928
+ from clipen.provider_registry import PROVIDERS
919
929
 
920
- launch = len(arguments) == 1 and arguments[0] in implemented_providers()
930
+ launch = len(arguments) == 1 and arguments[0] in PROVIDERS
921
931
  if list(arguments) not in (["install"], ["uninstall"]) and not launch:
922
- if len(arguments) == 1 and arguments[0] in PROVIDERS:
923
- print(f"Clipen 目前還不支援 {PROVIDERS[arguments[0]].display_name}({arguments[0]})。", file=sys.stderr)
924
932
  _print_usage(sys.stderr, repo_root)
925
933
  return 2
926
934
  try:
927
935
  _require_posix_file_locking()
928
936
  if list(arguments) == ["install"]:
937
+ ensure_web_build(repo_root)
929
938
  runtime = ensure_installation(repo_root)
930
939
  if runtime is not None:
931
940
  print("✓ Clipen 已安裝完成")
@@ -938,6 +947,7 @@ def main(repo_root: Path, arguments: Sequence[str]) -> int:
938
947
  if list(arguments) == ["uninstall"]:
939
948
  uninstall_installation()
940
949
  return 0
950
+ ensure_web_build(repo_root)
941
951
  runtime = completed_runtime(repo_root)
942
952
  except KeyboardInterrupt:
943
953
  action = "移除" if list(arguments) == ["uninstall"] else "設定"
@@ -1,16 +1,15 @@
1
- """Path-free, bounded inputs that may be shared with a planning provider."""
1
+ """Source candidates the editing tools read: path-free, bounded and with transcript reliability."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass
6
- from enum import Enum
7
5
  import hashlib
8
6
  import json
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
9
 
10
10
  from clipen.domain import SourceSpan
11
11
  from clipen.domain.validation import require_identifier
12
12
 
13
-
14
13
  _MAX_CANDIDATES = 256
15
14
  _MAX_CONTEXT_BYTES = 128 * 1024
16
15
 
@@ -22,17 +21,12 @@ class TranscriptReliability(str, Enum):
22
21
 
23
22
 
24
23
  def _bounded_text(value: object, field: str, maximum: int, *, empty: bool = False) -> None:
25
- if (
26
- not isinstance(value, str)
27
- or "\x00" in value
28
- or len(value) > maximum
29
- or (not empty and not value.strip())
30
- ):
24
+ if not isinstance(value, str) or "\x00" in value or len(value) > maximum or (not empty and not value.strip()):
31
25
  raise ValueError(f"{field} is invalid")
32
26
 
33
27
 
34
28
  @dataclass(frozen=True)
35
- class PlanningCandidate:
29
+ class SourceCandidate:
36
30
  candidate_id: str
37
31
  source: SourceSpan
38
32
  display_name: str
@@ -44,7 +38,7 @@ class PlanningCandidate:
44
38
  def __post_init__(self) -> None:
45
39
  require_identifier(self.candidate_id, "candidate_id")
46
40
  if not isinstance(self.source, SourceSpan):
47
- raise ValueError("planning candidate source is invalid")
41
+ raise ValueError("source candidate source is invalid")
48
42
  _bounded_text(self.display_name, "candidate display name", 255)
49
43
  if self.media_kind not in {"video", "audio"}:
50
44
  raise ValueError("candidate media kind is invalid")
@@ -53,10 +47,7 @@ class PlanningCandidate:
53
47
  raise ValueError("candidate transcript reliability is invalid")
54
48
  if self.transcript_excerpt is not None:
55
49
  _bounded_text(self.transcript_excerpt, "candidate transcript excerpt", 500)
56
- if (
57
- self.transcript_reliability is not TranscriptReliability.TRUSTED
58
- and self.transcript_excerpt is not None
59
- ):
50
+ if self.transcript_reliability is not TranscriptReliability.TRUSTED and self.transcript_excerpt is not None:
60
51
  raise ValueError("untrusted transcript text cannot enter provider context")
61
52
 
62
53
  def to_provider(self) -> dict[str, object]:
@@ -86,7 +77,7 @@ class PlanningCandidate:
86
77
  }
87
78
 
88
79
  @classmethod
89
- def from_storage(cls, value: object) -> "PlanningCandidate":
80
+ def from_storage(cls, value: object) -> "SourceCandidate":
90
81
  if not isinstance(value, dict) or set(value) != {
91
82
  "candidate_id",
92
83
  "source",
@@ -96,10 +87,10 @@ class PlanningCandidate:
96
87
  "transcript_reliability",
97
88
  "transcript_excerpt",
98
89
  }:
99
- raise ValueError("stored planning candidate is invalid")
90
+ raise ValueError("stored source candidate is invalid")
100
91
  excerpt = value["transcript_excerpt"]
101
92
  if excerpt is not None and not isinstance(excerpt, str):
102
- raise ValueError("stored planning transcript excerpt is invalid")
93
+ raise ValueError("stored source transcript excerpt is invalid")
103
94
  for field in (
104
95
  "candidate_id",
105
96
  "display_name",
@@ -108,7 +99,7 @@ class PlanningCandidate:
108
99
  "transcript_reliability",
109
100
  ):
110
101
  if not isinstance(value[field], str):
111
- raise ValueError(f"stored planning candidate {field} is invalid")
102
+ raise ValueError(f"stored source candidate {field} is invalid")
112
103
  return cls(
113
104
  value["candidate_id"],
114
105
  SourceSpan.from_storage(value["source"]),
@@ -121,33 +112,33 @@ class PlanningCandidate:
121
112
 
122
113
 
123
114
  @dataclass(frozen=True)
124
- class PlanningContext:
115
+ class SourceContext:
125
116
  project_id: str
126
117
  brief: str
127
118
  material_snapshot_id: str
128
119
  analysis_snapshot_id: str
129
- candidates: tuple[PlanningCandidate, ...]
120
+ candidates: tuple[SourceCandidate, ...]
130
121
  reference_notes: tuple[str, ...] = ()
131
122
  limitations: tuple[str, ...] = ()
132
123
 
133
124
  def __post_init__(self) -> None:
134
125
  for field in ("project_id", "material_snapshot_id", "analysis_snapshot_id"):
135
126
  require_identifier(getattr(self, field), field)
136
- _bounded_text(self.brief, "planning brief", 8_000)
127
+ _bounded_text(self.brief, "source brief", 8_000)
137
128
  candidates = tuple(self.candidates)
138
129
  reference_notes = tuple(self.reference_notes)
139
130
  limitations = tuple(self.limitations)
140
131
  if not candidates or len(candidates) > _MAX_CANDIDATES:
141
- raise ValueError("planning candidates are empty or exceed the bound")
142
- if any(not isinstance(candidate, PlanningCandidate) for candidate in candidates):
143
- raise ValueError("planning context contains an invalid candidate")
132
+ raise ValueError("source candidates are empty or exceed the bound")
133
+ if any(not isinstance(candidate, SourceCandidate) for candidate in candidates):
134
+ raise ValueError("source context contains an invalid candidate")
144
135
  identifiers = [candidate.candidate_id for candidate in candidates]
145
136
  if len(identifiers) != len(set(identifiers)):
146
- raise ValueError("planning candidate IDs must be unique")
137
+ raise ValueError("source candidate IDs must be unique")
147
138
  if len(limitations) > 128:
148
- raise ValueError("planning context has too many limitations")
139
+ raise ValueError("source context has too many limitations")
149
140
  if len(reference_notes) > 32:
150
- raise ValueError("planning context has too many reference notes")
141
+ raise ValueError("source context has too many reference notes")
151
142
  for note in reference_notes:
152
143
  _bounded_text(note, "planning reference note", 1_000)
153
144
  for limitation in limitations:
@@ -156,7 +147,7 @@ class PlanningContext:
156
147
  object.__setattr__(self, "reference_notes", reference_notes)
157
148
  object.__setattr__(self, "limitations", limitations)
158
149
  if len(self.encoded()) > _MAX_CONTEXT_BYTES:
159
- raise ValueError("planning context exceeds the provider input bound")
150
+ raise ValueError("source context exceeds the provider input bound")
160
151
 
161
152
  def to_provider(self) -> dict[str, object]:
162
153
  return {
@@ -187,7 +178,7 @@ class PlanningContext:
187
178
  }
188
179
 
189
180
  @classmethod
190
- def from_storage(cls, value: object) -> "PlanningContext":
181
+ def from_storage(cls, value: object) -> "SourceContext":
191
182
  if not isinstance(value, dict) or set(value) != {
192
183
  "project_id",
193
184
  "brief",
@@ -197,16 +188,12 @@ class PlanningContext:
197
188
  "reference_notes",
198
189
  "limitations",
199
190
  }:
200
- raise ValueError("stored planning context is invalid")
191
+ raise ValueError("stored source context is invalid")
201
192
  candidates = value["candidates"]
202
193
  notes = value["reference_notes"]
203
194
  limitations = value["limitations"]
204
- if (
205
- not isinstance(candidates, list)
206
- or not isinstance(notes, list)
207
- or not isinstance(limitations, list)
208
- ):
209
- raise ValueError("stored planning context collections are invalid")
195
+ if not isinstance(candidates, list) or not isinstance(notes, list) or not isinstance(limitations, list):
196
+ raise ValueError("stored source context collections are invalid")
210
197
  for field in (
211
198
  "project_id",
212
199
  "brief",
@@ -214,15 +201,15 @@ class PlanningContext:
214
201
  "analysis_snapshot_id",
215
202
  ):
216
203
  if not isinstance(value[field], str):
217
- raise ValueError(f"stored planning context {field} is invalid")
204
+ raise ValueError(f"stored source context {field} is invalid")
218
205
  if any(not isinstance(item, str) for item in (*notes, *limitations)):
219
- raise ValueError("stored planning context text is invalid")
206
+ raise ValueError("stored source context text is invalid")
220
207
  return cls(
221
208
  value["project_id"],
222
209
  value["brief"],
223
210
  value["material_snapshot_id"],
224
211
  value["analysis_snapshot_id"],
225
- tuple(PlanningCandidate.from_storage(item) for item in candidates),
212
+ tuple(SourceCandidate.from_storage(item) for item in candidates),
226
213
  tuple(notes),
227
214
  tuple(limitations),
228
215
  )
@@ -231,10 +218,5 @@ class PlanningContext:
231
218
  def content_hash(self) -> str:
232
219
  return hashlib.sha256(self.encoded()).hexdigest()
233
220
 
234
- @property
235
- def estimated_input_tokens(self) -> int:
236
- # UTF-8 bytes / 3 intentionally overestimates mixed Chinese/JSON input.
237
- return (len(self.encoded()) + 2) // 3
238
-
239
- def candidate_map(self) -> dict[str, PlanningCandidate]:
221
+ def candidate_map(self) -> dict[str, SourceCandidate]:
240
222
  return {candidate.candidate_id: candidate for candidate in self.candidates}
package/src/clipen/cli.py CHANGED
@@ -3,13 +3,13 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
- from pathlib import Path
7
6
  import sys
7
+ from pathlib import Path
8
8
  from typing import Sequence
9
9
 
10
10
  from clipen.controller import LocalSessionAuthority
11
11
  from clipen.controller.server import ServerPaths, probe_claude, probe_codex, run_server
12
- from clipen.provider_registry import PROVIDERS, implemented_providers
12
+ from clipen.provider_registry import PROVIDERS
13
13
  from clipen.workspace import (
14
14
  WorkspaceError,
15
15
  inspect_workspace_projects,
@@ -22,7 +22,7 @@ def _repo_root() -> Path:
22
22
  root = Path(configured) if configured else Path(__file__).resolve().parents[2]
23
23
  resolved = root.resolve(strict=True)
24
24
  if not (resolved / "apps" / "web" / "dist" / "index.html").is_file():
25
- raise RuntimeError("找不到 Clipen UI production bundle")
25
+ raise RuntimeError("找不到 Clipen 操作介面,請重新安裝(npx @clipen/clipen-cli 或 ./clipen install)。")
26
26
  return resolved
27
27
 
28
28
 
@@ -35,15 +35,10 @@ def _data_root() -> Path:
35
35
 
36
36
  def main(arguments: Sequence[str] | None = None) -> int:
37
37
  selected = list(sys.argv[1:] if arguments is None else arguments)
38
- available = implemented_providers()
39
- usage = "用法:clipen " + "|".join(available)
40
38
  if len(selected) != 1 or selected[0] not in PROVIDERS:
41
- print(usage, file=sys.stderr)
39
+ print("用法:clipen " + "|".join(PROVIDERS), file=sys.stderr)
42
40
  return 2
43
41
  descriptor = PROVIDERS[selected[0]]
44
- if not descriptor.implemented:
45
- print(f"Clipen 目前還不支援 {descriptor.display_name}({descriptor.provider_id})。{usage}", file=sys.stderr)
46
- return 2
47
42
  # Resolved at call time so each probe stays a module attribute.
48
43
  probe = {"codex": probe_codex, "claude": probe_claude}[descriptor.provider_id]
49
44
  try: