@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,991 @@
1
+ """A bounded, non-interactive Codex CLI adapter.
2
+
3
+ The adapter deliberately knows nothing about projects or source-media paths. A
4
+ Controller must first materialize the exact approved inputs into an isolated
5
+ attempt workspace.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import shutil
14
+ import signal
15
+ import subprocess
16
+ import tempfile
17
+ import time
18
+ import uuid
19
+ from dataclasses import dataclass, replace
20
+ from pathlib import Path
21
+ from typing import Mapping
22
+
23
+ from jsonschema import Draft202012Validator
24
+ from jsonschema.exceptions import SchemaError, ValidationError
25
+
26
+ from .errors import (
27
+ CancellationToken,
28
+ ProviderAuthenticationError,
29
+ ProviderCancelled,
30
+ ProviderNetworkError,
31
+ ProviderPermissionError,
32
+ ProviderProtocolError,
33
+ ProviderTimedOut,
34
+ ProviderUnavailable,
35
+ ProviderUsageLimitError,
36
+ )
37
+ from .recovery import (
38
+ AttemptReceiptError,
39
+ AttemptReceiptStore,
40
+ ProviderAttemptReceipt,
41
+ ProviderAttemptState,
42
+ ProviderUsage,
43
+ sha256_bytes,
44
+ sha256_file,
45
+ utc_now,
46
+ )
47
+
48
+ _MAX_PROMPT_BYTES = 1_000_000
49
+ _MAX_SCHEMA_BYTES = 1_000_000
50
+ _MAX_CAPTURE_BYTES = 2_000_000
51
+ _MAX_RESULT_BYTES = 2_000_000
52
+ _POLL_INTERVAL_SECONDS = 0.05
53
+ _SAFE_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
54
+ _PERMISSION_PROFILE = "clipen_attempt"
55
+ _CONFINEMENT_MARKER = b"clipen-confinement-ok\n"
56
+ _CONFINEMENT_SCRIPT = """
57
+ if ! /bin/cat "$1" >/dev/null 2>&1; then exit 10; fi
58
+ if /bin/cat "$2" >/dev/null 2>&1; then exit 20; fi
59
+ if /bin/cat "$3" >/dev/null 2>&1; then exit 30; fi
60
+ /bin/echo clipen-confinement-ok
61
+ """.strip()
62
+ _SECRET_PATTERNS = (
63
+ re.compile(rb"(?i)(authorization\s*:\s*bearer\s+)[^\s\"']+"),
64
+ re.compile(rb"(?i)(api[_-]?key\s*[=:]\s*)[^\s\"']+"),
65
+ re.compile(rb"\bsk-[A-Za-z0-9_-]{16,}\b"),
66
+ )
67
+ _ENVIRONMENT_ALLOWLIST = frozenset(
68
+ {
69
+ "ALL_PROXY",
70
+ "CODEX_HOME",
71
+ "HOME",
72
+ "HTTPS_PROXY",
73
+ "HTTP_PROXY",
74
+ "LANG",
75
+ "LC_ALL",
76
+ "LOGNAME",
77
+ "NO_PROXY",
78
+ "PATH",
79
+ "SHELL",
80
+ "SSL_CERT_DIR",
81
+ "SSL_CERT_FILE",
82
+ "TMPDIR",
83
+ "USER",
84
+ }
85
+ )
86
+
87
+
88
+ def _bounded_identifier(value: str, field: str) -> None:
89
+ if not isinstance(value, str) or _SAFE_IDENTIFIER.fullmatch(value) is None:
90
+ raise ValueError(f"{field} must be a safe bounded identifier")
91
+
92
+
93
+ def _inside(path: Path, root: Path) -> bool:
94
+ return path == root or path.is_relative_to(root)
95
+
96
+
97
+ def _isolated_workspace(path: Path) -> Path:
98
+ if path.is_symlink():
99
+ raise ValueError("attempt workspace cannot be a symbolic link")
100
+ resolved = path.resolve(strict=True)
101
+ if not resolved.is_dir():
102
+ raise ValueError("attempt workspace must be a directory")
103
+ return resolved
104
+
105
+
106
+ def _workspace_file(path: Path, workspace: Path, field: str) -> Path:
107
+ if path.is_symlink():
108
+ raise ValueError(f"{field} cannot be a symbolic link")
109
+ resolved = path.resolve(strict=True)
110
+ if not resolved.is_file() or not _inside(resolved, workspace):
111
+ raise ValueError(f"{field} must be a regular file inside the attempt workspace")
112
+ return resolved
113
+
114
+
115
+ # Clipen ignores the user's Codex config so it cannot change tools, rules or
116
+ # approvals. Only the chosen model and reasoning effort carry over.
117
+ _EFFORTS = frozenset({"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"})
118
+ _MODEL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,79}")
119
+ _TABLE = re.compile(r"^\s*\[\s*([^\[\]]+?)\s*\]\s*(?:#.*)?$")
120
+ _STRING = re.compile(r"""^\s*([A-Za-z0-9_]+)\s*=\s*(?:"([^"\\]*)"|'([^']*)')\s*(?:#.*)?$""")
121
+
122
+
123
+ def codex_preferences(environment: Mapping[str, str] | None = None) -> tuple[str | None, str | None]:
124
+ """The model and reasoning effort from the user's Codex config, honouring `profile`."""
125
+ source = os.environ if environment is None else environment
126
+ home = source.get("CODEX_HOME") or (str(Path(source["HOME"]) / ".codex") if source.get("HOME") else None)
127
+ if not home:
128
+ return None, None
129
+ path = Path(home) / "config.toml"
130
+ try:
131
+ if path.is_symlink() and not path.resolve().is_file() or path.stat().st_size > 1024 * 1024:
132
+ return None, None
133
+ lines = path.read_text(encoding="utf-8").splitlines()
134
+ except (OSError, UnicodeDecodeError):
135
+ return None, None
136
+ tables: dict[str, dict[str, str]] = {"": {}}
137
+ table = ""
138
+ for line in lines:
139
+ if header := _TABLE.match(line):
140
+ table = header.group(1).replace('"', "").replace(" ", "")
141
+ tables.setdefault(table, {})
142
+ elif value := _STRING.match(line):
143
+ tables[table][value.group(1)] = value.group(2) if value.group(2) is not None else value.group(3)
144
+ chosen = (
145
+ {**tables[""], **tables.get("profiles." + tables[""].get("profile", ""), {})}
146
+ if tables[""].get("profile")
147
+ else tables[""]
148
+ )
149
+ model, effort = chosen.get("model"), chosen.get("model_reasoning_effort")
150
+ return (model if model and _MODEL.fullmatch(model) else None, effort if effort in _EFFORTS else None)
151
+
152
+
153
+ def model_config(binary: str | Path, environment: Mapping[str, str] | None = None) -> tuple[str, ...]:
154
+ """`-c` overrides for the user's model and effort, kept only when this account supports them."""
155
+ preferences = codex_preferences(environment)
156
+ if preferences == (None, None):
157
+ return ()
158
+ from .account import available_models, resolve_codex_model
159
+
160
+ resolved = resolve_codex_model(preferences, available_models(binary, environment or os.environ))
161
+ if resolved is None:
162
+ return ()
163
+ return (
164
+ *(("-c", f"model={json.dumps(resolved['id'])}") if resolved["apply_model"] else ()),
165
+ *(("-c", f"model_reasoning_effort={json.dumps(resolved['effort'])}") if resolved["apply_effort"] else ()),
166
+ )
167
+
168
+
169
+ def _provider_environment(source: Mapping[str, str] | None = None) -> dict[str, str]:
170
+ inherited = os.environ if source is None else source
171
+ environment = {key: value for key, value in inherited.items() if key in _ENVIRONMENT_ALLOWLIST}
172
+ environment["CLICOLOR"] = "0"
173
+ environment["NO_COLOR"] = "1"
174
+ return environment
175
+
176
+
177
+ def _decode_capture(value: bytes, field: str, limit: int = _MAX_CAPTURE_BYTES) -> str:
178
+ if len(value) > limit:
179
+ raise ProviderProtocolError(f"Codex {field} exceeded the capture limit")
180
+ try:
181
+ return value.decode("utf-8", errors="strict")
182
+ except UnicodeDecodeError as error:
183
+ raise ProviderProtocolError(f"Codex {field} was not valid UTF-8") from error
184
+
185
+
186
+ def _load_output_schema(path: Path) -> dict[str, object]:
187
+ if path.stat().st_size > _MAX_SCHEMA_BYTES:
188
+ raise ValueError("output_schema must be at most 1,000,000 bytes")
189
+ try:
190
+ parsed = json.loads(path.read_text(encoding="utf-8"))
191
+ except (OSError, UnicodeError, json.JSONDecodeError) as error:
192
+ raise ValueError("output_schema must contain valid UTF-8 JSON") from error
193
+ if not isinstance(parsed, dict):
194
+ raise ValueError("output_schema must contain a JSON object")
195
+ try:
196
+ Draft202012Validator.check_schema(parsed)
197
+ except SchemaError as error:
198
+ raise ValueError("output_schema must be a valid JSON Schema 2020-12 document") from error
199
+ return parsed
200
+
201
+
202
+ def _toml_string(value: str) -> str:
203
+ """Encode a string using the TOML-compatible JSON basic-string subset."""
204
+
205
+ return json.dumps(value, ensure_ascii=True)
206
+
207
+
208
+ def _permission_config(workspace: Path, temp_root: Path | None = None) -> tuple[str, ...]:
209
+ workspace_key = _toml_string(str(workspace))
210
+ denied_roots = {"/private/tmp/**", "/tmp/**", "/var/tmp/**"}
211
+ if temp_root is not None:
212
+ denied_roots.add(f"{temp_root}/**")
213
+ filesystem_entries = [
214
+ f'{_toml_string(":minimal")}="read"',
215
+ f'{_toml_string(":workspace_roots")}="read"',
216
+ ]
217
+ filesystem_entries.extend(f'{_toml_string(path)}="deny"' for path in sorted(denied_roots))
218
+ return (
219
+ "-c",
220
+ f"default_permissions={_toml_string(_PERMISSION_PROFILE)}",
221
+ "-c",
222
+ f'permissions.{_PERMISSION_PROFILE}.description="Clipen isolated AI attempt"',
223
+ "-c",
224
+ f"permissions.{_PERMISSION_PROFILE}.workspace_roots={{{workspace_key}=true}}",
225
+ "-c",
226
+ f"permissions.{_PERMISSION_PROFILE}.filesystem={{{','.join(filesystem_entries)}}}",
227
+ "-c",
228
+ f"permissions.{_PERMISSION_PROFILE}.network.enabled=false",
229
+ "-c",
230
+ 'shell_environment_policy.inherit="none"',
231
+ "-c",
232
+ 'shell_environment_policy.set={PATH="/usr/bin:/bin",LANG="C"}',
233
+ )
234
+
235
+
236
+ @dataclass(frozen=True)
237
+ class CodexCapabilities:
238
+ """CLI features Clipen requires before offering Codex in the UI."""
239
+
240
+ ephemeral_sessions: bool
241
+ isolated_user_config: bool
242
+ isolated_rules: bool
243
+ granular_permissions: bool
244
+ json_events: bool
245
+ output_schema: bool
246
+ output_file: bool
247
+
248
+ @property
249
+ def supports_bounded_attempts(self) -> bool:
250
+ return all(
251
+ (
252
+ self.ephemeral_sessions,
253
+ self.isolated_user_config,
254
+ self.isolated_rules,
255
+ self.granular_permissions,
256
+ self.json_events,
257
+ self.output_schema,
258
+ self.output_file,
259
+ )
260
+ )
261
+
262
+
263
+ @dataclass(frozen=True)
264
+ class CodexProbeResult:
265
+ """Read-only availability snapshot; probing never invokes a model."""
266
+
267
+ version: str
268
+ authenticated: bool
269
+ capabilities: CodexCapabilities
270
+ confinement_verified: bool
271
+
272
+ @property
273
+ def available(self) -> bool:
274
+ return self.authenticated and self.capabilities.supports_bounded_attempts and self.confinement_verified
275
+
276
+
277
+ @dataclass(frozen=True)
278
+ class CodexAttempt:
279
+ attempt_id: str
280
+ workspace: Path
281
+ output_schema: Path
282
+ prompt: str
283
+ timeout_seconds: float = 300.0
284
+ images: tuple[Path, ...] = ()
285
+
286
+ def __post_init__(self) -> None:
287
+ _bounded_identifier(self.attempt_id, "attempt_id")
288
+ workspace = _isolated_workspace(self.workspace)
289
+ schema = _workspace_file(self.output_schema, workspace, "output_schema")
290
+ _load_output_schema(schema)
291
+ prompt_bytes = self.prompt.encode("utf-8")
292
+ if not self.prompt.strip() or len(prompt_bytes) > _MAX_PROMPT_BYTES:
293
+ raise ValueError("prompt must be non-empty and at most 1,000,000 UTF-8 bytes")
294
+ if not 0 < self.timeout_seconds <= 3600:
295
+ raise ValueError("timeout_seconds must be between zero and 3600")
296
+ self.image_identity()
297
+
298
+ def image_identity(self) -> list[dict[str, str]]:
299
+ if type(self.images) is not tuple or len(self.images) > 8:
300
+ raise ValueError("at most eight immutable image inputs are allowed")
301
+ identity = []
302
+ total = 0
303
+ for image in self.images:
304
+ path = _workspace_file(image, self.workspace.resolve(), "image")
305
+ info = path.stat()
306
+ total += info.st_size
307
+ if info.st_nlink != 1 or info.st_size > 2 * 1024**2 or total > 8 * 1024**2:
308
+ raise ValueError("image input exceeds bounds or is hardlinked")
309
+ with path.open("rb") as source:
310
+ if source.read(8) != b"\x89PNG\r\n\x1a\n":
311
+ raise ValueError("image input must be a PNG snapshot")
312
+ identity.append(
313
+ {"name": str(path.relative_to(self.workspace.resolve())), "sha256": sha256_file(path, 2 * 1024**2)}
314
+ )
315
+ return identity
316
+
317
+ def input_hash(self) -> str:
318
+ if not self.images:
319
+ return sha256_bytes(self.prompt.encode("utf-8"))
320
+ return sha256_bytes(
321
+ json.dumps({"prompt": self.prompt, "images": self.image_identity()}, sort_keys=True).encode("utf-8")
322
+ )
323
+
324
+
325
+ @dataclass(frozen=True)
326
+ class CodexAttemptResult:
327
+ attempt_id: str
328
+ payload: dict[str, object]
329
+ event_types: tuple[str, ...]
330
+ elapsed_seconds: float | None
331
+ usage: ProviderUsage | None = None
332
+
333
+
334
+ @dataclass(frozen=True)
335
+ class CodexReconciliation:
336
+ attempt_id: str
337
+ state: ProviderAttemptState
338
+ result: CodexAttemptResult | None
339
+ reason: str
340
+
341
+
342
+ class CodexExecAdapter:
343
+ """Run one ephemeral Codex attempt without loading project configuration."""
344
+
345
+ provider_id = "codex"
346
+ display_name = "Codex"
347
+
348
+ def __init__(
349
+ self,
350
+ attempt_root: Path,
351
+ binary: str | Path | None = None,
352
+ environment: Mapping[str, str] | None = None,
353
+ ) -> None:
354
+ self._attempt_root = _isolated_workspace(attempt_root)
355
+ selected = str(binary) if binary is not None else shutil.which("codex")
356
+ if not selected:
357
+ raise ProviderUnavailable("Codex CLI is not installed or not on PATH")
358
+ candidate = Path(selected)
359
+ if candidate.is_symlink():
360
+ candidate = candidate.resolve(strict=True)
361
+ else:
362
+ candidate = candidate.resolve(strict=True)
363
+ if not candidate.is_file() or not os.access(candidate, os.X_OK):
364
+ raise ProviderUnavailable("Codex CLI is not an executable regular file")
365
+ self._binary = candidate
366
+ self._environment = _provider_environment(environment)
367
+
368
+ @property
369
+ def binary(self) -> Path:
370
+ return self._binary
371
+
372
+ def version(self) -> str:
373
+ completed = self._probe_command("--version")
374
+ if completed.returncode != 0:
375
+ raise ProviderUnavailable("Codex CLI version probe failed")
376
+ version = _decode_capture(completed.stdout, "version output", 256).strip()
377
+ if not version or len(version) > 256:
378
+ raise ProviderProtocolError("Codex CLI returned an invalid version string")
379
+ return version
380
+
381
+ def capabilities(self) -> CodexCapabilities:
382
+ exec_help = self._probe_command("exec", "--help")
383
+ sandbox_help = self._probe_command("sandbox", "--help")
384
+ if exec_help.returncode != 0 or sandbox_help.returncode != 0:
385
+ raise ProviderUnavailable("Codex CLI capability probe failed")
386
+ help_text = _decode_capture(exec_help.stdout, "exec help")
387
+ sandbox_help_text = _decode_capture(sandbox_help.stdout, "sandbox help")
388
+ return CodexCapabilities(
389
+ ephemeral_sessions="--ephemeral" in help_text,
390
+ isolated_user_config="--ignore-user-config" in help_text,
391
+ isolated_rules="--ignore-rules" in help_text,
392
+ granular_permissions=(
393
+ "--config" in help_text
394
+ and "--strict-config" in help_text
395
+ and "--permission-profile" in sandbox_help_text
396
+ ),
397
+ json_events="--json" in help_text,
398
+ output_schema="--output-schema" in help_text,
399
+ output_file="--output-last-message" in help_text,
400
+ )
401
+
402
+ def probe(self) -> CodexProbeResult:
403
+ """Check the local CLI, auth, and contract without contacting a model."""
404
+
405
+ version = self.version()
406
+ capabilities = self.capabilities()
407
+ login = self._probe_command("login", "status")
408
+ confinement_verified = False
409
+ if login.returncode == 0 and capabilities.granular_permissions:
410
+ confinement_verified = self._verify_confinement()
411
+ return CodexProbeResult(
412
+ version=version,
413
+ authenticated=login.returncode == 0,
414
+ capabilities=capabilities,
415
+ confinement_verified=confinement_verified,
416
+ )
417
+
418
+ def _verify_confinement(self) -> bool:
419
+ """Run a model-free canary under the exact filesystem permission profile."""
420
+
421
+ try:
422
+ with (
423
+ tempfile.TemporaryDirectory(prefix=".permission-probe-", dir=self._attempt_root) as probe_directory,
424
+ tempfile.TemporaryDirectory(prefix="clipen-denied-") as denied_directory,
425
+ ):
426
+ probe_root = Path(probe_directory)
427
+ workspace = probe_root / "attempt"
428
+ probe_home = probe_root / "codex-home"
429
+ workspace.mkdir(mode=0o700)
430
+ probe_home.mkdir(mode=0o700)
431
+ inside = workspace / "inside.txt"
432
+ outside = probe_root / "outside.txt"
433
+ temp_outside = Path(denied_directory) / "outside.txt"
434
+ inside.write_text("inside-canary", encoding="utf-8")
435
+ outside.write_text("outside-canary", encoding="utf-8")
436
+ temp_outside.write_text("temp-canary", encoding="utf-8")
437
+ command = (
438
+ str(self._binary),
439
+ "sandbox",
440
+ *_permission_config(workspace, Path(tempfile.gettempdir()).resolve()),
441
+ "--permission-profile",
442
+ _PERMISSION_PROFILE,
443
+ "--cd",
444
+ str(workspace),
445
+ "--",
446
+ "/bin/sh",
447
+ "-c",
448
+ _CONFINEMENT_SCRIPT,
449
+ "clipen-canary",
450
+ str(inside),
451
+ str(outside),
452
+ str(temp_outside),
453
+ )
454
+ completed = subprocess.run(
455
+ command,
456
+ stdin=subprocess.DEVNULL,
457
+ stdout=subprocess.PIPE,
458
+ stderr=subprocess.PIPE,
459
+ env={**self._environment, "CODEX_HOME": str(probe_home)},
460
+ check=False,
461
+ timeout=15,
462
+ )
463
+ except (OSError, subprocess.TimeoutExpired):
464
+ return False
465
+ return completed.returncode == 0 and completed.stdout == _CONFINEMENT_MARKER
466
+
467
+ def _probe_command(self, *arguments: str) -> subprocess.CompletedProcess[bytes]:
468
+ try:
469
+ completed = subprocess.run(
470
+ [str(self._binary), *arguments],
471
+ stdin=subprocess.DEVNULL,
472
+ stdout=subprocess.PIPE,
473
+ stderr=subprocess.PIPE,
474
+ env=self._environment,
475
+ check=False,
476
+ timeout=10,
477
+ )
478
+ except (OSError, subprocess.TimeoutExpired) as error:
479
+ raise ProviderUnavailable("Codex CLI probe could not complete") from error
480
+ if len(completed.stdout) > _MAX_CAPTURE_BYTES or len(completed.stderr) > _MAX_CAPTURE_BYTES:
481
+ raise ProviderProtocolError("Codex CLI probe output exceeded the capture limit")
482
+ return completed
483
+
484
+ def command(self, attempt: CodexAttempt, output_path: Path) -> tuple[str, ...]:
485
+ workspace = _isolated_workspace(attempt.workspace)
486
+ if workspace == self._attempt_root or not _inside(workspace, self._attempt_root):
487
+ raise ValueError("attempt workspace must be a child of the managed attempt root")
488
+ schema = _workspace_file(attempt.output_schema, workspace, "output_schema")
489
+ if output_path.is_symlink():
490
+ raise ValueError("provider output cannot be a symbolic link")
491
+ resolved_output = output_path.resolve(strict=False)
492
+ if not _inside(resolved_output, workspace) or resolved_output.exists():
493
+ raise ValueError("provider output must be a new file inside the attempt workspace")
494
+ return (
495
+ str(self._binary),
496
+ "--ask-for-approval",
497
+ "never",
498
+ *_permission_config(workspace, Path(tempfile.gettempdir()).resolve()),
499
+ "exec",
500
+ "--ephemeral",
501
+ "--ignore-user-config",
502
+ "--ignore-rules",
503
+ "--strict-config",
504
+ "--skip-git-repo-check",
505
+ "--color",
506
+ "never",
507
+ "--json",
508
+ "--output-schema",
509
+ str(schema),
510
+ "--output-last-message",
511
+ str(resolved_output),
512
+ *(part for image in attempt.images for part in ("--image", str(image.resolve()))),
513
+ *model_config(self._binary, self._environment),
514
+ "--cd",
515
+ str(workspace),
516
+ "-",
517
+ )
518
+
519
+ def execute(
520
+ self,
521
+ attempt: CodexAttempt,
522
+ cancel_token: CancellationToken | None = None,
523
+ ) -> CodexAttemptResult:
524
+ if cancel_token is not None and cancel_token.is_set():
525
+ raise ProviderCancelled(f"Codex attempt {attempt.attempt_id} was cancelled")
526
+ workspace = _isolated_workspace(attempt.workspace)
527
+ output_path = workspace / f"provider-output-{attempt.attempt_id}.json"
528
+ events_path = workspace / f"provider-events-{attempt.attempt_id}.jsonl"
529
+ diagnostics_path = workspace / f"provider-diagnostics-{attempt.attempt_id}.log"
530
+ store = AttemptReceiptStore(workspace, attempt.attempt_id)
531
+ if store.path.exists() or store.path.is_symlink():
532
+ raise ProviderProtocolError("Codex attempt already has a receipt; reconcile it instead of rerunning")
533
+ for artifact in (output_path, events_path, diagnostics_path):
534
+ if artifact.exists() or artifact.is_symlink():
535
+ raise ProviderProtocolError("Codex attempt artifact already exists")
536
+ prompt_hash = attempt.input_hash()
537
+ schema_hash = sha256_file(attempt.output_schema, _MAX_SCHEMA_BYTES)
538
+ receipt = ProviderAttemptReceipt(
539
+ attempt_id=attempt.attempt_id,
540
+ state=ProviderAttemptState.PREPARED,
541
+ prompt_sha256=prompt_hash,
542
+ schema_sha256=schema_hash,
543
+ )
544
+ store.write(receipt)
545
+
546
+ def record_started(pid: int) -> None:
547
+ nonlocal receipt
548
+ receipt = replace(
549
+ receipt,
550
+ state=ProviderAttemptState.RUNNING,
551
+ started_at=utc_now(),
552
+ pid=pid,
553
+ )
554
+ store.write(receipt)
555
+
556
+ command = self.command(attempt, output_path)
557
+ started = time.monotonic()
558
+ returncode: int | None = None
559
+ try:
560
+ stdout, stderr, returncode = self._run_bounded(
561
+ command,
562
+ attempt,
563
+ workspace,
564
+ cancel_token,
565
+ events_path,
566
+ diagnostics_path,
567
+ record_started,
568
+ )
569
+ self._sanitize_persisted_artifacts(events_path, diagnostics_path, attempt.prompt)
570
+ stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
571
+ stderr = self._read_artifact(diagnostics_path, _MAX_CAPTURE_BYTES)
572
+ self._raise_for_failed_turn(stdout)
573
+ if returncode != 0:
574
+ self._raise_for_exit(returncode, stderr)
575
+ result = self._validated_result(attempt, output_path, stdout)
576
+ if attempt.input_hash() != prompt_hash:
577
+ raise ProviderProtocolError("approved image snapshots changed during the attempt")
578
+ receipt = replace(
579
+ receipt,
580
+ state=ProviderAttemptState.SUCCEEDED,
581
+ finished_at=utc_now(),
582
+ return_code=returncode,
583
+ output_sha256=sha256_file(output_path, _MAX_RESULT_BYTES),
584
+ events_sha256=sha256_file(events_path, _MAX_CAPTURE_BYTES),
585
+ diagnostics_sha256=sha256_file(diagnostics_path, _MAX_CAPTURE_BYTES),
586
+ usage=result.usage,
587
+ )
588
+ store.write(receipt)
589
+ return replace(result, elapsed_seconds=time.monotonic() - started)
590
+ except Exception as error:
591
+ self._sanitize_persisted_artifacts(events_path, diagnostics_path, attempt.prompt)
592
+ state, error_code = self._failure_receipt(error)
593
+ receipt = replace(
594
+ receipt,
595
+ state=state,
596
+ finished_at=utc_now(),
597
+ return_code=returncode,
598
+ output_sha256=self._optional_artifact_hash(output_path, _MAX_RESULT_BYTES),
599
+ events_sha256=self._optional_artifact_hash(events_path, _MAX_CAPTURE_BYTES),
600
+ diagnostics_sha256=self._optional_artifact_hash(diagnostics_path, _MAX_CAPTURE_BYTES),
601
+ usage=self._optional_usage(events_path),
602
+ error_code=error_code,
603
+ )
604
+ try:
605
+ store.write(receipt)
606
+ except AttemptReceiptError as receipt_error:
607
+ raise ProviderProtocolError(
608
+ "Codex attempt failed and its terminal receipt could not be saved"
609
+ ) from receipt_error
610
+ raise
611
+
612
+ def reconcile(self, attempt: CodexAttempt) -> CodexReconciliation:
613
+ workspace = _isolated_workspace(attempt.workspace)
614
+ store = AttemptReceiptStore(workspace, attempt.attempt_id)
615
+ try:
616
+ receipt = store.read()
617
+ except AttemptReceiptError:
618
+ return CodexReconciliation(
619
+ attempt.attempt_id,
620
+ ProviderAttemptState.UNKNOWN,
621
+ None,
622
+ "receipt_unavailable",
623
+ )
624
+ try:
625
+ if (
626
+ receipt.attempt_id != attempt.attempt_id
627
+ or receipt.prompt_sha256 != attempt.input_hash()
628
+ or receipt.schema_sha256 != sha256_file(attempt.output_schema, _MAX_SCHEMA_BYTES)
629
+ ):
630
+ raise AttemptReceiptError("attempt identity does not match its receipt")
631
+ output_path = workspace / f"provider-output-{attempt.attempt_id}.json"
632
+ events_path = workspace / f"provider-events-{attempt.attempt_id}.jsonl"
633
+ if receipt.state in {
634
+ ProviderAttemptState.SUCCEEDED,
635
+ ProviderAttemptState.RUNNING,
636
+ }:
637
+ stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
638
+ result = self._validated_result(attempt, output_path, stdout)
639
+ output_hash = sha256_file(output_path, _MAX_RESULT_BYTES)
640
+ events_hash = sha256_file(events_path, _MAX_CAPTURE_BYTES)
641
+ if receipt.state is ProviderAttemptState.SUCCEEDED:
642
+ if receipt.output_sha256 != output_hash or receipt.events_sha256 != events_hash:
643
+ raise AttemptReceiptError("terminal provider artifacts changed")
644
+ self._verify_recorded_hash(
645
+ workspace / f"provider-diagnostics-{attempt.attempt_id}.log",
646
+ receipt.diagnostics_sha256,
647
+ _MAX_CAPTURE_BYTES,
648
+ )
649
+ else:
650
+ diagnostics_path = workspace / (f"provider-diagnostics-{attempt.attempt_id}.log")
651
+ receipt = replace(
652
+ receipt,
653
+ state=ProviderAttemptState.SUCCEEDED,
654
+ finished_at=utc_now(),
655
+ return_code=0,
656
+ output_sha256=output_hash,
657
+ events_sha256=events_hash,
658
+ diagnostics_sha256=self._optional_artifact_hash(diagnostics_path, _MAX_CAPTURE_BYTES),
659
+ usage=result.usage,
660
+ error_code=None,
661
+ )
662
+ store.write(receipt)
663
+ return CodexReconciliation(
664
+ attempt.attempt_id,
665
+ ProviderAttemptState.SUCCEEDED,
666
+ result,
667
+ "terminal_artifacts_verified",
668
+ )
669
+ if receipt.state is ProviderAttemptState.PREPARED:
670
+ interrupted = replace(
671
+ receipt,
672
+ state=ProviderAttemptState.INTERRUPTED,
673
+ finished_at=utc_now(),
674
+ error_code="launch_interrupted",
675
+ )
676
+ store.write(interrupted)
677
+ return CodexReconciliation(
678
+ attempt.attempt_id,
679
+ ProviderAttemptState.INTERRUPTED,
680
+ None,
681
+ "launch_interrupted",
682
+ )
683
+ self._verify_recorded_hash(
684
+ workspace / f"provider-output-{attempt.attempt_id}.json",
685
+ receipt.output_sha256,
686
+ _MAX_RESULT_BYTES,
687
+ )
688
+ self._verify_recorded_hash(
689
+ workspace / f"provider-events-{attempt.attempt_id}.jsonl",
690
+ receipt.events_sha256,
691
+ _MAX_CAPTURE_BYTES,
692
+ )
693
+ self._verify_recorded_hash(
694
+ workspace / f"provider-diagnostics-{attempt.attempt_id}.log",
695
+ receipt.diagnostics_sha256,
696
+ _MAX_CAPTURE_BYTES,
697
+ )
698
+ return CodexReconciliation(
699
+ attempt.attempt_id,
700
+ receipt.state,
701
+ None,
702
+ receipt.error_code or "terminal_receipt_verified",
703
+ )
704
+ except (AttemptReceiptError, OSError, ValueError, ProviderProtocolError):
705
+ return CodexReconciliation(
706
+ attempt.attempt_id,
707
+ ProviderAttemptState.UNKNOWN,
708
+ None,
709
+ "terminal_state_unverified",
710
+ )
711
+
712
+ def _validated_result(self, attempt: CodexAttempt, output_path: Path, stdout: bytes) -> CodexAttemptResult:
713
+ if not output_path.is_file() or output_path.is_symlink():
714
+ raise ProviderProtocolError("Codex did not create the expected result file")
715
+ if output_path.stat().st_size > _MAX_RESULT_BYTES:
716
+ raise ProviderProtocolError("Codex result exceeded the size limit")
717
+ try:
718
+ payload = json.loads(output_path.read_text(encoding="utf-8"))
719
+ except (OSError, UnicodeError, json.JSONDecodeError) as error:
720
+ raise ProviderProtocolError("Codex result was not valid UTF-8 JSON") from error
721
+ if not isinstance(payload, dict):
722
+ raise ProviderProtocolError("Codex result must be a JSON object")
723
+ schema = _load_output_schema(
724
+ _workspace_file(
725
+ attempt.output_schema,
726
+ _isolated_workspace(attempt.workspace),
727
+ "output_schema",
728
+ )
729
+ )
730
+ try:
731
+ Draft202012Validator(schema).validate(payload)
732
+ except ValidationError as error:
733
+ raise ProviderProtocolError("Codex result did not match the output schema") from error
734
+ event_types, usage = self._events_and_usage(stdout)
735
+ if "turn.completed" not in event_types:
736
+ raise ProviderProtocolError("Codex event stream did not report a completed turn")
737
+ return CodexAttemptResult(
738
+ attempt_id=attempt.attempt_id,
739
+ payload=payload,
740
+ event_types=event_types,
741
+ elapsed_seconds=None,
742
+ usage=usage,
743
+ )
744
+
745
+ @staticmethod
746
+ def _raise_for_failed_turn(stdout: bytes, *, limit: int = _MAX_CAPTURE_BYTES) -> None:
747
+ """CLI failures can be reported only in JSONL while stderr stays empty."""
748
+ events = []
749
+ for line in _decode_capture(stdout, "JSONL stream", limit).splitlines():
750
+ try:
751
+ event = json.loads(line)
752
+ except json.JSONDecodeError:
753
+ continue # Normal protocol validation follows.
754
+ if isinstance(event, dict):
755
+ events.append(event)
756
+ terminal = next((e for e in reversed(events) if e.get("type") in {"turn.completed", "turn.failed"}), None)
757
+ if terminal is not None and terminal.get("type") == "turn.completed":
758
+ return
759
+ messages = []
760
+ for event in events:
761
+ if event.get("type") not in {"error", "turn.failed"}:
762
+ continue
763
+ detail = event.get("error", event)
764
+ message = detail.get("message") if isinstance(detail, dict) else detail
765
+ if isinstance(message, str):
766
+ messages.append(message)
767
+ if messages:
768
+ CodexExecAdapter._raise_for_exit(1, "\n".join(messages).encode("utf-8"))
769
+ if terminal is not None:
770
+ raise ProviderProtocolError("Codex reported a failed turn without a diagnostic")
771
+
772
+ @staticmethod
773
+ def _raise_for_exit(returncode: int, stderr: bytes) -> None:
774
+ diagnostic = _decode_capture(stderr, "stderr").lower()
775
+ if any(marker in diagnostic for marker in ("not logged in", "unauthorized", "login required")):
776
+ raise ProviderAuthenticationError("Codex login is missing or no longer valid")
777
+ if any(marker in diagnostic for marker in ("usage limit", "rate limit", "quota", "credits")):
778
+ raise ProviderUsageLimitError("Codex account usage limit prevented this attempt")
779
+ if any(
780
+ marker in diagnostic for marker in ("connection failed", "network is unreachable", "could not resolve host")
781
+ ):
782
+ raise ProviderNetworkError("Codex could not reach its service")
783
+ if any(marker in diagnostic for marker in ("sandbox", "operation not permitted", "permission")):
784
+ raise ProviderPermissionError("Codex permission confinement failed")
785
+ raise ProviderProtocolError(f"Codex attempt exited with code {returncode}")
786
+
787
+ def _stdin_payload(self, attempt: CodexAttempt) -> bytes:
788
+ """Codex reads the prompt from stdin and images from --image flags."""
789
+ return attempt.prompt.encode("utf-8")
790
+
791
+ def _run_bounded(
792
+ self,
793
+ command: tuple[str, ...],
794
+ attempt: CodexAttempt,
795
+ workspace: Path,
796
+ cancel_token: CancellationToken | None,
797
+ events_path: Path,
798
+ diagnostics_path: Path,
799
+ record_started,
800
+ ) -> tuple[bytes, bytes, int]:
801
+ deadline = time.monotonic() + attempt.timeout_seconds
802
+ with tempfile.TemporaryFile() as prompt_stream:
803
+ prompt_stream.write(self._stdin_payload(attempt))
804
+ prompt_stream.seek(0)
805
+ stdout_descriptor = os.open(events_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
806
+ try:
807
+ stderr_descriptor = os.open(diagnostics_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
808
+ except Exception:
809
+ os.close(stdout_descriptor)
810
+ raise
811
+ with (
812
+ os.fdopen(stdout_descriptor, "wb") as stdout_stream,
813
+ os.fdopen(stderr_descriptor, "wb") as stderr_stream,
814
+ ):
815
+ try:
816
+ process = subprocess.Popen(
817
+ command,
818
+ cwd=workspace,
819
+ env=self._environment,
820
+ stdin=prompt_stream,
821
+ stdout=stdout_stream,
822
+ stderr=stderr_stream,
823
+ start_new_session=os.name == "posix",
824
+ )
825
+ except OSError as error:
826
+ raise ProviderUnavailable("Codex CLI could not be launched") from error
827
+ record_started(process.pid)
828
+
829
+ while process.poll() is None:
830
+ if cancel_token is not None and cancel_token.is_set():
831
+ self._terminate(process)
832
+ raise ProviderCancelled(f"Codex attempt {attempt.attempt_id} was cancelled")
833
+ if time.monotonic() >= deadline:
834
+ self._terminate(process)
835
+ raise ProviderTimedOut(f"Codex attempt {attempt.attempt_id} exceeded its timeout")
836
+ if (
837
+ os.fstat(stdout_stream.fileno()).st_size > _MAX_CAPTURE_BYTES
838
+ or os.fstat(stderr_stream.fileno()).st_size > _MAX_CAPTURE_BYTES
839
+ ):
840
+ self._terminate(process)
841
+ raise ProviderProtocolError("Codex diagnostic output exceeded the capture limit")
842
+ time.sleep(_POLL_INTERVAL_SECONDS)
843
+
844
+ stdout_stream.flush()
845
+ stderr_stream.flush()
846
+ stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
847
+ stderr = self._read_artifact(diagnostics_path, _MAX_CAPTURE_BYTES)
848
+ return stdout, stderr, process.returncode
849
+
850
+ @staticmethod
851
+ def _events_and_usage(
852
+ stdout: bytes,
853
+ *,
854
+ limit: int = _MAX_CAPTURE_BYTES,
855
+ ) -> tuple[tuple[str, ...], ProviderUsage | None]:
856
+ event_types: list[str] = []
857
+ usage: ProviderUsage | None = None
858
+ lines = _decode_capture(stdout, "JSONL stream", limit).splitlines()
859
+ for line in lines:
860
+ if not line.strip():
861
+ continue
862
+ try:
863
+ event = json.loads(line)
864
+ except json.JSONDecodeError as error:
865
+ raise ProviderProtocolError("Codex JSONL stream contained invalid JSON") from error
866
+ if not isinstance(event, dict):
867
+ raise ProviderProtocolError("Codex JSONL events must be objects")
868
+ event_type = event.get("type")
869
+ if isinstance(event_type, str) and event_type:
870
+ event_types.append(event_type)
871
+ candidate_usage = event.get("usage")
872
+ if event_type in {"turn.completed", "turn.failed"} and isinstance(candidate_usage, dict):
873
+ try:
874
+ usage = ProviderUsage(
875
+ input_tokens=candidate_usage["input_tokens"],
876
+ cached_input_tokens=candidate_usage.get("cached_input_tokens", 0),
877
+ output_tokens=candidate_usage["output_tokens"],
878
+ )
879
+ except (KeyError, TypeError, ValueError) as error:
880
+ raise ProviderProtocolError("Codex usage data was malformed") from error
881
+ return tuple(event_types), usage
882
+
883
+ @classmethod
884
+ def _optional_usage(cls, path: Path) -> ProviderUsage | None:
885
+ try:
886
+ _, usage = cls._events_and_usage(cls._read_artifact(path, _MAX_CAPTURE_BYTES))
887
+ return usage
888
+ except (OSError, ProviderProtocolError):
889
+ return None
890
+
891
+ @staticmethod
892
+ def _read_artifact(path: Path, limit: int) -> bytes:
893
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > limit:
894
+ raise ProviderProtocolError("Codex attempt artifact is missing or oversized")
895
+ value = path.read_bytes()
896
+ if len(value) > limit:
897
+ raise ProviderProtocolError("Codex attempt artifact exceeded its size limit")
898
+ return value
899
+
900
+ @staticmethod
901
+ def _optional_artifact_hash(path: Path, limit: int) -> str | None:
902
+ try:
903
+ return sha256_file(path, limit)
904
+ except (AttemptReceiptError, OSError):
905
+ return None
906
+
907
+ @staticmethod
908
+ def _sanitize_persisted_artifacts(events_path: Path, diagnostics_path: Path, prompt: str) -> None:
909
+ prompt_bytes = prompt.encode("utf-8")
910
+ for path in (events_path, diagnostics_path):
911
+ if path.is_symlink() or not path.is_file():
912
+ continue
913
+ try:
914
+ value = path.read_bytes()
915
+ except OSError:
916
+ continue
917
+ sanitized = value.replace(prompt_bytes, b"[REDACTED_PROMPT]")
918
+ for pattern in _SECRET_PATTERNS:
919
+ if pattern.groups:
920
+ sanitized = pattern.sub(rb"\1[REDACTED_SECRET]", sanitized)
921
+ else:
922
+ sanitized = pattern.sub(b"[REDACTED_SECRET]", sanitized)
923
+ if sanitized == value:
924
+ continue
925
+ temporary = path.with_name(f".{path.name}.redacted-{uuid.uuid4().hex}")
926
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
927
+ try:
928
+ with os.fdopen(descriptor, "wb") as stream:
929
+ stream.write(sanitized)
930
+ stream.flush()
931
+ os.fsync(stream.fileno())
932
+ os.replace(temporary, path)
933
+ os.chmod(path, 0o600)
934
+ finally:
935
+ if temporary.exists() and not temporary.is_symlink():
936
+ temporary.unlink()
937
+
938
+ @staticmethod
939
+ def _verify_recorded_hash(path: Path, expected: str | None, limit: int) -> None:
940
+ if expected is None:
941
+ return
942
+ if sha256_file(path, limit) != expected:
943
+ raise AttemptReceiptError("provider artifact changed after receipt")
944
+
945
+ @staticmethod
946
+ def _failure_receipt(
947
+ error: Exception,
948
+ ) -> tuple[ProviderAttemptState, str]:
949
+ if isinstance(error, ProviderCancelled):
950
+ return ProviderAttemptState.CANCELLED, "cancelled"
951
+ if isinstance(error, ProviderTimedOut):
952
+ return ProviderAttemptState.TIMED_OUT, "timed_out"
953
+ if isinstance(error, ProviderAuthenticationError):
954
+ return ProviderAttemptState.FAILED, "authentication"
955
+ if isinstance(error, ProviderUsageLimitError):
956
+ return ProviderAttemptState.FAILED, "usage_limit"
957
+ if isinstance(error, ProviderNetworkError):
958
+ return ProviderAttemptState.FAILED, "network"
959
+ if isinstance(error, ProviderPermissionError):
960
+ return ProviderAttemptState.FAILED, "permission"
961
+ if isinstance(error, ProviderUnavailable):
962
+ return ProviderAttemptState.FAILED, "unavailable"
963
+ return ProviderAttemptState.FAILED, "protocol"
964
+
965
+ @staticmethod
966
+ def _terminate(process: subprocess.Popen[bytes]) -> None:
967
+ if process.poll() is not None:
968
+ return
969
+ if os.name == "posix":
970
+ try:
971
+ os.killpg(process.pid, signal.SIGTERM)
972
+ except ProcessLookupError:
973
+ process.wait(timeout=2)
974
+ return
975
+ except PermissionError:
976
+ process.terminate()
977
+ else:
978
+ process.terminate()
979
+ try:
980
+ process.wait(timeout=2)
981
+ except subprocess.TimeoutExpired:
982
+ if os.name == "posix":
983
+ try:
984
+ os.killpg(process.pid, signal.SIGKILL)
985
+ except ProcessLookupError:
986
+ pass
987
+ except PermissionError:
988
+ process.kill()
989
+ else:
990
+ process.kill()
991
+ process.wait(timeout=2)