pr-proof 0.0.0-stage → 0.1.1-beta.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/Procfile +2 -0
- package/README.md +300 -2
- package/app/__init__.py +1 -0
- package/app/api/__init__.py +1 -0
- package/app/api/cli.py +35 -0
- package/app/api/github.py +168 -0
- package/app/api/history.py +123 -0
- package/app/api/main.py +95 -0
- package/app/api/queue.py +45 -0
- package/app/api/responses.py +28 -0
- package/app/api/signature.py +19 -0
- package/app/api/sync.py +189 -0
- package/app/api/sync_rules_pure.py +71 -0
- package/app/api/webhook.py +172 -0
- package/app/setup/__init__.py +4 -0
- package/app/setup/cli.py +90 -0
- package/app/setup/configure.py +735 -0
- package/app/setup/files.py +104 -0
- package/app/setup/github_setup.py +153 -0
- package/app/setup/install_hints.json +32 -0
- package/app/setup/setup_pure.py +344 -0
- package/app/setup/start.py +113 -0
- package/app/shared/__init__.py +1 -0
- package/app/shared/comment_pure.py +29 -0
- package/app/shared/config.py +106 -0
- package/app/shared/db_pure.py +339 -0
- package/app/shared/embed_models_pure.py +55 -0
- package/app/shared/feedback_pure.py +84 -0
- package/app/shared/github_auth.py +74 -0
- package/app/shared/job_pure.py +43 -0
- package/app/shared/notify.py +97 -0
- package/app/shared/ops_alert_pure.py +38 -0
- package/app/shared/state_keys_pure.py +24 -0
- package/app/shared/version.py +27 -0
- package/app/worker/__init__.py +1 -0
- package/app/worker/access_pure.py +180 -0
- package/app/worker/ai/__init__.py +1 -0
- package/app/worker/ai/claude_cli.py +684 -0
- package/app/worker/ai/mcp_relay.py +42 -0
- package/app/worker/ai/path_hook.py +103 -0
- package/app/worker/ai/tool_server.py +139 -0
- package/app/worker/ai/workdir.py +333 -0
- package/app/worker/base_config.py +173 -0
- package/app/worker/budget.py +100 -0
- package/app/worker/cache_key_pure.py +34 -0
- package/app/worker/call_budget_pure.py +132 -0
- package/app/worker/checker_authoring_pure.py +599 -0
- package/app/worker/checker_pure.py +196 -0
- package/app/worker/cli.py +97 -0
- package/app/worker/command.py +191 -0
- package/app/worker/command_pure.py +38 -0
- package/app/worker/coverage.py +123 -0
- package/app/worker/coverage_pure.py +202 -0
- package/app/worker/deps.py +22 -0
- package/app/worker/diff_pure.py +419 -0
- package/app/worker/doc_rules_pure.py +201 -0
- package/app/worker/doc_rules_report.py +979 -0
- package/app/worker/eval_run_pure.py +241 -0
- package/app/worker/evaluation.py +151 -0
- package/app/worker/feedback.py +448 -0
- package/app/worker/feedback_pure.py +131 -0
- package/app/worker/feedback_report_pure.py +90 -0
- package/app/worker/feedback_triage.py +85 -0
- package/app/worker/feedback_triage_pure.py +363 -0
- package/app/worker/fix/__init__.py +1 -0
- package/app/worker/fix/decide.py +197 -0
- package/app/worker/fix/feedback_fix_pure.py +125 -0
- package/app/worker/fix/fix_decision_pure.py +386 -0
- package/app/worker/fix/fix_pure.py +70 -0
- package/app/worker/fix/mechanical_fix.py +214 -0
- package/app/worker/fix/model_fix.py +575 -0
- package/app/worker/fix/model_fix_pure.py +593 -0
- package/app/worker/fix/proposal.py +584 -0
- package/app/worker/fix/proposal_pure.py +103 -0
- package/app/worker/fix/scope.py +40 -0
- package/app/worker/fix/scope_pure.py +222 -0
- package/app/worker/generated_tests_pure.py +442 -0
- package/app/worker/github.py +471 -0
- package/app/worker/graph.py +963 -0
- package/app/worker/guard.py +91 -0
- package/app/worker/lang/__init__.py +0 -0
- package/app/worker/lang/install_pure.py +25 -0
- package/app/worker/lang/python.py +862 -0
- package/app/worker/loop.py +200 -0
- package/app/worker/main.py +76 -0
- package/app/worker/markdown_pure.py +29 -0
- package/app/worker/mcp_pure.py +150 -0
- package/app/worker/memory.py +503 -0
- package/app/worker/merged_fix_pure.py +236 -0
- package/app/worker/pr_check_report_pure.py +201 -0
- package/app/worker/pr_description_report_pure.py +112 -0
- package/app/worker/preflight.py +125 -0
- package/app/worker/rag_pure.py +285 -0
- package/app/worker/rag_switch_pure.py +203 -0
- package/app/worker/records.py +207 -0
- package/app/worker/records_pure.py +239 -0
- package/app/worker/repo.py +588 -0
- package/app/worker/repo_config_pure.py +269 -0
- package/app/worker/report.py +300 -0
- package/app/worker/retry.py +65 -0
- package/app/worker/rule_pure.py +223 -0
- package/app/worker/rule_reading_pure.py +503 -0
- package/app/worker/rules/__init__.py +1 -0
- package/app/worker/rules/checkers.py +615 -0
- package/app/worker/rules/detect.py +154 -0
- package/app/worker/rules/doc_rules.py +301 -0
- package/app/worker/rules/doc_sections_pure.py +168 -0
- package/app/worker/rules/judge.py +410 -0
- package/app/worker/rules/judge_pure.py +627 -0
- package/app/worker/rules/pr_check.py +404 -0
- package/app/worker/rules/pr_check_pure.py +922 -0
- package/app/worker/rules/pr_description.py +218 -0
- package/app/worker/rules/pr_description_pure.py +743 -0
- package/app/worker/rules/rules.py +314 -0
- package/app/worker/rules/run_check.py +95 -0
- package/app/worker/rules/run_check_pure.py +219 -0
- package/app/worker/rules/tool_choice_pure.py +135 -0
- package/app/worker/sandbox/__init__.py +1 -0
- package/app/worker/sandbox/checker_runner.py +412 -0
- package/app/worker/sandbox/container.py +130 -0
- package/app/worker/sandbox/docker_cli.py +170 -0
- package/app/worker/sandbox/safe_read.py +32 -0
- package/app/worker/sandbox/toolcache.py +425 -0
- package/app/worker/state.py +602 -0
- package/app/worker/test_lines.py +77 -0
- package/app/worker/test_run_pure.py +133 -0
- package/app/worker/text_edit_pure.py +66 -0
- package/app/worker/tools_pure.py +152 -0
- package/app/worker/update.py +305 -0
- package/app/worker/violation_pure.py +33 -0
- package/bin/pr-proof.js +173 -0
- package/docker/sandbox/Dockerfile +12 -0
- package/docker/sandbox/coveragerc +19 -0
- package/docker-compose.yml +5 -0
- package/package.json +31 -4
- package/pyproject.toml +60 -0
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
"""claude CLI 호출 (docs/DESIGN.md 8.4).
|
|
2
|
+
|
|
3
|
+
호출 모양은 넷이다. 수정 작성은 모델 폴더를 cwd로 파일 도구 다섯 개와 파이프라인 도구 둘(규칙 검사,
|
|
4
|
+
테스트)을 주고(`fix_tools`), 파이프라인 도구가 없는 수정 작성은 파일 도구만 준다(`file_tools`).
|
|
5
|
+
위반 판단은 모델 폴더를 cwd로 읽기 도구 셋(Read, Grep, Glob)만 주고 구조화 출력을 받는다
|
|
6
|
+
(`read_tools`: `run_structured`에 `read_in`을 준 호출). 나머지 단계는 빈 임시 폴더를 cwd로 도구
|
|
7
|
+
없이 부르고 구조화 출력을 받는다(`no_tools`). 모두 권한을 제한한 같은 옵션 위에 모양별 옵션을
|
|
8
|
+
더한다. 모델과 호출당 예산은 호출하는 쪽이 정한다.
|
|
9
|
+
파이프라인 도구는 파이프라인이 띄우는 stdio MCP 서버 하나로만 준다(`--mcp-config`와
|
|
10
|
+
`--strict-mcp-config`). 모델에게 명령 실행 도구는 주지 않는다.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
import threading
|
|
19
|
+
from collections.abc import Callable, Mapping
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from enum import StrEnum
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Final, Literal
|
|
24
|
+
|
|
25
|
+
from app.worker.mcp_pure import TOOL_NAMES, ToolUsage
|
|
26
|
+
|
|
27
|
+
# 호출 한 번의 시간 상한(초). 넘으면 프로세스를 죽이고 TIMEOUT으로 돌려준다
|
|
28
|
+
DEFAULT_TIMEOUT_S: Final = 600.0
|
|
29
|
+
# --max-budget-usd에 소수 넷째 자리까지 넘기므로 이보다 작으면 0이 된다
|
|
30
|
+
MIN_BUDGET_USD: Final = 0.0001
|
|
31
|
+
|
|
32
|
+
NOT_LOGGED_IN: Final = "Not logged in"
|
|
33
|
+
|
|
34
|
+
# 권한 제한 옵션. --restricted가 실행 도구·WebFetch를 빼고, 파일 도구를 cwd 안으로 제한하고,
|
|
35
|
+
# user·project·local 설정 파일(PR이 넣은 .claude/ 포함)과 CLAUDE.md를 읽지 않는다.
|
|
36
|
+
# --allowedTools는 승인만 하고 도구 목록을 줄이지 않으므로(2.1.327에서 WebSearch, Task 등 21개가
|
|
37
|
+
# 보였다) 목록은 --tools로 정한다. 스킬·명령은 끄고, 세션 기록은 ~/.claude에 남기지 않는다
|
|
38
|
+
_COMMON_ARGS: Final = (
|
|
39
|
+
"-p",
|
|
40
|
+
"--restricted",
|
|
41
|
+
"--strict-mcp-config",
|
|
42
|
+
"--permission-mode",
|
|
43
|
+
"dontAsk",
|
|
44
|
+
"--disable-slash-commands",
|
|
45
|
+
"--no-session-persistence",
|
|
46
|
+
"--output-format",
|
|
47
|
+
"stream-json", # 첫 줄의 system/init에 도구 목록이 있다. json 형식에는 없다
|
|
48
|
+
"--verbose",
|
|
49
|
+
)
|
|
50
|
+
FILE_TOOLS: Final = "Read,Grep,Glob,Write,Edit"
|
|
51
|
+
# 읽기만 하는 모양의 도구. 쓰기 도구와 명령 실행 도구는 없다
|
|
52
|
+
READ_TOOLS: Final = "Read,Grep,Glob"
|
|
53
|
+
PIPELINE_TOOLS: Final = ",".join(TOOL_NAMES)
|
|
54
|
+
CallShape = Literal["file_tools", "fix_tools", "read_tools", "no_tools"]
|
|
55
|
+
# --tools는 내장 도구만 고른다. MCP 도구는 --mcp-config의 서버에서 오고, dontAsk 모드에서는
|
|
56
|
+
# --allowedTools에 이름이 있어야 부를 수 있다
|
|
57
|
+
_SHAPE_ARGS: Final[Mapping[str, tuple[str, ...]]] = {
|
|
58
|
+
"file_tools": ("--tools", FILE_TOOLS, "--allowedTools", FILE_TOOLS),
|
|
59
|
+
"fix_tools": ("--tools", FILE_TOOLS, "--allowedTools", f"{FILE_TOOLS},{PIPELINE_TOOLS}"),
|
|
60
|
+
"read_tools": ("--tools", READ_TOOLS, "--allowedTools", READ_TOOLS),
|
|
61
|
+
"no_tools": ("--tools", ""),
|
|
62
|
+
}
|
|
63
|
+
# --json-schema를 주면 CLI가 답을 받는 도구 하나를 스스로 더한다. 파일·웹·실행 도구가 아니다
|
|
64
|
+
STRUCTURED_OUTPUT_TOOL: Final = "StructuredOutput"
|
|
65
|
+
# 모양마다 system/init의 도구 목록이 정확히 이것이어야 한다. 다르면 호출을 중단한다
|
|
66
|
+
_SHAPE_TOOLS: Final[Mapping[str, frozenset[str]]] = {
|
|
67
|
+
"file_tools": frozenset(FILE_TOOLS.split(",")),
|
|
68
|
+
"fix_tools": frozenset(FILE_TOOLS.split(",")) | frozenset(TOOL_NAMES),
|
|
69
|
+
"read_tools": frozenset(READ_TOOLS.split(",")) | {STRUCTURED_OUTPUT_TOOL},
|
|
70
|
+
"no_tools": frozenset({STRUCTURED_OUTPUT_TOOL}),
|
|
71
|
+
}
|
|
72
|
+
# 읽기 도구 중 경로를 받는 입력 키. Grep·Glob에 경로가 없으면 cwd 전체를 본 것이다
|
|
73
|
+
_READ_PATH_KEYS: Final[Mapping[str, str]] = {"Read": "file_path", "Grep": "path", "Glob": "path"}
|
|
74
|
+
# 파이프라인 도구가 든 호출의 시간 상한(초): 모델 600초 + 도구 시간 상한 900초 + 여유 300초
|
|
75
|
+
FIX_TOOLS_TIMEOUT_S: Final = 1800.0
|
|
76
|
+
# 테스트 도구 한 번은 샌드박스의 pytest 시간 상한(600초)까지 걸린다. CLI의 MCP 도구 대기 시간(ms)
|
|
77
|
+
MCP_TOOL_TIMEOUT_MS: Final = "660000"
|
|
78
|
+
|
|
79
|
+
# claude가 로컬 로그인을 찾는 데 필요한 변수만 넘긴다.
|
|
80
|
+
# HOME: ~/.claude(설정·세션), Linux에서는 ~/.claude/.credentials.json
|
|
81
|
+
# USER: macOS 키체인 항목의 계정 이름. 없으면 "Not logged in"이 된다 (2.1.327에서 확인)
|
|
82
|
+
# PATH: claude가 부르는 보조 명령(git 등)을 찾는다
|
|
83
|
+
# CLAUDE_CONFIG_DIR: 설정 폴더를 옮긴 경우에만 있다
|
|
84
|
+
# ANTHROPIC_API_KEY 같은 토큰과 파이프라인의 다른 환경 변수는 넘기지 않는다
|
|
85
|
+
_ENV_PASSTHROUGH: Final = ("HOME", "USER", "PATH", "CLAUDE_CONFIG_DIR")
|
|
86
|
+
# 실제 입력 토큰은 셋의 합이다. input_tokens만 보면 캐시를 쓴 호출에서 2 같은 값이 나온다
|
|
87
|
+
_INPUT_TOKEN_KEYS: Final = (
|
|
88
|
+
"input_tokens",
|
|
89
|
+
"cache_creation_input_tokens",
|
|
90
|
+
"cache_read_input_tokens",
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
log = logging.getLogger(__name__)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class AIErrorKind(StrEnum):
|
|
98
|
+
TIMEOUT = "timeout"
|
|
99
|
+
LAUNCH = "launch" # claude를 실행하지 못함 (명령 없음, worktree 없음)
|
|
100
|
+
EXIT = "exit" # 0이 아닌 종료 코드나 is_error (로그인 풀림 포함)
|
|
101
|
+
BAD_JSON = "bad_json"
|
|
102
|
+
BUDGET = "budget" # --max-budget-usd를 넘김
|
|
103
|
+
# 모델에 보인 도구 목록이 기대와 다르거나, 경로 감시 훅이 돌지 않음. 결과를 쓰지 않는다
|
|
104
|
+
TOOLS = "tools"
|
|
105
|
+
TOOL_CAP = "tool_cap" # 읽기 도구를 부른 횟수가 호출 하나의 상한을 넘음
|
|
106
|
+
APPLY = "apply" # 모델 폴더의 변경을 worktree에 적용하지 못함
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class PermissionDenial:
|
|
111
|
+
"""허용 범위 밖이라 거부된 도구 호출 한 건 (worktree 밖 Read 등)."""
|
|
112
|
+
|
|
113
|
+
tool_name: str
|
|
114
|
+
tool_input: Mapping[str, object]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class ClaudeResult:
|
|
119
|
+
"""claude 호출 결과. ok는 호출이 정상으로 끝났다는 뜻일 뿐, 수정안의 판정이 아니다.
|
|
120
|
+
|
|
121
|
+
cost_usd가 None이면 비용을 알 수 없다 (시간 초과, JSON 없음). 상한은 호출 수로 세므로 이 값은
|
|
122
|
+
판단에 쓰지 않는다 (DESIGN 9.2).
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
ok: bool
|
|
126
|
+
error: AIErrorKind | None
|
|
127
|
+
cost_usd: float | None
|
|
128
|
+
num_turns: int
|
|
129
|
+
permission_denials: tuple[PermissionDenial, ...]
|
|
130
|
+
text: str
|
|
131
|
+
detail: str = ""
|
|
132
|
+
# 모델이 부르려 한, 허용 목록 밖 도구의 (이름, 횟수). 목록에 없는 도구는 CLI가 "없는 도구"로
|
|
133
|
+
# 답해 permission_denials에 잡히지 않으므로 스트림의 tool_use에서 센다
|
|
134
|
+
unexpected_tools: tuple[tuple[str, int], ...] = ()
|
|
135
|
+
# 모델이 부른, 목록 안 도구의 횟수. 경로 감시 훅이 호출마다 돌았는지 맞춰 보는 데 쓴다
|
|
136
|
+
tool_uses: int = 0
|
|
137
|
+
model_id: str = "" # 별칭이 가리킨 전체 모델 id. 모르면 ""
|
|
138
|
+
input_tokens: int | None = None # 캐시 생성·읽기를 합친 실제 입력. 모르면 None
|
|
139
|
+
output_tokens: int | None = None
|
|
140
|
+
# 모델 폴더에서 worktree에 적용한 diff. `workdir.run_in_model_folder`만 채운다
|
|
141
|
+
applied: bytes = b""
|
|
142
|
+
# 파이프라인 도구를 부른 횟수와 시간. 도구가 든 호출에서 `workdir.run_in_model_folder`가 채운다
|
|
143
|
+
tool_usage: ToolUsage = ToolUsage()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class AIEnvironmentError(RuntimeError):
|
|
147
|
+
"""claude를 실행할 수 없다 (명령 없음, 로그인 풀림). PR 탓이 아니라 환경 오류로 재시도한다."""
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def environment_problem(result: ClaudeResult) -> str | None:
|
|
151
|
+
"""PR과 관계없이 claude를 쓸 수 없는 상태면 그 이유."""
|
|
152
|
+
if result.error == AIErrorKind.LAUNCH:
|
|
153
|
+
return f"claude를 실행하지 못함: {result.detail}"
|
|
154
|
+
if result.error == AIErrorKind.TOOLS:
|
|
155
|
+
return f"claude 호출을 중단함: {result.detail}"
|
|
156
|
+
if NOT_LOGGED_IN in result.text or NOT_LOGGED_IN in result.detail:
|
|
157
|
+
return "claude 로그인이 풀림"
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# 표준 출력 한 줄 → 호출을 중단할 이유. 계속해도 되면 None
|
|
162
|
+
Watch = Callable[[str], str | None]
|
|
163
|
+
# (args, 표준 입력, cwd, env, timeout, watch) → 완료된 프로세스. 시간 초과는 TimeoutExpired로,
|
|
164
|
+
# watch가 이유를 내면 프로세스를 죽이고 ToolListMismatch로 올린다
|
|
165
|
+
Runner = Callable[
|
|
166
|
+
[list[str], str, Path, dict[str, str], float, Watch], subprocess.CompletedProcess[str]
|
|
167
|
+
]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class ToolListMismatch(Exception):
|
|
171
|
+
"""system/init의 도구 목록이 기대와 달라 호출을 중단했다."""
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class ToolCapReached(Exception):
|
|
175
|
+
"""읽기 도구를 부른 횟수가 호출 하나의 상한을 넘어 호출을 중단했다."""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(frozen=True)
|
|
179
|
+
class ReadFolder:
|
|
180
|
+
"""읽기 도구를 주는 호출의 폴더 (`app/worker/ai/workdir.py`의 모델 폴더)."""
|
|
181
|
+
|
|
182
|
+
work: Path # cwd. worktree의 일반 파일만 복사한 폴더
|
|
183
|
+
settings: Path # 경로 감시 훅을 건 설정 파일. work 밖에 있다
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def claude_env(environ: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
187
|
+
"""claude가 로그인을 찾는 데 필요한 변수만 고른다."""
|
|
188
|
+
source = os.environ if environ is None else environ
|
|
189
|
+
return {k: source[k] for k in _ENV_PASSTHROUGH if k in source}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def build_args(
|
|
193
|
+
shape: CallShape, model: str, max_budget_usd: float, extra: tuple[str, ...] = ()
|
|
194
|
+
) -> list[str]:
|
|
195
|
+
"""claude 명령 인자. 프롬프트는 인자가 아니라 표준 입력으로 넘긴다."""
|
|
196
|
+
if not model or model.startswith("-"):
|
|
197
|
+
raise ValueError(f"잘못된 모델 이름: {model!r}")
|
|
198
|
+
if not max_budget_usd >= MIN_BUDGET_USD:
|
|
199
|
+
raise ValueError(f"호출당 예산은 {MIN_BUDGET_USD} 이상이어야 한다: {max_budget_usd}")
|
|
200
|
+
return [
|
|
201
|
+
"claude",
|
|
202
|
+
*_COMMON_ARGS,
|
|
203
|
+
*_SHAPE_ARGS[shape],
|
|
204
|
+
*extra,
|
|
205
|
+
"--model",
|
|
206
|
+
model,
|
|
207
|
+
"--max-budget-usd",
|
|
208
|
+
f"{max_budget_usd:.4f}",
|
|
209
|
+
]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def tool_list_problem(event: Mapping[str, object], shape: CallShape) -> str | None:
|
|
213
|
+
"""system/init 메시지의 도구 목록이 이 모양의 기대와 정확히 같지 않으면 그 이유."""
|
|
214
|
+
tools = event.get("tools")
|
|
215
|
+
if not isinstance(tools, list) or not all(isinstance(t, str) for t in tools):
|
|
216
|
+
return "system/init에 도구 목록이 없음"
|
|
217
|
+
expected, seen = _SHAPE_TOOLS[shape], set(tools)
|
|
218
|
+
if seen == expected:
|
|
219
|
+
return None
|
|
220
|
+
extra, missing = sorted(seen - expected), sorted(expected - seen)
|
|
221
|
+
version = event.get("claude_code_version")
|
|
222
|
+
return (
|
|
223
|
+
f"도구 목록이 기대와 다름: 더 있음 {extra}, 없음 {missing} "
|
|
224
|
+
f"(claude CLI {version if isinstance(version, str) else '버전 모름'})"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _init_event(line: str) -> dict | None:
|
|
229
|
+
event = _json_object(line)
|
|
230
|
+
if event is not None and event.get("type") == "system" and event.get("subtype") == "init":
|
|
231
|
+
return event
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _watch_for(shape: CallShape, max_tool_uses: int | None = None) -> Watch:
|
|
236
|
+
"""init의 도구 목록을 확인한다. max_tool_uses가 있으면 모델이 부른 도구(구조화 출력을 내는
|
|
237
|
+
도구는 빼고)가 그보다 많아지는 순간 ToolCapReached로 멈춘다."""
|
|
238
|
+
used = 0
|
|
239
|
+
|
|
240
|
+
def watch(line: str) -> str | None:
|
|
241
|
+
nonlocal used
|
|
242
|
+
event = _json_object(line)
|
|
243
|
+
if event is not None and event.get("type") == "system" and event.get("subtype") == "init":
|
|
244
|
+
return tool_list_problem(event, shape)
|
|
245
|
+
if max_tool_uses is not None:
|
|
246
|
+
used += sum(1 for n in _tool_names(event) if n != STRUCTURED_OUTPUT_TOOL)
|
|
247
|
+
if used > max_tool_uses:
|
|
248
|
+
raise ToolCapReached(f"도구 호출이 상한 {max_tool_uses}회를 넘음")
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
return watch
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _run(
|
|
255
|
+
args: list[str], stdin: str, cwd: Path, env: dict[str, str], timeout: float, watch: Watch
|
|
256
|
+
) -> subprocess.CompletedProcess[str]:
|
|
257
|
+
"""출력을 줄 단위로 읽으며 watch에 보인다. init은 모델을 부르기 전에 나와 거기서 멈춘다."""
|
|
258
|
+
timed_out = threading.Event()
|
|
259
|
+
with (
|
|
260
|
+
tempfile.TemporaryFile("w+") as stderr,
|
|
261
|
+
subprocess.Popen(
|
|
262
|
+
args, cwd=cwd, env=env, text=True,
|
|
263
|
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr,
|
|
264
|
+
) as proc,
|
|
265
|
+
): # fmt: skip
|
|
266
|
+
assert proc.stdin is not None and proc.stdout is not None
|
|
267
|
+
|
|
268
|
+
def expire() -> None:
|
|
269
|
+
timed_out.set()
|
|
270
|
+
proc.kill()
|
|
271
|
+
|
|
272
|
+
def feed() -> None:
|
|
273
|
+
try:
|
|
274
|
+
proc.stdin.write(stdin)
|
|
275
|
+
proc.stdin.close()
|
|
276
|
+
except OSError: # 프로세스가 입력을 다 읽기 전에 끝남
|
|
277
|
+
pass
|
|
278
|
+
|
|
279
|
+
timer = threading.Timer(timeout, expire)
|
|
280
|
+
feeder = threading.Thread(target=feed, daemon=True)
|
|
281
|
+
timer.start()
|
|
282
|
+
feeder.start()
|
|
283
|
+
lines: list[str] = []
|
|
284
|
+
try:
|
|
285
|
+
for line in proc.stdout:
|
|
286
|
+
lines.append(line)
|
|
287
|
+
reason = watch(line)
|
|
288
|
+
if reason is not None:
|
|
289
|
+
proc.kill()
|
|
290
|
+
raise ToolListMismatch(reason)
|
|
291
|
+
proc.wait()
|
|
292
|
+
finally:
|
|
293
|
+
timer.cancel()
|
|
294
|
+
proc.kill()
|
|
295
|
+
feeder.join()
|
|
296
|
+
if timed_out.is_set():
|
|
297
|
+
raise subprocess.TimeoutExpired(args, timeout)
|
|
298
|
+
stderr.seek(0)
|
|
299
|
+
return subprocess.CompletedProcess(args, proc.returncode, "".join(lines), stderr.read())
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def run_claude(
|
|
303
|
+
worktree: Path,
|
|
304
|
+
prompt: str,
|
|
305
|
+
*,
|
|
306
|
+
model: str,
|
|
307
|
+
max_budget_usd: float,
|
|
308
|
+
timeout: float = DEFAULT_TIMEOUT_S,
|
|
309
|
+
runner: Runner = _run,
|
|
310
|
+
environ: Mapping[str, str] | None = None,
|
|
311
|
+
settings: Path | None = None,
|
|
312
|
+
system_prompt: str | None = None,
|
|
313
|
+
mcp_config: str | None = None,
|
|
314
|
+
) -> ClaudeResult:
|
|
315
|
+
"""worktree를 cwd로 파일 도구(와 파이프라인 도구)를 준 claude를 한 번 실행한다. 셸을 거치지
|
|
316
|
+
않는다.
|
|
317
|
+
|
|
318
|
+
settings는 파이프라인이 쓴 설정 파일(경로 감시 훅)이다. `--restricted`는 사용자·저장소의 설정을
|
|
319
|
+
읽지 않지만 `--settings`로 넘긴 파일은 읽는다 (2.1.328에서 확인).
|
|
320
|
+
system_prompt는 파이프라인의 지시다(`--append-system-prompt`, 8.4). prompt에는 자료만 넣는다.
|
|
321
|
+
mcp_config가 있으면 파이프라인 도구 서버 하나를 붙인 `fix_tools` 모양이다.
|
|
322
|
+
"""
|
|
323
|
+
shape: CallShape = "file_tools" if mcp_config is None else "fix_tools"
|
|
324
|
+
extra: tuple[str, ...] = () if settings is None else ("--settings", str(settings))
|
|
325
|
+
if system_prompt is not None:
|
|
326
|
+
_check_system_prompt(system_prompt)
|
|
327
|
+
extra += ("--append-system-prompt", system_prompt)
|
|
328
|
+
if mcp_config is not None:
|
|
329
|
+
extra += ("--mcp-config", mcp_config)
|
|
330
|
+
env = claude_env(environ)
|
|
331
|
+
if mcp_config is not None:
|
|
332
|
+
env["MCP_TOOL_TIMEOUT"] = MCP_TOOL_TIMEOUT_MS
|
|
333
|
+
args = build_args(shape, model, max_budget_usd, extra)
|
|
334
|
+
try:
|
|
335
|
+
watch = _watch_for(shape)
|
|
336
|
+
proc = runner(args, prompt, worktree, env, timeout, watch)
|
|
337
|
+
except subprocess.TimeoutExpired:
|
|
338
|
+
return _failure(AIErrorKind.TIMEOUT, f"{timeout:g}초 안에 끝나지 않음")
|
|
339
|
+
except ToolListMismatch as e:
|
|
340
|
+
log.error("claude 수정 호출을 중단함: %s", e)
|
|
341
|
+
return _failure(AIErrorKind.TOOLS, str(e))
|
|
342
|
+
except OSError as e:
|
|
343
|
+
return _failure(AIErrorKind.LAUNCH, str(e))
|
|
344
|
+
result = parse_output(proc.stdout, proc.returncode, proc.stderr, shape)
|
|
345
|
+
if result.error == AIErrorKind.TOOLS:
|
|
346
|
+
log.error("claude 수정 호출의 도구 목록 확인 실패: %s", result.detail)
|
|
347
|
+
return result
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@dataclass(frozen=True)
|
|
351
|
+
class StructuredResult:
|
|
352
|
+
"""도구 없는 호출의 결과. ok이면 data에 스키마로 받은 객체가 있다 (형식 확인은 부른 쪽이 한다).
|
|
353
|
+
|
|
354
|
+
model_id는 별칭이 가리킨 전체 모델 id(`modelUsage`의 키)다. 모르면 "".
|
|
355
|
+
input_tokens는 캐시 생성·읽기를 합친 실제 입력이다. 모르면 None.
|
|
356
|
+
tool_uses(목록 안 도구를 부른 횟수, 구조화 출력은 빼고)와 reads(모델이 읽기 도구에 준 경로.
|
|
357
|
+
cwd 기준이고 cwd 자체는 ".")는 읽기 도구를 준 호출(`read_tools`)에서만 찬다.
|
|
358
|
+
"""
|
|
359
|
+
|
|
360
|
+
ok: bool
|
|
361
|
+
error: AIErrorKind | None
|
|
362
|
+
data: Mapping[str, object] | None
|
|
363
|
+
model_id: str
|
|
364
|
+
input_tokens: int | None
|
|
365
|
+
output_tokens: int | None
|
|
366
|
+
cost_usd: float | None
|
|
367
|
+
permission_denials: int
|
|
368
|
+
detail: str = ""
|
|
369
|
+
tool_uses: int = 0
|
|
370
|
+
reads: tuple[str, ...] = ()
|
|
371
|
+
unexpected_tools: tuple[tuple[str, int], ...] = () # 목록 밖 도구의 (이름, 횟수)
|
|
372
|
+
num_turns: int = 0
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def run_structured(
|
|
376
|
+
prompt: str,
|
|
377
|
+
*,
|
|
378
|
+
system_prompt: str,
|
|
379
|
+
schema: Mapping[str, object],
|
|
380
|
+
model: str,
|
|
381
|
+
max_budget_usd: float,
|
|
382
|
+
timeout: float = DEFAULT_TIMEOUT_S,
|
|
383
|
+
runner: Runner = _run,
|
|
384
|
+
environ: Mapping[str, str] | None = None,
|
|
385
|
+
read_in: ReadFolder | None = None,
|
|
386
|
+
max_tool_uses: int | None = None,
|
|
387
|
+
) -> StructuredResult:
|
|
388
|
+
"""claude를 한 번 실행하고 스키마에 맞춘 JSON 객체를 받는다 (8.4).
|
|
389
|
+
|
|
390
|
+
파이프라인의 지시는 system_prompt(--append-system-prompt)로만, 믿지 않는 자료는 prompt(표준
|
|
391
|
+
입력)로만 넘긴다. read_in이 없으면 도구 없이(`no_tools`) 부르고, cwd는 이 호출만의 빈 임시
|
|
392
|
+
폴더라 저장소의 파일·설정이 보이지 않는다. read_in이 있으면 그 폴더를 cwd로 읽기 도구 셋만
|
|
393
|
+
주고(`read_tools`) 경로 감시 훅의 설정을 `--settings`로 넘긴다. 훅이 돌았는지는 폴더를 연 쪽
|
|
394
|
+
(`workdir.reading_folder`)이 확인한다. max_tool_uses는 읽기 도구를 부를 수 있는 횟수이고,
|
|
395
|
+
넘으면 프로세스를 멈추고 TOOL_CAP으로 돌려준다.
|
|
396
|
+
"""
|
|
397
|
+
_check_system_prompt(system_prompt)
|
|
398
|
+
shape: CallShape = "no_tools" if read_in is None else "read_tools"
|
|
399
|
+
extra: tuple[str, ...] = () if read_in is None else ("--settings", str(read_in.settings))
|
|
400
|
+
extra += ("--append-system-prompt", system_prompt, "--json-schema", json.dumps(schema))
|
|
401
|
+
args = build_args(shape, model, max_budget_usd, extra)
|
|
402
|
+
watch = _watch_for(shape, None if read_in is None else max_tool_uses)
|
|
403
|
+
try:
|
|
404
|
+
if read_in is None:
|
|
405
|
+
with tempfile.TemporaryDirectory(prefix="claude-no-tools-") as empty:
|
|
406
|
+
proc = runner(args, prompt, Path(empty), claude_env(environ), timeout, watch)
|
|
407
|
+
else:
|
|
408
|
+
proc = runner(args, prompt, read_in.work, claude_env(environ), timeout, watch)
|
|
409
|
+
except subprocess.TimeoutExpired:
|
|
410
|
+
return _structured_failure(AIErrorKind.TIMEOUT, f"{timeout:g}초 안에 끝나지 않음")
|
|
411
|
+
except ToolListMismatch as e:
|
|
412
|
+
log.error("claude 구조화 출력 호출(%s)을 중단함: %s", shape, e)
|
|
413
|
+
return _structured_failure(AIErrorKind.TOOLS, str(e))
|
|
414
|
+
except ToolCapReached as e:
|
|
415
|
+
log.warning("claude 읽기 호출을 중단함: %s", e)
|
|
416
|
+
return _structured_failure(AIErrorKind.TOOL_CAP, str(e))
|
|
417
|
+
except OSError as e:
|
|
418
|
+
return _structured_failure(AIErrorKind.LAUNCH, str(e))
|
|
419
|
+
cwd = None if read_in is None else read_in.work
|
|
420
|
+
result = parse_structured_output(proc.stdout, proc.returncode, proc.stderr, shape, cwd)
|
|
421
|
+
if result.unexpected_tools:
|
|
422
|
+
log.warning("claude가 목록 밖 도구를 부르려 함: %s", result.unexpected_tools)
|
|
423
|
+
return result
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _check_system_prompt(system_prompt: str) -> None:
|
|
427
|
+
if not system_prompt or system_prompt.startswith("-"):
|
|
428
|
+
raise ValueError("시스템 프롬프트가 비었거나 '-'로 시작한다")
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def parse_output(
|
|
432
|
+
stdout: str, returncode: int, stderr: str = "", shape: CallShape = "file_tools"
|
|
433
|
+
) -> ClaudeResult:
|
|
434
|
+
"""stream-json 출력을 읽는다. 실패해도 결과 줄에 있는 비용과 거부 목록은 남긴다."""
|
|
435
|
+
init, data = _events(stdout)
|
|
436
|
+
if data is None:
|
|
437
|
+
return _failure(AIErrorKind.BAD_JSON, _tail(stderr or stdout), returncode=returncode)
|
|
438
|
+
error, detail = _checked_status(init, shape, data, returncode)
|
|
439
|
+
text = data.get("result")
|
|
440
|
+
input_tokens, output_tokens = _usage(data.get("usage"))
|
|
441
|
+
return ClaudeResult(
|
|
442
|
+
ok=error is None,
|
|
443
|
+
error=error,
|
|
444
|
+
cost_usd=_cost(data),
|
|
445
|
+
num_turns=_turns(data),
|
|
446
|
+
permission_denials=_denials(data.get("permission_denials")),
|
|
447
|
+
text=text if isinstance(text, str) else "",
|
|
448
|
+
detail=detail,
|
|
449
|
+
unexpected_tools=_unexpected_tools(stdout, shape),
|
|
450
|
+
tool_uses=_expected_tool_uses(stdout, shape),
|
|
451
|
+
model_id=_model_id(data.get("modelUsage")),
|
|
452
|
+
input_tokens=input_tokens,
|
|
453
|
+
output_tokens=output_tokens,
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def parse_structured_output(
|
|
458
|
+
stdout: str,
|
|
459
|
+
returncode: int,
|
|
460
|
+
stderr: str = "",
|
|
461
|
+
shape: CallShape = "no_tools",
|
|
462
|
+
cwd: Path | None = None,
|
|
463
|
+
) -> StructuredResult:
|
|
464
|
+
"""`--json-schema`를 준 호출의 출력. `structured_output`, 없으면 `result`를 JSON으로 읽는다.
|
|
465
|
+
|
|
466
|
+
cwd가 있으면(읽기 도구를 준 호출) 모델이 읽은 경로를 cwd 기준으로 모은다."""
|
|
467
|
+
init, data = _events(stdout)
|
|
468
|
+
if data is None:
|
|
469
|
+
detail = f"종료 코드 {returncode}: {_tail(stderr or stdout)}"
|
|
470
|
+
return _structured_failure(AIErrorKind.BAD_JSON, detail)
|
|
471
|
+
error, detail = _checked_status(init, shape, data, returncode)
|
|
472
|
+
answer = None
|
|
473
|
+
if error is None:
|
|
474
|
+
answer = _answer(data)
|
|
475
|
+
if answer is None:
|
|
476
|
+
error, detail = AIErrorKind.BAD_JSON, "구조화 출력이 없거나 JSON 객체가 아님"
|
|
477
|
+
input_tokens, output_tokens = _usage(data.get("usage"))
|
|
478
|
+
return StructuredResult(
|
|
479
|
+
ok=error is None,
|
|
480
|
+
error=error,
|
|
481
|
+
data=answer,
|
|
482
|
+
model_id=_model_id(data.get("modelUsage")),
|
|
483
|
+
input_tokens=input_tokens,
|
|
484
|
+
output_tokens=output_tokens,
|
|
485
|
+
cost_usd=_cost(data),
|
|
486
|
+
permission_denials=len(_denials(data.get("permission_denials"))),
|
|
487
|
+
detail=detail,
|
|
488
|
+
tool_uses=_expected_tool_uses(stdout, shape, skip=STRUCTURED_OUTPUT_TOOL),
|
|
489
|
+
reads=() if cwd is None else read_paths(stdout, cwd),
|
|
490
|
+
unexpected_tools=_unexpected_tools(stdout, shape),
|
|
491
|
+
num_turns=_turns(data),
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _turns(data: dict) -> int:
|
|
496
|
+
turns = data.get("num_turns")
|
|
497
|
+
return turns if isinstance(turns, int) else 0
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _json_object(text: str) -> dict | None:
|
|
501
|
+
try:
|
|
502
|
+
data = json.loads(text)
|
|
503
|
+
except json.JSONDecodeError:
|
|
504
|
+
return None
|
|
505
|
+
return data if isinstance(data, dict) else None
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _events(stdout: str) -> tuple[dict | None, dict | None]:
|
|
509
|
+
"""줄마다 JSON 하나인 출력에서 (system/init, 마지막 result)를 찾는다."""
|
|
510
|
+
init, result = None, None
|
|
511
|
+
for line in stdout.splitlines():
|
|
512
|
+
event = _json_object(line)
|
|
513
|
+
if event is None:
|
|
514
|
+
continue
|
|
515
|
+
if init is None and _init_event(line) is not None:
|
|
516
|
+
init = event
|
|
517
|
+
elif event.get("type") == "result":
|
|
518
|
+
result = event
|
|
519
|
+
return init, result
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _tool_blocks(event: dict | None) -> list[dict]:
|
|
523
|
+
"""assistant 메시지 한 줄의 tool_use 블록들."""
|
|
524
|
+
message = event.get("message") if event and event.get("type") == "assistant" else None
|
|
525
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
526
|
+
return [
|
|
527
|
+
b for b in (content if isinstance(content, list) else ())
|
|
528
|
+
if isinstance(b, dict) and b.get("type") == "tool_use"
|
|
529
|
+
] # fmt: skip
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _tool_names(event: dict | None) -> list[str]:
|
|
533
|
+
return [str(b.get("name", "")) for b in _tool_blocks(event)]
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _tool_counts(stdout: str) -> dict[str, int]:
|
|
537
|
+
"""assistant 메시지의 tool_use를 도구 이름별로 센다."""
|
|
538
|
+
counts: dict[str, int] = {}
|
|
539
|
+
for line in stdout.splitlines():
|
|
540
|
+
for name in _tool_names(_json_object(line)):
|
|
541
|
+
counts[name] = counts.get(name, 0) + 1
|
|
542
|
+
return counts
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def folder_relative(path: str, cwd: Path) -> str | None:
|
|
546
|
+
"""도구 입력의 경로를 cwd 기준 경로로. 링크를 푼 실제 위치가 cwd 밖이면 None, cwd 자체는 "."."""
|
|
547
|
+
if not path or "\0" in path:
|
|
548
|
+
return None
|
|
549
|
+
root = os.path.realpath(cwd)
|
|
550
|
+
real = os.path.realpath(os.path.join(root, path))
|
|
551
|
+
if real != root and not real.startswith(root + os.sep):
|
|
552
|
+
return None
|
|
553
|
+
return Path(os.path.relpath(real, root)).as_posix()
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def read_paths(stdout: str, cwd: Path) -> tuple[str, ...]:
|
|
557
|
+
"""모델이 Read·Grep·Glob에 준 경로 (cwd 기준, 이름순, 겹침 없음). 경로가 없는 Grep·Glob은
|
|
558
|
+
cwd 전체(".")다. cwd 밖의 경로는 훅이 거부했으므로 넣지 않는다."""
|
|
559
|
+
found: set[str] = set()
|
|
560
|
+
for line in stdout.splitlines():
|
|
561
|
+
for block in _tool_blocks(_json_object(line)):
|
|
562
|
+
key = _READ_PATH_KEYS.get(str(block.get("name", "")))
|
|
563
|
+
tool_input = block.get("input")
|
|
564
|
+
if key is None or not isinstance(tool_input, dict):
|
|
565
|
+
continue
|
|
566
|
+
value = tool_input.get(key)
|
|
567
|
+
if value is None and key == "path":
|
|
568
|
+
value = "."
|
|
569
|
+
rel = folder_relative(value, cwd) if isinstance(value, str) else None
|
|
570
|
+
if rel is not None:
|
|
571
|
+
found.add(rel)
|
|
572
|
+
return tuple(sorted(found))
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _unexpected_tools(stdout: str, shape: CallShape) -> tuple[tuple[str, int], ...]:
|
|
576
|
+
"""assistant 메시지의 tool_use 중 이 모양의 목록에 없는 이름과 횟수 (이름순)."""
|
|
577
|
+
counts = _tool_counts(stdout)
|
|
578
|
+
return tuple(sorted((n, c) for n, c in counts.items() if n not in _SHAPE_TOOLS[shape]))
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _expected_tool_uses(stdout: str, shape: CallShape, skip: str = "") -> int:
|
|
582
|
+
counts = _tool_counts(stdout)
|
|
583
|
+
return sum(c for n, c in counts.items() if n in _SHAPE_TOOLS[shape] and n != skip)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _checked_status(
|
|
587
|
+
init: dict | None, shape: CallShape, data: dict, returncode: int
|
|
588
|
+
) -> tuple[AIErrorKind | None, str]:
|
|
589
|
+
"""호출의 상태에 도구 목록 확인을 더한다. 실행 중 확인(watch)을 거치지 않은 출력도 걸린다.
|
|
590
|
+
|
|
591
|
+
init이 없는 실패(로그인 풀림 등)는 원래 오류를 남긴다. 성공인데 init이 없으면 확인하지 못한
|
|
592
|
+
것이므로 오류다.
|
|
593
|
+
"""
|
|
594
|
+
error, detail = _status(data, returncode)
|
|
595
|
+
if init is not None:
|
|
596
|
+
problem = tool_list_problem(init, shape)
|
|
597
|
+
else:
|
|
598
|
+
problem = None if error is not None else "system/init이 없어 도구 목록을 확인하지 못함"
|
|
599
|
+
return (AIErrorKind.TOOLS, problem) if problem is not None else (error, detail)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _status(data: dict, returncode: int) -> tuple[AIErrorKind | None, str]:
|
|
603
|
+
"""종료 코드와 is_error를 같이 본다. 없는 모델 이름도 subtype은 "success"로 끝난다."""
|
|
604
|
+
subtype = str(data.get("subtype", ""))
|
|
605
|
+
if "budget" in subtype:
|
|
606
|
+
error = AIErrorKind.BUDGET
|
|
607
|
+
elif returncode != 0 or data.get("is_error") is True:
|
|
608
|
+
error = AIErrorKind.EXIT
|
|
609
|
+
else:
|
|
610
|
+
return None, ""
|
|
611
|
+
return error, f"종료 코드 {returncode}, subtype {subtype}"
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _cost(data: dict) -> float | None:
|
|
615
|
+
cost = data.get("total_cost_usd")
|
|
616
|
+
return float(cost) if isinstance(cost, int | float) else None
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _answer(data: dict) -> dict | None:
|
|
620
|
+
structured = data.get("structured_output")
|
|
621
|
+
if isinstance(structured, dict):
|
|
622
|
+
return structured
|
|
623
|
+
text = data.get("result")
|
|
624
|
+
return _json_object(text) if isinstance(text, str) else None
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _usage(raw: object) -> tuple[int | None, int | None]:
|
|
628
|
+
if not isinstance(raw, dict):
|
|
629
|
+
return None, None
|
|
630
|
+
parts = [raw.get(k) for k in _INPUT_TOKEN_KEYS]
|
|
631
|
+
numbers = [p for p in parts if isinstance(p, int)]
|
|
632
|
+
output = raw.get("output_tokens")
|
|
633
|
+
return (sum(numbers) if numbers else None), (output if isinstance(output, int) else None)
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _model_id(raw: object) -> str:
|
|
637
|
+
"""`modelUsage`의 키 중 출력이 가장 많은 모델. 같으면 이름순으로 앞의 것."""
|
|
638
|
+
if not isinstance(raw, dict) or not raw:
|
|
639
|
+
return ""
|
|
640
|
+
|
|
641
|
+
def output(name: str) -> int:
|
|
642
|
+
entry = raw[name]
|
|
643
|
+
tokens = entry.get("outputTokens") if isinstance(entry, dict) else None
|
|
644
|
+
return tokens if isinstance(tokens, int) else 0
|
|
645
|
+
|
|
646
|
+
return min(raw, key=lambda name: (-output(name), name))
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _denials(raw: object) -> tuple[PermissionDenial, ...]:
|
|
650
|
+
if not isinstance(raw, list):
|
|
651
|
+
return ()
|
|
652
|
+
return tuple(
|
|
653
|
+
PermissionDenial(
|
|
654
|
+
tool_name=str(d.get("tool_name", "")),
|
|
655
|
+
tool_input=d["tool_input"] if isinstance(d.get("tool_input"), dict) else {},
|
|
656
|
+
)
|
|
657
|
+
for d in raw
|
|
658
|
+
if isinstance(d, dict)
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _failure(kind: AIErrorKind, detail: str, returncode: int | None = None) -> ClaudeResult:
|
|
663
|
+
if returncode is not None:
|
|
664
|
+
detail = f"종료 코드 {returncode}: {detail}"
|
|
665
|
+
return ClaudeResult(
|
|
666
|
+
ok=False,
|
|
667
|
+
error=kind,
|
|
668
|
+
cost_usd=None,
|
|
669
|
+
num_turns=0,
|
|
670
|
+
permission_denials=(),
|
|
671
|
+
text="",
|
|
672
|
+
detail=detail,
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def _structured_failure(kind: AIErrorKind, detail: str) -> StructuredResult:
|
|
677
|
+
return StructuredResult(
|
|
678
|
+
ok=False, error=kind, data=None, model_id="", input_tokens=None, output_tokens=None,
|
|
679
|
+
cost_usd=None, permission_denials=0, detail=detail,
|
|
680
|
+
) # fmt: skip
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _tail(text: str, limit: int = 500) -> str:
|
|
684
|
+
return text.strip()[-limit:]
|