@acosmi/sdk-ts 2.9.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,35 @@ All notable changes to `@acosmi/sdk-ts` will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.11.0] - 2026-07-09 — 窗口限额 (WINDOW_LIMIT_EXCEEDED) 结构化承接
9
+
10
+ 后端新增 5 小时 / 7 天滚动窗口 credit 限额:hold 失败返回 429 + 顶层 `errorCode:"WINDOW_LIMIT_EXCEEDED"` + `windowKind` / `windowResetAt`(`/chat` OpenAI 网关扁平形态与 `/anthropic` Anthropic 形态皆有),agent-run SSE error 事件与额度总览同步扩展。SDK 把机器码与窗口字段结构化透传,并顺带修复 `/chat` 网关错误形态 message 一直解析为空的历史缺口。
11
+
12
+ ### Added
13
+
14
+ - **`HTTPError.errorCode` / `windowKind` / `windowResetAt`** — 后端业务机器码(响应体顶层 `errorCode`)与窗口限额字段(档位 `'FIVE_HOUR' | 'WEEKLY'`、预计恢复时间 ISO-8601 UTC)结构化上提;`parseHTTPError` 在任一错误形态下透传。构造 options 加性扩展,既有调用零改动。
15
+ - **`isWindowLimitError(err)` / `isWindowLimitStreamError(err)`** — 窗口限额识别:前者是 `HTTPError` type guard(结构化 `errorCode` 优先,message/body 含 `WINDOW_LIMIT_EXCEEDED` 子串防御兜底,覆盖后端部署版本错位期);后者面向流式产物(`StreamError` / `AgentRunStreamError` / 裸 error payload,`code === 'window_limit_exceeded'` 优先 + 同样的子串兜底)。普通 429 rate limit 不误判。
16
+ - **`AgentRunErrorPayload.windowKind` / `windowResetAt`** — agent-run SSE error 事件可选窗口字段,事件解析(`normalizeError` 白名单 pick)透传,camelCase 契约主拼写 + snake_case 兼容兜底。
17
+ - **`QuotaSummary.windowLimits`(`WindowLimitStatus[]`)** — 额度总览新增滚动窗口限额状态:`{ kind: 'FIVE_HOUR' | 'WEEKLY', limitCredits, usedCredits, resetAt?: string | null }`;后端未启用窗口限额时字段整个缺失,向后兼容。
18
+
19
+ ### Fixed
20
+
21
+ - **`/chat` OpenAI 网关错误形态 message 丢失** — `parseHTTPError` 此前只解析嵌套 `{error:{type,message}}` 形态;网关顶层扁平形态 `{code:429,message:"..."}` 的 message 恒为空、机器码只存活在 body 原串。现补顶层 `message` 解析(该形态无 error.type 来源,`type` 留空),非 JSON body / 空 body 行为逐字节不变。
22
+
23
+ ## [2.10.0] - 2026-06-20 — 多模态向量 / 重排序 (qwen3-vl-embedding / qwen3-vl-rerank)
24
+
25
+ 向量与重排序端点扩展为**多模态**(text / image / **video**),对接 DashScope `qwen3-vl-embedding`(多模态向量端点)与 `qwen3-vl-rerank`(原生 rerank 端点 + 多模态 content)。面向自建搜索引擎的图文 / 视频检索场景。计费口径不变(`total_tokens` 套 input 费率),上游模型名仍由管理员后台自填,不在 SDK / 网关硬编码。
26
+
27
+ ### Added
28
+
29
+ - **`EmbeddingRequest.contents`** — 多模态向量输入:`MultimodalContent[]`(`{ text?, image?, video? }`)。与 `input`(文本线路)二选一;多模态托管模型用 `contents`。同时新增可选 `output_type` / `fps` / `enable_fusion` 参数。
30
+ - **`RerankRequest` 多态 query / documents** — `query: RerankQuery`(`string | { text?, image? }`),`documents: RerankDocument[]`(`(string | { text?, image?, video? })[]`);新增可选 `fps`(多模态视频文档抽帧率)。文本调用完全向后兼容(仍可传 `string` / `string[]`)。
31
+ - **类型** — `MultimodalContent` / `RerankQuery` / `RerankDocument`。
32
+
33
+ ### Changed
34
+
35
+ - **`EmbeddingRequest.input` 改为可选**(`input?: string | string[]`)——多模态线路改用 `contents`。文本调用方无需改动(仍可只传 `input`)。
36
+
8
37
  ## [2.9.0] - 2026-06-20 — 向量 (Embedding) + 重排序 (Rerank) 端点 + listModels 全集模式
9
38
 
10
39
  托管模型网关新增向量与重排序两类模型(上游接阿里云百炼 DashScope),SDK 订阅会员可经现有会员计费体系(Hold→Settle→Release,按 `total_tokens` 套 input 费率)直接调用。具体上游模型名(`text-embedding-v4` / `gte-rerank-v2` / `qwen3-rerank` 等)由管理员在托管模型后台自填,不在 SDK / 网关硬编码。
package/README.md CHANGED
@@ -215,6 +215,28 @@ for (const r of resp.results) {
215
215
 
216
216
  > 重排序对外是**统一扁平契约**;网关内部按模型绑定的线路(DashScope 原生嵌套 `gte-rerank-v2` / OpenAI 兼容扁平 `qwen3-rerank`)自动转换并归一化响应,SDK 侧无需关心。
217
217
 
218
+ ### 多模态向量 / 重排序(v2.10+,text / image / video)
219
+
220
+ 对接 DashScope `qwen3-vl-embedding`(多模态向量)与 `qwen3-vl-rerank`(多模态重排序)。向量用 `contents` 取代 `input`;重排序的 `query` / `documents` 接受多模态对象(`{ text? , image?, video? }`)。适用于自建搜索引擎的图文 / 视频检索。
221
+
222
+ ```ts
223
+ // 多模态向量:图 / 视频 / 文本混合
224
+ const emb = await client.embeddings(mmEmbModel!.id, {
225
+ contents: [{ text: '一只橘猫' }, { image: 'https://…/cat.png' }, { video: 'https://…/clip.mp4' }],
226
+ output_type: 'dense', // 可选
227
+ fps: 2, // 可选:视频抽帧率
228
+ });
229
+
230
+ // 多模态重排序:query 与候选可为多模态对象,也可混入纯文本字符串
231
+ const rr = await client.rerank(mmRerankModel!.id, {
232
+ query: { text: '红色跑车' },
233
+ documents: [{ image: 'https://…/car.png' }, { video: 'https://…/road.mp4' }, '一段描述文字'],
234
+ fps: 1.5, // 可选
235
+ });
236
+ ```
237
+
238
+ > 文本调用完全向后兼容:`input` / 字符串 `query` / 字符串 `documents` 行为不变。多模态托管模型须由管理员在后台勾选对应能力位与输入模态(text/image/video)。
239
+
218
240
  ## 双格式红线(设计核心)
219
241
 
220
242
  SDK 同时提供 **Anthropic + OpenAI 两条 endpoint**,**等地位**,对应两个不同下游产品。
@@ -91,7 +91,21 @@ var init_types = __esm({
91
91
  });
92
92
 
93
93
  // src/shared/errors.ts
94
- var RateLimitError, BusinessError, OrderTerminalError, ModelNotFoundError, HTTPError, NetworkError, StreamError;
94
+ function isWindowLimitError(err) {
95
+ if (!(err instanceof HTTPError)) return false;
96
+ if (err.errorCode === windowLimitErrorCode) return true;
97
+ return err.message.includes(windowLimitErrorCode) || err.body.includes(windowLimitErrorCode);
98
+ }
99
+ function isWindowLimitStreamError(err) {
100
+ if (err == null || typeof err !== "object") return false;
101
+ const e = err;
102
+ if (e.code === windowLimitStreamCode) return true;
103
+ for (const field of [e.message, e.userMessage, e.rawError]) {
104
+ if (typeof field === "string" && field.includes(windowLimitErrorCode)) return true;
105
+ }
106
+ return false;
107
+ }
108
+ var RateLimitError, BusinessError, OrderTerminalError, ModelNotFoundError, HTTPError, NetworkError, StreamError, windowLimitErrorCode, windowLimitStreamCode;
95
109
  var init_errors = __esm({
96
110
  "src/shared/errors.ts"() {
97
111
  RateLimitError = class extends Error {
@@ -138,6 +152,12 @@ var init_errors = __esm({
138
152
  retryAfter;
139
153
  /** 原始响应体 (截断到 maxErrorBodySize) */
140
154
  body;
155
+ /** 后端业务机器码 (响应体顶层 errorCode, e.g. "WINDOW_LIMIT_EXCEEDED"); 缺失为 undefined */
156
+ errorCode;
157
+ /** 窗口限额场景: 触发的滚动窗口档位 (FIVE_HOUR = 5 小时 / WEEKLY = 7 天); 缺失为 undefined */
158
+ windowKind;
159
+ /** 窗口限额场景: 预计恢复时间 (ISO-8601 UTC); 缺失为 undefined */
160
+ windowResetAt;
141
161
  constructor(statusCode, opts = {}) {
142
162
  let msg;
143
163
  if (opts.type) {
@@ -155,6 +175,9 @@ var init_errors = __esm({
155
175
  this.type = opts.type ?? "";
156
176
  this.retryAfter = opts.retryAfter ?? 0;
157
177
  this.body = opts.body ?? "";
178
+ this.errorCode = opts.errorCode;
179
+ this.windowKind = opts.windowKind;
180
+ this.windowResetAt = opts.windowResetAt;
158
181
  }
159
182
  };
160
183
  NetworkError = class extends Error {
@@ -210,6 +233,8 @@ var init_errors = __esm({
210
233
  this.retryable = retryable;
211
234
  }
212
235
  };
236
+ windowLimitErrorCode = "WINDOW_LIMIT_EXCEEDED";
237
+ windowLimitStreamCode = "window_limit_exceeded";
213
238
  }
214
239
  });
215
240
 
@@ -1930,19 +1955,28 @@ function parseHTTPErrorWithHeader(statusCode, body, header) {
1930
1955
  }
1931
1956
  let type = "";
1932
1957
  let message = "";
1958
+ let errorCode;
1959
+ let windowKind;
1960
+ let windowResetAt;
1933
1961
  try {
1934
1962
  const obj = JSON.parse(bodyStr);
1935
1963
  if (obj && typeof obj === "object") {
1936
- const errObj = obj.error;
1964
+ const top = obj;
1965
+ const errObj = top.error;
1937
1966
  if (errObj && typeof errObj === "object") {
1938
1967
  const e = errObj;
1939
1968
  if (typeof e.message === "string") message = e.message;
1940
1969
  if (typeof e.type === "string") type = e.type;
1970
+ } else if (typeof top.message === "string") {
1971
+ message = top.message;
1941
1972
  }
1973
+ if (typeof top.errorCode === "string") errorCode = top.errorCode;
1974
+ if (top.windowKind === "FIVE_HOUR" || top.windowKind === "WEEKLY") windowKind = top.windowKind;
1975
+ if (typeof top.windowResetAt === "string") windowResetAt = top.windowResetAt;
1942
1976
  }
1943
1977
  } catch {
1944
1978
  }
1945
- return new HTTPError(statusCode, { type, message, retryAfter, body: bodyStr });
1979
+ return new HTTPError(statusCode, { type, message, retryAfter, body: bodyStr, errorCode, windowKind, windowResetAt });
1946
1980
  }
1947
1981
  function classifyTransport(op, urlStr, err) {
1948
1982
  const ne = new NetworkError(op, urlStr, err);
@@ -2206,9 +2240,16 @@ var Client = class _Client {
2206
2240
  fetchImpl;
2207
2241
  /** 互斥锁 (TS 用 Promise chain 替代 sync.Mutex) */
2208
2242
  mu = Promise.resolve();
2209
- /** WebSocket 状态 (实际方法由 ws.ts mixin 维护) */
2243
+ /**
2244
+ * WebSocket 状态 (实际方法由 ws.ts mixin 维护)。
2245
+ * @internal — 实现细节: 跨模块 (ws.ts mixin) 需可见故为 public, 但非消费者 API,
2246
+ * 消费者用 connect/subscribe 等高层方法; 引用的 WSState 不进公开文档。
2247
+ */
2210
2248
  ws = null;
2211
- /** v0.15.1: token 就绪等待机制 — login 成功后 resolve, 等待方解除阻塞 */
2249
+ /**
2250
+ * v0.15.1: token 就绪等待机制 — login 成功后 resolve, 等待方解除阻塞。
2251
+ * @internal — 内部同步原语 (Deferred), 非消费者 API。
2252
+ */
2212
2253
  tokenReady = newDeferred();
2213
2254
  /** Login 进行中 — 等待方需等而非 fail-fast */
2214
2255
  loginInFlight = false;
@@ -5629,6 +5670,9 @@ function normalizeError(value) {
5629
5670
  message: stringField(value, "message", "error") || "agent run failed",
5630
5671
  stage: optionalStringField(value, "stage"),
5631
5672
  retryable: typeof value.retryable === "boolean" ? value.retryable : void 0,
5673
+ // 窗口限额扩展 (code="window_limit_exceeded"): 契约 wire 为 camelCase, 蛇形兼容兜底。
5674
+ windowKind: optionalStringField(value, "windowKind", "window_kind"),
5675
+ windowResetAt: optionalStringField(value, "windowResetAt", "window_reset_at"),
5632
5676
  raw: value
5633
5677
  };
5634
5678
  }
@@ -7546,6 +7590,6 @@ function brandCredential(c) {
7546
7590
  return c;
7547
7591
  }
7548
7592
 
7549
- 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, LocalStorageTokenStore as DefaultBrowserTokenStore, 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, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, 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 };
7593
+ 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, LocalStorageTokenStore as DefaultBrowserTokenStore, 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, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, 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 };
7550
7594
  //# sourceMappingURL=index.mjs.map
7551
7595
  //# sourceMappingURL=index.mjs.map