@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.
- package/LICENSE +21 -0
- package/README.md +89 -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 +55 -4
- package/pyproject.toml +44 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/dev.txt +2 -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 +410 -0
- package/src/clipen/analysis/audio.py +394 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +929 -0
- package/src/clipen/analysis/image_similarity.py +134 -0
- package/src/clipen/analysis/keyframes.py +159 -0
- package/src/clipen/analysis/models.py +228 -0
- package/src/clipen/analysis/qwen_worker.py +594 -0
- package/src/clipen/analysis/resources.py +22 -0
- package/src/clipen/analysis/runtime.py +62 -0
- package/src/clipen/analysis/service.py +594 -0
- package/src/clipen/analysis/setup.py +921 -0
- package/src/clipen/analysis/setup_cli.py +107 -0
- package/src/clipen/analysis/storage.py +1864 -0
- package/src/clipen/analysis/transcription.py +906 -0
- package/src/clipen/analysis/visual.py +237 -0
- package/src/clipen/annotations/__init__.py +13 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +428 -0
- package/src/clipen/annotations/suggestions.py +115 -0
- package/src/clipen/asr_release.py +132 -0
- package/src/clipen/bootstrap.py +978 -0
- package/src/clipen/candidates.py +222 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1657 -0
- package/src/clipen/controller/server.py +533 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +110 -0
- package/src/clipen/domain/timeline.py +582 -0
- package/src/clipen/domain/validation.py +14 -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 +127 -0
- package/src/clipen/editing/agent_repository.py +978 -0
- package/src/clipen/editing/agent_tools.py +613 -0
- package/src/clipen/editing/alignment.py +150 -0
- package/src/clipen/editing/alignment_setup.py +156 -0
- package/src/clipen/editing/alignment_worker.py +24 -0
- package/src/clipen/editing/change_report.py +128 -0
- package/src/clipen/editing/compiler.py +40 -0
- package/src/clipen/editing/component_looks.py +131 -0
- package/src/clipen/editing/component_review.py +74 -0
- package/src/clipen/editing/coordinator.py +497 -0
- package/src/clipen/editing/editorial_review.py +309 -0
- package/src/clipen/editing/evidence_jobs.py +552 -0
- package/src/clipen/editing/history_changes.py +192 -0
- package/src/clipen/editing/music_choices.py +18 -0
- package/src/clipen/editing/production_catalog.py +629 -0
- package/src/clipen/editing/production_limits.py +85 -0
- package/src/clipen/editing/production_media.py +435 -0
- package/src/clipen/editing/production_preview.py +373 -0
- package/src/clipen/editing/production_progress.py +236 -0
- package/src/clipen/editing/production_requirements.py +117 -0
- package/src/clipen/editing/production_tools.py +1198 -0
- package/src/clipen/editing/program_audio.py +248 -0
- package/src/clipen/editing/program_direction.py +83 -0
- package/src/clipen/editing/program_story.py +91 -0
- package/src/clipen/editing/program_subtitles.py +232 -0
- package/src/clipen/editing/programme_review.py +121 -0
- package/src/clipen/editing/prompt_history.py +84 -0
- package/src/clipen/editing/recut.py +167 -0
- package/src/clipen/editing/refinement_references.py +278 -0
- package/src/clipen/editing/resolve_export.py +847 -0
- package/src/clipen/editing/resolve_titles.py +291 -0
- package/src/clipen/editing/skill_tools.py +951 -0
- package/src/clipen/editing/source_dialogue.py +192 -0
- package/src/clipen/editing/speech_coverage.py +50 -0
- package/src/clipen/editing/speech_quality.py +11 -0
- package/src/clipen/editing/tool_receipts.py +98 -0
- package/src/clipen/editing/versions.py +219 -0
- package/src/clipen/editing/visual_preview.py +189 -0
- package/src/clipen/editing/workbench.py +136 -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 +188 -0
- package/src/clipen/finishing/catalog.py +264 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +45 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +42 -0
- package/src/clipen/mcp_editing/server.py +396 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +253 -0
- package/src/clipen/media/models.py +349 -0
- package/src/clipen/media/preview.py +137 -0
- package/src/clipen/media/probe.py +418 -0
- package/src/clipen/media/service.py +304 -0
- package/src/clipen/media/storage.py +694 -0
- package/src/clipen/music_vocabulary.py +34 -0
- package/src/clipen/power.py +28 -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 +256 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +36 -0
- package/src/clipen/projects/models.py +189 -0
- package/src/clipen/projects/picker.py +232 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +159 -0
- package/src/clipen/projects/storage.py +1458 -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 +77 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +245 -0
- package/src/clipen/providers/claude.py +409 -0
- package/src/clipen/providers/claude_editing.py +118 -0
- package/src/clipen/providers/codex.py +991 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +567 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +269 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +139 -0
- package/src/clipen/rendering/custom_components.py +328 -0
- package/src/clipen/rendering/custom_render.py +218 -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 +96 -0
- package/src/clipen/rendering/program_components.py +254 -0
- package/src/clipen/rendering/program_creator.py +804 -0
- package/src/clipen/rendering/program_identities.py +350 -0
- package/src/clipen/rendering/program_motion.py +186 -0
- package/src/clipen/rendering/program_studio.py +227 -0
- package/src/clipen/rendering/program_styles.py +321 -0
- package/src/clipen/rendering/program_subtitles.py +89 -0
- package/src/clipen/rendering/renderer.py +737 -0
- package/src/clipen/rendering/storage.py +230 -0
- package/src/clipen/rendering/titles.py +467 -0
- package/src/clipen/skills/__init__.py +5 -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 +314 -0
- package/src/clipen/skills/library.py +137 -0
- package/src/clipen/skills/package.py +254 -0
- package/src/clipen/skills/visual_styles.py +55 -0
- package/src/clipen/workspace.py +181 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Model-free checks and process environment for the Claude Code CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Mapping
|
|
14
|
+
|
|
15
|
+
from jsonschema import Draft202012Validator
|
|
16
|
+
from jsonschema.exceptions import ValidationError
|
|
17
|
+
|
|
18
|
+
from .codex import (
|
|
19
|
+
_MAX_CAPTURE_BYTES,
|
|
20
|
+
_MAX_RESULT_BYTES,
|
|
21
|
+
CodexAttempt,
|
|
22
|
+
CodexAttemptResult,
|
|
23
|
+
CodexExecAdapter,
|
|
24
|
+
_decode_capture,
|
|
25
|
+
_inside,
|
|
26
|
+
_isolated_workspace,
|
|
27
|
+
_load_output_schema,
|
|
28
|
+
_provider_environment,
|
|
29
|
+
_workspace_file,
|
|
30
|
+
)
|
|
31
|
+
from .errors import (
|
|
32
|
+
ProviderAuthenticationError,
|
|
33
|
+
ProviderNetworkError,
|
|
34
|
+
ProviderPermissionError,
|
|
35
|
+
ProviderProtocolError,
|
|
36
|
+
ProviderUnavailable,
|
|
37
|
+
ProviderUsageLimitError,
|
|
38
|
+
)
|
|
39
|
+
from .recovery import ProviderUsage
|
|
40
|
+
|
|
41
|
+
# Flags the bounded editing attempt depends on; an older CLI without them
|
|
42
|
+
# could load user tools or settings, so it is reported as unsupported.
|
|
43
|
+
REQUIRED_FLAGS = (
|
|
44
|
+
"--print",
|
|
45
|
+
"--input-format",
|
|
46
|
+
"--output-format",
|
|
47
|
+
"--json-schema",
|
|
48
|
+
"--safe-mode",
|
|
49
|
+
"--mcp-config",
|
|
50
|
+
"--strict-mcp-config",
|
|
51
|
+
"--tools",
|
|
52
|
+
"--allowedTools",
|
|
53
|
+
"--permission-mode",
|
|
54
|
+
"--no-session-persistence",
|
|
55
|
+
"--setting-sources",
|
|
56
|
+
)
|
|
57
|
+
_PROBE_TIMEOUT_SECONDS = 20
|
|
58
|
+
_CLAUDE_ENVIRONMENT = frozenset({"ANTHROPIC_API_KEY", "CLAUDE_CONFIG_DIR"})
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# Clipen excludes user settings so they cannot add tools, hooks or rules. Only
|
|
62
|
+
# the chosen model and effort carry over, like Codex's model and effort.
|
|
63
|
+
_CLAUDE_EFFORTS = frozenset({"low", "medium", "high", "xhigh", "max"})
|
|
64
|
+
_CLAUDE_MODEL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,79}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def claude_preferences(environment: Mapping[str, str] | None = None) -> tuple[str | None, str | None]:
|
|
68
|
+
"""The `model` and `effortLevel` from the user's Claude Code settings."""
|
|
69
|
+
source = os.environ if environment is None else environment
|
|
70
|
+
home = source.get("CLAUDE_CONFIG_DIR") or (str(Path(source["HOME"]) / ".claude") if source.get("HOME") else None)
|
|
71
|
+
if not home:
|
|
72
|
+
return None, None
|
|
73
|
+
path = Path(home) / "settings.json"
|
|
74
|
+
try:
|
|
75
|
+
if path.stat().st_size > 1024 * 1024:
|
|
76
|
+
return None, None
|
|
77
|
+
settings = json.loads(path.read_text(encoding="utf-8"))
|
|
78
|
+
except (OSError, ValueError):
|
|
79
|
+
return None, None
|
|
80
|
+
if not isinstance(settings, dict):
|
|
81
|
+
return None, None
|
|
82
|
+
model, effort = settings.get("model"), settings.get("effortLevel")
|
|
83
|
+
return (
|
|
84
|
+
model if isinstance(model, str) and _CLAUDE_MODEL.fullmatch(model) else None,
|
|
85
|
+
effort if effort in _CLAUDE_EFFORTS else None,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def model_arguments(environment: Mapping[str, str] | None = None) -> tuple[str, ...]:
|
|
90
|
+
model, effort = claude_preferences(environment)
|
|
91
|
+
return (*(("--model", model) if model else ()), *(("--effort", effort) if effort else ()))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def claude_environment(source: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
95
|
+
inherited = os.environ if source is None else source
|
|
96
|
+
environment = _provider_environment(inherited)
|
|
97
|
+
environment.update({key: value for key, value in inherited.items() if key in _CLAUDE_ENVIRONMENT})
|
|
98
|
+
environment.update(
|
|
99
|
+
{
|
|
100
|
+
# Match Codex's 600-second MCP tool timeout for bounded music downloads.
|
|
101
|
+
"MCP_TOOL_TIMEOUT": "600000",
|
|
102
|
+
"MCP_TIMEOUT": "60000",
|
|
103
|
+
"DISABLE_AUTOUPDATER": "1",
|
|
104
|
+
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
|
|
105
|
+
}
|
|
106
|
+
)
|
|
107
|
+
return environment
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def raise_for_claude_failure(returncode: int, diagnostic: str, status: object = None) -> None:
|
|
111
|
+
text = diagnostic.lower()
|
|
112
|
+
if status == 401 or any(
|
|
113
|
+
marker in text
|
|
114
|
+
for marker in (
|
|
115
|
+
"not logged in",
|
|
116
|
+
"invalid api key",
|
|
117
|
+
"/login",
|
|
118
|
+
"authentication_error",
|
|
119
|
+
"authentication_failed",
|
|
120
|
+
"failed to authenticate",
|
|
121
|
+
"oauth token",
|
|
122
|
+
"oauth session",
|
|
123
|
+
)
|
|
124
|
+
):
|
|
125
|
+
raise ProviderAuthenticationError("Claude login is missing or no longer valid")
|
|
126
|
+
if status == 429 or any(
|
|
127
|
+
marker in text
|
|
128
|
+
for marker in ("usage limit", "rate limit", "rate_limit", "quota", "credit balance", "limit reached")
|
|
129
|
+
):
|
|
130
|
+
raise ProviderUsageLimitError("Claude account usage limit prevented this attempt")
|
|
131
|
+
if any(
|
|
132
|
+
marker in text
|
|
133
|
+
for marker in (
|
|
134
|
+
"connection error",
|
|
135
|
+
"network is unreachable",
|
|
136
|
+
"could not resolve host",
|
|
137
|
+
"econnrefused",
|
|
138
|
+
"enotfound",
|
|
139
|
+
)
|
|
140
|
+
):
|
|
141
|
+
raise ProviderNetworkError("Claude could not reach its service")
|
|
142
|
+
if "permission denied" in text or "operation not permitted" in text:
|
|
143
|
+
raise ProviderPermissionError("Claude permission confinement failed")
|
|
144
|
+
raise ProviderProtocolError(f"Claude attempt exited with code {returncode}")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True, slots=True)
|
|
148
|
+
class ClaudeProbeResult:
|
|
149
|
+
version: str
|
|
150
|
+
authenticated: bool
|
|
151
|
+
missing_flags: tuple[str, ...]
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def supports_bounded_attempts(self) -> bool:
|
|
155
|
+
return not self.missing_flags
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def available(self) -> bool:
|
|
159
|
+
return self.authenticated and self.supports_bounded_attempts
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class ClaudeCliAdapter:
|
|
163
|
+
"""Inspect the local Claude Code CLI without contacting a model."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, binary: str | Path | None = None, environment: Mapping[str, str] | None = None) -> None:
|
|
166
|
+
selected = str(binary) if binary is not None else shutil.which("claude")
|
|
167
|
+
if not selected:
|
|
168
|
+
raise ProviderUnavailable("Claude Code CLI is not installed or not on PATH")
|
|
169
|
+
candidate = Path(selected).resolve(strict=True)
|
|
170
|
+
if not candidate.is_file() or not os.access(candidate, os.X_OK):
|
|
171
|
+
raise ProviderUnavailable("Claude Code CLI is not an executable regular file")
|
|
172
|
+
self.binary = candidate
|
|
173
|
+
self.environment = claude_environment(environment)
|
|
174
|
+
|
|
175
|
+
def _probe_command(self, *arguments: str) -> subprocess.CompletedProcess[bytes]:
|
|
176
|
+
try:
|
|
177
|
+
return subprocess.run(
|
|
178
|
+
(str(self.binary), *arguments),
|
|
179
|
+
env=self.environment,
|
|
180
|
+
stdin=subprocess.DEVNULL,
|
|
181
|
+
capture_output=True,
|
|
182
|
+
timeout=_PROBE_TIMEOUT_SECONDS,
|
|
183
|
+
check=False,
|
|
184
|
+
)
|
|
185
|
+
except (OSError, subprocess.TimeoutExpired) as error:
|
|
186
|
+
raise ProviderUnavailable("Claude Code CLI probe failed") from error
|
|
187
|
+
|
|
188
|
+
def version(self) -> str:
|
|
189
|
+
completed = self._probe_command("--version")
|
|
190
|
+
if completed.returncode != 0:
|
|
191
|
+
raise ProviderUnavailable("Claude Code CLI version probe failed")
|
|
192
|
+
version = _decode_capture(completed.stdout, "version output", 256).strip()
|
|
193
|
+
if not version:
|
|
194
|
+
raise ProviderProtocolError("Claude Code CLI returned an invalid version string")
|
|
195
|
+
return version
|
|
196
|
+
|
|
197
|
+
def missing_flags(self) -> tuple[str, ...]:
|
|
198
|
+
completed = self._probe_command("--help")
|
|
199
|
+
if completed.returncode != 0:
|
|
200
|
+
raise ProviderUnavailable("Claude Code CLI capability probe failed")
|
|
201
|
+
help_text = _decode_capture(completed.stdout, "help output")
|
|
202
|
+
return tuple(flag for flag in REQUIRED_FLAGS if flag not in help_text)
|
|
203
|
+
|
|
204
|
+
def authenticated(self) -> bool:
|
|
205
|
+
if self.environment.get("ANTHROPIC_API_KEY"):
|
|
206
|
+
return True
|
|
207
|
+
completed = self._probe_command("auth", "status", "--json")
|
|
208
|
+
try:
|
|
209
|
+
status = json.loads(_decode_capture(completed.stdout, "auth status", 64 * 1024))
|
|
210
|
+
except (ProviderProtocolError, json.JSONDecodeError):
|
|
211
|
+
return False
|
|
212
|
+
return isinstance(status, dict) and status.get("loggedIn") is True
|
|
213
|
+
|
|
214
|
+
def probe(self) -> ClaudeProbeResult:
|
|
215
|
+
return ClaudeProbeResult(self.version(), self.authenticated(), self.missing_flags())
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _stream_events(stdout: bytes, limit: int = _MAX_CAPTURE_BYTES) -> list[dict]:
|
|
219
|
+
if len(stdout) > limit:
|
|
220
|
+
raise ProviderProtocolError("Claude stream-json output exceeded the capture limit")
|
|
221
|
+
events = []
|
|
222
|
+
# Parse line by line from bytes so a large log is never copied into one string.
|
|
223
|
+
for line in stdout.splitlines():
|
|
224
|
+
if not line.strip():
|
|
225
|
+
continue
|
|
226
|
+
try:
|
|
227
|
+
event = json.loads(line)
|
|
228
|
+
except (json.JSONDecodeError, UnicodeDecodeError) as error:
|
|
229
|
+
raise ProviderProtocolError("Claude stream contained invalid JSON") from error
|
|
230
|
+
if not isinstance(event, dict):
|
|
231
|
+
raise ProviderProtocolError("Claude stream events must be objects")
|
|
232
|
+
# Tool results echo every thumbnail back; nothing reads them, so keep only the type.
|
|
233
|
+
events.append({"type": "user"} if event.get("type") == "user" else event)
|
|
234
|
+
return events
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def stream_event_types(events: list[dict]) -> tuple[str, ...]:
|
|
238
|
+
types = []
|
|
239
|
+
for event in events:
|
|
240
|
+
kind, subtype = event.get("type"), event.get("subtype")
|
|
241
|
+
if isinstance(kind, str) and kind:
|
|
242
|
+
types.append(f"{kind}.{subtype}" if isinstance(subtype, str) and subtype else kind)
|
|
243
|
+
return tuple(types)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def stream_usage(events: list[dict]) -> ProviderUsage | None:
|
|
247
|
+
"""Claude reports fresh, cache-written and cache-read input separately."""
|
|
248
|
+
result = next((e for e in reversed(events) if e.get("type") == "result"), None)
|
|
249
|
+
reported = None if result is None else result.get("usage")
|
|
250
|
+
if not isinstance(reported, dict):
|
|
251
|
+
return None
|
|
252
|
+
try:
|
|
253
|
+
read = reported.get("cache_read_input_tokens", 0)
|
|
254
|
+
return ProviderUsage(
|
|
255
|
+
input_tokens=reported["input_tokens"] + reported.get("cache_creation_input_tokens", 0) + read,
|
|
256
|
+
cached_input_tokens=read,
|
|
257
|
+
output_tokens=reported["output_tokens"],
|
|
258
|
+
)
|
|
259
|
+
except (KeyError, TypeError, ValueError) as error:
|
|
260
|
+
raise ProviderProtocolError("Claude usage data was malformed") from error
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def raise_for_failed_result(events: list[dict], diagnostic: str = "") -> None:
|
|
264
|
+
result = next((e for e in reversed(events) if e.get("type") == "result"), None)
|
|
265
|
+
if result is None or (not result.get("is_error") and result.get("subtype") == "success"):
|
|
266
|
+
return
|
|
267
|
+
message = " ".join(str(part) for part in (result.get("result"), result.get("errors"), diagnostic) if part)
|
|
268
|
+
raise_for_claude_failure(1, message, result.get("api_error_status"))
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class ClaudeExecAdapter(CodexExecAdapter):
|
|
272
|
+
"""Run one schema-bound Claude attempt with the same receipts as Codex.
|
|
273
|
+
|
|
274
|
+
Workspace isolation, receipts, redaction, schema validation and reconcile
|
|
275
|
+
are inherited; only the launch, stdin and output stream differ.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
provider_id = "claude"
|
|
279
|
+
display_name = "Claude"
|
|
280
|
+
|
|
281
|
+
def __init__(
|
|
282
|
+
self,
|
|
283
|
+
attempt_root: Path,
|
|
284
|
+
binary: str | Path | None = None,
|
|
285
|
+
environment: Mapping[str, str] | None = None,
|
|
286
|
+
) -> None:
|
|
287
|
+
self._attempt_root = _isolated_workspace(attempt_root)
|
|
288
|
+
cli = ClaudeCliAdapter(binary, environment)
|
|
289
|
+
self._cli = cli
|
|
290
|
+
self._binary = cli.binary
|
|
291
|
+
self._environment = cli.environment
|
|
292
|
+
|
|
293
|
+
def version(self) -> str:
|
|
294
|
+
return self._cli.version()
|
|
295
|
+
|
|
296
|
+
def probe(self) -> ClaudeProbeResult:
|
|
297
|
+
"""Check the local CLI and login without contacting a model."""
|
|
298
|
+
return self._cli.probe()
|
|
299
|
+
|
|
300
|
+
def command(self, attempt: CodexAttempt, output_path: Path) -> tuple[str, ...]:
|
|
301
|
+
workspace = _isolated_workspace(attempt.workspace)
|
|
302
|
+
if workspace == self._attempt_root or not _inside(workspace, self._attempt_root):
|
|
303
|
+
raise ValueError("attempt workspace must be a child of the managed attempt root")
|
|
304
|
+
schema = _workspace_file(attempt.output_schema, workspace, "output_schema")
|
|
305
|
+
if output_path.is_symlink():
|
|
306
|
+
raise ValueError("provider output cannot be a symbolic link")
|
|
307
|
+
resolved_output = output_path.resolve(strict=False)
|
|
308
|
+
if not _inside(resolved_output, workspace) or resolved_output.exists():
|
|
309
|
+
raise ValueError("provider output must be a new file inside the attempt workspace")
|
|
310
|
+
return (
|
|
311
|
+
str(self._binary),
|
|
312
|
+
"--print",
|
|
313
|
+
"--input-format",
|
|
314
|
+
"stream-json",
|
|
315
|
+
"--output-format",
|
|
316
|
+
"stream-json",
|
|
317
|
+
"--verbose",
|
|
318
|
+
"--json-schema",
|
|
319
|
+
json.dumps(_load_output_schema(schema), ensure_ascii=True),
|
|
320
|
+
# Inputs arrive only through stdin; no tools, MCP servers, user
|
|
321
|
+
# settings or CLAUDE.md, like Codex's --ignore-user-config/--ignore-rules.
|
|
322
|
+
"--safe-mode",
|
|
323
|
+
"--tools",
|
|
324
|
+
"",
|
|
325
|
+
"--strict-mcp-config",
|
|
326
|
+
"--permission-mode",
|
|
327
|
+
"dontAsk",
|
|
328
|
+
"--setting-sources",
|
|
329
|
+
"project",
|
|
330
|
+
"--no-session-persistence",
|
|
331
|
+
"--disable-slash-commands",
|
|
332
|
+
*model_arguments(self._environment),
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
def _stdin_payload(self, attempt: CodexAttempt) -> bytes:
|
|
336
|
+
"""Send the prompt and approved PNG snapshots as one user message."""
|
|
337
|
+
content: list[dict[str, object]] = [{"type": "text", "text": attempt.prompt}]
|
|
338
|
+
for image in attempt.images:
|
|
339
|
+
path = _workspace_file(image, attempt.workspace.resolve(), "image")
|
|
340
|
+
content.append(
|
|
341
|
+
{
|
|
342
|
+
"type": "image",
|
|
343
|
+
"source": {
|
|
344
|
+
"type": "base64",
|
|
345
|
+
"media_type": "image/png",
|
|
346
|
+
"data": base64.b64encode(path.read_bytes()).decode("ascii"),
|
|
347
|
+
},
|
|
348
|
+
}
|
|
349
|
+
)
|
|
350
|
+
message = {"type": "user", "message": {"role": "user", "content": content}}
|
|
351
|
+
return (json.dumps(message, ensure_ascii=False) + "\n").encode("utf-8")
|
|
352
|
+
|
|
353
|
+
@staticmethod
|
|
354
|
+
def _events_and_usage(
|
|
355
|
+
stdout: bytes, *, limit: int = _MAX_CAPTURE_BYTES
|
|
356
|
+
) -> tuple[tuple[str, ...], ProviderUsage | None]:
|
|
357
|
+
events = _stream_events(stdout, limit)
|
|
358
|
+
return stream_event_types(events), stream_usage(events)
|
|
359
|
+
|
|
360
|
+
@staticmethod
|
|
361
|
+
def _raise_for_failed_turn(stdout: bytes, *, limit: int = _MAX_CAPTURE_BYTES) -> None:
|
|
362
|
+
try:
|
|
363
|
+
events = _stream_events(stdout, limit)
|
|
364
|
+
except ProviderProtocolError:
|
|
365
|
+
return # Normal result validation reports the malformed stream.
|
|
366
|
+
raise_for_failed_result(events)
|
|
367
|
+
|
|
368
|
+
@staticmethod
|
|
369
|
+
def _raise_for_exit(returncode: int, stderr: bytes) -> None:
|
|
370
|
+
raise_for_claude_failure(returncode, _decode_capture(stderr, "stderr"))
|
|
371
|
+
|
|
372
|
+
def _validated_result(self, attempt: CodexAttempt, output_path: Path, stdout: bytes) -> CodexAttemptResult:
|
|
373
|
+
events = _stream_events(stdout)
|
|
374
|
+
result = next((e for e in reversed(events) if e.get("type") == "result"), None)
|
|
375
|
+
if result is None or result.get("is_error") or result.get("subtype") != "success":
|
|
376
|
+
raise ProviderProtocolError("Claude stream did not report a successful result")
|
|
377
|
+
if output_path.is_symlink():
|
|
378
|
+
raise ProviderProtocolError("Claude result path is unsafe")
|
|
379
|
+
if not output_path.exists():
|
|
380
|
+
# Claude returns structured output in its stream; persist it once so
|
|
381
|
+
# receipts and reconcile hash the same file as a Codex attempt.
|
|
382
|
+
payload = result.get("structured_output")
|
|
383
|
+
if payload is None and isinstance(result.get("result"), str):
|
|
384
|
+
try:
|
|
385
|
+
payload = json.loads(result["result"])
|
|
386
|
+
except json.JSONDecodeError:
|
|
387
|
+
payload = None
|
|
388
|
+
encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
389
|
+
if len(encoded) > _MAX_RESULT_BYTES:
|
|
390
|
+
raise ProviderProtocolError("Claude result exceeded the size limit")
|
|
391
|
+
descriptor = os.open(output_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
392
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
393
|
+
stream.write(encoded)
|
|
394
|
+
if output_path.stat().st_size > _MAX_RESULT_BYTES:
|
|
395
|
+
raise ProviderProtocolError("Claude result exceeded the size limit")
|
|
396
|
+
try:
|
|
397
|
+
payload = json.loads(output_path.read_text(encoding="utf-8"))
|
|
398
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
399
|
+
raise ProviderProtocolError("Claude result was not valid UTF-8 JSON") from error
|
|
400
|
+
if not isinstance(payload, dict):
|
|
401
|
+
raise ProviderProtocolError("Claude result must be a JSON object")
|
|
402
|
+
schema = _load_output_schema(
|
|
403
|
+
_workspace_file(attempt.output_schema, _isolated_workspace(attempt.workspace), "output_schema")
|
|
404
|
+
)
|
|
405
|
+
try:
|
|
406
|
+
Draft202012Validator(schema).validate(payload)
|
|
407
|
+
except ValidationError as error:
|
|
408
|
+
raise ProviderProtocolError("Claude result did not match the output schema") from error
|
|
409
|
+
return CodexAttemptResult(attempt.attempt_id, payload, stream_event_types(events), None, stream_usage(events))
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""One-shot Claude Code agent runner bound to a single Clipen MCP edit session."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Mapping
|
|
8
|
+
|
|
9
|
+
from .claude import (
|
|
10
|
+
_stream_events,
|
|
11
|
+
claude_environment,
|
|
12
|
+
claude_preferences,
|
|
13
|
+
model_arguments,
|
|
14
|
+
raise_for_claude_failure,
|
|
15
|
+
raise_for_failed_result,
|
|
16
|
+
stream_event_types,
|
|
17
|
+
stream_usage,
|
|
18
|
+
)
|
|
19
|
+
from .codex import _decode_capture
|
|
20
|
+
from .editing_agent import _MAX_CAPTURE_BYTES, _MCP_TOOLS, BoundedEditingAgent, mcp_server_arguments
|
|
21
|
+
from .errors import ProviderProtocolError
|
|
22
|
+
from .recovery import ProviderUsage
|
|
23
|
+
|
|
24
|
+
MCP_SERVER = "clipen"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def allowed_tools() -> str:
|
|
28
|
+
return ",".join(f"mcp__{MCP_SERVER}__{name}" for name in _MCP_TOOLS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ClaudeEditingAgent(BoundedEditingAgent):
|
|
32
|
+
"""Launch `claude -p` with only the Clipen MCP tools and no user settings."""
|
|
33
|
+
|
|
34
|
+
provider_id = "claude"
|
|
35
|
+
display_name = "Claude"
|
|
36
|
+
executable = "claude"
|
|
37
|
+
|
|
38
|
+
def provider_environment(self, source: Mapping[str, str] | None) -> dict[str, str]:
|
|
39
|
+
return claude_environment(source)
|
|
40
|
+
|
|
41
|
+
def command(
|
|
42
|
+
self,
|
|
43
|
+
project_id: str,
|
|
44
|
+
run_id: str,
|
|
45
|
+
workspace: Path,
|
|
46
|
+
output_path: Path,
|
|
47
|
+
) -> tuple[str, ...]:
|
|
48
|
+
server = {
|
|
49
|
+
"type": "stdio",
|
|
50
|
+
"command": str(self.python),
|
|
51
|
+
"args": mcp_server_arguments(self.projects_root, project_id, run_id, self.local_runtime),
|
|
52
|
+
}
|
|
53
|
+
return (
|
|
54
|
+
str(self.binary),
|
|
55
|
+
"--print",
|
|
56
|
+
"--output-format",
|
|
57
|
+
"stream-json",
|
|
58
|
+
"--verbose",
|
|
59
|
+
"--no-session-persistence",
|
|
60
|
+
"--strict-mcp-config",
|
|
61
|
+
"--mcp-config",
|
|
62
|
+
json.dumps({"mcpServers": {MCP_SERVER: server}}, ensure_ascii=True),
|
|
63
|
+
# No built-in tools: no shell, file access or web fetches. The model
|
|
64
|
+
# acts only through the allowlisted Clipen MCP tools.
|
|
65
|
+
"--tools",
|
|
66
|
+
"",
|
|
67
|
+
"--allowedTools",
|
|
68
|
+
allowed_tools(),
|
|
69
|
+
"--permission-mode",
|
|
70
|
+
"dontAsk",
|
|
71
|
+
# Excludes user settings, hooks, plugins and CLAUDE.md (verified with a
|
|
72
|
+
# canary CLAUDE.md in the attempt directory). --safe-mode would do the
|
|
73
|
+
# same but also disables the --mcp-config server this agent needs.
|
|
74
|
+
"--setting-sources",
|
|
75
|
+
"project",
|
|
76
|
+
"--disable-slash-commands",
|
|
77
|
+
*model_arguments(self.environment),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
def events_and_usage(self, stdout: bytes) -> tuple[tuple[str, ...], ProviderUsage | None]:
|
|
81
|
+
events = _stream_events(stdout, _MAX_CAPTURE_BYTES)
|
|
82
|
+
return stream_event_types(events), stream_usage(events)
|
|
83
|
+
|
|
84
|
+
def record_account(self, stdout: bytes) -> None:
|
|
85
|
+
# Claude Code has no quota query; keep what this attempt reported.
|
|
86
|
+
from .account import record_claude_account
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
record_claude_account(
|
|
90
|
+
self.attempt_root, _stream_events(stdout, _MAX_CAPTURE_BYTES), claude_preferences(self.environment)[0]
|
|
91
|
+
)
|
|
92
|
+
except (OSError, ProviderProtocolError):
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
def closing_message(self, stdout: bytes, final_message: Path) -> str | None:
|
|
96
|
+
# Claude reports its last message in the stream's result event.
|
|
97
|
+
result = next(
|
|
98
|
+
(e for e in reversed(_stream_events(stdout, _MAX_CAPTURE_BYTES)) if e.get("type") == "result"), None
|
|
99
|
+
)
|
|
100
|
+
value = None if result is None else result.get("result")
|
|
101
|
+
return value if isinstance(value, str) else None
|
|
102
|
+
|
|
103
|
+
def raise_for_failure(self, stdout: bytes, stderr: bytes, returncode: int) -> None:
|
|
104
|
+
events = _stream_events(stdout, _MAX_CAPTURE_BYTES)
|
|
105
|
+
diagnostic = _decode_capture(stderr, "stderr", _MAX_CAPTURE_BYTES)
|
|
106
|
+
init = next((e for e in events if e.get("type") == "system" and e.get("subtype") == "init"), None)
|
|
107
|
+
if not any(e.get("type") == "result" for e in events):
|
|
108
|
+
raise_for_claude_failure(returncode, diagnostic)
|
|
109
|
+
if init is not None:
|
|
110
|
+
servers = init.get("mcp_servers")
|
|
111
|
+
connected = isinstance(servers, list) and any(
|
|
112
|
+
isinstance(s, dict) and s.get("name") == MCP_SERVER and s.get("status") == "connected" for s in servers
|
|
113
|
+
)
|
|
114
|
+
if not connected:
|
|
115
|
+
raise ProviderProtocolError("Claude could not connect to the Clipen MCP server")
|
|
116
|
+
raise_for_failed_result(events, diagnostic)
|
|
117
|
+
if returncode != 0:
|
|
118
|
+
raise_for_claude_failure(returncode, diagnostic)
|