pi-gemini-app 0.1.2 → 0.1.4
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.md +5 -5
- package/extensions/pi/provider.js +3 -3
- package/package.json +4 -2
- package/src/gateway/automatic-recovery.mjs +5 -4
- package/src/gateway/native-evidence.mjs +1 -1
- package/src/gateway/native-search-diagnostic.mjs +3 -3
- package/src/gateway/native-transport.mjs +1 -1
- package/src/gateway/output-recovery.mjs +4 -3
- package/src/gateway/quota.mjs +1 -1
- package/src/native-provider.mjs +11 -7
- package/src/openai-contract.mjs +14 -7
- package/src/tool-protocol.mjs +73 -13
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# `pi-gemini-app` — Google Gemini App Provider for Pi
|
|
2
2
|
|
|
3
|
-
Native in-process provider extension for `@earendil-works/pi-coding-agent` (`pi`). Connects directly to Gemini's native HTTP/2 endpoint (`ProcessQuery`) inside the Pi process—no separate HTTP gateway server, Docker container, or extra npm runtime dependencies required.
|
|
3
|
+
Native in-process provider extension for `@earendil-works/pi-coding-agent` (`pi`) and GooeyPi. Connects directly to Gemini's native HTTP/2 endpoint (`ProcessQuery`) inside the Pi process—no separate HTTP gateway server, Docker container, or extra npm runtime dependencies required.
|
|
4
4
|
|
|
5
5
|
> **Disclaimer**: Unofficial interoperability software. Not affiliated with, endorsed by, or sponsored by Google. You must authenticate personally with your own eligible Google account.
|
|
6
6
|
|
|
@@ -36,7 +36,7 @@ Or add the extension path to your Pi settings (`~/.pi/agent/settings.json`):
|
|
|
36
36
|
|
|
37
37
|
## Architecture & When to Choose `pi-gemini-app` vs `gemini-app2api`
|
|
38
38
|
|
|
39
|
-
- **In-Process Direct HTTP/2 (`pi-gemini-app`)**: Runs completely inside Pi using Node.js built-ins (`node:http2`, `node:crypto`). Ideal for single-user Pi terminal sessions with zero background daemons or Docker containers.
|
|
39
|
+
- **In-Process Direct HTTP/2 (`pi-gemini-app`)**: Runs completely inside Pi / GooeyPi using Node.js built-ins (`node:http2`, `node:crypto`). Ideal for single-user Pi / GooeyPi terminal sessions with zero background daemons or Docker containers.
|
|
40
40
|
- **Full Standalone Gateway (`gemini-app2api`)**: Use the [main repository](https://github.com/ShawTim/gemini-app2api) if you need multi-account quota pooling/failover, OpenAI-compatible `/v1/chat/completions` & `/v1/responses` endpoints for Cursor/Cline/Codex CLI, or the `/admin` web operations console.
|
|
41
41
|
|
|
42
42
|
## Authentication (`/login gemini-app`)
|
|
@@ -65,18 +65,18 @@ Optional environment overrides if using your own OAuth desktop client:
|
|
|
65
65
|
|
|
66
66
|
| Model ID | Display Name | Context Window | Max Output | Capabilities |
|
|
67
67
|
| :--- | :--- | ---: | ---: | :--- |
|
|
68
|
-
| `gemini-
|
|
68
|
+
| `gemini-neon` | Gemini Neon | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`); `gemini-argon` temporarily aliases here |
|
|
69
69
|
| `gemini-hydrogen` | Gemini Hydrogen | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
|
|
70
70
|
| `gemini-flash-lite` | Gemini Flash Lite | 128,000 | 8,192 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
|
|
71
71
|
| `gemini-auto` | Gemini Auto | 128,000 | 8,192 | Smart Model Selection for Free & paid Google accounts (text, static images, tools) |
|
|
72
72
|
|
|
73
73
|
> **Subscription Tier Detection**: `/login gemini-app` automatically detects your account's Google AI subscription tier via `GetUsageInfo`. **Free** accounts automatically filter available models to `gemini-auto` (avoiding paid-mode precondition rejections), while **AI Plus**, **AI Pro**, and **AI Ultra** accounts expose all models. Run `/gemini-quota` at any time to check both your detected tier and rolling usage windows.
|
|
74
74
|
>
|
|
75
|
-
> **Quota Tip**: `gemini-
|
|
75
|
+
> **Quota Tip**: On `thinking=2` coding and tool-call loops, `gemini-neon` uses only `~1.5x–2x` the rolling-window quota of `gemini-hydrogen` (and `~4x–5x` on `thinking=0` generation), so you can daily-drive `gemini-neon` comfortably or switch to `gemini-hydrogen` when you want `~1.7x–2.6x` faster responses and extra quota headroom.
|
|
76
76
|
>
|
|
77
77
|
> **Usage Accounting**: Token counters reported in Pi are local character-based estimates over message text (`~3.5` chars/token, excluding image payloads and tool schemas) rather than official Google token counts.
|
|
78
78
|
>
|
|
79
|
-
> **Auto-Compaction**: The configured `contextWindow` (`
|
|
79
|
+
> **Auto-Compaction**: The configured `contextWindow` (`512,000` for Neon/Hydrogen; `128,000` for Flash Lite/Auto) works automatically with Pi's proactive compaction (`contextWindow - reserveTokens`) and `413` context-overflow recovery compaction (or manual `/compact`).
|
|
80
80
|
|
|
81
81
|
## Commands
|
|
82
82
|
|
|
@@ -27,13 +27,13 @@ export function filterGeminiModels(models, credential) {
|
|
|
27
27
|
|
|
28
28
|
export const MODELS = Object.freeze([
|
|
29
29
|
{
|
|
30
|
-
id: 'gemini-
|
|
31
|
-
name: 'Gemini
|
|
30
|
+
id: 'gemini-neon',
|
|
31
|
+
name: 'Gemini Neon',
|
|
32
32
|
api: API_ID,
|
|
33
33
|
provider: PROVIDER_ID,
|
|
34
34
|
baseUrl: BASE_URL,
|
|
35
35
|
type: 'chat',
|
|
36
|
-
contextWindow:
|
|
36
|
+
contextWindow: 512000,
|
|
37
37
|
maxTokens: 16384,
|
|
38
38
|
input: ['text', 'image'],
|
|
39
39
|
reasoning: true,
|
package/package.json
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-gemini-app",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "In-process Google Gemini App provider extension for Pi (direct native HTTP/2, /login gemini-app, /gemini-quota, zero runtime dependencies).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"pi-package",
|
|
8
8
|
"pi-extension",
|
|
9
9
|
"pi-coding-agent",
|
|
10
|
+
"gooeypi",
|
|
10
11
|
"gemini",
|
|
11
|
-
"gemini-
|
|
12
|
+
"gemini-neon",
|
|
12
13
|
"gemini-hydrogen",
|
|
14
|
+
"gemini-auto",
|
|
13
15
|
"provider",
|
|
14
16
|
"oauth"
|
|
15
17
|
],
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Request-scoped bounded recovery; never repair/execute an invalid tool call.
|
|
2
|
-
import { MODEL_MODES } from '../openai-contract.mjs';
|
|
2
|
+
import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
|
|
3
3
|
import { isVerifiedEmptyResponse } from './output-recovery.mjs';
|
|
4
4
|
import { isExplicitQuotaFailure } from './quota-failover.mjs';
|
|
5
5
|
const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
|
|
@@ -19,10 +19,11 @@ export function toolRecoveryInstruction(code) {
|
|
|
19
19
|
return null;
|
|
20
20
|
}
|
|
21
21
|
export function automaticRecoveryKind(error, model, { allowAutoModel = false } = {}) {
|
|
22
|
+
const resolvedModel = canonicalModel(model);
|
|
22
23
|
if (isExplicitQuotaFailure(error)) return 'quota';
|
|
23
|
-
if (isVerifiedEmptyResponse(error,
|
|
24
|
-
const isAuto = allowAutoModel === true &&
|
|
25
|
-
const expected = MODEL_MODES[
|
|
24
|
+
if (isVerifiedEmptyResponse(error, resolvedModel, { allowAutoModel })) return 'empty_response';
|
|
25
|
+
const isAuto = allowAutoModel === true && resolvedModel === 'gemini-auto';
|
|
26
|
+
const expected = MODEL_MODES[resolvedModel];
|
|
26
27
|
if (!isAuto && expected === undefined) return null;
|
|
27
28
|
const modeOk = mode => isAuto
|
|
28
29
|
? (mode === null || mode === undefined || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
|
|
@@ -54,7 +54,7 @@ export function safeAccountError(value) {
|
|
|
54
54
|
typeof value.code === "string" && /^[A-Z0-9_]{1,80}$/.test(value.code)
|
|
55
55
|
? value.code
|
|
56
56
|
: "NATIVE_TURN_FAILED",
|
|
57
|
-
...(NATIVE_MODELS.includes(value.model) || value.model === "gemini-flash"
|
|
57
|
+
...(NATIVE_MODELS.includes(value.model) || value.model === "gemini-argon" || value.model === "gemini-flash"
|
|
58
58
|
? { model: value.model }
|
|
59
59
|
: {}),
|
|
60
60
|
nativeEvidence,
|
|
@@ -220,20 +220,20 @@ export async function runNativeSearchDiagnostic({
|
|
|
220
220
|
const result = await provider.runTurn(
|
|
221
221
|
"diagnostic",
|
|
222
222
|
{
|
|
223
|
-
model: "gemini-
|
|
223
|
+
model: "gemini-neon",
|
|
224
224
|
messages: [{ role: "user", content: query }],
|
|
225
225
|
thinking_level: 2,
|
|
226
226
|
},
|
|
227
227
|
() => {},
|
|
228
228
|
{ signal },
|
|
229
229
|
);
|
|
230
|
-
if (result.resolvedModeCategory !==
|
|
230
|
+
if (result.resolvedModeCategory !== 3 || result.thinkingLevel !== 2)
|
|
231
231
|
return fail("NATIVE_THINKING_MISMATCH");
|
|
232
232
|
return {
|
|
233
233
|
ok: true,
|
|
234
234
|
answer: result.content,
|
|
235
235
|
query,
|
|
236
|
-
requestedModel: "gemini-
|
|
236
|
+
requestedModel: "gemini-neon",
|
|
237
237
|
revisionCount: result.revisionCount,
|
|
238
238
|
resolvedModeCategory: result.resolvedModeCategory,
|
|
239
239
|
requestedThinkingLevel: 2,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Only a fully completed, verified empty ordinary turn is recoverable automatically.
|
|
2
2
|
// Never promote thoughts/shareable/structured output to an assistant answer.
|
|
3
|
-
import { MODEL_MODES } from '../openai-contract.mjs';
|
|
3
|
+
import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
|
|
4
4
|
import { parse } from '../../native-wire/protobuf.mjs';
|
|
5
5
|
import { protocolError } from '../tool-protocol.mjs';
|
|
6
6
|
export const EMPTY_RESPONSE_REASONS = Object.freeze(['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty']);
|
|
@@ -29,11 +29,12 @@ export function inspectNativeOutput(fields) {
|
|
|
29
29
|
...(Number.isSafeInteger(completenessState) && completenessState >= 0 && completenessState <= 0x7fffffff ? { nativeCompletenessState: completenessState } : {}) };
|
|
30
30
|
}
|
|
31
31
|
export function isVerifiedEmptyResponse(error, model, { allowAutoModel = false } = {}) {
|
|
32
|
+
const resolvedModel = canonicalModel(model);
|
|
32
33
|
const e = error?.nativeEvidence;
|
|
33
|
-
const isAuto = allowAutoModel === true &&
|
|
34
|
+
const isAuto = allowAutoModel === true && resolvedModel === 'gemini-auto';
|
|
34
35
|
const modeOk = isAuto
|
|
35
36
|
? (e?.observedMode === null || e?.observedMode === undefined || (Number.isSafeInteger(e.observedMode) && e.observedMode >= 0 && e.observedMode <= 64))
|
|
36
|
-
: (MODEL_MODES[
|
|
37
|
+
: (MODEL_MODES[resolvedModel] !== undefined && e?.observedMode === MODEL_MODES[resolvedModel]);
|
|
37
38
|
return error?.status === 502 && error.code === 'EMPTY_NATIVE_RESPONSE' &&
|
|
38
39
|
e?.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
|
|
39
40
|
e.wireEnded === true && e.modelCompleted === true && modeOk &&
|
package/src/gateway/quota.mjs
CHANGED
|
@@ -162,7 +162,7 @@ export function safeQuota(value) {
|
|
|
162
162
|
helpItems: Array.isArray(r.helpItems) ? r.helpItems.slice(0, 16).filter(h => h && typeof h.label === "string" && typeof h.description === "string").map(h => ({ label: h.label.slice(0, 512), description: h.description.slice(0, 2048) })) : [],
|
|
163
163
|
})) : [];
|
|
164
164
|
const times = { budgetsUpdatedAt: safeTime(value.budgetsUpdatedAt) || (budgets.length ? safeTime(value.updatedAt) : null), refillsUpdatedAt: safeTime(value.refillsUpdatedAt) || (refills.length ? safeTime(value.updatedAt) : null), usageUpdatedAt: safeTime(value.usageUpdatedAt) || (usageRows.length ? safeTime(value.updatedAt) : null) };
|
|
165
|
-
return { source: value.source === "official" && value.provider === "google-robin" ? "official" : "unknown", status: ["ok", "missing", "error", "unqueried"].includes(value.status) ? value.status : "unknown", updatedAt: safeTime(value.updatedAt), ...times, lastAttemptAt: safeTime(value.lastAttemptAt), errorCode: SAFE_ERRORS.has(value.errorCode) || value.errorCode === "INVALID_QUOTA_METADATA" ? value.errorCode : null, budgets, refills, usageRows, provider: "google-robin", remainingPercent: budgets.length === 1 ? budgets[0].remainingPercent : null, ...(typeof value.observedModel === "string" && ["gemini-argon", "gemini-argon-thinking", "gemini-hydrogen", "gemini-flash", "gemini-flash-lite", "gemini-3.1-pro-preview", "gemini-3.1-flash-preview"].includes(value.observedModel) ? { observedModel: value.observedModel } : {}) };
|
|
165
|
+
return { source: value.source === "official" && value.provider === "google-robin" ? "official" : "unknown", status: ["ok", "missing", "error", "unqueried"].includes(value.status) ? value.status : "unknown", updatedAt: safeTime(value.updatedAt), ...times, lastAttemptAt: safeTime(value.lastAttemptAt), errorCode: SAFE_ERRORS.has(value.errorCode) || value.errorCode === "INVALID_QUOTA_METADATA" ? value.errorCode : null, budgets, refills, usageRows, provider: "google-robin", remainingPercent: budgets.length === 1 ? budgets[0].remainingPercent : null, ...(typeof value.observedModel === "string" && ["gemini-neon", "gemini-argon", "gemini-argon-thinking", "gemini-hydrogen", "gemini-flash", "gemini-flash-lite", "gemini-3.1-pro-preview", "gemini-3.1-flash-preview"].includes(value.observedModel) ? { observedModel: value.observedModel } : {}) };
|
|
166
166
|
}
|
|
167
167
|
export function quotaFailureCode(error) { return SAFE_ERRORS.has(error?.code) ? error.code : "QUOTA_REFRESH_FAILED"; }
|
|
168
168
|
|
package/src/native-provider.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import crypto from 'node:crypto';
|
|
|
7
7
|
import { parse } from '../native-wire/protobuf.mjs';
|
|
8
8
|
import { decodeClientGenerateResponse } from '../native-wire/robin-current.mjs';
|
|
9
9
|
import { ProtocolError, protocolError, compileToolPolicy, createToolCallSplitter, validateToolCompletion } from './tool-protocol.mjs';
|
|
10
|
-
import { MODEL_MODES, NATIVE_MODELS, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
|
|
10
|
+
import { MODEL_ALIASES, MODEL_MODES, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
|
|
11
11
|
import { RESPONSE_TOOL_IDENTITIES } from './responses-tool-namespaces.mjs';
|
|
12
12
|
import { safeNativeEvidence } from './gateway/native-evidence.mjs';
|
|
13
13
|
import { decodePassiveQuota, mergeQuotaObservation } from './gateway/quota.mjs';
|
|
@@ -20,7 +20,7 @@ import { validateStructuredOutputText } from './gateway/structured-output.mjs';
|
|
|
20
20
|
import { mapNativeSearchAnnotations, extractNativeSearchSources } from './gateway/native-search-citations.mjs';
|
|
21
21
|
import { softErrorReason } from './gateway/soft-error.mjs';
|
|
22
22
|
import { observeNative } from './gateway/native-diagnostic.mjs';
|
|
23
|
-
export { NATIVE_MODELS, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
|
|
23
|
+
export { MODEL_ALIASES, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
|
|
24
24
|
|
|
25
25
|
import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './gateway/native-response-limits.mjs';
|
|
26
26
|
const fail = (code, status = 502) => { throw protocolError(code, status); };
|
|
@@ -37,6 +37,7 @@ const failWithEvidence = (code, evidence) => {
|
|
|
37
37
|
};
|
|
38
38
|
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
39
39
|
const HYDROGEN_ATTRIBUTION = /\bhydrogen\b/i;
|
|
40
|
+
const NEON_ATTRIBUTION = /\bneon\b/i;
|
|
40
41
|
function one(fields, number) {
|
|
41
42
|
const found = fields.filter(field => field.number === number);
|
|
42
43
|
if (found.length > 1) fail('INVALID_NATIVE_RESPONSE');
|
|
@@ -100,7 +101,7 @@ function safeFailure(error) {
|
|
|
100
101
|
|
|
101
102
|
|
|
102
103
|
export class NativeDirectProvider {
|
|
103
|
-
constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-
|
|
104
|
+
constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-neon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
|
|
104
105
|
if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
|
|
105
106
|
if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
|
|
106
107
|
if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
|
|
@@ -108,14 +109,15 @@ export class NativeDirectProvider {
|
|
|
108
109
|
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) throw new TypeError('invalid timeout');
|
|
109
110
|
if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
|
|
110
111
|
if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
|
|
112
|
+
const resolvedAlias = canonicalModel(modelAlias);
|
|
111
113
|
const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
|
|
112
|
-
if (!allowedModels.includes(
|
|
114
|
+
if (!allowedModels.includes(resolvedAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
|
|
113
115
|
this.authManager = authManager; this.openTurn = openTurn; this.uploadImages = uploadImages; this.timeoutMs = timeoutMs;
|
|
114
116
|
this.downloadImages = downloadImages;
|
|
115
117
|
if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
|
|
116
118
|
this.allowTextSnapshotReplacement = allowTextSnapshotReplacement;
|
|
117
119
|
this.allowAutoModel = allowAutoModel;
|
|
118
|
-
this.modelAlias =
|
|
120
|
+
this.modelAlias = resolvedAlias; this.continuationEnabled = false;
|
|
119
121
|
}
|
|
120
122
|
|
|
121
123
|
buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body, { allowAutoModel: this.allowAutoModel })); }
|
|
@@ -205,10 +207,12 @@ export class NativeDirectProvider {
|
|
|
205
207
|
timer = setTimeout(() => stop(protocolError('NATIVE_TURN_TIMEOUT', 504)), timeoutMs);
|
|
206
208
|
const bounded = promise => Promise.race([promise, deadline]);
|
|
207
209
|
const requiresHydrogen = body.model === 'gemini-hydrogen';
|
|
210
|
+
const requiresNeon = body.model === 'gemini-neon';
|
|
208
211
|
let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
|
|
209
212
|
let modelComplete = false, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
|
|
210
213
|
let observedFallback = null, downgradeReason = null, observedAttribution = null;
|
|
211
|
-
const
|
|
214
|
+
const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
|
|
215
|
+
const attributionVerified = () => attributionMatches(observedAttribution);
|
|
212
216
|
let snapshotId = null, revisionCount = 0, quotaObservation = null, quotaFrames = 0;
|
|
213
217
|
let emptyResponseReason = null, outputObserved = false, responseLimitReason = null, outputFailureReason = null;
|
|
214
218
|
const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
|
|
@@ -314,7 +318,7 @@ export class NativeDirectProvider {
|
|
|
314
318
|
}
|
|
315
319
|
if (frameResolved && info.attribution !== null && info.attribution.length > 0) {
|
|
316
320
|
observedAttribution = info.attribution;
|
|
317
|
-
if (
|
|
321
|
+
if (!attributionMatches(info.attribution)) downgrade = true;
|
|
318
322
|
}
|
|
319
323
|
// Final generate evidence must name the requested mode unless auto selection is enabled.
|
|
320
324
|
// Prior proven rejection is sticky; an unresolved zero is not a proven downgrade.
|
package/src/openai-contract.mjs
CHANGED
|
@@ -14,9 +14,16 @@ import { RESPONSE_TOOL_IDENTITIES, normalizeResponsesTools, responsesCallFields
|
|
|
14
14
|
import { toResponsesUsage } from './openai-usage.mjs';
|
|
15
15
|
|
|
16
16
|
const fail = (code, status = 400, param = null) => { throw protocolError(code, status, param); };
|
|
17
|
-
export const NATIVE_MODELS = Object.freeze(['gemini-
|
|
18
|
-
//
|
|
19
|
-
export const
|
|
17
|
+
export const NATIVE_MODELS = Object.freeze(['gemini-neon', 'gemini-hydrogen', 'gemini-flash-lite']);
|
|
18
|
+
// Temporary compatibility alias while clients migrate from retired gemini-argon (mode 8) to gemini-neon (mode 3).
|
|
19
|
+
export const MODEL_ALIASES = Object.freeze({ 'gemini-argon': 'gemini-neon' });
|
|
20
|
+
// Native ModeCategory wire values: PRO=3 (Gemini 4 Neon), FAST=1 (Gemini 4 Hydrogen), FLASH_LITE=6. Never auto/Plus.
|
|
21
|
+
export const MODEL_MODES = Object.freeze({ 'gemini-neon': 3, 'gemini-hydrogen': 1, 'gemini-flash-lite': 6 });
|
|
22
|
+
export function canonicalModel(model) {
|
|
23
|
+
if (typeof model !== 'string') return model;
|
|
24
|
+
const stripped = model.startsWith('models/') ? model.slice(7) : model;
|
|
25
|
+
return Object.hasOwn(MODEL_ALIASES, stripped) ? MODEL_ALIASES[stripped] : stripped;
|
|
26
|
+
}
|
|
20
27
|
// Ordinary effort hints must never opt into native asynchronous Deep Think (3).
|
|
21
28
|
// Extended thinking (2) is the existing normal-turn default, not an ordered scale.
|
|
22
29
|
export const REASONING_EFFORT_LEVELS = Object.freeze({ none: 0, minimal: 0, low: 1, medium: 2, high: 2, xhigh: 2 });
|
|
@@ -167,9 +174,9 @@ function content(value, { assistant = false, responses = false, user = false, pr
|
|
|
167
174
|
return parts.some(part => part.type === 'image_url') ? parts : parts.map(part => part.text).join('');
|
|
168
175
|
}
|
|
169
176
|
function settings(body, { allowAutoModel = false } = {}) {
|
|
170
|
-
const model = body.model === undefined ? 'gemini-
|
|
177
|
+
const model = body.model === undefined ? 'gemini-neon' : body.model;
|
|
171
178
|
if (typeof model !== 'string') fail('UNSUPPORTED_MODEL', 400, 'model');
|
|
172
|
-
const alias =
|
|
179
|
+
const alias = canonicalModel(model);
|
|
173
180
|
const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
|
|
174
181
|
if (!allowedModels.includes(alias)) fail('UNSUPPORTED_MODEL', 400, 'model');
|
|
175
182
|
const thinking = thinkingSettings(body);
|
|
@@ -245,7 +252,7 @@ export function buildCanonicalPrompt(body, resolvedImages) {
|
|
|
245
252
|
const tailReminder = activeToolNames
|
|
246
253
|
? '\n\n[Tool Protocol Reminder]\nUpstream native/internal function-calling channels are disabled (`INVALID_ARGUMENT: function does not exist`). Never invoke tools through native/internal tool channels; to call `' +
|
|
247
254
|
activeToolNames +
|
|
248
|
-
'`, write a literal plain-text Markdown ```tool_call fenced JSON block in your visible assistant response.'
|
|
255
|
+
'`, write a literal plain-text Markdown ```tool_call fenced JSON block in your visible assistant response. Stop immediately after your tool_call block(s) and never emit [Caller tool result] yourself.'
|
|
249
256
|
: '';
|
|
250
257
|
const prompt = '[System Instructions]\n' + preamble + '\n\n' + userText + tailReminder;
|
|
251
258
|
if (prompt.length > MAX_CHARS || Buffer.byteLength(prompt) > PROMPT_MAX_BYTES) fail('PROMPT_TOO_LARGE', 413);
|
|
@@ -317,7 +324,7 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
|
|
|
317
324
|
const resolved = settings(payload, { allowAutoModel });
|
|
318
325
|
const response_format = normalizeChatResponseFormat(payload.response_format);
|
|
319
326
|
if (resolved.native_search) {
|
|
320
|
-
if (resolved.model !== 'gemini-
|
|
327
|
+
if (resolved.model !== 'gemini-neon' || resolved.thinking_level !== 2) fail('UNSUPPORTED_NATIVE_SEARCH_MODE');
|
|
321
328
|
if (response_format) fail('NATIVE_SEARCH_RESPONSE_FORMAT_CONFLICT');
|
|
322
329
|
if ((payload.tools !== undefined && (!Array.isArray(payload.tools) || payload.tools.length)) || (payload.tool_choice !== undefined && payload.tool_choice !== 'auto') || payload.parallel_tool_calls !== undefined) fail('NATIVE_SEARCH_TOOL_CONFLICT');
|
|
323
330
|
if (Array.isArray(payload.messages) && payload.messages.some(message => message?.role === 'tool' || message?.tool_calls !== undefined || message?.tool_call_id !== undefined)) fail('NATIVE_SEARCH_TOOL_HISTORY_UNSUPPORTED');
|
package/src/tool-protocol.mjs
CHANGED
|
@@ -120,7 +120,7 @@ export function validateToolCompletion(calls, policy) {
|
|
|
120
120
|
|
|
121
121
|
export function buildToolInstruction(tools = [], choice = 'auto') {
|
|
122
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. Tool calls are prohibited for this turn. Do not emit a tool_call fence. For literal examples use a json fence.';
|
|
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
124
|
return [
|
|
125
125
|
'# Available Local Tools (caller-owned prompt protocol, NOT native function calling)',
|
|
126
126
|
JSON.stringify(tools),
|
|
@@ -132,6 +132,7 @@ export function buildToolInstruction(tools = [], choice = 'auto') {
|
|
|
132
132
|
'```',
|
|
133
133
|
'Arguments must be a JSON object matching the declared schema. Never invent tools or results.',
|
|
134
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.',
|
|
135
136
|
'A standalone top-level tool_call fence is reserved for actual requests; use json fences for literal examples. Inline references are text.',
|
|
136
137
|
policy.forced ? `You MUST request only ${policy.forced}.` : choice === 'required' ? 'You MUST request at least one declared tool.' : 'Request tools only when needed.',
|
|
137
138
|
].join('\n');
|
|
@@ -161,10 +162,28 @@ export function flattenMessages(messages = [], { maxChars = 3_500_000 } = {}) {
|
|
|
161
162
|
return { systemText, userText };
|
|
162
163
|
}
|
|
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
|
+
|
|
164
180
|
/** Bounded tool-fence splitter. Only complete JSON/name/schema-checked calls
|
|
165
|
-
* become call events; preview exposes ordinary pending text, never a tool body.
|
|
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. */
|
|
166
185
|
export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBytes(12).toString('hex'), policy = compileToolPolicy([]) } = {}) {
|
|
167
|
-
let pending = '', scanned = 0, seen = 0, closed = false, bytes = 0;
|
|
186
|
+
let pending = '', scanned = 0, seen = 0, closed = false, suppressed = false, bytes = 0;
|
|
168
187
|
let mode = 'text', marker = '`', fenceLength = 3, toolBody = '', toolBytes = 0, headerBytes = 0, inlineTicks = 0;
|
|
169
188
|
const ids = new Set();
|
|
170
189
|
const malformed = reason => {
|
|
@@ -184,10 +203,25 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
184
203
|
};
|
|
185
204
|
const inlineText = (text, raw, eol, events) => {
|
|
186
205
|
if (/^(?: {4}|\t| {0,3}(?:>|[-+*][ \t]|\d+[.)][ \t]))/.test(text)) {
|
|
187
|
-
inlineTicks = 0;
|
|
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;
|
|
188
217
|
}
|
|
189
218
|
if (!text.trim()) inlineTicks = 0;
|
|
190
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
|
+
}
|
|
191
225
|
if (text[i] === '\\' && !inlineTicks) {
|
|
192
226
|
i += 2;
|
|
193
227
|
while (text[i] === '`' && text[i - 1] === '`') i++;
|
|
@@ -210,6 +244,7 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
210
244
|
events.push({ type: 'content', text: raw });
|
|
211
245
|
};
|
|
212
246
|
const line = (raw, final, events) => {
|
|
247
|
+
if (suppressed) return;
|
|
213
248
|
const eol = /\r?\n$/.exec(raw)?.[0] ?? '';
|
|
214
249
|
const text = eol ? raw.slice(0, -eol.length) : raw;
|
|
215
250
|
// Prefix-only matching avoids backtracking across long untrusted lines.
|
|
@@ -220,8 +255,15 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
220
255
|
// JSON/name/schema validation, not incidental Markdown suffix layout,
|
|
221
256
|
// authorizes the call. Never scan the suffix again as another request.
|
|
222
257
|
emitCall(events); mode = 'text'; toolBody = ''; toolBytes = 0; inlineTicks = 0;
|
|
223
|
-
if (info.trim())
|
|
224
|
-
|
|
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 });
|
|
225
267
|
return;
|
|
226
268
|
}
|
|
227
269
|
if (run?.[0] === '`' && info.trim()) malformed('closing_fence');
|
|
@@ -255,10 +297,15 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
255
297
|
if (end < 0) break;
|
|
256
298
|
line(pending.slice(consumed, end + 1), false, events);
|
|
257
299
|
consumed = end + 1; from = consumed;
|
|
300
|
+
if (suppressed) { pending = ''; scanned = 0; return events; }
|
|
258
301
|
}
|
|
259
302
|
if (consumed) pending = pending.slice(consumed);
|
|
260
303
|
scanned = pending.length;
|
|
261
|
-
if (final && pending) {
|
|
304
|
+
if (final && pending) {
|
|
305
|
+
line(pending, true, events);
|
|
306
|
+
pending = ''; scanned = 0;
|
|
307
|
+
if (suppressed) return events;
|
|
308
|
+
}
|
|
262
309
|
if (mode === 'tool') {
|
|
263
310
|
if (headerBytes + toolBytes + Buffer.byteLength(pending) > TOOL_LIMITS.bytes) fail('TOOL_SIZE_LIMIT', 502);
|
|
264
311
|
if (final) fail('TRUNCATED_TOOL_CALL', 502);
|
|
@@ -269,18 +316,31 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
|
|
|
269
316
|
push(text) {
|
|
270
317
|
if (closed) fail('SPLITTER_CLOSED', 502);
|
|
271
318
|
if (typeof text !== 'string' || (bytes += Buffer.byteLength(text)) > 8 * 1024 * 1024) fail('RESPONSE_TOO_LARGE', 502);
|
|
319
|
+
if (suppressed) return [];
|
|
272
320
|
pending += text;
|
|
273
321
|
return drain(false);
|
|
274
322
|
},
|
|
275
|
-
flush() {
|
|
323
|
+
flush() {
|
|
324
|
+
if (closed) fail('SPLITTER_CLOSED', 502);
|
|
325
|
+
closed = true;
|
|
326
|
+
if (suppressed) return [];
|
|
327
|
+
return drain(true);
|
|
328
|
+
},
|
|
276
329
|
preview() {
|
|
277
|
-
if (mode === 'tool') return '';
|
|
330
|
+
if (suppressed || mode === 'tool') return '';
|
|
278
331
|
if (mode === 'ordinary') return pending;
|
|
279
332
|
if (!pending.trim() && pending.length <= 3) return '';
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
if (tick
|
|
283
|
-
|
|
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;
|
|
284
344
|
},
|
|
285
345
|
get toolCallCount() { return seen; },
|
|
286
346
|
};
|