@magpie-community/opencode-agy-tui-auth 0.1.4 → 0.1.5
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.
- package/README.en.md +8 -4
- package/README.md +8 -4
- package/array-items.mjs +209 -0
- package/index.mjs +365 -70
- package/package.json +7 -2
- package/re2-pattern.mjs +606 -0
- package/tool-budget.mjs +157 -0
- package/tool-schema.mjs +672 -0
- package/tools.mjs +204 -0
package/tool-schema.mjs
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
// A copy of packages/agy-cli/tool-schema.mjs (each package is published alone): a
|
|
2
|
+
// change to one goes to the other.
|
|
3
|
+
// Expand JSON Schema constructs that agy's ACP -> CloudCode Schema translator
|
|
4
|
+
// either ignores or drops (`$ref` into `$defs`/`definitions`, `allOf`, `oneOf`,
|
|
5
|
+
// object/primitive `anyOf` unions, `const` discriminators, `additionalProperties`
|
|
6
|
+
// dictionaries, and boolean schemas), before `sanitizeInputSchema` and
|
|
7
|
+
// `ensureGeminiArrayItems` normalize types, RE2 patterns, and untyped arrays.
|
|
8
|
+
//
|
|
9
|
+
// Nullable unions lower to `type: [X, "null"]` (matching `sanitizeInputSchema`),
|
|
10
|
+
// which both agy's local JSON Schema validator and its CloudCode schema
|
|
11
|
+
// translator accept for null and non-null values alike.
|
|
12
|
+
// Local $ref/allOf/const expansion inspired by
|
|
13
|
+
// DylanLIiii/opencode-antigravity-bridge (MIT).
|
|
14
|
+
|
|
15
|
+
const NUMBER_BOUNDS = [
|
|
16
|
+
"minimum", "maximum", "minLength", "maxLength",
|
|
17
|
+
"minItems", "maxItems", "minProperties", "maxProperties",
|
|
18
|
+
]
|
|
19
|
+
const CONTAINER_MAPS = ["properties", "patternProperties", "dependentSchemas"]
|
|
20
|
+
const BOOLEAN_OR_SCHEMA_CHILDREN = ["additionalProperties", "unevaluatedProperties", "unevaluatedItems"]
|
|
21
|
+
const SCHEMA_ONLY_CHILDREN = ["propertyNames", "contains", "if", "then", "else", "not"]
|
|
22
|
+
const VISITED_OBJECT_KEYS = new Set([
|
|
23
|
+
...CONTAINER_MAPS,
|
|
24
|
+
...BOOLEAN_OR_SCHEMA_CHILDREN,
|
|
25
|
+
...SCHEMA_ONLY_CHILDREN,
|
|
26
|
+
"prefixItems", "items", "anyOf", "oneOf",
|
|
27
|
+
])
|
|
28
|
+
// Keywords whose value is a name -> schema map: a pointer may pass through
|
|
29
|
+
// them but must not stop on them.
|
|
30
|
+
const POINTER_MAP_KEYWORDS = new Set(["properties", "patternProperties", "dependentSchemas", "$defs", "definitions"])
|
|
31
|
+
|
|
32
|
+
// Only `$ref` and `allOf` inlining is charged; ordinary traversal is free.
|
|
33
|
+
const MAX_INLINED_NODES = 8192
|
|
34
|
+
const MAX_INLINED_BYTES = 256 * 1024
|
|
35
|
+
const MAX_DEPTH = 64
|
|
36
|
+
const MAX_VARIANT_HINT_CHARS = 1600
|
|
37
|
+
const MAX_VARIANT_SUMMARY_CHARS = 240
|
|
38
|
+
const MAX_VARIANT_DESCRIPTION_CHARS = 80
|
|
39
|
+
|
|
40
|
+
const ANY_VALUE_HINT = "Accepts any JSON value."
|
|
41
|
+
const NO_VALUE_HINT = "No value is allowed by the original schema."
|
|
42
|
+
const NULL_HINT = "Must be null."
|
|
43
|
+
const RECURSIVE_HINT = "Recursive schema; follow the tool's original argument contract."
|
|
44
|
+
const LIMIT_HINT = "Schema expansion limit reached; follow the tool's original argument contract."
|
|
45
|
+
|
|
46
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
47
|
+
|
|
48
|
+
function appendHint(node, hint) {
|
|
49
|
+
if (!hint) return
|
|
50
|
+
if (typeof node.description === "string" && node.description.trim()) {
|
|
51
|
+
if (!node.description.includes(hint)) node.description = `${node.description} (${hint})`
|
|
52
|
+
} else {
|
|
53
|
+
node.description = hint
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function clip(text, max) {
|
|
58
|
+
const flat = text.replace(/\s+/g, " ").trim()
|
|
59
|
+
return flat.length > max ? `${flat.slice(0, max - 3).trimEnd()}...` : flat
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function scalarBytes(value) {
|
|
63
|
+
if (typeof value === "string") return Buffer.byteLength(value) + 2
|
|
64
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value).length
|
|
65
|
+
return 4
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function ownBytes(out) {
|
|
69
|
+
let bytes = 2
|
|
70
|
+
for (const [key, value] of Object.entries(out)) {
|
|
71
|
+
if (value === undefined) continue
|
|
72
|
+
bytes += Buffer.byteLength(key) + 4
|
|
73
|
+
if (value === null || typeof value !== "object") {
|
|
74
|
+
bytes += scalarBytes(value)
|
|
75
|
+
} else if (key === "properties" || key === "patternProperties" || key === "dependentSchemas") {
|
|
76
|
+
bytes += 2
|
|
77
|
+
for (const mapKey of Object.keys(value)) bytes += Buffer.byteLength(mapKey) + 4
|
|
78
|
+
} else if (VISITED_OBJECT_KEYS.has(key)) {
|
|
79
|
+
bytes += 2
|
|
80
|
+
} else if (Array.isArray(value) && value.every((item) => item === null || typeof item !== "object")) {
|
|
81
|
+
bytes += 2
|
|
82
|
+
for (const item of value) bytes += scalarBytes(item) + 1
|
|
83
|
+
} else {
|
|
84
|
+
bytes += Buffer.byteLength(JSON.stringify(value))
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return bytes
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function resolvePointer(root, ref) {
|
|
91
|
+
if (ref === "#") return root
|
|
92
|
+
if (!ref.startsWith("#/")) return undefined
|
|
93
|
+
let parts
|
|
94
|
+
try {
|
|
95
|
+
parts = decodeURIComponent(ref.slice(2)).split("/")
|
|
96
|
+
} catch {
|
|
97
|
+
return undefined
|
|
98
|
+
}
|
|
99
|
+
let target = root
|
|
100
|
+
let inMap = false
|
|
101
|
+
for (const part of parts) {
|
|
102
|
+
const key = part.replace(/~1/g, "/").replace(/~0/g, "~")
|
|
103
|
+
if ((!isObject(target) && !Array.isArray(target)) || !Object.hasOwn(target, key)) return undefined
|
|
104
|
+
// Inside a map the key is a name (`#/properties/properties` is a schema);
|
|
105
|
+
// at a schema node it is a keyword.
|
|
106
|
+
const entersMap = !inMap && isObject(target) && POINTER_MAP_KEYWORDS.has(key)
|
|
107
|
+
target = target[key]
|
|
108
|
+
inMap = entersMap
|
|
109
|
+
}
|
|
110
|
+
if (inMap) return undefined
|
|
111
|
+
return isObject(target) || typeof target === "boolean" ? target : undefined
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isNullType(type) {
|
|
115
|
+
return type === "null" || (Array.isArray(type) && type.length === 1 && type[0] === "null")
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function isNullSchema(schema) {
|
|
119
|
+
if (!isObject(schema)) return false
|
|
120
|
+
if (isNullType(schema.type)) return true
|
|
121
|
+
// A lowered `const: null` leaf (no type, only the null hint).
|
|
122
|
+
return schema.type === undefined && typeof schema.description === "string" &&
|
|
123
|
+
schema.description.includes(NULL_HINT) && schema.properties === undefined &&
|
|
124
|
+
schema.items === undefined && schema.enum === undefined && schema.const === undefined &&
|
|
125
|
+
schema.anyOf === undefined && schema.oneOf === undefined
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function declaresArray(schema) {
|
|
129
|
+
if (!isObject(schema)) return false
|
|
130
|
+
return schema.type === "array" || (Array.isArray(schema.type) && schema.type.includes("array"))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function isObjectBranch(schema) {
|
|
134
|
+
if (!isObject(schema)) return false
|
|
135
|
+
if (schema.type === "object") return true
|
|
136
|
+
if (Array.isArray(schema.type) && schema.type.includes("object") &&
|
|
137
|
+
schema.type.every((t) => t === "object" || t === "null")) {
|
|
138
|
+
return true
|
|
139
|
+
}
|
|
140
|
+
if (schema.type !== undefined) return false
|
|
141
|
+
return isObject(schema.properties) || Array.isArray(schema.required) ||
|
|
142
|
+
schema.additionalProperties !== undefined || isObject(schema.patternProperties)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function primitiveTypeOf(schema) {
|
|
146
|
+
if (!isObject(schema)) return null
|
|
147
|
+
const raw = typeof schema.type === "string"
|
|
148
|
+
? [schema.type]
|
|
149
|
+
: Array.isArray(schema.type)
|
|
150
|
+
? schema.type.filter((t) => t !== "null")
|
|
151
|
+
: []
|
|
152
|
+
if (raw.length !== 1) return null
|
|
153
|
+
const t = raw[0]
|
|
154
|
+
return (t === "string" || t === "number" || t === "integer" || t === "boolean") ? t : null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Stand-in for a subtree that is not expanded (recursion, depth or budget):
|
|
158
|
+
// keep what kind of value it is, never invent a type it did not declare.
|
|
159
|
+
function structuralFallback(schema, hint) {
|
|
160
|
+
const nullable = isObject(schema) && Array.isArray(schema.type) && schema.type.includes("null")
|
|
161
|
+
const withNull = (t) => nullable ? [t, "null"] : t
|
|
162
|
+
if (isObjectBranch(schema)) return { type: withNull("object"), description: hint }
|
|
163
|
+
if (declaresArray(schema)) return { type: withNull("array"), description: hint }
|
|
164
|
+
const prim = primitiveTypeOf(schema)
|
|
165
|
+
if (prim) return { type: withNull(prim), description: hint }
|
|
166
|
+
return { description: hint }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function summarizeSchema(schema, depth = 0) {
|
|
170
|
+
if (!isObject(schema)) return schema === false ? "never" : "any"
|
|
171
|
+
if (Array.isArray(schema.enum) && schema.enum.length) {
|
|
172
|
+
const shown = schema.enum.slice(0, 12).map((v) => JSON.stringify(v)).join(" | ")
|
|
173
|
+
return schema.enum.length > 12 ? `${shown} | ...` : shown
|
|
174
|
+
}
|
|
175
|
+
if (schema.const !== undefined) return JSON.stringify(schema.const)
|
|
176
|
+
const types = Array.isArray(schema.type) ? schema.type : typeof schema.type === "string" ? [schema.type] : []
|
|
177
|
+
const rawType = types.length ? types.join("|") : undefined
|
|
178
|
+
const nullable = types.includes("null")
|
|
179
|
+
const nonNullTypes = types.filter((t) => t !== "null")
|
|
180
|
+
if ((!rawType || (nonNullTypes.length === 1 && nonNullTypes[0] === "object")) && isObject(schema.properties)) {
|
|
181
|
+
if (depth >= 2) return rawType || "object"
|
|
182
|
+
const req = new Set(Array.isArray(schema.required) ? schema.required : [])
|
|
183
|
+
const entries = Object.entries(schema.properties)
|
|
184
|
+
const shown = entries.slice(0, 8).map(([k, v]) => `${k}${req.has(k) ? "" : "?"}: ${summarizeSchema(v, depth + 1)}`)
|
|
185
|
+
if (entries.length > 8) shown.push("...")
|
|
186
|
+
const body = `{ ${shown.join(", ")} }`
|
|
187
|
+
return nullable ? `${body} | null` : body
|
|
188
|
+
}
|
|
189
|
+
if ((!rawType || rawType === "object") && Array.isArray(schema.required) && schema.required.length) {
|
|
190
|
+
return `{ required: [${schema.required.join(", ")}] }`
|
|
191
|
+
}
|
|
192
|
+
if ((nonNullTypes.length === 1 && nonNullTypes[0] === "array") || (!rawType && isObject(schema.items))) {
|
|
193
|
+
if (depth >= 2 || !isObject(schema.items)) return rawType || "array"
|
|
194
|
+
const body = `array<${summarizeSchema(schema.items, depth + 1)}>`
|
|
195
|
+
return nullable ? `${body} | null` : body
|
|
196
|
+
}
|
|
197
|
+
const combo = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : null
|
|
198
|
+
if (combo && combo.length) {
|
|
199
|
+
if (depth >= 2) return "union"
|
|
200
|
+
const shown = combo.slice(0, 6).map((b) => summarizeSchema(b, depth + 1)).join(" | ")
|
|
201
|
+
return combo.length > 6 ? `${shown} | ...` : shown
|
|
202
|
+
}
|
|
203
|
+
return rawType || "any"
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function typeList(type) {
|
|
207
|
+
if (typeof type === "string") return [type]
|
|
208
|
+
if (Array.isArray(type)) return type.filter((t) => typeof t === "string")
|
|
209
|
+
return null
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function intersectTypes(a, b) {
|
|
213
|
+
const left = typeList(a)
|
|
214
|
+
const right = typeList(b)
|
|
215
|
+
if (!left || !left.length) return { type: b }
|
|
216
|
+
if (!right || !right.length) return { type: a }
|
|
217
|
+
const common = new Set()
|
|
218
|
+
for (const t of left) {
|
|
219
|
+
if (right.includes(t)) common.add(t)
|
|
220
|
+
else if ((t === "number" && right.includes("integer")) || (t === "integer" && right.includes("number"))) {
|
|
221
|
+
common.add("integer")
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (!common.size) return { type: a, conflict: true }
|
|
225
|
+
const nonNull = [...common].filter((t) => t !== "null")
|
|
226
|
+
const list = common.has("null") ? [...nonNull, "null"] : nonNull
|
|
227
|
+
return { type: list.length === 1 ? list[0] : list }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function intersectSchemas(schemas) {
|
|
231
|
+
const meaningful = schemas.filter((schema) => isObject(schema) && Object.keys(schema).length)
|
|
232
|
+
if (!meaningful.length) return {}
|
|
233
|
+
if (meaningful.length === 1) return { ...meaningful[0] }
|
|
234
|
+
const out = { ...meaningful[0] }
|
|
235
|
+
const conflicts = []
|
|
236
|
+
for (const schema of meaningful.slice(1)) {
|
|
237
|
+
appendHint(out, schema.description)
|
|
238
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
239
|
+
if (key === "description" || key === "properties" || key === "required" || key === "items" ||
|
|
240
|
+
key === "enum" || key === "type" || NUMBER_BOUNDS.includes(key)) continue
|
|
241
|
+
if (out[key] === undefined) out[key] = value
|
|
242
|
+
}
|
|
243
|
+
if (schema.type !== undefined) {
|
|
244
|
+
const merged = intersectTypes(out.type, schema.type)
|
|
245
|
+
if (merged.conflict) conflicts.push(`${typeList(out.type).join("|")} vs ${typeList(schema.type).join("|")}`)
|
|
246
|
+
out.type = merged.type
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
for (const conflict of conflicts) appendHint(out, `Conflicting type constraints in allOf: ${conflict}.`)
|
|
250
|
+
const objects = meaningful.filter((schema) => isObject(schema.properties))
|
|
251
|
+
if (objects.length) {
|
|
252
|
+
const keys = [...new Set(objects.flatMap((schema) => Object.keys(schema.properties)))]
|
|
253
|
+
out.properties = Object.fromEntries(keys.map((key) => [
|
|
254
|
+
key,
|
|
255
|
+
intersectSchemas(objects.filter((schema) => Object.hasOwn(schema.properties, key)).map((schema) => schema.properties[key])),
|
|
256
|
+
]))
|
|
257
|
+
out.type ??= "object"
|
|
258
|
+
}
|
|
259
|
+
const reqKeys = [...new Set(meaningful.flatMap((schema) => Array.isArray(schema.required) ? schema.required : []))]
|
|
260
|
+
if (reqKeys.length) {
|
|
261
|
+
out.required = reqKeys
|
|
262
|
+
out.type ??= "object"
|
|
263
|
+
}
|
|
264
|
+
const arrays = meaningful.filter((schema) => isObject(schema.items))
|
|
265
|
+
if (arrays.length) {
|
|
266
|
+
out.items = intersectSchemas(arrays.map((schema) => schema.items))
|
|
267
|
+
out.type ??= "array"
|
|
268
|
+
}
|
|
269
|
+
for (const key of NUMBER_BOUNDS) {
|
|
270
|
+
const values = meaningful.map((schema) => schema[key]).filter((v) => typeof v === "number" && Number.isFinite(v))
|
|
271
|
+
if (!values.length) continue
|
|
272
|
+
const lower = key === "minimum" || key.startsWith("min")
|
|
273
|
+
out[key] = (lower ? Math.max : Math.min)(...values)
|
|
274
|
+
}
|
|
275
|
+
const enums = meaningful.filter((schema) => Array.isArray(schema.enum))
|
|
276
|
+
if (enums.length) {
|
|
277
|
+
const first = enums[0].enum
|
|
278
|
+
const common = first.filter((value) => enums.every((schema) => schema.enum.includes(value)))
|
|
279
|
+
if (common.length) {
|
|
280
|
+
out.enum = [...new Set(common)]
|
|
281
|
+
} else {
|
|
282
|
+
delete out.enum
|
|
283
|
+
appendHint(out, "Conflicting enum constraints in allOf.")
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return out
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function primitiveFamily(nonNull) {
|
|
290
|
+
const types = new Set()
|
|
291
|
+
for (const branch of nonNull) {
|
|
292
|
+
const t = primitiveTypeOf(branch)
|
|
293
|
+
if (!t) return null
|
|
294
|
+
types.add(t)
|
|
295
|
+
}
|
|
296
|
+
if (types.size === 1) return [...types][0]
|
|
297
|
+
if (types.size === 2 && types.has("number") && types.has("integer")) return "number"
|
|
298
|
+
return null
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function branchLiterals(branch) {
|
|
302
|
+
if (Array.isArray(branch.enum) && branch.enum.length > 0) return branch.enum
|
|
303
|
+
if (branch.const !== undefined && branch.const !== null) return [branch.const]
|
|
304
|
+
return null
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function unionPrimitiveBranches(nonNull, family, hasNull) {
|
|
308
|
+
const out = { type: hasNull ? [family, "null"] : family }
|
|
309
|
+
const descriptions = [...new Set(
|
|
310
|
+
nonNull.map((b) => typeof b.description === "string" ? b.description.trim() : "").filter(Boolean),
|
|
311
|
+
)]
|
|
312
|
+
if (descriptions.length) out.description = descriptions.slice(0, 3).join("; ")
|
|
313
|
+
|
|
314
|
+
// A `const` is a one-value enum. sanitizeInputSchema keeps non-empty string
|
|
315
|
+
// enums and turns numeric, boolean, or null-bearing ones into an "Allowed values" hint.
|
|
316
|
+
const literals = nonNull.map(branchLiterals)
|
|
317
|
+
if (literals.every(Boolean)) {
|
|
318
|
+
const values = [...new Set(literals.flat().filter((v) => v !== null))]
|
|
319
|
+
out.enum = hasNull ? [...values, null] : values
|
|
320
|
+
} else if (literals.some(Boolean)) {
|
|
321
|
+
const known = [...new Set(literals.filter(Boolean).flat())].slice(0, 12).map((v) => JSON.stringify(v)).join(", ")
|
|
322
|
+
appendHint(out, `Known values include: ${known}`)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
for (const key of NUMBER_BOUNDS) {
|
|
326
|
+
if (!nonNull.every((b) => typeof b[key] === "number" && Number.isFinite(b[key]))) continue
|
|
327
|
+
const values = nonNull.map((b) => b[key])
|
|
328
|
+
const lower = key === "minimum" || key.startsWith("min")
|
|
329
|
+
out[key] = (lower ? Math.min : Math.max)(...values)
|
|
330
|
+
}
|
|
331
|
+
const formats = [...new Set(nonNull.map((b) => b.format).filter((f) => typeof f === "string" && f))]
|
|
332
|
+
if (formats.length === 1 && nonNull.every((b) => b.format === formats[0])) out.format = formats[0]
|
|
333
|
+
const patterns = [...new Set(nonNull.map((b) => b.pattern).filter((p) => typeof p === "string" && p))]
|
|
334
|
+
if (patterns.length === 1 && nonNull.every((b) => b.pattern === patterns[0])) out.pattern = patterns[0]
|
|
335
|
+
|
|
336
|
+
return out
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function unionPropertySchemas(schemas) {
|
|
340
|
+
const meaningful = schemas.filter(isObject)
|
|
341
|
+
if (!meaningful.length) return {}
|
|
342
|
+
if (meaningful.length === 1) return { ...meaningful[0] }
|
|
343
|
+
const nonNull = meaningful.filter((b) => !isNullSchema(b))
|
|
344
|
+
const hasNull = nonNull.length < meaningful.length ||
|
|
345
|
+
meaningful.some((b) => Array.isArray(b.type) && b.type.includes("null"))
|
|
346
|
+
if (!nonNull.length) return { description: NULL_HINT }
|
|
347
|
+
if (nonNull.every(isObjectBranch)) return unionObjectBranches(nonNull, hasNull)
|
|
348
|
+
const family = primitiveFamily(nonNull)
|
|
349
|
+
if (family) return unionPrimitiveBranches(nonNull, family, hasNull)
|
|
350
|
+
return {
|
|
351
|
+
anyOf: meaningful,
|
|
352
|
+
description: `Accepts anyOf: ${meaningful.map((b) => summarizeSchema(b)).join(" | ")}`,
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function variantsHint(branches) {
|
|
357
|
+
const parts = []
|
|
358
|
+
let length = 0
|
|
359
|
+
for (let i = 0; i < branches.length; i++) {
|
|
360
|
+
const branch = branches[i]
|
|
361
|
+
let part = clip(summarizeSchema(branch, 1), MAX_VARIANT_SUMMARY_CHARS)
|
|
362
|
+
if (typeof branch.description === "string" && branch.description.trim()) {
|
|
363
|
+
part += ` (${clip(branch.description, MAX_VARIANT_DESCRIPTION_CHARS)})`
|
|
364
|
+
}
|
|
365
|
+
if (parts.length && length + part.length + 3 > MAX_VARIANT_HINT_CHARS) {
|
|
366
|
+
parts.push(`... (+${branches.length - i} more)`)
|
|
367
|
+
break
|
|
368
|
+
}
|
|
369
|
+
parts.push(part)
|
|
370
|
+
length += part.length + 3
|
|
371
|
+
}
|
|
372
|
+
return `Variants: ${parts.join(" | ")}`
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function unionObjectBranches(nonNull, hasNull) {
|
|
376
|
+
const out = { type: hasNull ? ["object", "null"] : "object" }
|
|
377
|
+
if (nonNull.length === 1 && typeof nonNull[0].description === "string" && nonNull[0].description.trim()) {
|
|
378
|
+
out.description = nonNull[0].description
|
|
379
|
+
}
|
|
380
|
+
const propKeys = [...new Set(nonNull.flatMap((b) => isObject(b.properties) ? Object.keys(b.properties) : []))]
|
|
381
|
+
if (propKeys.length) {
|
|
382
|
+
out.properties = Object.fromEntries(propKeys.map((key) => [
|
|
383
|
+
key,
|
|
384
|
+
unionPropertySchemas(
|
|
385
|
+
nonNull.filter((b) => isObject(b.properties) && Object.hasOwn(b.properties, key)).map((b) => b.properties[key]),
|
|
386
|
+
),
|
|
387
|
+
]))
|
|
388
|
+
}
|
|
389
|
+
const reqSets = nonNull.map((b) => new Set(Array.isArray(b.required) ? b.required : []))
|
|
390
|
+
const commonReq = [...reqSets[0]].filter((key) => reqSets.every((set) => set.has(key)))
|
|
391
|
+
if (commonReq.length) out.required = commonReq
|
|
392
|
+
|
|
393
|
+
if (nonNull.some((b) => b.additionalProperties === true)) {
|
|
394
|
+
out.additionalProperties = true
|
|
395
|
+
} else if (nonNull.some((b) => isObject(b.additionalProperties))) {
|
|
396
|
+
out.additionalProperties = unionPropertySchemas(
|
|
397
|
+
nonNull.filter((b) => isObject(b.additionalProperties)).map((b) => b.additionalProperties),
|
|
398
|
+
)
|
|
399
|
+
} else if (nonNull.every((b) => b.additionalProperties === false)) {
|
|
400
|
+
out.additionalProperties = false
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (nonNull.length > 1) appendHint(out, variantsHint(nonNull))
|
|
404
|
+
return out
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function lowerUnionKey(out, key) {
|
|
408
|
+
const branches = out[key]
|
|
409
|
+
if (!Array.isArray(branches)) return out
|
|
410
|
+
if (!branches.length) {
|
|
411
|
+
delete out[key]
|
|
412
|
+
return out
|
|
413
|
+
}
|
|
414
|
+
const nonNull = branches.filter((b) => !isNullSchema(b))
|
|
415
|
+
const hasNull = nonNull.length < branches.length ||
|
|
416
|
+
branches.some((b) => Array.isArray(b?.type) && b.type.includes("null"))
|
|
417
|
+
|
|
418
|
+
if (!nonNull.length) {
|
|
419
|
+
delete out[key]
|
|
420
|
+
if (isNullType(out.type)) delete out.type
|
|
421
|
+
appendHint(out, NULL_HINT)
|
|
422
|
+
return out
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Leave array-bearing combinators intact so `ensureGeminiArrayItems` can lift
|
|
426
|
+
// item schemas without narrowing `string | string[]` or `array | null`.
|
|
427
|
+
if (declaresArray(out) || nonNull.some(declaresArray)) {
|
|
428
|
+
if (key === "oneOf") {
|
|
429
|
+
out.anyOf = Array.isArray(out.anyOf) ? [...out.anyOf, ...branches] : branches
|
|
430
|
+
delete out.oneOf
|
|
431
|
+
}
|
|
432
|
+
if (!declaresArray(out)) {
|
|
433
|
+
appendHint(out, `Accepts anyOf: ${branches.map((b) => summarizeSchema(b)).join(" | ")}`)
|
|
434
|
+
}
|
|
435
|
+
return out
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (nonNull.every(isObjectBranch)) {
|
|
439
|
+
const rest = { ...out }
|
|
440
|
+
delete rest[key]
|
|
441
|
+
return intersectSchemas([rest, unionObjectBranches(nonNull, hasNull)])
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const family = primitiveFamily(nonNull)
|
|
445
|
+
if (family) {
|
|
446
|
+
const rest = { ...out }
|
|
447
|
+
delete rest[key]
|
|
448
|
+
return intersectSchemas([rest, unionPrimitiveBranches(nonNull, family, hasNull)])
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if (key === "oneOf") {
|
|
452
|
+
out.anyOf = Array.isArray(out.anyOf) ? [...out.anyOf, ...branches] : branches
|
|
453
|
+
delete out.oneOf
|
|
454
|
+
}
|
|
455
|
+
appendHint(out, `Accepts anyOf: ${branches.map((b) => summarizeSchema(b)).join(" | ")}`)
|
|
456
|
+
return out
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function constConflict(out) {
|
|
460
|
+
if (!Array.isArray(out.enum)) return
|
|
461
|
+
if (!out.enum.includes(out.const)) {
|
|
462
|
+
appendHint(out, `Conflicting const and enum constraints; const is ${JSON.stringify(out.const)}.`)
|
|
463
|
+
}
|
|
464
|
+
delete out.enum
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// `const` on a leaf. Non-empty strings become a one-value enum; `""`, numbers,
|
|
468
|
+
// booleans, objects and arrays keep `const` (sanitizeInputSchema turns it into
|
|
469
|
+
// a "Must equal" hint) and get the matching type.
|
|
470
|
+
function lowerConst(out) {
|
|
471
|
+
const value = out.const
|
|
472
|
+
if (value === null) {
|
|
473
|
+
delete out.const
|
|
474
|
+
if (isNullType(out.type)) delete out.type
|
|
475
|
+
appendHint(out, NULL_HINT)
|
|
476
|
+
return
|
|
477
|
+
}
|
|
478
|
+
if (typeof value === "string") {
|
|
479
|
+
const types = typeList(out.type)
|
|
480
|
+
if (types && !types.every((t) => t === "string" || t === "null")) return
|
|
481
|
+
// `const` already excludes null, so a nullable string type narrows to string.
|
|
482
|
+
out.type = "string"
|
|
483
|
+
if (!value.length) {
|
|
484
|
+
constConflict(out)
|
|
485
|
+
return
|
|
486
|
+
}
|
|
487
|
+
if (Array.isArray(out.enum) && !out.enum.includes(value)) {
|
|
488
|
+
appendHint(out, `Conflicting const and enum constraints; const is ${JSON.stringify(value)}.`)
|
|
489
|
+
}
|
|
490
|
+
out.enum = [value]
|
|
491
|
+
delete out.const
|
|
492
|
+
return
|
|
493
|
+
}
|
|
494
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
495
|
+
out.type ??= Number.isInteger(value) ? "integer" : "number"
|
|
496
|
+
constConflict(out)
|
|
497
|
+
} else if (typeof value === "boolean") {
|
|
498
|
+
out.type ??= "boolean"
|
|
499
|
+
constConflict(out)
|
|
500
|
+
} else if (Array.isArray(value)) {
|
|
501
|
+
out.type ??= "array"
|
|
502
|
+
} else if (isObject(value)) {
|
|
503
|
+
out.type ??= "object"
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export function expandToolSchema(root) {
|
|
508
|
+
if (!isObject(root)) return root
|
|
509
|
+
|
|
510
|
+
// Cycle-free `$ref` targets are expanded once and deep-cloned on reuse.
|
|
511
|
+
const cache = new Map()
|
|
512
|
+
let produced = 0 // schema objects emitted, including cached copies
|
|
513
|
+
let producedBytes = 0 // estimated JSON bytes emitted, including cached copies
|
|
514
|
+
let inlined = 0 // of those, nodes emitted through $ref / allOf expansion
|
|
515
|
+
let inlinedBytes = 0 // of those, bytes emitted through $ref / allOf expansion
|
|
516
|
+
let limits = 0 // recursion / depth / budget fallbacks emitted
|
|
517
|
+
let deepest = 0
|
|
518
|
+
|
|
519
|
+
function limit(schema, hint) {
|
|
520
|
+
const out = structuralFallback(schema, hint)
|
|
521
|
+
limits++
|
|
522
|
+
produced++
|
|
523
|
+
producedBytes += ownBytes(out)
|
|
524
|
+
return out
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function measure(inlineDepth, fn) {
|
|
528
|
+
const start = { produced, producedBytes, inlined, inlinedBytes, limits, deepest }
|
|
529
|
+
deepest = inlineDepth
|
|
530
|
+
const schema = fn()
|
|
531
|
+
const result = {
|
|
532
|
+
schema,
|
|
533
|
+
weight: produced - start.produced,
|
|
534
|
+
bytes: producedBytes - start.producedBytes,
|
|
535
|
+
nested: inlined - start.inlined,
|
|
536
|
+
nestedBytes: inlinedBytes - start.inlinedBytes,
|
|
537
|
+
limited: limits !== start.limits,
|
|
538
|
+
height: deepest - inlineDepth,
|
|
539
|
+
}
|
|
540
|
+
deepest = Math.max(start.deepest, deepest)
|
|
541
|
+
// Charge only what nested expansions have not charged already.
|
|
542
|
+
inlined += Math.max(0, result.weight - result.nested)
|
|
543
|
+
inlinedBytes += Math.max(0, result.bytes - result.nestedBytes)
|
|
544
|
+
return result
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function expandRef(target, inlineDepth, active) {
|
|
548
|
+
if (typeof target === "boolean") return visit(target, inlineDepth, active)
|
|
549
|
+
if (inlined >= MAX_INLINED_NODES || inlinedBytes >= MAX_INLINED_BYTES) return limit(target, LIMIT_HINT)
|
|
550
|
+
const hit = cache.get(target)
|
|
551
|
+
if (hit && inlineDepth + hit.height <= MAX_DEPTH) {
|
|
552
|
+
if (inlined + hit.weight > MAX_INLINED_NODES || inlinedBytes + hit.bytes > MAX_INLINED_BYTES) {
|
|
553
|
+
return limit(target, LIMIT_HINT)
|
|
554
|
+
}
|
|
555
|
+
produced += hit.weight
|
|
556
|
+
inlined += hit.weight
|
|
557
|
+
producedBytes += hit.bytes
|
|
558
|
+
inlinedBytes += hit.bytes
|
|
559
|
+
deepest = Math.max(deepest, inlineDepth + hit.height)
|
|
560
|
+
return structuredClone(hit.schema)
|
|
561
|
+
}
|
|
562
|
+
const result = measure(inlineDepth, () => visit(target, inlineDepth, active))
|
|
563
|
+
if (!result.limited) {
|
|
564
|
+
cache.set(target, {
|
|
565
|
+
schema: structuredClone(result.schema),
|
|
566
|
+
weight: result.weight,
|
|
567
|
+
bytes: result.bytes,
|
|
568
|
+
height: result.height,
|
|
569
|
+
})
|
|
570
|
+
}
|
|
571
|
+
return result.schema
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function visit(schema, inlineDepth, active) {
|
|
575
|
+
deepest = Math.max(deepest, inlineDepth)
|
|
576
|
+
if (!isObject(schema)) {
|
|
577
|
+
const out = { description: schema === false ? NO_VALUE_HINT : ANY_VALUE_HINT }
|
|
578
|
+
produced++
|
|
579
|
+
producedBytes += ownBytes(out)
|
|
580
|
+
return out
|
|
581
|
+
}
|
|
582
|
+
if (active.has(schema)) return limit(schema, RECURSIVE_HINT)
|
|
583
|
+
if (inlineDepth > MAX_DEPTH) return limit(schema, LIMIT_HINT)
|
|
584
|
+
produced++
|
|
585
|
+
const nextActive = new Set(active).add(schema)
|
|
586
|
+
const child = (value) => visit(value, inlineDepth, nextActive)
|
|
587
|
+
|
|
588
|
+
let out = {}
|
|
589
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
590
|
+
if (key === "$defs" || key === "definitions" || key === "$schema" || key === "$id" ||
|
|
591
|
+
key === "$ref" || key === "allOf") continue
|
|
592
|
+
out[key] = value
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
if (out.const !== undefined) lowerConst(out)
|
|
596
|
+
|
|
597
|
+
for (const mapKey of CONTAINER_MAPS) {
|
|
598
|
+
if (isObject(out[mapKey])) {
|
|
599
|
+
out[mapKey] = Object.fromEntries(Object.entries(out[mapKey]).map(([k, v]) => [k, child(v)]))
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
for (const childKey of BOOLEAN_OR_SCHEMA_CHILDREN) {
|
|
603
|
+
if (isObject(out[childKey])) {
|
|
604
|
+
out[childKey] = child(out[childKey])
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
for (const childKey of SCHEMA_ONLY_CHILDREN) {
|
|
608
|
+
if (out[childKey] !== undefined && (isObject(out[childKey]) || typeof out[childKey] === "boolean")) {
|
|
609
|
+
out[childKey] = child(out[childKey])
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (Array.isArray(out.prefixItems)) {
|
|
613
|
+
out.prefixItems = out.prefixItems.map((item) => child(item))
|
|
614
|
+
}
|
|
615
|
+
if (Array.isArray(out.items)) {
|
|
616
|
+
out.items = out.items.map((item) => child(item))
|
|
617
|
+
} else if (isObject(out.items)) {
|
|
618
|
+
out.items = child(out.items)
|
|
619
|
+
} else if (out.items === false) {
|
|
620
|
+
if (Array.isArray(out.prefixItems) && out.prefixItems.length > 0) {
|
|
621
|
+
// A closed tuple. agy ignores prefixItems, so give it the element
|
|
622
|
+
// union and the tuple length instead of forbidding every element.
|
|
623
|
+
const length = out.prefixItems.length
|
|
624
|
+
out.maxItems = typeof out.maxItems === "number" ? Math.min(out.maxItems, length) : length
|
|
625
|
+
out.items = structuredClone(unionPropertySchemas(out.prefixItems))
|
|
626
|
+
} else {
|
|
627
|
+
out.maxItems = 0
|
|
628
|
+
out.items = { type: "string", description: NO_VALUE_HINT }
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
for (const key of ["anyOf", "oneOf"]) {
|
|
632
|
+
if (Array.isArray(out[key])) out[key] = out[key].map((branch) => child(branch))
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
if (typeof schema.$ref === "string") {
|
|
636
|
+
const target = resolvePointer(root, schema.$ref)
|
|
637
|
+
if (target !== undefined) {
|
|
638
|
+
out = intersectSchemas([out, expandRef(target, inlineDepth + 1, nextActive)])
|
|
639
|
+
} else {
|
|
640
|
+
appendHint(out, `Unresolved schema reference: ${schema.$ref}`)
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length) {
|
|
645
|
+
const branches = schema.allOf.map((branch) => {
|
|
646
|
+
if (inlined >= MAX_INLINED_NODES || inlinedBytes >= MAX_INLINED_BYTES) {
|
|
647
|
+
return limit(branch, LIMIT_HINT)
|
|
648
|
+
}
|
|
649
|
+
return measure(inlineDepth + 1, () => visit(branch, inlineDepth + 1, nextActive)).schema
|
|
650
|
+
})
|
|
651
|
+
out = intersectSchemas([out, ...branches])
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
out = lowerUnionKey(out, "oneOf")
|
|
655
|
+
out = lowerUnionKey(out, "anyOf")
|
|
656
|
+
|
|
657
|
+
if (out.additionalProperties === true) {
|
|
658
|
+
appendHint(out, "Accepts arbitrary additional key-value properties.")
|
|
659
|
+
} else if (isObject(out.additionalProperties)) {
|
|
660
|
+
appendHint(out, `Additional properties: ${summarizeSchema(out.additionalProperties)}`)
|
|
661
|
+
}
|
|
662
|
+
if (isObject(out.patternProperties) && Object.keys(out.patternProperties).length > 0) {
|
|
663
|
+
const shown = Object.entries(out.patternProperties).slice(0, 6).map(([pat, val]) => `${pat}: ${summarizeSchema(val)}`)
|
|
664
|
+
appendHint(out, `Pattern properties: ${shown.join(", ")}`)
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
producedBytes += ownBytes(out)
|
|
668
|
+
return out
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
return visit(root, 0, new Set())
|
|
672
|
+
}
|