opencode-gemini-app 0.0.0-stage → 0.1.0
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/DISCLAIMER.md +17 -0
- package/LICENSE +21 -0
- package/README.md +44 -2
- package/extensions/opencode/auth.js +324 -0
- package/extensions/opencode/fetch.js +494 -0
- package/extensions/opencode/index.js +27 -0
- package/extensions/opencode/models.js +84 -0
- package/extensions/pi/auth.js +215 -0
- package/native-wire/consumer-tool-codec.mjs +239 -0
- package/native-wire/oauth-loopback.mjs +175 -0
- package/native-wire/protobuf.mjs +133 -0
- package/native-wire/robin-current.mjs +172 -0
- package/package.json +75 -4
- package/src/gateway/automatic-recovery.mjs +64 -0
- package/src/gateway/image-download.mjs +110 -0
- package/src/gateway/image-upload.mjs +219 -0
- package/src/gateway/native-diagnostic.mjs +189 -0
- package/src/gateway/native-evidence.mjs +113 -0
- package/src/gateway/native-response-limits.mjs +8 -0
- package/src/gateway/native-search-citations.mjs +196 -0
- package/src/gateway/native-search-diagnostic.mjs +282 -0
- package/src/gateway/native-search-metadata.mjs +749 -0
- package/src/gateway/native-transport.mjs +375 -0
- package/src/gateway/oauth-client-defaults.mjs +12 -0
- package/src/gateway/oauth-identity.mjs +67 -0
- package/src/gateway/outbound-proxy.mjs +320 -0
- package/src/gateway/output-recovery.mjs +48 -0
- package/src/gateway/quota-failover.mjs +14 -0
- package/src/gateway/quota-transport.mjs +37 -0
- package/src/gateway/quota.mjs +181 -0
- package/src/gateway/soft-error.mjs +25 -0
- package/src/gateway/structured-output.mjs +157 -0
- package/src/gateway/subscription.mjs +51 -0
- package/src/gateway/terms.mjs +126 -0
- package/src/image-input.mjs +137 -0
- package/src/image-url.mjs +21 -0
- package/src/native-provider.mjs +681 -0
- package/src/openai-contract.mjs +576 -0
- package/src/openai-usage.mjs +66 -0
- package/src/prompt-tool-schema.mjs +391 -0
- package/src/responses-tool-namespaces.mjs +84 -0
- package/src/tool-protocol.mjs +348 -0
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
export const PROMPT_TOOL_LIMITS = Object.freeze({
|
|
2
|
+
bytes: 256 * 1024,
|
|
3
|
+
declarationBytes: 512 * 1024,
|
|
4
|
+
depth: 16,
|
|
5
|
+
nodes: 4096,
|
|
6
|
+
declarationNodes: 16384,
|
|
7
|
+
tools: 256,
|
|
8
|
+
work: 65536,
|
|
9
|
+
});
|
|
10
|
+
const LIMITS = PROMPT_TOOL_LIMITS;
|
|
11
|
+
|
|
12
|
+
function error(code, message = code, status = 400, param = null) {
|
|
13
|
+
const e = new Error(message); e.code = code; e.status = status;
|
|
14
|
+
if (param !== null) e.param = param;
|
|
15
|
+
return e;
|
|
16
|
+
}
|
|
17
|
+
const declaration = (message) => error('INVALID_TOOL_DECLARATION', message);
|
|
18
|
+
const badSchema = (message) => error('UNSUPPORTED_TOOL_SCHEMA', message);
|
|
19
|
+
|
|
20
|
+
function jsonTree(
|
|
21
|
+
value,
|
|
22
|
+
state,
|
|
23
|
+
depth = 0,
|
|
24
|
+
seen = new Set(),
|
|
25
|
+
maxDepth = LIMITS.depth,
|
|
26
|
+
limits = { maxNodes: LIMITS.nodes, maxBytes: LIMITS.bytes, paramPrefix: 'tools' },
|
|
27
|
+
) {
|
|
28
|
+
const { maxNodes = LIMITS.nodes, maxBytes = LIMITS.bytes, paramPrefix = 'tools' } = limits;
|
|
29
|
+
if (++state.nodes > maxNodes) throw error('TOOL_SIZE_LIMIT', 'TOOL_SIZE_LIMIT', 400, paramPrefix ? `${paramPrefix}.nodes` : null);
|
|
30
|
+
if (depth > maxDepth) throw error('TOOL_SIZE_LIMIT', 'TOOL_SIZE_LIMIT', 400, paramPrefix ? `${paramPrefix}.depth` : null);
|
|
31
|
+
const add = n => {
|
|
32
|
+
state.bytes = (state.bytes || 0) + n;
|
|
33
|
+
if (state.bytes > maxBytes) throw error('TOOL_SIZE_LIMIT', 'TOOL_SIZE_LIMIT', 400, paramPrefix ? `${paramPrefix}.bytes` : null);
|
|
34
|
+
};
|
|
35
|
+
if (typeof value === 'string') { if (Buffer.from(value).toString('utf8') !== value) throw error('INVALID_TOOL_STRING'); add(Buffer.byteLength(value)); return; }
|
|
36
|
+
if (value === null || typeof value === 'boolean') { add(4); return; }
|
|
37
|
+
if (typeof value === 'number') { if (!Number.isFinite(value)) throw declaration('Non-finite JSON number'); add(8); return; }
|
|
38
|
+
if (typeof value !== 'object') throw declaration('Value is not plain JSON');
|
|
39
|
+
if (seen.has(value)) throw declaration('Cyclic JSON value');
|
|
40
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw declaration('Non-plain JSON object');
|
|
41
|
+
seen.add(value);
|
|
42
|
+
if (Array.isArray(value)) {
|
|
43
|
+
for (let i = 0; i < value.length; i++) { if (!Object.hasOwn(value, i)) throw declaration('Sparse array'); jsonTree(value[i], state, depth + 1, seen, maxDepth, limits); }
|
|
44
|
+
} else for (const key of Object.keys(value)) { add(Buffer.byteLength(key)); jsonTree(value[key], state, depth + 1, seen, maxDepth, limits); }
|
|
45
|
+
seen.delete(value);
|
|
46
|
+
}
|
|
47
|
+
function clone(v) { return Array.isArray(v) ? v.map(clone) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, clone(x)])) : v; }
|
|
48
|
+
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
49
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
|
|
50
|
+
const SCHEMA_ANNOTATIONS = new Set([
|
|
51
|
+
'$schema', '$id', 'title', 'default', 'examples', 'deprecated', 'readOnly', 'writeOnly', 'format',
|
|
52
|
+
]);
|
|
53
|
+
export function stripSchemaAnnotations(value, seen = new Map()) {
|
|
54
|
+
if (!isPlainObject(value)) return value;
|
|
55
|
+
if (seen.has(value)) return seen.get(value);
|
|
56
|
+
const out = {};
|
|
57
|
+
seen.set(value, out);
|
|
58
|
+
for (const [key, child] of Object.entries(value)) {
|
|
59
|
+
if (SCHEMA_ANNOTATIONS.has(key)) continue;
|
|
60
|
+
if (['properties', '$defs', 'definitions', 'patternProperties'].includes(key) && isPlainObject(child)) {
|
|
61
|
+
out[key] = Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, stripSchemaAnnotations(schema, seen)]));
|
|
62
|
+
} else if (['items', 'additionalProperties', 'additionalItems', 'not', 'if', 'then', 'else'].includes(key)) {
|
|
63
|
+
out[key] = Array.isArray(child) ? child.map((item) => stripSchemaAnnotations(item, seen)) : stripSchemaAnnotations(child, seen);
|
|
64
|
+
} else if (['anyOf', 'oneOf', 'allOf', 'prefixItems'].includes(key) && Array.isArray(child)) {
|
|
65
|
+
out[key] = child.map((item) => stripSchemaAnnotations(item, seen));
|
|
66
|
+
} else {
|
|
67
|
+
out[key] = child;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
const types = new Set(['null','boolean','object','array','number','integer','string']);
|
|
73
|
+
function schemaType(s) {
|
|
74
|
+
if (!own(s, 'type')) return null;
|
|
75
|
+
const ts = Array.isArray(s.type) ? s.type : [s.type];
|
|
76
|
+
if (!ts.length || ts.some(t => typeof t !== 'string' || !types.has(t)) || new Set(ts).size !== ts.length) throw badSchema('Invalid schema type');
|
|
77
|
+
return ts;
|
|
78
|
+
}
|
|
79
|
+
function nonnegativeInt(s, k) { if (own(s,k) && (!Number.isSafeInteger(s[k]) || s[k] < 0)) throw badSchema(`Invalid ${k}`); }
|
|
80
|
+
function finite(s,k) { if (own(s,k) && (typeof s[k] !== 'number' || !Number.isFinite(s[k]))) throw badSchema(`Invalid ${k}`); }
|
|
81
|
+
function literalValid(v) { try { jsonTree(v,{nodes:0}); return true; } catch { return false; } }
|
|
82
|
+
const DIRECT_SCHEMA_STEP_KEYS = new Set(['not', 'additionalProperties', 'additionalItems']);
|
|
83
|
+
const MAPPED_SCHEMA_STEP_KEYS = new Set(['properties', '$defs', 'definitions', 'patternProperties']);
|
|
84
|
+
const ARRAY_SCHEMA_STEP_KEYS = new Set(['anyOf', 'oneOf', 'allOf', 'prefixItems']);
|
|
85
|
+
|
|
86
|
+
function isCanonicalIndexToken(part) {
|
|
87
|
+
return /^(?:0|[1-9]\d*)$/.test(part);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function definition(root, ref, { strictPointer = false } = {}) {
|
|
91
|
+
if (typeof ref !== 'string' || !ref.startsWith('#/')) throw badSchema('External references are unsupported');
|
|
92
|
+
const parts = ref.slice(2).split('/').map(x => x.replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
93
|
+
if (!['$defs', 'definitions'].includes(parts[0]) || parts.length < 2 || parts.length > 36) throw badSchema('Unknown local reference');
|
|
94
|
+
let target = root;
|
|
95
|
+
for (let i = 0; i < parts.length;) {
|
|
96
|
+
const part = parts[i];
|
|
97
|
+
if (!target || typeof target !== 'object' || Array.isArray(target) || !own(target, part)) throw badSchema('Unknown local reference');
|
|
98
|
+
if (i === 0) {
|
|
99
|
+
const container = target[part];
|
|
100
|
+
const defName = parts[1];
|
|
101
|
+
if (!container || typeof container !== 'object' || Array.isArray(container) || !own(container, defName)) throw badSchema('Unknown local reference');
|
|
102
|
+
target = container[defName];
|
|
103
|
+
i = 2;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (DIRECT_SCHEMA_STEP_KEYS.has(part)) {
|
|
107
|
+
target = target[part];
|
|
108
|
+
i += 1;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (part === 'items') {
|
|
112
|
+
if (Array.isArray(target.items)) {
|
|
113
|
+
if (i + 1 >= parts.length || !isCanonicalIndexToken(parts[i + 1])) throw badSchema('Unknown local reference');
|
|
114
|
+
const idx = Number(parts[i + 1]);
|
|
115
|
+
if (idx >= target.items.length) throw badSchema('Unknown local reference');
|
|
116
|
+
target = target.items[idx];
|
|
117
|
+
i += 2;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
target = target.items;
|
|
121
|
+
i += 1;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (MAPPED_SCHEMA_STEP_KEYS.has(part)) {
|
|
125
|
+
if (i + 1 >= parts.length) throw badSchema('Unknown local reference');
|
|
126
|
+
const key = parts[i + 1];
|
|
127
|
+
if (part === 'patternProperties' && strictPointer && key !== '^(.*)$' && key !== '^.*$') {
|
|
128
|
+
throw badSchema('Unsupported patternProperties pattern');
|
|
129
|
+
}
|
|
130
|
+
const map = target[part];
|
|
131
|
+
if (!map || typeof map !== 'object' || Array.isArray(map) || !own(map, key)) throw badSchema('Unknown local reference');
|
|
132
|
+
target = map[key];
|
|
133
|
+
i += 2;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (ARRAY_SCHEMA_STEP_KEYS.has(part)) {
|
|
137
|
+
if (i + 1 >= parts.length || !isCanonicalIndexToken(parts[i + 1])) throw badSchema('Unknown local reference');
|
|
138
|
+
const arr = target[part];
|
|
139
|
+
const idx = Number(parts[i + 1]);
|
|
140
|
+
if (!Array.isArray(arr) || idx >= arr.length) throw badSchema('Unknown local reference');
|
|
141
|
+
target = arr[idx];
|
|
142
|
+
i += 2;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
throw badSchema('Invalid reference target');
|
|
146
|
+
}
|
|
147
|
+
if (typeof target !== 'boolean' && (!target || typeof target !== 'object' || Array.isArray(target))) throw badSchema('Invalid reference target');
|
|
148
|
+
return target;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const OUTPUT_SCHEMA_KEYWORDS = new Set([
|
|
152
|
+
'$ref', '$defs', 'definitions',
|
|
153
|
+
'type', 'nullable', 'const', 'enum',
|
|
154
|
+
'allOf', 'anyOf', 'oneOf', 'not',
|
|
155
|
+
'minLength', 'maxLength',
|
|
156
|
+
'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf',
|
|
157
|
+
'minItems', 'maxItems', 'uniqueItems', 'items', 'prefixItems', 'additionalItems',
|
|
158
|
+
'minProperties', 'maxProperties', 'required', 'properties', 'additionalProperties', 'patternProperties',
|
|
159
|
+
]);
|
|
160
|
+
const OUTPUT_SCHEMA_METADATA = new Set([
|
|
161
|
+
...SCHEMA_ANNOTATIONS,
|
|
162
|
+
'description',
|
|
163
|
+
'$comment',
|
|
164
|
+
]);
|
|
165
|
+
|
|
166
|
+
function checkSchema(root, { rejectUnsupportedKeywords = false } = {}) {
|
|
167
|
+
const defs = new Map();
|
|
168
|
+
const walked = new WeakSet();
|
|
169
|
+
function walk(s, depth=0, visited=new Set()) {
|
|
170
|
+
if (depth > LIMITS.depth) throw error('TOOL_SIZE_LIMIT', 'TOOL_SIZE_LIMIT', 400, 'tools.depth');
|
|
171
|
+
if (typeof s === 'boolean') return;
|
|
172
|
+
if (!s || typeof s !== 'object' || Array.isArray(s)) throw badSchema('Schema must be an object');
|
|
173
|
+
if (visited.has(s)) throw badSchema('Cyclic schema'); visited.add(s); walked.add(s);
|
|
174
|
+
if (rejectUnsupportedKeywords) {
|
|
175
|
+
for (const k of Object.keys(s)) {
|
|
176
|
+
if (!OUTPUT_SCHEMA_KEYWORDS.has(k) && !OUTPUT_SCHEMA_METADATA.has(k)) {
|
|
177
|
+
throw badSchema(`Unsupported output schema keyword: ${/^[A-Za-z0-9_$-]{1,64}$/.test(k) ? k : 'unknown'}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (own(s, 'description') && typeof s.description !== 'string') throw badSchema('Invalid schema description');
|
|
181
|
+
if (own(s, '$comment') && typeof s.$comment !== 'string') throw badSchema('Invalid schema $comment');
|
|
182
|
+
if (own(s, 'additionalItems') && !Array.isArray(s.items)) throw badSchema('additionalItems requires tuple items array');
|
|
183
|
+
if (own(s, 'prefixItems') && Array.isArray(s.items)) throw badSchema('Cannot combine prefixItems with tuple items array');
|
|
184
|
+
}
|
|
185
|
+
schemaType(s);
|
|
186
|
+
if (own(s,'nullable') && typeof s.nullable !== 'boolean') throw badSchema('Invalid nullable');
|
|
187
|
+
if (own(s,'const') && !literalValid(s.const)) throw badSchema('Invalid const');
|
|
188
|
+
if (own(s,'enum') && (!Array.isArray(s.enum) || !s.enum.length || s.enum.some(v => !literalValid(v)))) throw badSchema('Invalid enum');
|
|
189
|
+
for (const k of ['minLength','maxLength','minItems','maxItems','minProperties','maxProperties']) nonnegativeInt(s,k);
|
|
190
|
+
for (const k of ['minimum','maximum','exclusiveMinimum','exclusiveMaximum','multipleOf']) finite(s,k);
|
|
191
|
+
if (s.multipleOf !== undefined && s.multipleOf <= 0) throw badSchema('Invalid multipleOf');
|
|
192
|
+
if (typeof s.uniqueItems === 'string' || typeof s.uniqueItems === 'number' || (own(s,'uniqueItems') && typeof s.uniqueItems !== 'boolean')) throw badSchema('Invalid uniqueItems');
|
|
193
|
+
if (own(s,'required') && (!Array.isArray(s.required) || s.required.some(x => typeof x !== 'string') || new Set(s.required).size !== s.required.length)) throw badSchema('Invalid required');
|
|
194
|
+
if (own(s,'properties') && (!s.properties || typeof s.properties !== 'object' || Array.isArray(s.properties))) throw badSchema('Invalid properties');
|
|
195
|
+
if (own(s,'additionalProperties') && typeof s.additionalProperties !== 'boolean' && (!s.additionalProperties || typeof s.additionalProperties !== 'object' || Array.isArray(s.additionalProperties))) throw badSchema('Invalid additionalProperties');
|
|
196
|
+
for (const k of ['anyOf','oneOf','allOf']) if (own(s,k) && (!Array.isArray(s[k]) || !s[k].length)) throw badSchema(`Invalid ${k}`);
|
|
197
|
+
if (own(s,'items') && typeof s.items !== 'boolean' && (!s.items || typeof s.items !== 'object')) throw badSchema('Invalid items');
|
|
198
|
+
if (own(s,'prefixItems') && !Array.isArray(s.prefixItems)) throw badSchema('Invalid prefixItems');
|
|
199
|
+
for (const k of ['$defs','definitions']) if (own(s,k) && (!s[k] || typeof s[k] !== 'object' || Array.isArray(s[k]))) throw badSchema('Invalid definitions');
|
|
200
|
+
if (own(s,'patternProperties') && (!s.patternProperties || typeof s.patternProperties !== 'object' || Array.isArray(s.patternProperties))) throw badSchema('Invalid patternProperties');
|
|
201
|
+
if (own(s,'$defs') && s.$defs && typeof s.$defs==='object') for (const [k,v] of Object.entries(s.$defs)) defs.set(`/$defs/${k}`,v);
|
|
202
|
+
if (own(s,'definitions') && s.definitions && typeof s.definitions==='object') for (const [k,v] of Object.entries(s.definitions)) defs.set(`/definitions/${k}`,v);
|
|
203
|
+
for (const k of ['properties','$defs','definitions']) if (s[k] && typeof s[k]==='object') for (const v of Object.values(s[k])) walk(v,depth+1,visited);
|
|
204
|
+
for (const k of ['items','additionalProperties','additionalItems','not']) if (own(s,k)) { const children = k === 'items' && Array.isArray(s[k]) ? s[k] : [s[k]]; for (const child of children) walk(child,depth+1,visited); }
|
|
205
|
+
if (s.prefixItems) for (const child of s.prefixItems) walk(child,depth+1,visited);
|
|
206
|
+
for (const k of ['anyOf','oneOf','allOf']) if (s[k]) for (const v of s[k]) walk(v,depth+1,visited);
|
|
207
|
+
if (s.patternProperties && typeof s.patternProperties==='object' && !Array.isArray(s.patternProperties)) for (const [p,v] of Object.entries(s.patternProperties)) { if (p !== '^(.*)$' && p !== '^.*$') { if (rejectUnsupportedKeywords) throw badSchema('Unsupported patternProperties pattern'); continue; } walk(v,depth+1,visited); }
|
|
208
|
+
visited.delete(s);
|
|
209
|
+
}
|
|
210
|
+
walk(root);
|
|
211
|
+
// Validate all local references syntactically and resolve only known definition pointers.
|
|
212
|
+
function refs(s, seen=new Set()) {
|
|
213
|
+
if (!s || typeof s!=='object' || seen.has(s)) return; seen.add(s);
|
|
214
|
+
if (own(s,'$ref')) {
|
|
215
|
+
const target = definition(root, s.$ref, { strictPointer: rejectUnsupportedKeywords });
|
|
216
|
+
if (target && typeof target === 'object' && !walked.has(target)) walk(target, 0, new Set());
|
|
217
|
+
refs(target, seen);
|
|
218
|
+
}
|
|
219
|
+
for (const k of ['properties','$defs','definitions']) if (s[k] && typeof s[k]==='object') for(const v of Object.values(s[k])) refs(v,seen);
|
|
220
|
+
for (const k of ['items','additionalProperties','additionalItems','not']) if (own(s,k)) { const children = k === 'items' && Array.isArray(s[k]) ? s[k] : [s[k]]; for (const child of children) refs(child,seen); }
|
|
221
|
+
if (s.prefixItems) for (const child of s.prefixItems) refs(child,seen);
|
|
222
|
+
for (const k of ['anyOf','oneOf','allOf']) if(s[k]) for(const v of s[k]) refs(v,seen);
|
|
223
|
+
if(s.patternProperties && typeof s.patternProperties==='object') for(const [p,v] of Object.entries(s.patternProperties)) if(p==='^(.*)$'||p==='^.*$') refs(v,seen);
|
|
224
|
+
}
|
|
225
|
+
refs(root);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Unknown optional metadata/validation keywords are ignored deliberately; known
|
|
229
|
+
// constraints above are checked strictly. Arbitrary regex/pattern hints are never executed.
|
|
230
|
+
export function compilePromptTools(tools = []) {
|
|
231
|
+
if (!Array.isArray(tools)) throw declaration('Tools must be an array');
|
|
232
|
+
if (tools.length > LIMITS.tools) throw error('TOOL_SIZE_LIMIT', 'TOOL_SIZE_LIMIT', 400, 'tools.count');
|
|
233
|
+
const state = { nodes: 0 };
|
|
234
|
+
jsonTree(tools, state, 0, new Set(), LIMITS.depth * 3 + 4, {
|
|
235
|
+
maxNodes: LIMITS.declarationNodes,
|
|
236
|
+
maxBytes: LIMITS.declarationBytes,
|
|
237
|
+
paramPrefix: 'tools',
|
|
238
|
+
});
|
|
239
|
+
let text; try { text = JSON.stringify(tools); } catch { throw declaration('Tools are not JSON serializable'); }
|
|
240
|
+
if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > LIMITS.declarationBytes) {
|
|
241
|
+
throw error('TOOL_SIZE_LIMIT', 'TOOL_SIZE_LIMIT', 400, 'tools.bytes');
|
|
242
|
+
}
|
|
243
|
+
const out = new Map();
|
|
244
|
+
for (const tool of tools) {
|
|
245
|
+
if (!tool || typeof tool !== 'object' || Array.isArray(tool) || tool.type !== 'function') throw error('UNSUPPORTED_TOOL_TYPE');
|
|
246
|
+
for (const k of Object.keys(tool)) if (!['type','function'].includes(k)) throw declaration(`Unexpected tool key ${k}`);
|
|
247
|
+
const fn=tool.function;
|
|
248
|
+
if (!fn || typeof fn!=='object' || Array.isArray(fn)) throw declaration('Invalid function declaration');
|
|
249
|
+
for(const k of Object.keys(fn)) if(!['name','description','parameters','strict'].includes(k)) throw declaration(`Unexpected function key ${k}`);
|
|
250
|
+
if(typeof fn.name!=='string'||!/^[A-Za-z0-9_-]{1,64}$/.test(fn.name)) throw declaration('Invalid function name');
|
|
251
|
+
if(out.has(fn.name)) throw declaration('Duplicate function name');
|
|
252
|
+
if(own(fn,'description')&&typeof fn.description!=='string') throw declaration('Invalid description');
|
|
253
|
+
if(own(fn,'strict')&&typeof fn.strict!=='boolean') throw declaration('Invalid strict hint');
|
|
254
|
+
const parameters=own(fn,'parameters')?fn.parameters:{type:'object'};
|
|
255
|
+
jsonTree(parameters, { nodes: 0 }, 0, new Set(), LIMITS.depth * 3 + 4, {
|
|
256
|
+
maxNodes: LIMITS.nodes,
|
|
257
|
+
maxBytes: LIMITS.bytes,
|
|
258
|
+
paramPrefix: 'tools',
|
|
259
|
+
});
|
|
260
|
+
checkSchema(parameters);
|
|
261
|
+
out.set(fn.name,{name:fn.name,parameters:clone(parameters)});
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function mapOutputSchemaError(e) {
|
|
267
|
+
if (e?.code === 'TOOL_SIZE_LIMIT') return error('OUTPUT_SCHEMA_SIZE_LIMIT', e.message || 'Output schema exceeds size limit', 400);
|
|
268
|
+
if (e?.code === 'UNSUPPORTED_TOOL_SCHEMA') return error('UNSUPPORTED_OUTPUT_SCHEMA', e.message || 'Unsupported output schema', 400);
|
|
269
|
+
return error('INVALID_RESPONSE_FORMAT', e?.message || 'Invalid output schema', 400);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Validate and clone a standalone structured output JSON Schema object. */
|
|
273
|
+
export function compileOutputSchema(schema) {
|
|
274
|
+
if (!isPlainObject(schema)) throw error('INVALID_RESPONSE_FORMAT', 'Output schema must be a plain JSON object', 400);
|
|
275
|
+
try {
|
|
276
|
+
jsonTree(schema, { nodes: 0 }, 0, new Set(), LIMITS.depth * 3 + 4);
|
|
277
|
+
} catch (e) {
|
|
278
|
+
throw mapOutputSchemaError(e);
|
|
279
|
+
}
|
|
280
|
+
let text;
|
|
281
|
+
try { text = JSON.stringify(schema); } catch { throw error('INVALID_RESPONSE_FORMAT', 'Output schema is not JSON serializable', 400); }
|
|
282
|
+
if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > LIMITS.bytes) {
|
|
283
|
+
throw error('OUTPUT_SCHEMA_SIZE_LIMIT', 'Output schema exceeds 256 KiB budget', 400);
|
|
284
|
+
}
|
|
285
|
+
try {
|
|
286
|
+
checkSchema(schema, { rejectUnsupportedKeywords: true });
|
|
287
|
+
} catch (e) {
|
|
288
|
+
throw error(e?.code === 'TOOL_SIZE_LIMIT' ? 'OUTPUT_SCHEMA_SIZE_LIMIT' : 'UNSUPPORTED_OUTPUT_SCHEMA', e?.message || 'Unsupported output schema', 400);
|
|
289
|
+
}
|
|
290
|
+
return clone(schema);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function parseFiniteDecimal(num) {
|
|
294
|
+
if (num === 0) return { coeff: 0n, exp: 0 };
|
|
295
|
+
const raw = Math.abs(num).toString();
|
|
296
|
+
const eIdx = raw.indexOf('e');
|
|
297
|
+
const mantissa = eIdx >= 0 ? raw.slice(0, eIdx) : raw;
|
|
298
|
+
const baseExp = eIdx >= 0 ? Number.parseInt(raw.slice(eIdx + 1), 10) : 0;
|
|
299
|
+
const dotIdx = mantissa.indexOf('.');
|
|
300
|
+
const fracLen = dotIdx >= 0 ? mantissa.length - dotIdx - 1 : 0;
|
|
301
|
+
const digits = dotIdx >= 0 ? mantissa.slice(0, dotIdx) + mantissa.slice(dotIdx + 1) : mantissa;
|
|
302
|
+
return { coeff: BigInt(digits), exp: baseExp - fracLen };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function isExactMultipleOf(value, multiple) {
|
|
306
|
+
if (value === 0) return true;
|
|
307
|
+
if (!Number.isFinite(value) || !Number.isFinite(multiple) || multiple <= 0) return false;
|
|
308
|
+
const v = parseFiniteDecimal(value);
|
|
309
|
+
const m = parseFiniteDecimal(multiple);
|
|
310
|
+
const expDiff = Math.abs(v.exp - m.exp);
|
|
311
|
+
if (expDiff > 1000) return false;
|
|
312
|
+
const scale = 10n ** BigInt(expDiff);
|
|
313
|
+
const vCoeff = v.exp > m.exp ? v.coeff * scale : v.coeff;
|
|
314
|
+
const mCoeff = m.exp > v.exp ? m.coeff * scale : m.coeff;
|
|
315
|
+
return mCoeff !== 0n && vCoeff % mCoeff === 0n;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function validateValueAgainstSchema(value, schema, mismatchCode, mismatchMessage, { strictApplicability = false } = {}) {
|
|
319
|
+
let work=LIMITS.work, exhausted=false;
|
|
320
|
+
const mismatch=()=>{ throw error(mismatchCode,mismatchMessage,502); };
|
|
321
|
+
const take=(n=1)=>{ work-=n; if(work<0){exhausted=true;mismatch();} };
|
|
322
|
+
function equal(a,b) {
|
|
323
|
+
take();
|
|
324
|
+
if(typeof a==='string'&&typeof b==='string') take(Math.ceil((a.length+b.length)/64));
|
|
325
|
+
if(a===b)return true;
|
|
326
|
+
if(!a||!b||typeof a!=='object'||typeof b!=='object'||Array.isArray(a)!==Array.isArray(b))return false;
|
|
327
|
+
const ak=Object.keys(a),bk=Object.keys(b);
|
|
328
|
+
return ak.length===bk.length&&ak.every(k=>own(b,k)&&equal(a[k],b[k]));
|
|
329
|
+
}
|
|
330
|
+
function canonical(v) {
|
|
331
|
+
take();
|
|
332
|
+
if(typeof v==='string')take(Math.ceil(v.length/64));
|
|
333
|
+
if(Array.isArray(v))return '['+v.map(canonical).join(',')+']';
|
|
334
|
+
if(v&&typeof v==='object')return '{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}';
|
|
335
|
+
return JSON.stringify(v);
|
|
336
|
+
}
|
|
337
|
+
try { jsonTree(value,{nodes:0}); } catch { mismatch(); }
|
|
338
|
+
const root=schema;
|
|
339
|
+
function visit(v,s,depth=0) {
|
|
340
|
+
take(); if(depth>LIMITS.depth){exhausted=true;mismatch();}
|
|
341
|
+
if(s===true)return;if(s===false)mismatch();
|
|
342
|
+
if(v===null&&s.nullable===true)return;
|
|
343
|
+
if(own(s,'$ref'))visit(v,definition(root,s.$ref,{strictPointer:strictApplicability}),depth+1);
|
|
344
|
+
if(own(s,'const')&&!equal(v,s.const))mismatch();
|
|
345
|
+
if(s.enum&&!s.enum.some(x=>equal(v,x)))mismatch();
|
|
346
|
+
if(s.allOf)for(const x of s.allOf)visit(v,x,depth+1);
|
|
347
|
+
if(own(s,'not')){let matched=true;try{visit(v,s.not,depth+1);}catch(e){if(e.code!==mismatchCode||exhausted)throw e;matched=false;}if(matched)mismatch();}
|
|
348
|
+
for(const k of ['anyOf','oneOf'])if(s[k]){let n=0;for(const x of s[k]){try{visit(v,x,depth+1);n++;if(k==='anyOf')break;}catch(e){if(e.code!==mismatchCode||exhausted)throw e;}}if(k==='anyOf'?n<1:n!==1)mismatch();}
|
|
349
|
+
let ts=schemaType(s);if(!ts&&!strictApplicability)ts=s.properties||s.required||s.additionalProperties!==undefined||s.patternProperties?['object']:null;
|
|
350
|
+
const match=t=>t==='null'?v===null:t==='boolean'?typeof v==='boolean':t==='string'?typeof v==='string':t==='number'?typeof v==='number'&&Number.isFinite(v):t==='integer'?Number.isSafeInteger(v):t==='array'?Array.isArray(v):t==='object'?v!==null&&typeof v==='object'&&!Array.isArray(v):false;
|
|
351
|
+
if(ts&&!ts.some(match))mismatch();
|
|
352
|
+
if(typeof v==='string'){const n=[...v].length;if(s.minLength!==undefined&&n<s.minLength||s.maxLength!==undefined&&n>s.maxLength)mismatch();}
|
|
353
|
+
if(typeof v==='number'){if(s.minimum!==undefined&&v<s.minimum||s.maximum!==undefined&&v>s.maximum||s.exclusiveMinimum!==undefined&&v<=s.exclusiveMinimum||s.exclusiveMaximum!==undefined&&v>=s.exclusiveMaximum||s.multipleOf!==undefined&&!isExactMultipleOf(v,s.multipleOf))mismatch();}
|
|
354
|
+
if(Array.isArray(v)){
|
|
355
|
+
if(s.minItems!==undefined&&v.length<s.minItems||s.maxItems!==undefined&&v.length>s.maxItems)mismatch();
|
|
356
|
+
if(s.uniqueItems&&new Set(v.map(canonical)).size!==v.length)mismatch();
|
|
357
|
+
const prefix=s.prefixItems||(Array.isArray(s.items)?s.items:[]);
|
|
358
|
+
for(let i=0;i<Math.min(v.length,prefix.length);i++)visit(v[i],prefix[i],depth+1);
|
|
359
|
+
const rest=Array.isArray(s.items)?s.additionalItems:s.items;
|
|
360
|
+
if(rest!==undefined)for(let i=prefix.length;i<v.length;i++)visit(v[i],rest,depth+1);
|
|
361
|
+
}
|
|
362
|
+
if(v&&typeof v==='object'&&!Array.isArray(v)){
|
|
363
|
+
const keys=Object.keys(v);if(s.minProperties!==undefined&&keys.length<s.minProperties||s.maxProperties!==undefined&&keys.length>s.maxProperties)mismatch();
|
|
364
|
+
for(const r of s.required||[])if(!own(v,r))mismatch();
|
|
365
|
+
for(const[k,x]of Object.entries(v)){
|
|
366
|
+
let covered=false;
|
|
367
|
+
if(s.properties&&own(s.properties,k)){visit(x,s.properties[k],depth+1);covered=true;}
|
|
368
|
+
for(const[p,ps]of Object.entries(s.patternProperties||{}))if(p==='^(.*)$'||p==='^.*$'){visit(x,ps,depth+1);covered=true;}
|
|
369
|
+
if(!covered&&s.additionalProperties!==undefined)visit(x,s.additionalProperties,depth+1);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
visit(value,schema);return true;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function validatePromptToolArguments(value, schema) {
|
|
377
|
+
jsonTree(schema,{nodes:0},0,new Set(),LIMITS.depth * 3 + 4);
|
|
378
|
+
checkSchema(schema);
|
|
379
|
+
return validateValueAgainstSchema(value, schema, 'TOOL_ARGUMENT_SCHEMA_MISMATCH', 'Tool arguments do not match schema');
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Validate parsed structured output JSON against a bounded JSON Schema. */
|
|
383
|
+
export function validateOutputValue(value, schema) {
|
|
384
|
+
try {
|
|
385
|
+
jsonTree(schema, { nodes: 0 }, 0, new Set(), LIMITS.depth * 3 + 4);
|
|
386
|
+
checkSchema(schema, { rejectUnsupportedKeywords: true });
|
|
387
|
+
} catch (e) {
|
|
388
|
+
throw mapOutputSchemaError(e);
|
|
389
|
+
}
|
|
390
|
+
return validateValueAgainstSchema(value, schema, 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH', 'Structured output does not match schema', { strictApplicability: true });
|
|
391
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Responses namespace adapter. The prompt protocol remains flat and caller-owned.
|
|
2
|
+
// Codex 0.148.0 ResponseItem uses function_call { namespace?, name, ... }.
|
|
3
|
+
// Internal aliases never appear on the Responses wire. Symbols cannot be supplied
|
|
4
|
+
// by JSON clients and survive canonical-body/result object spreads, not JSON output.
|
|
5
|
+
import { PROMPT_TOOL_LIMITS } from './prompt-tool-schema.mjs';
|
|
6
|
+
import { plainObject, protocolError } from './tool-protocol.mjs';
|
|
7
|
+
export const RESPONSE_TOOL_IDENTITIES = Symbol('responseToolIdentities');
|
|
8
|
+
const fail = (code, param = null) => { throw protocolError(code, 400, param); };
|
|
9
|
+
const keys = (value, allowed) => {
|
|
10
|
+
if (!plainObject(value)) fail('INVALID_TOOL_DECLARATION');
|
|
11
|
+
if (Object.keys(value).some(key => !allowed.includes(key))) fail('UNSUPPORTED_PARAMETER');
|
|
12
|
+
};
|
|
13
|
+
const name = value => {
|
|
14
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(value)) fail('INVALID_TOOL_DECLARATION');
|
|
15
|
+
return value;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function normalizeResponsesTools(payload) {
|
|
19
|
+
const source = payload.tools === undefined ? [] : payload.tools;
|
|
20
|
+
if (!Array.isArray(source)) fail('INVALID_TOOL_DECLARATION');
|
|
21
|
+
if (source.length > PROMPT_TOOL_LIMITS.tools) fail('TOOL_SIZE_LIMIT', 'tools.count');
|
|
22
|
+
if (Buffer.byteLength(JSON.stringify(source)) > PROMPT_TOOL_LIMITS.declarationBytes) fail('TOOL_SIZE_LIMIT', 'tools.bytes');
|
|
23
|
+
const declarations = [], namespaces = new Set(), reserved = new Set(), identities = new Map(), aliases = new Map();
|
|
24
|
+
const add = (tool, namespace, description) => {
|
|
25
|
+
keys(tool, ['type', 'name', 'description', 'parameters', 'strict']);
|
|
26
|
+
if (tool.type !== 'function') fail('UNSUPPORTED_TOOL_TYPE');
|
|
27
|
+
name(tool.name);
|
|
28
|
+
if (tool.description !== undefined && typeof tool.description !== 'string') fail('INVALID_TOOL_DECLARATION');
|
|
29
|
+
if (declarations.length >= PROMPT_TOOL_LIMITS.tools) fail('TOOL_SIZE_LIMIT', 'tools.count');
|
|
30
|
+
declarations.push({ tool, namespace, description });
|
|
31
|
+
if (namespace === undefined) reserved.add(tool.name);
|
|
32
|
+
};
|
|
33
|
+
for (const tool of source) {
|
|
34
|
+
if (plainObject(tool) && tool.type === 'namespace') {
|
|
35
|
+
keys(tool, ['type', 'name', 'description', 'tools']);
|
|
36
|
+
name(tool.name);
|
|
37
|
+
if (namespaces.has(tool.name) || typeof tool.description !== 'string' || !Array.isArray(tool.tools) || !tool.tools.length) fail('INVALID_TOOL_DECLARATION');
|
|
38
|
+
namespaces.add(tool.name);
|
|
39
|
+
for (const child of tool.tools) add(child, tool.name, tool.description);
|
|
40
|
+
} else add(tool);
|
|
41
|
+
}
|
|
42
|
+
// Reserve historical flat names too: an undeclared old call must not alias a
|
|
43
|
+
// currently declared namespace tool. History is not current authorization.
|
|
44
|
+
for (const item of Array.isArray(payload.input) ? payload.input : []) {
|
|
45
|
+
if (item?.type === 'function_call' && item.namespace == null && typeof item.name === 'string') reserved.add(item.name);
|
|
46
|
+
}
|
|
47
|
+
let nextAlias = 0;
|
|
48
|
+
const callName = (toolName, namespace) => {
|
|
49
|
+
name(toolName);
|
|
50
|
+
if (namespace == null) return toolName;
|
|
51
|
+
name(namespace);
|
|
52
|
+
const key = JSON.stringify([namespace, toolName]);
|
|
53
|
+
if (!aliases.has(key)) {
|
|
54
|
+
let alias;
|
|
55
|
+
do { alias = `ns_${nextAlias++}`; } while (reserved.has(alias));
|
|
56
|
+
reserved.add(alias); aliases.set(key, alias);
|
|
57
|
+
identities.set(alias, { namespace, name: toolName });
|
|
58
|
+
}
|
|
59
|
+
return aliases.get(key);
|
|
60
|
+
};
|
|
61
|
+
const tools = declarations.map(({ tool, namespace, description }) => {
|
|
62
|
+
const { type, ...fn } = tool;
|
|
63
|
+
const mapped = { ...fn, name: callName(fn.name, namespace) };
|
|
64
|
+
if (namespace !== undefined) mapped.description = `Namespace tool ${JSON.stringify({ namespace, name: fn.name })}. ${description}\n${fn.description ?? ''}`;
|
|
65
|
+
return { type, function: mapped };
|
|
66
|
+
});
|
|
67
|
+
let choice = payload.tool_choice ?? 'auto';
|
|
68
|
+
if (payload.tool_choice === null) fail('UNSUPPORTED_TOOL_CHOICE');
|
|
69
|
+
if (plainObject(choice)) {
|
|
70
|
+
// Only the established flat forced-choice shape is supported. No invented
|
|
71
|
+
// namespace selector: string auto/none/required apply to all flattened tools.
|
|
72
|
+
keys(choice, ['type', 'name']);
|
|
73
|
+
if (choice.type !== 'function') fail('UNSUPPORTED_TOOL_CHOICE');
|
|
74
|
+
choice = { type: 'function', function: { name: choice.name } };
|
|
75
|
+
// A flat selector must not accidentally select a generated alias.
|
|
76
|
+
if (identities.has(choice.function.name)) fail('UNDECLARED_TOOL');
|
|
77
|
+
}
|
|
78
|
+
return { tools, choice, callName, identities };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function responsesCallFields(call, metadata) {
|
|
82
|
+
const identity = metadata?.[RESPONSE_TOOL_IDENTITIES]?.get(call.function.name);
|
|
83
|
+
return { call_id: call.id, ...(identity ?? { name: call.function.name }), arguments: call.function.arguments };
|
|
84
|
+
}
|