@kenkaiiii/gg-ai 5.68.0 → 5.69.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/dist/index.d.cts CHANGED
@@ -186,8 +186,24 @@ interface Usage {
186
186
  webFetchRequests?: number;
187
187
  };
188
188
  }
189
+ interface PreparedContext {
190
+ /** Read-only observation after generic sanitization/image limiting, before provider encoding.
191
+ * Do not log or retain these messages: they may contain secrets and image data. */
192
+ messages: readonly Message[];
193
+ tools: readonly {
194
+ name: string;
195
+ description: string;
196
+ parameters: Record<string, unknown>;
197
+ }[];
198
+ imagesBefore: number;
199
+ imagesAfter: number;
200
+ /** First message whose images were removed for this request, or null. */
201
+ firstImageDropMessage: number | null;
202
+ }
189
203
  interface StreamOptions {
190
204
  provider: Provider;
205
+ /** Optional, synchronous diagnostics observer. Exceptions cannot fail a model request. */
206
+ onContextPrepared?: (context: PreparedContext) => void;
191
207
  model: string;
192
208
  messages: Message[];
193
209
  tools?: Tool[];
@@ -578,18 +594,85 @@ type JsonSchema = Record<string, unknown>;
578
594
  /**
579
595
  * Resolve a tool's JSON Schema for provider tool definitions: prefer the
580
596
  * tool's pre-built `rawInputSchema`, otherwise convert its Zod `parameters`.
597
+ *
598
+ * A no-argument tool may declare a bare `{ "type": "object" }` root (common
599
+ * for MCP servers). OpenAI rejects that root with HTTP 400 "object schema
600
+ * missing properties", failing the whole request, so an object root without
601
+ * `properties` gets an explicit empty one. JSON Schema meaning is unchanged.
581
602
  */
582
603
  declare function resolveToolSchema(tool: Tool): JsonSchema;
583
604
 
584
605
  /**
585
- * Cap historical images before provider dispatch, removing the oldest first.
606
+ * Cap historical images before provider dispatch, removing the oldest first, in batches so the
607
+ * cached conversation prefix stays byte-identical between requests.
586
608
  * The persisted/live conversation is never mutated; only modified messages and
587
609
  * tool results are cloned for the outgoing request.
588
610
  */
589
611
  declare function clampProviderContextImages(messages: Message[], provider: Provider, supportsImages: boolean | undefined): Message[];
612
+ /**
613
+ * What a provider accepts as a replayed tool-call name. `pattern` already
614
+ * encodes the length limit where the provider documents one; `maxLength` is
615
+ * checked separately so the generic rule can cap length without a charset.
616
+ */
617
+ interface ToolCallNameRule {
618
+ /** Short identifier, for diagnostics and tests. */
619
+ id: "anthropic" | "openai-chat" | "openai-responses" | "gemini" | "generic";
620
+ maxLength: number;
621
+ pattern?: RegExp;
622
+ }
623
+ /**
624
+ * Per-transport tool-name rules. A legitimate call always carries the name of a
625
+ * tool we declared, and tool declarations are validated against these same
626
+ * rules, so only model-invented names (blank, invocation text stuffed into the
627
+ * name slot, …) can fail them.
628
+ */
629
+ declare const TOOL_CALL_NAME_RULES: Record<ToolCallNameRule["id"], ToolCallNameRule>;
630
+ /** True when `name` is a tool-call name the provider described by `rule` will accept. */
631
+ declare function isValidToolCallName(name: unknown, rule: ToolCallNameRule): boolean;
632
+ /**
633
+ * Pick the tool-name rule for the transport a request will actually use. Mirrors
634
+ * the routing in `stream.ts`: `openai` with an `accountId` is the Codex
635
+ * (Responses) endpoint, MiniMax rides the Anthropic transport but is a third
636
+ * party, and an `openai` pointed at a custom baseUrl is an unknown compatible
637
+ * server.
638
+ */
639
+ declare function toolCallNameRuleFor(provider: Provider | string, options?: {
640
+ accountId?: string;
641
+ baseUrl?: string;
642
+ }): ToolCallNameRule;
643
+ /**
644
+ * Drop assistant tool calls whose name (or id) the target provider rejects,
645
+ * together with the tool results that answer them.
646
+ *
647
+ * One malformed call — a blank name, a whole invocation string written into the
648
+ * name slot, a name over the provider's length limit — would otherwise sit in
649
+ * history and 400 every later request (`tool_use.name: String should match
650
+ * pattern`, `string_above_max_length`, …), wedging the session.
651
+ *
652
+ * Pairing is positional per window: each assistant turn opens a window, and its
653
+ * results (role `tool`) are matched FIFO per id until the next assistant or user
654
+ * message, so a reused id never consumes another turn's result. Valid sibling
655
+ * calls, text and thinking are kept in place. An assistant turn left with
656
+ * nothing replayable is removed whole, as is a tool message left empty — every
657
+ * transport accepts the resulting adjacent user turns (the Anthropic API
658
+ * combines consecutive same-role turns). A Codex reasoning item orphaned by the
659
+ * drop is removed too. If the drop would leave the request ENDING on that
660
+ * pruned assistant turn (its only call was the bad one, so no results follow),
661
+ * the turn is removed as well: a trailing assistant message is an assistant
662
+ * prefill, which current Claude models reject and other APIs treat as a
663
+ * continuation rather than a fresh turn.
664
+ *
665
+ * Returns the input array untouched when nothing is malformed.
666
+ */
667
+ declare function dropInvalidToolCalls(messages: Message[], rule: ToolCallNameRule): Message[];
590
668
  declare function toAnthropicMessages(messages: Message[], cacheControl?: {
591
669
  type: "ephemeral";
592
670
  ttl?: "1h";
671
+ }, options?: {
672
+ /** Replay server-side refusal `fallback` blocks in place. Only set when the
673
+ * request carries the server-side-fallback beta; otherwise they are
674
+ * stripped (after applying the replay rules). Default false. */
675
+ fallbackBlocks?: boolean;
593
676
  }): {
594
677
  system: Anthropic.TextBlockParam[] | undefined;
595
678
  messages: Anthropic.MessageParam[];
@@ -693,4 +776,4 @@ interface PalsuProviderConfig {
693
776
  */
694
777
  declare function registerPalsuProvider(config?: PalsuProviderConfig): PalsuProviderHandle;
695
778
 
696
- export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, environmentSecrets, formatError, formatErrorForDisplay, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, localWireModelId, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText };
779
+ export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreparedContext, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, TOOL_CALL_NAME_RULES, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolCallNameRule, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, dropInvalidToolCalls, environmentSecrets, formatError, formatErrorForDisplay, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, isValidToolCallName, localWireModelId, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor };
package/dist/index.d.ts CHANGED
@@ -186,8 +186,24 @@ interface Usage {
186
186
  webFetchRequests?: number;
187
187
  };
188
188
  }
189
+ interface PreparedContext {
190
+ /** Read-only observation after generic sanitization/image limiting, before provider encoding.
191
+ * Do not log or retain these messages: they may contain secrets and image data. */
192
+ messages: readonly Message[];
193
+ tools: readonly {
194
+ name: string;
195
+ description: string;
196
+ parameters: Record<string, unknown>;
197
+ }[];
198
+ imagesBefore: number;
199
+ imagesAfter: number;
200
+ /** First message whose images were removed for this request, or null. */
201
+ firstImageDropMessage: number | null;
202
+ }
189
203
  interface StreamOptions {
190
204
  provider: Provider;
205
+ /** Optional, synchronous diagnostics observer. Exceptions cannot fail a model request. */
206
+ onContextPrepared?: (context: PreparedContext) => void;
191
207
  model: string;
192
208
  messages: Message[];
193
209
  tools?: Tool[];
@@ -578,18 +594,85 @@ type JsonSchema = Record<string, unknown>;
578
594
  /**
579
595
  * Resolve a tool's JSON Schema for provider tool definitions: prefer the
580
596
  * tool's pre-built `rawInputSchema`, otherwise convert its Zod `parameters`.
597
+ *
598
+ * A no-argument tool may declare a bare `{ "type": "object" }` root (common
599
+ * for MCP servers). OpenAI rejects that root with HTTP 400 "object schema
600
+ * missing properties", failing the whole request, so an object root without
601
+ * `properties` gets an explicit empty one. JSON Schema meaning is unchanged.
581
602
  */
582
603
  declare function resolveToolSchema(tool: Tool): JsonSchema;
583
604
 
584
605
  /**
585
- * Cap historical images before provider dispatch, removing the oldest first.
606
+ * Cap historical images before provider dispatch, removing the oldest first, in batches so the
607
+ * cached conversation prefix stays byte-identical between requests.
586
608
  * The persisted/live conversation is never mutated; only modified messages and
587
609
  * tool results are cloned for the outgoing request.
588
610
  */
589
611
  declare function clampProviderContextImages(messages: Message[], provider: Provider, supportsImages: boolean | undefined): Message[];
612
+ /**
613
+ * What a provider accepts as a replayed tool-call name. `pattern` already
614
+ * encodes the length limit where the provider documents one; `maxLength` is
615
+ * checked separately so the generic rule can cap length without a charset.
616
+ */
617
+ interface ToolCallNameRule {
618
+ /** Short identifier, for diagnostics and tests. */
619
+ id: "anthropic" | "openai-chat" | "openai-responses" | "gemini" | "generic";
620
+ maxLength: number;
621
+ pattern?: RegExp;
622
+ }
623
+ /**
624
+ * Per-transport tool-name rules. A legitimate call always carries the name of a
625
+ * tool we declared, and tool declarations are validated against these same
626
+ * rules, so only model-invented names (blank, invocation text stuffed into the
627
+ * name slot, …) can fail them.
628
+ */
629
+ declare const TOOL_CALL_NAME_RULES: Record<ToolCallNameRule["id"], ToolCallNameRule>;
630
+ /** True when `name` is a tool-call name the provider described by `rule` will accept. */
631
+ declare function isValidToolCallName(name: unknown, rule: ToolCallNameRule): boolean;
632
+ /**
633
+ * Pick the tool-name rule for the transport a request will actually use. Mirrors
634
+ * the routing in `stream.ts`: `openai` with an `accountId` is the Codex
635
+ * (Responses) endpoint, MiniMax rides the Anthropic transport but is a third
636
+ * party, and an `openai` pointed at a custom baseUrl is an unknown compatible
637
+ * server.
638
+ */
639
+ declare function toolCallNameRuleFor(provider: Provider | string, options?: {
640
+ accountId?: string;
641
+ baseUrl?: string;
642
+ }): ToolCallNameRule;
643
+ /**
644
+ * Drop assistant tool calls whose name (or id) the target provider rejects,
645
+ * together with the tool results that answer them.
646
+ *
647
+ * One malformed call — a blank name, a whole invocation string written into the
648
+ * name slot, a name over the provider's length limit — would otherwise sit in
649
+ * history and 400 every later request (`tool_use.name: String should match
650
+ * pattern`, `string_above_max_length`, …), wedging the session.
651
+ *
652
+ * Pairing is positional per window: each assistant turn opens a window, and its
653
+ * results (role `tool`) are matched FIFO per id until the next assistant or user
654
+ * message, so a reused id never consumes another turn's result. Valid sibling
655
+ * calls, text and thinking are kept in place. An assistant turn left with
656
+ * nothing replayable is removed whole, as is a tool message left empty — every
657
+ * transport accepts the resulting adjacent user turns (the Anthropic API
658
+ * combines consecutive same-role turns). A Codex reasoning item orphaned by the
659
+ * drop is removed too. If the drop would leave the request ENDING on that
660
+ * pruned assistant turn (its only call was the bad one, so no results follow),
661
+ * the turn is removed as well: a trailing assistant message is an assistant
662
+ * prefill, which current Claude models reject and other APIs treat as a
663
+ * continuation rather than a fresh turn.
664
+ *
665
+ * Returns the input array untouched when nothing is malformed.
666
+ */
667
+ declare function dropInvalidToolCalls(messages: Message[], rule: ToolCallNameRule): Message[];
590
668
  declare function toAnthropicMessages(messages: Message[], cacheControl?: {
591
669
  type: "ephemeral";
592
670
  ttl?: "1h";
671
+ }, options?: {
672
+ /** Replay server-side refusal `fallback` blocks in place. Only set when the
673
+ * request carries the server-side-fallback beta; otherwise they are
674
+ * stripped (after applying the replay rules). Default false. */
675
+ fallbackBlocks?: boolean;
593
676
  }): {
594
677
  system: Anthropic.TextBlockParam[] | undefined;
595
678
  messages: Anthropic.MessageParam[];
@@ -693,4 +776,4 @@ interface PalsuProviderConfig {
693
776
  */
694
777
  declare function registerPalsuProvider(config?: PalsuProviderConfig): PalsuProviderHandle;
695
778
 
696
- export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, environmentSecrets, formatError, formatErrorForDisplay, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, localWireModelId, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText };
779
+ export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreparedContext, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, TOOL_CALL_NAME_RULES, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolCallNameRule, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, dropInvalidToolCalls, environmentSecrets, formatError, formatErrorForDisplay, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, isValidToolCallName, localWireModelId, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor };