@clipen/clipen-cli 0.0.0-stage → 1.0.1

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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +55 -4
  11. package/pyproject.toml +44 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/dev.txt +2 -0
  14. package/requirements/runtime.txt +20 -0
  15. package/src/clipen/__init__.py +3 -0
  16. package/src/clipen/analysis/__init__.py +89 -0
  17. package/src/clipen/analysis/artifacts.py +410 -0
  18. package/src/clipen/analysis/audio.py +394 -0
  19. package/src/clipen/analysis/evidence.py +102 -0
  20. package/src/clipen/analysis/evidence_service.py +929 -0
  21. package/src/clipen/analysis/image_similarity.py +134 -0
  22. package/src/clipen/analysis/keyframes.py +159 -0
  23. package/src/clipen/analysis/models.py +228 -0
  24. package/src/clipen/analysis/qwen_worker.py +594 -0
  25. package/src/clipen/analysis/resources.py +22 -0
  26. package/src/clipen/analysis/runtime.py +62 -0
  27. package/src/clipen/analysis/service.py +594 -0
  28. package/src/clipen/analysis/setup.py +921 -0
  29. package/src/clipen/analysis/setup_cli.py +107 -0
  30. package/src/clipen/analysis/storage.py +1864 -0
  31. package/src/clipen/analysis/transcription.py +906 -0
  32. package/src/clipen/analysis/visual.py +237 -0
  33. package/src/clipen/annotations/__init__.py +13 -0
  34. package/src/clipen/annotations/models.py +22 -0
  35. package/src/clipen/annotations/storage.py +428 -0
  36. package/src/clipen/annotations/suggestions.py +115 -0
  37. package/src/clipen/asr_release.py +132 -0
  38. package/src/clipen/bootstrap.py +978 -0
  39. package/src/clipen/candidates.py +222 -0
  40. package/src/clipen/cli.py +84 -0
  41. package/src/clipen/controller/__init__.py +17 -0
  42. package/src/clipen/controller/app.py +1657 -0
  43. package/src/clipen/controller/server.py +533 -0
  44. package/src/clipen/domain/__init__.py +30 -0
  45. package/src/clipen/domain/errors.py +5 -0
  46. package/src/clipen/domain/media_time.py +110 -0
  47. package/src/clipen/domain/timeline.py +582 -0
  48. package/src/clipen/domain/validation.py +14 -0
  49. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  50. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  51. package/src/clipen/editing/README.md +115 -0
  52. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  53. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  54. package/src/clipen/editing/__init__.py +15 -0
  55. package/src/clipen/editing/agent.py +13 -0
  56. package/src/clipen/editing/agent_models.py +127 -0
  57. package/src/clipen/editing/agent_repository.py +978 -0
  58. package/src/clipen/editing/agent_tools.py +613 -0
  59. package/src/clipen/editing/alignment.py +150 -0
  60. package/src/clipen/editing/alignment_setup.py +156 -0
  61. package/src/clipen/editing/alignment_worker.py +24 -0
  62. package/src/clipen/editing/change_report.py +128 -0
  63. package/src/clipen/editing/compiler.py +40 -0
  64. package/src/clipen/editing/component_looks.py +131 -0
  65. package/src/clipen/editing/component_review.py +74 -0
  66. package/src/clipen/editing/coordinator.py +497 -0
  67. package/src/clipen/editing/editorial_review.py +309 -0
  68. package/src/clipen/editing/evidence_jobs.py +552 -0
  69. package/src/clipen/editing/history_changes.py +192 -0
  70. package/src/clipen/editing/music_choices.py +18 -0
  71. package/src/clipen/editing/production_catalog.py +629 -0
  72. package/src/clipen/editing/production_limits.py +85 -0
  73. package/src/clipen/editing/production_media.py +435 -0
  74. package/src/clipen/editing/production_preview.py +373 -0
  75. package/src/clipen/editing/production_progress.py +236 -0
  76. package/src/clipen/editing/production_requirements.py +117 -0
  77. package/src/clipen/editing/production_tools.py +1198 -0
  78. package/src/clipen/editing/program_audio.py +248 -0
  79. package/src/clipen/editing/program_direction.py +83 -0
  80. package/src/clipen/editing/program_story.py +91 -0
  81. package/src/clipen/editing/program_subtitles.py +232 -0
  82. package/src/clipen/editing/programme_review.py +121 -0
  83. package/src/clipen/editing/prompt_history.py +84 -0
  84. package/src/clipen/editing/recut.py +167 -0
  85. package/src/clipen/editing/refinement_references.py +278 -0
  86. package/src/clipen/editing/resolve_export.py +847 -0
  87. package/src/clipen/editing/resolve_titles.py +291 -0
  88. package/src/clipen/editing/skill_tools.py +951 -0
  89. package/src/clipen/editing/source_dialogue.py +192 -0
  90. package/src/clipen/editing/speech_coverage.py +50 -0
  91. package/src/clipen/editing/speech_quality.py +11 -0
  92. package/src/clipen/editing/tool_receipts.py +98 -0
  93. package/src/clipen/editing/versions.py +219 -0
  94. package/src/clipen/editing/visual_preview.py +189 -0
  95. package/src/clipen/editing/workbench.py +136 -0
  96. package/src/clipen/filesystem.py +25 -0
  97. package/src/clipen/finishing/README.md +103 -0
  98. package/src/clipen/finishing/__init__.py +1 -0
  99. package/src/clipen/finishing/audio.py +188 -0
  100. package/src/clipen/finishing/catalog.py +264 -0
  101. package/src/clipen/finishing/models.py +14 -0
  102. package/src/clipen/finishing/renderer.py +45 -0
  103. package/src/clipen/mcp_editing/__init__.py +5 -0
  104. package/src/clipen/mcp_editing/__main__.py +42 -0
  105. package/src/clipen/mcp_editing/server.py +396 -0
  106. package/src/clipen/media/__init__.py +50 -0
  107. package/src/clipen/media/discovery.py +253 -0
  108. package/src/clipen/media/models.py +349 -0
  109. package/src/clipen/media/preview.py +137 -0
  110. package/src/clipen/media/probe.py +418 -0
  111. package/src/clipen/media/service.py +304 -0
  112. package/src/clipen/media/storage.py +694 -0
  113. package/src/clipen/music_vocabulary.py +34 -0
  114. package/src/clipen/power.py +28 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +256 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +36 -0
  121. package/src/clipen/projects/models.py +189 -0
  122. package/src/clipen/projects/picker.py +232 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +159 -0
  125. package/src/clipen/projects/storage.py +1458 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +77 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +245 -0
  131. package/src/clipen/providers/claude.py +409 -0
  132. package/src/clipen/providers/claude_editing.py +118 -0
  133. package/src/clipen/providers/codex.py +991 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +567 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +269 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +139 -0
  141. package/src/clipen/rendering/custom_components.py +328 -0
  142. package/src/clipen/rendering/custom_render.py +218 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +96 -0
  158. package/src/clipen/rendering/program_components.py +254 -0
  159. package/src/clipen/rendering/program_creator.py +804 -0
  160. package/src/clipen/rendering/program_identities.py +350 -0
  161. package/src/clipen/rendering/program_motion.py +186 -0
  162. package/src/clipen/rendering/program_studio.py +227 -0
  163. package/src/clipen/rendering/program_styles.py +321 -0
  164. package/src/clipen/rendering/program_subtitles.py +89 -0
  165. package/src/clipen/rendering/renderer.py +737 -0
  166. package/src/clipen/rendering/storage.py +230 -0
  167. package/src/clipen/rendering/titles.py +467 -0
  168. package/src/clipen/skills/__init__.py +5 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +314 -0
  228. package/src/clipen/skills/library.py +137 -0
  229. package/src/clipen/skills/package.py +254 -0
  230. package/src/clipen/skills/visual_styles.py +55 -0
  231. package/src/clipen/workspace.py +181 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,978 @@
1
+ """Standard-library-only source bootstrap used before Clipen dependencies exist."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import platform
9
+ import re
10
+ import shlex
11
+ import shutil
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import uuid
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
+ from typing import Iterator, Mapping, Sequence, TextIO
22
+
23
+ from clipen.asr_release import (
24
+ ASR_SOFTWARE_LICENSE,
25
+ ASR_SOFTWARE_LICENSE_URL,
26
+ DOWNLOAD_BYTES,
27
+ INSTALLED_BYTES,
28
+ LICENSE_NOTICE,
29
+ MODEL_NAME,
30
+ MODEL_REPOSITORY,
31
+ MODEL_REVISION,
32
+ PROGRESS_RECORD_PREFIX,
33
+ quick_release_is_ready,
34
+ release_root,
35
+ )
36
+
37
+ try:
38
+ import fcntl as _fcntl
39
+ except ImportError: # Windows does not provide POSIX advisory file locks.
40
+ _fcntl = None
41
+
42
+
43
+ _RUNTIME_SCHEMA = 1
44
+ _PIP_VERSION = "26.2.1"
45
+ _SETUPTOOLS_VERSION = "84.0.0"
46
+ _WHEEL_VERSION = "0.48.0"
47
+ _PROFILE_START = "# >>> Clipen managed PATH >>>"
48
+ _PROFILE_END = "# <<< Clipen managed PATH <<<"
49
+ _COMMAND_MARKER = "# Managed by Clipen; rerun ./install or clipen install to update."
50
+ _MANAGED_COMMAND_PREFIX = "# Managed by Clipen;"
51
+ _REMOVABLE_DIRECTORIES = (
52
+ "runtime", # Legacy source runtime.
53
+ "runtimes",
54
+ "asr",
55
+ "models",
56
+ "cache",
57
+ "logs",
58
+ )
59
+ _REMOVABLE_FILES = (
60
+ "setup.json", # Legacy setup receipt.
61
+ "install-receipt.json",
62
+ ".controller.json",
63
+ ".controller.lock",
64
+ )
65
+
66
+
67
+ class BootstrapError(RuntimeError):
68
+ """The managed source runtime could not be prepared safely."""
69
+
70
+
71
+ def _require_posix_file_locking() -> ModuleType:
72
+ if _fcntl is None:
73
+ raise BootstrapError("這個開發版本尚不支援 Windows;第一次設定需要 POSIX 檔案鎖")
74
+ return _fcntl
75
+
76
+
77
+ def clipen_data_root() -> Path:
78
+ if sys.platform == "darwin":
79
+ return Path.home() / "Library" / "Application Support" / "Clipen"
80
+ xdg_data = os.environ.get("XDG_DATA_HOME")
81
+ return Path(xdg_data) / "clipen" if xdg_data else Path.home() / ".local" / "share" / "clipen"
82
+
83
+
84
+ def _toml_multiline_string(line: bytes, quote: bytes | None) -> bytes | None:
85
+ """Track quoted strings so table-looking text inside TOML strings stays opaque."""
86
+ index = 0
87
+ while index < len(line):
88
+ if quote is not None:
89
+ if quote.startswith(b'"') and line[index : index + 1] == b"\\":
90
+ index += 2
91
+ elif line.startswith(quote, index):
92
+ index += len(quote)
93
+ quote = None
94
+ else:
95
+ index += 1
96
+ elif line[index : index + 1] == b"#":
97
+ break
98
+ elif line[index : index + 1] in (b'"', b"'"):
99
+ character = line[index : index + 1]
100
+ quote = character * 3 if line.startswith(character * 3, index) else character
101
+ index += len(quote)
102
+ else:
103
+ index += 1
104
+ return quote if quote is not None and len(quote) == 3 else None
105
+
106
+
107
+ def _replace_project_version(contents: bytes, version: bytes) -> bytes:
108
+ """Normalize only a literal [project].version, without requiring TOML packages."""
109
+ in_project = False
110
+ multiline = None
111
+ result = []
112
+ for line in contents.splitlines(keepends=True):
113
+ if multiline is None and re.match(rb"^[ \t]*\[", line):
114
+ in_project = bool(re.fullmatch(rb"[ \t]*\[project\][ \t]*(?:#[^\r\n]*)?(?:\r?\n)?", line))
115
+ if multiline is None and in_project:
116
+ match = re.fullmatch(
117
+ rb"[ \t]*version[ \t]*=[ \t]*(['\"])([A-Za-z0-9.!+_-]+)\1[ \t]*(?:#[^\r\n]*)?(?:\r?\n)?",
118
+ line,
119
+ )
120
+ if match:
121
+ line = line[: match.start(2)] + version + line[match.end(2) :]
122
+ multiline = _toml_multiline_string(line, multiline)
123
+ result.append(line)
124
+ return b"".join(result)
125
+
126
+
127
+ def runtime_fingerprint(repo_root: Path) -> str:
128
+ # Retain the original development-version hash so existing runtimes remain valid.
129
+ return _runtime_fingerprint(repo_root, project_version=b"0.0.0")
130
+
131
+
132
+ def _runtime_fingerprint(repo_root: Path, *, project_version: bytes | None) -> str:
133
+ digest = hashlib.sha256()
134
+ digest.update(f"schema={_RUNTIME_SCHEMA}\n".encode())
135
+ digest.update(f"python={sys.version_info.major}.{sys.version_info.minor}\n".encode())
136
+ digest.update(f"platform={platform.system()}-{platform.machine()}\n".encode())
137
+ digest.update(f"repo={repo_root.resolve(strict=True)}\n".encode())
138
+ digest.update(f"bootstrap-tools={_PIP_VERSION},{_SETUPTOOLS_VERSION},{_WHEEL_VERSION}\n".encode())
139
+ for relative in (
140
+ "pyproject.toml",
141
+ "requirements/runtime.txt",
142
+ "requirements/asr-runtime.txt",
143
+ ):
144
+ path = repo_root / relative
145
+ if not path.is_file() or path.is_symlink():
146
+ raise BootstrapError(f"缺少必要的 runtime 定義:{relative}")
147
+ digest.update(relative.encode())
148
+ contents = path.read_bytes()
149
+ if relative == "pyproject.toml" and project_version is not None:
150
+ contents = _replace_project_version(contents, project_version)
151
+ digest.update(contents)
152
+ return digest.hexdigest()[:16]
153
+
154
+
155
+ def runtime_python(runtime: Path) -> Path:
156
+ return runtime / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
157
+
158
+
159
+ def _receipt_path(runtime: Path) -> Path:
160
+ return runtime / "clipen-runtime.json"
161
+
162
+
163
+ def runtime_is_ready(runtime: Path, fingerprint: str, repo_root: Path) -> bool:
164
+ if runtime.is_symlink() or not runtime.is_dir():
165
+ return False
166
+ python = runtime_python(runtime)
167
+ receipt_path = _receipt_path(runtime)
168
+ if python.is_symlink() or not python.is_file() or not os.access(python, os.X_OK):
169
+ return False
170
+ if receipt_path.is_symlink() or not receipt_path.is_file():
171
+ return False
172
+ try:
173
+ receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
174
+ except (OSError, UnicodeError, json.JSONDecodeError):
175
+ return False
176
+ return (
177
+ isinstance(receipt, dict)
178
+ and receipt.get("schema") == _RUNTIME_SCHEMA
179
+ and receipt.get("fingerprint") == fingerprint
180
+ and receipt.get("repo_root") == str(repo_root.resolve(strict=True))
181
+ )
182
+
183
+
184
+ def _ready_runtime(root: Path, fingerprint: str, repo_root: Path) -> Path | None:
185
+ if root.is_symlink():
186
+ return None
187
+ runtime = root / fingerprint
188
+ if runtime_is_ready(runtime, fingerprint, repo_root):
189
+ return runtime
190
+ if runtime.exists() or runtime.is_symlink():
191
+ return None
192
+ # Older receipts used the unnormalized project version. Reconstruct their
193
+ # exact hash using installed package metadata; all other inputs must match.
194
+ for candidate in sorted(root.glob("[0-9a-f]" * 16)):
195
+ if not runtime_is_ready(candidate, candidate.name, repo_root):
196
+ continue
197
+ library = candidate / "lib"
198
+ python_library = library / f"python{sys.version_info.major}.{sys.version_info.minor}"
199
+ packages = python_library / "site-packages"
200
+ if any(path.is_symlink() for path in (library, python_library, packages)):
201
+ continue
202
+ for metadata in sorted(packages.glob("clipen-*.dist-info")):
203
+ if metadata.is_symlink() or not metadata.is_dir():
204
+ continue
205
+ version = metadata.name[len("clipen-") : -len(".dist-info")].encode()
206
+ if (
207
+ re.fullmatch(rb"[A-Za-z0-9.!+_-]+", version)
208
+ and _runtime_fingerprint(repo_root, project_version=version) == candidate.name
209
+ ):
210
+ return candidate
211
+ return None
212
+
213
+
214
+ def _confirm_setup(
215
+ runtime: Path,
216
+ stdin: TextIO,
217
+ stdout: TextIO,
218
+ *,
219
+ command_path: Path | None = None,
220
+ profile_path: Path | None = None,
221
+ asr_root: Path | None = None,
222
+ include_runtime: bool = True,
223
+ ) -> bool:
224
+ print("Clipen 第一次設定" if include_runtime else "Clipen 需要完成設定", file=stdout)
225
+ print("將會建立:", file=stdout)
226
+ if include_runtime:
227
+ print(" • Clipen 專用 Python 虛擬環境", file=stdout)
228
+ print(" • 鎖定版本的本機 Controller 與安全驗證套件", file=stdout)
229
+ if asr_root is not None:
230
+ print(" • 隔離的本機語音辨識執行環境", file=stdout)
231
+ print(f" • 固定版本 {MODEL_NAME} 模型", file=stdout)
232
+ if command_path is not None and profile_path is not None:
233
+ print(f" • `clipen` 指令:{command_path}", file=stdout)
234
+ print(f" • 將 Clipen 加入 PATH:{profile_path}", file=stdout)
235
+ if not _chrome_ready(Path.home()):
236
+ print(" • Chromium(這台 Mac 沒有 Google Chrome;Clipen 用它畫畫面元件,約 150 MB)", file=stdout)
237
+ if include_runtime:
238
+ print(f"Clipen runtime:{runtime}", file=stdout)
239
+ if asr_root is not None:
240
+ print(f"語音辨識:{asr_root}", file=stdout)
241
+ print(
242
+ f"語音辨識部分需下載約 {DOWNLOAD_BYTES / 1_000_000_000:.1f} GB,"
243
+ f"安裝後約 {INSTALLED_BYTES / 1_000_000_000:.1f} GB。",
244
+ file=stdout,
245
+ )
246
+ print(
247
+ f"模型來源:{MODEL_REPOSITORY} @ {MODEL_REVISION[:8]}",
248
+ file=stdout,
249
+ )
250
+ print("繁體中文轉換套件:PyPI 鎖定版本", file=stdout)
251
+ print(
252
+ f"MLX Speech 本機執行程式:{ASR_SOFTWARE_LICENSE}({ASR_SOFTWARE_LICENSE_URL})",
253
+ file=stdout,
254
+ )
255
+ print(LICENSE_NOTICE, file=stdout)
256
+ print("依網路速度可能需要數分鐘;安裝期間會持續顯示目前階段與經過時間。", file=stdout)
257
+ print("不會修改系統 Python,也不會使用 sudo。", file=stdout)
258
+ print("AI(Codex/Claude)登入與模型呼叫不會在設定階段執行。", file=stdout)
259
+ if not stdin.isatty():
260
+ raise BootstrapError("第一次設定需要在互動式 Terminal 中確認。")
261
+ stdout.write("開始完整設定?[Y/n] ")
262
+ stdout.flush()
263
+ answer = stdin.readline().strip().lower()
264
+ return answer in {"", "y", "yes"}
265
+
266
+
267
+ # What the web UI is built from, inside apps/web.
268
+ _WEB_SOURCES = ("src", "public", "index.html", "package.json", "package-lock.json", "vite.config.ts", "tsconfig.json")
269
+
270
+
271
+ def _newest_web_source(web: Path) -> float:
272
+ newest = 0.0
273
+ for name in _WEB_SOURCES:
274
+ path = web / name
275
+ files = path.rglob("*") if path.is_dir() else [path]
276
+ newest = max([newest, *(item.stat().st_mtime for item in files if item.is_file())])
277
+ return newest
278
+
279
+
280
+ def ensure_web_build(repo_root: Path, stream: TextIO = sys.stdout) -> None:
281
+ """A source checkout builds its web UI when it is missing or older than its sources.
282
+
283
+ The npm package ships the UI already built and carries no web sources, so it skips this.
284
+ """
285
+ web = repo_root / "apps" / "web"
286
+ if not (web / "package.json").is_file():
287
+ return
288
+ built = web / "dist" / "index.html"
289
+ if built.is_file() and built.stat().st_mtime >= _newest_web_source(web):
290
+ return
291
+ npm = shutil.which("npm")
292
+ if npm is None:
293
+ raise BootstrapError("從原始碼執行 Clipen 需要 Node.js 18 以上來建立操作介面:https://nodejs.org")
294
+ print("正在建立 Clipen 操作介面…", file=stream)
295
+ quiet = {"cwd": web, "check": True, "stdout": subprocess.DEVNULL}
296
+ if not (web / "node_modules").is_dir():
297
+ subprocess.run([npm, "ci", "--no-audit", "--no-fund"], **quiet)
298
+ subprocess.run([npm, "run", "build"], **quiet)
299
+ print("✓ 操作介面建立完成", file=stream)
300
+
301
+
302
+ def _install_hint(repo_root: Path) -> str:
303
+ """How this copy of Clipen is set up again: from npm (npx) or from a source checkout."""
304
+ return "npx @clipen/clipen-cli install" if (repo_root / ".clipen-npm").is_file() else "./install"
305
+
306
+
307
+ def _chrome_ready(home: Path) -> bool:
308
+ """Free designs are drawn in Chrome; Google Chrome or Playwright's Chromium will do."""
309
+ apps = [Path("/Applications/Google Chrome.app"), home / "Applications" / "Google Chrome.app"]
310
+ return any(app.exists() for app in apps) or any((home / "Library" / "Caches" / "ms-playwright").glob("chromium-*"))
311
+
312
+
313
+ def _ensure_chrome(runtime: Path, data_root: Path, home: Path, stdout: TextIO) -> None:
314
+ if _chrome_ready(home):
315
+ return
316
+ print("這台 Mac 沒有 Google Chrome;正在下載 Clipen 畫元件用的 Chromium(約 150 MB)…", file=stdout)
317
+ log_root = data_root / "logs"
318
+ log_root.mkdir(mode=0o700, parents=True, exist_ok=True)
319
+ with (log_root / "bootstrap-chromium.log").open("w", encoding="utf-8") as log:
320
+ _run_logged((str(runtime_python(runtime)), "-m", "playwright", "install", "chromium"), cwd=runtime, log=log)
321
+ print("✓ Chromium 準備完成", file=stdout)
322
+
323
+
324
+ def _command_script(repo_root: Path) -> str:
325
+ launcher = repo_root.resolve(strict=True) / "clipen"
326
+ if launcher.is_symlink() or not launcher.is_file() or not os.access(launcher, os.X_OK):
327
+ raise BootstrapError("Repo 內的 clipen launcher 不存在或不可執行")
328
+ # Run the launcher with the Python that set Clipen up: a Mac's own python3 is too old.
329
+ python = Path(sys.executable).resolve()
330
+ return f'#!/bin/sh\n{_COMMAND_MARKER}\nexec {shlex.quote(str(python))} {shlex.quote(str(launcher))} "$@"\n'
331
+
332
+
333
+ def _shell_profile(home: Path, environment: Mapping[str, str]) -> Path:
334
+ shell = Path(environment.get("SHELL", "")).name
335
+ if shell == "zsh" or (not shell and sys.platform == "darwin"):
336
+ return home / ".zshrc"
337
+ if shell == "bash":
338
+ return home / (".bash_profile" if sys.platform == "darwin" else ".bashrc")
339
+ raise BootstrapError("目前只能自動設定 zsh 或 bash;請將 Clipen 的 bin 目錄手動加入 PATH")
340
+
341
+
342
+ def _profile_block(bin_root: Path) -> str:
343
+ return f'{_PROFILE_START}\nexport PATH={shlex.quote(str(bin_root))}:"$PATH"\n{_PROFILE_END}'
344
+
345
+
346
+ def _replace_profile_block(contents: str, block: str) -> str:
347
+ if contents.count(_PROFILE_START) > 1 or contents.count(_PROFILE_END) > 1:
348
+ raise BootstrapError("shell 設定中有重複的 Clipen PATH 區塊,請先保留並回報問題")
349
+ start = contents.find(_PROFILE_START)
350
+ end = contents.find(_PROFILE_END)
351
+ if (start < 0) != (end < 0) or (start >= 0 and end < start):
352
+ raise BootstrapError("shell 設定中的 Clipen PATH 區塊不完整,請先保留並回報問題")
353
+ if start >= 0:
354
+ end += len(_PROFILE_END)
355
+ updated = contents[:start] + block + contents[end:]
356
+ else:
357
+ separator = "" if not contents or contents.endswith("\n") else "\n"
358
+ updated = f"{contents}{separator}{block}\n"
359
+ return updated
360
+
361
+
362
+ def _remove_profile_block(contents: str) -> str:
363
+ if contents.count(_PROFILE_START) > 1 or contents.count(_PROFILE_END) > 1:
364
+ raise BootstrapError("shell 設定中有重複的 Clipen PATH 區塊,未進行移除")
365
+ start = contents.find(_PROFILE_START)
366
+ end = contents.find(_PROFILE_END)
367
+ if (start < 0) != (end < 0) or (start >= 0 and end < start):
368
+ raise BootstrapError("shell 設定中的 Clipen PATH 區塊不完整,未進行移除")
369
+ if start < 0:
370
+ return contents
371
+ end += len(_PROFILE_END)
372
+ if end < len(contents) and contents[end] == "\n":
373
+ end += 1
374
+ elif start > 0 and contents[start - 1] == "\n":
375
+ start -= 1
376
+ return contents[:start] + contents[end:]
377
+
378
+
379
+ def _atomic_write(path: Path, contents: str, mode: int) -> None:
380
+ staging = path.parent / f".{path.name}.clipen-{uuid.uuid4().hex}.tmp"
381
+ try:
382
+ with staging.open("x", encoding="utf-8") as output:
383
+ output.write(contents)
384
+ output.flush()
385
+ os.fsync(output.fileno())
386
+ staging.chmod(mode)
387
+ os.replace(staging, path)
388
+ finally:
389
+ if staging.exists() and not staging.is_symlink():
390
+ staging.unlink()
391
+
392
+
393
+ def _install_command(
394
+ repo_root: Path,
395
+ data_root: Path,
396
+ home: Path,
397
+ environment: Mapping[str, str],
398
+ ) -> tuple[Path, Path]:
399
+ bin_root = data_root / "bin"
400
+ if bin_root.exists() and (bin_root.is_symlink() or not bin_root.is_dir()):
401
+ raise BootstrapError("Clipen bin 目錄不是安全的實體目錄")
402
+ bin_root.mkdir(mode=0o700, parents=True, exist_ok=True)
403
+ command_path = bin_root / "clipen"
404
+ script = _command_script(repo_root)
405
+ if command_path.exists() or command_path.is_symlink():
406
+ if command_path.is_symlink() or not command_path.is_file():
407
+ raise BootstrapError("Clipen 指令位置已被不安全的檔案占用")
408
+ try:
409
+ existing_command = command_path.read_text(encoding="utf-8")
410
+ except (OSError, UnicodeError) as error:
411
+ raise BootstrapError("無法安全讀取既有的 Clipen 指令") from error
412
+ if _COMMAND_MARKER not in existing_command:
413
+ raise BootstrapError("Clipen 指令位置已有其他程式,未進行覆寫")
414
+
415
+ profile_path = _shell_profile(home, environment)
416
+ if profile_path.exists() or profile_path.is_symlink():
417
+ if profile_path.is_symlink() or not profile_path.is_file():
418
+ raise BootstrapError("shell 設定檔不是安全的實體檔案,未進行修改")
419
+ try:
420
+ profile = profile_path.read_text(encoding="utf-8")
421
+ except (OSError, UnicodeError) as error:
422
+ raise BootstrapError("無法安全讀取 shell 設定檔") from error
423
+ profile_mode = stat.S_IMODE(profile_path.stat().st_mode)
424
+ else:
425
+ profile = ""
426
+ profile_mode = 0o600
427
+ updated_profile = _replace_profile_block(profile, _profile_block(bin_root))
428
+
429
+ _atomic_write(command_path, script, 0o700)
430
+ if updated_profile != profile:
431
+ _atomic_write(profile_path, updated_profile, profile_mode)
432
+ return command_path, profile_path
433
+
434
+
435
+ def _command_is_ready(
436
+ repo_root: Path,
437
+ data_root: Path,
438
+ home: Path,
439
+ environment: Mapping[str, str],
440
+ ) -> bool:
441
+ try:
442
+ command_path = data_root / "bin" / "clipen"
443
+ profile_path = _shell_profile(home, environment)
444
+ return (
445
+ not command_path.is_symlink()
446
+ and command_path.is_file()
447
+ and command_path.read_text(encoding="utf-8") == _command_script(repo_root)
448
+ and not profile_path.is_symlink()
449
+ and profile_path.is_file()
450
+ and _profile_block(data_root / "bin") in profile_path.read_text(encoding="utf-8")
451
+ )
452
+ except (BootstrapError, OSError, UnicodeError):
453
+ return False
454
+
455
+
456
+ @contextmanager
457
+ def _bootstrap_lock(runtime_root: Path) -> Iterator[None]:
458
+ locking = _require_posix_file_locking()
459
+ lock_path = runtime_root / ".bootstrap.lock"
460
+ with lock_path.open("a+b") as lock:
461
+ locking.flock(lock.fileno(), locking.LOCK_EX)
462
+ try:
463
+ yield
464
+ finally:
465
+ locking.flock(lock.fileno(), locking.LOCK_UN)
466
+
467
+
468
+ def _run_logged(command: Sequence[str], *, cwd: Path, log: TextIO) -> None:
469
+ completed = subprocess.run(
470
+ list(command),
471
+ cwd=cwd,
472
+ stdin=subprocess.DEVNULL,
473
+ stdout=log,
474
+ stderr=subprocess.STDOUT,
475
+ check=False,
476
+ timeout=15 * 60,
477
+ env={
478
+ **os.environ,
479
+ "PIP_DISABLE_PIP_VERSION_CHECK": "1",
480
+ "PYTHONNOUSERSITE": "1",
481
+ },
482
+ )
483
+ if completed.returncode != 0:
484
+ raise BootstrapError(f"runtime 安裝命令失敗(結束代碼 {completed.returncode})")
485
+
486
+
487
+ def _install_runtime(staging: Path, repo_root: Path, fingerprint: str, log_path: Path) -> None:
488
+ venv.EnvBuilder(with_pip=True, clear=False, symlinks=False).create(staging)
489
+ python = runtime_python(staging)
490
+ if not python.is_file():
491
+ raise BootstrapError("無法建立 Clipen Python runtime")
492
+
493
+ with log_path.open("w", encoding="utf-8") as log:
494
+ _run_logged(
495
+ (
496
+ str(python),
497
+ "-m",
498
+ "pip",
499
+ "install",
500
+ f"pip=={_PIP_VERSION}",
501
+ f"setuptools=={_SETUPTOOLS_VERSION}",
502
+ f"wheel=={_WHEEL_VERSION}",
503
+ ),
504
+ cwd=repo_root,
505
+ log=log,
506
+ )
507
+ _run_logged(
508
+ (
509
+ str(python),
510
+ "-m",
511
+ "pip",
512
+ "install",
513
+ "--requirement",
514
+ str(repo_root / "requirements" / "runtime.txt"),
515
+ ),
516
+ cwd=repo_root,
517
+ log=log,
518
+ )
519
+ _run_logged(
520
+ (
521
+ str(python),
522
+ "-m",
523
+ "pip",
524
+ "install",
525
+ "--no-deps",
526
+ "--no-build-isolation",
527
+ "--editable",
528
+ str(repo_root),
529
+ ),
530
+ cwd=repo_root,
531
+ log=log,
532
+ )
533
+
534
+ receipt = {
535
+ "schema": _RUNTIME_SCHEMA,
536
+ "fingerprint": fingerprint,
537
+ "repo_root": str(repo_root.resolve(strict=True)),
538
+ "python": f"{sys.version_info.major}.{sys.version_info.minor}",
539
+ "platform": f"{platform.system()}-{platform.machine()}",
540
+ "created_at": datetime.now(timezone.utc).isoformat(),
541
+ }
542
+ receipt_path = _receipt_path(staging)
543
+ receipt_path.write_text(json.dumps(receipt, indent=2), encoding="utf-8")
544
+ receipt_path.chmod(0o600)
545
+
546
+
547
+ def _install_asr_bundle(
548
+ runtime: Path,
549
+ repo_root: Path,
550
+ data_root: Path,
551
+ log_path: Path,
552
+ stdout: TextIO,
553
+ ) -> None:
554
+ command = (
555
+ str(runtime_python(runtime)),
556
+ "-m",
557
+ "clipen.analysis.setup_cli",
558
+ "--data-root",
559
+ str(data_root),
560
+ "--requirements",
561
+ str(repo_root / "requirements" / "asr-runtime.txt"),
562
+ )
563
+ captured = 0
564
+ process: subprocess.Popen[str] | None = None
565
+ progress_active = False
566
+ progress_width = 0
567
+ try:
568
+ with log_path.open("w", encoding="utf-8") as log:
569
+ process = subprocess.Popen(
570
+ command,
571
+ cwd=repo_root,
572
+ stdin=subprocess.DEVNULL,
573
+ stdout=subprocess.PIPE,
574
+ stderr=subprocess.STDOUT,
575
+ text=True,
576
+ encoding="utf-8",
577
+ errors="replace",
578
+ bufsize=1,
579
+ env={
580
+ **os.environ,
581
+ "PYTHONNOUSERSITE": "1",
582
+ "CLIPEN_REPO_ROOT": str(repo_root),
583
+ },
584
+ )
585
+ assert process.stdout is not None
586
+ for line in process.stdout:
587
+ captured += len(line.encode("utf-8"))
588
+ if captured > 4 * 1024 * 1024:
589
+ process.terminate()
590
+ raise BootstrapError("語音辨識設定輸出超過安全上限")
591
+ is_progress = line.startswith(PROGRESS_RECORD_PREFIX)
592
+ visible_line = line[len(PROGRESS_RECORD_PREFIX) :].rstrip("\r\n") if is_progress else line
593
+ log.write(f"{visible_line}\n" if is_progress else visible_line)
594
+ log.flush()
595
+ if is_progress and stdout.isatty():
596
+ padding = " " * max(0, progress_width - len(visible_line))
597
+ stdout.write(f"\r{visible_line}{padding}")
598
+ progress_active = True
599
+ progress_width = len(visible_line)
600
+ else:
601
+ if progress_active:
602
+ stdout.write("\n")
603
+ progress_active = False
604
+ progress_width = 0
605
+ stdout.write(f"{visible_line}\n" if is_progress else visible_line)
606
+ stdout.flush()
607
+ returncode = process.wait()
608
+ if progress_active:
609
+ stdout.write("\n")
610
+ stdout.flush()
611
+ progress_active = False
612
+ except BaseException:
613
+ if progress_active:
614
+ stdout.write("\n")
615
+ stdout.flush()
616
+ if process is not None and process.poll() is None:
617
+ process.terminate()
618
+ try:
619
+ process.wait(timeout=10)
620
+ except subprocess.TimeoutExpired:
621
+ process.kill()
622
+ process.wait(timeout=5)
623
+ raise
624
+ if returncode != 0:
625
+ raise BootstrapError(f"本機語音辨識設定失敗;診斷紀錄:{log_path}")
626
+
627
+
628
+ def ensure_runtime(
629
+ repo_root: Path,
630
+ *,
631
+ data_root: Path | None = None,
632
+ stdin: TextIO = sys.stdin,
633
+ stdout: TextIO = sys.stdout,
634
+ confirmed: bool = False,
635
+ ) -> Path | None:
636
+ repo_root = repo_root.resolve(strict=True)
637
+ fingerprint = runtime_fingerprint(repo_root)
638
+ root = (data_root or clipen_data_root()) / "runtimes"
639
+ root.mkdir(mode=0o700, parents=True, exist_ok=True)
640
+ if root.is_symlink():
641
+ raise BootstrapError("Clipen runtime 根目錄不能是 symbolic link")
642
+ runtime = root / fingerprint
643
+
644
+ with _bootstrap_lock(root):
645
+ ready = _ready_runtime(root, fingerprint, repo_root)
646
+ if ready is not None:
647
+ return ready
648
+ if runtime.exists():
649
+ raise BootstrapError(f"Clipen runtime 不完整,請先保留此目錄並回報問題:{runtime}")
650
+ if not confirmed and not _confirm_setup(runtime, stdin, stdout):
651
+ print("已取消,沒有建立 Clipen runtime。", file=stdout)
652
+ return None
653
+
654
+ staging = root / f".{fingerprint}.staging-{uuid.uuid4().hex}"
655
+ log_root = (data_root or clipen_data_root()) / "logs"
656
+ log_root.mkdir(mode=0o700, parents=True, exist_ok=True)
657
+ log_path = log_root / f"bootstrap-{fingerprint}.log"
658
+ print("正在建立 Clipen 執行環境…", file=stdout)
659
+ try:
660
+ staging.mkdir(mode=0o700)
661
+ _install_runtime(staging, repo_root, fingerprint, log_path)
662
+ staging.rename(runtime)
663
+ except Exception:
664
+ if staging.exists() and not staging.is_symlink():
665
+ shutil.rmtree(staging)
666
+ raise
667
+ print("✓ Clipen 執行環境建立完成", file=stdout)
668
+ return runtime
669
+
670
+
671
+ def ensure_installation(
672
+ repo_root: Path,
673
+ *,
674
+ data_root: Path | None = None,
675
+ home: Path | None = None,
676
+ environment: Mapping[str, str] | None = None,
677
+ stdin: TextIO = sys.stdin,
678
+ stdout: TextIO = sys.stdout,
679
+ ) -> Path | None:
680
+ repo_root = repo_root.resolve(strict=True)
681
+ selected_data_root = data_root or clipen_data_root()
682
+ selected_home = home or Path.home()
683
+ selected_environment = environment if environment is not None else os.environ
684
+ if platform.system() != "Darwin" or platform.machine() != "arm64":
685
+ raise BootstrapError("目前完整設定只支援 Apple 晶片的 macOS")
686
+ fingerprint = runtime_fingerprint(repo_root)
687
+ ready = _ready_runtime(selected_data_root / "runtimes", fingerprint, repo_root)
688
+ runtime = ready or selected_data_root / "runtimes" / fingerprint
689
+ asr_requirements = repo_root / "requirements" / "asr-runtime.txt"
690
+ runtime_ready = ready is not None
691
+ asr_ready = quick_release_is_ready(selected_data_root, asr_requirements)
692
+ command_ready = _command_is_ready(repo_root, selected_data_root, selected_home, selected_environment)
693
+
694
+ if not runtime_ready or not asr_ready:
695
+ command_path = selected_data_root / "bin" / "clipen"
696
+ profile_path = _shell_profile(selected_home, selected_environment)
697
+ if not _confirm_setup(
698
+ runtime,
699
+ stdin,
700
+ stdout,
701
+ command_path=None if command_ready else command_path,
702
+ profile_path=None if command_ready else profile_path,
703
+ asr_root=None if asr_ready else release_root(selected_data_root),
704
+ include_runtime=not runtime_ready,
705
+ ):
706
+ print("已取消,既有 Clipen 資料沒有變動。", file=stdout)
707
+ return None
708
+ if not runtime_ready:
709
+ installed_runtime = ensure_runtime(
710
+ repo_root,
711
+ data_root=selected_data_root,
712
+ stdin=stdin,
713
+ stdout=stdout,
714
+ confirmed=True,
715
+ )
716
+ if installed_runtime is None:
717
+ return None
718
+ runtime = installed_runtime
719
+ if not asr_ready:
720
+ log_root = selected_data_root / "logs"
721
+ log_root.mkdir(mode=0o700, parents=True, exist_ok=True)
722
+ if log_root.is_symlink():
723
+ raise BootstrapError("Clipen log 目錄不能是 symbolic link")
724
+ asr_log = log_root / f"bootstrap-asr-{fingerprint}.log"
725
+ print("正在準備本機語音辨識與固定模型…", file=stdout)
726
+ _install_asr_bundle(
727
+ runtime,
728
+ repo_root,
729
+ selected_data_root,
730
+ asr_log,
731
+ stdout,
732
+ )
733
+ if not quick_release_is_ready(selected_data_root, asr_requirements):
734
+ raise BootstrapError(f"語音辨識安裝未通過啟動檢查;診斷紀錄:{asr_log}")
735
+ _ensure_chrome(runtime, selected_data_root, selected_home, stdout)
736
+ if not command_ready:
737
+ command_path, profile_path = _install_command(
738
+ repo_root, selected_data_root, selected_home, selected_environment
739
+ )
740
+ print(f"✓ 已建立指令:{command_path}", file=stdout)
741
+ print(f"✓ 已更新 PATH:{profile_path}", file=stdout)
742
+ print("下次開啟 Terminal 後可直接輸入:clipen codex(或 clipen claude)", file=stdout)
743
+ print("✓ Clipen 完整設定完成", file=stdout)
744
+ return runtime
745
+
746
+ if stdin.isatty():
747
+ _ensure_chrome(runtime, selected_data_root, selected_home, stdout)
748
+
749
+ if not command_ready:
750
+ if not stdin.isatty():
751
+ return runtime
752
+ print("Clipen 需要完成一次指令設定。", file=stdout)
753
+ print(f"將建立:{selected_data_root / 'bin' / 'clipen'}", file=stdout)
754
+ profile_path = _shell_profile(selected_home, selected_environment)
755
+ print(f"將更新 PATH:{profile_path}", file=stdout)
756
+ stdout.write("完成設定?[Y/n] ")
757
+ stdout.flush()
758
+ if stdin.readline().strip().lower() not in {"", "y", "yes"}:
759
+ print(f"已略過;可再次執行 {_install_hint(repo_root)} 完成指令設定。", file=stdout)
760
+ return runtime
761
+ command_path, profile_path = _install_command(
762
+ repo_root, selected_data_root, selected_home, selected_environment
763
+ )
764
+ print(f"✓ 已建立指令:{command_path}", file=stdout)
765
+ print(f"✓ 已更新 PATH:{profile_path}", file=stdout)
766
+ print("下次開啟 Terminal 後可直接輸入:clipen codex(或 clipen claude)", file=stdout)
767
+ return runtime
768
+
769
+
770
+ def completed_runtime(repo_root: Path, *, data_root: Path | None = None) -> Path:
771
+ """Return the installed runtime without performing setup or downloads."""
772
+
773
+ repo_root = repo_root.resolve(strict=True)
774
+ selected_data_root = data_root or clipen_data_root()
775
+ if platform.system() != "Darwin" or platform.machine() != "arm64":
776
+ raise BootstrapError("目前只支援 Apple 晶片的 macOS")
777
+ fingerprint = runtime_fingerprint(repo_root)
778
+ runtime = _ready_runtime(selected_data_root / "runtimes", fingerprint, repo_root)
779
+ requirements = repo_root / "requirements" / "asr-runtime.txt"
780
+ if runtime is None or not quick_release_is_ready(selected_data_root, requirements):
781
+ raise BootstrapError(
782
+ f"Clipen 尚未完成安裝;第一次請執行 {_install_hint(repo_root)},"
783
+ "已有 clipen 指令時可執行 clipen install 修復"
784
+ )
785
+ return runtime
786
+
787
+
788
+ def _controller_is_running(data_root: Path) -> bool:
789
+ locking = _require_posix_file_locking()
790
+ lock_path = data_root / ".controller.lock"
791
+ if not lock_path.exists() and not lock_path.is_symlink():
792
+ return False
793
+ flags = os.O_RDWR | getattr(os, "O_NOFOLLOW", 0)
794
+ try:
795
+ descriptor = os.open(lock_path, flags)
796
+ except OSError as error:
797
+ raise BootstrapError("無法安全檢查 Clipen 是否仍在執行") from error
798
+ try:
799
+ info = os.fstat(descriptor)
800
+ if not stat.S_ISREG(info.st_mode):
801
+ raise BootstrapError("Clipen 執行鎖不是安全的實體檔案")
802
+ try:
803
+ locking.flock(descriptor, locking.LOCK_EX | locking.LOCK_NB)
804
+ except BlockingIOError:
805
+ return True
806
+ locking.flock(descriptor, locking.LOCK_UN)
807
+ return False
808
+ finally:
809
+ os.close(descriptor)
810
+
811
+
812
+ def _validate_removable_path(path: Path, data_root: Path, *, directory: bool) -> None:
813
+ if not path.exists() and not path.is_symlink():
814
+ return
815
+ if path.is_symlink() or path.parent.resolve(strict=True) != data_root:
816
+ raise BootstrapError(f"拒絕移除不安全的 Clipen 路徑:{path}")
817
+ if directory:
818
+ if not path.is_dir() or path.is_mount():
819
+ raise BootstrapError(f"拒絕移除非一般目錄:{path}")
820
+ for current, directories, _files in os.walk(path, followlinks=False):
821
+ for name in directories:
822
+ candidate = Path(current) / name
823
+ if not candidate.is_symlink() and candidate.is_mount():
824
+ raise BootstrapError(f"拒絕移除包含 mount point 的目錄:{candidate}")
825
+ elif not path.is_file():
826
+ raise BootstrapError(f"拒絕移除非一般檔案:{path}")
827
+
828
+
829
+ def uninstall_installation(
830
+ *,
831
+ data_root: Path | None = None,
832
+ home: Path | None = None,
833
+ environment: Mapping[str, str] | None = None,
834
+ stdin: TextIO = sys.stdin,
835
+ stdout: TextIO = sys.stdout,
836
+ ) -> bool:
837
+ """Remove Clipen-managed installation files while preserving all projects."""
838
+
839
+ selected_data_root = data_root or clipen_data_root()
840
+ selected_home = home or Path.home()
841
+ selected_environment = environment if environment is not None else os.environ
842
+ profile_path = _shell_profile(selected_home, selected_environment)
843
+ bin_root = selected_data_root / "bin"
844
+ command_path = bin_root / "clipen"
845
+
846
+ print("移除 Clipen", file=stdout)
847
+ print("將會移除:", file=stdout)
848
+ print(" • Clipen runtime 與本機語音辨識模型", file=stdout)
849
+ print(f" • `clipen` 指令:{command_path}", file=stdout)
850
+ print(f" • PATH 設定:{profile_path}", file=stdout)
851
+ print("會保留 Clipen 作品資料、毛片、參考作品與匯出檔案。", file=stdout)
852
+ if not stdin.isatty():
853
+ raise BootstrapError("移除 Clipen 需要在互動式 Terminal 中確認")
854
+ stdout.write("確定移除?[y/N] ")
855
+ stdout.flush()
856
+ if stdin.readline().strip().lower() not in {"y", "yes"}:
857
+ print("已取消,沒有移除任何內容。", file=stdout)
858
+ return False
859
+
860
+ if selected_data_root.exists() or selected_data_root.is_symlink():
861
+ if selected_data_root.is_symlink() or not selected_data_root.is_dir():
862
+ raise BootstrapError("Clipen 資料根目錄不安全,未進行移除")
863
+ resolved_data_root = selected_data_root.resolve(strict=True)
864
+ if _controller_is_running(resolved_data_root):
865
+ raise BootstrapError("Clipen 仍在執行;請先在啟動它的 Terminal 按 Ctrl+C")
866
+ else:
867
+ resolved_data_root = selected_data_root
868
+
869
+ profile = ""
870
+ updated_profile = ""
871
+ profile_mode = 0o600
872
+ if profile_path.exists() or profile_path.is_symlink():
873
+ if profile_path.is_symlink() or not profile_path.is_file():
874
+ raise BootstrapError("shell 設定檔不是安全的實體檔案,未進行移除")
875
+ profile = profile_path.read_text(encoding="utf-8")
876
+ updated_profile = _remove_profile_block(profile)
877
+ profile_mode = stat.S_IMODE(profile_path.stat().st_mode)
878
+
879
+ if bin_root.exists() or bin_root.is_symlink():
880
+ if bin_root.is_symlink() or not bin_root.is_dir():
881
+ raise BootstrapError("Clipen bin 目錄不安全,未進行移除")
882
+ if command_path.exists() or command_path.is_symlink():
883
+ if command_path.is_symlink() or not command_path.is_file():
884
+ raise BootstrapError("clipen 指令位置不是安全的實體檔案,未進行移除")
885
+ command = command_path.read_text(encoding="utf-8")
886
+ if not any(line.startswith(_MANAGED_COMMAND_PREFIX) for line in command.splitlines()[:3]):
887
+ raise BootstrapError("clipen 指令不是由 Clipen 管理,未進行移除")
888
+
889
+ if selected_data_root.exists():
890
+ for name in _REMOVABLE_DIRECTORIES:
891
+ _validate_removable_path(resolved_data_root / name, resolved_data_root, directory=True)
892
+ for name in _REMOVABLE_FILES:
893
+ _validate_removable_path(resolved_data_root / name, resolved_data_root, directory=False)
894
+
895
+ if selected_data_root.exists():
896
+ for name in _REMOVABLE_DIRECTORIES:
897
+ path = resolved_data_root / name
898
+ if path.exists():
899
+ shutil.rmtree(path)
900
+ for name in _REMOVABLE_FILES:
901
+ path = resolved_data_root / name
902
+ if path.exists():
903
+ path.unlink()
904
+ bin_root = resolved_data_root / "bin"
905
+ if command_path.exists():
906
+ command_path.unlink()
907
+ if bin_root.is_dir() and not bin_root.is_symlink() and not any(bin_root.iterdir()):
908
+ bin_root.rmdir()
909
+ if updated_profile != profile:
910
+ _atomic_write(profile_path, updated_profile, profile_mode)
911
+ print("✓ Clipen 已移除", file=stdout)
912
+ print("作品資料與所有毛片均已保留。", file=stdout)
913
+ return True
914
+
915
+
916
+ def _print_usage(stream: TextIO, repo_root: Path | None = None) -> None:
917
+ npm = repo_root is not None and (repo_root / ".clipen-npm").is_file()
918
+ print(f"第一次安裝:{'npx @clipen/clipen-cli' if npm else './install'}", file=stream)
919
+ print("啟動 Clipen:clipen codex 或 clipen claude", file=stream)
920
+ print(f"移除 Clipen:{'clipen uninstall' if npm else './uninstall'}", file=stream)
921
+
922
+
923
+ def main(repo_root: Path, arguments: Sequence[str]) -> int:
924
+ if list(arguments) in (["--help"], ["-h"]):
925
+ _print_usage(sys.stdout, repo_root)
926
+ return 0
927
+ from clipen.provider_registry import PROVIDERS, implemented_providers
928
+
929
+ launch = len(arguments) == 1 and arguments[0] in implemented_providers()
930
+ if list(arguments) not in (["install"], ["uninstall"]) and not launch:
931
+ if len(arguments) == 1 and arguments[0] in PROVIDERS:
932
+ print(f"Clipen 目前還不支援 {PROVIDERS[arguments[0]].display_name}({arguments[0]})。", file=sys.stderr)
933
+ _print_usage(sys.stderr, repo_root)
934
+ return 2
935
+ try:
936
+ _require_posix_file_locking()
937
+ if list(arguments) == ["install"]:
938
+ ensure_web_build(repo_root)
939
+ runtime = ensure_installation(repo_root)
940
+ if runtime is not None:
941
+ print("✓ Clipen 已安裝完成")
942
+ print("\n接下來:")
943
+ print("1. 開啟新的 Terminal")
944
+ print("2. cd 到你想存放 Clipen 作品資料的目錄")
945
+ print("3. 執行:clipen codex(或 clipen claude)")
946
+ print("\n不需要回到 Clipen 程式碼目錄;毛片也可以放在其他位置。")
947
+ return 0
948
+ if list(arguments) == ["uninstall"]:
949
+ uninstall_installation()
950
+ return 0
951
+ ensure_web_build(repo_root)
952
+ runtime = completed_runtime(repo_root)
953
+ except KeyboardInterrupt:
954
+ action = "移除" if list(arguments) == ["uninstall"] else "設定"
955
+ print(f"\nClipen {action}已取消", file=sys.stderr)
956
+ return 130
957
+ except (BootstrapError, OSError, subprocess.SubprocessError) as error:
958
+ action = {
959
+ "install": "安裝",
960
+ "uninstall": "移除",
961
+ }.get(list(arguments)[0], "啟動")
962
+ print(f"Clipen {action}失敗:{error}", file=sys.stderr)
963
+ return 1
964
+ if runtime is None:
965
+ return 0
966
+
967
+ python = runtime_python(runtime)
968
+ environment = {
969
+ **os.environ,
970
+ "CLIPEN_REPO_ROOT": str(repo_root.resolve(strict=True)),
971
+ "PYTHONNOUSERSITE": "1",
972
+ }
973
+ os.execve(
974
+ python,
975
+ [str(python), "-m", "clipen.cli", arguments[0]],
976
+ environment,
977
+ )
978
+ return 1