@juspay/neurolink 13.8.30 → 13.9.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/CHANGELOG.md +3 -3
- package/dist/browser/neurolink.min.js +437 -437
- package/dist/core/nativeGenerateLoop.d.ts +21 -0
- package/dist/core/nativeGenerateLoop.js +29 -21
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp/externalServerManager.js +12 -1
- package/dist/providers/openaiChatCompletionsBase.js +12 -8
- package/dist/providers/openaiChatCompletionsClient.js +37 -6
- package/dist/proxy/claudeFormat.js +10 -7
- package/dist/proxy/geminiFormat.js +29 -33
- package/dist/proxy/proxyImageInput.d.ts +57 -9
- package/dist/proxy/proxyImageInput.js +162 -10
- package/dist/server/abstract/baseServerAdapter.js +3 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/middleware/index.d.ts +1 -0
- package/dist/server/middleware/index.js +1 -0
- package/dist/server/middleware/session.d.ts +93 -0
- package/dist/server/middleware/session.js +175 -0
- package/dist/server/routes/CLAUDE.md +29 -0
- package/dist/types/server.d.ts +40 -2
- package/dist/utils/imageDetection.d.ts +22 -0
- package/dist/utils/imageDetection.js +95 -0
- package/dist/utils/retryAfter.js +13 -6
- package/dist/voice/CLAUDE.md +79 -0
- package/docs-site/static/search-index.json +22 -11
- package/package.json +2 -1
|
@@ -84,6 +84,16 @@ export declare const toPrepareStepRecord: (step: {
|
|
|
84
84
|
export declare const hasNativeDoGenerate: (value: unknown) => value is {
|
|
85
85
|
doGenerate: (options: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
|
86
86
|
};
|
|
87
|
+
/**
|
|
88
|
+
* Parse a tool call's arguments, distinguishing "no arguments" from "the model
|
|
89
|
+
* emitted something that is not JSON". Silently substituting `{}` for the
|
|
90
|
+
* second case ran the tool with empty input and reported success, so a
|
|
91
|
+
* malformed call looked identical to a legitimate no-arg one.
|
|
92
|
+
*/
|
|
93
|
+
export declare const parseToolInput: (raw: unknown) => {
|
|
94
|
+
input: unknown;
|
|
95
|
+
error?: string;
|
|
96
|
+
};
|
|
87
97
|
/** A tool's inputSchema with its lazy (function) form, if any, resolved. */
|
|
88
98
|
export declare const resolveToolInputSchema: (schema: Tool["inputSchema"]) => Exclude<Tool["inputSchema"], (...args: never[]) => unknown>;
|
|
89
99
|
/**
|
|
@@ -99,6 +109,17 @@ export declare const toNativeToolDeclaration: (name: string, tool: Tool) => {
|
|
|
99
109
|
description: string;
|
|
100
110
|
inputSchema: object;
|
|
101
111
|
};
|
|
112
|
+
/**
|
|
113
|
+
* Validate parsed input against the tool's own schema when it exposes one.
|
|
114
|
+
*
|
|
115
|
+
* `generateText` validated tool input before dispatch; the native loop did
|
|
116
|
+
* not, so a call whose shape the tool rejects reached `execute` and failed
|
|
117
|
+
* inside user code — or worse, did not fail. A Zod schema is detected by
|
|
118
|
+
* `safeParse`; anything else is passed through, since a JSON Schema needs a
|
|
119
|
+
* validator this loop has no business carrying. A throwing resolver or
|
|
120
|
+
* refinement rejects only that call, without forwarding private exception text.
|
|
121
|
+
*/
|
|
122
|
+
export declare const validateToolInput: (tool: Tool | undefined, input: unknown) => Promise<ReturnType<typeof parseToolInput>>;
|
|
102
123
|
/**
|
|
103
124
|
* Spell a JSON Schema into the conversation's system turn.
|
|
104
125
|
*
|
|
@@ -324,7 +324,7 @@ const readTotal = (value) => typeof value === "object" &&
|
|
|
324
324
|
* second case ran the tool with empty input and reported success, so a
|
|
325
325
|
* malformed call looked identical to a legitimate no-arg one.
|
|
326
326
|
*/
|
|
327
|
-
const parseToolInput = (raw) => {
|
|
327
|
+
export const parseToolInput = (raw) => {
|
|
328
328
|
if (typeof raw !== "string") {
|
|
329
329
|
return { input: raw ?? {} };
|
|
330
330
|
}
|
|
@@ -376,24 +376,32 @@ function declaredInputSchema(name, tool) {
|
|
|
376
376
|
* not, so a call whose shape the tool rejects reached `execute` and failed
|
|
377
377
|
* inside user code — or worse, did not fail. A Zod schema is detected by
|
|
378
378
|
* `safeParse`; anything else is passed through, since a JSON Schema needs a
|
|
379
|
-
* validator this loop has no business carrying.
|
|
379
|
+
* validator this loop has no business carrying. A throwing resolver or
|
|
380
|
+
* refinement rejects only that call, without forwarding private exception text.
|
|
380
381
|
*/
|
|
381
|
-
const validateToolInput = (tool, input) => {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
382
|
+
export const validateToolInput = async (tool, input) => {
|
|
383
|
+
try {
|
|
384
|
+
const schema = tool?.inputSchema
|
|
385
|
+
? resolveToolInputSchema(tool.inputSchema)
|
|
386
|
+
: undefined;
|
|
387
|
+
if (!schema ||
|
|
388
|
+
typeof schema !== "object" ||
|
|
389
|
+
!("safeParse" in schema) ||
|
|
390
|
+
typeof schema.safeParse !== "function") {
|
|
391
|
+
return { input };
|
|
392
|
+
}
|
|
393
|
+
const result = "safeParseAsync" in schema && typeof schema.safeParseAsync === "function"
|
|
394
|
+
? await schema.safeParseAsync(input)
|
|
395
|
+
: schema.safeParse(input);
|
|
396
|
+
if (result.success) {
|
|
397
|
+
return { input: result.data };
|
|
398
|
+
}
|
|
399
|
+
const detail = result.error instanceof Error ? result.error.message : "schema mismatch";
|
|
400
|
+
return { input, error: `input did not match the tool's schema: ${detail}` };
|
|
390
401
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
return undefined;
|
|
402
|
+
catch {
|
|
403
|
+
return { input, error: "input schema validation threw" };
|
|
394
404
|
}
|
|
395
|
-
const detail = result.error instanceof Error ? result.error.message : "schema mismatch";
|
|
396
|
-
return `input did not match the tool's schema: ${detail}`;
|
|
397
405
|
};
|
|
398
406
|
/**
|
|
399
407
|
* Spell a JSON Schema into the conversation's system turn.
|
|
@@ -745,16 +753,16 @@ async function runGenerateSteps(args, toolExecutionSummaries, stepSpans) {
|
|
|
745
753
|
const id = String(call.toolCallId ?? "");
|
|
746
754
|
const startTime = new Date();
|
|
747
755
|
const parsed = parseToolInput(call.input);
|
|
748
|
-
const input = parsed.input;
|
|
749
756
|
// resolveLiveTool also loads a deferred tool the model called by its
|
|
750
757
|
// catalog name without searching first.
|
|
751
758
|
const tool = resolveLiveTool(args.toolsRecord, name);
|
|
759
|
+
const validated = parsed.error || typeof tool?.execute !== "function"
|
|
760
|
+
? parsed
|
|
761
|
+
: await validateToolInput(tool, parsed.input);
|
|
762
|
+
const input = validated.input;
|
|
752
763
|
let output;
|
|
753
764
|
let failure;
|
|
754
|
-
const rejection =
|
|
755
|
-
(typeof tool?.execute === "function"
|
|
756
|
-
? validateToolInput(tool, input)
|
|
757
|
-
: undefined);
|
|
765
|
+
const rejection = validated.error;
|
|
758
766
|
if (typeof tool?.execute !== "function") {
|
|
759
767
|
failure = `Tool not found: ${name}`;
|
|
760
768
|
output = { error: failure };
|
package/dist/index.d.ts
CHANGED
|
@@ -460,7 +460,7 @@ export { DEFAULT_COMPACTION_THRESHOLD, resolveHistoryBudget, } from "./context/b
|
|
|
460
460
|
* await server.start();
|
|
461
461
|
* ```
|
|
462
462
|
*/
|
|
463
|
-
export { AgentExecuteRequestSchema, AlreadyRunningError, BaseServerAdapter, ConfigurationError, createAgentRoutes, createAgentWebSocketHandler, createAllRoutes, createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompressionMiddleware, createDataStreamResponse, createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware, createServer, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes, ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError, pipeAsyncIterableToDataStream, RouteConflictError, RouteNotFoundError, registerAllRoutes, ServerAdapterError, ServerAdapterErrorCode, ServerAdapterFactory, ServerAuthenticationError, ServerAuthorizationError, ServerNameParamSchema, ServerRateLimitError, ServerStartError, ServerStopError, ServerTimeoutError, ServerValidationError, SessionIdParamSchema, StreamAbortedError, StreamingError, ToolArgumentsSchema, ToolExecuteRequestSchema, ToolNameParamSchema, ToolSearchQuerySchema, ValidationError, validateParams, validateQuery, validateRequest, WebSocketConnectionError, WebSocketConnectionManager, WebSocketError, WebSocketMessageRouter, wrapError, } from "./server/index.js";
|
|
463
|
+
export { AgentExecuteRequestSchema, AlreadyRunningError, BaseServerAdapter, ConfigurationError, createAgentRoutes, createAgentWebSocketHandler, createAllRoutes, createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompressionMiddleware, createDataStreamResponse, createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware, createServer, createSessionMiddleware, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes, ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError, pipeAsyncIterableToDataStream, RouteConflictError, RouteNotFoundError, registerAllRoutes, ServerAdapterError, ServerAdapterErrorCode, ServerAdapterFactory, ServerAuthenticationError, ServerAuthorizationError, ServerNameParamSchema, ServerRateLimitError, ServerStartError, ServerStopError, ServerTimeoutError, ServerValidationError, SessionIdParamSchema, StreamAbortedError, StreamingError, ToolArgumentsSchema, ToolExecuteRequestSchema, ToolNameParamSchema, ToolSearchQuerySchema, ValidationError, validateParams, validateQuery, validateRequest, WebSocketConnectionError, WebSocketConnectionManager, WebSocketError, WebSocketMessageRouter, wrapError, } from "./server/index.js";
|
|
464
464
|
/**
|
|
465
465
|
* @deprecated Use `ServerTimeoutError` instead — renamed to end the naming
|
|
466
466
|
* collision with the canonical `utils/timeout.ts` `TimeoutError`. Kept as an
|
package/dist/index.js
CHANGED
|
@@ -701,7 +701,7 @@ createAuthMiddleware, createCacheInvalidator, createCacheMiddleware, createCompr
|
|
|
701
701
|
// Streaming
|
|
702
702
|
createDataStreamWriter, createErrorHandlingMiddleware, createErrorResponse, createFieldValidator, createHealthRoutes, createLoggingMiddleware, createMCPRoutes, createMemoryRoutes, createNDJSONHeaders, createOpenAPIGenerator, createRateLimitMiddleware, createRequestIdMiddleware, createRequestValidationMiddleware, createRoleMiddleware, createSecurityHeadersMiddleware,
|
|
703
703
|
// Server Factory
|
|
704
|
-
createServer, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes,
|
|
704
|
+
createServer, createSessionMiddleware, createSlidingWindowRateLimitMiddleware, createSSEHeaders, createTimingMiddleware, createToolRoutes,
|
|
705
705
|
// Error Constants
|
|
706
706
|
ErrorCategory, ErrorRecoveryStrategies, ErrorSeverity, ExpressServerAdapter, FastifyServerAdapter, generateOpenAPIFromConfig, generateOpenAPISpec, HandlerError, HonoServerAdapter, InMemoryCacheStore, InMemoryRateLimitStore, InvalidAuthenticationError, KoaServerAdapter, MissingDependencyError, NotRunningError,
|
|
707
707
|
// OpenAPI
|
|
@@ -48,8 +48,19 @@ import { SpanStatusCode } from "@opentelemetry/api";
|
|
|
48
48
|
// listener under the hood). This restores stdin's normal, non-unref'd
|
|
49
49
|
// behavior for any real consumer — internal or external — while a process
|
|
50
50
|
// that never touches stdin still exits on its own.
|
|
51
|
+
//
|
|
52
|
+
// "newListener" only sees listeners added after this point. A consumer that
|
|
53
|
+
// was already reading stdin when it first imported this package — a stdio MCP
|
|
54
|
+
// server that connects its transport, then lazy-imports @juspay/neurolink —
|
|
55
|
+
// would never trigger it, and unref'ing its live stdin made the process exit
|
|
56
|
+
// mid-session with code 0. So leave stdin alone when a consumer is already
|
|
57
|
+
// attached.
|
|
51
58
|
if (process.stdin && typeof process.stdin.unref === "function") {
|
|
52
|
-
process.stdin.
|
|
59
|
+
const stdinAlreadyConsumed = process.stdin.listenerCount("data") > 0 ||
|
|
60
|
+
process.stdin.listenerCount("readable") > 0;
|
|
61
|
+
if (!stdinAlreadyConsumed) {
|
|
62
|
+
process.stdin.unref();
|
|
63
|
+
}
|
|
53
64
|
process.stdin.prependListener("newListener", (event) => {
|
|
54
65
|
if (event === "data" || event === "readable") {
|
|
55
66
|
process.stdin.ref();
|
|
@@ -36,7 +36,7 @@ import { NoOutputGeneratedError } from "../utils/generationErrors.js";
|
|
|
36
36
|
import { buildNoOutputSentinel, stampNoOutputSpan, } from "../utils/noOutputSentinel.js";
|
|
37
37
|
import { composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, TimeoutError, } from "../utils/timeout.js";
|
|
38
38
|
import { resolveRequestKind } from "../core/resolveRequestKind.js";
|
|
39
|
-
import { appendJsonSchemaInstruction, hasNativeDoGenerate, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, } from "../core/nativeGenerateLoop.js";
|
|
39
|
+
import { appendJsonSchemaInstruction, hasNativeDoGenerate, parseToolInput, resolveStepToolChoice, runNativeGenerateLoop, toNativeToolDeclaration, toPrepareStepRecord, validateToolInput, } from "../core/nativeGenerateLoop.js";
|
|
40
40
|
import { resolveToolExecutionRecords, toolCallsFromSummaries, } from "../core/toolExecutionRecorder.js";
|
|
41
41
|
import { convertZodToJsonSchema } from "../utils/schemaConversion.js";
|
|
42
42
|
import { coerceJsonToSchema, recoverScalarRoot, schemaAccepts, } from "../utils/json/coerce.js";
|
|
@@ -2408,13 +2408,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2408
2408
|
});
|
|
2409
2409
|
for (const [, t] of stepResult.toolCalls) {
|
|
2410
2410
|
const startedAt = new Date();
|
|
2411
|
-
|
|
2412
|
-
try {
|
|
2413
|
-
input = JSON.parse(t.argsBuffered || "{}");
|
|
2414
|
-
}
|
|
2415
|
-
catch {
|
|
2416
|
-
input = t.argsBuffered;
|
|
2417
|
-
}
|
|
2411
|
+
const parsed = parseToolInput(t.argsBuffered);
|
|
2418
2412
|
let output;
|
|
2419
2413
|
let errorMsg;
|
|
2420
2414
|
// The model calls tools by their WIRE names; execution, events, and
|
|
@@ -2426,6 +2420,11 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2426
2420
|
// loaded via search_tools — that's a real tool, not a hallucination.
|
|
2427
2421
|
const toolDef = toolsRecord[registryName] ??
|
|
2428
2422
|
resolveDeferredTool(toolsRecord, registryName);
|
|
2423
|
+
const validated = parsed.error || typeof toolDef?.execute !== "function"
|
|
2424
|
+
? parsed
|
|
2425
|
+
: await validateToolInput(toolDef, parsed.input);
|
|
2426
|
+
const input = validated.input;
|
|
2427
|
+
const rejection = validated.error;
|
|
2429
2428
|
// No `tool:start` here either: registered and built-in tools emit their
|
|
2430
2429
|
// own start/end pair from the executor that runs them, and this raw
|
|
2431
2430
|
// emission made every one of them count twice.
|
|
@@ -2435,6 +2434,11 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
2435
2434
|
// Rejected before any execute ran, so no executor will report it.
|
|
2436
2435
|
this.emitRejectedToolCall(registryName, errorMsg, t.id);
|
|
2437
2436
|
}
|
|
2437
|
+
else if (rejection) {
|
|
2438
|
+
errorMsg = `Tool '${registryName}': ${rejection}`;
|
|
2439
|
+
output = { error: errorMsg };
|
|
2440
|
+
this.emitRejectedToolCall(registryName, errorMsg, t.id);
|
|
2441
|
+
}
|
|
2438
2442
|
else {
|
|
2439
2443
|
try {
|
|
2440
2444
|
output = await toolDef.execute(input, {});
|
|
@@ -727,6 +727,8 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
727
727
|
let parseErr;
|
|
728
728
|
// Key of the tool call the previous delta wrote to (for unindexed deltas).
|
|
729
729
|
let lastToolCallKey;
|
|
730
|
+
let nextToolCallKey = 0;
|
|
731
|
+
const toolCallKeysById = new Map();
|
|
730
732
|
const handleEvent = (msg) => {
|
|
731
733
|
const data = msg.data;
|
|
732
734
|
if (!data || data === "[DONE]") {
|
|
@@ -770,24 +772,53 @@ export const parseSSEStream = async (body, onTextDelta, onReasoningDelta) => {
|
|
|
770
772
|
}
|
|
771
773
|
if (delta?.tool_calls) {
|
|
772
774
|
for (const tc of delta.tool_calls) {
|
|
775
|
+
if (tc.index !== undefined &&
|
|
776
|
+
(!Number.isSafeInteger(tc.index) ||
|
|
777
|
+
tc.index < 0 ||
|
|
778
|
+
tc.index >= Number.MAX_SAFE_INTEGER)) {
|
|
779
|
+
parseErr = new Error("Streamed tool call has an invalid index");
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
const id = typeof tc.id === "string" && tc.id.length > 0 ? tc.id : undefined;
|
|
783
|
+
const knownKey = id === undefined ? undefined : toolCallKeysById.get(id);
|
|
773
784
|
// Gemini's OpenAI-compatible endpoint omits `index`: an unindexed
|
|
774
|
-
//
|
|
785
|
+
// repeated id continues its own call. A new identity/name starts a
|
|
786
|
+
// call; anonymous fragments continue the last call. Allocation stays
|
|
787
|
+
// constant-time instead of rescanning every earlier stream entry.
|
|
775
788
|
const index = tc.index ??
|
|
776
|
-
|
|
777
|
-
|
|
789
|
+
knownKey ??
|
|
790
|
+
(id || tc.function?.name || lastToolCallKey === undefined
|
|
791
|
+
? nextToolCallKey
|
|
778
792
|
: lastToolCallKey);
|
|
793
|
+
if (!Number.isSafeInteger(index) ||
|
|
794
|
+
index >= Number.MAX_SAFE_INTEGER ||
|
|
795
|
+
(knownKey !== undefined && knownKey !== index)) {
|
|
796
|
+
parseErr = new Error("Streamed tool call has a conflicting identity");
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
nextToolCallKey = Math.max(nextToolCallKey, index + 1);
|
|
779
800
|
lastToolCallKey = index;
|
|
780
801
|
let state = result.toolCalls.get(index);
|
|
802
|
+
if (state &&
|
|
803
|
+
id !== undefined &&
|
|
804
|
+
state.id !== id &&
|
|
805
|
+
toolCallKeysById.has(state.id)) {
|
|
806
|
+
parseErr = new Error("Streamed tool call has a conflicting identity");
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
781
809
|
if (!state) {
|
|
782
810
|
state = {
|
|
783
|
-
id:
|
|
811
|
+
id: id ?? `call_${index}_${Date.now()}`,
|
|
784
812
|
name: tc.function?.name ?? "",
|
|
785
813
|
argsBuffered: "",
|
|
786
814
|
};
|
|
787
815
|
result.toolCalls.set(index, state);
|
|
788
816
|
}
|
|
789
|
-
else if (
|
|
790
|
-
state.id =
|
|
817
|
+
else if (id !== undefined) {
|
|
818
|
+
state.id = id;
|
|
819
|
+
}
|
|
820
|
+
if (id !== undefined) {
|
|
821
|
+
toolCallKeysById.set(id, index);
|
|
791
822
|
}
|
|
792
823
|
if (tc.function?.name) {
|
|
793
824
|
state.name = tc.function.name;
|
|
@@ -107,16 +107,19 @@ export function parseClaudeRequest(body) {
|
|
|
107
107
|
}
|
|
108
108
|
else if (block.type === "image") {
|
|
109
109
|
if (isLatestUserMsg) {
|
|
110
|
-
// Current turn: extract full URI to top-level images for the pipeline
|
|
111
|
-
|
|
112
|
-
|
|
110
|
+
// Current turn: extract full URI to top-level images for the pipeline.
|
|
111
|
+
// An empty payload or URL is kept (as `data:<type>;base64,` or ""),
|
|
112
|
+
// never skipped: the image vetter refuses it, so a request that
|
|
113
|
+
// names a picture and supplies none is not sent on without it.
|
|
114
|
+
let imageUri;
|
|
115
|
+
if (block.source.type === "base64") {
|
|
113
116
|
const mediaType = block.source.media_type || "image/png";
|
|
114
|
-
imageUri = `data:${mediaType};base64,${block.source.data}`;
|
|
117
|
+
imageUri = `data:${mediaType};base64,${block.source.data ?? ""}`;
|
|
115
118
|
}
|
|
116
|
-
else if (block.source.type === "url"
|
|
117
|
-
imageUri = block.source.url;
|
|
119
|
+
else if (block.source.type === "url") {
|
|
120
|
+
imageUri = block.source.url ?? "";
|
|
118
121
|
}
|
|
119
|
-
if (imageUri) {
|
|
122
|
+
if (imageUri !== undefined) {
|
|
120
123
|
images.push(imageUri);
|
|
121
124
|
}
|
|
122
125
|
}
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* its own usage line, so getting them wrong is visible to the user rather than
|
|
19
19
|
* merely wrong in a log.
|
|
20
20
|
*/
|
|
21
|
+
import { toStandardBase64 } from "./proxyImageInput.js";
|
|
21
22
|
/** Google's role for assistant turns. */
|
|
22
23
|
const MODEL_ROLE = "model";
|
|
23
24
|
/**
|
|
@@ -39,30 +40,6 @@ function partsToText(parts) {
|
|
|
39
40
|
}
|
|
40
41
|
/** `image/<subtype>` as a MIME restricted-name (RFC 6838): no space, comma or semicolon. */
|
|
41
42
|
const IMAGE_MIME_TYPE = /^image\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/i;
|
|
42
|
-
/** Standard or URL-safe base64, the two alphabets Google's JSON `bytes` fields accept. */
|
|
43
|
-
const RAW_BASE64 = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
44
|
-
/**
|
|
45
|
-
* `data` as padded standard-alphabet base64, which is what a `data:` URI carries,
|
|
46
|
-
* or undefined when it is not well-formed base64.
|
|
47
|
-
*
|
|
48
|
-
* The SDK forwards the base64 text of a `data:` URI to the provider as it is, so
|
|
49
|
-
* a URL-safe or unpadded payload would reach a provider that expects neither.
|
|
50
|
-
* The alphabet check alone lets through a payload no decoder takes: one
|
|
51
|
-
* character over a multiple of four is no base64 length at all, and padding
|
|
52
|
-
* must be exactly what the length calls for.
|
|
53
|
-
*/
|
|
54
|
-
function toStandardBase64(data) {
|
|
55
|
-
const standard = /[-_]/.test(data)
|
|
56
|
-
? data.replace(/-/g, "+").replace(/_/g, "/")
|
|
57
|
-
: data;
|
|
58
|
-
const body = standard.replace(/=+$/, "");
|
|
59
|
-
const padding = standard.length - body.length;
|
|
60
|
-
const missing = (4 - (body.length % 4)) % 4;
|
|
61
|
-
if (missing === 3 || (padding > 0 && padding !== missing)) {
|
|
62
|
-
return undefined;
|
|
63
|
-
}
|
|
64
|
-
return `${body}${"=".repeat(missing)}`;
|
|
65
|
-
}
|
|
66
43
|
/**
|
|
67
44
|
* The `input.images` entry for one `inlineData`, or undefined when it has none.
|
|
68
45
|
*
|
|
@@ -77,22 +54,41 @@ function toStandardBase64(data) {
|
|
|
77
54
|
* `mimeType`, an impossible length or inconsistent padding is refused there as
|
|
78
55
|
* `invalid_image_reference`. Audio and PDF parts land in the same place; this
|
|
79
56
|
* parser has never told them from images.
|
|
57
|
+
*
|
|
58
|
+
* Wrapping is not a verdict that the bytes are an image. Base64 text of a
|
|
59
|
+
* decodable length is wrapped whatever it decodes to (a path such as
|
|
60
|
+
* `/var/tmp/name` is made only of base64 characters), and the vetter then
|
|
61
|
+
* refuses it as `invalid_image_data` unless the bytes are a recognised image.
|
|
62
|
+
* It also replaces the declared `mimeType` with the type the bytes have.
|
|
63
|
+
*
|
|
64
|
+
* A part that declares an image type but carries no bytes (`data` empty,
|
|
65
|
+
* absent, or not a string at all) is an image with an empty payload, not a part without an image, so it
|
|
66
|
+
* is wrapped as `data:<mimeType>;base64,` and the vetter refuses it as
|
|
67
|
+
* `invalid_image_data`. Dropping it here would send the rest of the request
|
|
68
|
+
* upstream as though the client had never attached a picture. Without an image
|
|
69
|
+
* type there is nothing to call it an image by, and the part is left out as it
|
|
70
|
+
* always was.
|
|
80
71
|
*/
|
|
81
72
|
function inlineDataToImage(inlineData) {
|
|
82
73
|
const data = inlineData?.data;
|
|
83
|
-
if (typeof data !== "string" || data.length === 0) {
|
|
84
|
-
return undefined;
|
|
85
|
-
}
|
|
86
74
|
const mimeType = inlineData?.mimeType;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
75
|
+
const imageType = typeof mimeType === "string" && IMAGE_MIME_TYPE.test(mimeType)
|
|
76
|
+
? mimeType.toLowerCase()
|
|
77
|
+
: undefined;
|
|
78
|
+
if (data === undefined || data === "") {
|
|
79
|
+
return imageType === undefined ? undefined : `data:${imageType};base64,`;
|
|
80
|
+
}
|
|
81
|
+
if (typeof data !== "string") {
|
|
82
|
+
// `data: null`, a number or an object under an image type is still an
|
|
83
|
+
// image slot with no usable payload: refuse it like an empty one rather
|
|
84
|
+
// than drop the picture and send the rest of the request on.
|
|
85
|
+
return imageType === undefined ? undefined : `data:${imageType};base64,`;
|
|
86
|
+
}
|
|
87
|
+
if (imageType === undefined) {
|
|
90
88
|
return data;
|
|
91
89
|
}
|
|
92
90
|
const standard = toStandardBase64(data);
|
|
93
|
-
return standard === undefined
|
|
94
|
-
? data
|
|
95
|
-
: `data:${mimeType.toLowerCase()};base64,${standard}`;
|
|
91
|
+
return standard === undefined ? data : `data:${imageType};base64,${standard}`;
|
|
96
92
|
}
|
|
97
93
|
function partsToImages(parts) {
|
|
98
94
|
if (!Array.isArray(parts)) {
|
|
@@ -10,14 +10,39 @@
|
|
|
10
10
|
* names its own files. Neither suits a request that arrived over a socket.
|
|
11
11
|
*
|
|
12
12
|
* So the proxy resolves every reference itself and hands the SDK nothing but
|
|
13
|
-
*
|
|
14
|
-
* - `data:` URIs
|
|
13
|
+
* images it has checked:
|
|
14
|
+
* - `data:` URIs carry their own content. The payload is decoded strictly (an
|
|
15
|
+
* alphabet, length or padding no decoder takes is refused) and its leading
|
|
16
|
+
* bytes must be a recognised image, whatever the URI says it is. The SDK is
|
|
17
|
+
* handed `data:<detected type>;base64,<standard payload>`: the type comes
|
|
18
|
+
* from the bytes, never from the client, so a JPEG labelled `image/png`
|
|
19
|
+
* reaches the provider as `image/jpeg`;
|
|
15
20
|
* - `https://` URLs are downloaded with the same helper the agent routes use
|
|
16
21
|
* (`resolveAgentInput` -> `safeDownload`): redirects refused, addresses
|
|
17
|
-
* checked, size capped
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
22
|
+
* checked, size capped. The bytes must then be a recognised image too, or
|
|
23
|
+
* the URL is refused, so a page that answers `200 text/html` is never sent
|
|
24
|
+
* on as a picture. The SDK reads the type of those bytes itself, from the
|
|
25
|
+
* same signatures;
|
|
26
|
+
* - everything else (local paths, `http://`, `file://`, any other scheme, an
|
|
27
|
+
* empty string) is refused before the file system or the network is
|
|
28
|
+
* touched, so the answer for a path that exists and one that does not is the
|
|
29
|
+
* same.
|
|
30
|
+
*
|
|
31
|
+
* An image slot that carries nothing is refused too, never skipped. The doors
|
|
32
|
+
* hand over what the client sent: an empty `data:` payload (an OpenAI
|
|
33
|
+
* `data:image/png;base64,`, a Claude `base64` source or a Gemini `inlineData`
|
|
34
|
+
* of an image type whose `data` is empty or absent) is `invalid_image_data`, and
|
|
35
|
+
* an empty URL (an OpenAI `image_url.url` or a Claude `url` source) is
|
|
36
|
+
* `invalid_image_reference`.
|
|
37
|
+
*
|
|
38
|
+
* "A recognised image" is a file signature (`sniffInputImageMimeType`): PNG,
|
|
39
|
+
* JPEG, WebP and GIF, which every provider takes, and HEIC, HEIF, AVIF, BMP,
|
|
40
|
+
* TIFF, ICO and JPEG 2000, which no provider except Google (HEIC and HEIF only)
|
|
41
|
+
* takes. The SDK tries to convert those seven to PNG before dispatch, for every
|
|
42
|
+
* provider, Google included; when neither sharp nor ffmpeg can read the file it
|
|
43
|
+
* sends the original bytes under the detected type. SVG is markup and is
|
|
44
|
+
* refused. Nothing in the proxy decodes the picture: a body that is corrupt
|
|
45
|
+
* after a valid signature is the provider's to refuse.
|
|
21
46
|
*
|
|
22
47
|
* Unlike the agent routes there is no allowed-roots setting: the proxy listens
|
|
23
48
|
* on loopback without credentials by default, and a path allow-list on a server
|
|
@@ -36,19 +61,42 @@
|
|
|
36
61
|
* @module proxy/proxyImageInput
|
|
37
62
|
*/
|
|
38
63
|
import { ProxyContextPreflightError } from "./proxyContextPreflight.js";
|
|
64
|
+
/**
|
|
65
|
+
* `data` as padded standard-alphabet base64, which is what a `data:` URI carries,
|
|
66
|
+
* or undefined when it is not well-formed base64.
|
|
67
|
+
*
|
|
68
|
+
* The SDK forwards the base64 text of a `data:` URI to the provider as it is, so
|
|
69
|
+
* a URL-safe or unpadded payload would reach a provider that expects neither.
|
|
70
|
+
* The alphabet check alone lets through a payload no decoder takes: one
|
|
71
|
+
* character over a multiple of four is no base64 length at all, and padding
|
|
72
|
+
* must be exactly what the length calls for. An empty string is not base64.
|
|
73
|
+
*
|
|
74
|
+
* One rule for every door: the Gemini parser applies it before wrapping raw
|
|
75
|
+
* `inlineData`, and the vetter applies it again to every `data:` URI it is given.
|
|
76
|
+
*/
|
|
77
|
+
export declare function toStandardBase64(data: string): string | undefined;
|
|
39
78
|
/** An image reference the proxy refuses; answers 400 in the client's format. */
|
|
40
79
|
export declare class ProxyImageInputError extends ProxyContextPreflightError {
|
|
41
80
|
constructor(code: string, message: string);
|
|
42
81
|
}
|
|
43
82
|
/**
|
|
44
|
-
* Resolve one list of client image references to what the SDK may be given
|
|
83
|
+
* Resolve one list of client image references to what the SDK may be given:
|
|
84
|
+
* `data:` URIs rewritten to carry the type their bytes have, and downloaded
|
|
85
|
+
* bytes that are an image.
|
|
86
|
+
*
|
|
87
|
+
* Inline images are judged before anything is downloaded, so a request already
|
|
88
|
+
* doomed by one costs no network. Size and count are judged on the `data:` URIs
|
|
89
|
+
* as the client sent them (their string length), then on the downloads (their
|
|
90
|
+
* bytes), exactly as the agent routes judge them.
|
|
45
91
|
*
|
|
46
92
|
* `signal` cancels the work: a download in flight is aborted and no further
|
|
47
93
|
* reference is started. A cancellation rejects with the signal's own error, not
|
|
48
94
|
* with a {@link ProxyImageInputError}, since nothing was refused.
|
|
49
95
|
*
|
|
50
|
-
* @throws {ProxyImageInputError} for the first reference that is refused
|
|
51
|
-
*
|
|
96
|
+
* @throws {ProxyImageInputError} for the first reference that is refused
|
|
97
|
+
* (`invalid_image_reference`, `invalid_image_data`, `image_url_unfetchable`),
|
|
98
|
+
* or for a list that carries too many images or too many bytes
|
|
99
|
+
* (`image_input_too_large`).
|
|
52
100
|
*/
|
|
53
101
|
export declare function vetProxyImages(images: readonly unknown[], signal?: AbortSignal): Promise<Array<string | Buffer>>;
|
|
54
102
|
/**
|