@magpie-community/opencode-agy-tui-auth 0.1.3 → 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/tools.mjs ADDED
@@ -0,0 +1,204 @@
1
+ // The caller's tools, as agy's MCP server offers them (magpie's
2
+ // `mcp-helper`, internal/tuitools): an OpenAI chat body's `tools` become
3
+ // MCP tools ({name, description, inputSchema}), their schemas made what
4
+ // agy's Gemini translator takes, the set cut to agy's tool budget.
5
+ //
6
+ // sanitizeInputSchema and its helpers are a copy of packages/agy-cli's
7
+ // (index.mjs, normalizeTools' schema step): a change to one goes to the
8
+ // other.
9
+ import { ensureGeminiArrayItems } from "./array-items.mjs"
10
+ import { sanitizePatternFields } from "./re2-pattern.mjs"
11
+ import { fitTools } from "./tool-budget.mjs"
12
+ import { expandToolSchema } from "./tool-schema.mjs"
13
+
14
+ const refuse = (message) => Object.assign(new Error(message), { status: 400 })
15
+
16
+ function appendSchemaHint(node, hint) {
17
+ if (!hint) return
18
+ if (typeof node.description === "string" && node.description.trim()) {
19
+ if (!node.description.includes(hint)) node.description = `${node.description} (${hint})`
20
+ } else {
21
+ node.description = hint
22
+ }
23
+ }
24
+
25
+ function plainSchemaMap(value) {
26
+ return value && typeof value === "object" && !Array.isArray(value)
27
+ }
28
+
29
+ // agy rejects every extra key on an object whose properties map is missing
30
+ // or empty when additionalProperties is left out (plugins#1332). JSON Schema
31
+ // allows those keys. An explicit additionalProperties, a restrictive
32
+ // unevaluatedProperties, a non-empty properties map, and a non-empty
33
+ // patternProperties map stay as declared.
34
+ function emptyObjectIsOpen(node) {
35
+ const resolved = typeof node.type === "string"
36
+ ? node.type
37
+ : Array.isArray(node.type)
38
+ ? node.type.find((item) => item !== "null") || null
39
+ : null
40
+ const implicitObject = node.type === undefined && plainSchemaMap(node.properties)
41
+ if (resolved !== "object" && !implicitObject) return false
42
+ if (node.additionalProperties !== undefined) return false
43
+ if (node.unevaluatedProperties !== undefined && node.unevaluatedProperties !== true) return false
44
+ if (plainSchemaMap(node.patternProperties) && Object.keys(node.patternProperties).length > 0) return false
45
+ if (node.properties !== undefined && !plainSchemaMap(node.properties)) return false
46
+ if (plainSchemaMap(node.properties) && Object.keys(node.properties).length > 0) return false
47
+ return true
48
+ }
49
+
50
+ // Sanitize JSON Schema constructs that agy's ACP -> Google Code Assist translator
51
+ // converts into invalid Schema protos (e.g. union types leaving stale array/object
52
+ // keywords, or non-string/empty enum entries producing `enum[0]: cannot be empty`).
53
+ function sanitizeInputSchema(schema) {
54
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return schema
55
+ const out = { ...schema }
56
+
57
+ if (Array.isArray(out.type)) {
58
+ const types = out.type.filter((item) => typeof item === "string")
59
+ const nullable = types.includes("null")
60
+ const nonNull = types.filter((item) => item !== "null")
61
+ if (nonNull.length > 1) {
62
+ let chosen = nonNull[0]
63
+ if (nonNull.includes("array") && out.items !== undefined) chosen = "array"
64
+ else if (nonNull.includes("object") && (out.properties !== undefined || out.additionalProperties !== undefined)) {
65
+ chosen = "object"
66
+ }
67
+ out.type = nullable ? [chosen, "null"] : chosen
68
+ appendSchemaHint(out, `Accepts types: ${types.join(" | ")}`)
69
+ } else if (nonNull.length === 1) {
70
+ out.type = nullable ? [nonNull[0], "null"] : nonNull[0]
71
+ }
72
+ }
73
+
74
+ const resolvedType = typeof out.type === "string"
75
+ ? out.type
76
+ : Array.isArray(out.type)
77
+ ? out.type.find((item) => item !== "null") || null
78
+ : null
79
+
80
+ if (resolvedType && resolvedType !== "array") {
81
+ delete out.items
82
+ delete out.prefixItems
83
+ delete out.minItems
84
+ delete out.maxItems
85
+ delete out.uniqueItems
86
+ delete out.contains
87
+ }
88
+ if (resolvedType && resolvedType !== "object") {
89
+ delete out.properties
90
+ delete out.patternProperties
91
+ delete out.required
92
+ delete out.minProperties
93
+ delete out.maxProperties
94
+ delete out.dependentRequired
95
+ }
96
+
97
+ if (Array.isArray(out.enum)) {
98
+ const invalidEnum = out.enum.length === 0 ||
99
+ (resolvedType && resolvedType !== "string") ||
100
+ out.enum.some((item) => typeof item !== "string" || item.length === 0)
101
+ if (invalidEnum) {
102
+ if (out.enum.length) {
103
+ appendSchemaHint(out, `Allowed values: ${out.enum.map((item) => JSON.stringify(item)).join(", ")}`)
104
+ }
105
+ delete out.enum
106
+ }
107
+ }
108
+
109
+ if (out.const !== undefined && (typeof out.const !== "string" || out.const.length === 0 || (resolvedType && resolvedType !== "string"))) {
110
+ appendSchemaHint(out, `Must equal: ${JSON.stringify(out.const)}`)
111
+ delete out.const
112
+ }
113
+
114
+ if (out.properties && typeof out.properties === "object" && !Array.isArray(out.properties)) {
115
+ out.properties = Object.fromEntries(
116
+ Object.entries(out.properties).map(([key, value]) => [key, sanitizeInputSchema(value)]),
117
+ )
118
+ if (Array.isArray(out.required)) {
119
+ const filtered = out.required.filter((key) => typeof key === "string" && Object.hasOwn(out.properties, key))
120
+ if (filtered.length) out.required = filtered
121
+ else delete out.required
122
+ }
123
+ }
124
+ if (out.patternProperties && typeof out.patternProperties === "object" && !Array.isArray(out.patternProperties)) {
125
+ out.patternProperties = Object.fromEntries(
126
+ Object.entries(out.patternProperties).map(([key, value]) => [key, sanitizeInputSchema(value)]),
127
+ )
128
+ }
129
+ if (out.additionalProperties && typeof out.additionalProperties === "object" && !Array.isArray(out.additionalProperties)) {
130
+ out.additionalProperties = sanitizeInputSchema(out.additionalProperties)
131
+ }
132
+ if (Array.isArray(out.items)) {
133
+ out.items = out.items.map((item) => sanitizeInputSchema(item))
134
+ } else if (out.items && typeof out.items === "object") {
135
+ out.items = sanitizeInputSchema(out.items)
136
+ }
137
+ if (Array.isArray(out.prefixItems)) {
138
+ out.prefixItems = out.prefixItems.map((item) => sanitizeInputSchema(item))
139
+ }
140
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
141
+ if (Array.isArray(out[key])) out[key] = out[key].map((item) => sanitizeInputSchema(item))
142
+ }
143
+ if (out.not && typeof out.not === "object" && !Array.isArray(out.not)) {
144
+ out.not = sanitizeInputSchema(out.not)
145
+ }
146
+ for (const defsKey of ["$defs", "definitions"]) {
147
+ if (out[defsKey] && typeof out[defsKey] === "object" && !Array.isArray(out[defsKey])) {
148
+ out[defsKey] = Object.fromEntries(
149
+ Object.entries(out[defsKey]).map(([key, value]) => [key, sanitizeInputSchema(value)]),
150
+ )
151
+ }
152
+ }
153
+ for (const key of ["propertyNames", "contains", "if", "then", "else", "unevaluatedProperties", "unevaluatedItems"]) {
154
+ if (out[key] && typeof out[key] === "object" && !Array.isArray(out[key])) {
155
+ out[key] = sanitizeInputSchema(out[key])
156
+ }
157
+ }
158
+ if (out.dependentSchemas && typeof out.dependentSchemas === "object" && !Array.isArray(out.dependentSchemas)) {
159
+ out.dependentSchemas = Object.fromEntries(
160
+ Object.entries(out.dependentSchemas).map(([key, value]) => [key, sanitizeInputSchema(value)]),
161
+ )
162
+ }
163
+ // agy (Go/RE2) will reject the whole toolbox if any pattern is only valid as
164
+ // ECMA-262. Translate or drop those patterns here; tool-call arguments in
165
+ // the response are plain JSON and do not need a reverse transform.
166
+ sanitizePatternFields(out)
167
+ // After patterns: a map whose keys were all dropped is no longer a
168
+ // patternProperties object. Say the remaining empty object is open.
169
+ if (emptyObjectIsOpen(out)) out.additionalProperties = true
170
+ return out
171
+ }
172
+
173
+ // mcpToolsOf is the body's tools as MCP tools; none when it declares none
174
+ // or turns them off (tool_choice "none"). A tool_choice naming one function
175
+ // offers only that one. A tool agy can't be given (no name, a name used
176
+ // twice, a schema that isn't an object) is refused, never dropped.
177
+ export function mcpToolsOf(body) {
178
+ const list = body?.tools
179
+ if (!Array.isArray(list) || !list.length) return []
180
+ const choice = body.tool_choice
181
+ if (choice === "none" || choice?.type === "none") return []
182
+ const selected = choice?.type === "function" ? choice.function?.name ?? choice.name : null
183
+ const seen = new Set()
184
+ const tools = []
185
+ for (const entry of list) {
186
+ if (entry?.type && entry.type !== "function") throw refuse(`agy-tui offers function tools only; the request has a ${entry.type} tool`)
187
+ const fn = entry?.function ?? entry
188
+ const name = fn?.name
189
+ if (typeof name !== "string" || !/^[A-Za-z0-9_.:-]{1,64}$/.test(name)) throw refuse(`a tool without a valid name${typeof name === "string" ? ` (${JSON.stringify(name.slice(0, 80))})` : ""}`)
190
+ if (seen.has(name)) throw refuse(`the tool ${name} is declared twice`)
191
+ seen.add(name)
192
+ if (selected && name !== selected) continue
193
+ const raw = fn.parameters ?? { type: "object", properties: {} }
194
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw refuse(`the tool ${name} has a schema that isn't an object`)
195
+ const inputSchema = ensureGeminiArrayItems(sanitizeInputSchema(expandToolSchema(raw)))
196
+ // agy adds a required toolSummary to every tool it loads, and strips it
197
+ // before the call: one the caller already requires would be twice
198
+ if (Array.isArray(inputSchema.required)) inputSchema.required = inputSchema.required.filter((k) => k !== "toolSummary")
199
+ if (inputSchema.type === undefined) inputSchema.type = "object"
200
+ tools.push({ name, description: typeof fn.description === "string" ? fn.description : "", inputSchema })
201
+ }
202
+ if (selected && !tools.length) throw refuse(`tool_choice names ${selected}, which the request doesn't declare`)
203
+ return fitTools(tools)
204
+ }