-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime_adapters.py
More file actions
305 lines (270 loc) · 14.8 KB
/
Copy pathruntime_adapters.py
File metadata and controls
305 lines (270 loc) · 14.8 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Runtime boundaries for source ingestion and structured agent calls.
No adapter is activated without explicit environment configuration. This keeps
the local demo deterministic and prevents accidental transmission of project
content to GitHub or a model provider.
"""
from __future__ import annotations
import json
import os
import re
import time
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlparse
from urllib.request import Request, urlopen
import agent_runtime
class AdapterError(RuntimeError):
"""A recoverable configuration, network, or response-contract error."""
ENVIRONMENT_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
PROVIDER_SECRET = re.compile(r"(?i)(?:sk-[a-z0-9_-]{12,}|bearer\s+[a-z0-9._-]{12,}|(?:api[_-]?key|token|secret)\s*[=:]\s*\S+)")
def load_local_env(path: Path | None = None) -> None:
"""Load simple KEY=VALUE entries from a local .env without shell evaluation.
Process environment always wins, values are never logged, and command
substitutions are treated as ordinary text rather than executed.
"""
env_file = path or Path(__file__).with_name(".env")
try:
lines = env_file.read_text(encoding="utf-8").splitlines()
except FileNotFoundError:
return
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].lstrip()
if "=" not in line:
continue
name, value = line.split("=", 1)
name = name.strip()
if not ENVIRONMENT_NAME.fullmatch(name):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
os.environ.setdefault(name, value)
def provider_error_detail(error: HTTPError) -> str:
"""Return a short, redacted provider diagnostic suitable for an audit record."""
message = ""
try:
body = json.loads(error.read().decode("utf-8", errors="replace"))
candidate = body.get("error", {}).get("message") if isinstance(body, dict) else None
if isinstance(candidate, str):
message = candidate
except (json.JSONDecodeError, UnicodeDecodeError, AttributeError):
pass
if not message:
return f"Remote service returned {error.code}."
safe_message = PROVIDER_SECRET.sub("[REDACTED]", message)[:400]
return f"Remote service returned {error.code}: {safe_message}"
@dataclass(frozen=True)
class Settings:
github_token: str | None
github_owner: str | None
github_repo: str | None
model_endpoint: str | None
model_api_key: str | None
model_name: str | None = "gpt-5.6-terra"
model_reasoning_effort: str | None = "medium"
@classmethod
def from_env(cls) -> "Settings":
load_local_env()
return cls(
github_token=os.getenv("GITHUB_TOKEN"),
github_owner=os.getenv("GITHUB_OWNER"),
github_repo=os.getenv("GITHUB_REPO"),
model_endpoint=os.getenv("MODEL_ENDPOINT"),
model_api_key=os.getenv("MODEL_API_KEY"),
model_name=os.getenv("MODEL_NAME") or "gpt-5.6-terra",
model_reasoning_effort=os.getenv("MODEL_REASONING_EFFORT") or "medium",
)
@property
def github_ready(self) -> bool:
return bool(self.github_token and self.github_owner and self.github_repo)
@property
def model_ready(self) -> bool:
return bool(self.model_endpoint and self.model_api_key and self.model_name)
def _request_json(url: str, headers: dict[str, str], body: dict[str, Any] | None = None) -> Any:
data = json.dumps(body).encode() if body is not None else None
request = Request(url, data=data, headers=headers, method="POST" if body is not None else "GET")
try:
with urlopen(request, timeout=30) as response:
return json.loads(response.read())
except HTTPError as error:
raise AdapterError(provider_error_detail(error)) from error
except (URLError, TimeoutError) as error:
raise AdapterError("Remote service could not be reached.") from error
except json.JSONDecodeError as error:
raise AdapterError("Remote service returned invalid JSON.") from error
class GitHubSourceAdapter:
"""Read-only GitHub App/PAT adapter for explicit handoff-time ingestion."""
def __init__(self, settings: Settings):
if not settings.github_ready:
raise AdapterError("GitHub ingestion is not configured. Set GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO.")
self.settings = settings
self.base = f"https://api.github.com/repos/{settings.github_owner}/{settings.github_repo}"
self.headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {settings.github_token}", "X-GitHub-Api-Version": "2022-11-28"}
def _get(self, path: str, **query: str) -> Any:
suffix = f"?{urlencode(query)}" if query else ""
return _request_json(self.base + path + suffix, self.headers)
def fetch_since(self, author: str, since: str) -> list[dict[str, Any]]:
"""Return normalized, small evidence records; never retain full diffs or logs."""
sources: list[dict[str, Any]] = []
commits = self._get("/commits", since=since, author=author, per_page="100")
for commit in commits:
details = self._get(f"/commits/{commit['sha']}")
message = details["commit"]["message"].splitlines()[0]
paths = [f["filename"] for f in details.get("files", [])]
sources.append({"kind": "commit", "external_id": commit["sha"], "title": message, "source_url": commit["html_url"], "author": commit.get("author", {}).get("login", author), "occurred_at": details["commit"]["author"]["date"], "excerpt": f"Commit {commit['sha'][:7]}: {message}", "paths": paths, "metadata": {"source": "github"}})
pulls = self._get("/pulls", state="all", sort="updated", direction="desc", per_page="100")
cutoff = datetime.fromisoformat(since.replace("Z", "+00:00"))
for pull in pulls:
updated = datetime.fromisoformat(pull["updated_at"].replace("Z", "+00:00"))
if pull["user"]["login"] != author or updated < cutoff:
continue
paths = [f["filename"] for f in self._get(f"/pulls/{pull['number']}/files", per_page="100")]
sources.append({"kind": "pull_request", "external_id": str(pull["number"]), "title": f"PR #{pull['number']}: {pull['title']}", "source_url": pull["html_url"], "author": author, "occurred_at": pull["updated_at"], "excerpt": (pull.get("body") or pull["title"])[:500], "paths": paths, "metadata": {"state": pull["state"], "source": "github"}})
for review in self._get(f"/pulls/{pull['number']}/reviews", per_page="100"):
sources.append({"kind": "review", "external_id": f"{pull['number']}:{review['id']}", "title": f"PR #{pull['number']} review: {review.get('state', 'commented').lower()}", "source_url": pull["html_url"], "author": review.get("user", {}).get("login"), "occurred_at": review.get("submitted_at") or pull["updated_at"], "excerpt": (review.get("body") or "Review submitted without body.")[:500], "paths": paths, "metadata": {"pull_number": pull["number"], "source": "github"}})
return sources
class StructuredModelAdapter:
"""OpenAI Responses adapter for stateless, structured agent executions."""
_REASONING_EFFORTS = frozenset({"none", "low", "medium", "high", "xhigh", "max"})
def __init__(self, settings: Settings):
if not settings.model_ready:
raise AdapterError("Model execution is not configured. Set MODEL_ENDPOINT and MODEL_API_KEY.")
endpoint = settings.model_endpoint or ""
if urlparse(endpoint).path.rstrip("/").endswith("/responses") is False:
raise AdapterError("MODEL_ENDPOINT must point to an OpenAI-compatible Responses API endpoint ending in /responses.")
if settings.model_reasoning_effort not in self._REASONING_EFFORTS:
choices = ", ".join(sorted(self._REASONING_EFFORTS))
raise AdapterError(f"MODEL_REASONING_EFFORT must be one of: {choices}.")
self.settings = settings
def run(self, agent_name: str, payload: dict[str, Any]) -> tuple[dict[str, Any], int]:
request = agent_runtime.build_request(agent_name, payload)
started = time.monotonic()
response = _request_json(
self.settings.model_endpoint or "",
{"Authorization": f"Bearer {self.settings.model_api_key}", "Content-Type": "application/json"},
{
"model": self.settings.model_name,
"instructions": request["instructions"],
"input": json.dumps(request["input"], separators=(",", ":")),
"reasoning": {"effort": self.settings.model_reasoning_effort},
"store": False,
"text": {
"format": {
"type": "json_schema",
"name": f"{agent_name.replace('-', '_')}_output",
"strict": True,
"schema": agent_output_schema(agent_name),
}
},
},
)
elapsed_ms = int((time.monotonic() - started) * 1000)
try:
content = response.get("output_text") or response_output_text(response)
output = json.loads(content)
except (AttributeError, TypeError, json.JSONDecodeError) as error:
raise AdapterError("Model response did not satisfy the required JSON contract.") from error
if not isinstance(output, dict):
raise AdapterError("Model response must be a JSON object.")
validate_agent_output(agent_name, output)
return output, elapsed_ms
def response_output_text(response: dict[str, Any]) -> str:
"""Extract final text without assuming every Responses output item is a message."""
parts: list[str] = []
for item in response.get("output", []):
if not isinstance(item, dict) or item.get("type") != "message":
continue
for content in item.get("content", []):
if isinstance(content, dict) and content.get("type") == "output_text" and isinstance(content.get("text"), str):
parts.append(content["text"])
if not parts:
raise AdapterError("Model response did not include output_text.")
return "".join(parts)
def agent_output_schema(agent_name: str) -> dict[str, Any]:
"""Return the closed structured-output schema for each versioned agent contract."""
object_schema = lambda properties, required: {
"type": "object",
"additionalProperties": False,
"properties": properties,
"required": required,
}
source_id = {"type": "integer"}
evidence_ids = {"type": "array", "items": source_id}
nullable_string = {"type": ["string", "null"]}
nullable_item_id = {"type": ["integer", "string", "null"]}
if agent_name == "activity-synthesizer":
timeline = object_schema({"source_id": source_id, "summary": {"type": "string"}}, ["source_id", "summary"])
omitted = object_schema({"source_id": source_id, "reason": {"type": "string"}}, ["source_id", "reason"])
proposal = object_schema(
{
"kind": {"type": "string", "enum": ["fact", "finding", "assumption", "hypothesis", "conclusion", "blocker", "decision", "continuation"]},
"body": {"type": "string"},
"evidence_ids": evidence_ids,
"path_scopes": {"type": "array", "items": {"type": "string"}},
"component_suggestion": nullable_string,
"ticket_references": {"type": "array", "items": {"type": "string"}},
"certainty": {"type": "string", "enum": ["observed", "author_assertion", "assumption", "hypothesis", "conclusion"]},
},
["kind", "body", "evidence_ids", "path_scopes", "component_suggestion", "ticket_references", "certainty"],
)
return object_schema(
{
"timeline": {"type": "array", "items": timeline},
"omitted_activity": {"type": "array", "items": omitted},
"proposed_items": {"type": "array", "items": proposal},
"uncertainties": {"type": "array", "items": {"type": "string"}},
},
["timeline", "omitted_activity", "proposed_items", "uncertainties"],
)
if agent_name == "evidence-reviewer":
finding = object_schema(
{
"severity": {"type": "string", "enum": ["high", "medium", "low"]},
"requires_response": {"type": "boolean"},
"category": {"type": "string"},
"item_id": nullable_item_id,
"body": {"type": "string"},
"evidence_ids": evidence_ids,
"question": nullable_string,
},
["severity", "requires_response", "category", "item_id", "body", "evidence_ids", "question"],
)
relation = object_schema(
{
"from_item_id": nullable_item_id,
"to_item_id": nullable_item_id,
"relation_type": {"type": "string", "enum": ["contradicts", "supersedes", "resolves", "derives-from", "relates-to"]},
"proposed_state": {"type": "string", "enum": ["disputed", "disproven", "superseded", "resolved"]},
"rationale": {"type": "string"},
"evidence_ids": evidence_ids,
},
["from_item_id", "to_item_id", "relation_type", "proposed_state", "rationale", "evidence_ids"],
)
return object_schema(
{"findings": {"type": "array", "items": finding}, "proposed_relations": {"type": "array", "items": relation}},
["findings", "proposed_relations"],
)
raise AdapterError(f"Unsupported agent: {agent_name}")
def validate_agent_output(agent_name: str, output: dict[str, Any]) -> None:
"""Reject plausible-looking but unusable agent output at the trust boundary."""
required = {
"activity-synthesizer": ("timeline", "omitted_activity", "proposed_items", "uncertainties"),
"evidence-reviewer": ("findings", "proposed_relations"),
}
try:
keys = required[agent_name]
except KeyError as error:
raise AdapterError(f"Unsupported agent: {agent_name}") from error
unexpected = [key for key in output if key not in keys]
if unexpected:
raise AdapterError(f"Model response has unexpected fields: {', '.join(unexpected)}.")
missing = [key for key in keys if key not in output or not isinstance(output[key], list)]
if missing:
raise AdapterError(f"Model response is missing required list fields: {', '.join(missing)}.")