@clipen/clipen-cli 0.0.0-stage → 1.0.0

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