@acosmi/sdk-ts 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -0
  3. package/dist/browser/index.js +3950 -0
  4. package/dist/browser/index.js.map +1 -0
  5. package/dist/index.js +3950 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/node/adapters/anthropic.cjs +257 -0
  8. package/dist/node/adapters/anthropic.cjs.map +1 -0
  9. package/dist/node/adapters/anthropic.d.cts +39 -0
  10. package/dist/node/adapters/anthropic.d.ts +39 -0
  11. package/dist/node/adapters/anthropic.js +254 -0
  12. package/dist/node/adapters/anthropic.js.map +1 -0
  13. package/dist/node/adapters/openai.cjs +472 -0
  14. package/dist/node/adapters/openai.cjs.map +1 -0
  15. package/dist/node/adapters/openai.d.cts +64 -0
  16. package/dist/node/adapters/openai.d.ts +64 -0
  17. package/dist/node/adapters/openai.js +465 -0
  18. package/dist/node/adapters/openai.js.map +1 -0
  19. package/dist/node/index-C3Z_84Bv.d.cts +992 -0
  20. package/dist/node/index-C3Z_84Bv.d.ts +992 -0
  21. package/dist/node/index-nvLKgCm9.d.cts +147 -0
  22. package/dist/node/index-nvLKgCm9.d.ts +147 -0
  23. package/dist/node/index.cjs +4024 -0
  24. package/dist/node/index.cjs.map +1 -0
  25. package/dist/node/index.d.cts +791 -0
  26. package/dist/node/index.d.ts +791 -0
  27. package/dist/node/index.js +3950 -0
  28. package/dist/node/index.js.map +1 -0
  29. package/dist/node/sanitize/index.cjs +248 -0
  30. package/dist/node/sanitize/index.cjs.map +1 -0
  31. package/dist/node/sanitize/index.d.cts +1 -0
  32. package/dist/node/sanitize/index.d.ts +1 -0
  33. package/dist/node/sanitize/index.js +217 -0
  34. package/dist/node/sanitize/index.js.map +1 -0
  35. package/package.json +84 -0
@@ -0,0 +1,992 @@
1
+ /** OAuth Authorization Server 元数据 (RFC 8414) */
2
+ interface ServerMetadata {
3
+ issuer: string;
4
+ authorization_endpoint: string;
5
+ token_endpoint: string;
6
+ revocation_endpoint: string;
7
+ registration_endpoint: string;
8
+ scopes_supported: string[];
9
+ }
10
+ /** OAuth token 响应 */
11
+ interface TokenResponse {
12
+ access_token: string;
13
+ token_type: string;
14
+ expires_in: number;
15
+ refresh_token?: string;
16
+ scope?: string;
17
+ }
18
+ /** 持久化 token 对 */
19
+ interface TokenSet {
20
+ access_token: string;
21
+ refresh_token: string;
22
+ /** ISO 8601 格式 */
23
+ expires_at: string;
24
+ scope: string;
25
+ client_id: string;
26
+ server_url: string;
27
+ }
28
+ /** token 是否已过期 (提前 30 秒视为过期) */
29
+ declare function tokenSetIsExpired(t: TokenSet): boolean;
30
+ /** 动态注册响应 */
31
+ interface ClientRegistration {
32
+ client_id: string;
33
+ client_secret?: string;
34
+ }
35
+ /** 模型能力矩阵 — 下游通过此结构决定 UI 功能开关和 Beta Header 注入 */
36
+ interface ModelCapabilities {
37
+ supports_thinking: boolean;
38
+ supports_adaptive_thinking: boolean;
39
+ /** 交错思考 (Interleaved Thinking) */
40
+ supports_isp: boolean;
41
+ supports_web_search: boolean;
42
+ supports_tool_search: boolean;
43
+ supports_structured_output: boolean;
44
+ supports_effort: boolean;
45
+ /** 模型是否支持 thinking_level="max" 强度档 (深度思考) */
46
+ supports_max_effort: boolean;
47
+ /** Opus 4.6 独有 (Speed="fast") */
48
+ supports_fast_mode: boolean;
49
+ /** Auto 模式 (模型自主选择工具/搜索策略) */
50
+ supports_auto_mode: boolean;
51
+ supports_1m_context: boolean;
52
+ supports_prompt_cache: boolean;
53
+ /** 通过 context-management beta 控制 */
54
+ supports_cache_editing: boolean;
55
+ /** Claude 4 内置 */
56
+ supports_token_efficient: boolean;
57
+ supports_redact_thinking: boolean;
58
+ max_input_tokens: number;
59
+ max_output_tokens: number;
60
+ }
61
+ /** BucketClass 字面量常量 — V30 二轮审计 D-P1-3 修复 */
62
+ declare const BucketClassCommercial = "COMMERCIAL";
63
+ declare const BucketClassGeneric = "GENERIC";
64
+ /**
65
+ * 用户在某 modelId 上的桶余额聚合视图 (V30 entitlement-listing).
66
+ *
67
+ * 多桶聚合规则 (上游 nexus-v4 计算后下发, 全部单位为 ETU):
68
+ * - quotaEtu / usedEtu / remainingEtu: 该 modelId 下用户全部 active 桶求和
69
+ * - sharedPoolEtu: 求和量中"来自通配桶"的部分 (跨模型可消耗)
70
+ * - bucketClass / expiresAt: 取最高优先级桶
71
+ * - expired: 全部桶都过期才置 true
72
+ */
73
+ interface BucketInfo {
74
+ quotaEtu: number;
75
+ usedEtu: number;
76
+ remainingEtu: number;
77
+ sharedPoolEtu?: number;
78
+ expiresAt?: string;
79
+ bucketClass: string;
80
+ expired?: boolean;
81
+ /** v0.19+ — GENERIC alive 桶 tokenRemaining 求和 ("免费余额", 真实可消费) */
82
+ freeRemainingEtu: number;
83
+ /** v0.19+ — COMMERCIAL alive 桶 tokenRemaining 求和 ("付费余额") */
84
+ paidRemainingEtu: number;
85
+ }
86
+ /** 大小写不敏感判定 — 与 buildBucketView (managed_model.go) EqualFold 语义对齐 */
87
+ declare function bucketInfoIsCommercial(b: BucketInfo | null | undefined): boolean;
88
+ /** 托管模型 */
89
+ interface ManagedModel {
90
+ id: string;
91
+ name: string;
92
+ provider: string;
93
+ modelId: string;
94
+ maxTokens: number;
95
+ isEnabled: boolean;
96
+ pricePerMTok?: number;
97
+ isDefault?: boolean;
98
+ contextWindow?: number;
99
+ capabilities: ModelCapabilities;
100
+ /**
101
+ * 上游 gateway 为此模型启用的请求格式列表
102
+ * 取值: "anthropic" | "openai"
103
+ * 空值表示上游未声明, SDK 回落 provider 硬编码分支 (向后兼容)
104
+ */
105
+ supported_formats?: string[];
106
+ /**
107
+ * 上游建议客户端优先使用的格式
108
+ * 取值: "anthropic" | "openai"; 空值等价于 supported_formats[0]
109
+ */
110
+ preferred_format?: string;
111
+ /**
112
+ * 当前用户在此模型上的桶余额聚合 (V0.18 V30 entitlement-listing).
113
+ *
114
+ * 仅当调用方为非 admin 用户 (web user / desktop OAuth) 时上游才会返回此字段:
115
+ * - admin / X-Internal-Bypass 调用 → 缺失
116
+ * - 普通用户 → 非空, 含 quota/used/remaining 求和
117
+ */
118
+ bucketInfo?: BucketInfo;
119
+ }
120
+ /** 单桶视图 — QuotaSummary.freeBuckets/paidBuckets 元素 */
121
+ interface BucketRow {
122
+ bucketId: string;
123
+ /** 精确桶为具体 modelId, 通配桶为 "*" */
124
+ modelId: string;
125
+ /** COMMERCIAL | GENERIC */
126
+ bucketClass: string;
127
+ tokenQuota: number;
128
+ tokenUsed: number;
129
+ tokenRemaining: number;
130
+ /** 永久桶为 undefined */
131
+ expiresAt?: string;
132
+ expired?: boolean;
133
+ }
134
+ declare function bucketRowIsCommercial(r: BucketRow | null | undefined): boolean;
135
+ /**
136
+ * GET /api/v4/entitlements/quota-summary 返回体, 调用 client.getQuotaSummary 获取.
137
+ *
138
+ * 设计目的: 个人中心钱包栏一次性展示"我还有多少免费 + 多少付费"+ 各自最近到期时间.
139
+ */
140
+ interface QuotaSummary {
141
+ /** GENERIC (免费/赠送) alive 桶 tokenRemaining 求和 */
142
+ freeTotalEtu: number;
143
+ /** COMMERCIAL (付费购买) alive 桶 tokenRemaining 求和 */
144
+ paidTotalEtu: number;
145
+ /** GENERIC 桶详情 (含过期, UI 列流水); 空时为空数组 */
146
+ freeBuckets: BucketRow[];
147
+ /** COMMERCIAL 桶详情 (含过期); 空时为空数组 */
148
+ paidBuckets: BucketRow[];
149
+ /** GENERIC alive 桶中最早到期; 永久桶/无 alive 时缺失 */
150
+ nextFreeExpiresAt?: string;
151
+ /** COMMERCIAL alive 桶中最早到期; 同上 */
152
+ nextPaidExpiresAt?: string;
153
+ }
154
+ /** 聊天消息 (简单文本格式, CrabClaw 使用) */
155
+ interface ChatMessage {
156
+ role: string;
157
+ content: string;
158
+ }
159
+ /** Anthropic 响应内容块 */
160
+ interface ChatContentBlock {
161
+ type: string;
162
+ text?: string;
163
+ citations?: unknown;
164
+ thinking?: string;
165
+ signature?: string;
166
+ data?: string;
167
+ id?: string;
168
+ name?: string;
169
+ /** json.RawMessage in Go */
170
+ input?: unknown;
171
+ server_name?: string;
172
+ caller?: unknown;
173
+ tool_use_id?: string;
174
+ content?: unknown;
175
+ is_error?: boolean;
176
+ }
177
+ /** Anthropic 格式 token 用量 */
178
+ interface ChatUsage {
179
+ input_tokens: number;
180
+ output_tokens: number;
181
+ cache_creation_input_tokens?: number;
182
+ cache_read_input_tokens?: number;
183
+ }
184
+ /** 三档思考级别 (v0.9.0) */
185
+ declare const ThinkingOff = "off";
186
+ declare const ThinkingHigh = "high";
187
+ declare const ThinkingMax = "max";
188
+ /** 标准思考最低 maxTokens — CrabCode 默认 MAX_OUTPUT_TOKENS_DEFAULT = 32_000 */
189
+ declare const ThinkingHighMinMaxTokens = 32000;
190
+ /** 深度思考回退 maxTokens — Opus 4.6 上限 128K */
191
+ declare const ThinkingMaxFallbackMaxTokens = 128000;
192
+ /** 控制模型思考行为 */
193
+ interface ThinkingConfig {
194
+ /** "enabled" | "disabled" | "adaptive" */
195
+ type: string;
196
+ /** 仅 type="enabled" 时 (旧模型回退) */
197
+ budget_tokens?: number;
198
+ /** 思考级别 (v0.9.0): "off" | "high" | "max" */
199
+ level?: string;
200
+ /** "none" | "summary" | "" (默认空=完整) */
201
+ display?: string;
202
+ }
203
+ /** 根据三档 level 创建配置 */
204
+ declare function newThinkingConfig(level: string): ThinkingConfig;
205
+ /** 服务端工具定义 — SDK 将工具 schema 合入 API 请求的 tools 数组 */
206
+ interface ServerTool {
207
+ type: string;
208
+ name: string;
209
+ config?: Record<string, unknown>;
210
+ }
211
+ /** Server Tool 类型常量 */
212
+ declare const ServerToolTypeWebSearch = "web_search_20250305";
213
+ /** 地理位置 */
214
+ interface GeoLoc {
215
+ /** ISO 3166-1 alpha-2 */
216
+ country: string;
217
+ city?: string;
218
+ }
219
+ /** ServerTool.config 结构 (type=web_search_20250305) */
220
+ interface WebSearchConfig {
221
+ /** 每请求最大搜索次数, 默认 8 */
222
+ max_uses?: number;
223
+ /** 域名白名单 (与 blocked_domains 互斥) */
224
+ allowed_domains?: string[];
225
+ /** 域名黑名单 (与 allowed_domains 互斥) */
226
+ blocked_domains?: string[];
227
+ user_location?: GeoLoc;
228
+ }
229
+ /** 控制推理努力级别 */
230
+ interface EffortConfig {
231
+ /** "low" | "medium" | "high" | "max" */
232
+ level: string;
233
+ }
234
+ /** 控制输出格式 (结构化输出) */
235
+ interface OutputConfig {
236
+ /** "json_schema" | "" */
237
+ format?: string;
238
+ schema?: unknown;
239
+ }
240
+ /**
241
+ * 创建搜索 Server Tool 的便捷方法
242
+ * allowed_domains 与 blocked_domains 互斥, 同时传入抛 Error
243
+ */
244
+ declare function newWebSearchTool(cfg?: WebSearchConfig | null): ServerTool;
245
+ /**
246
+ * 聊天请求
247
+ *
248
+ * 基础字段供 CrabClaw 使用, 扩展字段供 CrabCode 使用。
249
+ * 所有新增字段零值不改变行为 (向后兼容)。
250
+ *
251
+ * 注意:扩展字段(rawMessages/system/tools/...)不会被原样 JSON.stringify,
252
+ * 而由 buildRequestBody (adapter) 选择性序列化到请求体。
253
+ */
254
+ interface ChatRequest {
255
+ messages?: ChatMessage[];
256
+ stream?: boolean;
257
+ max_tokens?: number;
258
+ /** 复杂消息体 (含 content blocks / 多模态), 非 nil 时优先于 messages */
259
+ rawMessages?: unknown;
260
+ /** string 或 ContentBlock[] */
261
+ system?: unknown;
262
+ /** 标准工具定义 (Tool[]) */
263
+ tools?: unknown;
264
+ temperature?: number;
265
+ thinking?: ThinkingConfig;
266
+ metadata?: Record<string, string>;
267
+ /** 显式 beta (SDK 自动合并) */
268
+ betas?: string[];
269
+ /** 服务端工具 (buildRequestBody 合入 tools 数组) */
270
+ serverTools?: ServerTool[];
271
+ /** "" | "fast" (Fast Mode) */
272
+ speed?: string;
273
+ effort?: EffortConfig;
274
+ outputConfig?: OutputConfig;
275
+ /** 任意扩展字段 (buildRequestBody 合入请求体) */
276
+ extraBody?: Record<string, unknown>;
277
+ /**
278
+ * v0.13.0: OpenAI wire format 原生字段。AnthropicAdapter 忽略,
279
+ * OpenAIAdapter 按 OpenAI 规范序列化。
280
+ *
281
+ * 对应 OpenAI `parallel_tool_calls` 顶层字段, undefined = 不设置 (沿用上游默认 true)。
282
+ */
283
+ parallelToolCalls?: boolean;
284
+ }
285
+ /** 联网搜索结果来源 (与后端 adk/stream_helpers.go SourceItem 对齐) */
286
+ interface WebSearchSource {
287
+ title: string;
288
+ url: string;
289
+ snippet?: string;
290
+ }
291
+ /** 搜索来源事件 (从 SSE "sources" 事件解析) */
292
+ interface SourcesEvent {
293
+ sources: WebSearchSource[];
294
+ session_id?: string;
295
+ }
296
+ /**
297
+ * 从 StreamEvent 中解析搜索来源
298
+ * 返回 null 表示该事件不是 sources 类型
299
+ */
300
+ declare function parseSourcesEvent(ev: StreamEvent): SourcesEvent | null;
301
+ interface OpenAIChatResponse {
302
+ id: string;
303
+ /** "chat.completion" */
304
+ object: string;
305
+ model: string;
306
+ choices: OpenAIChatChoice[];
307
+ usage: OpenAIUsage;
308
+ }
309
+ interface OpenAIChatChoice {
310
+ index: number;
311
+ message: OpenAIChatMessage;
312
+ /** "stop", "tool_calls", "length" */
313
+ finish_reason: string;
314
+ }
315
+ interface OpenAIChatMessage {
316
+ role: string;
317
+ content: string;
318
+ tool_calls?: OpenAIToolCall[];
319
+ /** GLM/DeepSeek thinking */
320
+ reasoning_content?: string;
321
+ }
322
+ interface OpenAIToolCall {
323
+ id: string;
324
+ /** "function" */
325
+ type: string;
326
+ function: OpenAIFunctionCall;
327
+ }
328
+ interface OpenAIFunctionCall {
329
+ name: string;
330
+ arguments: string;
331
+ }
332
+ interface OpenAIUsage {
333
+ prompt_tokens: number;
334
+ completion_tokens: number;
335
+ total_tokens: number;
336
+ }
337
+ /** OpenAI SSE delta 格式 */
338
+ interface OpenAIStreamChunk {
339
+ id: string;
340
+ /** "chat.completion.chunk" */
341
+ object: string;
342
+ choices: OpenAIStreamChoice[];
343
+ usage?: OpenAIUsage;
344
+ }
345
+ interface OpenAIStreamChoice {
346
+ index: number;
347
+ delta: OpenAIStreamDelta;
348
+ finish_reason: string | null;
349
+ }
350
+ interface OpenAIStreamDelta {
351
+ role?: string;
352
+ content?: string;
353
+ reasoning_content?: string;
354
+ tool_calls?: OpenAIStreamToolCall[];
355
+ }
356
+ interface OpenAIStreamToolCall {
357
+ index: number;
358
+ id?: string;
359
+ type?: string;
360
+ function: OpenAIFunctionCall;
361
+ }
362
+ /**
363
+ * 同步聊天响应 (Anthropic format, v0.4.1)
364
+ *
365
+ * tokenRemaining / callRemaining / modelTokenRemaining* 不在 wire JSON 中, 由 client 从 Header 填充。
366
+ * 哨兵 -1 表示服务端未返回。
367
+ */
368
+ interface ChatResponse {
369
+ id: string;
370
+ type: string;
371
+ model: string;
372
+ role: string;
373
+ content: ChatContentBlock[];
374
+ stop_reason: string;
375
+ usage: ChatUsage;
376
+ /** -1 表示服务端未返回 */
377
+ tokenRemaining: number;
378
+ callRemaining: number;
379
+ modelTokenRemaining: number;
380
+ modelTokenRemainingETU: number;
381
+ }
382
+ /**
383
+ * Anthropic 内容块
384
+ * 覆盖: text / thinking / redacted_thinking / tool_use / tool_result /
385
+ * server_tool_use / mcp_tool_use / mcp_tool_result
386
+ */
387
+ interface AnthropicContentBlock {
388
+ type: string;
389
+ text?: string;
390
+ /** tool_use / server_tool_use / mcp_tool_use block ID */
391
+ id?: string;
392
+ /** tool_use function name */
393
+ name?: string;
394
+ /** tool_use arguments (json.RawMessage) */
395
+ input?: unknown;
396
+ /** thinking block content */
397
+ thinking?: string;
398
+ /** text — web_search 搜索引用 */
399
+ citations?: unknown;
400
+ /** thinking — Anthropic 签名 (后续请求必须回传) */
401
+ signature?: string;
402
+ /** redacted_thinking — base64 编码的被审查思考内容 */
403
+ data?: string;
404
+ /** server_tool_use / mcp_tool_use / mcp_tool_result — 服务端工具来源 */
405
+ server_name?: string;
406
+ /** mcp_tool_use — MCP 调用者上下文 */
407
+ caller?: unknown;
408
+ /** tool_result / mcp_tool_result — 工具执行结果 */
409
+ tool_use_id?: string;
410
+ content?: unknown;
411
+ is_error?: boolean;
412
+ }
413
+ /** Anthropic token 用量 */
414
+ interface AnthropicUsage {
415
+ input_tokens: number;
416
+ output_tokens: number;
417
+ cache_creation_input_tokens?: number;
418
+ cache_read_input_tokens?: number;
419
+ }
420
+ /**
421
+ * Anthropic 原生格式同步响应
422
+ * POST /managed-models/:id/anthropic 返回此格式 (无 response.Success 包装)
423
+ */
424
+ interface AnthropicResponse {
425
+ id: string;
426
+ /** "message" */
427
+ type: string;
428
+ /** "assistant" */
429
+ role: string;
430
+ content: AnthropicContentBlock[];
431
+ model: string;
432
+ stop_reason: string;
433
+ stop_sequence?: string | null;
434
+ usage: AnthropicUsage;
435
+ }
436
+ /** 提取所有 text 类型内容块的文本,拼接返回 */
437
+ declare function anthropicResponseTextContent(r: AnthropicResponse): string;
438
+ /** 提取所有 thinking 类型内容块的文本,拼接返回 */
439
+ declare function anthropicResponseThinkingContent(r: AnthropicResponse): string;
440
+ /** 返回所有 tool_use 类型的内容块 */
441
+ declare function anthropicResponseToolUseBlocks(r: AnthropicResponse): AnthropicContentBlock[];
442
+ /**
443
+ * SSE 流式事件
444
+ *
445
+ * v0.11.0 新增 blockIndex/blockType/ephemeral 三字段 (in-band content block 元数据)。
446
+ * 零值等价 v0.10.0 行为, 未识别的事件三字段全部零值。
447
+ */
448
+ interface StreamEvent {
449
+ event: string;
450
+ data: string;
451
+ /** 对齐 Anthropic content_block_start/delta/stop 的 index 字段 */
452
+ blockIndex?: number;
453
+ /** 由 content_block_start 解析得到, delta/stop 从 index→type 映射查出 */
454
+ blockType?: string;
455
+ /** 网关标记此 block 下一轮不应回传 */
456
+ ephemeral?: boolean;
457
+ }
458
+ /**
459
+ * 流式结算事件 (从 settled SSE 事件解析)
460
+ * 包含本次请求的 token 消耗及结算后的剩余余额
461
+ */
462
+ interface StreamSettlement {
463
+ requestId: string;
464
+ consumeStatus: string;
465
+ inputTokens: number;
466
+ outputTokens: number;
467
+ totalTokens: number;
468
+ /** 结算后剩余 token (-1 表示服务端未返回) */
469
+ tokenRemaining: number;
470
+ /** 结算后剩余调用次数 (-1 表示服务端未返回) */
471
+ callRemaining: number;
472
+ }
473
+ /** 从 settled 类型的 StreamEvent 中解析结算信息. 不是 settled 类型则返回 null. */
474
+ declare function parseSettlement(ev: StreamEvent): StreamSettlement | null;
475
+ /** 权益余额 (聚合) */
476
+ interface EntitlementBalance {
477
+ totalTokenQuota: number;
478
+ totalTokenUsed: number;
479
+ totalTokenRemaining: number;
480
+ totalCallQuota: number;
481
+ totalCallUsed: number;
482
+ totalCallRemaining: number;
483
+ activeEntitlements: number;
484
+ }
485
+ /** 单条权益明细 */
486
+ interface EntitlementItem {
487
+ id: string;
488
+ type: string;
489
+ status: string;
490
+ tokenQuota: number;
491
+ tokenUsed: number;
492
+ tokenRemaining: number;
493
+ callQuota: number;
494
+ callUsed: number;
495
+ callRemaining: number;
496
+ expiresAt?: string;
497
+ sourceId?: string;
498
+ sourceType?: string;
499
+ remark?: string;
500
+ createdAt: string;
501
+ }
502
+ /** 详细余额 (含每条权益明细) */
503
+ interface BalanceDetail {
504
+ totalTokenQuota: number;
505
+ totalTokenUsed: number;
506
+ totalTokenRemaining: number;
507
+ totalCallQuota: number;
508
+ totalCallUsed: number;
509
+ totalCallRemaining: number;
510
+ activeEntitlements: number;
511
+ entitlements: EntitlementItem[];
512
+ }
513
+ /** 核销记录 */
514
+ interface ConsumeRecord {
515
+ id: string;
516
+ entitlementId: string;
517
+ requestId: string;
518
+ modelId?: string;
519
+ tokensConsumed: number;
520
+ status: string;
521
+ createdAt: string;
522
+ }
523
+ /** 核销记录分页响应 */
524
+ interface ConsumeRecordPage {
525
+ records: ConsumeRecord[];
526
+ total: number;
527
+ page: number;
528
+ pageSize: number;
529
+ }
530
+ /**
531
+ * 单桶视图 (用户多桶 hero / 模型切换提示用)
532
+ *
533
+ * 字段名仍叫 ETU 但 T3 死代码清除后 = raw token (V29 系数管理已退役)。
534
+ */
535
+ interface ModelBucket {
536
+ bucketId: string;
537
+ entitlementId: string;
538
+ /** "*" = 通配 */
539
+ modelId: string;
540
+ /** COMMERCIAL / GENERIC */
541
+ bucketClass: string;
542
+ tokenQuota: number;
543
+ tokenUsed: number;
544
+ tokenRemaining: number;
545
+ callQuota: number;
546
+ callUsed: number;
547
+ callRemaining: number;
548
+ allowedModelsJson?: string;
549
+ }
550
+ /** GetByModel 响应; primaryBucket 在 bucketId 为空时表示无可用桶。 */
551
+ interface ModelByQuotaResponse {
552
+ modelId: string;
553
+ /** 折算后剩余 (调度判定用) */
554
+ etuRemaining: number;
555
+ /** 反系数估算的原始 token (UI 展示用) */
556
+ rawTokenRemaining: number;
557
+ hasQuota: boolean;
558
+ primaryBucket?: ModelBucket;
559
+ }
560
+ /** 单条模型系数 (SDK TTL 8s 缓存源) */
561
+ interface ModelCoefficient {
562
+ modelId: string;
563
+ tenantId: string;
564
+ inputCoef: number;
565
+ outputCoef: number;
566
+ cacheReadCoef: number;
567
+ cacheCreationCoef: number;
568
+ version: number;
569
+ effectiveAt: string;
570
+ }
571
+ /** 流量包商品。price 用 string (Go json.Number) 避免浮点精度丢失。 */
572
+ interface TokenPackage {
573
+ id: string;
574
+ name: string;
575
+ description?: string;
576
+ tokenQuota: number;
577
+ callQuota?: number;
578
+ price: string;
579
+ validDays: number;
580
+ isEnabled: boolean;
581
+ sortOrder?: number;
582
+ }
583
+ /** 订单。amount 用 string (Go json.Number) 避免精度丢失。 */
584
+ interface Order {
585
+ id: string;
586
+ packageId: string;
587
+ packageName?: string;
588
+ amount: string;
589
+ status: string;
590
+ payUrl?: string;
591
+ createdAt: string;
592
+ }
593
+ /** 订单状态 */
594
+ interface OrderStatus {
595
+ orderId: string;
596
+ status: string;
597
+ }
598
+ /** 下单请求 */
599
+ interface PayPayload {
600
+ payMethod?: string;
601
+ }
602
+ /** 钱包统计。金额使用 string (Go json.Number) 避免浮点精度丢失 (金融安全) */
603
+ interface WalletStats {
604
+ balance: string;
605
+ monthlyConsumption: string;
606
+ monthlyRecharge: string;
607
+ transactionCount: number;
608
+ }
609
+ /** 交易记录 */
610
+ interface Transaction {
611
+ id: string;
612
+ type: string;
613
+ amount: string;
614
+ remark?: string;
615
+ createdAt: string;
616
+ }
617
+ interface SkillStoreItem {
618
+ id: string;
619
+ pluginId: string;
620
+ key: string;
621
+ name: string;
622
+ description: string;
623
+ icon: string;
624
+ category: string;
625
+ inputSchema: string;
626
+ outputSchema: string;
627
+ timeout: number;
628
+ retryCount: number;
629
+ retryDelay: number;
630
+ version: string;
631
+ totalCalls: number;
632
+ avgDurationMs: number;
633
+ successRate: number;
634
+ isEnabled: boolean;
635
+ securityLevel: string;
636
+ securityScore: number;
637
+ scope: string;
638
+ status: string;
639
+ downloadCount: number;
640
+ readme: string;
641
+ tags: string[];
642
+ author: string;
643
+ publisherId: string;
644
+ isPublished: boolean;
645
+ pluginName: string;
646
+ pluginIcon: string;
647
+ updatedAt: string;
648
+ visibility?: string;
649
+ certificationStatus?: string;
650
+ source?: string;
651
+ }
652
+ /** 技能商店搜索参数 (非 wire 类型, 用于 client 方法参数) */
653
+ interface SkillStoreQuery {
654
+ category?: string;
655
+ keyword?: string;
656
+ tag?: string;
657
+ }
658
+ /** 技能统计概览 */
659
+ interface SkillSummary {
660
+ installed: number;
661
+ created: number;
662
+ total: number;
663
+ storeAvailable: number;
664
+ }
665
+ /** 技能商店分页浏览响应 */
666
+ interface SkillBrowseResponse {
667
+ items: SkillStoreItem[];
668
+ total: number;
669
+ page: number;
670
+ pageSize: number;
671
+ }
672
+ /**
673
+ * 技能商店列表项(轻量,仅含浏览所需字段)
674
+ * 配合服务端 fields=minimal 参数使用,响应体积缩减 90%+
675
+ */
676
+ interface SkillStoreListItem {
677
+ id: string;
678
+ key: string;
679
+ name: string;
680
+ description: string;
681
+ icon: string;
682
+ category: string;
683
+ version: string;
684
+ author: string;
685
+ downloadCount: number;
686
+ tags: string[];
687
+ certificationStatus?: string;
688
+ visibility?: string;
689
+ source?: string;
690
+ updatedAt: string;
691
+ }
692
+ /** 技能商店轻量浏览响应 */
693
+ interface SkillBrowseListResponse {
694
+ items: SkillStoreListItem[];
695
+ total: number;
696
+ page: number;
697
+ pageSize: number;
698
+ }
699
+ /** 技能认证状态响应 */
700
+ interface CertificationStatus {
701
+ skillId: string;
702
+ certificationStatus: string;
703
+ certifiedAt?: number;
704
+ securityLevel?: string;
705
+ securityScore: number;
706
+ report?: unknown;
707
+ }
708
+ interface GenerateSkillRequest {
709
+ purpose: string;
710
+ examples?: string[];
711
+ inputHints?: string;
712
+ outputHints?: string;
713
+ category?: string;
714
+ language?: string;
715
+ }
716
+ interface GenerateSkillResult {
717
+ skillName: string;
718
+ skillKey: string;
719
+ description: string;
720
+ skillMd: string;
721
+ inputSchema: string;
722
+ outputSchema: string;
723
+ testCases: string[];
724
+ readme: string;
725
+ category: string;
726
+ tags: string[];
727
+ timeout: number;
728
+ }
729
+ interface OptimizeSkillRequest {
730
+ skillName: string;
731
+ description?: string;
732
+ inputSchema?: string;
733
+ outputSchema?: string;
734
+ readme?: string;
735
+ aspects?: string[];
736
+ }
737
+ interface OptimizeSkillResult {
738
+ optimizedSkill: GenerateSkillResult;
739
+ changes: string[];
740
+ score: number;
741
+ }
742
+ interface ToolView {
743
+ id: string;
744
+ key: string;
745
+ name: string;
746
+ description: string;
747
+ icon: string;
748
+ category: string;
749
+ inputSchema: string;
750
+ outputSchema: string;
751
+ timeout: number;
752
+ isEnabled: boolean;
753
+ provider?: ToolProvider;
754
+ }
755
+ interface ToolProvider {
756
+ id: string;
757
+ name: string;
758
+ icon: string;
759
+ sourceType: string;
760
+ mcpEndpoint?: string;
761
+ isEnabled: boolean;
762
+ }
763
+ interface ToolListResponse {
764
+ skills: ToolView[];
765
+ total: number;
766
+ }
767
+ /** 下载限流错误 (429) */
768
+ declare class RateLimitError extends Error {
769
+ retryAfter: string;
770
+ raw: string;
771
+ constructor(message: string, retryAfter: string, raw: string);
772
+ }
773
+ /**
774
+ * API 业务层错误 (HTTP 200 但 code != 0)
775
+ * tk-dist 代理透传 yudao 响应, HTTP 状态码为 200, 业务错误在 JSON code 字段
776
+ */
777
+ declare class BusinessError extends Error {
778
+ code: number;
779
+ constructor(code: number, message: string);
780
+ }
781
+ /**
782
+ * 订单到达非成功终态 (FAILED/CANCELLED/CLOSED/EXPIRED/REFUNDED)
783
+ * waitForPayment 在订单终态为非成功时抛此错误
784
+ */
785
+ declare class OrderTerminalError extends Error {
786
+ orderId: string;
787
+ status: string;
788
+ constructor(orderId: string, status: string);
789
+ }
790
+ /**
791
+ * 模型缓存未命中且 listModels 刷新后仍未找到。
792
+ *
793
+ * 历史上 getCachedModel miss 时硬返 ManagedModel{provider:"anthropic"} 占位,
794
+ * 导致未预热场景下的 chat 请求按 AnthropicAdapter 编码, 被发到错误端点。
795
+ * v0.13.x 改为 miss → listModels 自动刷新一次; 仍 miss → 抛此错误。
796
+ */
797
+ declare class ModelNotFoundError extends Error {
798
+ modelId: string;
799
+ constructor(modelId: string);
800
+ }
801
+ /**
802
+ * 结构化 HTTP 非 2xx 错误.
803
+ *
804
+ * 用 instanceof 提取:
805
+ * try { ... } catch (e) {
806
+ * if (e instanceof HTTPError && e.statusCode === 429) { ... }
807
+ * }
808
+ */
809
+ declare class HTTPError extends Error {
810
+ statusCode: number;
811
+ /** anthropic.error.type / openai.error.type, 缺失为空 */
812
+ type: string;
813
+ /** Retry-After 头解析的秒数, 0 表示未提供或解析失败 */
814
+ retryAfter: number;
815
+ /** 原始响应体 (截断到 maxErrorBodySize) */
816
+ body: string;
817
+ constructor(statusCode: number, opts?: {
818
+ type?: string;
819
+ message?: string;
820
+ retryAfter?: number;
821
+ body?: string;
822
+ });
823
+ }
824
+ /**
825
+ * 结构化网络层错误 (传输失败, 区别于上游业务错误).
826
+ *
827
+ * 包装 fetch 抛出的错误 — 含 timeout / EOF / connection refused / DNS 失败等.
828
+ * retry policy: isTimeout / isEOF 任一为 true → 默认可重试.
829
+ */
830
+ declare class NetworkError extends Error {
831
+ /** 操作描述, e.g. "POST /v1/messages" */
832
+ op: string;
833
+ /** 请求 URL (脱敏后) */
834
+ url: string;
835
+ cause?: unknown;
836
+ timeout: boolean;
837
+ eof: boolean;
838
+ constructor(op: string, url: string, cause: unknown, opts?: {
839
+ timeout?: boolean;
840
+ eof?: boolean;
841
+ });
842
+ isTimeout(): boolean;
843
+ isEOF(): boolean;
844
+ }
845
+ /**
846
+ * 流式失败事件的结构化表示。
847
+ *
848
+ * 由 gateway 的 `managed_model_stream_failed` 事件解析得到。客户端可通过
849
+ * instanceof 提取并按 code/retryable 决策。
850
+ */
851
+ declare class StreamError extends Error {
852
+ /** 例: "empty_response" / "rate_limit" / "overloaded" / "" */
853
+ code: string;
854
+ /** 例: "provider" / "settlement" */
855
+ stage: string;
856
+ /** 用户友好提示 (中文); 历史字段, 与 rawError 区分 */
857
+ userMessage: string;
858
+ /** gateway 原始 error 字符串 */
859
+ rawError: string;
860
+ /** 客户端是否值得重试 */
861
+ retryable: boolean;
862
+ constructor(opts?: {
863
+ code?: string;
864
+ stage?: string;
865
+ message?: string;
866
+ rawError?: string;
867
+ retryable?: boolean;
868
+ });
869
+ }
870
+ /** nexus-v4 标准响应。兼容 yudao 格式 (msg) 和 nexus-v4 格式 (message) */
871
+ interface APIResponse<T> {
872
+ code: number;
873
+ message?: string;
874
+ msg?: string;
875
+ data: T;
876
+ }
877
+ /** 优先返回 message, 降级到 msg (兼容 yudao 透传) */
878
+ declare function apiResponseGetMessage<T>(r: APIResponse<T>): string;
879
+ /** 检查业务层错误码 — code != 0 时抛 BusinessError */
880
+ declare function apiResponseBusinessError<T>(r: APIResponse<T>): BusinessError | null;
881
+ /** yudao 分页响应格式 (tk-dist 代理透传) */
882
+ interface YudaoPageResult<T> {
883
+ list: T[];
884
+ total: number;
885
+ }
886
+ /** 单条通知 */
887
+ interface Notification {
888
+ id: string;
889
+ title: string;
890
+ content: string;
891
+ /** system | billing | security | task | commission | entitlement */
892
+ type: string;
893
+ isRead: boolean;
894
+ createdAt: string;
895
+ }
896
+ /** 分页通知列表 */
897
+ interface NotificationList {
898
+ list: Notification[];
899
+ unreadCount: number;
900
+ total: number;
901
+ page: number;
902
+ pageSize: number;
903
+ }
904
+ /** 未读通知计数 */
905
+ interface NotificationUnreadCount {
906
+ unreadCount: number;
907
+ }
908
+ /** 通知偏好 (按类型+渠道) */
909
+ interface NotificationPreference {
910
+ typeCode: string;
911
+ channelInApp: boolean;
912
+ channelEmail: boolean;
913
+ channelSms: boolean;
914
+ channelPush: boolean;
915
+ }
916
+ /** 推送设备注册 */
917
+ interface DeviceRegistration {
918
+ /** android | ios | harmony */
919
+ platform: string;
920
+ token: string;
921
+ appVersion: string;
922
+ }
923
+ /** 服务端推送事件 */
924
+ interface WSEvent {
925
+ type: string;
926
+ topic?: string;
927
+ /** json.RawMessage in Go */
928
+ data?: unknown;
929
+ connId?: string;
930
+ timestamp?: string;
931
+ message?: string;
932
+ }
933
+ /**
934
+ * 从 WSEvent 中解析通知
935
+ * 返回 null 表示该事件不是系统通知
936
+ */
937
+ declare function parseNotificationEvent(ev: WSEvent): Notification | null;
938
+
939
+ /** 标识请求格式 */
940
+ declare enum ProviderFormat {
941
+ /** Anthropic 原生格式 */
942
+ Anthropic = 0,
943
+ /** OpenAI 兼容格式 */
944
+ OpenAI = 1
945
+ }
946
+ /** 将 ChatRequest 转换为特定格式的 adapter 接口 */
947
+ interface ProviderAdapter {
948
+ /** 此 adapter 使用的请求格式 */
949
+ format(): ProviderFormat;
950
+ /**
951
+ * API 路径后缀
952
+ * Anthropic: "/anthropic", OpenAI: "/chat"
953
+ */
954
+ endpointSuffix(): string;
955
+ /**
956
+ * 将 ChatRequest 转换为 HTTP body (object → JSON.stringify)
957
+ * caps 用于条件化字段注入 (如 betas)
958
+ */
959
+ buildRequestBody(caps: ModelCapabilities, req: ChatRequest): Record<string, unknown>;
960
+ /** 解析同步响应 body 为 ChatResponse */
961
+ parseResponse(body: Uint8Array | string): ChatResponse;
962
+ /**
963
+ * 解析一行 SSE data 为 StreamEvent
964
+ * 返回 { event, done }; done=true 表示流结束 ([DONE] 或 message_stop)
965
+ */
966
+ parseStreamLine(eventType: string, data: string): {
967
+ event: StreamEvent;
968
+ done: boolean;
969
+ };
970
+ }
971
+
972
+ /**
973
+ * 根据 provider 返回对应的 adapter (v0.5.0 遗留 API, 向后兼容)
974
+ * 新代码应使用 getAdapterForModel
975
+ */
976
+ declare function getAdapter(provider: string): ProviderAdapter;
977
+ /**
978
+ * 按 ManagedModel 的 preferred_format / supported_formats 选择 adapter
979
+ *
980
+ * 决策顺序:
981
+ * 1. preferred_format 非空 → 按其值返回 (anthropic | openai)
982
+ * 2. supported_formats 含 "anthropic" → AnthropicAdapter
983
+ * 3. supported_formats 含 "openai" → OpenAIAdapter
984
+ * 4. 两字段均空 (旧上游) → 回落 provider 名硬编码 (原 getAdapter 行为)
985
+ *
986
+ * 这使得 dashscope / zhipu / deepseek 等 provider 的模型如果上游启用了
987
+ * Anthropic 兼容端点, 也能走 /anthropic 路径, 不再被 provider 字符串硬编码到 /chat
988
+ * 导致 tool_reference 400.
989
+ */
990
+ declare function getAdapterForModel(m: ManagedModel): ProviderAdapter;
991
+
992
+ export { type ConsumeRecord as $, type AnthropicResponse as A, type BalanceDetail as B, type ClientRegistration as C, type DeviceRegistration as D, type EntitlementBalance as E, type NotificationPreference as F, type GenerateSkillRequest as G, type WSEvent as H, type APIResponse as I, type AnthropicContentBlock as J, type AnthropicUsage as K, BucketClassCommercial as L, type ModelCapabilities as M, type NotificationList as N, type Order as O, type ProviderAdapter as P, type QuotaSummary as Q, BucketClassGeneric as R, type ServerMetadata as S, type TokenResponse as T, type BucketInfo as U, type BucketRow as V, type WalletStats as W, BusinessError as X, type ChatContentBlock as Y, type ChatMessage as Z, type ChatUsage as _, type TokenSet as a, type EffortConfig as a0, type GeoLoc as a1, HTTPError as a2, ModelNotFoundError as a3, NetworkError as a4, type Notification as a5, type NotificationUnreadCount as a6, type OpenAIChatChoice as a7, type OpenAIChatMessage as a8, type OpenAIChatResponse as a9, anthropicResponseTextContent as aA, anthropicResponseThinkingContent as aB, anthropicResponseToolUseBlocks as aC, apiResponseBusinessError as aD, apiResponseGetMessage as aE, bucketInfoIsCommercial as aF, bucketRowIsCommercial as aG, getAdapter as aH, getAdapterForModel as aI, newThinkingConfig as aJ, newWebSearchTool as aK, parseNotificationEvent as aL, parseSettlement as aM, parseSourcesEvent as aN, tokenSetIsExpired as aO, type OpenAIFunctionCall as aa, type OpenAIStreamChoice as ab, type OpenAIStreamChunk as ac, type OpenAIStreamDelta as ad, type OpenAIStreamToolCall as ae, type OpenAIToolCall as af, type OpenAIUsage as ag, OrderTerminalError as ah, type OutputConfig as ai, ProviderFormat as aj, RateLimitError as ak, type ServerTool as al, ServerToolTypeWebSearch as am, type SkillStoreListItem as an, StreamError as ao, type ThinkingConfig as ap, ThinkingHigh as aq, ThinkingHighMinMaxTokens as ar, ThinkingMax as as, ThinkingMaxFallbackMaxTokens as at, ThinkingOff as au, type ToolListResponse as av, type ToolProvider as aw, type WebSearchConfig as ax, type WebSearchSource as ay, type YudaoPageResult as az, type ChatRequest as b, type ManagedModel as c, type ModelCoefficient as d, type ChatResponse as e, type StreamEvent as f, type SourcesEvent as g, type StreamSettlement as h, type EntitlementItem as i, type ConsumeRecordPage as j, type ModelByQuotaResponse as k, type ModelBucket as l, type TokenPackage as m, type PayPayload as n, type OrderStatus as o, type Transaction as p, type SkillStoreQuery as q, type SkillStoreItem as r, type SkillBrowseResponse as s, type SkillBrowseListResponse as t, type SkillSummary as u, type CertificationStatus as v, type GenerateSkillResult as w, type OptimizeSkillRequest as x, type OptimizeSkillResult as y, type ToolView as z };