traceforge-pcb 1.0.0__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 (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,764 @@
1
+ """Model providers.
2
+
3
+ The agent loop speaks the Anthropic Messages shape (``client.messages.stream``).
4
+ Claude models use the official Anthropic SDK directly. Other providers (OpenAI,
5
+ Google Gemini) are wrapped in adapters that present the same interface, so the loop, tools,
6
+ prompts and session format stay identical whichever model runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import json
13
+ import os
14
+ from types import SimpleNamespace
15
+ from typing import Any
16
+
17
+ from anthropic.types import Message, TextBlock, ThinkingBlock, ToolUseBlock, Usage
18
+
19
+ DEFAULT_OPENAI_MODEL = "gpt-6.1-sol"
20
+ DEFAULT_GEMINI_MODEL = "gemini-2.5-flash" # fallback only; see models.pick_tiers
21
+
22
+
23
+ def provider_for(model: str, explicit: str | None = None) -> str:
24
+ if explicit and explicit != "auto":
25
+ return explicit
26
+ if model.startswith("local/"): # usage records of a local server's model
27
+ return "local"
28
+ if model.startswith("claude"):
29
+ return "anthropic"
30
+ if model.startswith(("gpt", "o1", "o3", "o4", "o5", "codex")):
31
+ return "openai"
32
+ if model.startswith(("gemini", "models/gemini")):
33
+ return "gemini"
34
+ return "anthropic"
35
+
36
+
37
+ def gemini_key() -> str | None:
38
+ """Gemini API key: ``GEMINI_API_KEY`` or ``GOOGLE_API_KEY`` (as the google-genai SDK)."""
39
+ return os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") or None
40
+
41
+
42
+ def default_provider() -> str:
43
+ """Pick a provider from the credentials that are available."""
44
+ has_anthropic = bool(
45
+ os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_AUTH_TOKEN")
46
+ )
47
+ if not has_anthropic and os.environ.get("OPENAI_API_KEY"):
48
+ return "openai"
49
+ if not has_anthropic and gemini_key():
50
+ return "gemini"
51
+ return "anthropic"
52
+
53
+
54
+ def make_client(provider: str, settings: Any = None) -> Any:
55
+ if provider == "local":
56
+ from traceforge.local import LocalAdapter
57
+
58
+ return LocalAdapter.from_settings(settings)
59
+ if provider == "openai":
60
+ return OpenAIAdapter()
61
+ if provider == "gemini":
62
+ return GeminiAdapter()
63
+ import anthropic
64
+
65
+ return anthropic.AsyncAnthropic()
66
+
67
+
68
+ # --------------------------------------------------------------------- OpenAI
69
+ #
70
+ # OpenAI models run through the Responses API, the endpoint that supports
71
+ # function tools together with reasoning. The loop is stateless (``store`` is
72
+ # off): each turn sends the whole history. OpenAI's encrypted reasoning items
73
+ # are kept in the Anthropic-shaped history as ``thinking`` blocks whose
74
+ # signature carries the item, and sent back in place, so the model keeps its
75
+ # reasoning across tool calls.
76
+
77
+ _REASONING_TAG = "openai-reasoning:"
78
+ _EFFORT = {"low": "low", "medium": "medium", "high": "high", "xhigh": "high", "max": "high"}
79
+
80
+
81
+ def _text_of(blocks: Any) -> str:
82
+ if isinstance(blocks, str):
83
+ return blocks
84
+ return "\n\n".join(
85
+ b.get("text", "") for b in blocks if isinstance(b, dict) and b.get("type") == "text"
86
+ )
87
+
88
+
89
+ def to_openai_input(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
90
+ """Anthropic-shaped history -> Responses API input items, in order."""
91
+ items: list[dict[str, Any]] = []
92
+ for message in messages:
93
+ content = message["content"]
94
+ role = message["role"]
95
+ if isinstance(content, str):
96
+ items.append({"role": role, "content": content})
97
+ continue
98
+ if role == "assistant":
99
+ for block in content:
100
+ kind = block.get("type")
101
+ if kind == "thinking":
102
+ signature = block.get("signature") or ""
103
+ if signature.startswith(_REASONING_TAG):
104
+ items.append(json.loads(signature[len(_REASONING_TAG) :]))
105
+ elif kind == "text" and block.get("text"):
106
+ items.append({"role": "assistant", "content": block["text"]})
107
+ elif kind == "tool_use":
108
+ items.append(
109
+ {
110
+ "type": "function_call",
111
+ "call_id": block["id"],
112
+ "name": block["name"],
113
+ "arguments": json.dumps(block.get("input") or {}),
114
+ }
115
+ )
116
+ continue
117
+ texts: list[str] = []
118
+ images: list[dict[str, Any]] = []
119
+ for block in content:
120
+ if block.get("type") == "tool_result":
121
+ result = block.get("content", "")
122
+ if not isinstance(result, str):
123
+ found = [_openai_image(b) for b in result if b.get("type") == "image"]
124
+ images.extend(i for i in found if i)
125
+ result = _text_of(result)
126
+ if found:
127
+ result += (
128
+ f"\n[{len(found)} image(s) from this tool follow in the next message]"
129
+ )
130
+ if block.get("is_error"):
131
+ result = f"[tool error] {result}"
132
+ items.append(
133
+ {
134
+ "type": "function_call_output",
135
+ "call_id": block["tool_use_id"],
136
+ "output": result,
137
+ }
138
+ )
139
+ elif block.get("type") == "text":
140
+ texts.append(block["text"])
141
+ elif block.get("type") == "image":
142
+ image = _openai_image(block)
143
+ if image:
144
+ images.append(image)
145
+ if texts or images:
146
+ # Function outputs carry text only; images (from tools or the user) follow
147
+ # as one user message, after every output of the step.
148
+ parts: list[dict[str, Any]] = []
149
+ if texts:
150
+ parts.append({"type": "input_text", "text": "\n\n".join(texts)})
151
+ parts.extend(images)
152
+ if images and not texts:
153
+ parts.insert(0, {"type": "input_text", "text": "Images returned by the tools:"})
154
+ items.append({"role": "user", "content": parts})
155
+ return items
156
+
157
+
158
+ def _openai_image(block: dict[str, Any]) -> dict[str, Any] | None:
159
+ source = block.get("source") or {}
160
+ if source.get("type") == "base64" and source.get("data"):
161
+ url = f"data:{source.get('media_type', 'image/png')};base64,{source['data']}"
162
+ elif source.get("type") == "url" and source.get("url"):
163
+ url = source["url"]
164
+ else:
165
+ return None
166
+ return {"type": "input_image", "image_url": url, "detail": "auto"}
167
+
168
+
169
+ def to_openai_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
170
+ return [
171
+ {
172
+ "type": "function",
173
+ "name": t["name"],
174
+ "description": t.get("description", ""),
175
+ "parameters": t.get("input_schema", {"type": "object"}),
176
+ "strict": False,
177
+ }
178
+ for t in tools
179
+ ]
180
+
181
+
182
+ def _get(obj: Any, name: str, default: Any = None) -> Any:
183
+ if isinstance(obj, dict):
184
+ return obj.get(name, default)
185
+ return getattr(obj, name, default)
186
+
187
+
188
+ def _dump(item: Any) -> dict[str, Any]:
189
+ if isinstance(item, dict):
190
+ data = dict(item)
191
+ elif hasattr(item, "model_dump"):
192
+ data = item.model_dump(exclude_none=True)
193
+ else:
194
+ data = dict(vars(item))
195
+ data.pop("status", None)
196
+ return {k: v for k, v in data.items() if v is not None}
197
+
198
+
199
+ class _OpenAIStream:
200
+ def __init__(self, adapter: OpenAIAdapter, request: dict[str, Any]):
201
+ self.adapter = adapter
202
+ self.request = request
203
+ self._final: Message | None = None
204
+
205
+ async def __aenter__(self) -> _OpenAIStream:
206
+ return self
207
+
208
+ async def __aexit__(self, *exc: Any) -> bool:
209
+ return False
210
+
211
+ def __aiter__(self):
212
+ return self._events()
213
+
214
+ async def _create(self):
215
+ import openai
216
+
217
+ try:
218
+ return await self.adapter.client.responses.create(**self.request)
219
+ except openai.BadRequestError as exc:
220
+ reasoning = self.request.get("reasoning") or {}
221
+ if "summary" in reasoning and "summar" in str(exc).lower():
222
+ reasoning.pop("summary") # e.g. reasoning summaries not enabled for the org
223
+ try:
224
+ return await self.adapter.client.responses.create(**self.request)
225
+ except openai.OpenAIError as retry_exc:
226
+ raise _agent_error(retry_exc) from retry_exc
227
+ if "reasoning" in self.request and "reasoning" in str(exc).lower():
228
+ self.request.pop("reasoning") # a model without reasoning controls
229
+ self.request.pop("include", None)
230
+ try:
231
+ return await self.adapter.client.responses.create(**self.request)
232
+ except openai.OpenAIError as retry_exc:
233
+ raise _agent_error(retry_exc) from retry_exc
234
+ raise _agent_error(exc) from exc
235
+ except openai.OpenAIError as exc:
236
+ raise _agent_error(exc) from exc
237
+
238
+ async def _events(self):
239
+ import openai
240
+
241
+ from traceforge.agent import AgentError
242
+
243
+ stream = await self._create()
244
+ response = None
245
+ try:
246
+ async for event in stream:
247
+ kind = _get(event, "type", "")
248
+ if kind == "response.output_text.delta":
249
+ yield SimpleNamespace(type="text", text=_get(event, "delta", ""))
250
+ elif kind == "response.reasoning_summary_text.delta":
251
+ yield SimpleNamespace(type="thinking", thinking=_get(event, "delta", ""))
252
+ elif kind in ("response.completed", "response.incomplete"):
253
+ response = _get(event, "response")
254
+ elif kind == "response.failed":
255
+ error = _get(_get(event, "response"), "error")
256
+ raise AgentError(f"OpenAI response failed: {_get(error, 'message', error)}")
257
+ elif kind == "error":
258
+ raise AgentError(f"OpenAI stream error: {_get(event, 'message', event)}")
259
+ except openai.OpenAIError as exc:
260
+ raise _agent_error(exc) from exc
261
+ if response is None:
262
+ raise AgentError("OpenAI stream ended without a response")
263
+ self._final = self._to_message(response)
264
+
265
+ def _to_message(self, response: Any) -> Message:
266
+ blocks: list[Any] = []
267
+ calls = 0
268
+ refused = False
269
+ for item in _get(response, "output", None) or []:
270
+ kind = _get(item, "type")
271
+ if kind == "reasoning":
272
+ summary = "\n".join(
273
+ _get(part, "text", "") for part in (_get(item, "summary", None) or [])
274
+ )
275
+ blocks.append(
276
+ ThinkingBlock(
277
+ type="thinking",
278
+ thinking=summary,
279
+ signature=_REASONING_TAG + json.dumps(_dump(item)),
280
+ )
281
+ )
282
+ elif kind == "message":
283
+ text = ""
284
+ for part in _get(item, "content", None) or []:
285
+ if _get(part, "type") == "output_text":
286
+ text += _get(part, "text", "")
287
+ elif _get(part, "type") == "refusal":
288
+ refused = True
289
+ text += _get(part, "refusal", "")
290
+ if text:
291
+ blocks.append(TextBlock(type="text", text=text))
292
+ elif kind == "function_call":
293
+ calls += 1
294
+ raw = _get(item, "arguments", "") or "{}"
295
+ try:
296
+ arguments = json.loads(raw)
297
+ except json.JSONDecodeError:
298
+ arguments = {"INVALID_JSON": raw[:2000]}
299
+ blocks.append(
300
+ ToolUseBlock(
301
+ type="tool_use",
302
+ id=_get(item, "call_id") or _get(item, "id") or f"call_{calls}",
303
+ name=_get(item, "name", ""),
304
+ input=arguments if isinstance(arguments, dict) else {"value": arguments},
305
+ )
306
+ )
307
+ usage = _get(response, "usage")
308
+ cached = int(_get(_get(usage, "input_tokens_details"), "cached_tokens", 0) or 0)
309
+ prompt = int(_get(usage, "input_tokens", 0) or 0)
310
+ reason = _get(_get(response, "incomplete_details"), "reason")
311
+ if refused and not calls:
312
+ stop = "refusal"
313
+ elif calls:
314
+ stop = "max_tokens" if reason == "max_output_tokens" else "tool_use"
315
+ elif reason == "max_output_tokens":
316
+ stop = "max_tokens"
317
+ elif reason == "content_filter":
318
+ stop = "refusal"
319
+ else:
320
+ stop = "end_turn"
321
+ return Message.model_construct(
322
+ id=_get(response, "id", "openai") or "openai",
323
+ type="message",
324
+ role="assistant",
325
+ model=self.request["model"],
326
+ content=blocks,
327
+ stop_reason=stop,
328
+ stop_sequence=None,
329
+ stop_details=None,
330
+ usage=Usage.model_construct(
331
+ input_tokens=prompt - cached,
332
+ output_tokens=int(_get(usage, "output_tokens", 0) or 0),
333
+ cache_read_input_tokens=cached,
334
+ cache_creation_input_tokens=0,
335
+ ),
336
+ )
337
+
338
+ async def get_final_message(self) -> Message:
339
+ if self._final is None:
340
+ async for _ in self._events():
341
+ pass
342
+ assert self._final is not None
343
+ return self._final
344
+
345
+
346
+ class _Messages:
347
+ def __init__(self, adapter: OpenAIAdapter):
348
+ self.adapter = adapter
349
+
350
+ def stream(self, **kwargs: Any) -> _OpenAIStream:
351
+ request: dict[str, Any] = {
352
+ "model": kwargs["model"],
353
+ "instructions": _text_of(kwargs.get("system", "")),
354
+ "input": to_openai_input(kwargs["messages"]),
355
+ "max_output_tokens": kwargs.get("max_tokens", 32_000),
356
+ "stream": True,
357
+ "store": False,
358
+ }
359
+ if kwargs.get("tools"):
360
+ request["tools"] = to_openai_tools(kwargs["tools"])
361
+ effort = (kwargs.get("output_config") or {}).get("effort")
362
+ if effort:
363
+ request["reasoning"] = {"effort": _EFFORT.get(effort, "medium"), "summary": "auto"}
364
+ request["include"] = ["reasoning.encrypted_content"]
365
+ return _OpenAIStream(self.adapter, request)
366
+
367
+
368
+ class OpenAIAdapter:
369
+ """Presents ``messages.stream`` on top of OpenAI's Responses API."""
370
+
371
+ def __init__(self, client: Any = None):
372
+ if client is None:
373
+ try:
374
+ import openai
375
+ except ImportError as exc: # pragma: no cover - optional dependency
376
+ raise ImportError(
377
+ "OpenAI models need the 'openai' extra: pip install 'traceforge-pcb[openai]'"
378
+ ) from exc
379
+ client = openai.AsyncOpenAI()
380
+ self.client = client
381
+ self.messages = _Messages(self)
382
+
383
+
384
+ def _agent_error(exc: Exception) -> Exception:
385
+ from traceforge.agent import AgentError
386
+
387
+ status = getattr(exc, "status_code", None)
388
+ if status == 401:
389
+ return AgentError("OpenAI authentication failed. Check OPENAI_API_KEY.")
390
+ if status == 429:
391
+ return AgentError(f"Rate limited by OpenAI: {exc}")
392
+ if status == 404:
393
+ return AgentError(f"OpenAI model not found or not available to this key: {exc}")
394
+ return AgentError(f"OpenAI API error{f' {status}' if status else ''}: {exc}")
395
+
396
+
397
+ # --------------------------------------------------------------------- Gemini
398
+ #
399
+ # Gemini models run through the google-genai SDK's ``generate_content_stream``.
400
+ # Like the OpenAI adapter the loop is stateless: each turn sends the whole history.
401
+ # Gemini signs its reasoning with ``thought_signature``s on the parts of a model turn
402
+ # and needs them back unchanged (function calls fail without them on Gemini 3), so
403
+ # each assistant message keeps the turn's raw parts in a ``thinking`` block whose
404
+ # signature carries them; that turn is replayed from those parts.
405
+
406
+ _GEMINI_TAG = "gemini-parts:"
407
+ _GEMINI_LEVEL = {"low": "low", "medium": "medium", "high": "high", "xhigh": "high", "max": "high"}
408
+ # Gemini 2.x models take a thinking token budget instead of a level.
409
+ _GEMINI_BUDGET = {"low": 1024, "medium": 8192, "high": 24576, "xhigh": 24576, "max": 32768}
410
+ # Documented placeholder for function calls that were not made by Gemini (history from
411
+ # another provider): it tells Gemini 3 to skip thought-signature validation.
412
+ _SKIP_SIGNATURE = "skip_thought_signature_validator"
413
+ _GEMINI_REFUSALS = {
414
+ "SAFETY",
415
+ "RECITATION",
416
+ "BLOCKLIST",
417
+ "PROHIBITED_CONTENT",
418
+ "SPII",
419
+ "IMAGE_SAFETY",
420
+ "IMAGE_PROHIBITED_CONTENT",
421
+ }
422
+
423
+
424
+ # Finish reasons where the model produced a broken tool call (or none): not a clean end.
425
+ _GEMINI_BROKEN = {"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "TOO_MANY_TOOL_CALLS"}
426
+
427
+
428
+ def blocks_have_text(blocks: list[Any]) -> bool:
429
+ return any(isinstance(b, TextBlock) and b.text.strip() for b in blocks)
430
+
431
+
432
+ def _gemini_image(block: dict[str, Any]) -> dict[str, Any] | None:
433
+ source = block.get("source") or {}
434
+ if source.get("type") == "base64" and source.get("data"):
435
+ return {
436
+ "inline_data": {
437
+ "mime_type": source.get("media_type", "image/png"),
438
+ "data": source["data"], # base64; the SDK decodes it
439
+ }
440
+ }
441
+ if source.get("type") == "url" and source.get("url"):
442
+ return {"file_data": {"file_uri": source["url"], "mime_type": "image/*"}}
443
+ return None
444
+
445
+
446
+ def to_gemini_contents(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
447
+ """Anthropic-shaped history -> Gemini ``contents`` (roles ``user`` and ``model``)."""
448
+ contents: list[dict[str, Any]] = []
449
+ names: dict[str, str] = {} # tool_use id -> function name (function responses need it)
450
+ for message in messages:
451
+ content = message["content"]
452
+ role = "model" if message["role"] == "assistant" else "user"
453
+ if isinstance(content, str):
454
+ contents.append({"role": role, "parts": [{"text": content}]})
455
+ continue
456
+ parts: list[dict[str, Any]] = []
457
+ if role == "model":
458
+ for block in content:
459
+ if block.get("type") == "tool_use":
460
+ names[block["id"]] = block["name"]
461
+ raw = next(
462
+ (
463
+ b.get("signature", "")[len(_GEMINI_TAG) :]
464
+ for b in content
465
+ if b.get("type") == "thinking"
466
+ and str(b.get("signature") or "").startswith(_GEMINI_TAG)
467
+ ),
468
+ None,
469
+ )
470
+ if raw is not None:
471
+ parts = json.loads(raw)
472
+ else:
473
+ for block in content:
474
+ if block.get("type") == "text" and block.get("text"):
475
+ parts.append({"text": block["text"]})
476
+ elif block.get("type") == "tool_use":
477
+ parts.append(
478
+ {
479
+ "function_call": {
480
+ "id": block["id"],
481
+ "name": block["name"],
482
+ "args": block.get("input") or {},
483
+ },
484
+ "thought_signature": base64.b64encode(
485
+ _SKIP_SIGNATURE.encode()
486
+ ).decode(),
487
+ }
488
+ )
489
+ if parts:
490
+ contents.append({"role": "model", "parts": parts})
491
+ continue
492
+ trailing: list[dict[str, Any]] = []
493
+ for block in content:
494
+ kind = block.get("type")
495
+ if kind == "tool_result":
496
+ result = block.get("content", "")
497
+ if not isinstance(result, str):
498
+ found = [_gemini_image(b) for b in result if b.get("type") == "image"]
499
+ trailing.extend(i for i in found if i)
500
+ result = _text_of(result)
501
+ if any(found):
502
+ result += f"\n[{len(found)} image(s) from this tool follow]"
503
+ key = "error" if block.get("is_error") else "result"
504
+ call_id = block["tool_use_id"]
505
+ parts.append(
506
+ {
507
+ "function_response": {
508
+ "id": call_id,
509
+ "name": names.get(call_id, "tool"),
510
+ "response": {key: result},
511
+ }
512
+ }
513
+ )
514
+ elif kind == "text" and block.get("text"):
515
+ trailing.append({"text": block["text"]})
516
+ elif kind == "image":
517
+ image = _gemini_image(block)
518
+ if image:
519
+ trailing.append(image)
520
+ # Function responses first, then text and images (from tools or the user).
521
+ parts.extend(trailing)
522
+ if parts:
523
+ contents.append({"role": "user", "parts": parts})
524
+ return contents
525
+
526
+
527
+ def to_gemini_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
528
+ return [
529
+ {
530
+ "function_declarations": [
531
+ {
532
+ "name": t["name"],
533
+ "description": t.get("description", ""),
534
+ "parameters_json_schema": t.get("input_schema", {"type": "object"}),
535
+ }
536
+ for t in tools
537
+ ]
538
+ }
539
+ ]
540
+
541
+
542
+ def _gemini_part(part: Any) -> dict[str, Any]:
543
+ """A response part as a JSON-safe dict (bytes such as signatures become base64)."""
544
+ if isinstance(part, dict):
545
+ data = dict(part)
546
+ elif hasattr(part, "model_dump"):
547
+ data = part.model_dump(exclude_none=True, mode="json")
548
+ else:
549
+ data = dict(vars(part))
550
+ signature = data.get("thought_signature")
551
+ if isinstance(signature, bytes):
552
+ data["thought_signature"] = base64.b64encode(signature).decode()
553
+ call = data.get("function_call")
554
+ if call is not None and not isinstance(call, dict):
555
+ data["function_call"] = _gemini_part(call)
556
+ return {k: v for k, v in data.items() if v is not None}
557
+
558
+
559
+ class _GeminiStream:
560
+ def __init__(self, adapter: GeminiAdapter, request: dict[str, Any]):
561
+ self.adapter = adapter
562
+ self.request = request
563
+ self._final: Message | None = None
564
+
565
+ async def __aenter__(self) -> _GeminiStream:
566
+ return self
567
+
568
+ async def __aexit__(self, *exc: Any) -> bool:
569
+ return False
570
+
571
+ def __aiter__(self):
572
+ return self._events()
573
+
574
+ async def _events(self):
575
+ from traceforge.agent import AgentError
576
+
577
+ parts: list[dict[str, Any]] = []
578
+ usage: Any = None
579
+ finish = ""
580
+ response_id = ""
581
+ try:
582
+ stream = await self.adapter.client.aio.models.generate_content_stream(**self.request)
583
+ async for chunk in stream:
584
+ usage = _get(chunk, "usage_metadata") or usage
585
+ response_id = _get(chunk, "response_id") or response_id
586
+ feedback = _get(chunk, "prompt_feedback")
587
+ if _get(feedback, "block_reason") and not _get(chunk, "candidates"):
588
+ finish = "SAFETY"
589
+ for candidate in (_get(chunk, "candidates") or [])[:1]:
590
+ reason = _get(candidate, "finish_reason")
591
+ if reason:
592
+ finish = str(getattr(reason, "value", reason))
593
+ for raw in _get(_get(candidate, "content"), "parts", None) or []:
594
+ part = _gemini_part(raw)
595
+ text = part.get("text")
596
+ if text:
597
+ yield SimpleNamespace(
598
+ type="thinking" if part.get("thought") else "text",
599
+ **({"thinking": text} if part.get("thought") else {"text": text}),
600
+ )
601
+ _merge_part(parts, part)
602
+ except AgentError:
603
+ raise
604
+ except Exception as exc: # google.genai.errors.APIError and transport errors
605
+ raise _gemini_error(exc) from exc
606
+ self._final = self._to_message(parts, usage, finish, response_id)
607
+
608
+ def _to_message(
609
+ self, parts: list[dict[str, Any]], usage: Any, finish: str, response_id: str
610
+ ) -> Message:
611
+ blocks: list[Any] = []
612
+ calls = 0
613
+ for part in parts:
614
+ call = part.get("function_call")
615
+ if call:
616
+ calls += 1
617
+ call["id"] = call.get("id") or f"gemini_call_{calls}" # replayed with the id
618
+ thoughts = "".join(p.get("text", "") for p in parts if p.get("thought"))
619
+ if parts:
620
+ # Raw parts (with thought signatures) for the next request; shown as thinking.
621
+ blocks.append(
622
+ ThinkingBlock(
623
+ type="thinking", thinking=thoughts, signature=_GEMINI_TAG + json.dumps(parts)
624
+ )
625
+ )
626
+ for part in parts:
627
+ if part.get("thought"):
628
+ continue
629
+ if part.get("text"):
630
+ if blocks and isinstance(blocks[-1], TextBlock):
631
+ blocks[-1] = TextBlock(type="text", text=blocks[-1].text + part["text"])
632
+ else:
633
+ blocks.append(TextBlock(type="text", text=part["text"]))
634
+ call = part.get("function_call")
635
+ if call:
636
+ args = call.get("args") or {}
637
+ blocks.append(
638
+ ToolUseBlock(
639
+ type="tool_use",
640
+ id=call["id"],
641
+ name=call.get("name", ""),
642
+ input=args if isinstance(args, dict) else {"value": args},
643
+ )
644
+ )
645
+ finish = finish.upper().rsplit(".", 1)[-1]
646
+ if calls:
647
+ stop = "max_tokens" if finish == "MAX_TOKENS" else "tool_use"
648
+ elif finish == "MAX_TOKENS":
649
+ stop = "max_tokens"
650
+ elif finish in _GEMINI_REFUSALS:
651
+ stop = "refusal"
652
+ elif finish in _GEMINI_BROKEN and not blocks_have_text(blocks):
653
+ from traceforge.agent import AgentError
654
+
655
+ raise AgentError(f"Gemini ended the turn with {finish} and no usable output")
656
+ else:
657
+ stop = "end_turn"
658
+ prompt = int(_get(usage, "prompt_token_count", 0) or 0)
659
+ cached = int(_get(usage, "cached_content_token_count", 0) or 0)
660
+ output = int(_get(usage, "candidates_token_count", 0) or 0) + int(
661
+ _get(usage, "thoughts_token_count", 0) or 0
662
+ )
663
+ return Message.model_construct(
664
+ id=response_id or "gemini",
665
+ type="message",
666
+ role="assistant",
667
+ model=self.request["model"],
668
+ content=blocks,
669
+ stop_reason=stop,
670
+ stop_sequence=None,
671
+ stop_details=None,
672
+ usage=Usage.model_construct(
673
+ input_tokens=max(prompt - cached, 0),
674
+ output_tokens=output,
675
+ cache_read_input_tokens=cached,
676
+ cache_creation_input_tokens=0,
677
+ ),
678
+ )
679
+
680
+ async def get_final_message(self) -> Message:
681
+ if self._final is None:
682
+ async for _ in self._events():
683
+ pass
684
+ assert self._final is not None
685
+ return self._final
686
+
687
+
688
+ def _merge_part(parts: list[dict[str, Any]], part: dict[str, Any]) -> None:
689
+ """Join streamed text pieces into one part; a signature closes the part it is on."""
690
+ previous = parts[-1] if parts else None
691
+ plain = set(part) <= {"text", "thought", "thought_signature"}
692
+ if (
693
+ previous is not None
694
+ and plain
695
+ and set(previous) <= {"text", "thought"}
696
+ and "text" in previous
697
+ and bool(previous.get("thought")) == bool(part.get("thought"))
698
+ ):
699
+ previous["text"] = previous.get("text", "") + part.get("text", "")
700
+ if part.get("thought_signature"):
701
+ previous["thought_signature"] = part["thought_signature"]
702
+ return
703
+ if part.get("text") == "" and not part.get("thought_signature"):
704
+ return
705
+ parts.append(part)
706
+
707
+
708
+ class _GeminiMessages:
709
+ def __init__(self, adapter: GeminiAdapter):
710
+ self.adapter = adapter
711
+
712
+ def stream(self, **kwargs: Any) -> _GeminiStream:
713
+ model = str(kwargs["model"])
714
+ config: dict[str, Any] = {"max_output_tokens": kwargs.get("max_tokens", 32_000)}
715
+ system = _text_of(kwargs.get("system", ""))
716
+ if system:
717
+ config["system_instruction"] = system
718
+ if kwargs.get("tools"):
719
+ config["tools"] = to_gemini_tools(kwargs["tools"])
720
+ config["automatic_function_calling"] = {"disable": True}
721
+ effort = (kwargs.get("output_config") or {}).get("effort")
722
+ # Only Gemini models think; others (e.g. Gemma) reject a thinking config.
723
+ if effort and model.split("/")[-1].startswith("gemini"):
724
+ thinking: dict[str, Any] = {"include_thoughts": True}
725
+ if model.split("/")[-1].startswith(("gemini-2", "gemini-1")):
726
+ thinking["thinking_budget"] = _GEMINI_BUDGET.get(effort, 8192)
727
+ else:
728
+ thinking["thinking_level"] = _GEMINI_LEVEL.get(effort, "medium")
729
+ config["thinking_config"] = thinking
730
+ request = {
731
+ "model": model,
732
+ "contents": to_gemini_contents(kwargs["messages"]),
733
+ "config": config,
734
+ }
735
+ return _GeminiStream(self.adapter, request)
736
+
737
+
738
+ class GeminiAdapter:
739
+ """Presents ``messages.stream`` on top of the google-genai SDK."""
740
+
741
+ def __init__(self, client: Any = None):
742
+ if client is None:
743
+ try:
744
+ from google import genai
745
+ except ImportError as exc: # pragma: no cover - optional dependency
746
+ raise ImportError(
747
+ "Gemini models need the 'gemini' extra: pip install 'traceforge-pcb[gemini]'"
748
+ ) from exc
749
+ client = genai.Client(api_key=gemini_key())
750
+ self.client = client
751
+ self.messages = _GeminiMessages(self)
752
+
753
+
754
+ def _gemini_error(exc: Exception) -> Exception:
755
+ from traceforge.agent import AgentError
756
+
757
+ status = getattr(exc, "code", None) or getattr(exc, "status_code", None)
758
+ if status in (401, 403):
759
+ return AgentError("Gemini authentication failed. Check GEMINI_API_KEY (or GOOGLE_API_KEY).")
760
+ if status == 429:
761
+ return AgentError(f"Rate limited by Gemini: {exc}")
762
+ if status == 404:
763
+ return AgentError(f"Gemini model not found or not available to this key: {exc}")
764
+ return AgentError(f"Gemini API error{f' {status}' if status else ''}: {exc}")