python-codex 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl

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.
Files changed (76) hide show
  1. pycodex/__init__.py +22 -12
  2. pycodex/agent.py +89 -74
  3. pycodex/bootstrap.py +37 -251
  4. pycodex/cli.py +19 -28
  5. pycodex/config.py +36 -0
  6. pycodex/context.py +368 -51
  7. pycodex/events.py +14 -187
  8. pycodex/model.py +197 -95
  9. pycodex/multi_agents.py +401 -0
  10. pycodex/portable/__init__.py +8 -6
  11. pycodex/portable/client.py +24 -39
  12. pycodex/portable/protocol.py +28 -0
  13. pycodex/portable/server.py +3 -3
  14. pycodex/prompts/developer_messages.json +13 -0
  15. pycodex/prompts/goals/budget_limit.md +19 -0
  16. pycodex/prompts/goals/continuation.md +56 -0
  17. pycodex/prompts/models.json +1143 -200
  18. pycodex/protocol.py +81 -15
  19. pycodex/runtime.py +370 -226
  20. pycodex/tools/__init__.py +102 -10
  21. pycodex/tools/agent_tool_schemas.py +0 -38
  22. pycodex/tools/apply_patch_tool.py +17 -34
  23. pycodex/tools/base_tool.py +63 -35
  24. pycodex/tools/clock_manager.py +182 -0
  25. pycodex/tools/clock_tool.py +58 -187
  26. pycodex/tools/code_mode_manager.py +165 -246
  27. pycodex/tools/exec_command_tool.py +0 -18
  28. pycodex/tools/exec_runtime.py +332 -0
  29. pycodex/tools/exec_tool.py +74 -31
  30. pycodex/tools/followup_task_tool.py +44 -0
  31. pycodex/tools/goal_manager.py +205 -0
  32. pycodex/tools/goal_tool.py +126 -0
  33. pycodex/tools/interrupt_agent_tool.py +48 -0
  34. pycodex/tools/list_agents_tool.py +66 -0
  35. pycodex/tools/python_tool_schema.py +141 -0
  36. pycodex/tools/request_permissions_tool.py +1 -0
  37. pycodex/tools/runtime_services.py +122 -450
  38. pycodex/tools/send_message_tool.py +42 -0
  39. pycodex/tools/spawn_agent_tool.py +55 -94
  40. pycodex/tools/unified_exec_manager.py +26 -35
  41. pycodex/tools/wait_agent_tool.py +46 -66
  42. pycodex/tools/wait_tool.py +24 -13
  43. pycodex/tools/web_search_tool.py +1 -0
  44. pycodex/utils/codex_config.py +105 -0
  45. pycodex/utils/compactor.py +4 -0
  46. pycodex/utils/compat.py +43 -2
  47. pycodex/utils/doctor.py +5 -4
  48. pycodex/utils/dotenv.py +0 -7
  49. pycodex/utils/event_helpers.py +143 -13
  50. pycodex/utils/history.py +59 -0
  51. pycodex/utils/session_persist.py +104 -48
  52. python_codex-0.6.1.dist-info/METADATA +201 -0
  53. python_codex-0.6.1.dist-info/RECORD +106 -0
  54. responses_server/__init__.py +2 -0
  55. responses_server/app.py +10 -7
  56. responses_server/config.py +6 -12
  57. responses_server/gemini_api.py +333 -0
  58. responses_server/messages_api.py +9 -1
  59. responses_server/payload_processors.py +4 -4
  60. responses_server/request_translation.py +486 -0
  61. responses_server/server.py +31 -24
  62. responses_server/stream_events.py +124 -0
  63. responses_server/stream_router.py +48 -830
  64. responses_server/tools/custom_adapter.py +29 -29
  65. responses_server/tools/web_search.py +3 -0
  66. responses_server/transport.py +388 -0
  67. pycodex/tools/close_agent_tool.py +0 -60
  68. pycodex/tools/exec_runtime.js +0 -161
  69. pycodex/tools/request_user_input_tool.py +0 -102
  70. pycodex/tools/resume_agent_tool.py +0 -54
  71. pycodex/tools/send_input_tool.py +0 -110
  72. python_codex-0.5.2.dist-info/METADATA +0 -262
  73. python_codex-0.5.2.dist-info/RECORD +0 -90
  74. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/WHEEL +0 -0
  75. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/entry_points.txt +0 -0
  76. {python_codex-0.5.2.dist-info → python_codex-0.6.1.dist-info}/licenses/LICENSE +0 -0
responses_server/app.py CHANGED
@@ -16,8 +16,9 @@ from starlette.responses import JSONResponse, StreamingResponse
16
16
  from starlette.routing import Route
17
17
 
18
18
  from .config import CompatServerConfig
19
- from .server import ResponseServer
20
- from .stream_router import OutcommingChatError, UnsupportedIncommingFeature
19
+ from .request_translation import UnsupportedIncommingFeature
20
+ from .server import PreparedResponse, ResponseServer
21
+ from .transport import OutcommingChatError
21
22
 
22
23
 
23
24
  def _run_uvicorn_server(server) -> "None":
@@ -32,20 +33,22 @@ async def _http_exception_response(request: "Request", exc: "HTTPException"):
32
33
 
33
34
 
34
35
  def _format_sse_event(
35
- event_name: "str", payload: "typing.Dict[str, object]"
36
+ event_name: "typing.Union[str, None]", payload: "typing.Dict[str, object]"
36
37
  ) -> "bytes":
38
+ if event_name is None:
39
+ return b": keep-alive\n\n"
37
40
  data = json.dumps(payload, ensure_ascii=False)
38
41
  return f"event: {event_name}\ndata: {data}\n\n".encode("utf-8")
39
42
 
40
43
 
41
44
  def _stream_events(
42
45
  response_server: "ResponseServer",
43
- request_body: "typing.Dict[str, object]",
46
+ prepared: "PreparedResponse",
44
47
  request_headers: "typing.Dict[str, str]",
45
48
  ) -> "Iterator[bytes]":
46
49
  try:
47
50
  event_iter = response_server.start_response_stream(
48
- request_body, request_headers
51
+ prepared, request_headers
49
52
  )
50
53
  for event_name, payload in event_iter:
51
54
  yield _format_sse_event(event_name, payload)
@@ -159,7 +162,7 @@ class ManagedResponseServer:
159
162
  str(key).lower(): str(value) for key, value in request.headers.items()
160
163
  }
161
164
  try:
162
- response_server.stream_router.validate_incomming_request(request_body)
165
+ prepared = response_server.prepare_response(request_body)
163
166
  except UnsupportedIncommingFeature as exc:
164
167
  return JSONResponse(
165
168
  {"error": {"message": str(exc)}},
@@ -167,7 +170,7 @@ class ManagedResponseServer:
167
170
  )
168
171
 
169
172
  return StreamingResponse(
170
- _stream_events(response_server, request_body, request_headers),
173
+ _stream_events(response_server, prepared, request_headers),
171
174
  media_type="text/event-stream",
172
175
  headers={
173
176
  "Cache-Control": "no-cache",
@@ -32,6 +32,11 @@ class CompatServerConfig:
32
32
  base = self.outcomming_base_url.rstrip("/")
33
33
  return f"{base}/messages"
34
34
 
35
+ def outcomming_gemini_url(self, model: "str") -> "str":
36
+ base = self.outcomming_base_url.rstrip("/")
37
+ model_path = urllib.parse.quote(model, safe="")
38
+ return f"{base}/models/{model_path}:streamGenerateContent?alt=sse"
39
+
35
40
  def outcomming_models_url(self) -> "str":
36
41
  base = self.outcomming_base_url.rstrip("/")
37
42
  return f"{base}/models"
@@ -40,17 +45,6 @@ class CompatServerConfig:
40
45
  value = str(self.outcomming_api or "").strip().lower()
41
46
  return value or "chat_completions"
42
47
 
43
- def with_ephemeral_port(self) -> "CompatServerConfig":
44
- return CompatServerConfig(
45
- host=self.host,
46
- port=0,
47
- outcomming_base_url=self.outcomming_base_url,
48
- outcomming_api=self.outcomming_api,
49
- outcomming_api_key_env=self.outcomming_api_key_env,
50
- model_provider=self.model_provider,
51
- timeout_seconds=self.timeout_seconds,
52
- )
53
-
54
48
  @classmethod
55
49
  def from_base_url(
56
50
  cls,
@@ -64,7 +58,7 @@ class CompatServerConfig:
64
58
  raise ValueError(f"invalid outcomming base url: {outcomming_base_url}")
65
59
  normalized_path = parsed.path.rstrip("/")
66
60
  if normalized_path in {"", "/"}:
67
- parsed = parsed._replace(path="/v1")
61
+ parsed = parsed._replace(path="/v1beta" if outcomming_api == "gemini" else "/v1")
68
62
  outcomming_base_url = urllib.parse.urlunparse(parsed)
69
63
  else:
70
64
  outcomming_base_url = urllib.parse.urlunparse(
@@ -0,0 +1,333 @@
1
+ """Gemini generateContent request and streaming response adapter."""
2
+
3
+ import json
4
+ import re
5
+ import uuid
6
+ from copy import deepcopy
7
+
8
+
9
+ class GeminiAPIAdapterError(ValueError):
10
+ pass
11
+
12
+
13
+ def build_gemini_request(request):
14
+ contents = []
15
+ system_parts = []
16
+ calls = {}
17
+ for message in request.get("messages", []):
18
+ role = message["role"]
19
+ if role in {"system", "developer"}:
20
+ system_parts.extend(_content_parts(message.get("content")))
21
+ continue
22
+ if role == "assistant":
23
+ active_call_ids = set()
24
+ for call in message.get("tool_calls", []):
25
+ calls[call["id"]] = call["function"]["name"]
26
+ active_call_ids.add(call["id"])
27
+ native = message.get("provider_data", [])
28
+ native = [entry for entry in native if entry["provider"] == "gemini"]
29
+ if native:
30
+ # Compaction may prune a call/result pair while retaining the
31
+ # opaque reasoning item. Never replay a removed function call.
32
+ parts = [deepcopy(entry["part"]) for entry in native
33
+ if "call_id" not in entry or entry["call_id"] in active_call_ids]
34
+ else:
35
+ parts = _content_parts(message.get("content"))
36
+ for call in message.get("tool_calls", []):
37
+ function = call["function"]
38
+ arguments = json.loads(function["arguments"])
39
+ if not isinstance(arguments, dict):
40
+ raise GeminiAPIAdapterError("Gemini function arguments must be objects")
41
+ parts.append({"functionCall": {
42
+ "name": function["name"], "args": arguments, "id": call["id"],
43
+ }})
44
+ role = "model"
45
+ elif role == "tool":
46
+ call_id = message["tool_call_id"]
47
+ if call_id not in calls:
48
+ raise GeminiAPIAdapterError("Gemini tool result has no matching function call")
49
+ parts = [{"functionResponse": {
50
+ "name": calls[call_id], "id": call_id,
51
+ "response": {"result": message.get("content", "")},
52
+ }}]
53
+ role = "user"
54
+ elif role == "user":
55
+ parts = _content_parts(message.get("content"))
56
+ else:
57
+ raise GeminiAPIAdapterError("unsupported Gemini message role: {!r}".format(role))
58
+ if parts:
59
+ # Batch parallel function responses, keeping subsequent image input
60
+ # in its own user content as provided by the canonical translator.
61
+ if message["role"] == "tool" and contents and all(
62
+ "functionResponse" in part for part in contents[-1]["parts"]
63
+ ):
64
+ contents[-1]["parts"].extend(parts)
65
+ else:
66
+ contents.append({"role": role, "parts": parts})
67
+
68
+ payload = {"contents": contents}
69
+ if system_parts:
70
+ payload["systemInstruction"] = {"parts": system_parts}
71
+ generation = {"thinkingConfig": {"includeThoughts": True}}
72
+ if "max_tokens" in request:
73
+ generation["maxOutputTokens"] = request["max_tokens"]
74
+ effort = request.get("chat_template_kwargs", {}).get("reasoning_effort")
75
+ if effort is not None:
76
+ levels = {
77
+ "none": "minimal", "minimal": "minimal", "low": "low",
78
+ "medium": "medium", "high": "high", "xhigh": "high", "max": "high",
79
+ }
80
+ if effort not in levels:
81
+ raise GeminiAPIAdapterError("unsupported Gemini reasoning effort: {!r}".format(effort))
82
+ generation["thinkingConfig"]["thinkingLevel"] = levels[effort]
83
+ payload["generationConfig"] = generation
84
+
85
+ declarations = []
86
+ for tool in request.get("tools", []):
87
+ if tool["type"] != "function":
88
+ raise GeminiAPIAdapterError("Gemini backend requires function-style tools")
89
+ function = tool["function"]
90
+ declarations.append({
91
+ "name": function["name"], "description": function.get("description", ""),
92
+ "parametersJsonSchema": deepcopy(function.get("parameters", {"type": "object"})),
93
+ })
94
+ if declarations:
95
+ payload["tools"] = [{"functionDeclarations": declarations}]
96
+ choice = request.get("tool_choice", "auto")
97
+ if isinstance(choice, dict) and choice.get("type") == "function":
98
+ config = {"mode": "ANY", "allowedFunctionNames": [choice["function"]["name"]]}
99
+ elif choice in ("auto", "required", "none"):
100
+ config = {"mode": {"auto": "AUTO", "required": "ANY", "none": "NONE"}[choice]}
101
+ else:
102
+ raise GeminiAPIAdapterError("unsupported Gemini tool_choice")
103
+ config["streamFunctionCallArguments"] = True
104
+ payload["toolConfig"] = {"functionCallingConfig": config}
105
+ return payload
106
+
107
+
108
+ def _content_parts(content):
109
+ if not content:
110
+ return []
111
+ if isinstance(content, str):
112
+ return [{"text": content}]
113
+ parts = []
114
+ for part in content:
115
+ if part["type"] == "text":
116
+ parts.append({"text": part["text"]})
117
+ elif part["type"] == "image_url":
118
+ url = part["image_url"]["url"]
119
+ if url.startswith("data:"):
120
+ header, separator, data = url.partition(",")
121
+ mime_type = header[5:].split(";")[0]
122
+ if not separator or not header.endswith(";base64") or not mime_type or not data:
123
+ raise GeminiAPIAdapterError("Gemini images require a base64 data URL with a media type")
124
+ parts.append({"inlineData": {"mimeType": mime_type, "data": data}})
125
+ else:
126
+ raise GeminiAPIAdapterError("Gemini images require a base64 data URL with a media type")
127
+ else:
128
+ raise GeminiAPIAdapterError("unsupported Gemini content part: {!r}".format(part["type"]))
129
+ return parts
130
+
131
+
132
+ def iter_chat_chunks(payload, state):
133
+ if not isinstance(payload, dict):
134
+ raise GeminiAPIAdapterError("Gemini stream payload must be an object")
135
+ if "error" in payload:
136
+ error = payload["error"]
137
+ message = error.get("message", "Gemini API error") if isinstance(error, dict) else str(error)
138
+ raise GeminiAPIAdapterError(message)
139
+ blocked = payload.get("promptFeedback", {}).get("blockReason")
140
+ if blocked:
141
+ raise GeminiAPIAdapterError("Gemini prompt blocked: {}".format(blocked))
142
+ candidates = payload.get("candidates", [])
143
+ if len(candidates) > 1:
144
+ raise GeminiAPIAdapterError("Gemini adapter requires a single candidate")
145
+ for candidate in candidates:
146
+ if candidate.get("index", 0) != 0:
147
+ raise GeminiAPIAdapterError("unexpected Gemini candidate index")
148
+ finish = candidate.get("finishReason")
149
+ if finish and finish != "STOP":
150
+ raise GeminiAPIAdapterError("Gemini generation ended with {}".format(finish))
151
+ for part in candidate.get("content", {}).get("parts", []):
152
+ if "functionCall" in part:
153
+ chunk = _consume_function_call(part, state)
154
+ if chunk is not None:
155
+ yield chunk
156
+ elif "text" in part or "thoughtSignature" in part:
157
+ entry = {"provider": "gemini", "part": deepcopy(part)}
158
+ state.setdefault("provider_data", []).append(entry)
159
+ text = part.get("text", "")
160
+ if not text and state.get("last_call_id"):
161
+ entry["call_id"] = state["last_call_id"]
162
+ if text:
163
+ state.pop("last_call_id", None)
164
+ kind = "reasoning_content" if part.get("thought") else "content"
165
+ yield _delta({kind: text})
166
+ else:
167
+ raise GeminiAPIAdapterError("unsupported Gemini output part: {}".format(
168
+ ", ".join(sorted(part)),
169
+ ))
170
+ if finish:
171
+ if "function_call" in state:
172
+ raise GeminiAPIAdapterError("Gemini stream ended with an incomplete function call")
173
+ state["finished"] = True
174
+ yield {"choices": [{"index": 0, "delta": {}, "finish_reason": (
175
+ "tool_calls" if "tool_index" in state else "stop"
176
+ )}]}
177
+ usage = payload.get("usageMetadata", {})
178
+ token_counts = state.setdefault("token_counts", {})
179
+ for key in ("candidatesTokenCount", "thoughtsTokenCount"):
180
+ if key in usage:
181
+ token_counts[key] = usage[key]
182
+ translated = {}
183
+ for source, target in (("promptTokenCount", "prompt_tokens"), ("totalTokenCount", "total_tokens")):
184
+ if source in usage:
185
+ translated[target] = usage[source]
186
+ if "candidatesTokenCount" in usage or "thoughtsTokenCount" in usage:
187
+ translated["completion_tokens"] = (
188
+ token_counts.get("candidatesTokenCount", 0)
189
+ + token_counts.get("thoughtsTokenCount", 0)
190
+ )
191
+ if "thoughtsTokenCount" in usage:
192
+ translated["completion_tokens_details"] = {"reasoning_tokens": usage["thoughtsTokenCount"]}
193
+ if "cachedContentTokenCount" in usage:
194
+ translated["prompt_tokens_details"] = {"cached_tokens": usage["cachedContentTokenCount"]}
195
+ if translated:
196
+ yield {"choices": [], "usage": translated}
197
+
198
+
199
+ def _consume_function_call(part, state):
200
+ call = part["functionCall"]
201
+ active = state.get("function_call")
202
+ if active is None:
203
+ if not isinstance(call.get("name"), str) or not call["name"] or not isinstance(call.get("args", {}), dict):
204
+ raise GeminiAPIAdapterError("invalid Gemini function call")
205
+ native = {key: deepcopy(value) for key, value in call.items()
206
+ if key not in {"partialArgs", "willContinue"}}
207
+ entry = {"provider": "gemini", "part": dict(deepcopy(part), functionCall=native),
208
+ "call_id": call.get("id") or "call_" + uuid.uuid4().hex}
209
+ state.setdefault("provider_data", []).append(entry)
210
+ state["tool_index"] = state.get("tool_index", -1) + 1
211
+ active = {"entry": entry, "pending": {}}
212
+ state["function_call"] = active
213
+ state["last_call_id"] = entry["call_id"]
214
+ else:
215
+ native = active["entry"]["part"]["functionCall"]
216
+ if ("name" in call and call["name"] != native["name"]
217
+ or "id" in call and call["id"] != native.get("id")
218
+ or "args" in call):
219
+ raise GeminiAPIAdapterError("conflicting Gemini function call fragment")
220
+ if "thoughtSignature" in part:
221
+ state["provider_data"].append({
222
+ "provider": "gemini", "call_id": active["entry"]["call_id"],
223
+ "part": {"text": "", "thoughtSignature": part["thoughtSignature"]},
224
+ })
225
+ for partial in call.get("partialArgs", []):
226
+ _consume_partial_argument(partial, native.setdefault("args", {}), active["pending"])
227
+ if call.get("willContinue", False):
228
+ return None
229
+ if active["pending"]:
230
+ raise GeminiAPIAdapterError("Gemini function call ended with incomplete arguments")
231
+ del state["function_call"]
232
+ return _delta({"tool_calls": [{
233
+ "index": state["tool_index"], "id": active["entry"]["call_id"], "type": "function",
234
+ "function": {"name": native["name"], "arguments": json.dumps(
235
+ native.get("args", {}), ensure_ascii=False, separators=(",", ":"),
236
+ )},
237
+ }]})
238
+
239
+
240
+ def _consume_partial_argument(partial, arguments, pending):
241
+ raw_path = partial.get("jsonPath")
242
+ container = raw_path[-2:] if isinstance(raw_path, str) else None
243
+ is_container = container in ("{}", "[]")
244
+ path = _argument_path(raw_path[:-2] if is_container else raw_path)
245
+ fields = [key for key in ("stringValue", "numberValue", "boolValue", "nullValue")
246
+ if key in partial]
247
+ if len(fields) != (0 if is_container else 1):
248
+ raise GeminiAPIAdapterError("Gemini partial argument must contain one value")
249
+ field = fields[0] if fields else None
250
+ value = partial[field] if field is not None else ([] if container == "[]" else {})
251
+ if field == "stringValue":
252
+ if not isinstance(value, str):
253
+ raise GeminiAPIAdapterError("invalid Gemini string argument")
254
+ chunks = pending.setdefault(path, [])
255
+ chunks.append(value)
256
+ if partial.get("willContinue", False):
257
+ return
258
+ value = "".join(pending.pop(path))
259
+ else:
260
+ if path in pending or partial.get("willContinue", False):
261
+ raise GeminiAPIAdapterError("invalid Gemini scalar argument continuation")
262
+ if field == "numberValue" and (isinstance(value, bool) or not isinstance(value, (int, float))):
263
+ raise GeminiAPIAdapterError("invalid Gemini number argument")
264
+ if field == "boolValue" and not isinstance(value, bool):
265
+ raise GeminiAPIAdapterError("invalid Gemini boolean argument")
266
+ if field == "nullValue":
267
+ if isinstance(value, bool) or value not in (None, "NULL_VALUE", 0):
268
+ raise GeminiAPIAdapterError("invalid Gemini null argument")
269
+ value = None
270
+ node = arguments
271
+ for index, key in enumerate(path):
272
+ last = index == len(path) - 1
273
+ child = value if last else ([] if isinstance(path[index + 1], int) else {})
274
+ if isinstance(node, dict) and isinstance(key, str):
275
+ if key not in node:
276
+ node[key] = child
277
+ elif last:
278
+ raise GeminiAPIAdapterError("duplicate Gemini argument path")
279
+ elif isinstance(node, list) and isinstance(key, int) and key <= len(node):
280
+ if key == len(node):
281
+ node.append(child)
282
+ elif last:
283
+ raise GeminiAPIAdapterError("duplicate Gemini argument path")
284
+ else:
285
+ raise GeminiAPIAdapterError("invalid Gemini argument path structure")
286
+ node = node[key]
287
+
288
+
289
+ def _argument_path(path):
290
+ # Function arguments use concrete member/index paths, never JSONPath queries.
291
+ pattern = r'''\.([^\W\d]\w*)|\[(0|[1-9][0-9]*|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\]'''
292
+ if not isinstance(path, str) or not path.startswith("$"):
293
+ raise GeminiAPIAdapterError("invalid Gemini argument path")
294
+ keys = []
295
+ offset = 1
296
+ while offset < len(path):
297
+ match = re.match(pattern, path[offset:])
298
+ if match is None:
299
+ raise GeminiAPIAdapterError("invalid Gemini argument path")
300
+ member, bracket = match.groups()
301
+ if member is not None:
302
+ key = member
303
+ elif bracket[0] in ("'", '"'):
304
+ if bracket[0] == "'":
305
+ bracket = '"' + re.sub(
306
+ r'''\\(.)|"''',
307
+ lambda item: "'" if item.group(1) == "'" else
308
+ '\\"' if item.group(0) == '"' else item.group(0),
309
+ bracket[1:-1],
310
+ ) + '"'
311
+ try:
312
+ key = json.loads(bracket)
313
+ except ValueError as exc:
314
+ raise GeminiAPIAdapterError("invalid Gemini argument path") from exc
315
+ else:
316
+ key = int(bracket)
317
+ keys.append(key)
318
+ offset += match.end()
319
+ if not keys or not isinstance(keys[0], str):
320
+ raise GeminiAPIAdapterError("Gemini function arguments must be objects")
321
+ return tuple(keys)
322
+
323
+
324
+ def _delta(delta):
325
+ return {"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
326
+
327
+
328
+ def continuation_chunk(state):
329
+ """Use the existing opaque reasoning-item contract for durable native state."""
330
+ return {"reasoning_item": {
331
+ "type": "reasoning", "summary": [],
332
+ "provider_data": deepcopy(state.get("provider_data", [])),
333
+ }}
@@ -5,7 +5,9 @@ DEFAULT_MESSAGES_MAX_TOKENS = 32000
5
5
 
6
6
 
7
7
  class MessagesAPIAdapterError(ValueError):
8
- pass
8
+ def __init__(self, message, error_type=None):
9
+ super().__init__(message)
10
+ self.error_type = error_type
9
11
 
10
12
 
11
13
  def build_messages_request(
@@ -160,6 +162,12 @@ def iter_chat_chunks(
160
162
  delta = payload.get("delta") or {}
161
163
  if not isinstance(delta, dict):
162
164
  return chunks
165
+ if delta.get("stop_reason") == "refusal":
166
+ message = "messages generation refused (stop_reason=refusal)"
167
+ details = delta.get("stop_details")
168
+ if isinstance(details, dict) and details.get("explanation"):
169
+ message += ": " + str(details["explanation"])
170
+ raise MessagesAPIAdapterError(message, error_type="invalid_prompt")
163
171
  finish_reason = _translate_stop_reason(delta.get("stop_reason"))
164
172
  if finish_reason and not bool(state.get("finish_emitted")):
165
173
  state["finish_reason"] = finish_reason
@@ -2,8 +2,8 @@
2
2
 
3
3
  Each downstream chat-completions provider may have its own payload quirks:
4
4
  extra fields, removed fields, role normalization, tool-shape tweaks, etc.
5
- Keep all of those provider-specific rewrites here so `StreamRouter` can keep
6
- building one canonical `outcomming_request`, while `server.py` selects the
5
+ Keep all of those provider-specific rewrites here so request translation produces
6
+ one canonical `outcomming_request`, while `server.py` selects the
7
7
  appropriate hook from `CompatServerConfig.model_provider`.
8
8
  """
9
9
 
@@ -11,7 +11,7 @@ import typing
11
11
  from copy import deepcopy
12
12
  from typing import Callable, Optional
13
13
 
14
- from typing_extensions import TypedDict
14
+ from pycodex.utils.compat import TypedDict
15
15
 
16
16
  ChatMessage = typing.Dict[str, object]
17
17
 
@@ -20,7 +20,7 @@ class OutgoingRequest(TypedDict):
20
20
  """Canonical downstream `/v1/chat/completions` request shape.
21
21
 
22
22
  `model`, `messages`, and `stream` are always populated by
23
- `StreamRouter.build_outcomming_request(...)`. Provider-specific fields that
23
+ `request_translation.build_outcomming_request(...)`. Provider-specific fields that
24
24
  may be omitted use `Optional[...]` here so the schema stays simple and does
25
25
  not rely on TypedDict inheritance.
26
26
  """