@jini-ai/agent-runtime 0.4.10 → 0.4.12

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 (112) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/acp-model-probe.d.ts +2 -20
  3. package/dist/agent-protocol/acp/json.js +46 -37
  4. package/dist/agent-protocol/acp/models.js +91 -73
  5. package/dist/agent-protocol/acp/rpc.d.ts +3 -2
  6. package/dist/agent-protocol/acp/rpc.js +3 -2
  7. package/dist/agent-protocol/acp/session-params.d.ts +1 -1
  8. package/dist/agent-protocol/acp/session-params.js +33 -30
  9. package/dist/agent-protocol/acp/session.d.ts +3 -1
  10. package/dist/agent-protocol/acp/session.js +62 -24
  11. package/dist/agent-protocol/acp/updates.js +49 -35
  12. package/dist/agent-protocol/pi-rpc/session.js +3 -1
  13. package/dist/anthropic-live-models.d.ts +12 -4
  14. package/dist/anthropic-live-models.js +0 -0
  15. package/dist/auth.js +84 -91
  16. package/dist/claude-code-models.d.ts +6 -5
  17. package/dist/claude-code-models.js +19 -12
  18. package/dist/claude-segment-usage.d.ts +3 -3
  19. package/dist/claude-segment-usage.js +63 -29
  20. package/dist/claude-stream.js +12 -5
  21. package/dist/copilot-stream.js +42 -50
  22. package/dist/defs/aider.js +3 -4
  23. package/dist/defs/amr.js +52 -61
  24. package/dist/defs/antigravity.d.ts +6 -5
  25. package/dist/defs/antigravity.js +48 -34
  26. package/dist/defs/auggie.d.ts +1 -1
  27. package/dist/defs/claude-compatible-args.d.ts +19 -0
  28. package/dist/defs/claude-compatible-args.js +42 -0
  29. package/dist/defs/claude.d.ts +7 -2
  30. package/dist/defs/claude.js +96 -85
  31. package/dist/defs/cline.d.ts +1 -1
  32. package/dist/defs/codebuddy.d.ts +1 -1
  33. package/dist/defs/codebuddy.js +29 -46
  34. package/dist/defs/codex.d.ts +15 -3
  35. package/dist/defs/codex.js +143 -108
  36. package/dist/defs/cursor-agent.d.ts +9 -7
  37. package/dist/defs/cursor-agent.js +53 -51
  38. package/dist/defs/devin.d.ts +1 -1
  39. package/dist/defs/goose.d.ts +1 -1
  40. package/dist/defs/hermes.d.ts +1 -1
  41. package/dist/defs/kilo.d.ts +1 -1
  42. package/dist/defs/kimi.d.ts +1 -1
  43. package/dist/defs/kiro.d.ts +1 -1
  44. package/dist/defs/opencode.d.ts +5 -4
  45. package/dist/defs/opencode.js +26 -32
  46. package/dist/defs/pi.d.ts +6 -5
  47. package/dist/defs/pi.js +24 -26
  48. package/dist/defs/qoder.d.ts +4 -3
  49. package/dist/defs/qoder.js +25 -25
  50. package/dist/defs/reasonix.d.ts +1 -1
  51. package/dist/defs/shared.d.ts +12 -3
  52. package/dist/defs/shared.js +19 -13
  53. package/dist/defs/trae-cli.d.ts +1 -1
  54. package/dist/defs/vibe.d.ts +1 -1
  55. package/dist/detection.d.ts +13 -20
  56. package/dist/detection.js +129 -111
  57. package/dist/env.js +56 -41
  58. package/dist/executables.js +103 -114
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.js +1 -0
  61. package/dist/json-event-stream.js +611 -527
  62. package/dist/launch.js +44 -37
  63. package/dist/model-discovery-adapters.d.ts +17 -0
  64. package/dist/model-discovery-adapters.js +223 -164
  65. package/dist/model-discovery-config.js +107 -87
  66. package/dist/model-discovery-sdk.d.ts +16 -2
  67. package/dist/model-discovery-sdk.js +4 -3
  68. package/dist/model-discovery-shared.d.ts +14 -0
  69. package/dist/model-discovery-shared.js +50 -15
  70. package/dist/model-discovery-types.d.ts +2 -0
  71. package/dist/model-discovery.js +219 -117
  72. package/dist/models.d.ts +14 -1
  73. package/dist/models.js +75 -19
  74. package/dist/native-tool-policy.d.ts +29 -0
  75. package/dist/native-tool-policy.js +36 -0
  76. package/dist/opencode-log.js +46 -30
  77. package/dist/paths.d.ts +2 -0
  78. package/dist/paths.js +3 -3
  79. package/dist/providers/aihubmix.js +13 -18
  80. package/dist/providers/anthropic-messages.d.ts +7 -0
  81. package/dist/providers/anthropic-messages.js +45 -21
  82. package/dist/providers/azure-chat.d.ts +5 -0
  83. package/dist/providers/azure-chat.js +13 -5
  84. package/dist/providers/connection-guard.d.ts +2 -45
  85. package/dist/providers/connection-guard.js +11 -10
  86. package/dist/providers/connection-test.d.ts +4 -0
  87. package/dist/providers/connection-test.js +127 -110
  88. package/dist/providers/elevenlabs.js +4 -1
  89. package/dist/providers/google-messages.d.ts +7 -0
  90. package/dist/providers/google-messages.js +69 -23
  91. package/dist/providers/google-schema.js +17 -23
  92. package/dist/providers/model-catalog.js +160 -145
  93. package/dist/providers/oauth-callback-server.js +37 -34
  94. package/dist/providers/oauth-credentials.js +23 -23
  95. package/dist/providers/oauth-tokens.js +16 -24
  96. package/dist/providers/openai-chat.d.ts +42 -0
  97. package/dist/providers/openai-chat.js +80 -10
  98. package/dist/providers/operation-schema.d.ts +25 -0
  99. package/dist/providers/operation-schema.js +226 -0
  100. package/dist/providers/response-text.d.ts +10 -0
  101. package/dist/providers/response-text.js +23 -0
  102. package/dist/providers/tool-turn-types.d.ts +35 -9
  103. package/dist/providers/tool-turn.d.ts +7 -0
  104. package/dist/providers/tool-turn.js +113 -32
  105. package/dist/qoder-stream.js +93 -80
  106. package/dist/registry.d.ts +45 -0
  107. package/dist/registry.js +39 -0
  108. package/dist/runtime-state.d.ts +1 -1
  109. package/dist/types.d.ts +43 -1
  110. package/package.json +16 -7
  111. package/dist/defs/gemini.d.ts +0 -24
  112. package/dist/defs/gemini.js +0 -81
@@ -116,6 +116,56 @@ export function extractOpenAiErrorDetail({ rawText }) {
116
116
  }
117
117
  return rawText.trim().slice(0, 500);
118
118
  }
119
+ /** Only explicit HTTP schema/capability rejections qualify, never auth, rate limits or transport failures.
120
+ * @complexity O(e) time and O(e) space for at most 16 KiB of error text; no I/O.
121
+ */
122
+ function isStrictToolRejection({ status, rawErrorText }) {
123
+ if (status !== 400 && status !== 422)
124
+ return false;
125
+ const detail = rawErrorText.slice(0, 16384);
126
+ const namesFeature = /\bstrict\b|\bVALIDATED\b|function[_ .]?calling[_ .]?config|(?:input[_ ]|json[_ ])?schema|structured.outputs/i.test(detail);
127
+ const rejectsFeature = /unsupported|not support|unknown (?:field|parameter|name)|unrecognized|not (?:allowed|permitted)|invalid (?:json )?schema|schema[^\n]*invalid|invalid (?:enum )?value[^\n]*(?:VALIDATED|function[_ .]?calling[_ .]?config)|requires?[^\n]*beta/i.test(detail);
128
+ return namesFeature && rejectsFeature;
129
+ }
130
+ /**
131
+ * Allow one recognized pre-generation downgrade for this turn. Diagnostic callbacks receive
132
+ * names and a closed reason code, never the provider's error text or tool arguments.
133
+ * @param input - Protocol and optional host diagnostic sink.
134
+ * @returns Turn-local strict preference and a rejection decision; callback errors propagate.
135
+ * @example const retry = createStrictToolRetry({ protocol: 'openai' });
136
+ * @complexity O(e + t) per rejection for bounded error text e and t tool names; O(t) diagnostic space.
137
+ */
138
+ export function createStrictToolRetry({ protocol, onSchemaFallback }, _options = {}) {
139
+ let enabled = true;
140
+ return {
141
+ get enabled() { return enabled; },
142
+ downgrade({ status, rawErrorText, toolNames }) {
143
+ if (!enabled || toolNames.length === 0)
144
+ return false;
145
+ if (!isStrictToolRejection({ status, rawErrorText }))
146
+ return false;
147
+ enabled = false;
148
+ for (const toolId of new Set(toolNames))
149
+ onSchemaFallback?.({ toolId, protocol, reason: 'endpoint-rejected' });
150
+ return true;
151
+ },
152
+ };
153
+ }
154
+ /** Refresh OpenAI-compatible tools through the projection owner; legacy callers retain their schemas.
155
+ * @param input - Existing adapter options and the turn's downgrade state.
156
+ * @returns A request-local copy; projection callback failures propagate.
157
+ * @example refreshOpenAiTools({ options, retry });
158
+ * @complexity O(t) local time/space for t tools; projection cost belongs to getTools.
159
+ */
160
+ export function refreshOpenAiTools({ options, retry }, _optional = {}) {
161
+ let tools = options.getTools?.({ strict: retry.enabled }) ?? options.tools;
162
+ if (!retry.enabled)
163
+ tools = tools?.map(tool => {
164
+ const { strict: _strict, ...definition } = tool.function;
165
+ return { ...tool, function: definition };
166
+ });
167
+ return { ...options, ...(tools !== undefined ? { tools } : {}) };
168
+ }
119
169
  /** Parses one SSE frame's data as a JSON object, or `null` for a malformed/empty keep-alive frame or a non-object payload — both are tolerated by the caller as "nothing to do this frame". */
120
170
  export function parseOpenAiSseData({ raw }) {
121
171
  let data;
@@ -217,6 +267,20 @@ function emitPendingOpenAiToolUseEvents(toolCalls, onEvent) {
217
267
  onEvent({ type: 'tool_use', id: call.id, name: call.name, input: call.input });
218
268
  }
219
269
  }
270
+ /** Tool-schema retry has precedence; consume only the hook that selected a replacement body. */
271
+ function resolveOpenAiRetry({ init, status, rawText }, _options = {}) {
272
+ const toolRetryBody = init.retryToolBody?.({ status, rawErrorText: rawText, body: init.body });
273
+ if (toolRetryBody) {
274
+ const { retryToolBody: _retryToolBody, ...retryInit } = init;
275
+ return { type: 'retry', retryInit: { ...retryInit, body: toolRetryBody } };
276
+ }
277
+ const retryBody = init.retryableBody?.(status, rawText);
278
+ if (retryBody) {
279
+ const { retryableBody: _retryableBody, ...retryInit } = init;
280
+ return { type: 'retry', retryInit: { ...retryInit, body: retryBody } };
281
+ }
282
+ return null;
283
+ }
220
284
  /**
221
285
  * Opens the streaming POST and validates the response, returning its readable body once every
222
286
  * pre-stream failure mode (network error, non-2xx status with no retry available, missing body)
@@ -224,7 +288,7 @@ function emitPendingOpenAiToolUseEvents(toolCalls, onEvent) {
224
288
  * those — the caller only has to branch on the outcome's `type`, keeping `hasEnded()` as the sole
225
289
  * gate for every exit path (see `runOpenAiCompatibleRequest`'s doc).
226
290
  */
227
- async function requestOpenAiCompatibleStream(init) {
291
+ async function requestOpenAiCompatibleStream({ init }, _options = {}) {
228
292
  const { onEvent, emitEnd } = init;
229
293
  let response;
230
294
  try {
@@ -253,11 +317,9 @@ async function requestOpenAiCompatibleStream(init) {
253
317
  }
254
318
  if (!response.ok) {
255
319
  const rawText = await response.text();
256
- const retryBody = init.retryableBody?.(response.status, rawText);
257
- if (retryBody) {
258
- const { retryableBody: _retryableBody, ...retryInit } = init;
259
- return { type: 'retry', retryInit: { ...retryInit, body: retryBody } };
260
- }
320
+ const retryOutcome = resolveOpenAiRetry({ init, status: response.status, rawText });
321
+ if (retryOutcome)
322
+ return retryOutcome;
261
323
  onEvent({
262
324
  type: 'error',
263
325
  message: redactSecrets({ input: extractOpenAiErrorDetail({ rawText: rawText }) }, { exactSecrets: init.redactSecretsList }),
@@ -310,7 +372,7 @@ export function processOpenAiStreamFrame({ state, frame, onEvent }) {
310
372
  export async function runOpenAiCompatibleRequest(requiredArgs, optionalArgs = {}) {
311
373
  const init = { ...optionalArgs, ...requiredArgs };
312
374
  const { onEvent, hasEnded } = init;
313
- const fetchOutcome = await requestOpenAiCompatibleStream(init);
375
+ const fetchOutcome = await requestOpenAiCompatibleStream({ init });
314
376
  if (fetchOutcome.type === 'ended') {
315
377
  return { finishReason: null, toolCalls: [], text: '' };
316
378
  }
@@ -348,7 +410,7 @@ export async function runOpenAiCompatibleRequest(requiredArgs, optionalArgs = {}
348
410
  return { finishReason: state.finishReason, toolCalls: resolvedToolCalls, text: state.fullText };
349
411
  }
350
412
  /** Validates `options.baseUrl`, then delegates to {@link runOpenAiCompatibleRequest} with OpenAI's own URL/header/body builders. Thin wrapper kept so `runOpenAiToolTurn`'s per-iteration call site stays unchanged by the extraction. */
351
- async function runSingleOpenAiRequest(options, messages, emitEnd, hasEnded) {
413
+ async function runSingleOpenAiRequest(options, messages, emitEnd, hasEnded, retry) {
352
414
  // DNS-resolving, not merely textual: the synchronous check only inspects the literal hostname,
353
415
  // so `https://internal.example.com -> 10.0.0.5` passed it and this runner connected to private
354
416
  // infrastructure on behalf of whoever supplied `baseUrl`. Matches what the Azure, Google and
@@ -359,10 +421,17 @@ async function runSingleOpenAiRequest(options, messages, emitEnd, hasEnded) {
359
421
  emitEnd('error');
360
422
  return { finishReason: null, toolCalls: [], text: '' };
361
423
  }
424
+ const requestOptions = refreshOpenAiTools({ options, retry });
362
425
  return (({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded, ...optionalArgs }) => runOpenAiCompatibleRequest({ url, headers, body, redactSecretsList, guardMessageId, providerLabel, onEvent, emitEnd, hasEnded }, optionalArgs))({
363
426
  url: openAiRequestUrl({ baseUrl: options.baseUrl }),
364
427
  headers: (({ apiKey, model, messages, onEvent, ...optionalArgs }) => openAiHeaders({ apiKey, model, messages, onEvent }, optionalArgs))(options),
365
- body: openAiRequestBody({ options: options, messages: messages }),
428
+ body: openAiRequestBody({ options: requestOptions, messages: messages }),
429
+ retryToolBody: ({ status, rawErrorText, body }) => {
430
+ const toolNames = (requestOptions.tools ?? []).filter(tool => tool.function.strict).map(tool => tool.function.name);
431
+ if (!retry.downgrade({ status, rawErrorText, toolNames }))
432
+ return null;
433
+ return { ...body, tools: refreshOpenAiTools({ options, retry }).tools };
434
+ },
366
435
  ...(baseUrlCheck.pinnedAddress ? { pinnedAddress: baseUrlCheck.pinnedAddress } : {}),
367
436
  ...(options.signal ? { signal: options.signal } : {}),
368
437
  ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
@@ -516,6 +585,7 @@ export function buildOpenAiToolExchangeMessages({ toolResultMessages, followUpPa
516
585
  */
517
586
  export async function runOpenAiToolTurn(requiredArgs, optionalArgs = {}) {
518
587
  const options = { ...optionalArgs, ...requiredArgs };
588
+ const retry = createStrictToolRetry({ protocol: 'openai', onSchemaFallback: options.onSchemaFallback });
519
589
  const maxToolTurns = options.maxToolTurns ?? DEFAULT_MAX_TOOL_TURNS;
520
590
  const executeTool = options.executeTool;
521
591
  const endGuard = createTurnEndGuard(options.onEvent, (reason) => ({ type: 'end', reason }));
@@ -524,7 +594,7 @@ export async function runOpenAiToolTurn(requiredArgs, optionalArgs = {}) {
524
594
  let toolTurns = 0;
525
595
  let lastFinishReason = null;
526
596
  while (true) {
527
- const outcome = await runSingleOpenAiRequest(options, messages, emitEnd, endGuard.hasEnded);
597
+ const outcome = await runSingleOpenAiRequest(options, messages, emitEnd, endGuard.hasEnded, retry);
528
598
  lastFinishReason = outcome.finishReason;
529
599
  if (endGuard.hasEnded())
530
600
  break;
@@ -0,0 +1,25 @@
1
+ import type { ProviderProtocol } from './tool-turn-types.js';
2
+ /** Closed reason codes are safe to observe: no schema, argument values or provider error text. */
3
+ export type OperationSchemaFallbackReason = 'endpoint-unsupported' | 'endpoint-rejected' | 'open-map' | 'recursive-schema' | 'unresolved-reference' | 'unsupported-schema' | 'optional-nullable' | 'schema-limit';
4
+ export interface CompiledOperationSchema {
5
+ readonly schema: Record<string, unknown>;
6
+ readonly strict: boolean;
7
+ readonly fallbackReason?: OperationSchemaFallbackReason;
8
+ /** Decode wire-only representations; authoritative validation still belongs to the host. */
9
+ readonly decodeInput: (input: unknown) => unknown;
10
+ }
11
+ /**
12
+ * Project a conservative strict schema under the fixed prefer policy. Unsupported contracts stay
13
+ * non-strict and require host validation; open maps and recursive schemas are never narrowed.
14
+ * @param required - Authoritative input schema and the actual wire protocol.
15
+ * @param optional - Strict endpoint support, supplied by the request adapter for this endpoint/model.
16
+ * @returns Wire schema, value-free fallback reason and a decoder for exactly that projection.
17
+ * @complexity O(n) time/space in the bounded expanded schema; decoding O(a) in argument nodes.
18
+ */
19
+ export declare function compileOperationSchema({ schema: inputSchema, protocol }: {
20
+ schema: unknown;
21
+ protocol: ProviderProtocol;
22
+ }, { strict }?: {
23
+ strict?: boolean;
24
+ }): CompiledOperationSchema;
25
+ //# sourceMappingURL=operation-schema.d.ts.map
@@ -0,0 +1,226 @@
1
+ import { googleParametersOf, findNumericEnumPaths, coerceNumericEnumStringsToNumbers } from './google-schema.js';
2
+ class SchemaProjectionError extends Error {
3
+ reason;
4
+ constructor(reason) {
5
+ super(reason);
6
+ this.reason = reason;
7
+ }
8
+ }
9
+ const EMPTY_SCHEMA = { type: 'object', additionalProperties: false, properties: {}, required: [] };
10
+ const SCHEMA_KEYS = new Set(['type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'anyOf', '$defs', 'definitions', '$ref', '$schema', 'title', 'description', 'default', 'examples']);
11
+ const TYPES = new Set(['object', 'array', 'string', 'integer', 'number', 'boolean', 'null']);
12
+ function isRecord(value) {
13
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
14
+ }
15
+ function reject(reason) { throw new SchemaProjectionError(reason); }
16
+ /** Resolve local JSON pointers only. Expansion is bounded by the same node/depth budget as inline schemas. */
17
+ function resolveReference(schema, context) {
18
+ if (schema.$ref === undefined)
19
+ return schema;
20
+ if (typeof schema.$ref !== 'string' || !schema.$ref.startsWith('#/'))
21
+ return reject('unresolved-reference');
22
+ if (Object.keys(schema).some(key => !['$ref', 'description', 'title'].includes(key)))
23
+ return reject('unsupported-schema');
24
+ let target = context.root;
25
+ for (const part of schema.$ref.slice(2).split('/')) {
26
+ const key = part.replace(/~1/g, '/').replace(/~0/g, '~');
27
+ if (!isRecord(target) || !Object.hasOwn(target, key))
28
+ return reject('unresolved-reference');
29
+ target = target[key];
30
+ }
31
+ if (!isRecord(target))
32
+ return reject('unresolved-reference');
33
+ return target;
34
+ }
35
+ /** Only simple nullable unions are projected; ambiguous variant decoders use host-validated fallback. */
36
+ function normalizedNode(schema) {
37
+ if (schema.anyOf === undefined)
38
+ return schema;
39
+ if (!Array.isArray(schema.anyOf) || schema.anyOf.length !== 2)
40
+ return reject('unsupported-schema');
41
+ const nullMember = schema.anyOf.find(member => isRecord(member) && member.type === 'null');
42
+ if (!isRecord(nullMember) || Object.keys(nullMember).some(key => !['type', 'title', 'description'].includes(key)))
43
+ return reject('unsupported-schema');
44
+ const nonNull = schema.anyOf.filter(member => !isRecord(member) || member.type !== 'null');
45
+ if (nonNull.length !== 1 || !isRecord(nonNull[0]))
46
+ return reject('unsupported-schema');
47
+ if (Object.keys(schema).some(key => !['anyOf', 'title', 'description', 'default'].includes(key)))
48
+ return reject('unsupported-schema');
49
+ const child = nonNull[0];
50
+ if (typeof child.type !== 'string')
51
+ return reject('unsupported-schema');
52
+ return { ...child, type: [child.type, 'null'] };
53
+ }
54
+ function nodeTypes(schema) {
55
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
56
+ if (types.length === 0)
57
+ return reject('unsupported-schema');
58
+ if (!types.every((type) => typeof type === 'string' && TYPES.has(type)))
59
+ return reject('unsupported-schema');
60
+ if (new Set(types).size !== types.length)
61
+ return reject('unsupported-schema');
62
+ if (types.length > 1 && (types.length !== 2 || !types.includes('null')))
63
+ return reject('unsupported-schema');
64
+ return types;
65
+ }
66
+ function schemaMetadata(schema) {
67
+ return Object.fromEntries(['title', 'description'].filter(key => schema[key] !== undefined).map(key => [key, schema[key]]));
68
+ }
69
+ /** Literal constraints stay authoritative; numeric enum stringification is owned by google-schema. */
70
+ function projectLiterals(schema, projected) {
71
+ if (schema.enum !== undefined)
72
+ projected.enum = literalValues(schema.enum);
73
+ if (Object.hasOwn(schema, 'const')) {
74
+ if (schema.enum !== undefined)
75
+ return reject('unsupported-schema');
76
+ projected.enum = literalValues([schema.const]);
77
+ }
78
+ }
79
+ function literalValues(value) {
80
+ if (!Array.isArray(value) || value.length === 0)
81
+ return reject('unsupported-schema');
82
+ if (value.some(member => member !== null && !['string', 'number', 'boolean'].includes(typeof member)))
83
+ return reject('unsupported-schema');
84
+ return [...value];
85
+ }
86
+ function childContext(context, schema) {
87
+ return { ...context, depth: context.depth + 1, ancestors: new Set([...context.ancestors, schema]) };
88
+ }
89
+ function makeNullable(schema) {
90
+ return { anyOf: [schema, { type: 'null' }] };
91
+ }
92
+ /** A missing additionalProperties is open JSON Schema too; closing it would silently discard allowed keys. */
93
+ function projectObject(schema, context) {
94
+ if (schema.additionalProperties !== false)
95
+ return reject('open-map');
96
+ const properties = schema.properties ?? {};
97
+ const required = schema.required ?? [];
98
+ if (!isRecord(properties) || !Array.isArray(required))
99
+ return reject('unsupported-schema');
100
+ if (required.some(key => typeof key !== 'string' || !Object.hasOwn(properties, key)))
101
+ return reject('unsupported-schema');
102
+ const requiredKeys = new Set(required);
103
+ const children = Object.entries(properties).map(([key, child]) => [key, projectNode(child, context, !requiredKeys.has(key))]);
104
+ const projected = {
105
+ type: schema.type, ...schemaMetadata(schema), additionalProperties: false,
106
+ properties: Object.fromEntries(children.map(([key, child]) => [key, child.schema])),
107
+ required: Object.keys(properties),
108
+ };
109
+ projectLiterals(schema, projected);
110
+ return { schema: projected, decoder: { omitNull: false, properties: Object.fromEntries(children.map(([key, child]) => [key, child.decoder])) } };
111
+ }
112
+ function projectValue(schema, context) {
113
+ const types = nodeTypes(schema);
114
+ if (types.includes('object'))
115
+ return projectObject(schema, context);
116
+ const projected = { type: schema.type, ...schemaMetadata(schema) };
117
+ projectLiterals(schema, projected);
118
+ let decoder = { omitNull: false };
119
+ if (types.includes('array')) {
120
+ const item = projectNode(schema.items, context, false);
121
+ projected.items = item.schema;
122
+ decoder = { ...decoder, items: item.decoder };
123
+ }
124
+ decoder = googleEnumDecoder(projected, decoder, context.protocol);
125
+ return { schema: projected, decoder };
126
+ }
127
+ /** Let the existing Google sanitizer stringify a nullable numeric enum too, retaining real nulls. */
128
+ function googleEnumDecoder(schema, decoder, protocol) {
129
+ if (protocol !== 'google' || !Array.isArray(schema.enum))
130
+ return decoder;
131
+ const values = schema.enum.filter(value => value !== null);
132
+ if (values.length === 0 || !values.every(value => typeof value === 'number'))
133
+ return decoder;
134
+ if (schema.enum.includes(null)) {
135
+ const types = nodeTypes(schema);
136
+ if (!types.includes('null'))
137
+ return reject('unsupported-schema');
138
+ schema.enum = values;
139
+ }
140
+ return { ...decoder, numericEnum: values };
141
+ }
142
+ /** O(n) for the expanded tree, bounded to 2048 nodes and 32 levels; no I/O or input mutation. */
143
+ function projectNode(value, context, optional) {
144
+ if (--context.budget.remaining < 0 || context.depth > 32)
145
+ return reject('schema-limit');
146
+ if (!isRecord(value))
147
+ return reject('unsupported-schema');
148
+ const resolved = resolveReference(value, context);
149
+ if (context.ancestors.has(resolved))
150
+ return reject('recursive-schema');
151
+ if (Object.keys(resolved).some(key => !SCHEMA_KEYS.has(key)))
152
+ return reject('unsupported-schema');
153
+ const schema = normalizedNode(resolved);
154
+ if (Object.keys(schema).some(key => !SCHEMA_KEYS.has(key)))
155
+ return reject('unsupported-schema');
156
+ const types = nodeTypes(schema);
157
+ // Required wire properties cannot represent both omission and a genuine null-as-clear.
158
+ // Prefer fallback over inventing a sentinel or forcing an unintended clear operation.
159
+ if (optional && types.includes('null'))
160
+ return reject('optional-nullable');
161
+ const result = projectValue(schema, childContext(context, resolved));
162
+ // Synthetic null means omission only for originally non-nullable optional properties.
163
+ // A required nullable field's real null remains a clear operation, even inside nested objects.
164
+ if (!optional)
165
+ return result;
166
+ return { schema: makeNullable(result.schema), decoder: { ...result.decoder, omitNull: true } };
167
+ }
168
+ function decodeValue(input, decoder) {
169
+ if (typeof input === 'string' && decoder.numericEnum?.some(value => String(value) === input))
170
+ return Number(input);
171
+ if (Array.isArray(input) && decoder.items)
172
+ return input.map(value => decodeValue(value, decoder.items));
173
+ if (!isRecord(input) || !decoder.properties)
174
+ return input;
175
+ return decodeObject(input, decoder.properties);
176
+ }
177
+ function decodeObject(input, properties) {
178
+ const entries = [];
179
+ for (const [key, value] of Object.entries(input)) {
180
+ const child = Object.hasOwn(properties, key) ? properties[key] : undefined;
181
+ if (value === null && child?.omitNull)
182
+ continue;
183
+ entries.push([key, child ? decodeValue(value, child) : value]);
184
+ }
185
+ return Object.fromEntries(entries);
186
+ }
187
+ function fallback(schema, protocol, reason) {
188
+ if (protocol !== 'google')
189
+ return { schema, strict: false, fallbackReason: reason, decodeInput: input => input };
190
+ const paths = findNumericEnumPaths({ schema });
191
+ return {
192
+ schema: googleParametersOf({ descriptor: { id: '', inputSchema: schema } }), strict: false, fallbackReason: reason,
193
+ decodeInput: input => coerceNumericEnumStringsToNumbers({ input, paths }),
194
+ };
195
+ }
196
+ function compileStrict(schema, protocol) {
197
+ const result = projectNode(schema, { root: schema, protocol, ancestors: new Set(), budget: { remaining: 2048 }, depth: 0 }, false);
198
+ if (result.schema.type !== 'object')
199
+ return reject('unsupported-schema');
200
+ const wireSchema = protocol === 'google' ? googleParametersOf({ descriptor: { id: '', inputSchema: result.schema } }) : result.schema;
201
+ return { schema: wireSchema, strict: true, decodeInput: input => decodeValue(input, result.decoder) };
202
+ }
203
+ /**
204
+ * Project a conservative strict schema under the fixed prefer policy. Unsupported contracts stay
205
+ * non-strict and require host validation; open maps and recursive schemas are never narrowed.
206
+ * @param required - Authoritative input schema and the actual wire protocol.
207
+ * @param optional - Strict endpoint support, supplied by the request adapter for this endpoint/model.
208
+ * @returns Wire schema, value-free fallback reason and a decoder for exactly that projection.
209
+ * @complexity O(n) time/space in the bounded expanded schema; decoding O(a) in argument nodes.
210
+ */
211
+ export function compileOperationSchema({ schema: inputSchema, protocol }, { strict = false } = {}) {
212
+ const schema = isRecord(inputSchema) ? inputSchema : EMPTY_SCHEMA;
213
+ if (inputSchema !== undefined && !isRecord(inputSchema))
214
+ return fallback(schema, protocol, 'unsupported-schema');
215
+ if (!strict)
216
+ return fallback(schema, protocol, 'endpoint-unsupported');
217
+ try {
218
+ return compileStrict(schema, protocol);
219
+ }
220
+ catch (error) {
221
+ if (!(error instanceof SchemaProjectionError))
222
+ throw error;
223
+ return fallback(schema, protocol, error.reason);
224
+ }
225
+ }
226
+ //# sourceMappingURL=operation-schema.js.map
@@ -0,0 +1,10 @@
1
+ /** Maximum bytes retained from an upstream provider's error response. */
2
+ export declare const MAX_PROVIDER_ERROR_BYTES: number;
3
+ /** Collects a bounded response, refusing excess bytes and closing the iterator on every exit.
4
+ * Errors contain no upstream content. O(bytes) time/space, bounded by maxBytes. */
5
+ export declare function readProviderResponseText({ body }: {
6
+ body: AsyncIterable<Uint8Array | string>;
7
+ }, { maxBytes }?: {
8
+ maxBytes?: number;
9
+ }): Promise<string>;
10
+ //# sourceMappingURL=response-text.d.ts.map
@@ -0,0 +1,23 @@
1
+ /** Maximum bytes retained from an upstream provider's error response. */
2
+ export const MAX_PROVIDER_ERROR_BYTES = 64 * 1024;
3
+ /** Collects a bounded response, refusing excess bytes and closing the iterator on every exit.
4
+ * Errors contain no upstream content. O(bytes) time/space, bounded by maxBytes. */
5
+ export async function readProviderResponseText({ body }, { maxBytes = MAX_PROVIDER_ERROR_BYTES } = {}) {
6
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
7
+ throw new RangeError('Invalid provider response limit');
8
+ const chunks = [];
9
+ let size = 0;
10
+ try {
11
+ for await (const chunk of body) {
12
+ size += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;
13
+ if (size > maxBytes)
14
+ throw new Error('Provider response exceeded the byte limit');
15
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk));
16
+ }
17
+ }
18
+ catch {
19
+ throw new Error('Provider response could not be read within the byte limit');
20
+ }
21
+ return Buffer.concat(chunks, size).toString('utf8');
22
+ }
23
+ //# sourceMappingURL=response-text.js.map
@@ -1,19 +1,40 @@
1
- import type { runAnthropicToolTurn } from './anthropic-messages.js';
2
- import type { runOpenAiToolTurn } from './openai-chat.js';
3
- import type { runAzureToolTurn } from './azure-chat.js';
4
- import type { runGoogleToolTurn } from './google-messages.js';
5
- /** Adapter ports retain each existing provider's request and tool-loop contract. */
1
+ import type { runAnthropicToolTurn, AnthropicToolDef } from './anthropic-messages.js';
2
+ import type { runOpenAiToolTurn, OpenAiFunctionToolDef } from './openai-chat.js';
3
+ import type { runAzureToolTurn, AzureFunctionToolDef } from './azure-chat.js';
4
+ import type { runGoogleToolTurn, GoogleToolDef } from './google-messages.js';
5
+ import type { OperationSchemaFallbackReason } from './operation-schema.js';
6
+ /** Request adapters choose strict support for their actual endpoint/model; policy is always prefer. */
7
+ export interface ProviderToolSnapshotOptions {
8
+ readonly strict?: boolean;
9
+ }
10
+ export interface ProviderSchemaFallback {
11
+ readonly toolId: string;
12
+ readonly protocol: ProviderProtocol;
13
+ readonly reason: OperationSchemaFallbackReason;
14
+ }
15
+ type RefreshableAdapter<Required, Optional, Result, Tool> = (required: Required, optional?: Optional & {
16
+ /** Read immediately before each request, including a recognized schema downgrade. */
17
+ readonly getTools?: (options?: ProviderToolSnapshotOptions) => readonly Tool[];
18
+ readonly onSchemaFallback?: (event: ProviderSchemaFallback) => void;
19
+ }) => Result;
20
+ type AnthropicAdapter = typeof runAnthropicToolTurn;
21
+ type OpenAiAdapter = typeof runOpenAiToolTurn;
22
+ type AzureAdapter = typeof runAzureToolTurn;
23
+ type GoogleAdapter = typeof runGoogleToolTurn;
24
+ /** Existing adapters remain assignable; refresh-aware loops consume the optional projection hook. */
6
25
  export interface ProviderTurnAdapters {
7
- readonly anthropic: typeof runAnthropicToolTurn;
8
- readonly openai: typeof runOpenAiToolTurn;
9
- readonly azure: typeof runAzureToolTurn;
10
- readonly google: typeof runGoogleToolTurn;
26
+ readonly anthropic: RefreshableAdapter<Parameters<AnthropicAdapter>[0], Parameters<AnthropicAdapter>[1], ReturnType<AnthropicAdapter>, AnthropicToolDef>;
27
+ readonly openai: RefreshableAdapter<Parameters<OpenAiAdapter>[0], Parameters<OpenAiAdapter>[1], ReturnType<OpenAiAdapter>, OpenAiFunctionToolDef>;
28
+ readonly azure: RefreshableAdapter<Parameters<AzureAdapter>[0], Parameters<AzureAdapter>[1], ReturnType<AzureAdapter>, AzureFunctionToolDef>;
29
+ readonly google: RefreshableAdapter<Parameters<GoogleAdapter>[0], Parameters<GoogleAdapter>[1], ReturnType<GoogleAdapter>, GoogleToolDef>;
11
30
  }
12
31
  /** Structural descriptors keep host registries out of the runtime dependency graph. */
13
32
  export interface ProviderToolDescriptor {
14
33
  readonly id: string;
15
34
  readonly description?: string;
16
35
  readonly inputSchema?: unknown;
36
+ /** Preserve a wire name already assigned by the run's core exposure snapshot. */
37
+ readonly wireName?: string;
17
38
  }
18
39
  export type ProviderProtocol = "anthropic" | "openai" | "azure" | "google";
19
40
  export interface ProviderChatMessage {
@@ -86,9 +107,14 @@ export interface ProviderToolTurnResult {
86
107
  }
87
108
  /** Optional turn controls; dependencies belong in the required input object. */
88
109
  export interface ProviderToolTurnOptions {
110
+ /** Current run-scoped descriptors; adapters refresh the projection before every request. */
111
+ readonly getToolSnapshot?: () => readonly ProviderToolDescriptor[];
112
+ /** Value-free diagnostic only; execution must still validate through the host executor. */
113
+ readonly onSchemaFallback?: (event: ProviderSchemaFallback) => void;
89
114
  readonly baseUrl?: string;
90
115
  readonly maxTokens?: number;
91
116
  readonly maxToolTurns?: number;
92
117
  readonly signal?: AbortSignal;
93
118
  }
119
+ export {};
94
120
  //# sourceMappingURL=tool-turn-types.d.ts.map
@@ -1,8 +1,15 @@
1
1
  import type { ProviderTurnAdapters, ProviderToolTurnInput, ProviderToolTurnResult, ProviderToolTurnOptions } from './tool-turn-types.js';
2
2
  export type * from './tool-turn-types.js';
3
+ export { compileOperationSchema } from './operation-schema.js';
4
+ export type { CompiledOperationSchema, OperationSchemaFallbackReason } from './operation-schema.js';
3
5
  export { googleParametersOf, sanitizeGoogleSchema, findNumericEnumPaths, coerceNumericEnumStringsToNumbers } from './google-schema.js';
4
6
  /** Existing provider loops, ready for host composition; callers may replace any adapter. */
5
7
  export declare const providerTurnAdapters: ProviderTurnAdapters;
8
+ /** Invalid snapshot names fail closed before an adapter can dispatch an ambiguous operation. */
9
+ export declare class ProviderToolProjectionError extends Error {
10
+ readonly code = "invalid-wire-name";
11
+ constructor(_required: Record<string, never>, options?: ErrorOptions);
12
+ }
6
13
  /** Runs one provider-neutral turn through the supplied adapters. The adapter end event takes precedence over a raw provider stop code.
7
14
  * Local mapping is proportional to the descriptors, expanded schemas and emitted result parts; request and loop cost belongs to the adapter ports.
8
15
  */