@acosmi/sdk-ts 2.14.0 → 2.16.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.
@@ -1,7 +1,7 @@
1
- import { a as AnthropicResponse } from './openai-BRreM1fK.cjs';
2
- export { A as AnthropicContentBlock, b as AnthropicUsage, O as OpenAIAdapter, d as anthropicResponseTextContent, e as anthropicResponseThinkingContent, f as anthropicResponseToolUseBlocks } from './openai-BRreM1fK.cjs';
3
- import { M as ManagedModel, Q as QuotaSummary, L as WindowResetSummary, n as ModelCapabilities, e as ChatRequest, P as ProviderAdapter, f as ChatResponse, I as ImageGenerationRequest, k as ImageGenerationResponse, V as VideoGenerationRequest, H as VideoTaskResponse, i as EmbeddingRequest, j as EmbeddingResponse, r as RerankRequest, s as RerankResponse, w as StreamEvent, v as SourcesEvent, x as StreamSettlement, l as InputModality } from './index-BoxWrEq0.cjs';
4
- export { B as BucketClassCommercial, a as BucketClassGeneric, b as BucketInfo, c as BucketRow, C as ChatContentBlock, d as ChatMessage, g as ChatUsage, E as EffortConfig, h as EmbeddingData, G as GeoLoc, m as InputModalityTag, o as MultimodalContent, O as OutputConfig, p as ProviderFormat, R as RerankDocument, q as RerankQuery, t as RerankResult, S as ServerTool, u as ServerToolTypeWebSearch, T as ThinkingConfig, y as ThinkingHigh, z as ThinkingHighMinMaxTokens, A as ThinkingMax, D as ThinkingMaxFallbackMaxTokens, F as ThinkingOff, W as WebSearchConfig, J as WebSearchSource, K as WindowLimitStatus, N as bucketInfoIsCommercial, U as bucketRowIsCommercial, X as getAdapter, Y as getAdapterForModel, Z as newThinkingConfig, _ as newWebSearchTool, $ as parseSettlement, a0 as parseSourcesEvent } from './index-BoxWrEq0.cjs';
1
+ import { a as AnthropicResponse } from './openai-B6mz3cyj.cjs';
2
+ export { A as AnthropicContentBlock, b as AnthropicUsage, O as OpenAIAdapter, d as anthropicResponseTextContent, e as anthropicResponseThinkingContent, f as anthropicResponseToolUseBlocks } from './openai-B6mz3cyj.cjs';
3
+ import { M as ManagedModel, Q as QuotaSummary, U as WindowResetSummary, n as ModelCapabilities, e as ChatRequest, P as ProviderAdapter, f as ChatResponse, I as ImageGenerationRequest, k as ImageGenerationResponse, V as VideoGenerationRequest, K as VideoTaskResponse, i as EmbeddingRequest, j as EmbeddingResponse, r as RerankRequest, s as RerankResponse, y as StreamEvent, v as SourcesEvent, z as StreamSettlement, l as InputModality } from './index-yOZUFtNQ.cjs';
4
+ export { B as BucketClassCommercial, a as BucketClassGeneric, b as BucketInfo, c as BucketRow, C as ChatContentBlock, d as ChatMessage, g as ChatUsage, E as EffortConfig, h as EmbeddingData, G as GeoLoc, m as InputModalityTag, o as MultimodalContent, O as OutputConfig, p as ProviderFormat, R as RerankDocument, q as RerankQuery, t as RerankResult, S as ServerTool, u as ServerToolTypeWebSearch, w as SourcesEventIssueCode, x as SourcesEventParseResult, T as ThinkingConfig, A as ThinkingHigh, D as ThinkingHighMinMaxTokens, F as ThinkingMax, H as ThinkingMaxFallbackMaxTokens, J as ThinkingOff, W as WebSearchConfig, L as WebSearchSource, N as WindowLimitStatus, X as bucketInfoIsCommercial, Y as bucketRowIsCommercial, Z as classifySourcesEvent, _ as getAdapter, $ as getAdapterForModel, a0 as newThinkingConfig, a1 as newWebSearchTool, a2 as parseSettlement, a3 as parseSourcesEvent } from './index-yOZUFtNQ.cjs';
5
5
  import { M as MinimalSanitizeConfig } from './index-Bah9A83R.cjs';
6
6
  export { A as sanitize } from './index-Bah9A83R.cjs';
7
7
  export { AnthropicAdapter } from './adapters/anthropic.cjs';
@@ -777,6 +777,33 @@ type BrowserRefreshMode = 'direct' | 'server-proxy' | 'none';
777
777
  declare const ErrOAuthCORSBlocked: "oauth_cors_blocked";
778
778
  declare const ErrRefreshProxyFailed: "refresh_proxy_failed";
779
779
  declare const ErrTokenExpired: "token_expired";
780
+ /**
781
+ * v1.6.0: chat / chatMessages / chatStream / chatMessagesStream 的 per-request 超时上限。
782
+ *
783
+ * 上游 (如 DeepSeek) 在开始推理前可能持续保活长达 10 分钟; SDK 必须容纳
784
+ * "首字节前等待 + 推理 + 流式传输" 全程, 否则会在等待阶段误超时切断。
785
+ * 单值覆盖, 不区分首字节 vs 总耗时 (AbortController 是总耗时上限)。
786
+ *
787
+ * 2026-08-06 导出: 供回归闸门按**符号**断言, 避免测试抄字面量后与本常量各自漂移
788
+ * (抄件断言恒绿 = 零覆盖)。消费方若要自定义更短预算, 传 signal 即可 —
789
+ * withRequestTimeout 取二者先到者, 无需读本值。
790
+ */
791
+ declare const CHAT_REQUEST_TIMEOUT_MS: number;
792
+ /**
793
+ * 流式链路的"对端还活着"回调 (2026-08-06)。
794
+ *
795
+ * **为什么需要它**: 消费方 (如 CrabCode) 自带流空闲看门狗, 判据是"多久没收到事件"。
796
+ * 但 SSE 上有两类**有字节、无事件**的情形, 看门狗对它们完全失明:
797
+ * 1. 上游/网关在推理前发的保活注释行 (": keep-alive") — 被 isSSECommentLine 吞掉
798
+ * 2. OpenAI 格式下 converter.convert() 对某些 data 行返回零事件
799
+ * 两种情形下连接都健康、字节在流动, 看门狗却会掐流。心跳只有在**抵达做判决的那一层**
800
+ * 时才叫心跳 —— 网关补心跳而 SDK 吞掉, 等于没补。
801
+ *
802
+ * 本回调对**每一条** SSE 行触发一次 (含注释行), 早于任何过滤与解析。语义是
803
+ * "链路刚刚有动静", 不是"来了一个事件" —— 消费方拿它重置自己的空闲计时器即可。
804
+ * 回调抛错会被吞掉且不中断流 (它是旁路信号, 不该有能力杀死主链路)。
805
+ */
806
+ type UpstreamActivityCallback = () => void;
780
807
  /**
781
808
  * 非流式 JSON API 请求的默认超时 (毫秒)。
782
809
  *
@@ -1084,14 +1111,18 @@ declare class Client {
1084
1111
  /**
1085
1112
  * 流式聊天 (SSE), 通过 async generator 返回事件
1086
1113
  * v0.5.0: 根据 adapter 路由端点
1114
+ *
1115
+ * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
1087
1116
  */
1088
- chatStream(modelID: string, req: ChatRequest, signal?: AbortSignal): AsyncIterable<StreamEvent>;
1117
+ chatStream(modelID: string, req: ChatRequest, signal?: AbortSignal, onUpstreamActivity?: UpstreamActivityCallback): AsyncIterable<StreamEvent>;
1089
1118
  /**
1090
1119
  * Anthropic 原生格式流式聊天 (SSE)
1091
1120
  * 调用 POST /managed-models/:id/anthropic, SSE 事件为 Anthropic 协议格式
1092
1121
  * 无 started/settled/failed 自定义事件, 无 data: [DONE], message_stop 为自然结束
1122
+ *
1123
+ * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
1093
1124
  */
1094
- chatMessagesStream(modelID: string, req: ChatRequest, signal?: AbortSignal): AsyncIterable<StreamEvent>;
1125
+ chatMessagesStream(modelID: string, req: ChatRequest, signal?: AbortSignal, onUpstreamActivity?: UpstreamActivityCallback): AsyncIterable<StreamEvent>;
1095
1126
  private chatStreamGen;
1096
1127
  private chatMessagesStreamGen;
1097
1128
  /**
@@ -1133,7 +1164,19 @@ declare class Client {
1133
1164
  headers: Headers;
1134
1165
  }>;
1135
1166
  private doJSONFullInternal;
1136
- /** doJSONFull 的 raw bytes 变体 (chat 用, 不立即 JSON.parse) */
1167
+ /**
1168
+ * doJSONFull 的 raw bytes 变体 (chat 用, 不立即 JSON.parse)
1169
+ *
1170
+ * ⚠️ 契约 (2026-08-06): `timeoutMs` 的 30s 默认值只适用于**控制面**端点 (列目录 /
1171
+ * 查配额 / 取任务状态)。凡走**模型推理或生成**的端点 —— chat / anthropic /
1172
+ * embeddings / rerank / images / videos —— 一律必须显式传入 `CHAT_REQUEST_TIMEOUT_MS`,
1173
+ * 哪怕调用方已经用 `withRequestTimeout` 建了外层预算: 外层只约束 `signal`, 内层
1174
+ * 会**另建**一个 `timeoutMs` 计时器, 30s 恒先于任何更长的外层预算触发。
1175
+ *
1176
+ * 这不是假设 —— 2026-08-06 事故里 chat 路径正因漏传本参数而被恒定钉死在 30s,
1177
+ * 且上方 v1.6.0 的注释还声称它已是 11min。回归闸门见
1178
+ * `tests/chat-timeout-budget.test.ts`。
1179
+ */
1137
1180
  doJSONFullRaw(method: string, path: string, body: unknown | null, signal?: AbortSignal, timeoutMs?: number): Promise<{
1138
1181
  result: Uint8Array;
1139
1182
  headers: Headers;
@@ -5186,4 +5229,4 @@ declare class ChatBridgeClient {
5186
5229
  revokeCredential(credentialRef: string, signal?: AbortSignal): Promise<void>;
5187
5230
  }
5188
5231
 
5189
- export { AGENT_RUN_META_TITLE, AGENT_RUN_META_WORKSPACE, ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, type APIResponse, type AdapterKind, type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunListOptions, type AgentRunListResult, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRemoteCreateRequest, type AgentRunRunOptions, type AgentRunRuntime, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApiClientRef, type ApproveSealApprovalQuery, type AssignSeatRequest, type Audience, AudienceEnum, type AuthorizeResult, type BalanceDetail, type BalanceDetailEntitlement, type BillingMode, BillingModeEnum, type BillingPreflightResult, type BlockMeta, type BookConsultationRequest, type BridgeThreadRef, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type BuyResponse, type ByokCreateRequest, type ByokCredential, type ByokCredentialStatus, type ByokProvider, type CancelSealApprovalQuery, type CaseLead, type CaseMatter, type CertificationStatus, type ChannelAttachment, type ChannelCard, type ChannelCardAction, type ChannelInboundEvent, type ChannelOutboundEvent, ChatBridgeClient, type ChatBridgeSession, type ChatCredentialPublic, type ChatIntegration, ChatRequest, ChatResponse, type ChatThread, Client, type ClientRegistration, type ComplianceAssetType, type ComplianceBenefitType, type ComplianceBillingDisplayStatus, type ComplianceCapability, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceQuoteResponse, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceSku, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, type ConsumeRecord, type ConsumeRecordPage, type ContractTemplateField, type ContractTemplateFieldType, type ContractTemplatePageItem, type ContractTemplateResp, type ContractTemplateStatus, type ContractTemplateVersion, type CorporateTransfer, CrabCodeByokClient, type CreateContractTemplateRequest, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateIntegrationRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, type CredentialRef, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, type DeviceRegistration, EmbeddingRequest, EmbeddingResponse, type EnterpriseKycMyStatusView, type EnterpriseMember, type EnterpriseSummary, type EntitlementBalance, type EntitlementItem, type EnvelopeContractItem, 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 EvidenceAssetPageItem, type EvidencePackage, type EvidencePackagePageItem, type FeatureGateState, type FeatureGateStatus, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, type GateQuota, type GenerateSkillRequest, type GenerateSkillResult, HTTPError, type IdempotencyKey, IdempotencyKeyHeader, ImageGenerationRequest, ImageGenerationResponse, InMemoryTokenStore, type InitiateCorporateTransferInput, type InitiateCorporateTransferResult, InputModality, type IntegrationStatus, type InviteMemberRequest, type Invoice, type IssueTimestampRequest, type LawyerCredentialMyView, type LawyerSummary, type LegalConsultation, type LegalServiceOrder, type LegalServiceSku, type LegalSkuCode, type ListContractTemplatesRequest, type ListEvidenceAssetsRequest, type ListEvidencePackagesRequest, type ListOperationsRequest, type ListReportsRequest, type ListSealApprovalsRequest, type ListSealUsesRequest, type ListSigningEnvelopesRequest, type ListTimestampsRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, type Membership, type ModelBucket, type ModelByQuotaResponse, ModelCapabilities, type ModelCoefficient, ModelNotFoundError, NetworkError, type Notification, type NotificationList, type NotificationPreference, type NotificationUnreadCount, type OAuthMetadataProfile, OAuthTokenEndpointError, type OpenAIChatChoice, type OpenAIChatMessage, type OpenAIChatResponse, type OpenAIFunctionCall, type OpenAIStreamChoice, type OpenAIStreamChunk, type OpenAIStreamDelta, type OpenAIStreamToolCall, type OpenAIToolCall, type OpenAIUsage, type OperationDetail, type OperationId, type OperationPageItem, type OperationSource, type OperationStatus, type OptimizeSkillRequest, type OptimizeSkillResult, type Order, type OrderListItem, type OrderStatus, OrderTerminalError, type OrgConsumeReport, type OrgSeat, type OrgSubscription, type PageRequest, type PageResult, type PayPayload, type PaymentMethod, type PermissionPolicy, type Platform, type PricingConfig, type PrincipalRef, type Product, type ProductFamily, ProductFamilyEnum, ProviderAdapter, type ProviderRequestStatus, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, type PublicModelSummary, QuotaSummary, RETRY_ADVICE_REASONS, RateLimitError, type RefundPolicy, type RefundRecord, type Region, type RegionScope, RegionScopeEnum, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type RemoteControlDone, type RemoteControlError, type RemoteControlEvent, type RemoteControlEventType, type RemoteControlPermissionRequest, type RemoteControlPermissionResult, type RemoteControlReasoningDelta, type RemoteControlSettle, type RemoteControlStatus, type RemoteControlTextDelta, type RemoteControlToolCall, type RemoteControlToolResult, type RemoteControlUsage, type RemotePermissionDecision, type RemotePermissionResultRequest, type RemoteSessionPlacement, type RemoteSessionRef, type RemoteSessionTokenGrant, type RemoteUserMessageAck, type RemoteUserMessageRequest, type ReportDownload, type ReportPageItem, type ReqTimeoutCtl, type RequestInvoiceInput, type RequestRefundInput, RerankRequest, RerankResponse, type RetryAdvice, type RetryAdviceReason, type RetryPolicy, type RetryRequestInfo, type RolloverPolicy, type RunnerKind, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, type SealApprovalPageItem, type SealUsePageItem, type ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, type SigningEnvelopePageItem, type SkillBrowseListResponse, type SkillBrowseResponse, type SkillStoreItem, type SkillStoreListItem, type SkillStoreQuery, type SkillSummary, type SortDirection, SourcesEvent, type StepUpStatus, type StoreCredentialRequest, StreamError, StreamEvent, StreamSettlement, type SubmitCaseLeadRequest, type SubmitSealApprovalRequest, type SubscriptionAudience, type SubscriptionPlan, type SubscriptionTier, type TenantRef, type TimestampPageItem, type TimestampToken, type TimestampVerifyResult, type TokenPackage, type TokenResponse, type TokenSet, type TokenStore, type ToolListResponse, type ToolProvider, type ToolView, type Transaction, type TsaProvider, type TsaStats, type UpdateContractTemplateRequest, type UploadContractTemplatePdfRequest, type UserSubscription, type VerifyStatus, type VerifyTimestampRequest, VideoGenerationRequest, VideoTaskResponse, type VoidEnvelopeRequest, type WSConfig, type WSEvent, type WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, WindowResetSummary, type WorkspacePolicy, type YudaoPageResult, allScopes, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, buildBetas, chatBridgeScopes, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getWindowLimitStreamDetails, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isContinuableWindowLimitError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, isWindowLimitError, isWindowLimitStreamError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
5232
+ export { AGENT_RUN_META_TITLE, AGENT_RUN_META_WORKSPACE, ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, type APIResponse, type AdapterKind, type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunListOptions, type AgentRunListResult, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRemoteCreateRequest, type AgentRunRunOptions, type AgentRunRuntime, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApiClientRef, type ApproveSealApprovalQuery, type AssignSeatRequest, type Audience, AudienceEnum, type AuthorizeResult, type BalanceDetail, type BalanceDetailEntitlement, type BillingMode, BillingModeEnum, type BillingPreflightResult, type BlockMeta, type BookConsultationRequest, type BridgeThreadRef, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type BuyResponse, type ByokCreateRequest, type ByokCredential, type ByokCredentialStatus, type ByokProvider, CHAT_REQUEST_TIMEOUT_MS, type CancelSealApprovalQuery, type CaseLead, type CaseMatter, type CertificationStatus, type ChannelAttachment, type ChannelCard, type ChannelCardAction, type ChannelInboundEvent, type ChannelOutboundEvent, ChatBridgeClient, type ChatBridgeSession, type ChatCredentialPublic, type ChatIntegration, ChatRequest, ChatResponse, type ChatThread, Client, type ClientRegistration, type ComplianceAssetType, type ComplianceBenefitType, type ComplianceBillingDisplayStatus, type ComplianceCapability, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceQuoteResponse, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceSku, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, type ConsumeRecord, type ConsumeRecordPage, type ContractTemplateField, type ContractTemplateFieldType, type ContractTemplatePageItem, type ContractTemplateResp, type ContractTemplateStatus, type ContractTemplateVersion, type CorporateTransfer, CrabCodeByokClient, type CreateContractTemplateRequest, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateIntegrationRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, type CredentialRef, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, type DeviceRegistration, EmbeddingRequest, EmbeddingResponse, type EnterpriseKycMyStatusView, type EnterpriseMember, type EnterpriseSummary, type EntitlementBalance, type EntitlementItem, type EnvelopeContractItem, 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 EvidenceAssetPageItem, type EvidencePackage, type EvidencePackagePageItem, type FeatureGateState, type FeatureGateStatus, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, type GateQuota, type GenerateSkillRequest, type GenerateSkillResult, HTTPError, type IdempotencyKey, IdempotencyKeyHeader, ImageGenerationRequest, ImageGenerationResponse, InMemoryTokenStore, type InitiateCorporateTransferInput, type InitiateCorporateTransferResult, InputModality, type IntegrationStatus, type InviteMemberRequest, type Invoice, type IssueTimestampRequest, type LawyerCredentialMyView, type LawyerSummary, type LegalConsultation, type LegalServiceOrder, type LegalServiceSku, type LegalSkuCode, type ListContractTemplatesRequest, type ListEvidenceAssetsRequest, type ListEvidencePackagesRequest, type ListOperationsRequest, type ListReportsRequest, type ListSealApprovalsRequest, type ListSealUsesRequest, type ListSigningEnvelopesRequest, type ListTimestampsRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, type Membership, type ModelBucket, type ModelByQuotaResponse, ModelCapabilities, type ModelCoefficient, ModelNotFoundError, NetworkError, type Notification, type NotificationList, type NotificationPreference, type NotificationUnreadCount, type OAuthMetadataProfile, OAuthTokenEndpointError, type OpenAIChatChoice, type OpenAIChatMessage, type OpenAIChatResponse, type OpenAIFunctionCall, type OpenAIStreamChoice, type OpenAIStreamChunk, type OpenAIStreamDelta, type OpenAIStreamToolCall, type OpenAIToolCall, type OpenAIUsage, type OperationDetail, type OperationId, type OperationPageItem, type OperationSource, type OperationStatus, type OptimizeSkillRequest, type OptimizeSkillResult, type Order, type OrderListItem, type OrderStatus, OrderTerminalError, type OrgConsumeReport, type OrgSeat, type OrgSubscription, type PageRequest, type PageResult, type PayPayload, type PaymentMethod, type PermissionPolicy, type Platform, type PricingConfig, type PrincipalRef, type Product, type ProductFamily, ProductFamilyEnum, ProviderAdapter, type ProviderRequestStatus, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, type PublicModelSummary, QuotaSummary, RETRY_ADVICE_REASONS, RateLimitError, type RefundPolicy, type RefundRecord, type Region, type RegionScope, RegionScopeEnum, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type RemoteControlDone, type RemoteControlError, type RemoteControlEvent, type RemoteControlEventType, type RemoteControlPermissionRequest, type RemoteControlPermissionResult, type RemoteControlReasoningDelta, type RemoteControlSettle, type RemoteControlStatus, type RemoteControlTextDelta, type RemoteControlToolCall, type RemoteControlToolResult, type RemoteControlUsage, type RemotePermissionDecision, type RemotePermissionResultRequest, type RemoteSessionPlacement, type RemoteSessionRef, type RemoteSessionTokenGrant, type RemoteUserMessageAck, type RemoteUserMessageRequest, type ReportDownload, type ReportPageItem, type ReqTimeoutCtl, type RequestInvoiceInput, type RequestRefundInput, RerankRequest, RerankResponse, type RetryAdvice, type RetryAdviceReason, type RetryPolicy, type RetryRequestInfo, type RolloverPolicy, type RunnerKind, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, type SealApprovalPageItem, type SealUsePageItem, type ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, type SigningEnvelopePageItem, type SkillBrowseListResponse, type SkillBrowseResponse, type SkillStoreItem, type SkillStoreListItem, type SkillStoreQuery, type SkillSummary, type SortDirection, SourcesEvent, type StepUpStatus, type StoreCredentialRequest, StreamError, StreamEvent, StreamSettlement, type SubmitCaseLeadRequest, type SubmitSealApprovalRequest, type SubscriptionAudience, type SubscriptionPlan, type SubscriptionTier, type TenantRef, type TimestampPageItem, type TimestampToken, type TimestampVerifyResult, type TokenPackage, type TokenResponse, type TokenSet, type TokenStore, type ToolListResponse, type ToolProvider, type ToolView, type Transaction, type TsaProvider, type TsaStats, type UpdateContractTemplateRequest, type UploadContractTemplatePdfRequest, type UpstreamActivityCallback, type UserSubscription, type VerifyStatus, type VerifyTimestampRequest, VideoGenerationRequest, VideoTaskResponse, type VoidEnvelopeRequest, type WSConfig, type WSEvent, type WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, WindowResetSummary, type WorkspacePolicy, type YudaoPageResult, allScopes, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, buildBetas, chatBridgeScopes, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getWindowLimitStreamDetails, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isContinuableWindowLimitError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, isWindowLimitError, isWindowLimitStreamError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
@@ -1,7 +1,7 @@
1
- import { a as AnthropicResponse } from './openai-Dpz9QgEJ.js';
2
- export { A as AnthropicContentBlock, b as AnthropicUsage, O as OpenAIAdapter, d as anthropicResponseTextContent, e as anthropicResponseThinkingContent, f as anthropicResponseToolUseBlocks } from './openai-Dpz9QgEJ.js';
3
- import { M as ManagedModel, Q as QuotaSummary, L as WindowResetSummary, n as ModelCapabilities, e as ChatRequest, P as ProviderAdapter, f as ChatResponse, I as ImageGenerationRequest, k as ImageGenerationResponse, V as VideoGenerationRequest, H as VideoTaskResponse, i as EmbeddingRequest, j as EmbeddingResponse, r as RerankRequest, s as RerankResponse, w as StreamEvent, v as SourcesEvent, x as StreamSettlement, l as InputModality } from './index-BoxWrEq0.js';
4
- export { B as BucketClassCommercial, a as BucketClassGeneric, b as BucketInfo, c as BucketRow, C as ChatContentBlock, d as ChatMessage, g as ChatUsage, E as EffortConfig, h as EmbeddingData, G as GeoLoc, m as InputModalityTag, o as MultimodalContent, O as OutputConfig, p as ProviderFormat, R as RerankDocument, q as RerankQuery, t as RerankResult, S as ServerTool, u as ServerToolTypeWebSearch, T as ThinkingConfig, y as ThinkingHigh, z as ThinkingHighMinMaxTokens, A as ThinkingMax, D as ThinkingMaxFallbackMaxTokens, F as ThinkingOff, W as WebSearchConfig, J as WebSearchSource, K as WindowLimitStatus, N as bucketInfoIsCommercial, U as bucketRowIsCommercial, X as getAdapter, Y as getAdapterForModel, Z as newThinkingConfig, _ as newWebSearchTool, $ as parseSettlement, a0 as parseSourcesEvent } from './index-BoxWrEq0.js';
1
+ import { a as AnthropicResponse } from './openai-DuQHy2AA.js';
2
+ export { A as AnthropicContentBlock, b as AnthropicUsage, O as OpenAIAdapter, d as anthropicResponseTextContent, e as anthropicResponseThinkingContent, f as anthropicResponseToolUseBlocks } from './openai-DuQHy2AA.js';
3
+ import { M as ManagedModel, Q as QuotaSummary, U as WindowResetSummary, n as ModelCapabilities, e as ChatRequest, P as ProviderAdapter, f as ChatResponse, I as ImageGenerationRequest, k as ImageGenerationResponse, V as VideoGenerationRequest, K as VideoTaskResponse, i as EmbeddingRequest, j as EmbeddingResponse, r as RerankRequest, s as RerankResponse, y as StreamEvent, v as SourcesEvent, z as StreamSettlement, l as InputModality } from './index-yOZUFtNQ.js';
4
+ export { B as BucketClassCommercial, a as BucketClassGeneric, b as BucketInfo, c as BucketRow, C as ChatContentBlock, d as ChatMessage, g as ChatUsage, E as EffortConfig, h as EmbeddingData, G as GeoLoc, m as InputModalityTag, o as MultimodalContent, O as OutputConfig, p as ProviderFormat, R as RerankDocument, q as RerankQuery, t as RerankResult, S as ServerTool, u as ServerToolTypeWebSearch, w as SourcesEventIssueCode, x as SourcesEventParseResult, T as ThinkingConfig, A as ThinkingHigh, D as ThinkingHighMinMaxTokens, F as ThinkingMax, H as ThinkingMaxFallbackMaxTokens, J as ThinkingOff, W as WebSearchConfig, L as WebSearchSource, N as WindowLimitStatus, X as bucketInfoIsCommercial, Y as bucketRowIsCommercial, Z as classifySourcesEvent, _ as getAdapter, $ as getAdapterForModel, a0 as newThinkingConfig, a1 as newWebSearchTool, a2 as parseSettlement, a3 as parseSourcesEvent } from './index-yOZUFtNQ.js';
5
5
  import { M as MinimalSanitizeConfig } from './index-Bah9A83R.js';
6
6
  export { A as sanitize } from './index-Bah9A83R.js';
7
7
  export { AnthropicAdapter } from './adapters/anthropic.js';
@@ -777,6 +777,33 @@ type BrowserRefreshMode = 'direct' | 'server-proxy' | 'none';
777
777
  declare const ErrOAuthCORSBlocked: "oauth_cors_blocked";
778
778
  declare const ErrRefreshProxyFailed: "refresh_proxy_failed";
779
779
  declare const ErrTokenExpired: "token_expired";
780
+ /**
781
+ * v1.6.0: chat / chatMessages / chatStream / chatMessagesStream 的 per-request 超时上限。
782
+ *
783
+ * 上游 (如 DeepSeek) 在开始推理前可能持续保活长达 10 分钟; SDK 必须容纳
784
+ * "首字节前等待 + 推理 + 流式传输" 全程, 否则会在等待阶段误超时切断。
785
+ * 单值覆盖, 不区分首字节 vs 总耗时 (AbortController 是总耗时上限)。
786
+ *
787
+ * 2026-08-06 导出: 供回归闸门按**符号**断言, 避免测试抄字面量后与本常量各自漂移
788
+ * (抄件断言恒绿 = 零覆盖)。消费方若要自定义更短预算, 传 signal 即可 —
789
+ * withRequestTimeout 取二者先到者, 无需读本值。
790
+ */
791
+ declare const CHAT_REQUEST_TIMEOUT_MS: number;
792
+ /**
793
+ * 流式链路的"对端还活着"回调 (2026-08-06)。
794
+ *
795
+ * **为什么需要它**: 消费方 (如 CrabCode) 自带流空闲看门狗, 判据是"多久没收到事件"。
796
+ * 但 SSE 上有两类**有字节、无事件**的情形, 看门狗对它们完全失明:
797
+ * 1. 上游/网关在推理前发的保活注释行 (": keep-alive") — 被 isSSECommentLine 吞掉
798
+ * 2. OpenAI 格式下 converter.convert() 对某些 data 行返回零事件
799
+ * 两种情形下连接都健康、字节在流动, 看门狗却会掐流。心跳只有在**抵达做判决的那一层**
800
+ * 时才叫心跳 —— 网关补心跳而 SDK 吞掉, 等于没补。
801
+ *
802
+ * 本回调对**每一条** SSE 行触发一次 (含注释行), 早于任何过滤与解析。语义是
803
+ * "链路刚刚有动静", 不是"来了一个事件" —— 消费方拿它重置自己的空闲计时器即可。
804
+ * 回调抛错会被吞掉且不中断流 (它是旁路信号, 不该有能力杀死主链路)。
805
+ */
806
+ type UpstreamActivityCallback = () => void;
780
807
  /**
781
808
  * 非流式 JSON API 请求的默认超时 (毫秒)。
782
809
  *
@@ -1084,14 +1111,18 @@ declare class Client {
1084
1111
  /**
1085
1112
  * 流式聊天 (SSE), 通过 async generator 返回事件
1086
1113
  * v0.5.0: 根据 adapter 路由端点
1114
+ *
1115
+ * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
1087
1116
  */
1088
- chatStream(modelID: string, req: ChatRequest, signal?: AbortSignal): AsyncIterable<StreamEvent>;
1117
+ chatStream(modelID: string, req: ChatRequest, signal?: AbortSignal, onUpstreamActivity?: UpstreamActivityCallback): AsyncIterable<StreamEvent>;
1089
1118
  /**
1090
1119
  * Anthropic 原生格式流式聊天 (SSE)
1091
1120
  * 调用 POST /managed-models/:id/anthropic, SSE 事件为 Anthropic 协议格式
1092
1121
  * 无 started/settled/failed 自定义事件, 无 data: [DONE], message_stop 为自然结束
1122
+ *
1123
+ * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
1093
1124
  */
1094
- chatMessagesStream(modelID: string, req: ChatRequest, signal?: AbortSignal): AsyncIterable<StreamEvent>;
1125
+ chatMessagesStream(modelID: string, req: ChatRequest, signal?: AbortSignal, onUpstreamActivity?: UpstreamActivityCallback): AsyncIterable<StreamEvent>;
1095
1126
  private chatStreamGen;
1096
1127
  private chatMessagesStreamGen;
1097
1128
  /**
@@ -1133,7 +1164,19 @@ declare class Client {
1133
1164
  headers: Headers;
1134
1165
  }>;
1135
1166
  private doJSONFullInternal;
1136
- /** doJSONFull 的 raw bytes 变体 (chat 用, 不立即 JSON.parse) */
1167
+ /**
1168
+ * doJSONFull 的 raw bytes 变体 (chat 用, 不立即 JSON.parse)
1169
+ *
1170
+ * ⚠️ 契约 (2026-08-06): `timeoutMs` 的 30s 默认值只适用于**控制面**端点 (列目录 /
1171
+ * 查配额 / 取任务状态)。凡走**模型推理或生成**的端点 —— chat / anthropic /
1172
+ * embeddings / rerank / images / videos —— 一律必须显式传入 `CHAT_REQUEST_TIMEOUT_MS`,
1173
+ * 哪怕调用方已经用 `withRequestTimeout` 建了外层预算: 外层只约束 `signal`, 内层
1174
+ * 会**另建**一个 `timeoutMs` 计时器, 30s 恒先于任何更长的外层预算触发。
1175
+ *
1176
+ * 这不是假设 —— 2026-08-06 事故里 chat 路径正因漏传本参数而被恒定钉死在 30s,
1177
+ * 且上方 v1.6.0 的注释还声称它已是 11min。回归闸门见
1178
+ * `tests/chat-timeout-budget.test.ts`。
1179
+ */
1137
1180
  doJSONFullRaw(method: string, path: string, body: unknown | null, signal?: AbortSignal, timeoutMs?: number): Promise<{
1138
1181
  result: Uint8Array;
1139
1182
  headers: Headers;
@@ -5186,4 +5229,4 @@ declare class ChatBridgeClient {
5186
5229
  revokeCredential(credentialRef: string, signal?: AbortSignal): Promise<void>;
5187
5230
  }
5188
5231
 
5189
- export { AGENT_RUN_META_TITLE, AGENT_RUN_META_WORKSPACE, ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, type APIResponse, type AdapterKind, type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunListOptions, type AgentRunListResult, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRemoteCreateRequest, type AgentRunRunOptions, type AgentRunRuntime, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApiClientRef, type ApproveSealApprovalQuery, type AssignSeatRequest, type Audience, AudienceEnum, type AuthorizeResult, type BalanceDetail, type BalanceDetailEntitlement, type BillingMode, BillingModeEnum, type BillingPreflightResult, type BlockMeta, type BookConsultationRequest, type BridgeThreadRef, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type BuyResponse, type ByokCreateRequest, type ByokCredential, type ByokCredentialStatus, type ByokProvider, type CancelSealApprovalQuery, type CaseLead, type CaseMatter, type CertificationStatus, type ChannelAttachment, type ChannelCard, type ChannelCardAction, type ChannelInboundEvent, type ChannelOutboundEvent, ChatBridgeClient, type ChatBridgeSession, type ChatCredentialPublic, type ChatIntegration, ChatRequest, ChatResponse, type ChatThread, Client, type ClientRegistration, type ComplianceAssetType, type ComplianceBenefitType, type ComplianceBillingDisplayStatus, type ComplianceCapability, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceQuoteResponse, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceSku, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, type ConsumeRecord, type ConsumeRecordPage, type ContractTemplateField, type ContractTemplateFieldType, type ContractTemplatePageItem, type ContractTemplateResp, type ContractTemplateStatus, type ContractTemplateVersion, type CorporateTransfer, CrabCodeByokClient, type CreateContractTemplateRequest, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateIntegrationRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, type CredentialRef, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, type DeviceRegistration, EmbeddingRequest, EmbeddingResponse, type EnterpriseKycMyStatusView, type EnterpriseMember, type EnterpriseSummary, type EntitlementBalance, type EntitlementItem, type EnvelopeContractItem, 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 EvidenceAssetPageItem, type EvidencePackage, type EvidencePackagePageItem, type FeatureGateState, type FeatureGateStatus, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, type GateQuota, type GenerateSkillRequest, type GenerateSkillResult, HTTPError, type IdempotencyKey, IdempotencyKeyHeader, ImageGenerationRequest, ImageGenerationResponse, InMemoryTokenStore, type InitiateCorporateTransferInput, type InitiateCorporateTransferResult, InputModality, type IntegrationStatus, type InviteMemberRequest, type Invoice, type IssueTimestampRequest, type LawyerCredentialMyView, type LawyerSummary, type LegalConsultation, type LegalServiceOrder, type LegalServiceSku, type LegalSkuCode, type ListContractTemplatesRequest, type ListEvidenceAssetsRequest, type ListEvidencePackagesRequest, type ListOperationsRequest, type ListReportsRequest, type ListSealApprovalsRequest, type ListSealUsesRequest, type ListSigningEnvelopesRequest, type ListTimestampsRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, type Membership, type ModelBucket, type ModelByQuotaResponse, ModelCapabilities, type ModelCoefficient, ModelNotFoundError, NetworkError, type Notification, type NotificationList, type NotificationPreference, type NotificationUnreadCount, type OAuthMetadataProfile, OAuthTokenEndpointError, type OpenAIChatChoice, type OpenAIChatMessage, type OpenAIChatResponse, type OpenAIFunctionCall, type OpenAIStreamChoice, type OpenAIStreamChunk, type OpenAIStreamDelta, type OpenAIStreamToolCall, type OpenAIToolCall, type OpenAIUsage, type OperationDetail, type OperationId, type OperationPageItem, type OperationSource, type OperationStatus, type OptimizeSkillRequest, type OptimizeSkillResult, type Order, type OrderListItem, type OrderStatus, OrderTerminalError, type OrgConsumeReport, type OrgSeat, type OrgSubscription, type PageRequest, type PageResult, type PayPayload, type PaymentMethod, type PermissionPolicy, type Platform, type PricingConfig, type PrincipalRef, type Product, type ProductFamily, ProductFamilyEnum, ProviderAdapter, type ProviderRequestStatus, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, type PublicModelSummary, QuotaSummary, RETRY_ADVICE_REASONS, RateLimitError, type RefundPolicy, type RefundRecord, type Region, type RegionScope, RegionScopeEnum, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type RemoteControlDone, type RemoteControlError, type RemoteControlEvent, type RemoteControlEventType, type RemoteControlPermissionRequest, type RemoteControlPermissionResult, type RemoteControlReasoningDelta, type RemoteControlSettle, type RemoteControlStatus, type RemoteControlTextDelta, type RemoteControlToolCall, type RemoteControlToolResult, type RemoteControlUsage, type RemotePermissionDecision, type RemotePermissionResultRequest, type RemoteSessionPlacement, type RemoteSessionRef, type RemoteSessionTokenGrant, type RemoteUserMessageAck, type RemoteUserMessageRequest, type ReportDownload, type ReportPageItem, type ReqTimeoutCtl, type RequestInvoiceInput, type RequestRefundInput, RerankRequest, RerankResponse, type RetryAdvice, type RetryAdviceReason, type RetryPolicy, type RetryRequestInfo, type RolloverPolicy, type RunnerKind, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, type SealApprovalPageItem, type SealUsePageItem, type ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, type SigningEnvelopePageItem, type SkillBrowseListResponse, type SkillBrowseResponse, type SkillStoreItem, type SkillStoreListItem, type SkillStoreQuery, type SkillSummary, type SortDirection, SourcesEvent, type StepUpStatus, type StoreCredentialRequest, StreamError, StreamEvent, StreamSettlement, type SubmitCaseLeadRequest, type SubmitSealApprovalRequest, type SubscriptionAudience, type SubscriptionPlan, type SubscriptionTier, type TenantRef, type TimestampPageItem, type TimestampToken, type TimestampVerifyResult, type TokenPackage, type TokenResponse, type TokenSet, type TokenStore, type ToolListResponse, type ToolProvider, type ToolView, type Transaction, type TsaProvider, type TsaStats, type UpdateContractTemplateRequest, type UploadContractTemplatePdfRequest, type UserSubscription, type VerifyStatus, type VerifyTimestampRequest, VideoGenerationRequest, VideoTaskResponse, type VoidEnvelopeRequest, type WSConfig, type WSEvent, type WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, WindowResetSummary, type WorkspacePolicy, type YudaoPageResult, allScopes, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, buildBetas, chatBridgeScopes, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getWindowLimitStreamDetails, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isContinuableWindowLimitError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, isWindowLimitError, isWindowLimitStreamError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
5232
+ export { AGENT_RUN_META_TITLE, AGENT_RUN_META_WORKSPACE, ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, type APIResponse, type AdapterKind, type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunListOptions, type AgentRunListResult, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRemoteCreateRequest, type AgentRunRunOptions, type AgentRunRuntime, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApiClientRef, type ApproveSealApprovalQuery, type AssignSeatRequest, type Audience, AudienceEnum, type AuthorizeResult, type BalanceDetail, type BalanceDetailEntitlement, type BillingMode, BillingModeEnum, type BillingPreflightResult, type BlockMeta, type BookConsultationRequest, type BridgeThreadRef, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type BuyResponse, type ByokCreateRequest, type ByokCredential, type ByokCredentialStatus, type ByokProvider, CHAT_REQUEST_TIMEOUT_MS, type CancelSealApprovalQuery, type CaseLead, type CaseMatter, type CertificationStatus, type ChannelAttachment, type ChannelCard, type ChannelCardAction, type ChannelInboundEvent, type ChannelOutboundEvent, ChatBridgeClient, type ChatBridgeSession, type ChatCredentialPublic, type ChatIntegration, ChatRequest, ChatResponse, type ChatThread, Client, type ClientRegistration, type ComplianceAssetType, type ComplianceBenefitType, type ComplianceBillingDisplayStatus, type ComplianceCapability, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceQuoteResponse, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceSku, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, type ConsumeRecord, type ConsumeRecordPage, type ContractTemplateField, type ContractTemplateFieldType, type ContractTemplatePageItem, type ContractTemplateResp, type ContractTemplateStatus, type ContractTemplateVersion, type CorporateTransfer, CrabCodeByokClient, type CreateContractTemplateRequest, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateIntegrationRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, type CredentialRef, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, type DeviceRegistration, EmbeddingRequest, EmbeddingResponse, type EnterpriseKycMyStatusView, type EnterpriseMember, type EnterpriseSummary, type EntitlementBalance, type EntitlementItem, type EnvelopeContractItem, 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 EvidenceAssetPageItem, type EvidencePackage, type EvidencePackagePageItem, type FeatureGateState, type FeatureGateStatus, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, type GateQuota, type GenerateSkillRequest, type GenerateSkillResult, HTTPError, type IdempotencyKey, IdempotencyKeyHeader, ImageGenerationRequest, ImageGenerationResponse, InMemoryTokenStore, type InitiateCorporateTransferInput, type InitiateCorporateTransferResult, InputModality, type IntegrationStatus, type InviteMemberRequest, type Invoice, type IssueTimestampRequest, type LawyerCredentialMyView, type LawyerSummary, type LegalConsultation, type LegalServiceOrder, type LegalServiceSku, type LegalSkuCode, type ListContractTemplatesRequest, type ListEvidenceAssetsRequest, type ListEvidencePackagesRequest, type ListOperationsRequest, type ListReportsRequest, type ListSealApprovalsRequest, type ListSealUsesRequest, type ListSigningEnvelopesRequest, type ListTimestampsRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, type Membership, type ModelBucket, type ModelByQuotaResponse, ModelCapabilities, type ModelCoefficient, ModelNotFoundError, NetworkError, type Notification, type NotificationList, type NotificationPreference, type NotificationUnreadCount, type OAuthMetadataProfile, OAuthTokenEndpointError, type OpenAIChatChoice, type OpenAIChatMessage, type OpenAIChatResponse, type OpenAIFunctionCall, type OpenAIStreamChoice, type OpenAIStreamChunk, type OpenAIStreamDelta, type OpenAIStreamToolCall, type OpenAIToolCall, type OpenAIUsage, type OperationDetail, type OperationId, type OperationPageItem, type OperationSource, type OperationStatus, type OptimizeSkillRequest, type OptimizeSkillResult, type Order, type OrderListItem, type OrderStatus, OrderTerminalError, type OrgConsumeReport, type OrgSeat, type OrgSubscription, type PageRequest, type PageResult, type PayPayload, type PaymentMethod, type PermissionPolicy, type Platform, type PricingConfig, type PrincipalRef, type Product, type ProductFamily, ProductFamilyEnum, ProviderAdapter, type ProviderRequestStatus, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, type PublicModelSummary, QuotaSummary, RETRY_ADVICE_REASONS, RateLimitError, type RefundPolicy, type RefundRecord, type Region, type RegionScope, RegionScopeEnum, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type RemoteControlDone, type RemoteControlError, type RemoteControlEvent, type RemoteControlEventType, type RemoteControlPermissionRequest, type RemoteControlPermissionResult, type RemoteControlReasoningDelta, type RemoteControlSettle, type RemoteControlStatus, type RemoteControlTextDelta, type RemoteControlToolCall, type RemoteControlToolResult, type RemoteControlUsage, type RemotePermissionDecision, type RemotePermissionResultRequest, type RemoteSessionPlacement, type RemoteSessionRef, type RemoteSessionTokenGrant, type RemoteUserMessageAck, type RemoteUserMessageRequest, type ReportDownload, type ReportPageItem, type ReqTimeoutCtl, type RequestInvoiceInput, type RequestRefundInput, RerankRequest, RerankResponse, type RetryAdvice, type RetryAdviceReason, type RetryPolicy, type RetryRequestInfo, type RolloverPolicy, type RunnerKind, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, type SealApprovalPageItem, type SealUsePageItem, type ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, type SigningEnvelopePageItem, type SkillBrowseListResponse, type SkillBrowseResponse, type SkillStoreItem, type SkillStoreListItem, type SkillStoreQuery, type SkillSummary, type SortDirection, SourcesEvent, type StepUpStatus, type StoreCredentialRequest, StreamError, StreamEvent, StreamSettlement, type SubmitCaseLeadRequest, type SubmitSealApprovalRequest, type SubscriptionAudience, type SubscriptionPlan, type SubscriptionTier, type TenantRef, type TimestampPageItem, type TimestampToken, type TimestampVerifyResult, type TokenPackage, type TokenResponse, type TokenSet, type TokenStore, type ToolListResponse, type ToolProvider, type ToolView, type Transaction, type TsaProvider, type TsaStats, type UpdateContractTemplateRequest, type UploadContractTemplatePdfRequest, type UpstreamActivityCallback, type UserSubscription, type VerifyStatus, type VerifyTimestampRequest, VideoGenerationRequest, VideoTaskResponse, type VoidEnvelopeRequest, type WSConfig, type WSEvent, type WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, WindowResetSummary, type WorkspacePolicy, type YudaoPageResult, allScopes, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, buildBetas, chatBridgeScopes, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getWindowLimitStreamDetails, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isContinuableWindowLimitError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, isWindowLimitError, isWindowLimitStreamError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
@@ -41,6 +41,57 @@ function newWebSearchTool(cfg) {
41
41
  }
42
42
  return st;
43
43
  }
44
+ function classifySourcesEvent(ev) {
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(ev.data);
48
+ } catch {
49
+ return ev.event === "sources" ? { kind: "malformed_sources", code: "invalid_json" } : { kind: "not_sources" };
50
+ }
51
+ const wrapper = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
52
+ if (wrapper?.type !== "sources" && ev.event !== "sources") {
53
+ return { kind: "not_sources" };
54
+ }
55
+ if (!wrapper || !Object.prototype.hasOwnProperty.call(wrapper, "sources")) {
56
+ return { kind: "malformed_sources", code: "missing_sources" };
57
+ }
58
+ if (Object.prototype.hasOwnProperty.call(wrapper, "session_id") && wrapper.session_id !== void 0 && typeof wrapper.session_id !== "string") {
59
+ return { kind: "malformed_sources", code: "session_id_invalid" };
60
+ }
61
+ if (!Array.isArray(wrapper.sources)) {
62
+ return { kind: "malformed_sources", code: "sources_not_array" };
63
+ }
64
+ const sessionID = typeof wrapper.session_id === "string" ? wrapper.session_id : void 0;
65
+ if (wrapper.sources.length === 0) {
66
+ return {
67
+ kind: "empty_sources",
68
+ ...sessionID === void 0 ? {} : { session_id: sessionID }
69
+ };
70
+ }
71
+ for (const source of wrapper.sources) {
72
+ if (typeof source !== "object" || source === null || Array.isArray(source)) {
73
+ return { kind: "malformed_sources", code: "source_not_object" };
74
+ }
75
+ const item = source;
76
+ if (typeof item.title !== "string") {
77
+ return { kind: "malformed_sources", code: "source_title_invalid" };
78
+ }
79
+ if (typeof item.url !== "string") {
80
+ return { kind: "malformed_sources", code: "source_url_invalid" };
81
+ }
82
+ if (Object.prototype.hasOwnProperty.call(item, "snippet") && item.snippet !== void 0 && typeof item.snippet !== "string") {
83
+ return { kind: "malformed_sources", code: "source_snippet_invalid" };
84
+ }
85
+ }
86
+ return {
87
+ kind: "sources",
88
+ value: {
89
+ ...wrapper,
90
+ sources: wrapper.sources,
91
+ ...sessionID === void 0 ? {} : { session_id: sessionID }
92
+ }
93
+ };
94
+ }
44
95
  function parseSourcesEvent(ev) {
45
96
  let wrapper;
46
97
  try {
@@ -2237,6 +2288,13 @@ var ErrOAuthCORSBlocked = "oauth_cors_blocked";
2237
2288
  var ErrRefreshProxyFailed = "refresh_proxy_failed";
2238
2289
  var ErrTokenExpired = "token_expired";
2239
2290
  var CHAT_REQUEST_TIMEOUT_MS = 11 * 60 * 1e3;
2291
+ function notifyUpstreamActivity(cb) {
2292
+ if (!cb) return;
2293
+ try {
2294
+ cb();
2295
+ } catch {
2296
+ }
2297
+ }
2240
2298
  var DEFAULT_API_TIMEOUT_MS = 6e4;
2241
2299
  function newDeferred() {
2242
2300
  let resolve;
@@ -2950,7 +3008,13 @@ var Client = class _Client {
2950
3008
  try {
2951
3009
  const { body, adapter } = await this.buildChatRequest(modelID, r, ctl.signal);
2952
3010
  const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
2953
- const { result, headers } = await this.doJSONFullRaw("POST", endpoint, body, ctl.signal);
3011
+ const { result, headers } = await this.doJSONFullRaw(
3012
+ "POST",
3013
+ endpoint,
3014
+ body,
3015
+ ctl.signal,
3016
+ CHAT_REQUEST_TIMEOUT_MS
3017
+ );
2954
3018
  const resp = adapter.parseResponse(result);
2955
3019
  const v1 = headers.get("X-Token-Remaining");
2956
3020
  if (v1) {
@@ -3015,7 +3079,13 @@ var Client = class _Client {
3015
3079
  */
3016
3080
  async generateVideo(modelID, req, signal) {
3017
3081
  const endpoint = `/managed-models/${encodeURIComponent(modelID)}/videos/generations`;
3018
- const { result } = await this.doJSONFullRaw("POST", endpoint, req, signal);
3082
+ const { result } = await this.doJSONFullRaw(
3083
+ "POST",
3084
+ endpoint,
3085
+ req,
3086
+ signal,
3087
+ CHAT_REQUEST_TIMEOUT_MS
3088
+ );
3019
3089
  return this.unwrapAPIResponse(result);
3020
3090
  }
3021
3091
  /**
@@ -3084,7 +3154,8 @@ var Client = class _Client {
3084
3154
  "POST",
3085
3155
  `/managed-models/${encodeURIComponent(modelID)}/anthropic`,
3086
3156
  data,
3087
- ctl.signal
3157
+ ctl.signal,
3158
+ CHAT_REQUEST_TIMEOUT_MS
3088
3159
  );
3089
3160
  const rawStr = new TextDecoder().decode(result);
3090
3161
  try {
@@ -3118,7 +3189,13 @@ var Client = class _Client {
3118
3189
  const body = adapter.buildRequestBody(caps, r);
3119
3190
  const data = JSON.stringify(body);
3120
3191
  const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
3121
- const { result } = await this.doJSONFullRaw("POST", endpoint, data, ctl.signal);
3192
+ const { result } = await this.doJSONFullRaw(
3193
+ "POST",
3194
+ endpoint,
3195
+ data,
3196
+ ctl.signal,
3197
+ CHAT_REQUEST_TIMEOUT_MS
3198
+ );
3122
3199
  const { parseOpenAIResponseToAnthropic: parseOpenAIResponseToAnthropic2 } = await Promise.resolve().then(() => (init_openai(), openai_exports));
3123
3200
  return parseOpenAIResponseToAnthropic2(result);
3124
3201
  } finally {
@@ -3128,23 +3205,27 @@ var Client = class _Client {
3128
3205
  /**
3129
3206
  * 流式聊天 (SSE), 通过 async generator 返回事件
3130
3207
  * v0.5.0: 根据 adapter 路由端点
3208
+ *
3209
+ * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
3131
3210
  */
3132
- chatStream(modelID, req, signal) {
3211
+ chatStream(modelID, req, signal, onUpstreamActivity) {
3133
3212
  return {
3134
- [Symbol.asyncIterator]: () => this.chatStreamGen(modelID, req, signal, false)
3213
+ [Symbol.asyncIterator]: () => this.chatStreamGen(modelID, req, signal, false, onUpstreamActivity)
3135
3214
  };
3136
3215
  }
3137
3216
  /**
3138
3217
  * Anthropic 原生格式流式聊天 (SSE)
3139
3218
  * 调用 POST /managed-models/:id/anthropic, SSE 事件为 Anthropic 协议格式
3140
3219
  * 无 started/settled/failed 自定义事件, 无 data: [DONE], message_stop 为自然结束
3220
+ *
3221
+ * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
3141
3222
  */
3142
- chatMessagesStream(modelID, req, signal) {
3223
+ chatMessagesStream(modelID, req, signal, onUpstreamActivity) {
3143
3224
  return {
3144
- [Symbol.asyncIterator]: () => this.chatMessagesStreamGen(modelID, req, signal, false)
3225
+ [Symbol.asyncIterator]: () => this.chatMessagesStreamGen(modelID, req, signal, false, onUpstreamActivity)
3145
3226
  };
3146
3227
  }
3147
- async *chatStreamGen(modelID, req, signal, retried) {
3228
+ async *chatStreamGen(modelID, req, signal, retried, onUpstreamActivity) {
3148
3229
  const r = { ...req, stream: true };
3149
3230
  const { body, adapter } = await this.buildChatRequest(modelID, r, signal);
3150
3231
  const token = await this.ensureToken(signal);
@@ -3177,7 +3258,7 @@ var Client = class _Client {
3177
3258
  `stream: unauthorized and refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`
3178
3259
  );
3179
3260
  }
3180
- yield* this.chatStreamGen(modelID, req, signal, true);
3261
+ yield* this.chatStreamGen(modelID, req, signal, true, onUpstreamActivity);
3181
3262
  return;
3182
3263
  }
3183
3264
  if (!resp.ok) {
@@ -3193,6 +3274,7 @@ var Client = class _Client {
3193
3274
  }
3194
3275
  let currentEvent = "";
3195
3276
  for await (const line of iterSSELines(resp.body)) {
3277
+ notifyUpstreamActivity(onUpstreamActivity);
3196
3278
  if (isSSECommentLine(line)) continue;
3197
3279
  if (line.startsWith("event:")) {
3198
3280
  currentEvent = line.slice("event:".length).trim();
@@ -3213,7 +3295,7 @@ var Client = class _Client {
3213
3295
  }
3214
3296
  }
3215
3297
  }
3216
- async *chatMessagesStreamGen(modelID, req, signal, retried) {
3298
+ async *chatMessagesStreamGen(modelID, req, signal, retried, onUpstreamActivity) {
3217
3299
  const r = { ...req, stream: true };
3218
3300
  const { body, adapter } = await this.buildChatRequest(modelID, r, signal);
3219
3301
  const token = await this.ensureToken(signal);
@@ -3246,7 +3328,7 @@ var Client = class _Client {
3246
3328
  `messages stream: unauthorized and refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`
3247
3329
  );
3248
3330
  }
3249
- yield* this.chatMessagesStreamGen(modelID, req, signal, true);
3331
+ yield* this.chatMessagesStreamGen(modelID, req, signal, true, onUpstreamActivity);
3250
3332
  return;
3251
3333
  }
3252
3334
  if (!resp.ok) {
@@ -3259,6 +3341,7 @@ var Client = class _Client {
3259
3341
  if (adapter.format() === 1 /* OpenAI */) {
3260
3342
  const converter = newOpenAIStreamConverter();
3261
3343
  for await (const line of iterSSELines(resp.body)) {
3344
+ notifyUpstreamActivity(onUpstreamActivity);
3262
3345
  if (isSSECommentLine(line)) continue;
3263
3346
  if (line.startsWith("event:")) {
3264
3347
  line.slice("event:".length).trim();
@@ -3273,6 +3356,7 @@ var Client = class _Client {
3273
3356
  const blockTypeMap = /* @__PURE__ */ new Map();
3274
3357
  let currentEvent = "";
3275
3358
  for await (const line of iterSSELines(resp.body)) {
3359
+ notifyUpstreamActivity(onUpstreamActivity);
3276
3360
  if (isSSECommentLine(line)) continue;
3277
3361
  if (line.startsWith("event:")) {
3278
3362
  currentEvent = line.slice("event:".length).trim();
@@ -3405,7 +3489,19 @@ var Client = class _Client {
3405
3489
  ctl.dispose();
3406
3490
  }
3407
3491
  }
3408
- /** doJSONFull 的 raw bytes 变体 (chat 用, 不立即 JSON.parse) */
3492
+ /**
3493
+ * doJSONFull 的 raw bytes 变体 (chat 用, 不立即 JSON.parse)
3494
+ *
3495
+ * ⚠️ 契约 (2026-08-06): `timeoutMs` 的 30s 默认值只适用于**控制面**端点 (列目录 /
3496
+ * 查配额 / 取任务状态)。凡走**模型推理或生成**的端点 —— chat / anthropic /
3497
+ * embeddings / rerank / images / videos —— 一律必须显式传入 `CHAT_REQUEST_TIMEOUT_MS`,
3498
+ * 哪怕调用方已经用 `withRequestTimeout` 建了外层预算: 外层只约束 `signal`, 内层
3499
+ * 会**另建**一个 `timeoutMs` 计时器, 30s 恒先于任何更长的外层预算触发。
3500
+ *
3501
+ * 这不是假设 —— 2026-08-06 事故里 chat 路径正因漏传本参数而被恒定钉死在 30s,
3502
+ * 且上方 v1.6.0 的注释还声称它已是 11min。回归闸门见
3503
+ * `tests/chat-timeout-budget.test.ts`。
3504
+ */
3409
3505
  async doJSONFullRaw(method, path, body, signal, timeoutMs = 3e4) {
3410
3506
  return this.doJSONFullRawInternal(method, path, body, signal, false, timeoutMs);
3411
3507
  }
@@ -7066,6 +7162,15 @@ function sleep2(ms, signal) {
7066
7162
  }
7067
7163
 
7068
7164
  // src/support/bug-report.ts
7165
+ function unwrapBugReport(raw, op, isComplete) {
7166
+ if (raw && isComplete(raw)) return raw;
7167
+ const inner = raw?.data;
7168
+ if (inner && isComplete(inner)) return inner;
7169
+ const keys = raw && typeof raw === "object" ? Object.keys(raw) : [];
7170
+ throw new Error(
7171
+ `acosmi: ${op}: gateway accepted the request but the response is missing required fields (observed keys: ${keys.length > 0 ? keys.join(",") : "<none>"})`
7172
+ );
7173
+ }
7069
7174
  Client.prototype.submitBugReport = async function(reportData, signal) {
7070
7175
  if (reportData == null) {
7071
7176
  throw new Error("acosmi: reportData required");
@@ -7082,7 +7187,11 @@ Client.prototype.submitBugReport = async function(reportData, signal) {
7082
7187
  { content: contentStr },
7083
7188
  signal
7084
7189
  );
7085
- return result.data;
7190
+ return unwrapBugReport(
7191
+ result,
7192
+ "submitBugReport",
7193
+ (r) => typeof r.feedback_id === "string" && r.feedback_id.length > 0
7194
+ );
7086
7195
  };
7087
7196
  Client.prototype.getBugReport = async function(bugID, signal) {
7088
7197
  const trimmed = bugID.trim();
@@ -7095,7 +7204,7 @@ Client.prototype.getBugReport = async function(bugID, signal) {
7095
7204
  null,
7096
7205
  signal
7097
7206
  );
7098
- return resp.data;
7207
+ return unwrapBugReport(resp, "getBugReport", (r) => typeof r.id === "string");
7099
7208
  };
7100
7209
 
7101
7210
  // src/subscription/client.ts
@@ -7677,6 +7786,6 @@ function brandCredential(c) {
7677
7786
  return c;
7678
7787
  }
7679
7788
 
7680
- export { AGENT_RUN_META_TITLE, AGENT_RUN_META_WORKSPACE, ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, AgentRunStreamError, AgentRunsClient, AnthropicAdapter, AudienceEnum, BillingModeEnum, BucketClassCommercial, BucketClassGeneric, BusinessError, ChatBridgeClient, Client, ComplianceClient, CompliancePollError, CrabCodeByokClient, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, 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, FileTokenStore, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OAuthTokenEndpointError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, ServerToolTypeWebSearch, StreamError, ThinkingHigh, ThinkingHighMinMaxTokens, ThinkingMax, ThinkingMaxFallbackMaxTokens, ThinkingOff, allScopes, anthropicResponseTextContent, anthropicResponseThinkingContent, anthropicResponseToolUseBlocks, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, bucketInfoIsCommercial, bucketRowIsCommercial, buildBetas, chatBridgeScopes, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getAdapter, getAdapterForModel, getWindowLimitStreamDetails, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isContinuableWindowLimitError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, isWindowLimitError, isWindowLimitStreamError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newThinkingConfig, newTokenSet, newWebSearchTool, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, parseSettlement, parseSourcesEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, sanitize_exports as sanitize, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
7789
+ export { AGENT_RUN_META_TITLE, AGENT_RUN_META_WORKSPACE, ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, AgentRunStreamError, AgentRunsClient, AnthropicAdapter, AudienceEnum, BillingModeEnum, BucketClassCommercial, BucketClassGeneric, BusinessError, CHAT_REQUEST_TIMEOUT_MS, ChatBridgeClient, Client, ComplianceClient, CompliancePollError, CrabCodeByokClient, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, 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, FileTokenStore, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OAuthTokenEndpointError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, ServerToolTypeWebSearch, StreamError, ThinkingHigh, ThinkingHighMinMaxTokens, ThinkingMax, ThinkingMaxFallbackMaxTokens, ThinkingOff, allScopes, anthropicResponseTextContent, anthropicResponseThinkingContent, anthropicResponseToolUseBlocks, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, bucketInfoIsCommercial, bucketRowIsCommercial, buildBetas, chatBridgeScopes, classifyComplianceError, classifySourcesEvent, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getAdapter, getAdapterForModel, getWindowLimitStreamDetails, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isContinuableWindowLimitError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, isWindowLimitError, isWindowLimitStreamError, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newThinkingConfig, newTokenSet, newWebSearchTool, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, parseSettlement, parseSourcesEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, sanitize_exports as sanitize, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
7681
7790
  //# sourceMappingURL=index.mjs.map
7682
7791
  //# sourceMappingURL=index.mjs.map