@prestyj/ai 4.11.4 → 4.12.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
@@ -451,6 +451,28 @@ declare function toOpenAIMessages(messages: Message[], options?: {
451
451
  supportsImages?: boolean;
452
452
  }): OpenAI.ChatCompletionMessageParam[];
453
453
 
454
+ /**
455
+ * Fire a minimal `max_tokens: 1` request that populates the Anthropic prompt
456
+ * cache with the system prompt + tools prefix, so the first real user turn is
457
+ * a cache read instead of a cold cache write. Best-effort: any error is
458
+ * swallowed so a failed pre-warm never blocks the session.
459
+ *
460
+ * Called by AgentSession when speedProfile is "optimized", before the first
461
+ * real agent-loop turn. The cache TTL follows the `cacheRetention` option —
462
+ * pass "long" (1 h) so the pre-warm survives until the user's first message.
463
+ */
464
+ declare function prewarmAnthropicCache(options: {
465
+ apiKey: string;
466
+ model: string;
467
+ system: string;
468
+ tools?: StreamOptions["tools"];
469
+ serverTools?: StreamOptions["serverTools"];
470
+ baseUrl?: string;
471
+ userAgent?: string;
472
+ cacheRetention?: StreamOptions["cacheRetention"];
473
+ signal?: AbortSignal;
474
+ }): Promise<void>;
475
+
454
476
  interface PalsuProviderState {
455
477
  callCount: number;
456
478
  }
@@ -520,4 +542,4 @@ interface PalsuProviderConfig {
520
542
  */
521
543
  declare function registerPalsuProvider(config?: PalsuProviderConfig): PalsuProviderHandle;
522
544
 
523
- export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, type ImageContent, type Message, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, type RawContent, 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, classifyProviderError, formatError, formatErrorForDisplay, isHardBillingMessage, isUsageLimitError, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, providerRegistry, registerPalsuProvider, setProviderDiagnostic, stream, toAnthropicMessages, toOpenAIMessages };
545
+ export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, type ImageContent, type Message, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, type RawContent, 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, classifyProviderError, formatError, formatErrorForDisplay, isHardBillingMessage, isUsageLimitError, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, prewarmAnthropicCache, providerRegistry, registerPalsuProvider, setProviderDiagnostic, stream, toAnthropicMessages, toOpenAIMessages };
package/dist/index.d.ts CHANGED
@@ -451,6 +451,28 @@ declare function toOpenAIMessages(messages: Message[], options?: {
451
451
  supportsImages?: boolean;
452
452
  }): OpenAI.ChatCompletionMessageParam[];
453
453
 
454
+ /**
455
+ * Fire a minimal `max_tokens: 1` request that populates the Anthropic prompt
456
+ * cache with the system prompt + tools prefix, so the first real user turn is
457
+ * a cache read instead of a cold cache write. Best-effort: any error is
458
+ * swallowed so a failed pre-warm never blocks the session.
459
+ *
460
+ * Called by AgentSession when speedProfile is "optimized", before the first
461
+ * real agent-loop turn. The cache TTL follows the `cacheRetention` option —
462
+ * pass "long" (1 h) so the pre-warm survives until the user's first message.
463
+ */
464
+ declare function prewarmAnthropicCache(options: {
465
+ apiKey: string;
466
+ model: string;
467
+ system: string;
468
+ tools?: StreamOptions["tools"];
469
+ serverTools?: StreamOptions["serverTools"];
470
+ baseUrl?: string;
471
+ userAgent?: string;
472
+ cacheRetention?: StreamOptions["cacheRetention"];
473
+ signal?: AbortSignal;
474
+ }): Promise<void>;
475
+
454
476
  interface PalsuProviderState {
455
477
  callCount: number;
456
478
  }
@@ -520,4 +542,4 @@ interface PalsuProviderConfig {
520
542
  */
521
543
  declare function registerPalsuProvider(config?: PalsuProviderConfig): PalsuProviderHandle;
522
544
 
523
- export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, type ImageContent, type Message, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, type RawContent, 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, classifyProviderError, formatError, formatErrorForDisplay, isHardBillingMessage, isUsageLimitError, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, providerRegistry, registerPalsuProvider, setProviderDiagnostic, stream, toAnthropicMessages, toOpenAIMessages };
545
+ export { type AssistantMessage, type CacheRetention, type ContentPart, type DoneEvent, EZCoderAIError, type ErrorEvent, type ErrorSource, EventStream, type FormattedError, type ImageContent, type Message, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type Provider, type ProviderDiagnosticFn, type ProviderEntry, ProviderError, type ProviderStreamFn, type RawContent, 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, classifyProviderError, formatError, formatErrorForDisplay, isHardBillingMessage, isUsageLimitError, palsuAssistantMessage, palsuText, palsuThinking, palsuToolCall, prewarmAnthropicCache, providerRegistry, registerPalsuProvider, setProviderDiagnostic, stream, toAnthropicMessages, toOpenAIMessages };
package/dist/index.js CHANGED
@@ -364,10 +364,15 @@ var StreamResult = class {
364
364
 
365
365
  // src/utils/zod-to-json-schema.ts
366
366
  import { z } from "zod";
367
+ var schemaCache = /* @__PURE__ */ new WeakMap();
367
368
  function zodToJsonSchema(schema) {
369
+ const cached = schemaCache.get(schema);
370
+ if (cached) return cached;
368
371
  const jsonSchema = z.toJSONSchema(schema);
369
372
  const { $schema: _schema, ...rest } = jsonSchema;
370
- return normalizeRootForAnthropic(rest);
373
+ const normalized = normalizeRootForAnthropic(rest);
374
+ schemaCache.set(schema, normalized);
375
+ return normalized;
371
376
  }
372
377
  function resolveToolSchema(tool) {
373
378
  return tool.rawInputSchema ?? zodToJsonSchema(tool.parameters);
@@ -975,26 +980,86 @@ function parseToolArguments(argsJson) {
975
980
  }
976
981
 
977
982
  // src/providers/anthropic.ts
983
+ var anthropicClientCache = /* @__PURE__ */ new Map();
978
984
  function createClient(options) {
979
985
  const isOAuth = options.apiKey?.startsWith("sk-ant-oat");
980
- return new Anthropic({
986
+ const userAgent = isOAuth ? options.userAgent ?? "claude-cli/2.1.75 (external, cli)" : "";
987
+ const cacheKey = `${options.apiKey ?? ""}|${options.baseUrl ?? ""}|${userAgent}`;
988
+ if (!options.fetch) {
989
+ const cached = anthropicClientCache.get(cacheKey);
990
+ if (cached) return cached;
991
+ }
992
+ const client = new Anthropic({
981
993
  ...isOAuth ? { apiKey: null, authToken: options.apiKey } : { apiKey: options.apiKey },
982
994
  ...options.baseUrl ? { baseURL: options.baseUrl } : {},
983
995
  ...options.fetch ? { fetch: options.fetch } : {},
984
- // Disable SDK retries — the agent loop has its own stall/overload retry
985
- // logic that surfaces errors properly. SDK retries on 429s can cause
986
- // multi-minute hangs when the provider stops responding mid-retry.
987
996
  maxRetries: 0,
988
997
  ...isOAuth ? {
989
998
  defaultHeaders: {
990
999
  // Anthropic's OAuth edge validates the claude-cli version. Callers
991
1000
  // (ezcoder) resolve the live version at runtime; the literal here
992
- // is the offline fallback for direct gg-ai consumers.
993
- "user-agent": options.userAgent ?? "claude-cli/2.1.75 (external, cli)",
1001
+ // is the offline fallback for direct ai consumers.
1002
+ "user-agent": userAgent,
994
1003
  "x-app": "cli"
995
1004
  }
996
1005
  } : {}
997
1006
  });
1007
+ if (!options.fetch) {
1008
+ if (anthropicClientCache.size >= 8) {
1009
+ const oldest = anthropicClientCache.keys().next().value;
1010
+ if (oldest) anthropicClientCache.delete(oldest);
1011
+ }
1012
+ anthropicClientCache.set(cacheKey, client);
1013
+ }
1014
+ return client;
1015
+ }
1016
+ async function prewarmAnthropicCache(options) {
1017
+ try {
1018
+ const client = createClient({
1019
+ apiKey: options.apiKey,
1020
+ baseUrl: options.baseUrl,
1021
+ userAgent: options.userAgent
1022
+ });
1023
+ const cacheControl = toAnthropicCacheControl(options.cacheRetention ?? "long", options.baseUrl);
1024
+ const { system, messages } = toAnthropicMessages(
1025
+ [
1026
+ { role: "system", content: options.system },
1027
+ { role: "user", content: "." }
1028
+ ],
1029
+ cacheControl
1030
+ );
1031
+ const isOAuth = options.apiKey.startsWith("sk-ant-oat");
1032
+ const fullSystem = isOAuth ? [
1033
+ {
1034
+ type: "text",
1035
+ text: "You are Claude Code, Anthropic's official CLI for Claude."
1036
+ },
1037
+ ...system ?? []
1038
+ ] : system;
1039
+ const tools = options.tools?.length ? toAnthropicTools(options.tools, {
1040
+ cacheControl,
1041
+ enableFineGrainedToolStreaming: true
1042
+ }) : void 0;
1043
+ await client.messages.create(
1044
+ {
1045
+ model: options.model,
1046
+ max_tokens: 1,
1047
+ messages,
1048
+ ...fullSystem ? { system: fullSystem } : {},
1049
+ ...tools ? {
1050
+ tools: [
1051
+ ...tools,
1052
+ ...options.serverTools ?? []
1053
+ ]
1054
+ } : {}
1055
+ },
1056
+ {
1057
+ signal: options.signal ?? void 0,
1058
+ ...isOAuth ? { headers: { "anthropic-beta": "claude-code-20250219,oauth-2025-04-20" } } : {}
1059
+ }
1060
+ );
1061
+ } catch {
1062
+ }
998
1063
  }
999
1064
  function streamAnthropic(options) {
1000
1065
  return new StreamResult(runStream(options), options.signal);
@@ -1574,13 +1639,27 @@ function extractOpenAIUsage(usage) {
1574
1639
  cacheRead
1575
1640
  };
1576
1641
  }
1642
+ var openaiClientCache = /* @__PURE__ */ new Map();
1577
1643
  function createClient2(options) {
1578
- return new OpenAI({
1644
+ const cacheKey = `${options.apiKey ?? ""}|${options.baseUrl ?? ""}|${JSON.stringify(options.defaultHeaders ?? {})}`;
1645
+ if (!options.fetch) {
1646
+ const cached = openaiClientCache.get(cacheKey);
1647
+ if (cached) return cached;
1648
+ }
1649
+ const client = new OpenAI({
1579
1650
  apiKey: options.apiKey,
1580
1651
  ...options.baseUrl ? { baseURL: options.baseUrl } : {},
1581
1652
  ...options.fetch ? { fetch: options.fetch } : {},
1582
1653
  ...options.defaultHeaders ? { defaultHeaders: options.defaultHeaders } : {}
1583
1654
  });
1655
+ if (!options.fetch) {
1656
+ if (openaiClientCache.size >= 8) {
1657
+ const oldest = openaiClientCache.keys().next().value;
1658
+ if (oldest) openaiClientCache.delete(oldest);
1659
+ }
1660
+ openaiClientCache.set(cacheKey, client);
1661
+ }
1662
+ return client;
1584
1663
  }
1585
1664
  function streamOpenAI(options) {
1586
1665
  return new StreamResult(runStream2(options), options.signal);
@@ -1995,9 +2074,6 @@ async function* runStream3(options) {
1995
2074
  body.tools = toCodexTools(options.tools);
1996
2075
  }
1997
2076
  body.prompt_cache_key = normalizePromptCacheKey(options.promptCacheKey ?? "ezcoder");
1998
- if (options.cacheRetention === "long") {
1999
- body.prompt_cache_retention = "24h";
2000
- }
2001
2077
  if (options.temperature != null && !options.thinking) {
2002
2078
  body.temperature = options.temperature;
2003
2079
  }
@@ -3310,6 +3386,7 @@ export {
3310
3386
  palsuText,
3311
3387
  palsuThinking,
3312
3388
  palsuToolCall,
3389
+ prewarmAnthropicCache,
3313
3390
  providerRegistry,
3314
3391
  registerPalsuProvider,
3315
3392
  setProviderDiagnostic,