synth-code 0.0.1__py3-none-macosx_15_0_arm64.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 (110) hide show
  1. synth_code/__init__.py +0 -0
  2. synth_code/account.py +551 -0
  3. synth_code/account_http.py +86 -0
  4. synth_code/account_refusal.py +80 -0
  5. synth_code/accounting.py +148 -0
  6. synth_code/activity_grouping.py +149 -0
  7. synth_code/agent_panels.py +127 -0
  8. synth_code/approvals.py +397 -0
  9. synth_code/blobs.py +31 -0
  10. synth_code/cli.py +734 -0
  11. synth_code/client.py +413 -0
  12. synth_code/composer_delivery.py +139 -0
  13. synth_code/conversation.py +949 -0
  14. synth_code/daemon.py +34 -0
  15. synth_code/edition.py +306 -0
  16. synth_code/enrollment.py +304 -0
  17. synth_code/file_edit_facts.py +10 -0
  18. synth_code/freeze.py +234 -0
  19. synth_code/grant.py +59 -0
  20. synth_code/history.py +140 -0
  21. synth_code/history_generated.py +219 -0
  22. synth_code/history_wire.py +166 -0
  23. synth_code/image_input.py +109 -0
  24. synth_code/image_preview.py +105 -0
  25. synth_code/legacy_history.py +161 -0
  26. synth_code/live_turns.py +171 -0
  27. synth_code/model_picker.py +311 -0
  28. synth_code/native/manifest.json +1 -0
  29. synth_code/native/synth-code-runtime +0 -0
  30. synth_code/native.py +95 -0
  31. synth_code/oauth.py +284 -0
  32. synth_code/operator.py +116 -0
  33. synth_code/pack_source.py +65 -0
  34. synth_code/panel_request.py +291 -0
  35. synth_code/panels.py +40 -0
  36. synth_code/plugin_host.py +459 -0
  37. synth_code/protocol.py +35 -0
  38. synth_code/provider.py +313 -0
  39. synth_code/provider_fault.py +173 -0
  40. synth_code/provider_frames.py +571 -0
  41. synth_code/recommendation.py +324 -0
  42. synth_code/report.py +72 -0
  43. synth_code/research_events.py +44 -0
  44. synth_code/research_trace.py +449 -0
  45. synth_code/rex_view.py +58 -0
  46. synth_code/runtime_refusal.py +108 -0
  47. synth_code/schema/budgets.json +17 -0
  48. synth_code/schema/history-v2.json +1002 -0
  49. synth_code/session.py +291 -0
  50. synth_code/shoal.py +564 -0
  51. synth_code/side_panel.py +309 -0
  52. synth_code/skills.py +269 -0
  53. synth_code/slash.py +425 -0
  54. synth_code/source_view.py +135 -0
  55. synth_code/starter.json +13 -0
  56. synth_code/stdio.py +75 -0
  57. synth_code/stream.py +142 -0
  58. synth_code/subscriptions.py +267 -0
  59. synth_code/synth_authority.py +362 -0
  60. synth_code/synth_extra.py +32 -0
  61. synth_code/terminal.py +817 -0
  62. synth_code/terminal_journal.py +284 -0
  63. synth_code/terminal_layout.py +643 -0
  64. synth_code/terminal_surfaces.py +470 -0
  65. synth_code/terminal_viewport.py +125 -0
  66. synth_code/tool_render.py +86 -0
  67. synth_code/transcript_frames.py +212 -0
  68. synth_code/transcript_placement.py +63 -0
  69. synth_code/transcript_rows.py +456 -0
  70. synth_code/transport.py +243 -0
  71. synth_code/v001_history.py +468 -0
  72. synth_code/view.py +854 -0
  73. synth_code/views/__init__.py +93 -0
  74. synth_code/views/charts.py +196 -0
  75. synth_code/views/curses_adapter.py +116 -0
  76. synth_code/views/engine.py +170 -0
  77. synth_code/views/model.py +226 -0
  78. synth_code/views/primitives.py +270 -0
  79. synth_code/views/tiling.py +124 -0
  80. synth_code-0.0.1.dist-info/METADATA +50 -0
  81. synth_code-0.0.1.dist-info/RECORD +110 -0
  82. synth_code-0.0.1.dist-info/WHEEL +5 -0
  83. synth_code-0.0.1.dist-info/entry_points.txt +6 -0
  84. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-APACHE +190 -0
  85. synth_code-0.0.1.dist-info/licenses/temper/LICENSE-MIT +21 -0
  86. synth_code-0.0.1.dist-info/licenses/temper/SOURCE.json +433 -0
  87. synth_code-0.0.1.dist-info/top_level.txt +2 -0
  88. synth_code_plugins/_sdk/__init__.py +19 -0
  89. synth_code_plugins/_sdk/callback_wire.py +240 -0
  90. synth_code_plugins/_sdk/callbacks.py +317 -0
  91. synth_code_plugins/_sdk/compliance.py +51 -0
  92. synth_code_plugins/_sdk/contracts.py +236 -0
  93. synth_code_plugins/_sdk/discovery.py +75 -0
  94. synth_code_plugins/_sdk/job_binding.py +71 -0
  95. synth_code_plugins/_sdk/lifecycle.py +50 -0
  96. synth_code_plugins/_sdk/lifecycle_generated.py +15 -0
  97. synth_code_plugins/_sdk/manifest.py +269 -0
  98. synth_code_plugins/_sdk/pack.py +332 -0
  99. synth_code_plugins/_sdk/push.py +98 -0
  100. synth_code_plugins/_sdk/records.py +26 -0
  101. synth_code_plugins/_sdk/registry.py +491 -0
  102. synth_code_plugins/_sdk/schemas.py +210 -0
  103. synth_code_plugins/_sdk/sources.py +230 -0
  104. synth_code_plugins/_sdk/surfaces.py +54 -0
  105. synth_code_plugins/_sdk/tools.py +172 -0
  106. synth_code_plugins/_sdk/worker_memory.py +49 -0
  107. synth_code_plugins/core/SKILL.md +6 -0
  108. synth_code_plugins/core/__init__.py +21 -0
  109. synth_code_plugins/core/plugin.toml +44 -0
  110. synth_code_plugins/core/source.py +18 -0
synth_code/shoal.py ADDED
@@ -0,0 +1,564 @@
1
+ """One admitted Responses turn using a pre-scoped customer session."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import ssl
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from enum import StrEnum
11
+ from functools import cache
12
+ from urllib import error, parse, request
13
+
14
+ import certifi
15
+
16
+ from .accounting import receipt_accounting
17
+
18
+ __all__ = [
19
+ "FunctionCall",
20
+ "SameOrigin",
21
+ "StepInvalid",
22
+ "StepInvalidCode",
23
+ "StepRole",
24
+ "function_calls",
25
+ "infer_step",
26
+ "infer_turn",
27
+ "opener",
28
+ "request_step",
29
+ "request_turn",
30
+ "step_body",
31
+ "step_idempotency_key",
32
+ "step_messages",
33
+ "tls_context",
34
+ ]
35
+
36
+ # The runtime owns the total adapter deadline. Let a queued response stay quiet
37
+ # on the socket longer than a short connect-style timeout would allow.
38
+ SOCKET_IDLE_TIMEOUT_SECONDS = 90
39
+
40
+
41
+ class ShoalError(RuntimeError):
42
+ def __init__(self, code: str, *, status: int | None = None):
43
+ self.code = code
44
+ self.status = status
45
+ super().__init__(
46
+ f"Shoal HTTP {status}: {code}"
47
+ if status is not None
48
+ else f"Shoal failed: {code}"
49
+ )
50
+
51
+
52
+ class SameOrigin(request.HTTPRedirectHandler):
53
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
54
+ raise ValueError("Inference credential redirect refused")
55
+
56
+
57
+ @cache
58
+ def tls_context() -> ssl.SSLContext:
59
+ """Verify servers against certifi's bundle, independent of the host's trust store."""
60
+ return ssl.create_default_context(cafile=certifi.where())
61
+
62
+
63
+ def opener() -> request.OpenerDirector:
64
+ """Same-origin HTTPS opener for credentialed account and inference calls."""
65
+ return request.build_opener(SameOrigin(), request.HTTPSHandler(context=tls_context()))
66
+
67
+
68
+ def response_body(response, on_delta, on_event, *, line_bytes, stream_bytes):
69
+ if response.headers.get_content_type() != "text/event-stream":
70
+ body = response.read(line_bytes + 1)
71
+ if len(body) > line_bytes:
72
+ raise ValueError("Response exceeded byte limit")
73
+ return json.loads(body)
74
+ size = 0
75
+ event_size = 0
76
+ pieces = []
77
+
78
+ def consume():
79
+ event = json.loads(b"\n".join(pieces))
80
+ kind = event.get("type")
81
+ if on_event is not None:
82
+ on_event(event)
83
+ if kind == "response.output_text.delta" and on_delta is not None:
84
+ on_delta(event["delta"])
85
+ elif kind == "response.completed":
86
+ return event["response"]
87
+ elif kind == "response.incomplete":
88
+ raise ShoalError("incomplete_response")
89
+ elif kind in ("error", "response.failed"):
90
+ code = event.get("code") or (
91
+ event.get("response", {}).get("error") or {}
92
+ ).get("code")
93
+ raise ShoalError(code if isinstance(code, str) else "untyped_stream_error")
94
+ return None
95
+
96
+ while line := response.readline(line_bytes + 1):
97
+ size += len(line)
98
+ event_size += len(line)
99
+ if size > stream_bytes or event_size > line_bytes:
100
+ raise ShoalError("response_too_large")
101
+ line = line.rstrip(b"\r\n")
102
+ if line.startswith(b"data:"):
103
+ data = line[5:].lstrip()
104
+ if data == b"[DONE]":
105
+ break
106
+ pieces.append(data)
107
+ elif not line:
108
+ event_size = 0
109
+ if pieces:
110
+ complete = consume()
111
+ pieces.clear()
112
+ if complete is not None:
113
+ return complete
114
+ if pieces and (complete := consume()) is not None:
115
+ return complete
116
+ raise ShoalError("incomplete_stream")
117
+
118
+
119
+ def _endpoint():
120
+ """Resolve the Shoal origin and credential: (origin, token, organization, fixture)."""
121
+ from .edition import beta_env, qualification_shoal_origin
122
+ from .enrollment import SHOAL
123
+
124
+ if (twin := qualification_shoal_origin()) is not None:
125
+ return twin, "fixture-only", None, True
126
+ origin = beta_env("SYNTH_CODE_SHOAL_ORIGIN", SHOAL)
127
+ url = parse.urlsplit(origin)
128
+ fixture = (
129
+ url.scheme == "http"
130
+ and url.hostname == "127.0.0.1"
131
+ and beta_env("SYNTH_CODE_FIXTURE") == "1"
132
+ )
133
+ if (
134
+ (url.scheme != "https" and not fixture)
135
+ or url.path not in ("", "/")
136
+ or url.query
137
+ or url.fragment
138
+ or url.username
139
+ ):
140
+ raise ValueError("Invalid Shoal origin")
141
+ from .grant import read
142
+
143
+ token, organization = ("fixture-only", None) if fixture else read(origin)
144
+ return origin, token, organization, fixture
145
+
146
+
147
+ def infer_turn(turn, on_delta=None, *, on_event=None):
148
+ from .edition import beta_env
149
+
150
+ origin, token, organization, fixture = _endpoint()
151
+ return request_turn(
152
+ turn,
153
+ origin=origin,
154
+ token=token,
155
+ organization=organization,
156
+ fixture=fixture,
157
+ output_limit=160 if turn.get("role", "side") == "side" else 2048,
158
+ opener=opener(),
159
+ on_delta=on_delta,
160
+ on_event=on_event,
161
+ checkpoint=beta_env("SYNTH_CODE_INFERENCE_CHECKPOINT"),
162
+ )
163
+
164
+
165
+ def infer_step(step, *, on_event=None):
166
+ """Send one version-3 `step` frame to Shoal and return its step receipt."""
167
+ from .edition import beta_env
168
+
169
+ origin, token, organization, fixture = _endpoint()
170
+ return request_step(
171
+ step,
172
+ origin=origin,
173
+ token=token,
174
+ organization=organization,
175
+ fixture=fixture,
176
+ opener=opener(),
177
+ on_event=on_event,
178
+ checkpoint=beta_env("SYNTH_CODE_INFERENCE_CHECKPOINT"),
179
+ )
180
+
181
+
182
+ def request_turn(
183
+ turn,
184
+ *,
185
+ origin,
186
+ token,
187
+ organization,
188
+ fixture,
189
+ output_limit,
190
+ opener,
191
+ on_delta=None,
192
+ checkpoint=None,
193
+ on_event=None,
194
+ ):
195
+ from .provider_frames import AdapterBudgets
196
+
197
+ budgets = AdapterBudgets.resolve(turn)
198
+ data = {
199
+ "model": "inkling-2-mini",
200
+ "input": turn["context"],
201
+ "max_output_tokens": output_limit,
202
+ "stream": on_delta is not None or on_event is not None,
203
+ }
204
+ key = hashlib.sha256(turn["identity"].encode()).hexdigest()
205
+ result = _post(
206
+ data,
207
+ key,
208
+ origin=origin,
209
+ token=token,
210
+ opener=opener,
211
+ budgets=budgets,
212
+ on_delta=on_delta,
213
+ on_event=on_event,
214
+ )
215
+ served = _served(result, organization=organization, checkpoint=checkpoint)
216
+ messages = output_messages(result)
217
+ if not messages:
218
+ raise ValueError("Missing model output")
219
+ return {
220
+ "provider": "inkling-2-mini",
221
+ "organization": organization,
222
+ "request_idempotency_key": key,
223
+ **served,
224
+ "thread": None,
225
+ "turn": result["id"],
226
+ "messages": messages,
227
+ "usage": result.get("usage"),
228
+ "fixture": fixture,
229
+ "history_verified": False,
230
+ }
231
+
232
+
233
+ def _post(data, key, *, origin, token, opener, budgets, on_delta, on_event):
234
+ req = request.Request(
235
+ origin.rstrip("/") + "/v1/responses",
236
+ data=json.dumps(data).encode(),
237
+ headers={
238
+ "Authorization": "Bearer " + token,
239
+ "Content-Type": "application/json",
240
+ "Idempotency-Key": key,
241
+ },
242
+ )
243
+ try:
244
+ with opener.open(req, timeout=SOCKET_IDLE_TIMEOUT_SECONDS) as response:
245
+ result = response_body(
246
+ response,
247
+ on_delta,
248
+ on_event,
249
+ line_bytes=budgets.provider_line_bytes,
250
+ stream_bytes=budgets.adapter_stdout_bytes,
251
+ )
252
+ except error.HTTPError as exc:
253
+ try:
254
+ payload = json.loads(exc.read(4096))
255
+ except (OSError, ValueError) as decode_error:
256
+ raise ShoalError(
257
+ "invalid_http_error_body", status=exc.code
258
+ ) from decode_error
259
+ problem = payload.get("error") if isinstance(payload, dict) else None
260
+ code = problem.get("code") if isinstance(problem, dict) else None
261
+ raise ShoalError(
262
+ code if isinstance(code, str) else "untyped_http_error", status=exc.code
263
+ ) from exc
264
+ except error.URLError as exc:
265
+ if isinstance(exc.reason, TimeoutError):
266
+ raise TimeoutError("Shoal response timed out") from exc
267
+ raise
268
+ return result
269
+
270
+
271
+ def _served(result, *, organization, checkpoint):
272
+ """Check the served envelope and return the receipt fields Shoal reported."""
273
+ shoal_meta = result.get("shoal") if isinstance(result.get("shoal"), dict) else {}
274
+ pricing = (
275
+ shoal_meta.get("pricing") if isinstance(shoal_meta.get("pricing"), dict) else {}
276
+ )
277
+ served_checkpoint = shoal_meta.get("model_artifact_id") or result.get("checkpoint")
278
+ # Shoal's receipt and Core's usage record are distinct accounting identities;
279
+ # never substitute one for the other or infer funding from pricing fields.
280
+ customer_pricing = {
281
+ field: pricing[field]
282
+ for field in (
283
+ "schema_version",
284
+ "status",
285
+ "charge_kind",
286
+ "basis",
287
+ "currency",
288
+ "charge",
289
+ "tariff_id",
290
+ "tariff_version",
291
+ "quote_id",
292
+ "quoted_charge",
293
+ )
294
+ if field in pricing
295
+ }
296
+ if result.get("model") != "inkling-2-mini" or (
297
+ checkpoint and served_checkpoint != checkpoint
298
+ ):
299
+ raise ValueError("Served model or checkpoint differs from grant")
300
+ if (
301
+ organization
302
+ and result.get("organization_id")
303
+ and result["organization_id"] != organization
304
+ ):
305
+ raise ShoalError("account_org_mismatch", status=403)
306
+ if result.get("status") != "completed" or not result.get("id"):
307
+ raise ShoalError("incomplete_response")
308
+ return {
309
+ "shoal_receipt_id": shoal_meta.get("receipt_id"),
310
+ # Production Shoal sends neither field; record a typed marker, not `null`.
311
+ "accounting": receipt_accounting(result),
312
+ "pricing": customer_pricing or None,
313
+ "model": result["model"],
314
+ "checkpoint": served_checkpoint,
315
+ }
316
+
317
+
318
+ def output_messages(result):
319
+ return [
320
+ {"item": item["id"], "content_index": content_index, "text": part["text"]}
321
+ for item in result["output"]
322
+ if item.get("type", "message") == "message"
323
+ for content_index, part in enumerate(item.get("content", []))
324
+ if part.get("type") == "output_text"
325
+ ]
326
+
327
+
328
+ # --- Temper tool loop: one stateless Responses step (TEMPER_TOOL_LOOP.md sections 2, 5, 6) ---
329
+
330
+ STEP_FRAME_VERSION = 3
331
+ STEP_MODEL = "inkling-2-mini"
332
+ # Shoal's per-step cap on returned function calls (contract section 6).
333
+ MAX_TOOL_CALLS = 8
334
+ # Function-call arguments may carry up to 24 KiB of file content plus JSON escaping.
335
+ TOOL_OUTPUT_TOKENS = 12288
336
+ SIDE_OUTPUT_TOKENS = 160
337
+ INPUT_ITEM_TYPES = frozenset({"message", "function_call", "function_call_output"})
338
+
339
+
340
+ class StepRole(StrEnum):
341
+ CORE = "core"
342
+ SIDE = "side"
343
+ DELEGATE = "delegate"
344
+
345
+ @property
346
+ def output_limit(self) -> int:
347
+ return SIDE_OUTPUT_TOKENS if self is StepRole.SIDE else TOOL_OUTPUT_TOKENS
348
+
349
+ @property
350
+ def uses_tools(self) -> bool:
351
+ return self is not StepRole.SIDE
352
+
353
+
354
+ class StepInvalidCode(StrEnum):
355
+ # The Rust step frame does not match the version-3 contract; nothing was sent.
356
+ STEP_REQUEST_INVALID = "step_request_invalid"
357
+ # Shoal returned a `function_call` item that is not a complete, well-typed call.
358
+ MALFORMED_FUNCTION_CALL = "malformed_function_call"
359
+ # The streamed function call differs from the call in the completed response.
360
+ FUNCTION_CALL_STREAM_MISMATCH = "function_call_stream_mismatch"
361
+ # Shoal returned more calls than `max_tool_calls`, or calls when tools were off.
362
+ FUNCTION_CALL_BUDGET_EXCEEDED = "function_call_budget_exceeded"
363
+ # A completed response carried neither text nor a function call.
364
+ EMPTY_STEP_OUTPUT = "empty_step_output"
365
+
366
+
367
+ class StepInvalid(ValueError):
368
+ """A step request or answer refused with a stable code and the reason."""
369
+
370
+ def __init__(self, code: StepInvalidCode, cause: str) -> None:
371
+ self.code = code
372
+ self.cause = cause
373
+ super().__init__(f"{code}: {cause}")
374
+
375
+
376
+ @dataclass(frozen=True, slots=True)
377
+ class FunctionCall:
378
+ item: str
379
+ call_id: str
380
+ name: str
381
+ arguments: str
382
+
383
+ def wire(self) -> dict[str, str]:
384
+ return {"call_id": self.call_id, "name": self.name, "arguments": self.arguments}
385
+
386
+
387
+ def step_idempotency_key(identity: str, step: int) -> str:
388
+ """`sha256(identity + "\x1f" + step)`: one key per step, stable across replays."""
389
+ return hashlib.sha256(f"{identity}\x1f{step}".encode()).hexdigest()
390
+
391
+
392
+ def _refuse_request(cause: str) -> StepInvalid:
393
+ return StepInvalid(StepInvalidCode.STEP_REQUEST_INVALID, cause)
394
+
395
+
396
+ def _nonempty(value: object) -> bool:
397
+ return isinstance(value, str) and bool(value)
398
+
399
+
400
+ def _input_item(index: int, item: object) -> Mapping[str, object]:
401
+ if not isinstance(item, Mapping) or item.get("type") not in INPUT_ITEM_TYPES:
402
+ raise _refuse_request(f"input[{index}] is not a message, function_call or function_call_output")
403
+ match item["type"]:
404
+ case "function_call":
405
+ if not all(_nonempty(item.get(field)) for field in ("call_id", "name")) or not isinstance(
406
+ item.get("arguments"), str
407
+ ):
408
+ raise _refuse_request(f"input[{index}] function_call needs call_id, name and string arguments")
409
+ case "function_call_output":
410
+ if not _nonempty(item.get("call_id")) or not isinstance(item.get("output"), str):
411
+ raise _refuse_request(f"input[{index}] function_call_output needs call_id and string output")
412
+ return item
413
+
414
+
415
+ def _tool(index: int, tool: object) -> Mapping[str, object]:
416
+ if (
417
+ not isinstance(tool, Mapping)
418
+ or tool.get("type") != "function"
419
+ or not _nonempty(tool.get("name"))
420
+ or not isinstance(tool.get("description"), str)
421
+ or not isinstance(tool.get("parameters"), Mapping)
422
+ or tool.get("strict") is not True
423
+ ):
424
+ raise _refuse_request(f"tools[{index}] is not a strict function tool")
425
+ return tool
426
+
427
+
428
+ def step_body(step: Mapping[str, object], *, stream: bool) -> dict[str, object]:
429
+ """The `/v1/responses` body for one step frame. Byte-identical across replays."""
430
+ if step.get("version") != STEP_FRAME_VERSION or step.get("kind") != "step":
431
+ raise _refuse_request("frame is not version 3 kind step")
432
+ if step.get("provider") != STEP_MODEL:
433
+ raise _refuse_request(f"provider is not {STEP_MODEL}")
434
+ try:
435
+ role = StepRole(step.get("role"))
436
+ except ValueError as error:
437
+ raise _refuse_request("role is not core, side or delegate") from error
438
+ if not _nonempty(step.get("identity")):
439
+ raise _refuse_request("identity is empty")
440
+ index = step.get("step")
441
+ if type(index) is not int or index < 0:
442
+ raise _refuse_request("step is not an unsigned integer")
443
+ if not isinstance(step.get("instructions"), str):
444
+ raise _refuse_request("instructions is not a string")
445
+ items = step.get("input")
446
+ if not isinstance(items, list) or not items:
447
+ raise _refuse_request("input is not a non-empty list")
448
+ tools = step.get("tools", [])
449
+ if not isinstance(tools, list):
450
+ raise _refuse_request("tools is not a list")
451
+ tool_choice = step.get("tool_choice", "auto" if role.uses_tools else "none")
452
+ if role.uses_tools:
453
+ if tool_choice != "auto":
454
+ raise _refuse_request(f"{role} steps use tool_choice auto")
455
+ elif tools or tool_choice != "none":
456
+ raise _refuse_request("side steps carry no tools and tool_choice none")
457
+ if step.get("parallel_tool_calls", False) is not False:
458
+ raise _refuse_request("parallel_tool_calls must be false")
459
+ limit = step.get("max_output_tokens", role.output_limit)
460
+ if limit != role.output_limit:
461
+ raise _refuse_request(f"max_output_tokens for {role} is {role.output_limit}, not {limit!r}")
462
+ body: dict[str, object] = {
463
+ "model": STEP_MODEL,
464
+ "instructions": step["instructions"],
465
+ "input": [dict(_input_item(i, item)) for i, item in enumerate(items)],
466
+ "tools": [dict(_tool(i, tool)) for i, tool in enumerate(tools)],
467
+ "tool_choice": tool_choice,
468
+ "parallel_tool_calls": False,
469
+ "max_output_tokens": role.output_limit,
470
+ "stream": stream,
471
+ }
472
+ if role.uses_tools:
473
+ body["max_tool_calls"] = MAX_TOOL_CALLS
474
+ return body
475
+
476
+
477
+ def function_calls(result: Mapping[str, object], *, tools_enabled: bool) -> list[FunctionCall]:
478
+ """Strictly parse `function_call` output items. Unknown names pass: Rust settles them `unknown_tool`."""
479
+ calls: list[FunctionCall] = []
480
+ seen: set[str] = set()
481
+ for index, item in enumerate(result["output"]):
482
+ if not isinstance(item, Mapping) or item.get("type") != "function_call":
483
+ continue
484
+ fields = {field: item.get(field) for field in ("id", "call_id", "name", "arguments")}
485
+ missing = [field for field, value in fields.items() if not _nonempty(value)]
486
+ if missing:
487
+ raise StepInvalid(
488
+ StepInvalidCode.MALFORMED_FUNCTION_CALL, f"output[{index}] lacks string {', '.join(missing)}"
489
+ )
490
+ if item.get("status", "completed") != "completed":
491
+ raise StepInvalid(StepInvalidCode.MALFORMED_FUNCTION_CALL, f"output[{index}] status {item.get('status')!r}")
492
+ try:
493
+ arguments = json.loads(fields["arguments"])
494
+ except ValueError as error:
495
+ raise StepInvalid(
496
+ StepInvalidCode.MALFORMED_FUNCTION_CALL, f"output[{index}] arguments are not JSON"
497
+ ) from error
498
+ if not isinstance(arguments, dict):
499
+ raise StepInvalid(StepInvalidCode.MALFORMED_FUNCTION_CALL, f"output[{index}] arguments are not an object")
500
+ if fields["call_id"] in seen:
501
+ raise StepInvalid(StepInvalidCode.MALFORMED_FUNCTION_CALL, f"output[{index}] repeats call_id")
502
+ seen.add(fields["call_id"])
503
+ calls.append(FunctionCall(fields["id"], fields["call_id"], fields["name"], fields["arguments"]))
504
+ if calls and not tools_enabled:
505
+ raise StepInvalid(StepInvalidCode.FUNCTION_CALL_BUDGET_EXCEEDED, "function call on a step without tools")
506
+ if len(calls) > MAX_TOOL_CALLS:
507
+ raise StepInvalid(
508
+ StepInvalidCode.FUNCTION_CALL_BUDGET_EXCEEDED, f"{len(calls)} calls exceed max_tool_calls {MAX_TOOL_CALLS}"
509
+ )
510
+ return calls
511
+
512
+
513
+ def step_messages(result: Mapping[str, object]) -> list[dict[str, object]]:
514
+ """Text parts with content. Inkling opens an empty `message` beside every function call;
515
+ it carries nothing, so it is not a message. `reasoning` items are never messages."""
516
+ return [message for message in output_messages(result) if message["text"]]
517
+
518
+
519
+ def request_step(
520
+ step,
521
+ *,
522
+ origin,
523
+ token,
524
+ organization,
525
+ fixture,
526
+ opener,
527
+ on_event=None,
528
+ checkpoint=None,
529
+ ):
530
+ """One stateless step. Returns the step receipt fields; the adapter never runs a tool."""
531
+ from .provider_frames import AdapterBudgets
532
+
533
+ budgets = AdapterBudgets.resolve(step)
534
+ body = step_body(step, stream=on_event is not None)
535
+ role = StepRole(step["role"])
536
+ key = step_idempotency_key(step["identity"], step["step"])
537
+ result = _post(
538
+ body,
539
+ key,
540
+ origin=origin,
541
+ token=token,
542
+ opener=opener,
543
+ budgets=budgets,
544
+ on_delta=None,
545
+ on_event=on_event,
546
+ )
547
+ served = _served(result, organization=organization, checkpoint=checkpoint)
548
+ messages = step_messages(result)
549
+ calls = function_calls(result, tools_enabled=role.uses_tools)
550
+ if not messages and not calls:
551
+ raise StepInvalid(StepInvalidCode.EMPTY_STEP_OUTPUT, "response carried no text and no function call")
552
+ return {
553
+ "provider": STEP_MODEL,
554
+ "organization": organization,
555
+ "request_idempotency_key": key,
556
+ **served,
557
+ "turn": result["id"],
558
+ "step": step["step"],
559
+ "messages": messages,
560
+ "function_calls": calls,
561
+ "usage": result.get("usage"),
562
+ "fixture": fixture,
563
+ "history_verified": False,
564
+ }