@neurocode-ai/llm 1.18.8

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 (152) hide show
  1. package/AGENTS.md +321 -0
  2. package/DESIGN.md +1114 -0
  3. package/README.md +131 -0
  4. package/example/call-sites.md +591 -0
  5. package/example/tutorial.ts +255 -0
  6. package/package.json +51 -0
  7. package/script/recording-cost-report.ts +250 -0
  8. package/script/setup-recording-env.ts +542 -0
  9. package/src/cache-policy.ts +111 -0
  10. package/src/index.ts +33 -0
  11. package/src/llm.ts +186 -0
  12. package/src/protocols/anthropic-messages.ts +855 -0
  13. package/src/protocols/bedrock-converse.ts +674 -0
  14. package/src/protocols/bedrock-event-stream.ts +87 -0
  15. package/src/protocols/gemini.ts +512 -0
  16. package/src/protocols/index.ts +6 -0
  17. package/src/protocols/openai-chat.ts +506 -0
  18. package/src/protocols/openai-compatible-chat.ts +24 -0
  19. package/src/protocols/openai-responses.ts +1022 -0
  20. package/src/protocols/shared.ts +326 -0
  21. package/src/protocols/utils/bedrock-auth.ts +70 -0
  22. package/src/protocols/utils/bedrock-cache.ts +37 -0
  23. package/src/protocols/utils/bedrock-media.ts +90 -0
  24. package/src/protocols/utils/cache.ts +16 -0
  25. package/src/protocols/utils/gemini-tool-schema.ts +99 -0
  26. package/src/protocols/utils/lifecycle.ts +102 -0
  27. package/src/protocols/utils/openai-options.ts +93 -0
  28. package/src/protocols/utils/tool-schema.ts +86 -0
  29. package/src/protocols/utils/tool-stream.ts +218 -0
  30. package/src/provider-error.ts +43 -0
  31. package/src/provider.ts +36 -0
  32. package/src/providers/amazon-bedrock.ts +43 -0
  33. package/src/providers/anthropic.ts +35 -0
  34. package/src/providers/azure.ts +110 -0
  35. package/src/providers/cloudflare.ts +127 -0
  36. package/src/providers/github-copilot.ts +69 -0
  37. package/src/providers/google.ts +35 -0
  38. package/src/providers/index.ts +11 -0
  39. package/src/providers/openai-compatible-profile.ts +20 -0
  40. package/src/providers/openai-compatible.ts +65 -0
  41. package/src/providers/openai-options.ts +83 -0
  42. package/src/providers/openai.ts +63 -0
  43. package/src/providers/openrouter.ts +98 -0
  44. package/src/providers/xai.ts +56 -0
  45. package/src/route/auth-options.ts +57 -0
  46. package/src/route/auth.ts +156 -0
  47. package/src/route/client.ts +436 -0
  48. package/src/route/endpoint.ts +53 -0
  49. package/src/route/executor.ts +385 -0
  50. package/src/route/framing.ts +27 -0
  51. package/src/route/index.ts +25 -0
  52. package/src/route/protocol.ts +84 -0
  53. package/src/route/transport/http.ts +155 -0
  54. package/src/route/transport/index.ts +33 -0
  55. package/src/route/transport/websocket.ts +280 -0
  56. package/src/schema/errors.ts +207 -0
  57. package/src/schema/events.ts +618 -0
  58. package/src/schema/ids.ts +43 -0
  59. package/src/schema/index.ts +5 -0
  60. package/src/schema/messages.ts +312 -0
  61. package/src/schema/options.ts +276 -0
  62. package/src/tool-runtime.ts +78 -0
  63. package/src/tool.ts +253 -0
  64. package/src/utils/record.ts +3 -0
  65. package/sst-env.d.ts +10 -0
  66. package/test/adapter.test.ts +171 -0
  67. package/test/auth-options.types.ts +168 -0
  68. package/test/auth.test.ts +103 -0
  69. package/test/cache-policy.test.ts +262 -0
  70. package/test/continuation-scenarios.ts +104 -0
  71. package/test/endpoint.test.ts +58 -0
  72. package/test/executor.test.ts +458 -0
  73. package/test/exports.test.ts +76 -0
  74. package/test/fixtures/media/restroom.png +0 -0
  75. package/test/fixtures/recordings/anthropic-messages/accepts-malformed-assistant-tool-order-with-default-patch.json +29 -0
  76. package/test/fixtures/recordings/anthropic-messages/anthropic-opus-4-7-image-tool-result.json +43 -0
  77. package/test/fixtures/recordings/anthropic-messages/claude-opus-4-7-drives-a-tool-loop.json +56 -0
  78. package/test/fixtures/recordings/anthropic-messages/rejects-malformed-assistant-tool-order-without-patch.json +29 -0
  79. package/test/fixtures/recordings/anthropic-messages/streams-text.json +29 -0
  80. package/test/fixtures/recordings/anthropic-messages/streams-tool-call.json +29 -0
  81. package/test/fixtures/recordings/anthropic-messages-cache/writes-then-reads-cache-control-on-identical-second-call.json +48 -0
  82. package/test/fixtures/recordings/bedrock-converse/drives-a-tool-loop.json +55 -0
  83. package/test/fixtures/recordings/bedrock-converse/streams-a-tool-call.json +29 -0
  84. package/test/fixtures/recordings/bedrock-converse/streams-text.json +29 -0
  85. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  86. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-llama-3-1-8b-text.json +32 -0
  87. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  88. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-llama-3-1-8b-text.json +32 -0
  89. package/test/fixtures/recordings/gemini/gemini-2-5-flash-image.json +32 -0
  90. package/test/fixtures/recordings/gemini/streams-text.json +28 -0
  91. package/test/fixtures/recordings/gemini/streams-tool-call.json +28 -0
  92. package/test/fixtures/recordings/gemini-cache/reports-cachedcontenttokencount-on-identical-second-call.json +46 -0
  93. package/test/fixtures/recordings/openai-chat/continues-after-tool-result.json +28 -0
  94. package/test/fixtures/recordings/openai-chat/drives-a-tool-loop-end-to-end.json +46 -0
  95. package/test/fixtures/recordings/openai-chat/streams-text.json +28 -0
  96. package/test/fixtures/recordings/openai-chat/streams-tool-call.json +28 -0
  97. package/test/fixtures/recordings/openai-compatible-chat/deepseek-streams-text.json +28 -0
  98. package/test/fixtures/recordings/openai-compatible-chat/groq-llama-3-3-70b-drives-a-tool-loop.json +53 -0
  99. package/test/fixtures/recordings/openai-compatible-chat/groq-streams-text.json +28 -0
  100. package/test/fixtures/recordings/openai-compatible-chat/groq-streams-tool-call.json +28 -0
  101. package/test/fixtures/recordings/openai-compatible-chat/openrouter-claude-opus-4-7-drives-a-tool-loop.json +54 -0
  102. package/test/fixtures/recordings/openai-compatible-chat/openrouter-gpt-4o-mini-drives-a-tool-loop.json +53 -0
  103. package/test/fixtures/recordings/openai-compatible-chat/openrouter-gpt-5-5-drives-a-tool-loop.json +54 -0
  104. package/test/fixtures/recordings/openai-compatible-chat/openrouter-streams-text.json +28 -0
  105. package/test/fixtures/recordings/openai-compatible-chat/openrouter-streams-tool-call.json +28 -0
  106. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-text.json +28 -0
  107. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-tool-call.json +28 -0
  108. package/test/fixtures/recordings/openai-responses/gpt-5-5-drives-a-tool-loop.json +54 -0
  109. package/test/fixtures/recordings/openai-responses/gpt-5-5-streams-text.json +28 -0
  110. package/test/fixtures/recordings/openai-responses/gpt-5-5-streams-tool-call.json +28 -0
  111. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-image-tool-result.json +42 -0
  112. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning-continuation.json +58 -0
  113. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning.json +32 -0
  114. package/test/fixtures/recordings/openai-responses-cache/reports-cached-tokens-on-identical-second-call.json +46 -0
  115. package/test/generate-object.test.ts +184 -0
  116. package/test/lib/effect.ts +50 -0
  117. package/test/lib/http.ts +98 -0
  118. package/test/lib/openai-chunks.ts +27 -0
  119. package/test/lib/sse.ts +17 -0
  120. package/test/lib/tool-runtime.ts +146 -0
  121. package/test/llm.test.ts +199 -0
  122. package/test/prepare.test.ts +178 -0
  123. package/test/provider/anthropic-messages-cache.recorded.test.ts +53 -0
  124. package/test/provider/anthropic-messages.recorded.test.ts +45 -0
  125. package/test/provider/anthropic-messages.test.ts +895 -0
  126. package/test/provider/bedrock-converse-cache.recorded.test.ts +54 -0
  127. package/test/provider/bedrock-converse.test.ts +744 -0
  128. package/test/provider/cloudflare.test.ts +230 -0
  129. package/test/provider/gemini-cache.recorded.test.ts +48 -0
  130. package/test/provider/gemini.test.ts +584 -0
  131. package/test/provider/golden.recorded.test.ts +223 -0
  132. package/test/provider/openai-chat.test.ts +674 -0
  133. package/test/provider/openai-compatible-chat.test.ts +238 -0
  134. package/test/provider/openai-responses-cache.recorded.test.ts +46 -0
  135. package/test/provider/openai-responses.test.ts +1472 -0
  136. package/test/provider/openrouter.test.ts +56 -0
  137. package/test/provider-error.test.ts +30 -0
  138. package/test/provider.types.ts +41 -0
  139. package/test/recorded-golden.ts +97 -0
  140. package/test/recorded-runner.ts +100 -0
  141. package/test/recorded-scenarios.ts +531 -0
  142. package/test/recorded-test.ts +94 -0
  143. package/test/recorded-utils.ts +56 -0
  144. package/test/recorded-websocket.ts +26 -0
  145. package/test/response.test.ts +98 -0
  146. package/test/route.test.ts +43 -0
  147. package/test/schema.test.ts +86 -0
  148. package/test/tool-runtime.test.ts +818 -0
  149. package/test/tool-schema-projection.test.ts +117 -0
  150. package/test/tool-stream.test.ts +99 -0
  151. package/test/tool.types.ts +40 -0
  152. package/tsconfig.json +15 -0
package/DESIGN.md ADDED
@@ -0,0 +1,1114 @@
1
+ # AI Library Design
2
+
3
+ > Discussion draft. This document describes the intended replacement for the
4
+ > current private `@opencode-ai/llm` API. Names and exact TypeScript signatures
5
+ > are illustrative until implementation, but the domain boundaries and defaults
6
+ > are deliberate.
7
+
8
+ ## Status
9
+
10
+ - Proposed package: `@opencode-ai/ai`
11
+ - Initial stable domain: `LLM`
12
+ - Release posture: pre-1.0, with a stable-core intent
13
+ - Migration posture: clean break; do not preserve compatibility aliases
14
+ - Primary audience: general-purpose TypeScript developers using Effect
15
+ - Secondary audience: OpenCode and other durable agent runtimes
16
+
17
+ The package name leaves room for future domains such as embeddings, images, and
18
+ speech. Those domains are not part of this design and should not be forced into
19
+ the LLM run/turn model.
20
+
21
+ ## Goals
22
+
23
+ 1. Make a useful model call require very little code.
24
+ 2. Make the default behavior good enough that most callers do not configure it.
25
+ 3. Let advanced callers inspect, transform, or replace every important stage.
26
+ 4. Keep provider quirks behind provider and protocol boundaries.
27
+ 5. Preserve one provider turn as an explicit primitive for durable runtimes.
28
+ 6. Keep serializable request data separate from process-local execution behavior.
29
+ 7. Make unsupported combinations fail locally with useful typed errors.
30
+ 8. Stay Effect-native without making package-specific service provisioning part
31
+ of every call site.
32
+
33
+ ## Non-goals
34
+
35
+ - A global provider or model registry
36
+ - Durable agent orchestration or persistence
37
+ - Session history ownership
38
+ - Permission handling
39
+ - Cost billing or accounting guarantees
40
+ - Runtime model-catalog network requests
41
+ - Compatibility with the current private API
42
+ - Designing embeddings, image generation, speech, or transcription now
43
+
44
+ ## Design Principles
45
+
46
+ ### Progressive disclosure
47
+
48
+ The API has four layers:
49
+
50
+ 1. **Run a model** with `LLM.generate` or `LLM.stream`.
51
+ 2. **Control one provider turn** with `LLM.generateTurn` or `LLM.streamTurn`.
52
+ 3. **Customize execution** with model defaults, call options, hooks, and provider
53
+ configuration.
54
+ 4. **Author providers** with experimental provider definitions and protocols.
55
+
56
+ Normal documentation should teach only the first layer initially.
57
+
58
+ ### Values over registries
59
+
60
+ Provider definitions, configured providers, models, protocols, tools, and hooks
61
+ are immutable values. Importing a provider does not register anything globally.
62
+
63
+ ### Portable data, local behavior
64
+
65
+ Requests, messages, tool definitions, events, usage, and result projections are
66
+ plain immutable data with schemas. Configured models, executable tools, hooks,
67
+ and provider definitions may contain functions and Effect requirements and are
68
+ not serializable.
69
+
70
+ ### Strong defaults, explicit overrides
71
+
72
+ Defaults should make common calls correct without hiding where behavior comes
73
+ from. Overrides compose in a documented order and never require patching
74
+ installed dependencies.
75
+
76
+ ## Domain Model
77
+
78
+ ### Provider Definition
79
+
80
+ An immutable, declarative description of a provider integration. It owns model
81
+ selection, option schemas, catalog corrections, protocols, and provider-wide
82
+ hooks. It is an experimental provider-authoring API.
83
+
84
+ ### Configured Provider
85
+
86
+ A provider definition bound to deployment concerns such as credentials,
87
+ endpoint, transport, and provider headers.
88
+
89
+ `configure(...)` is intentionally deployment-only. It does not establish hidden
90
+ generation defaults.
91
+
92
+ ### Model
93
+
94
+ A process-local executable model value selected from a configured provider. It
95
+ contains identity, capabilities, pricing metadata, provider-specific option
96
+ types, reusable request-behavior defaults, and hidden execution behavior.
97
+
98
+ Normal users do not need to learn the current `Route` composite. Protocol,
99
+ endpoint, auth, transport, and hooks are bound behind `Model`.
100
+
101
+ ### Request
102
+
103
+ Portable, model-independent input for a model call. It may contain system
104
+ instructions, messages, tool definitions, generation controls, output intent,
105
+ cache policy, and metadata. It does not contain a configured model, executable
106
+ tool handlers, or hooks.
107
+
108
+ ### Provider Turn
109
+
110
+ Exactly one request to a model provider and its normalized response. It does not
111
+ execute local tools or continue the conversation.
112
+
113
+ ### Model Run
114
+
115
+ A complete interaction consisting of one or more provider turns. A run executes
116
+ local tools, appends their results, and continues until the model completes or a
117
+ stopping condition matches.
118
+
119
+ ### TurnResult
120
+
121
+ The result of exactly one provider turn.
122
+
123
+ ### GenerateResult
124
+
125
+ The result of a complete model run. It preserves every turn, tool activity,
126
+ aggregate usage, and estimated cost while exposing shortcuts to the final output.
127
+
128
+ ### Protocol
129
+
130
+ The provider-wire contract that lowers portable requests into provider-native
131
+ bodies and raises provider-native stream events into normalized turn events.
132
+ Protocols are public, reusable, fully inspectable, and immutably patchable, but
133
+ the entire protocol-authoring API is experimental.
134
+
135
+ ## Happy Path
136
+
137
+ ### Effect
138
+
139
+ ```ts
140
+ import { Effect } from "effect"
141
+ import { LLM } from "@opencode-ai/ai"
142
+ import { OpenAI } from "@opencode-ai/ai/providers/openai"
143
+
144
+ // Environment-based credentials are a provider default. No LLMClient layer is
145
+ // required: the Effect exposes standard runtime dependencies directly.
146
+ const model = OpenAI.model("gpt-4.1-mini")
147
+
148
+ const program = Effect.gen(function* () {
149
+ const result = yield* LLM.generate({
150
+ model,
151
+ system: "You are concise.",
152
+ prompt: "Explain Effect in one sentence.",
153
+ })
154
+
155
+ // `generate` always returns GenerateResult, even when the run has one turn.
156
+ console.log(result.text)
157
+ console.log(result.turns.length) // 1
158
+ console.log(result.usage)
159
+ console.log(result.cost) // Estimated cost, or undefined if any turn is unpriced.
160
+ })
161
+ ```
162
+
163
+ The required Effect environment should contain standard services plus services
164
+ required by tools and hooks. It should not contain an `LLMClient` wrapper service.
165
+
166
+ ### Current API
167
+
168
+ The current README appears similarly small but omits the package-specific service
169
+ and layer required at runtime:
170
+
171
+ ```ts
172
+ // Current API: this request contains an executable model/route value.
173
+ const request = LLM.request({
174
+ model: OpenAI.configure({ apiKey }).responses("gpt-4o-mini"),
175
+ prompt: "Say hello.",
176
+ })
177
+
178
+ // Current API: this performs one provider turn, despite the broad name.
179
+ const response = yield * LLM.generate(request)
180
+
181
+ // Current API: execution also needs LLMClient.layer and RequestExecutor services.
182
+ ```
183
+
184
+ The proposal removes mandatory request construction, removes package-specific
185
+ runtime provisioning, and makes `generate` mean a complete run.
186
+
187
+ ## Provider And Model Selection
188
+
189
+ ### Environment defaults
190
+
191
+ ```ts
192
+ import { OpenAI } from "@opencode-ai/ai/providers/openai"
193
+
194
+ // Open strings receive autocomplete for IDs from the generated models.dev
195
+ // snapshot but continue to accept newly released and fine-tuned model IDs.
196
+ const model = OpenAI.model("gpt-4.1-mini")
197
+ ```
198
+
199
+ ### Deployment configuration
200
+
201
+ ```ts
202
+ const openai = OpenAI.configure({
203
+ apiKey,
204
+ baseURL: "https://gateway.example.com/openai/v1",
205
+ headers: {
206
+ "x-tenant": "acme",
207
+ },
208
+ })
209
+
210
+ const model = openai.model("gpt-4.1-mini")
211
+ ```
212
+
213
+ `configure(...)` owns deployment concerns only:
214
+
215
+ - Credentials and authentication
216
+ - Base URL and deployment location
217
+ - Transport selection
218
+ - Provider/deployment headers
219
+ - Other provider-specific connection setup
220
+
221
+ It does not own temperature, maximum output tokens, cache policy, retry policy,
222
+ tools, output schema, or system instructions.
223
+
224
+ ### Reusable model defaults
225
+
226
+ ```ts
227
+ const model = OpenAI.model("gpt-4.1-mini", {
228
+ generation: {
229
+ temperature: 0.2,
230
+ maxTokens: 2_000,
231
+ },
232
+ cache: "auto",
233
+ provider: {
234
+ store: false,
235
+ },
236
+ })
237
+ ```
238
+
239
+ The second argument may default request behavior but not prompt/history or
240
+ executable tools. Call-level values override model defaults.
241
+
242
+ Provider-specific options are inferred from the concrete model:
243
+
244
+ ```ts
245
+ yield *
246
+ LLM.generate({
247
+ model: OpenAI.model("gpt-4.1-mini"),
248
+ prompt: "Hello",
249
+ provider: {
250
+ store: false,
251
+ // OpenAI-specific autocomplete here; no `{ openai: ... }` nesting.
252
+ },
253
+ })
254
+ ```
255
+
256
+ Code choosing between providers dynamically must narrow the model before using
257
+ provider-specific options. Portable generation controls remain available without
258
+ narrowing.
259
+
260
+ ### Current API
261
+
262
+ ```ts
263
+ // Current API mixes deployment configuration and reusable request behavior.
264
+ const model = OpenAI.configure({
265
+ apiKey,
266
+ generation: { maxTokens: 160 },
267
+ providerOptions: {
268
+ openai: { store: false },
269
+ },
270
+ }).model("gpt-4o-mini")
271
+ ```
272
+
273
+ The proposal separates deployment configuration from selected-model behavior and
274
+ removes provider-keyed option bags when a concrete model already identifies the
275
+ provider.
276
+
277
+ ## Requests
278
+
279
+ ### Inline input
280
+
281
+ ```ts
282
+ const result =
283
+ yield *
284
+ LLM.generate({
285
+ model,
286
+ system: "You are concise.",
287
+ prompt: "Summarize this pull request.",
288
+ generation: { maxTokens: 500 },
289
+ })
290
+ ```
291
+
292
+ ### Reusable portable request
293
+
294
+ ```ts
295
+ const request = LLM.request({
296
+ system: "You are concise.",
297
+ prompt: "Summarize this pull request.",
298
+ generation: { maxTokens: 500 },
299
+ })
300
+
301
+ // Bind process-local execution behavior only when running.
302
+ const result = yield * LLM.generate({ model, request })
303
+ ```
304
+
305
+ `LLM.request(...)` returns a plain immutable object. Use ordinary object spread
306
+ to derive another request:
307
+
308
+ ```ts
309
+ const longer = {
310
+ ...request,
311
+ generation: {
312
+ ...request.generation,
313
+ maxTokens: 1_000,
314
+ },
315
+ }
316
+ ```
317
+
318
+ There is no `LLM.updateRequest(...)` helper and no request Schema class.
319
+
320
+ ### Conversation history
321
+
322
+ ```ts
323
+ import { Message } from "@opencode-ai/ai"
324
+
325
+ const request = LLM.request({
326
+ system: "You are concise.",
327
+ messages: [
328
+ Message.user("What is Effect?"),
329
+ Message.assistant("A TypeScript library for typed functional effects."),
330
+ Message.user("Why would I use it?"),
331
+ ],
332
+ })
333
+ ```
334
+
335
+ Message helpers return plain immutable data. Object literals remain valid when
336
+ they satisfy the same input type.
337
+
338
+ `system` stays separate from chronological messages because it is the initial
339
+ privileged instruction. A chronological system message represents an instruction
340
+ change at a specific point in history.
341
+
342
+ ## Complete Runs
343
+
344
+ ### Automatic local tool loop
345
+
346
+ ```ts
347
+ import { Effect, Schema } from "effect"
348
+ import { LLM, Tool } from "@opencode-ai/ai"
349
+
350
+ const tools = {
351
+ getWeather: Tool.make({
352
+ description: "Get current weather for a city.",
353
+ parameters: Schema.Struct({ city: Schema.String }),
354
+ success: Schema.Struct({ forecast: Schema.String }),
355
+
356
+ // Tool service requirements and typed errors flow into LLM.generate's
357
+ // Effect environment/error model instead of being erased.
358
+ execute: ({ city }) => Weather.get(city),
359
+
360
+ // Expected domain failures need an explicit model-visible representation.
361
+ formatError: (error) => ({
362
+ type: "text",
363
+ text: `Weather lookup failed: ${error.message}`,
364
+ }),
365
+ }),
366
+ }
367
+
368
+ const result =
369
+ yield *
370
+ LLM.generate({
371
+ model,
372
+ prompt: "What is the weather in London?",
373
+ tools,
374
+ })
375
+
376
+ // The runtime advertises definitions, dispatches calls, records results, and
377
+ // continues provider turns automatically.
378
+ console.log(result.text)
379
+ console.log(result.turns)
380
+ console.log(result.toolExecutions)
381
+ ```
382
+
383
+ The default stopping condition is equivalent to:
384
+
385
+ ```ts
386
+ stopWhen: StopWhen.turnCount(20)
387
+ ```
388
+
389
+ This matches the Vercel AI SDK `ToolLoopAgent` default. Reaching the limit is a
390
+ successful result with `stopReason: "max-turns"`, not an Effect failure.
391
+
392
+ ### Custom stopping
393
+
394
+ ```ts
395
+ const result =
396
+ yield *
397
+ LLM.generate({
398
+ model,
399
+ prompt,
400
+ tools,
401
+ stopWhen: StopWhen.any(StopWhen.turnCount(8), StopWhen.hasToolCall("finalize")),
402
+ })
403
+ ```
404
+
405
+ `stopWhen` accepts one predicate. Composition is explicit through combinators
406
+ such as `StopWhen.any`, `StopWhen.all`, and `StopWhen.not`.
407
+
408
+ Successful run stop reasons are closed:
409
+
410
+ ```ts
411
+ type RunStopReason = "completed" | "max-turns" | "stop-condition"
412
+ ```
413
+
414
+ ### Tool concurrency
415
+
416
+ Independent tool calls emitted in one turn run concurrently with a bounded,
417
+ configurable concurrency limit. Results are appended in deterministic emitted
418
+ order. The runtime does not infer dependencies between tool calls; the model must
419
+ request dependent calls in separate turns.
420
+
421
+ Tools may declare an optional timeout. The overall run timeout still applies.
422
+
423
+ ### Current API
424
+
425
+ Today callers must manually bridge every layer:
426
+
427
+ ```ts
428
+ const request = LLM.request({
429
+ model,
430
+ prompt,
431
+ tools: Tool.toDefinitions(tools),
432
+ })
433
+
434
+ const events = yield * LLM.stream(request).pipe(Stream.runCollect)
435
+ const call = Array.from(events).find(LLMEvent.is.toolCall)
436
+
437
+ if (call && !call.providerExecuted) {
438
+ const dispatched = yield * ToolRuntime.dispatch(tools, call)
439
+ const followUp = LLM.updateRequest(request, {
440
+ messages: [...request.messages, Message.assistant([call]), Message.tool({ ...call, result: dispatched.result })],
441
+ })
442
+ // Caller must invoke the provider again and repeat the loop.
443
+ }
444
+ ```
445
+
446
+ That explicit flow remains possible through turn APIs, but it is no longer the
447
+ only tool experience.
448
+
449
+ ## One Provider Turn
450
+
451
+ OpenCode and other durable runtimes need to own persistence, tool settlement,
452
+ and continuation. They use the explicit turn API:
453
+
454
+ ```ts
455
+ const result =
456
+ yield *
457
+ LLM.generateTurn({
458
+ model,
459
+ request,
460
+ // Definitions only. generateTurn never dispatches local handlers.
461
+ tools: {
462
+ getWeather: Tool.definition({
463
+ description: "Get current weather for a city.",
464
+ parameters: WeatherInput,
465
+ }),
466
+ },
467
+ })
468
+
469
+ // Persist the TurnResult and settle calls durably before the next turn.
470
+ for (const call of result.toolCalls) {
471
+ // Application-owned dispatch and persistence.
472
+ }
473
+ ```
474
+
475
+ `generateTurn` and `streamTurn` make exactly one provider request. They never
476
+ execute a local tool and never continue automatically.
477
+
478
+ This separation is load-bearing:
479
+
480
+ - `generate` / `stream`: complete Model Run
481
+ - `generateTurn` / `streamTurn`: one Provider Turn
482
+
483
+ ## Portable Tool Definitions
484
+
485
+ A portable request may declare serializable definitions, but executable handlers
486
+ are bound at run time:
487
+
488
+ ```ts
489
+ const request = LLM.request({
490
+ prompt: "What is the weather in London?",
491
+ tools: {
492
+ getWeather: Tool.definition({
493
+ description: "Get current weather for a city.",
494
+ parameters: WeatherInput,
495
+ }),
496
+ },
497
+ })
498
+
499
+ const result =
500
+ yield *
501
+ LLM.generate({
502
+ model,
503
+ request,
504
+ tools: {
505
+ getWeather: Tool.make({
506
+ description: "Get current weather for a city.",
507
+ parameters: WeatherInput,
508
+ success: WeatherOutput,
509
+ execute: getWeather,
510
+ formatError,
511
+ }),
512
+ },
513
+ })
514
+ ```
515
+
516
+ Definitions and handlers match by record key. Before the first provider call,
517
+ the runtime validates that every local definition has a compatible executable
518
+ binding. Missing or incompatible bindings fail with a typed tool-binding error.
519
+
520
+ Provider-hosted tools are distinct typed values:
521
+
522
+ ```ts
523
+ const result =
524
+ yield *
525
+ LLM.generate({
526
+ model: OpenAI.model("gpt-4.1"),
527
+ prompt: "Find today's relevant announcements.",
528
+ tools: {
529
+ search: OpenAI.tool.webSearch({ searchContextSize: "medium" }),
530
+ },
531
+ })
532
+ ```
533
+
534
+ Hosted tools do not pretend to have local handlers, and callers do not inspect a
535
+ `providerExecuted` boolean to decide whether dispatch is safe.
536
+
537
+ ## Streaming
538
+
539
+ ### Run stream
540
+
541
+ `LLM.stream` returns an Effect `Stream<RunEvent, LLMError, Requirements>`.
542
+ Run events explicitly expose orchestration boundaries:
543
+
544
+ ```ts
545
+ const program = LLM.stream({ model, prompt, tools }).pipe(
546
+ Stream.tap((event) =>
547
+ Effect.sync(() => {
548
+ switch (event.type) {
549
+ case "run-start":
550
+ break
551
+ case "turn-start":
552
+ break
553
+ case "turn-event":
554
+ // Normalized text, reasoning, tool-call, usage, and finish events.
555
+ if (event.event.type === "text-delta") {
556
+ process.stdout.write(event.event.text)
557
+ }
558
+ break
559
+ case "tool-start":
560
+ break
561
+ case "tool-finish":
562
+ break
563
+ case "turn-finish":
564
+ break
565
+ case "run-finish":
566
+ // Contains the same full GenerateResult returned by LLM.generate.
567
+ console.log(event.result.usage)
568
+ break
569
+ }
570
+ }),
571
+ ),
572
+ Stream.runDrain,
573
+ )
574
+ ```
575
+
576
+ Exact event tag spelling remains an implementation detail to finalize, but the
577
+ algebra is settled:
578
+
579
+ - A separate `RunEvent` union for run, turn, and tool lifecycle
580
+ - A focused `TurnEvent` union for normalized provider output
581
+ - `streamTurn` emits only `TurnEvent`
582
+ - The terminal run event contains the full `GenerateResult`
583
+
584
+ External cancellation remains Effect interruption. It does not fabricate a
585
+ successful result with an `interrupted` stop reason.
586
+
587
+ ## Structured Output
588
+
589
+ Structured output is an option on `generate`, not a separate operation:
590
+
591
+ ```ts
592
+ const Weather = Schema.Struct({
593
+ city: Schema.String,
594
+ forecast: Schema.String,
595
+ highCelsius: Schema.Number,
596
+ })
597
+
598
+ const result =
599
+ yield *
600
+ LLM.generate({
601
+ model,
602
+ prompt: "Give me today's weather for London.",
603
+ output: Weather,
604
+ })
605
+
606
+ // Inferred from Weather.
607
+ result.output.city
608
+ ```
609
+
610
+ The model declaration and protocol select the best reliable strategy:
611
+
612
+ 1. Provider-native structured output when supported and reliable
613
+ 2. Forced tool output when required as a compatibility fallback
614
+ 3. Typed unsupported-capability failure before network execution when neither is
615
+ available
616
+
617
+ Advanced callers may override the strategy when exact provider semantics matter.
618
+
619
+ ### Current API
620
+
621
+ ```ts
622
+ // Current API is a separate operation and always forces a synthetic tool.
623
+ const result =
624
+ yield *
625
+ LLM.generateObject({
626
+ model,
627
+ prompt,
628
+ schema: Weather,
629
+ })
630
+ ```
631
+
632
+ The proposal unifies generation and lets capabilities choose the strategy rather
633
+ than permanently encoding one cross-provider workaround.
634
+
635
+ ## Model Catalog
636
+
637
+ `models.dev` is the release-time source for:
638
+
639
+ - Model ID suggestions
640
+ - Capabilities and modalities
641
+ - Context and output limits
642
+ - Pricing
643
+ - Other available model metadata
644
+
645
+ The package ships a generated, versioned snapshot. Normal execution performs no
646
+ catalog network requests.
647
+
648
+ Provider definitions may correct generated metadata where protocol-specific
649
+ knowledge is more accurate. Precedence is:
650
+
651
+ ```text
652
+ models.dev snapshot
653
+ < provider-definition correction
654
+ < provider configuration override
655
+ < model-selection override
656
+ < call override
657
+ ```
658
+
659
+ Unknown model IDs inherit only capabilities guaranteed by the selected protocol.
660
+ Unsupported request capabilities fail before network execution unless the caller
661
+ explicitly overrides the model declaration.
662
+
663
+ ## Usage And Cost
664
+
665
+ `GenerateResult` aggregates normalized usage across every turn, including cache
666
+ read/write usage where providers report it.
667
+
668
+ It also exposes estimated cost using the generated models.dev pricing snapshot:
669
+
670
+ ```ts
671
+ result.usage.inputTokens
672
+ result.usage.outputTokens
673
+ result.usage.cacheReadInputTokens
674
+ result.usage.cacheWriteInputTokens
675
+
676
+ result.cost?.total
677
+ result.cost?.currency // e.g. "USD"
678
+ ```
679
+
680
+ Cost is an estimate, not a billing guarantee. If reliable pricing is unavailable
681
+ for any turn, aggregate run cost is unavailable rather than partial or silently
682
+ zero. Per-turn metadata should retain the catalog/pricing identity used so an
683
+ estimate can be explained.
684
+
685
+ ## Caching
686
+
687
+ Prompt caching remains `"auto"` by default. The library places protocol-aware
688
+ cache boundaries where explicit caching is supported and does nothing on the wire
689
+ where providers cache implicitly.
690
+
691
+ ```ts
692
+ yield *
693
+ LLM.generate({
694
+ model,
695
+ prompt,
696
+ cache: "none", // Explicit opt-out.
697
+ })
698
+ ```
699
+
700
+ Granular cache policy remains available as an advanced request option.
701
+
702
+ ## Retries, Timeouts, And Cancellation
703
+
704
+ ### Retries
705
+
706
+ The default retry policy is deliberately conservative:
707
+
708
+ - Retry bounded transient transport and rate-limit failures
709
+ - Retry only before observable output
710
+ - Never silently retry after ambiguous tool execution or other side effects
711
+ - Allow each call to override or disable retry behavior
712
+
713
+ Retry configuration is call-scoped only. Provider and model configuration do not
714
+ silently inherit custom retry policies.
715
+
716
+ ### Timeouts
717
+
718
+ ```ts
719
+ yield *
720
+ LLM.generate({
721
+ model,
722
+ prompt,
723
+ timeout: "2 minutes", // Entire run, including tools.
724
+ turnTimeout: "30 seconds", // Each provider turn.
725
+ tools,
726
+ })
727
+ ```
728
+
729
+ Exact Duration input spelling follows Effect conventions. Individual tools may
730
+ also declare optional timeouts.
731
+
732
+ ### Cancellation
733
+
734
+ - Effect API: fiber interruption
735
+ - Promise API: `AbortSignal`, rejecting with a recognizable abort error
736
+ - Cancellation is not a successful run stop reason
737
+
738
+ ## Hooks
739
+
740
+ Stable high-level hooks exist at five named stages:
741
+
742
+ 1. Canonical request
743
+ 2. Provider-native body
744
+ 3. Prepared transport request
745
+ 4. Normalized event
746
+ 5. Error
747
+
748
+ Hooks are Effectful. They may transform the stage value or fail with a typed
749
+ error. They may not secretly short-circuit execution, synthesize a response,
750
+ retry, or redirect control flow.
751
+
752
+ ```ts
753
+ const model = OpenAI.model("gpt-4.1", {
754
+ hooks: {
755
+ request: (request) =>
756
+ Effect.succeed({
757
+ ...request,
758
+ metadata: { ...request.metadata, tenant: "acme" },
759
+ }),
760
+ body: (body, context) => auditBody(body, context),
761
+ transport: (request) => signInternalGatewayRequest(request),
762
+ event: (event) => redactProviderMetadata(event),
763
+ error: (error) => classifyInternalError(error),
764
+ },
765
+ })
766
+ ```
767
+
768
+ Hook scopes compose in this order:
769
+
770
+ ```text
771
+ provider-definition hooks -> model hooks -> call hooks
772
+ ```
773
+
774
+ Each hook sees the prior hook's output. Replacement requires an explicit
775
+ definition-level patch, not accidental last-writer-wins semantics.
776
+
777
+ Provider-definition hooks are authored by provider integrations. They are not
778
+ passed through `Provider.configure(...)`, which remains deployment-only.
779
+
780
+ ## HTTP And Provider Escape Hatches
781
+
782
+ The request customization ladder is:
783
+
784
+ 1. Portable generation controls
785
+ 2. Model-typed `provider` options
786
+ 3. Stable staged hooks
787
+ 4. Serializable HTTP/body overlays
788
+ 5. Experimental provider-definition or protocol patching
789
+
790
+ ```ts
791
+ yield *
792
+ LLM.generate({
793
+ model,
794
+ prompt,
795
+ http: {
796
+ headers: { "x-experimental": "1" },
797
+ query: { debug: "true" },
798
+ body: { newlyReleasedProviderField: true },
799
+ },
800
+ })
801
+ ```
802
+
803
+ Raw overlays are intentional last-resort support for provider features that ship
804
+ before the library has a typed option.
805
+
806
+ ## Provider-Native Metadata
807
+
808
+ Normalized message/content/event unions remain closed and exhaustive. Unknown or
809
+ provider-required round-trip data lives in caller-writable `providerMetadata`.
810
+
811
+ ```ts
812
+ const assistant = Message.assistant([
813
+ {
814
+ type: "reasoning",
815
+ text: "...",
816
+ providerMetadata: {
817
+ openai: {
818
+ // Opaque provider data needed for replay or continuation.
819
+ },
820
+ },
821
+ },
822
+ ])
823
+ ```
824
+
825
+ Protocols validate metadata they consume. The field is an escape hatch, not a
826
+ portable semantic guarantee.
827
+
828
+ ## Error Model
829
+
830
+ The Effect error channel is a tagged domain union rather than one `LLMError`
831
+ wrapper with nested reasons. Illustrative categories:
832
+
833
+ ```ts
834
+ type LLMError =
835
+ | AuthenticationError
836
+ | InvalidRequestError
837
+ | UnsupportedCapabilityError
838
+ | ToolBindingError
839
+ | TransportError
840
+ | ProviderResponseError
841
+ | InvalidProviderOutputError
842
+ | HookError
843
+ ```
844
+
845
+ Each error retains relevant provider/model/turn/stage context and its underlying
846
+ cause where available.
847
+
848
+ Expected tool errors keep their own typed error channel. `Tool.make` requires an
849
+ explicit mapping before such errors become model-visible tool results. Expected
850
+ mapped failures let the model recover; defects and interruption fail the run.
851
+
852
+ ## Observability
853
+
854
+ The core library emits Effect-native spans and metrics for:
855
+
856
+ - Model runs
857
+ - Provider turns
858
+ - Provider requests
859
+ - Retries
860
+ - Tool executions
861
+
862
+ Default telemetry records metadata only:
863
+
864
+ - Provider and model identity
865
+ - Timing
866
+ - Token/cache usage
867
+ - Estimated cost availability
868
+ - Finish and stop reasons
869
+ - Retry counts
870
+ - Tool names
871
+
872
+ Prompts, model output, tool arguments, and tool results are never recorded by
873
+ default. Explicit hooks or telemetry configuration may opt into content capture.
874
+
875
+ ## Promise API
876
+
877
+ Promise wrappers live at a separate subpath so the root remains unambiguously
878
+ Effect-first:
879
+
880
+ ```ts
881
+ import { LLM } from "@opencode-ai/ai/promise"
882
+ import { OpenAI } from "@opencode-ai/ai/providers/openai"
883
+
884
+ const result = await LLM.generate({
885
+ model: OpenAI.model("gpt-4.1-mini"),
886
+ prompt: "Explain Effect in one sentence.",
887
+ signal: abortController.signal,
888
+ })
889
+ ```
890
+
891
+ Streaming returns an `AsyncIterable<RunEvent>`:
892
+
893
+ ```ts
894
+ for await (const event of LLM.stream({ model, prompt, signal })) {
895
+ if (event.type === "turn-event" && event.event.type === "text-delta") {
896
+ process.stdout.write(event.event.text)
897
+ }
898
+ }
899
+ ```
900
+
901
+ Top-level Promise functions use a default runtime for built-in services. Custom
902
+ Effect service requirements use a configured client:
903
+
904
+ ```ts
905
+ const client = LLM.makeClient({
906
+ layer: Layer.mergeAll(WeatherLive, AuditLive),
907
+ })
908
+
909
+ const result = await client.generate({ model, prompt, tools })
910
+ ```
911
+
912
+ The Promise API mirrors Effect semantics. It does not invent different run,
913
+ error, stopping, or cancellation behavior.
914
+
915
+ ## Schemas
916
+
917
+ Schemas live in a dedicated namespace/subpath instead of flooding root exports:
918
+
919
+ ```ts
920
+ import { LLMSchema } from "@opencode-ai/ai/schema"
921
+
922
+ const request = yield * Schema.decodeUnknown(LLMSchema.Request)(input)
923
+ ```
924
+
925
+ Schemas cover only serializable domain values:
926
+
927
+ - Requests and messages
928
+ - Portable tool definitions
929
+ - Turn and run events
930
+ - Serializable result projections
931
+ - Usage and cost estimates
932
+ - Tagged errors where serializable
933
+ - Provider metadata containers
934
+
935
+ Configured models, executable tools, hooks, provider definitions, and protocols
936
+ are process-local behavior and do not receive fake serialization schemas.
937
+
938
+ ## Provider Authoring
939
+
940
+ Provider authoring is public but experimental.
941
+
942
+ ### Declarative provider definition
943
+
944
+ ```ts
945
+ import { Provider, Protocol } from "@opencode-ai/ai/provider"
946
+
947
+ export const ExampleAI = Provider.define({
948
+ id: "example",
949
+ options: ExampleProviderOptions,
950
+ configure: configureExampleDeployment,
951
+ protocols: {
952
+ responses: ExampleResponses,
953
+ },
954
+ models: ({ deployment, catalog }) => ({
955
+ model: (id, defaults) =>
956
+ Provider.model({
957
+ id,
958
+ deployment,
959
+ protocol: ExampleResponses,
960
+ metadata: catalog.model(id),
961
+ defaults,
962
+ }),
963
+ }),
964
+ catalog: generatedExampleCatalog,
965
+ corrections: exampleCatalogCorrections,
966
+ hooks: exampleProviderHooks,
967
+ })
968
+ ```
969
+
970
+ The exact builder fields need implementation design, but it must remain one
971
+ declarative immutable object, infer provider option types, and support `.with(...)`
972
+ patching. It must not register globally.
973
+
974
+ Built-ins export their immutable definition for advanced forking:
975
+
976
+ ```ts
977
+ import { OpenAI } from "@opencode-ai/ai/providers/openai"
978
+
979
+ const PatchedOpenAI = OpenAI.definition.with({
980
+ protocols: {
981
+ responses: OpenAI.protocols.responses.with({
982
+ // Explicit immutable stage patch.
983
+ body: {
984
+ fromRequest: patchResponsesBody,
985
+ },
986
+ }),
987
+ },
988
+ })
989
+ ```
990
+
991
+ ### Protocols
992
+
993
+ A protocol exposes all native types and stages:
994
+
995
+ - Provider-native request body and schema
996
+ - Transport frame type
997
+ - Provider-native event and schema
998
+ - Parser state
999
+ - Request lowering
1000
+ - Event stepping
1001
+ - Terminal detection and final flushing
1002
+
1003
+ Every stage is immutably patchable. This is deliberately more open than the AI
1004
+ SDK integrations that motivated this package.
1005
+
1006
+ ```ts
1007
+ const PatchedResponses = OpenAIResponses.with({
1008
+ body: {
1009
+ fromRequest: (request) =>
1010
+ OpenAIResponses.body.fromRequest(request).pipe(Effect.map((body) => ({ ...body, custom_field: true }))),
1011
+ },
1012
+ stream: {
1013
+ step: patchResponsesStep,
1014
+ },
1015
+ })
1016
+ ```
1017
+
1018
+ Protocol body, frame, native event, and parser-state types are exported. Because
1019
+ provider wire formats change often, these types and patch APIs are explicitly
1020
+ experimental and do not receive the high-level API's compatibility promise.
1021
+
1022
+ ## Package Surface
1023
+
1024
+ Illustrative export layout:
1025
+
1026
+ ```text
1027
+ @opencode-ai/ai
1028
+ LLM
1029
+ Message
1030
+ Tool
1031
+ StopWhen
1032
+ stable domain types
1033
+
1034
+ @opencode-ai/ai/promise
1035
+ Promise/AsyncIterable LLM facade
1036
+
1037
+ @opencode-ai/ai/schema
1038
+ serializable domain schemas
1039
+
1040
+ @opencode-ai/ai/provider
1041
+ experimental Provider and Protocol authoring APIs
1042
+
1043
+ @opencode-ai/ai/providers/openai
1044
+ @opencode-ai/ai/providers/anthropic
1045
+ @opencode-ai/ai/providers/google
1046
+ ...
1047
+ ```
1048
+
1049
+ Providers are imported through individual subpaths. The root does not export all
1050
+ providers, and there is no preferred all-providers barrel.
1051
+
1052
+ ## Defaults
1053
+
1054
+ | Concern | Default |
1055
+ | ---------------------------- | --------------------------------------------------- |
1056
+ | `LLM.generate` semantics | Complete Model Run |
1057
+ | `LLM.generateTurn` semantics | Exactly one Provider Turn |
1058
+ | Maximum turns | 20 |
1059
+ | Turn-limit outcome | Successful `max-turns` result |
1060
+ | Tool execution | Automatic in runs |
1061
+ | Tool concurrency | Concurrent, bounded, deterministic result order |
1062
+ | Prompt caching | `auto` |
1063
+ | Retries | Conservative, pre-output transient failures only |
1064
+ | Structured output | Capability-selected native or tool strategy |
1065
+ | Capability mismatch | Typed failure before network execution |
1066
+ | Unknown model capability | Conservative protocol baseline |
1067
+ | Telemetry content | Metadata only |
1068
+ | Cost | Estimated aggregate or unavailable |
1069
+ | Cancellation | Interruption/rejection, never successful completion |
1070
+
1071
+ ## Clean-break Migration
1072
+
1073
+ The redesign intentionally removes or changes these current concepts:
1074
+
1075
+ | Current | Proposed |
1076
+ | --------------------------------------- | ----------------------------------------------------------- |
1077
+ | `@opencode-ai/llm` | `@opencode-ai/ai` |
1078
+ | Mandatory `LLM.request({ model, ... })` | Inline calls or model-free portable requests |
1079
+ | `LLM.generate` means one turn | `LLM.generate` means complete run |
1080
+ | `LLMClient.generate/stream` | `LLM.generateTurn/streamTurn` for one turn |
1081
+ | `LLMClient.layer` requirement | Standard Effect requirements exposed directly |
1082
+ | Public `Route` mental model | Hidden behind executable `Model` |
1083
+ | `Provider.make` structural helper | Experimental declarative `Provider.define` |
1084
+ | Schema classes as canonical values | Plain immutable values plus schema subpath |
1085
+ | `LLM.updateRequest` | Object spread |
1086
+ | `Tool.toDefinitions` in normal calls | Named executable tool records |
1087
+ | Manual `ToolRuntime.dispatch` loop | Automatic run dispatch; explicit turn API for orchestration |
1088
+ | `providerOptions: { openai: ... }` | Model-typed `provider: ...` |
1089
+ | `generateObject` | Typed `output` option on `generate` |
1090
+ | One event union for provider output | Separate `TurnEvent` and `RunEvent` unions |
1091
+ | `providerExecuted` dispatch check | Distinct hosted-tool constructors |
1092
+ | One wrapped `LLMError` | Tagged domain error union |
1093
+
1094
+ OpenCode should migrate to `generateTurn` / `streamTurn`, preserving its durable
1095
+ prompt admission, persistence, permission, tool settlement, and continuation
1096
+ boundaries. It should not use the automatic run API for Session orchestration.
1097
+
1098
+ ## Remaining Implementation-level Questions
1099
+
1100
+ These do not reopen the main design:
1101
+
1102
+ 1. Exact `RunEvent` and `TurnEvent` tag names and payloads
1103
+ 2. Exact `GenerateResult` shortcut fields for text, reasoning, output, and messages
1104
+ 3. Exact Provider definition TypeScript shape needed for strong inference
1105
+ 4. Exact protocol `.with(...)` patch syntax and replacement semantics
1106
+ 5. Exact Duration input fields and names
1107
+ 6. Exact models.dev generation pipeline and correction-file format
1108
+ 7. Exact cost representation and decimal arithmetic strategy
1109
+ 8. Exact default retry schedule and bounded tool concurrency number
1110
+ 9. Whether request-level serializable HTTP overlays belong in the stable schema
1111
+ 10. Which tagged errors are serializable versus process-local
1112
+
1113
+ These should be resolved with call-site sketches and implementation spikes rather
1114
+ than by changing the domain boundaries above.