@acosmi/sdk-ts 1.3.2 → 1.4.1

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.
@@ -1,5 +1,5 @@
1
- import { M as ManagedModel, I as InputModality, S as ServerMetadata, T as TokenResponse, a as TokenSet, C as ClientRegistration, B as BusinessError, b as ModelCoefficient, Q as QuotaSummary, c as ModelCapabilities, d as ChatRequest, P as ProviderAdapter, e as ChatResponse, A as AnthropicResponse, f as StreamEvent, g as SourcesEvent, h as StreamSettlement, E as EntitlementBalance, i as BalanceDetail, j as EntitlementItem, k as ConsumeRecordPage, l as ModelByQuotaResponse, m as ModelBucket, n as TokenPackage, o as PayPayload, O as Order, p as OrderStatus, W as WalletStats, q as Transaction, r as SkillStoreQuery, s as SkillStoreItem, t as SkillBrowseResponse, u as SkillBrowseListResponse, v as SkillSummary, w as CertificationStatus, G as GenerateSkillRequest, x as GenerateSkillResult, y as OptimizeSkillRequest, z as OptimizeSkillResult, D as ToolView, N as NotificationList, F as DeviceRegistration, H as NotificationPreference, J as WSEvent } from './index-28x02ITB.cjs';
2
- export { K as APIResponse, L as AnthropicContentBlock, R as AnthropicUsage, U as BucketClassCommercial, V as BucketClassGeneric, X as BucketInfo, Y as BucketRow, Z as ChatContentBlock, _ as ChatMessage, $ as ChatUsage, a0 as ConsumeRecord, a1 as EffortConfig, a2 as GeoLoc, a3 as HTTPError, a4 as ModelNotFoundError, a5 as NetworkError, a6 as Notification, a7 as NotificationUnreadCount, a8 as OpenAIChatChoice, a9 as OpenAIChatMessage, aa as OpenAIChatResponse, ab as OpenAIFunctionCall, ac as OpenAIStreamChoice, ad as OpenAIStreamChunk, ae as OpenAIStreamDelta, af as OpenAIStreamToolCall, ag as OpenAIToolCall, ah as OpenAIUsage, ai as OrderTerminalError, aj as OutputConfig, ak as ProviderFormat, al as RateLimitError, am as ServerTool, an as ServerToolTypeWebSearch, ao as SkillStoreListItem, ap as StreamError, aq as ThinkingConfig, ar as ThinkingHigh, as as ThinkingHighMinMaxTokens, at as ThinkingMax, au as ThinkingMaxFallbackMaxTokens, av as ThinkingOff, aw as ToolListResponse, ax as ToolProvider, ay as WebSearchConfig, az as WebSearchSource, aA as YudaoPageResult, aB as anthropicResponseTextContent, aC as anthropicResponseThinkingContent, aD as anthropicResponseToolUseBlocks, aE as apiResponseBusinessError, aF as apiResponseGetMessage, aG as bucketInfoIsCommercial, aH as bucketRowIsCommercial, aI as getAdapter, aJ as getAdapterForModel, aK as newThinkingConfig, aL as newWebSearchTool, aM as parseNotificationEvent, aN as parseSettlement, aO as parseSourcesEvent, aP as tokenSetIsExpired } from './index-28x02ITB.cjs';
1
+ import { M as ManagedModel, I as InputModality, S as ServerMetadata, T as TokenSet, a as TokenResponse, C as ClientRegistration, B as BusinessError, b as ModelCoefficient, Q as QuotaSummary, c as ModelCapabilities, d as ChatRequest, P as ProviderAdapter, e as ChatResponse, A as AnthropicResponse, f as StreamEvent, g as SourcesEvent, h as StreamSettlement, E as EntitlementBalance, i as BalanceDetail, j as EntitlementItem, k as ConsumeRecordPage, l as ModelByQuotaResponse, m as ModelBucket, n as TokenPackage, o as PayPayload, O as Order, p as OrderStatus, W as WalletStats, q as Transaction, r as SkillStoreQuery, s as SkillStoreItem, t as SkillBrowseResponse, u as SkillBrowseListResponse, v as SkillSummary, w as CertificationStatus, G as GenerateSkillRequest, x as GenerateSkillResult, y as OptimizeSkillRequest, z as OptimizeSkillResult, D as ToolView, N as NotificationList, F as DeviceRegistration, H as NotificationPreference, J as WSEvent } from './index-CbG9NqE-.cjs';
2
+ export { K as APIResponse, L as AnthropicContentBlock, R as AnthropicUsage, U as BucketClassCommercial, V as BucketClassGeneric, X as BucketInfo, Y as BucketRow, Z as ChatContentBlock, _ as ChatMessage, $ as ChatUsage, a0 as ConsumeRecord, a1 as EffortConfig, a2 as GeoLoc, a3 as HTTPError, a4 as ModelNotFoundError, a5 as NetworkError, a6 as Notification, a7 as NotificationUnreadCount, a8 as OpenAIChatChoice, a9 as OpenAIChatMessage, aa as OpenAIChatResponse, ab as OpenAIFunctionCall, ac as OpenAIStreamChoice, ad as OpenAIStreamChunk, ae as OpenAIStreamDelta, af as OpenAIStreamToolCall, ag as OpenAIToolCall, ah as OpenAIUsage, ai as OrderTerminalError, aj as OutputConfig, ak as ProviderFormat, al as RateLimitError, am as ServerTool, an as ServerToolTypeWebSearch, ao as SkillStoreListItem, ap as StreamError, aq as ThinkingConfig, ar as ThinkingHigh, as as ThinkingHighMinMaxTokens, at as ThinkingMax, au as ThinkingMaxFallbackMaxTokens, av as ThinkingOff, aw as ToolListResponse, ax as ToolProvider, ay as WebSearchConfig, az as WebSearchSource, aA as YudaoPageResult, aB as anthropicResponseTextContent, aC as anthropicResponseThinkingContent, aD as anthropicResponseToolUseBlocks, aE as apiResponseBusinessError, aF as apiResponseGetMessage, aG as bucketInfoIsCommercial, aH as bucketRowIsCommercial, aI as getAdapter, aJ as getAdapterForModel, aK as newThinkingConfig, aL as newWebSearchTool, aM as parseNotificationEvent, aN as parseSettlement, aO as parseSourcesEvent, aP as tokenSetIsExpired } from './index-CbG9NqE-.cjs';
3
3
  import { M as MinimalSanitizeConfig } from './index-nvLKgCm9.cjs';
4
4
  export { i as sanitize } from './index-nvLKgCm9.cjs';
5
5
  export { AnthropicAdapter } from './adapters/anthropic.cjs';
@@ -48,6 +48,19 @@ declare function findFirstModelByInputModality(models: ManagedModel[], modality:
48
48
  */
49
49
  declare function findDesktopVisualUnderstandingModel(models: ManagedModel[]): ManagedModel | null;
50
50
 
51
+ /** OAuth metadata profile — 决定 well-known 端点的路径后缀 */
52
+ type OAuthMetadataProfile = 'web' | 'desktop';
53
+ /**
54
+ * 从 well-known 端点获取指定 profile 的 OAuth 服务元数据。
55
+ *
56
+ * serverURL 可能含路径 (如 "https://acosmi.ai/api/v4"),
57
+ * well-known 端点按 RFC 8414 必须在 origin 根路径:
58
+ * https://acosmi.ai/.well-known/oauth-authorization-server/<profile>
59
+ *
60
+ * profile='desktop' 对应桌面 loopback OAuth;profile='web' 对应浏览器 Web OAuth。
61
+ * 内部 helper — `discover` / `discoverWebOAuthMetadata` 是其薄包装。
62
+ */
63
+ declare function discoverWithProfile(serverURL: string, profile: OAuthMetadataProfile, signal?: AbortSignal): Promise<ServerMetadata>;
51
64
  /**
52
65
  * 从 well-known 端点获取 Desktop OAuth 服务元数据。
53
66
  *
@@ -56,13 +69,48 @@ declare function findDesktopVisualUnderstandingModel(models: ManagedModel[]): Ma
56
69
  * https://acosmi.ai/.well-known/oauth-authorization-server/desktop
57
70
  */
58
71
  declare function discover(serverURL: string, signal?: AbortSignal): Promise<ServerMetadata>;
72
+ /**
73
+ * 从 well-known 端点获取 Web OAuth 服务元数据。
74
+ *
75
+ * 与 `discover` 行为一致, 但请求路径为
76
+ * https://acosmi.com/.well-known/oauth-authorization-server/web
77
+ *
78
+ * 浏览器侧 Web OAuth (csign 等第一方 Web 应用) 必须用此 profile,
79
+ * 它返回 Web authorize/token 端点; `discover` 的 desktop profile 返回的是
80
+ * 桌面 loopback 端点, 不可混用。
81
+ */
82
+ declare function discoverWebOAuthMetadata(serverURL: string, signal?: AbortSignal): Promise<ServerMetadata>;
59
83
  /** 动态注册桌面客户端,获取 client_id */
60
84
  declare function register(meta: ServerMetadata, appName: string, signal?: AbortSignal): Promise<ClientRegistration>;
85
+ /** Web OAuth 动态注册参数 */
86
+ interface RegisterWebOAuthClientOptions {
87
+ /** 客户端展示名 (RFC 7591 client_name) */
88
+ clientName: string;
89
+ /** 浏览器 Web OAuth 的 redirect_uri 列表 (如 ["https://sign.zhonglvbao.com/login/callback"]) */
90
+ redirectURIs: string[];
91
+ /** 可选 scope 列表 — 提供时以空格连接写入 RFC 7591 scope 字段 */
92
+ scopes?: string[];
93
+ }
94
+ /**
95
+ * 动态注册 Web OAuth (浏览器) 客户端,获取 client_id。
96
+ *
97
+ * 与 `register` (桌面 loopback, 硬编码 redirect_uri=127.0.0.1) 的区别:
98
+ * 本函数允许传入任意 Web redirect_uri,供 csign 等第一方 Web 应用使用。
99
+ * `token_endpoint_auth_method` 仍为 `none` (PKCE public client)。
100
+ */
101
+ declare function registerWebOAuthClient(meta: ServerMetadata, opts: RegisterWebOAuthClientOptions, signal?: AbortSignal): Promise<ClientRegistration>;
102
+ /**
103
+ * 生成 OAuth `state` 参数 — 32 字节加密随机数, base64url 无填充。
104
+ *
105
+ * 与 `generateCodeVerifier` 共用随机源 (`randomBase64Url32`)。Web OAuth 流程
106
+ * 用它做 CSRF 防护: 授权请求带上 state, callback 回来必须逐字符比对。
107
+ */
108
+ declare function generateState(): Promise<string>;
61
109
  type LoginEventType = 'auth_url' | 'complete' | 'error';
62
110
  declare const EventAuthURL: "auth_url";
63
111
  declare const EventComplete: "complete";
64
112
  declare const EventError: "error";
65
- type LoginErrCode = 'discovery_failed' | 'registration_failed' | 'browser_open_failed' | 'auth_denied' | 'auth_timeout' | 'token_exchange_failed' | 'ssl_proxy_detected';
113
+ type LoginErrCode = 'discovery_failed' | 'registration_failed' | 'browser_open_failed' | 'auth_denied' | 'auth_timeout' | 'token_exchange_failed' | 'ssl_proxy_detected' | 'state_mismatch';
66
114
  declare const ErrDiscovery: "discovery_failed";
67
115
  declare const ErrRegistration: "registration_failed";
68
116
  declare const ErrBrowserOpen: "browser_open_failed";
@@ -70,6 +118,8 @@ declare const ErrAuthDenied: "auth_denied";
70
118
  declare const ErrTimeout: "auth_timeout";
71
119
  declare const ErrTokenExchange: "token_exchange_failed";
72
120
  declare const ErrSSLProxy: "ssl_proxy_detected";
121
+ /** Web OAuth callback 的 state 与发起时不一致 (CSRF 防护) */
122
+ declare const ErrStateMismatch: "state_mismatch";
73
123
  /** 登录流程事件 */
74
124
  interface LoginEvent {
75
125
  type: LoginEventType;
@@ -112,6 +162,76 @@ declare function authorize(meta: ServerMetadata, clientID: string, scopes: strin
112
162
  result: AuthorizeResult;
113
163
  verifier: string;
114
164
  }>;
165
+ /**
166
+ * Web OAuth 授权请求 — `createWebAuthorizationRequest` 的返回结构。
167
+ *
168
+ * 发起方 (csign Next Route Handler 等) 应把整个对象作为 pending 状态持久化
169
+ * (HttpOnly cookie 等),callback 回来时取出供 `completeWebAuthorizationRequest` 校验。
170
+ */
171
+ interface WebAuthorizationRequest {
172
+ /** 完整授权 URL — 浏览器整页跳转到此地址 */
173
+ authUrl: string;
174
+ /** CSRF state — callback 必须回传同值 */
175
+ state: string;
176
+ /** PKCE code_verifier — 换 token 时使用, 切勿泄露给浏览器 URL */
177
+ verifier: string;
178
+ /** 动态注册得到的 client_id */
179
+ clientID: string;
180
+ /** 本次授权使用的 redirect_uri */
181
+ redirectURI: string;
182
+ /** OAuth issuer / SDK 业务域名 (用于 callback 阶段重新发现 metadata) */
183
+ serverURL: string;
184
+ /** 创建时间戳 (Date.now()),发起方可据此实现 TTL 过期判定 */
185
+ createdAt: number;
186
+ }
187
+ /** `createWebAuthorizationRequest` 参数 */
188
+ interface CreateWebAuthorizationRequestOptions {
189
+ /** 动态注册得到的 client_id */
190
+ clientID: string;
191
+ /** redirect_uri (须与动态注册登记的一致) */
192
+ redirectURI: string;
193
+ /** 请求的 scope 列表 — 以空格连接写入 authUrl */
194
+ scopes: string[];
195
+ /** OAuth issuer / SDK 业务域名 */
196
+ serverURL: string;
197
+ /** 可选 — SSO 场景下预填邮箱 */
198
+ loginHint?: string;
199
+ }
200
+ /**
201
+ * 构造 Web OAuth 授权请求。
202
+ *
203
+ * 生成 PKCE verifier + S256 challenge + CSRF state,按 OAuth 2.1 拼装授权 URL
204
+ * (含 `state` 参数 — SDK 桌面 `authorize` 不带 state, Web 流程必须带)。
205
+ *
206
+ * 返回的 `WebAuthorizationRequest` 应整体持久化为 pending 状态,
207
+ * callback 阶段交给 `completeWebAuthorizationRequest`。
208
+ */
209
+ declare function createWebAuthorizationRequest(meta: ServerMetadata, opts: CreateWebAuthorizationRequestOptions): Promise<WebAuthorizationRequest>;
210
+ /** `completeWebAuthorizationRequest` 的 pending 状态 (即 WebAuthorizationRequest 的子集) */
211
+ interface WebAuthorizationPending {
212
+ state: string;
213
+ verifier: string;
214
+ clientID: string;
215
+ redirectURI: string;
216
+ serverURL: string;
217
+ }
218
+ /** `completeWebAuthorizationRequest` 的 callback 参数 */
219
+ interface WebAuthorizationCallbackParams {
220
+ /** 授权服务器回传的 authorization code */
221
+ code: string;
222
+ /** 授权服务器回传的 state — 必须与 pending.state 一致 */
223
+ state: string;
224
+ }
225
+ /**
226
+ * 完成 Web OAuth 授权 — 校验 state → 换 token → 返回可持久化的 TokenSet。
227
+ *
228
+ * `pending` 为 `createWebAuthorizationRequest` 返回对象 (或其等价持久化结构);
229
+ * `params` 为 callback URL 解析出的 `code` / `state`。
230
+ *
231
+ * state 不匹配时抛错 (CSRF 防护)。内部依次:
232
+ * discoverWebOAuthMetadata(pending.serverURL) → exchangeCode(...) → newTokenSet(...)。
233
+ */
234
+ declare function completeWebAuthorizationRequest(pending: WebAuthorizationPending, params: WebAuthorizationCallbackParams, signal?: AbortSignal): Promise<TokenSet>;
115
235
  declare function exchangeCode(meta: ServerMetadata, clientID: string, code: string, redirectURI: string, codeVerifier: string, signal?: AbortSignal): Promise<TokenResponse>;
116
236
  /** 刷新 access_token */
117
237
  declare function refreshToken(meta: ServerMetadata, clientID: string, refreshTokenValue: string, signal?: AbortSignal): Promise<TokenResponse>;
@@ -720,7 +840,36 @@ interface Config {
720
840
  * `client.compliance.*`,不与既有模型网关 API 冲突。
721
841
  */
722
842
  complianceBaseURL?: string;
723
- }
843
+ /**
844
+ * OAuth metadata profile — 决定 `ensureToken` 刷新 token 时
845
+ * 发现 metadata 走哪个 well-known 端点。
846
+ *
847
+ * - `'desktop'` (默认): `/.well-known/oauth-authorization-server/desktop`
848
+ * — 桌面 loopback OAuth (`login()`) 流程。
849
+ * - `'web'`: `/.well-known/oauth-authorization-server/web`
850
+ * — 浏览器 Web OAuth (csign 等第一方 Web 应用) 签发的 token,
851
+ * 其 refresh 必须走 Web token 端点。
852
+ *
853
+ * 未设置时默认 `'desktop'`,对既有调用方行为完全无影响。
854
+ * `login()` 桌面 loopback 路径不受此配置影响。
855
+ */
856
+ oauthMetadataProfile?: OAuthMetadataProfile;
857
+ /**
858
+ * Browser refresh strategy for Web OAuth tokens.
859
+ *
860
+ * - `'direct'` (default): refresh directly against the OAuth token endpoint.
861
+ * - `'server-proxy'`: POST the current TokenSet to a same-origin refresh proxy,
862
+ * useful when the OAuth issuer intentionally blocks browser CORS.
863
+ * - `'none'`: do not refresh automatically; expired tokens throw `token_expired`.
864
+ */
865
+ browserRefreshMode?: BrowserRefreshMode;
866
+ /** Same-origin refresh proxy URL used when `browserRefreshMode='server-proxy'`. */
867
+ refreshProxyURL?: string;
868
+ }
869
+ type BrowserRefreshMode = 'direct' | 'server-proxy' | 'none';
870
+ declare const ErrOAuthCORSBlocked: "oauth_cors_blocked";
871
+ declare const ErrRefreshProxyFailed: "refresh_proxy_failed";
872
+ declare const ErrTokenExpired: "token_expired";
724
873
  interface Deferred<T> {
725
874
  promise: Promise<T>;
726
875
  resolve: (v: T) => void;
@@ -746,6 +895,12 @@ declare class Client {
746
895
  serverURL: string;
747
896
  /** Compliance API 根地址 (已 trim 尾随 /); null = 走默认 ${serverURL}/admin-api */
748
897
  complianceBaseURL: string | null;
898
+ /** OAuth metadata profile — 刷新 token 时发现 metadata 用 (默认 'desktop') */
899
+ oauthMetadataProfile: OAuthMetadataProfile;
900
+ /** Browser Web OAuth refresh strategy (default 'direct') */
901
+ browserRefreshMode: BrowserRefreshMode;
902
+ /** Same-origin refresh proxy URL for browserRefreshMode='server-proxy' */
903
+ refreshProxyURL: string | null;
749
904
  /** OAuth metadata (lazy loaded) */
750
905
  meta: ServerMetadata | null;
751
906
  /** 当前 token (内存) */
@@ -817,6 +972,10 @@ declare class Client {
817
972
  ensureToken(signal?: AbortSignal): Promise<string>;
818
973
  /** 强制刷新 token (用于 401 重试) */
819
974
  forceRefresh(signal?: AbortSignal): Promise<void>;
975
+ private refreshCurrentToken;
976
+ private refreshCurrentTokenDirect;
977
+ private refreshCurrentTokenViaProxy;
978
+ private saveRefreshedToken;
820
979
  /** 互斥锁 helper (替代 Go sync.Mutex) */
821
980
  private withMu;
822
981
  /** v1.0.2: 跨进程临界区 helper. store.withLock 可选, 缺省则直接调用 fn (LocalStorage /
@@ -1604,4 +1763,4 @@ declare module '@acosmi/sdk-ts' {
1604
1763
  }
1605
1764
  }
1606
1765
 
1607
- export { type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRunOptions, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApproveSealApprovalQuery, type AuthorizeResult, BalanceDetail, type BlockMeta, type BugReportResult, type BugView, BusinessError, type CancelSealApprovalQuery, CertificationStatus, ChatRequest, ChatResponse, Client, ClientRegistration, type ComplianceAssetType, type ComplianceBillingDisplayStatus, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, ConsumeRecordPage, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, DefaultRetryPolicy, DeviceRegistration, EntitlementBalance, EntitlementItem, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrTimeout, ErrTokenExchange, EventAuthURL, EventComplete, EventError, type EvidenceAsset, type EvidencePackage, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, GenerateSkillRequest, GenerateSkillResult, InMemoryTokenStore, InputModality, type IssueTimestampRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, ModelBucket, ModelByQuotaResponse, ModelCapabilities, ModelCoefficient, NotificationList, NotificationPreference, OptimizeSkillRequest, OptimizeSkillResult, Order, OrderStatus, PayPayload, ProviderAdapter, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, QuotaSummary, type RejectSealApprovalQuery, type ReportDownload, type RetryPolicy, type RetryRequestInfo, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, SkillBrowseListResponse, SkillBrowseResponse, SkillStoreItem, SkillStoreQuery, SkillSummary, SourcesEvent, StreamEvent, StreamSettlement, type SubmitSealApprovalRequest, type TimestampToken, type TimestampVerifyResult, TokenPackage, TokenResponse, TokenSet, type TokenStore, ToolView, Transaction, type VerifyTimestampRequest, type WSConfig, WSEvent, WalletStats, allScopes, authorize, buildBetas, classifyComplianceError, commerceScopes, complianceScopes, computeBackoff, defaultRetryable, defaultSafeToRetry, discover, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSLError, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, refreshToken, register, revokeToken, skillScopes, uniqueMerge };
1766
+ export { type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRunOptions, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApproveSealApprovalQuery, type AuthorizeResult, BalanceDetail, type BlockMeta, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type CancelSealApprovalQuery, CertificationStatus, ChatRequest, ChatResponse, Client, ClientRegistration, type ComplianceAssetType, type ComplianceBillingDisplayStatus, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, ConsumeRecordPage, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, DefaultRetryPolicy, DeviceRegistration, EntitlementBalance, EntitlementItem, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, type EvidenceAsset, type EvidencePackage, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, GenerateSkillRequest, GenerateSkillResult, InMemoryTokenStore, InputModality, type IssueTimestampRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, ModelBucket, ModelByQuotaResponse, ModelCapabilities, ModelCoefficient, NotificationList, NotificationPreference, type OAuthMetadataProfile, OptimizeSkillRequest, OptimizeSkillResult, Order, OrderStatus, PayPayload, ProviderAdapter, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, QuotaSummary, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type ReportDownload, type RetryPolicy, type RetryRequestInfo, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, SkillBrowseListResponse, SkillBrowseResponse, SkillStoreItem, SkillStoreQuery, SkillSummary, SourcesEvent, StreamEvent, StreamSettlement, type SubmitSealApprovalRequest, type TimestampToken, type TimestampVerifyResult, TokenPackage, TokenResponse, TokenSet, type TokenStore, ToolView, Transaction, type VerifyTimestampRequest, type WSConfig, WSEvent, WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, allScopes, authorize, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSLError, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, refreshToken, register, registerWebOAuthClient, revokeToken, skillScopes, uniqueMerge };
@@ -1,5 +1,5 @@
1
- import { M as ManagedModel, I as InputModality, S as ServerMetadata, T as TokenResponse, a as TokenSet, C as ClientRegistration, B as BusinessError, b as ModelCoefficient, Q as QuotaSummary, c as ModelCapabilities, d as ChatRequest, P as ProviderAdapter, e as ChatResponse, A as AnthropicResponse, f as StreamEvent, g as SourcesEvent, h as StreamSettlement, E as EntitlementBalance, i as BalanceDetail, j as EntitlementItem, k as ConsumeRecordPage, l as ModelByQuotaResponse, m as ModelBucket, n as TokenPackage, o as PayPayload, O as Order, p as OrderStatus, W as WalletStats, q as Transaction, r as SkillStoreQuery, s as SkillStoreItem, t as SkillBrowseResponse, u as SkillBrowseListResponse, v as SkillSummary, w as CertificationStatus, G as GenerateSkillRequest, x as GenerateSkillResult, y as OptimizeSkillRequest, z as OptimizeSkillResult, D as ToolView, N as NotificationList, F as DeviceRegistration, H as NotificationPreference, J as WSEvent } from './index-28x02ITB.js';
2
- export { K as APIResponse, L as AnthropicContentBlock, R as AnthropicUsage, U as BucketClassCommercial, V as BucketClassGeneric, X as BucketInfo, Y as BucketRow, Z as ChatContentBlock, _ as ChatMessage, $ as ChatUsage, a0 as ConsumeRecord, a1 as EffortConfig, a2 as GeoLoc, a3 as HTTPError, a4 as ModelNotFoundError, a5 as NetworkError, a6 as Notification, a7 as NotificationUnreadCount, a8 as OpenAIChatChoice, a9 as OpenAIChatMessage, aa as OpenAIChatResponse, ab as OpenAIFunctionCall, ac as OpenAIStreamChoice, ad as OpenAIStreamChunk, ae as OpenAIStreamDelta, af as OpenAIStreamToolCall, ag as OpenAIToolCall, ah as OpenAIUsage, ai as OrderTerminalError, aj as OutputConfig, ak as ProviderFormat, al as RateLimitError, am as ServerTool, an as ServerToolTypeWebSearch, ao as SkillStoreListItem, ap as StreamError, aq as ThinkingConfig, ar as ThinkingHigh, as as ThinkingHighMinMaxTokens, at as ThinkingMax, au as ThinkingMaxFallbackMaxTokens, av as ThinkingOff, aw as ToolListResponse, ax as ToolProvider, ay as WebSearchConfig, az as WebSearchSource, aA as YudaoPageResult, aB as anthropicResponseTextContent, aC as anthropicResponseThinkingContent, aD as anthropicResponseToolUseBlocks, aE as apiResponseBusinessError, aF as apiResponseGetMessage, aG as bucketInfoIsCommercial, aH as bucketRowIsCommercial, aI as getAdapter, aJ as getAdapterForModel, aK as newThinkingConfig, aL as newWebSearchTool, aM as parseNotificationEvent, aN as parseSettlement, aO as parseSourcesEvent, aP as tokenSetIsExpired } from './index-28x02ITB.js';
1
+ import { M as ManagedModel, I as InputModality, S as ServerMetadata, T as TokenSet, a as TokenResponse, C as ClientRegistration, B as BusinessError, b as ModelCoefficient, Q as QuotaSummary, c as ModelCapabilities, d as ChatRequest, P as ProviderAdapter, e as ChatResponse, A as AnthropicResponse, f as StreamEvent, g as SourcesEvent, h as StreamSettlement, E as EntitlementBalance, i as BalanceDetail, j as EntitlementItem, k as ConsumeRecordPage, l as ModelByQuotaResponse, m as ModelBucket, n as TokenPackage, o as PayPayload, O as Order, p as OrderStatus, W as WalletStats, q as Transaction, r as SkillStoreQuery, s as SkillStoreItem, t as SkillBrowseResponse, u as SkillBrowseListResponse, v as SkillSummary, w as CertificationStatus, G as GenerateSkillRequest, x as GenerateSkillResult, y as OptimizeSkillRequest, z as OptimizeSkillResult, D as ToolView, N as NotificationList, F as DeviceRegistration, H as NotificationPreference, J as WSEvent } from './index-CbG9NqE-.js';
2
+ export { K as APIResponse, L as AnthropicContentBlock, R as AnthropicUsage, U as BucketClassCommercial, V as BucketClassGeneric, X as BucketInfo, Y as BucketRow, Z as ChatContentBlock, _ as ChatMessage, $ as ChatUsage, a0 as ConsumeRecord, a1 as EffortConfig, a2 as GeoLoc, a3 as HTTPError, a4 as ModelNotFoundError, a5 as NetworkError, a6 as Notification, a7 as NotificationUnreadCount, a8 as OpenAIChatChoice, a9 as OpenAIChatMessage, aa as OpenAIChatResponse, ab as OpenAIFunctionCall, ac as OpenAIStreamChoice, ad as OpenAIStreamChunk, ae as OpenAIStreamDelta, af as OpenAIStreamToolCall, ag as OpenAIToolCall, ah as OpenAIUsage, ai as OrderTerminalError, aj as OutputConfig, ak as ProviderFormat, al as RateLimitError, am as ServerTool, an as ServerToolTypeWebSearch, ao as SkillStoreListItem, ap as StreamError, aq as ThinkingConfig, ar as ThinkingHigh, as as ThinkingHighMinMaxTokens, at as ThinkingMax, au as ThinkingMaxFallbackMaxTokens, av as ThinkingOff, aw as ToolListResponse, ax as ToolProvider, ay as WebSearchConfig, az as WebSearchSource, aA as YudaoPageResult, aB as anthropicResponseTextContent, aC as anthropicResponseThinkingContent, aD as anthropicResponseToolUseBlocks, aE as apiResponseBusinessError, aF as apiResponseGetMessage, aG as bucketInfoIsCommercial, aH as bucketRowIsCommercial, aI as getAdapter, aJ as getAdapterForModel, aK as newThinkingConfig, aL as newWebSearchTool, aM as parseNotificationEvent, aN as parseSettlement, aO as parseSourcesEvent, aP as tokenSetIsExpired } from './index-CbG9NqE-.js';
3
3
  import { M as MinimalSanitizeConfig } from './index-nvLKgCm9.js';
4
4
  export { i as sanitize } from './index-nvLKgCm9.js';
5
5
  export { AnthropicAdapter } from './adapters/anthropic.js';
@@ -48,6 +48,19 @@ declare function findFirstModelByInputModality(models: ManagedModel[], modality:
48
48
  */
49
49
  declare function findDesktopVisualUnderstandingModel(models: ManagedModel[]): ManagedModel | null;
50
50
 
51
+ /** OAuth metadata profile — 决定 well-known 端点的路径后缀 */
52
+ type OAuthMetadataProfile = 'web' | 'desktop';
53
+ /**
54
+ * 从 well-known 端点获取指定 profile 的 OAuth 服务元数据。
55
+ *
56
+ * serverURL 可能含路径 (如 "https://acosmi.ai/api/v4"),
57
+ * well-known 端点按 RFC 8414 必须在 origin 根路径:
58
+ * https://acosmi.ai/.well-known/oauth-authorization-server/<profile>
59
+ *
60
+ * profile='desktop' 对应桌面 loopback OAuth;profile='web' 对应浏览器 Web OAuth。
61
+ * 内部 helper — `discover` / `discoverWebOAuthMetadata` 是其薄包装。
62
+ */
63
+ declare function discoverWithProfile(serverURL: string, profile: OAuthMetadataProfile, signal?: AbortSignal): Promise<ServerMetadata>;
51
64
  /**
52
65
  * 从 well-known 端点获取 Desktop OAuth 服务元数据。
53
66
  *
@@ -56,13 +69,48 @@ declare function findDesktopVisualUnderstandingModel(models: ManagedModel[]): Ma
56
69
  * https://acosmi.ai/.well-known/oauth-authorization-server/desktop
57
70
  */
58
71
  declare function discover(serverURL: string, signal?: AbortSignal): Promise<ServerMetadata>;
72
+ /**
73
+ * 从 well-known 端点获取 Web OAuth 服务元数据。
74
+ *
75
+ * 与 `discover` 行为一致, 但请求路径为
76
+ * https://acosmi.com/.well-known/oauth-authorization-server/web
77
+ *
78
+ * 浏览器侧 Web OAuth (csign 等第一方 Web 应用) 必须用此 profile,
79
+ * 它返回 Web authorize/token 端点; `discover` 的 desktop profile 返回的是
80
+ * 桌面 loopback 端点, 不可混用。
81
+ */
82
+ declare function discoverWebOAuthMetadata(serverURL: string, signal?: AbortSignal): Promise<ServerMetadata>;
59
83
  /** 动态注册桌面客户端,获取 client_id */
60
84
  declare function register(meta: ServerMetadata, appName: string, signal?: AbortSignal): Promise<ClientRegistration>;
85
+ /** Web OAuth 动态注册参数 */
86
+ interface RegisterWebOAuthClientOptions {
87
+ /** 客户端展示名 (RFC 7591 client_name) */
88
+ clientName: string;
89
+ /** 浏览器 Web OAuth 的 redirect_uri 列表 (如 ["https://sign.zhonglvbao.com/login/callback"]) */
90
+ redirectURIs: string[];
91
+ /** 可选 scope 列表 — 提供时以空格连接写入 RFC 7591 scope 字段 */
92
+ scopes?: string[];
93
+ }
94
+ /**
95
+ * 动态注册 Web OAuth (浏览器) 客户端,获取 client_id。
96
+ *
97
+ * 与 `register` (桌面 loopback, 硬编码 redirect_uri=127.0.0.1) 的区别:
98
+ * 本函数允许传入任意 Web redirect_uri,供 csign 等第一方 Web 应用使用。
99
+ * `token_endpoint_auth_method` 仍为 `none` (PKCE public client)。
100
+ */
101
+ declare function registerWebOAuthClient(meta: ServerMetadata, opts: RegisterWebOAuthClientOptions, signal?: AbortSignal): Promise<ClientRegistration>;
102
+ /**
103
+ * 生成 OAuth `state` 参数 — 32 字节加密随机数, base64url 无填充。
104
+ *
105
+ * 与 `generateCodeVerifier` 共用随机源 (`randomBase64Url32`)。Web OAuth 流程
106
+ * 用它做 CSRF 防护: 授权请求带上 state, callback 回来必须逐字符比对。
107
+ */
108
+ declare function generateState(): Promise<string>;
61
109
  type LoginEventType = 'auth_url' | 'complete' | 'error';
62
110
  declare const EventAuthURL: "auth_url";
63
111
  declare const EventComplete: "complete";
64
112
  declare const EventError: "error";
65
- type LoginErrCode = 'discovery_failed' | 'registration_failed' | 'browser_open_failed' | 'auth_denied' | 'auth_timeout' | 'token_exchange_failed' | 'ssl_proxy_detected';
113
+ type LoginErrCode = 'discovery_failed' | 'registration_failed' | 'browser_open_failed' | 'auth_denied' | 'auth_timeout' | 'token_exchange_failed' | 'ssl_proxy_detected' | 'state_mismatch';
66
114
  declare const ErrDiscovery: "discovery_failed";
67
115
  declare const ErrRegistration: "registration_failed";
68
116
  declare const ErrBrowserOpen: "browser_open_failed";
@@ -70,6 +118,8 @@ declare const ErrAuthDenied: "auth_denied";
70
118
  declare const ErrTimeout: "auth_timeout";
71
119
  declare const ErrTokenExchange: "token_exchange_failed";
72
120
  declare const ErrSSLProxy: "ssl_proxy_detected";
121
+ /** Web OAuth callback 的 state 与发起时不一致 (CSRF 防护) */
122
+ declare const ErrStateMismatch: "state_mismatch";
73
123
  /** 登录流程事件 */
74
124
  interface LoginEvent {
75
125
  type: LoginEventType;
@@ -112,6 +162,76 @@ declare function authorize(meta: ServerMetadata, clientID: string, scopes: strin
112
162
  result: AuthorizeResult;
113
163
  verifier: string;
114
164
  }>;
165
+ /**
166
+ * Web OAuth 授权请求 — `createWebAuthorizationRequest` 的返回结构。
167
+ *
168
+ * 发起方 (csign Next Route Handler 等) 应把整个对象作为 pending 状态持久化
169
+ * (HttpOnly cookie 等),callback 回来时取出供 `completeWebAuthorizationRequest` 校验。
170
+ */
171
+ interface WebAuthorizationRequest {
172
+ /** 完整授权 URL — 浏览器整页跳转到此地址 */
173
+ authUrl: string;
174
+ /** CSRF state — callback 必须回传同值 */
175
+ state: string;
176
+ /** PKCE code_verifier — 换 token 时使用, 切勿泄露给浏览器 URL */
177
+ verifier: string;
178
+ /** 动态注册得到的 client_id */
179
+ clientID: string;
180
+ /** 本次授权使用的 redirect_uri */
181
+ redirectURI: string;
182
+ /** OAuth issuer / SDK 业务域名 (用于 callback 阶段重新发现 metadata) */
183
+ serverURL: string;
184
+ /** 创建时间戳 (Date.now()),发起方可据此实现 TTL 过期判定 */
185
+ createdAt: number;
186
+ }
187
+ /** `createWebAuthorizationRequest` 参数 */
188
+ interface CreateWebAuthorizationRequestOptions {
189
+ /** 动态注册得到的 client_id */
190
+ clientID: string;
191
+ /** redirect_uri (须与动态注册登记的一致) */
192
+ redirectURI: string;
193
+ /** 请求的 scope 列表 — 以空格连接写入 authUrl */
194
+ scopes: string[];
195
+ /** OAuth issuer / SDK 业务域名 */
196
+ serverURL: string;
197
+ /** 可选 — SSO 场景下预填邮箱 */
198
+ loginHint?: string;
199
+ }
200
+ /**
201
+ * 构造 Web OAuth 授权请求。
202
+ *
203
+ * 生成 PKCE verifier + S256 challenge + CSRF state,按 OAuth 2.1 拼装授权 URL
204
+ * (含 `state` 参数 — SDK 桌面 `authorize` 不带 state, Web 流程必须带)。
205
+ *
206
+ * 返回的 `WebAuthorizationRequest` 应整体持久化为 pending 状态,
207
+ * callback 阶段交给 `completeWebAuthorizationRequest`。
208
+ */
209
+ declare function createWebAuthorizationRequest(meta: ServerMetadata, opts: CreateWebAuthorizationRequestOptions): Promise<WebAuthorizationRequest>;
210
+ /** `completeWebAuthorizationRequest` 的 pending 状态 (即 WebAuthorizationRequest 的子集) */
211
+ interface WebAuthorizationPending {
212
+ state: string;
213
+ verifier: string;
214
+ clientID: string;
215
+ redirectURI: string;
216
+ serverURL: string;
217
+ }
218
+ /** `completeWebAuthorizationRequest` 的 callback 参数 */
219
+ interface WebAuthorizationCallbackParams {
220
+ /** 授权服务器回传的 authorization code */
221
+ code: string;
222
+ /** 授权服务器回传的 state — 必须与 pending.state 一致 */
223
+ state: string;
224
+ }
225
+ /**
226
+ * 完成 Web OAuth 授权 — 校验 state → 换 token → 返回可持久化的 TokenSet。
227
+ *
228
+ * `pending` 为 `createWebAuthorizationRequest` 返回对象 (或其等价持久化结构);
229
+ * `params` 为 callback URL 解析出的 `code` / `state`。
230
+ *
231
+ * state 不匹配时抛错 (CSRF 防护)。内部依次:
232
+ * discoverWebOAuthMetadata(pending.serverURL) → exchangeCode(...) → newTokenSet(...)。
233
+ */
234
+ declare function completeWebAuthorizationRequest(pending: WebAuthorizationPending, params: WebAuthorizationCallbackParams, signal?: AbortSignal): Promise<TokenSet>;
115
235
  declare function exchangeCode(meta: ServerMetadata, clientID: string, code: string, redirectURI: string, codeVerifier: string, signal?: AbortSignal): Promise<TokenResponse>;
116
236
  /** 刷新 access_token */
117
237
  declare function refreshToken(meta: ServerMetadata, clientID: string, refreshTokenValue: string, signal?: AbortSignal): Promise<TokenResponse>;
@@ -720,7 +840,36 @@ interface Config {
720
840
  * `client.compliance.*`,不与既有模型网关 API 冲突。
721
841
  */
722
842
  complianceBaseURL?: string;
723
- }
843
+ /**
844
+ * OAuth metadata profile — 决定 `ensureToken` 刷新 token 时
845
+ * 发现 metadata 走哪个 well-known 端点。
846
+ *
847
+ * - `'desktop'` (默认): `/.well-known/oauth-authorization-server/desktop`
848
+ * — 桌面 loopback OAuth (`login()`) 流程。
849
+ * - `'web'`: `/.well-known/oauth-authorization-server/web`
850
+ * — 浏览器 Web OAuth (csign 等第一方 Web 应用) 签发的 token,
851
+ * 其 refresh 必须走 Web token 端点。
852
+ *
853
+ * 未设置时默认 `'desktop'`,对既有调用方行为完全无影响。
854
+ * `login()` 桌面 loopback 路径不受此配置影响。
855
+ */
856
+ oauthMetadataProfile?: OAuthMetadataProfile;
857
+ /**
858
+ * Browser refresh strategy for Web OAuth tokens.
859
+ *
860
+ * - `'direct'` (default): refresh directly against the OAuth token endpoint.
861
+ * - `'server-proxy'`: POST the current TokenSet to a same-origin refresh proxy,
862
+ * useful when the OAuth issuer intentionally blocks browser CORS.
863
+ * - `'none'`: do not refresh automatically; expired tokens throw `token_expired`.
864
+ */
865
+ browserRefreshMode?: BrowserRefreshMode;
866
+ /** Same-origin refresh proxy URL used when `browserRefreshMode='server-proxy'`. */
867
+ refreshProxyURL?: string;
868
+ }
869
+ type BrowserRefreshMode = 'direct' | 'server-proxy' | 'none';
870
+ declare const ErrOAuthCORSBlocked: "oauth_cors_blocked";
871
+ declare const ErrRefreshProxyFailed: "refresh_proxy_failed";
872
+ declare const ErrTokenExpired: "token_expired";
724
873
  interface Deferred<T> {
725
874
  promise: Promise<T>;
726
875
  resolve: (v: T) => void;
@@ -746,6 +895,12 @@ declare class Client {
746
895
  serverURL: string;
747
896
  /** Compliance API 根地址 (已 trim 尾随 /); null = 走默认 ${serverURL}/admin-api */
748
897
  complianceBaseURL: string | null;
898
+ /** OAuth metadata profile — 刷新 token 时发现 metadata 用 (默认 'desktop') */
899
+ oauthMetadataProfile: OAuthMetadataProfile;
900
+ /** Browser Web OAuth refresh strategy (default 'direct') */
901
+ browserRefreshMode: BrowserRefreshMode;
902
+ /** Same-origin refresh proxy URL for browserRefreshMode='server-proxy' */
903
+ refreshProxyURL: string | null;
749
904
  /** OAuth metadata (lazy loaded) */
750
905
  meta: ServerMetadata | null;
751
906
  /** 当前 token (内存) */
@@ -817,6 +972,10 @@ declare class Client {
817
972
  ensureToken(signal?: AbortSignal): Promise<string>;
818
973
  /** 强制刷新 token (用于 401 重试) */
819
974
  forceRefresh(signal?: AbortSignal): Promise<void>;
975
+ private refreshCurrentToken;
976
+ private refreshCurrentTokenDirect;
977
+ private refreshCurrentTokenViaProxy;
978
+ private saveRefreshedToken;
820
979
  /** 互斥锁 helper (替代 Go sync.Mutex) */
821
980
  private withMu;
822
981
  /** v1.0.2: 跨进程临界区 helper. store.withLock 可选, 缺省则直接调用 fn (LocalStorage /
@@ -1604,4 +1763,4 @@ declare module '@acosmi/sdk-ts' {
1604
1763
  }
1605
1764
  }
1606
1765
 
1607
- export { type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRunOptions, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApproveSealApprovalQuery, type AuthorizeResult, BalanceDetail, type BlockMeta, type BugReportResult, type BugView, BusinessError, type CancelSealApprovalQuery, CertificationStatus, ChatRequest, ChatResponse, Client, ClientRegistration, type ComplianceAssetType, type ComplianceBillingDisplayStatus, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, ConsumeRecordPage, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, DefaultRetryPolicy, DeviceRegistration, EntitlementBalance, EntitlementItem, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrTimeout, ErrTokenExchange, EventAuthURL, EventComplete, EventError, type EvidenceAsset, type EvidencePackage, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, GenerateSkillRequest, GenerateSkillResult, InMemoryTokenStore, InputModality, type IssueTimestampRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, ModelBucket, ModelByQuotaResponse, ModelCapabilities, ModelCoefficient, NotificationList, NotificationPreference, OptimizeSkillRequest, OptimizeSkillResult, Order, OrderStatus, PayPayload, ProviderAdapter, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, QuotaSummary, type RejectSealApprovalQuery, type ReportDownload, type RetryPolicy, type RetryRequestInfo, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, SkillBrowseListResponse, SkillBrowseResponse, SkillStoreItem, SkillStoreQuery, SkillSummary, SourcesEvent, StreamEvent, StreamSettlement, type SubmitSealApprovalRequest, type TimestampToken, type TimestampVerifyResult, TokenPackage, TokenResponse, TokenSet, type TokenStore, ToolView, Transaction, type VerifyTimestampRequest, type WSConfig, WSEvent, WalletStats, allScopes, authorize, buildBetas, classifyComplianceError, commerceScopes, complianceScopes, computeBackoff, defaultRetryable, defaultSafeToRetry, discover, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSLError, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, refreshToken, register, revokeToken, skillScopes, uniqueMerge };
1766
+ export { type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRunOptions, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApproveSealApprovalQuery, type AuthorizeResult, BalanceDetail, type BlockMeta, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type CancelSealApprovalQuery, CertificationStatus, ChatRequest, ChatResponse, Client, ClientRegistration, type ComplianceAssetType, type ComplianceBillingDisplayStatus, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, ConsumeRecordPage, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, DefaultRetryPolicy, DeviceRegistration, EntitlementBalance, EntitlementItem, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, type EvidenceAsset, type EvidencePackage, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, GenerateSkillRequest, GenerateSkillResult, InMemoryTokenStore, InputModality, type IssueTimestampRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, ModelBucket, ModelByQuotaResponse, ModelCapabilities, ModelCoefficient, NotificationList, NotificationPreference, type OAuthMetadataProfile, OptimizeSkillRequest, OptimizeSkillResult, Order, OrderStatus, PayPayload, ProviderAdapter, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, QuotaSummary, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type ReportDownload, type RetryPolicy, type RetryRequestInfo, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, SkillBrowseListResponse, SkillBrowseResponse, SkillStoreItem, SkillStoreQuery, SkillSummary, SourcesEvent, StreamEvent, StreamSettlement, type SubmitSealApprovalRequest, type TimestampToken, type TimestampVerifyResult, TokenPackage, TokenResponse, TokenSet, type TokenStore, ToolView, Transaction, type VerifyTimestampRequest, type WSConfig, WSEvent, WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, allScopes, authorize, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSLError, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, refreshToken, register, registerWebOAuthClient, revokeToken, skillScopes, uniqueMerge };