@techis/ai-runtime 0.3.0-rc.16 → 0.4.0-rc.4

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 (287) hide show
  1. package/ADAPTER-AUTHORING.md +101 -0
  2. package/ADAPTER-CONFORMANCE.md +50 -0
  3. package/ANTHROPIC-MESSAGES.md +115 -0
  4. package/API.md +275 -0
  5. package/GEMINI-INTERACTIONS.md +49 -0
  6. package/MIGRATION.md +114 -0
  7. package/MOONSHOT-CHAT.md +53 -0
  8. package/OPENAI-RESPONSES.md +62 -0
  9. package/README.md +52 -39
  10. package/THIRD_PARTY_NOTICES +34 -34
  11. package/ZAI-CHAT.md +35 -0
  12. package/dist/adapters/anthropic-capabilities.d.ts +14 -0
  13. package/dist/adapters/anthropic-capabilities.d.ts.map +1 -0
  14. package/dist/adapters/anthropic-capabilities.js +63 -0
  15. package/dist/adapters/anthropic-capabilities.js.map +1 -0
  16. package/dist/adapters/anthropic-mapping.d.ts +7 -0
  17. package/dist/adapters/anthropic-mapping.d.ts.map +1 -0
  18. package/dist/adapters/anthropic-mapping.js +370 -0
  19. package/dist/adapters/anthropic-mapping.js.map +1 -0
  20. package/dist/adapters/anthropic-stream.d.ts +16 -0
  21. package/dist/adapters/anthropic-stream.d.ts.map +1 -0
  22. package/dist/adapters/anthropic-stream.js +271 -0
  23. package/dist/adapters/anthropic-stream.js.map +1 -0
  24. package/dist/adapters/anthropic.d.ts +4 -0
  25. package/dist/adapters/anthropic.d.ts.map +1 -0
  26. package/dist/adapters/anthropic.js +63 -0
  27. package/dist/adapters/anthropic.js.map +1 -0
  28. package/dist/adapters/chat-stream.d.ts +17 -0
  29. package/dist/adapters/chat-stream.d.ts.map +1 -0
  30. package/dist/adapters/chat-stream.js +220 -0
  31. package/dist/adapters/chat-stream.js.map +1 -0
  32. package/dist/adapters/conformance.d.ts +75 -0
  33. package/dist/adapters/conformance.d.ts.map +1 -0
  34. package/dist/adapters/conformance.js +156 -0
  35. package/dist/adapters/conformance.js.map +1 -0
  36. package/dist/adapters/gemini-mapping.d.ts +17 -0
  37. package/dist/adapters/gemini-mapping.d.ts.map +1 -0
  38. package/dist/adapters/gemini-mapping.js +295 -0
  39. package/dist/adapters/gemini-mapping.js.map +1 -0
  40. package/dist/adapters/gemini-stream.d.ts +6 -0
  41. package/dist/adapters/gemini-stream.d.ts.map +1 -0
  42. package/dist/adapters/gemini-stream.js +316 -0
  43. package/dist/adapters/gemini-stream.js.map +1 -0
  44. package/dist/adapters/gemini.d.ts +3 -1
  45. package/dist/adapters/gemini.d.ts.map +1 -1
  46. package/dist/adapters/gemini.js +43 -62
  47. package/dist/adapters/gemini.js.map +1 -1
  48. package/dist/adapters/http.d.ts +22 -6
  49. package/dist/adapters/http.d.ts.map +1 -1
  50. package/dist/adapters/http.js +152 -56
  51. package/dist/adapters/http.js.map +1 -1
  52. package/dist/adapters/moonshot-mapping.d.ts +14 -0
  53. package/dist/adapters/moonshot-mapping.d.ts.map +1 -0
  54. package/dist/adapters/moonshot-mapping.js +242 -0
  55. package/dist/adapters/moonshot-mapping.js.map +1 -0
  56. package/dist/adapters/moonshot.d.ts.map +1 -1
  57. package/dist/adapters/moonshot.js +48 -13
  58. package/dist/adapters/moonshot.js.map +1 -1
  59. package/dist/adapters/openai-mapping.d.ts +13 -0
  60. package/dist/adapters/openai-mapping.d.ts.map +1 -0
  61. package/dist/adapters/openai-mapping.js +242 -0
  62. package/dist/adapters/openai-mapping.js.map +1 -0
  63. package/dist/adapters/openai-stream.d.ts +5 -0
  64. package/dist/adapters/openai-stream.d.ts.map +1 -0
  65. package/dist/adapters/openai-stream.js +288 -0
  66. package/dist/adapters/openai-stream.js.map +1 -0
  67. package/dist/adapters/openai.d.ts +1 -1
  68. package/dist/adapters/openai.d.ts.map +1 -1
  69. package/dist/adapters/openai.js +32 -65
  70. package/dist/adapters/openai.js.map +1 -1
  71. package/dist/adapters/registry.d.ts +12 -1
  72. package/dist/adapters/registry.d.ts.map +1 -1
  73. package/dist/adapters/registry.js +145 -1
  74. package/dist/adapters/registry.js.map +1 -1
  75. package/dist/adapters/request-capabilities.d.ts +4 -0
  76. package/dist/adapters/request-capabilities.d.ts.map +1 -0
  77. package/dist/adapters/request-capabilities.js +53 -0
  78. package/dist/adapters/request-capabilities.js.map +1 -0
  79. package/dist/adapters/sse.d.ts +24 -0
  80. package/dist/adapters/sse.d.ts.map +1 -0
  81. package/dist/adapters/sse.js +209 -0
  82. package/dist/adapters/sse.js.map +1 -0
  83. package/dist/adapters/stream-evidence.d.ts +14 -0
  84. package/dist/adapters/stream-evidence.d.ts.map +1 -0
  85. package/dist/adapters/stream-evidence.js +69 -0
  86. package/dist/adapters/stream-evidence.js.map +1 -0
  87. package/dist/adapters/types.d.ts +99 -1
  88. package/dist/adapters/types.d.ts.map +1 -1
  89. package/dist/adapters/validation.d.ts +8 -0
  90. package/dist/adapters/validation.d.ts.map +1 -0
  91. package/dist/adapters/validation.js +231 -0
  92. package/dist/adapters/validation.js.map +1 -0
  93. package/dist/adapters/zai-mapping.d.ts +12 -0
  94. package/dist/adapters/zai-mapping.d.ts.map +1 -0
  95. package/dist/adapters/zai-mapping.js +246 -0
  96. package/dist/adapters/zai-mapping.js.map +1 -0
  97. package/dist/adapters/zai.d.ts +1 -25
  98. package/dist/adapters/zai.d.ts.map +1 -1
  99. package/dist/adapters/zai.js +37 -67
  100. package/dist/adapters/zai.js.map +1 -1
  101. package/dist/bundle-source.d.ts.map +1 -1
  102. package/dist/bundle-source.js +9 -7
  103. package/dist/bundle-source.js.map +1 -1
  104. package/dist/catalog-delivery.d.ts +7 -0
  105. package/dist/catalog-delivery.d.ts.map +1 -1
  106. package/dist/catalog-delivery.js +87 -39
  107. package/dist/catalog-delivery.js.map +1 -1
  108. package/dist/catalog-publication-source.d.ts +16 -0
  109. package/dist/catalog-publication-source.d.ts.map +1 -0
  110. package/dist/catalog-publication-source.js +99 -0
  111. package/dist/catalog-publication-source.js.map +1 -0
  112. package/dist/catalog-publication.d.ts +50 -0
  113. package/dist/catalog-publication.d.ts.map +1 -0
  114. package/dist/catalog-publication.js +127 -0
  115. package/dist/catalog-publication.js.map +1 -0
  116. package/dist/catalog-reader-configuration.d.ts +6 -0
  117. package/dist/catalog-reader-configuration.d.ts.map +1 -0
  118. package/dist/catalog-reader-configuration.js +2 -0
  119. package/dist/catalog-reader-configuration.js.map +1 -0
  120. package/dist/catalog-transfer.d.ts +11 -0
  121. package/dist/catalog-transfer.d.ts.map +1 -0
  122. package/dist/catalog-transfer.js +55 -0
  123. package/dist/catalog-transfer.js.map +1 -0
  124. package/dist/client.d.ts +9 -1
  125. package/dist/client.d.ts.map +1 -1
  126. package/dist/client.js +14 -6
  127. package/dist/client.js.map +1 -1
  128. package/dist/compatibility-client.d.ts +58 -0
  129. package/dist/compatibility-client.d.ts.map +1 -0
  130. package/dist/compatibility-client.js +116 -0
  131. package/dist/compatibility-client.js.map +1 -0
  132. package/dist/compatibility-execution.d.ts +47 -0
  133. package/dist/compatibility-execution.d.ts.map +1 -0
  134. package/dist/compatibility-execution.js +2 -0
  135. package/dist/compatibility-execution.js.map +1 -0
  136. package/dist/compatibility-stream-projection.d.ts +116 -0
  137. package/dist/compatibility-stream-projection.d.ts.map +1 -0
  138. package/dist/compatibility-stream-projection.js +188 -0
  139. package/dist/compatibility-stream-projection.js.map +1 -0
  140. package/dist/compatibility-types.d.ts +281 -0
  141. package/dist/compatibility-types.d.ts.map +1 -0
  142. package/dist/compatibility-types.js +2 -0
  143. package/dist/compatibility-types.js.map +1 -0
  144. package/dist/continuation.d.ts +49 -0
  145. package/dist/continuation.d.ts.map +1 -0
  146. package/dist/continuation.js +187 -0
  147. package/dist/continuation.js.map +1 -0
  148. package/dist/cost.d.ts +19 -4
  149. package/dist/cost.d.ts.map +1 -1
  150. package/dist/cost.js +109 -38
  151. package/dist/cost.js.map +1 -1
  152. package/dist/direct-model-client.d.ts +4 -0
  153. package/dist/direct-model-client.d.ts.map +1 -0
  154. package/dist/direct-model-client.js +37 -0
  155. package/dist/direct-model-client.js.map +1 -0
  156. package/dist/direct-model-types.d.ts +40 -0
  157. package/dist/direct-model-types.d.ts.map +1 -0
  158. package/dist/direct-model-types.js +2 -0
  159. package/dist/direct-model-types.js.map +1 -0
  160. package/dist/errors.d.ts +27 -1
  161. package/dist/errors.d.ts.map +1 -1
  162. package/dist/errors.js +10 -7
  163. package/dist/errors.js.map +1 -1
  164. package/dist/execution-configuration.d.ts +33 -0
  165. package/dist/execution-configuration.d.ts.map +1 -0
  166. package/dist/execution-configuration.js +16 -0
  167. package/dist/execution-configuration.js.map +1 -0
  168. package/dist/feature-planning.d.ts +23 -0
  169. package/dist/feature-planning.d.ts.map +1 -0
  170. package/dist/feature-planning.js +249 -0
  171. package/dist/feature-planning.js.map +1 -0
  172. package/dist/feature-policy.d.ts +13 -0
  173. package/dist/feature-policy.d.ts.map +1 -0
  174. package/dist/feature-policy.js +60 -0
  175. package/dist/feature-policy.js.map +1 -0
  176. package/dist/generation-input.d.ts +7 -0
  177. package/dist/generation-input.d.ts.map +1 -0
  178. package/dist/generation-input.js +24 -0
  179. package/dist/generation-input.js.map +1 -0
  180. package/dist/generation-stream.d.ts +35 -0
  181. package/dist/generation-stream.d.ts.map +1 -0
  182. package/dist/generation-stream.js +178 -0
  183. package/dist/generation-stream.js.map +1 -0
  184. package/dist/index.d.ts +36 -5
  185. package/dist/index.d.ts.map +1 -1
  186. package/dist/index.js +30 -3
  187. package/dist/index.js.map +1 -1
  188. package/dist/model-client-types.d.ts +99 -0
  189. package/dist/model-client-types.d.ts.map +1 -0
  190. package/dist/model-client-types.js +7 -0
  191. package/dist/model-client-types.js.map +1 -0
  192. package/dist/model-client.d.ts +3 -0
  193. package/dist/model-client.d.ts.map +1 -0
  194. package/dist/model-client.js +96 -0
  195. package/dist/model-client.js.map +1 -0
  196. package/dist/model-configuration.d.ts +40 -0
  197. package/dist/model-configuration.d.ts.map +1 -0
  198. package/dist/model-configuration.js +102 -0
  199. package/dist/model-configuration.js.map +1 -0
  200. package/dist/named-client-types.d.ts +72 -0
  201. package/dist/named-client-types.d.ts.map +1 -0
  202. package/dist/named-client-types.js +4 -0
  203. package/dist/named-client-types.js.map +1 -0
  204. package/dist/named-client.d.ts +4 -0
  205. package/dist/named-client.d.ts.map +1 -0
  206. package/dist/named-client.js +68 -0
  207. package/dist/named-client.js.map +1 -0
  208. package/dist/named-configuration.d.ts +57 -0
  209. package/dist/named-configuration.d.ts.map +1 -0
  210. package/dist/named-configuration.js +119 -0
  211. package/dist/named-configuration.js.map +1 -0
  212. package/dist/native-operation.d.ts +6 -0
  213. package/dist/native-operation.d.ts.map +1 -0
  214. package/dist/native-operation.js +45 -0
  215. package/dist/native-operation.js.map +1 -0
  216. package/dist/package-updates.d.ts +2 -0
  217. package/dist/package-updates.d.ts.map +1 -1
  218. package/dist/package-updates.js +5 -9
  219. package/dist/package-updates.js.map +1 -1
  220. package/dist/profile-client.d.ts +13 -0
  221. package/dist/profile-client.d.ts.map +1 -0
  222. package/dist/profile-client.js +57 -0
  223. package/dist/profile-client.js.map +1 -0
  224. package/dist/published-catalog.d.ts +22 -0
  225. package/dist/published-catalog.d.ts.map +1 -0
  226. package/dist/published-catalog.js +25 -0
  227. package/dist/published-catalog.js.map +1 -0
  228. package/dist/reasoning-resolution.d.ts.map +1 -1
  229. package/dist/reasoning-resolution.js +11 -2
  230. package/dist/reasoning-resolution.js.map +1 -1
  231. package/dist/request-mapping.d.ts +15 -0
  232. package/dist/request-mapping.d.ts.map +1 -0
  233. package/dist/request-mapping.js +479 -0
  234. package/dist/request-mapping.js.map +1 -0
  235. package/dist/resolution.d.ts.map +1 -1
  236. package/dist/resolution.js +7 -10
  237. package/dist/resolution.js.map +1 -1
  238. package/dist/result-mapping.d.ts +17 -0
  239. package/dist/result-mapping.d.ts.map +1 -0
  240. package/dist/result-mapping.js +123 -0
  241. package/dist/result-mapping.js.map +1 -0
  242. package/dist/route-adoption-node.d.ts +22 -0
  243. package/dist/route-adoption-node.d.ts.map +1 -0
  244. package/dist/route-adoption-node.js +134 -0
  245. package/dist/route-adoption-node.js.map +1 -0
  246. package/dist/route-adoption.d.ts +100 -0
  247. package/dist/route-adoption.d.ts.map +1 -0
  248. package/dist/route-adoption.js +176 -0
  249. package/dist/route-adoption.js.map +1 -0
  250. package/dist/route-client.d.ts +78 -0
  251. package/dist/route-client.d.ts.map +1 -0
  252. package/dist/route-client.js +91 -0
  253. package/dist/route-client.js.map +1 -0
  254. package/dist/route-readiness.d.ts +27 -0
  255. package/dist/route-readiness.d.ts.map +1 -0
  256. package/dist/route-readiness.js +78 -0
  257. package/dist/route-readiness.js.map +1 -0
  258. package/dist/route-set-file-source.d.ts +7 -0
  259. package/dist/route-set-file-source.d.ts.map +1 -0
  260. package/dist/route-set-file-source.js +27 -0
  261. package/dist/route-set-file-source.js.map +1 -0
  262. package/dist/route-set-json-source.d.ts +27 -0
  263. package/dist/route-set-json-source.d.ts.map +1 -0
  264. package/dist/route-set-json-source.js +126 -0
  265. package/dist/route-set-json-source.js.map +1 -0
  266. package/dist/route-set.d.ts +30 -0
  267. package/dist/route-set.d.ts.map +1 -0
  268. package/dist/route-set.js +33 -0
  269. package/dist/route-set.js.map +1 -0
  270. package/dist/run.d.ts +42 -4
  271. package/dist/run.d.ts.map +1 -1
  272. package/dist/run.js +925 -474
  273. package/dist/run.js.map +1 -1
  274. package/dist/system-instructions.d.ts +23 -0
  275. package/dist/system-instructions.d.ts.map +1 -0
  276. package/dist/system-instructions.js +57 -0
  277. package/dist/system-instructions.js.map +1 -0
  278. package/dist/types.d.ts +3 -1
  279. package/dist/types.d.ts.map +1 -1
  280. package/dist/types.js.map +1 -1
  281. package/dist/version.d.ts +1 -1
  282. package/dist/version.d.ts.map +1 -1
  283. package/dist/version.js +1 -1
  284. package/dist/version.js.map +1 -1
  285. package/package.json +35 -26
  286. package/third-party-licenses.json +2 -7
  287. /package/third-party-licenses/{fast-uri@3.1.7 → fast-uri@3.1.9}/LICENSE +0 -0
@@ -0,0 +1,101 @@
1
+ # Authoring and overriding adapters
2
+
3
+ Clients may add or replace adapters explicitly when creating a runtime client. This is useful for a private provider, a reviewed protocol variation or host-specific transport behavior. Native JSON options already cover additional provider request settings; use an adapter when request/result/stream translation itself must change. The same registration works with both client coding styles and native named-configuration clients.
4
+
5
+ ## Registration and identity
6
+
7
+ ```ts
8
+ import { createAIClient, type CreateAIClientOptions, type ProviderAdapter } from '@techis/ai-runtime';
9
+
10
+ type HostOptions = Omit<CreateAIClientOptions, 'adapters' | 'adapterRegistration'>;
11
+
12
+ export function withPrivateProvider(options: HostOptions, adapter: ProviderAdapter) {
13
+ return createAIClient({ ...options, adapterRegistration: { add: [adapter] } });
14
+ }
15
+
16
+ export function withOpenAiReplacement(options: HostOptions, adapter: ProviderAdapter) {
17
+ return createAIClient({ ...options, adapterRegistration: { replace: [
18
+ { adapterId: 'openai-responses', adapter, compatibleAdapterVersion: '2.0.0' }
19
+ ] } });
20
+ }
21
+
22
+ export function withCompleteSet(options: HostOptions, adapters: ProviderAdapter[]) {
23
+ return createAIClient({ ...options, adapters });
24
+ }
25
+ ```
26
+
27
+ - `add` introduces a new unique route. Its catalog model must name that route and a provider the adapter declares.
28
+ - `replace` targets an existing default route and preserves unrelated defaults. The replacement must serve every provider of the replaced route. Replacing a missing route or registering duplicate/conflicting implementation identities rejects.
29
+ - `compatibleAdapterVersion` declares compatibility with the catalog route's minimum requirement. It is required if the implementation ID differs from the route; for the same ID it defaults to the implementation version. Declare compatibility only after qualifying it.
30
+ - The actual adapter `id`/`version` and contract version remain visible in receipts, independently of route compatibility. The catalog's minimum adapter version is a numeric version floor, not a general npm semver range.
31
+ - Legacy `adapters` replaces the entire set, including `[]`. It cannot be combined with `adapterRegistration`.
32
+
33
+ Explicit registration validates and snapshots metadata per client and binds methods to the supplied instance, preserving class/private-field behavior. It does not mutate global defaults. Legacy full-set registration retains its prior object-reference behavior. The host still owns implementation state; use fresh instances if sharing one stateful adapter would couple clients. Registrations are not dynamically changed on a captured run.
34
+
35
+ ## Contract versions
36
+
37
+ Omitted `contractVersion` or `1` is the legacy execute-only contract. It retains legacy request/result fields; it cannot claim rich function/native/streaming conformance by omitting tests. Unknown contract versions reject at registration.
38
+
39
+ Contract `2` requires an explicit `supportedFeatures` declaration. Both `generate` and the two rich interfaces enter the shared execution engine; contract-2 adapters receive canonical `request.generation` alongside the legacy fields. The runtime applies configuration, caps, feature planning and continuation before dispatch. Never route by client signature.
40
+
41
+ | Member | Author responsibility |
42
+ | --- | --- |
43
+ | `id`, `version`, `providers`, `defaultEndpoint` | Stable bounded identity, semantic version, provider coverage and valid default endpoint. |
44
+ | `supportedInputModalities`, `supportsStructuredOutput`, `supportedProviderTools` | Truthful declarations consistent with implemented transport. Absence of provider tools means none. |
45
+ | `supportedFeatures`, `protocol`, `supportsResponseId` | Explicit rich feature set, outbound protocol/version and whether exact-bound stored IDs can be consumed. |
46
+ | `requestCapabilities` | Restrictions inside supported features; omission does not establish actual wire support. |
47
+ | `resolveRequestCapabilities(model, reasoning)` | Optional pure per-model/control refinement, evaluated and validated before credentials, including after fallback control changes. |
48
+ | `translateReasoning(model, control)` | Map the selected native reasoning control without conflating provider defaults, disabled thinking, effort and token budgets. |
49
+ | `execute(request, fetchImpl)` | Use the resolved endpoint/credential/signal, preserve native evidence, and return legacy output plus canonical generation output. |
50
+ | `stream(request, fetchImpl)` | Incrementally translate provider data and emit one terminal result with consistent final content and usage. Required when advertising streaming. |
51
+
52
+ Capabilities can restrict sampling; tool choices; strict schemas (including `validated-auto`); object-valued function arguments; image detail; top-level text system instructions; native/local schema enforcement; prompt-based JSON objects; developer roles; and common search options/domain counts. Model-dependent declarations must be deterministic and free of network calls, configuration mutation and tool execution. Primary mismatches reject; backups preserve supported behavior and disclose omissions. Declarations do not implement native translation.
53
+
54
+ ## A complete synthetic adapter example
55
+
56
+ This adapter serves a fictional local provider and implements only its declared text/streaming features. It never sends HTTP or pretends to be a production provider. A configuration for it must use provider `example`, route `example-local` and compatible text-only model metadata. The full rich conformance suite will correctly reject its omitted tools/native-feature categories; use it to understand the lifecycle, not as evidence of provider qualification.
57
+
58
+ ```ts
59
+ import { CancellationError, type AdapterRequest, type AdapterResponse, type ProviderAdapter } from '@techis/ai-runtime';
60
+
61
+ export function createExampleAdapter(): ProviderAdapter {
62
+ const response = (request: AdapterRequest): AdapterResponse => {
63
+ if (request.signal?.aborted) throw new CancellationError();
64
+ const text = 'Synthetic answer';
65
+ return { output: { kind: 'text', text }, generation: { status: 'completed', text,
66
+ items: [{ type: 'message', role: 'assistant', content: [{ type: 'text', text }] }],
67
+ native: { provider: 'example', adapterId: 'example-local', adapterVersion: '1.0.0', body: { text } }
68
+ } };
69
+ };
70
+ return {
71
+ id: 'example-local', version: '1.0.0', contractVersion: 2, providers: ['example'], protocol: 'synthetic-v1',
72
+ defaultEndpoint: 'https://example.invalid', supportedInputModalities: ['text'], supportsStructuredOutput: false,
73
+ supportedFeatures: ['text', 'streaming'], translateReasoning: () => ({}),
74
+ async execute(request) { return response(request); },
75
+ async *stream(request) {
76
+ const result = response(request);
77
+ yield { type: 'text-delta', delta: result.generation!.text };
78
+ if (request.signal?.aborted) throw new CancellationError();
79
+ yield { type: 'result', response: result };
80
+ }
81
+ };
82
+ }
83
+ ```
84
+
85
+ Production adapters must implement every advertised feature and all applicable failure/continuation behavior. Use the injected fetch for transport and honor the request signal throughout response reading. The request's endpoint/credential are host-resolved authority; never let `providerOptions` override them. HTTP errors should become the appropriate exported `AISubsystemError` subclass, with sanitized default details and explicit native/HTTP evidence. Do not hide authentication failures as retryable transport failures. Never execute client functions or create a tool loop inside an adapter.
86
+
87
+ ## Results, streams and fidelity
88
+
89
+ Return `AdapterResponse.output` for legacy projection and `generation` for the canonical ordered result. Preserve completed, requires-action, refusal, incomplete and failure distinctions, received usage and original malformed argument strings. Preserve native body/request ID and provider-local replay blocks; do not manufacture portable history from opaque data. Mark `responseIdReusable: false` when an ID cannot retrieve stored state. Reuse is also bound by the runtime to provider/model/actual implementation/configuration revision.
90
+
91
+ `AdapterStreamEvent` includes start, text/refusal/reasoning deltas, function start/delta/done, native events, usage and terminal `result`. Function IDs and indexes must remain stable across interleaving calls. Output-item/content indexes are distinct from tool indexes. Emit refusal separately from answer text. Usage snapshots use the latest reported dimension, including zero; absence remains unknown. Finish with exactly one result and no later event. EOF without a result, contradictory final data, malformed frames and duplicate/inconsistent identities fail.
92
+
93
+ The runtime owns single-consumer semantics, public projections, terminal receipt settlement and output-exposure retry boundaries. Adapters must release readers in cancellation/error/iterator cleanup, avoid hidden retries/reconnections and preserve partial/native evidence on failures. A provider-derived event exposed to the caller prevents fallback within that invocation. Native final bodies may be assembled from incremental frames, but the original events must remain available where the adapter advertises native fidelity. Apply bounded frame/aggregate parsing; the built-in SSE implementations use 1 MiB/32 MiB limits.
94
+
95
+ ## Qualification and adoption
96
+
97
+ Use [runAdapterConformance](ADAPTER-CONFORMANCE.md) with fresh synthetic fixtures for all nine required categories, both signatures and final/streaming: at least 36 cells. Add provider-specific exact-wire, extension, replay, parallel-call, malformed-stream, usage and capability tests. Run fixtures through the public installed archive, not only internal imports. Synthetic conformance is not proof of live availability, price or entitlement.
98
+
99
+ A custom adapter is trusted host code, and the harness is not a sandbox. Test transports must use the injected synthetic fetch; do not embed credentials or make accidental live calls. Default receipts/reports exclude unrestricted provider payloads. Store any additional diagnostics under host policy.
100
+
101
+ Adopt the exact implementation and route compatibility version explicitly with the matching configuration. Retain the prior package/configuration/adapter set for rollback and create new runs after adoption. Never relabel a historical adapter or manifest. See [migration](MIGRATION.md) and [native extension precedence](API.md#native-extensions-and-precedence).
@@ -0,0 +1,50 @@
1
+ # Custom adapter qualification
2
+
3
+ `runAdapterConformance` is an exported, test-framework-independent harness. It runs each supplied synthetic fixture through Responses and Chat Completions coding styles in both final and streaming modes. It uses the actual runtime, configuration validation, registration, receipt generation and result projections. It does not select a different outbound provider API for a different coding style.
4
+
5
+ Provide fresh adapter/transport state from each case's `setup(context)` callback:
6
+
7
+ ```ts
8
+ import { runAdapterConformance, type AdapterConformanceCase, type ConfigurationSnapshot,
9
+ type ProviderAdapter, type FetchImpl } from '@techis/ai-runtime';
10
+
11
+ export async function qualifyText(syntheticSnapshot: ConfigurationSnapshot, createCompanyAdapter: () => ProviderAdapter,
12
+ recordedTransport: (mode: 'final' | 'stream') => FetchImpl) {
13
+ const cases: AdapterConformanceCase[] = [{
14
+ id: 'plain-text', category: 'text',
15
+ setup: ({ mode }) => ({
16
+ snapshot: syntheticSnapshot, personaId: 'writer',
17
+ registration: { adapters: [createCompanyAdapter()] },
18
+ requests: {
19
+ responses: { input: 'Synthetic question' },
20
+ chat: { messages: [{ role: 'user', content: 'Synthetic question' }] }
21
+ },
22
+ fetchImpl: recordedTransport(mode),
23
+ expected: { outcome: 'completed', text: 'Synthetic answer' }
24
+ })
25
+ }];
26
+ return runAdapterConformance(cases);
27
+ }
28
+ ```
29
+
30
+ `syntheticSnapshot`, `createCompanyAdapter` and `recordedTransport` are explicit host fixture inputs. This function compiles independently, but running it requires those fixtures and a `writer` persona in the snapshot. Keep provider credentials out of fixtures; the harness supplies a fixed synthetic credential and has no default network fetch. Custom adapter code remains trusted application code: the harness is not a process sandbox, so transport implementations must use the injected fetch. See [adapter authoring](ADAPTER-AUTHORING.md) for the full contract and registration lifecycle.
31
+
32
+ For an explicit replacement, use `registration: { adapterRegistration: { replace: [{ adapterId: 'openai-responses', adapter, compatibleAdapterVersion: '2.0.0' }] } }`. For a new route, use `add`; legacy `adapters` remains full-set injection. Fixture catalog route IDs, providers and minimum versions must agree with that registration. Reports distinguish route compatibility from the actual implementation version. Unknown extension contract versions fail registration with a clear diagnostic.
33
+
34
+ The required categories are `text`, `tools`, `native`, `usage`, `capabilities`, `refusal`, `incomplete`, `error` and `cancellation`: at least nine cases, producing 36 interface/mode cells. Expectations must assert the category's relevant data. Use `items` for complete canonical tool calls and raw arguments, `nativeBody` for exact native JSON, `usage` for all expected reported dimensions (including explicit zero), and `diagnostics` for effective feature handling. Error cases specify `errorCode`. Cancellation cases set `cancel: 'before-call'`, or `'after-first-event'` in their streaming setup and `'before-call'` in final setup.
35
+
36
+ The harness checks schema-valid, single terminal receipts, actual adapter identity, shared error outcomes, final-result repeatability, native data and usage. A per-cell timeout defaults to five seconds and is configurable up to 60 seconds. Reports omit prompts, response bodies, credentials and assertion payloads. A transport call without an injected fixture fails qualification.
37
+
38
+ `conforms` is true only when every supplied cell passes and every required category is present. `missingCategories` and failed cells remain explicit; a one-case example is never complete qualification. Add cases for your provider's native options, tool-result replay, parallel calls, unknown frames, malformed frames, disconnects, usage snapshots and model-specific limits. The harness does not prove live access, real-world pricing, provider feature support or all wire-protocol behavior; those need the corresponding recorded or live evidence.
39
+
40
+ Legacy execute-only adapters remain usable through their existing contract. This complete rich-adapter matrix intentionally requires streaming and tool/native support; a legacy-only adapter cannot receive a full rich conformance result by omitting those categories.
41
+
42
+ Contract-2 adapters can declare `requestCapabilities` for restrictions within a supported feature: allowed tool choices, strict function schema support, native versus local JSON-schema enforcement, developer-role support and common search option/domain limits. Registration validates and snapshots this data. Primary mismatches fail before credentials; backup mismatches keep supported behavior with warnings. Local schema validation and developer-to-system mapping are disclosed. This metadata does not implement a protocol mapping or establish conformance by itself; include matching wire and fallback tests for each declared limit.
43
+
44
+ Additional declared limits cover allowed image details, top-level text system instructions and object-valued function arguments. `strictFunctionSchemas: 'validated-auto'` identifies a global validated-tool mode that cannot also force a function choice. Tests must distinguish supported automatic strict mode from that unsupported combination and verify that backup text-context conversion preserves malformed argument data without repairing or executing it.
45
+
46
+ Optional `resolveRequestCapabilities(model, reasoning)` supplies per-model/control overrides to the static declaration; `sampling: false` identifies fixed sampling. It must be pure and return only valid capability data. The runtime supplies cloned inputs and validates/snapshots the result before credentials; registry snapshots bind the method to its original instance. If fallback reasoning changes, capabilities are checked again before dispatch. Test both initial planning and that second check, including primary rejection and backup warnings. This hook does not authorize network calls, tool execution or configuration mutation.
47
+
48
+ `jsonObject: 'prompt'` discloses a provider's prompt-based JSON-object request with local validation. It is independent of `jsonSchema`, so an adapter can support native JSON schema while lacking a native unrestricted JSON-object mode. Include both wire-format and caller-visible diagnostic tests; never silently manufacture a schema that cannot represent arbitrary JSON objects.
49
+
50
+ Use `refusal-delta` for incremental refusal content, with the same optional item/output/content positions as `text-delta`. The runtime projects it as Responses refusal events or Chat `delta.refusal` and retains it in partial error evidence. A refusal is not answer text. Test both an ordinary refused terminal result and a failure after partial refusal delivery.
@@ -0,0 +1,115 @@
1
+ # Anthropic Messages in the 0.4 development runtime
2
+
3
+ Adapter `anthropic-messages` version `2.0.0` implements contract 2 and uses `POST /v1/messages` with the reviewed
4
+ `anthropic-version: 2026-10-21` header through either client coding style. The existing factory and route ID remain available.
5
+ Adopting this unpublished runtime is an explicit version change; it does not upgrade an installed consumer or rewrite model/catalog pins.
6
+
7
+ ## Requests and client-owned continuation
8
+
9
+ Responses-style input and Chat-style messages map to ordered Messages content. Initial system/developer instructions use the top-level system
10
+ field. Reviewed models supporting inline system messages retain later instructions in place, with the provider's placement checks. Other models
11
+ use top-level text instructions with a diagnostic. URL and JPEG/PNG/GIF/WebP base64 images are supported; shared image-detail controls are not.
12
+ API-version-invalid user text citations and direct assistant document blocks reject. Native nested tool/document blocks remain available.
13
+
14
+ Client functions use `input_schema`, optional `strict`, and native automatic/none/required/named tool choices where supported by the selected
15
+ model and reasoning control. Parallel selection uses `disable_parallel_tool_use`. Returned calls are data for the client to execute. The runtime
16
+ does not invoke tools, repair arguments, retry side effects, run a tool loop, or resume a paused provider turn on its own.
17
+
18
+ Keep the returned continuation envelope or append the complete Responses output when sending results. Either method preserves thinking,
19
+ signatures, redacted content, citations and interleaved calls in their original order. Supply every pending call result; null, false, zero and empty
20
+ strings remain distinct. A partial argument string from interrupted or malformed SSE remains visible for diagnostics. It cannot be replayed as an
21
+ Anthropic object argument without an explicit client decision. Messages has no common storage control or reusable server response ID.
22
+
23
+ ```ts
24
+ import type { AIRun, ResponsesCreateRequest, ResponsesInputItem, ResponsesResult } from '@techis/ai-runtime';
25
+
26
+ export async function lookup(run: AIRun, executeAllowed: (result: ResponsesResult) => Promise<ResponsesInputItem[]>) {
27
+ const tools: ResponsesCreateRequest['tools'] = [{ type: 'function', name: 'lookup', parameters: {
28
+ type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false
29
+ }, strict: true }];
30
+ const first = await run.responses.create({ input: 'Look up this item', tools }, { operationId: 'lookup.request' });
31
+ if (first.outcome !== 'requires_action') return first;
32
+ if (!first.continuation) throw new Error('Continuation is required for this example');
33
+ // The host callback validates/authorizes calls, executes its own functions and supplies every pending result.
34
+ const toolResults = await executeAllowed(first);
35
+ return run.responses.create({ continuation: first.continuation, input: toolResults, tools }, { operationId: 'lookup.results' });
36
+ }
37
+ ```
38
+
39
+ `pause_turn`, `max_tokens` and `model_context_window_exceeded` are explicit incomplete outcomes. A paused hosted-tool turn can be resumed by the
40
+ client using its continuation and empty input. `tool_use` with client calls requires action. Refusal is distinct from an empty completed answer.
41
+ Legacy `generate` retains its final-answer-only contract and rejects tool/incomplete outcomes with preserved rich/native error evidence.
42
+
43
+ ## Schema, reasoning and native options
44
+
45
+ JSON schema uses native `output_config.format`, with the schema preserved and final output also validated locally. Use the provider's supported
46
+ schema subset, including `additionalProperties: false` for objects. Generic `json_object` uses a prompt instruction plus local validation and emits
47
+ a diagnostic; the adapter does not invent a native unrestricted JSON mode.
48
+
49
+ Reasoning defaults remain provider defaults. Supported controls map to adaptive/manual thinking, disabled thinking and `output_config.effort`.
50
+ Reviewed model limits govern manual budgets, disabled thinking and forced tool selection. Manual budgets must be at least 1,024 and less than
51
+ the effective output cap. The current shared control does not express `between_tools` or the interleaved-budget exception. Unsupported primary
52
+ controls reject; backups warn and omit unsupported controls. Sampling parameters are absent in this API version, including default values.
53
+
54
+ Selected `providerOptions.anthropic` leaves are preserved unless they collide with runtime-owned paths. Native-only siblings such as
55
+ `thinking.display`, metadata, cache control and output-config extensions can be supplied. A collision fails before credentials. The `betas` array
56
+ selects explicit, header-safe beta identifiers; arbitrary headers, credentials, endpoint changes and API-version overrides are not request options.
57
+
58
+ ## Hosted search and results
59
+
60
+ A common web-search declaration uses native `web_search_20260318` with direct calls by default. Common allowed-domain filters and approximate
61
+ location map to native fields. Context-size and offline-only controls are unsupported. The `providerOptions.anthropic.web_search` fragment carries
62
+ native settings such as `max_uses`, a reviewed tool version or response inclusion; common values retain precedence. Hosted search and client
63
+ functions can coexist. Server-tool blocks, results and tool-error data stay native and are never exposed as client-executed functions.
64
+
65
+ `native.body` retains the parsed or assembled Message, including unknown fields. SSE assembly preserves raw events, ordered blocks, citations,
66
+ thinking/signature deltas and cumulative usage. It enforces shared frame/aggregate bounds, deadlines and cancellation. Unknown events are retained
67
+ without guessing their meaning. Observed output and usage survive timeouts, disconnections, cancellation and provider stream errors.
68
+
69
+ Input totals include uncached, cache-read and cache-write counts only when all are reported. Reasoning is a reported subset of output, not an
70
+ additional charge. Search/fetch counts use provider usage rather than counting result blocks. Missing usage remains unknown. Hosted tools,
71
+ unqualified cache tiers, fast/priority modes and regional billing keep cost unknown without corresponding qualified rates. Default receipts and
72
+ serialized errors omit prompts, tool content, native bodies, reasoning and credentials; safe request IDs remain available.
73
+
74
+ ## Public streaming
75
+
76
+ Both client coding styles accept `stream: true` and return a lazy `GenerationStream` with incremental events, cancellation and `finalResult()`.
77
+ Final and public streaming calls share the same Messages assembler, credential rules, beta headers, endpoint checks and redirect policy. Final
78
+ calls also retain their existing JSON-response fallback. The public stream uses the provider's SSE protocol.
79
+
80
+ Text and thinking arrive incrementally; signatures and redacted thinking remain native replay data. Indexed content blocks map to ordered
81
+ canonical messages and client function calls. Function indexes count client functions independently of native block positions. JSON fragments
82
+ append exactly; completed object JSON becomes an object in the final result, while malformed, incomplete and non-object JSON stays a raw string
83
+ for client validation. Argument-done events retain the received fragment spelling. Server-tool inputs/results never become client functions.
84
+
85
+ `native.body` is the assembled Message, and `native.events` retains original parsed frames with event names, IDs and SSE retry metadata.
86
+ Unknown blocks/deltas, citations, provider fallback markers and serving-model metadata remain accessible. There is no client tool loop,
87
+ automatic paused-turn resume, automatic stream recovery or runtime retry after output has reached the caller. An unexposed internal drain
88
+ retains the configured retry policy. Pings before message start do not expose output.
89
+
90
+ `message_stop` completes a stream only after closed content blocks and a supported stop reason. Inconsistent identities, indexes, lifecycle
91
+ events, known fields, invalid UTF-8 and byte-limit violations reject with partial evidence. Cumulative usage merges without adding repeated
92
+ totals. Abort, deadlines, disconnects, early iterator return and provider errors preserve available text, arguments, usage and native data.
93
+ Authentication/permission errors stop; documented rate/overload/API errors retain their corresponding retry classification before exposure.
94
+
95
+ A streaming classifier can report refusal after text was already delivered. The rich result keeps that text and exposes `stop_details.explanation`
96
+ as separate refusal content, or a generic refusal status message if no explanation was supplied. Native details remain intact, and the client
97
+ controls subsequent conversation handling. `pause_turn`, output/context limits and truncated tool arguments remain incomplete outcomes.
98
+
99
+ ## Qualification boundary
100
+
101
+ The source has synthetic final-call and public-stream coverage for both client styles, tool replay, pause/resume, native preservation,
102
+ failure handling, usage and backup degradation. Gated-network tests prove incremental delivery before terminal bytes arrive.
103
+ Live access, account entitlement, packaged release, Windows x64 Studio installation and consumer adoption require their own evidence.
104
+
105
+ Reviewed references: [Messages](https://platform.claude.com/docs/en/api/messages/create),
106
+ [version migration](https://platform.claude.com/docs/en/api/migration-2026-10-21),
107
+ [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking),
108
+ [tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use),
109
+ [system-message placement](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages),
110
+ [structured output](https://platform.claude.com/docs/en/build-with-claude/structured-outputs),
111
+ [web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool),
112
+ [stop reasons](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons),
113
+ [SSE](https://platform.claude.com/docs/en/build-with-claude/streaming),
114
+ [fine-grained tool streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming),
115
+ [streaming refusals](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals).
package/API.md ADDED
@@ -0,0 +1,275 @@
1
+ # Runtime API guide
2
+
3
+ ## Embedded Models adoption — 0.4.0-rc.4
4
+
5
+ `startRun` accepts exactly one of `routeId` or `routeName`. Persist stable IDs in application assignments; ID selection resolves captured
6
+ membership directly and survives rename/name reuse. Use `createFileRouteSetResolver` for frozen JSON or `createHttpRouteSetJsonResolver`
7
+ for bounded anonymous JSON reads. Its optional credential callback is separate from provider credentials and public reads need no sign-in.
8
+
9
+ `ApplicationRouteAdoptionRepository` and `createFileRouteAdoptionRepository` provide immutable application generations, preview/import,
10
+ qualification, explicit CAS activation, history and rollback. Import does not enable. `resolveRouteImportAssignments` validates an accepted
11
+ proposal against the actual authoring result and returns its authoritative stable IDs. `inspectRouteReadiness` performs local checks without
12
+ inference. Invocation `featurePolicy` preserves required features during backup planning; callers omitting it retain existing behavior.
13
+
14
+ `createModelRun` accepts `applicationId`, exact `catalog`, `catalogId`, `settings`, `systemInstructions`, host connections and credential resolver.
15
+ It exposes Generate/Responses/Chat final and streaming through the common engine, with one model/attempt and no authoring records or backup.
16
+ Its `DirectModelExecutionReceipt` has exact catalog/settings/model-configuration digests and no Route/set/persona/binding identity.
17
+ Errors expose `directModelExecutionReceipt`; mixed usage stores accept both receipt families without rewriting historical files.
18
+ The factory rejects non-string application IDs and duplicate catalog model/price IDs before host callbacks or provider dispatch.
19
+
20
+ Complete repository recipes and the exact protocol are in `docs/greenfield-adoption.md`, `docs/existing-application-adoption.md`,
21
+ `docs/embedded-models-adoption-api.md`, `examples/consumer/src/adopted-route-host.ts` and `examples/consumer/src/direct-model.ts`.
22
+ Candidate archives are qualified on Windows x64 with Node 24.20.0; no publication, deployment or installed-application change is implied.
23
+
24
+ ## Request routes and route sets
25
+
26
+ New integrations use `RequestRoute`, `routeId`, `routeName`, `RouteSet` and `routeSetId`. A request route contains a primary model,
27
+ its settings and optional ordered backups; a route set collects named routes for loading together. Use `createAIClient` with
28
+ `routeSetSource(createHttpRouteSetResolver(...))` and `startRun({ routeName, systemInstructions })`, or `createRequestRouteRun` for
29
+ an independently held route. The host supplies provider credentials and endpoints. Workspace/persona registration is unnecessary.
30
+
31
+ The source repository includes `docs/request-routes.md` and `docs/route-terminology-migration-2026-10-30.md`; the example below uses
32
+ only the installed public packages. See also [package migration notes](MIGRATION.md#request-route-and-route-set-terminology).
33
+ Old profile/model-configuration SDK names remain deprecated compatibility paths; their historical examples below retain those signatures.
34
+ Canonical route-set snapshots use schema 5; route execution receipts use schema 6. Existing identifiers, history and old JSON remain readable
35
+ through the supplied codecs. Packages and remote services have not been published or deployed by this local change.
36
+
37
+ ```ts
38
+ import { createAIClient, createHttpRouteSetResolver, routeSetSource, type RouteCredentialResolver } from "@techis/ai-runtime";
39
+ import type { RouteSetRequest, NativeConnection } from "@techis/ai-contracts";
40
+
41
+ export async function summarize(host: {
42
+ url: string; request: RouteSetRequest; applicationId: string; authorizationIdentity: string; token(): Promise<string>;
43
+ providerConnections: Record<string, NativeConnection>; credentialResolver: RouteCredentialResolver;
44
+ }, routeName: string, systemInstructions: string, input: string) {
45
+ const resolver = createHttpRouteSetResolver(host);
46
+ const client = createAIClient({ applicationId: host.applicationId, configurationSource: routeSetSource(resolver),
47
+ providerConnections: host.providerConnections, credentialResolver: host.credentialResolver });
48
+ const workflow = await client.captureWorkflow();
49
+ const run = await workflow.startRun({ routeName, systemInstructions });
50
+ return run.responses.create({ input }, { operationId: "summary" });
51
+ }
52
+ ```
53
+
54
+ The request is `{ routeSetId, selection: { kind: "active" } }` for a standalone set. Retained scoped sets also carry their original
55
+ applicationId. The host's execution applicationId is its actual attribution identity, not a registration requirement for the set.
56
+ Instructions and provider access remain host-owned and outside route-set content. `routeSetDownloadUrl` produces the authenticated
57
+ management URL; credentials belong in headers. `createRequestRouteRun` executes an independently held RequestRoute/catalog directly.
58
+ `readRequestRouteExport` reads new single-route JSON and older verified Studio single-route bundles. No workspace or persona is created.
59
+
60
+ ## Independent catalog discovery
61
+
62
+ `createPublishedCatalogDeliveryClient({ store, source? })` supplies the installed baseline, reader version and release-provisioned catalog
63
+ source. `store` is a host-owned atomic `CatalogPublicationInboxStore`, separate from a legacy full-delivery `CatalogInboxStore`.
64
+ Call `check("bounded-caller-id")` to retain the current compatible catalog publication, or `read()` to use its retained snapshots offline.
65
+ The normal response contains the catalog and immutable URI/hash references to evidence/history. It does not download either artifact or
66
+ past catalogs. This API cannot select a profile or change application configuration.
67
+
68
+ The public release carries a stable read URL and a shared key scoped only to the catalog GET function. End users need no operator account.
69
+ `createPublishedCatalogDeliverySource({ configuration?, fetchImpl? })` allows explicit trusted-host/test configuration; renderer input must
70
+ not choose the endpoint or key. HTTPS origin/path, response limits, source/baseline identity, freshness, known-parent and runtime checks apply.
71
+ A source/key failure leaves the retained inbox/active configuration unchanged; the bundled catalog also remains available.
72
+
73
+ `reader.evidence(publication)` explicitly fetches and verifies the original full reviewed delivery; `reader.history(publication)` fetches
74
+ its small history index. `reader.catalog(history.revisions[n])` explicitly fetches an exact historical catalog and checks its referenced hash.
75
+ No optional download changes the discovery inbox or adopts a catalog/profile. Keys stay on the configured endpoint; redirects are rejected.
76
+
77
+ The Function verifies full accepted evidence and lineage before publication. Normal readers trust that authenticated HTTPS publisher and
78
+ check the lightweight snapshot's integrity/compatibility; they do not claim to independently recheck missing evidence or unseen ancestry.
79
+ Full-chain verification remains available through the existing `createCatalogDeliveryClient` when an explicit audit retrieves its artifacts.
80
+ Older downloaded catalog snapshots survive an SDK baseline upgrade. Keep previous combined proof caches intact when using the new inbox namespace.
81
+ `inbox.head` is the current reader's newest compatible retained publication at/above its installed baseline; `releases` also preserves archived
82
+ snapshots for other supported readers. A read computes that view without changing the store. If no eligible snapshot exists, `head` is null:
83
+ keep the bundled or explicitly selected catalog. Do not choose an execution catalog by taking the greatest sequence across `releases`.
84
+ The SDK's bundled catalog stays pinned to its release; normal AI-client construction never invokes this optional discovery API.
85
+
86
+ The first release of this reader code needs deployment/key provisioning and an approved code release. Later compatible catalog data is
87
+ published to the Function independently. See the repository's `docs/independent-catalog-updates.md` for rollout and operating steps.
88
+
89
+ This guide describes the unpublished `0.4.0-rc.4` runtime/contracts pair and its exported types. Examples are TypeScript functions with explicit host inputs; calling provider examples requires a configured host and may incur charges. They are compile-checked against local public archives. Synthetic qualification does not establish live account/model access.
90
+
91
+ ## Configuration and pins
92
+
93
+ `createAIClient` accepts `CreateAIClientOptions`: `applicationId`, a configuration source, optional `environmentId` (default `local`), host credential resolver, fetch, caps, receipt sink and adapter registration. Sources include inline snapshots and verified exported bundles; a catalog alone lacks bindings, profiles and instructions. An omitted legacy credential resolver uses the environment resolver. Supply credentials only in trusted host code.
94
+
95
+ `captureWorkflow()` captures the manifest; `startRun({ personaId })` resolves a persona and pins its profile, catalog/model, prices, instructions, connections and adapter requirements. Starting a run directly also pins its resolution. Configuration refresh affects newly captured work. Package updates and catalog discovery never silently change a captured run's model selection.
96
+
97
+ ```ts
98
+ import { createAIClient, bundleSource, type CredentialResolver } from '@techis/ai-runtime';
99
+
100
+ export async function openRun(applicationId: string, environmentId: string, directory: string,
101
+ credentialResolver: CredentialResolver, personaId: string) {
102
+ const client = createAIClient({ applicationId, environmentId, configurationSource: bundleSource({ directory }), credentialResolver });
103
+ const workflow = await client.captureWorkflow();
104
+ return workflow.startRun({ personaId });
105
+ }
106
+ ```
107
+
108
+ Named configuration uses `createNamedAIClient` (or the `createAIClient` overload), `namedConfigurationSource(resolver)` and a required native credential resolver. `createNamedConfigurationResolver` accepts a host loader and stable source/authorization cache identities; its default maximum age is zero. It validates the exact native snapshot and does not reuse stale state after authorization or validation failure. Native runs start with `bindingId`, expose native configuration/workspace/revision identities, and return native receipts. Do not supply legacy `environmentId`, `scopedV2`, `cachePolicy` or `snapshotCache` options to this overload. Protected sanitized/forbidden payload policies require the host's `authorizePayload` implementation; the runtime does not invent a sanitizer.
109
+
110
+ ```ts
111
+ import { createNamedAIClient, type CreateNamedAIClientOptions } from '@techis/ai-runtime';
112
+
113
+ export async function openNamedRun(options: CreateNamedAIClientOptions, bindingId: string) {
114
+ const workflow = await createNamedAIClient(options).captureWorkflow();
115
+ return workflow.startRun({ bindingId });
116
+ }
117
+ ```
118
+
119
+ ## Two client signatures
120
+
121
+ Both interfaces are on a run. OpenAI outbound calls use Responses; Gemini uses Interactions v1, Anthropic uses Messages, and Z.AI/Moonshot use their native Chat protocols. Choosing a client signature never selects the provider protocol. This is the documented compatibility subset, not a full provider SDK replacement.
122
+
123
+ ```ts
124
+ import { createCompatibleClient, type AIRun } from '@techis/ai-runtime';
125
+
126
+ export async function compareStyles(run: AIRun, input: string, signal: AbortSignal) {
127
+ const responses = await run.responses.create({ input }, { operationId: 'example.responses', signal });
128
+ const chat = await run.chat.completions.create({ messages: [{ role: 'user', content: input }] },
129
+ { operationId: 'example.chat', signal });
130
+ const bound = createCompatibleClient(run, { operationId: 'example.bound', signal });
131
+ return { responses, chat, bound };
132
+ }
133
+ ```
134
+
135
+ The example makes two separate calls. `GenerationCallOptions` carries `operationId`, optional `requestId`, `signal`, `execution`, `caps` and `effortByModel`. Use safe logical identifiers, not prompts or secrets. Bound-client defaults are shallowly overridden by per-call options. Requests/options are copied for execution; do not rely on later caller mutations.
136
+
137
+ `stream: true` returns `GenerationStream` synchronously and starts work lazily; `stream: false` or omission returns a result promise. A dynamic boolean produces the union. `model`, if supplied, asserts the configured primary pin; it does not override routing.
138
+
139
+ | Purpose | Responses request | Chat Completions request |
140
+ | --- | --- | --- |
141
+ | Conversation | `input`: string or ordered input items; optional `instructions` | `messages`: ordered system/developer/user/assistant/tool messages |
142
+ | Images | `input_image` with URL/base64 data URL and detail | `image_url` content blocks with detail |
143
+ | Client functions | `tools: [{ type: 'function', name, parameters, description?, strict? }]` | `tools: [{ type: 'function', function: { name, parameters, description?, strict? } }]` |
144
+ | Selection | `tool_choice`: auto/none/required or function name; `parallel_tool_calls` | Same modes, named choice nested in `function`; `parallel_tool_calls` |
145
+ | Function results | `function_call_output` with `call_id` and JSON `output` | `role: 'tool'`, `tool_call_id` and JSON `content` |
146
+ | Hosted search | `tools: [{ type: 'web_search', ...options }]` | `web_search_options` |
147
+ | Output format | `text.format`: text/json_object/json_schema | `response_format`: text/json_object or nested `json_schema` |
148
+ | Output cap | `max_output_tokens` | `max_completion_tokens`; `max_tokens` alias may coexist only with the same value |
149
+ | Reasoning | `reasoning.effort` | `reasoning_effort` |
150
+ | Common controls | `temperature`, `top_p`, `store`, `providerOptions`, `continuation`, `stream` | Same; only `n: 1`; `stream_options.include_usage` controls projected usage |
151
+ | Stored continuation | `previous_response_id` or bound `continuation` | Bound `continuation` |
152
+
153
+ Unknown root fields and malformed/shared conflicting values reject. The adapter/model can restrict otherwise mapped fields: for example, image detail, sampling, strict schemas, forced function choice, storage and search options. Unsupported primary requests reject before credential resolution. Unsupported backup features are omitted or represented as text context with warnings while supported behavior continues. Unknown capability metadata produces an explicit diagnostic; it is not proof of support or automatic rejection. Inspect `diagnostics` and receipt warnings.
154
+
155
+ Output limits intersect context/model/profile/client/call bounds; explicit requests may move a default up or down within those bounds. Reasoning defaults, explicit effort, token budget and disabled thinking are distinct. Provider guides below enumerate the native/model restrictions and local versus native schema enforcement.
156
+
157
+ ## Results and native data
158
+
159
+ Responses results provide `output`, `output_text`, response status and usage. Chat results provide one choice with message content, tool calls, refusal and finish reason. Both additionally expose `outcome`, ordered canonical `items`, `native`, `continuation`, `diagnostics`, `runtime_usage`, optional incomplete/error details and `executionReceipt`.
160
+
161
+ | Canonical outcome | Client responsibility |
162
+ | --- | --- |
163
+ | `completed` | Consume the final output and examine degradation warnings. |
164
+ | `requires_action` | Validate and execute allowed application functions, then explicitly send results. |
165
+ | `refused` | Handle refusal separately from answer text. |
166
+ | `incomplete` | Inspect received data/reason; decide explicitly whether and how to continue. |
167
+ | `failed` | Handle the canonical failure and preserved evidence; transport/provider failures can reject rather than return. |
168
+
169
+ `native` includes provider, actual adapter identity/version, original or assembled native body, request ID when supplied, and streaming events when available. Canonical items retain ordered native blocks, call IDs, arguments, citations and replay metadata. Text-only/choice projections cannot represent every native item; inspect `items`/`native` when fidelity matters. Malformed argument strings remain data, not repaired executable arguments. IDs for responses, output items, tool calls and HTTP requests are distinct.
170
+
171
+ Native bodies, event payloads, continuation history and explicit error evidence can contain sensitive data. They are caller-accessible, not automatically copied into default receipts or error JSON. Apply host storage/logging policy before persisting them.
172
+
173
+ ## Client-owned functions and continuation
174
+
175
+ Declare functions; receive calls; have application code validate names/arguments, authorize actions and execute them. The runtime never runs functions, retries their side effects or owns the workflow. Provider-hosted search stays inside the adapter and is not a client function.
176
+
177
+ ```ts
178
+ import type { AIRun, FunctionCall, JsonValue, ResponsesCreateRequest, ResponsesInputItem } from '@techis/ai-runtime';
179
+
180
+ export async function lookupOnce(run: AIRun, executeAllowed: (call: FunctionCall) => Promise<JsonValue>) {
181
+ const tools: ResponsesCreateRequest['tools'] = [{ type: 'function', name: 'lookup', parameters: {
182
+ type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false
183
+ } }];
184
+ const first = await run.responses.create({ input: 'Look up item A', tools }, { operationId: 'lookup.request' });
185
+ if (first.outcome !== 'requires_action') return first;
186
+ if (!first.continuation) throw new Error('Continuation is required for this example');
187
+ const results: ResponsesInputItem[] = [];
188
+ for (const item of first.items) {
189
+ if (item.type === 'function_call') results.push({ type: 'function_call_output', call_id: item.callId,
190
+ output: await executeAllowed(item) });
191
+ }
192
+ return run.responses.create({ continuation: first.continuation, input: results, tools }, { operationId: 'lookup.results' });
193
+ }
194
+ ```
195
+
196
+ `executeAllowed` is a host callback responsible for validation/authorization; this example does one explicit continuation and does not promise the next result is final. Preserve every pending call ID, supply each result exactly once, and complete parallel result groups before a new user turn. Null, false, zero and empty results are valid JSON values. Duplicate/missing/orphaned results reject.
197
+
198
+ Pass the returned continuation envelope and only the new suffix. Its portable history is a prefix; supplying that history again duplicates context. A reusable server response ID is valid only for the same provider/model/actual adapter/version/configuration revision. `previous_response_id` cannot conflict with the envelope. Bare IDs have no portable history. A changed target can continue only with sufficient portable history; incompatible opaque native material is omitted with diagnostics, and a native-only continuation cannot be invented. `store: false` prevents response-ID reuse. Stateless providers preserve replay material; no provider polling or automatic paused-turn resume is performed.
199
+
200
+ ## Streaming
201
+
202
+ ```ts
203
+ import type { AIRun } from '@techis/ai-runtime';
204
+
205
+ export async function streamAnswer(run: AIRun, input: string, signal: AbortSignal, render: (text: string) => void) {
206
+ const stream = run.chat.completions.create({ messages: [{ role: 'user', content: input }], stream: true,
207
+ stream_options: { include_usage: true } }, { operationId: 'answer.stream', signal });
208
+ for await (const event of stream) {
209
+ if ('type' in event) continue; // runtime.native, runtime.warning or runtime.error: handle under host policy.
210
+ const text = event.choices[0]?.delta.content;
211
+ if (text) render(text);
212
+ }
213
+ return stream.finalResult();
214
+ }
215
+ ```
216
+
217
+ Responses events have `type`, sequence and attempt metadata; text/refusal/reasoning/function deltas and item/content completion precede terminal completion. Chat uses incremental chunks, interleaved indexed function arguments and optional projected usage; `RuntimeStreamExtension` events are a separate union branch. Preserve native events if required by the application. A refusal delta is not answer text.
218
+
219
+ Streams are single-consumer; concurrent `next()` calls reject. `finalResult()` can drain a stream directly without exposing intermediate events, or return its settled result after iteration. Do not await it inside an unfinished iteration. Repeated calls reuse one result and never issue inference again. `abort()` or early iterator return cancels uncommitted work; cancellation after terminal commitment cannot rewrite the outcome. Iterator failure and `finalResult()` share the canonical error and terminal receipt.
220
+
221
+ Fallback/retry is allowed only while policy permits and no provider-derived event has reached the consumer. Once exposed, partial text, native data, reasoning or tool data cannot be replaced by another provider within that invocation. An internal `finalResult()` drain has no intermediate exposure. EOF without a terminal result, malformed frames and contradictory IDs/indexes/content fail explicitly. Native SSE implementations bound individual frames to 1 MiB and aggregate input to 32 MiB; they do not silently reconnect. See each provider guide for retained native event/body semantics.
222
+
223
+ ## Native extensions and precedence
224
+
225
+ `providerOptions` is a JSON object per provider namespace. Profile-slot options form the base; call options recursively merge objects and override individual leaves. Arrays, scalars and null replace their prior values. Absent leaves inherit; false, zero and empty values remain explicit. Only the selected provider's namespace is forwarded, but every supplied namespace is validated.
226
+
227
+ ```ts
228
+ import type { AIRun } from '@techis/ai-runtime';
229
+
230
+ export function nativeOptions(run: AIRun) {
231
+ return run.responses.create({ input: 'Summarize briefly', reasoning: { effort: 'low' },
232
+ providerOptions: { openai: { text: { verbosity: 'low' }, reasoning: { summary: 'auto' }, metadata: { purpose: 'summary' } } }
233
+ }, { operationId: 'summary.native-options' });
234
+ }
235
+ ```
236
+
237
+ Runtime-owned fields reject collisions; they are not silently overridden. These include model, instructions/history, tools/selection, streaming, storage/continuation, shared sampling/output limits/formats/reasoning, endpoint/transport, credentials/headers, timing/caps and configuration identity. Nested owned paths such as `reasoning.effort`, `text.format`, `output_config.format`, thinking budgets and generation-config limits are also protected; unrelated siblings remain available. Prototype/reserved JSON keys reject. Provider-specific options do not grant credential, endpoint, workflow or tool-execution authority. The provider may reject an otherwise valid native extension. Native billing selectors can make estimated cost unknown.
238
+
239
+ ## Errors, receipts and timing
240
+
241
+ Catch `AISubsystemError`. Its `code`, `retryable` and sanitized `details` describe the failure; legacy `executionReceipt` or native `nativeExecutionReceipt` provides terminal evidence when an invocation has begun. Explicit non-enumerable `native`, `partialResult` and `httpResponse` properties preserve received evidence without adding it to default JSON. Configuration/argument failures before an invocation exists may have no receipt.
242
+
243
+ ```ts
244
+ import { AISubsystemError, type AIRun } from '@techis/ai-runtime';
245
+
246
+ export async function callWithEvidence(run: AIRun, signal: AbortSignal) {
247
+ try {
248
+ return await run.responses.create({ input: 'Explain the result' }, { operationId: 'explain', signal,
249
+ execution: { timingPolicy: 'caller', deadlineMs: 300_000, attemptTimeoutMs: 60_000 } });
250
+ } catch (error) {
251
+ if (error instanceof AISubsystemError) console.error(error.code, error.executionReceipt?.receiptId);
252
+ throw error;
253
+ }
254
+ }
255
+ ```
256
+
257
+ Error codes cover configuration invalid/unavailable/revoked, unsupported capability/adapter, credential unavailable/invalid, model unavailable, provider rate limit/timeout/server error/invalid request, network error, cancellation, invalid/truncated output, exhausted attempts, budget and input limits. HTTP status remains authoritative over an error body. `retryable` alone does not authorize retry: policy, attempts, deadlines, caps, continuation and output exposure also govern dispatch. Integrity, authorization and cancellation stop; a missing credential can skip an eligible route, whereas an invalid credential is a distinct stop condition.
258
+
259
+ `timingPolicy: 'caller'` makes each call's deadline cover queues, credentials, attempts, backoff and fallback. Omit `attemptTimeoutMs` to use the remaining total budget; omit both timers to rely on cancellation and transport/provider limits. Omitting `timingPolicy` retains legacy profile/default timing. Cancellation prevents later retries and discards late results; custom transports must honor `AbortSignal` to stop their own activity.
260
+
261
+ Each invoked operation emits one terminal receipt to `onExecutionReceipt`, including failed/cancelled/degraded attempts. Sink failure adds a warning and does not repeat inference. Receipts record actual adapter identity, route compatibility, protocol, features and pinned configuration without unrestricted provider bodies. Usage snapshots merge by dimension with latest explicit values, including zero; absence stays unknown. Receipt terminal usage is the last attempt's usage; sum dispatched attempts for call totals. Cache/reasoning subsets are not additive to total input/output twice. Pricing uncertainties, native billing scope and hosted-tool charges can keep cost unknown; preflight estimates are labeled estimates, not billing guarantees.
262
+
263
+ Legacy `generate` remains final-only and rejects refusal, incomplete/failed output or required client-tool action with preserved evidence. Migrate to a rich interface when those outcomes must be handled as data.
264
+
265
+ ## Provider and extension reference
266
+
267
+ | Default route | Native protocol and limits |
268
+ | --- | --- |
269
+ | `openai-responses` | [OpenAI Responses](OPENAI-RESPONSES.md) |
270
+ | `zai-chat-completions` | [Z.AI Chat](ZAI-CHAT.md) |
271
+ | `gemini-generate-content` | [Gemini Interactions v1](GEMINI-INTERACTIONS.md); stable route and old factory alias retained |
272
+ | `moonshot-chat-completions` | [Moonshot Chat](MOONSHOT-CHAT.md) |
273
+ | `anthropic-messages` | [Anthropic Messages](ANTHROPIC-MESSAGES.md) |
274
+
275
+ All five implement contract 2 final and streaming mapping. See [adapter authoring](ADAPTER-AUTHORING.md) for explicit overrides, [conformance](ADAPTER-CONFORMANCE.md) for synthetic qualification and [migration](MIGRATION.md) for adoption/recovery. A mapping and passing synthetic tests do not establish live provider availability or every model's capabilities.