@acosmi/sdk-ts 2.18.0 → 2.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2317,6 +2317,22 @@ function notifyUpstreamActivity(cb) {
2317
2317
  } catch {
2318
2318
  }
2319
2319
  }
2320
+ var GATEWAY_REQUEST_ID_HEADER = "X-Acosmi-Request-Id";
2321
+ function readGatewayRequestID(headers) {
2322
+ const raw = headers.get(GATEWAY_REQUEST_ID_HEADER);
2323
+ if (!raw) return void 0;
2324
+ const trimmed = raw.trim();
2325
+ return trimmed === "" ? void 0 : trimmed;
2326
+ }
2327
+ function notifyGatewayRequestID(cb, headers) {
2328
+ if (!cb) return;
2329
+ const id = readGatewayRequestID(headers);
2330
+ if (id === void 0) return;
2331
+ try {
2332
+ cb(id);
2333
+ } catch {
2334
+ }
2335
+ }
2320
2336
  var DEFAULT_API_TIMEOUT_MS = 6e4;
2321
2337
  function newDeferred() {
2322
2338
  let resolve;
@@ -3024,7 +3040,7 @@ var Client = class _Client {
3024
3040
  * 响应的 tokenRemaining / callRemaining 字段来自服务端 Header, 反映结算后余额
3025
3041
  * v0.5.0: 根据 provider 自动路由到 /anthropic 或 /chat 端点
3026
3042
  */
3027
- async chat(modelID, req, signal) {
3043
+ async chat(modelID, req, signal, onGatewayRequestID) {
3028
3044
  const r = { ...req, stream: false };
3029
3045
  const ctl = withRequestTimeout(CHAT_REQUEST_TIMEOUT_MS, signal);
3030
3046
  try {
@@ -3037,6 +3053,7 @@ var Client = class _Client {
3037
3053
  ctl.signal,
3038
3054
  CHAT_REQUEST_TIMEOUT_MS
3039
3055
  );
3056
+ notifyGatewayRequestID(onGatewayRequestID, headers);
3040
3057
  const resp = adapter.parseResponse(result);
3041
3058
  const v1 = headers.get("X-Token-Remaining");
3042
3059
  if (v1) {
@@ -3157,28 +3174,29 @@ var Client = class _Client {
3157
3174
  * Anthropic → chatMessagesAnthropic (现有路径, POST /anthropic)
3158
3175
  * 其他厂商 → chatMessagesOpenAI (POST /chat, 响应转换为 AnthropicResponse)
3159
3176
  */
3160
- async chatMessages(modelID, req, signal) {
3177
+ async chatMessages(modelID, req, signal, onGatewayRequestID) {
3161
3178
  const m = await this.ensureModelCached(modelID, signal);
3162
3179
  const adapter = getAdapterForModel(m);
3163
3180
  if (adapter.format() === 0 /* Anthropic */) {
3164
- return this.chatMessagesAnthropic(modelID, req, adapter, signal);
3181
+ return this.chatMessagesAnthropic(modelID, req, adapter, signal, onGatewayRequestID);
3165
3182
  }
3166
- return this.chatMessagesOpenAI(modelID, req, adapter, signal);
3183
+ return this.chatMessagesOpenAI(modelID, req, adapter, signal, onGatewayRequestID);
3167
3184
  }
3168
- async chatMessagesAnthropic(modelID, req, adapter, signal) {
3185
+ async chatMessagesAnthropic(modelID, req, adapter, signal, onGatewayRequestID) {
3169
3186
  const r = { ...req, stream: false };
3170
3187
  const ctl = withRequestTimeout(CHAT_REQUEST_TIMEOUT_MS, signal);
3171
3188
  try {
3172
3189
  const caps = this.getCachedCapabilities(modelID) ?? zeroModelCapabilities();
3173
3190
  const body = adapter.buildRequestBody(caps, r);
3174
3191
  const data = JSON.stringify(body);
3175
- const { result } = await this.doJSONFullRaw(
3192
+ const { result, headers } = await this.doJSONFullRaw(
3176
3193
  "POST",
3177
3194
  `/managed-models/${encodeURIComponent(modelID)}/anthropic`,
3178
3195
  data,
3179
3196
  ctl.signal,
3180
3197
  CHAT_REQUEST_TIMEOUT_MS
3181
3198
  );
3199
+ notifyGatewayRequestID(onGatewayRequestID, headers);
3182
3200
  const rawStr = new TextDecoder().decode(result);
3183
3201
  try {
3184
3202
  const wrapper = JSON.parse(rawStr);
@@ -3203,7 +3221,7 @@ var Client = class _Client {
3203
3221
  ctl.dispose();
3204
3222
  }
3205
3223
  }
3206
- async chatMessagesOpenAI(modelID, req, adapter, signal) {
3224
+ async chatMessagesOpenAI(modelID, req, adapter, signal, onGatewayRequestID) {
3207
3225
  const r = { ...req, stream: false };
3208
3226
  const ctl = withRequestTimeout(CHAT_REQUEST_TIMEOUT_MS, signal);
3209
3227
  try {
@@ -3211,13 +3229,14 @@ var Client = class _Client {
3211
3229
  const body = adapter.buildRequestBody(caps, r);
3212
3230
  const data = JSON.stringify(body);
3213
3231
  const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
3214
- const { result } = await this.doJSONFullRaw(
3232
+ const { result, headers } = await this.doJSONFullRaw(
3215
3233
  "POST",
3216
3234
  endpoint,
3217
3235
  data,
3218
3236
  ctl.signal,
3219
3237
  CHAT_REQUEST_TIMEOUT_MS
3220
3238
  );
3239
+ notifyGatewayRequestID(onGatewayRequestID, headers);
3221
3240
  const { parseOpenAIResponseToAnthropic: parseOpenAIResponseToAnthropic2 } = await Promise.resolve().then(() => (init_openai(), openai_exports));
3222
3241
  return parseOpenAIResponseToAnthropic2(result);
3223
3242
  } finally {
@@ -3229,10 +3248,11 @@ var Client = class _Client {
3229
3248
  * v0.5.0: 根据 adapter 路由端点
3230
3249
  *
3231
3250
  * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
3251
+ * @param onGatewayRequestID 见 {@link GatewayRequestIDCallback}
3232
3252
  */
3233
- chatStream(modelID, req, signal, onUpstreamActivity) {
3253
+ chatStream(modelID, req, signal, onUpstreamActivity, onGatewayRequestID) {
3234
3254
  return {
3235
- [Symbol.asyncIterator]: () => this.chatStreamGen(modelID, req, signal, false, onUpstreamActivity)
3255
+ [Symbol.asyncIterator]: () => this.chatStreamGen(modelID, req, signal, false, onUpstreamActivity, onGatewayRequestID)
3236
3256
  };
3237
3257
  }
3238
3258
  /**
@@ -3241,13 +3261,14 @@ var Client = class _Client {
3241
3261
  * 无 started/settled/failed 自定义事件, 无 data: [DONE], message_stop 为自然结束
3242
3262
  *
3243
3263
  * @param onUpstreamActivity 见 {@link UpstreamActivityCallback}
3264
+ * @param onGatewayRequestID 见 {@link GatewayRequestIDCallback}
3244
3265
  */
3245
- chatMessagesStream(modelID, req, signal, onUpstreamActivity) {
3266
+ chatMessagesStream(modelID, req, signal, onUpstreamActivity, onGatewayRequestID) {
3246
3267
  return {
3247
- [Symbol.asyncIterator]: () => this.chatMessagesStreamGen(modelID, req, signal, false, onUpstreamActivity)
3268
+ [Symbol.asyncIterator]: () => this.chatMessagesStreamGen(modelID, req, signal, false, onUpstreamActivity, onGatewayRequestID)
3248
3269
  };
3249
3270
  }
3250
- async *chatStreamGen(modelID, req, signal, retried, onUpstreamActivity) {
3271
+ async *chatStreamGen(modelID, req, signal, retried, onUpstreamActivity, onGatewayRequestID) {
3251
3272
  const r = { ...req, stream: true };
3252
3273
  const { body, adapter } = await this.buildChatRequest(modelID, r, signal);
3253
3274
  const token = await this.ensureToken(signal);
@@ -3280,9 +3301,10 @@ var Client = class _Client {
3280
3301
  `stream: unauthorized and refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`
3281
3302
  );
3282
3303
  }
3283
- yield* this.chatStreamGen(modelID, req, signal, true, onUpstreamActivity);
3304
+ yield* this.chatStreamGen(modelID, req, signal, true, onUpstreamActivity, onGatewayRequestID);
3284
3305
  return;
3285
3306
  }
3307
+ notifyGatewayRequestID(onGatewayRequestID, resp.headers);
3286
3308
  if (!resp.ok) {
3287
3309
  const bodyBytes = await readLimited(resp.body, maxErrorBodySize);
3288
3310
  throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
@@ -3317,7 +3339,7 @@ var Client = class _Client {
3317
3339
  }
3318
3340
  }
3319
3341
  }
3320
- async *chatMessagesStreamGen(modelID, req, signal, retried, onUpstreamActivity) {
3342
+ async *chatMessagesStreamGen(modelID, req, signal, retried, onUpstreamActivity, onGatewayRequestID) {
3321
3343
  const r = { ...req, stream: true };
3322
3344
  const { body, adapter } = await this.buildChatRequest(modelID, r, signal);
3323
3345
  const token = await this.ensureToken(signal);
@@ -3350,9 +3372,10 @@ var Client = class _Client {
3350
3372
  `messages stream: unauthorized and refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`
3351
3373
  );
3352
3374
  }
3353
- yield* this.chatMessagesStreamGen(modelID, req, signal, true, onUpstreamActivity);
3375
+ yield* this.chatMessagesStreamGen(modelID, req, signal, true, onUpstreamActivity, onGatewayRequestID);
3354
3376
  return;
3355
3377
  }
3378
+ notifyGatewayRequestID(onGatewayRequestID, resp.headers);
3356
3379
  if (!resp.ok) {
3357
3380
  const bodyBytes = await readLimited(resp.body, maxErrorBodySize);
3358
3381
  throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
@@ -7812,6 +7835,6 @@ function brandCredential(c) {
7812
7835
  return c;
7813
7836
  }
7814
7837
 
7815
- 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, ScopeAgentAccessManage, 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, agentAccessScopes, 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 };
7838
+ 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, GATEWAY_REQUEST_ID_HEADER, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OAuthTokenEndpointError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeAgentAccessManage, 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, agentAccessScopes, 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 };
7816
7839
  //# sourceMappingURL=index.mjs.map
7817
7840
  //# sourceMappingURL=index.mjs.map