@prestyj/ai 5.28.1 → 5.29.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[];
@@ -245,6 +261,14 @@ interface StreamOptions {
245
261
  * stalls — broken SSE connections (transient CDN / proxy issues) often
246
262
  * recover when the same request is issued over a plain HTTP request/response. */
247
263
  streaming?: boolean;
264
+ /** Cache prewarm (Anthropic only; other providers ignore it). Sends the exact
265
+ * same request prefix (system, tools, messages, thinking, betas) with
266
+ * `max_tokens: 1` over a non-streaming request so the prompt cache is written
267
+ * before the user's next real turn. If the configured thinking mode cannot be
268
+ * kept identical at `max_tokens: 1` (budget thinking requires
269
+ * budget_tokens < max_tokens), no request is sent and the response has
270
+ * zero usage with stopReason "end_turn". */
271
+ prewarm?: boolean;
248
272
  /** Override the User-Agent sent with OAuth-authenticated Anthropic requests.
249
273
  * Anthropic's OAuth edge rejects requests whose claude-cli version lags too
250
274
  * far behind the real Claude Code release; callers that track the live
@@ -570,18 +594,85 @@ type JsonSchema = Record<string, unknown>;
570
594
  /**
571
595
  * Resolve a tool's JSON Schema for provider tool definitions: prefer the
572
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.
573
602
  */
574
603
  declare function resolveToolSchema(tool: Tool): JsonSchema;
575
604
 
576
605
  /**
577
- * 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.
578
608
  * The persisted/live conversation is never mutated; only modified messages and
579
609
  * tool results are cloned for the outgoing request.
580
610
  */
581
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[];
582
668
  declare function toAnthropicMessages(messages: Message[], cacheControl?: {
583
669
  type: "ephemeral";
584
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;
585
676
  }): {
586
677
  system: Anthropic.TextBlockParam[] | undefined;
587
678
  messages: Anthropic.MessageParam[];
@@ -685,4 +776,4 @@ interface PalsuProviderConfig {
685
776
  */
686
777
  declare function registerPalsuProvider(config?: PalsuProviderConfig): PalsuProviderHandle;
687
778
 
688
- export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, 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, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, 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[];
@@ -245,6 +261,14 @@ interface StreamOptions {
245
261
  * stalls — broken SSE connections (transient CDN / proxy issues) often
246
262
  * recover when the same request is issued over a plain HTTP request/response. */
247
263
  streaming?: boolean;
264
+ /** Cache prewarm (Anthropic only; other providers ignore it). Sends the exact
265
+ * same request prefix (system, tools, messages, thinking, betas) with
266
+ * `max_tokens: 1` over a non-streaming request so the prompt cache is written
267
+ * before the user's next real turn. If the configured thinking mode cannot be
268
+ * kept identical at `max_tokens: 1` (budget thinking requires
269
+ * budget_tokens < max_tokens), no request is sent and the response has
270
+ * zero usage with stopReason "end_turn". */
271
+ prewarm?: boolean;
248
272
  /** Override the User-Agent sent with OAuth-authenticated Anthropic requests.
249
273
  * Anthropic's OAuth edge rejects requests whose claude-cli version lags too
250
274
  * far behind the real Claude Code release; callers that track the live
@@ -570,18 +594,85 @@ type JsonSchema = Record<string, unknown>;
570
594
  /**
571
595
  * Resolve a tool's JSON Schema for provider tool definitions: prefer the
572
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.
573
602
  */
574
603
  declare function resolveToolSchema(tool: Tool): JsonSchema;
575
604
 
576
605
  /**
577
- * 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.
578
608
  * The persisted/live conversation is never mutated; only modified messages and
579
609
  * tool results are cloned for the outgoing request.
580
610
  */
581
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[];
582
668
  declare function toAnthropicMessages(messages: Message[], cacheControl?: {
583
669
  type: "ephemeral";
584
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;
585
676
  }): {
586
677
  system: Anthropic.TextBlockParam[] | undefined;
587
678
  messages: Anthropic.MessageParam[];
@@ -685,4 +776,4 @@ interface PalsuProviderConfig {
685
776
  */
686
777
  declare function registerPalsuProvider(config?: PalsuProviderConfig): PalsuProviderHandle;
687
778
 
688
- export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, 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, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, 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 };