@anthonyhaussman/opencode-agy-auth 0.0.0-test.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.
Files changed (60) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +178 -0
  3. package/dist/index.d.ts +8 -0
  4. package/dist/index.js +22014 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/src/constants.d.ts +9 -0
  7. package/dist/src/fetch.d.ts +1 -0
  8. package/dist/src/plugin/auth.d.ts +14 -0
  9. package/dist/src/plugin/cache.d.ts +35 -0
  10. package/dist/src/plugin/dynamic-models.d.ts +26 -0
  11. package/dist/src/plugin/headers.d.ts +7 -0
  12. package/dist/src/plugin/notify.d.ts +9 -0
  13. package/dist/src/plugin/oauth-authorize.d.ts +26 -0
  14. package/dist/src/plugin/pricing.d.ts +10 -0
  15. package/dist/src/plugin/project/context.d.ts +13 -0
  16. package/dist/src/plugin/project/index.d.ts +2 -0
  17. package/dist/src/plugin/project/types.d.ts +84 -0
  18. package/dist/src/plugin/project/utils.d.ts +35 -0
  19. package/dist/src/plugin/provider.d.ts +12 -0
  20. package/dist/src/plugin/quota-summary.d.ts +16 -0
  21. package/dist/src/plugin/quota-utils.d.ts +5 -0
  22. package/dist/src/plugin/quota.d.ts +16 -0
  23. package/dist/src/plugin/tier.d.ts +25 -0
  24. package/dist/src/plugin/token.d.ts +2 -0
  25. package/dist/src/plugin/traffic.d.ts +47 -0
  26. package/dist/src/plugin/types.d.ts +83 -0
  27. package/dist/src/plugin/v2-fetch.d.ts +7 -0
  28. package/dist/src/plugin/v2-session.d.ts +10 -0
  29. package/dist/src/plugin/v2-storage.d.ts +3 -0
  30. package/dist/src/plugin/v2.d.ts +15 -0
  31. package/dist/src/plugin.d.ts +8 -0
  32. package/dist/src/sdk/activity-request-id.d.ts +5 -0
  33. package/dist/src/sdk/agy-cli-version.d.ts +1 -0
  34. package/dist/src/sdk/cache/signature-cache.d.ts +130 -0
  35. package/dist/src/sdk/chat-logger.d.ts +8 -0
  36. package/dist/src/sdk/fetch_models.d.ts +48 -0
  37. package/dist/src/sdk/fetch_project.d.ts +9 -0
  38. package/dist/src/sdk/fetch_quota.d.ts +9 -0
  39. package/dist/src/sdk/oauth.d.ts +26 -0
  40. package/dist/src/sdk/request/identifiers.d.ts +16 -0
  41. package/dist/src/sdk/request/index.d.ts +12 -0
  42. package/dist/src/sdk/request/openai.d.ts +17 -0
  43. package/dist/src/sdk/request/prepare.d.ts +19 -0
  44. package/dist/src/sdk/request/response.d.ts +5 -0
  45. package/dist/src/sdk/request/shared.d.ts +20 -0
  46. package/dist/src/sdk/request/thinking.d.ts +129 -0
  47. package/dist/src/sdk/request/tool-mapper.d.ts +47 -0
  48. package/dist/src/sdk/request/turn-state-tracker.d.ts +21 -0
  49. package/dist/src/sdk/request-helpers/errors.d.ts +9 -0
  50. package/dist/src/sdk/request-helpers/index.d.ts +4 -0
  51. package/dist/src/sdk/request-helpers/parsing.d.ts +9 -0
  52. package/dist/src/sdk/request-helpers/thinking.d.ts +5 -0
  53. package/dist/src/sdk/request-helpers/types.d.ts +65 -0
  54. package/dist/src/sdk/retry/cooldown-store.d.ts +14 -0
  55. package/dist/src/sdk/retry/helpers.d.ts +19 -0
  56. package/dist/src/sdk/retry/index.d.ts +9 -0
  57. package/dist/src/sdk/retry/quota.d.ts +37 -0
  58. package/dist/src/sdk/terminal-hyperlink.d.ts +3 -0
  59. package/dist/src/sdk/user-agent.d.ts +5 -0
  60. package/package.json +60 -0
@@ -0,0 +1,130 @@
1
+ /**
2
+ * NOTE: Special Design - Cross-turn signature disk-level persistent cache
3
+ * Google Agy / Gemini 2.5/3 thinking models introduce strict "Thought Signature Validation" restrictions:
4
+ * In multi-turn dialogues (especially with Tool calls), the next request must carry a context signature (thoughtSignature) exactly matching the previous API response.
5
+ * To avoid conversation crashes caused by the following:
6
+ * 1. IDE-side session lifecycle rebuilds, causing loss of in-memory signature states.
7
+ * 2. Concurrent packets from multi-turn Tool interactions disrupting the memory cache of signatures.
8
+ * We implement a disk cache layer here with a background thread that periodically flushes to disk. Using a combination of session ID (sessionId) and historical thought chain hash digest as the Key,
9
+ * it persists the signatures and thought chains. Even if the IDE restarts or turns split, it can pull back the latest matching signature to fulfill official validation constraints.
10
+ */
11
+ /**
12
+ * Signature cache configuration options
13
+ */
14
+ export interface SignatureCacheConfig {
15
+ /** Whether to enable caching */
16
+ enabled: boolean;
17
+ /** In-memory cache time-to-live (seconds) */
18
+ memory_ttl_seconds: number;
19
+ /** Disk cache time-to-live (seconds) */
20
+ disk_ttl_seconds: number;
21
+ /** Auto-save interval to disk (seconds) */
22
+ write_interval_seconds: number;
23
+ }
24
+ /**
25
+ * Cache runtime state and statistics
26
+ */
27
+ interface CacheStats {
28
+ /** Memory hit count */
29
+ memoryHits: number;
30
+ /** Disk hit count */
31
+ diskHits: number;
32
+ /** Miss count */
33
+ misses: number;
34
+ /** Disk write count */
35
+ writes: number;
36
+ /** Total number of entries currently in memory */
37
+ memoryEntries: number;
38
+ /** Whether the cache is dirty (has unsaved data) */
39
+ dirty: boolean;
40
+ /** Whether disk storage is enabled */
41
+ diskEnabled: boolean;
42
+ }
43
+ /**
44
+ * Retrieve full thought chain cache data structure
45
+ */
46
+ export interface ThinkingCacheData {
47
+ /** Thought chain text */
48
+ text: string;
49
+ /** Signature */
50
+ signature: string;
51
+ /** Associated tool ID list */
52
+ toolIds?: string[];
53
+ }
54
+ export declare class SignatureCache {
55
+ private cache;
56
+ private memoryTtlMs;
57
+ private diskTtlMs;
58
+ private writeIntervalMs;
59
+ private cacheFilePath;
60
+ private enabled;
61
+ private dirty;
62
+ private writeTimer;
63
+ private cleanupTimer;
64
+ private stats;
65
+ constructor(config: SignatureCacheConfig);
66
+ /**
67
+ * Generates a unique cache key based on session ID and model ID
68
+ */
69
+ static makeKey(sessionId: string, modelId: string): string;
70
+ /**
71
+ * Stores a signature in cache (marks as dirty, awaits background disk write)
72
+ */
73
+ store(key: string, signature: string): void;
74
+ /**
75
+ * Retrieves a signature from cache and updates hit stats
76
+ * Returns null if expired or missing
77
+ */
78
+ retrieve(key: string): string | null;
79
+ /**
80
+ * Checks if a key is valid and unexpired in cache (without affecting stats)
81
+ */
82
+ has(key: string): boolean;
83
+ /**
84
+ * Caches the full thought chain text content and signature
85
+ * Allows self-healing and recovery of historical thought blocks even if the context is subsequently compressed.
86
+ */
87
+ storeThinking(key: string, thinkingText: string, signature: string, toolIds?: string[]): void;
88
+ /**
89
+ * Extracts full thought chain info from cache
90
+ */
91
+ retrieveThinking(key: string): ThinkingCacheData | null;
92
+ /**
93
+ * Checks if full thought chain content exists for a key
94
+ */
95
+ hasThinking(key: string): boolean;
96
+ /**
97
+ * Gets current cache stats and memory footprint
98
+ */
99
+ getStats(): CacheStats;
100
+ /**
101
+ * Manually triggers immediate save to disk
102
+ */
103
+ flush(): Promise<boolean>;
104
+ /**
105
+ * Graceful shutdown: stops all timers and flushes unsaved data to disk
106
+ */
107
+ shutdown(): void;
108
+ /**
109
+ * Loads signature cache from disk and validates TTL state
110
+ */
111
+ private loadFromDisk;
112
+ /**
113
+ * Synchronously saves memory cache to disk (using atomic write: temp file then rename)
114
+ * Merges with existing unexpired entries on disk during write
115
+ */
116
+ private saveToDisk;
117
+ /**
118
+ * Starts timers for auto-saving and auto-cleaning expired memory entries
119
+ */
120
+ private startBackgroundTasks;
121
+ /**
122
+ * Removes memory cache entries exceeding their TTL
123
+ */
124
+ private cleanupExpired;
125
+ }
126
+ /**
127
+ * Instantiates signature cache object based on config. Returns null if disabled.
128
+ */
129
+ export declare function createSignatureCache(config: SignatureCacheConfig | undefined): SignatureCache | null;
130
+ export {};
@@ -0,0 +1,8 @@
1
+ export interface ChatLogger {
2
+ logRequest(url: string, method: string, headers: HeadersInit | undefined, body: BodyInit | null | undefined): void;
3
+ logResponseHeaders(status: number, statusText: string, headers: Headers): void;
4
+ logResponseBody(body: string): void;
5
+ createLoggingTransformStream(): TransformStream<Uint8Array, Uint8Array>;
6
+ close(): void;
7
+ }
8
+ export declare function createChatLogger(): ChatLogger | null;
@@ -0,0 +1,48 @@
1
+ export interface AvailableModelDetails {
2
+ displayName: string;
3
+ supportsImages?: boolean;
4
+ supportsThinking?: boolean;
5
+ thinkingBudget?: number;
6
+ minThinkingBudget?: number;
7
+ thinkingLevel?: number;
8
+ recommended?: boolean;
9
+ maxTokens?: number;
10
+ maxOutputTokens?: number;
11
+ tokenizerType?: string;
12
+ quotaInfo?: {
13
+ remainingFraction?: number;
14
+ resetTime?: string;
15
+ };
16
+ model?: string;
17
+ apiProvider?: string;
18
+ modelProvider?: string;
19
+ supportsVideo?: boolean;
20
+ supportedMimeTypes?: Record<string, boolean>;
21
+ modelExperiments?: Record<string, unknown>;
22
+ [key: string]: unknown;
23
+ }
24
+ export interface FetchAvailableModelsResponse {
25
+ models?: Record<string, AvailableModelDetails>;
26
+ defaultAgentModelId?: string;
27
+ agentModelSorts?: Array<{
28
+ displayName: string;
29
+ groups: Array<{
30
+ modelIds: string[];
31
+ }>;
32
+ }>;
33
+ commandModelIds?: string[];
34
+ tabModelIds?: string[];
35
+ imageGenerationModelIds?: string[];
36
+ mqueryModelIds?: string[];
37
+ webSearchModelIds?: string[];
38
+ deprecatedModelIds?: Record<string, unknown>;
39
+ commitMessageModelIds?: string[];
40
+ audioTranscriptionModelIds?: string[];
41
+ experimentIds?: number[];
42
+ tieredModelIds?: Record<string, string[]>;
43
+ [key: string]: unknown;
44
+ }
45
+ /**
46
+ * Fetches the list of available models for the current account under the specified project from the Agy server.
47
+ */
48
+ export declare function fetchAvailableModels(accessToken: string, projectId: string, userAgentModel?: string, signal?: AbortSignal): Promise<FetchAvailableModelsResponse>;
@@ -0,0 +1,9 @@
1
+ import { type LoadCodeAssistPayload } from '../plugin/project/types';
2
+ /**
3
+ * Loads hosted project information for a given access token and optional project.
4
+ */
5
+ export declare function loadManagedProject(accessToken: string, projectId?: string, userAgentModel?: string): Promise<LoadCodeAssistPayload | null>;
6
+ /**
7
+ * Enables a hosted project for the user, optionally retrying until complete.
8
+ */
9
+ export declare function onboardManagedProject(accessToken: string, tierId: string, projectId?: string, userAgentModel?: string, attempts?: number, delayMs?: number): Promise<string | undefined>;
@@ -0,0 +1,9 @@
1
+ import type { RetrieveUserQuotaResponse, RetrieveUserQuotaSummaryResponse } from '../plugin/project/types';
2
+ /**
3
+ * Fetches the Code Assist quota bucket information, which contains the model IDs visible to the current account/project.
4
+ */
5
+ export declare function retrieveUserQuota(accessToken: string, projectId: string, userAgentModel?: string): Promise<RetrieveUserQuotaResponse | null>;
6
+ /**
7
+ * Fetches the Code Assist quota summary, grouped by model family with window-based buckets.
8
+ */
9
+ export declare function retrieveUserQuotaSummary(accessToken: string, projectId: string, userAgentModel?: string): Promise<RetrieveUserQuotaSummaryResponse | null>;
@@ -0,0 +1,26 @@
1
+ export interface AgyAuthorization {
2
+ url: string;
3
+ verifier: string;
4
+ state: string;
5
+ }
6
+ interface AgyTokenExchangeSuccess {
7
+ type: 'success';
8
+ refresh: string;
9
+ access: string;
10
+ expires: number;
11
+ email?: string;
12
+ }
13
+ interface AgyTokenExchangeFailure {
14
+ type: 'failed';
15
+ error: string;
16
+ }
17
+ export type AgyTokenExchangeResult = AgyTokenExchangeSuccess | AgyTokenExchangeFailure;
18
+ /**
19
+ * Builds the Agy OAuth authorization URL with PKCE.
20
+ */
21
+ export declare function authorizeAgy(): Promise<AgyAuthorization>;
22
+ /**
23
+ * Exchanges the authorization code for Agy using a known PKCE verifier.
24
+ */
25
+ export declare function exchangeAgyWithVerifier(code: string, verifier: string): Promise<AgyTokenExchangeResult>;
26
+ export {};
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Applies canonical identifiers for wrapped Code Assist payloads.
3
+ */
4
+ export declare function normalizeWrappedIdentifiers(wrapped: Record<string, unknown>): {
5
+ userPromptId: string;
6
+ sessionId: string;
7
+ requestId: string;
8
+ };
9
+ /**
10
+ * Applies canonical identifiers for unwrapped request payloads prior to wrapping.
11
+ */
12
+ export declare function normalizeRequestPayloadIdentifiers(payload: Record<string, unknown>): {
13
+ userPromptId: string;
14
+ sessionId: string;
15
+ requestId: string;
16
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * NOTE: The request module here handles serialization, deserialization, and streaming data conversion between the standard OpenAI protocol and Agy's native Gemini protocol.
3
+ * Though normally an app/adapter layer responsibility, it's highly coupled with Agy's exclusive SSE streaming deduplication and multi-turn signature caching,
4
+ * so to ensure a simple and clean external interface, we package it as a built-in SDK capability, shielding the upper layer from all protocol conversion internal complexities.
5
+ */
6
+ export { prepareAgyRequest } from "./prepare";
7
+ export type { ThinkingConfigDefaults } from "./prepare";
8
+ export { transformAgyResponse } from "./response";
9
+ export { isGenerativeLanguageRequest, parseGenerativeLanguageRequest } from "./shared";
10
+ export { initTurnStateTracker, getTurnStateTracker, shutdownTurnStateTracker, TurnStateTracker } from "./turn-state-tracker";
11
+ export type { TurnState } from "./turn-state-tracker";
12
+ export { ToolMapper, getToolMapper, sanitizeToolName, restoreToolNamesInResponse, clearToolMapper, } from "./tool-mapper";
@@ -0,0 +1,17 @@
1
+ /**
2
+ * NOTE: Format/protocol conversion logic is typically in the app layer (Plugin), but is implemented here inside the SDK as a special case.
3
+ * Reason:
4
+ * Format conversion (OpenAI format to Gemini/Agy native and vice versa) is tightly coupled with Agy's unique streaming SSE data parsing,
5
+ * thought chain deduplication, and signature self-healing (Thinking Recovery / Signature Cache) in multi-turn dialogues.
6
+ * Encapsulating this conversion in the SDK completely shields the OpenCode plugin app layer from non-standard API interaction complexities,
7
+ * allowing the plugin to simply call and forward standard OpenAI formatted requests and response streams.
8
+ */
9
+ import type { ToolMapper } from "./tool-mapper";
10
+ /**
11
+ * Converts OpenAI's `tool_calls` into Gemini's `functionCall` sections.
12
+ */
13
+ export declare function transformOpenAIToolCalls(requestPayload: Record<string, unknown>, toolMapper?: ToolMapper): void;
14
+ /**
15
+ * Adds synthesized thoughtSignature to function calls in the flattened and wrapped payload.
16
+ */
17
+ export declare function addThoughtSignaturesToFunctionCalls(requestPayload: Record<string, unknown>): void;
@@ -0,0 +1,19 @@
1
+ export interface ThinkingConfigDefaults {
2
+ provider?: unknown;
3
+ models?: Record<string, unknown>;
4
+ }
5
+ /**
6
+ * Rewrites OpenAI-style requests into the format for Gemini Code Assist requests.
7
+ */
8
+ export declare function prepareAgyRequest(input: RequestInfo, init: RequestInit | undefined, accessToken: string, projectId: string, thinkingConfigDefaults?: ThinkingConfigDefaults, modelEnums?: Readonly<Record<string, string>>): {
9
+ request: RequestInfo;
10
+ init: RequestInit;
11
+ streaming: boolean;
12
+ requestedModel?: string;
13
+ sessionId?: string;
14
+ };
15
+ export declare const LEGACY_MODEL_ENUM_FALLBACKS: Record<string, string>;
16
+ export declare function getModelEnum(modelName: string): string;
17
+ export declare function isClaudeModel(model: string): boolean;
18
+ export declare function sanitizeClaudeThinkingParts(contents: any[], model: string, sessionId?: string): void;
19
+ export declare function ensureTrailingUserTurn(contents: any[]): any[];
@@ -0,0 +1,5 @@
1
+ import type { ChatLogger } from "../chat-logger";
2
+ /**
3
+ * Normalizes Gemini/Agy responses, preserving request metadata and usage counters.
4
+ */
5
+ export declare function transformAgyResponse(response: Response, streaming: boolean, _ignoredDebugContext?: any, requestedModel?: string, sessionId?: string, chatLogger?: ChatLogger | null): Promise<Response>;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Returns the URL string for supported RequestInfo inputs.
3
+ */
4
+ export declare function toRequestUrlString(value: RequestInfo): string;
5
+ /**
6
+ * Detects Gemini/Generative Language API requests via URL.
7
+ */
8
+ export declare function isGenerativeLanguageRequest(input: RequestInfo): input is string;
9
+ export declare function parseGenerativeLanguageRequest(input: RequestInfo): {
10
+ requestedModel: string;
11
+ effectiveModel: string;
12
+ action: string;
13
+ } | undefined;
14
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
15
+ export declare function readString(value: unknown): string | undefined;
16
+ export declare function pickString(...values: unknown[]): string | undefined;
17
+ /**
18
+ * Preserves Cloud Code trace identity for downstream clients by mapping traceId to responseId.
19
+ */
20
+ export declare function injectResponseIdFromTrace<T extends Record<string, unknown>>(body: T): T;
@@ -0,0 +1,129 @@
1
+ /**
2
+ * NOTE: Special Design - Streaming deduplication and signature state self-healing
3
+ * Agy/Gemini official API has the following non-standard behaviors and strict constraints that must be specially handled here:
4
+ * 1. [Streaming Deduplication]: In the data packets returned by the official API during streaming, thought chain (Thinking) content is output cumulatively.
5
+ * We must perform hash comparison and truncation on each returned delta to prevent the IDE from receiving duplicate text.
6
+ * 2. [Signature State Self-healing]: In multi-turn dialogues, if the thoughtSignature is lost due to tool calls or client state breakage,
7
+ * the official API throws a signature mismatch error. An auto-detection mechanism (e.g., needsThinkingRecovery) is designed here to, upon signature breakage,
8
+ * automatically backfill/align fallback thought chain fragments and signatures in context messages, allowing the dialogue chain to self-heal and continue.
9
+ */
10
+ /**
11
+ * Cached signed thought chain data structure
12
+ */
13
+ export interface SignedThinking {
14
+ /** Full thought chain text content */
15
+ text: string;
16
+ /** Corresponding server signature */
17
+ signature: string;
18
+ }
19
+ /**
20
+ * External contract interface for signature storage manager
21
+ */
22
+ export interface SignatureStore {
23
+ get(sessionKey: string): SignedThinking | undefined;
24
+ set(sessionKey: string, value: SignedThinking): void;
25
+ has(sessionKey: string): boolean;
26
+ delete(sessionKey: string): void;
27
+ }
28
+ /**
29
+ * Custom callback functions for the streaming phase
30
+ */
31
+ export interface StreamingCallbacks {
32
+ onCacheSignature?: (sessionKey: string, text: string, signature: string) => void;
33
+ onInjectDebug?: (response: unknown, debugText: string) => unknown;
34
+ transformThinkingParts?: (parts: unknown) => unknown;
35
+ onTurnStateUpdate?: (sessionKey: string, state: {
36
+ turnHasThinking: boolean;
37
+ lastModelHasToolCalls: boolean;
38
+ }) => void;
39
+ }
40
+ /**
41
+ * Configuration parameters for the streaming phase
42
+ */
43
+ export interface StreamingOptions {
44
+ /** Unique identifier for the signature session, used for cross-turn signature recovery */
45
+ signatureSessionKey?: string;
46
+ /** Debugging text to inject into the stream (optional) */
47
+ debugText?: string;
48
+ /** Whether to cache the latest generated signature in this stream */
49
+ cacheSignatures?: boolean;
50
+ /** Set of already rendered thought chain hashes, used to avoid duplicate output in tool call loops */
51
+ displayedThinkingHashes?: Set<string>;
52
+ }
53
+ /**
54
+ * Text buffer for caching thought chains of a specific index or type (handles streaming chunk cumulative output)
55
+ */
56
+ export interface ThoughtBuffer {
57
+ get(index: number): string | undefined;
58
+ set(index: number, text: string): void;
59
+ clear(): void;
60
+ }
61
+ /**
62
+ * Agent and tool interaction state record during multi-turn dialogue runtime
63
+ */
64
+ export interface ConversationState {
65
+ /** Whether inside an incomplete tool call loop (i.e., last turn ended with functionResponse, continuing this turn) */
66
+ inToolLoop: boolean;
67
+ /** Array index of the first model reply message in the current dialogue turn */
68
+ turnStartIdx: number;
69
+ /** Whether the start of the current dialogue turn contains a thought chain (thought) */
70
+ turnHasThinking: boolean;
71
+ /** Array index of the last model reply message */
72
+ lastModelIdx: number;
73
+ /** Whether the last model message contains a thought chain */
74
+ lastModelHasThinking: boolean;
75
+ /** Whether the last model message contains a tool call (tool_use) */
76
+ lastModelHasToolCalls: boolean;
77
+ }
78
+ /**
79
+ * Creates a memory Map-based signature storage manager
80
+ */
81
+ export declare function createSignatureStore(): SignatureStore;
82
+ /**
83
+ * Creates a thought chain text accumulation buffer for temporarily storing streaming chunks
84
+ */
85
+ export declare function createThoughtBuffer(): ThoughtBuffer;
86
+ /**
87
+ * Default global memory signature storage
88
+ */
89
+ export declare const defaultSignatureStore: SignatureStore;
90
+ /**
91
+ * Analyzes multi-turn historical dialogue arrays to extract context metrics like agent interaction loop state, model message positions, whether the turn has thoughts, etc.
92
+ */
93
+ export declare function analyzeConversationState(contents: any[]): ConversationState;
94
+ /**
95
+ * Closes the tool execution loop and injects transition content to smoothly recover the dialogue without providing the old thought chain
96
+ */
97
+ export declare function closeToolLoopForThinking(contents: any[]): any[];
98
+ /**
99
+ * Checks if the current state meets conditions to trigger historical self-healing
100
+ */
101
+ export declare function needsThinkingRecovery(state: ConversationState): boolean;
102
+ /**
103
+ * Determines if the current model reply message had its thought chain pruned (has only tool calls but lost its preceding thought chain description)
104
+ */
105
+ export declare function looksLikeCompactedThinkingTurn(msg: any): boolean;
106
+ /**
107
+ * Deeply determines if the start of this Turn contains historical rounds whose thought chains might have been pruned/compressed by the system
108
+ */
109
+ export declare function hasPossibleCompactedThinking(contents: any[], turnStartIdx: number): boolean;
110
+ /**
111
+ * For streaming SSE data packets, calculates and locally strips duplicated thought chain text
112
+ * Simultaneously supports Gemini's exclusive candidates.content structure and Claude's exclusive content[type=thinking] structure
113
+ */
114
+ export declare function deduplicateThinkingText(response: unknown, sentBuffer: ThoughtBuffer, displayedThinkingHashes?: Set<string>): unknown;
115
+ /**
116
+ * Caches thought chain content and its validation signature from the returned message body for signature alignment in the next interaction round
117
+ * Also supports Gemini signature mechanism (candidates[].thoughtSignature) and Claude signature mechanism (content[].signature)
118
+ */
119
+ export declare function cacheThinkingSignaturesFromResponse(response: unknown, signatureSessionKey: string, signatureStore: SignatureStore, thoughtBuffer: ThoughtBuffer, onCacheSignature?: (sessionKey: string, text: string, signature: string) => void): void;
120
+ /**
121
+ * Transforms a single complete SSE event, triggering thought chain caching and incremental deduplication here
122
+ */
123
+ export declare function transformSseEvent(eventText: string, signatureStore: SignatureStore, thoughtBuffer: ThoughtBuffer, sentThinkingBuffer: ThoughtBuffer, callbacks: StreamingCallbacks, options: StreamingOptions, debugState: {
124
+ injected: boolean;
125
+ }): string;
126
+ /**
127
+ * Creates a TransformStream processor to split, deduplicate, and recombine the output stream
128
+ */
129
+ export declare function createStreamingTransformer(signatureStore: SignatureStore, callbacks: StreamingCallbacks, options?: StreamingOptions): TransformStream<Uint8Array, Uint8Array>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Tool Name Schema Mapping for Gemini API
3
+ *
4
+ * Gemini API tool schemas strictly enforce function names matching `^[a-zA-Z_][a-zA-Z0-9_]*$`.
5
+ * Agent frameworks (MCP servers, OpenCode plugins, OpenAI adapters) often use hyphens (-), dots (.),
6
+ * slashes (/), or colons (:) in tool names (e.g. `context7_resolve_library_id`, `atlassian:get-issue`, `my-tool`).
7
+ *
8
+ * This module maintains a bidirectional mapping between original client tool names and Gemini-compliant tool names,
9
+ * resolving collisions deterministically and persisting session mappings across multi-turn tool loops.
10
+ */
11
+ export declare function sanitizeToolName(name: string): string;
12
+ export declare class ToolMapper {
13
+ private originalToSanitized;
14
+ private sanitizedToOriginal;
15
+ /**
16
+ * Register a tool name and get its Gemini-compliant sanitized name.
17
+ * Handles naming collisions by appending a numeric suffix if needed.
18
+ */
19
+ register(originalName: string): string;
20
+ /**
21
+ * Map an original tool name to sanitized Gemini name.
22
+ * If not already registered, registers it on the fly.
23
+ */
24
+ toGemini(originalName: string): string;
25
+ /**
26
+ * Restore a sanitized Gemini tool name back to the original client tool name.
27
+ */
28
+ fromGemini(sanitizedName: string): string;
29
+ /**
30
+ * Register tools from Gemini `tools[].functionDeclarations` array.
31
+ */
32
+ registerFromFunctionDeclarations(tools: unknown): void;
33
+ /**
34
+ * Register tools from OpenAI format `tools[].function.name`.
35
+ */
36
+ registerFromOpenAITools(tools: unknown): void;
37
+ /**
38
+ * Scan contents/messages to register any previously used tool names.
39
+ */
40
+ registerFromContents(contents: unknown): void;
41
+ }
42
+ export declare function getToolMapper(sessionId?: string): ToolMapper;
43
+ export declare function clearToolMapper(sessionId: string): void;
44
+ /**
45
+ * Restores original client tool names inside Gemini candidates/parts functionCall objects.
46
+ */
47
+ export declare function restoreToolNamesInResponse(body: unknown, toolMapper: ToolMapper): void;
@@ -0,0 +1,21 @@
1
+ import { type ConversationState } from "./thinking";
2
+ export type TurnState = Pick<ConversationState, "inToolLoop" | "turnHasThinking" | "lastModelHasThinking" | "lastModelHasToolCalls">;
3
+ export declare class TurnStateTracker {
4
+ private entries;
5
+ private dirty;
6
+ private lastWriteTime;
7
+ private writeTimer;
8
+ private readonly diskEnabled;
9
+ constructor(diskEnabled?: boolean);
10
+ getState(sessionId: string): TurnState | undefined;
11
+ needsThinkingRecovery(sessionId: string): boolean;
12
+ updateAfterResponse(sessionId: string, newState: TurnState): void;
13
+ recoverFromContents(sessionId: string, contents: any[]): TurnState;
14
+ clear(sessionId: string): void;
15
+ shutdown(): void;
16
+ private scheduleThrottledWrite;
17
+ private clearWriteTimer;
18
+ }
19
+ export declare function initTurnStateTracker(): TurnStateTracker;
20
+ export declare function getTurnStateTracker(): TurnStateTracker | null;
21
+ export declare function shutdownTurnStateTracker(): void;
@@ -0,0 +1,9 @@
1
+ import { type GeminiApiBody, type GeminiErrorEnhancement } from "./types";
2
+ /**
3
+ * Enhances 404 errors for Gemini 3 models with direct preview access information.
4
+ */
5
+ export declare function rewriteGeminiPreviewAccessError(body: GeminiApiBody, status: number, requestedModel?: string): GeminiApiBody | null;
6
+ /**
7
+ * Enhances Gemini errors with validation/quota messages and retry hints.
8
+ */
9
+ export declare function enhanceGeminiErrorResponse(body: GeminiApiBody, status: number): GeminiErrorEnhancement | null;
@@ -0,0 +1,4 @@
1
+ export { CLOUDCODE_DOMAINS, GEMINI_PREVIEW_LINK, type GeminiApiBody, type GeminiApiError, type GeminiErrorEnhancement, type GeminiUsageMetadata, type ThinkingConfig, } from "./types";
2
+ export { normalizeThinkingConfig } from "./thinking";
3
+ export { parseGeminiApiBody, extractUsageMetadata } from "./parsing";
4
+ export { rewriteGeminiPreviewAccessError, enhanceGeminiErrorResponse } from "./errors";
@@ -0,0 +1,9 @@
1
+ import type { GeminiApiBody, GeminiUsageMetadata } from "./types";
2
+ /**
3
+ * Parses the Gemini API response body; handles array-wrapped responses sometimes returned by the API.
4
+ */
5
+ export declare function parseGeminiApiBody(rawText: string): GeminiApiBody | null;
6
+ /**
7
+ * Extracts usageMetadata from the response object with type-safe guards.
8
+ */
9
+ export declare function extractUsageMetadata(body: GeminiApiBody): GeminiUsageMetadata | null;
@@ -0,0 +1,5 @@
1
+ import type { ThinkingConfig } from "./types";
2
+ /**
3
+ * Normalizes thinkingConfig aliases to standard Gemini field names.
4
+ */
5
+ export declare function normalizeThinkingConfig(config: unknown): ThinkingConfig | undefined;
@@ -0,0 +1,65 @@
1
+ export declare const GEMINI_PREVIEW_LINK = "https://goo.gle/enable-preview-features";
2
+ export interface GeminiApiError {
3
+ code?: number;
4
+ message?: string;
5
+ status?: string;
6
+ details?: unknown[];
7
+ [key: string]: unknown;
8
+ }
9
+ /**
10
+ * The minimal representation of the Gemini API response we touch.
11
+ */
12
+ export interface GeminiApiBody {
13
+ response?: unknown;
14
+ error?: GeminiApiError;
15
+ [key: string]: unknown;
16
+ }
17
+ export interface GeminiErrorEnhancement {
18
+ body?: GeminiApiBody;
19
+ retryAfterMs?: number;
20
+ }
21
+ /**
22
+ * Usage metadata exposed by Gemini responses. Fields are optional to reflect partial payloads.
23
+ */
24
+ export interface GeminiUsageMetadata {
25
+ totalTokenCount?: number;
26
+ promptTokenCount?: number;
27
+ candidatesTokenCount?: number;
28
+ cachedContentTokenCount?: number;
29
+ }
30
+ /**
31
+ * Thinking configuration accepted by Gemini.
32
+ */
33
+ export interface ThinkingConfig {
34
+ thinkingBudget?: number;
35
+ thinkingLevel?: string | number;
36
+ includeThoughts?: boolean;
37
+ }
38
+ export interface GoogleRpcErrorInfo {
39
+ "@type"?: string;
40
+ reason?: string;
41
+ domain?: string;
42
+ metadata?: Record<string, string>;
43
+ }
44
+ export interface GoogleRpcHelp {
45
+ "@type"?: string;
46
+ links?: Array<{
47
+ description?: string;
48
+ url?: string;
49
+ }>;
50
+ }
51
+ export interface GoogleRpcQuotaFailure {
52
+ "@type"?: string;
53
+ violations?: Array<{
54
+ subject?: string;
55
+ description?: string;
56
+ }>;
57
+ }
58
+ export interface GoogleRpcRetryInfo {
59
+ "@type"?: string;
60
+ retryDelay?: string | {
61
+ seconds?: number;
62
+ nanos?: number;
63
+ };
64
+ }
65
+ export declare const CLOUDCODE_DOMAINS: string[];
@@ -0,0 +1,14 @@
1
+ export declare function loadCooldowns(): Map<string, number>;
2
+ export declare function saveCooldowns(entries: Map<string, number>): boolean;
3
+ export declare class CooldownStore {
4
+ private dirty;
5
+ private lastWriteTime;
6
+ private writeTimer;
7
+ private entries;
8
+ bind(entries: Map<string, number>): void;
9
+ markDirty(): void;
10
+ flush(): boolean;
11
+ shutdown(): void;
12
+ private scheduleThrottledWrite;
13
+ private clearWriteTimer;
14
+ }