@acosmi/sdk-ts 1.4.1 → 1.5.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/CHANGELOG.md +160 -0
  2. package/README.md +99 -5
  3. package/dist/browser/index.mjs +2432 -1891
  4. package/dist/browser/index.mjs.map +1 -1
  5. package/dist/index.mjs +2432 -1891
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/node/adapters/anthropic.cjs +6 -4
  8. package/dist/node/adapters/anthropic.cjs.map +1 -1
  9. package/dist/node/adapters/anthropic.d.cts +1 -1
  10. package/dist/node/adapters/anthropic.d.ts +1 -1
  11. package/dist/node/adapters/anthropic.mjs +6 -4
  12. package/dist/node/adapters/anthropic.mjs.map +1 -1
  13. package/dist/node/adapters/openai.cjs +4 -2
  14. package/dist/node/adapters/openai.cjs.map +1 -1
  15. package/dist/node/adapters/openai.d.cts +2 -64
  16. package/dist/node/adapters/openai.d.ts +2 -64
  17. package/dist/node/adapters/openai.mjs +4 -2
  18. package/dist/node/adapters/openai.mjs.map +1 -1
  19. package/dist/node/index-DEA6LXw6.d.cts +409 -0
  20. package/dist/node/index-DEA6LXw6.d.ts +409 -0
  21. package/dist/node/index.cjs +2438 -1890
  22. package/dist/node/index.cjs.map +1 -1
  23. package/dist/node/index.d.cts +2846 -1225
  24. package/dist/node/index.d.ts +2846 -1225
  25. package/dist/node/index.mjs +2432 -1891
  26. package/dist/node/index.mjs.map +1 -1
  27. package/dist/node/openai-BDodfhsG.d.cts +125 -0
  28. package/dist/node/openai-vfUUgdvL.d.ts +125 -0
  29. package/docs/compliance.md +452 -2
  30. package/examples/agent-runs-stream.ts +118 -0
  31. package/examples/auth-oauth-flow.ts +97 -0
  32. package/examples/core-chat.ts +85 -0
  33. package/package.json +5 -2
  34. package/dist/node/index-CbG9NqE-.d.cts +0 -1027
  35. package/dist/node/index-CbG9NqE-.d.ts +0 -1027
@@ -1,52 +1,188 @@
1
- import { M as ManagedModel, I as InputModality, S as ServerMetadata, T as TokenSet, a as TokenResponse, C as ClientRegistration, B as BusinessError, b as ModelCoefficient, Q as QuotaSummary, c as ModelCapabilities, d as ChatRequest, P as ProviderAdapter, e as ChatResponse, A as AnthropicResponse, f as StreamEvent, g as SourcesEvent, h as StreamSettlement, E as EntitlementBalance, i as BalanceDetail, j as EntitlementItem, k as ConsumeRecordPage, l as ModelByQuotaResponse, m as ModelBucket, n as TokenPackage, o as PayPayload, O as Order, p as OrderStatus, W as WalletStats, q as Transaction, r as SkillStoreQuery, s as SkillStoreItem, t as SkillBrowseResponse, u as SkillBrowseListResponse, v as SkillSummary, w as CertificationStatus, G as GenerateSkillRequest, x as GenerateSkillResult, y as OptimizeSkillRequest, z as OptimizeSkillResult, D as ToolView, N as NotificationList, F as DeviceRegistration, H as NotificationPreference, J as WSEvent } from './index-CbG9NqE-.js';
2
- export { K as APIResponse, L as AnthropicContentBlock, R as AnthropicUsage, U as BucketClassCommercial, V as BucketClassGeneric, X as BucketInfo, Y as BucketRow, Z as ChatContentBlock, _ as ChatMessage, $ as ChatUsage, a0 as ConsumeRecord, a1 as EffortConfig, a2 as GeoLoc, a3 as HTTPError, a4 as ModelNotFoundError, a5 as NetworkError, a6 as Notification, a7 as NotificationUnreadCount, a8 as OpenAIChatChoice, a9 as OpenAIChatMessage, aa as OpenAIChatResponse, ab as OpenAIFunctionCall, ac as OpenAIStreamChoice, ad as OpenAIStreamChunk, ae as OpenAIStreamDelta, af as OpenAIStreamToolCall, ag as OpenAIToolCall, ah as OpenAIUsage, ai as OrderTerminalError, aj as OutputConfig, ak as ProviderFormat, al as RateLimitError, am as ServerTool, an as ServerToolTypeWebSearch, ao as SkillStoreListItem, ap as StreamError, aq as ThinkingConfig, ar as ThinkingHigh, as as ThinkingHighMinMaxTokens, at as ThinkingMax, au as ThinkingMaxFallbackMaxTokens, av as ThinkingOff, aw as ToolListResponse, ax as ToolProvider, ay as WebSearchConfig, az as WebSearchSource, aA as YudaoPageResult, aB as anthropicResponseTextContent, aC as anthropicResponseThinkingContent, aD as anthropicResponseToolUseBlocks, aE as apiResponseBusinessError, aF as apiResponseGetMessage, aG as bucketInfoIsCommercial, aH as bucketRowIsCommercial, aI as getAdapter, aJ as getAdapterForModel, aK as newThinkingConfig, aL as newWebSearchTool, aM as parseNotificationEvent, aN as parseSettlement, aO as parseSourcesEvent, aP as tokenSetIsExpired } from './index-CbG9NqE-.js';
1
+ import { A as AnthropicResponse } from './openai-vfUUgdvL.js';
2
+ export { a as AnthropicContentBlock, b as AnthropicUsage, O as OpenAIAdapter, c as anthropicResponseTextContent, d as anthropicResponseThinkingContent, e as anthropicResponseToolUseBlocks } from './openai-vfUUgdvL.js';
3
+ import { M as ManagedModel, Q as QuotaSummary, a as ModelCapabilities, C as ChatRequest, P as ProviderAdapter, b as ChatResponse, S as StreamEvent, c as SourcesEvent, d as StreamSettlement, I as InputModality } from './index-DEA6LXw6.js';
4
+ export { B as BucketClassCommercial, e as BucketClassGeneric, f as BucketInfo, g as BucketRow, h as ChatContentBlock, i as ChatMessage, j as ChatUsage, E as EffortConfig, G as GeoLoc, O as OutputConfig, k as ProviderFormat, l as ServerTool, m as ServerToolTypeWebSearch, T as ThinkingConfig, n as ThinkingHigh, o as ThinkingHighMinMaxTokens, p as ThinkingMax, q as ThinkingMaxFallbackMaxTokens, r as ThinkingOff, W as WebSearchConfig, s as WebSearchSource, t as bucketInfoIsCommercial, u as bucketRowIsCommercial, v as getAdapter, w as getAdapterForModel, x as newThinkingConfig, y as newWebSearchTool, z as parseSettlement, A as parseSourcesEvent } from './index-DEA6LXw6.js';
3
5
  import { M as MinimalSanitizeConfig } from './index-nvLKgCm9.js';
4
6
  export { i as sanitize } from './index-nvLKgCm9.js';
5
7
  export { AnthropicAdapter } from './adapters/anthropic.js';
6
- export { OpenAIAdapter } from './adapters/openai.js';
7
8
 
9
+ /** 权益余额 (聚合) */
10
+ interface EntitlementBalance {
11
+ totalTokenQuota: number;
12
+ totalTokenUsed: number;
13
+ totalTokenRemaining: number;
14
+ totalCallQuota: number;
15
+ totalCallUsed: number;
16
+ totalCallRemaining: number;
17
+ activeEntitlements: number;
18
+ }
19
+ /** 单条权益明细 */
20
+ interface EntitlementItem {
21
+ id: string;
22
+ type: string;
23
+ status: string;
24
+ tokenQuota: number;
25
+ tokenUsed: number;
26
+ tokenRemaining: number;
27
+ callQuota: number;
28
+ callUsed: number;
29
+ callRemaining: number;
30
+ expiresAt?: string;
31
+ sourceId?: string;
32
+ sourceType?: string;
33
+ remark?: string;
34
+ createdAt: string;
35
+ }
36
+ /** 详细余额 (含每条权益明细) */
37
+ interface BalanceDetail {
38
+ totalTokenQuota: number;
39
+ totalTokenUsed: number;
40
+ totalTokenRemaining: number;
41
+ totalCallQuota: number;
42
+ totalCallUsed: number;
43
+ totalCallRemaining: number;
44
+ activeEntitlements: number;
45
+ entitlements: EntitlementItem[];
46
+ }
47
+ /** 核销记录 */
48
+ interface ConsumeRecord {
49
+ id: string;
50
+ entitlementId: string;
51
+ requestId: string;
52
+ modelId?: string;
53
+ tokensConsumed: number;
54
+ status: string;
55
+ createdAt: string;
56
+ }
57
+ /** 核销记录分页响应 */
58
+ interface ConsumeRecordPage {
59
+ records: ConsumeRecord[];
60
+ total: number;
61
+ page: number;
62
+ pageSize: number;
63
+ }
8
64
  /**
9
- * 判断 ManagedModel 是否声明支持指定输入模态.
10
- *
11
- * 语义:
12
- * - model 为 null/undefined → false
13
- * - model.inputModalities 缺失或非数组 → false (保守, 未声明不当支持)
14
- * - 大小写敏感 (上游契约即小写 'text' | 'image')
15
- */
16
- declare function modelSupportsInputModality(model: ManagedModel | null | undefined, modality: InputModality): boolean;
17
- /** 等价 modelSupportsInputModality(model, 'image') — 调用方常见快捷判定. */
18
- declare function modelSupportsImageInput(model: ManagedModel | null | undefined): boolean;
19
- /**
20
- * 在 catalog 中按 catalog 顺序查找首个支持指定模态的模型.
21
- *
22
- * 选择规则:
23
- * 1. isEnabled !== false (默认开, 显式 false 才剔除)
24
- * 2. inputModalities 包含指定模态
25
- * 3. 命中后按 catalog 顺序返回第一个; 未命中返 null
26
- *
27
- * 注意: 该 helper 不读 isDefault, 调用方需要 "默认优先" 请用
28
- * findDesktopVisualUnderstandingModel 或自行排序.
29
- */
30
- declare function findFirstModelByInputModality(models: ManagedModel[], modality: InputModality): ManagedModel | null;
31
- /**
32
- * 在 catalog 中选出最适合做 "桌面视觉理解 sidecar" 的模型.
33
- *
34
- * 设计目的: CrabCode desktop automation 链路里, 主模型不一定多模态;
35
- * 截图先送 sidecar 解析成结构化 UI 描述, 再喂主模型. 这里选 sidecar 模型
36
- * 严格走运营标注的 supports_desktop_visual_understanding capability, 不靠
37
- * 模型名猜.
38
- *
39
- * 选择规则 (按用户指定顺序):
40
- * 1. isEnabled !== false
41
- * 2. capabilities.supports_desktop_visual_understanding === true
42
- * 3. inputModalities 包含 'image' (必须真能吃图)
43
- * 4. 命中集合中优先 isDefault === true; 否则返回 catalog 顺序第一个
65
+ * 单桶视图 (用户多桶 hero / 模型切换提示用)
44
66
  *
45
- * 全部不满足返 null. 调用方收到 null 应:
46
- * - 提示用户在管理后台/网关侧开启桌面视觉 sidecar 模型, 或
47
- * - 降级停掉依赖截图的工作流, 而不是硬选一个非视觉模型送图.
67
+ * 字段名仍叫 ETU T3 死代码清除后 = raw token (V29 系数管理已退役)。
48
68
  */
49
- declare function findDesktopVisualUnderstandingModel(models: ManagedModel[]): ManagedModel | null;
69
+ interface ModelBucket {
70
+ bucketId: string;
71
+ entitlementId: string;
72
+ /** "*" = 通配 */
73
+ modelId: string;
74
+ /** COMMERCIAL / GENERIC */
75
+ bucketClass: string;
76
+ tokenQuota: number;
77
+ tokenUsed: number;
78
+ tokenRemaining: number;
79
+ callQuota: number;
80
+ callUsed: number;
81
+ callRemaining: number;
82
+ allowedModelsJson?: string;
83
+ }
84
+ /** GetByModel 响应; primaryBucket 在 bucketId 为空时表示无可用桶。 */
85
+ interface ModelByQuotaResponse {
86
+ modelId: string;
87
+ /** 折算后剩余 (调度判定用) */
88
+ etuRemaining: number;
89
+ /** 反系数估算的原始 token (UI 展示用) */
90
+ rawTokenRemaining: number;
91
+ hasQuota: boolean;
92
+ primaryBucket?: ModelBucket;
93
+ }
94
+ /** 单条模型系数 (SDK TTL 8s 缓存源) */
95
+ interface ModelCoefficient {
96
+ modelId: string;
97
+ tenantId: string;
98
+ inputCoef: number;
99
+ outputCoef: number;
100
+ cacheReadCoef: number;
101
+ cacheCreationCoef: number;
102
+ version: number;
103
+ effectiveAt: string;
104
+ }
105
+ /** 流量包商品。price 用 string (Go json.Number) 避免浮点精度丢失。 */
106
+ interface TokenPackage {
107
+ id: string;
108
+ name: string;
109
+ description?: string;
110
+ tokenQuota: number;
111
+ callQuota?: number;
112
+ price: string;
113
+ validDays: number;
114
+ isEnabled: boolean;
115
+ sortOrder?: number;
116
+ }
117
+ /** 订单。amount 用 string (Go json.Number) 避免精度丢失。 */
118
+ interface Order {
119
+ id: string;
120
+ packageId: string;
121
+ packageName?: string;
122
+ amount: string;
123
+ status: string;
124
+ payUrl?: string;
125
+ createdAt: string;
126
+ }
127
+ /** 订单状态 */
128
+ interface OrderStatus {
129
+ orderId: string;
130
+ status: string;
131
+ }
132
+ /** 下单请求 */
133
+ interface PayPayload {
134
+ payMethod?: string;
135
+ }
136
+ /** 钱包统计。金额使用 string (Go json.Number) 避免浮点精度丢失 (金融安全) */
137
+ interface WalletStats {
138
+ balance: string;
139
+ monthlyConsumption: string;
140
+ monthlyRecharge: string;
141
+ transactionCount: number;
142
+ }
143
+ /** 交易记录 */
144
+ interface Transaction {
145
+ id: string;
146
+ type: string;
147
+ amount: string;
148
+ remark?: string;
149
+ createdAt: string;
150
+ }
151
+
152
+ /** OAuth Authorization Server 元数据 (RFC 8414) */
153
+ interface ServerMetadata {
154
+ issuer: string;
155
+ authorization_endpoint: string;
156
+ token_endpoint: string;
157
+ revocation_endpoint: string;
158
+ registration_endpoint: string;
159
+ scopes_supported: string[];
160
+ }
161
+ /** OAuth token 响应 */
162
+ interface TokenResponse {
163
+ access_token: string;
164
+ token_type: string;
165
+ expires_in: number;
166
+ refresh_token?: string;
167
+ scope?: string;
168
+ }
169
+ /** 持久化 token 对 */
170
+ interface TokenSet {
171
+ access_token: string;
172
+ refresh_token: string;
173
+ /** ISO 8601 格式 */
174
+ expires_at: string;
175
+ scope: string;
176
+ client_id: string;
177
+ server_url: string;
178
+ }
179
+ /** token 是否已过期 (提前 30 秒视为过期) */
180
+ declare function tokenSetIsExpired(t: TokenSet): boolean;
181
+ /** 动态注册响应 */
182
+ interface ClientRegistration {
183
+ client_id: string;
184
+ client_secret?: string;
185
+ }
50
186
 
51
187
  /** OAuth metadata profile — 决定 well-known 端点的路径后缀 */
52
188
  type OAuthMetadataProfile = 'web' | 'desktop';
@@ -245,694 +381,311 @@ declare function revokeToken(meta: ServerMetadata, token: string, signal?: Abort
245
381
  */
246
382
  declare function newTokenSet(resp: TokenResponse, clientID: string, serverURL: string): TokenSet;
247
383
 
248
- declare const ScopeAI = "ai";
249
- declare const ScopeSkills = "skills";
250
- declare const ScopeAccount = "account";
251
- /** @deprecated 旧细粒度 scope, 保留向后兼容, 新代码请用分组 scope */
252
- declare const ScopeModels = "models";
253
- /** @deprecated */
254
- declare const ScopeModelsChat = "models:chat";
255
- /** @deprecated */
256
- declare const ScopeEntitlements = "entitlements";
257
- /** @deprecated */
258
- declare const ScopeTokenPackages = "token-packages";
259
- /** @deprecated */
260
- declare const ScopeSkillStore = "skill_store";
261
- /** @deprecated */
262
- declare const ScopeTools = "tools";
263
- /** @deprecated */
264
- declare const ScopeToolsExecute = "tools:execute";
265
- /** @deprecated */
266
- declare const ScopeWallet = "wallet";
267
- /** @deprecated */
268
- declare const ScopeWalletReadonly = "wallet:readonly";
269
- /** @deprecated */
270
- declare const ScopeProfile = "profile";
271
- declare const ScopeComplianceEvidenceRead = "compliance:evidence:read";
272
- declare const ScopeComplianceEvidenceWrite = "compliance:evidence:write";
273
- declare const ScopeComplianceTimestampIssue = "compliance:timestamp:issue";
274
- declare const ScopeComplianceTimestampVerify = "compliance:timestamp:verify";
275
- declare const ScopeComplianceContractSigningRead = "compliance:contract_signing:read";
276
- declare const ScopeComplianceContractSigningWrite = "compliance:contract_signing:write";
277
- declare const ScopeComplianceSealManage = "compliance:seal:manage";
278
- declare const ScopeComplianceSealApprovalRequest = "compliance:seal_approval:request";
279
- declare const ScopeComplianceSealApprovalApprove = "compliance:seal_approval:approve";
280
- declare const ScopeComplianceSealUseExecute = "compliance:seal_use:execute";
281
- declare const ScopeComplianceReportsRead = "compliance:reports:read";
282
- declare const ScopeComplianceReportsWrite = "compliance:reports:write";
283
- declare const ScopeComplianceReportsPublish = "compliance:reports:publish";
284
- /** 类型联合:合规域细粒度 scope。Java compliance verifier 只按细粒度匹配, 不做分组展开。 */
285
- type ComplianceScope = typeof ScopeComplianceEvidenceRead | typeof ScopeComplianceEvidenceWrite | typeof ScopeComplianceTimestampIssue | typeof ScopeComplianceTimestampVerify | typeof ScopeComplianceContractSigningRead | typeof ScopeComplianceContractSigningWrite | typeof ScopeComplianceSealManage | typeof ScopeComplianceSealApprovalRequest | typeof ScopeComplianceSealApprovalApprove | typeof ScopeComplianceSealUseExecute | typeof ScopeComplianceReportsRead | typeof ScopeComplianceReportsWrite | typeof ScopeComplianceReportsPublish;
286
- /** 全部分组 scope (推荐) */
287
- declare function allScopes(): string[];
288
- /** 全部合规域 scope。OAuth 申请合规权限时使用; 谨慎一次性申请全部, 推荐按业务最小集合申请。 */
289
- declare function complianceScopes(): ComplianceScope[];
290
- /** 模型服务相关 scope */
291
- declare function modelScopes(): string[];
292
- /** 商城/钱包 scope */
293
- declare function commerceScopes(): string[];
294
- /** 技能/工具 scope */
295
- declare function skillScopes(): string[];
296
-
297
384
  /**
298
- * Compliance envelope 稳定业务状态。
385
+ * Token 持久化接口
386
+ * 桌面智能体可自行实现 (如 macOS Keychain / Windows Credential Manager)
299
387
  *
300
- * 字面量与 Java {@code EnvelopeStatusEnum} 的 `name()` 一致(这是 enum,是 wire 上的实际
301
- * 字符串);前端按这些字符串分支展示文案。
388
+ * 跨端约定:
389
+ * - Save: 写入持久化, 失败抛 Error
390
+ * - Load: 读取, 不存在返回 null (与 Go IsNotExist 行为一致)
391
+ * - Clear: 删除, 不存在不抛错 (Logout 后 Clear 不应报错, [RC-11])
392
+ * - withLock (v1.0.2 新增, 可选): 跨进程临界区. Client 在 refresh token rotation
393
+ * 场景下用此包裹 "load → check → refresh → save" 整段, 防多进程共享同一 store
394
+ * (典型: FileTokenStore 默认 ~/.acosmi/tokens.json) 撞 HTTP 400 refresh token
395
+ * not found. 不实现时 Client 自动回退到仅进程内串行 (LocalStorage / InMemory
396
+ * 单进程语义无需此方法).
302
397
  */
303
- type ComplianceEnvelopeStatus = 'DRAFT' | 'CONTRACT_READY' | 'APPROVED' | 'SIGN_PENDING' | 'PENDING_EVIDENCE' | 'PENDING_RECONCILIATION' | 'SUCCESS' | 'FAILED' | 'CANCELED';
304
- /** Compliance 用印审批稳定状态。 */
305
- type ComplianceSealApprovalStatus = 'DRAFT' | 'SUBMITTED' | 'APPROVED' | 'REJECTED' | 'CANCELED' | 'USED' | 'EXPIRED';
306
- /** Provider 业务状态(前端可见的脱敏视图,不暴露下游内部字段)。 */
307
- type ComplianceProviderStatus = 'pending' | 'success' | 'failed' | 'unknown' | 'retrying';
398
+ interface TokenStore {
399
+ save(tokens: TokenSet): Promise<void>;
400
+ load(): Promise<TokenSet | null>;
401
+ clear(): Promise<void>;
402
+ withLock?<T>(fn: () => Promise<T>): Promise<T>;
403
+ }
308
404
  /**
309
- * 计费 / 履约的对外稳定状态视图。distribution compliance-billing 内部 API
310
- * (quote/reserve/commit/cancel/reconcile) 不暴露给前端 — 前端只能看见这 4 个语义。
405
+ * 基于文件的 token 存储 (开发/测试用)
406
+ * 生产环境建议替换为系统钥匙串实现
407
+ *
408
+ * 默认路径: ~/.acosmi/tokens.json
409
+ *
410
+ * 浏览器环境调用 new FileTokenStore() 会抛错 — 浏览器请用 LocalStorageTokenStore 或 InMemoryTokenStore.
311
411
  */
312
- type ComplianceBillingDisplayStatus = 'reserved' | 'committed' | 'canceled' | 'pending_reconciliation';
313
- /** 高风险动作 step-up — 重新做 OAuth introspection 或重新登录,提升 token 等级后再尝试。 */
314
- declare const ErrComplianceStepUpRequired = "COMPLIANCE_STEP_UP_REQUIRED";
315
- /** envelope 闸门关闭 — 审批 gate 等条件未同时就绪,前端展示"功能开放中"。 */
316
- declare const ErrEnvelopeGateClosed = "ENVELOPE_GATE_CLOSED";
317
- /** 履约 provider 未配置 — 受控环境材料缺失时业务路径会一致拒绝,不要前端重试。 */
318
- declare const ErrProviderNotConfigured = "PROVIDER_NOT_CONFIGURED";
319
- /** Provider 返回 unknown / retrying — 客户必须等待对账,前端展示"处理中(人工核对)"。 */
320
- declare const ErrProviderUnknownNoRetry = "PROVIDER_REQUEST_UNKNOWN_NO_RETRY";
321
- /** callback 不能直接确认扣费 — 后端守门,前端无需处理,记录到审计日志展示即可。 */
322
- declare const ErrBillingCallbackCannotCommit = "BILLING_CALLBACK_CANNOT_COMMIT";
323
- /** provider 成功但本地未验证通过,不允许扣费。 */
324
- declare const ErrBillingCommitRequiresLocalVerify = "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY";
325
- /** distribution compliance-billing 必须 S2S — 前端误调用时拿到该错误码,禁止 retry。 */
326
- declare const ErrBillingS2sForbidden = "BILLING_S2S_FORBIDDEN";
327
- /** 审批 gate 各类失败语义(前端展示"审批中 / 审批已用 / 审批失效")。 */
328
- declare const ErrSealApprovalNotApproved = "SEAL_APPROVAL_STATE_NOT_APPROVED";
329
- declare const ErrSealApprovalExpired = "SEAL_APPROVAL_EXPIRED";
330
- declare const ErrSealApprovalNonceUsed = "SEAL_APPROVAL_NONCE_USED";
331
- declare const ErrSealApprovalContractHashMismatch = "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH";
332
- declare const ErrSealApprovalSealMismatch = "SEAL_APPROVAL_SEAL_MISMATCH";
333
- declare const ErrSealApprovalLocationMismatch = "SEAL_APPROVAL_LOCATION_MISMATCH";
334
- declare const ErrSealApprovalTransactorMismatch = "SEAL_APPROVAL_TRANSACTOR_MISMATCH";
335
- /** 用印重复消费防护 前端遇到该错误必须刷新审批单状态,不允许"换一次 nonce 再试"。 */
336
- declare const ErrSealUseAlreadyConsumed = "SEAL_USE_ALREADY_CONSUMED";
337
- /** 该错误码联合用于前端选择性展示文案;非穷举式 enum,后端保留新增空间。 */
338
- type ComplianceClientErrorCode = typeof ErrComplianceStepUpRequired | typeof ErrEnvelopeGateClosed | typeof ErrProviderNotConfigured | typeof ErrProviderUnknownNoRetry | typeof ErrBillingCallbackCannotCommit | typeof ErrBillingCommitRequiresLocalVerify | typeof ErrBillingS2sForbidden | typeof ErrSealApprovalNotApproved | typeof ErrSealApprovalExpired | typeof ErrSealApprovalNonceUsed | typeof ErrSealApprovalContractHashMismatch | typeof ErrSealApprovalSealMismatch | typeof ErrSealApprovalLocationMismatch | typeof ErrSealApprovalTransactorMismatch | typeof ErrSealUseAlreadyConsumed;
412
+ /** 跨进程文件锁配置 (v1.0.2). 公开常量是为了让 caller / 测试可观察, 不建议生产代码改. */
413
+ declare const fileLockDefaults: {
414
+ /** 获取锁的超时上限 (毫秒). refresh 流程含网络 < 30s, 30s 已远超正常完成时间. */
415
+ readonly acquireTimeoutMs: 30000;
416
+ /** 旧锁判定阈值 (毫秒). 锁文件 mtime 早于此值视为 stale 进程崩溃残留, 自动 break. */
417
+ readonly staleMs: 60000;
418
+ /** 重试间隔基数 (毫秒). 真实间隔 = base + random(0, jitter). */
419
+ readonly retryBaseMs: 30;
420
+ readonly retryJitterMs: 70;
421
+ };
422
+ declare class FileTokenStore implements TokenStore {
423
+ private path;
424
+ /** 进程内串行化 (Promise chain) — 与跨进程 flock 配合, 避免单进程内并发持锁产生死锁式互等. */
425
+ private chain;
426
+ constructor(path?: string);
427
+ private resolvePath;
428
+ /** 进程内串行 (维持 v1.0.1 单进程语义). flock 之外另一层防御: 如果用户自己就是单进程
429
+ * 并发场景, 不必每次都进 flock 旁路文件 IO. */
430
+ private withChain;
431
+ /**
432
+ * 跨进程临界区. sidecar `<path>.lock` 文件 + O_EXCL 创建语义实现互斥:
433
+ * - 创建成功 = 持有锁; 写入 pid+timestamp 便于诊断
434
+ * - 创建失败 (EEXIST) = 别的进程持锁, backoff 重试
435
+ * - 锁文件 mtime > staleMs = 进程崩溃残留, unlink 后重试
436
+ * - acquireTimeoutMs 超时 = 抛错 (caller 应作为 transient error 处理, 上层 retry)
437
+ *
438
+ * 注意: O_EXCL NFS 上不保证原子; FileTokenStore 适用于本地文件系统 (典型用户家目录).
439
+ * 真要跨机共享 token, 应实现自定义 Keychain / 数据库 store, 不要用 FileTokenStore.
440
+ */
441
+ withLock<T>(fn: () => Promise<T>): Promise<T>;
442
+ /**
443
+ * 写入 token. 流程:
444
+ * 1. mkdir -p (默认路径目录)
445
+ * 2. 写入 `<path>.tmp.<pid>`
446
+ * 3. fsync 后 rename 到正式路径 (POSIX 上 rename(2) 同分区原子, Windows 上 ReplaceFile)
447
+ *
448
+ * 选择 atomic rename 而非直接 writeFile: 多进程并发或本进程崩溃时, 读端永远看到的是
449
+ * 完整的旧/新 JSON, 不会读到截断半文件 (Client.create.store.load 可能在另一进程
450
+ * 写入中间触发, atomic rename 避免它解析失败).
451
+ */
452
+ save(tokens: TokenSet): Promise<void>;
453
+ load(): Promise<TokenSet | null>;
454
+ clear(): Promise<void>;
455
+ }
339
456
  /**
340
- * 判定一个错误码是否属于"需要前端引导用户重新认证/审批"的高级语义,
341
- * 而不是简单 retry。这类错误前端不允许在 UI 层做自动重试。
457
+ * 创建文件 token 存储 (与 Go NewFileTokenStore 等价)
458
+ * @param path 自定义路径; 空则使用默认 ~/.acosmi/tokens.json
342
459
  */
343
- declare function isComplianceTerminalError(code: string): boolean;
460
+ declare function newFileTokenStore(path?: string): FileTokenStore;
344
461
  /**
345
- * "是否允许在 UI 上呈现为'扣费已确认'"的判定。
346
- * provider 状态为 unknown / retrying / pending 时一律不展示为已确认。
462
+ * 基于 LocalStorage 的 token 存储 (浏览器)
463
+ *
464
+ * 仅在浏览器环境可用 (检测 globalThis.localStorage)。
465
+ * 不持久化跨设备同步, 适合单机 SPA 使用。
347
466
  */
348
- declare function isBillingConfirmable(providerStatus: ComplianceProviderStatus | undefined, billingStatus: ComplianceBillingDisplayStatus | undefined): boolean;
467
+ declare class LocalStorageTokenStore implements TokenStore {
468
+ private key;
469
+ constructor(key?: string);
470
+ save(tokens: TokenSet): Promise<void>;
471
+ load(): Promise<TokenSet | null>;
472
+ clear(): Promise<void>;
473
+ }
474
+ /**
475
+ * 内存 token 存储 (不持久化, 进程重启即丢失)
476
+ * 适合: 测试 / Deno script / 短期 SDK 调用 / 不希望落盘的安全场景
477
+ */
478
+ declare class InMemoryTokenStore implements TokenStore {
479
+ private tokens;
480
+ save(tokens: TokenSet): Promise<void>;
481
+ load(): Promise<TokenSet | null>;
482
+ clear(): Promise<void>;
483
+ }
349
484
 
350
- type ComplianceAssetType = 'CONTRACT' | 'CODE' | 'IMAGE' | 'DOCUMENT' | 'ARCHIVE' | 'HASH_ONLY' | 'URL_SNAPSHOT' | 'RELEASE' | 'LOG' | 'OTHER';
351
- type ComplianceHashAlgorithm = 'sha256' | 'sha512' | 'sm3';
352
- type ComplianceDigestSource = 'CLIENT' | 'COMPLIANCE_SERVICE' | 'PROVIDER';
353
- type CompliancePrivacyLevel = 'public' | 'private';
354
- /** 证据资产对外稳定视图。对应后端 EvidenceAssetRespVO。 */
355
- interface EvidenceAsset {
356
- id: number;
357
- /** 业务编号;SDK / 前端引用时优先使用 evidenceNo。 */
358
- evidenceNo: string;
359
- /** publish 后的公开 verify code;DRAFT / 非 public privacy 时为 null。 */
360
- publicVerifyCode?: string | null;
361
- assetType: ComplianceAssetType | string;
362
- name: string;
363
- mimeType?: string | null;
364
- size?: number | null;
365
- hashAlgorithm: ComplianceHashAlgorithm | string;
366
- /** 资产 hash(hex 字符串)。 */
367
- contentHash: string;
368
- canonicalizationProfile?: string | null;
369
- digestSource: ComplianceDigestSource | string;
370
- privacyLevel: CompliancePrivacyLevel | string;
371
- status: string;
372
- }
373
- /** 创建证据资产请求;与 Java EvidenceAssetCreateReq 对齐。 */
374
- interface CreateEvidenceAssetRequest {
375
- /** AssetTypeEnum.name()。 */
376
- assetType: ComplianceAssetType | string;
377
- name: string;
378
- mimeType?: string;
379
- /** 'sha256' / 'sha512' / 'sm3'。 */
380
- hashAlgorithm: ComplianceHashAlgorithm | string;
381
- /** hex 字符串;hash-only 资产必填。 */
382
- declaredHash?: string;
383
- /** CLIENT / COMPLIANCE_SERVICE / PROVIDER。 */
384
- digestSource?: ComplianceDigestSource | string;
385
- /** 原文 base64;hash-only 时缺省即可。 */
386
- contentBase64?: string;
387
- /** public / private(默认 private)。 */
388
- privacyLevel?: CompliancePrivacyLevel | string;
389
- source?: string;
390
- }
391
- /** 公开 verify 结果。隐私边界:不暴露 PII / 合同原文 / storage / provider raw。 */
392
- interface PublicEvidenceVerifyResult {
393
- evidenceNo: string;
394
- assetType: string;
395
- hashAlgorithm: string;
396
- contentHash: string;
397
- size?: number | null;
398
- canonicalizationProfile?: string | null;
399
- verifiedAt: string;
400
- packageId?: number | null;
401
- manifestHash?: string | null;
402
- packageHash?: string | null;
403
- manifestOfflineVerify: boolean;
404
- }
405
- type ComplianceTimestampVerificationStatus = 'PENDING' | 'VERIFIED' | 'FAILED' | 'LOCAL_VERIFY_FAILED' | 'UNKNOWN' | 'RETRYING';
406
- /** 时间章 token 对外视图(不含 provider/object/tsa 内部字段)。 */
407
- interface TimestampToken {
408
- id: number;
409
- assetId: number;
410
- policyOid?: string | null;
411
- serialNumber?: string | null;
412
- /** gen_time ISO-8601;UNKNOWN/PENDING 状态可能为 null。 */
413
- genTime?: string | null;
414
- accuracy?: string | null;
415
- verificationStatus: ComplianceTimestampVerificationStatus | string;
416
- verifiedAt?: string | null;
417
- verificationError?: string | null;
418
- }
419
- /** 申请时间章请求。`provider` 字段已从服务端契约下线;SDK 永远不传。 */
420
- interface IssueTimestampRequest {
421
- name?: string;
422
- mimeType?: string;
423
- hashAlgorithm: ComplianceHashAlgorithm | string;
424
- /** 客户端声明 digest(hex);contentBase64 非空时作为校验值。 */
425
- digest?: string;
426
- contentBase64?: string;
427
- }
428
- /** verify 请求 / 结果。 */
429
- interface VerifyTimestampRequest {
430
- tokenId: number;
485
+ /** 表示一次 retry 评估的请求快照 仅供 SafeToRetry 闸门使用 */
486
+ interface RetryRequestInfo {
487
+ method: string;
488
+ url: string;
431
489
  }
432
- interface TimestampVerifyResult {
433
- passed: boolean;
434
- reason: string;
490
+ /**
491
+ * 配置 SDK 重试行为.
492
+ *
493
+ * undefined 字段使用 DefaultRetryPolicy 对应字段; null/undefined RetryPolicy 自身禁用重试.
494
+ */
495
+ interface RetryPolicy {
496
+ /** 总尝试次数 (含首次). 1 = 不重试; 默认 2. */
497
+ maxAttempts?: number;
498
+ /** 首次重试退避时长 (毫秒). 默认 200. */
499
+ backoffMs?: number;
500
+ /** 退避最大值 (指数增长封顶, 毫秒). 默认 2000. */
501
+ backoffMaxMs?: number;
502
+ /** 指数倍数. 默认 2.0. */
503
+ backoffMul?: number;
504
+ /**
505
+ * 错误层闸门: 是否值得重试.
506
+ * 默认 defaultRetryable: HTTPError 5xx/429, NetworkError Timeout/EOF, 排除 StreamError.
507
+ */
508
+ onRetryable?: (err: unknown) => boolean;
509
+ /**
510
+ * 请求层闸门 (计费安全核心): 当前请求是否值得重试.
511
+ * 默认 defaultSafeToRetry: GET/HEAD/OPTIONS true, 其他 false.
512
+ * chat/messages/upload POST → 默认 false 兜底, 双扣绝不发生.
513
+ */
514
+ safeToRetry?: (req: RetryRequestInfo) => boolean;
435
515
  }
436
- interface EvidencePackage {
437
- id: number;
438
- assetId: number;
439
- timestampTokenId?: number | null;
440
- chainId: string;
441
- packageVersion: string;
442
- hashAlgorithm: string;
443
- manifestHash: string;
444
- packageHash: string;
445
- status: string;
516
+ /**
517
+ * 安全默认值.
518
+ *
519
+ * 计费安全红线: safeToRetry 默认 POST=false → chat/messages 用户 0 行为变化.
520
+ * GET 类查询 (skill-store/models/balance) 自动得 2x 稳定性.
521
+ */
522
+ declare const DefaultRetryPolicy: Required<Omit<RetryPolicy, never>>;
523
+ /**
524
+ * 计费安全闸门.
525
+ *
526
+ * 仅以下 method 视为幂等:
527
+ * - GET / HEAD / OPTIONS: 天然幂等
528
+ *
529
+ * POST/PUT/DELETE/PATCH 默认 false (双扣保护). 调用方需要 GET 类 POST 重试可自定义 safeToRetry.
530
+ */
531
+ declare function defaultSafeToRetry(req: RetryRequestInfo): boolean;
532
+ /**
533
+ * 错误层闸门.
534
+ *
535
+ * 显式排除 (优先级最高):
536
+ * - StreamError: V2 P0 SSE 中段错误, 流已部分写出, 重试 = 双 token + 重复消息
537
+ * - AbortSignal aborted: 用户主动 abort, 重试无意义 (TS 中由调用方在 onRetryable 之前检查)
538
+ *
539
+ * 视为可重试:
540
+ * - HTTPError 5xx 或 429
541
+ * - NetworkError isTimeout() 或 isEOF()
542
+ *
543
+ * 其他 (如 4xx 业务错误 / DNS 失败 / BusinessError): 不重试
544
+ */
545
+ declare function defaultRetryable(err: unknown): boolean;
546
+ /** 实际生效策略 (undefined → DefaultRetryPolicy 兜底; 字段缺失填默认值) */
547
+ declare function effectivePolicy(p: RetryPolicy | null | undefined): Required<RetryPolicy> | null;
548
+ /**
549
+ * 计算第 attempt 次重试的退避时长 (毫秒, attempt 从 0 起).
550
+ * 优先级: HTTPError.retryAfter (上限 60s) > 指数退避 (backoffMs * backoffMul^attempt, 封顶 backoffMaxMs)
551
+ */
552
+ declare function computeBackoff(p: Required<RetryPolicy>, attempt: number, err: unknown): number;
553
+
554
+ type FilterStatus = 'ok' | 'admin-bypass' | 'internal-bypass' | 'disabled-by-flag' | 'fallback-tkdist-error' | 'fallback-tkdist-deployment-skew' | 'fallback-no-buckets' | 'fallback-missing-userid' | '';
555
+ declare const FilterStatusOK: FilterStatus;
556
+ declare const FilterStatusAdminBypass: FilterStatus;
557
+ declare const FilterStatusInternalBypass: FilterStatus;
558
+ declare const FilterStatusDisabledByFlag: FilterStatus;
559
+ declare const FilterStatusFallbackTkdistError: FilterStatus;
560
+ declare const FilterStatusFallbackTkdistSkew: FilterStatus;
561
+ declare const FilterStatusFallbackNoBuckets: FilterStatus;
562
+ declare const FilterStatusFallbackMissingUser: FilterStatus;
563
+ declare const FilterStatusUnknown: FilterStatus;
564
+ /** 客户端配置 */
565
+ interface Config {
566
+ /**
567
+ * nexus-v4 API 根地址 (默认 https://acosmi.com)。
568
+ * SDK 自动追加 /api/v4, 无需手动拼接。
569
+ */
570
+ serverURL?: string;
571
+ /** token 持久化实现, 缺省时按平台选 (Node File / Browser LocalStorage / Memory) */
572
+ store?: TokenStore;
573
+ /** 自定义 fetch 实现 (默认 globalThis.fetch) */
574
+ fetchImpl?: typeof fetch;
575
+ /**
576
+ * 重试策略 (L6, v0.15)
577
+ *
578
+ * undefined = 禁用重试 (v0.14.1 行为, 老调用方 0 影响)
579
+ * 非 undefined = 启用 — 默认 SafeToRetry POST=false 兜底, chat/messages POST 仍 0 retry
580
+ * GET 类查询 (skill-store/models/balance) 自动得 2x 稳定性
581
+ *
582
+ * 计费安全: 自定义 SafeToRetry 时, 严禁让 POST chat/messages 通过, 否则双扣
583
+ */
584
+ retryPolicy?: RetryPolicy;
585
+ /**
586
+ * Compliance (时间章 / 电子证据 / 合同签署) API 根地址。
587
+ *
588
+ * Java compliance 模块的 controller 注册在 `/compliance/...` 下,部署到
589
+ * `/admin-api/*` 前缀。未配置时默认 `${serverURL}/admin-api`,也可显式覆盖到
590
+ * 独立 ingress(如 `https://compliance.example.com`)。
591
+ *
592
+ * 该地址不被 `/api/v4` 拼接路径复用,compliance 调用走自己的子 client
593
+ * `client.compliance.*`,不与既有模型网关 API 冲突。
594
+ */
595
+ complianceBaseURL?: string;
596
+ /**
597
+ * OAuth metadata profile — 决定 `ensureToken` 刷新 token 时
598
+ * 发现 metadata 走哪个 well-known 端点。
599
+ *
600
+ * - `'desktop'` (默认): `/.well-known/oauth-authorization-server/desktop`
601
+ * — 桌面 loopback OAuth (`login()`) 流程。
602
+ * - `'web'`: `/.well-known/oauth-authorization-server/web`
603
+ * — 浏览器 Web OAuth (csign 等第一方 Web 应用) 签发的 token,
604
+ * 其 refresh 必须走 Web token 端点。
605
+ *
606
+ * 未设置时默认 `'desktop'`,对既有调用方行为完全无影响。
607
+ * `login()` 桌面 loopback 路径不受此配置影响。
608
+ */
609
+ oauthMetadataProfile?: OAuthMetadataProfile;
610
+ /**
611
+ * Browser refresh strategy for Web OAuth tokens.
612
+ *
613
+ * - `'direct'` (default): refresh directly against the OAuth token endpoint.
614
+ * - `'server-proxy'`: POST the current TokenSet to a same-origin refresh proxy,
615
+ * useful when the OAuth issuer intentionally blocks browser CORS.
616
+ * - `'none'`: do not refresh automatically; expired tokens throw `token_expired`.
617
+ */
618
+ browserRefreshMode?: BrowserRefreshMode;
619
+ /** Same-origin refresh proxy URL used when `browserRefreshMode='server-proxy'`. */
620
+ refreshProxyURL?: string;
446
621
  }
447
- interface ComplianceReport {
448
- id: number;
449
- reportNo: string;
450
- reportType: string;
451
- status: string;
452
- assetId?: number | null;
453
- packageId?: number | null;
454
- publicUrlToken?: string | null;
455
- publishedAt?: string | null;
456
- bodyHash?: string | null;
622
+ type BrowserRefreshMode = 'direct' | 'server-proxy' | 'none';
623
+ declare const ErrOAuthCORSBlocked: "oauth_cors_blocked";
624
+ declare const ErrRefreshProxyFailed: "refresh_proxy_failed";
625
+ declare const ErrTokenExpired: "token_expired";
626
+ interface Deferred<T> {
627
+ promise: Promise<T>;
628
+ resolve: (v: T) => void;
629
+ reject: (e: unknown) => void;
457
630
  }
458
- interface CreateReportRequest {
459
- assetId: number;
460
- packageId: number;
461
- }
462
- /** 离线复核下载 VO;建议调用方持久化作为长期可重复验证依据。 */
463
- interface ReportDownload {
464
- id: number;
465
- reportNo: string;
466
- reportType: string;
467
- status: string;
468
- bodyHash?: string | null;
469
- publishedAt?: string | null;
470
- assetEvidenceNo?: string | null;
471
- assetHashAlgorithm?: string | null;
472
- assetContentHash?: string | null;
473
- packageManifestHash?: string | null;
474
- packageHash?: string | null;
475
- packageHashAlgorithm?: string | null;
476
- timestampSerialNumber?: string | null;
477
- timestampGenTime?: string | null;
478
- timestampVerificationStatus?: string | null;
479
- }
480
- interface SigningEnvelope {
481
- id: number;
482
- envelopeNo: string;
483
- applicantUserId?: string | null;
484
- status: string;
485
- primaryContractId?: number | null;
486
- contractHash?: string | null;
487
- hashAlgorithm?: string | null;
488
- billingGroupId?: string | null;
489
- chainId?: string | null;
490
- requestId?: string | null;
491
- pendingReason?: string | null;
492
- signedAt?: string | null;
493
- evidenceReadyAt?: string | null;
494
- committedAt?: string | null;
495
- }
496
- /** 创建 envelope 请求;只保留调用方业务字段,内部主体快照和履约通道由后端推导。 */
497
- interface CreateSigningEnvelopeRequest {
498
- envelopeNo?: string;
499
- requestId?: string;
500
- /** 调用方稳定 idempotency-key(不传则由 Idempotency-Key header 兜底)。 */
501
- idempotencyKey?: string;
502
- billingGroupId?: string;
503
- chainId?: string;
504
- }
505
- /** sign 请求;service 默认闸门关闭,SDK 写示例必须处理 ENVELOPE_GATE_CLOSED 错误。 */
506
- interface SignEnvelopeRequest {
507
- approvalRequestId?: number;
508
- contractId?: number;
509
- contractHash?: string;
510
- sealId?: number;
511
- signLocationType?: string;
512
- signLocationPayload?: string;
513
- transactorId?: number;
514
- requestId?: string;
515
- idempotencyKey?: string;
516
- }
517
- /** H5 短链请求。 */
518
- interface CreateH5SigningUrlRequest extends SignEnvelopeRequest {
519
- }
520
- interface SealApproval {
521
- id: number;
522
- envelopeId?: number | null;
523
- contractId?: number | null;
524
- contractHash?: string | null;
525
- hashAlgorithm?: string | null;
526
- sealId?: number | null;
527
- applicantUserId?: string | null;
528
- approverUserId?: string | null;
529
- transactorId?: number | null;
530
- signLocationType?: string | null;
531
- signLocationPayload?: string | null;
532
- reason?: string | null;
533
- expiresAt?: string | null;
534
- status: string;
535
- approvedAt?: string | null;
536
- rejectedAt?: string | null;
537
- canceledAt?: string | null;
538
- }
539
- /** 提交审批;provider 侧字段由后端归一,SDK 调用方不传。 */
540
- interface SubmitSealApprovalRequest {
541
- envelopeId?: number;
542
- contractId?: number;
543
- contractHash?: string;
544
- hashAlgorithm?: string;
545
- sealId?: number;
546
- approverUserId?: string;
547
- transactorId?: number;
548
- signLocationType?: string;
549
- signLocationPayload?: string;
550
- reason?: string;
551
- }
552
- interface ApproveSealApprovalQuery {
553
- expiresAt?: string;
554
- note?: string;
555
- }
556
- interface RejectSealApprovalQuery {
557
- reason?: string;
558
- }
559
- interface CancelSealApprovalQuery {
560
- reason?: string;
561
- }
562
- type ComplianceProviderRequestStatus = 'PENDING' | 'SUCCESS' | 'FAILED' | 'UNKNOWN' | 'RETRYING';
563
- interface ProviderRequestStatusView {
564
- id: number;
565
- status: ComplianceProviderRequestStatus | string;
566
- /** SUCCESS / FAILED 终态。 */
567
- terminal: boolean;
568
- /** 当前状态是否允许 SDK 安全重试请求(仅对 RETRYING 为 true)。 */
569
- retryable: boolean;
570
- businessNo?: string | null;
571
- contractNo?: string | null;
572
- sealId?: string | null;
573
- attemptCount?: number | null;
574
- reconciliationStatus?: string | null;
575
- nextRetryAt?: string | null;
576
- requestedAt?: string | null;
577
- respondedAt?: string | null;
578
- }
579
- /** Compliance 写操作选项;写操作不自动 retry,不自动 401 重放。 */
580
- interface ComplianceWriteOptions {
581
- /**
582
- * 调用方稳定的幂等键。写操作强烈建议持久化;缺省时服务端按 UUID 兜底,但调用方
583
- * 在重试 / 恢复时无法对账。
584
- */
585
- idempotencyKey?: string;
586
- signal?: AbortSignal;
587
- }
588
- /** 轮询参数(exponential backoff)。 */
589
- interface CompliancePollOptions {
590
- /** 总超时(ms),缺省 60s。 */
591
- timeoutMs?: number;
592
- /** 初始 interval(ms),缺省 1000。 */
593
- initialIntervalMs?: number;
594
- /** interval 倍增上限(ms),缺省 5000。 */
595
- maxIntervalMs?: number;
596
- /** 倍增系数,缺省 1.5。 */
597
- multiplier?: number;
598
- signal?: AbortSignal;
599
- }
600
-
601
- /**
602
- * SDK 内部 symbolic key;用于代码分支判断与文档。**不是 wire contract**。
603
- */
604
- type ComplianceErrorKey = 'COMPLIANCE_UNAUTHORIZED' | 'COMPLIANCE_INSUFFICIENT_SCOPE' | 'COMPLIANCE_STEP_UP_REQUIRED' | 'COMPLIANCE_TOKEN_INVALID' | 'SUBJECT_SNAPSHOT_REQUIRED' | 'SUBJECT_SNAPSHOT_NOT_FOUND' | 'SUBJECT_SNAPSHOT_TENANT_MISMATCH' | 'EVIDENCE_ASSET_NOT_FOUND' | 'EVIDENCE_ASSET_HASH_MISMATCH' | 'EVIDENCE_ASSET_PAYLOAD_REQUIRED' | 'TIMESTAMP_TOKEN_NOT_FOUND' | 'TIMESTAMP_PROVIDER_FAILED' | 'TIMESTAMP_PROVIDER_UNKNOWN' | 'TIMESTAMP_LOCAL_VERIFY_FAILED' | 'TIMESTAMP_PROVIDER_NOT_AVAILABLE' | 'EVIDENCE_PACKAGE_NOT_FOUND' | 'EVIDENCE_PACKAGE_TIMESTAMP_REQUIRED' | 'EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH' | 'REPORT_NOT_FOUND' | 'REPORT_ALREADY_PUBLISHED' | 'REPORT_DRAFT_REQUIRED' | 'EVIDENCE_VERIFY_TARGET_REQUIRED' | 'EVIDENCE_VERIFY_TARGET_NOT_FOUND' | 'PROVIDER_REQUEST_UNKNOWN_NO_RETRY' | 'PROVIDER_CALLBACK_SOURCE_INVALID' | 'PROVIDER_NOT_CONFIGURED' | 'PROVIDER_REQUEST_NOT_FOUND' | 'PROVIDER_REQUEST_IDEMPOTENCY_REQUIRED' | 'PROVIDER_REQUEST_STATUS_NOT_TERMINAL' | 'ENVELOPE_NOT_FOUND' | 'ENVELOPE_TENANT_MISMATCH' | 'ENVELOPE_STATE_NOT_ALLOWED' | 'ENVELOPE_GATE_CLOSED' | 'CONTRACT_NOT_FOUND' | 'CONTRACT_HASH_MISMATCH' | 'PROVIDER_AUTHORIZATION_NOT_CONFIRMED' | 'ENVELOPE_EVIDENCE_NOT_READY' | 'SEAL_ASSET_NOT_FOUND' | 'SEAL_APPROVAL_NOT_FOUND' | 'SEAL_APPROVAL_STATE_NOT_APPROVED' | 'SEAL_APPROVAL_EXPIRED' | 'SEAL_APPROVAL_ALREADY_USED' | 'SEAL_APPROVAL_NONCE_USED' | 'SEAL_APPROVAL_SEAL_MISMATCH' | 'SEAL_APPROVAL_LOCATION_MISMATCH' | 'SEAL_APPROVAL_TRANSACTOR_MISMATCH' | 'SEAL_APPROVAL_CONTRACT_HASH_MISMATCH' | 'SEAL_APPROVAL_INVALID_TRANSITION' | 'SEAL_USE_ALREADY_CONSUMED' | 'AUDIT_CHAIN_TAMPER_DETECTED' | 'BILLING_COMMIT_REQUIRES_LOCAL_VERIFY' | 'BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS' | 'BILLING_CALLBACK_CANNOT_COMMIT' | 'BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE' | 'BILLING_S2S_FORBIDDEN' | 'UNKNOWN_COMPLIANCE_ERROR';
605
- /** 单个错误的 SDK 视图。 */
606
- interface ComplianceErrorInfo {
607
- /** Java numeric error code (wire contract)。 */
608
- code: number;
609
- /** 服务端原始 message(中文,可变);仅用于日志/展示。 */
610
- message: string;
611
- /** SDK 分支判断用 symbolic key。 */
612
- key: ComplianceErrorKey;
613
- /** 是否安全自动重试 — compliance 写接口几乎全为 false。 */
614
- retryable: boolean;
615
- /** 是否已经是终态 — 用户必须用新 idempotency-key 重新发起。 */
616
- terminal: boolean;
617
- /** 高风险动作需要 step-up / introspection。 */
618
- stepUpRequired: boolean;
619
- }
620
- /**
621
- * 把一个 BusinessError 分类为 compliance 视图。
622
- * 非 compliance 段位的错误码会回退到 UNKNOWN_COMPLIANCE_ERROR,调用方应该当作业务错误处理。
623
- */
624
- declare function classifyComplianceError(err: BusinessError): ComplianceErrorInfo;
625
- /**
626
- * 判断 BusinessError 是否属于 compliance 段位(1-031-xxx-xxx)。
627
- * 不在段位的错误码可能来自其它 yudao 模块,按通用业务错误处理即可。
628
- */
629
- declare function isComplianceBusinessError(err: BusinessError): boolean;
630
-
631
- /**
632
- * Token 持久化接口
633
- * 桌面智能体可自行实现 (如 macOS Keychain / Windows Credential Manager)
634
- *
635
- * 跨端约定:
636
- * - Save: 写入持久化, 失败抛 Error
637
- * - Load: 读取, 不存在返回 null (与 Go IsNotExist 行为一致)
638
- * - Clear: 删除, 不存在不抛错 (Logout 后 Clear 不应报错, [RC-11])
639
- * - withLock (v1.0.2 新增, 可选): 跨进程临界区. Client 在 refresh token rotation
640
- * 场景下用此包裹 "load → check → refresh → save" 整段, 防多进程共享同一 store
641
- * (典型: FileTokenStore 默认 ~/.acosmi/tokens.json) 撞 HTTP 400 refresh token
642
- * not found. 不实现时 Client 自动回退到仅进程内串行 (LocalStorage / InMemory
643
- * 单进程语义无需此方法).
644
- */
645
- interface TokenStore {
646
- save(tokens: TokenSet): Promise<void>;
647
- load(): Promise<TokenSet | null>;
648
- clear(): Promise<void>;
649
- withLock?<T>(fn: () => Promise<T>): Promise<T>;
631
+ /**
632
+ * WebSocket 状态 — 内部使用, 实际方法由 ws.ts mixin 提供
633
+ * 留作 forward declaration, 避免循环依赖
634
+ */
635
+ interface WSState {
636
+ connected: boolean;
637
+ [key: string]: any;
650
638
  }
651
639
  /**
652
- * 基于文件的 token 存储 (开发/测试用)
653
- * 生产环境建议替换为系统钥匙串实现
654
- *
655
- * 默认路径: ~/.acosmi/tokens.json
640
+ * Acosmi nexus-v4 统一 API 客户端
656
641
  *
657
- * 浏览器环境调用 new FileTokenStore() 会抛错 — 浏览器请用 LocalStorageTokenStore 或 InMemoryTokenStore.
642
+ * 覆盖全域 API: 模型/权益/商城/钱包/技能/工具/WebSocket
643
+ * 自动处理 token 刷新, 所有 API 调用线程安全 (基于 Promise chain)
658
644
  */
659
- /** 跨进程文件锁配置 (v1.0.2). 公开常量是为了让 caller / 测试可观察, 不建议生产代码改. */
660
- declare const fileLockDefaults: {
661
- /** 获取锁的超时上限 (毫秒). refresh 流程含网络 < 30s, 30s 已远超正常完成时间. */
662
- readonly acquireTimeoutMs: 30000;
663
- /** 旧锁判定阈值 (毫秒). 锁文件 mtime 早于此值视为 stale 进程崩溃残留, 自动 break. */
664
- readonly staleMs: 60000;
665
- /** 重试间隔基数 (毫秒). 真实间隔 = base + random(0, jitter). */
666
- readonly retryBaseMs: 30;
667
- readonly retryJitterMs: 70;
668
- };
669
- declare class FileTokenStore implements TokenStore {
670
- private path;
671
- /** 进程内串行化 (Promise chain) — 与跨进程 flock 配合, 避免单进程内并发持锁产生死锁式互等. */
672
- private chain;
673
- constructor(path?: string);
674
- private resolvePath;
675
- /** 进程内串行 (维持 v1.0.1 单进程语义). flock 之外另一层防御: 如果用户自己就是单进程
676
- * 并发场景, 不必每次都进 flock 旁路文件 IO. */
677
- private withChain;
678
- /**
679
- * 跨进程临界区.sidecar `<path>.lock` 文件 + O_EXCL 创建语义实现互斥:
680
- * - 创建成功 = 持有锁; 写入 pid+timestamp 便于诊断
681
- * - 创建失败 (EEXIST) = 别的进程持锁, backoff 重试
682
- * - 锁文件 mtime > staleMs = 进程崩溃残留, unlink 后重试
683
- * - acquireTimeoutMs 超时 = 抛错 (caller 应作为 transient error 处理, 上层 retry)
684
- *
685
- * 注意: O_EXCL NFS 上不保证原子; FileTokenStore 适用于本地文件系统 (典型用户家目录).
686
- * 真要跨机共享 token, 应实现自定义 Keychain / 数据库 store, 不要用 FileTokenStore.
687
- */
688
- withLock<T>(fn: () => Promise<T>): Promise<T>;
689
- /**
690
- * 写入 token. 流程:
691
- * 1. mkdir -p (默认路径目录)
692
- * 2. 写入 `<path>.tmp.<pid>`
693
- * 3. fsync rename 到正式路径 (POSIX 上 rename(2) 同分区原子, Windows 上 ReplaceFile)
694
- *
695
- * 选择 atomic rename 而非直接 writeFile: 多进程并发或本进程崩溃时, 读端永远看到的是
696
- * 完整的旧/新 JSON, 不会读到截断半文件 (Client.create.store.load 可能在另一进程
697
- * 写入中间触发, atomic rename 避免它解析失败).
698
- */
699
- save(tokens: TokenSet): Promise<void>;
700
- load(): Promise<TokenSet | null>;
701
- clear(): Promise<void>;
702
- }
703
- /**
704
- * 创建文件 token 存储 (与 Go NewFileTokenStore 等价)
705
- * @param path 自定义路径; 空则使用默认 ~/.acosmi/tokens.json
706
- */
707
- declare function newFileTokenStore(path?: string): FileTokenStore;
708
- /**
709
- * 基于 LocalStorage 的 token 存储 (浏览器)
710
- *
711
- * 仅在浏览器环境可用 (检测 globalThis.localStorage)。
712
- * 不持久化跨设备同步, 适合单机 SPA 使用。
713
- */
714
- declare class LocalStorageTokenStore implements TokenStore {
715
- private key;
716
- constructor(key?: string);
717
- save(tokens: TokenSet): Promise<void>;
718
- load(): Promise<TokenSet | null>;
719
- clear(): Promise<void>;
720
- }
721
- /**
722
- * 内存 token 存储 (不持久化, 进程重启即丢失)
723
- * 适合: 测试 / Deno script / 短期 SDK 调用 / 不希望落盘的安全场景
724
- */
725
- declare class InMemoryTokenStore implements TokenStore {
726
- private tokens;
727
- save(tokens: TokenSet): Promise<void>;
728
- load(): Promise<TokenSet | null>;
729
- clear(): Promise<void>;
730
- }
731
-
732
- /** 表示一次 retry 评估的请求快照 — 仅供 SafeToRetry 闸门使用 */
733
- interface RetryRequestInfo {
734
- method: string;
735
- url: string;
736
- }
737
- /**
738
- * 配置 SDK 重试行为.
739
- *
740
- * undefined 字段使用 DefaultRetryPolicy 对应字段; null/undefined RetryPolicy 自身禁用重试.
741
- */
742
- interface RetryPolicy {
743
- /** 总尝试次数 (含首次). 1 = 不重试; 默认 2. */
744
- maxAttempts?: number;
745
- /** 首次重试退避时长 (毫秒). 默认 200. */
746
- backoffMs?: number;
747
- /** 退避最大值 (指数增长封顶, 毫秒). 默认 2000. */
748
- backoffMaxMs?: number;
749
- /** 指数倍数. 默认 2.0. */
750
- backoffMul?: number;
751
- /**
752
- * 错误层闸门: 是否值得重试.
753
- * 默认 defaultRetryable: HTTPError 5xx/429, NetworkError Timeout/EOF, 排除 StreamError.
754
- */
755
- onRetryable?: (err: unknown) => boolean;
756
- /**
757
- * 请求层闸门 (计费安全核心): 当前请求是否值得重试.
758
- * 默认 defaultSafeToRetry: GET/HEAD/OPTIONS true, 其他 false.
759
- * chat/messages/upload POST → 默认 false 兜底, 双扣绝不发生.
760
- */
761
- safeToRetry?: (req: RetryRequestInfo) => boolean;
762
- }
763
- /**
764
- * 安全默认值.
765
- *
766
- * 计费安全红线: safeToRetry 默认 POST=false → chat/messages 用户 0 行为变化.
767
- * GET 类查询 (skill-store/models/balance) 自动得 2x 稳定性.
768
- */
769
- declare const DefaultRetryPolicy: Required<Omit<RetryPolicy, never>>;
770
- /**
771
- * 计费安全闸门.
772
- *
773
- * 仅以下 method 视为幂等:
774
- * - GET / HEAD / OPTIONS: 天然幂等
775
- *
776
- * POST/PUT/DELETE/PATCH 默认 false (双扣保护). 调用方需要 GET 类 POST 重试可自定义 safeToRetry.
777
- */
778
- declare function defaultSafeToRetry(req: RetryRequestInfo): boolean;
779
- /**
780
- * 错误层闸门.
781
- *
782
- * 显式排除 (优先级最高):
783
- * - StreamError: V2 P0 SSE 中段错误, 流已部分写出, 重试 = 双 token + 重复消息
784
- * - AbortSignal aborted: 用户主动 abort, 重试无意义 (TS 中由调用方在 onRetryable 之前检查)
785
- *
786
- * 视为可重试:
787
- * - HTTPError 5xx 或 429
788
- * - NetworkError isTimeout() 或 isEOF()
789
- *
790
- * 其他 (如 4xx 业务错误 / DNS 失败 / BusinessError): 不重试
791
- */
792
- declare function defaultRetryable(err: unknown): boolean;
793
- /** 实际生效策略 (undefined → DefaultRetryPolicy 兜底; 字段缺失填默认值) */
794
- declare function effectivePolicy(p: RetryPolicy | null | undefined): Required<RetryPolicy> | null;
795
- /**
796
- * 计算第 attempt 次重试的退避时长 (毫秒, attempt 从 0 起).
797
- * 优先级: HTTPError.retryAfter (上限 60s) > 指数退避 (backoffMs * backoffMul^attempt, 封顶 backoffMaxMs)
798
- */
799
- declare function computeBackoff(p: Required<RetryPolicy>, attempt: number, err: unknown): number;
800
-
801
- type FilterStatus = 'ok' | 'admin-bypass' | 'internal-bypass' | 'disabled-by-flag' | 'fallback-tkdist-error' | 'fallback-tkdist-deployment-skew' | 'fallback-no-buckets' | 'fallback-missing-userid' | '';
802
- declare const FilterStatusOK: FilterStatus;
803
- declare const FilterStatusAdminBypass: FilterStatus;
804
- declare const FilterStatusInternalBypass: FilterStatus;
805
- declare const FilterStatusDisabledByFlag: FilterStatus;
806
- declare const FilterStatusFallbackTkdistError: FilterStatus;
807
- declare const FilterStatusFallbackTkdistSkew: FilterStatus;
808
- declare const FilterStatusFallbackNoBuckets: FilterStatus;
809
- declare const FilterStatusFallbackMissingUser: FilterStatus;
810
- declare const FilterStatusUnknown: FilterStatus;
811
- /** 客户端配置 */
812
- interface Config {
813
- /**
814
- * nexus-v4 API 根地址 (默认 https://acosmi.com)。
815
- * SDK 自动追加 /api/v4, 无需手动拼接。
816
- */
817
- serverURL?: string;
818
- /** token 持久化实现, 缺省时按平台选 (Node File / Browser LocalStorage / Memory) */
819
- store?: TokenStore;
820
- /** 自定义 fetch 实现 (默认 globalThis.fetch) */
821
- fetchImpl?: typeof fetch;
822
- /**
823
- * 重试策略 (L6, v0.15)
824
- *
825
- * undefined = 禁用重试 (v0.14.1 行为, 老调用方 0 影响)
826
- * 非 undefined = 启用 — 默认 SafeToRetry POST=false 兜底, chat/messages POST 仍 0 retry
827
- * GET 类查询 (skill-store/models/balance) 自动得 2x 稳定性
828
- *
829
- * 计费安全: 自定义 SafeToRetry 时, 严禁让 POST chat/messages 通过, 否则双扣
830
- */
831
- retryPolicy?: RetryPolicy;
832
- /**
833
- * Compliance (时间章 / 电子证据 / 合同签署) API 根地址。
834
- *
835
- * Java compliance 模块的 controller 注册在 `/compliance/...` 下,部署到
836
- * `/admin-api/*` 前缀。未配置时默认 `${serverURL}/admin-api`,也可显式覆盖到
837
- * 独立 ingress(如 `https://compliance.example.com`)。
838
- *
839
- * 该地址不被 `/api/v4` 拼接路径复用,compliance 调用走自己的子 client
840
- * `client.compliance.*`,不与既有模型网关 API 冲突。
841
- */
842
- complianceBaseURL?: string;
843
- /**
844
- * OAuth metadata profile — 决定 `ensureToken` 刷新 token 时
845
- * 发现 metadata 走哪个 well-known 端点。
846
- *
847
- * - `'desktop'` (默认): `/.well-known/oauth-authorization-server/desktop`
848
- * — 桌面 loopback OAuth (`login()`) 流程。
849
- * - `'web'`: `/.well-known/oauth-authorization-server/web`
850
- * — 浏览器 Web OAuth (csign 等第一方 Web 应用) 签发的 token,
851
- * 其 refresh 必须走 Web token 端点。
852
- *
853
- * 未设置时默认 `'desktop'`,对既有调用方行为完全无影响。
854
- * `login()` 桌面 loopback 路径不受此配置影响。
855
- */
856
- oauthMetadataProfile?: OAuthMetadataProfile;
857
- /**
858
- * Browser refresh strategy for Web OAuth tokens.
859
- *
860
- * - `'direct'` (default): refresh directly against the OAuth token endpoint.
861
- * - `'server-proxy'`: POST the current TokenSet to a same-origin refresh proxy,
862
- * useful when the OAuth issuer intentionally blocks browser CORS.
863
- * - `'none'`: do not refresh automatically; expired tokens throw `token_expired`.
864
- */
865
- browserRefreshMode?: BrowserRefreshMode;
866
- /** Same-origin refresh proxy URL used when `browserRefreshMode='server-proxy'`. */
867
- refreshProxyURL?: string;
868
- }
869
- type BrowserRefreshMode = 'direct' | 'server-proxy' | 'none';
870
- declare const ErrOAuthCORSBlocked: "oauth_cors_blocked";
871
- declare const ErrRefreshProxyFailed: "refresh_proxy_failed";
872
- declare const ErrTokenExpired: "token_expired";
873
- interface Deferred<T> {
874
- promise: Promise<T>;
875
- resolve: (v: T) => void;
876
- reject: (e: unknown) => void;
877
- }
878
- /**
879
- * WebSocket 状态 — 内部使用, 实际方法由 ws.ts mixin 提供
880
- * 留作 forward declaration, 避免循环依赖
881
- */
882
- interface WSState {
883
- connected: boolean;
884
- [key: string]: any;
885
- }
886
- /**
887
- * Acosmi nexus-v4 统一 API 客户端
888
- *
889
- * 覆盖全域 API: 模型/权益/商城/钱包/技能/工具/WebSocket
890
- * 自动处理 token 刷新, 所有 API 调用线程安全 (基于 Promise chain)
891
- */
892
- declare class Client {
893
- /** SDK 内部使用 — 业务方法 (mixin) 通过 this.* 访问以下字段 */
894
- /** 服务器根地址 (已 trim 尾随 /) */
895
- serverURL: string;
896
- /** Compliance API 根地址 (已 trim 尾随 /); null = 走默认 ${serverURL}/admin-api */
897
- complianceBaseURL: string | null;
898
- /** OAuth metadata profile — 刷新 token 时发现 metadata 用 (默认 'desktop') */
899
- oauthMetadataProfile: OAuthMetadataProfile;
900
- /** Browser Web OAuth refresh strategy (default 'direct') */
901
- browserRefreshMode: BrowserRefreshMode;
902
- /** Same-origin refresh proxy URL for browserRefreshMode='server-proxy' */
903
- refreshProxyURL: string | null;
904
- /** OAuth metadata (lazy loaded) */
905
- meta: ServerMetadata | null;
906
- /** 当前 token (内存) */
907
- tokens: TokenSet | null;
908
- /** token 持久化 */
909
- store: TokenStore;
910
- /** fetch 实现 (默认 globalThis.fetch) */
911
- fetchImpl: typeof fetch;
912
- /** 互斥锁 (TS 用 Promise chain 替代 sync.Mutex) */
913
- private mu;
914
- /** WebSocket 状态 (实际方法由 ws.ts mixin 维护) */
915
- ws: WSState | null;
916
- /** v0.15.1: token 就绪等待机制 — login 成功后 resolve, 等待方解除阻塞 */
917
- tokenReady: Deferred<void>;
918
- /** Login 进行中 — 等待方需等而非 fail-fast */
919
- loginInFlight: boolean;
920
- /** 防止 tokenReady 被多次 resolve (替代 Go sync.Once) */
921
- private tokenReadyResolved;
922
- /** 模型能力缓存 (CrabCode 扩展) */
923
- modelCache: ManagedModel[];
924
- modelCacheTimeMs: number;
925
- /** sanitize-bridge 配置 (默认禁用) */
926
- defensiveCfg: MinimalSanitizeConfig | null;
927
- autoStripEphemeral: boolean;
928
- /** L6 (v0.15): 重试策略. null = 禁用 (v0.14.1 行为) */
929
- retryPolicy: Required<RetryPolicy> | null;
930
- /** V29 系数缓存 (TTL 8s, listCoefficients 内部用) */
931
- coefCacheData: ModelCoefficient[] | null;
932
- coefCacheTimeMs: number;
933
- /** 串行化锁 (替代 Go sync.Mutex) */
934
- private coefMu;
935
- constructor(cfg?: Config);
645
+ declare class Client {
646
+ /** SDK 内部使用 — 业务方法 (mixin) 通过 this.* 访问以下字段 */
647
+ /** 服务器根地址 ( trim 尾随 /) */
648
+ serverURL: string;
649
+ /** Compliance API 根地址 ( trim 尾随 /); null = 走默认 ${serverURL}/admin-api */
650
+ complianceBaseURL: string | null;
651
+ /** OAuth metadata profile 刷新 token 时发现 metadata 用 (默认 'desktop') */
652
+ oauthMetadataProfile: OAuthMetadataProfile;
653
+ /** Browser Web OAuth refresh strategy (default 'direct') */
654
+ browserRefreshMode: BrowserRefreshMode;
655
+ /** Same-origin refresh proxy URL for browserRefreshMode='server-proxy' */
656
+ refreshProxyURL: string | null;
657
+ /** OAuth metadata (lazy loaded) */
658
+ meta: ServerMetadata | null;
659
+ /** 当前 token (内存) */
660
+ tokens: TokenSet | null;
661
+ /** token 持久化 */
662
+ store: TokenStore;
663
+ /** fetch 实现 (默认 globalThis.fetch) */
664
+ fetchImpl: typeof fetch;
665
+ /** 互斥锁 (TS Promise chain 替代 sync.Mutex) */
666
+ private mu;
667
+ /** WebSocket 状态 (实际方法由 ws.ts mixin 维护) */
668
+ ws: WSState | null;
669
+ /** v0.15.1: token 就绪等待机制 login 成功后 resolve, 等待方解除阻塞 */
670
+ tokenReady: Deferred<void>;
671
+ /** Login 进行中 等待方需等而非 fail-fast */
672
+ loginInFlight: boolean;
673
+ /** 防止 tokenReady 被多次 resolve (替代 Go sync.Once) */
674
+ private tokenReadyResolved;
675
+ /** 模型能力缓存 (CrabCode 扩展) */
676
+ modelCache: ManagedModel[];
677
+ modelCacheTimeMs: number;
678
+ /** sanitize-bridge 配置 (默认禁用) */
679
+ defensiveCfg: MinimalSanitizeConfig | null;
680
+ autoStripEphemeral: boolean;
681
+ /** L6 (v0.15): 重试策略. null = 禁用 (v0.14.1 行为) */
682
+ retryPolicy: Required<RetryPolicy> | null;
683
+ /** V29 系数缓存 (TTL 8s, listCoefficients 内部用) */
684
+ coefCacheData: ModelCoefficient[] | null;
685
+ coefCacheTimeMs: number;
686
+ /** 串行化锁 (替代 Go sync.Mutex) */
687
+ private coefMu;
688
+ constructor(cfg?: Config);
936
689
  /**
937
690
  * 异步初始化 (从 store 加载已有 token)
938
691
  * 替代 Go NewClient (Go 同步 IO, TS 必须 async)
@@ -1147,563 +900,2431 @@ declare class Client {
1147
900
  body?: string;
1148
901
  }, signal?: AbortSignal): Promise<Response>;
1149
902
  }
1150
-
1151
- declare module '@acosmi/sdk-ts' {
1152
- interface Client {
1153
- /** SDK-facing 时间章与电子证据 / 合同签署能力。 */
1154
- readonly compliance: ComplianceClient;
1155
- }
903
+
904
+ declare module '@acosmi/sdk-ts' {
905
+ interface Client {
906
+ /**
907
+ * 配置请求前的底线防御 (体积 / deny-list / 深度)。
908
+ * 传空值 {} 关闭 (所有字段为零 = 禁用)。
909
+ * 并发安全, 可在任意时间调用。
910
+ */
911
+ setDefensiveSanitize(cfg: MinimalSanitizeConfig): void;
912
+ /**
913
+ * 开启后, 每次请求前 SDK 会从 rawMessages 中剥除带 acosmi_ephemeral:true 标记的 block,
914
+ * 并联动剥除引用已剥 tool_use 的 tool_result, 避免 provider 报 "tool_use_id 不存在".
915
+ *
916
+ * 标记来源: 网关在响应 content_block_start 中 in-band 注入; 消费者把上一轮 assistant
917
+ * 回复原样拼回 history 即可触发剥离。
918
+ */
919
+ setAutoStripEphemeralHistory(on: boolean): void;
920
+ /**
921
+ * 在 buildChatRequest 开头调用, 把配置化的防御策略应用到 req。
922
+ * 未配置时立即返回, 零开销。
923
+ *
924
+ * 失败时抛错 — 调用方应放弃本次请求。
925
+ */
926
+ applyRequestSanitizers(req: ChatRequest): void;
927
+ }
928
+ }
929
+
930
+ /** 下载限流错误 (429) */
931
+ declare class RateLimitError extends Error {
932
+ retryAfter: string;
933
+ raw: string;
934
+ constructor(message: string, retryAfter: string, raw: string);
935
+ }
936
+ /**
937
+ * API 业务层错误 (HTTP 200 但 code != 0)
938
+ * tk-dist 代理透传 yudao 响应, HTTP 状态码为 200, 业务错误在 JSON code 字段
939
+ */
940
+ declare class BusinessError extends Error {
941
+ code: number;
942
+ constructor(code: number, message: string);
943
+ }
944
+ /**
945
+ * 订单到达非成功终态 (FAILED/CANCELLED/CLOSED/EXPIRED/REFUNDED)
946
+ * waitForPayment 在订单终态为非成功时抛此错误
947
+ */
948
+ declare class OrderTerminalError extends Error {
949
+ orderId: string;
950
+ status: string;
951
+ constructor(orderId: string, status: string);
952
+ }
953
+ /**
954
+ * 模型缓存未命中且 listModels 刷新后仍未找到。
955
+ *
956
+ * 历史上 getCachedModel miss 时硬返 ManagedModel{provider:"anthropic"} 占位,
957
+ * 导致未预热场景下的 chat 请求按 AnthropicAdapter 编码, 被发到错误端点。
958
+ * v0.13.x 改为 miss → listModels 自动刷新一次; 仍 miss → 抛此错误。
959
+ */
960
+ declare class ModelNotFoundError extends Error {
961
+ modelId: string;
962
+ constructor(modelId: string);
963
+ }
964
+ /**
965
+ * 结构化 HTTP 非 2xx 错误.
966
+ *
967
+ * 用 instanceof 提取:
968
+ * try { ... } catch (e) {
969
+ * if (e instanceof HTTPError && e.statusCode === 429) { ... }
970
+ * }
971
+ */
972
+ declare class HTTPError extends Error {
973
+ statusCode: number;
974
+ /** anthropic.error.type / openai.error.type, 缺失为空 */
975
+ type: string;
976
+ /** Retry-After 头解析的秒数, 0 表示未提供或解析失败 */
977
+ retryAfter: number;
978
+ /** 原始响应体 (截断到 maxErrorBodySize) */
979
+ body: string;
980
+ constructor(statusCode: number, opts?: {
981
+ type?: string;
982
+ message?: string;
983
+ retryAfter?: number;
984
+ body?: string;
985
+ });
986
+ }
987
+ /**
988
+ * 结构化网络层错误 (传输失败, 区别于上游业务错误).
989
+ *
990
+ * 包装 fetch 抛出的错误 — 含 timeout / EOF / connection refused / DNS 失败等.
991
+ * retry policy: isTimeout / isEOF 任一为 true → 默认可重试.
992
+ */
993
+ declare class NetworkError extends Error {
994
+ /** 操作描述, e.g. "POST /v1/messages" */
995
+ op: string;
996
+ /** 请求 URL (脱敏后) */
997
+ url: string;
998
+ cause?: unknown;
999
+ timeout: boolean;
1000
+ eof: boolean;
1001
+ constructor(op: string, url: string, cause: unknown, opts?: {
1002
+ timeout?: boolean;
1003
+ eof?: boolean;
1004
+ });
1005
+ isTimeout(): boolean;
1006
+ isEOF(): boolean;
1007
+ }
1008
+ /**
1009
+ * 流式失败事件的结构化表示。
1010
+ *
1011
+ * 由 gateway 的 `managed_model_stream_failed` 事件解析得到。客户端可通过
1012
+ * instanceof 提取并按 code/retryable 决策。
1013
+ */
1014
+ declare class StreamError extends Error {
1015
+ /** 例: "empty_response" / "rate_limit" / "overloaded" / "" */
1016
+ code: string;
1017
+ /** 例: "provider" / "settlement" */
1018
+ stage: string;
1019
+ /** 用户友好提示 (中文); 历史字段, 与 rawError 区分 */
1020
+ userMessage: string;
1021
+ /** gateway 原始 error 字符串 */
1022
+ rawError: string;
1023
+ /** 客户端是否值得重试 */
1024
+ retryable: boolean;
1025
+ constructor(opts?: {
1026
+ code?: string;
1027
+ stage?: string;
1028
+ message?: string;
1029
+ rawError?: string;
1030
+ retryable?: boolean;
1031
+ });
1032
+ }
1033
+
1034
+ /** nexus-v4 标准响应。兼容 yudao 格式 (msg) 和 nexus-v4 格式 (message) */
1035
+ interface APIResponse<T> {
1036
+ code: number;
1037
+ message?: string;
1038
+ msg?: string;
1039
+ data: T;
1040
+ }
1041
+ /** 优先返回 message, 降级到 msg (兼容 yudao 透传) */
1042
+ declare function apiResponseGetMessage<T>(r: APIResponse<T>): string;
1043
+ /** 检查业务层错误码 — code != 0 时抛 BusinessError */
1044
+ declare function apiResponseBusinessError<T>(r: APIResponse<T>): BusinessError | null;
1045
+ /** yudao 分页响应格式 (tk-dist 代理透传) */
1046
+ interface YudaoPageResult<T> {
1047
+ list: T[];
1048
+ total: number;
1049
+ }
1050
+
1051
+ /** 排序方向。wire 上为小写字符串。 */
1052
+ type SortDirection = 'asc' | 'desc';
1053
+ /**
1054
+ * 跨域统一分页【请求】参数。
1055
+ *
1056
+ * 既有域(billing / compliance / skills / notifications)各自内联了
1057
+ * `page` / `pageNo` + `pageSize`,互不一致;本类型是为后续新命名空间
1058
+ * (平台控制面 / `compliance.list*`)提供的统一形态。
1059
+ *
1060
+ * 字段全部可选 —— 调用方省略时由服务端取默认页;排序字段白名单由各命名
1061
+ * 空间各自的 API 文档约定,SDK 不在客户端做字段校验。
1062
+ */
1063
+ interface PageRequest {
1064
+ /** 1-based 页码。 */
1065
+ pageNo?: number;
1066
+ /** 每页条数。 */
1067
+ pageSize?: number;
1068
+ /** 排序字段名(领域字段,由各命名空间文档约定白名单)。 */
1069
+ sortBy?: string;
1070
+ /** 排序方向;省略时由服务端决定默认值。 */
1071
+ sortDirection?: SortDirection;
1072
+ }
1073
+ /**
1074
+ * 跨域统一分页【结果】。
1075
+ *
1076
+ * **刻意做成 `YudaoPageResult<T>` 的别名** —— 全 SDK 单一分页结果结构
1077
+ * `{ list, total }`。新命名空间统一用 `PageResult<T>` 这个对外名,
1078
+ * 底层与 tk-dist 代理透传的 yudao 分页结构完全等价、零转换、零双标准。
1079
+ */
1080
+ type PageResult<T> = YudaoPageResult<T>;
1081
+
1082
+ type ComplianceProviderRequestStatus = 'PENDING' | 'SUCCESS' | 'FAILED' | 'UNKNOWN' | 'RETRYING';
1083
+ interface ProviderRequestStatusView {
1084
+ id: number;
1085
+ status: ComplianceProviderRequestStatus | string;
1086
+ /** SUCCESS / FAILED 终态。 */
1087
+ terminal: boolean;
1088
+ /** 当前状态是否允许 SDK 安全重试请求(仅对 RETRYING 为 true)。 */
1089
+ retryable: boolean;
1090
+ businessNo?: string | null;
1091
+ contractNo?: string | null;
1092
+ sealId?: string | null;
1093
+ attemptCount?: number | null;
1094
+ reconciliationStatus?: string | null;
1095
+ nextRetryAt?: string | null;
1096
+ requestedAt?: string | null;
1097
+ respondedAt?: string | null;
1098
+ }
1099
+
1100
+ /** 统一操作关联键。贯通控制台 / API / MCP / CrabCode / scheduler 各来源。 */
1101
+ type OperationId = string;
1102
+ /**
1103
+ * 操作来源。开放联合 —— 平台侧 5 种固定值,合规域可追加自定义来源字符串。
1104
+ * `(string & {})` 在保留 IDE 字面量补全的同时不拒绝未知来源(后端保留新增空间)。
1105
+ */
1106
+ type OperationSource = 'console' | 'api' | 'scheduler' | 'crabcode' | 'mcp' | (string & NonNullable<unknown>);
1107
+ /**
1108
+ * 操作状态机。开放联合,后端保留新增空间。
1109
+ *
1110
+ * 与 `compliance/status.ts` 的 `ComplianceEnvelopeStatus` 等领域状态【正交】:
1111
+ * 领域状态描述某个履约对象的业务态,`OperationStatus` 描述【一次操作】本身
1112
+ * 的执行进度。
1113
+ */
1114
+ type OperationStatus = 'pending' | 'running' | 'retrying' | 'awaiting_callback' | 'awaiting_verify' | 'succeeded' | 'failed' | 'canceled' | 'unknown' | (string & NonNullable<unknown>);
1115
+ /**
1116
+ * 本地 verify 状态(§6.4)。
1117
+ *
1118
+ * provider success 仅表示 provider request 终态;时间章 / 签署 / 验签 /
1119
+ * 证据包 / 报告发布须经后端本地 verify / evidence chain verify。`VerifyStatus`
1120
+ * 与 provider 状态是【两个独立维度】,operation projection 必须分别展示
1121
+ * (local verify failed → 业务 failed,不 billing settle)。
1122
+ */
1123
+ type VerifyStatus = 'pending' | 'verified' | 'failed' | 'skipped' | 'unknown' | (string & NonNullable<unknown>);
1124
+ /**
1125
+ * 幂等键。作用域 = tenant + principal/client + action + product;同 key 同
1126
+ * canonical request 返回原结果,同 key 异 request 拒绝(§6.3 / §2 边界 9)。
1127
+ * SDK 写接口经 `IdempotencyKeyHeader` 透传,调用方必须【持久化】key。
1128
+ */
1129
+ type IdempotencyKey = string;
1130
+ /** 幂等键 HTTP header 名 —— 全 SDK 写接口的单一真相源。 */
1131
+ declare const IdempotencyKeyHeader: "Idempotency-Key";
1132
+ /**
1133
+ * Provider request 状态。
1134
+ *
1135
+ * 复核约束(§9.4 勘误):**不另造同名近似类型** —— 直接复用
1136
+ * `compliance/provider/types.ts` 既有 `ComplianceProviderRequestStatus`
1137
+ * (`PENDING` / `SUCCESS` / `FAILED` / `UNKNOWN` / `RETRYING`)。
1138
+ */
1139
+ type ProviderRequestStatus = ComplianceProviderRequestStatus;
1140
+
1141
+ /**
1142
+ * SDK 内部 symbolic key;用于代码分支判断与文档。**不是 wire contract**。
1143
+ */
1144
+ type ComplianceErrorKey = 'COMPLIANCE_UNAUTHORIZED' | 'COMPLIANCE_INSUFFICIENT_SCOPE' | 'COMPLIANCE_STEP_UP_REQUIRED' | 'COMPLIANCE_TOKEN_INVALID' | 'SUBJECT_SNAPSHOT_REQUIRED' | 'SUBJECT_SNAPSHOT_NOT_FOUND' | 'SUBJECT_SNAPSHOT_TENANT_MISMATCH' | 'EVIDENCE_ASSET_NOT_FOUND' | 'EVIDENCE_ASSET_HASH_MISMATCH' | 'EVIDENCE_ASSET_PAYLOAD_REQUIRED' | 'TIMESTAMP_TOKEN_NOT_FOUND' | 'TIMESTAMP_PROVIDER_FAILED' | 'TIMESTAMP_PROVIDER_UNKNOWN' | 'TIMESTAMP_LOCAL_VERIFY_FAILED' | 'TIMESTAMP_PROVIDER_NOT_AVAILABLE' | 'EVIDENCE_PACKAGE_NOT_FOUND' | 'EVIDENCE_PACKAGE_TIMESTAMP_REQUIRED' | 'EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH' | 'REPORT_NOT_FOUND' | 'REPORT_ALREADY_PUBLISHED' | 'REPORT_DRAFT_REQUIRED' | 'EVIDENCE_VERIFY_TARGET_REQUIRED' | 'EVIDENCE_VERIFY_TARGET_NOT_FOUND' | 'PROVIDER_REQUEST_UNKNOWN_NO_RETRY' | 'PROVIDER_CALLBACK_SOURCE_INVALID' | 'PROVIDER_NOT_CONFIGURED' | 'PROVIDER_REQUEST_NOT_FOUND' | 'PROVIDER_REQUEST_IDEMPOTENCY_REQUIRED' | 'PROVIDER_REQUEST_STATUS_NOT_TERMINAL' | 'ENVELOPE_NOT_FOUND' | 'ENVELOPE_TENANT_MISMATCH' | 'ENVELOPE_STATE_NOT_ALLOWED' | 'ENVELOPE_GATE_CLOSED' | 'CONTRACT_NOT_FOUND' | 'CONTRACT_HASH_MISMATCH' | 'PROVIDER_AUTHORIZATION_NOT_CONFIRMED' | 'ENVELOPE_EVIDENCE_NOT_READY' | 'SEAL_ASSET_NOT_FOUND' | 'SEAL_APPROVAL_NOT_FOUND' | 'SEAL_APPROVAL_STATE_NOT_APPROVED' | 'SEAL_APPROVAL_EXPIRED' | 'SEAL_APPROVAL_ALREADY_USED' | 'SEAL_APPROVAL_NONCE_USED' | 'SEAL_APPROVAL_SEAL_MISMATCH' | 'SEAL_APPROVAL_LOCATION_MISMATCH' | 'SEAL_APPROVAL_TRANSACTOR_MISMATCH' | 'SEAL_APPROVAL_CONTRACT_HASH_MISMATCH' | 'SEAL_APPROVAL_INVALID_TRANSITION' | 'SEAL_USE_ALREADY_CONSUMED' | 'AUDIT_CHAIN_TAMPER_DETECTED' | 'BILLING_COMMIT_REQUIRES_LOCAL_VERIFY' | 'BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS' | 'BILLING_CALLBACK_CANNOT_COMMIT' | 'BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE' | 'BILLING_S2S_FORBIDDEN' | 'UNKNOWN_COMPLIANCE_ERROR';
1145
+ /** 单个错误的 SDK 视图。 */
1146
+ interface ComplianceErrorInfo {
1147
+ /** Java numeric error code (wire contract)。 */
1148
+ code: number;
1149
+ /** 服务端原始 message(中文,可变);仅用于日志/展示。 */
1150
+ message: string;
1151
+ /** SDK 分支判断用 symbolic key。 */
1152
+ key: ComplianceErrorKey;
1153
+ /** 是否安全自动重试 — compliance 写接口几乎全为 false。 */
1154
+ retryable: boolean;
1155
+ /** 是否已经是终态 — 用户必须用新 idempotency-key 重新发起。 */
1156
+ terminal: boolean;
1157
+ /** 高风险动作需要 step-up / introspection。 */
1158
+ stepUpRequired: boolean;
1159
+ }
1160
+ /**
1161
+ * 把一个 BusinessError 分类为 compliance 视图。
1162
+ * 非 compliance 段位的错误码会回退到 UNKNOWN_COMPLIANCE_ERROR,调用方应该当作业务错误处理。
1163
+ */
1164
+ declare function classifyComplianceError(err: BusinessError): ComplianceErrorInfo;
1165
+ /**
1166
+ * 判断 BusinessError 是否属于 compliance 段位(1-031-xxx-xxx)。
1167
+ * 不在段位的错误码可能来自其它 yudao 模块,按通用业务错误处理即可。
1168
+ */
1169
+ declare function isComplianceBusinessError(err: BusinessError): boolean;
1170
+
1171
+ /**
1172
+ * 失败补救原因。开放枚举的【封闭】部分 —— 这 11 个值覆盖 §6.6 要求的全集。
1173
+ *
1174
+ * 其中 `gate_closed` / `step_up_required` / `tenant_mismatch` /
1175
+ * `insufficient_scope` 与既有错误码登记表同名概念一一对应(见下方映射表),
1176
+ * 不是新造的码。
1177
+ */
1178
+ type RetryAdviceReason = 'unknown' | 'retrying' | 'failed' | 'gate_closed' | 'step_up_required' | 'tenant_mismatch' | 'insufficient_scope' | 'quota_exceeded' | 'provider_timeout' | 'local_verify_failed' | 'billing_preflight_failed';
1179
+ /** `RetryAdviceReason` 全集(11 项)—— 供迭代 / 校验使用。 */
1180
+ declare const RETRY_ADVICE_REASONS: readonly RetryAdviceReason[];
1181
+ /**
1182
+ * 失败补救建议统一模型(§6.6)。
1183
+ *
1184
+ * 高风险 / 收费动作失败后,后端 operation projection 产出本结构告诉调用方
1185
+ * 「能不能重试、要不要换幂等键、要不要人工介入」。
1186
+ */
1187
+ interface RetryAdvice {
1188
+ /** 是否值得【自动】重试。compliance 写接口几乎恒为 false(双扣红线)。 */
1189
+ retryable: boolean;
1190
+ /** 建议的重试等待时长(秒);与 `HTTPError.retryAfter` 单位一致。 */
1191
+ retryAfter?: number;
1192
+ /**
1193
+ * 重试时是否必须沿用【同一】幂等键。
1194
+ * 同 key 同 canonical request → 服务端返回原结果(对账语义);
1195
+ * 终态错误须改用【新】幂等键重新发起(§6.3)。
1196
+ */
1197
+ sameIdempotencyKeyRequired: boolean;
1198
+ /** 是否需要人工介入(重新登录 / step-up / 联系支持),不能纯自动恢复。 */
1199
+ manualActionRequired: boolean;
1200
+ /** 归一化失败原因。 */
1201
+ reason: RetryAdviceReason;
1202
+ /** 面向终端用户的提示文案(调用方可用自有 copy 表覆盖)。 */
1203
+ userMessage?: string;
1204
+ /** 面向开发者的诊断信息(如服务端原始 message)。 */
1205
+ developerMessage?: string;
1206
+ /** 支持工单关联码(如 `compliance:1031004004`)。 */
1207
+ supportCode?: string;
1208
+ }
1209
+ /** SDK compliance 符号 key → `RetryAdviceReason`。未知 key 兜底 `unknown`。 */
1210
+ declare function retryReasonForComplianceKey(key: ComplianceErrorKey): RetryAdviceReason;
1211
+ /** Go OAuth 标准错误字符串 → `RetryAdviceReason`。未登记的兜底 `unknown`。 */
1212
+ declare function retryReasonForOAuthError(oauthError: string): RetryAdviceReason;
1213
+ /**
1214
+ * 把 `ComplianceErrorInfo`(compliance/errors.ts `classifyComplianceError` 的产出)
1215
+ * 投影为统一 `RetryAdvice`。
1216
+ *
1217
+ * 语义:
1218
+ * - `retryable` 直接透传 `info.retryable`(compliance 写接口恒 false)。
1219
+ * - 终态错误(`info.terminal`)→ 须改用【新】幂等键 →
1220
+ * `sameIdempotencyKeyRequired=false`、`manualActionRequired=true`。
1221
+ * - step-up 错误 → 重新做 OAuth introspection 后用【同一】幂等键重试 →
1222
+ * `sameIdempotencyKeyRequired=true`、`manualActionRequired=true`。
1223
+ * - 其余(非终态、非 step-up)→ 沿用同一幂等键对账重发。
1224
+ *
1225
+ * 不读、不写 `ComplianceErrorInfo` 以外的状态;入参不被 mutate。
1226
+ */
1227
+ declare function complianceErrorToRetryAdvice(info: ComplianceErrorInfo): RetryAdvice;
1228
+
1229
+ /**
1230
+ * 租户轻量引用。
1231
+ *
1232
+ * 完整租户详情(状态 / 类型 / 产品开通 / 主体类型 / 地区 / 组织配置)见
1233
+ * 后续 `tenant` 命名空间。
1234
+ */
1235
+ interface TenantRef {
1236
+ tenantId: string;
1237
+ /** 展示名;后端可省略。 */
1238
+ name?: string;
1239
+ }
1240
+ /**
1241
+ * Principal(操作主体)轻量引用。
1242
+ *
1243
+ * 完整 principal 视图(脱敏联系方式 / 角色 / scope / 认证方式 / token jti /
1244
+ * 登录来源)见后续 `iam` 命名空间。前端【不自解 JWT】推断身份(§1.1 复核
1245
+ * 边界)—— 一律由 SDK 暴露稳定 principal。
1246
+ */
1247
+ interface PrincipalRef {
1248
+ principalId: string;
1249
+ /** 关联用户 id;与 `principalId` 可能不同(同一用户多 principal)。 */
1250
+ userId?: string;
1251
+ /** 所属租户 id。 */
1252
+ tenantId?: string;
1253
+ /** 展示名;后端可省略。 */
1254
+ displayName?: string;
1255
+ }
1256
+ /**
1257
+ * API client 轻量引用。
1258
+ *
1259
+ * 完整 API client 治理(CRUD / secret 轮换 / 回调域名 / IP 白名单 / 调用
1260
+ * 日志)见对外鉴权层独立计划范围 —— 本期不实现(用户决策 2026-05-22)。
1261
+ */
1262
+ interface ApiClientRef {
1263
+ clientId: string;
1264
+ /** 展示名;后端可省略。 */
1265
+ name?: string;
1266
+ }
1267
+
1268
+ /**
1269
+ * 高风险 / 收费动作的 gate 状态机(§U-6)。开放联合,后端保留新增空间。
1270
+ *
1271
+ * `gates.ts`(csign workbench)拿不到能力时 fail-closed 返回 `unknown` —
1272
+ * 与本枚举的 `unknown` 一致。
1273
+ */
1274
+ type FeatureGateState = 'executable' | 'scope_missing' | 'not_provisioned' | 'quota_exceeded' | 'step_up_required' | 'gate_closed' | 'unknown' | (string & NonNullable<unknown>);
1275
+ /** 配额快照。`FeatureGateStatus.quota` 与 `BillingPreflightResult` 复用。 */
1276
+ interface GateQuota {
1277
+ /** 配额上限。 */
1278
+ limit?: number;
1279
+ /** 已用量。 */
1280
+ used?: number;
1281
+ /** 剩余量。 */
1282
+ remaining?: number;
1283
+ /** 配额单位(如 `etu` / `count`);后端可省略。 */
1284
+ unit?: string;
1285
+ }
1286
+ /**
1287
+ * step-up(高风险动作二次验证)状态(§6.1)。
1288
+ *
1289
+ * 字段形态先行沉淀;step-up 发起 / 校验的【后端运行期能力】随对外鉴权层
1290
+ * 计划本期不实施。
1291
+ */
1292
+ interface StepUpStatus {
1293
+ /** 当前动作是否要求 step-up。 */
1294
+ required: boolean;
1295
+ /** 是否已满足(已完成且未过期)。 */
1296
+ satisfied: boolean;
1297
+ /** step-up 方式(如 `webauthn` / `oauth_introspection`);后端可省略。 */
1298
+ method?: string;
1299
+ /** 满足态过期时间(ISO 8601);未满足时省略。 */
1300
+ expiresAt?: string;
1301
+ /** 未满足 / 失败原因;满足时省略。 */
1302
+ reason?: string;
1303
+ }
1304
+ /**
1305
+ * gate / capability 查询结果(§U-6)。
1306
+ *
1307
+ * 高风险动作(signEnvelope / createH5SigningUrl / publishReport /
1308
+ * approveSealApproval / executeSealUse / claimLeadWithConflictOverride)执行前
1309
+ * 查询本结构,区分「可执行 / scope 缺失 / 未开通 / quota 不足 / 需 step-up /
1310
+ * gate closed」。拿不到时必须 fail-closed(`executable=false`,§2 边界 7)。
1311
+ */
1312
+ interface FeatureGateStatus {
1313
+ /** 最终是否可执行。fail-closed:拿不到能力时为 false。 */
1314
+ executable: boolean;
1315
+ /** 不可执行的具体状态。 */
1316
+ state: FeatureGateState;
1317
+ /** 缺失 / 所需 OAuth scope。 */
1318
+ requiredScopes?: string[];
1319
+ /** 是否需要 step-up。 */
1320
+ requiredStepUp?: boolean;
1321
+ /** 缺失的 entitlement / feature 标识。 */
1322
+ missingEntitlements?: string[];
1323
+ /** 配额快照。 */
1324
+ quota?: GateQuota;
1325
+ /** 人类可读原因(诊断 / 展示)。 */
1326
+ reason?: string;
1327
+ /** 失败补救建议(叠加层,见 retry-advice.ts)。 */
1328
+ retryAdvice?: RetryAdvice;
1329
+ /** 关联 operation / preflight id。 */
1330
+ operationId?: OperationId;
1331
+ }
1332
+ /**
1333
+ * 收费 / 高风险动作的 billing preflight 结果(§4.4 / §4.5)。
1334
+ *
1335
+ * 在动作执行【前】返回可执行性、预估扣费、所需 step-up / scopes。金额字段为
1336
+ * `string`(json.Number 端口,避免 JS number 精度损失 —— 金融安全红线)。
1337
+ */
1338
+ interface BillingPreflightResult {
1339
+ /** 是否可执行(含 quota / entitlement / gate 综合判定)。 */
1340
+ executable: boolean;
1341
+ /** 预估扣费金额;`string` 表示,避免浮点精度丢失。 */
1342
+ estimatedCharge?: string;
1343
+ /** 计费单位 / 币种(如 `etu` / `CNY`)。 */
1344
+ currency?: string;
1345
+ /** 所需 OAuth scope。 */
1346
+ requiredScopes?: string[];
1347
+ /** 是否需要 step-up。 */
1348
+ requiredStepUp?: boolean;
1349
+ /** 配额快照。 */
1350
+ quota?: GateQuota;
1351
+ /** 失败补救建议。 */
1352
+ retryAdvice?: RetryAdvice;
1353
+ /** preflight 关联 id —— 后续真实扣费动作回填以串联 hold/settle/release。 */
1354
+ preflightId?: string;
1355
+ /** 不可执行原因(诊断 / 展示)。 */
1356
+ reason?: string;
1357
+ }
1358
+
1359
+ declare const ScopeAI = "ai";
1360
+ declare const ScopeSkills = "skills";
1361
+ declare const ScopeAccount = "account";
1362
+ /** @deprecated 旧细粒度 scope, 保留向后兼容, 新代码请用分组 scope */
1363
+ declare const ScopeModels = "models";
1364
+ /** @deprecated */
1365
+ declare const ScopeModelsChat = "models:chat";
1366
+ /** @deprecated */
1367
+ declare const ScopeEntitlements = "entitlements";
1368
+ /** @deprecated */
1369
+ declare const ScopeTokenPackages = "token-packages";
1370
+ /** @deprecated */
1371
+ declare const ScopeSkillStore = "skill_store";
1372
+ /** @deprecated */
1373
+ declare const ScopeTools = "tools";
1374
+ /** @deprecated */
1375
+ declare const ScopeToolsExecute = "tools:execute";
1376
+ /** @deprecated */
1377
+ declare const ScopeWallet = "wallet";
1378
+ /** @deprecated */
1379
+ declare const ScopeWalletReadonly = "wallet:readonly";
1380
+ /** @deprecated */
1381
+ declare const ScopeProfile = "profile";
1382
+ /** 全部分组 scope (推荐) */
1383
+ declare function allScopes(): string[];
1384
+ /** 模型服务相关 scope */
1385
+ declare function modelScopes(): string[];
1386
+ /** 商城/钱包 scope */
1387
+ declare function commerceScopes(): string[];
1388
+ /** 技能/工具 scope */
1389
+ declare function skillScopes(): string[];
1390
+
1391
+ interface OpenAIChatResponse {
1392
+ id: string;
1393
+ /** "chat.completion" */
1394
+ object: string;
1395
+ model: string;
1396
+ choices: OpenAIChatChoice[];
1397
+ usage: OpenAIUsage;
1398
+ }
1399
+ interface OpenAIChatChoice {
1400
+ index: number;
1401
+ message: OpenAIChatMessage;
1402
+ /** "stop", "tool_calls", "length" */
1403
+ finish_reason: string;
1404
+ }
1405
+ interface OpenAIChatMessage {
1406
+ role: string;
1407
+ content: string;
1408
+ tool_calls?: OpenAIToolCall[];
1409
+ /** GLM/DeepSeek thinking */
1410
+ reasoning_content?: string;
1411
+ }
1412
+ interface OpenAIToolCall {
1413
+ id: string;
1414
+ /** "function" */
1415
+ type: string;
1416
+ function: OpenAIFunctionCall;
1417
+ }
1418
+ interface OpenAIFunctionCall {
1419
+ name: string;
1420
+ arguments: string;
1421
+ }
1422
+ interface OpenAIUsage {
1423
+ prompt_tokens: number;
1424
+ completion_tokens: number;
1425
+ total_tokens: number;
1426
+ }
1427
+ /** OpenAI SSE delta 格式 */
1428
+ interface OpenAIStreamChunk {
1429
+ id: string;
1430
+ /** "chat.completion.chunk" */
1431
+ object: string;
1432
+ choices: OpenAIStreamChoice[];
1433
+ usage?: OpenAIUsage;
1434
+ }
1435
+ interface OpenAIStreamChoice {
1436
+ index: number;
1437
+ delta: OpenAIStreamDelta;
1438
+ finish_reason: string | null;
1439
+ }
1440
+ interface OpenAIStreamDelta {
1441
+ role?: string;
1442
+ content?: string;
1443
+ reasoning_content?: string;
1444
+ tool_calls?: OpenAIStreamToolCall[];
1445
+ }
1446
+ interface OpenAIStreamToolCall {
1447
+ index: number;
1448
+ id?: string;
1449
+ type?: string;
1450
+ function: OpenAIFunctionCall;
1451
+ }
1452
+
1453
+ /**
1454
+ * 判断 ManagedModel 是否声明支持指定输入模态.
1455
+ *
1456
+ * 语义:
1457
+ * - model 为 null/undefined → false
1458
+ * - model.inputModalities 缺失或非数组 → false (保守, 未声明不当支持)
1459
+ * - 大小写敏感 (上游契约即小写 'text' | 'image')
1460
+ */
1461
+ declare function modelSupportsInputModality(model: ManagedModel | null | undefined, modality: InputModality): boolean;
1462
+ /** 等价 modelSupportsInputModality(model, 'image') — 调用方常见快捷判定. */
1463
+ declare function modelSupportsImageInput(model: ManagedModel | null | undefined): boolean;
1464
+ /**
1465
+ * 在 catalog 中按 catalog 顺序查找首个支持指定模态的模型.
1466
+ *
1467
+ * 选择规则:
1468
+ * 1. isEnabled !== false (默认开, 显式 false 才剔除)
1469
+ * 2. inputModalities 包含指定模态
1470
+ * 3. 命中后按 catalog 顺序返回第一个; 未命中返 null
1471
+ *
1472
+ * 注意: 该 helper 不读 isDefault, 调用方需要 "默认优先" 请用
1473
+ * findDesktopVisualUnderstandingModel 或自行排序.
1474
+ */
1475
+ declare function findFirstModelByInputModality(models: ManagedModel[], modality: InputModality): ManagedModel | null;
1476
+ /**
1477
+ * 在 catalog 中选出最适合做 "桌面视觉理解 sidecar" 的模型.
1478
+ *
1479
+ * 设计目的: CrabCode desktop automation 链路里, 主模型不一定多模态;
1480
+ * 截图先送 sidecar 解析成结构化 UI 描述, 再喂主模型. 这里选 sidecar 模型
1481
+ * 严格走运营标注的 supports_desktop_visual_understanding capability, 不靠
1482
+ * 模型名猜.
1483
+ *
1484
+ * 选择规则 (按用户指定顺序):
1485
+ * 1. isEnabled !== false
1486
+ * 2. capabilities.supports_desktop_visual_understanding === true
1487
+ * 3. inputModalities 包含 'image' (必须真能吃图)
1488
+ * 4. 命中集合中优先 isDefault === true; 否则返回 catalog 顺序第一个
1489
+ *
1490
+ * 全部不满足返 null. 调用方收到 null 应:
1491
+ * - 提示用户在管理后台/网关侧开启桌面视觉 sidecar 模型, 或
1492
+ * - 降级停掉依赖截图的工作流, 而不是硬选一个非视觉模型送图.
1493
+ */
1494
+ declare function findDesktopVisualUnderstandingModel(models: ManagedModel[]): ManagedModel | null;
1495
+
1496
+ /** SDK 为单个 content block 缓存的元数据 */
1497
+ interface BlockMeta {
1498
+ type: string;
1499
+ ephemeral: boolean;
1500
+ }
1501
+ /**
1502
+ * 按 Anthropic SSE 事件类型解析 data, 更新 blockTypeMap, 返回 [index, type, ephemeral]。
1503
+ *
1504
+ * 仅当事件为 content_block_start / content_block_delta / content_block_stop
1505
+ * 时返回非空 type; 其他事件返回空 type, 调用方据此判别是否填充 StreamEvent 元数据字段。
1506
+ */
1507
+ declare function extractAnthropicBlockMeta(eventType: string, data: string, blockTypeMap: Map<number, BlockMeta>): [number, string, boolean];
1508
+
1509
+ /** 根据模型能力和请求参数自动组装 beta header 列表 */
1510
+ declare function buildBetas(caps: ModelCapabilities, req: ChatRequest): string[];
1511
+ /** 合并两个字符串数组并去重, 保留顺序 */
1512
+ declare function uniqueMerge(base: string[], extra: string[]): string[];
1513
+
1514
+ declare module '@acosmi/sdk-ts' {
1515
+ interface Client {
1516
+ /** 查询当前用户的权益余额 (聚合) */
1517
+ getBalance(signal?: AbortSignal): Promise<EntitlementBalance>;
1518
+ /** 查询详细余额 (含每条权益明细) */
1519
+ getBalanceDetail(signal?: AbortSignal): Promise<BalanceDetail>;
1520
+ /** 查询当前用户权益列表; status: "ACTIVE" / "EXPIRED" / "" (全部) */
1521
+ listEntitlements(status: string, signal?: AbortSignal): Promise<EntitlementItem[]>;
1522
+ /** 查询核销记录 (分页) */
1523
+ listConsumeRecords(page: number, pageSize: number, signal?: AbortSignal): Promise<ConsumeRecordPage>;
1524
+ /** 领取当月免费额度 — 幂等: 已领取时返回已有权益 */
1525
+ claimMonthlyFree(signal?: AbortSignal): Promise<EntitlementItem>;
1526
+ /** 查询当前用户在指定模型下的剩余 token (raw + ETU) */
1527
+ getByModel(modelID: string, signal?: AbortSignal): Promise<ModelByQuotaResponse>;
1528
+ /** 列出当前用户的全部桶 */
1529
+ listBuckets(signal?: AbortSignal): Promise<ModelBucket[]>;
1530
+ /** 拉取模型系数表; SDK 自带 8s TTL 内存缓存以减小调用风暴. */
1531
+ listCoefficients(signal?: AbortSignal): Promise<ModelCoefficient[]>;
1532
+ /** 手动失效系数缓存 (admin 调价后建议立即调一次) */
1533
+ invalidateCoefficientCache(): void;
1534
+ }
1535
+ }
1536
+
1537
+ declare module '@acosmi/sdk-ts' {
1538
+ interface Client {
1539
+ /** 获取商城流量包列表 (兼容 yudao 分页和直接数组两种格式) */
1540
+ listTokenPackages(signal?: AbortSignal): Promise<TokenPackage[]>;
1541
+ /** 获取流量包详情 */
1542
+ getTokenPackageDetail(packageID: string, signal?: AbortSignal): Promise<TokenPackage>;
1543
+ /** 购买流量包 (创建订单) */
1544
+ buyTokenPackage(packageID: string, payload: PayPayload | null, signal?: AbortSignal): Promise<Order>;
1545
+ /** 查询订单支付状态 */
1546
+ getOrderStatus(orderID: string, signal?: AbortSignal): Promise<OrderStatus>;
1547
+ /** 查询我的订单列表 */
1548
+ listMyOrders(signal?: AbortSignal): Promise<Order[]>;
1549
+ /**
1550
+ * 轮询订单支付状态直到终态
1551
+ * 成功支付返回 status; 终态失败抛 OrderTerminalError
1552
+ * pollIntervalMs <= 0 时默认 2 秒
1553
+ */
1554
+ waitForPayment(orderID: string, pollIntervalMs: number, signal?: AbortSignal): Promise<OrderStatus>;
1555
+ }
1556
+ }
1557
+
1558
+ declare module '@acosmi/sdk-ts' {
1559
+ interface Client {
1560
+ /** 获取钱包统计 (余额/月消费/月充值) */
1561
+ getWalletStats(signal?: AbortSignal): Promise<WalletStats>;
1562
+ /** 获取最近交易记录 */
1563
+ getWalletTransactions(signal?: AbortSignal): Promise<Transaction[]>;
1564
+ }
1565
+ }
1566
+
1567
+ interface SkillStoreItem {
1568
+ id: string;
1569
+ pluginId: string;
1570
+ key: string;
1571
+ name: string;
1572
+ description: string;
1573
+ icon: string;
1574
+ category: string;
1575
+ inputSchema: string;
1576
+ outputSchema: string;
1577
+ timeout: number;
1578
+ retryCount: number;
1579
+ retryDelay: number;
1580
+ version: string;
1581
+ totalCalls: number;
1582
+ avgDurationMs: number;
1583
+ successRate: number;
1584
+ isEnabled: boolean;
1585
+ securityLevel: string;
1586
+ securityScore: number;
1587
+ scope: string;
1588
+ status: string;
1589
+ downloadCount: number;
1590
+ readme: string;
1591
+ tags: string[];
1592
+ author: string;
1593
+ publisherId: string;
1594
+ isPublished: boolean;
1595
+ pluginName: string;
1596
+ pluginIcon: string;
1597
+ updatedAt: string;
1598
+ visibility?: string;
1599
+ certificationStatus?: string;
1600
+ source?: string;
1601
+ }
1602
+ /** 技能商店搜索参数 (非 wire 类型, 用于 client 方法参数) */
1603
+ interface SkillStoreQuery {
1604
+ category?: string;
1605
+ keyword?: string;
1606
+ tag?: string;
1607
+ }
1608
+ /** 技能统计概览 */
1609
+ interface SkillSummary {
1610
+ installed: number;
1611
+ created: number;
1612
+ total: number;
1613
+ storeAvailable: number;
1614
+ }
1615
+ /** 技能商店分页浏览响应 */
1616
+ interface SkillBrowseResponse {
1617
+ items: SkillStoreItem[];
1618
+ total: number;
1619
+ page: number;
1620
+ pageSize: number;
1621
+ }
1622
+ /**
1623
+ * 技能商店列表项(轻量,仅含浏览所需字段)
1624
+ * 配合服务端 fields=minimal 参数使用,响应体积缩减 90%+
1625
+ */
1626
+ interface SkillStoreListItem {
1627
+ id: string;
1628
+ key: string;
1629
+ name: string;
1630
+ description: string;
1631
+ icon: string;
1632
+ category: string;
1633
+ version: string;
1634
+ author: string;
1635
+ downloadCount: number;
1636
+ tags: string[];
1637
+ certificationStatus?: string;
1638
+ visibility?: string;
1639
+ source?: string;
1640
+ updatedAt: string;
1641
+ }
1642
+ /** 技能商店轻量浏览响应 */
1643
+ interface SkillBrowseListResponse {
1644
+ items: SkillStoreListItem[];
1645
+ total: number;
1646
+ page: number;
1647
+ pageSize: number;
1648
+ }
1649
+ /** 技能认证状态响应 */
1650
+ interface CertificationStatus {
1651
+ skillId: string;
1652
+ certificationStatus: string;
1653
+ certifiedAt?: number;
1654
+ securityLevel?: string;
1655
+ securityScore: number;
1656
+ report?: unknown;
1657
+ }
1658
+ interface GenerateSkillRequest {
1659
+ purpose: string;
1660
+ examples?: string[];
1661
+ inputHints?: string;
1662
+ outputHints?: string;
1663
+ category?: string;
1664
+ language?: string;
1665
+ }
1666
+ interface GenerateSkillResult {
1667
+ skillName: string;
1668
+ skillKey: string;
1669
+ description: string;
1670
+ skillMd: string;
1671
+ inputSchema: string;
1672
+ outputSchema: string;
1673
+ testCases: string[];
1674
+ readme: string;
1675
+ category: string;
1676
+ tags: string[];
1677
+ timeout: number;
1678
+ }
1679
+ interface OptimizeSkillRequest {
1680
+ skillName: string;
1681
+ description?: string;
1682
+ inputSchema?: string;
1683
+ outputSchema?: string;
1684
+ readme?: string;
1685
+ aspects?: string[];
1686
+ }
1687
+ interface OptimizeSkillResult {
1688
+ optimizedSkill: GenerateSkillResult;
1689
+ changes: string[];
1690
+ score: number;
1691
+ }
1692
+ interface ToolView {
1693
+ id: string;
1694
+ key: string;
1695
+ name: string;
1696
+ description: string;
1697
+ icon: string;
1698
+ category: string;
1699
+ inputSchema: string;
1700
+ outputSchema: string;
1701
+ timeout: number;
1702
+ isEnabled: boolean;
1703
+ provider?: ToolProvider;
1704
+ }
1705
+ interface ToolProvider {
1706
+ id: string;
1707
+ name: string;
1708
+ icon: string;
1709
+ sourceType: string;
1710
+ mcpEndpoint?: string;
1711
+ isEnabled: boolean;
1712
+ }
1713
+ interface ToolListResponse {
1714
+ skills: ToolView[];
1715
+ total: number;
1716
+ }
1717
+
1718
+ declare module '@acosmi/sdk-ts' {
1719
+ interface Client {
1720
+ /** 浏览技能商店 (公共端点, 无需认证) */
1721
+ browseSkillStore(query: SkillStoreQuery, signal?: AbortSignal): Promise<SkillStoreItem[]>;
1722
+ /** 浏览公共技能商店 (V3 分页接口) */
1723
+ browseSkills(page: number, pageSize: number, category: string, keyword: string, tag: string, source: string, signal?: AbortSignal): Promise<SkillBrowseResponse>;
1724
+ /** 轻量浏览公共技能商店 (fields=minimal, 响应体积缩减 90%+) */
1725
+ browseSkillsList(page: number, pageSize: number, category: string, keyword: string, tag: string, source: string, signal?: AbortSignal): Promise<SkillBrowseListResponse>;
1726
+ /** 获取技能商店中某个技能的详情 (公共端点) */
1727
+ getSkillDetail(skillID: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1728
+ /** 按 key 精确查找公共技能 (公共端点) */
1729
+ resolveSkill(key: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1730
+ /** 安装技能到当前用户的租户空间 (需 OAuth scope: skill_store) */
1731
+ installSkill(skillID: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1732
+ /**
1733
+ * 下载技能 ZIP 包 (公共端点, 双模式)
1734
+ * 有 token 时自动附带 (享受无限流), 无 token 时匿名 (受限流)
1735
+ * @returns [data, filename]; 限流时抛 RateLimitError
1736
+ */
1737
+ downloadSkill(skillID: string, signal?: AbortSignal): Promise<{
1738
+ data: Uint8Array;
1739
+ filename: string;
1740
+ }>;
1741
+ /**
1742
+ * 上传技能 ZIP 包
1743
+ * @param scope "TENANT"
1744
+ * @param intent "PERSONAL" (仅自己用) 或 "PUBLIC_INTENT" (走认证→公开)
1745
+ */
1746
+ uploadSkill(zipData: Uint8Array, scope: string, intent: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1747
+ /** 获取技能统计概览 */
1748
+ getSkillSummary(signal?: AbortSignal): Promise<SkillSummary>;
1749
+ /** 触发技能认证管线 (异步) */
1750
+ certifySkill(skillID: string, signal?: AbortSignal): Promise<void>;
1751
+ /** 查询技能认证状态 */
1752
+ getCertificationStatus(skillID: string, signal?: AbortSignal): Promise<CertificationStatus>;
1753
+ /** 根据自然语言描述生成技能定义 (基于独立 LLM) */
1754
+ generateSkill(req: GenerateSkillRequest, signal?: AbortSignal): Promise<GenerateSkillResult>;
1755
+ /** 优化已有技能定义 */
1756
+ optimizeSkill(req: OptimizeSkillRequest, signal?: AbortSignal): Promise<OptimizeSkillResult>;
1757
+ /** 校验技能定义正确性 */
1758
+ validateSkill(skillName: string, signal?: AbortSignal): Promise<void>;
1759
+ }
1760
+ }
1761
+
1762
+ declare module '@acosmi/sdk-ts' {
1763
+ interface Client {
1764
+ /** 获取当前用户租户下的所有工具 (Skill 优先 + Plugin 兜底) */
1765
+ listTools(signal?: AbortSignal): Promise<ToolView[]>;
1766
+ /** 获取单个工具详情 */
1767
+ getTool(toolID: string, signal?: AbortSignal): Promise<ToolView>;
1768
+ }
1769
+ }
1770
+
1771
+ /** 单条通知 */
1772
+ interface Notification {
1773
+ id: string;
1774
+ title: string;
1775
+ content: string;
1776
+ /** system | billing | security | task | commission | entitlement */
1777
+ type: string;
1778
+ isRead: boolean;
1779
+ createdAt: string;
1780
+ }
1781
+ /** 分页通知列表 */
1782
+ interface NotificationList {
1783
+ list: Notification[];
1784
+ unreadCount: number;
1785
+ total: number;
1786
+ page: number;
1787
+ pageSize: number;
1788
+ }
1789
+ /** 未读通知计数 */
1790
+ interface NotificationUnreadCount {
1791
+ unreadCount: number;
1792
+ }
1793
+ /** 通知偏好 (按类型+渠道) */
1794
+ interface NotificationPreference {
1795
+ typeCode: string;
1796
+ channelInApp: boolean;
1797
+ channelEmail: boolean;
1798
+ channelSms: boolean;
1799
+ channelPush: boolean;
1800
+ }
1801
+ /** 推送设备注册 */
1802
+ interface DeviceRegistration {
1803
+ /** android | ios | harmony */
1804
+ platform: string;
1805
+ token: string;
1806
+ appVersion: string;
1807
+ }
1808
+ /** 服务端推送事件 */
1809
+ interface WSEvent {
1810
+ type: string;
1811
+ topic?: string;
1812
+ /** json.RawMessage in Go */
1813
+ data?: unknown;
1814
+ connId?: string;
1815
+ timestamp?: string;
1816
+ message?: string;
1817
+ }
1818
+ /**
1819
+ * 从 WSEvent 中解析通知
1820
+ * 返回 null 表示该事件不是系统通知
1821
+ */
1822
+ declare function parseNotificationEvent(ev: WSEvent): Notification | null;
1823
+
1824
+ declare module '@acosmi/sdk-ts' {
1825
+ interface Client {
1826
+ /** 分页查询通知列表 */
1827
+ listNotifications(page: number, pageSize: number, typeFilter: string, signal?: AbortSignal): Promise<NotificationList>;
1828
+ /** 获取未读通知数量 */
1829
+ getUnreadCount(signal?: AbortSignal): Promise<number>;
1830
+ /** 标记单条通知已读 */
1831
+ markNotificationRead(id: string, signal?: AbortSignal): Promise<void>;
1832
+ /** 标记全部通知已读 */
1833
+ markAllNotificationsRead(signal?: AbortSignal): Promise<void>;
1834
+ /** 删除通知 */
1835
+ deleteNotification(id: string, signal?: AbortSignal): Promise<void>;
1836
+ /** 注册推送设备 token */
1837
+ registerDevice(reg: DeviceRegistration, signal?: AbortSignal): Promise<void>;
1838
+ /** 注销推送设备 token */
1839
+ unregisterDevice(token: string, signal?: AbortSignal): Promise<void>;
1840
+ /** 获取通知偏好设置 */
1841
+ listNotificationPreferences(signal?: AbortSignal): Promise<NotificationPreference[]>;
1842
+ /** 更新通知偏好 */
1843
+ updateNotificationPreference(typeCode: string, pref: NotificationPreference, signal?: AbortSignal): Promise<void>;
1844
+ }
1845
+ }
1846
+
1847
+ /** WebSocket 长连接配置 */
1848
+ interface WSConfig {
1849
+ /** 收到服务端事件回调 */
1850
+ onEvent?: (ev: WSEvent) => void;
1851
+ /** 连接建立回调 */
1852
+ onConnect?: () => void;
1853
+ /** 断线回调 */
1854
+ onDisconnect?: (err: unknown) => void;
1855
+ /** 自动订阅的主题 */
1856
+ topics?: string[];
1857
+ /** 最小重连间隔 (ms, 默认 2000) */
1858
+ reconnectMinMs?: number;
1859
+ /** 最大重连间隔 (ms, 默认 60000) */
1860
+ reconnectMaxMs?: number;
1861
+ /** 是否自动重连 (默认 true) */
1862
+ autoReconnect?: boolean;
1863
+ }
1864
+ declare module '@acosmi/sdk-ts' {
1865
+ interface Client {
1866
+ /**
1867
+ * 建立 WebSocket 长连接 — 等待首次连接成功或 abort。
1868
+ */
1869
+ connect(cfg: WSConfig, signal?: AbortSignal): Promise<void>;
1870
+ /** 优雅断开 WebSocket 连接 */
1871
+ disconnect(): Promise<void>;
1872
+ /** WebSocket 是否已连接 */
1873
+ isConnected(): boolean;
1874
+ }
1875
+ }
1876
+
1877
+ type AgentRunStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
1878
+ interface AgentRunLocalContextPolicy {
1879
+ enabled?: boolean;
1880
+ readonly?: boolean;
1881
+ maxBytes?: number;
1882
+ allowedTools?: string[];
1883
+ }
1884
+ interface AgentRunArtifactPolicy {
1885
+ enabled?: boolean;
1886
+ maxFiles?: number;
1887
+ }
1888
+ interface AgentRunCreateRequest {
1889
+ appId: string;
1890
+ mode?: string;
1891
+ sessionId?: string;
1892
+ input: string;
1893
+ messages?: unknown[];
1894
+ model?: string;
1895
+ activeSkillIds?: string[];
1896
+ knowledgeBaseIds?: string[];
1897
+ metadata?: Record<string, string>;
1898
+ localContextPolicy?: AgentRunLocalContextPolicy;
1899
+ artifactPolicy?: AgentRunArtifactPolicy;
1900
+ }
1901
+ interface AgentRun {
1902
+ runId: string;
1903
+ sessionId: string;
1904
+ appId?: string;
1905
+ mode?: string;
1906
+ status: AgentRunStatus;
1907
+ createdAt?: string;
1908
+ startedAt?: string;
1909
+ completedAt?: string;
1910
+ error?: AgentRunErrorPayload;
1911
+ metadata?: Record<string, string>;
1912
+ }
1913
+ interface AgentRunCreateResponse {
1914
+ runId: string;
1915
+ sessionId: string;
1916
+ status: AgentRunStatus;
1917
+ }
1918
+ interface AgentRunArtifact {
1919
+ id: string;
1920
+ filename: string;
1921
+ contentType?: string;
1922
+ size?: number;
1923
+ type?: string;
1924
+ metadata?: Record<string, string>;
1925
+ }
1926
+ interface AgentRunArtifactList {
1927
+ artifacts: AgentRunArtifact[];
1928
+ }
1929
+ interface AgentRunDownload {
1930
+ data: Uint8Array;
1931
+ filename: string;
1932
+ contentType?: string;
1933
+ }
1934
+ interface AgentRunUsage {
1935
+ inputTokens?: number;
1936
+ outputTokens?: number;
1937
+ totalTokens?: number;
1938
+ cacheReadTokens?: number;
1939
+ cacheCreateTokens?: number;
1940
+ exact?: boolean;
1941
+ source?: string;
1942
+ [key: string]: unknown;
1943
+ }
1944
+ interface AgentRunSettlement {
1945
+ requestId?: string;
1946
+ status?: string;
1947
+ consumeStatus?: string;
1948
+ inputTokens?: number;
1949
+ outputTokens?: number;
1950
+ totalTokens?: number;
1951
+ cacheReadTokens?: number;
1952
+ cacheCreateTokens?: number;
1953
+ tokenRemaining?: number;
1954
+ callRemaining?: number;
1955
+ retryQueued?: boolean;
1956
+ exact?: boolean;
1957
+ [key: string]: unknown;
1958
+ }
1959
+ interface AgentRunErrorPayload {
1960
+ code?: string;
1961
+ message: string;
1962
+ stage?: string;
1963
+ retryable?: boolean;
1964
+ raw?: unknown;
1965
+ }
1966
+ interface AgentRunLocalToolResult {
1967
+ requestId: string;
1968
+ ok: boolean;
1969
+ content?: unknown;
1970
+ error?: string;
1971
+ }
1972
+ interface AgentRunLocalToolHandlerContext {
1973
+ runId: string;
1974
+ requestId: string;
1975
+ name: string;
1976
+ signal: AbortSignal;
1977
+ }
1978
+ type AgentRunLocalToolHandler = (input: unknown, context: AgentRunLocalToolHandlerContext) => Promise<unknown> | unknown;
1979
+ interface AgentRunStreamOptions {
1980
+ /**
1981
+ * true by default. When enabled, an error event is converted into
1982
+ * AgentRunStreamError after the event has been parsed.
1983
+ */
1984
+ throwOnError?: boolean;
1985
+ }
1986
+ interface AgentRunRunOptions extends AgentRunStreamOptions {
1987
+ }
1988
+ interface AgentRunWithLocalToolsOptions extends AgentRunRunOptions {
1989
+ timeoutMs?: number;
1990
+ onEvent?: (event: AgentRunStreamEvent) => void | Promise<void>;
1991
+ }
1992
+ type AgentRunStreamEvent = {
1993
+ type: 'run_started';
1994
+ runId: string;
1995
+ sessionId: string;
1996
+ } | {
1997
+ type: 'status';
1998
+ status: AgentRunStatus | string;
1999
+ message?: string;
2000
+ } | {
2001
+ type: 'text_delta';
2002
+ text: string;
2003
+ } | {
2004
+ type: 'reasoning_delta';
2005
+ text: string;
2006
+ } | {
2007
+ type: 'tool_call';
2008
+ id: string;
2009
+ name: string;
2010
+ input?: unknown;
2011
+ } | {
2012
+ type: 'tool_result';
2013
+ id: string;
2014
+ name?: string;
2015
+ result?: unknown;
2016
+ error?: string;
2017
+ } | {
2018
+ type: 'local_tool_request';
2019
+ requestId: string;
2020
+ name: string;
2021
+ input: unknown;
2022
+ } | {
2023
+ type: 'artifact';
2024
+ artifact: AgentRunArtifact;
2025
+ } | {
2026
+ type: 'sources';
2027
+ sources: unknown;
2028
+ } | {
2029
+ type: 'usage';
2030
+ usage: AgentRunUsage;
2031
+ } | {
2032
+ type: 'settle';
2033
+ settlement: AgentRunSettlement;
2034
+ } | {
2035
+ type: 'error';
2036
+ error: AgentRunErrorPayload;
2037
+ } | {
2038
+ type: 'done';
2039
+ runId: string;
2040
+ status: AgentRunStatus | string;
2041
+ };
2042
+ declare class AgentRunStreamError extends Error {
2043
+ event: Extract<AgentRunStreamEvent, {
2044
+ type: 'error';
2045
+ }>;
2046
+ code: string;
2047
+ stage: string;
2048
+ retryable: boolean;
2049
+ constructor(event: Extract<AgentRunStreamEvent, {
2050
+ type: 'error';
2051
+ }>);
2052
+ }
2053
+
2054
+ declare module '@acosmi/sdk-ts' {
2055
+ interface Client {
2056
+ /** SDK-facing cloud agent run gateway. */
2057
+ readonly agentRuns: AgentRunsClient;
2058
+ }
2059
+ }
2060
+ declare class AgentRunsClient {
2061
+ private readonly client;
2062
+ constructor(client: Client);
2063
+ create(req: AgentRunCreateRequest, signal?: AbortSignal): Promise<AgentRunCreateResponse>;
2064
+ get(runId: string, signal?: AbortSignal): Promise<AgentRun>;
2065
+ stream(runId: string, opts?: AgentRunStreamOptions, signal?: AbortSignal): AsyncIterable<AgentRunStreamEvent>;
2066
+ cancel(runId: string, signal?: AbortSignal): Promise<AgentRun>;
2067
+ listArtifacts(runId: string, signal?: AbortSignal): Promise<AgentRunArtifact[]>;
2068
+ downloadArtifact(runId: string, artifactId: string, signal?: AbortSignal): Promise<AgentRunDownload>;
2069
+ submitLocalToolResult(runId: string, result: AgentRunLocalToolResult, signal?: AbortSignal): Promise<AgentRun>;
2070
+ run(req: AgentRunCreateRequest, opts?: AgentRunRunOptions, signal?: AbortSignal): AsyncIterable<AgentRunStreamEvent>;
2071
+ runWithLocalTools(req: AgentRunCreateRequest, handlers: Record<string, AgentRunLocalToolHandler>, opts?: AgentRunWithLocalToolsOptions, signal?: AbortSignal): AsyncIterable<AgentRunStreamEvent>;
2072
+ private runGen;
2073
+ private runWithLocalToolsGen;
2074
+ private invokeLocalTool;
2075
+ private streamGen;
2076
+ private requestAPI;
2077
+ private requestRaw;
2078
+ }
2079
+
2080
+ declare const ScopeComplianceEvidenceRead = "compliance:evidence:read";
2081
+ declare const ScopeComplianceEvidenceWrite = "compliance:evidence:write";
2082
+ declare const ScopeComplianceTimestampIssue = "compliance:timestamp:issue";
2083
+ declare const ScopeComplianceTimestampVerify = "compliance:timestamp:verify";
2084
+ declare const ScopeComplianceContractSigningRead = "compliance:contract_signing:read";
2085
+ declare const ScopeComplianceContractSigningWrite = "compliance:contract_signing:write";
2086
+ declare const ScopeComplianceSealManage = "compliance:seal:manage";
2087
+ declare const ScopeComplianceSealApprovalRequest = "compliance:seal_approval:request";
2088
+ declare const ScopeComplianceSealApprovalApprove = "compliance:seal_approval:approve";
2089
+ declare const ScopeComplianceSealUseExecute = "compliance:seal_use:execute";
2090
+ declare const ScopeComplianceReportsRead = "compliance:reports:read";
2091
+ declare const ScopeComplianceReportsWrite = "compliance:reports:write";
2092
+ declare const ScopeComplianceReportsPublish = "compliance:reports:publish";
2093
+ declare const ScopeComplianceContractTemplateRead = "compliance:contract_template:read";
2094
+ declare const ScopeComplianceContractTemplateWrite = "compliance:contract_template:write";
2095
+ /** 类型联合:合规域细粒度 scope。Java compliance verifier 只按细粒度匹配, 不做分组展开。 */
2096
+ type ComplianceScope = typeof ScopeComplianceEvidenceRead | typeof ScopeComplianceEvidenceWrite | typeof ScopeComplianceTimestampIssue | typeof ScopeComplianceTimestampVerify | typeof ScopeComplianceContractSigningRead | typeof ScopeComplianceContractSigningWrite | typeof ScopeComplianceSealManage | typeof ScopeComplianceSealApprovalRequest | typeof ScopeComplianceSealApprovalApprove | typeof ScopeComplianceSealUseExecute | typeof ScopeComplianceReportsRead | typeof ScopeComplianceReportsWrite | typeof ScopeComplianceReportsPublish | typeof ScopeComplianceContractTemplateRead | typeof ScopeComplianceContractTemplateWrite;
2097
+ /** 全部合规域 scope。OAuth 申请合规权限时使用; 谨慎一次性申请全部, 推荐按业务最小集合申请。 */
2098
+ declare function complianceScopes(): ComplianceScope[];
2099
+
2100
+ /**
2101
+ * Compliance envelope 稳定业务状态。
2102
+ *
2103
+ * 字面量与 Java {@code EnvelopeStatusEnum} 的 `name()` 一致(这是 enum,是 wire 上的实际
2104
+ * 字符串);前端按这些字符串分支展示文案。
2105
+ */
2106
+ type ComplianceEnvelopeStatus = 'DRAFT' | 'CONTRACT_READY' | 'APPROVED' | 'SIGN_PENDING' | 'PENDING_EVIDENCE' | 'PENDING_RECONCILIATION' | 'SUCCESS' | 'FAILED' | 'CANCELED';
2107
+ /** Compliance 用印审批稳定状态。 */
2108
+ type ComplianceSealApprovalStatus = 'DRAFT' | 'SUBMITTED' | 'APPROVED' | 'REJECTED' | 'CANCELED' | 'USED' | 'EXPIRED';
2109
+ /** Provider 业务状态(前端可见的脱敏视图,不暴露下游内部字段)。 */
2110
+ type ComplianceProviderStatus = 'pending' | 'success' | 'failed' | 'unknown' | 'retrying';
2111
+ /**
2112
+ * 计费 / 履约的对外稳定状态视图。distribution compliance-billing 内部 API
2113
+ * (quote/reserve/commit/cancel/reconcile) 不暴露给前端 — 前端只能看见这 4 个语义。
2114
+ */
2115
+ type ComplianceBillingDisplayStatus = 'reserved' | 'committed' | 'canceled' | 'pending_reconciliation';
2116
+ /** 高风险动作 step-up — 重新做 OAuth introspection 或重新登录,提升 token 等级后再尝试。 */
2117
+ declare const ErrComplianceStepUpRequired = "COMPLIANCE_STEP_UP_REQUIRED";
2118
+ /** envelope 闸门关闭 — 审批 gate 等条件未同时就绪,前端展示"功能开放中"。 */
2119
+ declare const ErrEnvelopeGateClosed = "ENVELOPE_GATE_CLOSED";
2120
+ /** 履约 provider 未配置 — 受控环境材料缺失时业务路径会一致拒绝,不要前端重试。 */
2121
+ declare const ErrProviderNotConfigured = "PROVIDER_NOT_CONFIGURED";
2122
+ /** Provider 返回 unknown / retrying — 客户必须等待对账,前端展示"处理中(人工核对)"。 */
2123
+ declare const ErrProviderUnknownNoRetry = "PROVIDER_REQUEST_UNKNOWN_NO_RETRY";
2124
+ /** callback 不能直接确认扣费 — 后端守门,前端无需处理,记录到审计日志展示即可。 */
2125
+ declare const ErrBillingCallbackCannotCommit = "BILLING_CALLBACK_CANNOT_COMMIT";
2126
+ /** provider 成功但本地未验证通过,不允许扣费。 */
2127
+ declare const ErrBillingCommitRequiresLocalVerify = "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY";
2128
+ /** distribution compliance-billing 必须 S2S — 前端误调用时拿到该错误码,禁止 retry。 */
2129
+ declare const ErrBillingS2sForbidden = "BILLING_S2S_FORBIDDEN";
2130
+ /** 审批 gate 各类失败语义(前端展示"审批中 / 审批已用 / 审批失效")。 */
2131
+ declare const ErrSealApprovalNotApproved = "SEAL_APPROVAL_STATE_NOT_APPROVED";
2132
+ declare const ErrSealApprovalExpired = "SEAL_APPROVAL_EXPIRED";
2133
+ declare const ErrSealApprovalNonceUsed = "SEAL_APPROVAL_NONCE_USED";
2134
+ declare const ErrSealApprovalContractHashMismatch = "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH";
2135
+ declare const ErrSealApprovalSealMismatch = "SEAL_APPROVAL_SEAL_MISMATCH";
2136
+ declare const ErrSealApprovalLocationMismatch = "SEAL_APPROVAL_LOCATION_MISMATCH";
2137
+ declare const ErrSealApprovalTransactorMismatch = "SEAL_APPROVAL_TRANSACTOR_MISMATCH";
2138
+ /** 用印重复消费防护 — 前端遇到该错误必须刷新审批单状态,不允许"换一次 nonce 再试"。 */
2139
+ declare const ErrSealUseAlreadyConsumed = "SEAL_USE_ALREADY_CONSUMED";
2140
+ /** 该错误码联合用于前端选择性展示文案;非穷举式 enum,后端保留新增空间。 */
2141
+ type ComplianceClientErrorCode = typeof ErrComplianceStepUpRequired | typeof ErrEnvelopeGateClosed | typeof ErrProviderNotConfigured | typeof ErrProviderUnknownNoRetry | typeof ErrBillingCallbackCannotCommit | typeof ErrBillingCommitRequiresLocalVerify | typeof ErrBillingS2sForbidden | typeof ErrSealApprovalNotApproved | typeof ErrSealApprovalExpired | typeof ErrSealApprovalNonceUsed | typeof ErrSealApprovalContractHashMismatch | typeof ErrSealApprovalSealMismatch | typeof ErrSealApprovalLocationMismatch | typeof ErrSealApprovalTransactorMismatch | typeof ErrSealUseAlreadyConsumed;
2142
+ /**
2143
+ * 判定一个错误码是否属于"需要前端引导用户重新认证/审批"的高级语义,
2144
+ * 而不是简单 retry。这类错误前端不允许在 UI 层做自动重试。
2145
+ */
2146
+ declare function isComplianceTerminalError(code: string): boolean;
2147
+ /**
2148
+ * "是否允许在 UI 上呈现为'扣费已确认'"的判定。
2149
+ * provider 状态为 unknown / retrying / pending 时一律不展示为已确认。
2150
+ */
2151
+ declare function isBillingConfirmable(providerStatus: ComplianceProviderStatus | undefined, billingStatus: ComplianceBillingDisplayStatus | undefined): boolean;
2152
+
2153
+ /** Compliance 写操作选项;写操作不自动 retry,不自动 401 重放。 */
2154
+ interface ComplianceWriteOptions {
2155
+ /**
2156
+ * 调用方稳定的幂等键。写操作强烈建议持久化;缺省时服务端按 UUID 兜底,但调用方
2157
+ * 在重试 / 恢复时无法对账。
2158
+ */
2159
+ idempotencyKey?: string;
2160
+ signal?: AbortSignal;
2161
+ }
2162
+ /** 轮询参数(exponential backoff)。 */
2163
+ interface CompliancePollOptions {
2164
+ /** 总超时(ms),缺省 60s。 */
2165
+ timeoutMs?: number;
2166
+ /** 初始 interval(ms),缺省 1000。 */
2167
+ initialIntervalMs?: number;
2168
+ /** interval 倍增上限(ms),缺省 5000。 */
2169
+ maxIntervalMs?: number;
2170
+ /** 倍增系数,缺省 1.5。 */
2171
+ multiplier?: number;
2172
+ signal?: AbortSignal;
2173
+ }
2174
+
2175
+ type ComplianceAssetType = 'CONTRACT' | 'CODE' | 'IMAGE' | 'DOCUMENT' | 'ARCHIVE' | 'HASH_ONLY' | 'URL_SNAPSHOT' | 'RELEASE' | 'LOG' | 'OTHER';
2176
+ type ComplianceHashAlgorithm = 'sha256' | 'sha512' | 'sm3';
2177
+ type ComplianceDigestSource = 'CLIENT' | 'COMPLIANCE_SERVICE' | 'PROVIDER';
2178
+ type CompliancePrivacyLevel = 'public' | 'private';
2179
+ /** 证据资产对外稳定视图。对应后端 EvidenceAssetRespVO。 */
2180
+ interface EvidenceAsset {
2181
+ id: number;
2182
+ /** 业务编号;SDK / 前端引用时优先使用 evidenceNo。 */
2183
+ evidenceNo: string;
2184
+ /** publish 后的公开 verify code;DRAFT / 非 public privacy 时为 null。 */
2185
+ publicVerifyCode?: string | null;
2186
+ assetType: ComplianceAssetType | string;
2187
+ name: string;
2188
+ mimeType?: string | null;
2189
+ size?: number | null;
2190
+ hashAlgorithm: ComplianceHashAlgorithm | string;
2191
+ /** 资产 hash(hex 字符串)。 */
2192
+ contentHash: string;
2193
+ canonicalizationProfile?: string | null;
2194
+ digestSource: ComplianceDigestSource | string;
2195
+ privacyLevel: CompliancePrivacyLevel | string;
2196
+ status: string;
2197
+ }
2198
+ /** 创建证据资产请求;与 Java EvidenceAssetCreateReq 对齐。 */
2199
+ interface CreateEvidenceAssetRequest {
2200
+ /** AssetTypeEnum.name()。 */
2201
+ assetType: ComplianceAssetType | string;
2202
+ name: string;
2203
+ mimeType?: string;
2204
+ /** 'sha256' / 'sha512' / 'sm3'。 */
2205
+ hashAlgorithm: ComplianceHashAlgorithm | string;
2206
+ /** hex 字符串;hash-only 资产必填。 */
2207
+ declaredHash?: string;
2208
+ /** CLIENT / COMPLIANCE_SERVICE / PROVIDER。 */
2209
+ digestSource?: ComplianceDigestSource | string;
2210
+ /** 原文 base64;hash-only 时缺省即可。 */
2211
+ contentBase64?: string;
2212
+ /** public / private(默认 private)。 */
2213
+ privacyLevel?: CompliancePrivacyLevel | string;
2214
+ source?: string;
2215
+ }
2216
+ /** 公开 verify 结果。隐私边界:不暴露 PII / 合同原文 / storage / provider raw。 */
2217
+ interface PublicEvidenceVerifyResult {
2218
+ evidenceNo: string;
2219
+ assetType: string;
2220
+ hashAlgorithm: string;
2221
+ contentHash: string;
2222
+ size?: number | null;
2223
+ canonicalizationProfile?: string | null;
2224
+ verifiedAt: string;
2225
+ packageId?: number | null;
2226
+ manifestHash?: string | null;
2227
+ packageHash?: string | null;
2228
+ manifestOfflineVerify: boolean;
2229
+ }
2230
+ interface EvidencePackage {
2231
+ id: number;
2232
+ assetId: number;
2233
+ timestampTokenId?: number | null;
2234
+ chainId: string;
2235
+ packageVersion: string;
2236
+ hashAlgorithm: string;
2237
+ manifestHash: string;
2238
+ packageHash: string;
2239
+ status: string;
2240
+ }
2241
+ /**
2242
+ * 证据资产分页【列表项】视图。对应后端 G1 `EvidenceAssetPageItem`。
2243
+ *
2244
+ * 与 {@link EvidenceAsset} 一致的 SDK-safe 子集 + `createTime`;时间字段为
2245
+ * ISO-8601 字符串。
2246
+ */
2247
+ interface EvidenceAssetPageItem {
2248
+ id: number;
2249
+ evidenceNo: string;
2250
+ publicVerifyCode?: string | null;
2251
+ assetType: ComplianceAssetType | string;
2252
+ name: string;
2253
+ mimeType?: string | null;
2254
+ size?: number | null;
2255
+ hashAlgorithm: ComplianceHashAlgorithm | string;
2256
+ contentHash: string;
2257
+ canonicalizationProfile?: string | null;
2258
+ digestSource: ComplianceDigestSource | string;
2259
+ privacyLevel: CompliancePrivacyLevel | string;
2260
+ status: string;
2261
+ /** 创建时间 ISO-8601。 */
2262
+ createTime: string;
2263
+ }
2264
+ /**
2265
+ * `listEvidenceAssets` 请求参数。
2266
+ *
2267
+ * 继承 {@link PageRequest} 的 `pageNo` / `pageSize` / `sortBy` / `sortDirection`,
2268
+ * 全部可选;省略时由服务端取默认页。
2269
+ *
2270
+ * `createTimeStart` / `createTimeEnd` 为调用方提供的【原样字符串】,后端按
2271
+ * `yyyy-MM-dd HH:mm:ss` 解析(例如 `'2026-05-01 00:00:00'`);SDK 不做格式校验、
2272
+ * 不做时区转换,原样透传查询参数。
2273
+ */
2274
+ interface ListEvidenceAssetsRequest extends PageRequest {
2275
+ /** 资产类型过滤(`AssetTypeEnum.name()`)。 */
2276
+ assetType?: ComplianceAssetType | string;
2277
+ /** 资产状态过滤。 */
2278
+ status?: string;
2279
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2280
+ createTimeStart?: string;
2281
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2282
+ createTimeEnd?: string;
2283
+ }
2284
+ /**
2285
+ * 证据包分页【列表项】视图。对应后端 G1 `EvidencePackagePageItem`。
2286
+ */
2287
+ interface EvidencePackagePageItem {
2288
+ id: number;
2289
+ assetId: number;
2290
+ timestampTokenId?: number | null;
2291
+ chainId: string;
2292
+ packageVersion: string;
2293
+ hashAlgorithm: string;
2294
+ manifestHash: string;
2295
+ packageHash: string;
2296
+ status: string;
2297
+ /** 创建时间 ISO-8601。 */
2298
+ createTime: string;
2299
+ }
2300
+ /**
2301
+ * `listEvidencePackages` 请求参数。`createTimeStart` / `createTimeEnd` 语义见
2302
+ * {@link ListEvidenceAssetsRequest}。
2303
+ */
2304
+ interface ListEvidencePackagesRequest extends PageRequest {
2305
+ /** 证据包状态过滤。 */
2306
+ status?: string;
2307
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2308
+ createTimeStart?: string;
2309
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2310
+ createTimeEnd?: string;
2311
+ }
2312
+
2313
+ type ComplianceTimestampVerificationStatus = 'PENDING' | 'VERIFIED' | 'FAILED' | 'LOCAL_VERIFY_FAILED' | 'UNKNOWN' | 'RETRYING';
2314
+ /** 时间章 token 对外视图(不含 provider/object/tsa 内部字段)。 */
2315
+ interface TimestampToken {
2316
+ id: number;
2317
+ assetId: number;
2318
+ policyOid?: string | null;
2319
+ serialNumber?: string | null;
2320
+ /** gen_time ISO-8601;UNKNOWN/PENDING 状态可能为 null。 */
2321
+ genTime?: string | null;
2322
+ accuracy?: string | null;
2323
+ verificationStatus: ComplianceTimestampVerificationStatus | string;
2324
+ verifiedAt?: string | null;
2325
+ verificationError?: string | null;
2326
+ }
2327
+ /** 申请时间章请求。`provider` 字段已从服务端契约下线;SDK 永远不传。 */
2328
+ interface IssueTimestampRequest {
2329
+ name?: string;
2330
+ mimeType?: string;
2331
+ hashAlgorithm: ComplianceHashAlgorithm | string;
2332
+ /** 客户端声明 digest(hex);contentBase64 非空时作为校验值。 */
2333
+ digest?: string;
2334
+ contentBase64?: string;
2335
+ }
2336
+ /** verify 请求 / 结果。 */
2337
+ interface VerifyTimestampRequest {
2338
+ tokenId: number;
2339
+ }
2340
+ interface TimestampVerifyResult {
2341
+ passed: boolean;
2342
+ reason: string;
1156
2343
  }
1157
2344
  /**
1158
- * compliance polling 检测到终态失败 / 已过 timeout / step-up 时抛出。
2345
+ * 时间章分页【列表项】视图。对应后端 G1 `TimestampPageItem`。
1159
2346
  *
1160
- * 分类逻辑:终态失败优先于 timeout;timeout 不算 retryable,调用方必须用新 idempotency-key
1161
- * 重新发起整条链路。
2347
+ * {@link TimestampToken} 一致的 SDK-safe 子集 + `createTime`;时间字段为
2348
+ * ISO-8601 字符串。
1162
2349
  */
1163
- declare class CompliancePollError extends Error {
1164
- readonly kind: 'timeout' | 'terminal_failure' | 'step_up_required' | 'unknown';
1165
- readonly lastInfo?: ComplianceErrorInfo;
1166
- constructor(message: string, kind: 'timeout' | 'terminal_failure' | 'step_up_required' | 'unknown', lastInfo?: ComplianceErrorInfo);
2350
+ interface TimestampPageItem {
2351
+ id: number;
2352
+ assetId: number;
2353
+ policyOid?: string | null;
2354
+ serialNumber?: string | null;
2355
+ genTime?: string | null;
2356
+ accuracy?: string | null;
2357
+ verificationStatus: ComplianceTimestampVerificationStatus | string;
2358
+ verifiedAt?: string | null;
2359
+ verificationError?: string | null;
2360
+ /** 创建时间 ISO-8601。 */
2361
+ createTime: string;
1167
2362
  }
1168
- declare class ComplianceClient {
1169
- private readonly client;
1170
- constructor(client: Client);
1171
- /** 创建证据资产(写)。 */
1172
- createEvidenceAsset(req: CreateEvidenceAssetRequest, opts?: ComplianceWriteOptions): Promise<EvidenceAsset>;
1173
- /** 证据资产详情。 */
1174
- getEvidenceAsset(id: number, signal?: AbortSignal): Promise<EvidenceAsset>;
1175
- /**
1176
- * 公开 verify。隐私边界:返回字段不含 PII / 合同原文 / storage / provider raw。
1177
- *
1178
- * 匿名可调用:未 login 时走匿名请求,不会抛 `not authorized, call login() first`。
1179
- * login / 已持有 token 时附带 `Authorization` 以保留审计上下文。public 端点不
1180
- * 应要求认证 收到 401 直接抛 HTTPError,不触发 `forceRefresh`,也不做 refresh
1181
- * replay。
1182
- */
1183
- verifyEvidencePublic(params: {
1184
- evidenceNo?: string;
1185
- publicVerifyCode?: string;
1186
- }, signal?: AbortSignal): Promise<PublicEvidenceVerifyResult>;
1187
- /** 申请时间章(写)。SDK 永远不传 provider 字段。 */
1188
- issueTimestamp(req: IssueTimestampRequest, opts?: ComplianceWriteOptions): Promise<TimestampToken>;
1189
- /** 给已有资产申请时间章。SDK 永远不传 provider 字段。 */
1190
- issueTimestampForAsset(assetId: number, opts?: ComplianceWriteOptions): Promise<TimestampToken>;
1191
- /** 读 — 时间章 token 详情。 */
1192
- getTimestamp(id: number, signal?: AbortSignal): Promise<TimestampToken>;
1193
- /** verify — 本地离线校验已申请的时间章。 */
1194
- verifyTimestamp(req: VerifyTimestampRequest, opts?: ComplianceWriteOptions): Promise<TimestampVerifyResult>;
1195
- /**
1196
- * 轮询到 VERIFIED 终态。
1197
- * - VERIFIED → 返回 token;
1198
- * - FAILED / LOCAL_VERIFY_FAILED → 抛 {@link CompliancePollError} kind='terminal_failure';
1199
- * - UNKNOWN / RETRYING / PENDING → 继续轮询直到 timeout;
1200
- * - timeout → 抛 {@link CompliancePollError} kind='timeout'。
1201
- */
1202
- waitForTimestampVerified(id: number, opts?: CompliancePollOptions): Promise<TimestampToken>;
1203
- /** 构建证据包(写)。 */
1204
- buildEvidencePackage(assetId: number, timestampTokenId?: number, opts?: ComplianceWriteOptions): Promise<EvidencePackage>;
1205
- /** 创建证据报告(写)。 */
1206
- createReport(req: CreateReportRequest, opts?: ComplianceWriteOptions): Promise<ComplianceReport>;
1207
- /** 读 — 报告详情。 */
1208
- getReport(id: number, signal?: AbortSignal): Promise<ComplianceReport>;
1209
- /**
1210
- * 发布报告(写,step-up 必须)。
1211
- *
1212
- * `@status gated` — step-up 闸门未闭合前服务端会一致返回
1213
- * `COMPLIANCE_STEP_UP_REQUIRED`(数值码 1031000013)。SDK 不会自动重试、不伪成功;
1214
- * 调用方需要引导用户重新做 OAuth introspection 或重新登录后再次调用本方法
1215
- *(使用同一 idempotency-key)。方法状态分级见 `docs/compliance.md` Method Status。
1216
- */
1217
- publishReport(id: number, opts?: ComplianceWriteOptions): Promise<ComplianceReport>;
1218
- /**
1219
- * 下载报告(读)。返回 {@link ReportDownload}:报告 hash + 资产 hash + 证据包 hash +
1220
- * 时间章 serial/genTime,足以离线复核。
1221
- * 不返回 bodyCanonicalJson / storage key / subject snapshot id。
1222
- */
1223
- downloadReport(id: number, signal?: AbortSignal): Promise<ReportDownload>;
1224
- /** 创建 envelope(写)。返回 envelope id。 */
1225
- createSigningEnvelope(req: CreateSigningEnvelopeRequest, opts?: ComplianceWriteOptions): Promise<number>;
1226
- /** 读 — envelope 详情。租户由服务端从 compliance token principal 推导。 */
1227
- getSigningEnvelope(envelopeId: number, signal?: AbortSignal): Promise<SigningEnvelope>;
1228
- /**
1229
- * 正式签署(写,step-up 必须)。
1230
- *
1231
- * `@status gated` — 服务端闸门关闭时会一致返回 `ENVELOPE_GATE_CLOSED` (1031004004)。
1232
- * SDK 不重试、不伪成功;调用方应该将该错误展示为"功能未开放"。
1233
- */
1234
- signEnvelope(envelopeId: number, req: SignEnvelopeRequest, opts?: ComplianceWriteOptions): Promise<void>;
1235
- /**
1236
- * 创建 H5 签署短链(写,step-up 必须)。
1237
- *
1238
- * `@status gated` — 同 {@link signEnvelope}:服务端闸门关闭时 SDK 不重试、不伪成功。
1239
- */
1240
- createH5SigningUrl(envelopeId: number, req: CreateH5SigningUrlRequest, opts?: ComplianceWriteOptions): Promise<string>;
1241
- /** 同步 provider 状态(写但只读对账,不创建新 provider 请求)。 */
1242
- syncSigningEnvelopeStatus(envelopeId: number, opts?: ComplianceWriteOptions): Promise<void>;
1243
- /**
1244
- * 提交用印审批申请(写)。
1245
- *
1246
- * `@status production-ready` — 服务端以 `Idempotency-Key` + 业务请求指纹做重放保护:
1247
- * 同 key + 同请求 → 返回原审批 id;同 key + 不同请求 → 拒绝复用幂等键。强烈建议调用方
1248
- * 持久化 `idempotencyKey`,网络重试 / 任务恢复时复用,避免重复创建审批单。
1249
- */
1250
- submitSealApproval(req: SubmitSealApprovalRequest, opts?: ComplianceWriteOptions): Promise<number>;
1251
- /**
1252
- * 审批通过用印申请(写,step-up 必须)。
1253
- *
1254
- * `@status gated` — step-up 未闭合前服务端会返回 `COMPLIANCE_STEP_UP_REQUIRED`。
1255
- * SDK 不重试、不伪成功。方法状态分级见 `docs/compliance.md` Method Status。
1256
- */
1257
- approveSealApproval(id: number, query: ApproveSealApprovalQuery, opts?: ComplianceWriteOptions): Promise<void>;
1258
- rejectSealApproval(id: number, query: RejectSealApprovalQuery, opts?: ComplianceWriteOptions): Promise<void>;
1259
- cancelSealApproval(id: number, query: CancelSealApprovalQuery, opts?: ComplianceWriteOptions): Promise<void>;
1260
- listPendingSealApprovals(signal?: AbortSignal): Promise<SealApproval[]>;
1261
- getSealApproval(id: number, signal?: AbortSignal): Promise<SealApproval>;
1262
- getProviderRequest(id: number, signal?: AbortSignal): Promise<ProviderRequestStatusView>;
1263
- /**
1264
- * 轮询 provider request 到 SUCCESS / FAILED 终态。
1265
- * - SUCCESS / FAILED → 返回最后视图;
1266
- * - UNKNOWN / RETRYING / PENDING → 继续轮询;
1267
- * - timeout → 抛 {@link CompliancePollError} kind='timeout',不自动重发原 provider 请求。
1268
- *
1269
- * SUCCESS 不代表 billing 已 commit;调用方仍需通过业务侧 envelope / asset 终态判断。
1270
- */
1271
- waitForProviderRequestTerminal(id: number, opts?: CompliancePollOptions): Promise<ProviderRequestStatusView>;
1272
- classifyError(err: unknown): ComplianceErrorInfo | null;
1273
- /**
1274
- * 读路径:GET / 公开 verify。允许 401 单次刷新后重放(GET 幂等安全)。
1275
- * 与 client.doJSONFullInternal 行为一致;不复用其代码因为 base URL 不同。
1276
- */
1277
- private read;
1278
- /**
1279
- * 公开读路径:public verify。
1280
- *
1281
- * 与 {@link read} 的区别 — public 端点不应要求认证:
1282
- * - 无 token 时匿名请求:ensureToken 抛 `not authorized` 会被吞掉,继续匿名发送。
1283
- * - 有 token 时附带 `Authorization`,保留后端审计上下文。
1284
- * - 不做 401 refresh replay:401 直接抛 HTTPError,不触发 `forceRefresh`。
1285
- *
1286
- * URL 仍走 `client.complianceURL(path)`,不复用 `/api/v4`;底层复用
1287
- * `client.doRequest`,不新增 fetch/axios 直连。
1288
- */
1289
- private publicRead;
1290
- /**
1291
- * 写路径:POST。
1292
- * - 发送前 ensureToken 一次确保 token fresh。
1293
- * - 不自动 401 重放:401 → 抛 HTTPError;调用方必须自己刷新 token 后用同一
1294
- * idempotency-key 重新发起,避免 provider 侧重复请求。
1295
- * - 不走 doRequestWithRetry:写操作不允许 5xx/timeout 自动重试。
1296
- */
1297
- private write;
1298
- private executeJson;
1299
- private poll;
2363
+ /**
2364
+ * `listTimestamps` 请求参数。
2365
+ *
2366
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2367
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2368
+ * 解析;SDK 不做格式校验或时区转换。
2369
+ */
2370
+ interface ListTimestampsRequest extends PageRequest {
2371
+ /** 时间章 provider 过滤(`TsaProviderEnum.name()` 之类)。 */
2372
+ provider?: string;
2373
+ /** 校验状态过滤。 */
2374
+ verificationStatus?: ComplianceTimestampVerificationStatus | string;
2375
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2376
+ createTimeStart?: string;
2377
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2378
+ createTimeEnd?: string;
1300
2379
  }
1301
-
1302
- /** SDK 为单个 content block 缓存的元数据 */
1303
- interface BlockMeta {
1304
- type: string;
1305
- ephemeral: boolean;
2380
+ /**
2381
+ * 时间章授权机构(TSA)provider 视图。对应后端 G3 `TsaProviderVO`。
2382
+ *
2383
+ * 描述某个 TSA provider 的对外可见状态——名称、所处环境、当前是否可用。
2384
+ * 只读视图:不含 provider 端点、凭证、证书或其它内部接入材料。
2385
+ */
2386
+ interface TsaProvider {
2387
+ /** provider 名称(如 `TsaProviderEnum.name()`)。 */
2388
+ name: string;
2389
+ /** provider 所处环境(如 `production` / `sandbox`)。 */
2390
+ environment: string;
2391
+ /** 该 provider 当前是否可用。 */
2392
+ available: boolean;
1306
2393
  }
1307
2394
  /**
1308
- * Anthropic SSE 事件类型解析 data, 更新 blockTypeMap, 返回 [index, type, ephemeral]。
2395
+ * 时间章统计视图。对应后端 G3 `TsaStatsVO`。
1309
2396
  *
1310
- * 仅当事件为 content_block_start / content_block_delta / content_block_stop
1311
- * 时返回非空 type; 其他事件返回空 type, 调用方据此判别是否填充 StreamEvent 元数据字段。
2397
+ * 只读聚合:时间章总数 + 按校验状态分桶的计数。
1312
2398
  */
1313
- declare function extractAnthropicBlockMeta(eventType: string, data: string, blockTypeMap: Map<number, BlockMeta>): [number, string, boolean];
2399
+ interface TsaStats {
2400
+ /** 时间章总数。 */
2401
+ total: number;
2402
+ /**
2403
+ * 按校验状态分桶的计数。键为校验状态枚举名(如 `VERIFIED` / `PENDING` /
2404
+ * `FAILED`),值为该状态下的时间章数量。
2405
+ */
2406
+ byVerificationStatus: Record<string, number>;
2407
+ }
1314
2408
 
1315
- type AgentRunStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
1316
- interface AgentRunLocalContextPolicy {
1317
- enabled?: boolean;
1318
- readonly?: boolean;
1319
- maxBytes?: number;
1320
- allowedTools?: string[];
2409
+ interface ComplianceReport {
2410
+ id: number;
2411
+ reportNo: string;
2412
+ reportType: string;
2413
+ status: string;
2414
+ assetId?: number | null;
2415
+ packageId?: number | null;
2416
+ publicUrlToken?: string | null;
2417
+ publishedAt?: string | null;
2418
+ bodyHash?: string | null;
1321
2419
  }
1322
- interface AgentRunArtifactPolicy {
1323
- enabled?: boolean;
1324
- maxFiles?: number;
2420
+ interface CreateReportRequest {
2421
+ assetId: number;
2422
+ packageId: number;
1325
2423
  }
1326
- interface AgentRunCreateRequest {
1327
- appId: string;
1328
- mode?: string;
1329
- sessionId?: string;
1330
- input: string;
1331
- messages?: unknown[];
1332
- model?: string;
1333
- activeSkillIds?: string[];
1334
- knowledgeBaseIds?: string[];
1335
- metadata?: Record<string, string>;
1336
- localContextPolicy?: AgentRunLocalContextPolicy;
1337
- artifactPolicy?: AgentRunArtifactPolicy;
2424
+ /** 离线复核下载 VO;建议调用方持久化作为长期可重复验证依据。 */
2425
+ interface ReportDownload {
2426
+ id: number;
2427
+ reportNo: string;
2428
+ reportType: string;
2429
+ status: string;
2430
+ bodyHash?: string | null;
2431
+ publishedAt?: string | null;
2432
+ assetEvidenceNo?: string | null;
2433
+ assetHashAlgorithm?: string | null;
2434
+ assetContentHash?: string | null;
2435
+ packageManifestHash?: string | null;
2436
+ packageHash?: string | null;
2437
+ packageHashAlgorithm?: string | null;
2438
+ timestampSerialNumber?: string | null;
2439
+ timestampGenTime?: string | null;
2440
+ timestampVerificationStatus?: string | null;
1338
2441
  }
1339
- interface AgentRun {
1340
- runId: string;
1341
- sessionId: string;
1342
- appId?: string;
1343
- mode?: string;
1344
- status: AgentRunStatus;
1345
- createdAt?: string;
1346
- startedAt?: string;
1347
- completedAt?: string;
1348
- error?: AgentRunErrorPayload;
1349
- metadata?: Record<string, string>;
2442
+ /**
2443
+ * 证据报告分页【列表项】视图。对应后端 G1 `ReportPageItem`。
2444
+ *
2445
+ * 与 {@link ComplianceReport} 一致的 SDK-safe 子集 + `createTime`;时间字段为
2446
+ * ISO-8601 字符串。
2447
+ */
2448
+ interface ReportPageItem {
2449
+ id: number;
2450
+ reportNo: string;
2451
+ reportType: string;
2452
+ status: string;
2453
+ assetId?: number | null;
2454
+ packageId?: number | null;
2455
+ publicUrlToken?: string | null;
2456
+ publishedAt?: string | null;
2457
+ bodyHash?: string | null;
2458
+ /** 创建时间 ISO-8601。 */
2459
+ createTime: string;
1350
2460
  }
1351
- interface AgentRunCreateResponse {
1352
- runId: string;
1353
- sessionId: string;
1354
- status: AgentRunStatus;
2461
+ /**
2462
+ * `listReports` 请求参数。
2463
+ *
2464
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2465
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2466
+ * 解析;SDK 不做格式校验或时区转换。
2467
+ */
2468
+ interface ListReportsRequest extends PageRequest {
2469
+ /** 报告状态过滤。 */
2470
+ status?: string;
2471
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2472
+ createTimeStart?: string;
2473
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2474
+ createTimeEnd?: string;
1355
2475
  }
1356
- interface AgentRunArtifact {
1357
- id: string;
1358
- filename: string;
1359
- contentType?: string;
1360
- size?: number;
1361
- type?: string;
1362
- metadata?: Record<string, string>;
2476
+
2477
+ interface SigningEnvelope {
2478
+ id: number;
2479
+ envelopeNo: string;
2480
+ applicantUserId?: string | null;
2481
+ status: string;
2482
+ primaryContractId?: number | null;
2483
+ contractHash?: string | null;
2484
+ hashAlgorithm?: string | null;
2485
+ billingGroupId?: string | null;
2486
+ chainId?: string | null;
2487
+ requestId?: string | null;
2488
+ pendingReason?: string | null;
2489
+ signedAt?: string | null;
2490
+ evidenceReadyAt?: string | null;
2491
+ committedAt?: string | null;
1363
2492
  }
1364
- interface AgentRunArtifactList {
1365
- artifacts: AgentRunArtifact[];
2493
+ /** 创建 envelope 请求;只保留调用方业务字段,内部主体快照和履约通道由后端推导。 */
2494
+ interface CreateSigningEnvelopeRequest {
2495
+ envelopeNo?: string;
2496
+ requestId?: string;
2497
+ /** 调用方稳定 idempotency-key(不传则由 Idempotency-Key header 兜底)。 */
2498
+ idempotencyKey?: string;
2499
+ billingGroupId?: string;
2500
+ chainId?: string;
1366
2501
  }
1367
- interface AgentRunDownload {
1368
- data: Uint8Array;
1369
- filename: string;
1370
- contentType?: string;
2502
+ /** sign 请求;service 默认闸门关闭,SDK 写示例必须处理 ENVELOPE_GATE_CLOSED 错误。 */
2503
+ interface SignEnvelopeRequest {
2504
+ approvalRequestId?: number;
2505
+ contractId?: number;
2506
+ contractHash?: string;
2507
+ sealId?: number;
2508
+ signLocationType?: string;
2509
+ signLocationPayload?: string;
2510
+ transactorId?: number;
2511
+ requestId?: string;
2512
+ idempotencyKey?: string;
1371
2513
  }
1372
- interface AgentRunUsage {
1373
- inputTokens?: number;
1374
- outputTokens?: number;
1375
- totalTokens?: number;
1376
- cacheReadTokens?: number;
1377
- cacheCreateTokens?: number;
1378
- exact?: boolean;
1379
- source?: string;
1380
- [key: string]: unknown;
2514
+ /** H5 短链请求。 */
2515
+ interface CreateH5SigningUrlRequest extends SignEnvelopeRequest {
1381
2516
  }
1382
- interface AgentRunSettlement {
1383
- requestId?: string;
2517
+ /**
2518
+ * 签署 envelope 分页【列表项】视图。对应后端 G1 `SigningEnvelopePageItem`。
2519
+ *
2520
+ * 与 {@link SigningEnvelope} 一致的 SDK-safe 子集 + `createTime`;时间字段为
2521
+ * ISO-8601 字符串。
2522
+ */
2523
+ interface SigningEnvelopePageItem {
2524
+ id: number;
2525
+ envelopeNo: string;
2526
+ applicantUserId?: string | null;
2527
+ status: string;
2528
+ primaryContractId?: number | null;
2529
+ contractHash?: string | null;
2530
+ hashAlgorithm?: string | null;
2531
+ billingGroupId?: string | null;
2532
+ chainId?: string | null;
2533
+ requestId?: string | null;
2534
+ pendingReason?: string | null;
2535
+ signedAt?: string | null;
2536
+ evidenceReadyAt?: string | null;
2537
+ committedAt?: string | null;
2538
+ /** 创建时间 ISO-8601。 */
2539
+ createTime: string;
2540
+ }
2541
+ /**
2542
+ * `listSigningEnvelopes` 请求参数。
2543
+ *
2544
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2545
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2546
+ * 解析;SDK 不做格式校验或时区转换。
2547
+ */
2548
+ interface ListSigningEnvelopesRequest extends PageRequest {
2549
+ /** envelope 状态过滤。 */
1384
2550
  status?: string;
1385
- consumeStatus?: string;
1386
- inputTokens?: number;
1387
- outputTokens?: number;
1388
- totalTokens?: number;
1389
- cacheReadTokens?: number;
1390
- cacheCreateTokens?: number;
1391
- tokenRemaining?: number;
1392
- callRemaining?: number;
1393
- retryQueued?: boolean;
1394
- exact?: boolean;
1395
- [key: string]: unknown;
2551
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2552
+ createTimeStart?: string;
2553
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2554
+ createTimeEnd?: string;
1396
2555
  }
1397
- interface AgentRunErrorPayload {
1398
- code?: string;
1399
- message: string;
1400
- stage?: string;
1401
- retryable?: boolean;
1402
- raw?: unknown;
2556
+ /**
2557
+ * 签署 envelope 下挂的合同【列表项】视图。对应后端 G4 `EnvelopeContractItem`。
2558
+ *
2559
+ * 一个 envelope 可挂多份合同;本视图描述合同的元数据与哈希指纹,便于离线复核。
2560
+ * SDK-safe 子集——不含合同原文 / storage key / provider raw payload。时间字段
2561
+ * 为 ISO-8601 字符串。
2562
+ */
2563
+ interface EnvelopeContractItem {
2564
+ /** 合同行 id(数值主键)。 */
2565
+ id: number;
2566
+ /** 所属 envelope id。 */
2567
+ envelopeId: number;
2568
+ /** 合同编号。 */
2569
+ contractNo: string;
2570
+ /** 合同标题。 */
2571
+ title: string;
2572
+ /** 合同文件 MIME 类型。 */
2573
+ mimeType: string;
2574
+ /** 合同文件字节数。 */
2575
+ size: number;
2576
+ /** 哈希算法(如 `sha256`)。 */
2577
+ hashAlgorithm: string;
2578
+ /** 合同原文内容哈希。 */
2579
+ contentHash: string;
2580
+ /** 签署后内容哈希(未签署时缺省)。 */
2581
+ signedContentHash?: string;
2582
+ /** 合同状态。 */
2583
+ status: string;
2584
+ /** 创建时间 ISO-8601。 */
2585
+ createTime: string;
1403
2586
  }
1404
- interface AgentRunLocalToolResult {
1405
- requestId: string;
1406
- ok: boolean;
1407
- content?: unknown;
1408
- error?: string;
2587
+ /**
2588
+ * `voidEnvelope` 请求体。作废一个签署 envelope,`reason` 为必填的作废原因。
2589
+ */
2590
+ interface VoidEnvelopeRequest {
2591
+ /** 作废原因(必填,随 JSON body 提交)。 */
2592
+ reason: string;
1409
2593
  }
1410
- interface AgentRunLocalToolHandlerContext {
1411
- runId: string;
1412
- requestId: string;
1413
- name: string;
1414
- signal: AbortSignal;
2594
+
2595
+ interface SealApproval {
2596
+ id: number;
2597
+ envelopeId?: number | null;
2598
+ contractId?: number | null;
2599
+ contractHash?: string | null;
2600
+ hashAlgorithm?: string | null;
2601
+ sealId?: number | null;
2602
+ applicantUserId?: string | null;
2603
+ approverUserId?: string | null;
2604
+ transactorId?: number | null;
2605
+ signLocationType?: string | null;
2606
+ signLocationPayload?: string | null;
2607
+ reason?: string | null;
2608
+ expiresAt?: string | null;
2609
+ status: string;
2610
+ approvedAt?: string | null;
2611
+ rejectedAt?: string | null;
2612
+ canceledAt?: string | null;
1415
2613
  }
1416
- type AgentRunLocalToolHandler = (input: unknown, context: AgentRunLocalToolHandlerContext) => Promise<unknown> | unknown;
1417
- interface AgentRunStreamOptions {
1418
- /**
1419
- * true by default. When enabled, an error event is converted into
1420
- * AgentRunStreamError after the event has been parsed.
1421
- */
1422
- throwOnError?: boolean;
2614
+ /** 提交审批;provider 侧字段由后端归一,SDK 调用方不传。 */
2615
+ interface SubmitSealApprovalRequest {
2616
+ envelopeId?: number;
2617
+ contractId?: number;
2618
+ contractHash?: string;
2619
+ hashAlgorithm?: string;
2620
+ sealId?: number;
2621
+ approverUserId?: string;
2622
+ transactorId?: number;
2623
+ signLocationType?: string;
2624
+ signLocationPayload?: string;
2625
+ reason?: string;
1423
2626
  }
1424
- interface AgentRunRunOptions extends AgentRunStreamOptions {
2627
+ interface ApproveSealApprovalQuery {
2628
+ expiresAt?: string;
2629
+ note?: string;
1425
2630
  }
1426
- interface AgentRunWithLocalToolsOptions extends AgentRunRunOptions {
1427
- timeoutMs?: number;
1428
- onEvent?: (event: AgentRunStreamEvent) => void | Promise<void>;
2631
+ interface RejectSealApprovalQuery {
2632
+ reason?: string;
1429
2633
  }
1430
- type AgentRunStreamEvent = {
1431
- type: 'run_started';
1432
- runId: string;
1433
- sessionId: string;
1434
- } | {
1435
- type: 'status';
1436
- status: AgentRunStatus | string;
1437
- message?: string;
1438
- } | {
1439
- type: 'text_delta';
1440
- text: string;
1441
- } | {
1442
- type: 'reasoning_delta';
1443
- text: string;
1444
- } | {
1445
- type: 'tool_call';
1446
- id: string;
1447
- name: string;
1448
- input?: unknown;
1449
- } | {
1450
- type: 'tool_result';
1451
- id: string;
1452
- name?: string;
1453
- result?: unknown;
1454
- error?: string;
1455
- } | {
1456
- type: 'local_tool_request';
1457
- requestId: string;
1458
- name: string;
1459
- input: unknown;
1460
- } | {
1461
- type: 'artifact';
1462
- artifact: AgentRunArtifact;
1463
- } | {
1464
- type: 'sources';
1465
- sources: unknown;
1466
- } | {
1467
- type: 'usage';
1468
- usage: AgentRunUsage;
1469
- } | {
1470
- type: 'settle';
1471
- settlement: AgentRunSettlement;
1472
- } | {
1473
- type: 'error';
1474
- error: AgentRunErrorPayload;
1475
- } | {
1476
- type: 'done';
1477
- runId: string;
1478
- status: AgentRunStatus | string;
1479
- };
1480
- declare class AgentRunStreamError extends Error {
1481
- event: Extract<AgentRunStreamEvent, {
1482
- type: 'error';
1483
- }>;
1484
- code: string;
1485
- stage: string;
1486
- retryable: boolean;
1487
- constructor(event: Extract<AgentRunStreamEvent, {
1488
- type: 'error';
1489
- }>);
2634
+ interface CancelSealApprovalQuery {
2635
+ reason?: string;
2636
+ }
2637
+ /**
2638
+ * 用印审批分页【列表项】视图。对应后端 G1 `SealApprovalPageItem`。
2639
+ *
2640
+ * {@link SealApproval} 一致的 SDK-safe 子集 + `createTime`;时间字段为
2641
+ * ISO-8601 字符串。
2642
+ */
2643
+ interface SealApprovalPageItem {
2644
+ id: number;
2645
+ envelopeId?: number | null;
2646
+ contractId?: number | null;
2647
+ contractHash?: string | null;
2648
+ hashAlgorithm?: string | null;
2649
+ sealId?: number | null;
2650
+ applicantUserId?: string | null;
2651
+ approverUserId?: string | null;
2652
+ transactorId?: number | null;
2653
+ signLocationType?: string | null;
2654
+ signLocationPayload?: string | null;
2655
+ reason?: string | null;
2656
+ expiresAt?: string | null;
2657
+ status: string;
2658
+ approvedAt?: string | null;
2659
+ rejectedAt?: string | null;
2660
+ canceledAt?: string | null;
2661
+ /** 创建时间 ISO-8601。 */
2662
+ createTime: string;
1490
2663
  }
1491
-
1492
- declare module '@acosmi/sdk-ts' {
1493
- interface Client {
1494
- /** SDK-facing cloud agent run gateway. */
1495
- readonly agentRuns: AgentRunsClient;
1496
- }
2664
+ /**
2665
+ * `listSealApprovals` 请求参数。
2666
+ *
2667
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2668
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2669
+ * 解析;SDK 不做格式校验或时区转换。
2670
+ */
2671
+ interface ListSealApprovalsRequest extends PageRequest {
2672
+ /** 审批状态过滤。 */
2673
+ status?: string;
2674
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2675
+ createTimeStart?: string;
2676
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2677
+ createTimeEnd?: string;
1497
2678
  }
1498
- declare class AgentRunsClient {
1499
- private readonly client;
1500
- constructor(client: Client);
1501
- create(req: AgentRunCreateRequest, signal?: AbortSignal): Promise<AgentRunCreateResponse>;
1502
- get(runId: string, signal?: AbortSignal): Promise<AgentRun>;
1503
- stream(runId: string, opts?: AgentRunStreamOptions, signal?: AbortSignal): AsyncIterable<AgentRunStreamEvent>;
1504
- cancel(runId: string, signal?: AbortSignal): Promise<AgentRun>;
1505
- listArtifacts(runId: string, signal?: AbortSignal): Promise<AgentRunArtifact[]>;
1506
- downloadArtifact(runId: string, artifactId: string, signal?: AbortSignal): Promise<AgentRunDownload>;
1507
- submitLocalToolResult(runId: string, result: AgentRunLocalToolResult, signal?: AbortSignal): Promise<AgentRun>;
1508
- run(req: AgentRunCreateRequest, opts?: AgentRunRunOptions, signal?: AbortSignal): AsyncIterable<AgentRunStreamEvent>;
1509
- runWithLocalTools(req: AgentRunCreateRequest, handlers: Record<string, AgentRunLocalToolHandler>, opts?: AgentRunWithLocalToolsOptions, signal?: AbortSignal): AsyncIterable<AgentRunStreamEvent>;
1510
- private runGen;
1511
- private runWithLocalToolsGen;
1512
- private invokeLocalTool;
1513
- private streamGen;
1514
- private requestAPI;
1515
- private requestRaw;
2679
+ /**
2680
+ * 用印执行记录分页【列表项】视图。对应后端 G6 `SealUsePageItem`。
2681
+ *
2682
+ * 一次用印执行(seal use)描述【该次盖章动作本身】的执行进度——envelope /
2683
+ * contract / seal / 审批联动后真正调用 provider 落章的那一笔记录,与
2684
+ * envelope 领域状态正交。SDK-safe 视图——不含 provider raw payload / 证书 /
2685
+ * storage key。时间字段为 ISO-8601 字符串。
2686
+ */
2687
+ interface SealUsePageItem {
2688
+ id: number;
2689
+ envelopeId: number;
2690
+ contractId: number;
2691
+ sealId: number;
2692
+ /** 用印执行状态。 */
2693
+ usageStatus: string;
2694
+ /** 签署位置类型(坐标 / 关键字 / 域字段等)。 */
2695
+ signLocationType?: string | null;
2696
+ /** 调起时间 ISO-8601。 */
2697
+ invokedAt?: string | null;
2698
+ /** 成功落章时间 ISO-8601。 */
2699
+ consumedAt?: string | null;
2700
+ /** 失败时的错误原因(如有)。 */
2701
+ failureReason?: string | null;
2702
+ /** 创建时间 ISO-8601。 */
2703
+ createTime: string;
1516
2704
  }
1517
-
1518
- /** 根据模型能力和请求参数自动组装 beta header 列表 */
1519
- declare function buildBetas(caps: ModelCapabilities, req: ChatRequest): string[];
1520
- /** 合并两个字符串数组并去重, 保留顺序 */
1521
- declare function uniqueMerge(base: string[], extra: string[]): string[];
1522
-
1523
- declare module '@acosmi/sdk-ts' {
1524
- interface Client {
1525
- /** 查询当前用户的权益余额 (聚合) */
1526
- getBalance(signal?: AbortSignal): Promise<EntitlementBalance>;
1527
- /** 查询详细余额 (含每条权益明细) */
1528
- getBalanceDetail(signal?: AbortSignal): Promise<BalanceDetail>;
1529
- /** 查询当前用户权益列表; status: "ACTIVE" / "EXPIRED" / "" (全部) */
1530
- listEntitlements(status: string, signal?: AbortSignal): Promise<EntitlementItem[]>;
1531
- /** 查询核销记录 (分页) */
1532
- listConsumeRecords(page: number, pageSize: number, signal?: AbortSignal): Promise<ConsumeRecordPage>;
1533
- /** 领取当月免费额度 幂等: 已领取时返回已有权益 */
1534
- claimMonthlyFree(signal?: AbortSignal): Promise<EntitlementItem>;
1535
- /** 查询当前用户在指定模型下的剩余 token (raw + ETU) */
1536
- getByModel(modelID: string, signal?: AbortSignal): Promise<ModelByQuotaResponse>;
1537
- /** 列出当前用户的全部桶 */
1538
- listBuckets(signal?: AbortSignal): Promise<ModelBucket[]>;
1539
- /** 拉取模型系数表; SDK 自带 8s TTL 内存缓存以减小调用风暴. */
1540
- listCoefficients(signal?: AbortSignal): Promise<ModelCoefficient[]>;
1541
- /** 手动失效系数缓存 (admin 调价后建议立即调一次) */
1542
- invalidateCoefficientCache(): void;
1543
- }
2705
+ /**
2706
+ * `listSealUses` 请求参数。
2707
+ *
2708
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2709
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2710
+ * 解析;SDK 不做格式校验或时区转换。
2711
+ */
2712
+ interface ListSealUsesRequest extends PageRequest {
2713
+ /** 印章 id 过滤。 */
2714
+ sealId?: number;
2715
+ /** 签署 envelope id 过滤。 */
2716
+ envelopeId?: number;
2717
+ /** 用印执行状态过滤。 */
2718
+ usageStatus?: string;
2719
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2720
+ createTimeStart?: string;
2721
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2722
+ createTimeEnd?: string;
1544
2723
  }
1545
2724
 
1546
- declare module '@acosmi/sdk-ts' {
1547
- interface Client {
1548
- /** 获取商城流量包列表 (兼容 yudao 分页和直接数组两种格式) */
1549
- listTokenPackages(signal?: AbortSignal): Promise<TokenPackage[]>;
1550
- /** 获取流量包详情 */
1551
- getTokenPackageDetail(packageID: string, signal?: AbortSignal): Promise<TokenPackage>;
1552
- /** 购买流量包 (创建订单) */
1553
- buyTokenPackage(packageID: string, payload: PayPayload | null, signal?: AbortSignal): Promise<Order>;
1554
- /** 查询订单支付状态 */
1555
- getOrderStatus(orderID: string, signal?: AbortSignal): Promise<OrderStatus>;
1556
- /** 查询我的订单列表 */
1557
- listMyOrders(signal?: AbortSignal): Promise<Order[]>;
1558
- /**
1559
- * 轮询订单支付状态直到终态
1560
- * 成功支付返回 status; 终态失败抛 OrderTerminalError
1561
- * pollIntervalMs <= 0 时默认 2 秒
1562
- */
1563
- waitForPayment(orderID: string, pollIntervalMs: number, signal?: AbortSignal): Promise<OrderStatus>;
1564
- }
2725
+ /**
2726
+ * 单个 compliance 高风险 / 收费动作的能力闸门视图。对应后端 G2 `CapabilityVO`。
2727
+ *
2728
+ * 后端为每个动作返回一条:`signEnvelope` / `createH5SigningUrl` /
2729
+ * `publishReport` / `approveSealApproval` / `executeSealUse` / `createSeal`。
2730
+ *
2731
+ * 拿不到能力时调用方必须 fail-closed(视为 `executable=false`)。`state` 复用
2732
+ * 跨域 {@link FeatureGateState} 开放联合——后端保留新增空间。
2733
+ */
2734
+ interface ComplianceCapability {
2735
+ /** 动作标识(如 `signEnvelope` / `publishReport`)。 */
2736
+ action: string;
2737
+ /** 该动作当前是否可执行。fail-closed:拿不到能力时按 false 处理。 */
2738
+ executable: boolean;
2739
+ /**
2740
+ * 不可执行的具体状态。后端取值:`executable` / `scope_missing` /
2741
+ * `not_provisioned` / `step_up_required` / `gate_closed` / `unknown`。
2742
+ */
2743
+ state: FeatureGateState;
2744
+ /** 该动作所需的 OAuth scope。 */
2745
+ requiredScopes: string[];
2746
+ /** 该动作是否需要 step-up(高风险动作二次验证)。 */
2747
+ requiredStepUp: boolean;
2748
+ /** 人类可读原因(诊断 / 展示)。 */
2749
+ reason: string;
1565
2750
  }
1566
-
1567
- declare module '@acosmi/sdk-ts' {
1568
- interface Client {
1569
- /** 获取钱包统计 (余额/月消费/月充值) */
1570
- getWalletStats(signal?: AbortSignal): Promise<WalletStats>;
1571
- /** 获取最近交易记录 */
1572
- getWalletTransactions(signal?: AbortSignal): Promise<Transaction[]>;
1573
- }
2751
+ /**
2752
+ * compliance 操作投影【列表项】视图。对应后端 G2 `OperationPageItem`。
2753
+ *
2754
+ * 与领域对象状态【正交】:描述【一次操作】本身的执行进度,而非某个履约对象的
2755
+ * 业务态。时间字段为 ISO-8601 字符串。
2756
+ */
2757
+ interface OperationPageItem {
2758
+ /** 行 id(数值主键)。 */
2759
+ id: number;
2760
+ /** 操作幂等键(跨来源统一关联键)。 */
2761
+ operationId: string;
2762
+ /** 操作状态。 */
2763
+ status: string;
2764
+ /** 是否终态。 */
2765
+ terminal: boolean;
2766
+ /** 当前状态是否允许 SDK 安全重试。 */
2767
+ retryable: boolean;
2768
+ /** 已尝试次数。 */
2769
+ attemptCount: number;
2770
+ /** 关联业务编号。 */
2771
+ businessNo?: string | null;
2772
+ /** 关联合同编号。 */
2773
+ contractNo?: string | null;
2774
+ /** 关联印章 id。 */
2775
+ sealId?: number | null;
2776
+ /** 对账状态。 */
2777
+ reconciliationStatus?: string | null;
2778
+ /** 下次重试时间 ISO-8601。 */
2779
+ nextRetryAt?: string | null;
2780
+ /** 请求发起时间 ISO-8601。 */
2781
+ requestedAt?: string | null;
2782
+ /** provider 响应时间 ISO-8601。 */
2783
+ respondedAt?: string | null;
2784
+ /** 创建时间 ISO-8601。 */
2785
+ createTime: string;
1574
2786
  }
1575
-
1576
- declare module '@acosmi/sdk-ts' {
1577
- interface Client {
1578
- /** 浏览技能商店 (公共端点, 无需认证) */
1579
- browseSkillStore(query: SkillStoreQuery, signal?: AbortSignal): Promise<SkillStoreItem[]>;
1580
- /** 浏览公共技能商店 (V3 分页接口) */
1581
- browseSkills(page: number, pageSize: number, category: string, keyword: string, tag: string, source: string, signal?: AbortSignal): Promise<SkillBrowseResponse>;
1582
- /** 轻量浏览公共技能商店 (fields=minimal, 响应体积缩减 90%+) */
1583
- browseSkillsList(page: number, pageSize: number, category: string, keyword: string, tag: string, source: string, signal?: AbortSignal): Promise<SkillBrowseListResponse>;
1584
- /** 获取技能商店中某个技能的详情 (公共端点) */
1585
- getSkillDetail(skillID: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1586
- /** key 精确查找公共技能 (公共端点) */
1587
- resolveSkill(key: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1588
- /** 安装技能到当前用户的租户空间 (需 OAuth scope: skill_store) */
1589
- installSkill(skillID: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1590
- /**
1591
- * 下载技能 ZIP 包 (公共端点, 双模式)
1592
- * token 时自动附带 (享受无限流), 无 token 时匿名 (受限流)
1593
- * @returns [data, filename]; 限流时抛 RateLimitError
1594
- */
1595
- downloadSkill(skillID: string, signal?: AbortSignal): Promise<{
1596
- data: Uint8Array;
1597
- filename: string;
1598
- }>;
1599
- /**
1600
- * 上传技能 ZIP 包
1601
- * @param scope "TENANT"
1602
- * @param intent "PERSONAL" (仅自己用) 或 "PUBLIC_INTENT" (走认证→公开)
1603
- */
1604
- uploadSkill(zipData: Uint8Array, scope: string, intent: string, signal?: AbortSignal): Promise<SkillStoreItem>;
1605
- /** 获取技能统计概览 */
1606
- getSkillSummary(signal?: AbortSignal): Promise<SkillSummary>;
1607
- /** 触发技能认证管线 (异步) */
1608
- certifySkill(skillID: string, signal?: AbortSignal): Promise<void>;
1609
- /** 查询技能认证状态 */
1610
- getCertificationStatus(skillID: string, signal?: AbortSignal): Promise<CertificationStatus>;
1611
- /** 根据自然语言描述生成技能定义 (基于独立 LLM) */
1612
- generateSkill(req: GenerateSkillRequest, signal?: AbortSignal): Promise<GenerateSkillResult>;
1613
- /** 优化已有技能定义 */
1614
- optimizeSkill(req: OptimizeSkillRequest, signal?: AbortSignal): Promise<OptimizeSkillResult>;
1615
- /** 校验技能定义正确性 */
1616
- validateSkill(skillName: string, signal?: AbortSignal): Promise<void>;
1617
- }
2787
+ /**
2788
+ * compliance 操作投影【详情】视图。对应后端 G2 `OperationDetail`。
2789
+ *
2790
+ * 当前与 {@link OperationPageItem} 字段一致——单独成类型以便后端在详情视图
2791
+ * 追加字段时不破坏列表项契约。
2792
+ */
2793
+ interface OperationDetail {
2794
+ /** id(数值主键)。 */
2795
+ id: number;
2796
+ /** 操作幂等键(跨来源统一关联键)。 */
2797
+ operationId: string;
2798
+ /** 操作状态。 */
2799
+ status: string;
2800
+ /** 是否终态。 */
2801
+ terminal: boolean;
2802
+ /** 当前状态是否允许 SDK 安全重试。 */
2803
+ retryable: boolean;
2804
+ /** 已尝试次数。 */
2805
+ attemptCount: number;
2806
+ /** 关联业务编号。 */
2807
+ businessNo?: string | null;
2808
+ /** 关联合同编号。 */
2809
+ contractNo?: string | null;
2810
+ /** 关联印章 id。 */
2811
+ sealId?: number | null;
2812
+ /** 对账状态。 */
2813
+ reconciliationStatus?: string | null;
2814
+ /** 下次重试时间 ISO-8601。 */
2815
+ nextRetryAt?: string | null;
2816
+ /** 请求发起时间 ISO-8601。 */
2817
+ requestedAt?: string | null;
2818
+ /** provider 响应时间 ISO-8601。 */
2819
+ respondedAt?: string | null;
2820
+ /** 创建时间 ISO-8601。 */
2821
+ createTime: string;
1618
2822
  }
1619
-
1620
- declare module '@acosmi/sdk-ts' {
1621
- interface Client {
1622
- /** 获取当前用户租户下的所有工具 (Skill 优先 + Plugin 兜底) */
1623
- listTools(signal?: AbortSignal): Promise<ToolView[]>;
1624
- /** 获取单个工具详情 */
1625
- getTool(toolID: string, signal?: AbortSignal): Promise<ToolView>;
1626
- }
2823
+ /**
2824
+ * `listOperations` 请求参数。
2825
+ *
2826
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2827
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2828
+ * 解析;SDK 不做格式校验或时区转换。
2829
+ */
2830
+ interface ListOperationsRequest extends PageRequest {
2831
+ /** 操作状态过滤。 */
2832
+ status?: string;
2833
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2834
+ createTimeStart?: string;
2835
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2836
+ createTimeEnd?: string;
1627
2837
  }
1628
2838
 
1629
- declare module '@acosmi/sdk-ts' {
1630
- interface Client {
1631
- /** 分页查询通知列表 */
1632
- listNotifications(page: number, pageSize: number, typeFilter: string, signal?: AbortSignal): Promise<NotificationList>;
1633
- /** 获取未读通知数量 */
1634
- getUnreadCount(signal?: AbortSignal): Promise<number>;
1635
- /** 标记单条通知已读 */
1636
- markNotificationRead(id: string, signal?: AbortSignal): Promise<void>;
1637
- /** 标记全部通知已读 */
1638
- markAllNotificationsRead(signal?: AbortSignal): Promise<void>;
1639
- /** 删除通知 */
1640
- deleteNotification(id: string, signal?: AbortSignal): Promise<void>;
1641
- /** 注册推送设备 token */
1642
- registerDevice(reg: DeviceRegistration, signal?: AbortSignal): Promise<void>;
1643
- /** 注销推送设备 token */
1644
- unregisterDevice(token: string, signal?: AbortSignal): Promise<void>;
1645
- /** 获取通知偏好设置 */
1646
- listNotificationPreferences(signal?: AbortSignal): Promise<NotificationPreference[]>;
1647
- /** 更新通知偏好 */
1648
- updateNotificationPreference(typeCode: string, pref: NotificationPreference, signal?: AbortSignal): Promise<void>;
1649
- }
2839
+ /** 模板上的可填充字段类型:签名 / 印章 / 文本 / 日期 / 勾选。 */
2840
+ type ContractTemplateFieldType = 'signature' | 'seal' | 'text' | 'date' | 'check';
2841
+ /**
2842
+ * 模板字段叠加项。一个模板包含一组字段——签名 / 印章 / 文本 / 日期 / 勾选——
2843
+ * 字段在 PDF 上的位置以 `page`(页码)+ `x`/`y`/`width`/`height`(坐标 / 尺寸)
2844
+ * 描述。SDK 不在客户端做几何 / 坐标系校验,原样透传给后端。
2845
+ */
2846
+ interface ContractTemplateField {
2847
+ /** 字段稳定 key,调用方业务侧自定。 */
2848
+ key: string;
2849
+ /** 字段类型。 */
2850
+ type: ContractTemplateFieldType;
2851
+ /** 字段在 UI 上展示的标签。 */
2852
+ label: string;
2853
+ /** PDF 页码(1-based 或调用方约定,SDK 原样透传)。 */
2854
+ page: number;
2855
+ /** PDF 坐标系横坐标。 */
2856
+ x: number;
2857
+ /** PDF 坐标系纵坐标。 */
2858
+ y: number;
2859
+ /** 字段宽度。 */
2860
+ width: number;
2861
+ /** 字段高度。 */
2862
+ height: number;
2863
+ /** 字段绑定的角色(签署人角色 key,可选)。 */
2864
+ assignedRole?: string;
2865
+ /** 字段在模板内的排序键。 */
2866
+ order: number;
2867
+ /** 是否为必填字段。 */
2868
+ required: boolean;
2869
+ }
2870
+ /** 模板状态。DRAFT 可编辑 / 删除 / 上传 PDF / publish;PUBLISHED / ARCHIVED 只读。 */
2871
+ type ContractTemplateStatus = 'DRAFT' | 'PUBLISHED' | 'ARCHIVED';
2872
+ /**
2873
+ * 合同模板详情。对应后端 G5 `ContractTemplateResp`。
2874
+ *
2875
+ * - `pdfHash` / `pdfPageCount` 在【上传 PDF】之后才有值。
2876
+ * - `currentVersion` 记录【已发布】版本号;DRAFT 阶段为 0。
2877
+ * - `fields` 是【当前编辑中】的字段叠加快照——publish 时会同步固化进版本表。
2878
+ * - 时间字段 `createTime` 为 ISO-8601 字符串。
2879
+ */
2880
+ interface ContractTemplateResp {
2881
+ id: number;
2882
+ /** 模板编号(业务编号,区别于数值主键 `id`)。 */
2883
+ templateNo: string;
2884
+ name: string;
2885
+ description?: string | null;
2886
+ status: ContractTemplateStatus;
2887
+ /** 已上传 PDF 的哈希;未上传时缺省。 */
2888
+ pdfHash?: string | null;
2889
+ /** 已上传 PDF 的页数;未上传时缺省。 */
2890
+ pdfPageCount?: number | null;
2891
+ fields: ContractTemplateField[];
2892
+ /** 已发布版本号;DRAFT 阶段为 0。 */
2893
+ currentVersion: number;
2894
+ /** 创建时间 ISO-8601。 */
2895
+ createTime: string;
1650
2896
  }
1651
-
1652
- declare module '@acosmi/sdk-ts' {
1653
- interface Client {
1654
- /**
1655
- * 配置请求前的底线防御 (体积 / deny-list / 深度)
1656
- * 传空值 {} 关闭 (所有字段为零 = 禁用)。
1657
- * 并发安全, 可在任意时间调用。
1658
- */
1659
- setDefensiveSanitize(cfg: MinimalSanitizeConfig): void;
1660
- /**
1661
- * 开启后, 每次请求前 SDK 会从 rawMessages 中剥除带 acosmi_ephemeral:true 标记的 block,
1662
- * 并联动剥除引用已剥 tool_use 的 tool_result, 避免 provider 报 "tool_use_id 不存在".
1663
- *
1664
- * 标记来源: 网关在响应 content_block_start 中 in-band 注入; 消费者把上一轮 assistant
1665
- * 回复原样拼回 history 即可触发剥离。
1666
- */
1667
- setAutoStripEphemeralHistory(on: boolean): void;
1668
- /**
1669
- * 在 buildChatRequest 开头调用, 把配置化的防御策略应用到 req。
1670
- * 未配置时立即返回, 零开销。
1671
- *
1672
- * 失败时抛错 调用方应放弃本次请求。
1673
- */
1674
- applyRequestSanitizers(req: ChatRequest): void;
1675
- }
2897
+ /**
2898
+ * 合同模板分页【列表项】视图。对应后端 G5 `ContractTemplatePageItem`。
2899
+ *
2900
+ * 与 {@link ContractTemplateResp} 一致的 SDK-safe 子集,**不含 `fields`**——
2901
+ * 字段叠加只在详情 / 版本快照里返回,分页列表不下发,避免大对象 N+1
2902
+ */
2903
+ interface ContractTemplatePageItem {
2904
+ id: number;
2905
+ templateNo: string;
2906
+ name: string;
2907
+ description?: string | null;
2908
+ status: ContractTemplateStatus;
2909
+ pdfHash?: string | null;
2910
+ pdfPageCount?: number | null;
2911
+ currentVersion: number;
2912
+ /** 创建时间 ISO-8601。 */
2913
+ createTime: string;
2914
+ }
2915
+ /**
2916
+ * 合同模板版本快照。对应后端 G5 `ContractTemplateVersion`。
2917
+ *
2918
+ * 每次 publish 会落一个版本快照,记录当时的 `name` / `pdfHash` / `fields` /
2919
+ * `statusAtSnapshot`(publish 时模板的状态字面量)。版本是【不可变】的离线复核
2920
+ * 依据。
2921
+ */
2922
+ interface ContractTemplateVersion {
2923
+ id: number;
2924
+ templateId: number;
2925
+ version: number;
2926
+ name: string;
2927
+ pdfHash?: string | null;
2928
+ fields: ContractTemplateField[];
2929
+ /** publish 时模板状态的字面量快照。 */
2930
+ statusAtSnapshot: string;
2931
+ /** 创建时间 ISO-8601。 */
2932
+ createTime: string;
2933
+ }
2934
+ /**
2935
+ * 创建合同模板请求。`fields` 可选——通常先在 DRAFT 状态创建模板、再上传 PDF、
2936
+ * 然后再单独 `updateContractTemplate` 设置 / 调整字段叠加。
2937
+ */
2938
+ interface CreateContractTemplateRequest {
2939
+ name: string;
2940
+ description?: string;
2941
+ fields?: ContractTemplateField[];
2942
+ }
2943
+ /**
2944
+ * 更新合同模板请求。仅 DRAFT 状态下允许调用——服务端在 PUBLISHED / ARCHIVED
2945
+ * 状态下会拒绝更新。所有字段可选,缺省的字段视为【不修改】。
2946
+ */
2947
+ interface UpdateContractTemplateRequest {
2948
+ name?: string;
2949
+ description?: string;
2950
+ fields?: ContractTemplateField[];
1676
2951
  }
1677
-
1678
- /** WebSocket 长连接配置 */
1679
- interface WSConfig {
1680
- /** 收到服务端事件回调 */
1681
- onEvent?: (ev: WSEvent) => void;
1682
- /** 连接建立回调 */
1683
- onConnect?: () => void;
1684
- /** 断线回调 */
1685
- onDisconnect?: (err: unknown) => void;
1686
- /** 自动订阅的主题 */
1687
- topics?: string[];
1688
- /** 最小重连间隔 (ms, 默认 2000) */
1689
- reconnectMinMs?: number;
1690
- /** 最大重连间隔 (ms, 默认 60000) */
1691
- reconnectMaxMs?: number;
1692
- /** 是否自动重连 (默认 true) */
1693
- autoReconnect?: boolean;
2952
+ /**
2953
+ * 上传模板 PDF 请求。`pdfBase64` 为 base64 编码的 PDF 原文;SDK 不在客户端做
2954
+ * PDF 解析 / 几何校验。
2955
+ */
2956
+ interface UploadContractTemplatePdfRequest {
2957
+ /** base64 编码的 PDF 原文。 */
2958
+ pdfBase64: string;
2959
+ }
2960
+ /**
2961
+ * `listContractTemplates` 请求参数。
2962
+ *
2963
+ * 继承 {@link PageRequest} 分页 / 排序字段;全部可选。`createTimeStart` /
2964
+ * `createTimeEnd` 为调用方提供的【原样字符串】,后端按 `yyyy-MM-dd HH:mm:ss`
2965
+ * 解析;SDK 不做格式校验或时区转换。
2966
+ */
2967
+ interface ListContractTemplatesRequest extends PageRequest {
2968
+ /** 模板状态过滤。 */
2969
+ status?: ContractTemplateStatus | string;
2970
+ /** 创建时间下界,`yyyy-MM-dd HH:mm:ss`。 */
2971
+ createTimeStart?: string;
2972
+ /** 创建时间上界,`yyyy-MM-dd HH:mm:ss`。 */
2973
+ createTimeEnd?: string;
1694
2974
  }
2975
+
1695
2976
  declare module '@acosmi/sdk-ts' {
1696
2977
  interface Client {
1697
- /**
1698
- * 建立 WebSocket 长连接 — 等待首次连接成功或 abort。
1699
- */
1700
- connect(cfg: WSConfig, signal?: AbortSignal): Promise<void>;
1701
- /** 优雅断开 WebSocket 连接 */
1702
- disconnect(): Promise<void>;
1703
- /** WebSocket 是否已连接 */
1704
- isConnected(): boolean;
2978
+ /** SDK-facing 时间章与电子证据 / 合同签署能力。 */
2979
+ readonly compliance: ComplianceClient;
1705
2980
  }
1706
2981
  }
2982
+ /**
2983
+ * 当 compliance polling 检测到终态失败 / 已过 timeout / step-up 时抛出。
2984
+ *
2985
+ * 分类逻辑:终态失败优先于 timeout;timeout 不算 retryable,调用方必须用新 idempotency-key
2986
+ * 重新发起整条链路。
2987
+ */
2988
+ declare class CompliancePollError extends Error {
2989
+ readonly kind: 'timeout' | 'terminal_failure' | 'step_up_required' | 'unknown';
2990
+ readonly lastInfo?: ComplianceErrorInfo;
2991
+ constructor(message: string, kind: 'timeout' | 'terminal_failure' | 'step_up_required' | 'unknown', lastInfo?: ComplianceErrorInfo);
2992
+ }
2993
+ declare class ComplianceClient {
2994
+ private readonly client;
2995
+ constructor(client: Client);
2996
+ /** 创建证据资产(写)。 */
2997
+ createEvidenceAsset(req: CreateEvidenceAssetRequest, opts?: ComplianceWriteOptions): Promise<EvidenceAsset>;
2998
+ /** 读 — 证据资产详情。 */
2999
+ getEvidenceAsset(id: number, signal?: AbortSignal): Promise<EvidenceAsset>;
3000
+ /**
3001
+ * 读 — 证据资产分页列表(compliance gateway S1)。
3002
+ *
3003
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 yudao `PageResult<T>`
3004
+ * (`{ total, list }`)。所有过滤项可选;`createTimeStart` / `createTimeEnd`
3005
+ * 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
3006
+ */
3007
+ listEvidenceAssets(req?: ListEvidenceAssetsRequest, signal?: AbortSignal): Promise<PageResult<EvidenceAssetPageItem>>;
3008
+ /**
3009
+ * 公开 verify。隐私边界:返回字段不含 PII / 合同原文 / storage / provider raw。
3010
+ *
3011
+ * 匿名可调用:未 login 时走匿名请求,不会抛 `not authorized, call login() first`。
3012
+ * 已 login / 已持有 token 时附带 `Authorization` 以保留审计上下文。public 端点不
3013
+ * 应要求认证 — 收到 401 直接抛 HTTPError,不触发 `forceRefresh`,也不做 refresh
3014
+ * replay。
3015
+ */
3016
+ verifyEvidencePublic(params: {
3017
+ evidenceNo?: string;
3018
+ publicVerifyCode?: string;
3019
+ }, signal?: AbortSignal): Promise<PublicEvidenceVerifyResult>;
3020
+ /** 申请时间章(写)。SDK 永远不传 provider 字段。 */
3021
+ issueTimestamp(req: IssueTimestampRequest, opts?: ComplianceWriteOptions): Promise<TimestampToken>;
3022
+ /** 给已有资产申请时间章。SDK 永远不传 provider 字段。 */
3023
+ issueTimestampForAsset(assetId: number, opts?: ComplianceWriteOptions): Promise<TimestampToken>;
3024
+ /** 读 — 时间章 token 详情。 */
3025
+ getTimestamp(id: number, signal?: AbortSignal): Promise<TimestampToken>;
3026
+ /**
3027
+ * 读 — 时间章分页列表(compliance gateway S1)。
3028
+ *
3029
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
3030
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
3031
+ */
3032
+ listTimestamps(req?: ListTimestampsRequest, signal?: AbortSignal): Promise<PageResult<TimestampPageItem>>;
3033
+ /** verify — 本地离线校验已申请的时间章。 */
3034
+ verifyTimestamp(req: VerifyTimestampRequest, opts?: ComplianceWriteOptions): Promise<TimestampVerifyResult>;
3035
+ /**
3036
+ * 轮询到 VERIFIED 终态。
3037
+ * - VERIFIED → 返回 token;
3038
+ * - FAILED / LOCAL_VERIFY_FAILED → 抛 {@link CompliancePollError} kind='terminal_failure';
3039
+ * - UNKNOWN / RETRYING / PENDING → 继续轮询直到 timeout;
3040
+ * - timeout → 抛 {@link CompliancePollError} kind='timeout'。
3041
+ */
3042
+ waitForTimestampVerified(id: number, opts?: CompliancePollOptions): Promise<TimestampToken>;
3043
+ /**
3044
+ * 读 — 时间章授权机构(TSA)provider 列表(compliance gateway S3)。
3045
+ *
3046
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G3 为每个 TSA provider 返回
3047
+ * 一条 {@link TsaProvider}:名称、所处环境、当前是否可用。只读视图,不含
3048
+ * provider 端点 / 凭证 / 证书等内部接入材料。
3049
+ */
3050
+ listTsaProviders(signal?: AbortSignal): Promise<TsaProvider[]>;
3051
+ /**
3052
+ * 读 — 时间章统计视图(compliance gateway S3)。
3053
+ *
3054
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 {@link TsaStats}:时间章总数
3055
+ * + 按校验状态分桶的计数。只读聚合视图。
3056
+ */
3057
+ getTsaStats(signal?: AbortSignal): Promise<TsaStats>;
3058
+ /** 构建证据包(写)。 */
3059
+ buildEvidencePackage(assetId: number, timestampTokenId?: number, opts?: ComplianceWriteOptions): Promise<EvidencePackage>;
3060
+ /**
3061
+ * 读 — 证据包分页列表(compliance gateway S1)。
3062
+ *
3063
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
3064
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
3065
+ */
3066
+ listEvidencePackages(req?: ListEvidencePackagesRequest, signal?: AbortSignal): Promise<PageResult<EvidencePackagePageItem>>;
3067
+ /** 创建证据报告(写)。 */
3068
+ createReport(req: CreateReportRequest, opts?: ComplianceWriteOptions): Promise<ComplianceReport>;
3069
+ /** 读 — 报告详情。 */
3070
+ getReport(id: number, signal?: AbortSignal): Promise<ComplianceReport>;
3071
+ /**
3072
+ * 读 — 证据报告分页列表(compliance gateway S1)。
3073
+ *
3074
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
3075
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
3076
+ */
3077
+ listReports(req?: ListReportsRequest, signal?: AbortSignal): Promise<PageResult<ReportPageItem>>;
3078
+ /**
3079
+ * 发布报告(写,step-up 必须)。
3080
+ *
3081
+ * `@status gated` — step-up 闸门未闭合前服务端会一致返回
3082
+ * `COMPLIANCE_STEP_UP_REQUIRED`(数值码 1031000013)。SDK 不会自动重试、不伪成功;
3083
+ * 调用方需要引导用户重新做 OAuth introspection 或重新登录后再次调用本方法
3084
+ *(使用同一 idempotency-key)。方法状态分级见 `docs/compliance.md` Method Status。
3085
+ */
3086
+ publishReport(id: number, opts?: ComplianceWriteOptions): Promise<ComplianceReport>;
3087
+ /**
3088
+ * 下载报告(读)。返回 {@link ReportDownload}:报告 hash + 资产 hash + 证据包 hash +
3089
+ * 时间章 serial/genTime,足以离线复核。
3090
+ * 不返回 bodyCanonicalJson / storage key / subject snapshot id。
3091
+ */
3092
+ downloadReport(id: number, signal?: AbortSignal): Promise<ReportDownload>;
3093
+ /** 创建 envelope(写)。返回 envelope id。 */
3094
+ createSigningEnvelope(req: CreateSigningEnvelopeRequest, opts?: ComplianceWriteOptions): Promise<number>;
3095
+ /** 读 — envelope 详情。租户由服务端从 compliance token principal 推导。 */
3096
+ getSigningEnvelope(envelopeId: number, signal?: AbortSignal): Promise<SigningEnvelope>;
3097
+ /**
3098
+ * 读 — 签署 envelope 分页列表(compliance gateway S1)。
3099
+ *
3100
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
3101
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
3102
+ */
3103
+ listSigningEnvelopes(req?: ListSigningEnvelopesRequest, signal?: AbortSignal): Promise<PageResult<SigningEnvelopePageItem>>;
3104
+ /**
3105
+ * 正式签署(写,step-up 必须)。
3106
+ *
3107
+ * `@status gated` — 服务端闸门关闭时会一致返回 `ENVELOPE_GATE_CLOSED` (1031004004)。
3108
+ * SDK 不重试、不伪成功;调用方应该将该错误展示为"功能未开放"。
3109
+ */
3110
+ signEnvelope(envelopeId: number, req: SignEnvelopeRequest, opts?: ComplianceWriteOptions): Promise<void>;
3111
+ /**
3112
+ * 创建 H5 签署短链(写,step-up 必须)。
3113
+ *
3114
+ * `@status gated` — 同 {@link signEnvelope}:服务端闸门关闭时 SDK 不重试、不伪成功。
3115
+ */
3116
+ createH5SigningUrl(envelopeId: number, req: CreateH5SigningUrlRequest, opts?: ComplianceWriteOptions): Promise<string>;
3117
+ /** 同步 provider 状态(写但只读对账,不创建新 provider 请求)。 */
3118
+ syncSigningEnvelopeStatus(envelopeId: number, opts?: ComplianceWriteOptions): Promise<void>;
3119
+ /**
3120
+ * 读 — envelope 下挂的合同列表(compliance gateway S4)。
3121
+ *
3122
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G4 为每份挂在该 envelope 上的
3123
+ * 合同返回一条 {@link EnvelopeContractItem}:编号 / 标题 / MIME / 大小 / 哈希
3124
+ * 指纹 / 状态。返回普通数组(非 `PageResult`)。SDK-safe 视图——不含合同原文 /
3125
+ * storage key / provider raw payload。
3126
+ */
3127
+ listEnvelopeContracts(envelopeId: number, signal?: AbortSignal): Promise<EnvelopeContractItem[]>;
3128
+ /**
3129
+ * 读 — envelope 关联的 provider 请求列表(compliance gateway S4)。
3130
+ *
3131
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G4 复用操作投影
3132
+ * {@link OperationPageItem}:描述每次 provider 请求本身的执行进度,与 envelope
3133
+ * 领域状态正交。返回普通数组(非 `PageResult`)。
3134
+ */
3135
+ listEnvelopeProviderRequests(envelopeId: number, signal?: AbortSignal): Promise<OperationPageItem[]>;
3136
+ /**
3137
+ * 作废 envelope(写,compliance gateway S4)。
3138
+ *
3139
+ * 走 compliance 写路径——发送前 `ensureToken` 一次、不自动重试、`401` 不刷新
3140
+ * 重放;支持 `Idempotency-Key` header(强烈建议调用方持久化幂等键,重试 / 恢复
3141
+ * 时复用,避免重复作废)。`req.reason` 为必填的作废原因,随 JSON body 提交。
3142
+ */
3143
+ voidEnvelope(envelopeId: number, req: VoidEnvelopeRequest, opts?: ComplianceWriteOptions): Promise<boolean>;
3144
+ /**
3145
+ * 提交用印审批申请(写)。
3146
+ *
3147
+ * `@status production-ready` — 服务端以 `Idempotency-Key` + 业务请求指纹做重放保护:
3148
+ * 同 key + 同请求 → 返回原审批 id;同 key + 不同请求 → 拒绝复用幂等键。强烈建议调用方
3149
+ * 持久化 `idempotencyKey`,网络重试 / 任务恢复时复用,避免重复创建审批单。
3150
+ */
3151
+ submitSealApproval(req: SubmitSealApprovalRequest, opts?: ComplianceWriteOptions): Promise<number>;
3152
+ /**
3153
+ * 审批通过用印申请(写,step-up 必须)。
3154
+ *
3155
+ * `@status gated` — step-up 未闭合前服务端会返回 `COMPLIANCE_STEP_UP_REQUIRED`。
3156
+ * SDK 不重试、不伪成功。方法状态分级见 `docs/compliance.md` Method Status。
3157
+ */
3158
+ approveSealApproval(id: number, query: ApproveSealApprovalQuery, opts?: ComplianceWriteOptions): Promise<void>;
3159
+ rejectSealApproval(id: number, query: RejectSealApprovalQuery, opts?: ComplianceWriteOptions): Promise<void>;
3160
+ cancelSealApproval(id: number, query: CancelSealApprovalQuery, opts?: ComplianceWriteOptions): Promise<void>;
3161
+ listPendingSealApprovals(signal?: AbortSignal): Promise<SealApproval[]>;
3162
+ getSealApproval(id: number, signal?: AbortSignal): Promise<SealApproval>;
3163
+ /**
3164
+ * 读 — 用印审批分页列表(compliance gateway S1)。
3165
+ *
3166
+ * 与 {@link listPendingSealApprovals}(仅 pending、不分页)不同,本方法支持分页与
3167
+ * 状态 / 时间过滤。走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;
3168
+ * `createTimeStart` / `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,
3169
+ * SDK 原样透传。
3170
+ */
3171
+ listSealApprovals(req?: ListSealApprovalsRequest, signal?: AbortSignal): Promise<PageResult<SealApprovalPageItem>>;
3172
+ /**
3173
+ * 读 — 用印执行记录分页列表(compliance gateway S6)。
3174
+ *
3175
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 yudao `PageResult<T>`
3176
+ * (`{ total, list }`)。一次用印执行(seal use)描述 envelope / contract /
3177
+ * seal / 审批联动后【真正调用 provider 落章】的那一笔记录,与 envelope
3178
+ * 领域状态正交。所有过滤项可选;`createTimeStart` / `createTimeEnd` 由调用方
3179
+ * 按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
3180
+ *
3181
+ * 与后端复用同一只读 scope `CONTRACT_SIGNING_READ`
3182
+ *({@link ScopeComplianceContractSigningRead})——不引入新 scope。
3183
+ */
3184
+ listSealUses(req?: ListSealUsesRequest, signal?: AbortSignal): Promise<PageResult<SealUsePageItem>>;
3185
+ getProviderRequest(id: number, signal?: AbortSignal): Promise<ProviderRequestStatusView>;
3186
+ /**
3187
+ * 轮询 provider request 到 SUCCESS / FAILED 终态。
3188
+ * - SUCCESS / FAILED → 返回最后视图;
3189
+ * - UNKNOWN / RETRYING / PENDING → 继续轮询;
3190
+ * - timeout → 抛 {@link CompliancePollError} kind='timeout',不自动重发原 provider 请求。
3191
+ *
3192
+ * SUCCESS 不代表 billing 已 commit;调用方仍需通过业务侧 envelope / asset 终态判断。
3193
+ */
3194
+ waitForProviderRequestTerminal(id: number, opts?: CompliancePollOptions): Promise<ProviderRequestStatusView>;
3195
+ /**
3196
+ * 读 — compliance 能力闸门列表(compliance gateway S2)。
3197
+ *
3198
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G2 为每个高风险 / 收费动作
3199
+ * (`signEnvelope` / `createH5SigningUrl` / `publishReport` /
3200
+ * `approveSealApproval` / `executeSealUse` / `createSeal`)返回一条
3201
+ * {@link ComplianceCapability}:是否可执行、所处状态、所需 scope / step-up。
3202
+ *
3203
+ * 调用方在高风险动作执行【前】查询本结果做门控;拿不到能力时必须 fail-closed
3204
+ *(按 `executable=false` 处理)。
3205
+ */
3206
+ getCapabilities(signal?: AbortSignal): Promise<ComplianceCapability[]>;
3207
+ /**
3208
+ * 读 — 单个动作的能力闸门视图(便捷方法)。
3209
+ *
3210
+ * 拉取完整 {@link getCapabilities} 列表并返回 `action` 匹配的那一条,无匹配时
3211
+ * 返回 `undefined`。**每次调用产生一次网络请求**——需要门控多个动作时应改用
3212
+ * {@link getCapabilities} 一次性取回再本地查表,避免重复请求。
3213
+ *
3214
+ * 与 {@link getCapabilities} 一致走 GET 读路径(允许 401 单次刷新重放)。
3215
+ */
3216
+ getFeatureGate(action: string, signal?: AbortSignal): Promise<ComplianceCapability | undefined>;
3217
+ /**
3218
+ * 读 — compliance 操作投影分页列表(compliance gateway S2)。
3219
+ *
3220
+ * 走 GET 读路径。返回 yudao `PageResult<T>`(`{ total, list }`)。所有过滤项
3221
+ * 可选;`createTimeStart` / `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss`
3222
+ * 提供,SDK 原样透传,不做格式校验或时区转换。
3223
+ *
3224
+ * 操作投影描述【一次操作】本身的执行进度,与履约对象的领域状态正交。
3225
+ */
3226
+ listOperations(req?: ListOperationsRequest, signal?: AbortSignal): Promise<PageResult<OperationPageItem>>;
3227
+ /**
3228
+ * 读 — compliance 操作投影详情(compliance gateway S2)。
3229
+ *
3230
+ * `id` 为数值行主键(非 `operationId` 幂等键)。走 GET 读路径(允许 401 单次
3231
+ * 刷新重放)。
3232
+ */
3233
+ getOperation(id: number, signal?: AbortSignal): Promise<OperationDetail>;
3234
+ /**
3235
+ * 创建合同模板(写)。
3236
+ *
3237
+ * 走 compliance 写路径——发送前 `ensureToken` 一次、不自动重试、`401` 不刷新
3238
+ * 重放;支持 `Idempotency-Key` header(强烈建议调用方持久化幂等键,重试 / 恢复
3239
+ * 时复用,避免重复创建模板)。模板创建后初始状态为 `DRAFT`。
3240
+ */
3241
+ createContractTemplate(req: CreateContractTemplateRequest, opts?: ComplianceWriteOptions): Promise<ContractTemplateResp>;
3242
+ /**
3243
+ * 更新合同模板(写,仅 DRAFT 状态)。
3244
+ *
3245
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。所有字段
3246
+ * 可选,缺省字段视为不修改。服务端在 PUBLISHED / ARCHIVED 状态下会拒绝更新。
3247
+ */
3248
+ updateContractTemplate(id: number, req: UpdateContractTemplateRequest, opts?: ComplianceWriteOptions): Promise<ContractTemplateResp>;
3249
+ /**
3250
+ * 删除合同模板(写,仅 DRAFT 状态)。
3251
+ *
3252
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。服务端
3253
+ * 在 PUBLISHED / ARCHIVED 状态下会拒绝删除——已发布的模板应改走 `archive`。
3254
+ */
3255
+ deleteContractTemplate(id: number, opts?: ComplianceWriteOptions): Promise<void>;
3256
+ /** 读 — 合同模板详情。 */
3257
+ getContractTemplate(id: number, signal?: AbortSignal): Promise<ContractTemplateResp>;
3258
+ /**
3259
+ * 读 — 合同模板分页列表(compliance gateway S5)。
3260
+ *
3261
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 yudao `PageResult<T>`
3262
+ * (`{ total, list }`)。所有过滤项可选;`createTimeStart` / `createTimeEnd`
3263
+ * 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。列表项视图
3264
+ * {@link ContractTemplatePageItem} 不含 `fields`——字段叠加只在详情 / 版本
3265
+ * 快照里返回。
3266
+ */
3267
+ listContractTemplates(req?: ListContractTemplatesRequest, signal?: AbortSignal): Promise<PageResult<ContractTemplatePageItem>>;
3268
+ /**
3269
+ * 上传合同模板 PDF(写)。
3270
+ *
3271
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。请求体
3272
+ * 为 `{ pdfBase64 }`;SDK 不在客户端做 PDF 解析 / 几何校验,原样透传给后端。
3273
+ * 返回上传后的最新模板视图(含 `pdfHash` / `pdfPageCount`)。
3274
+ */
3275
+ uploadContractTemplatePdf(id: number, req: UploadContractTemplatePdfRequest, opts?: ComplianceWriteOptions): Promise<ContractTemplateResp>;
3276
+ /**
3277
+ * 发布合同模板(写)。DRAFT → PUBLISHED,落版本快照。
3278
+ *
3279
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。
3280
+ * publish 后 `currentVersion` 递增,`fields` 与 `pdfHash` 同步固化进版本表。
3281
+ */
3282
+ publishContractTemplate(id: number, opts?: ComplianceWriteOptions): Promise<ContractTemplateResp>;
3283
+ /**
3284
+ * 归档合同模板(写)。PUBLISHED → ARCHIVED。
3285
+ *
3286
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。
3287
+ * 已归档模板只读,不再允许 publish / 编辑 / 删除。
3288
+ */
3289
+ archiveContractTemplate(id: number, opts?: ComplianceWriteOptions): Promise<ContractTemplateResp>;
3290
+ /**
3291
+ * 读 — 合同模板版本快照列表。
3292
+ *
3293
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 {@link ContractTemplateVersion}
3294
+ * 普通数组(非 `PageResult`)——每次 publish 落一个不可变快照,记录当时的
3295
+ * `name` / `pdfHash` / `fields` / `statusAtSnapshot`,是离线复核 / 版本对账
3296
+ * 的依据。
3297
+ */
3298
+ listContractTemplateVersions(id: number, signal?: AbortSignal): Promise<ContractTemplateVersion[]>;
3299
+ classifyError(err: unknown): ComplianceErrorInfo | null;
3300
+ /**
3301
+ * 读路径:GET / 公开 verify。允许 401 单次刷新后重放(GET 幂等安全)。
3302
+ * 与 client.doJSONFullInternal 行为一致;不复用其代码因为 base URL 不同。
3303
+ */
3304
+ private read;
3305
+ /**
3306
+ * 公开读路径:public verify。
3307
+ *
3308
+ * 与 {@link read} 的区别 — public 端点不应要求认证:
3309
+ * - 无 token 时匿名请求:ensureToken 抛 `not authorized` 会被吞掉,继续匿名发送。
3310
+ * - 有 token 时附带 `Authorization`,保留后端审计上下文。
3311
+ * - 不做 401 refresh replay:401 直接抛 HTTPError,不触发 `forceRefresh`。
3312
+ *
3313
+ * URL 仍走 `client.complianceURL(path)`,不复用 `/api/v4`;底层复用
3314
+ * `client.doRequest`,不新增 fetch/axios 直连。
3315
+ */
3316
+ private publicRead;
3317
+ /**
3318
+ * 写路径:POST。
3319
+ * - 发送前 ensureToken 一次确保 token fresh。
3320
+ * - 不自动 401 重放:401 → 抛 HTTPError;调用方必须自己刷新 token 后用同一
3321
+ * idempotency-key 重新发起,避免 provider 侧重复请求。
3322
+ * - 不走 doRequestWithRetry:写操作不允许 5xx/timeout 自动重试。
3323
+ */
3324
+ private write;
3325
+ private executeJson;
3326
+ private poll;
3327
+ }
1707
3328
 
1708
3329
  /** POST /api/v4/crabcode_cli_feedback 返回体 */
1709
3330
  interface BugReportResult {
@@ -1763,4 +3384,4 @@ declare module '@acosmi/sdk-ts' {
1763
3384
  }
1764
3385
  }
1765
3386
 
1766
- export { type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRunOptions, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApproveSealApprovalQuery, type AuthorizeResult, BalanceDetail, type BlockMeta, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type CancelSealApprovalQuery, CertificationStatus, ChatRequest, ChatResponse, Client, ClientRegistration, type ComplianceAssetType, type ComplianceBillingDisplayStatus, ComplianceClient, type ComplianceClientErrorCode, type ComplianceDigestSource, type ComplianceEnvelopeStatus, type ComplianceErrorInfo, type ComplianceErrorKey, type ComplianceHashAlgorithm, CompliancePollError, type CompliancePollOptions, type CompliancePrivacyLevel, type ComplianceProviderRequestStatus, type ComplianceProviderStatus, type ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, ConsumeRecordPage, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, DefaultRetryPolicy, DeviceRegistration, EntitlementBalance, EntitlementItem, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, type EvidenceAsset, type EvidencePackage, FileTokenStore, type FilterStatus, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, GenerateSkillRequest, GenerateSkillResult, InMemoryTokenStore, InputModality, type IssueTimestampRequest, LocalStorageTokenStore, type LoginErrCode, type LoginEvent, type LoginEventType, type LoginOptions, ManagedModel, ModelBucket, ModelByQuotaResponse, ModelCapabilities, ModelCoefficient, NotificationList, NotificationPreference, type OAuthMetadataProfile, OptimizeSkillRequest, OptimizeSkillResult, Order, OrderStatus, PayPayload, ProviderAdapter, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, QuotaSummary, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type ReportDownload, type RetryPolicy, type RetryRequestInfo, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, type SealApproval, ServerMetadata, type SignEnvelopeRequest, type SigningEnvelope, SkillBrowseListResponse, SkillBrowseResponse, SkillStoreItem, SkillStoreQuery, SkillSummary, SourcesEvent, StreamEvent, StreamSettlement, type SubmitSealApprovalRequest, type TimestampToken, type TimestampVerifyResult, TokenPackage, TokenResponse, TokenSet, type TokenStore, ToolView, Transaction, type VerifyTimestampRequest, type WSConfig, WSEvent, WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, allScopes, authorize, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSLError, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, refreshToken, register, registerWebOAuthClient, revokeToken, skillScopes, uniqueMerge };
3387
+ export { type APIResponse, type AgentRun, type AgentRunArtifact, type AgentRunArtifactList, type AgentRunArtifactPolicy, type AgentRunCreateRequest, type AgentRunCreateResponse, type AgentRunDownload, type AgentRunErrorPayload, type AgentRunLocalContextPolicy, type AgentRunLocalToolHandler, type AgentRunLocalToolHandlerContext, type AgentRunLocalToolResult, type AgentRunRunOptions, type AgentRunSettlement, type AgentRunStatus, AgentRunStreamError, type AgentRunStreamEvent, type AgentRunStreamOptions, type AgentRunUsage, type AgentRunWithLocalToolsOptions, AgentRunsClient, AnthropicResponse, type ApiClientRef, type ApproveSealApprovalQuery, type AuthorizeResult, type BalanceDetail, type BillingPreflightResult, type BlockMeta, type BrowserRefreshMode, type BugReportResult, type BugView, BusinessError, type CancelSealApprovalQuery, type CertificationStatus, ChatRequest, ChatResponse, Client, type ClientRegistration, type ComplianceAssetType, 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 ComplianceReport, type ComplianceScope, type ComplianceSealApprovalStatus, type ComplianceTimestampVerificationStatus, type ComplianceWriteOptions, type Config, type ConsumeRecord, type ConsumeRecordPage, type ContractTemplateField, type ContractTemplateFieldType, type ContractTemplatePageItem, type ContractTemplateResp, type ContractTemplateStatus, type ContractTemplateVersion, type CreateContractTemplateRequest, type CreateEvidenceAssetRequest, type CreateH5SigningUrlRequest, type CreateReportRequest, type CreateSigningEnvelopeRequest, type CreateWebAuthorizationRequestOptions, DefaultRetryPolicy, type DeviceRegistration, 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, InMemoryTokenStore, InputModality, type IssueTimestampRequest, 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 ModelBucket, type ModelByQuotaResponse, ModelCapabilities, type ModelCoefficient, ModelNotFoundError, NetworkError, type Notification, type NotificationList, type NotificationPreference, type NotificationUnreadCount, type OAuthMetadataProfile, 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 OrderStatus, OrderTerminalError, type PageRequest, type PageResult, type PayPayload, type PrincipalRef, ProviderAdapter, type ProviderRequestStatus, type ProviderRequestStatusView, type PublicEvidenceVerifyResult, QuotaSummary, RETRY_ADVICE_REASONS, RateLimitError, type RegisterWebOAuthClientOptions, type RejectSealApprovalQuery, type ReportDownload, type ReportPageItem, type RetryAdvice, type RetryAdviceReason, type RetryPolicy, type RetryRequestInfo, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, 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, StreamError, StreamEvent, StreamSettlement, type SubmitSealApprovalRequest, 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 VerifyStatus, type VerifyTimestampRequest, type VoidEnvelopeRequest, type WSConfig, type WSEvent, type WalletStats, type WebAuthorizationCallbackParams, type WebAuthorizationPending, type WebAuthorizationRequest, type YudaoPageResult, allScopes, apiResponseBusinessError, apiResponseGetMessage, authorize, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, isBillingConfirmable, isComplianceBusinessError, isComplianceTerminalError, isSSLError, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newTokenSet, parseNotificationEvent, refreshToken, register, registerWebOAuthClient, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, skillScopes, tokenSetIsExpired, uniqueMerge };