pi-gemini-app 0.1.15 → 0.1.17
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 +3 -2
- package/extensions/pi/provider.js +4 -1
- package/extensions/pi/stream.js +5 -6
- package/extensions/pi/transcript.js +8 -6
- package/native-wire/consumer-tool-codec.mjs +3 -2
- package/native-wire/robin-current.mjs +20 -12
- package/package.json +3 -1
- package/src/gateway/image-download.mjs +66 -19
- package/src/gateway/native-conversation-cleanup.mjs +134 -0
- package/src/gateway/native-diagnostic.mjs +3 -1
- package/src/gateway/native-evidence.mjs +15 -1
- package/src/gateway/native-search-citations.mjs +1 -1
- package/src/gateway/native-search-diagnostic.mjs +196 -78
- package/src/gateway/native-transport.mjs +2 -0
- package/src/gateway/output-recovery.mjs +3 -2
- package/src/gateway/quota.mjs +6 -3
- package/src/gateway/structured-output.mjs +1 -1
- package/src/gateway/subscription.mjs +4 -0
- package/src/gateway/terms.mjs +7 -5
- package/src/image-input.mjs +135 -16
- package/src/native-provider.mjs +140 -53
- package/src/openai-contract.mjs +139 -38
- package/src/prompt-tool-schema.mjs +35 -10
- package/src/tool-protocol.mjs +47 -9
package/README.md
CHANGED
|
@@ -71,17 +71,18 @@ Optional environment overrides if using your own OAuth desktop client:
|
|
|
71
71
|
| Model ID | Display Name | Context Window | Max Output | Capabilities |
|
|
72
72
|
| :--- | :--- | ---: | ---: | :--- |
|
|
73
73
|
| `gemini-neon` | Gemini Neon | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`); `gemini-argon` temporarily aliases here |
|
|
74
|
+
| `gemini-carbon` | Gemini Carbon | 512,000 | 16,384 | Gemini 4 Carbon, Google AI Ultra accounts only; text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`); the 512,000 window is the same advisory value as Neon and was not measured with a needle test for Carbon |
|
|
74
75
|
| `gemini-hydrogen` | Gemini Hydrogen | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
|
|
75
76
|
| `gemini-flash-lite` | Gemini Flash Lite | 128,000 | 8,192 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
|
|
76
77
|
| `gemini-auto` | Gemini Auto | 128,000 | 8,192 | Smart Model Selection for Free & paid Google accounts (text, static images, tools) |
|
|
77
78
|
|
|
78
|
-
> **Subscription Tier Detection**: `/login gemini-app` automatically detects your account's Google AI subscription tier via `
|
|
79
|
+
> **Subscription Tier Detection**: `/login gemini-app` automatically detects your account's Google AI subscription tier via `GetUserStatus`. **Free** accounts automatically filter available models to `gemini-auto` (avoiding paid-mode precondition rejections), while **AI Plus** and **AI Pro** accounts expose all models except `gemini-carbon`, and **AI Ultra** accounts expose all models. Run `/gemini-quota` at any time to check both your detected tier and rolling usage windows.
|
|
79
80
|
>
|
|
80
81
|
> **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.
|
|
81
82
|
>
|
|
82
83
|
> **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.
|
|
83
84
|
>
|
|
84
|
-
> **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`).
|
|
85
|
+
> **Auto-Compaction**: The configured `contextWindow` (`512,000` for Neon/Carbon/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`).
|
|
85
86
|
|
|
86
87
|
## Commands
|
|
87
88
|
|
|
@@ -4,7 +4,7 @@ import { MODEL_SPECS } from '../../src/openai-contract.mjs';
|
|
|
4
4
|
import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
|
|
5
5
|
import { fetchGoogleSubscription as defaultFetchGoogleSubscription } from '../../src/gateway/subscription-transport.mjs';
|
|
6
6
|
import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
|
|
7
|
-
import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
|
|
7
|
+
import { decodeSubscription as defaultDecodeSubscription, isCarbonExcludedTier } from '../../src/gateway/subscription.mjs';
|
|
8
8
|
|
|
9
9
|
const BASE_URL = 'https://robinfrontend-pa.googleapis.com';
|
|
10
10
|
const PROVIDER_ID = 'gemini-app';
|
|
@@ -24,6 +24,9 @@ export function filterGeminiModels(models, credential) {
|
|
|
24
24
|
if (tier === 'free') {
|
|
25
25
|
return models.filter((m) => m.provider !== PROVIDER_ID || m.id === 'gemini-auto');
|
|
26
26
|
}
|
|
27
|
+
if (isCarbonExcludedTier(tier)) {
|
|
28
|
+
return models.filter((m) => m.provider !== PROVIDER_ID || m.id !== 'gemini-carbon');
|
|
29
|
+
}
|
|
27
30
|
return models;
|
|
28
31
|
}
|
|
29
32
|
|
package/extensions/pi/stream.js
CHANGED
|
@@ -5,6 +5,7 @@ import { TOOL_ERRORS, automaticRecoveryKind as defaultAutomaticRecoveryKind } fr
|
|
|
5
5
|
import { canCompleteInterruptedOutput } from '../../src/gateway/output-recovery.mjs';
|
|
6
6
|
import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
|
|
7
7
|
import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
|
|
8
|
+
import { extractSafeUpstreamMessage } from '../../src/gateway/native-evidence.mjs';
|
|
8
9
|
|
|
9
10
|
const PREFIX_BYTES = 2048;
|
|
10
11
|
|
|
@@ -49,11 +50,7 @@ function formatFriendlyError(error, isAborted, modelId) {
|
|
|
49
50
|
) {
|
|
50
51
|
return `Google Gemini authentication expired or permission denied${error?.code ? ` (${error.code})` : ''}. Please run /login gemini-app to sign in again.`;
|
|
51
52
|
}
|
|
52
|
-
const upstreamMessage =
|
|
53
|
-
typeof error?.nativeEvidence?.upstreamMessage === 'string' &&
|
|
54
|
-
error.nativeEvidence.upstreamMessage.length > 0
|
|
55
|
-
? error.nativeEvidence.upstreamMessage
|
|
56
|
-
: '';
|
|
53
|
+
const upstreamMessage = extractSafeUpstreamMessage(error, { singleLine: true }) ?? '';
|
|
57
54
|
const code = typeof error?.code === 'string' && error.code.length > 0 ? error.code : '';
|
|
58
55
|
if (code === 'NATIVE_PRECONDITION_REQUIRED') {
|
|
59
56
|
if (/terms of service|tos_not_accepted/i.test(upstreamMessage)) {
|
|
@@ -328,7 +325,8 @@ export function createGeminiStreamHandler({
|
|
|
328
325
|
|
|
329
326
|
let body;
|
|
330
327
|
let codec;
|
|
331
|
-
|
|
328
|
+
let imageCache;
|
|
329
|
+
({ payload: body, codec, imageCache } = await buildChatPayload(model, context, options, {
|
|
332
330
|
getCurrentSystemPrompt,
|
|
333
331
|
getCurrentTools,
|
|
334
332
|
toToolDeclaration,
|
|
@@ -444,6 +442,7 @@ export function createGeminiStreamHandler({
|
|
|
444
442
|
recoveryCode,
|
|
445
443
|
recoveryReason,
|
|
446
444
|
getOutputCommitState,
|
|
445
|
+
...(imageCache?.size ? { imageCache } : {}),
|
|
447
446
|
});
|
|
448
447
|
if (turnResult?.thinkingLevel !== undefined && turnResult.thinkingLevel !== null) {
|
|
449
448
|
observedThinking = turnResult.thinkingLevel;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import crypto from 'node:crypto';
|
|
2
2
|
import {
|
|
3
|
-
|
|
3
|
+
createValidatedImageCache,
|
|
4
4
|
MAX_IMAGES,
|
|
5
5
|
MAX_IMAGE_BYTES,
|
|
6
6
|
MAX_TOTAL_IMAGE_BYTES,
|
|
@@ -151,6 +151,7 @@ export function resolveThinkingLevel(options = {}, { simple = false } = {}) {
|
|
|
151
151
|
function planImageBudget(messages) {
|
|
152
152
|
const accepted = new Map();
|
|
153
153
|
const degraded = new Map();
|
|
154
|
+
const decodedImages = createValidatedImageCache();
|
|
154
155
|
let count = 0;
|
|
155
156
|
let totalBytes = 0;
|
|
156
157
|
|
|
@@ -189,19 +190,20 @@ function planImageBudget(messages) {
|
|
|
189
190
|
degraded.set(key, `[Image omitted: ${mimeType} exceeded ${Math.round(MAX_TOTAL_IMAGE_BYTES / (1024 * 1024))}MB total image budget]`);
|
|
190
191
|
continue;
|
|
191
192
|
}
|
|
193
|
+
let decoded;
|
|
192
194
|
try {
|
|
193
|
-
|
|
195
|
+
decoded = decodedImages.decodeDataUrl(dataUrl);
|
|
194
196
|
} catch (err) {
|
|
195
197
|
degraded.set(key, `[Image omitted: invalid ${mimeType} (${err?.code || 'INVALID_IMAGE'})]`);
|
|
196
198
|
continue;
|
|
197
199
|
}
|
|
198
200
|
count++;
|
|
199
201
|
totalBytes += byteLength;
|
|
200
|
-
accepted.set(key,
|
|
202
|
+
accepted.set(key, decoded.url);
|
|
201
203
|
}
|
|
202
204
|
}
|
|
203
205
|
|
|
204
|
-
return { accepted, degraded };
|
|
206
|
+
return { accepted, degraded, decodedImages };
|
|
205
207
|
}
|
|
206
208
|
|
|
207
209
|
function serializeToolArguments(block) {
|
|
@@ -355,7 +357,7 @@ export async function buildChatPayload(
|
|
|
355
357
|
};
|
|
356
358
|
});
|
|
357
359
|
|
|
358
|
-
const { accepted: acceptedImages, degraded: degradedImages } = planImageBudget(rawMessages);
|
|
360
|
+
const { accepted: acceptedImages, degraded: degradedImages, decodedImages } = planImageBudget(rawMessages);
|
|
359
361
|
const messages = [];
|
|
360
362
|
|
|
361
363
|
const systemPrompt = sanitizeText(getCurrentSystemPrompt(rawMessages));
|
|
@@ -563,5 +565,5 @@ export async function buildChatPayload(
|
|
|
563
565
|
}
|
|
564
566
|
}
|
|
565
567
|
|
|
566
|
-
return { payload, codec };
|
|
568
|
+
return { payload, codec, imageCache: decodedImages };
|
|
567
569
|
}
|
|
@@ -226,12 +226,13 @@ export function buildConsumerToolInitial({ userText, images = [], systemText, to
|
|
|
226
226
|
const omitThinking = smartModelSelection && thinkingLevel === null;
|
|
227
227
|
if (!omitThinking && (!Number.isSafeInteger(thinkingLevel) || thinkingLevel < 0 || thinkingLevel > 4)) rejectTool('INVALID_THINKING_LEVEL');
|
|
228
228
|
if (typeof temporaryChat !== 'boolean') rejectTool('INVALID_TEMPORARY_CHAT');
|
|
229
|
-
const
|
|
229
|
+
const disableNativeTools = !(registry.size || allowNativeTools);
|
|
230
|
+
const base = buildClientGenerate({ userText, images, systemText, identifiers, clientMetadata: metadata, temporaryChat, smartModelSelection, disableNativeTools });
|
|
230
231
|
const desktopInfo = cat(...[...registry.values()].map(tool => m(2, tool.declaration)), ...(ownedDeviceId===undefined?[]:[s(6,ownedDeviceId)]), ...(clientToolsCapability ? [m(7, unsignedVarint(CLIENT_TOOLS_CAPABILITY))] : []));
|
|
231
232
|
const omitMode = smartModelSelection && (modeCategory === undefined || modeCategory === null);
|
|
232
233
|
const requestedMode = omitMode ? null : (modeCategory === undefined ? ARGON_MODE_CATEGORY : modeCategory);
|
|
233
234
|
if (!omitMode && (!Number.isSafeInteger(requestedMode) || requestedMode < 0 || requestedMode > 255)) rejectTool('INVALID_MODE_CATEGORY');
|
|
234
|
-
const template = cat(
|
|
235
|
+
const template = cat(base, ...(omitMode ? [] : [v(47, requestedMode)]), ...(omitThinking ? [] : [v(48, thinkingLevel)]), ...(agentChat ? [v(49, 1)] : []), ...(registry.size ? [m(51, cat(...(ownedDeviceId===undefined?[]:[s(1,ownedDeviceId)]),m(3, desktopInfo), ...(localSession ? [v(5, 1)] : [])))] : []));
|
|
235
236
|
if (continuation !== undefined && !Buffer.isBuffer(continuation)) rejectTool('INVALID_OWN_CONTINUATION');
|
|
236
237
|
// Proven empty InitialRequest.ext1013 marker; NOT an outer update carrier or declaration list.
|
|
237
238
|
const initial = cat(m(1, buildRequestMetadata(metadata)), ...(continuation === undefined ? [] : [m(6, continuation)]), m(1001, m(1, template)), m(1004, Buffer.alloc(0)), ...(registry.size && operationFeature ? [m(1009, Buffer.alloc(0))] : []), ...(halfCloseFeature ? [m(1010, Buffer.alloc(0))] : []), ...(clientToolsFeature ? [m(1013, Buffer.alloc(0))] : []));
|
|
@@ -67,7 +67,7 @@ function imageAttachments(images) {
|
|
|
67
67
|
return images.map((image, index) => {
|
|
68
68
|
const extension = image?.mimeType === 'image/png' ? 'png' : image?.mimeType === 'image/jpeg' ? 'jpg' : image?.mimeType === 'image/webp' ? 'webp' : null;
|
|
69
69
|
const id = image?.blobId;
|
|
70
|
-
if (!extension || Object.hasOwn(image, 'data') || typeof id !== 'string' || !id.length || Buffer.byteLength(id) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(id) ||
|
|
70
|
+
if (!extension || Object.hasOwn(image, 'data') || typeof id !== 'string' || !id.length || Buffer.byteLength(id) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(id) || !id.isWellFormed()) throw new TypeError('Invalid native image');
|
|
71
71
|
const blob = Buffer.concat([string(1, id), varintField(2, 1), string(3, image.mimeType), varintField(4, 1)]);
|
|
72
72
|
return message(3, Buffer.concat([message(1, blob), string(2, `image-${index + 1}.${extension}`)]));
|
|
73
73
|
});
|
|
@@ -77,8 +77,9 @@ function imageAttachments(images) {
|
|
|
77
77
|
* Model IDs and mode numbers are passed explicitly by caller policy.
|
|
78
78
|
* Built-in tools, overage credits and smart model selection default off.
|
|
79
79
|
*/
|
|
80
|
-
export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false, smartModelSelection = false } = {}) {
|
|
80
|
+
export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false, smartModelSelection = false, disableNativeTools = true } = {}) {
|
|
81
81
|
if (typeof smartModelSelection !== 'boolean') throw new TypeError('Invalid smart model selection');
|
|
82
|
+
if (typeof disableNativeTools !== 'boolean') throw new TypeError('Invalid native tools flag');
|
|
82
83
|
const fields = [message(1, Buffer.concat([string(1, userText), ...imageAttachments(images)]))];
|
|
83
84
|
if (modelId !== undefined) fields.push(message(3, string(2, modelId)));
|
|
84
85
|
if (identifiers !== undefined) {
|
|
@@ -90,7 +91,7 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
|
|
|
90
91
|
}
|
|
91
92
|
fields.push(varintField(5, 1));
|
|
92
93
|
if (clientMetadata !== undefined) fields.push(message(13, buildRequestMetadata(clientMetadata)));
|
|
93
|
-
fields.push(varintField(15, 1));
|
|
94
|
+
fields.push(varintField(15, disableNativeTools ? 1 : 0));
|
|
94
95
|
if (systemText !== undefined) fields.push(message(29, string(4, systemText)));
|
|
95
96
|
// Temporary chat keeps the turn out of the account's saved conversation history.
|
|
96
97
|
if (temporaryChat) fields.push(varintField(31, 1));
|
|
@@ -100,16 +101,16 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
|
|
|
100
101
|
return output;
|
|
101
102
|
}
|
|
102
103
|
|
|
103
|
-
/** Decode
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
export function decodeClientGenerateResponse(bytes) {
|
|
107
|
-
const fields = parse(bytes), ids = field(fields, 2);
|
|
104
|
+
/** Decode already-parsed ClientGenerateResponse fields (single-pass helper). */
|
|
105
|
+
export function decodeClientGenerateResponseFields(fields, { includeModels = true } = {}) {
|
|
106
|
+
const ids = field(fields, 2);
|
|
108
107
|
const models = [];
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
108
|
+
if (includeModels) {
|
|
109
|
+
for (const model of fields.filter(value => value.number === 1)) {
|
|
110
|
+
if (model.wire !== 2) throw new Error('Invalid model response');
|
|
111
|
+
const item = parse(model.payload), display = field(item, 2);
|
|
112
|
+
models.push({ responseId: stringValue(item, 1), text: display === undefined ? null : stringValue(parse(display), 1) });
|
|
113
|
+
}
|
|
113
114
|
}
|
|
114
115
|
const responseIds = ids === undefined ? [] : parse(ids);
|
|
115
116
|
return {
|
|
@@ -124,6 +125,13 @@ export function decodeClientGenerateResponse(bytes) {
|
|
|
124
125
|
};
|
|
125
126
|
}
|
|
126
127
|
|
|
128
|
+
/** Decode inner ClientGenerateResponse. Thought contents are not exported.
|
|
129
|
+
* Model identity fields are recorded as evidence and verified by caller policy.
|
|
130
|
+
*/
|
|
131
|
+
export function decodeClientGenerateResponse(bytes) {
|
|
132
|
+
return decodeClientGenerateResponseFields(parse(bytes));
|
|
133
|
+
}
|
|
134
|
+
|
|
127
135
|
/** Extension 1014 wrapper field 1 -> streaming ContinuationIdentifiers
|
|
128
136
|
* consumed by InitialRequest field 6. Treat opaque token bytes as private session state.
|
|
129
137
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-gemini-app",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.17",
|
|
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": [
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"gooeypi",
|
|
11
11
|
"gemini",
|
|
12
12
|
"gemini-neon",
|
|
13
|
+
"gemini-carbon",
|
|
13
14
|
"gemini-hydrogen",
|
|
14
15
|
"gemini-auto",
|
|
15
16
|
"provider",
|
|
@@ -58,6 +59,7 @@
|
|
|
58
59
|
"src/gateway/automatic-recovery.mjs",
|
|
59
60
|
"src/gateway/image-download.mjs",
|
|
60
61
|
"src/gateway/image-upload.mjs",
|
|
62
|
+
"src/gateway/native-conversation-cleanup.mjs",
|
|
61
63
|
"src/gateway/native-diagnostic.mjs",
|
|
62
64
|
"src/gateway/native-evidence.mjs",
|
|
63
65
|
"src/gateway/native-response-limits.mjs",
|
|
@@ -11,31 +11,53 @@ const fail = (code, status = 400) => { throw protocolError(code, status); };
|
|
|
11
11
|
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
12
12
|
const MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
|
|
13
13
|
|
|
14
|
+
const DEFAULT_DOWNLOAD_CONCURRENCY = 4;
|
|
15
|
+
const MAX_DOWNLOAD_CONCURRENCY = 8;
|
|
16
|
+
|
|
14
17
|
/** No proxy, cookies, caller/Google headers, cache, retries or URL-bearing errors. */
|
|
15
|
-
export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 } = {}, {
|
|
18
|
+
export async function downloadRemoteImages(images, { signal, timeoutMs = 30000, concurrency = DEFAULT_DOWNLOAD_CONCURRENCY } = {}, {
|
|
16
19
|
lookup = dnsLookup, request = (url, options, callback) => (url.protocol === 'https:' ? https : http).request(url, options, callback),
|
|
17
20
|
} = {}) {
|
|
18
21
|
if (!Array.isArray(images) || images.length > MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
|
|
19
22
|
if (!images.some(image => image.url)) return images;
|
|
20
23
|
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 180000) fail('INVALID_IMAGE_DOWNLOAD_TIMEOUT');
|
|
24
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > MAX_DOWNLOAD_CONCURRENCY) fail('INVALID_IMAGE_DOWNLOAD_CONCURRENCY');
|
|
21
25
|
if (signal?.aborted) fail('IMAGE_DOWNLOAD_ABORTED', 499);
|
|
22
26
|
const controller = new AbortController();
|
|
23
27
|
let rejectStop;
|
|
28
|
+
let stopError = null;
|
|
24
29
|
const stopped = new Promise((_, reject) => { rejectStop = reject; });
|
|
30
|
+
stopped.catch(() => {});
|
|
25
31
|
// The shared deadline includes DNS, every redirect and every image in this batch.
|
|
26
|
-
const stop = error => {
|
|
32
|
+
const stop = error => {
|
|
33
|
+
if (!stopError) {
|
|
34
|
+
stopError = error;
|
|
35
|
+
rejectStop(error);
|
|
36
|
+
}
|
|
37
|
+
controller.abort();
|
|
38
|
+
};
|
|
27
39
|
const abort = () => stop(protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
|
|
28
40
|
signal?.addEventListener('abort', abort, { once: true });
|
|
29
41
|
const timer = setTimeout(() => stop(protocolError('IMAGE_DOWNLOAD_TIMEOUT', 504)), timeoutMs);
|
|
30
42
|
const bounded = promise => Promise.race([promise, stopped]);
|
|
31
|
-
let
|
|
43
|
+
let sharedRemaining = MAX_TOTAL_IMAGE_BYTES - images.reduce((sum, image) => sum + (image.data?.length ?? 0), 0);
|
|
32
44
|
try {
|
|
33
|
-
if (
|
|
34
|
-
const result =
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
45
|
+
if (sharedRemaining < 0) fail('IMAGES_TOO_LARGE', 413);
|
|
46
|
+
const result = new Array(images.length);
|
|
47
|
+
const remoteTasks = [];
|
|
48
|
+
for (let index = 0; index < images.length; index++) {
|
|
49
|
+
const image = images[index];
|
|
50
|
+
if (!image.url) {
|
|
51
|
+
result[index] = image;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
// Validate URL syntax upfront in deterministic index order before opening any socket.
|
|
55
|
+
remoteTasks.push({ index, initialUrl: parseRemoteImageUrl(image.url) });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const downloadOne = async ({ index, initialUrl }) => {
|
|
59
|
+
let url = initialUrl;
|
|
60
|
+
for (let redirects = 0; ; redirects++) {
|
|
39
61
|
if (controller.signal.aborted) await stopped;
|
|
40
62
|
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
41
63
|
const addresses = isIP(host) ? [{ address: host, family: isIP(host) }] : await bounded(lookup(host, { all: true, verbatim: true }));
|
|
@@ -49,10 +71,9 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
|
|
|
49
71
|
controller.signal.removeEventListener('abort', cancel);
|
|
50
72
|
if (error) { res?.destroy(); req?.destroy(); reject(error); } else resolve(value);
|
|
51
73
|
};
|
|
52
|
-
const cancel = () => finish(protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
|
|
53
|
-
const limit = Math.min(MAX_IMAGE_BYTES, remaining);
|
|
74
|
+
const cancel = () => finish(stopError ?? protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
|
|
54
75
|
try {
|
|
55
|
-
if (
|
|
76
|
+
if (sharedRemaining <= 0) fail('IMAGES_TOO_LARGE', 413);
|
|
56
77
|
req = request(url, {
|
|
57
78
|
method: 'GET', agent: false, maxHeaderSize: 16384,
|
|
58
79
|
headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': GATEWAY_USER_AGENT },
|
|
@@ -76,11 +97,19 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
|
|
|
76
97
|
const length = res.headers['content-length'];
|
|
77
98
|
if (res.statusCode !== 200) { finish(protocolError('IMAGE_DOWNLOAD_HTTP_ERROR', 502)); return; }
|
|
78
99
|
if (!MIME.has(mimeType) || encoding !== undefined && encoding !== 'identity') { finish(protocolError('UNSUPPORTED_IMAGE_FORMAT')); return; }
|
|
79
|
-
if (length !== undefined && (!/^\d+$/.test(length) || Number(length) >
|
|
100
|
+
if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > Math.min(MAX_IMAGE_BYTES, sharedRemaining))) {
|
|
101
|
+
finish(protocolError('IMAGES_TOO_LARGE', 413));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
80
104
|
const chunks = [];
|
|
81
105
|
res.on('data', chunk => {
|
|
106
|
+
if (settled) return;
|
|
82
107
|
size += chunk.length;
|
|
83
|
-
|
|
108
|
+
sharedRemaining -= chunk.length;
|
|
109
|
+
if (size > MAX_IMAGE_BYTES || sharedRemaining < 0) {
|
|
110
|
+
finish(protocolError('IMAGES_TOO_LARGE', 413));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
84
113
|
chunks.push(chunk);
|
|
85
114
|
});
|
|
86
115
|
res.on('end', () => { ended = true; });
|
|
@@ -95,16 +124,34 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
|
|
|
95
124
|
} catch (error) { finish(error); }
|
|
96
125
|
}));
|
|
97
126
|
if (response.next) { url = response.next; continue; }
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
result.push(decoded); break;
|
|
127
|
+
result[index] = decodeImageBytes(response.data, response.mimeType);
|
|
128
|
+
return;
|
|
101
129
|
}
|
|
102
|
-
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const workerCount = Math.min(concurrency, remoteTasks.length);
|
|
133
|
+
let cursor = 0;
|
|
134
|
+
const workers = Array.from({ length: workerCount }, async () => {
|
|
135
|
+
while (cursor < remoteTasks.length) {
|
|
136
|
+
if (controller.signal.aborted) break;
|
|
137
|
+
const task = remoteTasks[cursor++];
|
|
138
|
+
try {
|
|
139
|
+
await downloadOne(task);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
stop(error);
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
await Promise.all(workers);
|
|
147
|
+
if (stopError) throw stopError;
|
|
103
148
|
return result;
|
|
104
149
|
} catch (error) {
|
|
105
|
-
|
|
150
|
+
const reported = stopError ?? error;
|
|
151
|
+
if (reported instanceof ProtocolError) throw reported;
|
|
106
152
|
fail('IMAGE_DOWNLOAD_FAILED', 502);
|
|
107
153
|
} finally {
|
|
154
|
+
controller.abort();
|
|
108
155
|
clearTimeout(timer); signal?.removeEventListener('abort', abort);
|
|
109
156
|
}
|
|
110
157
|
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Bounded best-effort deletion of a single Robin conversation created by this turn.
|
|
2
|
+
// Never lists, reads, or touches any conversation ID other than the one supplied.
|
|
3
|
+
import { lengthDelimited as m } from "../../native-wire/protobuf.mjs";
|
|
4
|
+
import { frameGrpcMessage, GrpcMessageReader, GATEWAY_USER_AGENT } from "../../native-wire/robin-current.mjs";
|
|
5
|
+
import { connectHttp2 } from "./outbound-proxy.mjs";
|
|
6
|
+
|
|
7
|
+
export const DELETE_CONVERSATION_RPC =
|
|
8
|
+
"/assistant.mobile.robin.RobinService/DeleteConversation";
|
|
9
|
+
const ORIGIN = "https://robinfrontend-pa.googleapis.com";
|
|
10
|
+
|
|
11
|
+
export function isValidConversationId(value) {
|
|
12
|
+
return (
|
|
13
|
+
typeof value === "string" &&
|
|
14
|
+
value.length >= 1 &&
|
|
15
|
+
value.length <= 256 &&
|
|
16
|
+
!/[\x00-\x1f\x7f\s]/.test(value)
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function deleteNativeConversation(
|
|
21
|
+
accessToken,
|
|
22
|
+
conversationId,
|
|
23
|
+
{ timeoutMs = 5000, connect = connectHttp2 } = {},
|
|
24
|
+
) {
|
|
25
|
+
if (
|
|
26
|
+
typeof accessToken !== "string" ||
|
|
27
|
+
!accessToken ||
|
|
28
|
+
accessToken.length > 65536 ||
|
|
29
|
+
/\s/.test(accessToken)
|
|
30
|
+
) {
|
|
31
|
+
return { ok: false, code: "CLEANUP_INVALID_CREDENTIAL" };
|
|
32
|
+
}
|
|
33
|
+
if (!isValidConversationId(conversationId)) {
|
|
34
|
+
return { ok: false, code: "CLEANUP_INVALID_CONVERSATION_ID" };
|
|
35
|
+
}
|
|
36
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15000) {
|
|
37
|
+
return { ok: false, code: "CLEANUP_INVALID_TIMEOUT" };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return new Promise((resolve) => {
|
|
41
|
+
let client, request, timer;
|
|
42
|
+
let settled = false;
|
|
43
|
+
let httpStatus = null;
|
|
44
|
+
let grpcStatus = null;
|
|
45
|
+
let invalidStatus = false;
|
|
46
|
+
let receivedBytes = 0;
|
|
47
|
+
let frameCount = 0;
|
|
48
|
+
const MAX_CLEANUP_RESPONSE_BYTES = 64 * 1024;
|
|
49
|
+
const reader = new GrpcMessageReader();
|
|
50
|
+
const finish = (result) => {
|
|
51
|
+
if (settled) return;
|
|
52
|
+
settled = true;
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
try { request?.close(); } catch {}
|
|
55
|
+
try { client?.destroy(); } catch {}
|
|
56
|
+
resolve(result);
|
|
57
|
+
};
|
|
58
|
+
const onHeaders = (headers) => {
|
|
59
|
+
if (headers[":status"] !== undefined) {
|
|
60
|
+
const parsed = Number(headers[":status"]);
|
|
61
|
+
if (Number.isInteger(parsed)) httpStatus = parsed;
|
|
62
|
+
else invalidStatus = true;
|
|
63
|
+
}
|
|
64
|
+
if (headers["grpc-status"] !== undefined) {
|
|
65
|
+
const raw = String(headers["grpc-status"]);
|
|
66
|
+
if (/^\d{1,2}$/.test(raw) && Number(raw) <= 16) grpcStatus = Number(raw);
|
|
67
|
+
else invalidStatus = true;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
timer = setTimeout(() => finish({ ok: false, code: "CLEANUP_TIMEOUT" }), timeoutMs);
|
|
71
|
+
timer.unref?.();
|
|
72
|
+
try {
|
|
73
|
+
client = connect(ORIGIN);
|
|
74
|
+
client.on("error", () => finish({ ok: false, code: "CLEANUP_CONNECTION_FAILED" }));
|
|
75
|
+
client.on("close", () => {
|
|
76
|
+
if (!settled) finish({ ok: false, code: "CLEANUP_CLOSED_EARLY" });
|
|
77
|
+
});
|
|
78
|
+
request = client.request({
|
|
79
|
+
":method": "POST",
|
|
80
|
+
":path": DELETE_CONVERSATION_RPC,
|
|
81
|
+
authorization: "Bearer " + accessToken,
|
|
82
|
+
"content-type": "application/grpc",
|
|
83
|
+
te: "trailers",
|
|
84
|
+
"grpc-timeout": `${timeoutMs}m`,
|
|
85
|
+
"user-agent": GATEWAY_USER_AGENT,
|
|
86
|
+
});
|
|
87
|
+
request.on("response", onHeaders);
|
|
88
|
+
request.on("trailers", onHeaders);
|
|
89
|
+
request.on("data", (chunk) => {
|
|
90
|
+
if (settled) return;
|
|
91
|
+
receivedBytes += chunk.length;
|
|
92
|
+
if (receivedBytes > MAX_CLEANUP_RESPONSE_BYTES) {
|
|
93
|
+
finish({ ok: false, code: "CLEANUP_RESPONSE_TOO_LARGE" });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const frames = reader.push(chunk);
|
|
98
|
+
frameCount += frames.length;
|
|
99
|
+
if (frameCount > 1) {
|
|
100
|
+
finish({ ok: false, code: "CLEANUP_MALFORMED_RESPONSE" });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
finish({ ok: false, code: "CLEANUP_MALFORMED_RESPONSE" });
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
request.on("error", () => finish({ ok: false, code: "CLEANUP_STREAM_FAILED" }));
|
|
108
|
+
request.on("close", () => {
|
|
109
|
+
if (!settled) finish({ ok: false, code: "CLEANUP_CLOSED_EARLY" });
|
|
110
|
+
});
|
|
111
|
+
request.on("end", () => {
|
|
112
|
+
if (settled) return;
|
|
113
|
+
if (Number.isInteger(request?.rstCode) && request.rstCode > 0) {
|
|
114
|
+
finish({ ok: false, code: "CLEANUP_STREAM_RESET" });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
reader.finish();
|
|
119
|
+
} catch {
|
|
120
|
+
finish({ ok: false, code: "CLEANUP_MALFORMED_RESPONSE" });
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (!invalidStatus && httpStatus === 200 && grpcStatus === 0) {
|
|
124
|
+
finish({ ok: true });
|
|
125
|
+
} else {
|
|
126
|
+
finish({ ok: false, code: "CLEANUP_REJECTED" });
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
request.end(frameGrpcMessage(m(1, Buffer.from(conversationId, "utf8"))));
|
|
130
|
+
} catch {
|
|
131
|
+
finish({ ok: false, code: "CLEANUP_CONNECTION_FAILED" });
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
@@ -107,11 +107,13 @@ export class NativeDiagnostic {
|
|
|
107
107
|
let fd;
|
|
108
108
|
try {
|
|
109
109
|
if (!this.directory || !/^req_[a-f0-9-]{36}$/.test(requestId)) return null;
|
|
110
|
+
const armPath = path.join(this.directory, NATIVE_DIAGNOSTIC_FILES.arm);
|
|
111
|
+
const armStat = fs.lstatSync(armPath, { throwIfNoEntry: false });
|
|
112
|
+
if (!armStat || !privateRegular(armStat)) return null;
|
|
110
113
|
const directory = fs.lstatSync(this.directory);
|
|
111
114
|
if (!directory.isDirectory() || (directory.mode & 0o077) !== 0) return null;
|
|
112
115
|
const files = Object.fromEntries(Object.entries(NATIVE_DIAGNOSTIC_FILES).map(([key, name]) => [key, path.join(this.directory, name)]));
|
|
113
116
|
if (fs.existsSync(files.claimed) || fs.existsSync(files.result)) return null;
|
|
114
|
-
if (!privateRegular(fs.lstatSync(files.arm))) return null;
|
|
115
117
|
fd = fs.openSync(files.arm, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
116
118
|
const stat = fs.fstatSync(fd);
|
|
117
119
|
if (!privateRegular(stat) || stat.size > 256 || stat.size < 1) return null;
|
|
@@ -44,9 +44,23 @@ export function sanitizeUpstreamMessage(value) {
|
|
|
44
44
|
/\b(?:sk-|gsk_|gw_|gk_|gapi_)[A-Za-z0-9_-]{16,}|\b[0-9]{7,}\b|\b[A-Za-z0-9_-]{64,}\b/g,
|
|
45
45
|
"[identifier redacted]",
|
|
46
46
|
)
|
|
47
|
-
.replace(/[\x00-\x08\x0b\
|
|
47
|
+
.replace(/[\x00-\x08\x0b-\x0d\x0e-\x1f\x7f-\x9f]/g, "");
|
|
48
48
|
return text.length > 2048 ? text.slice(0, 2036) + "\n[truncated]" : text;
|
|
49
49
|
}
|
|
50
|
+
export function extractSafeUpstreamMessage(error, { singleLine = false } = {}) {
|
|
51
|
+
const raw =
|
|
52
|
+
typeof error?.nativeEvidence?.upstreamMessage === "string" &&
|
|
53
|
+
error.nativeEvidence.upstreamMessage.length > 0
|
|
54
|
+
? error.nativeEvidence.upstreamMessage
|
|
55
|
+
: typeof error?.upstreamMessage === "string" &&
|
|
56
|
+
error.upstreamMessage.length > 0
|
|
57
|
+
? error.upstreamMessage
|
|
58
|
+
: null;
|
|
59
|
+
if (!raw) return null;
|
|
60
|
+
const clean = sanitizeUpstreamMessage(raw);
|
|
61
|
+
if (!clean) return null;
|
|
62
|
+
return singleLine ? clean.replace(/[\t\n]+/g, " ").replace(/\s{2,}/g, " ").trim() || null : clean;
|
|
63
|
+
}
|
|
50
64
|
export function decodeGrpcMessage(value) {
|
|
51
65
|
if (typeof value !== "string" || value.length > 32768) return null;
|
|
52
66
|
let text = value;
|
|
@@ -14,7 +14,7 @@ function sliceCodeUnitsSafe(text, maxChars = CITATION_LIMITS.MAX_TITLE_CHARS) {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
function cleanPlainTitle(value, { stripHtml = false } = {}) {
|
|
17
|
-
if (typeof value !== 'string' ||
|
|
17
|
+
if (typeof value !== 'string' || !value.isWellFormed()) return '';
|
|
18
18
|
let text = stripHtml ? value.replace(/<[^>]*>/g, '') : value;
|
|
19
19
|
text = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
20
20
|
return sliceCodeUnitsSafe(text, CITATION_LIMITS.MAX_TITLE_CHARS);
|