agent-bios 0.19.4 → 0.20.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/DEPENDENCIES.md +19 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +4 -3
- package/claude/guides/gpt-prompting.md +235 -136
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +4 -3
- package/codex/guides/gpt-prompting.md +235 -136
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.20.0.md +102 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +17 -7
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +38 -7
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
"""The Codex app-server as agent-bios speaks it: one client, the names it uses, and two checks.
|
|
2
|
+
|
|
3
|
+
The vendor marks the app-server and its schema command experimental, and agent-bios relies on them for
|
|
4
|
+
private activation and for codex-run's context evidence (D-20261102-d8310f). So:
|
|
5
|
+
|
|
6
|
+
- Every method, field and enum value the code sends or reads is listed once, in USED, and checked per
|
|
7
|
+
installed Codex version against the protocol schema that version generates offline
|
|
8
|
+
(`codex app-server generate-json-schema --experimental`). A missing name refuses by name and
|
|
9
|
+
version. The verdict is kept per version under `<state dir>/codex-protocol/` when the caller names
|
|
10
|
+
a state directory, and in the process otherwise.
|
|
11
|
+
- Every result the code reads is checked for its shape, in SHAPES, before it is read; a wrong or
|
|
12
|
+
missing shape refuses naming the method and the field. The effective `developer_instructions`
|
|
13
|
+
is read only through developer_instructions(), which holds it to the layers that state it
|
|
14
|
+
(D-20261102-efc529): null is the user's "none", and "" the user's own empty value.
|
|
15
|
+
- The client reads the server on a thread into a queue. A select() on the text stream missed a
|
|
16
|
+
line Python had already buffered, so a notification and the response in one write left the
|
|
17
|
+
response unread until the timeout; on POSIX the thread reads the descriptor itself, keeping its
|
|
18
|
+
own partial line, so nothing is buffered where select() cannot see it.
|
|
19
|
+
- The server runs in a process group of its own and is ended with that group (Owned), which
|
|
20
|
+
session-distill's dispatcher also uses for its server-policy probe (author-side imports shipped,
|
|
21
|
+
never the reverse).
|
|
22
|
+
|
|
23
|
+
Loaded by path: beside codex_frame_filter.py, deployed together, and by compose from the package's
|
|
24
|
+
wrappers/ directory (host_platform.codex_protocol_for).
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import atexit
|
|
29
|
+
import contextlib
|
|
30
|
+
import hashlib
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
import pathlib
|
|
34
|
+
import queue
|
|
35
|
+
import re
|
|
36
|
+
import select
|
|
37
|
+
import shutil
|
|
38
|
+
import signal
|
|
39
|
+
import subprocess
|
|
40
|
+
import sys
|
|
41
|
+
import tempfile
|
|
42
|
+
import threading
|
|
43
|
+
import time
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ProtocolError(Exception):
|
|
47
|
+
"""The app-server, its schema, or a result is not what agent-bios was checked against."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# (method, side, path). A path walks object fields by name, `[]` into array items, and a last
|
|
51
|
+
# `=value` names an enum value the code compares against.
|
|
52
|
+
USED = (
|
|
53
|
+
("initialize", "params", "clientInfo.name"),
|
|
54
|
+
("initialize", "params", "clientInfo.title"),
|
|
55
|
+
("initialize", "params", "clientInfo.version"),
|
|
56
|
+
("initialize", "params", "capabilities.experimentalApi"),
|
|
57
|
+
("hooks/list", "params", "cwds"),
|
|
58
|
+
("hooks/list", "result", "data[].errors"),
|
|
59
|
+
("hooks/list", "result", "data[].hooks[].eventName"),
|
|
60
|
+
("hooks/list", "result", "data[].hooks[].matcher"),
|
|
61
|
+
("hooks/list", "result", "data[].hooks[].command"),
|
|
62
|
+
("hooks/list", "result", "data[].hooks[].source=sessionFlags"),
|
|
63
|
+
("hooks/list", "result", "data[].hooks[].enabled"),
|
|
64
|
+
("hooks/list", "result", "data[].hooks[].trustStatus=trusted"),
|
|
65
|
+
("config/read", "params", "cwd"),
|
|
66
|
+
("config/read", "params", "includeLayers"),
|
|
67
|
+
("config/read", "result", "config.developer_instructions"),
|
|
68
|
+
("config/read", "result", "config.features"),
|
|
69
|
+
("config/read", "result", "layers[].name.type=sessionFlags"),
|
|
70
|
+
("config/read", "result", "layers[].config"),
|
|
71
|
+
("thread/start", "params", "cwd"),
|
|
72
|
+
("thread/start", "params", "developerInstructions"),
|
|
73
|
+
("thread/start", "params", "ephemeral"),
|
|
74
|
+
("thread/start", "params", "experimentalRawEvents"),
|
|
75
|
+
("thread/start", "params", "model"),
|
|
76
|
+
("thread/start", "params", "approvalPolicy"),
|
|
77
|
+
("thread/start", "params", "sandbox"),
|
|
78
|
+
("thread/start", "params", "config"),
|
|
79
|
+
("thread/start", "result", "thread.id"),
|
|
80
|
+
("thread/start", "result", "thread.path"),
|
|
81
|
+
("thread/start", "result", "instructionSources"),
|
|
82
|
+
("thread/start", "result", "model"),
|
|
83
|
+
("thread/start", "result", "cwd"),
|
|
84
|
+
("thread/start", "result", "reasoningEffort"),
|
|
85
|
+
("thread/inject_items", "params", "threadId"),
|
|
86
|
+
("thread/inject_items", "params", "items"),
|
|
87
|
+
("thread/read", "params", "threadId"),
|
|
88
|
+
("thread/read", "params", "includeTurns"),
|
|
89
|
+
("thread/read", "result", "thread.id"),
|
|
90
|
+
)
|
|
91
|
+
USED_DIGEST = hashlib.sha256(json.dumps(USED).encode()).hexdigest()
|
|
92
|
+
|
|
93
|
+
# Per reading: (path, accepted types, required). A path's `[]` checks every item.
|
|
94
|
+
SHAPES = {
|
|
95
|
+
"hooks/list": (
|
|
96
|
+
("data", "list", True), ("data[]", "dict", True), ("data[].errors", "list", True),
|
|
97
|
+
("data[].hooks", "list", True), ("data[].hooks[]", "dict", True),
|
|
98
|
+
("data[].hooks[].eventName", "str", False), ("data[].hooks[].matcher", "str|null", False),
|
|
99
|
+
("data[].hooks[].command", "str", False), ("data[].hooks[].source", "str", False),
|
|
100
|
+
("data[].hooks[].enabled", "bool", False), ("data[].hooks[].trustStatus", "str", False),
|
|
101
|
+
),
|
|
102
|
+
"config/read": (
|
|
103
|
+
("config", "dict", True), ("config.developer_instructions", "str|null", True),
|
|
104
|
+
("config.features", "dict", False), ("config.features.hooks", "bool", False),
|
|
105
|
+
("layers", "list|null", False), ("layers[]", "dict", True), ("layers[].name", "dict", True),
|
|
106
|
+
("layers[].name.type", "str", True), ("layers[].config", "dict", False),
|
|
107
|
+
("layers[].config.developer_instructions", "str|null", False),
|
|
108
|
+
),
|
|
109
|
+
"thread/start": (("thread", "dict", True), ("thread.id", "str", True), ("thread.path", "str|null", False)),
|
|
110
|
+
"thread/start#sources": (
|
|
111
|
+
("instructionSources", "list", True), ("instructionSources[]", "str", True), ("model", "str", False),
|
|
112
|
+
("cwd", "str", False), ("reasoningEffort", "str|null", False),
|
|
113
|
+
),
|
|
114
|
+
"thread/read": (("thread", "dict", True), ("thread.id", "str", True)),
|
|
115
|
+
"thread/inject_items": (),
|
|
116
|
+
"initialize": (),
|
|
117
|
+
}
|
|
118
|
+
TYPES = {"str": str, "bool": bool, "list": list, "dict": dict, "null": type(None)}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
_ABSENT = object()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _steps(path):
|
|
125
|
+
return [step for part in path.split(".") for step in re.findall(r"[^\[\]]+|\[\]", part)]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def shape_problems(reading, result):
|
|
129
|
+
"""What in `result` does not have the shape SHAPES[reading] declares, as "<path>: <problem>"."""
|
|
130
|
+
problems = []
|
|
131
|
+
|
|
132
|
+
def walk(value, steps, where, kinds, required):
|
|
133
|
+
if not steps:
|
|
134
|
+
if value is _ABSENT:
|
|
135
|
+
if required:
|
|
136
|
+
problems.append(f"{where}: missing")
|
|
137
|
+
elif not isinstance(value, tuple(TYPES[k] for k in kinds)) or (isinstance(value, bool) and "bool" not in kinds):
|
|
138
|
+
problems.append(f"{where}: {type(value).__name__}, not {'|'.join(kinds)}")
|
|
139
|
+
return
|
|
140
|
+
if value is _ABSENT or value is None:
|
|
141
|
+
return
|
|
142
|
+
step, rest = steps[0], steps[1:]
|
|
143
|
+
if step == "[]":
|
|
144
|
+
if isinstance(value, list):
|
|
145
|
+
for index, item in enumerate(value):
|
|
146
|
+
walk(item, rest, f"{where}[{index}]", kinds, required)
|
|
147
|
+
elif isinstance(value, dict):
|
|
148
|
+
walk(value.get(step, _ABSENT), rest, f"{where}.{step}" if where else step, kinds, required)
|
|
149
|
+
|
|
150
|
+
if not isinstance(result, dict):
|
|
151
|
+
return [f"result: {type(result).__name__}, not dict"]
|
|
152
|
+
for path, kinds, required in SHAPES[reading]:
|
|
153
|
+
walk(result, _steps(path), "", kinds.split("|"), required)
|
|
154
|
+
return problems
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def check_result(method, result, reading=None):
|
|
158
|
+
"""Raise ProtocolError naming every field of `result` whose shape is not the declared one. A
|
|
159
|
+
reading SHAPES does not declare is refused too: what the code reads has one owner, here."""
|
|
160
|
+
if (reading or method) not in SHAPES:
|
|
161
|
+
raise ProtocolError(f"app-server {method}: agent-bios declares no shape for {reading or method} "
|
|
162
|
+
f"(wrappers/codex_protocol.py SHAPES)")
|
|
163
|
+
problems = shape_problems(reading or method, result)
|
|
164
|
+
if problems:
|
|
165
|
+
raise ProtocolError(f"app-server {method} answered in a shape agent-bios does not read: {'; '.join(problems)}")
|
|
166
|
+
return result
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def developer_instructions(result):
|
|
170
|
+
"""The effective developer instructions a shape-checked config/read `result`, asked with
|
|
171
|
+
includeLayers, states: text, '' for none. Held to the layers (D-20261102-efc529, measured on
|
|
172
|
+
codex-cli 0.163.0: the key is always sent, null when no layer sets it, and the highest layer
|
|
173
|
+
that sets it wins, so a higher layer's "" over a lower layer's text is the user's choice): null
|
|
174
|
+
only when no layer sets a string, a string only when some layer sets that string. Anything else,
|
|
175
|
+
or no layers, refuses by name: an effective value that drops text a layer holds would replace
|
|
176
|
+
the user's developer instructions with nothing. So does a layer that reports no `config` (the
|
|
177
|
+
schema requires one): an unreported configuration is not an empty one, and only a reported
|
|
178
|
+
config without the field says that layer sets none. A layer's `config` is open in the generated
|
|
179
|
+
schema (`true`), so its field is held by SHAPES and this check, not by USED."""
|
|
180
|
+
value = result["config"]["developer_instructions"]
|
|
181
|
+
layers = result.get("layers")
|
|
182
|
+
if not isinstance(layers, list) or not layers:
|
|
183
|
+
raise ProtocolError("app-server config/read: no layers to hold config.developer_instructions to, "
|
|
184
|
+
"though agent-bios asked for them (includeLayers)")
|
|
185
|
+
unreported = [f"{layer['name']['type']} (layer {index})" for index, layer in enumerate(layers)
|
|
186
|
+
if not isinstance(layer.get("config"), dict)]
|
|
187
|
+
if unreported:
|
|
188
|
+
raise ProtocolError(f"app-server config/read: the {', '.join(unreported)} layer reported no config, so "
|
|
189
|
+
f"whether it sets developer_instructions is unknown")
|
|
190
|
+
stated = {}
|
|
191
|
+
for layer in layers:
|
|
192
|
+
held = layer["config"].get("developer_instructions")
|
|
193
|
+
if isinstance(held, str):
|
|
194
|
+
stated.setdefault(held, []).append(layer["name"]["type"])
|
|
195
|
+
if value is None and stated:
|
|
196
|
+
raise ProtocolError(f"app-server config/read: config.developer_instructions is null while the "
|
|
197
|
+
f"{', '.join(t for types in stated.values() for t in types)} layer(s) set it")
|
|
198
|
+
if isinstance(value, str) and value not in stated:
|
|
199
|
+
raise ProtocolError(f"app-server config/read: config.developer_instructions is a value no layer sets "
|
|
200
|
+
f"({len(value)} characters; layers setting it: "
|
|
201
|
+
f"{', '.join(t for types in stated.values() for t in types) or 'none'})")
|
|
202
|
+
return value or ""
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def schema_missing(bundle):
|
|
206
|
+
"""The USED names the generated schema `bundle` (codex_app_server_protocol.schemas.json, parsed)
|
|
207
|
+
does not carry. A step into an open part of the schema (`true`, or additionalProperties) is not
|
|
208
|
+
a missing name: the schema allows it and names nothing to check."""
|
|
209
|
+
def resolve(ref):
|
|
210
|
+
node = bundle
|
|
211
|
+
for part in ref.lstrip("#/").split("/"):
|
|
212
|
+
node = node[part]
|
|
213
|
+
return node
|
|
214
|
+
|
|
215
|
+
def alternatives(node, seen=()):
|
|
216
|
+
if node is True or node == {}:
|
|
217
|
+
return [True]
|
|
218
|
+
if not isinstance(node, dict):
|
|
219
|
+
return []
|
|
220
|
+
if "$ref" in node:
|
|
221
|
+
return [] if node["$ref"] in seen else alternatives(resolve(node["$ref"]), seen + (node["$ref"],))
|
|
222
|
+
found = [node]
|
|
223
|
+
for key in ("anyOf", "oneOf", "allOf"):
|
|
224
|
+
for sub in node.get(key, []):
|
|
225
|
+
found += alternatives(sub, seen)
|
|
226
|
+
return found
|
|
227
|
+
|
|
228
|
+
def step(nodes, name):
|
|
229
|
+
nexts = []
|
|
230
|
+
for node in nodes:
|
|
231
|
+
for alt in alternatives(node):
|
|
232
|
+
if alt is True:
|
|
233
|
+
nexts.append(True)
|
|
234
|
+
elif name == "[]":
|
|
235
|
+
if "items" in alt:
|
|
236
|
+
nexts += alternatives(alt["items"])
|
|
237
|
+
elif name in alt.get("properties", {}):
|
|
238
|
+
nexts += alternatives(alt["properties"][name])
|
|
239
|
+
elif alt.get("additionalProperties") not in (None, False):
|
|
240
|
+
nexts.append(True)
|
|
241
|
+
return nexts
|
|
242
|
+
|
|
243
|
+
requests = {}
|
|
244
|
+
for alt in bundle.get("definitions", {}).get("ClientRequest", {}).get("oneOf", []):
|
|
245
|
+
props = alt.get("properties", {})
|
|
246
|
+
methods = props.get("method", {}).get("enum") or []
|
|
247
|
+
ref = (props.get("params") or {}).get("$ref")
|
|
248
|
+
if methods and ref:
|
|
249
|
+
requests[methods[0]] = ref
|
|
250
|
+
missing = []
|
|
251
|
+
for method, side, path in USED:
|
|
252
|
+
if method not in requests:
|
|
253
|
+
missing.append(f"{method} (method)")
|
|
254
|
+
continue
|
|
255
|
+
ref = requests[method] if side == "params" else re.sub(r"Params$", "Response", requests[method])
|
|
256
|
+
try:
|
|
257
|
+
nodes = [resolve(ref)]
|
|
258
|
+
except (KeyError, TypeError):
|
|
259
|
+
missing.append(f"{method} {side}")
|
|
260
|
+
continue
|
|
261
|
+
steps, value = _steps(path), None
|
|
262
|
+
if "=" in steps[-1]:
|
|
263
|
+
steps[-1], value = steps[-1].split("=", 1)
|
|
264
|
+
for name in steps:
|
|
265
|
+
nodes = step(nodes, name)
|
|
266
|
+
if not nodes:
|
|
267
|
+
missing.append(f"{method} {side} {path}")
|
|
268
|
+
elif value is not None and True not in nodes and not any(
|
|
269
|
+
value in (alt.get("enum") or []) or alt.get("const") == value
|
|
270
|
+
for node in nodes for alt in alternatives(node) if isinstance(alt, dict)):
|
|
271
|
+
missing.append(f"{method} {side} {path}")
|
|
272
|
+
return missing
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def fixture_bundle(drop=()):
|
|
276
|
+
"""A schema bundle naming exactly USED (less the `drop` entries), in the generated schema's layout:
|
|
277
|
+
what a fake Codex writes for `app-server generate-json-schema`, so a fake can answer the check
|
|
278
|
+
without a vendor schema. The installed Codex's own schema is what decides in use."""
|
|
279
|
+
definitions, requests = {}, []
|
|
280
|
+
for method in dict.fromkeys(m for m, _, _ in USED):
|
|
281
|
+
base = "".join(part[:1].upper() + part[1:] for part in re.split(r"[/_]", method))
|
|
282
|
+
requests.append({"properties": {"method": {"enum": [method]}, "params": {"$ref": f"#/definitions/{base}Params"}}})
|
|
283
|
+
definitions[f"{base}Params"], definitions[f"{base}Response"] = {"type": "object"}, {"type": "object"}
|
|
284
|
+
for method, side, path in USED:
|
|
285
|
+
if (method, side, path) in drop:
|
|
286
|
+
continue
|
|
287
|
+
base = "".join(part[:1].upper() + part[1:] for part in re.split(r"[/_]", method))
|
|
288
|
+
node = definitions[f"{base}{'Params' if side == 'params' else 'Response'}"]
|
|
289
|
+
steps, value = _steps(path), None
|
|
290
|
+
if "=" in steps[-1]:
|
|
291
|
+
steps[-1], value = steps[-1].split("=", 1)
|
|
292
|
+
for step in steps:
|
|
293
|
+
if step == "[]":
|
|
294
|
+
node = node.setdefault("items", {"type": "object"})
|
|
295
|
+
else:
|
|
296
|
+
node = node.setdefault("properties", {}).setdefault(step, {"type": "object"})
|
|
297
|
+
if value is not None:
|
|
298
|
+
node.setdefault("enum", []).append(value)
|
|
299
|
+
definitions["ClientRequest"] = {"oneOf": requests}
|
|
300
|
+
return {"definitions": definitions}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
_VERDICTS = {}
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def codex_version(codex, env=None, timeout=30):
|
|
307
|
+
"""The version `codex --version` names, asked with a scratch CODEX_HOME: even this command
|
|
308
|
+
creates <CODEX_HOME>/tmp, and the check writes nothing into the caller's homes."""
|
|
309
|
+
try:
|
|
310
|
+
with tempfile.TemporaryDirectory(prefix="codex-protocol-") as scratch:
|
|
311
|
+
done = subprocess.run([codex, "--version"], env={**(os.environ if env is None else env), "CODEX_HOME": scratch},
|
|
312
|
+
capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)
|
|
313
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
314
|
+
raise ProtocolError(f"`{codex} --version` did not run: {exc}") from exc
|
|
315
|
+
version = done.stdout.strip().splitlines()[-1].strip() if done.returncode == 0 and done.stdout.strip() else ""
|
|
316
|
+
if not version:
|
|
317
|
+
raise ProtocolError(f"`{codex} --version` named no version (exit {done.returncode}); agent-bios checks the "
|
|
318
|
+
f"app-server protocol per Codex version and refuses an unnamed one")
|
|
319
|
+
return version
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def ensure_schema(codex, env=None, cache_dir=None, timeout=30):
|
|
323
|
+
"""Refuse unless the installed Codex's generated protocol schema carries every USED name. The
|
|
324
|
+
verdict is kept per binary (path, size, modification time), version and USED: in this process,
|
|
325
|
+
and in `cache_dir` when one is given and is a real directory (created inside its parent only)."""
|
|
326
|
+
env = dict(os.environ if env is None else env)
|
|
327
|
+
located = codex if os.sep in str(codex) else shutil.which(codex, path=env.get("PATH"))
|
|
328
|
+
if not located:
|
|
329
|
+
raise ProtocolError(f"no Codex executable named {codex!r} on PATH")
|
|
330
|
+
real = pathlib.Path(located).resolve()
|
|
331
|
+
status = real.stat()
|
|
332
|
+
binary = {"path": str(real), "size": status.st_size, "mtime_ns": status.st_mtime_ns}
|
|
333
|
+
memo = (json.dumps(binary, sort_keys=True), USED_DIGEST)
|
|
334
|
+
if memo in _VERDICTS:
|
|
335
|
+
return _raise_for(_VERDICTS[memo])
|
|
336
|
+
version = codex_version(str(real), env, timeout)
|
|
337
|
+
record_path = None
|
|
338
|
+
if cache_dir is not None:
|
|
339
|
+
cache = pathlib.Path(cache_dir)
|
|
340
|
+
if cache.parent.is_dir() and not cache.parent.is_symlink() and not cache.is_symlink():
|
|
341
|
+
cache.mkdir(mode=0o700, exist_ok=True)
|
|
342
|
+
record_path = cache / (re.sub(r"[^0-9A-Za-z._-]", "_", version) + ".json")
|
|
343
|
+
if record_path is not None and record_path.is_file() and not record_path.is_symlink():
|
|
344
|
+
try:
|
|
345
|
+
record = json.loads(record_path.read_text(encoding="utf-8"))
|
|
346
|
+
except (OSError, ValueError):
|
|
347
|
+
record = None
|
|
348
|
+
if (isinstance(record, dict) and record.get("binary") == binary and record.get("used") == USED_DIGEST
|
|
349
|
+
and record.get("version") == version and isinstance(record.get("missing"), list)):
|
|
350
|
+
_VERDICTS[memo] = record
|
|
351
|
+
return _raise_for(record)
|
|
352
|
+
missing, generated = generated_missing(str(real), env, timeout)
|
|
353
|
+
record = {"version": version, "binary": binary, "used": USED_DIGEST, "missing": missing,
|
|
354
|
+
"names": len(USED), "checked_at": time.time()}
|
|
355
|
+
# A schema that could not be generated is not a verdict about the version: it is kept neither in
|
|
356
|
+
# this process nor on disk, so the next check generates again.
|
|
357
|
+
if generated:
|
|
358
|
+
_VERDICTS[memo] = record
|
|
359
|
+
if record_path is not None and generated:
|
|
360
|
+
handle, staged = tempfile.mkstemp(dir=record_path.parent, prefix=".codex-protocol-")
|
|
361
|
+
try:
|
|
362
|
+
with os.fdopen(handle, "w", encoding="utf-8") as out:
|
|
363
|
+
json.dump(record, out, sort_keys=True)
|
|
364
|
+
os.replace(staged, record_path)
|
|
365
|
+
finally:
|
|
366
|
+
if os.path.exists(staged):
|
|
367
|
+
os.unlink(staged)
|
|
368
|
+
return _raise_for(record)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def generated_missing(codex, env, timeout=30):
|
|
372
|
+
"""Generate the version's schema offline into a scratch directory, with a scratch CODEX_HOME (the
|
|
373
|
+
command writes a tmp/ there): (the USED names it lacks, whether a schema was generated at all)."""
|
|
374
|
+
with tempfile.TemporaryDirectory(prefix="codex-protocol-") as scratch:
|
|
375
|
+
out = pathlib.Path(scratch) / "schema"
|
|
376
|
+
home = pathlib.Path(scratch) / "codex-home"
|
|
377
|
+
home.mkdir()
|
|
378
|
+
bundle_path = out / "codex_app_server_protocol.schemas.json"
|
|
379
|
+
try:
|
|
380
|
+
done = subprocess.run([codex, "app-server", "generate-json-schema", "--experimental", "--out", str(out)],
|
|
381
|
+
env={**env, "CODEX_HOME": str(home)}, capture_output=True, text=True,
|
|
382
|
+
timeout=timeout, stdin=subprocess.DEVNULL)
|
|
383
|
+
code = done.returncode
|
|
384
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
385
|
+
code = f"no exit ({exc})"
|
|
386
|
+
if code != 0 or not bundle_path.is_file():
|
|
387
|
+
return [f"the schema itself (`app-server generate-json-schema` exited {code} without "
|
|
388
|
+
f"{bundle_path.name})"], False
|
|
389
|
+
try:
|
|
390
|
+
bundle = json.loads(bundle_path.read_text(encoding="utf-8"))
|
|
391
|
+
except ValueError:
|
|
392
|
+
return [f"the schema itself ({bundle_path.name} is not JSON)"], False
|
|
393
|
+
return schema_missing(bundle), True
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _raise_for(record):
|
|
397
|
+
if record["missing"]:
|
|
398
|
+
raise ProtocolError(f"Codex {record['version']}'s app-server protocol schema lacks what agent-bios uses: "
|
|
399
|
+
f"{', '.join(record['missing'])}; this Codex version is not one agent-bios was checked "
|
|
400
|
+
f"against")
|
|
401
|
+
return record
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
TICK_S = 0.05 # how often a wait on a child's pipes or on its end looks again
|
|
405
|
+
CLOSE_S = 5 # how long a server whose input closed is given to end, and to end after SIGTERM
|
|
406
|
+
DRAIN_S = 2 # how long its output is given to close once its group has been ended
|
|
407
|
+
_UNREAPED = set() # every Owned whose child has not been reaped yet
|
|
408
|
+
_TERMINATED = [] # the termination signal raise_on_termination turned into Terminated, if any
|
|
409
|
+
_INSTALLED = [] # whether raise_on_termination has installed its handler in this process
|
|
410
|
+
_CLEANING = [0] # how many cleanups (Owned.end, Client.close, a collection's end) are running
|
|
411
|
+
_NOTED = [] # a termination signal that arrived during a cleanup, raised when the outermost ends
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
class Terminated(SystemExit):
|
|
415
|
+
"""SIGTERM or SIGHUP, raised while this process owns an unreaped child (raise_on_termination), so
|
|
416
|
+
the owner's cleanup ends the child's group on the way out; the process then ends by the signal."""
|
|
417
|
+
|
|
418
|
+
def __init__(self, signum):
|
|
419
|
+
super().__init__(128 + signum)
|
|
420
|
+
self.signum = signum
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def raise_on_termination():
|
|
424
|
+
"""For an entry point that owns children through Owned, called from its main thread: from now on
|
|
425
|
+
SIGTERM and SIGHUP raise Terminated while any Owned child is unreaped, and at exit the process ends
|
|
426
|
+
by the same signal; while none is, they end the process at once, as their default does, so code
|
|
427
|
+
that owns no child (a host session this process waits on, a UI) sees them unchanged. The library
|
|
428
|
+
never installs this itself."""
|
|
429
|
+
if threading.current_thread() is not threading.main_thread() or _INSTALLED:
|
|
430
|
+
return
|
|
431
|
+
_INSTALLED.append(True)
|
|
432
|
+
|
|
433
|
+
def handler(signum, _frame):
|
|
434
|
+
if _TERMINATED:
|
|
435
|
+
return # the first one ends the process once its cleanup is done
|
|
436
|
+
if _CLEANING[0]:
|
|
437
|
+
_NOTED[:] = _NOTED or [signum] # raised when the cleanup it would have cut short is done
|
|
438
|
+
return
|
|
439
|
+
if not _UNREAPED:
|
|
440
|
+
end_by(signum)
|
|
441
|
+
_TERMINATED.append(signum)
|
|
442
|
+
raise Terminated(signum)
|
|
443
|
+
for signum in (signal.SIGTERM, signal.SIGHUP):
|
|
444
|
+
signal.signal(signum, handler)
|
|
445
|
+
atexit.register(lambda: _TERMINATED and end_by(_TERMINATED[0]))
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def unreaped():
|
|
449
|
+
"""The numbers of the children this process owns through Owned and has not reaped."""
|
|
450
|
+
return sorted(owned.proc.pid for owned in _UNREAPED)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def end_by(signum):
|
|
454
|
+
"""End this process by `signum`'s default action, so whoever waits on it sees that signal. What
|
|
455
|
+
Python still buffers is written first, since the default action ends the process at once; a
|
|
456
|
+
terminal that has gone (SIGHUP) refuses the write, which is then given up."""
|
|
457
|
+
for stream in (sys.stdout, sys.stderr):
|
|
458
|
+
with contextlib.suppress(OSError, ValueError, AttributeError):
|
|
459
|
+
stream.flush()
|
|
460
|
+
signal.signal(signum, signal.SIG_DFL)
|
|
461
|
+
os.kill(os.getpid(), signum)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
class _Cleanup:
|
|
465
|
+
"""A cleanup a termination signal must not cut short: raise_on_termination's handler only notes a
|
|
466
|
+
signal that arrives inside one, and the outermost one raises it when it is done. When another
|
|
467
|
+
exception is already leaving the cleanup, that one goes on, and the process still ends by the noted
|
|
468
|
+
signal at exit."""
|
|
469
|
+
|
|
470
|
+
def __enter__(self):
|
|
471
|
+
_CLEANING[0] += 1
|
|
472
|
+
|
|
473
|
+
def __exit__(self, exc_type, _exc, _tb):
|
|
474
|
+
_CLEANING[0] -= 1
|
|
475
|
+
if _CLEANING[0] or not _NOTED or _TERMINATED:
|
|
476
|
+
return False
|
|
477
|
+
signum = _NOTED.pop()
|
|
478
|
+
_TERMINATED.append(signum)
|
|
479
|
+
if exc_type is None:
|
|
480
|
+
raise Terminated(signum)
|
|
481
|
+
return False
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
class Owned:
|
|
485
|
+
"""A child started in a session of its own (start_new_session=True), ended with its process group.
|
|
486
|
+
|
|
487
|
+
The child's end is watched without reaping it — kqueue's process filter where the platform has
|
|
488
|
+
one, since the Pythons macOS ships lack os.waitid, and waitid(WNOWAIT) elsewhere — and its group
|
|
489
|
+
is signalled before the child is reaped, on every path: until then the child's number, which is
|
|
490
|
+
the group's, belongs to no other process. A child that ended by itself has its group sent SIGKILL,
|
|
491
|
+
which reaches what it left behind in the group; one still running is sent SIGTERM, given its
|
|
492
|
+
grace, then SIGKILL. A process that made a session of its own has left the group and is beyond
|
|
493
|
+
this reach: a pipe it still holds is closed on this side after a bounded drain, never waited for,
|
|
494
|
+
and the caller is told. On Windows there is no group: the child is terminated, then killed, and
|
|
495
|
+
its handle keeps its number until it is waited for."""
|
|
496
|
+
|
|
497
|
+
def __init__(self, proc):
|
|
498
|
+
self.proc, self._ended, self._watch = proc, False, None
|
|
499
|
+
self.clock = time.monotonic # collect's clock; a control gives one that moves between two reads
|
|
500
|
+
_UNREAPED.add(self)
|
|
501
|
+
if os.name != "nt" and hasattr(select, "kqueue"):
|
|
502
|
+
self._watch = select.kqueue()
|
|
503
|
+
try:
|
|
504
|
+
self._watch.control([select.kevent(proc.pid, select.KQ_FILTER_PROC,
|
|
505
|
+
select.KQ_EV_ADD | select.KQ_EV_ONESHOT, select.KQ_NOTE_EXIT)], 0, 0)
|
|
506
|
+
except ProcessLookupError: # it ended before the watch began: an unreaped child cannot be watched
|
|
507
|
+
self._ended = True
|
|
508
|
+
|
|
509
|
+
def ended(self, wait_s=0.0):
|
|
510
|
+
"""Whether the child has ended, waiting at most `wait_s`. It is never reaped here."""
|
|
511
|
+
if self._ended or self.proc.returncode is not None:
|
|
512
|
+
return True
|
|
513
|
+
if os.name == "nt":
|
|
514
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
515
|
+
self.proc.wait(timeout=wait_s)
|
|
516
|
+
return self.proc.returncode is not None
|
|
517
|
+
if self._watch is not None:
|
|
518
|
+
self._ended = bool(self._watch.control(None, 1, max(wait_s, 0)))
|
|
519
|
+
return self._ended
|
|
520
|
+
deadline = time.monotonic() + wait_s
|
|
521
|
+
while os.waitid(os.P_PID, self.proc.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is None:
|
|
522
|
+
if time.monotonic() >= deadline:
|
|
523
|
+
return False
|
|
524
|
+
time.sleep(TICK_S)
|
|
525
|
+
self._ended = True
|
|
526
|
+
return True
|
|
527
|
+
|
|
528
|
+
def end(self, grace_s):
|
|
529
|
+
"""End the child's group, then reap the child. Nothing is signalled once the child is reaped,
|
|
530
|
+
SIGKILL is sent even when the wait for SIGTERM is interrupted, and a termination signal waits
|
|
531
|
+
until the child is reaped (_Cleanup)."""
|
|
532
|
+
with _Cleanup():
|
|
533
|
+
self._end(grace_s)
|
|
534
|
+
|
|
535
|
+
def _end(self, grace_s):
|
|
536
|
+
if self.proc.returncode is not None:
|
|
537
|
+
_UNREAPED.discard(self)
|
|
538
|
+
return
|
|
539
|
+
if os.name == "nt":
|
|
540
|
+
if not self.ended():
|
|
541
|
+
self.proc.terminate()
|
|
542
|
+
if not self.ended(grace_s):
|
|
543
|
+
self.proc.kill()
|
|
544
|
+
self.proc.wait()
|
|
545
|
+
_UNREAPED.discard(self)
|
|
546
|
+
return
|
|
547
|
+
try:
|
|
548
|
+
if not self.ended():
|
|
549
|
+
# ESRCH, or EPERM on macOS when the unreaped child is all the group holds: nothing to signal
|
|
550
|
+
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
551
|
+
os.killpg(self.proc.pid, signal.SIGTERM)
|
|
552
|
+
self.ended(grace_s)
|
|
553
|
+
finally:
|
|
554
|
+
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
555
|
+
os.killpg(self.proc.pid, signal.SIGKILL)
|
|
556
|
+
self.proc.wait()
|
|
557
|
+
_UNREAPED.discard(self)
|
|
558
|
+
if self._watch is not None:
|
|
559
|
+
self._watch.close()
|
|
560
|
+
|
|
561
|
+
def collect(self, limit_s, grace_s, drain_s):
|
|
562
|
+
"""(stdout, stderr, timed_out, held): the child's piped output, read until every pipe has closed
|
|
563
|
+
and the child has ended, for at most `limit_s`; then its group is ended (end) and the pipes are
|
|
564
|
+
read for at most `drain_s` more. The pipes are closed however the collection ends, an
|
|
565
|
+
interrupted one included. `held` is true when one was still open after the drain, held by a
|
|
566
|
+
process outside the group. POSIX only: Windows pipes cannot be selected."""
|
|
567
|
+
streams = [stream for stream in (self.proc.stdout, self.proc.stderr) if stream is not None]
|
|
568
|
+
fds = [None if stream is None else stream.fileno() for stream in (self.proc.stdout, self.proc.stderr)]
|
|
569
|
+
open_fds = {stream.fileno() for stream in streams}
|
|
570
|
+
read = {fd: [] for fd in open_fds}
|
|
571
|
+
|
|
572
|
+
def take(wait_s):
|
|
573
|
+
# a wait computed from a deadline that passed meanwhile is a poll, never a refusal
|
|
574
|
+
for fd in select.select(sorted(open_fds), [], [], max(wait_s, 0))[0]:
|
|
575
|
+
chunk = os.read(fd, 65536)
|
|
576
|
+
if chunk:
|
|
577
|
+
read[fd].append(chunk)
|
|
578
|
+
else:
|
|
579
|
+
open_fds.discard(fd)
|
|
580
|
+
deadline, timed_out = self.clock() + limit_s, False
|
|
581
|
+
try:
|
|
582
|
+
try:
|
|
583
|
+
while open_fds or not self.ended():
|
|
584
|
+
left = deadline - self.clock()
|
|
585
|
+
if left <= 0:
|
|
586
|
+
timed_out = True
|
|
587
|
+
break
|
|
588
|
+
if open_fds:
|
|
589
|
+
take(min(left, TICK_S))
|
|
590
|
+
else:
|
|
591
|
+
self.ended(min(left, TICK_S))
|
|
592
|
+
finally:
|
|
593
|
+
self.end(grace_s)
|
|
594
|
+
deadline = self.clock() + drain_s
|
|
595
|
+
while open_fds and self.clock() < deadline:
|
|
596
|
+
take(min(deadline - self.clock(), TICK_S))
|
|
597
|
+
finally:
|
|
598
|
+
for stream in streams:
|
|
599
|
+
stream.close()
|
|
600
|
+
held = bool(open_fds)
|
|
601
|
+
out, err = (b"" if fd is None else b"".join(read[fd]) for fd in fds)
|
|
602
|
+
return out, err, timed_out, held
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
class Client:
|
|
606
|
+
"""One app-server over stdio, read on a thread into a queue, in a process group of its own (Owned).
|
|
607
|
+
|
|
608
|
+
On POSIX a request is written to the server's input descriptor, made non-blocking, only while the
|
|
609
|
+
call's deadline lasts: a server that stops reading cannot hold a call past its timeout. A request
|
|
610
|
+
not sent whole by then leaves part of a frame in the server's input, so the client refuses every
|
|
611
|
+
later call, naming that request. Nothing is written through the buffered input stream, so closing
|
|
612
|
+
it flushes nothing. On Windows, where pipes cannot be selected, a request is written as before."""
|
|
613
|
+
|
|
614
|
+
def __init__(self, argv, cwd=None, env=None):
|
|
615
|
+
self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
616
|
+
cwd=cwd, env=env, start_new_session=True)
|
|
617
|
+
self.owned = Owned(self.proc)
|
|
618
|
+
self.broken = None
|
|
619
|
+
if os.name != "nt":
|
|
620
|
+
os.set_blocking(self.proc.stdin.fileno(), False)
|
|
621
|
+
self.sequence = 0
|
|
622
|
+
self.events = queue.Queue()
|
|
623
|
+
self.stopping, self.drained = threading.Event(), threading.Event()
|
|
624
|
+
self.reader = threading.Thread(target=self._read, daemon=True)
|
|
625
|
+
self.reader.start()
|
|
626
|
+
|
|
627
|
+
def _read(self):
|
|
628
|
+
try:
|
|
629
|
+
for line in self._lines():
|
|
630
|
+
try:
|
|
631
|
+
self.events.put(json.loads(line))
|
|
632
|
+
except ValueError:
|
|
633
|
+
self.events.put({"transport_error": "invalid app-server JSON"})
|
|
634
|
+
finally:
|
|
635
|
+
self.events.put({"transport_error": "app-server closed before its response"})
|
|
636
|
+
|
|
637
|
+
def _lines(self):
|
|
638
|
+
"""The server's output, line by line, until it closes or close() stops the reading. On POSIX
|
|
639
|
+
the descriptor is read directly, so a stop takes effect within TICK_S and no thread is left
|
|
640
|
+
reading a stream that a process outside the group holds open; Windows pipes cannot be
|
|
641
|
+
selected, so there the stream is read until it closes."""
|
|
642
|
+
if os.name == "nt":
|
|
643
|
+
yield from self.proc.stdout
|
|
644
|
+
self.drained.set()
|
|
645
|
+
return
|
|
646
|
+
fd, partial = self.proc.stdout.fileno(), b""
|
|
647
|
+
while not self.stopping.is_set():
|
|
648
|
+
if not select.select([fd], [], [], TICK_S)[0]:
|
|
649
|
+
continue
|
|
650
|
+
chunk = os.read(fd, 65536)
|
|
651
|
+
if not chunk:
|
|
652
|
+
self.drained.set()
|
|
653
|
+
if partial:
|
|
654
|
+
yield partial
|
|
655
|
+
return
|
|
656
|
+
*lines, partial = (partial + chunk).split(b"\n")
|
|
657
|
+
yield from lines
|
|
658
|
+
|
|
659
|
+
def _send(self, method, message, deadline):
|
|
660
|
+
if self.broken:
|
|
661
|
+
raise ProtocolError(self.broken)
|
|
662
|
+
data = (json.dumps(message) + "\n").encode("utf-8")
|
|
663
|
+
if os.name == "nt":
|
|
664
|
+
self.proc.stdin.write(data)
|
|
665
|
+
self.proc.stdin.flush()
|
|
666
|
+
return
|
|
667
|
+
fd, whole = self.proc.stdin.fileno(), len(data)
|
|
668
|
+
while data:
|
|
669
|
+
left = deadline - time.monotonic()
|
|
670
|
+
if left <= 0 and len(data) == whole:
|
|
671
|
+
raise ProtocolError(f"app-server timed out: {method} (the server read none of the request)")
|
|
672
|
+
if left <= 0:
|
|
673
|
+
self.broken = (f"app-server {method}: the request was not sent whole within its timeout, so the "
|
|
674
|
+
f"server's input holds part of it and this client sends nothing more")
|
|
675
|
+
raise ProtocolError(self.broken)
|
|
676
|
+
if not select.select([], [fd], [], min(left, TICK_S))[1]:
|
|
677
|
+
continue
|
|
678
|
+
try:
|
|
679
|
+
data = data[os.write(fd, data):]
|
|
680
|
+
except BlockingIOError:
|
|
681
|
+
continue
|
|
682
|
+
except OSError as exc: # a server that ended has broken the pipe
|
|
683
|
+
self.broken = f"app-server {method}: the server's input closed ({exc.__class__.__name__})"
|
|
684
|
+
raise ProtocolError(self.broken) from exc
|
|
685
|
+
|
|
686
|
+
def notify(self, method, timeout=45):
|
|
687
|
+
self._send(method, {"method": method}, time.monotonic() + timeout)
|
|
688
|
+
|
|
689
|
+
def call(self, method, params, timeout=45):
|
|
690
|
+
self.sequence += 1
|
|
691
|
+
request_id = self.sequence
|
|
692
|
+
deadline = time.monotonic() + timeout
|
|
693
|
+
self._send(method, {"id": request_id, "method": method, "params": params}, deadline)
|
|
694
|
+
while time.monotonic() < deadline:
|
|
695
|
+
try:
|
|
696
|
+
message = self.events.get(timeout=max(0.01, deadline - time.monotonic()))
|
|
697
|
+
except queue.Empty as exc:
|
|
698
|
+
raise ProtocolError(f"app-server timed out: {method}") from exc
|
|
699
|
+
if "transport_error" in message:
|
|
700
|
+
raise ProtocolError(message["transport_error"])
|
|
701
|
+
if message.get("id") != request_id:
|
|
702
|
+
continue
|
|
703
|
+
if "error" in message:
|
|
704
|
+
error = message["error"]
|
|
705
|
+
raise ProtocolError(f"app-server {method}: "
|
|
706
|
+
f"{error.get('message', 'refused') if isinstance(error, dict) else error}")
|
|
707
|
+
return message.get("result")
|
|
708
|
+
raise ProtocolError(f"app-server timed out: {method}")
|
|
709
|
+
|
|
710
|
+
def close(self):
|
|
711
|
+
"""The server's input is closed and it is given CLOSE_S to end, then its group is ended before
|
|
712
|
+
it is reaped (Owned.end). Its output then has DRAIN_S to close: a process outside the group
|
|
713
|
+
that still holds it is not waited for, and one line on stderr says so. The reader is stopped,
|
|
714
|
+
within TICK_S on POSIX, and the output is closed only once no thread reads it. Each step runs
|
|
715
|
+
however the one before it ended, an interrupted wait included, and a termination signal waits
|
|
716
|
+
until the last is done (_Cleanup)."""
|
|
717
|
+
with _Cleanup():
|
|
718
|
+
self._close()
|
|
719
|
+
|
|
720
|
+
def _close(self):
|
|
721
|
+
try:
|
|
722
|
+
try:
|
|
723
|
+
with contextlib.suppress(OSError):
|
|
724
|
+
self.proc.stdin.close() # nothing was written through its buffer, so this flushes nothing
|
|
725
|
+
self.owned.ended(CLOSE_S)
|
|
726
|
+
finally:
|
|
727
|
+
self.owned.end(CLOSE_S)
|
|
728
|
+
if not self.drained.wait(DRAIN_S):
|
|
729
|
+
with contextlib.suppress(OSError): # a terminal that has gone (SIGHUP) refuses the line
|
|
730
|
+
sys.stderr.write("agent-bios: a process the Codex app-server left outside its process group "
|
|
731
|
+
"still holds its output; agent-bios stopped reading it without waiting for it "
|
|
732
|
+
"to close\n")
|
|
733
|
+
finally:
|
|
734
|
+
self.stopping.set()
|
|
735
|
+
self.reader.join(timeout=DRAIN_S)
|
|
736
|
+
if not self.reader.is_alive():
|
|
737
|
+
self.proc.stdout.close()
|