@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.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +52 -4
- package/pyproject.toml +28 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +416 -0
- package/src/clipen/analysis/audio.py +392 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +751 -0
- package/src/clipen/analysis/image_similarity.py +143 -0
- package/src/clipen/analysis/keyframes.py +171 -0
- package/src/clipen/analysis/models.py +230 -0
- package/src/clipen/analysis/qwen_worker.py +629 -0
- package/src/clipen/analysis/resources.py +21 -0
- package/src/clipen/analysis/runtime.py +64 -0
- package/src/clipen/analysis/service.py +626 -0
- package/src/clipen/analysis/setup.py +935 -0
- package/src/clipen/analysis/setup_cli.py +117 -0
- package/src/clipen/analysis/storage.py +2046 -0
- package/src/clipen/analysis/transcription.py +948 -0
- package/src/clipen/analysis/visual.py +176 -0
- package/src/clipen/annotations/__init__.py +10 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +380 -0
- package/src/clipen/annotations/suggestions.py +120 -0
- package/src/clipen/asr_release.py +139 -0
- package/src/clipen/bootstrap.py +967 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1470 -0
- package/src/clipen/controller/server.py +543 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +117 -0
- package/src/clipen/domain/timeline.py +584 -0
- package/src/clipen/domain/validation.py +15 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +134 -0
- package/src/clipen/editing/agent_repository.py +757 -0
- package/src/clipen/editing/agent_tools.py +532 -0
- package/src/clipen/editing/alignment.py +110 -0
- package/src/clipen/editing/alignment_setup.py +108 -0
- package/src/clipen/editing/alignment_worker.py +22 -0
- package/src/clipen/editing/change_report.py +71 -0
- package/src/clipen/editing/compiler.py +41 -0
- package/src/clipen/editing/component_looks.py +107 -0
- package/src/clipen/editing/component_review.py +78 -0
- package/src/clipen/editing/coordinator.py +374 -0
- package/src/clipen/editing/editorial_review.py +187 -0
- package/src/clipen/editing/evidence_jobs.py +295 -0
- package/src/clipen/editing/history_changes.py +131 -0
- package/src/clipen/editing/music_choices.py +15 -0
- package/src/clipen/editing/production_catalog.py +192 -0
- package/src/clipen/editing/production_limits.py +59 -0
- package/src/clipen/editing/production_media.py +226 -0
- package/src/clipen/editing/production_preview.py +180 -0
- package/src/clipen/editing/production_progress.py +141 -0
- package/src/clipen/editing/production_requirements.py +50 -0
- package/src/clipen/editing/production_tools.py +596 -0
- package/src/clipen/editing/program_audio.py +118 -0
- package/src/clipen/editing/program_direction.py +49 -0
- package/src/clipen/editing/program_story.py +53 -0
- package/src/clipen/editing/program_subtitles.py +134 -0
- package/src/clipen/editing/programme_review.py +73 -0
- package/src/clipen/editing/prompt_history.py +47 -0
- package/src/clipen/editing/recut.py +127 -0
- package/src/clipen/editing/refinement_references.py +188 -0
- package/src/clipen/editing/resolve_export.py +616 -0
- package/src/clipen/editing/resolve_titles.py +234 -0
- package/src/clipen/editing/skill_tools.py +575 -0
- package/src/clipen/editing/source_dialogue.py +82 -0
- package/src/clipen/editing/speech_coverage.py +30 -0
- package/src/clipen/editing/speech_quality.py +6 -0
- package/src/clipen/editing/tool_receipts.py +52 -0
- package/src/clipen/editing/versions.py +161 -0
- package/src/clipen/editing/visual_preview.py +93 -0
- package/src/clipen/editing/workbench.py +74 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +149 -0
- package/src/clipen/finishing/catalog.py +181 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +26 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +40 -0
- package/src/clipen/mcp_editing/server.py +353 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +266 -0
- package/src/clipen/media/models.py +360 -0
- package/src/clipen/media/preview.py +147 -0
- package/src/clipen/media/probe.py +446 -0
- package/src/clipen/media/service.py +317 -0
- package/src/clipen/media/storage.py +742 -0
- package/src/clipen/music_vocabulary.py +5 -0
- package/src/clipen/planning/__init__.py +9 -0
- package/src/clipen/planning/models.py +240 -0
- package/src/clipen/power.py +23 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +269 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +34 -0
- package/src/clipen/projects/models.py +192 -0
- package/src/clipen/projects/picker.py +256 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +175 -0
- package/src/clipen/projects/storage.py +1478 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +75 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +194 -0
- package/src/clipen/providers/claude.py +375 -0
- package/src/clipen/providers/claude_editing.py +111 -0
- package/src/clipen/providers/codex.py +1036 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +565 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +270 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +126 -0
- package/src/clipen/rendering/custom_components.py +240 -0
- package/src/clipen/rendering/custom_render.py +197 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +64 -0
- package/src/clipen/rendering/program_components.py +193 -0
- package/src/clipen/rendering/program_creator.py +649 -0
- package/src/clipen/rendering/program_identities.py +255 -0
- package/src/clipen/rendering/program_motion.py +141 -0
- package/src/clipen/rendering/program_studio.py +168 -0
- package/src/clipen/rendering/program_styles.py +235 -0
- package/src/clipen/rendering/program_subtitles.py +52 -0
- package/src/clipen/rendering/renderer.py +708 -0
- package/src/clipen/rendering/storage.py +243 -0
- package/src/clipen/rendering/titles.py +360 -0
- package/src/clipen/skills/__init__.py +4 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +218 -0
- package/src/clipen/skills/library.py +131 -0
- package/src/clipen/skills/package.py +231 -0
- package/src/clipen/skills/visual_styles.py +44 -0
- package/src/clipen/workspace.py +210 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,1036 @@
|
|
|
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
|
+
from dataclasses import dataclass, replace
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import signal
|
|
17
|
+
import subprocess
|
|
18
|
+
import tempfile
|
|
19
|
+
import time
|
|
20
|
+
from typing import Mapping
|
|
21
|
+
import uuid
|
|
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
|
+
|
|
49
|
+
_MAX_PROMPT_BYTES = 1_000_000
|
|
50
|
+
_MAX_SCHEMA_BYTES = 1_000_000
|
|
51
|
+
_MAX_CAPTURE_BYTES = 2_000_000
|
|
52
|
+
_MAX_RESULT_BYTES = 2_000_000
|
|
53
|
+
_POLL_INTERVAL_SECONDS = 0.05
|
|
54
|
+
_SAFE_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
|
|
55
|
+
_PERMISSION_PROFILE = "clipen_attempt"
|
|
56
|
+
_CONFINEMENT_MARKER = b"clipen-confinement-ok\n"
|
|
57
|
+
_CONFINEMENT_SCRIPT = """
|
|
58
|
+
if ! /bin/cat "$1" >/dev/null 2>&1; then exit 10; fi
|
|
59
|
+
if /bin/cat "$2" >/dev/null 2>&1; then exit 20; fi
|
|
60
|
+
if /bin/cat "$3" >/dev/null 2>&1; then exit 30; fi
|
|
61
|
+
/bin/echo clipen-confinement-ok
|
|
62
|
+
""".strip()
|
|
63
|
+
_SECRET_PATTERNS = (
|
|
64
|
+
re.compile(rb"(?i)(authorization\s*:\s*bearer\s+)[^\s\"']+"),
|
|
65
|
+
re.compile(rb"(?i)(api[_-]?key\s*[=:]\s*)[^\s\"']+"),
|
|
66
|
+
re.compile(rb"\bsk-[A-Za-z0-9_-]{16,}\b"),
|
|
67
|
+
)
|
|
68
|
+
_ENVIRONMENT_ALLOWLIST = frozenset(
|
|
69
|
+
{
|
|
70
|
+
"ALL_PROXY",
|
|
71
|
+
"CODEX_HOME",
|
|
72
|
+
"HOME",
|
|
73
|
+
"HTTPS_PROXY",
|
|
74
|
+
"HTTP_PROXY",
|
|
75
|
+
"LANG",
|
|
76
|
+
"LC_ALL",
|
|
77
|
+
"LOGNAME",
|
|
78
|
+
"NO_PROXY",
|
|
79
|
+
"PATH",
|
|
80
|
+
"SHELL",
|
|
81
|
+
"SSL_CERT_DIR",
|
|
82
|
+
"SSL_CERT_FILE",
|
|
83
|
+
"TMPDIR",
|
|
84
|
+
"USER",
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _bounded_identifier(value: str, field: str) -> None:
|
|
90
|
+
if not isinstance(value, str) or _SAFE_IDENTIFIER.fullmatch(value) is None:
|
|
91
|
+
raise ValueError(f"{field} must be a safe bounded identifier")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _inside(path: Path, root: Path) -> bool:
|
|
95
|
+
return path == root or path.is_relative_to(root)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _isolated_workspace(path: Path) -> Path:
|
|
99
|
+
if path.is_symlink():
|
|
100
|
+
raise ValueError("attempt workspace cannot be a symbolic link")
|
|
101
|
+
resolved = path.resolve(strict=True)
|
|
102
|
+
if not resolved.is_dir():
|
|
103
|
+
raise ValueError("attempt workspace must be a directory")
|
|
104
|
+
return resolved
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _workspace_file(path: Path, workspace: Path, field: str) -> Path:
|
|
108
|
+
if path.is_symlink():
|
|
109
|
+
raise ValueError(f"{field} cannot be a symbolic link")
|
|
110
|
+
resolved = path.resolve(strict=True)
|
|
111
|
+
if not resolved.is_file() or not _inside(resolved, workspace):
|
|
112
|
+
raise ValueError(f"{field} must be a regular file inside the attempt workspace")
|
|
113
|
+
return resolved
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Clipen ignores the user's Codex config so it cannot change tools, rules or
|
|
117
|
+
# approvals. Only the chosen model and reasoning effort carry over.
|
|
118
|
+
_EFFORTS = frozenset({"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"})
|
|
119
|
+
_MODEL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,79}")
|
|
120
|
+
_TABLE = re.compile(r"^\s*\[\s*([^\[\]]+?)\s*\]\s*(?:#.*)?$")
|
|
121
|
+
_STRING = re.compile(r"""^\s*([A-Za-z0-9_]+)\s*=\s*(?:"([^"\\]*)"|'([^']*)')\s*(?:#.*)?$""")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def codex_preferences(environment: Mapping[str, str] | None = None) -> tuple[str | None, str | None]:
|
|
125
|
+
"""The model and reasoning effort from the user's Codex config, honouring `profile`."""
|
|
126
|
+
source = os.environ if environment is None else environment
|
|
127
|
+
home = source.get("CODEX_HOME") or (str(Path(source["HOME"]) / ".codex") if source.get("HOME") else None)
|
|
128
|
+
if not home:
|
|
129
|
+
return None, None
|
|
130
|
+
path = Path(home) / "config.toml"
|
|
131
|
+
try:
|
|
132
|
+
if path.is_symlink() and not path.resolve().is_file() or path.stat().st_size > 1024 * 1024:
|
|
133
|
+
return None, None
|
|
134
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
135
|
+
except (OSError, UnicodeDecodeError):
|
|
136
|
+
return None, None
|
|
137
|
+
tables: dict[str, dict[str, str]] = {"": {}}
|
|
138
|
+
table = ""
|
|
139
|
+
for line in lines:
|
|
140
|
+
if header := _TABLE.match(line):
|
|
141
|
+
table = header.group(1).replace('"', "").replace(" ", "")
|
|
142
|
+
tables.setdefault(table, {})
|
|
143
|
+
elif value := _STRING.match(line):
|
|
144
|
+
tables[table][value.group(1)] = value.group(2) if value.group(2) is not None else value.group(3)
|
|
145
|
+
chosen = {**tables[""], **tables.get("profiles." + tables[""].get("profile", ""), {})} if tables[""].get("profile") else tables[""]
|
|
146
|
+
model, effort = chosen.get("model"), chosen.get("model_reasoning_effort")
|
|
147
|
+
return (model if model and _MODEL.fullmatch(model) else None,
|
|
148
|
+
effort if effort in _EFFORTS else None)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def model_config(binary: str | Path, environment: Mapping[str, str] | None = None) -> tuple[str, ...]:
|
|
152
|
+
"""`-c` overrides for the user's model and effort, kept only when this account supports them."""
|
|
153
|
+
preferences = codex_preferences(environment)
|
|
154
|
+
if preferences == (None, None):
|
|
155
|
+
return ()
|
|
156
|
+
from .account import available_models, resolve_codex_model
|
|
157
|
+
resolved = resolve_codex_model(preferences, available_models(binary, environment or os.environ))
|
|
158
|
+
if resolved is None:
|
|
159
|
+
return ()
|
|
160
|
+
return (*(("-c", f"model={json.dumps(resolved['id'])}") if resolved["apply_model"] else ()),
|
|
161
|
+
*(("-c", f"model_reasoning_effort={json.dumps(resolved['effort'])}") if resolved["apply_effort"] else ()))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _provider_environment(source: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
165
|
+
inherited = os.environ if source is None else source
|
|
166
|
+
environment = {key: value for key, value in inherited.items() if key in _ENVIRONMENT_ALLOWLIST}
|
|
167
|
+
environment["CLICOLOR"] = "0"
|
|
168
|
+
environment["NO_COLOR"] = "1"
|
|
169
|
+
return environment
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _decode_capture(value: bytes, field: str, limit: int = _MAX_CAPTURE_BYTES) -> str:
|
|
173
|
+
if len(value) > limit:
|
|
174
|
+
raise ProviderProtocolError(f"Codex {field} exceeded the capture limit")
|
|
175
|
+
try:
|
|
176
|
+
return value.decode("utf-8", errors="strict")
|
|
177
|
+
except UnicodeDecodeError as error:
|
|
178
|
+
raise ProviderProtocolError(f"Codex {field} was not valid UTF-8") from error
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _load_output_schema(path: Path) -> dict[str, object]:
|
|
182
|
+
if path.stat().st_size > _MAX_SCHEMA_BYTES:
|
|
183
|
+
raise ValueError("output_schema must be at most 1,000,000 bytes")
|
|
184
|
+
try:
|
|
185
|
+
parsed = json.loads(path.read_text(encoding="utf-8"))
|
|
186
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
187
|
+
raise ValueError("output_schema must contain valid UTF-8 JSON") from error
|
|
188
|
+
if not isinstance(parsed, dict):
|
|
189
|
+
raise ValueError("output_schema must contain a JSON object")
|
|
190
|
+
try:
|
|
191
|
+
Draft202012Validator.check_schema(parsed)
|
|
192
|
+
except SchemaError as error:
|
|
193
|
+
raise ValueError("output_schema must be a valid JSON Schema 2020-12 document") from error
|
|
194
|
+
return parsed
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _toml_string(value: str) -> str:
|
|
198
|
+
"""Encode a string using the TOML-compatible JSON basic-string subset."""
|
|
199
|
+
|
|
200
|
+
return json.dumps(value, ensure_ascii=True)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _permission_config(workspace: Path, temp_root: Path | None = None) -> tuple[str, ...]:
|
|
204
|
+
workspace_key = _toml_string(str(workspace))
|
|
205
|
+
denied_roots = {"/private/tmp/**", "/tmp/**", "/var/tmp/**"}
|
|
206
|
+
if temp_root is not None:
|
|
207
|
+
denied_roots.add(f"{temp_root}/**")
|
|
208
|
+
filesystem_entries = [
|
|
209
|
+
f'{_toml_string(":minimal")}="read"',
|
|
210
|
+
f'{_toml_string(":workspace_roots")}="read"',
|
|
211
|
+
]
|
|
212
|
+
filesystem_entries.extend(
|
|
213
|
+
f'{_toml_string(path)}="deny"' for path in sorted(denied_roots)
|
|
214
|
+
)
|
|
215
|
+
return (
|
|
216
|
+
"-c",
|
|
217
|
+
f'default_permissions={_toml_string(_PERMISSION_PROFILE)}',
|
|
218
|
+
"-c",
|
|
219
|
+
f'permissions.{_PERMISSION_PROFILE}.description="Clipen isolated AI attempt"',
|
|
220
|
+
"-c",
|
|
221
|
+
f"permissions.{_PERMISSION_PROFILE}.workspace_roots={{{workspace_key}=true}}",
|
|
222
|
+
"-c",
|
|
223
|
+
f"permissions.{_PERMISSION_PROFILE}.filesystem={{{','.join(filesystem_entries)}}}",
|
|
224
|
+
"-c",
|
|
225
|
+
f"permissions.{_PERMISSION_PROFILE}.network.enabled=false",
|
|
226
|
+
"-c",
|
|
227
|
+
'shell_environment_policy.inherit="none"',
|
|
228
|
+
"-c",
|
|
229
|
+
'shell_environment_policy.set={PATH="/usr/bin:/bin",LANG="C"}',
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@dataclass(frozen=True)
|
|
234
|
+
class CodexCapabilities:
|
|
235
|
+
"""CLI features Clipen requires before offering Codex in the UI."""
|
|
236
|
+
|
|
237
|
+
ephemeral_sessions: bool
|
|
238
|
+
isolated_user_config: bool
|
|
239
|
+
isolated_rules: bool
|
|
240
|
+
granular_permissions: bool
|
|
241
|
+
json_events: bool
|
|
242
|
+
output_schema: bool
|
|
243
|
+
output_file: bool
|
|
244
|
+
|
|
245
|
+
@property
|
|
246
|
+
def supports_bounded_attempts(self) -> bool:
|
|
247
|
+
return all(
|
|
248
|
+
(
|
|
249
|
+
self.ephemeral_sessions,
|
|
250
|
+
self.isolated_user_config,
|
|
251
|
+
self.isolated_rules,
|
|
252
|
+
self.granular_permissions,
|
|
253
|
+
self.json_events,
|
|
254
|
+
self.output_schema,
|
|
255
|
+
self.output_file,
|
|
256
|
+
)
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@dataclass(frozen=True)
|
|
261
|
+
class CodexProbeResult:
|
|
262
|
+
"""Read-only availability snapshot; probing never invokes a model."""
|
|
263
|
+
|
|
264
|
+
version: str
|
|
265
|
+
authenticated: bool
|
|
266
|
+
capabilities: CodexCapabilities
|
|
267
|
+
confinement_verified: bool
|
|
268
|
+
|
|
269
|
+
@property
|
|
270
|
+
def available(self) -> bool:
|
|
271
|
+
return (
|
|
272
|
+
self.authenticated
|
|
273
|
+
and self.capabilities.supports_bounded_attempts
|
|
274
|
+
and self.confinement_verified
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@dataclass(frozen=True)
|
|
279
|
+
class CodexAttempt:
|
|
280
|
+
attempt_id: str
|
|
281
|
+
workspace: Path
|
|
282
|
+
output_schema: Path
|
|
283
|
+
prompt: str
|
|
284
|
+
timeout_seconds: float = 300.0
|
|
285
|
+
images: tuple[Path, ...] = ()
|
|
286
|
+
|
|
287
|
+
def __post_init__(self) -> None:
|
|
288
|
+
_bounded_identifier(self.attempt_id, "attempt_id")
|
|
289
|
+
workspace = _isolated_workspace(self.workspace)
|
|
290
|
+
schema = _workspace_file(self.output_schema, workspace, "output_schema")
|
|
291
|
+
_load_output_schema(schema)
|
|
292
|
+
prompt_bytes = self.prompt.encode("utf-8")
|
|
293
|
+
if not self.prompt.strip() or len(prompt_bytes) > _MAX_PROMPT_BYTES:
|
|
294
|
+
raise ValueError("prompt must be non-empty and at most 1,000,000 UTF-8 bytes")
|
|
295
|
+
if not 0 < self.timeout_seconds <= 3600:
|
|
296
|
+
raise ValueError("timeout_seconds must be between zero and 3600")
|
|
297
|
+
self.image_identity()
|
|
298
|
+
|
|
299
|
+
def image_identity(self) -> list[dict[str, str]]:
|
|
300
|
+
if type(self.images) is not tuple or len(self.images) > 8:
|
|
301
|
+
raise ValueError("at most eight immutable image inputs are allowed")
|
|
302
|
+
identity = []
|
|
303
|
+
total = 0
|
|
304
|
+
for image in self.images:
|
|
305
|
+
path = _workspace_file(image, self.workspace.resolve(), "image")
|
|
306
|
+
info = path.stat()
|
|
307
|
+
total += info.st_size
|
|
308
|
+
if info.st_nlink != 1 or info.st_size > 2 * 1024**2 or total > 8 * 1024**2:
|
|
309
|
+
raise ValueError("image input exceeds bounds or is hardlinked")
|
|
310
|
+
with path.open("rb") as source:
|
|
311
|
+
if source.read(8) != b"\x89PNG\r\n\x1a\n":
|
|
312
|
+
raise ValueError("image input must be a PNG snapshot")
|
|
313
|
+
identity.append({"name": str(path.relative_to(self.workspace.resolve())),
|
|
314
|
+
"sha256": sha256_file(path, 2 * 1024**2)})
|
|
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(json.dumps({"prompt": self.prompt, "images": self.image_identity()},
|
|
321
|
+
sort_keys=True).encode("utf-8"))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@dataclass(frozen=True)
|
|
325
|
+
class CodexAttemptResult:
|
|
326
|
+
attempt_id: str
|
|
327
|
+
payload: dict[str, object]
|
|
328
|
+
event_types: tuple[str, ...]
|
|
329
|
+
elapsed_seconds: float | None
|
|
330
|
+
usage: ProviderUsage | None = None
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
@dataclass(frozen=True)
|
|
334
|
+
class CodexReconciliation:
|
|
335
|
+
attempt_id: str
|
|
336
|
+
state: ProviderAttemptState
|
|
337
|
+
result: CodexAttemptResult | None
|
|
338
|
+
reason: str
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
class CodexExecAdapter:
|
|
342
|
+
"""Run one ephemeral Codex attempt without loading project configuration."""
|
|
343
|
+
|
|
344
|
+
provider_id = "codex"
|
|
345
|
+
display_name = "Codex"
|
|
346
|
+
|
|
347
|
+
def __init__(
|
|
348
|
+
self,
|
|
349
|
+
attempt_root: Path,
|
|
350
|
+
binary: str | Path | None = None,
|
|
351
|
+
environment: Mapping[str, str] | None = None,
|
|
352
|
+
) -> None:
|
|
353
|
+
self._attempt_root = _isolated_workspace(attempt_root)
|
|
354
|
+
selected = str(binary) if binary is not None else shutil.which("codex")
|
|
355
|
+
if not selected:
|
|
356
|
+
raise ProviderUnavailable("Codex CLI is not installed or not on PATH")
|
|
357
|
+
candidate = Path(selected)
|
|
358
|
+
if candidate.is_symlink():
|
|
359
|
+
candidate = candidate.resolve(strict=True)
|
|
360
|
+
else:
|
|
361
|
+
candidate = candidate.resolve(strict=True)
|
|
362
|
+
if not candidate.is_file() or not os.access(candidate, os.X_OK):
|
|
363
|
+
raise ProviderUnavailable("Codex CLI is not an executable regular file")
|
|
364
|
+
self._binary = candidate
|
|
365
|
+
self._environment = _provider_environment(environment)
|
|
366
|
+
|
|
367
|
+
@property
|
|
368
|
+
def binary(self) -> Path:
|
|
369
|
+
return self._binary
|
|
370
|
+
|
|
371
|
+
def version(self) -> str:
|
|
372
|
+
completed = self._probe_command("--version")
|
|
373
|
+
if completed.returncode != 0:
|
|
374
|
+
raise ProviderUnavailable("Codex CLI version probe failed")
|
|
375
|
+
version = _decode_capture(completed.stdout, "version output", 256).strip()
|
|
376
|
+
if not version or len(version) > 256:
|
|
377
|
+
raise ProviderProtocolError("Codex CLI returned an invalid version string")
|
|
378
|
+
return version
|
|
379
|
+
|
|
380
|
+
def capabilities(self) -> CodexCapabilities:
|
|
381
|
+
exec_help = self._probe_command("exec", "--help")
|
|
382
|
+
sandbox_help = self._probe_command("sandbox", "--help")
|
|
383
|
+
if exec_help.returncode != 0 or sandbox_help.returncode != 0:
|
|
384
|
+
raise ProviderUnavailable("Codex CLI capability probe failed")
|
|
385
|
+
help_text = _decode_capture(exec_help.stdout, "exec help")
|
|
386
|
+
sandbox_help_text = _decode_capture(sandbox_help.stdout, "sandbox help")
|
|
387
|
+
return CodexCapabilities(
|
|
388
|
+
ephemeral_sessions="--ephemeral" in help_text,
|
|
389
|
+
isolated_user_config="--ignore-user-config" in help_text,
|
|
390
|
+
isolated_rules="--ignore-rules" in help_text,
|
|
391
|
+
granular_permissions=(
|
|
392
|
+
"--config" in help_text
|
|
393
|
+
and "--strict-config" in help_text
|
|
394
|
+
and "--permission-profile" in sandbox_help_text
|
|
395
|
+
),
|
|
396
|
+
json_events="--json" in help_text,
|
|
397
|
+
output_schema="--output-schema" in help_text,
|
|
398
|
+
output_file="--output-last-message" in help_text,
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
def probe(self) -> CodexProbeResult:
|
|
402
|
+
"""Check the local CLI, auth, and contract without contacting a model."""
|
|
403
|
+
|
|
404
|
+
version = self.version()
|
|
405
|
+
capabilities = self.capabilities()
|
|
406
|
+
login = self._probe_command("login", "status")
|
|
407
|
+
confinement_verified = False
|
|
408
|
+
if login.returncode == 0 and capabilities.granular_permissions:
|
|
409
|
+
confinement_verified = self._verify_confinement()
|
|
410
|
+
return CodexProbeResult(
|
|
411
|
+
version=version,
|
|
412
|
+
authenticated=login.returncode == 0,
|
|
413
|
+
capabilities=capabilities,
|
|
414
|
+
confinement_verified=confinement_verified,
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
def _verify_confinement(self) -> bool:
|
|
418
|
+
"""Run a model-free canary under the exact filesystem permission profile."""
|
|
419
|
+
|
|
420
|
+
try:
|
|
421
|
+
with (
|
|
422
|
+
tempfile.TemporaryDirectory(prefix=".permission-probe-", dir=self._attempt_root)
|
|
423
|
+
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(
|
|
533
|
+
"Codex attempt already has a receipt; reconcile it instead of rerunning"
|
|
534
|
+
)
|
|
535
|
+
for artifact in (output_path, events_path, diagnostics_path):
|
|
536
|
+
if artifact.exists() or artifact.is_symlink():
|
|
537
|
+
raise ProviderProtocolError("Codex attempt artifact already exists")
|
|
538
|
+
prompt_hash = attempt.input_hash()
|
|
539
|
+
schema_hash = sha256_file(attempt.output_schema, _MAX_SCHEMA_BYTES)
|
|
540
|
+
receipt = ProviderAttemptReceipt(
|
|
541
|
+
attempt_id=attempt.attempt_id,
|
|
542
|
+
state=ProviderAttemptState.PREPARED,
|
|
543
|
+
prompt_sha256=prompt_hash,
|
|
544
|
+
schema_sha256=schema_hash,
|
|
545
|
+
)
|
|
546
|
+
store.write(receipt)
|
|
547
|
+
|
|
548
|
+
def record_started(pid: int) -> None:
|
|
549
|
+
nonlocal receipt
|
|
550
|
+
receipt = replace(
|
|
551
|
+
receipt,
|
|
552
|
+
state=ProviderAttemptState.RUNNING,
|
|
553
|
+
started_at=utc_now(),
|
|
554
|
+
pid=pid,
|
|
555
|
+
)
|
|
556
|
+
store.write(receipt)
|
|
557
|
+
|
|
558
|
+
command = self.command(attempt, output_path)
|
|
559
|
+
started = time.monotonic()
|
|
560
|
+
returncode: int | None = None
|
|
561
|
+
try:
|
|
562
|
+
stdout, stderr, returncode = self._run_bounded(
|
|
563
|
+
command,
|
|
564
|
+
attempt,
|
|
565
|
+
workspace,
|
|
566
|
+
cancel_token,
|
|
567
|
+
events_path,
|
|
568
|
+
diagnostics_path,
|
|
569
|
+
record_started,
|
|
570
|
+
)
|
|
571
|
+
self._sanitize_persisted_artifacts(
|
|
572
|
+
events_path, diagnostics_path, attempt.prompt
|
|
573
|
+
)
|
|
574
|
+
stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
|
|
575
|
+
stderr = self._read_artifact(diagnostics_path, _MAX_CAPTURE_BYTES)
|
|
576
|
+
self._raise_for_failed_turn(stdout)
|
|
577
|
+
if returncode != 0:
|
|
578
|
+
self._raise_for_exit(returncode, stderr)
|
|
579
|
+
result = self._validated_result(attempt, output_path, stdout)
|
|
580
|
+
if attempt.input_hash() != prompt_hash:
|
|
581
|
+
raise ProviderProtocolError("approved image snapshots changed during the attempt")
|
|
582
|
+
receipt = replace(
|
|
583
|
+
receipt,
|
|
584
|
+
state=ProviderAttemptState.SUCCEEDED,
|
|
585
|
+
finished_at=utc_now(),
|
|
586
|
+
return_code=returncode,
|
|
587
|
+
output_sha256=sha256_file(output_path, _MAX_RESULT_BYTES),
|
|
588
|
+
events_sha256=sha256_file(events_path, _MAX_CAPTURE_BYTES),
|
|
589
|
+
diagnostics_sha256=sha256_file(
|
|
590
|
+
diagnostics_path, _MAX_CAPTURE_BYTES
|
|
591
|
+
),
|
|
592
|
+
usage=result.usage,
|
|
593
|
+
)
|
|
594
|
+
store.write(receipt)
|
|
595
|
+
return replace(result, elapsed_seconds=time.monotonic() - started)
|
|
596
|
+
except Exception as error:
|
|
597
|
+
self._sanitize_persisted_artifacts(
|
|
598
|
+
events_path, diagnostics_path, attempt.prompt
|
|
599
|
+
)
|
|
600
|
+
state, error_code = self._failure_receipt(error)
|
|
601
|
+
receipt = replace(
|
|
602
|
+
receipt,
|
|
603
|
+
state=state,
|
|
604
|
+
finished_at=utc_now(),
|
|
605
|
+
return_code=returncode,
|
|
606
|
+
output_sha256=self._optional_artifact_hash(
|
|
607
|
+
output_path, _MAX_RESULT_BYTES
|
|
608
|
+
),
|
|
609
|
+
events_sha256=self._optional_artifact_hash(
|
|
610
|
+
events_path, _MAX_CAPTURE_BYTES
|
|
611
|
+
),
|
|
612
|
+
diagnostics_sha256=self._optional_artifact_hash(
|
|
613
|
+
diagnostics_path, _MAX_CAPTURE_BYTES
|
|
614
|
+
),
|
|
615
|
+
usage=self._optional_usage(events_path),
|
|
616
|
+
error_code=error_code,
|
|
617
|
+
)
|
|
618
|
+
try:
|
|
619
|
+
store.write(receipt)
|
|
620
|
+
except AttemptReceiptError as receipt_error:
|
|
621
|
+
raise ProviderProtocolError(
|
|
622
|
+
"Codex attempt failed and its terminal receipt could not be saved"
|
|
623
|
+
) from receipt_error
|
|
624
|
+
raise
|
|
625
|
+
|
|
626
|
+
def reconcile(self, attempt: CodexAttempt) -> CodexReconciliation:
|
|
627
|
+
workspace = _isolated_workspace(attempt.workspace)
|
|
628
|
+
store = AttemptReceiptStore(workspace, attempt.attempt_id)
|
|
629
|
+
try:
|
|
630
|
+
receipt = store.read()
|
|
631
|
+
except AttemptReceiptError:
|
|
632
|
+
return CodexReconciliation(
|
|
633
|
+
attempt.attempt_id,
|
|
634
|
+
ProviderAttemptState.UNKNOWN,
|
|
635
|
+
None,
|
|
636
|
+
"receipt_unavailable",
|
|
637
|
+
)
|
|
638
|
+
try:
|
|
639
|
+
if (
|
|
640
|
+
receipt.attempt_id != attempt.attempt_id
|
|
641
|
+
or receipt.prompt_sha256
|
|
642
|
+
!= attempt.input_hash()
|
|
643
|
+
or receipt.schema_sha256
|
|
644
|
+
!= sha256_file(attempt.output_schema, _MAX_SCHEMA_BYTES)
|
|
645
|
+
):
|
|
646
|
+
raise AttemptReceiptError("attempt identity does not match its receipt")
|
|
647
|
+
output_path = workspace / f"provider-output-{attempt.attempt_id}.json"
|
|
648
|
+
events_path = workspace / f"provider-events-{attempt.attempt_id}.jsonl"
|
|
649
|
+
if receipt.state in {
|
|
650
|
+
ProviderAttemptState.SUCCEEDED,
|
|
651
|
+
ProviderAttemptState.RUNNING,
|
|
652
|
+
}:
|
|
653
|
+
stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
|
|
654
|
+
result = self._validated_result(attempt, output_path, stdout)
|
|
655
|
+
output_hash = sha256_file(output_path, _MAX_RESULT_BYTES)
|
|
656
|
+
events_hash = sha256_file(events_path, _MAX_CAPTURE_BYTES)
|
|
657
|
+
if receipt.state is ProviderAttemptState.SUCCEEDED:
|
|
658
|
+
if (
|
|
659
|
+
receipt.output_sha256 != output_hash
|
|
660
|
+
or receipt.events_sha256 != events_hash
|
|
661
|
+
):
|
|
662
|
+
raise AttemptReceiptError("terminal provider artifacts changed")
|
|
663
|
+
self._verify_recorded_hash(
|
|
664
|
+
workspace
|
|
665
|
+
/ f"provider-diagnostics-{attempt.attempt_id}.log",
|
|
666
|
+
receipt.diagnostics_sha256,
|
|
667
|
+
_MAX_CAPTURE_BYTES,
|
|
668
|
+
)
|
|
669
|
+
else:
|
|
670
|
+
diagnostics_path = workspace / (
|
|
671
|
+
f"provider-diagnostics-{attempt.attempt_id}.log"
|
|
672
|
+
)
|
|
673
|
+
receipt = replace(
|
|
674
|
+
receipt,
|
|
675
|
+
state=ProviderAttemptState.SUCCEEDED,
|
|
676
|
+
finished_at=utc_now(),
|
|
677
|
+
return_code=0,
|
|
678
|
+
output_sha256=output_hash,
|
|
679
|
+
events_sha256=events_hash,
|
|
680
|
+
diagnostics_sha256=self._optional_artifact_hash(
|
|
681
|
+
diagnostics_path, _MAX_CAPTURE_BYTES
|
|
682
|
+
),
|
|
683
|
+
usage=result.usage,
|
|
684
|
+
error_code=None,
|
|
685
|
+
)
|
|
686
|
+
store.write(receipt)
|
|
687
|
+
return CodexReconciliation(
|
|
688
|
+
attempt.attempt_id,
|
|
689
|
+
ProviderAttemptState.SUCCEEDED,
|
|
690
|
+
result,
|
|
691
|
+
"terminal_artifacts_verified",
|
|
692
|
+
)
|
|
693
|
+
if receipt.state is ProviderAttemptState.PREPARED:
|
|
694
|
+
interrupted = replace(
|
|
695
|
+
receipt,
|
|
696
|
+
state=ProviderAttemptState.INTERRUPTED,
|
|
697
|
+
finished_at=utc_now(),
|
|
698
|
+
error_code="launch_interrupted",
|
|
699
|
+
)
|
|
700
|
+
store.write(interrupted)
|
|
701
|
+
return CodexReconciliation(
|
|
702
|
+
attempt.attempt_id,
|
|
703
|
+
ProviderAttemptState.INTERRUPTED,
|
|
704
|
+
None,
|
|
705
|
+
"launch_interrupted",
|
|
706
|
+
)
|
|
707
|
+
self._verify_recorded_hash(
|
|
708
|
+
workspace / f"provider-output-{attempt.attempt_id}.json",
|
|
709
|
+
receipt.output_sha256,
|
|
710
|
+
_MAX_RESULT_BYTES,
|
|
711
|
+
)
|
|
712
|
+
self._verify_recorded_hash(
|
|
713
|
+
workspace / f"provider-events-{attempt.attempt_id}.jsonl",
|
|
714
|
+
receipt.events_sha256,
|
|
715
|
+
_MAX_CAPTURE_BYTES,
|
|
716
|
+
)
|
|
717
|
+
self._verify_recorded_hash(
|
|
718
|
+
workspace / f"provider-diagnostics-{attempt.attempt_id}.log",
|
|
719
|
+
receipt.diagnostics_sha256,
|
|
720
|
+
_MAX_CAPTURE_BYTES,
|
|
721
|
+
)
|
|
722
|
+
return CodexReconciliation(
|
|
723
|
+
attempt.attempt_id,
|
|
724
|
+
receipt.state,
|
|
725
|
+
None,
|
|
726
|
+
receipt.error_code or "terminal_receipt_verified",
|
|
727
|
+
)
|
|
728
|
+
except (AttemptReceiptError, OSError, ValueError, ProviderProtocolError):
|
|
729
|
+
return CodexReconciliation(
|
|
730
|
+
attempt.attempt_id,
|
|
731
|
+
ProviderAttemptState.UNKNOWN,
|
|
732
|
+
None,
|
|
733
|
+
"terminal_state_unverified",
|
|
734
|
+
)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _validated_result(
|
|
738
|
+
self, attempt: CodexAttempt, output_path: Path, stdout: bytes
|
|
739
|
+
) -> CodexAttemptResult:
|
|
740
|
+
if not output_path.is_file() or output_path.is_symlink():
|
|
741
|
+
raise ProviderProtocolError("Codex did not create the expected result file")
|
|
742
|
+
if output_path.stat().st_size > _MAX_RESULT_BYTES:
|
|
743
|
+
raise ProviderProtocolError("Codex result exceeded the size limit")
|
|
744
|
+
try:
|
|
745
|
+
payload = json.loads(output_path.read_text(encoding="utf-8"))
|
|
746
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
747
|
+
raise ProviderProtocolError("Codex result was not valid UTF-8 JSON") from error
|
|
748
|
+
if not isinstance(payload, dict):
|
|
749
|
+
raise ProviderProtocolError("Codex result must be a JSON object")
|
|
750
|
+
schema = _load_output_schema(
|
|
751
|
+
_workspace_file(
|
|
752
|
+
attempt.output_schema,
|
|
753
|
+
_isolated_workspace(attempt.workspace),
|
|
754
|
+
"output_schema",
|
|
755
|
+
)
|
|
756
|
+
)
|
|
757
|
+
try:
|
|
758
|
+
Draft202012Validator(schema).validate(payload)
|
|
759
|
+
except ValidationError as error:
|
|
760
|
+
raise ProviderProtocolError("Codex result did not match the output schema") from error
|
|
761
|
+
event_types, usage = self._events_and_usage(stdout)
|
|
762
|
+
if "turn.completed" not in event_types:
|
|
763
|
+
raise ProviderProtocolError("Codex event stream did not report a completed turn")
|
|
764
|
+
return CodexAttemptResult(
|
|
765
|
+
attempt_id=attempt.attempt_id,
|
|
766
|
+
payload=payload,
|
|
767
|
+
event_types=event_types,
|
|
768
|
+
elapsed_seconds=None,
|
|
769
|
+
usage=usage,
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
@staticmethod
|
|
773
|
+
def _raise_for_failed_turn(stdout: bytes, *, limit: int = _MAX_CAPTURE_BYTES) -> None:
|
|
774
|
+
"""CLI failures can be reported only in JSONL while stderr stays empty."""
|
|
775
|
+
events=[]
|
|
776
|
+
for line in _decode_capture(stdout,'JSONL stream',limit).splitlines():
|
|
777
|
+
try:event=json.loads(line)
|
|
778
|
+
except json.JSONDecodeError:continue # Normal protocol validation follows.
|
|
779
|
+
if isinstance(event,dict):events.append(event)
|
|
780
|
+
terminal=next((e for e in reversed(events) if e.get('type') in {'turn.completed','turn.failed'}),None)
|
|
781
|
+
if terminal is not None and terminal.get('type')=='turn.completed':return
|
|
782
|
+
messages=[]
|
|
783
|
+
for event in events:
|
|
784
|
+
if event.get('type') not in {'error','turn.failed'}:continue
|
|
785
|
+
detail=event.get('error',event)
|
|
786
|
+
message=detail.get('message') if isinstance(detail,dict) else detail
|
|
787
|
+
if isinstance(message,str):messages.append(message)
|
|
788
|
+
if messages:
|
|
789
|
+
CodexExecAdapter._raise_for_exit(1,'\n'.join(messages).encode('utf-8'))
|
|
790
|
+
if terminal is not None:
|
|
791
|
+
raise ProviderProtocolError('Codex reported a failed turn without a diagnostic')
|
|
792
|
+
|
|
793
|
+
@staticmethod
|
|
794
|
+
def _raise_for_exit(returncode: int, stderr: bytes) -> None:
|
|
795
|
+
diagnostic = _decode_capture(stderr, "stderr").lower()
|
|
796
|
+
if any(marker in diagnostic for marker in ("not logged in", "unauthorized", "login required")):
|
|
797
|
+
raise ProviderAuthenticationError("Codex login is missing or no longer valid")
|
|
798
|
+
if any(marker in diagnostic for marker in ("usage limit", "rate limit", "quota", "credits")):
|
|
799
|
+
raise ProviderUsageLimitError("Codex account usage limit prevented this attempt")
|
|
800
|
+
if any(
|
|
801
|
+
marker in diagnostic
|
|
802
|
+
for marker in ("connection failed", "network is unreachable", "could not resolve host")
|
|
803
|
+
):
|
|
804
|
+
raise ProviderNetworkError("Codex could not reach its service")
|
|
805
|
+
if any(marker in diagnostic for marker in ("sandbox", "operation not permitted", "permission")):
|
|
806
|
+
raise ProviderPermissionError("Codex permission confinement failed")
|
|
807
|
+
raise ProviderProtocolError(f"Codex attempt exited with code {returncode}")
|
|
808
|
+
|
|
809
|
+
def _stdin_payload(self, attempt: CodexAttempt) -> bytes:
|
|
810
|
+
"""Codex reads the prompt from stdin and images from --image flags."""
|
|
811
|
+
return attempt.prompt.encode("utf-8")
|
|
812
|
+
|
|
813
|
+
def _run_bounded(
|
|
814
|
+
self,
|
|
815
|
+
command: tuple[str, ...],
|
|
816
|
+
attempt: CodexAttempt,
|
|
817
|
+
workspace: Path,
|
|
818
|
+
cancel_token: CancellationToken | None,
|
|
819
|
+
events_path: Path,
|
|
820
|
+
diagnostics_path: Path,
|
|
821
|
+
record_started,
|
|
822
|
+
) -> tuple[bytes, bytes, int]:
|
|
823
|
+
deadline = time.monotonic() + attempt.timeout_seconds
|
|
824
|
+
with tempfile.TemporaryFile() as prompt_stream:
|
|
825
|
+
prompt_stream.write(self._stdin_payload(attempt))
|
|
826
|
+
prompt_stream.seek(0)
|
|
827
|
+
stdout_descriptor = os.open(
|
|
828
|
+
events_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600
|
|
829
|
+
)
|
|
830
|
+
try:
|
|
831
|
+
stderr_descriptor = os.open(
|
|
832
|
+
diagnostics_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600
|
|
833
|
+
)
|
|
834
|
+
except Exception:
|
|
835
|
+
os.close(stdout_descriptor)
|
|
836
|
+
raise
|
|
837
|
+
with (
|
|
838
|
+
os.fdopen(stdout_descriptor, "wb") as stdout_stream,
|
|
839
|
+
os.fdopen(stderr_descriptor, "wb") as stderr_stream,
|
|
840
|
+
):
|
|
841
|
+
try:
|
|
842
|
+
process = subprocess.Popen(
|
|
843
|
+
command,
|
|
844
|
+
cwd=workspace,
|
|
845
|
+
env=self._environment,
|
|
846
|
+
stdin=prompt_stream,
|
|
847
|
+
stdout=stdout_stream,
|
|
848
|
+
stderr=stderr_stream,
|
|
849
|
+
start_new_session=os.name == "posix",
|
|
850
|
+
)
|
|
851
|
+
except OSError as error:
|
|
852
|
+
raise ProviderUnavailable("Codex CLI could not be launched") from error
|
|
853
|
+
record_started(process.pid)
|
|
854
|
+
|
|
855
|
+
while process.poll() is None:
|
|
856
|
+
if cancel_token is not None and cancel_token.is_set():
|
|
857
|
+
self._terminate(process)
|
|
858
|
+
raise ProviderCancelled(
|
|
859
|
+
f"Codex attempt {attempt.attempt_id} was cancelled"
|
|
860
|
+
)
|
|
861
|
+
if time.monotonic() >= deadline:
|
|
862
|
+
self._terminate(process)
|
|
863
|
+
raise ProviderTimedOut(
|
|
864
|
+
f"Codex attempt {attempt.attempt_id} exceeded its timeout"
|
|
865
|
+
)
|
|
866
|
+
if (
|
|
867
|
+
os.fstat(stdout_stream.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
868
|
+
or os.fstat(stderr_stream.fileno()).st_size > _MAX_CAPTURE_BYTES
|
|
869
|
+
):
|
|
870
|
+
self._terminate(process)
|
|
871
|
+
raise ProviderProtocolError(
|
|
872
|
+
"Codex diagnostic output exceeded the capture limit"
|
|
873
|
+
)
|
|
874
|
+
time.sleep(_POLL_INTERVAL_SECONDS)
|
|
875
|
+
|
|
876
|
+
stdout_stream.flush()
|
|
877
|
+
stderr_stream.flush()
|
|
878
|
+
stdout = self._read_artifact(events_path, _MAX_CAPTURE_BYTES)
|
|
879
|
+
stderr = self._read_artifact(diagnostics_path, _MAX_CAPTURE_BYTES)
|
|
880
|
+
return stdout, stderr, process.returncode
|
|
881
|
+
|
|
882
|
+
@staticmethod
|
|
883
|
+
def _events_and_usage(
|
|
884
|
+
stdout: bytes,
|
|
885
|
+
*, limit: int = _MAX_CAPTURE_BYTES,
|
|
886
|
+
) -> tuple[tuple[str, ...], ProviderUsage | None]:
|
|
887
|
+
event_types: list[str] = []
|
|
888
|
+
usage: ProviderUsage | None = None
|
|
889
|
+
lines = _decode_capture(stdout, "JSONL stream", limit).splitlines()
|
|
890
|
+
for line in lines:
|
|
891
|
+
if not line.strip():
|
|
892
|
+
continue
|
|
893
|
+
try:
|
|
894
|
+
event = json.loads(line)
|
|
895
|
+
except json.JSONDecodeError as error:
|
|
896
|
+
raise ProviderProtocolError("Codex JSONL stream contained invalid JSON") from error
|
|
897
|
+
if not isinstance(event, dict):
|
|
898
|
+
raise ProviderProtocolError("Codex JSONL events must be objects")
|
|
899
|
+
event_type = event.get("type")
|
|
900
|
+
if isinstance(event_type, str) and event_type:
|
|
901
|
+
event_types.append(event_type)
|
|
902
|
+
candidate_usage = event.get("usage")
|
|
903
|
+
if event_type in {"turn.completed", "turn.failed"} and isinstance(
|
|
904
|
+
candidate_usage, dict
|
|
905
|
+
):
|
|
906
|
+
try:
|
|
907
|
+
usage = ProviderUsage(
|
|
908
|
+
input_tokens=candidate_usage["input_tokens"],
|
|
909
|
+
cached_input_tokens=candidate_usage.get(
|
|
910
|
+
"cached_input_tokens", 0
|
|
911
|
+
),
|
|
912
|
+
output_tokens=candidate_usage["output_tokens"],
|
|
913
|
+
)
|
|
914
|
+
except (KeyError, TypeError, ValueError) as error:
|
|
915
|
+
raise ProviderProtocolError(
|
|
916
|
+
"Codex usage data was malformed"
|
|
917
|
+
) from error
|
|
918
|
+
return tuple(event_types), usage
|
|
919
|
+
|
|
920
|
+
@classmethod
|
|
921
|
+
def _optional_usage(cls, path: Path) -> ProviderUsage | None:
|
|
922
|
+
try:
|
|
923
|
+
_, usage = cls._events_and_usage(
|
|
924
|
+
cls._read_artifact(path, _MAX_CAPTURE_BYTES)
|
|
925
|
+
)
|
|
926
|
+
return usage
|
|
927
|
+
except (OSError, ProviderProtocolError):
|
|
928
|
+
return None
|
|
929
|
+
|
|
930
|
+
@staticmethod
|
|
931
|
+
def _read_artifact(path: Path, limit: int) -> bytes:
|
|
932
|
+
if path.is_symlink() or not path.is_file() or path.stat().st_size > limit:
|
|
933
|
+
raise ProviderProtocolError("Codex attempt artifact is missing or oversized")
|
|
934
|
+
value = path.read_bytes()
|
|
935
|
+
if len(value) > limit:
|
|
936
|
+
raise ProviderProtocolError("Codex attempt artifact exceeded its size limit")
|
|
937
|
+
return value
|
|
938
|
+
|
|
939
|
+
@staticmethod
|
|
940
|
+
def _optional_artifact_hash(path: Path, limit: int) -> str | None:
|
|
941
|
+
try:
|
|
942
|
+
return sha256_file(path, limit)
|
|
943
|
+
except (AttemptReceiptError, OSError):
|
|
944
|
+
return None
|
|
945
|
+
|
|
946
|
+
@staticmethod
|
|
947
|
+
def _sanitize_persisted_artifacts(
|
|
948
|
+
events_path: Path, diagnostics_path: Path, prompt: str
|
|
949
|
+
) -> None:
|
|
950
|
+
prompt_bytes = prompt.encode("utf-8")
|
|
951
|
+
for path in (events_path, diagnostics_path):
|
|
952
|
+
if path.is_symlink() or not path.is_file():
|
|
953
|
+
continue
|
|
954
|
+
try:
|
|
955
|
+
value = path.read_bytes()
|
|
956
|
+
except OSError:
|
|
957
|
+
continue
|
|
958
|
+
sanitized = value.replace(prompt_bytes, b"[REDACTED_PROMPT]")
|
|
959
|
+
for pattern in _SECRET_PATTERNS:
|
|
960
|
+
if pattern.groups:
|
|
961
|
+
sanitized = pattern.sub(rb"\1[REDACTED_SECRET]", sanitized)
|
|
962
|
+
else:
|
|
963
|
+
sanitized = pattern.sub(b"[REDACTED_SECRET]", sanitized)
|
|
964
|
+
if sanitized == value:
|
|
965
|
+
continue
|
|
966
|
+
temporary = path.with_name(f".{path.name}.redacted-{uuid.uuid4().hex}")
|
|
967
|
+
descriptor = os.open(
|
|
968
|
+
temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600
|
|
969
|
+
)
|
|
970
|
+
try:
|
|
971
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
972
|
+
stream.write(sanitized)
|
|
973
|
+
stream.flush()
|
|
974
|
+
os.fsync(stream.fileno())
|
|
975
|
+
os.replace(temporary, path)
|
|
976
|
+
os.chmod(path, 0o600)
|
|
977
|
+
finally:
|
|
978
|
+
if temporary.exists() and not temporary.is_symlink():
|
|
979
|
+
temporary.unlink()
|
|
980
|
+
|
|
981
|
+
@staticmethod
|
|
982
|
+
def _verify_recorded_hash(
|
|
983
|
+
path: Path, expected: str | None, limit: int
|
|
984
|
+
) -> None:
|
|
985
|
+
if expected is None:
|
|
986
|
+
return
|
|
987
|
+
if sha256_file(path, limit) != expected:
|
|
988
|
+
raise AttemptReceiptError("provider artifact changed after receipt")
|
|
989
|
+
|
|
990
|
+
@staticmethod
|
|
991
|
+
def _failure_receipt(
|
|
992
|
+
error: Exception,
|
|
993
|
+
) -> tuple[ProviderAttemptState, str]:
|
|
994
|
+
if isinstance(error, ProviderCancelled):
|
|
995
|
+
return ProviderAttemptState.CANCELLED, "cancelled"
|
|
996
|
+
if isinstance(error, ProviderTimedOut):
|
|
997
|
+
return ProviderAttemptState.TIMED_OUT, "timed_out"
|
|
998
|
+
if isinstance(error, ProviderAuthenticationError):
|
|
999
|
+
return ProviderAttemptState.FAILED, "authentication"
|
|
1000
|
+
if isinstance(error, ProviderUsageLimitError):
|
|
1001
|
+
return ProviderAttemptState.FAILED, "usage_limit"
|
|
1002
|
+
if isinstance(error, ProviderNetworkError):
|
|
1003
|
+
return ProviderAttemptState.FAILED, "network"
|
|
1004
|
+
if isinstance(error, ProviderPermissionError):
|
|
1005
|
+
return ProviderAttemptState.FAILED, "permission"
|
|
1006
|
+
if isinstance(error, ProviderUnavailable):
|
|
1007
|
+
return ProviderAttemptState.FAILED, "unavailable"
|
|
1008
|
+
return ProviderAttemptState.FAILED, "protocol"
|
|
1009
|
+
|
|
1010
|
+
@staticmethod
|
|
1011
|
+
def _terminate(process: subprocess.Popen[bytes]) -> None:
|
|
1012
|
+
if process.poll() is not None:
|
|
1013
|
+
return
|
|
1014
|
+
if os.name == "posix":
|
|
1015
|
+
try:
|
|
1016
|
+
os.killpg(process.pid, signal.SIGTERM)
|
|
1017
|
+
except ProcessLookupError:
|
|
1018
|
+
process.wait(timeout=2)
|
|
1019
|
+
return
|
|
1020
|
+
except PermissionError:
|
|
1021
|
+
process.terminate()
|
|
1022
|
+
else:
|
|
1023
|
+
process.terminate()
|
|
1024
|
+
try:
|
|
1025
|
+
process.wait(timeout=2)
|
|
1026
|
+
except subprocess.TimeoutExpired:
|
|
1027
|
+
if os.name == "posix":
|
|
1028
|
+
try:
|
|
1029
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
1030
|
+
except ProcessLookupError:
|
|
1031
|
+
pass
|
|
1032
|
+
except PermissionError:
|
|
1033
|
+
process.kill()
|
|
1034
|
+
else:
|
|
1035
|
+
process.kill()
|
|
1036
|
+
process.wait(timeout=2)
|