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.
Files changed (42) hide show
  1. package/DISCLAIMER.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +44 -2
  4. package/extensions/opencode/auth.js +324 -0
  5. package/extensions/opencode/fetch.js +494 -0
  6. package/extensions/opencode/index.js +27 -0
  7. package/extensions/opencode/models.js +84 -0
  8. package/extensions/pi/auth.js +215 -0
  9. package/native-wire/consumer-tool-codec.mjs +239 -0
  10. package/native-wire/oauth-loopback.mjs +175 -0
  11. package/native-wire/protobuf.mjs +133 -0
  12. package/native-wire/robin-current.mjs +172 -0
  13. package/package.json +75 -4
  14. package/src/gateway/automatic-recovery.mjs +64 -0
  15. package/src/gateway/image-download.mjs +110 -0
  16. package/src/gateway/image-upload.mjs +219 -0
  17. package/src/gateway/native-diagnostic.mjs +189 -0
  18. package/src/gateway/native-evidence.mjs +113 -0
  19. package/src/gateway/native-response-limits.mjs +8 -0
  20. package/src/gateway/native-search-citations.mjs +196 -0
  21. package/src/gateway/native-search-diagnostic.mjs +282 -0
  22. package/src/gateway/native-search-metadata.mjs +749 -0
  23. package/src/gateway/native-transport.mjs +375 -0
  24. package/src/gateway/oauth-client-defaults.mjs +12 -0
  25. package/src/gateway/oauth-identity.mjs +67 -0
  26. package/src/gateway/outbound-proxy.mjs +320 -0
  27. package/src/gateway/output-recovery.mjs +48 -0
  28. package/src/gateway/quota-failover.mjs +14 -0
  29. package/src/gateway/quota-transport.mjs +37 -0
  30. package/src/gateway/quota.mjs +181 -0
  31. package/src/gateway/soft-error.mjs +25 -0
  32. package/src/gateway/structured-output.mjs +157 -0
  33. package/src/gateway/subscription.mjs +51 -0
  34. package/src/gateway/terms.mjs +126 -0
  35. package/src/image-input.mjs +137 -0
  36. package/src/image-url.mjs +21 -0
  37. package/src/native-provider.mjs +681 -0
  38. package/src/openai-contract.mjs +576 -0
  39. package/src/openai-usage.mjs +66 -0
  40. package/src/prompt-tool-schema.mjs +391 -0
  41. package/src/responses-tool-namespaces.mjs +84 -0
  42. package/src/tool-protocol.mjs +348 -0
@@ -0,0 +1,348 @@
1
+ /** Caller-owned PROMPT tool protocol, not native function calling.
2
+ * A call requests caller execution; it is never evidence of execution.
3
+ * Tool-call blocks outside quoted/ordinary code request execution, including examples.
4
+ * Inline code references are text; legacy prose-prefixed opening blocks are supported.
5
+ */
6
+ import crypto from 'node:crypto';
7
+ import { TOOL_LIMITS } from '../native-wire/consumer-tool-codec.mjs';
8
+ import { compilePromptTools, validatePromptToolArguments } from './prompt-tool-schema.mjs';
9
+
10
+ export const plainObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
11
+ export class ProtocolError extends Error {
12
+ constructor(code, status = 400, param = null) {
13
+ super(status >= 500 || status === 429 || status === 499 ? 'Native response failed verification' : 'Unsupported or invalid request');
14
+ this.code = code; this.status = status;
15
+ this.param = typeof param === 'string' ? param : null;
16
+ this.type = status === 429 ? 'rate_limit_error' : status >= 500 || status === 499 ? 'api_error' : 'invalid_request_error';
17
+ }
18
+ }
19
+ export const protocolError = (code, status = 400, param = null) => new ProtocolError(code, status, param);
20
+ const fail = (code, status = 400, param = null) => { throw protocolError(code, status, param); };
21
+
22
+ /** Bounded JSON parser: rejects duplicate keys, non-finite numbers and deep or
23
+ * oversized trees, rather than silently overwriting ambiguous arguments. */
24
+ export function parseBoundedJson(text, { status = 400 } = {}) {
25
+ if (typeof text !== 'string' || Buffer.byteLength(text) > TOOL_LIMITS.bytes) fail('INVALID_TOOL_JSON', status);
26
+ let pos = 0, nodes = 0;
27
+ const bad = () => fail('INVALID_TOOL_JSON', status);
28
+ const ws = () => { while (/[\t\n\r ]/.test(text[pos] ?? '\0')) pos++; };
29
+ const string = () => {
30
+ const start = pos++;
31
+ while (pos < text.length) {
32
+ const ch = text[pos++];
33
+ if (ch === '"') {
34
+ try {
35
+ const result = JSON.parse(text.slice(start, pos));
36
+ if (Buffer.from(result).toString('utf8') !== result) bad();
37
+ return result;
38
+ } catch { bad(); }
39
+ }
40
+ if (ch === '\\') pos++;
41
+ }
42
+ bad();
43
+ };
44
+ const value = depth => {
45
+ if (++nodes > TOOL_LIMITS.nodes || depth > TOOL_LIMITS.depth) bad();
46
+ ws();
47
+ if (text[pos] === '"') return string();
48
+ if (text[pos] === '{' || text[pos] === '[') {
49
+ const object = text[pos++] === '{', result = object ? Object.create(null) : [];
50
+ const end = object ? '}' : ']';
51
+ ws();
52
+ if (text[pos] === end) { pos++; return result; }
53
+ for (;;) {
54
+ ws();
55
+ let key;
56
+ if (object) {
57
+ if (text[pos] !== '"') bad();
58
+ key = string();
59
+ if (Object.hasOwn(result, key)) bad();
60
+ ws(); if (text[pos++] !== ':') bad();
61
+ }
62
+ const child = value(depth + 1);
63
+ if (object) result[key] = child; else result.push(child);
64
+ ws();
65
+ const separator = text[pos++];
66
+ if (separator === end) return result;
67
+ if (separator !== ',') bad();
68
+ }
69
+ }
70
+ const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(text.slice(pos));
71
+ if (!token) bad();
72
+ pos += token[0].length;
73
+ const result = JSON.parse(token[0]);
74
+ if (typeof result === 'number' && !Number.isFinite(result)) bad();
75
+ return result;
76
+ };
77
+ const result = value(0);
78
+ ws(); if (pos !== text.length) bad();
79
+ return result;
80
+ }
81
+
82
+ /** Caller prompt tools use bounded JSON Schema, not the native protobuf encoder.
83
+ * PI unions, lengths, arrays, free objects and local definition refs are supported.
84
+ * Strict is an inert client hint; caller execution and tool-choice checks remain.
85
+ */
86
+ export function compileToolPolicy(tools = [], choice = 'auto') {
87
+ let registry;
88
+ try { registry = compilePromptTools(tools); }
89
+ catch (error) { throw protocolError(error.code || 'INVALID_TOOLS', 400, error.param ?? null); }
90
+ let forced = null;
91
+ if (plainObject(choice)) {
92
+ if (Object.keys(choice).some(k => !['type', 'function'].includes(k)) || choice.type !== 'function' || !plainObject(choice.function) || Object.keys(choice.function).some(k => k !== 'name') || typeof choice.function.name !== 'string') fail('UNSUPPORTED_TOOL_CHOICE');
93
+ forced = choice.function.name;
94
+ if (!registry.has(forced)) fail('UNDECLARED_TOOL');
95
+ } else if (!['none', 'auto', 'required'].includes(choice)) fail('UNSUPPORTED_TOOL_CHOICE');
96
+ if ((choice === 'required' || forced) && !registry.size) fail('TOOLS_REQUIRED');
97
+ return { registry, choice, forced, enabled: choice !== 'none' && registry.size > 0 };
98
+ }
99
+
100
+ export function validateToolCall(name, args, policy, { status = 502, historical = false } = {}) {
101
+ if (historical) {
102
+ // Replayed calls are caller-supplied history, not fresh execution requests.
103
+ // Current declarations/choice/schema cannot retroactively authorize them.
104
+ if (typeof name !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(name)) fail('INVALID_TOOL_CALL', status);
105
+ if (!plainObject(args)) fail('INVALID_TOOL_ARGUMENTS', status);
106
+ try { validatePromptToolArguments(args, { type: 'object' }); }
107
+ catch { fail('INVALID_TOOL_ARGUMENTS', status); }
108
+ return;
109
+ }
110
+ if (!policy.enabled) fail('TOOL_CALL_NOT_ALLOWED', status);
111
+ if (typeof name !== 'string' || !policy.registry.has(name)) fail('UNDECLARED_TOOL', status);
112
+ if (policy.forced && name !== policy.forced) fail('TOOL_CHOICE_MISMATCH', status);
113
+ if (!plainObject(args)) fail('INVALID_TOOL_ARGUMENTS', status);
114
+ try { validatePromptToolArguments(args, policy.registry.get(name).parameters); }
115
+ catch { fail('TOOL_ARGUMENT_SCHEMA_MISMATCH', status); }
116
+ }
117
+ export function validateToolCompletion(calls, policy) {
118
+ if ((policy.choice === 'required' || policy.forced) && !calls.length) fail('TOOL_CHOICE_NOT_SATISFIED', 502);
119
+ }
120
+
121
+ export function buildToolInstruction(tools = [], choice = 'auto') {
122
+ const policy = compileToolPolicy(tools, choice);
123
+ if (!policy.enabled) return 'Answer the latest user request now as the assistant. If caller tool results are present, use them to complete your answer; do not wait for another user message. Never invent tool outputs. Never emit transcript role markers such as [Caller tool result], [User], or [Assistant]. Tool calls are prohibited for this turn. Do not emit a tool_call fence. For literal examples use a json fence.';
124
+ return [
125
+ '# Available Local Tools (caller-owned prompt protocol, NOT native function calling)',
126
+ JSON.stringify(tools),
127
+ 'CRITICAL: Upstream native/internal function-calling channels are DISABLED on this backend and WILL return `INVALID_ARGUMENT: function does not exist` internally.',
128
+ 'NEVER invoke declared tools via native/internal tool-calling channels during reasoning or generation. Even if an internal tool channel reports `function does not exist`, ignore that internal error—declared tools ARE available exclusively as plain UTF-8 Markdown text in your visible assistant reply.',
129
+ 'To REQUEST execution, emit a top-level fenced block in your visible assistant text on separate lines:',
130
+ '```tool_call',
131
+ '{"name":"declared_name","arguments":{}}',
132
+ '```',
133
+ 'Arguments must be a JSON object matching the declared schema. Never invent tools or results.',
134
+ 'Only the caller executes tools. Wait for linked caller tool results before using results.',
135
+ 'After emitting your tool_call block(s), STOP your response immediately. Never emit, simulate, or echo [Caller tool result], [User], [Assistant], or any transcript role markers.',
136
+ 'A standalone top-level tool_call fence is reserved for actual requests; use json fences for literal examples. Inline references are text.',
137
+ policy.forced ? `You MUST request only ${policy.forced}.` : choice === 'required' ? 'You MUST request at least one declared tool.' : 'Request tools only when needed.',
138
+ ].join('\n');
139
+ }
140
+
141
+ /** Full replay only. Never truncate history (especially call/result links). */
142
+ export function flattenMessages(messages = [], { maxChars = 3_500_000 } = {}) {
143
+ if (!Array.isArray(messages) || !messages.length) fail('MESSAGES_REQUIRED');
144
+ const systems = [], transcript = [];
145
+ for (const message of messages) {
146
+ const content = message.content ?? '';
147
+ if (typeof content !== 'string') fail('INVALID_MESSAGE_CONTENT');
148
+ if (['system', 'developer'].includes(message.role)) { systems.push(content); continue; }
149
+ if (message.role === 'user') transcript.push('[User]\n' + content);
150
+ else if (message.role === 'assistant') {
151
+ const calls = (message.tool_calls ?? []).map(call => ({ id: call.id, name: call.function.name, arguments: parseBoundedJson(call.function.arguments) }));
152
+ transcript.push('[Assistant]\n' + content + (calls.length ? '\n[Prior markdown tool_call fence requests; not execution proof]\n' + JSON.stringify(calls) : ''));
153
+ } else if (message.role === 'tool') {
154
+ // JSON quoting prevents caller text from escaping delimiters; the caller is
155
+ // still the source, not an assertion that the provider executed anything.
156
+ transcript.push('[Caller tool result]\n' + JSON.stringify({ tool_call_id: message.tool_call_id, content }));
157
+ } else fail('UNSUPPORTED_ROLE');
158
+ }
159
+ if (!transcript.length) fail('NON_SYSTEM_MESSAGE_REQUIRED');
160
+ const systemText = systems.join('\n\n'), userText = '[Conversation]\n' + transcript.join('\n\n');
161
+ if (systemText.length + userText.length > maxChars) fail('PROMPT_TOO_LARGE', 413);
162
+ return { systemText, userText };
163
+ }
164
+
165
+ const CALLER_RESULT_MARKER = '[Caller tool result]';
166
+
167
+ // Returns the safe prefix length before a full or trailing partial CALLER_RESULT_MARKER.
168
+ // Because CALLER_RESULT_MARKER contains '[' only at index 0, any partial prefix at the end
169
+ // of `str` must start at the last '[' within the trailing slice.
170
+ function callerResultPreviewCut(str) {
171
+ const full = str.indexOf(CALLER_RESULT_MARKER);
172
+ if (full >= 0) return full;
173
+ const lastBracket = str.lastIndexOf('[');
174
+ if (lastBracket >= 0 && CALLER_RESULT_MARKER.startsWith(str.slice(lastBracket))) {
175
+ return lastBracket;
176
+ }
177
+ return -1;
178
+ }
179
+
180
+ /** Bounded tool-fence splitter. Only complete JSON/name/schema-checked calls
181
+ * become call events; preview exposes ordinary pending text, never a tool body.
182
+ * Once at least one real tool_call has been emitted, any unquoted hallucinated
183
+ * `[Caller tool result]` continuation and everything after it is suppressed so
184
+ * the caller receives only the real tool calls. */
185
+ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBytes(12).toString('hex'), policy = compileToolPolicy([]) } = {}) {
186
+ let pending = '', scanned = 0, seen = 0, closed = false, suppressed = false, bytes = 0;
187
+ let mode = 'text', marker = '`', fenceLength = 3, toolBody = '', toolBytes = 0, headerBytes = 0, inlineTicks = 0;
188
+ const ids = new Set();
189
+ const malformed = reason => {
190
+ const error = protocolError('MALFORMED_TOOL_CALL', 502);
191
+ error.toolProtocolReason = reason;
192
+ throw error;
193
+ };
194
+ const emitCall = events => {
195
+ const parsed = parseBoundedJson(toolBody.trim(), { status: 502 });
196
+ if (!plainObject(parsed) || Object.keys(parsed).some(k => !['name', 'arguments'].includes(k)) || typeof parsed.name !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(parsed.name) || !plainObject(parsed.arguments)) fail('INVALID_TOOL_CALL', 502);
197
+ validateToolCall(parsed.name, parsed.arguments, policy);
198
+ if (++seen > TOOL_LIMITS.calls) fail('TOOL_SIZE_LIMIT', 502);
199
+ const id = newId();
200
+ if (typeof id !== 'string' || !/^call_[A-Za-z0-9_-]{1,200}$/.test(id) || ids.has(id)) fail('INVALID_TOOL_CALL_ID', 502);
201
+ ids.add(id);
202
+ events.push({ type: 'call', call: { id, type: 'function', function: { name: parsed.name, arguments: JSON.stringify(parsed.arguments) } } });
203
+ };
204
+ const inlineText = (text, raw, eol, events) => {
205
+ if (/^(?: {4}|\t| {0,3}(?:>|[-+*][ \t]|\d+[.)][ \t]))/.test(text)) {
206
+ inlineTicks = 0;
207
+ if (seen > 0) {
208
+ const idx = text.indexOf(CALLER_RESULT_MARKER);
209
+ if (idx >= 0) {
210
+ if (idx > 0) events.push({ type: 'content', text: text.slice(0, idx) });
211
+ suppressed = true;
212
+ return;
213
+ }
214
+ }
215
+ events.push({ type: 'content', text: raw });
216
+ return;
217
+ }
218
+ if (!text.trim()) inlineTicks = 0;
219
+ for (let i = 0; i < text.length;) {
220
+ if (seen > 0 && !inlineTicks && text.startsWith(CALLER_RESULT_MARKER, i)) {
221
+ if (i) events.push({ type: 'content', text: text.slice(0, i) });
222
+ suppressed = true;
223
+ return;
224
+ }
225
+ if (text[i] === '\\' && !inlineTicks) {
226
+ i += 2;
227
+ while (text[i] === '`' && text[i - 1] === '`') i++;
228
+ continue;
229
+ }
230
+ if (text[i] !== '`') { i++; continue; }
231
+ let end = i; while (text[end] === '`') end++;
232
+ const length = end - i;
233
+ // Historical successful responses may append an actual block after prose.
234
+ // It still needs an exact label/newline and cannot be inside inline code.
235
+ if (!inlineTicks && length >= 3 && eol && /^[ \t]*tool_call[ \t]*$/.test(text.slice(end))) {
236
+ if (i) events.push({ type: 'content', text: text.slice(0, i) });
237
+ mode = 'tool'; fenceLength = length; headerBytes = Buffer.byteLength(text.slice(i) + eol);
238
+ return;
239
+ }
240
+ if (!inlineTicks) inlineTicks = length;
241
+ else if (inlineTicks === length) inlineTicks = 0;
242
+ i = end;
243
+ }
244
+ events.push({ type: 'content', text: raw });
245
+ };
246
+ const line = (raw, final, events) => {
247
+ if (suppressed) return;
248
+ const eol = /\r?\n$/.exec(raw)?.[0] ?? '';
249
+ const text = eol ? raw.slice(0, -eol.length) : raw;
250
+ // Prefix-only matching avoids backtracking across long untrusted lines.
251
+ const opening = /^ {0,3}(`{3,}|~{3,})/.exec(text);
252
+ const run = opening?.[1], info = opening ? text.slice(opening[0].length) : '';
253
+ if (mode === 'tool') {
254
+ if (run?.[0] === '`' && run.length >= fenceLength) {
255
+ // JSON/name/schema validation, not incidental Markdown suffix layout,
256
+ // authorizes the call. Never scan the suffix again as another request.
257
+ emitCall(events); mode = 'text'; toolBody = ''; toolBytes = 0; inlineTicks = 0;
258
+ if (info.trim()) {
259
+ const markerIdx = info.indexOf(CALLER_RESULT_MARKER);
260
+ if (markerIdx >= 0) {
261
+ if (markerIdx > 0) events.push({ type: 'content', text: info.slice(0, markerIdx) });
262
+ suppressed = true;
263
+ return;
264
+ }
265
+ events.push({ type: 'content', text: info + eol });
266
+ } else if (eol) events.push({ type: 'content', text: eol });
267
+ return;
268
+ }
269
+ if (run?.[0] === '`' && info.trim()) malformed('closing_fence');
270
+ toolBody += raw; toolBytes += Buffer.byteLength(raw);
271
+ if (toolBytes > TOOL_LIMITS.bytes + 4) fail('TOOL_SIZE_LIMIT', 502);
272
+ return;
273
+ }
274
+ if (mode === 'ordinary') {
275
+ events.push({ type: 'content', text: raw });
276
+ if (run?.[0] === marker && run.length >= fenceLength && /^[ \t]*$/.test(info)) mode = 'text';
277
+ return;
278
+ }
279
+ if (!opening || (run[0] === '`' && info.includes('`'))) {
280
+ inlineText(text, raw, eol, events); return;
281
+ }
282
+ const label = info.trim();
283
+ if (label === 'tool_call' && run[0] === '`') {
284
+ if (final && !eol) fail('TRUNCATED_TOOL_CALL', 502);
285
+ mode = 'tool'; inlineTicks = 0; fenceLength = run.length; headerBytes = Buffer.byteLength(raw);
286
+ return;
287
+ }
288
+ if (label.startsWith('tool_call')) malformed('opening_fence');
289
+ if (final && !eol && label && 'tool_call'.startsWith(label)) fail('TRUNCATED_TOOL_CALL', 502);
290
+ mode = 'ordinary'; inlineTicks = 0; marker = run[0]; fenceLength = run.length;
291
+ events.push({ type: 'content', text: raw });
292
+ };
293
+ const drain = final => {
294
+ const events = []; let consumed = 0, from = scanned;
295
+ for (;;) {
296
+ const end = pending.indexOf('\n', from);
297
+ if (end < 0) break;
298
+ line(pending.slice(consumed, end + 1), false, events);
299
+ consumed = end + 1; from = consumed;
300
+ if (suppressed) { pending = ''; scanned = 0; return events; }
301
+ }
302
+ if (consumed) pending = pending.slice(consumed);
303
+ scanned = pending.length;
304
+ if (final && pending) {
305
+ line(pending, true, events);
306
+ pending = ''; scanned = 0;
307
+ if (suppressed) return events;
308
+ }
309
+ if (mode === 'tool') {
310
+ if (headerBytes + toolBytes + Buffer.byteLength(pending) > TOOL_LIMITS.bytes) fail('TOOL_SIZE_LIMIT', 502);
311
+ if (final) fail('TRUNCATED_TOOL_CALL', 502);
312
+ }
313
+ return events;
314
+ };
315
+ return {
316
+ push(text) {
317
+ if (closed) fail('SPLITTER_CLOSED', 502);
318
+ if (typeof text !== 'string' || (bytes += Buffer.byteLength(text)) > 8 * 1024 * 1024) fail('RESPONSE_TOO_LARGE', 502);
319
+ if (suppressed) return [];
320
+ pending += text;
321
+ return drain(false);
322
+ },
323
+ flush() {
324
+ if (closed) fail('SPLITTER_CLOSED', 502);
325
+ closed = true;
326
+ if (suppressed) return [];
327
+ return drain(true);
328
+ },
329
+ preview() {
330
+ if (suppressed || mode === 'tool') return '';
331
+ if (mode === 'ordinary') return pending;
332
+ if (!pending.trim() && pending.length <= 3) return '';
333
+ let safe = pending;
334
+ const tick = safe.indexOf('`');
335
+ if (tick >= 0) {
336
+ if (tick <= 3 && /^ *$/.test(safe.slice(0, tick))) return '';
337
+ safe = safe.slice(0, tick);
338
+ }
339
+ if (seen > 0) {
340
+ const cut = callerResultPreviewCut(safe);
341
+ if (cut >= 0) safe = safe.slice(0, cut);
342
+ }
343
+ return safe;
344
+ },
345
+ get toolCallCount() { return seen; },
346
+ get suppressed() { return suppressed; },
347
+ };
348
+ }