Repository navigation
Expand file tree
/
Copy pathrun_codex_subagent_file_writer.py
More file actions
261 lines (229 loc) · 9.38 KB
/
Copy pathrun_codex_subagent_file_writer.py
File metadata and controls
261 lines (229 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python3
"""Watch subagent_request_*.json files and write Codex decision responses.
This is the external writer for the `subagent_file` transport. It reads the
request JSON emitted by CodexBrain, calls a concrete Codex transport
(`api`, `cli`, or future SDK adapters), and writes either:
* subagent_response_###.txt on success, or
* subagent_error_###.txt plus subagent_health_###.json on transport failure.
The writer preserves prompt/response/stdout/stderr/cmd artifacts next to the
request so transport failures stay separate from robot skill failures.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
import time
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from lmvs.codex_transports.factory import build_codex_transport
from lmvs.codex_transports.health import classify_transport_health
from lmvs.system_contracts import CodexDecisionRequest
REQUEST_RE = re.compile(r"subagent_request_(\d+)\.json$")
def _read_json(path: Path) -> Dict[str, Any]:
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError(f"{path} does not contain a JSON object")
return data
def _request_index(path: Path, payload: Dict[str, Any]) -> int:
raw_turn = payload.get("turn")
try:
if raw_turn is not None:
return int(raw_turn)
except Exception:
pass
match = REQUEST_RE.search(path.name)
if match:
return int(match.group(1))
return 0
def _paths(request_path: Path, payload: Dict[str, Any]) -> Dict[str, Path]:
idx = _request_index(request_path, payload)
response = payload.get("response_path")
response_path = (
Path(str(response))
if response
else request_path.with_name(f"subagent_response_{idx:03d}.txt")
)
error = payload.get("error_path")
health = payload.get("health_path")
return {
"response": response_path,
"error": Path(str(error)) if error else request_path.with_name(f"subagent_error_{idx:03d}.txt"),
"health": Path(str(health)) if health else request_path.with_name(f"subagent_health_{idx:03d}.json"),
"writer_prefix": request_path.with_name(f"subagent_writer_{idx:03d}"),
}
def _pending_requests(exchange_dir: Path, *, retry_errors: bool = False) -> Iterable[Path]:
for request_path in sorted(exchange_dir.glob("subagent_request_*.json")):
try:
payload = _read_json(request_path)
except Exception:
continue
paths = _paths(request_path, payload)
response_path = paths["response"]
error_path = paths["error"]
if response_path.exists() and response_path.read_text(errors="replace").strip():
continue
if error_path.exists() and not retry_errors:
continue
yield request_path
def _image_paths(payload: Dict[str, Any]) -> List[str]:
images = payload.get("images") or []
if not isinstance(images, list):
return []
return [str(path) for path in images if path and os.path.exists(str(path))]
def _transport_health(result: Any) -> Dict[str, Any]:
usage = getattr(result.response, "usage", {}) or {}
health = usage.get("transport_health")
if isinstance(health, dict):
return health
return classify_transport_health(
stdout=getattr(result, "stdout", ""),
stderr=getattr(result, "stderr", ""),
response=getattr(result, "text", ""),
error=getattr(result, "error", ""),
)
def _write_artifacts(
*,
request_path: Path,
payload: Dict[str, Any],
result: Any,
paths: Dict[str, Path],
) -> None:
prefix = paths["writer_prefix"]
health = _transport_health(result)
stderr_text = str(getattr(result, "stderr", "") or getattr(result, "error", ""))
if health:
stderr_text = (
stderr_text
+ "\ntransport_health="
+ json.dumps(health, sort_keys=True)
).strip()
prefix.with_name(prefix.name + "_prompt.txt").write_text(
str(payload.get("prompt") or ""),
encoding="utf-8",
)
prefix.with_name(prefix.name + "_response.txt").write_text(
str(getattr(result, "text", "") or ""),
encoding="utf-8",
)
prefix.with_name(prefix.name + "_stdout.txt").write_text(
str(getattr(result, "stdout", "") or ""),
encoding="utf-8",
)
prefix.with_name(prefix.name + "_stderr.txt").write_text(
stderr_text,
encoding="utf-8",
)
prefix.with_name(prefix.name + "_cmd.txt").write_text(
" ".join(repr(item) for item in getattr(result, "command", []) or []),
encoding="utf-8",
)
result_payload = result.to_dict() if hasattr(result, "to_dict") else {}
result_payload["request_path"] = str(request_path)
result_payload["transport_health"] = health
paths["health"].write_text(
json.dumps(result_payload, indent=2, sort_keys=True),
encoding="utf-8",
)
def handle_request(request_path: Path, args: argparse.Namespace) -> int:
payload = _read_json(request_path)
paths = _paths(request_path, payload)
paths["response"].parent.mkdir(parents=True, exist_ok=True)
prompt = str(payload.get("prompt") or "")
model = args.codex_api_model or str(payload.get("model") or "")
timeout_s = int(payload.get("timeout_s") or args.request_timeout_s)
transport = build_codex_transport(
args.transport,
codex_bin=args.codex_bin,
sandbox=args.sandbox,
workdir=args.workdir,
max_retries=args.max_retries,
http_base_url=args.codex_api_base_url,
http_credential_env=args.codex_api_key_env,
http_model=model or None,
)
result = transport.call(
CodexDecisionRequest(
prompt=prompt,
image_paths=_image_paths(payload),
output_schema=payload.get("output_schema") or {},
suite=payload.get("suite"),
task_id=payload.get("task_id"),
init_state=payload.get("init_state"),
turn=payload.get("turn"),
transport=args.transport,
timeout_s=timeout_s,
)
)
_write_artifacts(
request_path=request_path,
payload=payload,
result=result,
paths=paths,
)
if result.ok and str(result.text or "").strip():
paths["response"].write_text(str(result.text).strip() + "\n", encoding="utf-8")
if paths["error"].exists():
paths["error"].unlink()
return 0
error_text = str(result.error or result.stderr or "Codex writer transport failed")
paths["error"].write_text(error_text + "\n", encoding="utf-8")
return 1
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("exchange_dir", type=Path)
parser.add_argument(
"--transport",
choices=("api", "cli", "sdk_python", "sdk_typescript"),
default=os.environ.get("LMVS_SUBAGENT_WRITER_TRANSPORT", "api"),
)
parser.add_argument("--codex-bin", default=os.environ.get("CODEX_BIN", "codex"))
parser.add_argument("--sandbox", default="danger-full-access")
parser.add_argument("--workdir", default=str(ROOT))
parser.add_argument("--codex-api-base-url", default=os.environ.get("CODEX_API_BASE_URL"))
parser.add_argument("--codex-api-key-env", default="CODEX_API_KEY")
parser.add_argument("--codex-api-model", default=os.environ.get("CODEX_API_MODEL"))
parser.add_argument("--max-retries", type=int, default=1)
parser.add_argument("--request-timeout-s", type=int, default=240)
parser.add_argument("--poll-interval-s", type=float, default=0.25)
parser.add_argument("--wait-timeout-s", type=float, default=0.0)
parser.add_argument("--max-requests", type=int, default=0)
parser.add_argument("--once", action="store_true")
parser.add_argument("--retry-errors", action="store_true")
args = parser.parse_args()
args.exchange_dir.mkdir(parents=True, exist_ok=True)
processed = 0
failures = 0
deadline: Optional[float] = None
if args.wait_timeout_s > 0:
deadline = time.time() + float(args.wait_timeout_s)
while True:
pending = list(_pending_requests(args.exchange_dir, retry_errors=args.retry_errors))
if pending:
for request_path in pending:
code = handle_request(request_path, args)
processed += 1
failures += 1 if code else 0
print(
f"processed {request_path} status={'failed' if code else 'ok'}",
flush=True,
)
if args.once or (args.max_requests and processed >= args.max_requests):
return 1 if failures else 0
elif args.once:
if deadline is not None and time.time() < deadline:
time.sleep(max(0.01, float(args.poll_interval_s)))
continue
print(f"no pending subagent requests in {args.exchange_dir}", file=sys.stderr)
return 2
elif args.max_requests and processed >= args.max_requests:
return 1 if failures else 0
if deadline is not None and time.time() >= deadline:
return 1 if failures else 0
time.sleep(max(0.01, float(args.poll_interval_s)))
if __name__ == "__main__":
raise SystemExit(main())