@sixb/azure-ai-foundry 0.1.1

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -0
  3. package/dist/accounting.d.ts +5 -0
  4. package/dist/accounting.d.ts.map +1 -0
  5. package/dist/catalog.d.ts +29 -0
  6. package/dist/catalog.d.ts.map +1 -0
  7. package/dist/chat-accounting.d.ts +4 -0
  8. package/dist/chat-accounting.d.ts.map +1 -0
  9. package/dist/chat-request.d.ts +18 -0
  10. package/dist/chat-request.d.ts.map +1 -0
  11. package/dist/diagnostics.d.ts +10 -0
  12. package/dist/diagnostics.d.ts.map +1 -0
  13. package/dist/discovery.d.ts +63 -0
  14. package/dist/discovery.d.ts.map +1 -0
  15. package/dist/index.d.ts +6 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +1898 -0
  18. package/dist/index.js.map +25 -0
  19. package/dist/messages-accounting.d.ts +5 -0
  20. package/dist/messages-accounting.d.ts.map +1 -0
  21. package/dist/messages-request.d.ts +11 -0
  22. package/dist/messages-request.d.ts.map +1 -0
  23. package/dist/messages-schema.d.ts +4 -0
  24. package/dist/messages-schema.d.ts.map +1 -0
  25. package/dist/provider.d.ts +64 -0
  26. package/dist/provider.d.ts.map +1 -0
  27. package/dist/publisher.d.ts +7 -0
  28. package/dist/publisher.d.ts.map +1 -0
  29. package/dist/request.d.ts +20 -0
  30. package/dist/request.d.ts.map +1 -0
  31. package/dist/resolution.d.ts +36 -0
  32. package/dist/resolution.d.ts.map +1 -0
  33. package/dist/structured-output.d.ts +4 -0
  34. package/dist/structured-output.d.ts.map +1 -0
  35. package/dist/transport.d.ts +30 -0
  36. package/dist/transport.d.ts.map +1 -0
  37. package/dist/tsconfig.json +5 -0
  38. package/dist/util.d.ts +6 -0
  39. package/dist/util.d.ts.map +1 -0
  40. package/package.json +54 -0
  41. package/src/accounting.ts +117 -0
  42. package/src/catalog.ts +328 -0
  43. package/src/chat-accounting.ts +134 -0
  44. package/src/chat-request.ts +161 -0
  45. package/src/diagnostics.ts +34 -0
  46. package/src/discovery.ts +385 -0
  47. package/src/index.ts +17 -0
  48. package/src/messages-accounting.ts +105 -0
  49. package/src/messages-request.ts +164 -0
  50. package/src/messages-schema.ts +101 -0
  51. package/src/provider.ts +416 -0
  52. package/src/publisher.ts +34 -0
  53. package/src/request.ts +266 -0
  54. package/src/resolution.ts +179 -0
  55. package/src/structured-output.ts +135 -0
  56. package/src/transport.ts +268 -0
  57. package/src/util.ts +16 -0
@@ -0,0 +1,385 @@
1
+ import {
2
+ type LanguageModelDefinition,
3
+ type LanguageModelDefinitionCatalog,
4
+ ModelCatalogUnavailableError,
5
+ ModelProviderError,
6
+ } from "@sixb/core/models"
7
+ import { RequestDiagnostics } from "./diagnostics"
8
+ import type { FoundryProtocol } from "./transport"
9
+ import { abortable, type FoundryTransport, requestId } from "./transport"
10
+ import { object, PREFIX, positiveInteger } from "./util"
11
+
12
+ export interface AzureAIFoundryDiscoveryOptions {
13
+ readonly ttlMs?: number
14
+ /** Deadline for credentials, all pages, and body reads together. Default: 5,000 ms. */
15
+ readonly timeoutMs?: number
16
+ readonly maxPages?: number
17
+ readonly maxDeployments?: number
18
+ /** Aggregate response bytes across all pages. Default: 4 MiB. */
19
+ readonly maxResponseBytes?: number
20
+ }
21
+
22
+ export interface AzureAIFoundryDeployment {
23
+ readonly name: string
24
+ readonly modelName: string
25
+ readonly modelVersion: string
26
+ readonly modelPublisher: string
27
+ readonly connectionName?: string
28
+ readonly capabilities: Readonly<Record<string, string>>
29
+ readonly sku: {
30
+ readonly name: string
31
+ readonly capacity?: number
32
+ readonly family?: string
33
+ readonly size?: string
34
+ readonly tier?: string
35
+ }
36
+ }
37
+
38
+ export interface AzureAIFoundryCatalog extends LanguageModelDefinitionCatalog {
39
+ get(
40
+ name: string,
41
+ options?: { readonly protocol?: FoundryProtocol }
42
+ ): Promise<LanguageModelDefinition | undefined>
43
+ list(options?: {
44
+ readonly protocol?: FoundryProtocol
45
+ }): Promise<readonly LanguageModelDefinition[]>
46
+ refresh(options?: {
47
+ readonly protocol?: FoundryProtocol
48
+ }): Promise<readonly LanguageModelDefinition[]>
49
+ /** All discovered ModelDeployment records, including non-Responses offerings. */
50
+ deployments(): Promise<readonly AzureAIFoundryDeployment[]>
51
+ }
52
+
53
+ interface Snapshot {
54
+ readonly records: readonly AzureAIFoundryDeployment[]
55
+ readonly byName: ReadonlyMap<string, AzureAIFoundryDeployment>
56
+ readonly fetchedAt: string
57
+ }
58
+
59
+ export interface ResolvedDeployment {
60
+ readonly deployment: AzureAIFoundryDeployment
61
+ readonly discoveredAt: string
62
+ }
63
+
64
+ interface DiscoverySettings {
65
+ readonly url: string
66
+ readonly ttlMs: number
67
+ readonly timeoutMs: number
68
+ readonly maxPages: number
69
+ readonly maxDeployments: number
70
+ readonly maxResponseBytes: number
71
+ }
72
+
73
+ export class FoundryDeployments {
74
+ private readonly settings: DiscoverySettings
75
+ private cached?: Snapshot
76
+ private expiresAt = 0
77
+ private pending?: Promise<Snapshot>
78
+
79
+ constructor(
80
+ private readonly providerId: string,
81
+ private readonly transport: FoundryTransport,
82
+ discovery: AzureAIFoundryDiscoveryOptions = {}
83
+ ) {
84
+ for (const key of [
85
+ "ttlMs",
86
+ "timeoutMs",
87
+ "maxPages",
88
+ "maxDeployments",
89
+ "maxResponseBytes",
90
+ ] as const)
91
+ positiveInteger(discovery[key], `discovery.${key}`)
92
+ this.settings = {
93
+ url: `${transport.projectUrl}/deployments?api-version=v1`,
94
+ ttlMs: discovery.ttlMs ?? 60 * 60 * 1_000,
95
+ timeoutMs: discovery.timeoutMs ?? 5_000,
96
+ maxPages: discovery.maxPages ?? 100,
97
+ maxDeployments: discovery.maxDeployments ?? 10_000,
98
+ maxResponseBytes: discovery.maxResponseBytes ?? 4 * 1024 * 1024,
99
+ }
100
+ }
101
+
102
+ async list(refresh = false): Promise<readonly AzureAIFoundryDeployment[]> {
103
+ return (await this.load(refresh)).records
104
+ }
105
+
106
+ async resolve(name: string, offline: boolean): Promise<ResolvedDeployment> {
107
+ const snapshot = offline ? this.cached : await this.load()
108
+ const deployment = snapshot?.byName.get(name)
109
+ if (!snapshot || !deployment)
110
+ throw this.invalid(
111
+ `Deployment '${name}' was not found in ${offline ? "cached project deployments; resolve online first" : "this project"}.`
112
+ )
113
+ return {
114
+ deployment,
115
+ discoveredAt: snapshot.fetchedAt,
116
+ }
117
+ }
118
+
119
+ private load(refresh = false): Promise<Snapshot> {
120
+ if (this.pending) return this.pending
121
+ if (!refresh && this.cached && Date.now() < this.expiresAt) return Promise.resolve(this.cached)
122
+ this.pending = this.fetchSnapshot()
123
+ .then((snapshot) => {
124
+ this.cached = snapshot
125
+ this.expiresAt = Date.now() + this.settings.ttlMs
126
+ return snapshot
127
+ })
128
+ .catch((error: unknown) => {
129
+ // Retain the last complete snapshot for explicit offline resolution only.
130
+ this.expiresAt = 0
131
+ throw error
132
+ })
133
+ .finally(() => {
134
+ this.pending = undefined
135
+ })
136
+ return this.pending
137
+ }
138
+
139
+ private async fetchSnapshot(): Promise<Snapshot> {
140
+ const settings = this.settings
141
+ const diagnostics = new RequestDiagnostics()
142
+ const controller = new AbortController()
143
+ const timer = setTimeout(
144
+ () => controller.abort(new DOMException("Discovery timed out", "TimeoutError")),
145
+ settings.timeoutMs
146
+ )
147
+ const { signal } = controller
148
+ const records: AzureAIFoundryDeployment[] = []
149
+ const byName = new Map<string, AzureAIFoundryDeployment>()
150
+ const seen = new Set<string>()
151
+ const budget = { bytes: settings.maxResponseBytes }
152
+ let url: string | undefined = settings.url
153
+ let entries = 0
154
+ try {
155
+ while (url !== undefined) {
156
+ const pageUrl: string = this.pageUrl(url, settings.url)
157
+ if (seen.has(pageUrl)) throw this.invalid("Deployment pagination repeated a page.")
158
+ if (seen.size >= settings.maxPages)
159
+ throw this.invalid("Deployment pagination exceeded maxPages.")
160
+ seen.add(pageUrl)
161
+ const response = await this.fetchPage(pageUrl, signal, diagnostics)
162
+ const text = await this.readPage(response, budget, signal)
163
+ let value: unknown
164
+ try {
165
+ value = JSON.parse(text)
166
+ } catch (cause) {
167
+ throw this.invalid("Deployment response is not valid JSON.", cause)
168
+ }
169
+ const page = object(value)
170
+ if (!page || !Array.isArray(page.value))
171
+ throw this.invalid("Deployment response is missing its value array.")
172
+ entries += page.value.length
173
+ if (entries > settings.maxDeployments)
174
+ throw this.invalid("Deployment response exceeded maxDeployments.")
175
+ for (const item of page.value) {
176
+ const raw = object(item)
177
+ if (!raw || typeof raw.type !== "string" || !raw.type.trim())
178
+ throw this.invalid("Deployment record is missing its type.")
179
+ if (raw.type !== "ModelDeployment") continue
180
+ const record = deploymentRecord(raw, (message) => this.invalid(message))
181
+ if (byName.has(record.name))
182
+ throw this.invalid(
183
+ `Duplicate deployment '${record.name}'; deployment names must be unique across project connections.`
184
+ )
185
+ records.push(record)
186
+ byName.set(record.name, record)
187
+ }
188
+ if (
189
+ page.nextLink !== undefined &&
190
+ (typeof page.nextLink !== "string" || !page.nextLink.trim())
191
+ )
192
+ throw this.invalid("Deployment nextLink must be a nonempty URL.")
193
+ url = typeof page.nextLink === "string" ? this.pageUrl(page.nextLink, pageUrl) : undefined
194
+ }
195
+ return { records: Object.freeze(records), byName, fetchedAt: new Date().toISOString() }
196
+ } catch (error) {
197
+ if (error instanceof ModelCatalogUnavailableError)
198
+ throw new ModelCatalogUnavailableError(diagnostics.text(error.message), {
199
+ cause: diagnostics.failure(error.cause),
200
+ })
201
+ throw diagnostics.failure(error)
202
+ } finally {
203
+ clearTimeout(timer)
204
+ }
205
+ }
206
+
207
+ private pageUrl(link: string, initial: string): string {
208
+ let url: URL
209
+ try {
210
+ url = new URL(link, initial)
211
+ } catch (cause) {
212
+ throw this.invalid("Invalid deployment nextLink.", cause)
213
+ }
214
+ const base = new URL(initial)
215
+ if (
216
+ url.origin !== base.origin ||
217
+ url.pathname !== base.pathname ||
218
+ url.username ||
219
+ url.password ||
220
+ url.hash
221
+ )
222
+ throw this.invalid("Deployment nextLink must stay on the same project deployments endpoint.")
223
+ if (!url.searchParams.has("api-version")) url.searchParams.set("api-version", "v1")
224
+ if (
225
+ url.searchParams.getAll("api-version").length !== 1 ||
226
+ url.searchParams.get("api-version") !== "v1"
227
+ )
228
+ throw this.invalid("Deployment nextLink must use api-version=v1.")
229
+ url.searchParams.sort()
230
+ return url.href
231
+ }
232
+
233
+ private async fetchPage(
234
+ url: string,
235
+ signal: AbortSignal,
236
+ diagnostics: RequestDiagnostics
237
+ ): Promise<Response> {
238
+ let headers: Headers
239
+ try {
240
+ headers = await this.transport.headers(signal, diagnostics)
241
+ } catch (cause) {
242
+ throw this.unavailable(cause)
243
+ }
244
+ headers.set("accept", "application/json")
245
+ let response: Response
246
+ try {
247
+ response = await abortable(async () => {
248
+ const result = await this.transport.fetch(url, { headers, signal, redirect: "error" })
249
+ if (signal.aborted) void result.body?.cancel().catch(() => {})
250
+ return result
251
+ }, signal)
252
+ } catch (cause) {
253
+ throw this.unavailable(cause)
254
+ }
255
+ if (response.status !== 200) {
256
+ void response.body?.cancel().catch(() => {})
257
+ throw this.unavailable(
258
+ new ModelProviderError(
259
+ `${PREFIX} Deployment discovery failed with HTTP ${response.status}.`,
260
+ this.providerId,
261
+ "catalog",
262
+ { status: response.status, requestId: requestId(response) }
263
+ )
264
+ )
265
+ }
266
+ return response
267
+ }
268
+
269
+ private async readPage(
270
+ response: Response,
271
+ budget: { bytes: number },
272
+ signal: AbortSignal
273
+ ): Promise<string> {
274
+ if (!response.body) throw this.invalid("Deployment response has no body.")
275
+ const reader = response.body.getReader()
276
+ const cancel = () => {
277
+ void reader.cancel(signal.reason).catch(() => {})
278
+ }
279
+ signal.addEventListener("abort", cancel, { once: true })
280
+ const chunks: Uint8Array[] = []
281
+ try {
282
+ for (;;) {
283
+ const chunk = await abortable(() => reader.read(), signal).catch((cause: unknown) => {
284
+ throw this.unavailable(cause)
285
+ })
286
+ if (signal.aborted) throw this.unavailable(signal.reason)
287
+ if (chunk.done) return Buffer.concat(chunks).toString("utf8")
288
+ budget.bytes -= chunk.value.byteLength
289
+ if (budget.bytes < 0) throw this.invalid("Deployment response exceeded maxResponseBytes.")
290
+ chunks.push(chunk.value)
291
+ }
292
+ } finally {
293
+ signal.removeEventListener("abort", cancel)
294
+ void reader.cancel().catch(() => {})
295
+ reader.releaseLock()
296
+ }
297
+ }
298
+
299
+ private invalid(message: string, cause?: unknown): ModelProviderError {
300
+ return new ModelProviderError(`${PREFIX} ${message}`, this.providerId, "catalog", { cause })
301
+ }
302
+
303
+ private unavailable(cause: unknown): ModelCatalogUnavailableError {
304
+ return new ModelCatalogUnavailableError(`${PREFIX} Project deployment catalog unavailable.`, {
305
+ cause,
306
+ })
307
+ }
308
+ }
309
+
310
+ const BOOLEAN_KEYS = [
311
+ "responses",
312
+ "messages",
313
+ "chatCompletion",
314
+ "chat_completion",
315
+ "completion",
316
+ "embeddings",
317
+ "jsonObjectResponse",
318
+ "assistants",
319
+ ]
320
+
321
+ function deploymentRecord(
322
+ raw: Record<string, unknown>,
323
+ invalid: (message: string) => Error
324
+ ): AzureAIFoundryDeployment {
325
+ const required = (value: unknown, field: string): string => {
326
+ if (typeof value !== "string" || !value.trim())
327
+ throw invalid(`Deployment ${field} must be a nonempty string.`)
328
+ return value
329
+ }
330
+ const capabilities = object(raw.capabilities)
331
+ if (!capabilities || Object.values(capabilities).some((value) => typeof value !== "string"))
332
+ throw invalid("Deployment capabilities must contain string values.")
333
+ const sku = object(raw.sku)
334
+ if (!sku) throw invalid("Deployment sku must be an object.")
335
+ for (const key of ["family", "size", "tier"])
336
+ if (sku[key] !== undefined && typeof sku[key] !== "string")
337
+ throw invalid(`Deployment sku.${key} must be a string.`)
338
+ if (
339
+ sku.capacity !== undefined &&
340
+ (typeof sku.capacity !== "number" || !Number.isSafeInteger(sku.capacity) || sku.capacity < 0)
341
+ )
342
+ throw invalid("Deployment sku.capacity must be a nonnegative safe integer.")
343
+ if (typeof raw.modelVersion !== "string")
344
+ throw invalid("Deployment modelVersion must be a string.")
345
+ // Entries were validated above. Build a fresh map so callers cannot mutate cached raw metadata.
346
+ const strings = Object.fromEntries(
347
+ Object.entries(capabilities).map(([key, value]) => [key, String(value)])
348
+ )
349
+ for (const key of BOOLEAN_KEYS)
350
+ if (strings[key] !== undefined && !["true", "false"].includes(strings[key]))
351
+ throw invalid(`Deployment capability '${key}' must be 'true' or 'false'.`)
352
+ if (
353
+ strings.chatCompletion !== undefined &&
354
+ strings.chat_completion !== undefined &&
355
+ strings.chatCompletion !== strings.chat_completion
356
+ )
357
+ throw invalid("Deployment has contradictory Chat capability aliases.")
358
+ for (const key of ["maxContextToken", "maxOutputToken"]) {
359
+ if (
360
+ strings[key] !== undefined &&
361
+ (!/^[1-9]\d*$/.test(strings[key]) || !Number.isSafeInteger(Number(strings[key])))
362
+ )
363
+ throw invalid(`Deployment capability '${key}' must be a positive safe integer string.`)
364
+ }
365
+ const name = required(raw.name, "name")
366
+ if (name !== name.trim())
367
+ throw invalid("Deployment name must not contain surrounding whitespace.")
368
+ return Object.freeze({
369
+ name,
370
+ modelName: required(raw.modelName, "modelName"),
371
+ modelVersion: raw.modelVersion,
372
+ modelPublisher: required(raw.modelPublisher, "modelPublisher"),
373
+ ...(raw.connectionName === undefined
374
+ ? {}
375
+ : { connectionName: required(raw.connectionName, "connectionName") }),
376
+ capabilities: Object.freeze(strings),
377
+ sku: Object.freeze({
378
+ name: required(sku.name, "sku.name"),
379
+ ...(typeof sku.capacity === "number" ? { capacity: sku.capacity } : {}),
380
+ ...(typeof sku.family === "string" ? { family: sku.family } : {}),
381
+ ...(typeof sku.size === "string" ? { size: sku.size } : {}),
382
+ ...(typeof sku.tier === "string" ? { tier: sku.tier } : {}),
383
+ }),
384
+ })
385
+ }
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ export type { AzureAIFoundryCatalogOptions } from "./catalog"
2
+ export type {
3
+ AzureAIFoundryCatalog,
4
+ AzureAIFoundryDeployment,
5
+ AzureAIFoundryDiscoveryOptions,
6
+ } from "./discovery"
7
+ export type {
8
+ AzureAIFoundryChatOptions,
9
+ AzureAIFoundryMessagesOptions,
10
+ AzureAIFoundryModel,
11
+ AzureAIFoundryModelMetadata,
12
+ AzureAIFoundryModelOptions,
13
+ AzureAIFoundryOptions,
14
+ AzureAIFoundryProvider,
15
+ } from "./provider"
16
+ export { createAzureAIFoundry } from "./provider"
17
+ export type { FoundryProtocol } from "./transport"
@@ -0,0 +1,105 @@
1
+ import type {
2
+ JsonObject,
3
+ LanguageModelRateCard,
4
+ ModelCostEstimator,
5
+ ModelUsage,
6
+ } from "@sixb/core/models"
7
+ import { tokenEstimator } from "./accounting"
8
+ import { counter, object } from "./util"
9
+
10
+ /** Native Messages counters are additive; absent cache/thinking counters stay unknown. */
11
+ export function foundryMessagesUsage(raw: JsonObject): ModelUsage {
12
+ const uncached = counter(raw.input_tokens)
13
+ const read = counter(raw.cache_read_input_tokens)
14
+ const creation = object(raw.cache_creation)
15
+ const five = counter(creation?.ephemeral_5m_input_tokens)
16
+ const hour = counter(creation?.ephemeral_1h_input_tokens)
17
+ const write =
18
+ counter(raw.cache_creation_input_tokens) ??
19
+ (five !== undefined && hour !== undefined ? five + hour : undefined)
20
+ const output = counter(raw.output_tokens)
21
+ const thinking = counter(object(raw.output_tokens_details)?.thinking_tokens)
22
+ const input =
23
+ uncached !== undefined && read !== undefined && write !== undefined
24
+ ? uncached + read + write
25
+ : undefined
26
+ return {
27
+ ...(input === undefined ? {} : { inputTokens: input }),
28
+ ...(uncached === undefined ? {} : { uncachedInputTokens: uncached }),
29
+ ...(read === undefined ? {} : { cacheReadInputTokens: read }),
30
+ ...(write === undefined ? {} : { cacheWriteInputTokens: write }),
31
+ ...(five === undefined && write !== 0 ? {} : { cacheWrite5mInputTokens: five ?? 0 }),
32
+ ...(hour === undefined && write !== 0 ? {} : { cacheWrite1hInputTokens: hour ?? 0 }),
33
+ ...(output === undefined ? {} : { outputTokens: output }),
34
+ ...(thinking === undefined ? {} : { reasoningOutputTokens: thinking }),
35
+ ...(output !== undefined && thinking !== undefined && thinking <= output
36
+ ? { textOutputTokens: output - thinking }
37
+ : {}),
38
+ raw,
39
+ }
40
+ }
41
+
42
+ export function foundryMessagesEstimator(
43
+ card: LanguageModelRateCard | undefined,
44
+ request: JsonObject | undefined,
45
+ modelName?: string,
46
+ modelVersion?: string,
47
+ aliases?: readonly string[]
48
+ ): ModelCostEstimator {
49
+ const estimator = tokenEstimator(
50
+ card,
51
+ request,
52
+ ["temperature", "top_p", "top_k", "metadata", "stop_sequences", "cache_control"],
53
+ tokenMeters,
54
+ modelName,
55
+ modelVersion,
56
+ aliases ?? (modelName ? [modelName] : undefined)
57
+ )
58
+ const cache = object(request?.cache_control)
59
+ if (!cache) return estimator
60
+ const ttl = cache.ttl ?? "5m"
61
+ const writeRate = ttl === "1h" ? card?.cacheWriteInput1h : card?.cacheWriteInput5m
62
+ const unknownWriteRate = writeRate === undefined && card?.cacheWriteInput === undefined
63
+ return {
64
+ ...estimator,
65
+ estimateReservation: (tokens) =>
66
+ unknownWriteRate ? undefined : estimator.estimateReservation?.(tokens),
67
+ }
68
+ }
69
+
70
+ function tokenMeters(raw: JsonObject | undefined): boolean {
71
+ if (!raw) return true
72
+ const numeric = [
73
+ "input_tokens",
74
+ "output_tokens",
75
+ "cache_read_input_tokens",
76
+ "cache_creation_input_tokens",
77
+ ]
78
+ for (const [key, value] of Object.entries(raw)) {
79
+ if (numeric.includes(key)) {
80
+ if (counter(value) === undefined) return false
81
+ } else if (key === "cache_creation" || key === "output_tokens_details") {
82
+ const details = object(value)
83
+ const allowed =
84
+ key === "cache_creation"
85
+ ? ["ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens"]
86
+ : ["thinking_tokens"]
87
+ if (
88
+ !details ||
89
+ Object.entries(details).some(([k, v]) => !allowed.includes(k) || counter(v) === undefined)
90
+ )
91
+ return false
92
+ } else if (key === "server_tool_use") {
93
+ const tools = object(value)
94
+ if (
95
+ !tools ||
96
+ Object.entries(tools).some(
97
+ ([k, v]) => !["web_search_requests", "web_fetch_requests"].includes(k) || v !== 0
98
+ )
99
+ )
100
+ return false
101
+ } else if (key === "service_tier" && value === "standard") {
102
+ } else return false
103
+ }
104
+ return true
105
+ }
@@ -0,0 +1,164 @@
1
+ import {
2
+ type JsonObject,
3
+ type LanguageModelDefinition,
4
+ type LanguageModelRequest,
5
+ modelReasoningSupportIssue,
6
+ UnsupportedModelFeatureError,
7
+ } from "@sixb/core/models"
8
+ import { messagesInput } from "@sixb/model-protocols/messages"
9
+ import { messagesOutputSchema } from "./messages-schema"
10
+ import { prepareRequest } from "./request"
11
+ import { object, PREFIX, positiveInteger } from "./util"
12
+
13
+ export interface MessagesRequestOptions {
14
+ readonly maxOutputTokens?: number
15
+ readonly maxInputFileBytes?: number
16
+ readonly request?: JsonObject
17
+ /** Explicitly restrict thinking serialization to adaptive or manual mode. */
18
+ readonly thinkingMode?: "adaptive" | "manual"
19
+ }
20
+
21
+ const RESERVED = new Set([
22
+ "model",
23
+ "messages",
24
+ "system",
25
+ "tools",
26
+ "tool_choice",
27
+ "stream",
28
+ "max_tokens",
29
+ "thinking",
30
+ "output_config",
31
+ "output_format",
32
+ "disable_parallel_tool_use",
33
+ "container",
34
+ "mcp_servers",
35
+ "context_management",
36
+ ])
37
+
38
+ export function validateMessagesOptions(options: MessagesRequestOptions): void {
39
+ positiveInteger(options.maxOutputTokens, "maxOutputTokens")
40
+ positiveInteger(options.maxInputFileBytes, "maxInputFileBytes")
41
+ if (options.thinkingMode !== undefined && !["adaptive", "manual"].includes(options.thinkingMode))
42
+ throw new TypeError(`${PREFIX} thinkingMode must be adaptive or manual.`)
43
+ for (const key of Object.keys(options.request ?? {}))
44
+ if (RESERVED.has(key))
45
+ throw new TypeError(`${PREFIX} Messages request option '${key}' is owned by the adapter.`)
46
+ const cache = options.request?.cache_control
47
+ if (cache !== undefined) {
48
+ const value = object(cache)
49
+ if (
50
+ !value ||
51
+ value.type !== "ephemeral" ||
52
+ (value.ttl !== undefined && !["5m", "1h"].includes(String(value.ttl))) ||
53
+ Object.keys(value).some((key) => !["type", "ttl"].includes(key))
54
+ )
55
+ throw new TypeError(
56
+ `${PREFIX} cache_control must be ephemeral with an optional 5m or 1h ttl.`
57
+ )
58
+ }
59
+ }
60
+
61
+ export function foundryMessagesRequest(
62
+ request: LanguageModelRequest,
63
+ definition: LanguageModelDefinition,
64
+ options: MessagesRequestOptions,
65
+ scope: string
66
+ ): JsonObject {
67
+ const max = prepareRequest(request, definition, options, scope, true)
68
+ let conversation = false
69
+ for (const message of request.messages) {
70
+ if (message.role === "system" && conversation)
71
+ throw new UnsupportedModelFeatureError(
72
+ `${PREFIX} Messages system instructions must precede the conversation.`
73
+ )
74
+ if (message.role !== "system") conversation = true
75
+ }
76
+ if (max === undefined)
77
+ throw new TypeError(
78
+ `${PREFIX} Native Messages requires maxOutputTokens in the definition, binding, or request.`
79
+ )
80
+ const caps = definition.capabilities
81
+ if (request.tools.length && caps.localTools !== true)
82
+ throw new UnsupportedModelFeatureError(
83
+ `${PREFIX} Configure localTools capability before using Messages tools.`
84
+ )
85
+ const schema = request.responseFormat && messagesOutputSchema(request.responseFormat.schema)
86
+ if (request.responseFormat && (caps.nativeStructuredOutput !== true || !schema))
87
+ throw new UnsupportedModelFeatureError(
88
+ `${PREFIX} Messages structured output requires a declared capability and a supported closed-object Claude schema.`
89
+ )
90
+ const thinking = reasoningRequest(request, definition, options, max)
91
+ if (
92
+ thinking.thinking &&
93
+ object(thinking.thinking)?.type !== "disabled" &&
94
+ ["temperature", "top_p", "top_k"].some((key) => options.request?.[key] !== undefined)
95
+ )
96
+ throw new UnsupportedModelFeatureError(
97
+ `${PREFIX} Explicit sampling controls cannot be combined with Messages thinking.`
98
+ )
99
+ const mapped = messagesInput(request.messages, definition.providerId, PREFIX)
100
+ const output: JsonObject = {
101
+ ...(thinking.effort === undefined ? {} : { effort: thinking.effort }),
102
+ ...(schema ? { format: { type: "json_schema", schema } } : {}),
103
+ }
104
+ return {
105
+ ...options.request,
106
+ model: definition.modelId,
107
+ messages: mapped.messages,
108
+ ...(mapped.system.length ? { system: mapped.system } : {}),
109
+ stream: true,
110
+ max_tokens: max,
111
+ ...(thinking.thinking ? { thinking: thinking.thinking } : {}),
112
+ ...(Object.keys(output).length ? { output_config: output } : {}),
113
+ ...(request.tools.length
114
+ ? {
115
+ tools: request.tools.map((tool) => ({
116
+ name: tool.name,
117
+ description: tool.description,
118
+ input_schema: tool.inputSchema,
119
+ ...(caps.nativeStructuredOutput === true && messagesOutputSchema(tool.inputSchema)
120
+ ? { strict: true }
121
+ : {}),
122
+ })),
123
+ tool_choice: { type: "auto", disable_parallel_tool_use: caps.parallelToolCalls !== true },
124
+ }
125
+ : {}),
126
+ }
127
+ }
128
+
129
+ function reasoningRequest(
130
+ request: LanguageModelRequest,
131
+ definition: LanguageModelDefinition,
132
+ options: MessagesRequestOptions,
133
+ max: number
134
+ ): { thinking?: JsonObject; effort?: string } {
135
+ const reasoning = request.reasoning
136
+ if (reasoning === undefined || reasoning === "provider-default") return {}
137
+ const caps = definition.capabilities.reasoning
138
+ const issue = modelReasoningSupportIssue(caps, reasoning)
139
+ if (caps === undefined || issue)
140
+ throw new UnsupportedModelFeatureError(
141
+ `${PREFIX} ${issue ?? "Configure reasoning capabilities for this deployment"}.`
142
+ )
143
+ if (reasoning === "none") {
144
+ return {
145
+ thinking: { type: "disabled" },
146
+ }
147
+ }
148
+ if (typeof reasoning === "string") {
149
+ if (reasoning === "minimal" || options.thinkingMode === "manual")
150
+ throw new UnsupportedModelFeatureError(
151
+ `${PREFIX} Named efforts require an adaptive-thinking Claude offering.`
152
+ )
153
+ return { thinking: { type: "adaptive" }, effort: reasoning }
154
+ }
155
+ if (options.thinkingMode === "adaptive")
156
+ throw new UnsupportedModelFeatureError(
157
+ `${PREFIX} This Claude offering only supports adaptive thinking, not manual budgets.`
158
+ )
159
+ if (reasoning.budgetTokens < 1024 || reasoning.budgetTokens >= max)
160
+ throw new UnsupportedModelFeatureError(
161
+ `${PREFIX} Messages reasoning budget must be at least 1024 and below maxOutputTokens (${max}).`
162
+ )
163
+ return { thinking: { type: "enabled", budget_tokens: reasoning.budgetTokens } }
164
+ }