@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
@@ -10,11 +10,7 @@ var __export = (target, all) => {
10
10
  __defProp(target, name, { get: all[name], enumerable: true });
11
11
  };
12
12
 
13
- // src/types.ts
14
- function tokenSetIsExpired(t) {
15
- const expiresAt = new Date(t.expires_at).getTime();
16
- return Date.now() > expiresAt - 3e4;
17
- }
13
+ // src/models/types.ts
18
14
  function bucketInfoIsCommercial(b) {
19
15
  if (!b) return false;
20
16
  return b.bucketClass.toLowerCase() === exports.BucketClassCommercial.toLowerCase();
@@ -62,23 +58,6 @@ function parseSourcesEvent(ev) {
62
58
  }
63
59
  return { sources: wrapper.sources, session_id: wrapper.session_id };
64
60
  }
65
- function anthropicResponseTextContent(r) {
66
- const parts = [];
67
- for (const b of r.content) {
68
- if (b.type === "text" && b.text) parts.push(b.text);
69
- }
70
- return parts.join("");
71
- }
72
- function anthropicResponseThinkingContent(r) {
73
- const parts = [];
74
- for (const b of r.content) {
75
- if (b.type === "thinking" && b.thinking) parts.push(b.thinking);
76
- }
77
- return parts.join("");
78
- }
79
- function anthropicResponseToolUseBlocks(r) {
80
- return r.content.filter((b) => b.type === "tool_use");
81
- }
82
61
  function parseSettlement(ev) {
83
62
  if (ev.event !== "settled" && ev.event !== "pending_settle") {
84
63
  return null;
@@ -99,36 +78,9 @@ function parseSettlement(ev) {
99
78
  callRemaining: s.callRemaining ?? -1
100
79
  };
101
80
  }
102
- function apiResponseGetMessage(r) {
103
- return r.message ?? r.msg ?? "";
104
- }
105
- function apiResponseBusinessError(r) {
106
- if (r.code !== 0) {
107
- return new exports.BusinessError(r.code, apiResponseGetMessage(r));
108
- }
109
- return null;
110
- }
111
- function parseNotificationEvent(ev) {
112
- if (ev.type !== "event" || ev.topic !== "system") {
113
- return null;
114
- }
115
- if (ev.data == null) return null;
116
- let n;
117
- try {
118
- if (typeof ev.data === "string") {
119
- n = JSON.parse(ev.data);
120
- } else {
121
- n = ev.data;
122
- }
123
- } catch {
124
- return null;
125
- }
126
- if (!n.id) return null;
127
- return n;
128
- }
129
- exports.BucketClassCommercial = void 0; exports.BucketClassGeneric = void 0; exports.ThinkingOff = void 0; exports.ThinkingHigh = void 0; exports.ThinkingMax = void 0; exports.ThinkingHighMinMaxTokens = void 0; exports.ThinkingMaxFallbackMaxTokens = void 0; exports.ServerToolTypeWebSearch = void 0; exports.RateLimitError = void 0; exports.BusinessError = void 0; exports.OrderTerminalError = void 0; exports.ModelNotFoundError = void 0; exports.HTTPError = void 0; exports.NetworkError = void 0; exports.StreamError = void 0;
81
+ exports.BucketClassCommercial = void 0; exports.BucketClassGeneric = void 0; exports.ThinkingOff = void 0; exports.ThinkingHigh = void 0; exports.ThinkingMax = void 0; exports.ThinkingHighMinMaxTokens = void 0; exports.ThinkingMaxFallbackMaxTokens = void 0; exports.ServerToolTypeWebSearch = void 0;
130
82
  var init_types = __esm({
131
- "src/types.ts"() {
83
+ "src/models/types.ts"() {
132
84
  exports.BucketClassCommercial = "COMMERCIAL";
133
85
  exports.BucketClassGeneric = "GENERIC";
134
86
  exports.ThinkingOff = "off";
@@ -137,6 +89,13 @@ var init_types = __esm({
137
89
  exports.ThinkingHighMinMaxTokens = 32e3;
138
90
  exports.ThinkingMaxFallbackMaxTokens = 128e3;
139
91
  exports.ServerToolTypeWebSearch = "web_search_20250305";
92
+ }
93
+ });
94
+
95
+ // src/shared/errors.ts
96
+ exports.RateLimitError = void 0; exports.BusinessError = void 0; exports.OrderTerminalError = void 0; exports.ModelNotFoundError = void 0; exports.HTTPError = void 0; exports.NetworkError = void 0; exports.StreamError = void 0;
97
+ var init_errors = __esm({
98
+ "src/shared/errors.ts"() {
140
99
  exports.RateLimitError = class extends Error {
141
100
  retryAfter;
142
101
  raw;
@@ -256,7 +215,7 @@ var init_types = __esm({
256
215
  }
257
216
  });
258
217
 
259
- // src/betas.ts
218
+ // src/models/betas.ts
260
219
  function buildBetas(caps, req) {
261
220
  const betas = [];
262
221
  if (caps.supports_isp) {
@@ -303,7 +262,7 @@ function uniqueMerge(base, extra) {
303
262
  }
304
263
  var betaInterleavedThinking, betaContext1M, betaContextManagement, betaStructuredOutputs, betaAdvancedToolUse, betaEffort, betaPromptCachingScope, betaFastMode, betaRedactThinking, betaTokenEfficientTools;
305
264
  var init_betas = __esm({
306
- "src/betas.ts"() {
265
+ "src/models/betas.ts"() {
307
266
  init_types();
308
267
  betaInterleavedThinking = "interleaved-thinking-2025-05-14";
309
268
  betaContext1M = "context-1m-2025-08-07";
@@ -318,7 +277,7 @@ var init_betas = __esm({
318
277
  }
319
278
  });
320
279
 
321
- // src/adapters/anthropic.ts
280
+ // src/models/adapters/anthropic.ts
322
281
  function resolveThinkingLevel(body, req, caps) {
323
282
  const level = req.thinking?.level ?? "";
324
283
  if (level === exports.ThinkingOff) {
@@ -365,8 +324,9 @@ function resolveThinkingLevel(body, req, caps) {
365
324
  }
366
325
  exports.AnthropicAdapter = void 0;
367
326
  var init_anthropic = __esm({
368
- "src/adapters/anthropic.ts"() {
327
+ "src/models/adapters/anthropic.ts"() {
369
328
  init_types();
329
+ init_errors();
370
330
  init_betas();
371
331
  init_adapters();
372
332
  exports.AnthropicAdapter = class {
@@ -500,7 +460,7 @@ var init_anthropic = __esm({
500
460
  }
501
461
  });
502
462
 
503
- // src/adapters/openai.ts
463
+ // src/models/adapters/openai.ts
504
464
  var openai_exports = {};
505
465
  __export(openai_exports, {
506
466
  OpenAIAdapter: () => exports.OpenAIAdapter,
@@ -695,8 +655,9 @@ function newOpenAIStreamConverter() {
695
655
  }
696
656
  exports.OpenAIAdapter = void 0; var OpenAIStreamConverter;
697
657
  var init_openai = __esm({
698
- "src/adapters/openai.ts"() {
658
+ "src/models/adapters/openai.ts"() {
699
659
  init_types();
660
+ init_errors();
700
661
  init_adapters();
701
662
  exports.OpenAIAdapter = class {
702
663
  format() {
@@ -964,7 +925,7 @@ var init_openai = __esm({
964
925
  }
965
926
  });
966
927
 
967
- // src/adapters/index.ts
928
+ // src/models/adapters/index.ts
968
929
  function getAdapter(provider) {
969
930
  const a = adapterRegistry[provider.toLowerCase()];
970
931
  if (a) return a;
@@ -996,7 +957,7 @@ function getAdapterForModel(m) {
996
957
  }
997
958
  exports.ProviderFormat = void 0; var adapterRegistry, defaultOpenAIAdapter;
998
959
  var init_adapters = __esm({
999
- "src/adapters/index.ts"() {
960
+ "src/models/adapters/index.ts"() {
1000
961
  init_anthropic();
1001
962
  init_openai();
1002
963
  exports.ProviderFormat = /* @__PURE__ */ ((ProviderFormat2) => {
@@ -1013,50 +974,31 @@ var init_adapters = __esm({
1013
974
  }
1014
975
  });
1015
976
 
1016
- // src/index.ts
977
+ // src/core/client.ts
1017
978
  init_types();
1018
979
 
1019
- // src/model-helpers.ts
1020
- function modelSupportsInputModality(model, modality) {
1021
- if (!model) return false;
1022
- const mods = model.inputModalities;
1023
- if (!Array.isArray(mods)) return false;
1024
- return mods.includes(modality);
980
+ // src/auth/types.ts
981
+ function tokenSetIsExpired(t) {
982
+ const expiresAt = new Date(t.expires_at).getTime();
983
+ return Date.now() > expiresAt - 3e4;
1025
984
  }
1026
- function modelSupportsImageInput(model) {
1027
- return modelSupportsInputModality(model, "image");
985
+
986
+ // src/core/client.ts
987
+ init_errors();
988
+
989
+ // src/shared/api-response.ts
990
+ init_errors();
991
+ function apiResponseGetMessage(r) {
992
+ return r.message ?? r.msg ?? "";
1028
993
  }
1029
- function findFirstModelByInputModality(models, modality) {
1030
- if (!Array.isArray(models)) return null;
1031
- for (const m of models) {
1032
- if (!m) continue;
1033
- if (m.isEnabled === false) continue;
1034
- if (!modelSupportsInputModality(m, modality)) continue;
1035
- return m;
994
+ function apiResponseBusinessError(r) {
995
+ if (r.code !== 0) {
996
+ return new exports.BusinessError(r.code, apiResponseGetMessage(r));
1036
997
  }
1037
998
  return null;
1038
999
  }
1039
- function findDesktopVisualUnderstandingModel(models) {
1040
- if (!Array.isArray(models)) return null;
1041
- const candidates = [];
1042
- for (const m of models) {
1043
- if (!m) continue;
1044
- if (m.isEnabled === false) continue;
1045
- if (m.capabilities?.supports_desktop_visual_understanding !== true) continue;
1046
- if (!modelSupportsInputModality(m, "image")) continue;
1047
- candidates.push(m);
1048
- }
1049
- if (candidates.length === 0) return null;
1050
- for (const m of candidates) {
1051
- if (m.isDefault === true) return m;
1052
- }
1053
- return candidates[0];
1054
- }
1055
-
1056
- // src/index.ts
1057
- init_adapters();
1058
1000
 
1059
- // src/auth.ts
1001
+ // src/auth/auth.ts
1060
1002
  var authTimeoutMs = 3e4;
1061
1003
  async function discoverWithProfile(serverURL, profile, signal) {
1062
1004
  let parsed;
@@ -1506,251 +1448,29 @@ function withTimeout(ms, parent) {
1506
1448
  };
1507
1449
  }
1508
1450
 
1509
- // src/scopes.ts
1510
- var ScopeAI = "ai";
1511
- var ScopeSkills = "skills";
1512
- var ScopeAccount = "account";
1513
- var ScopeModels = "models";
1514
- var ScopeModelsChat = "models:chat";
1515
- var ScopeEntitlements = "entitlements";
1516
- var ScopeTokenPackages = "token-packages";
1517
- var ScopeSkillStore = "skill_store";
1518
- var ScopeTools = "tools";
1519
- var ScopeToolsExecute = "tools:execute";
1520
- var ScopeWallet = "wallet";
1521
- var ScopeWalletReadonly = "wallet:readonly";
1522
- var ScopeProfile = "profile";
1523
- var ScopeComplianceEvidenceRead = "compliance:evidence:read";
1524
- var ScopeComplianceEvidenceWrite = "compliance:evidence:write";
1525
- var ScopeComplianceTimestampIssue = "compliance:timestamp:issue";
1526
- var ScopeComplianceTimestampVerify = "compliance:timestamp:verify";
1527
- var ScopeComplianceContractSigningRead = "compliance:contract_signing:read";
1528
- var ScopeComplianceContractSigningWrite = "compliance:contract_signing:write";
1529
- var ScopeComplianceSealManage = "compliance:seal:manage";
1530
- var ScopeComplianceSealApprovalRequest = "compliance:seal_approval:request";
1531
- var ScopeComplianceSealApprovalApprove = "compliance:seal_approval:approve";
1532
- var ScopeComplianceSealUseExecute = "compliance:seal_use:execute";
1533
- var ScopeComplianceReportsRead = "compliance:reports:read";
1534
- var ScopeComplianceReportsWrite = "compliance:reports:write";
1535
- var ScopeComplianceReportsPublish = "compliance:reports:publish";
1536
- function allScopes() {
1537
- return [ScopeAI, ScopeSkills, ScopeAccount];
1538
- }
1539
- function complianceScopes() {
1540
- return [
1541
- ScopeComplianceEvidenceRead,
1542
- ScopeComplianceEvidenceWrite,
1543
- ScopeComplianceTimestampIssue,
1544
- ScopeComplianceTimestampVerify,
1545
- ScopeComplianceContractSigningRead,
1546
- ScopeComplianceContractSigningWrite,
1547
- ScopeComplianceSealManage,
1548
- ScopeComplianceSealApprovalRequest,
1549
- ScopeComplianceSealApprovalApprove,
1550
- ScopeComplianceSealUseExecute,
1551
- ScopeComplianceReportsRead,
1552
- ScopeComplianceReportsWrite,
1553
- ScopeComplianceReportsPublish
1554
- ];
1555
- }
1556
- function modelScopes() {
1557
- return [ScopeAI];
1558
- }
1559
- function commerceScopes() {
1560
- return [ScopeAI, ScopeAccount];
1561
- }
1562
- function skillScopes() {
1563
- return [ScopeSkills];
1564
- }
1565
-
1566
- // src/compliance-status.ts
1567
- var ErrComplianceStepUpRequired = "COMPLIANCE_STEP_UP_REQUIRED";
1568
- var ErrEnvelopeGateClosed = "ENVELOPE_GATE_CLOSED";
1569
- var ErrProviderNotConfigured = "PROVIDER_NOT_CONFIGURED";
1570
- var ErrProviderUnknownNoRetry = "PROVIDER_REQUEST_UNKNOWN_NO_RETRY";
1571
- var ErrBillingCallbackCannotCommit = "BILLING_CALLBACK_CANNOT_COMMIT";
1572
- var ErrBillingCommitRequiresLocalVerify = "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY";
1573
- var ErrBillingS2sForbidden = "BILLING_S2S_FORBIDDEN";
1574
- var ErrSealApprovalNotApproved = "SEAL_APPROVAL_STATE_NOT_APPROVED";
1575
- var ErrSealApprovalExpired = "SEAL_APPROVAL_EXPIRED";
1576
- var ErrSealApprovalNonceUsed = "SEAL_APPROVAL_NONCE_USED";
1577
- var ErrSealApprovalContractHashMismatch = "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH";
1578
- var ErrSealApprovalSealMismatch = "SEAL_APPROVAL_SEAL_MISMATCH";
1579
- var ErrSealApprovalLocationMismatch = "SEAL_APPROVAL_LOCATION_MISMATCH";
1580
- var ErrSealApprovalTransactorMismatch = "SEAL_APPROVAL_TRANSACTOR_MISMATCH";
1581
- var ErrSealUseAlreadyConsumed = "SEAL_USE_ALREADY_CONSUMED";
1582
- function isComplianceTerminalError(code) {
1583
- switch (code) {
1584
- case ErrEnvelopeGateClosed:
1585
- case ErrProviderNotConfigured:
1586
- case ErrProviderUnknownNoRetry:
1587
- case ErrBillingCallbackCannotCommit:
1588
- case ErrBillingCommitRequiresLocalVerify:
1589
- case ErrBillingS2sForbidden:
1590
- case ErrSealApprovalNonceUsed:
1591
- case ErrSealApprovalExpired:
1592
- case ErrSealApprovalContractHashMismatch:
1593
- case ErrSealApprovalSealMismatch:
1594
- case ErrSealApprovalLocationMismatch:
1595
- case ErrSealApprovalTransactorMismatch:
1596
- case ErrSealUseAlreadyConsumed:
1597
- return true;
1598
- default:
1599
- return false;
1600
- }
1601
- }
1602
- function isBillingConfirmable(providerStatus, billingStatus) {
1603
- return providerStatus === "success" && billingStatus === "committed";
1604
- }
1605
-
1606
- // src/compliance-errors.ts
1607
- var CODE_TO_KEY = {
1608
- // 通用 / token / scope (1-031-000-xxx)
1609
- 1031000001: "COMPLIANCE_UNAUTHORIZED",
1610
- 1031000002: "COMPLIANCE_TOKEN_INVALID",
1611
- 1031000003: "COMPLIANCE_TOKEN_INVALID",
1612
- 1031000004: "COMPLIANCE_TOKEN_INVALID",
1613
- 1031000005: "COMPLIANCE_TOKEN_INVALID",
1614
- 1031000006: "COMPLIANCE_TOKEN_INVALID",
1615
- 1031000007: "COMPLIANCE_TOKEN_INVALID",
1616
- 1031000008: "COMPLIANCE_TOKEN_INVALID",
1617
- 1031000009: "COMPLIANCE_TOKEN_INVALID",
1618
- 1031000010: "COMPLIANCE_TOKEN_INVALID",
1619
- 1031000011: "COMPLIANCE_TOKEN_INVALID",
1620
- 1031000012: "COMPLIANCE_INSUFFICIENT_SCOPE",
1621
- 1031000013: "COMPLIANCE_STEP_UP_REQUIRED",
1622
- // Subject snapshot (1-031-001-xxx)
1623
- 1031001001: "SUBJECT_SNAPSHOT_NOT_FOUND",
1624
- 1031001002: "SUBJECT_SNAPSHOT_TENANT_MISMATCH",
1625
- 1031001003: "SUBJECT_SNAPSHOT_REQUIRED",
1626
- // Evidence / Timestamp / Package / Report (1-031-002-xxx)
1627
- 1031002001: "EVIDENCE_ASSET_NOT_FOUND",
1628
- 1031002002: "SUBJECT_SNAPSHOT_TENANT_MISMATCH",
1629
- 1031002003: "EVIDENCE_ASSET_HASH_MISMATCH",
1630
- 1031002004: "EVIDENCE_ASSET_PAYLOAD_REQUIRED",
1631
- 1031002005: "EVIDENCE_ASSET_PAYLOAD_REQUIRED",
1632
- 1031002006: "TIMESTAMP_TOKEN_NOT_FOUND",
1633
- 1031002007: "TIMESTAMP_PROVIDER_FAILED",
1634
- 1031002008: "TIMESTAMP_PROVIDER_UNKNOWN",
1635
- 1031002009: "TIMESTAMP_LOCAL_VERIFY_FAILED",
1636
- 1031002010: "TIMESTAMP_PROVIDER_NOT_AVAILABLE",
1637
- 1031002011: "EVIDENCE_PACKAGE_NOT_FOUND",
1638
- 1031002012: "EVIDENCE_PACKAGE_TIMESTAMP_REQUIRED",
1639
- 1031002013: "EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH",
1640
- 1031002014: "REPORT_NOT_FOUND",
1641
- 1031002015: "REPORT_ALREADY_PUBLISHED",
1642
- 1031002016: "REPORT_DRAFT_REQUIRED",
1643
- 1031002017: "EVIDENCE_VERIFY_TARGET_REQUIRED",
1644
- 1031002018: "EVIDENCE_VERIFY_TARGET_NOT_FOUND",
1645
- // Provider request (1-031-003-xxx)
1646
- 1031003001: "PROVIDER_REQUEST_UNKNOWN_NO_RETRY",
1647
- 1031003002: "PROVIDER_CALLBACK_SOURCE_INVALID",
1648
- 1031003003: "PROVIDER_NOT_CONFIGURED",
1649
- 1031003010: "PROVIDER_REQUEST_NOT_FOUND",
1650
- 1031003011: "PROVIDER_REQUEST_IDEMPOTENCY_REQUIRED",
1651
- 1031003012: "PROVIDER_REQUEST_STATUS_NOT_TERMINAL",
1652
- // Envelope (1-031-004-xxx)
1653
- 1031004001: "ENVELOPE_NOT_FOUND",
1654
- 1031004002: "ENVELOPE_TENANT_MISMATCH",
1655
- 1031004003: "ENVELOPE_STATE_NOT_ALLOWED",
1656
- 1031004004: "ENVELOPE_GATE_CLOSED",
1657
- 1031004005: "CONTRACT_NOT_FOUND",
1658
- 1031004006: "CONTRACT_HASH_MISMATCH",
1659
- 1031004007: "CONTRACT_NOT_FOUND",
1660
- 1031004008: "PROVIDER_AUTHORIZATION_NOT_CONFIRMED",
1661
- 1031004009: "PROVIDER_AUTHORIZATION_NOT_CONFIRMED",
1662
- 1031004010: "ENVELOPE_EVIDENCE_NOT_READY",
1663
- // Seal approval / use (1-031-005-xxx)
1664
- 1031005001: "SEAL_ASSET_NOT_FOUND",
1665
- 1031005010: "SEAL_APPROVAL_NOT_FOUND",
1666
- 1031005011: "SEAL_APPROVAL_NOT_FOUND",
1667
- 1031005012: "SEAL_APPROVAL_STATE_NOT_APPROVED",
1668
- 1031005013: "SEAL_APPROVAL_EXPIRED",
1669
- 1031005014: "SEAL_APPROVAL_ALREADY_USED",
1670
- 1031005015: "SEAL_APPROVAL_NONCE_USED",
1671
- 1031005016: "SEAL_APPROVAL_SEAL_MISMATCH",
1672
- 1031005017: "SEAL_APPROVAL_LOCATION_MISMATCH",
1673
- 1031005018: "SEAL_APPROVAL_TRANSACTOR_MISMATCH",
1674
- 1031005019: "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH",
1675
- 1031005020: "SEAL_APPROVAL_INVALID_TRANSITION",
1676
- 1031005030: "SEAL_USE_ALREADY_CONSUMED",
1677
- // Billing (1-031-006-xxx)
1678
- 1031006004: "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY",
1679
- 1031006005: "BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS",
1680
- 1031006007: "BILLING_CALLBACK_CANNOT_COMMIT",
1681
- 1031006008: "BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE",
1682
- 1031006009: "BILLING_S2S_FORBIDDEN",
1683
- // Audit (1-031-007-xxx)
1684
- 1031007011: "AUDIT_CHAIN_TAMPER_DETECTED"
1685
- };
1686
- var STEP_UP_KEYS = /* @__PURE__ */ new Set(["COMPLIANCE_STEP_UP_REQUIRED"]);
1687
- var TERMINAL_KEYS = /* @__PURE__ */ new Set([
1688
- "ENVELOPE_GATE_CLOSED",
1689
- "PROVIDER_NOT_CONFIGURED",
1690
- "PROVIDER_REQUEST_UNKNOWN_NO_RETRY",
1691
- "BILLING_CALLBACK_CANNOT_COMMIT",
1692
- "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY",
1693
- "BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS",
1694
- "BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE",
1695
- "BILLING_S2S_FORBIDDEN",
1696
- "SEAL_APPROVAL_NONCE_USED",
1697
- "SEAL_APPROVAL_EXPIRED",
1698
- "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH",
1699
- "SEAL_APPROVAL_SEAL_MISMATCH",
1700
- "SEAL_APPROVAL_LOCATION_MISMATCH",
1701
- "SEAL_APPROVAL_TRANSACTOR_MISMATCH",
1702
- "SEAL_USE_ALREADY_CONSUMED",
1703
- "CONTRACT_HASH_MISMATCH",
1704
- "TIMESTAMP_LOCAL_VERIFY_FAILED",
1705
- "EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH",
1706
- "AUDIT_CHAIN_TAMPER_DETECTED",
1707
- "PROVIDER_REQUEST_NOT_FOUND",
1708
- "EVIDENCE_ASSET_HASH_MISMATCH",
1709
- "EVIDENCE_VERIFY_TARGET_NOT_FOUND",
1710
- "REPORT_ALREADY_PUBLISHED"
1711
- ]);
1712
- var RETRYABLE_KEYS = /* @__PURE__ */ new Set([]);
1713
- function classifyComplianceError(err) {
1714
- const key = CODE_TO_KEY[err.code] ?? "UNKNOWN_COMPLIANCE_ERROR";
1715
- return {
1716
- code: err.code,
1717
- message: err.message,
1718
- key,
1719
- retryable: RETRYABLE_KEYS.has(key),
1720
- terminal: TERMINAL_KEYS.has(key),
1721
- stepUpRequired: STEP_UP_KEYS.has(key)
1722
- };
1723
- }
1724
- function isComplianceBusinessError(err) {
1725
- return err.code >= 1031e6 && err.code <= 1031999999;
1726
- }
1727
-
1728
- // src/client.ts
1729
- init_types();
1730
-
1731
- // src/store.ts
1732
- var fileLockDefaults = {
1733
- /** 获取锁的超时上限 (毫秒). refresh 流程含网络 < 30s, 30s 已远超正常完成时间. */
1734
- acquireTimeoutMs: 3e4,
1735
- /** 旧锁判定阈值 (毫秒). 锁文件 mtime 早于此值视为 stale 进程崩溃残留, 自动 break. */
1736
- staleMs: 6e4,
1737
- /** 重试间隔基数 (毫秒). 真实间隔 = base + random(0, jitter). */
1738
- retryBaseMs: 30,
1739
- retryJitterMs: 70
1740
- };
1741
- var FileTokenStore = class {
1742
- path;
1743
- /** 进程内串行化 (Promise chain) — 与跨进程 flock 配合, 避免单进程内并发持锁产生死锁式互等. */
1744
- chain = Promise.resolve();
1745
- constructor(path) {
1746
- if (typeof process === "undefined" || !process.versions || !process.versions.node) {
1747
- throw new Error("FileTokenStore requires Node.js environment; use LocalStorageTokenStore or InMemoryTokenStore in browser");
1748
- }
1749
- if (path && path !== "") {
1750
- this.path = path;
1751
- } else {
1752
- this.path = "";
1753
- }
1451
+ // src/core/store.ts
1452
+ var fileLockDefaults = {
1453
+ /** 获取锁的超时上限 (毫秒). refresh 流程含网络 < 30s, 30s 已远超正常完成时间. */
1454
+ acquireTimeoutMs: 3e4,
1455
+ /** 旧锁判定阈值 (毫秒). 锁文件 mtime 早于此值视为 stale 进程崩溃残留, 自动 break. */
1456
+ staleMs: 6e4,
1457
+ /** 重试间隔基数 (毫秒). 真实间隔 = base + random(0, jitter). */
1458
+ retryBaseMs: 30,
1459
+ retryJitterMs: 70
1460
+ };
1461
+ var FileTokenStore = class {
1462
+ path;
1463
+ /** 进程内串行化 (Promise chain) — 与跨进程 flock 配合, 避免单进程内并发持锁产生死锁式互等. */
1464
+ chain = Promise.resolve();
1465
+ constructor(path) {
1466
+ if (typeof process === "undefined" || !process.versions || !process.versions.node) {
1467
+ throw new Error("FileTokenStore requires Node.js environment; use LocalStorageTokenStore or InMemoryTokenStore in browser");
1468
+ }
1469
+ if (path && path !== "") {
1470
+ this.path = path;
1471
+ } else {
1472
+ this.path = "";
1473
+ }
1754
1474
  }
1755
1475
  async resolvePath() {
1756
1476
  if (this.path && this.path !== "") return this.path;
@@ -1947,8 +1667,8 @@ var InMemoryTokenStore = class {
1947
1667
  }
1948
1668
  };
1949
1669
 
1950
- // src/retry.ts
1951
- init_types();
1670
+ // src/core/retry.ts
1671
+ init_errors();
1952
1672
  var DefaultRetryPolicy = {
1953
1673
  maxAttempts: 2,
1954
1674
  backoffMs: 200,
@@ -2003,10 +1723,10 @@ function computeBackoff(p, attempt, err) {
2003
1723
  return d;
2004
1724
  }
2005
1725
 
2006
- // src/client.ts
1726
+ // src/core/client.ts
2007
1727
  init_adapters();
2008
1728
 
2009
- // src/stream-meta.ts
1729
+ // src/models/stream-meta.ts
2010
1730
  function extractAnthropicBlockMeta(eventType, data, blockTypeMap) {
2011
1731
  switch (eventType) {
2012
1732
  case "content_block_start": {
@@ -2052,11 +1772,11 @@ function extractAnthropicBlockMeta(eventType, data, blockTypeMap) {
2052
1772
  }
2053
1773
  }
2054
1774
 
2055
- // src/client.ts
1775
+ // src/core/client.ts
2056
1776
  init_openai();
2057
1777
 
2058
- // src/client-helpers.ts
2059
- init_types();
1778
+ // src/core/http.ts
1779
+ init_errors();
2060
1780
  var maxDownloadSize = 50 * 1024 * 1024;
2061
1781
  var maxErrorBodySize = 1 * 1024 * 1024;
2062
1782
  var maxSSELineSize = 1 * 1024 * 1024;
@@ -2232,7 +1952,7 @@ async function readLimitedText(body, maxBytes) {
2232
1952
  return new TextDecoder("utf-8").decode(buf);
2233
1953
  }
2234
1954
 
2235
- // src/client.ts
1955
+ // src/core/client.ts
2236
1956
  var FilterStatusOK = "ok";
2237
1957
  var FilterStatusAdminBypass = "admin-bypass";
2238
1958
  var FilterStatusInternalBypass = "internal-bypass";
@@ -3447,850 +3167,1334 @@ async function sleep(ms, signal) {
3447
3167
  });
3448
3168
  }
3449
3169
 
3450
- // src/client/compliance.ts
3451
- init_types();
3452
- var cache = /* @__PURE__ */ new WeakMap();
3453
- Object.defineProperty(Client.prototype, "compliance", {
3454
- configurable: true,
3455
- enumerable: false,
3456
- get() {
3457
- let existing = cache.get(this);
3458
- if (!existing) {
3459
- existing = new ComplianceClient(this);
3460
- cache.set(this, existing);
3461
- }
3462
- return existing;
3463
- }
3170
+ // src/sanitize/index.ts
3171
+ var sanitize_exports = {};
3172
+ __export(sanitize_exports, {
3173
+ BlockCodeExecutionToolResult: () => BlockCodeExecutionToolResult,
3174
+ BlockContainerUpload: () => BlockContainerUpload,
3175
+ BlockDeniedError: () => BlockDeniedError,
3176
+ BlockDocument: () => BlockDocument,
3177
+ BlockImage: () => BlockImage,
3178
+ BlockMCPToolResult: () => BlockMCPToolResult,
3179
+ BlockMCPToolUse: () => BlockMCPToolUse,
3180
+ BlockRedactedThinking: () => BlockRedactedThinking,
3181
+ BlockSearchResult: () => BlockSearchResult,
3182
+ BlockServerToolUse: () => BlockServerToolUse,
3183
+ BlockText: () => BlockText,
3184
+ BlockThinking: () => BlockThinking,
3185
+ BlockToolReference: () => BlockToolReference,
3186
+ BlockToolResult: () => BlockToolResult,
3187
+ BlockToolUse: () => BlockToolUse,
3188
+ BlockVideo: () => BlockVideo,
3189
+ BlockWebSearchToolResult: () => BlockWebSearchToolResult,
3190
+ DeltaCitations: () => DeltaCitations,
3191
+ DeltaInputJSON: () => DeltaInputJSON,
3192
+ DeltaSignature: () => DeltaSignature,
3193
+ DeltaText: () => DeltaText,
3194
+ DeltaThinking: () => DeltaThinking,
3195
+ EphemeralMarkerField: () => EphemeralMarkerField,
3196
+ ErrBlockDenied: () => ErrBlockDenied,
3197
+ ErrHistoryTooDeep: () => ErrHistoryTooDeep,
3198
+ HistoryTooDeepError: () => HistoryTooDeepError,
3199
+ SizeError: () => SizeError,
3200
+ dropBlocks: () => dropBlocks,
3201
+ sanitize: () => sanitize,
3202
+ stripEphemeral: () => stripEphemeral
3464
3203
  });
3465
- var DEFAULT_POLL = {
3466
- timeoutMs: 6e4,
3467
- initialIntervalMs: 1e3,
3468
- maxIntervalMs: 5e3,
3469
- multiplier: 1.5
3204
+
3205
+ // src/sanitize/types.ts
3206
+ var BlockText = "text";
3207
+ var BlockImage = "image";
3208
+ var BlockVideo = "video";
3209
+ var BlockDocument = "document";
3210
+ var BlockSearchResult = "search_result";
3211
+ var BlockThinking = "thinking";
3212
+ var BlockRedactedThinking = "redacted_thinking";
3213
+ var BlockToolUse = "tool_use";
3214
+ var BlockToolResult = "tool_result";
3215
+ var BlockToolReference = "tool_reference";
3216
+ var BlockServerToolUse = "server_tool_use";
3217
+ var BlockWebSearchToolResult = "web_search_tool_result";
3218
+ var BlockCodeExecutionToolResult = "code_execution_tool_result";
3219
+ var BlockMCPToolUse = "mcp_tool_use";
3220
+ var BlockMCPToolResult = "mcp_tool_result";
3221
+ var BlockContainerUpload = "container_upload";
3222
+ var DeltaText = "text_delta";
3223
+ var DeltaInputJSON = "input_json_delta";
3224
+ var DeltaThinking = "thinking_delta";
3225
+ var DeltaSignature = "signature_delta";
3226
+ var DeltaCitations = "citations_delta";
3227
+ var EphemeralMarkerField = "acosmi_ephemeral";
3228
+
3229
+ // src/sanitize/config.ts
3230
+ var HistoryTooDeepError = class extends Error {
3231
+ constructor() {
3232
+ super("sanitize: messages history exceeds configured depth");
3233
+ this.name = "HistoryTooDeepError";
3234
+ }
3470
3235
  };
3471
- var CompliancePollError = class extends Error {
3472
- kind;
3473
- lastInfo;
3474
- constructor(message, kind, lastInfo) {
3475
- super(message);
3476
- this.name = "CompliancePollError";
3477
- this.kind = kind;
3478
- this.lastInfo = lastInfo;
3236
+ var BlockDeniedError = class extends Error {
3237
+ constructor() {
3238
+ super("sanitize: block type permanently denied");
3239
+ this.name = "BlockDeniedError";
3479
3240
  }
3480
3241
  };
3481
- var ComplianceClient = class {
3482
- constructor(client) {
3483
- this.client = client;
3242
+ var SizeError = class extends Error {
3243
+ blockType;
3244
+ actual;
3245
+ limit;
3246
+ constructor(blockType, actual, limit) {
3247
+ super(`sanitize: ${blockType} base64 size ${actual} exceeds limit ${limit}`);
3248
+ this.name = "SizeError";
3249
+ this.blockType = blockType;
3250
+ this.actual = actual;
3251
+ this.limit = limit;
3484
3252
  }
3485
- client;
3486
- // =========================================================================
3487
- // Evidence Asset
3488
- // =========================================================================
3489
- /** 创建证据资产(写)。 */
3490
- createEvidenceAsset(req, opts = {}) {
3491
- return this.write(
3492
- "POST",
3493
- "/compliance/evidence/assets",
3494
- req,
3495
- writeCtx(opts)
3496
- );
3253
+ };
3254
+ var ErrHistoryTooDeep = new HistoryTooDeepError();
3255
+ var ErrBlockDenied = new BlockDeniedError();
3256
+
3257
+ // src/sanitize/history.ts
3258
+ function dropBlocks(messages, pred) {
3259
+ const droppedToolUseIDs = collectDroppedToolUseIDs(messages, pred);
3260
+ const out = [];
3261
+ for (const msg of messages) {
3262
+ if (!isPlainObject(msg)) {
3263
+ out.push(msg);
3264
+ continue;
3265
+ }
3266
+ const content = msg["content"];
3267
+ if (!Array.isArray(content)) {
3268
+ out.push(msg);
3269
+ continue;
3270
+ }
3271
+ const { kept, changed } = filterBlocks(content, pred, droppedToolUseIDs);
3272
+ if (!changed) {
3273
+ out.push(msg);
3274
+ continue;
3275
+ }
3276
+ if (kept.length === 0) {
3277
+ continue;
3278
+ }
3279
+ const newMsg = { ...msg };
3280
+ newMsg["content"] = kept;
3281
+ out.push(newMsg);
3497
3282
  }
3498
- /** 读 — 证据资产详情。 */
3499
- getEvidenceAsset(id, signal) {
3500
- return this.read(
3501
- "GET",
3502
- `/compliance/evidence/assets/${encodeURIComponent(id)}`,
3503
- null,
3504
- signal
3505
- );
3283
+ return out;
3284
+ }
3285
+ function collectDroppedToolUseIDs(messages, pred) {
3286
+ const ids = /* @__PURE__ */ new Set();
3287
+ for (const msg of messages) {
3288
+ if (!isPlainObject(msg)) continue;
3289
+ const content = msg["content"];
3290
+ if (!Array.isArray(content)) continue;
3291
+ for (const raw of content) {
3292
+ if (!isPlainObject(raw)) continue;
3293
+ if (!pred(raw)) continue;
3294
+ const t = raw["type"];
3295
+ if (typeof t !== "string") continue;
3296
+ if (t === "tool_use" || t === "server_tool_use" || t === "mcp_tool_use") {
3297
+ const id = raw["id"];
3298
+ if (typeof id === "string" && id !== "") ids.add(id);
3299
+ }
3300
+ }
3506
3301
  }
3507
- /**
3508
- * 公开 verify。隐私边界:返回字段不含 PII / 合同原文 / storage / provider raw。
3509
- *
3510
- * 匿名可调用:未 login 时走匿名请求,不会抛 `not authorized, call login() first`。
3511
- * login / 已持有 token 时附带 `Authorization` 以保留审计上下文。public 端点不
3512
- * 应要求认证 收到 401 直接抛 HTTPError,不触发 `forceRefresh`,也不做 refresh
3513
- * replay。
3514
- */
3515
- verifyEvidencePublic(params, signal) {
3516
- const q = new URLSearchParams();
3517
- if (params.evidenceNo) q.set("evidenceNo", params.evidenceNo);
3518
- if (params.publicVerifyCode) q.set("publicVerifyCode", params.publicVerifyCode);
3519
- const qs = q.toString();
3520
- return this.publicRead(
3521
- "GET",
3522
- `/compliance/evidence/verify${qs ? "?" + qs : ""}`,
3523
- signal
3524
- );
3302
+ return ids;
3303
+ }
3304
+ function filterBlocks(content, pred, droppedToolUseIDs) {
3305
+ const kept = [];
3306
+ let changed = false;
3307
+ for (const raw of content) {
3308
+ if (!isPlainObject(raw)) {
3309
+ kept.push(raw);
3310
+ continue;
3311
+ }
3312
+ if (pred(raw)) {
3313
+ changed = true;
3314
+ continue;
3315
+ }
3316
+ if (droppedToolUseIDs.size > 0) {
3317
+ const t = raw["type"];
3318
+ if (t === "tool_result" || t === "mcp_tool_result") {
3319
+ const id = raw["tool_use_id"];
3320
+ if (typeof id === "string" && id !== "" && droppedToolUseIDs.has(id)) {
3321
+ changed = true;
3322
+ continue;
3323
+ }
3324
+ }
3325
+ }
3326
+ kept.push(raw);
3525
3327
  }
3526
- // =========================================================================
3527
- // Timestamp
3528
- // =========================================================================
3529
- /** 申请时间章(写)。SDK 永远不传 provider 字段。 */
3530
- issueTimestamp(req, opts = {}) {
3531
- return this.write("POST", "/compliance/timestamps", req, writeCtx(opts));
3328
+ return { kept, changed };
3329
+ }
3330
+ function stripEphemeral(messages) {
3331
+ return dropBlocks(messages, (b) => {
3332
+ const t = b["type"];
3333
+ if (t === "thinking" || t === "redacted_thinking") {
3334
+ return false;
3335
+ }
3336
+ const v = b[EphemeralMarkerField];
3337
+ return v === true;
3338
+ });
3339
+ }
3340
+ function isPlainObject(v) {
3341
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3342
+ }
3343
+
3344
+ // src/sanitize/defensive.ts
3345
+ function sanitize(messages, cfg) {
3346
+ if ((cfg.maxMessagesTurns ?? 0) > 0 && messages.length > cfg.maxMessagesTurns) {
3347
+ throw ErrHistoryTooDeep;
3532
3348
  }
3533
- /** 给已有资产申请时间章。SDK 永远不传 provider 字段。 */
3534
- issueTimestampForAsset(assetId, opts = {}) {
3535
- return this.write(
3536
- "POST",
3537
- `/compliance/evidence/assets/${encodeURIComponent(assetId)}/timestamp`,
3538
- null,
3539
- writeCtx(opts)
3540
- );
3349
+ if ((cfg.maxImageBytes ?? 0) > 0 || (cfg.maxVideoBytes ?? 0) > 0 || (cfg.maxPDFBytes ?? 0) > 0) {
3350
+ checkMediaSizes(messages, cfg);
3541
3351
  }
3542
- /** 时间章 token 详情。 */
3543
- getTimestamp(id, signal) {
3544
- return this.read(
3545
- "GET",
3546
- `/compliance/timestamps/${encodeURIComponent(id)}`,
3547
- null,
3548
- signal
3549
- );
3352
+ if (cfg.permanentDenyBlocks && cfg.permanentDenyBlocks.length > 0) {
3353
+ const denySet = /* @__PURE__ */ new Set();
3354
+ for (const bt of cfg.permanentDenyBlocks) denySet.add(bt);
3355
+ messages = dropBlocks(messages, (b) => {
3356
+ const t = b["type"];
3357
+ return typeof t === "string" && denySet.has(t);
3358
+ });
3550
3359
  }
3551
- /** verify — 本地离线校验已申请的时间章。 */
3552
- verifyTimestamp(req, opts = {}) {
3553
- return this.write(
3554
- "POST",
3555
- "/compliance/timestamps/verify",
3556
- req,
3557
- writeCtx(opts)
3558
- );
3360
+ return messages;
3361
+ }
3362
+ function checkMediaSizes(messages, cfg) {
3363
+ for (const msg of messages) {
3364
+ if (!isPlainObject2(msg)) continue;
3365
+ const content = msg["content"];
3366
+ if (!Array.isArray(content)) continue;
3367
+ for (const raw of content) {
3368
+ if (!isPlainObject2(raw)) continue;
3369
+ const bt = raw["type"];
3370
+ if (typeof bt !== "string") continue;
3371
+ let limit = 0;
3372
+ switch (bt) {
3373
+ case "image":
3374
+ limit = cfg.maxImageBytes ?? 0;
3375
+ break;
3376
+ case "video":
3377
+ limit = cfg.maxVideoBytes ?? 0;
3378
+ break;
3379
+ case "document":
3380
+ limit = cfg.maxPDFBytes ?? 0;
3381
+ break;
3382
+ default:
3383
+ continue;
3384
+ }
3385
+ if (limit <= 0) continue;
3386
+ const data = extractBase64Data(raw);
3387
+ if (data === "") continue;
3388
+ const actual = base64DecodedLen(data);
3389
+ if (actual > limit) {
3390
+ throw new SizeError(bt, actual, limit);
3391
+ }
3392
+ }
3559
3393
  }
3560
- /**
3561
- * 轮询到 VERIFIED 终态。
3562
- * - VERIFIED → 返回 token;
3563
- * - FAILED / LOCAL_VERIFY_FAILED → 抛 {@link CompliancePollError} kind='terminal_failure';
3564
- * - UNKNOWN / RETRYING / PENDING → 继续轮询直到 timeout;
3565
- * - timeout → 抛 {@link CompliancePollError} kind='timeout'。
3566
- */
3567
- async waitForTimestampVerified(id, opts = {}) {
3568
- return this.poll(
3569
- () => this.getTimestamp(id, opts.signal),
3570
- (t) => classifyTimestamp(t.verificationStatus),
3571
- opts
3572
- );
3394
+ }
3395
+ function extractBase64Data(block) {
3396
+ const src = block["source"];
3397
+ if (!isPlainObject2(src)) return "";
3398
+ if (src["type"] !== "base64") return "";
3399
+ const dataRaw = src["data"];
3400
+ if (typeof dataRaw !== "string") return "";
3401
+ let data = dataRaw;
3402
+ const i = data.indexOf("base64,");
3403
+ if (i >= 0) {
3404
+ data = data.slice(i + "base64,".length);
3573
3405
  }
3574
- // =========================================================================
3575
- // Evidence Package
3576
- // =========================================================================
3577
- /** 构建证据包(写)。 */
3578
- buildEvidencePackage(assetId, timestampTokenId, opts = {}) {
3579
- const tsParam = timestampTokenId == null ? "" : "?timestampTokenId=" + encodeURIComponent(timestampTokenId);
3580
- return this.write(
3581
- "POST",
3582
- `/compliance/evidence/assets/${encodeURIComponent(assetId)}/packages${tsParam}`,
3583
- null,
3584
- writeCtx(opts)
3585
- );
3406
+ return data;
3407
+ }
3408
+ function base64DecodedLen(b64) {
3409
+ const n = b64.length;
3410
+ let pad = 0;
3411
+ if (n >= 1 && b64[n - 1] === "=") pad++;
3412
+ if (n >= 2 && b64[n - 2] === "=") pad++;
3413
+ return Math.floor(n * 3 / 4) - pad;
3414
+ }
3415
+ function isPlainObject2(v) {
3416
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3417
+ }
3418
+
3419
+ // src/core/sanitize-bridge.ts
3420
+ Client.prototype.setDefensiveSanitize = function(cfg) {
3421
+ this.defensiveCfg = cfg;
3422
+ };
3423
+ Client.prototype.setAutoStripEphemeralHistory = function(on) {
3424
+ this.autoStripEphemeral = on;
3425
+ };
3426
+ Client.prototype.applyRequestSanitizers = function(req) {
3427
+ const cfg = this.defensiveCfg;
3428
+ const strip = this.autoStripEphemeral;
3429
+ if (cfg == null && !strip) return;
3430
+ if (req.rawMessages != null) {
3431
+ let msgs;
3432
+ try {
3433
+ msgs = normalizeRawMessages(req.rawMessages);
3434
+ } catch (e) {
3435
+ throw new Error(
3436
+ `sanitize: normalize raw messages: ${e instanceof Error ? e.message : String(e)}`
3437
+ );
3438
+ }
3439
+ if (cfg) {
3440
+ msgs = sanitize(msgs, cfg);
3441
+ }
3442
+ if (strip) {
3443
+ msgs = stripEphemeral(msgs);
3444
+ }
3445
+ req.rawMessages = msgs;
3446
+ return;
3586
3447
  }
3587
- // =========================================================================
3588
- // Report
3589
- // =========================================================================
3590
- /** 创建证据报告(写)。 */
3591
- createReport(req, opts = {}) {
3592
- return this.write("POST", "/compliance/reports", req, writeCtx(opts));
3448
+ if (cfg && (cfg.maxMessagesTurns ?? 0) > 0 && (req.messages?.length ?? 0) > cfg.maxMessagesTurns) {
3449
+ throw ErrHistoryTooDeep;
3593
3450
  }
3594
- /** 读 — 报告详情。 */
3595
- getReport(id, signal) {
3596
- return this.read(
3597
- "GET",
3598
- `/compliance/reports/${encodeURIComponent(id)}`,
3599
- null,
3600
- signal
3601
- );
3451
+ };
3452
+ function normalizeRawMessages(rm) {
3453
+ if (Array.isArray(rm)) return rm;
3454
+ let s;
3455
+ try {
3456
+ s = JSON.parse(JSON.stringify(rm));
3457
+ } catch (e) {
3458
+ throw new Error(`raw messages: ${e instanceof Error ? e.message : String(e)}`);
3602
3459
  }
3603
- /**
3604
- * 发布报告(写,step-up 必须)。
3605
- *
3606
- * `@status gated` — step-up 闸门未闭合前服务端会一致返回
3607
- * `COMPLIANCE_STEP_UP_REQUIRED`(数值码 1031000013)。SDK 不会自动重试、不伪成功;
3608
- * 调用方需要引导用户重新做 OAuth introspection 或重新登录后再次调用本方法
3609
- *(使用同一 idempotency-key)。方法状态分级见 `docs/compliance.md` Method Status。
3610
- */
3611
- publishReport(id, opts = {}) {
3612
- return this.write(
3613
- "POST",
3614
- `/compliance/reports/${encodeURIComponent(id)}/publish`,
3615
- null,
3616
- writeCtx(opts)
3617
- );
3460
+ if (!Array.isArray(s)) {
3461
+ throw new Error("raw messages must be a JSON array");
3618
3462
  }
3619
- /**
3620
- * 下载报告(读)。返回 {@link ReportDownload}:报告 hash + 资产 hash + 证据包 hash +
3621
- * 时间章 serial/genTime,足以离线复核。
3622
- * 不返回 bodyCanonicalJson / storage key / subject snapshot id。
3623
- */
3624
- downloadReport(id, signal) {
3625
- return this.read(
3626
- "GET",
3627
- `/compliance/reports/${encodeURIComponent(id)}/download`,
3628
- null,
3629
- signal
3630
- );
3463
+ return s;
3464
+ }
3465
+
3466
+ // src/shared/index.ts
3467
+ init_errors();
3468
+
3469
+ // src/shared/operation.ts
3470
+ var IdempotencyKeyHeader = "Idempotency-Key";
3471
+
3472
+ // src/shared/retry-advice.ts
3473
+ var RETRY_ADVICE_REASONS = [
3474
+ "unknown",
3475
+ "retrying",
3476
+ "failed",
3477
+ "gate_closed",
3478
+ "step_up_required",
3479
+ "tenant_mismatch",
3480
+ "insufficient_scope",
3481
+ "quota_exceeded",
3482
+ "provider_timeout",
3483
+ "local_verify_failed",
3484
+ "billing_preflight_failed"
3485
+ ];
3486
+ var COMPLIANCE_KEY_TO_RETRY_REASON = {
3487
+ // 通用 / token / scope
3488
+ COMPLIANCE_UNAUTHORIZED: "failed",
3489
+ COMPLIANCE_INSUFFICIENT_SCOPE: "insufficient_scope",
3490
+ COMPLIANCE_STEP_UP_REQUIRED: "step_up_required",
3491
+ COMPLIANCE_TOKEN_INVALID: "failed",
3492
+ // 主体快照
3493
+ SUBJECT_SNAPSHOT_REQUIRED: "failed",
3494
+ SUBJECT_SNAPSHOT_NOT_FOUND: "failed",
3495
+ SUBJECT_SNAPSHOT_TENANT_MISMATCH: "tenant_mismatch",
3496
+ // Evidence / Timestamp / Package / Report
3497
+ EVIDENCE_ASSET_NOT_FOUND: "failed",
3498
+ EVIDENCE_ASSET_HASH_MISMATCH: "local_verify_failed",
3499
+ EVIDENCE_ASSET_PAYLOAD_REQUIRED: "failed",
3500
+ TIMESTAMP_TOKEN_NOT_FOUND: "failed",
3501
+ TIMESTAMP_PROVIDER_FAILED: "failed",
3502
+ TIMESTAMP_PROVIDER_UNKNOWN: "unknown",
3503
+ TIMESTAMP_LOCAL_VERIFY_FAILED: "local_verify_failed",
3504
+ TIMESTAMP_PROVIDER_NOT_AVAILABLE: "provider_timeout",
3505
+ EVIDENCE_PACKAGE_NOT_FOUND: "failed",
3506
+ EVIDENCE_PACKAGE_TIMESTAMP_REQUIRED: "failed",
3507
+ EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH: "local_verify_failed",
3508
+ REPORT_NOT_FOUND: "failed",
3509
+ REPORT_ALREADY_PUBLISHED: "failed",
3510
+ REPORT_DRAFT_REQUIRED: "failed",
3511
+ EVIDENCE_VERIFY_TARGET_REQUIRED: "failed",
3512
+ EVIDENCE_VERIFY_TARGET_NOT_FOUND: "failed",
3513
+ // Provider request
3514
+ PROVIDER_REQUEST_UNKNOWN_NO_RETRY: "unknown",
3515
+ PROVIDER_CALLBACK_SOURCE_INVALID: "failed",
3516
+ PROVIDER_NOT_CONFIGURED: "gate_closed",
3517
+ PROVIDER_REQUEST_NOT_FOUND: "failed",
3518
+ PROVIDER_REQUEST_IDEMPOTENCY_REQUIRED: "failed",
3519
+ PROVIDER_REQUEST_STATUS_NOT_TERMINAL: "retrying",
3520
+ // Envelope
3521
+ ENVELOPE_NOT_FOUND: "failed",
3522
+ ENVELOPE_TENANT_MISMATCH: "tenant_mismatch",
3523
+ ENVELOPE_STATE_NOT_ALLOWED: "failed",
3524
+ ENVELOPE_GATE_CLOSED: "gate_closed",
3525
+ CONTRACT_NOT_FOUND: "failed",
3526
+ CONTRACT_HASH_MISMATCH: "local_verify_failed",
3527
+ PROVIDER_AUTHORIZATION_NOT_CONFIRMED: "failed",
3528
+ ENVELOPE_EVIDENCE_NOT_READY: "retrying",
3529
+ // Seal approval / use
3530
+ SEAL_ASSET_NOT_FOUND: "failed",
3531
+ SEAL_APPROVAL_NOT_FOUND: "failed",
3532
+ SEAL_APPROVAL_STATE_NOT_APPROVED: "failed",
3533
+ SEAL_APPROVAL_EXPIRED: "failed",
3534
+ SEAL_APPROVAL_ALREADY_USED: "failed",
3535
+ SEAL_APPROVAL_NONCE_USED: "failed",
3536
+ SEAL_APPROVAL_SEAL_MISMATCH: "failed",
3537
+ SEAL_APPROVAL_LOCATION_MISMATCH: "failed",
3538
+ SEAL_APPROVAL_TRANSACTOR_MISMATCH: "failed",
3539
+ SEAL_APPROVAL_CONTRACT_HASH_MISMATCH: "local_verify_failed",
3540
+ SEAL_APPROVAL_INVALID_TRANSITION: "failed",
3541
+ SEAL_USE_ALREADY_CONSUMED: "failed",
3542
+ // Audit chain
3543
+ AUDIT_CHAIN_TAMPER_DETECTED: "local_verify_failed",
3544
+ // Billing
3545
+ BILLING_COMMIT_REQUIRES_LOCAL_VERIFY: "local_verify_failed",
3546
+ BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS: "billing_preflight_failed",
3547
+ BILLING_CALLBACK_CANNOT_COMMIT: "billing_preflight_failed",
3548
+ BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE: "billing_preflight_failed",
3549
+ BILLING_S2S_FORBIDDEN: "failed",
3550
+ // SDK fallback
3551
+ UNKNOWN_COMPLIANCE_ERROR: "unknown"
3552
+ };
3553
+ function retryReasonForComplianceKey(key) {
3554
+ return COMPLIANCE_KEY_TO_RETRY_REASON[key] ?? "unknown";
3555
+ }
3556
+ var OAUTH_ERROR_TO_RETRY_REASON = {
3557
+ insufficient_scope: "insufficient_scope",
3558
+ invalid_token: "failed",
3559
+ invalid_grant: "failed",
3560
+ invalid_request: "failed",
3561
+ access_denied: "failed",
3562
+ unsupported_grant_type: "failed"
3563
+ };
3564
+ function retryReasonForOAuthError(oauthError) {
3565
+ return OAUTH_ERROR_TO_RETRY_REASON[oauthError] ?? "unknown";
3566
+ }
3567
+ function complianceErrorToRetryAdvice(info) {
3568
+ return {
3569
+ retryable: info.retryable,
3570
+ sameIdempotencyKeyRequired: !info.terminal,
3571
+ manualActionRequired: info.terminal || info.stepUpRequired,
3572
+ reason: retryReasonForComplianceKey(info.key),
3573
+ developerMessage: info.message,
3574
+ supportCode: `compliance:${info.code}`
3575
+ };
3576
+ }
3577
+
3578
+ // src/auth/scopes.ts
3579
+ var ScopeAI = "ai";
3580
+ var ScopeSkills = "skills";
3581
+ var ScopeAccount = "account";
3582
+ var ScopeModels = "models";
3583
+ var ScopeModelsChat = "models:chat";
3584
+ var ScopeEntitlements = "entitlements";
3585
+ var ScopeTokenPackages = "token-packages";
3586
+ var ScopeSkillStore = "skill_store";
3587
+ var ScopeTools = "tools";
3588
+ var ScopeToolsExecute = "tools:execute";
3589
+ var ScopeWallet = "wallet";
3590
+ var ScopeWalletReadonly = "wallet:readonly";
3591
+ var ScopeProfile = "profile";
3592
+ function allScopes() {
3593
+ return [ScopeAI, ScopeSkills, ScopeAccount];
3594
+ }
3595
+ function modelScopes() {
3596
+ return [ScopeAI];
3597
+ }
3598
+ function commerceScopes() {
3599
+ return [ScopeAI, ScopeAccount];
3600
+ }
3601
+ function skillScopes() {
3602
+ return [ScopeSkills];
3603
+ }
3604
+
3605
+ // src/models/index.ts
3606
+ init_types();
3607
+
3608
+ // src/models/wire-anthropic.ts
3609
+ function anthropicResponseTextContent(r) {
3610
+ const parts = [];
3611
+ for (const b of r.content) {
3612
+ if (b.type === "text" && b.text) parts.push(b.text);
3631
3613
  }
3632
- // =========================================================================
3633
- // Signing Envelope
3634
- // =========================================================================
3635
- /** 创建 envelope(写)。返回 envelope id。 */
3636
- createSigningEnvelope(req, opts = {}) {
3637
- return this.write(
3638
- "POST",
3639
- "/compliance/signing-envelopes",
3640
- req,
3641
- writeCtx(opts)
3642
- );
3614
+ return parts.join("");
3615
+ }
3616
+ function anthropicResponseThinkingContent(r) {
3617
+ const parts = [];
3618
+ for (const b of r.content) {
3619
+ if (b.type === "thinking" && b.thinking) parts.push(b.thinking);
3643
3620
  }
3644
- /** 读 — envelope 详情。租户由服务端从 compliance token principal 推导。 */
3645
- getSigningEnvelope(envelopeId, signal) {
3646
- return this.read(
3647
- "GET",
3648
- `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}`,
3649
- null,
3650
- signal
3651
- );
3621
+ return parts.join("");
3622
+ }
3623
+ function anthropicResponseToolUseBlocks(r) {
3624
+ return r.content.filter((b) => b.type === "tool_use");
3625
+ }
3626
+
3627
+ // src/models/model-helpers.ts
3628
+ function modelSupportsInputModality(model, modality) {
3629
+ if (!model) return false;
3630
+ const mods = model.inputModalities;
3631
+ if (!Array.isArray(mods)) return false;
3632
+ return mods.includes(modality);
3633
+ }
3634
+ function modelSupportsImageInput(model) {
3635
+ return modelSupportsInputModality(model, "image");
3636
+ }
3637
+ function findFirstModelByInputModality(models, modality) {
3638
+ if (!Array.isArray(models)) return null;
3639
+ for (const m of models) {
3640
+ if (!m) continue;
3641
+ if (m.isEnabled === false) continue;
3642
+ if (!modelSupportsInputModality(m, modality)) continue;
3643
+ return m;
3652
3644
  }
3653
- /**
3654
- * 正式签署(写,step-up 必须)。
3655
- *
3656
- * `@status gated` — 服务端闸门关闭时会一致返回 `ENVELOPE_GATE_CLOSED` (1031004004)。
3657
- * SDK 不重试、不伪成功;调用方应该将该错误展示为"功能未开放"。
3658
- */
3659
- signEnvelope(envelopeId, req, opts = {}) {
3660
- return this.write(
3661
- "POST",
3662
- `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/sign`,
3663
- req,
3664
- writeCtx(opts)
3665
- );
3645
+ return null;
3646
+ }
3647
+ function findDesktopVisualUnderstandingModel(models) {
3648
+ if (!Array.isArray(models)) return null;
3649
+ const candidates = [];
3650
+ for (const m of models) {
3651
+ if (!m) continue;
3652
+ if (m.isEnabled === false) continue;
3653
+ if (m.capabilities?.supports_desktop_visual_understanding !== true) continue;
3654
+ if (!modelSupportsInputModality(m, "image")) continue;
3655
+ candidates.push(m);
3666
3656
  }
3667
- /**
3668
- * 创建 H5 签署短链(写,step-up 必须)。
3669
- *
3670
- * `@status gated` — 同 {@link signEnvelope}:服务端闸门关闭时 SDK 不重试、不伪成功。
3671
- */
3672
- createH5SigningUrl(envelopeId, req, opts = {}) {
3673
- return this.write(
3674
- "POST",
3675
- `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/h5-url`,
3676
- req,
3677
- writeCtx(opts)
3678
- );
3657
+ if (candidates.length === 0) return null;
3658
+ for (const m of candidates) {
3659
+ if (m.isDefault === true) return m;
3679
3660
  }
3680
- /** 同步 provider 状态(写但只读对账,不创建新 provider 请求)。 */
3681
- syncSigningEnvelopeStatus(envelopeId, opts = {}) {
3682
- return this.write(
3683
- "POST",
3684
- `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/sync-provider-status`,
3685
- null,
3686
- writeCtx(opts)
3687
- );
3661
+ return candidates[0];
3662
+ }
3663
+
3664
+ // src/models/index.ts
3665
+ init_adapters();
3666
+ init_betas();
3667
+
3668
+ // src/billing/entitlements.ts
3669
+ Client.prototype.getBalance = async function(signal) {
3670
+ const resp = await this.doJSON(
3671
+ "GET",
3672
+ "/entitlements/balance",
3673
+ null,
3674
+ signal
3675
+ );
3676
+ return resp.data;
3677
+ };
3678
+ Client.prototype.getBalanceDetail = async function(signal) {
3679
+ const resp = await this.doJSON(
3680
+ "GET",
3681
+ "/entitlements/balance-detail",
3682
+ null,
3683
+ signal
3684
+ );
3685
+ return resp.data;
3686
+ };
3687
+ Client.prototype.listEntitlements = async function(status, signal) {
3688
+ let path = "/entitlements";
3689
+ if (status !== "") {
3690
+ path += `?status=${encodeURIComponent(status)}`;
3688
3691
  }
3689
- // =========================================================================
3690
- // Seal Approval
3691
- // =========================================================================
3692
- /**
3693
- * 提交用印审批申请(写)。
3694
- *
3695
- * `@status production-ready` — 服务端以 `Idempotency-Key` + 业务请求指纹做重放保护:
3696
- * 同 key + 同请求 → 返回原审批 id;同 key + 不同请求 → 拒绝复用幂等键。强烈建议调用方
3697
- * 持久化 `idempotencyKey`,网络重试 / 任务恢复时复用,避免重复创建审批单。
3698
- */
3699
- submitSealApproval(req, opts = {}) {
3700
- return this.write(
3701
- "POST",
3702
- "/compliance/seal-approvals",
3703
- req,
3704
- writeCtx(opts)
3705
- );
3692
+ const resp = await this.doJSON("GET", path, null, signal);
3693
+ return resp.data;
3694
+ };
3695
+ Client.prototype.listConsumeRecords = async function(page, pageSize, signal) {
3696
+ const path = `/entitlements/consume-records?page=${page}&pageSize=${pageSize}`;
3697
+ const resp = await this.doJSON("GET", path, null, signal);
3698
+ return resp.data;
3699
+ };
3700
+ Client.prototype.claimMonthlyFree = async function(signal) {
3701
+ const resp = await this.doJSON(
3702
+ "POST",
3703
+ "/entitlements/claim-monthly",
3704
+ null,
3705
+ signal
3706
+ );
3707
+ return resp.data;
3708
+ };
3709
+ Client.prototype.getByModel = async function(modelID, signal) {
3710
+ if (modelID === "") throw new Error("modelID required");
3711
+ const path = `/entitlements/by-model?modelId=${encodeURIComponent(modelID)}`;
3712
+ const resp = await this.doJSON("GET", path, null, signal);
3713
+ return resp.data;
3714
+ };
3715
+ Client.prototype.listBuckets = async function(signal) {
3716
+ const resp = await this.doJSON(
3717
+ "GET",
3718
+ "/entitlements/buckets",
3719
+ null,
3720
+ signal
3721
+ );
3722
+ return resp.data;
3723
+ };
3724
+ Client.prototype.listCoefficients = async function(signal) {
3725
+ if (this.coefCacheData && Date.now() - this.coefCacheTimeMs < coefCacheTTLMs) {
3726
+ return [...this.coefCacheData];
3706
3727
  }
3707
- /**
3708
- * 审批通过用印申请(写,step-up 必须)。
3709
- *
3710
- * `@status gated` — step-up 未闭合前服务端会返回 `COMPLIANCE_STEP_UP_REQUIRED`。
3711
- * SDK 不重试、不伪成功。方法状态分级见 `docs/compliance.md` Method Status。
3712
- */
3713
- approveSealApproval(id, query, opts = {}) {
3714
- const q = new URLSearchParams();
3715
- if (query.expiresAt) q.set("expiresAt", query.expiresAt);
3716
- if (query.note) q.set("note", query.note);
3717
- const qs = q.toString();
3718
- return this.write(
3719
- "POST",
3720
- `/compliance/seal-approvals/${encodeURIComponent(id)}/approve${qs ? "?" + qs : ""}`,
3721
- null,
3722
- writeCtx(opts)
3723
- );
3724
- }
3725
- rejectSealApproval(id, query, opts = {}) {
3726
- const q = new URLSearchParams();
3727
- if (query.reason) q.set("reason", query.reason);
3728
- const qs = q.toString();
3729
- return this.write(
3730
- "POST",
3731
- `/compliance/seal-approvals/${encodeURIComponent(id)}/reject${qs ? "?" + qs : ""}`,
3732
- null,
3733
- writeCtx(opts)
3734
- );
3735
- }
3736
- cancelSealApproval(id, query, opts = {}) {
3737
- const q = new URLSearchParams();
3738
- if (query.reason) q.set("reason", query.reason);
3739
- const qs = q.toString();
3740
- return this.write(
3741
- "POST",
3742
- `/compliance/seal-approvals/${encodeURIComponent(id)}/cancel${qs ? "?" + qs : ""}`,
3743
- null,
3744
- writeCtx(opts)
3745
- );
3746
- }
3747
- listPendingSealApprovals(signal) {
3748
- return this.read(
3749
- "GET",
3750
- "/compliance/seal-approvals/pending",
3751
- null,
3752
- signal
3753
- );
3754
- }
3755
- getSealApproval(id, signal) {
3756
- return this.read(
3757
- "GET",
3758
- `/compliance/seal-approvals/${encodeURIComponent(id)}`,
3759
- null,
3760
- signal
3761
- );
3762
- }
3763
- // =========================================================================
3764
- // Provider Request (read-only)
3765
- // =========================================================================
3766
- getProviderRequest(id, signal) {
3767
- return this.read(
3768
- "GET",
3769
- `/compliance/provider-requests/${encodeURIComponent(id)}`,
3770
- null,
3771
- signal
3772
- );
3773
- }
3774
- /**
3775
- * 轮询 provider request 到 SUCCESS / FAILED 终态。
3776
- * - SUCCESS / FAILED → 返回最后视图;
3777
- * - UNKNOWN / RETRYING / PENDING → 继续轮询;
3778
- * - timeout → 抛 {@link CompliancePollError} kind='timeout',不自动重发原 provider 请求。
3779
- *
3780
- * SUCCESS 不代表 billing 已 commit;调用方仍需通过业务侧 envelope / asset 终态判断。
3781
- */
3782
- async waitForProviderRequestTerminal(id, opts = {}) {
3783
- return this.poll(
3784
- () => this.getProviderRequest(id, opts.signal),
3785
- (v) => classifyProviderStatus(v.status),
3786
- opts
3787
- );
3788
- }
3789
- // =========================================================================
3790
- // Error classification (re-export for convenience)
3791
- // =========================================================================
3792
- classifyError(err) {
3793
- if (!isBusinessErrorLike(err)) return null;
3794
- if (!isComplianceBusinessError(err)) return null;
3795
- return classifyComplianceError(err);
3728
+ const resp = await this.doJSON(
3729
+ "GET",
3730
+ "/entitlements/coefficients",
3731
+ null,
3732
+ signal
3733
+ );
3734
+ this.coefCacheData = [...resp.data];
3735
+ this.coefCacheTimeMs = Date.now();
3736
+ return resp.data;
3737
+ };
3738
+ Client.prototype.invalidateCoefficientCache = function() {
3739
+ this.coefCacheData = null;
3740
+ this.coefCacheTimeMs = 0;
3741
+ };
3742
+
3743
+ // src/billing/packages.ts
3744
+ init_errors();
3745
+ Client.prototype.listTokenPackages = async function(signal) {
3746
+ const raw = await this.doJSON("GET", "/token-packages", null, signal);
3747
+ if (raw.data && typeof raw.data === "object" && "list" in raw.data) {
3748
+ const page = raw.data;
3749
+ if (Array.isArray(page.list)) return page.list;
3796
3750
  }
3797
- // =========================================================================
3798
- // Internal helpers
3799
- // =========================================================================
3800
- /**
3801
- * 读路径:GET / 公开 verify。允许 401 单次刷新后重放(GET 幂等安全)。
3802
- * 与 client.doJSONFullInternal 行为一致;不复用其代码因为 base URL 不同。
3803
- */
3804
- async read(method, path, body, signal, extraHeaders = {}) {
3805
- return this.executeJson(method, path, body, signal, {
3806
- retryOn401: true,
3807
- extraHeaders
3808
- });
3751
+ if (Array.isArray(raw.data)) return raw.data;
3752
+ throw new Error("decode token packages: unexpected shape");
3753
+ };
3754
+ Client.prototype.getTokenPackageDetail = async function(packageID, signal) {
3755
+ const resp = await this.doJSON(
3756
+ "GET",
3757
+ `/token-packages/${encodeURIComponent(packageID)}`,
3758
+ null,
3759
+ signal
3760
+ );
3761
+ return resp.data;
3762
+ };
3763
+ Client.prototype.buyTokenPackage = async function(packageID, payload, signal) {
3764
+ const body = payload ?? null;
3765
+ const resp = await this.doJSON(
3766
+ "POST",
3767
+ `/token-packages/${encodeURIComponent(packageID)}/buy`,
3768
+ body,
3769
+ signal
3770
+ );
3771
+ return resp.data;
3772
+ };
3773
+ Client.prototype.getOrderStatus = async function(orderID, signal) {
3774
+ const resp = await this.doJSON(
3775
+ "GET",
3776
+ `/token-packages/orders/${encodeURIComponent(orderID)}/status`,
3777
+ null,
3778
+ signal
3779
+ );
3780
+ return resp.data;
3781
+ };
3782
+ Client.prototype.listMyOrders = async function(signal) {
3783
+ const raw = await this.doJSON("GET", "/token-packages/my", null, signal);
3784
+ if (raw.data && typeof raw.data === "object" && "list" in raw.data) {
3785
+ const page = raw.data;
3786
+ if (Array.isArray(page.list)) return page.list;
3809
3787
  }
3810
- /**
3811
- * 公开读路径:public verify。
3812
- *
3813
- * {@link read} 的区别 public 端点不应要求认证:
3814
- * - token 时匿名请求:ensureToken `not authorized` 会被吞掉,继续匿名发送。
3815
- * - token 时附带 `Authorization`,保留后端审计上下文。
3816
- * - 不做 401 refresh replay:401 直接抛 HTTPError,不触发 `forceRefresh`。
3817
- *
3818
- * URL 仍走 `client.complianceURL(path)`,不复用 `/api/v4`;底层复用
3819
- * `client.doRequest`,不新增 fetch/axios 直连。
3820
- */
3821
- async publicRead(method, path, signal) {
3822
- let token = "";
3823
- try {
3824
- token = await this.client.ensureToken(signal);
3825
- } catch {
3826
- }
3827
- const url = this.client.complianceURL(path);
3828
- const headers = { Accept: "application/json" };
3829
- if (token) headers.Authorization = `Bearer ${token}`;
3830
- const resp = await this.client.doRequest({ method, url, headers }, signal);
3831
- if (resp.status < 200 || resp.status >= 300) {
3832
- const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
3833
- throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
3788
+ if (Array.isArray(raw.data)) return raw.data;
3789
+ throw new Error("decode orders: unexpected shape");
3790
+ };
3791
+ Client.prototype.waitForPayment = async function(orderID, pollIntervalMs, signal) {
3792
+ if (pollIntervalMs <= 0) pollIntervalMs = 2e3;
3793
+ while (true) {
3794
+ const status = await this.getOrderStatus(orderID, signal);
3795
+ if (isOrderTerminal(status.status)) {
3796
+ if (isOrderSuccess(status.status)) return status;
3797
+ throw new exports.OrderTerminalError(orderID, status.status);
3834
3798
  }
3835
- const text = await resp.text();
3836
- if (!text) return void 0;
3837
- const parsed = JSON.parse(text);
3838
- const bizErr = apiResponseBusinessError(parsed);
3839
- if (bizErr) throw bizErr;
3840
- return parsed.data;
3841
- }
3842
- /**
3843
- * 写路径:POST。
3844
- * - 发送前 ensureToken 一次确保 token fresh。
3845
- * - 不自动 401 重放:401 → 抛 HTTPError;调用方必须自己刷新 token 后用同一
3846
- * idempotency-key 重新发起,避免 provider 侧重复请求。
3847
- * - 不走 doRequestWithRetry:写操作不允许 5xx/timeout 自动重试。
3848
- */
3849
- async write(method, path, body, ctx) {
3850
- const headers = { ...ctx.extraHeaders ?? {} };
3851
- if (ctx.idempotencyKey) headers["Idempotency-Key"] = ctx.idempotencyKey;
3852
- return this.executeJson(method, path, body, ctx.signal, {
3853
- retryOn401: false,
3854
- extraHeaders: headers
3855
- });
3799
+ await sleepWithSignal(pollIntervalMs, signal);
3856
3800
  }
3857
- async executeJson(method, path, body, signal, opts, retried = false) {
3858
- const token = await this.client.ensureToken(signal);
3859
- const url = this.client.complianceURL(path);
3860
- const headers = {
3861
- Authorization: `Bearer ${token}`,
3862
- Accept: "application/json",
3863
- ...opts.extraHeaders
3864
- };
3865
- let bodyStr;
3866
- if (body != null) {
3867
- bodyStr = typeof body === "string" ? body : JSON.stringify(body);
3868
- headers["Content-Type"] = "application/json";
3869
- }
3870
- const resp = await this.client.doRequest({ method, url, headers, body: bodyStr }, signal);
3871
- if (resp.status === 401 && opts.retryOn401 && !retried) {
3872
- try {
3873
- await resp.body?.cancel();
3874
- } catch {
3875
- }
3876
- await this.client.forceRefresh(signal);
3877
- return this.executeJson(method, path, body, signal, opts, true);
3878
- }
3879
- if (resp.status < 200 || resp.status >= 300) {
3880
- const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
3881
- throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
3801
+ };
3802
+ async function sleepWithSignal(ms, signal) {
3803
+ if (ms <= 0) return;
3804
+ if (signal && signal.aborted) throw new Error("aborted");
3805
+ return new Promise((resolve, reject) => {
3806
+ const t = setTimeout(() => {
3807
+ if (signal && abortHandler) signal.removeEventListener("abort", abortHandler);
3808
+ resolve();
3809
+ }, ms);
3810
+ let abortHandler;
3811
+ if (signal) {
3812
+ abortHandler = () => {
3813
+ clearTimeout(t);
3814
+ signal.removeEventListener("abort", abortHandler);
3815
+ reject(new Error("aborted"));
3816
+ };
3817
+ signal.addEventListener("abort", abortHandler);
3882
3818
  }
3883
- const text = await resp.text();
3884
- if (!text) return void 0;
3885
- const parsed = JSON.parse(text);
3886
- const bizErr = apiResponseBusinessError(parsed);
3887
- if (bizErr) throw bizErr;
3888
- return parsed.data;
3889
- }
3890
- async poll(fetcher, classify, opts) {
3891
- const cfg = {
3892
- timeoutMs: opts.timeoutMs ?? DEFAULT_POLL.timeoutMs,
3893
- initialIntervalMs: opts.initialIntervalMs ?? DEFAULT_POLL.initialIntervalMs,
3894
- maxIntervalMs: opts.maxIntervalMs ?? DEFAULT_POLL.maxIntervalMs,
3895
- multiplier: opts.multiplier ?? DEFAULT_POLL.multiplier
3896
- };
3897
- const deadline = Date.now() + cfg.timeoutMs;
3898
- let interval = cfg.initialIntervalMs;
3899
- let lastValue;
3900
- while (Date.now() < deadline) {
3901
- if (opts.signal?.aborted) {
3902
- throw new CompliancePollError("compliance poll aborted", "unknown");
3903
- }
3904
- lastValue = await fetcher();
3905
- const decision = classify(lastValue);
3906
- if (decision === "done") return lastValue;
3907
- if (decision === "failed") {
3908
- throw new CompliancePollError(
3909
- "compliance poll observed terminal failure",
3910
- "terminal_failure"
3911
- );
3912
- }
3913
- const sleepMs = Math.min(interval, deadline - Date.now());
3914
- if (sleepMs <= 0) break;
3915
- await sleep2(sleepMs, opts.signal);
3916
- interval = Math.min(Math.floor(interval * cfg.multiplier), cfg.maxIntervalMs);
3917
- }
3918
- throw new CompliancePollError("compliance poll timed out", "timeout");
3919
- }
3920
- };
3921
- function classifyTimestamp(status) {
3922
- switch (status) {
3923
- case "VERIFIED":
3924
- return "done";
3925
- case "FAILED":
3926
- case "LOCAL_VERIFY_FAILED":
3927
- return "failed";
3928
- case "PENDING":
3929
- case "UNKNOWN":
3930
- case "RETRYING":
3931
- default:
3932
- return "continue";
3933
- }
3934
- }
3935
- function classifyProviderStatus(status) {
3936
- switch (status) {
3937
- case "SUCCESS":
3938
- return "done";
3939
- case "FAILED":
3940
- return "failed";
3941
- case "PENDING":
3942
- case "UNKNOWN":
3943
- case "RETRYING":
3944
- default:
3945
- return "continue";
3946
- }
3947
- }
3948
- function writeCtx(opts, extraHeaders = {}) {
3949
- return {
3950
- idempotencyKey: opts.idempotencyKey,
3951
- signal: opts.signal,
3952
- extraHeaders
3953
- };
3954
- }
3955
- function isBusinessErrorLike(err) {
3956
- if (err == null || typeof err !== "object") return false;
3957
- return typeof err.code === "number";
3958
- }
3959
- function sleep2(ms, signal) {
3960
- return new Promise((resolve, reject) => {
3961
- if (signal?.aborted) {
3962
- reject(new CompliancePollError("compliance poll aborted", "unknown"));
3963
- return;
3964
- }
3965
- const timer = setTimeout(() => {
3966
- signal?.removeEventListener("abort", onAbort);
3967
- resolve();
3968
- }, ms);
3969
- const onAbort = () => {
3970
- clearTimeout(timer);
3971
- signal?.removeEventListener("abort", onAbort);
3972
- reject(new CompliancePollError("compliance poll aborted", "unknown"));
3973
- };
3974
- signal?.addEventListener("abort", onAbort, { once: true });
3975
3819
  });
3976
3820
  }
3977
3821
 
3978
- // src/sanitize/index.ts
3979
- var sanitize_exports = {};
3980
- __export(sanitize_exports, {
3981
- BlockCodeExecutionToolResult: () => BlockCodeExecutionToolResult,
3982
- BlockContainerUpload: () => BlockContainerUpload,
3983
- BlockDeniedError: () => BlockDeniedError,
3984
- BlockDocument: () => BlockDocument,
3985
- BlockImage: () => BlockImage,
3986
- BlockMCPToolResult: () => BlockMCPToolResult,
3987
- BlockMCPToolUse: () => BlockMCPToolUse,
3988
- BlockRedactedThinking: () => BlockRedactedThinking,
3989
- BlockSearchResult: () => BlockSearchResult,
3990
- BlockServerToolUse: () => BlockServerToolUse,
3991
- BlockText: () => BlockText,
3992
- BlockThinking: () => BlockThinking,
3993
- BlockToolReference: () => BlockToolReference,
3994
- BlockToolResult: () => BlockToolResult,
3995
- BlockToolUse: () => BlockToolUse,
3996
- BlockVideo: () => BlockVideo,
3997
- BlockWebSearchToolResult: () => BlockWebSearchToolResult,
3998
- DeltaCitations: () => DeltaCitations,
3999
- DeltaInputJSON: () => DeltaInputJSON,
4000
- DeltaSignature: () => DeltaSignature,
4001
- DeltaText: () => DeltaText,
4002
- DeltaThinking: () => DeltaThinking,
4003
- EphemeralMarkerField: () => EphemeralMarkerField,
4004
- ErrBlockDenied: () => ErrBlockDenied,
4005
- ErrHistoryTooDeep: () => ErrHistoryTooDeep,
4006
- HistoryTooDeepError: () => HistoryTooDeepError,
4007
- SizeError: () => SizeError,
4008
- dropBlocks: () => dropBlocks,
4009
- sanitize: () => sanitize,
4010
- stripEphemeral: () => stripEphemeral
4011
- });
4012
-
4013
- // src/sanitize/types.ts
4014
- var BlockText = "text";
4015
- var BlockImage = "image";
4016
- var BlockVideo = "video";
4017
- var BlockDocument = "document";
4018
- var BlockSearchResult = "search_result";
4019
- var BlockThinking = "thinking";
4020
- var BlockRedactedThinking = "redacted_thinking";
4021
- var BlockToolUse = "tool_use";
4022
- var BlockToolResult = "tool_result";
4023
- var BlockToolReference = "tool_reference";
4024
- var BlockServerToolUse = "server_tool_use";
4025
- var BlockWebSearchToolResult = "web_search_tool_result";
4026
- var BlockCodeExecutionToolResult = "code_execution_tool_result";
4027
- var BlockMCPToolUse = "mcp_tool_use";
4028
- var BlockMCPToolResult = "mcp_tool_result";
4029
- var BlockContainerUpload = "container_upload";
4030
- var DeltaText = "text_delta";
4031
- var DeltaInputJSON = "input_json_delta";
4032
- var DeltaThinking = "thinking_delta";
4033
- var DeltaSignature = "signature_delta";
4034
- var DeltaCitations = "citations_delta";
4035
- var EphemeralMarkerField = "acosmi_ephemeral";
3822
+ // src/billing/wallet.ts
3823
+ Client.prototype.getWalletStats = async function(signal) {
3824
+ const resp = await this.doJSON("GET", "/wallet/stats", null, signal);
3825
+ return resp.data;
3826
+ };
3827
+ Client.prototype.getWalletTransactions = async function(signal) {
3828
+ const resp = await this.doJSON(
3829
+ "GET",
3830
+ "/wallet/transactions",
3831
+ null,
3832
+ signal
3833
+ );
3834
+ return resp.data;
3835
+ };
4036
3836
 
4037
- // src/sanitize/config.ts
4038
- var HistoryTooDeepError = class extends Error {
4039
- constructor() {
4040
- super("sanitize: messages history exceeds configured depth");
4041
- this.name = "HistoryTooDeepError";
4042
- }
3837
+ // src/skills/skills.ts
3838
+ init_errors();
3839
+ Client.prototype.browseSkillStore = async function(query, signal) {
3840
+ const resp = await this.browseSkills(
3841
+ 1,
3842
+ 50,
3843
+ query.category ?? "",
3844
+ query.keyword ?? "",
3845
+ query.tag ?? "",
3846
+ "",
3847
+ signal
3848
+ );
3849
+ return resp.items;
4043
3850
  };
4044
- var BlockDeniedError = class extends Error {
4045
- constructor() {
4046
- super("sanitize: block type permanently denied");
4047
- this.name = "BlockDeniedError";
4048
- }
3851
+ Client.prototype.browseSkills = async function(page, pageSize, category, keyword, tag, source, signal) {
3852
+ const qv = new URLSearchParams();
3853
+ qv.set("page", String(page));
3854
+ qv.set("pageSize", String(pageSize));
3855
+ if (category) qv.set("category", category);
3856
+ if (keyword) qv.set("keyword", keyword);
3857
+ if (tag) qv.set("tag", tag);
3858
+ if (source) qv.set("source", source);
3859
+ const resp = await this.doPublicJSON(
3860
+ "GET",
3861
+ `/skill-store?${qv.toString()}`,
3862
+ null,
3863
+ signal
3864
+ );
3865
+ return resp.data;
4049
3866
  };
4050
- var SizeError = class extends Error {
4051
- blockType;
4052
- actual;
4053
- limit;
4054
- constructor(blockType, actual, limit) {
4055
- super(`sanitize: ${blockType} base64 size ${actual} exceeds limit ${limit}`);
4056
- this.name = "SizeError";
4057
- this.blockType = blockType;
4058
- this.actual = actual;
4059
- this.limit = limit;
4060
- }
3867
+ Client.prototype.browseSkillsList = async function(page, pageSize, category, keyword, tag, source, signal) {
3868
+ const qv = new URLSearchParams();
3869
+ qv.set("page", String(page));
3870
+ qv.set("pageSize", String(pageSize));
3871
+ qv.set("fields", "minimal");
3872
+ if (category) qv.set("category", category);
3873
+ if (keyword) qv.set("keyword", keyword);
3874
+ if (tag) qv.set("tag", tag);
3875
+ if (source) qv.set("source", source);
3876
+ const resp = await this.doPublicJSON(
3877
+ "GET",
3878
+ `/skill-store?${qv.toString()}`,
3879
+ null,
3880
+ signal
3881
+ );
3882
+ return resp.data;
4061
3883
  };
4062
- var ErrHistoryTooDeep = new HistoryTooDeepError();
4063
- var ErrBlockDenied = new BlockDeniedError();
4064
-
4065
- // src/sanitize/history.ts
4066
- function dropBlocks(messages, pred) {
4067
- const droppedToolUseIDs = collectDroppedToolUseIDs(messages, pred);
4068
- const out = [];
4069
- for (const msg of messages) {
4070
- if (!isPlainObject(msg)) {
4071
- out.push(msg);
4072
- continue;
4073
- }
4074
- const content = msg["content"];
4075
- if (!Array.isArray(content)) {
4076
- out.push(msg);
4077
- continue;
4078
- }
4079
- const { kept, changed } = filterBlocks(content, pred, droppedToolUseIDs);
4080
- if (!changed) {
4081
- out.push(msg);
4082
- continue;
4083
- }
4084
- if (kept.length === 0) {
4085
- continue;
4086
- }
4087
- const newMsg = { ...msg };
4088
- newMsg["content"] = kept;
4089
- out.push(newMsg);
4090
- }
4091
- return out;
4092
- }
4093
- function collectDroppedToolUseIDs(messages, pred) {
4094
- const ids = /* @__PURE__ */ new Set();
4095
- for (const msg of messages) {
4096
- if (!isPlainObject(msg)) continue;
4097
- const content = msg["content"];
4098
- if (!Array.isArray(content)) continue;
4099
- for (const raw of content) {
4100
- if (!isPlainObject(raw)) continue;
4101
- if (!pred(raw)) continue;
4102
- const t = raw["type"];
4103
- if (typeof t !== "string") continue;
4104
- if (t === "tool_use" || t === "server_tool_use" || t === "mcp_tool_use") {
4105
- const id = raw["id"];
4106
- if (typeof id === "string" && id !== "") ids.add(id);
4107
- }
3884
+ Client.prototype.getSkillDetail = async function(skillID, signal) {
3885
+ const resp = await this.doPublicJSON(
3886
+ "GET",
3887
+ `/skill-store/${encodeURIComponent(skillID)}`,
3888
+ null,
3889
+ signal
3890
+ );
3891
+ return resp.data;
3892
+ };
3893
+ Client.prototype.resolveSkill = async function(key, signal) {
3894
+ const resp = await this.doPublicJSON(
3895
+ "GET",
3896
+ `/skill-store/resolve/${encodeURIComponent(key)}`,
3897
+ null,
3898
+ signal
3899
+ );
3900
+ return resp.data;
3901
+ };
3902
+ Client.prototype.installSkill = async function(skillID, signal) {
3903
+ const resp = await this.doJSON(
3904
+ "POST",
3905
+ `/skill-store/${encodeURIComponent(skillID)}/install`,
3906
+ null,
3907
+ signal
3908
+ );
3909
+ return resp.data;
3910
+ };
3911
+ Client.prototype.downloadSkill = async function(skillID, signal) {
3912
+ const ctl = new AbortController();
3913
+ const timer = setTimeout(() => ctl.abort(), 5 * 60 * 1e3);
3914
+ let parentHandler;
3915
+ if (signal) {
3916
+ if (signal.aborted) ctl.abort();
3917
+ else {
3918
+ parentHandler = () => ctl.abort();
3919
+ signal.addEventListener("abort", parentHandler);
4108
3920
  }
4109
3921
  }
4110
- return ids;
4111
- }
4112
- function filterBlocks(content, pred, droppedToolUseIDs) {
4113
- const kept = [];
4114
- let changed = false;
4115
- for (const raw of content) {
4116
- if (!isPlainObject(raw)) {
4117
- kept.push(raw);
4118
- continue;
3922
+ try {
3923
+ const url = this.apiURL(`/skill-store/${encodeURIComponent(skillID)}/download`);
3924
+ const headers = {};
3925
+ let token = "";
3926
+ try {
3927
+ token = await this.ensureToken(ctl.signal);
3928
+ } catch {
4119
3929
  }
4120
- if (pred(raw)) {
4121
- changed = true;
4122
- continue;
3930
+ if (token) headers["Authorization"] = `Bearer ${token}`;
3931
+ let resp;
3932
+ try {
3933
+ resp = await this.fetchImpl(url, { method: "GET", headers, signal: ctl.signal });
3934
+ } catch (e) {
3935
+ throw classifyTransport(`GET /skill-store/${skillID}/download`, url, e);
4123
3936
  }
4124
- if (droppedToolUseIDs.size > 0) {
4125
- const t = raw["type"];
4126
- if (t === "tool_result" || t === "mcp_tool_result") {
4127
- const id = raw["tool_use_id"];
4128
- if (typeof id === "string" && id !== "" && droppedToolUseIDs.has(id)) {
4129
- changed = true;
4130
- continue;
3937
+ if (resp.status === 429) {
3938
+ const bodyText = await readLimitedText(resp.body, maxErrorBodySize);
3939
+ throw new exports.RateLimitError("\u533F\u540D\u4E0B\u8F7D\u5DF2\u8FBE\u9650\u5236", resp.headers.get("Retry-After") ?? "", bodyText);
3940
+ }
3941
+ if (!resp.ok) {
3942
+ const bodyBytes = await readLimited(resp.body, maxErrorBodySize);
3943
+ throw new Error(
3944
+ `download skill: ${parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers).message}`
3945
+ );
3946
+ }
3947
+ const data = await readLimited(resp.body, maxDownloadSize + 1);
3948
+ if (data.byteLength > maxDownloadSize) {
3949
+ throw new Error(`download skill: response exceeds ${maxDownloadSize >> 20}MB limit`);
3950
+ }
3951
+ let filename = "skill.zip";
3952
+ const cd = resp.headers.get("Content-Disposition");
3953
+ if (cd) {
3954
+ const idx = cd.indexOf("filename");
3955
+ if (idx !== -1) {
3956
+ const parts = cd.slice(idx).split("=", 2);
3957
+ if (parts.length === 2) {
3958
+ filename = parts[1].trim().replace(/^["' ]+|["' ]+$/g, "");
4131
3959
  }
4132
3960
  }
4133
3961
  }
4134
- kept.push(raw);
3962
+ return { data, filename };
3963
+ } finally {
3964
+ clearTimeout(timer);
3965
+ if (parentHandler && signal) signal.removeEventListener("abort", parentHandler);
4135
3966
  }
4136
- return { kept, changed };
4137
- }
4138
- function stripEphemeral(messages) {
4139
- return dropBlocks(messages, (b) => {
4140
- const t = b["type"];
4141
- if (t === "thinking" || t === "redacted_thinking") {
4142
- return false;
3967
+ };
3968
+ Client.prototype.uploadSkill = async function(zipData, scope, intent, signal) {
3969
+ return uploadSkillInternal(this, zipData, scope, intent, false, signal);
3970
+ };
3971
+ async function uploadSkillInternal(c, zipData, scope, intent, retried, signal) {
3972
+ const ctl = new AbortController();
3973
+ const timer = setTimeout(() => ctl.abort(), 5 * 60 * 1e3);
3974
+ let parentHandler;
3975
+ if (signal) {
3976
+ if (signal.aborted) ctl.abort();
3977
+ else {
3978
+ parentHandler = () => ctl.abort();
3979
+ signal.addEventListener("abort", parentHandler);
4143
3980
  }
4144
- const v = b[EphemeralMarkerField];
4145
- return v === true;
4146
- });
4147
- }
4148
- function isPlainObject(v) {
4149
- return typeof v === "object" && v !== null && !Array.isArray(v);
4150
- }
4151
-
4152
- // src/sanitize/defensive.ts
4153
- function sanitize(messages, cfg) {
4154
- if ((cfg.maxMessagesTurns ?? 0) > 0 && messages.length > cfg.maxMessagesTurns) {
4155
- throw ErrHistoryTooDeep;
4156
- }
4157
- if ((cfg.maxImageBytes ?? 0) > 0 || (cfg.maxVideoBytes ?? 0) > 0 || (cfg.maxPDFBytes ?? 0) > 0) {
4158
- checkMediaSizes(messages, cfg);
4159
- }
4160
- if (cfg.permanentDenyBlocks && cfg.permanentDenyBlocks.length > 0) {
4161
- const denySet = /* @__PURE__ */ new Set();
4162
- for (const bt of cfg.permanentDenyBlocks) denySet.add(bt);
4163
- messages = dropBlocks(messages, (b) => {
4164
- const t = b["type"];
4165
- return typeof t === "string" && denySet.has(t);
4166
- });
4167
3981
  }
4168
- return messages;
4169
- }
4170
- function checkMediaSizes(messages, cfg) {
4171
- for (const msg of messages) {
4172
- if (!isPlainObject2(msg)) continue;
4173
- const content = msg["content"];
4174
- if (!Array.isArray(content)) continue;
4175
- for (const raw of content) {
4176
- if (!isPlainObject2(raw)) continue;
4177
- const bt = raw["type"];
4178
- if (typeof bt !== "string") continue;
4179
- let limit = 0;
4180
- switch (bt) {
4181
- case "image":
4182
- limit = cfg.maxImageBytes ?? 0;
4183
- break;
4184
- case "video":
4185
- limit = cfg.maxVideoBytes ?? 0;
4186
- break;
4187
- case "document":
4188
- limit = cfg.maxPDFBytes ?? 0;
4189
- break;
4190
- default:
4191
- continue;
3982
+ try {
3983
+ const token = await c.ensureToken(ctl.signal);
3984
+ const form = new FormData();
3985
+ form.append("scope", scope);
3986
+ form.append("intent", intent);
3987
+ const blob = new Blob([zipData], { type: "application/zip" });
3988
+ form.append("file", blob, "skill.zip");
3989
+ const url = c.apiURL("/skill-store/upload");
3990
+ let resp;
3991
+ try {
3992
+ resp = await c.fetchImpl(url, {
3993
+ method: "POST",
3994
+ headers: { Authorization: `Bearer ${token}` },
3995
+ body: form,
3996
+ signal: ctl.signal
3997
+ });
3998
+ } catch (e) {
3999
+ throw classifyTransport("POST /skill-store/upload", url, e);
4000
+ }
4001
+ if (resp.status === 401 && !retried) {
4002
+ try {
4003
+ await resp.body?.cancel();
4004
+ } catch {
4192
4005
  }
4193
- if (limit <= 0) continue;
4194
- const data = extractBase64Data(raw);
4195
- if (data === "") continue;
4196
- const actual = base64DecodedLen(data);
4197
- if (actual > limit) {
4198
- throw new SizeError(bt, actual, limit);
4006
+ try {
4007
+ await c.forceRefresh(ctl.signal);
4008
+ } catch (refreshErr) {
4009
+ throw new Error(
4010
+ `upload: unauthorized and refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`
4011
+ );
4199
4012
  }
4013
+ return uploadSkillInternal(c, zipData, scope, intent, true, signal);
4200
4014
  }
4015
+ if (resp.status < 200 || resp.status >= 300) {
4016
+ const bodyBytes = await readLimited(resp.body, maxErrorBodySize);
4017
+ throw new Error(
4018
+ `upload: ${parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers).message}`
4019
+ );
4020
+ }
4021
+ const text = await resp.text();
4022
+ const result = JSON.parse(text);
4023
+ return result.data.skill;
4024
+ } finally {
4025
+ clearTimeout(timer);
4026
+ if (parentHandler && signal) signal.removeEventListener("abort", parentHandler);
4201
4027
  }
4202
4028
  }
4203
- function extractBase64Data(block) {
4204
- const src = block["source"];
4205
- if (!isPlainObject2(src)) return "";
4206
- if (src["type"] !== "base64") return "";
4207
- const dataRaw = src["data"];
4208
- if (typeof dataRaw !== "string") return "";
4209
- let data = dataRaw;
4210
- const i = data.indexOf("base64,");
4211
- if (i >= 0) {
4212
- data = data.slice(i + "base64,".length);
4213
- }
4214
- return data;
4215
- }
4216
- function base64DecodedLen(b64) {
4217
- const n = b64.length;
4218
- let pad = 0;
4219
- if (n >= 1 && b64[n - 1] === "=") pad++;
4220
- if (n >= 2 && b64[n - 2] === "=") pad++;
4221
- return Math.floor(n * 3 / 4) - pad;
4222
- }
4223
- function isPlainObject2(v) {
4224
- return typeof v === "object" && v !== null && !Array.isArray(v);
4225
- }
4226
-
4227
- // src/agent-runs-types.ts
4228
- var AgentRunStreamError = class extends Error {
4229
- event;
4230
- code;
4231
- stage;
4232
- retryable;
4233
- constructor(event) {
4234
- const err = event.error;
4235
- super(err.stage ? `agent run failed: ${err.stage}: ${err.message}` : `agent run failed: ${err.message}`);
4236
- this.name = "AgentRunStreamError";
4237
- this.event = event;
4238
- this.code = err.code ?? "";
4239
- this.stage = err.stage ?? "";
4240
- this.retryable = err.retryable ?? false;
4241
- }
4029
+ Client.prototype.getSkillSummary = async function(signal) {
4030
+ const resp = await this.doJSON("GET", "/skills/summary", null, signal);
4031
+ return resp.data;
4032
+ };
4033
+ Client.prototype.certifySkill = async function(skillID, signal) {
4034
+ await this.doJSON(
4035
+ "POST",
4036
+ `/skill-store/${encodeURIComponent(skillID)}/certify`,
4037
+ null,
4038
+ signal
4039
+ );
4040
+ };
4041
+ Client.prototype.getCertificationStatus = async function(skillID, signal) {
4042
+ const resp = await this.doJSON(
4043
+ "GET",
4044
+ `/skill-store/${encodeURIComponent(skillID)}/certification`,
4045
+ null,
4046
+ signal
4047
+ );
4048
+ return resp.data;
4049
+ };
4050
+ Client.prototype.generateSkill = async function(req, signal) {
4051
+ const resp = await this.doJSON(
4052
+ "POST",
4053
+ "/skill-generator/generate",
4054
+ req,
4055
+ signal
4056
+ );
4057
+ return resp.data;
4058
+ };
4059
+ Client.prototype.optimizeSkill = async function(req, signal) {
4060
+ const resp = await this.doJSON(
4061
+ "POST",
4062
+ "/skill-generator/optimize",
4063
+ req,
4064
+ signal
4065
+ );
4066
+ return resp.data;
4067
+ };
4068
+ Client.prototype.validateSkill = async function(skillName, signal) {
4069
+ await this.doJSON(
4070
+ "POST",
4071
+ "/skill-generator/validate",
4072
+ { skillName },
4073
+ signal
4074
+ );
4242
4075
  };
4243
4076
 
4244
- // src/client/agent-runs.ts
4245
- init_types();
4246
- var agentRunsByClient = /* @__PURE__ */ new WeakMap();
4247
- Object.defineProperty(Client.prototype, "agentRuns", {
4248
- configurable: true,
4249
- enumerable: false,
4250
- get() {
4251
- let existing = agentRunsByClient.get(this);
4252
- if (!existing) {
4253
- existing = new AgentRunsClient(this);
4254
- agentRunsByClient.set(this, existing);
4077
+ // src/skills/tools.ts
4078
+ Client.prototype.listTools = async function(signal) {
4079
+ const resp = await this.doJSON("GET", "/tools", null, signal);
4080
+ return resp.data.skills;
4081
+ };
4082
+ Client.prototype.getTool = async function(toolID, signal) {
4083
+ const resp = await this.doJSON(
4084
+ "GET",
4085
+ `/tools/${encodeURIComponent(toolID)}`,
4086
+ null,
4087
+ signal
4088
+ );
4089
+ return resp.data;
4090
+ };
4091
+
4092
+ // src/notifications/types.ts
4093
+ function parseNotificationEvent(ev) {
4094
+ if (ev.type !== "event" || ev.topic !== "system") {
4095
+ return null;
4096
+ }
4097
+ if (ev.data == null) return null;
4098
+ let n;
4099
+ try {
4100
+ if (typeof ev.data === "string") {
4101
+ n = JSON.parse(ev.data);
4102
+ } else {
4103
+ n = ev.data;
4255
4104
  }
4256
- return existing;
4105
+ } catch {
4106
+ return null;
4257
4107
  }
4258
- });
4259
- var AgentRunsClient = class {
4260
- constructor(client) {
4261
- this.client = client;
4108
+ if (!n.id) return null;
4109
+ return n;
4110
+ }
4111
+
4112
+ // src/notifications/notifications.ts
4113
+ Client.prototype.listNotifications = async function(page, pageSize, typeFilter, signal) {
4114
+ let path = `/notifications?page=${page}&pageSize=${pageSize}`;
4115
+ if (typeFilter) path += `&type=${encodeURIComponent(typeFilter)}`;
4116
+ const resp = await this.doJSON("GET", path, null, signal);
4117
+ return resp.data;
4118
+ };
4119
+ Client.prototype.getUnreadCount = async function(signal) {
4120
+ const resp = await this.doJSON(
4121
+ "GET",
4122
+ "/notifications/unread-count",
4123
+ null,
4124
+ signal
4125
+ );
4126
+ return resp.data.unreadCount;
4127
+ };
4128
+ Client.prototype.markNotificationRead = async function(id, signal) {
4129
+ await this.doJSON(
4130
+ "PUT",
4131
+ `/notifications/${encodeURIComponent(id)}/read`,
4132
+ null,
4133
+ signal
4134
+ );
4135
+ };
4136
+ Client.prototype.markAllNotificationsRead = async function(signal) {
4137
+ await this.doJSON("PUT", "/notifications/read-all", null, signal);
4138
+ };
4139
+ Client.prototype.deleteNotification = async function(id, signal) {
4140
+ await this.doJSON(
4141
+ "DELETE",
4142
+ `/notifications/${encodeURIComponent(id)}`,
4143
+ null,
4144
+ signal
4145
+ );
4146
+ };
4147
+ Client.prototype.registerDevice = async function(reg, signal) {
4148
+ await this.doJSON("POST", "/devices/register", reg, signal);
4149
+ };
4150
+ Client.prototype.unregisterDevice = async function(token, signal) {
4151
+ await this.doJSON(
4152
+ "DELETE",
4153
+ `/devices/${encodeURIComponent(token)}`,
4154
+ null,
4155
+ signal
4156
+ );
4157
+ };
4158
+ Client.prototype.listNotificationPreferences = async function(signal) {
4159
+ const resp = await this.doJSON(
4160
+ "GET",
4161
+ "/notification-preferences",
4162
+ null,
4163
+ signal
4164
+ );
4165
+ return resp.data;
4166
+ };
4167
+ Client.prototype.updateNotificationPreference = async function(typeCode, pref, signal) {
4168
+ await this.doJSON(
4169
+ "PUT",
4170
+ `/notification-preferences/${encodeURIComponent(typeCode)}`,
4171
+ pref,
4172
+ signal
4173
+ );
4174
+ };
4175
+
4176
+ // src/notifications/ws.ts
4177
+ Client.prototype.connect = async function(cfg, signal) {
4178
+ const noop = () => {
4179
+ };
4180
+ const filledCfg = {
4181
+ onEvent: cfg.onEvent ?? noop,
4182
+ onConnect: cfg.onConnect ?? noop,
4183
+ onDisconnect: cfg.onDisconnect ?? noop,
4184
+ topics: cfg.topics ?? [],
4185
+ reconnectMinMs: cfg.reconnectMinMs ?? 2e3,
4186
+ reconnectMaxMs: cfg.reconnectMaxMs ?? 6e4,
4187
+ autoReconnect: cfg.autoReconnect ?? true
4188
+ };
4189
+ let resolveDone;
4190
+ const done = new Promise((r) => {
4191
+ resolveDone = r;
4192
+ });
4193
+ const abort = new AbortController();
4194
+ if (signal) {
4195
+ if (signal.aborted) abort.abort();
4196
+ else signal.addEventListener("abort", () => abort.abort());
4262
4197
  }
4263
- client;
4264
- async create(req, signal) {
4265
- const resp = await this.requestAPI(
4266
- "POST",
4267
- "/agent-runs",
4268
- toWireCreateRequest(req),
4269
- signal,
4270
- { retryOn401: false }
4271
- );
4272
- return fromWireCreateResponse(resp);
4198
+ const ws = {
4199
+ conn: null,
4200
+ cfg: filledCfg,
4201
+ abort,
4202
+ done,
4203
+ doneResolve: resolveDone,
4204
+ connected: false
4205
+ };
4206
+ await wsConnectOnce(this, ws);
4207
+ this.ws = ws;
4208
+ void wsLoop(this, ws);
4209
+ };
4210
+ Client.prototype.disconnect = async function() {
4211
+ const ws = this.ws;
4212
+ this.ws = null;
4213
+ if (!ws) return;
4214
+ ws.abort.abort();
4215
+ ws.connected = false;
4216
+ if (ws.conn) {
4217
+ try {
4218
+ ws.conn.close(1e3, "");
4219
+ } catch {
4220
+ }
4273
4221
  }
4274
- get(runId, signal) {
4275
- return this.requestAPI(
4276
- "GET",
4277
- `/agent-runs/${encodeURIComponent(runId)}`,
4278
- null,
4279
- signal,
4280
- { retryOn401: true }
4281
- ).then(fromWireRun);
4222
+ await Promise.race([
4223
+ ws.done,
4224
+ new Promise((resolve) => setTimeout(resolve, 5e3))
4225
+ ]);
4226
+ };
4227
+ Client.prototype.isConnected = function() {
4228
+ const ws = this.ws;
4229
+ if (!ws) return false;
4230
+ return ws.connected;
4231
+ };
4232
+ function wsURL(c) {
4233
+ const base = c.apiURL("/ws");
4234
+ return base.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://");
4235
+ }
4236
+ function getWebSocketCtor() {
4237
+ const WSCtor = globalThis.WebSocket;
4238
+ if (!WSCtor) {
4239
+ throw new Error(
4240
+ 'WebSocket not available \u2014 on Node \u226421 set globalThis.WebSocket = require("ws") before connect'
4241
+ );
4282
4242
  }
4283
- stream(runId, opts = {}, signal) {
4284
- return {
4285
- [Symbol.asyncIterator]: () => this.streamGen(runId, opts, signal)
4286
- };
4243
+ return WSCtor;
4244
+ }
4245
+ async function wsConnectOnce(c, ws) {
4246
+ const token = await c.ensureToken(ws.abort.signal);
4247
+ const url = wsURL(c);
4248
+ const WSCtor = getWebSocketCtor();
4249
+ const u = new URL(url);
4250
+ u.searchParams.set("token", token);
4251
+ let conn;
4252
+ try {
4253
+ conn = new WSCtor(u.toString());
4254
+ } catch (e) {
4255
+ throw new Error(`dial: ${e instanceof Error ? e.message : String(e)}`);
4287
4256
  }
4288
- cancel(runId, signal) {
4289
- return this.requestAPI(
4290
- "POST",
4291
- `/agent-runs/${encodeURIComponent(runId)}/cancel`,
4292
- {},
4293
- signal,
4257
+ await new Promise((resolve, reject) => {
4258
+ let opened = false;
4259
+ const handshakeTimer = setTimeout(() => {
4260
+ if (!opened) {
4261
+ try {
4262
+ conn.close();
4263
+ } catch {
4264
+ }
4265
+ reject(new Error("dial: handshake timeout"));
4266
+ }
4267
+ }, 3e4);
4268
+ conn.addEventListener("open", () => {
4269
+ opened = true;
4270
+ });
4271
+ conn.addEventListener("error", (e) => {
4272
+ clearTimeout(handshakeTimer);
4273
+ reject(new Error(`dial: ${e.message ?? "connection error"}`));
4274
+ });
4275
+ conn.addEventListener("message", (e) => {
4276
+ try {
4277
+ const msg = e.data;
4278
+ const welcome = JSON.parse(msg);
4279
+ if (welcome.type !== "welcome") {
4280
+ clearTimeout(handshakeTimer);
4281
+ try {
4282
+ conn.close();
4283
+ } catch {
4284
+ }
4285
+ reject(new Error(`unexpected first message: ${welcome.type}`));
4286
+ return;
4287
+ }
4288
+ clearTimeout(handshakeTimer);
4289
+ ws.conn = conn;
4290
+ ws.connected = true;
4291
+ if (ws.cfg.topics.length > 0) {
4292
+ try {
4293
+ conn.send(
4294
+ JSON.stringify({
4295
+ type: "subscribe",
4296
+ topics: ws.cfg.topics
4297
+ })
4298
+ );
4299
+ } catch (sendErr) {
4300
+ ws.conn = null;
4301
+ ws.connected = false;
4302
+ try {
4303
+ conn.close();
4304
+ } catch {
4305
+ }
4306
+ reject(new Error(`send subscribe: ${sendErr instanceof Error ? sendErr.message : String(sendErr)}`));
4307
+ return;
4308
+ }
4309
+ }
4310
+ ws.cfg.onConnect();
4311
+ console.log(`[acosmi-sdk] websocket connected, connId=${welcome.connId ?? ""}`);
4312
+ resolve();
4313
+ } catch (parseErr) {
4314
+ clearTimeout(handshakeTimer);
4315
+ try {
4316
+ conn.close();
4317
+ } catch {
4318
+ }
4319
+ reject(new Error(`parse welcome: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`));
4320
+ }
4321
+ }, { once: true });
4322
+ });
4323
+ }
4324
+ async function wsLoop(c, ws) {
4325
+ try {
4326
+ while (true) {
4327
+ await wsReadLoop(ws);
4328
+ if (ws.abort.signal.aborted) return;
4329
+ if (ws.conn) {
4330
+ try {
4331
+ ws.conn.close();
4332
+ } catch {
4333
+ }
4334
+ ws.conn = null;
4335
+ }
4336
+ ws.connected = false;
4337
+ if (!ws.cfg.autoReconnect) return;
4338
+ let delay = ws.cfg.reconnectMinMs;
4339
+ while (true) {
4340
+ if (ws.abort.signal.aborted) return;
4341
+ await sleepWithSignal2(delay, ws.abort.signal).catch(() => {
4342
+ });
4343
+ if (ws.abort.signal.aborted) return;
4344
+ console.log(`[acosmi-sdk] websocket reconnecting (delay=${delay}ms)...`);
4345
+ try {
4346
+ await wsConnectOnce(c, ws);
4347
+ break;
4348
+ } catch (err) {
4349
+ console.log(`[acosmi-sdk] websocket reconnect failed: ${err instanceof Error ? err.message : String(err)}`);
4350
+ delay = Math.min(delay * 2, ws.cfg.reconnectMaxMs);
4351
+ }
4352
+ }
4353
+ }
4354
+ } finally {
4355
+ ws.doneResolve();
4356
+ }
4357
+ }
4358
+ async function wsReadLoop(ws) {
4359
+ const conn = ws.conn;
4360
+ if (!conn) return;
4361
+ return new Promise((resolve) => {
4362
+ const handleMessage = (e) => {
4363
+ try {
4364
+ const data = e.data;
4365
+ const event = JSON.parse(data);
4366
+ try {
4367
+ ws.cfg.onEvent(event);
4368
+ } catch {
4369
+ }
4370
+ } catch {
4371
+ }
4372
+ };
4373
+ const handleClose = (e) => {
4374
+ conn.removeEventListener("message", handleMessage);
4375
+ conn.removeEventListener("close", handleClose);
4376
+ conn.removeEventListener("error", handleError);
4377
+ try {
4378
+ ws.cfg.onDisconnect(new Error(`closed: code=${e.code} reason=${e.reason}`));
4379
+ } catch {
4380
+ }
4381
+ resolve();
4382
+ };
4383
+ const handleError = (e) => {
4384
+ conn.removeEventListener("message", handleMessage);
4385
+ conn.removeEventListener("close", handleClose);
4386
+ conn.removeEventListener("error", handleError);
4387
+ try {
4388
+ ws.cfg.onDisconnect(e);
4389
+ } catch {
4390
+ }
4391
+ resolve();
4392
+ };
4393
+ conn.addEventListener("message", handleMessage);
4394
+ conn.addEventListener("close", handleClose);
4395
+ conn.addEventListener("error", handleError);
4396
+ if (ws.abort.signal.aborted) {
4397
+ try {
4398
+ conn.close();
4399
+ } catch {
4400
+ }
4401
+ } else {
4402
+ ws.abort.signal.addEventListener(
4403
+ "abort",
4404
+ () => {
4405
+ try {
4406
+ conn.close();
4407
+ } catch {
4408
+ }
4409
+ },
4410
+ { once: true }
4411
+ );
4412
+ }
4413
+ });
4414
+ }
4415
+ async function sleepWithSignal2(ms, signal) {
4416
+ if (ms <= 0) return;
4417
+ if (signal.aborted) throw new Error("aborted");
4418
+ return new Promise((resolve, reject) => {
4419
+ const t = setTimeout(() => {
4420
+ signal.removeEventListener("abort", abortHandler);
4421
+ resolve();
4422
+ }, ms);
4423
+ const abortHandler = () => {
4424
+ clearTimeout(t);
4425
+ signal.removeEventListener("abort", abortHandler);
4426
+ reject(new Error("aborted"));
4427
+ };
4428
+ signal.addEventListener("abort", abortHandler);
4429
+ });
4430
+ }
4431
+
4432
+ // src/agent-runs/types.ts
4433
+ var AgentRunStreamError = class extends Error {
4434
+ event;
4435
+ code;
4436
+ stage;
4437
+ retryable;
4438
+ constructor(event) {
4439
+ const err = event.error;
4440
+ super(err.stage ? `agent run failed: ${err.stage}: ${err.message}` : `agent run failed: ${err.message}`);
4441
+ this.name = "AgentRunStreamError";
4442
+ this.event = event;
4443
+ this.code = err.code ?? "";
4444
+ this.stage = err.stage ?? "";
4445
+ this.retryable = err.retryable ?? false;
4446
+ }
4447
+ };
4448
+
4449
+ // src/agent-runs/client.ts
4450
+ var agentRunsByClient = /* @__PURE__ */ new WeakMap();
4451
+ Object.defineProperty(Client.prototype, "agentRuns", {
4452
+ configurable: true,
4453
+ enumerable: false,
4454
+ get() {
4455
+ let existing = agentRunsByClient.get(this);
4456
+ if (!existing) {
4457
+ existing = new AgentRunsClient(this);
4458
+ agentRunsByClient.set(this, existing);
4459
+ }
4460
+ return existing;
4461
+ }
4462
+ });
4463
+ var AgentRunsClient = class {
4464
+ constructor(client) {
4465
+ this.client = client;
4466
+ }
4467
+ client;
4468
+ async create(req, signal) {
4469
+ const resp = await this.requestAPI(
4470
+ "POST",
4471
+ "/agent-runs",
4472
+ toWireCreateRequest(req),
4473
+ signal,
4474
+ { retryOn401: false }
4475
+ );
4476
+ return fromWireCreateResponse(resp);
4477
+ }
4478
+ get(runId, signal) {
4479
+ return this.requestAPI(
4480
+ "GET",
4481
+ `/agent-runs/${encodeURIComponent(runId)}`,
4482
+ null,
4483
+ signal,
4484
+ { retryOn401: true }
4485
+ ).then(fromWireRun);
4486
+ }
4487
+ stream(runId, opts = {}, signal) {
4488
+ return {
4489
+ [Symbol.asyncIterator]: () => this.streamGen(runId, opts, signal)
4490
+ };
4491
+ }
4492
+ cancel(runId, signal) {
4493
+ return this.requestAPI(
4494
+ "POST",
4495
+ `/agent-runs/${encodeURIComponent(runId)}/cancel`,
4496
+ {},
4497
+ signal,
4294
4498
  { retryOn401: false }
4295
4499
  ).then(fromWireRun);
4296
4500
  }
@@ -4720,801 +4924,1138 @@ function errorMessage(e) {
4720
4924
  return e instanceof Error ? e.message : String(e);
4721
4925
  }
4722
4926
 
4723
- // src/index.ts
4724
- init_betas();
4725
-
4726
- // src/client/entitlements.ts
4727
- Client.prototype.getBalance = async function(signal) {
4728
- const resp = await this.doJSON(
4729
- "GET",
4730
- "/entitlements/balance",
4731
- null,
4732
- signal
4733
- );
4734
- return resp.data;
4735
- };
4736
- Client.prototype.getBalanceDetail = async function(signal) {
4737
- const resp = await this.doJSON(
4738
- "GET",
4739
- "/entitlements/balance-detail",
4740
- null,
4741
- signal
4742
- );
4743
- return resp.data;
4744
- };
4745
- Client.prototype.listEntitlements = async function(status, signal) {
4746
- let path = "/entitlements";
4747
- if (status !== "") {
4748
- path += `?status=${encodeURIComponent(status)}`;
4749
- }
4750
- const resp = await this.doJSON("GET", path, null, signal);
4751
- return resp.data;
4752
- };
4753
- Client.prototype.listConsumeRecords = async function(page, pageSize, signal) {
4754
- const path = `/entitlements/consume-records?page=${page}&pageSize=${pageSize}`;
4755
- const resp = await this.doJSON("GET", path, null, signal);
4756
- return resp.data;
4757
- };
4758
- Client.prototype.claimMonthlyFree = async function(signal) {
4759
- const resp = await this.doJSON(
4760
- "POST",
4761
- "/entitlements/claim-monthly",
4762
- null,
4763
- signal
4764
- );
4765
- return resp.data;
4766
- };
4767
- Client.prototype.getByModel = async function(modelID, signal) {
4768
- if (modelID === "") throw new Error("modelID required");
4769
- const path = `/entitlements/by-model?modelId=${encodeURIComponent(modelID)}`;
4770
- const resp = await this.doJSON("GET", path, null, signal);
4771
- return resp.data;
4772
- };
4773
- Client.prototype.listBuckets = async function(signal) {
4774
- const resp = await this.doJSON(
4775
- "GET",
4776
- "/entitlements/buckets",
4777
- null,
4778
- signal
4779
- );
4780
- return resp.data;
4781
- };
4782
- Client.prototype.listCoefficients = async function(signal) {
4783
- if (this.coefCacheData && Date.now() - this.coefCacheTimeMs < coefCacheTTLMs) {
4784
- return [...this.coefCacheData];
4785
- }
4786
- const resp = await this.doJSON(
4787
- "GET",
4788
- "/entitlements/coefficients",
4789
- null,
4790
- signal
4791
- );
4792
- this.coefCacheData = [...resp.data];
4793
- this.coefCacheTimeMs = Date.now();
4794
- return resp.data;
4795
- };
4796
- Client.prototype.invalidateCoefficientCache = function() {
4797
- this.coefCacheData = null;
4798
- this.coefCacheTimeMs = 0;
4799
- };
4927
+ // src/compliance/scopes.ts
4928
+ var ScopeComplianceEvidenceRead = "compliance:evidence:read";
4929
+ var ScopeComplianceEvidenceWrite = "compliance:evidence:write";
4930
+ var ScopeComplianceTimestampIssue = "compliance:timestamp:issue";
4931
+ var ScopeComplianceTimestampVerify = "compliance:timestamp:verify";
4932
+ var ScopeComplianceContractSigningRead = "compliance:contract_signing:read";
4933
+ var ScopeComplianceContractSigningWrite = "compliance:contract_signing:write";
4934
+ var ScopeComplianceSealManage = "compliance:seal:manage";
4935
+ var ScopeComplianceSealApprovalRequest = "compliance:seal_approval:request";
4936
+ var ScopeComplianceSealApprovalApprove = "compliance:seal_approval:approve";
4937
+ var ScopeComplianceSealUseExecute = "compliance:seal_use:execute";
4938
+ var ScopeComplianceReportsRead = "compliance:reports:read";
4939
+ var ScopeComplianceReportsWrite = "compliance:reports:write";
4940
+ var ScopeComplianceReportsPublish = "compliance:reports:publish";
4941
+ var ScopeComplianceContractTemplateRead = "compliance:contract_template:read";
4942
+ var ScopeComplianceContractTemplateWrite = "compliance:contract_template:write";
4943
+ function complianceScopes() {
4944
+ return [
4945
+ ScopeComplianceEvidenceRead,
4946
+ ScopeComplianceEvidenceWrite,
4947
+ ScopeComplianceTimestampIssue,
4948
+ ScopeComplianceTimestampVerify,
4949
+ ScopeComplianceContractSigningRead,
4950
+ ScopeComplianceContractSigningWrite,
4951
+ ScopeComplianceSealManage,
4952
+ ScopeComplianceSealApprovalRequest,
4953
+ ScopeComplianceSealApprovalApprove,
4954
+ ScopeComplianceSealUseExecute,
4955
+ ScopeComplianceReportsRead,
4956
+ ScopeComplianceReportsWrite,
4957
+ ScopeComplianceReportsPublish,
4958
+ ScopeComplianceContractTemplateRead,
4959
+ ScopeComplianceContractTemplateWrite
4960
+ ];
4961
+ }
4800
4962
 
4801
- // src/client/packages.ts
4802
- init_types();
4803
- Client.prototype.listTokenPackages = async function(signal) {
4804
- const raw = await this.doJSON("GET", "/token-packages", null, signal);
4805
- if (raw.data && typeof raw.data === "object" && "list" in raw.data) {
4806
- const page = raw.data;
4807
- if (Array.isArray(page.list)) return page.list;
4808
- }
4809
- if (Array.isArray(raw.data)) return raw.data;
4810
- throw new Error("decode token packages: unexpected shape");
4811
- };
4812
- Client.prototype.getTokenPackageDetail = async function(packageID, signal) {
4813
- const resp = await this.doJSON(
4814
- "GET",
4815
- `/token-packages/${encodeURIComponent(packageID)}`,
4816
- null,
4817
- signal
4818
- );
4819
- return resp.data;
4820
- };
4821
- Client.prototype.buyTokenPackage = async function(packageID, payload, signal) {
4822
- const body = payload ?? null;
4823
- const resp = await this.doJSON(
4824
- "POST",
4825
- `/token-packages/${encodeURIComponent(packageID)}/buy`,
4826
- body,
4827
- signal
4828
- );
4829
- return resp.data;
4830
- };
4831
- Client.prototype.getOrderStatus = async function(orderID, signal) {
4832
- const resp = await this.doJSON(
4833
- "GET",
4834
- `/token-packages/orders/${encodeURIComponent(orderID)}/status`,
4835
- null,
4836
- signal
4837
- );
4838
- return resp.data;
4839
- };
4840
- Client.prototype.listMyOrders = async function(signal) {
4841
- const raw = await this.doJSON("GET", "/token-packages/my", null, signal);
4842
- if (raw.data && typeof raw.data === "object" && "list" in raw.data) {
4843
- const page = raw.data;
4844
- if (Array.isArray(page.list)) return page.list;
4845
- }
4846
- if (Array.isArray(raw.data)) return raw.data;
4847
- throw new Error("decode orders: unexpected shape");
4848
- };
4849
- Client.prototype.waitForPayment = async function(orderID, pollIntervalMs, signal) {
4850
- if (pollIntervalMs <= 0) pollIntervalMs = 2e3;
4851
- while (true) {
4852
- const status = await this.getOrderStatus(orderID, signal);
4853
- if (isOrderTerminal(status.status)) {
4854
- if (isOrderSuccess(status.status)) return status;
4855
- throw new exports.OrderTerminalError(orderID, status.status);
4856
- }
4857
- await sleepWithSignal(pollIntervalMs, signal);
4963
+ // src/compliance/status.ts
4964
+ var ErrComplianceStepUpRequired = "COMPLIANCE_STEP_UP_REQUIRED";
4965
+ var ErrEnvelopeGateClosed = "ENVELOPE_GATE_CLOSED";
4966
+ var ErrProviderNotConfigured = "PROVIDER_NOT_CONFIGURED";
4967
+ var ErrProviderUnknownNoRetry = "PROVIDER_REQUEST_UNKNOWN_NO_RETRY";
4968
+ var ErrBillingCallbackCannotCommit = "BILLING_CALLBACK_CANNOT_COMMIT";
4969
+ var ErrBillingCommitRequiresLocalVerify = "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY";
4970
+ var ErrBillingS2sForbidden = "BILLING_S2S_FORBIDDEN";
4971
+ var ErrSealApprovalNotApproved = "SEAL_APPROVAL_STATE_NOT_APPROVED";
4972
+ var ErrSealApprovalExpired = "SEAL_APPROVAL_EXPIRED";
4973
+ var ErrSealApprovalNonceUsed = "SEAL_APPROVAL_NONCE_USED";
4974
+ var ErrSealApprovalContractHashMismatch = "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH";
4975
+ var ErrSealApprovalSealMismatch = "SEAL_APPROVAL_SEAL_MISMATCH";
4976
+ var ErrSealApprovalLocationMismatch = "SEAL_APPROVAL_LOCATION_MISMATCH";
4977
+ var ErrSealApprovalTransactorMismatch = "SEAL_APPROVAL_TRANSACTOR_MISMATCH";
4978
+ var ErrSealUseAlreadyConsumed = "SEAL_USE_ALREADY_CONSUMED";
4979
+ function isComplianceTerminalError(code) {
4980
+ switch (code) {
4981
+ case ErrEnvelopeGateClosed:
4982
+ case ErrProviderNotConfigured:
4983
+ case ErrProviderUnknownNoRetry:
4984
+ case ErrBillingCallbackCannotCommit:
4985
+ case ErrBillingCommitRequiresLocalVerify:
4986
+ case ErrBillingS2sForbidden:
4987
+ case ErrSealApprovalNonceUsed:
4988
+ case ErrSealApprovalExpired:
4989
+ case ErrSealApprovalContractHashMismatch:
4990
+ case ErrSealApprovalSealMismatch:
4991
+ case ErrSealApprovalLocationMismatch:
4992
+ case ErrSealApprovalTransactorMismatch:
4993
+ case ErrSealUseAlreadyConsumed:
4994
+ return true;
4995
+ default:
4996
+ return false;
4858
4997
  }
4859
- };
4860
- async function sleepWithSignal(ms, signal) {
4861
- if (ms <= 0) return;
4862
- if (signal && signal.aborted) throw new Error("aborted");
4863
- return new Promise((resolve, reject) => {
4864
- const t = setTimeout(() => {
4865
- if (signal && abortHandler) signal.removeEventListener("abort", abortHandler);
4866
- resolve();
4867
- }, ms);
4868
- let abortHandler;
4869
- if (signal) {
4870
- abortHandler = () => {
4871
- clearTimeout(t);
4872
- signal.removeEventListener("abort", abortHandler);
4873
- reject(new Error("aborted"));
4874
- };
4875
- signal.addEventListener("abort", abortHandler);
4876
- }
4877
- });
4998
+ }
4999
+ function isBillingConfirmable(providerStatus, billingStatus) {
5000
+ return providerStatus === "success" && billingStatus === "committed";
4878
5001
  }
4879
5002
 
4880
- // src/client/wallet.ts
4881
- Client.prototype.getWalletStats = async function(signal) {
4882
- const resp = await this.doJSON("GET", "/wallet/stats", null, signal);
4883
- return resp.data;
4884
- };
4885
- Client.prototype.getWalletTransactions = async function(signal) {
4886
- const resp = await this.doJSON(
4887
- "GET",
4888
- "/wallet/transactions",
4889
- null,
4890
- signal
4891
- );
4892
- return resp.data;
4893
- };
4894
-
4895
- // src/client/skills.ts
4896
- init_types();
4897
- Client.prototype.browseSkillStore = async function(query, signal) {
4898
- const resp = await this.browseSkills(
4899
- 1,
4900
- 50,
4901
- query.category ?? "",
4902
- query.keyword ?? "",
4903
- query.tag ?? "",
4904
- "",
4905
- signal
4906
- );
4907
- return resp.items;
4908
- };
4909
- Client.prototype.browseSkills = async function(page, pageSize, category, keyword, tag, source, signal) {
4910
- const qv = new URLSearchParams();
4911
- qv.set("page", String(page));
4912
- qv.set("pageSize", String(pageSize));
4913
- if (category) qv.set("category", category);
4914
- if (keyword) qv.set("keyword", keyword);
4915
- if (tag) qv.set("tag", tag);
4916
- if (source) qv.set("source", source);
4917
- const resp = await this.doPublicJSON(
4918
- "GET",
4919
- `/skill-store?${qv.toString()}`,
4920
- null,
4921
- signal
4922
- );
4923
- return resp.data;
4924
- };
4925
- Client.prototype.browseSkillsList = async function(page, pageSize, category, keyword, tag, source, signal) {
4926
- const qv = new URLSearchParams();
4927
- qv.set("page", String(page));
4928
- qv.set("pageSize", String(pageSize));
4929
- qv.set("fields", "minimal");
4930
- if (category) qv.set("category", category);
4931
- if (keyword) qv.set("keyword", keyword);
4932
- if (tag) qv.set("tag", tag);
4933
- if (source) qv.set("source", source);
4934
- const resp = await this.doPublicJSON(
4935
- "GET",
4936
- `/skill-store?${qv.toString()}`,
4937
- null,
4938
- signal
4939
- );
4940
- return resp.data;
4941
- };
4942
- Client.prototype.getSkillDetail = async function(skillID, signal) {
4943
- const resp = await this.doPublicJSON(
4944
- "GET",
4945
- `/skill-store/${encodeURIComponent(skillID)}`,
4946
- null,
4947
- signal
4948
- );
4949
- return resp.data;
4950
- };
4951
- Client.prototype.resolveSkill = async function(key, signal) {
4952
- const resp = await this.doPublicJSON(
4953
- "GET",
4954
- `/skill-store/resolve/${encodeURIComponent(key)}`,
4955
- null,
4956
- signal
4957
- );
4958
- return resp.data;
4959
- };
4960
- Client.prototype.installSkill = async function(skillID, signal) {
4961
- const resp = await this.doJSON(
4962
- "POST",
4963
- `/skill-store/${encodeURIComponent(skillID)}/install`,
4964
- null,
4965
- signal
4966
- );
4967
- return resp.data;
5003
+ // src/compliance/errors.ts
5004
+ var CODE_TO_KEY = {
5005
+ // 通用 / token / scope (1-031-000-xxx)
5006
+ 1031000001: "COMPLIANCE_UNAUTHORIZED",
5007
+ 1031000002: "COMPLIANCE_TOKEN_INVALID",
5008
+ 1031000003: "COMPLIANCE_TOKEN_INVALID",
5009
+ 1031000004: "COMPLIANCE_TOKEN_INVALID",
5010
+ 1031000005: "COMPLIANCE_TOKEN_INVALID",
5011
+ 1031000006: "COMPLIANCE_TOKEN_INVALID",
5012
+ 1031000007: "COMPLIANCE_TOKEN_INVALID",
5013
+ 1031000008: "COMPLIANCE_TOKEN_INVALID",
5014
+ 1031000009: "COMPLIANCE_TOKEN_INVALID",
5015
+ 1031000010: "COMPLIANCE_TOKEN_INVALID",
5016
+ 1031000011: "COMPLIANCE_TOKEN_INVALID",
5017
+ 1031000012: "COMPLIANCE_INSUFFICIENT_SCOPE",
5018
+ 1031000013: "COMPLIANCE_STEP_UP_REQUIRED",
5019
+ // Subject snapshot (1-031-001-xxx)
5020
+ 1031001001: "SUBJECT_SNAPSHOT_NOT_FOUND",
5021
+ 1031001002: "SUBJECT_SNAPSHOT_TENANT_MISMATCH",
5022
+ 1031001003: "SUBJECT_SNAPSHOT_REQUIRED",
5023
+ // Evidence / Timestamp / Package / Report (1-031-002-xxx)
5024
+ 1031002001: "EVIDENCE_ASSET_NOT_FOUND",
5025
+ 1031002002: "SUBJECT_SNAPSHOT_TENANT_MISMATCH",
5026
+ 1031002003: "EVIDENCE_ASSET_HASH_MISMATCH",
5027
+ 1031002004: "EVIDENCE_ASSET_PAYLOAD_REQUIRED",
5028
+ 1031002005: "EVIDENCE_ASSET_PAYLOAD_REQUIRED",
5029
+ 1031002006: "TIMESTAMP_TOKEN_NOT_FOUND",
5030
+ 1031002007: "TIMESTAMP_PROVIDER_FAILED",
5031
+ 1031002008: "TIMESTAMP_PROVIDER_UNKNOWN",
5032
+ 1031002009: "TIMESTAMP_LOCAL_VERIFY_FAILED",
5033
+ 1031002010: "TIMESTAMP_PROVIDER_NOT_AVAILABLE",
5034
+ 1031002011: "EVIDENCE_PACKAGE_NOT_FOUND",
5035
+ 1031002012: "EVIDENCE_PACKAGE_TIMESTAMP_REQUIRED",
5036
+ 1031002013: "EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH",
5037
+ 1031002014: "REPORT_NOT_FOUND",
5038
+ 1031002015: "REPORT_ALREADY_PUBLISHED",
5039
+ 1031002016: "REPORT_DRAFT_REQUIRED",
5040
+ 1031002017: "EVIDENCE_VERIFY_TARGET_REQUIRED",
5041
+ 1031002018: "EVIDENCE_VERIFY_TARGET_NOT_FOUND",
5042
+ // Provider request (1-031-003-xxx)
5043
+ 1031003001: "PROVIDER_REQUEST_UNKNOWN_NO_RETRY",
5044
+ 1031003002: "PROVIDER_CALLBACK_SOURCE_INVALID",
5045
+ 1031003003: "PROVIDER_NOT_CONFIGURED",
5046
+ 1031003010: "PROVIDER_REQUEST_NOT_FOUND",
5047
+ 1031003011: "PROVIDER_REQUEST_IDEMPOTENCY_REQUIRED",
5048
+ 1031003012: "PROVIDER_REQUEST_STATUS_NOT_TERMINAL",
5049
+ // Envelope (1-031-004-xxx)
5050
+ 1031004001: "ENVELOPE_NOT_FOUND",
5051
+ 1031004002: "ENVELOPE_TENANT_MISMATCH",
5052
+ 1031004003: "ENVELOPE_STATE_NOT_ALLOWED",
5053
+ 1031004004: "ENVELOPE_GATE_CLOSED",
5054
+ 1031004005: "CONTRACT_NOT_FOUND",
5055
+ 1031004006: "CONTRACT_HASH_MISMATCH",
5056
+ 1031004007: "CONTRACT_NOT_FOUND",
5057
+ 1031004008: "PROVIDER_AUTHORIZATION_NOT_CONFIRMED",
5058
+ 1031004009: "PROVIDER_AUTHORIZATION_NOT_CONFIRMED",
5059
+ 1031004010: "ENVELOPE_EVIDENCE_NOT_READY",
5060
+ // Seal approval / use (1-031-005-xxx)
5061
+ 1031005001: "SEAL_ASSET_NOT_FOUND",
5062
+ 1031005010: "SEAL_APPROVAL_NOT_FOUND",
5063
+ 1031005011: "SEAL_APPROVAL_NOT_FOUND",
5064
+ 1031005012: "SEAL_APPROVAL_STATE_NOT_APPROVED",
5065
+ 1031005013: "SEAL_APPROVAL_EXPIRED",
5066
+ 1031005014: "SEAL_APPROVAL_ALREADY_USED",
5067
+ 1031005015: "SEAL_APPROVAL_NONCE_USED",
5068
+ 1031005016: "SEAL_APPROVAL_SEAL_MISMATCH",
5069
+ 1031005017: "SEAL_APPROVAL_LOCATION_MISMATCH",
5070
+ 1031005018: "SEAL_APPROVAL_TRANSACTOR_MISMATCH",
5071
+ 1031005019: "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH",
5072
+ 1031005020: "SEAL_APPROVAL_INVALID_TRANSITION",
5073
+ 1031005030: "SEAL_USE_ALREADY_CONSUMED",
5074
+ // Billing (1-031-006-xxx)
5075
+ 1031006004: "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY",
5076
+ 1031006005: "BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS",
5077
+ 1031006007: "BILLING_CALLBACK_CANNOT_COMMIT",
5078
+ 1031006008: "BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE",
5079
+ 1031006009: "BILLING_S2S_FORBIDDEN",
5080
+ // Audit (1-031-007-xxx)
5081
+ 1031007011: "AUDIT_CHAIN_TAMPER_DETECTED"
4968
5082
  };
4969
- Client.prototype.downloadSkill = async function(skillID, signal) {
4970
- const ctl = new AbortController();
4971
- const timer = setTimeout(() => ctl.abort(), 5 * 60 * 1e3);
4972
- let parentHandler;
4973
- if (signal) {
4974
- if (signal.aborted) ctl.abort();
4975
- else {
4976
- parentHandler = () => ctl.abort();
4977
- signal.addEventListener("abort", parentHandler);
4978
- }
4979
- }
4980
- try {
4981
- const url = this.apiURL(`/skill-store/${encodeURIComponent(skillID)}/download`);
4982
- const headers = {};
4983
- let token = "";
4984
- try {
4985
- token = await this.ensureToken(ctl.signal);
4986
- } catch {
4987
- }
4988
- if (token) headers["Authorization"] = `Bearer ${token}`;
4989
- let resp;
4990
- try {
4991
- resp = await this.fetchImpl(url, { method: "GET", headers, signal: ctl.signal });
4992
- } catch (e) {
4993
- throw classifyTransport(`GET /skill-store/${skillID}/download`, url, e);
4994
- }
4995
- if (resp.status === 429) {
4996
- const bodyText = await readLimitedText(resp.body, maxErrorBodySize);
4997
- throw new exports.RateLimitError("\u533F\u540D\u4E0B\u8F7D\u5DF2\u8FBE\u9650\u5236", resp.headers.get("Retry-After") ?? "", bodyText);
4998
- }
4999
- if (!resp.ok) {
5000
- const bodyBytes = await readLimited(resp.body, maxErrorBodySize);
5001
- throw new Error(
5002
- `download skill: ${parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers).message}`
5003
- );
5004
- }
5005
- const data = await readLimited(resp.body, maxDownloadSize + 1);
5006
- if (data.byteLength > maxDownloadSize) {
5007
- throw new Error(`download skill: response exceeds ${maxDownloadSize >> 20}MB limit`);
5008
- }
5009
- let filename = "skill.zip";
5010
- const cd = resp.headers.get("Content-Disposition");
5011
- if (cd) {
5012
- const idx = cd.indexOf("filename");
5013
- if (idx !== -1) {
5014
- const parts = cd.slice(idx).split("=", 2);
5015
- if (parts.length === 2) {
5016
- filename = parts[1].trim().replace(/^["' ]+|["' ]+$/g, "");
5017
- }
5018
- }
5083
+ var STEP_UP_KEYS = /* @__PURE__ */ new Set(["COMPLIANCE_STEP_UP_REQUIRED"]);
5084
+ var TERMINAL_KEYS = /* @__PURE__ */ new Set([
5085
+ "ENVELOPE_GATE_CLOSED",
5086
+ "PROVIDER_NOT_CONFIGURED",
5087
+ "PROVIDER_REQUEST_UNKNOWN_NO_RETRY",
5088
+ "BILLING_CALLBACK_CANNOT_COMMIT",
5089
+ "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY",
5090
+ "BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS",
5091
+ "BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE",
5092
+ "BILLING_S2S_FORBIDDEN",
5093
+ "SEAL_APPROVAL_NONCE_USED",
5094
+ "SEAL_APPROVAL_EXPIRED",
5095
+ "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH",
5096
+ "SEAL_APPROVAL_SEAL_MISMATCH",
5097
+ "SEAL_APPROVAL_LOCATION_MISMATCH",
5098
+ "SEAL_APPROVAL_TRANSACTOR_MISMATCH",
5099
+ "SEAL_USE_ALREADY_CONSUMED",
5100
+ "CONTRACT_HASH_MISMATCH",
5101
+ "TIMESTAMP_LOCAL_VERIFY_FAILED",
5102
+ "EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH",
5103
+ "AUDIT_CHAIN_TAMPER_DETECTED",
5104
+ "PROVIDER_REQUEST_NOT_FOUND",
5105
+ "EVIDENCE_ASSET_HASH_MISMATCH",
5106
+ "EVIDENCE_VERIFY_TARGET_NOT_FOUND",
5107
+ "REPORT_ALREADY_PUBLISHED"
5108
+ ]);
5109
+ var RETRYABLE_KEYS = /* @__PURE__ */ new Set([]);
5110
+ function classifyComplianceError(err) {
5111
+ const key = CODE_TO_KEY[err.code] ?? "UNKNOWN_COMPLIANCE_ERROR";
5112
+ return {
5113
+ code: err.code,
5114
+ message: err.message,
5115
+ key,
5116
+ retryable: RETRYABLE_KEYS.has(key),
5117
+ terminal: TERMINAL_KEYS.has(key),
5118
+ stepUpRequired: STEP_UP_KEYS.has(key)
5119
+ };
5120
+ }
5121
+ function isComplianceBusinessError(err) {
5122
+ return err.code >= 1031e6 && err.code <= 1031999999;
5123
+ }
5124
+
5125
+ // src/compliance/client.ts
5126
+ var cache = /* @__PURE__ */ new WeakMap();
5127
+ Object.defineProperty(Client.prototype, "compliance", {
5128
+ configurable: true,
5129
+ enumerable: false,
5130
+ get() {
5131
+ let existing = cache.get(this);
5132
+ if (!existing) {
5133
+ existing = new ComplianceClient(this);
5134
+ cache.set(this, existing);
5019
5135
  }
5020
- return { data, filename };
5021
- } finally {
5022
- clearTimeout(timer);
5023
- if (parentHandler && signal) signal.removeEventListener("abort", parentHandler);
5136
+ return existing;
5024
5137
  }
5138
+ });
5139
+ var DEFAULT_POLL = {
5140
+ timeoutMs: 6e4,
5141
+ initialIntervalMs: 1e3,
5142
+ maxIntervalMs: 5e3,
5143
+ multiplier: 1.5
5025
5144
  };
5026
- Client.prototype.uploadSkill = async function(zipData, scope, intent, signal) {
5027
- return uploadSkillInternal(this, zipData, scope, intent, false, signal);
5145
+ var CompliancePollError = class extends Error {
5146
+ kind;
5147
+ lastInfo;
5148
+ constructor(message, kind, lastInfo) {
5149
+ super(message);
5150
+ this.name = "CompliancePollError";
5151
+ this.kind = kind;
5152
+ this.lastInfo = lastInfo;
5153
+ }
5028
5154
  };
5029
- async function uploadSkillInternal(c, zipData, scope, intent, retried, signal) {
5030
- const ctl = new AbortController();
5031
- const timer = setTimeout(() => ctl.abort(), 5 * 60 * 1e3);
5032
- let parentHandler;
5033
- if (signal) {
5034
- if (signal.aborted) ctl.abort();
5035
- else {
5036
- parentHandler = () => ctl.abort();
5037
- signal.addEventListener("abort", parentHandler);
5038
- }
5155
+ var ComplianceClient = class {
5156
+ constructor(client) {
5157
+ this.client = client;
5039
5158
  }
5040
- try {
5041
- const token = await c.ensureToken(ctl.signal);
5042
- const form = new FormData();
5043
- form.append("scope", scope);
5044
- form.append("intent", intent);
5045
- const blob = new Blob([zipData], { type: "application/zip" });
5046
- form.append("file", blob, "skill.zip");
5047
- const url = c.apiURL("/skill-store/upload");
5048
- let resp;
5049
- try {
5050
- resp = await c.fetchImpl(url, {
5051
- method: "POST",
5052
- headers: { Authorization: `Bearer ${token}` },
5053
- body: form,
5054
- signal: ctl.signal
5055
- });
5056
- } catch (e) {
5057
- throw classifyTransport("POST /skill-store/upload", url, e);
5058
- }
5059
- if (resp.status === 401 && !retried) {
5060
- try {
5061
- await resp.body?.cancel();
5062
- } catch {
5063
- }
5064
- try {
5065
- await c.forceRefresh(ctl.signal);
5066
- } catch (refreshErr) {
5067
- throw new Error(
5068
- `upload: unauthorized and refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}`
5069
- );
5070
- }
5071
- return uploadSkillInternal(c, zipData, scope, intent, true, signal);
5072
- }
5073
- if (resp.status < 200 || resp.status >= 300) {
5074
- const bodyBytes = await readLimited(resp.body, maxErrorBodySize);
5075
- throw new Error(
5076
- `upload: ${parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers).message}`
5077
- );
5078
- }
5079
- const text = await resp.text();
5080
- const result = JSON.parse(text);
5081
- return result.data.skill;
5082
- } finally {
5083
- clearTimeout(timer);
5084
- if (parentHandler && signal) signal.removeEventListener("abort", parentHandler);
5159
+ client;
5160
+ // =========================================================================
5161
+ // Evidence Asset
5162
+ // =========================================================================
5163
+ /** 创建证据资产(写)。 */
5164
+ createEvidenceAsset(req, opts = {}) {
5165
+ return this.write(
5166
+ "POST",
5167
+ "/compliance/evidence/assets",
5168
+ req,
5169
+ writeCtx(opts)
5170
+ );
5171
+ }
5172
+ /** 读 — 证据资产详情。 */
5173
+ getEvidenceAsset(id, signal) {
5174
+ return this.read(
5175
+ "GET",
5176
+ `/compliance/evidence/assets/${encodeURIComponent(id)}`,
5177
+ null,
5178
+ signal
5179
+ );
5180
+ }
5181
+ /**
5182
+ * 读 — 证据资产分页列表(compliance gateway S1)。
5183
+ *
5184
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 yudao `PageResult<T>`
5185
+ * (`{ total, list }`)。所有过滤项可选;`createTimeStart` / `createTimeEnd`
5186
+ * 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
5187
+ */
5188
+ listEvidenceAssets(req = {}, signal) {
5189
+ return this.read(
5190
+ "GET",
5191
+ `/compliance/evidence/assets/page${pageQuery(req, ["assetType", "status", "createTimeStart", "createTimeEnd"])}`,
5192
+ null,
5193
+ signal
5194
+ );
5195
+ }
5196
+ /**
5197
+ * 公开 verify。隐私边界:返回字段不含 PII / 合同原文 / storage / provider raw。
5198
+ *
5199
+ * 匿名可调用:未 login 时走匿名请求,不会抛 `not authorized, call login() first`。
5200
+ * 已 login / 已持有 token 时附带 `Authorization` 以保留审计上下文。public 端点不
5201
+ * 应要求认证 — 收到 401 直接抛 HTTPError,不触发 `forceRefresh`,也不做 refresh
5202
+ * replay。
5203
+ */
5204
+ verifyEvidencePublic(params, signal) {
5205
+ const q = new URLSearchParams();
5206
+ if (params.evidenceNo) q.set("evidenceNo", params.evidenceNo);
5207
+ if (params.publicVerifyCode) q.set("publicVerifyCode", params.publicVerifyCode);
5208
+ const qs = q.toString();
5209
+ return this.publicRead(
5210
+ "GET",
5211
+ `/compliance/evidence/verify${qs ? "?" + qs : ""}`,
5212
+ signal
5213
+ );
5214
+ }
5215
+ // =========================================================================
5216
+ // Timestamp
5217
+ // =========================================================================
5218
+ /** 申请时间章(写)。SDK 永远不传 provider 字段。 */
5219
+ issueTimestamp(req, opts = {}) {
5220
+ return this.write("POST", "/compliance/timestamps", req, writeCtx(opts));
5221
+ }
5222
+ /** 给已有资产申请时间章。SDK 永远不传 provider 字段。 */
5223
+ issueTimestampForAsset(assetId, opts = {}) {
5224
+ return this.write(
5225
+ "POST",
5226
+ `/compliance/evidence/assets/${encodeURIComponent(assetId)}/timestamp`,
5227
+ null,
5228
+ writeCtx(opts)
5229
+ );
5230
+ }
5231
+ /** 读 — 时间章 token 详情。 */
5232
+ getTimestamp(id, signal) {
5233
+ return this.read(
5234
+ "GET",
5235
+ `/compliance/timestamps/${encodeURIComponent(id)}`,
5236
+ null,
5237
+ signal
5238
+ );
5239
+ }
5240
+ /**
5241
+ * 读 — 时间章分页列表(compliance gateway S1)。
5242
+ *
5243
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
5244
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
5245
+ */
5246
+ listTimestamps(req = {}, signal) {
5247
+ return this.read(
5248
+ "GET",
5249
+ `/compliance/timestamps/page${pageQuery(req, ["provider", "verificationStatus", "createTimeStart", "createTimeEnd"])}`,
5250
+ null,
5251
+ signal
5252
+ );
5253
+ }
5254
+ /** verify — 本地离线校验已申请的时间章。 */
5255
+ verifyTimestamp(req, opts = {}) {
5256
+ return this.write(
5257
+ "POST",
5258
+ "/compliance/timestamps/verify",
5259
+ req,
5260
+ writeCtx(opts)
5261
+ );
5262
+ }
5263
+ /**
5264
+ * 轮询到 VERIFIED 终态。
5265
+ * - VERIFIED → 返回 token;
5266
+ * - FAILED / LOCAL_VERIFY_FAILED → 抛 {@link CompliancePollError} kind='terminal_failure';
5267
+ * - UNKNOWN / RETRYING / PENDING → 继续轮询直到 timeout;
5268
+ * - timeout → 抛 {@link CompliancePollError} kind='timeout'。
5269
+ */
5270
+ async waitForTimestampVerified(id, opts = {}) {
5271
+ return this.poll(
5272
+ () => this.getTimestamp(id, opts.signal),
5273
+ (t) => classifyTimestamp(t.verificationStatus),
5274
+ opts
5275
+ );
5276
+ }
5277
+ // =========================================================================
5278
+ // TSA readonly views (read-only — compliance gateway S3 / gap-register U-7)
5279
+ // =========================================================================
5280
+ /**
5281
+ * 读 — 时间章授权机构(TSA)provider 列表(compliance gateway S3)。
5282
+ *
5283
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G3 为每个 TSA provider 返回
5284
+ * 一条 {@link TsaProvider}:名称、所处环境、当前是否可用。只读视图,不含
5285
+ * provider 端点 / 凭证 / 证书等内部接入材料。
5286
+ */
5287
+ listTsaProviders(signal) {
5288
+ return this.read(
5289
+ "GET",
5290
+ "/compliance/timestamps/providers",
5291
+ null,
5292
+ signal
5293
+ );
5294
+ }
5295
+ /**
5296
+ * 读 — 时间章统计视图(compliance gateway S3)。
5297
+ *
5298
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 {@link TsaStats}:时间章总数
5299
+ * + 按校验状态分桶的计数。只读聚合视图。
5300
+ */
5301
+ getTsaStats(signal) {
5302
+ return this.read(
5303
+ "GET",
5304
+ "/compliance/timestamps/stats",
5305
+ null,
5306
+ signal
5307
+ );
5308
+ }
5309
+ // =========================================================================
5310
+ // Evidence Package
5311
+ // =========================================================================
5312
+ /** 构建证据包(写)。 */
5313
+ buildEvidencePackage(assetId, timestampTokenId, opts = {}) {
5314
+ const tsParam = timestampTokenId == null ? "" : "?timestampTokenId=" + encodeURIComponent(timestampTokenId);
5315
+ return this.write(
5316
+ "POST",
5317
+ `/compliance/evidence/assets/${encodeURIComponent(assetId)}/packages${tsParam}`,
5318
+ null,
5319
+ writeCtx(opts)
5320
+ );
5321
+ }
5322
+ /**
5323
+ * 读 — 证据包分页列表(compliance gateway S1)。
5324
+ *
5325
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
5326
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
5327
+ */
5328
+ listEvidencePackages(req = {}, signal) {
5329
+ return this.read(
5330
+ "GET",
5331
+ `/compliance/evidence/packages/page${pageQuery(req, ["status", "createTimeStart", "createTimeEnd"])}`,
5332
+ null,
5333
+ signal
5334
+ );
5335
+ }
5336
+ // =========================================================================
5337
+ // Report
5338
+ // =========================================================================
5339
+ /** 创建证据报告(写)。 */
5340
+ createReport(req, opts = {}) {
5341
+ return this.write("POST", "/compliance/reports", req, writeCtx(opts));
5342
+ }
5343
+ /** 读 — 报告详情。 */
5344
+ getReport(id, signal) {
5345
+ return this.read(
5346
+ "GET",
5347
+ `/compliance/reports/${encodeURIComponent(id)}`,
5348
+ null,
5349
+ signal
5350
+ );
5351
+ }
5352
+ /**
5353
+ * 读 — 证据报告分页列表(compliance gateway S1)。
5354
+ *
5355
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
5356
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
5357
+ */
5358
+ listReports(req = {}, signal) {
5359
+ return this.read(
5360
+ "GET",
5361
+ `/compliance/reports/page${pageQuery(req, ["status", "createTimeStart", "createTimeEnd"])}`,
5362
+ null,
5363
+ signal
5364
+ );
5365
+ }
5366
+ /**
5367
+ * 发布报告(写,step-up 必须)。
5368
+ *
5369
+ * `@status gated` — step-up 闸门未闭合前服务端会一致返回
5370
+ * `COMPLIANCE_STEP_UP_REQUIRED`(数值码 1031000013)。SDK 不会自动重试、不伪成功;
5371
+ * 调用方需要引导用户重新做 OAuth introspection 或重新登录后再次调用本方法
5372
+ *(使用同一 idempotency-key)。方法状态分级见 `docs/compliance.md` Method Status。
5373
+ */
5374
+ publishReport(id, opts = {}) {
5375
+ return this.write(
5376
+ "POST",
5377
+ `/compliance/reports/${encodeURIComponent(id)}/publish`,
5378
+ null,
5379
+ writeCtx(opts)
5380
+ );
5381
+ }
5382
+ /**
5383
+ * 下载报告(读)。返回 {@link ReportDownload}:报告 hash + 资产 hash + 证据包 hash +
5384
+ * 时间章 serial/genTime,足以离线复核。
5385
+ * 不返回 bodyCanonicalJson / storage key / subject snapshot id。
5386
+ */
5387
+ downloadReport(id, signal) {
5388
+ return this.read(
5389
+ "GET",
5390
+ `/compliance/reports/${encodeURIComponent(id)}/download`,
5391
+ null,
5392
+ signal
5393
+ );
5394
+ }
5395
+ // =========================================================================
5396
+ // Signing Envelope
5397
+ // =========================================================================
5398
+ /** 创建 envelope(写)。返回 envelope id。 */
5399
+ createSigningEnvelope(req, opts = {}) {
5400
+ return this.write(
5401
+ "POST",
5402
+ "/compliance/signing-envelopes",
5403
+ req,
5404
+ writeCtx(opts)
5405
+ );
5406
+ }
5407
+ /** 读 — envelope 详情。租户由服务端从 compliance token principal 推导。 */
5408
+ getSigningEnvelope(envelopeId, signal) {
5409
+ return this.read(
5410
+ "GET",
5411
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}`,
5412
+ null,
5413
+ signal
5414
+ );
5415
+ }
5416
+ /**
5417
+ * 读 — 签署 envelope 分页列表(compliance gateway S1)。
5418
+ *
5419
+ * 走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;`createTimeStart` /
5420
+ * `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
5421
+ */
5422
+ listSigningEnvelopes(req = {}, signal) {
5423
+ return this.read(
5424
+ "GET",
5425
+ `/compliance/signing-envelopes/page${pageQuery(req, ["status", "createTimeStart", "createTimeEnd"])}`,
5426
+ null,
5427
+ signal
5428
+ );
5429
+ }
5430
+ /**
5431
+ * 正式签署(写,step-up 必须)。
5432
+ *
5433
+ * `@status gated` — 服务端闸门关闭时会一致返回 `ENVELOPE_GATE_CLOSED` (1031004004)。
5434
+ * SDK 不重试、不伪成功;调用方应该将该错误展示为"功能未开放"。
5435
+ */
5436
+ signEnvelope(envelopeId, req, opts = {}) {
5437
+ return this.write(
5438
+ "POST",
5439
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/sign`,
5440
+ req,
5441
+ writeCtx(opts)
5442
+ );
5443
+ }
5444
+ /**
5445
+ * 创建 H5 签署短链(写,step-up 必须)。
5446
+ *
5447
+ * `@status gated` — 同 {@link signEnvelope}:服务端闸门关闭时 SDK 不重试、不伪成功。
5448
+ */
5449
+ createH5SigningUrl(envelopeId, req, opts = {}) {
5450
+ return this.write(
5451
+ "POST",
5452
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/h5-url`,
5453
+ req,
5454
+ writeCtx(opts)
5455
+ );
5456
+ }
5457
+ /** 同步 provider 状态(写但只读对账,不创建新 provider 请求)。 */
5458
+ syncSigningEnvelopeStatus(envelopeId, opts = {}) {
5459
+ return this.write(
5460
+ "POST",
5461
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/sync-provider-status`,
5462
+ null,
5463
+ writeCtx(opts)
5464
+ );
5465
+ }
5466
+ /**
5467
+ * 读 — envelope 下挂的合同列表(compliance gateway S4)。
5468
+ *
5469
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G4 为每份挂在该 envelope 上的
5470
+ * 合同返回一条 {@link EnvelopeContractItem}:编号 / 标题 / MIME / 大小 / 哈希
5471
+ * 指纹 / 状态。返回普通数组(非 `PageResult`)。SDK-safe 视图——不含合同原文 /
5472
+ * storage key / provider raw payload。
5473
+ */
5474
+ listEnvelopeContracts(envelopeId, signal) {
5475
+ return this.read(
5476
+ "GET",
5477
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/contracts`,
5478
+ null,
5479
+ signal
5480
+ );
5481
+ }
5482
+ /**
5483
+ * 读 — envelope 关联的 provider 请求列表(compliance gateway S4)。
5484
+ *
5485
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G4 复用操作投影
5486
+ * {@link OperationPageItem}:描述每次 provider 请求本身的执行进度,与 envelope
5487
+ * 领域状态正交。返回普通数组(非 `PageResult`)。
5488
+ */
5489
+ listEnvelopeProviderRequests(envelopeId, signal) {
5490
+ return this.read(
5491
+ "GET",
5492
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/provider-requests`,
5493
+ null,
5494
+ signal
5495
+ );
5496
+ }
5497
+ /**
5498
+ * 作废 envelope(写,compliance gateway S4)。
5499
+ *
5500
+ * 走 compliance 写路径——发送前 `ensureToken` 一次、不自动重试、`401` 不刷新
5501
+ * 重放;支持 `Idempotency-Key` header(强烈建议调用方持久化幂等键,重试 / 恢复
5502
+ * 时复用,避免重复作废)。`req.reason` 为必填的作废原因,随 JSON body 提交。
5503
+ */
5504
+ voidEnvelope(envelopeId, req, opts = {}) {
5505
+ return this.write(
5506
+ "POST",
5507
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/void`,
5508
+ req,
5509
+ writeCtx(opts)
5510
+ );
5511
+ }
5512
+ // =========================================================================
5513
+ // Seal Approval
5514
+ // =========================================================================
5515
+ /**
5516
+ * 提交用印审批申请(写)。
5517
+ *
5518
+ * `@status production-ready` — 服务端以 `Idempotency-Key` + 业务请求指纹做重放保护:
5519
+ * 同 key + 同请求 → 返回原审批 id;同 key + 不同请求 → 拒绝复用幂等键。强烈建议调用方
5520
+ * 持久化 `idempotencyKey`,网络重试 / 任务恢复时复用,避免重复创建审批单。
5521
+ */
5522
+ submitSealApproval(req, opts = {}) {
5523
+ return this.write(
5524
+ "POST",
5525
+ "/compliance/seal-approvals",
5526
+ req,
5527
+ writeCtx(opts)
5528
+ );
5529
+ }
5530
+ /**
5531
+ * 审批通过用印申请(写,step-up 必须)。
5532
+ *
5533
+ * `@status gated` — step-up 未闭合前服务端会返回 `COMPLIANCE_STEP_UP_REQUIRED`。
5534
+ * SDK 不重试、不伪成功。方法状态分级见 `docs/compliance.md` Method Status。
5535
+ */
5536
+ approveSealApproval(id, query, opts = {}) {
5537
+ const q = new URLSearchParams();
5538
+ if (query.expiresAt) q.set("expiresAt", query.expiresAt);
5539
+ if (query.note) q.set("note", query.note);
5540
+ const qs = q.toString();
5541
+ return this.write(
5542
+ "POST",
5543
+ `/compliance/seal-approvals/${encodeURIComponent(id)}/approve${qs ? "?" + qs : ""}`,
5544
+ null,
5545
+ writeCtx(opts)
5546
+ );
5085
5547
  }
5086
- }
5087
- Client.prototype.getSkillSummary = async function(signal) {
5088
- const resp = await this.doJSON("GET", "/skills/summary", null, signal);
5089
- return resp.data;
5090
- };
5091
- Client.prototype.certifySkill = async function(skillID, signal) {
5092
- await this.doJSON(
5093
- "POST",
5094
- `/skill-store/${encodeURIComponent(skillID)}/certify`,
5095
- null,
5096
- signal
5097
- );
5098
- };
5099
- Client.prototype.getCertificationStatus = async function(skillID, signal) {
5100
- const resp = await this.doJSON(
5101
- "GET",
5102
- `/skill-store/${encodeURIComponent(skillID)}/certification`,
5103
- null,
5104
- signal
5105
- );
5106
- return resp.data;
5107
- };
5108
- Client.prototype.generateSkill = async function(req, signal) {
5109
- const resp = await this.doJSON(
5110
- "POST",
5111
- "/skill-generator/generate",
5112
- req,
5113
- signal
5114
- );
5115
- return resp.data;
5116
- };
5117
- Client.prototype.optimizeSkill = async function(req, signal) {
5118
- const resp = await this.doJSON(
5119
- "POST",
5120
- "/skill-generator/optimize",
5121
- req,
5122
- signal
5123
- );
5124
- return resp.data;
5125
- };
5126
- Client.prototype.validateSkill = async function(skillName, signal) {
5127
- await this.doJSON(
5128
- "POST",
5129
- "/skill-generator/validate",
5130
- { skillName },
5131
- signal
5132
- );
5133
- };
5134
-
5135
- // src/client/tools.ts
5136
- Client.prototype.listTools = async function(signal) {
5137
- const resp = await this.doJSON("GET", "/tools", null, signal);
5138
- return resp.data.skills;
5139
- };
5140
- Client.prototype.getTool = async function(toolID, signal) {
5141
- const resp = await this.doJSON(
5142
- "GET",
5143
- `/tools/${encodeURIComponent(toolID)}`,
5144
- null,
5145
- signal
5146
- );
5147
- return resp.data;
5148
- };
5149
-
5150
- // src/client/notifications.ts
5151
- Client.prototype.listNotifications = async function(page, pageSize, typeFilter, signal) {
5152
- let path = `/notifications?page=${page}&pageSize=${pageSize}`;
5153
- if (typeFilter) path += `&type=${encodeURIComponent(typeFilter)}`;
5154
- const resp = await this.doJSON("GET", path, null, signal);
5155
- return resp.data;
5156
- };
5157
- Client.prototype.getUnreadCount = async function(signal) {
5158
- const resp = await this.doJSON(
5159
- "GET",
5160
- "/notifications/unread-count",
5161
- null,
5162
- signal
5163
- );
5164
- return resp.data.unreadCount;
5165
- };
5166
- Client.prototype.markNotificationRead = async function(id, signal) {
5167
- await this.doJSON(
5168
- "PUT",
5169
- `/notifications/${encodeURIComponent(id)}/read`,
5170
- null,
5171
- signal
5172
- );
5173
- };
5174
- Client.prototype.markAllNotificationsRead = async function(signal) {
5175
- await this.doJSON("PUT", "/notifications/read-all", null, signal);
5176
- };
5177
- Client.prototype.deleteNotification = async function(id, signal) {
5178
- await this.doJSON(
5179
- "DELETE",
5180
- `/notifications/${encodeURIComponent(id)}`,
5181
- null,
5182
- signal
5183
- );
5184
- };
5185
- Client.prototype.registerDevice = async function(reg, signal) {
5186
- await this.doJSON("POST", "/devices/register", reg, signal);
5187
- };
5188
- Client.prototype.unregisterDevice = async function(token, signal) {
5189
- await this.doJSON(
5190
- "DELETE",
5191
- `/devices/${encodeURIComponent(token)}`,
5192
- null,
5193
- signal
5194
- );
5195
- };
5196
- Client.prototype.listNotificationPreferences = async function(signal) {
5197
- const resp = await this.doJSON(
5198
- "GET",
5199
- "/notification-preferences",
5200
- null,
5201
- signal
5202
- );
5203
- return resp.data;
5204
- };
5205
- Client.prototype.updateNotificationPreference = async function(typeCode, pref, signal) {
5206
- await this.doJSON(
5207
- "PUT",
5208
- `/notification-preferences/${encodeURIComponent(typeCode)}`,
5209
- pref,
5210
- signal
5211
- );
5212
- };
5213
-
5214
- // src/sanitize-bridge.ts
5215
- Client.prototype.setDefensiveSanitize = function(cfg) {
5216
- this.defensiveCfg = cfg;
5217
- };
5218
- Client.prototype.setAutoStripEphemeralHistory = function(on) {
5219
- this.autoStripEphemeral = on;
5220
- };
5221
- Client.prototype.applyRequestSanitizers = function(req) {
5222
- const cfg = this.defensiveCfg;
5223
- const strip = this.autoStripEphemeral;
5224
- if (cfg == null && !strip) return;
5225
- if (req.rawMessages != null) {
5226
- let msgs;
5227
- try {
5228
- msgs = normalizeRawMessages(req.rawMessages);
5229
- } catch (e) {
5230
- throw new Error(
5231
- `sanitize: normalize raw messages: ${e instanceof Error ? e.message : String(e)}`
5232
- );
5233
- }
5234
- if (cfg) {
5235
- msgs = sanitize(msgs, cfg);
5236
- }
5237
- if (strip) {
5238
- msgs = stripEphemeral(msgs);
5239
- }
5240
- req.rawMessages = msgs;
5241
- return;
5548
+ rejectSealApproval(id, query, opts = {}) {
5549
+ const q = new URLSearchParams();
5550
+ if (query.reason) q.set("reason", query.reason);
5551
+ const qs = q.toString();
5552
+ return this.write(
5553
+ "POST",
5554
+ `/compliance/seal-approvals/${encodeURIComponent(id)}/reject${qs ? "?" + qs : ""}`,
5555
+ null,
5556
+ writeCtx(opts)
5557
+ );
5558
+ }
5559
+ cancelSealApproval(id, query, opts = {}) {
5560
+ const q = new URLSearchParams();
5561
+ if (query.reason) q.set("reason", query.reason);
5562
+ const qs = q.toString();
5563
+ return this.write(
5564
+ "POST",
5565
+ `/compliance/seal-approvals/${encodeURIComponent(id)}/cancel${qs ? "?" + qs : ""}`,
5566
+ null,
5567
+ writeCtx(opts)
5568
+ );
5569
+ }
5570
+ listPendingSealApprovals(signal) {
5571
+ return this.read(
5572
+ "GET",
5573
+ "/compliance/seal-approvals/pending",
5574
+ null,
5575
+ signal
5576
+ );
5577
+ }
5578
+ getSealApproval(id, signal) {
5579
+ return this.read(
5580
+ "GET",
5581
+ `/compliance/seal-approvals/${encodeURIComponent(id)}`,
5582
+ null,
5583
+ signal
5584
+ );
5585
+ }
5586
+ /**
5587
+ * 读 — 用印审批分页列表(compliance gateway S1)。
5588
+ *
5589
+ * 与 {@link listPendingSealApprovals}(仅 pending、不分页)不同,本方法支持分页与
5590
+ * 状态 / 时间过滤。走 GET 读路径。返回 yudao `PageResult<T>`。所有过滤项可选;
5591
+ * `createTimeStart` / `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,
5592
+ * SDK 原样透传。
5593
+ */
5594
+ listSealApprovals(req = {}, signal) {
5595
+ return this.read(
5596
+ "GET",
5597
+ `/compliance/seal-approvals/page${pageQuery(req, ["status", "createTimeStart", "createTimeEnd"])}`,
5598
+ null,
5599
+ signal
5600
+ );
5601
+ }
5602
+ // =========================================================================
5603
+ // Seal Use (read-only — compliance gateway S6 / gap-register U-4)
5604
+ // =========================================================================
5605
+ /**
5606
+ * 读 — 用印执行记录分页列表(compliance gateway S6)。
5607
+ *
5608
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 yudao `PageResult<T>`
5609
+ * (`{ total, list }`)。一次用印执行(seal use)描述 envelope / contract /
5610
+ * seal / 审批联动后【真正调用 provider 落章】的那一笔记录,与 envelope
5611
+ * 领域状态正交。所有过滤项可选;`createTimeStart` / `createTimeEnd` 由调用方
5612
+ * 按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。
5613
+ *
5614
+ * 与后端复用同一只读 scope `CONTRACT_SIGNING_READ`
5615
+ *({@link ScopeComplianceContractSigningRead})——不引入新 scope。
5616
+ */
5617
+ listSealUses(req = {}, signal) {
5618
+ return this.read(
5619
+ "GET",
5620
+ `/compliance/seal-uses/page${pageQuery(req, ["sealId", "envelopeId", "usageStatus", "createTimeStart", "createTimeEnd"])}`,
5621
+ null,
5622
+ signal
5623
+ );
5624
+ }
5625
+ // =========================================================================
5626
+ // Provider Request (read-only)
5627
+ // =========================================================================
5628
+ getProviderRequest(id, signal) {
5629
+ return this.read(
5630
+ "GET",
5631
+ `/compliance/provider-requests/${encodeURIComponent(id)}`,
5632
+ null,
5633
+ signal
5634
+ );
5635
+ }
5636
+ /**
5637
+ * 轮询 provider request 到 SUCCESS / FAILED 终态。
5638
+ * - SUCCESS / FAILED → 返回最后视图;
5639
+ * - UNKNOWN / RETRYING / PENDING → 继续轮询;
5640
+ * - timeout → 抛 {@link CompliancePollError} kind='timeout',不自动重发原 provider 请求。
5641
+ *
5642
+ * SUCCESS 不代表 billing 已 commit;调用方仍需通过业务侧 envelope / asset 终态判断。
5643
+ */
5644
+ async waitForProviderRequestTerminal(id, opts = {}) {
5645
+ return this.poll(
5646
+ () => this.getProviderRequest(id, opts.signal),
5647
+ (v) => classifyProviderStatus(v.status),
5648
+ opts
5649
+ );
5650
+ }
5651
+ // =========================================================================
5652
+ // Capabilities (read-only — compliance gateway S2 / gap-register U-6)
5653
+ // =========================================================================
5654
+ /**
5655
+ * 读 — compliance 能力闸门列表(compliance gateway S2)。
5656
+ *
5657
+ * 走 GET 读路径(允许 401 单次刷新重放)。后端 G2 为每个高风险 / 收费动作
5658
+ * (`signEnvelope` / `createH5SigningUrl` / `publishReport` /
5659
+ * `approveSealApproval` / `executeSealUse` / `createSeal`)返回一条
5660
+ * {@link ComplianceCapability}:是否可执行、所处状态、所需 scope / step-up。
5661
+ *
5662
+ * 调用方在高风险动作执行【前】查询本结果做门控;拿不到能力时必须 fail-closed
5663
+ *(按 `executable=false` 处理)。
5664
+ */
5665
+ getCapabilities(signal) {
5666
+ return this.read(
5667
+ "GET",
5668
+ "/compliance/capabilities",
5669
+ null,
5670
+ signal
5671
+ );
5672
+ }
5673
+ /**
5674
+ * 读 — 单个动作的能力闸门视图(便捷方法)。
5675
+ *
5676
+ * 拉取完整 {@link getCapabilities} 列表并返回 `action` 匹配的那一条,无匹配时
5677
+ * 返回 `undefined`。**每次调用产生一次网络请求**——需要门控多个动作时应改用
5678
+ * {@link getCapabilities} 一次性取回再本地查表,避免重复请求。
5679
+ *
5680
+ * {@link getCapabilities} 一致走 GET 读路径(允许 401 单次刷新重放)。
5681
+ */
5682
+ async getFeatureGate(action, signal) {
5683
+ const caps = await this.getCapabilities(signal);
5684
+ return caps.find((c) => c.action === action);
5685
+ }
5686
+ // =========================================================================
5687
+ // Operation projection (read-only compliance gateway S2 / gap-register U-5)
5688
+ // =========================================================================
5689
+ /**
5690
+ * — compliance 操作投影分页列表(compliance gateway S2)。
5691
+ *
5692
+ * GET 读路径。返回 yudao `PageResult<T>`(`{ total, list }`)。所有过滤项
5693
+ * 可选;`createTimeStart` / `createTimeEnd` 由调用方按 `yyyy-MM-dd HH:mm:ss`
5694
+ * 提供,SDK 原样透传,不做格式校验或时区转换。
5695
+ *
5696
+ * 操作投影描述【一次操作】本身的执行进度,与履约对象的领域状态正交。
5697
+ */
5698
+ listOperations(req = {}, signal) {
5699
+ return this.read(
5700
+ "GET",
5701
+ `/compliance/operations/page${pageQuery(req, ["status", "createTimeStart", "createTimeEnd"])}`,
5702
+ null,
5703
+ signal
5704
+ );
5242
5705
  }
5243
- if (cfg && (cfg.maxMessagesTurns ?? 0) > 0 && (req.messages?.length ?? 0) > cfg.maxMessagesTurns) {
5244
- throw ErrHistoryTooDeep;
5706
+ /**
5707
+ * 读 — compliance 操作投影详情(compliance gateway S2)。
5708
+ *
5709
+ * `id` 为数值行主键(非 `operationId` 幂等键)。走 GET 读路径(允许 401 单次
5710
+ * 刷新重放)。
5711
+ */
5712
+ getOperation(id, signal) {
5713
+ return this.read(
5714
+ "GET",
5715
+ `/compliance/operations/${encodeURIComponent(id)}`,
5716
+ null,
5717
+ signal
5718
+ );
5245
5719
  }
5246
- };
5247
- function normalizeRawMessages(rm) {
5248
- if (Array.isArray(rm)) return rm;
5249
- let s;
5250
- try {
5251
- s = JSON.parse(JSON.stringify(rm));
5252
- } catch (e) {
5253
- throw new Error(`raw messages: ${e instanceof Error ? e.message : String(e)}`);
5720
+ // =========================================================================
5721
+ // Contract Template (compliance gateway S5 — gap-register U-2)
5722
+ // =========================================================================
5723
+ /**
5724
+ * 创建合同模板(写)。
5725
+ *
5726
+ * compliance 写路径——发送前 `ensureToken` 一次、不自动重试、`401` 不刷新
5727
+ * 重放;支持 `Idempotency-Key` header(强烈建议调用方持久化幂等键,重试 / 恢复
5728
+ * 时复用,避免重复创建模板)。模板创建后初始状态为 `DRAFT`。
5729
+ */
5730
+ createContractTemplate(req, opts = {}) {
5731
+ return this.write(
5732
+ "POST",
5733
+ "/compliance/contract-templates",
5734
+ req,
5735
+ writeCtx(opts)
5736
+ );
5254
5737
  }
5255
- if (!Array.isArray(s)) {
5256
- throw new Error("raw messages must be a JSON array");
5738
+ /**
5739
+ * 更新合同模板(写,仅 DRAFT 状态)。
5740
+ *
5741
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。所有字段
5742
+ * 可选,缺省字段视为不修改。服务端在 PUBLISHED / ARCHIVED 状态下会拒绝更新。
5743
+ */
5744
+ updateContractTemplate(id, req, opts = {}) {
5745
+ return this.write(
5746
+ "POST",
5747
+ `/compliance/contract-templates/${encodeURIComponent(id)}`,
5748
+ req,
5749
+ writeCtx(opts)
5750
+ );
5257
5751
  }
5258
- return s;
5259
- }
5260
-
5261
- // src/ws.ts
5262
- Client.prototype.connect = async function(cfg, signal) {
5263
- const noop = () => {
5264
- };
5265
- const filledCfg = {
5266
- onEvent: cfg.onEvent ?? noop,
5267
- onConnect: cfg.onConnect ?? noop,
5268
- onDisconnect: cfg.onDisconnect ?? noop,
5269
- topics: cfg.topics ?? [],
5270
- reconnectMinMs: cfg.reconnectMinMs ?? 2e3,
5271
- reconnectMaxMs: cfg.reconnectMaxMs ?? 6e4,
5272
- autoReconnect: cfg.autoReconnect ?? true
5273
- };
5274
- let resolveDone;
5275
- const done = new Promise((r) => {
5276
- resolveDone = r;
5277
- });
5278
- const abort = new AbortController();
5279
- if (signal) {
5280
- if (signal.aborted) abort.abort();
5281
- else signal.addEventListener("abort", () => abort.abort());
5752
+ /**
5753
+ * 删除合同模板(写,仅 DRAFT 状态)。
5754
+ *
5755
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。服务端
5756
+ * PUBLISHED / ARCHIVED 状态下会拒绝删除——已发布的模板应改走 `archive`。
5757
+ */
5758
+ deleteContractTemplate(id, opts = {}) {
5759
+ return this.write(
5760
+ "POST",
5761
+ `/compliance/contract-templates/${encodeURIComponent(id)}/delete`,
5762
+ null,
5763
+ writeCtx(opts)
5764
+ );
5282
5765
  }
5283
- const ws = {
5284
- conn: null,
5285
- cfg: filledCfg,
5286
- abort,
5287
- done,
5288
- doneResolve: resolveDone,
5289
- connected: false
5290
- };
5291
- await wsConnectOnce(this, ws);
5292
- this.ws = ws;
5293
- void wsLoop(this, ws);
5294
- };
5295
- Client.prototype.disconnect = async function() {
5296
- const ws = this.ws;
5297
- this.ws = null;
5298
- if (!ws) return;
5299
- ws.abort.abort();
5300
- ws.connected = false;
5301
- if (ws.conn) {
5302
- try {
5303
- ws.conn.close(1e3, "");
5304
- } catch {
5305
- }
5766
+ /** 合同模板详情。 */
5767
+ getContractTemplate(id, signal) {
5768
+ return this.read(
5769
+ "GET",
5770
+ `/compliance/contract-templates/${encodeURIComponent(id)}`,
5771
+ null,
5772
+ signal
5773
+ );
5306
5774
  }
5307
- await Promise.race([
5308
- ws.done,
5309
- new Promise((resolve) => setTimeout(resolve, 5e3))
5310
- ]);
5311
- };
5312
- Client.prototype.isConnected = function() {
5313
- const ws = this.ws;
5314
- if (!ws) return false;
5315
- return ws.connected;
5316
- };
5317
- function wsURL(c) {
5318
- const base = c.apiURL("/ws");
5319
- return base.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://");
5320
- }
5321
- function getWebSocketCtor() {
5322
- const WSCtor = globalThis.WebSocket;
5323
- if (!WSCtor) {
5324
- throw new Error(
5325
- 'WebSocket not available \u2014 on Node \u226421 set globalThis.WebSocket = require("ws") before connect'
5775
+ /**
5776
+ * 读 — 合同模板分页列表(compliance gateway S5)。
5777
+ *
5778
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 yudao `PageResult<T>`
5779
+ * (`{ total, list }`)。所有过滤项可选;`createTimeStart` / `createTimeEnd`
5780
+ * 由调用方按 `yyyy-MM-dd HH:mm:ss` 提供,SDK 原样透传。列表项视图
5781
+ * {@link ContractTemplatePageItem} 不含 `fields`——字段叠加只在详情 / 版本
5782
+ * 快照里返回。
5783
+ */
5784
+ listContractTemplates(req = {}, signal) {
5785
+ return this.read(
5786
+ "GET",
5787
+ `/compliance/contract-templates/page${pageQuery(req, ["status", "createTimeStart", "createTimeEnd"])}`,
5788
+ null,
5789
+ signal
5326
5790
  );
5327
5791
  }
5328
- return WSCtor;
5329
- }
5330
- async function wsConnectOnce(c, ws) {
5331
- const token = await c.ensureToken(ws.abort.signal);
5332
- const url = wsURL(c);
5333
- const WSCtor = getWebSocketCtor();
5334
- const u = new URL(url);
5335
- u.searchParams.set("token", token);
5336
- let conn;
5337
- try {
5338
- conn = new WSCtor(u.toString());
5339
- } catch (e) {
5340
- throw new Error(`dial: ${e instanceof Error ? e.message : String(e)}`);
5792
+ /**
5793
+ * 上传合同模板 PDF(写)。
5794
+ *
5795
+ * compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。请求体
5796
+ * `{ pdfBase64 }`;SDK 不在客户端做 PDF 解析 / 几何校验,原样透传给后端。
5797
+ * 返回上传后的最新模板视图(含 `pdfHash` / `pdfPageCount`)。
5798
+ */
5799
+ uploadContractTemplatePdf(id, req, opts = {}) {
5800
+ return this.write(
5801
+ "POST",
5802
+ `/compliance/contract-templates/${encodeURIComponent(id)}/pdf`,
5803
+ req,
5804
+ writeCtx(opts)
5805
+ );
5341
5806
  }
5342
- await new Promise((resolve, reject) => {
5343
- let opened = false;
5344
- const handshakeTimer = setTimeout(() => {
5345
- if (!opened) {
5346
- try {
5347
- conn.close();
5348
- } catch {
5349
- }
5350
- reject(new Error("dial: handshake timeout"));
5351
- }
5352
- }, 3e4);
5353
- conn.addEventListener("open", () => {
5354
- opened = true;
5355
- });
5356
- conn.addEventListener("error", (e) => {
5357
- clearTimeout(handshakeTimer);
5358
- reject(new Error(`dial: ${e.message ?? "connection error"}`));
5359
- });
5360
- conn.addEventListener("message", (e) => {
5361
- try {
5362
- const msg = e.data;
5363
- const welcome = JSON.parse(msg);
5364
- if (welcome.type !== "welcome") {
5365
- clearTimeout(handshakeTimer);
5366
- try {
5367
- conn.close();
5368
- } catch {
5369
- }
5370
- reject(new Error(`unexpected first message: ${welcome.type}`));
5371
- return;
5372
- }
5373
- clearTimeout(handshakeTimer);
5374
- ws.conn = conn;
5375
- ws.connected = true;
5376
- if (ws.cfg.topics.length > 0) {
5377
- try {
5378
- conn.send(
5379
- JSON.stringify({
5380
- type: "subscribe",
5381
- topics: ws.cfg.topics
5382
- })
5383
- );
5384
- } catch (sendErr) {
5385
- ws.conn = null;
5386
- ws.connected = false;
5387
- try {
5388
- conn.close();
5389
- } catch {
5390
- }
5391
- reject(new Error(`send subscribe: ${sendErr instanceof Error ? sendErr.message : String(sendErr)}`));
5392
- return;
5393
- }
5394
- }
5395
- ws.cfg.onConnect();
5396
- console.log(`[acosmi-sdk] websocket connected, connId=${welcome.connId ?? ""}`);
5397
- resolve();
5398
- } catch (parseErr) {
5399
- clearTimeout(handshakeTimer);
5400
- try {
5401
- conn.close();
5402
- } catch {
5403
- }
5404
- reject(new Error(`parse welcome: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`));
5405
- }
5406
- }, { once: true });
5407
- });
5408
- }
5409
- async function wsLoop(c, ws) {
5410
- try {
5411
- while (true) {
5412
- await wsReadLoop(ws);
5413
- if (ws.abort.signal.aborted) return;
5414
- if (ws.conn) {
5415
- try {
5416
- ws.conn.close();
5417
- } catch {
5418
- }
5419
- ws.conn = null;
5420
- }
5421
- ws.connected = false;
5422
- if (!ws.cfg.autoReconnect) return;
5423
- let delay = ws.cfg.reconnectMinMs;
5424
- while (true) {
5425
- if (ws.abort.signal.aborted) return;
5426
- await sleepWithSignal2(delay, ws.abort.signal).catch(() => {
5427
- });
5428
- if (ws.abort.signal.aborted) return;
5429
- console.log(`[acosmi-sdk] websocket reconnecting (delay=${delay}ms)...`);
5430
- try {
5431
- await wsConnectOnce(c, ws);
5432
- break;
5433
- } catch (err) {
5434
- console.log(`[acosmi-sdk] websocket reconnect failed: ${err instanceof Error ? err.message : String(err)}`);
5435
- delay = Math.min(delay * 2, ws.cfg.reconnectMaxMs);
5436
- }
5437
- }
5807
+ /**
5808
+ * 发布合同模板(写)。DRAFT PUBLISHED,落版本快照。
5809
+ *
5810
+ * compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。
5811
+ * publish 后 `currentVersion` 递增,`fields` 与 `pdfHash` 同步固化进版本表。
5812
+ */
5813
+ publishContractTemplate(id, opts = {}) {
5814
+ return this.write(
5815
+ "POST",
5816
+ `/compliance/contract-templates/${encodeURIComponent(id)}/publish`,
5817
+ null,
5818
+ writeCtx(opts)
5819
+ );
5820
+ }
5821
+ /**
5822
+ * 归档合同模板(写)。PUBLISHED → ARCHIVED。
5823
+ *
5824
+ * 走 compliance 写路径——`Idempotency-Key`、不重试、`401` 不刷新重放。
5825
+ * 已归档模板只读,不再允许 publish / 编辑 / 删除。
5826
+ */
5827
+ archiveContractTemplate(id, opts = {}) {
5828
+ return this.write(
5829
+ "POST",
5830
+ `/compliance/contract-templates/${encodeURIComponent(id)}/archive`,
5831
+ null,
5832
+ writeCtx(opts)
5833
+ );
5834
+ }
5835
+ /**
5836
+ * 读 — 合同模板版本快照列表。
5837
+ *
5838
+ * 走 GET 读路径(允许 401 单次刷新重放)。返回 {@link ContractTemplateVersion}
5839
+ * 普通数组(非 `PageResult`)——每次 publish 落一个不可变快照,记录当时的
5840
+ * `name` / `pdfHash` / `fields` / `statusAtSnapshot`,是离线复核 / 版本对账
5841
+ * 的依据。
5842
+ */
5843
+ listContractTemplateVersions(id, signal) {
5844
+ return this.read(
5845
+ "GET",
5846
+ `/compliance/contract-templates/${encodeURIComponent(id)}/versions`,
5847
+ null,
5848
+ signal
5849
+ );
5850
+ }
5851
+ // =========================================================================
5852
+ // Error classification (re-export for convenience)
5853
+ // =========================================================================
5854
+ classifyError(err) {
5855
+ if (!isBusinessErrorLike(err)) return null;
5856
+ if (!isComplianceBusinessError(err)) return null;
5857
+ return classifyComplianceError(err);
5858
+ }
5859
+ // =========================================================================
5860
+ // Internal helpers
5861
+ // =========================================================================
5862
+ /**
5863
+ * 读路径:GET / 公开 verify。允许 401 单次刷新后重放(GET 幂等安全)。
5864
+ * 与 client.doJSONFullInternal 行为一致;不复用其代码因为 base URL 不同。
5865
+ */
5866
+ async read(method, path, body, signal, extraHeaders = {}) {
5867
+ return this.executeJson(method, path, body, signal, {
5868
+ retryOn401: true,
5869
+ extraHeaders
5870
+ });
5871
+ }
5872
+ /**
5873
+ * 公开读路径:public verify。
5874
+ *
5875
+ * {@link read} 的区别 — public 端点不应要求认证:
5876
+ * - token 时匿名请求:ensureToken 抛 `not authorized` 会被吞掉,继续匿名发送。
5877
+ * - 有 token 时附带 `Authorization`,保留后端审计上下文。
5878
+ * - 不做 401 refresh replay:401 直接抛 HTTPError,不触发 `forceRefresh`。
5879
+ *
5880
+ * URL 仍走 `client.complianceURL(path)`,不复用 `/api/v4`;底层复用
5881
+ * `client.doRequest`,不新增 fetch/axios 直连。
5882
+ */
5883
+ async publicRead(method, path, signal) {
5884
+ let token = "";
5885
+ try {
5886
+ token = await this.client.ensureToken(signal);
5887
+ } catch {
5438
5888
  }
5439
- } finally {
5440
- ws.doneResolve();
5889
+ const url = this.client.complianceURL(path);
5890
+ const headers = { Accept: "application/json" };
5891
+ if (token) headers.Authorization = `Bearer ${token}`;
5892
+ const resp = await this.client.doRequest({ method, url, headers }, signal);
5893
+ if (resp.status < 200 || resp.status >= 300) {
5894
+ const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
5895
+ throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
5896
+ }
5897
+ const text = await resp.text();
5898
+ if (!text) return void 0;
5899
+ const parsed = JSON.parse(text);
5900
+ const bizErr = apiResponseBusinessError(parsed);
5901
+ if (bizErr) throw bizErr;
5902
+ return parsed.data;
5441
5903
  }
5442
- }
5443
- async function wsReadLoop(ws) {
5444
- const conn = ws.conn;
5445
- if (!conn) return;
5446
- return new Promise((resolve) => {
5447
- const handleMessage = (e) => {
5448
- try {
5449
- const data = e.data;
5450
- const event = JSON.parse(data);
5451
- try {
5452
- ws.cfg.onEvent(event);
5453
- } catch {
5454
- }
5455
- } catch {
5456
- }
5904
+ /**
5905
+ * 写路径:POST。
5906
+ * - 发送前 ensureToken 一次确保 token fresh。
5907
+ * - 不自动 401 重放:401 → 抛 HTTPError;调用方必须自己刷新 token 后用同一
5908
+ * idempotency-key 重新发起,避免 provider 侧重复请求。
5909
+ * - 不走 doRequestWithRetry:写操作不允许 5xx/timeout 自动重试。
5910
+ */
5911
+ async write(method, path, body, ctx) {
5912
+ const headers = { ...ctx.extraHeaders ?? {} };
5913
+ if (ctx.idempotencyKey) headers["Idempotency-Key"] = ctx.idempotencyKey;
5914
+ return this.executeJson(method, path, body, ctx.signal, {
5915
+ retryOn401: false,
5916
+ extraHeaders: headers
5917
+ });
5918
+ }
5919
+ async executeJson(method, path, body, signal, opts, retried = false) {
5920
+ const token = await this.client.ensureToken(signal);
5921
+ const url = this.client.complianceURL(path);
5922
+ const headers = {
5923
+ Authorization: `Bearer ${token}`,
5924
+ Accept: "application/json",
5925
+ ...opts.extraHeaders
5457
5926
  };
5458
- const handleClose = (e) => {
5459
- conn.removeEventListener("message", handleMessage);
5460
- conn.removeEventListener("close", handleClose);
5461
- conn.removeEventListener("error", handleError);
5927
+ let bodyStr;
5928
+ if (body != null) {
5929
+ bodyStr = typeof body === "string" ? body : JSON.stringify(body);
5930
+ headers["Content-Type"] = "application/json";
5931
+ }
5932
+ const resp = await this.client.doRequest({ method, url, headers, body: bodyStr }, signal);
5933
+ if (resp.status === 401 && opts.retryOn401 && !retried) {
5462
5934
  try {
5463
- ws.cfg.onDisconnect(new Error(`closed: code=${e.code} reason=${e.reason}`));
5935
+ await resp.body?.cancel();
5464
5936
  } catch {
5465
5937
  }
5466
- resolve();
5938
+ await this.client.forceRefresh(signal);
5939
+ return this.executeJson(method, path, body, signal, opts, true);
5940
+ }
5941
+ if (resp.status < 200 || resp.status >= 300) {
5942
+ const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
5943
+ throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
5944
+ }
5945
+ const text = await resp.text();
5946
+ if (!text) return void 0;
5947
+ const parsed = JSON.parse(text);
5948
+ const bizErr = apiResponseBusinessError(parsed);
5949
+ if (bizErr) throw bizErr;
5950
+ return parsed.data;
5951
+ }
5952
+ async poll(fetcher, classify, opts) {
5953
+ const cfg = {
5954
+ timeoutMs: opts.timeoutMs ?? DEFAULT_POLL.timeoutMs,
5955
+ initialIntervalMs: opts.initialIntervalMs ?? DEFAULT_POLL.initialIntervalMs,
5956
+ maxIntervalMs: opts.maxIntervalMs ?? DEFAULT_POLL.maxIntervalMs,
5957
+ multiplier: opts.multiplier ?? DEFAULT_POLL.multiplier
5467
5958
  };
5468
- const handleError = (e) => {
5469
- conn.removeEventListener("message", handleMessage);
5470
- conn.removeEventListener("close", handleClose);
5471
- conn.removeEventListener("error", handleError);
5472
- try {
5473
- ws.cfg.onDisconnect(e);
5474
- } catch {
5959
+ const deadline = Date.now() + cfg.timeoutMs;
5960
+ let interval = cfg.initialIntervalMs;
5961
+ let lastValue;
5962
+ while (Date.now() < deadline) {
5963
+ if (opts.signal?.aborted) {
5964
+ throw new CompliancePollError("compliance poll aborted", "unknown");
5475
5965
  }
5476
- resolve();
5477
- };
5478
- conn.addEventListener("message", handleMessage);
5479
- conn.addEventListener("close", handleClose);
5480
- conn.addEventListener("error", handleError);
5481
- if (ws.abort.signal.aborted) {
5482
- try {
5483
- conn.close();
5484
- } catch {
5966
+ lastValue = await fetcher();
5967
+ const decision = classify(lastValue);
5968
+ if (decision === "done") return lastValue;
5969
+ if (decision === "failed") {
5970
+ throw new CompliancePollError(
5971
+ "compliance poll observed terminal failure",
5972
+ "terminal_failure"
5973
+ );
5485
5974
  }
5486
- } else {
5487
- ws.abort.signal.addEventListener(
5488
- "abort",
5489
- () => {
5490
- try {
5491
- conn.close();
5492
- } catch {
5493
- }
5494
- },
5495
- { once: true }
5496
- );
5975
+ const sleepMs = Math.min(interval, deadline - Date.now());
5976
+ if (sleepMs <= 0) break;
5977
+ await sleep2(sleepMs, opts.signal);
5978
+ interval = Math.min(Math.floor(interval * cfg.multiplier), cfg.maxIntervalMs);
5497
5979
  }
5498
- });
5980
+ throw new CompliancePollError("compliance poll timed out", "timeout");
5981
+ }
5982
+ };
5983
+ function classifyTimestamp(status) {
5984
+ switch (status) {
5985
+ case "VERIFIED":
5986
+ return "done";
5987
+ case "FAILED":
5988
+ case "LOCAL_VERIFY_FAILED":
5989
+ return "failed";
5990
+ case "PENDING":
5991
+ case "UNKNOWN":
5992
+ case "RETRYING":
5993
+ default:
5994
+ return "continue";
5995
+ }
5499
5996
  }
5500
- async function sleepWithSignal2(ms, signal) {
5501
- if (ms <= 0) return;
5502
- if (signal.aborted) throw new Error("aborted");
5997
+ function classifyProviderStatus(status) {
5998
+ switch (status) {
5999
+ case "SUCCESS":
6000
+ return "done";
6001
+ case "FAILED":
6002
+ return "failed";
6003
+ case "PENDING":
6004
+ case "UNKNOWN":
6005
+ case "RETRYING":
6006
+ default:
6007
+ return "continue";
6008
+ }
6009
+ }
6010
+ function pageQuery(req, filterKeys) {
6011
+ const q = new URLSearchParams();
6012
+ const append = (key, value) => {
6013
+ if (value == null) return;
6014
+ const s = typeof value === "string" ? value : String(value);
6015
+ if (s === "") return;
6016
+ q.set(key, s);
6017
+ };
6018
+ append("pageNo", req.pageNo);
6019
+ append("pageSize", req.pageSize);
6020
+ append("sortBy", req.sortBy);
6021
+ append("sortDirection", req.sortDirection);
6022
+ for (const key of filterKeys) {
6023
+ append(String(key), req[key]);
6024
+ }
6025
+ const qs = q.toString();
6026
+ return qs ? "?" + qs : "";
6027
+ }
6028
+ function writeCtx(opts, extraHeaders = {}) {
6029
+ return {
6030
+ idempotencyKey: opts.idempotencyKey,
6031
+ signal: opts.signal,
6032
+ extraHeaders
6033
+ };
6034
+ }
6035
+ function isBusinessErrorLike(err) {
6036
+ if (err == null || typeof err !== "object") return false;
6037
+ return typeof err.code === "number";
6038
+ }
6039
+ function sleep2(ms, signal) {
5503
6040
  return new Promise((resolve, reject) => {
5504
- const t = setTimeout(() => {
5505
- signal.removeEventListener("abort", abortHandler);
6041
+ if (signal?.aborted) {
6042
+ reject(new CompliancePollError("compliance poll aborted", "unknown"));
6043
+ return;
6044
+ }
6045
+ const timer = setTimeout(() => {
6046
+ signal?.removeEventListener("abort", onAbort);
5506
6047
  resolve();
5507
6048
  }, ms);
5508
- const abortHandler = () => {
5509
- clearTimeout(t);
5510
- signal.removeEventListener("abort", abortHandler);
5511
- reject(new Error("aborted"));
6049
+ const onAbort = () => {
6050
+ clearTimeout(timer);
6051
+ signal?.removeEventListener("abort", onAbort);
6052
+ reject(new CompliancePollError("compliance poll aborted", "unknown"));
5512
6053
  };
5513
- signal.addEventListener("abort", abortHandler);
6054
+ signal?.addEventListener("abort", onAbort, { once: true });
5514
6055
  });
5515
6056
  }
5516
6057
 
5517
- // src/bug-report.ts
6058
+ // src/support/bug-report.ts
5518
6059
  Client.prototype.submitBugReport = async function(reportData, signal) {
5519
6060
  if (reportData == null) {
5520
6061
  throw new Error("acosmi: reportData required");
@@ -5592,12 +6133,16 @@ exports.FilterStatusFallbackTkdistSkew = FilterStatusFallbackTkdistSkew;
5592
6133
  exports.FilterStatusInternalBypass = FilterStatusInternalBypass;
5593
6134
  exports.FilterStatusOK = FilterStatusOK;
5594
6135
  exports.FilterStatusUnknown = FilterStatusUnknown;
6136
+ exports.IdempotencyKeyHeader = IdempotencyKeyHeader;
5595
6137
  exports.InMemoryTokenStore = InMemoryTokenStore;
5596
6138
  exports.LocalStorageTokenStore = LocalStorageTokenStore;
6139
+ exports.RETRY_ADVICE_REASONS = RETRY_ADVICE_REASONS;
5597
6140
  exports.ScopeAI = ScopeAI;
5598
6141
  exports.ScopeAccount = ScopeAccount;
5599
6142
  exports.ScopeComplianceContractSigningRead = ScopeComplianceContractSigningRead;
5600
6143
  exports.ScopeComplianceContractSigningWrite = ScopeComplianceContractSigningWrite;
6144
+ exports.ScopeComplianceContractTemplateRead = ScopeComplianceContractTemplateRead;
6145
+ exports.ScopeComplianceContractTemplateWrite = ScopeComplianceContractTemplateWrite;
5601
6146
  exports.ScopeComplianceEvidenceRead = ScopeComplianceEvidenceRead;
5602
6147
  exports.ScopeComplianceEvidenceWrite = ScopeComplianceEvidenceWrite;
5603
6148
  exports.ScopeComplianceReportsPublish = ScopeComplianceReportsPublish;
@@ -5633,6 +6178,7 @@ exports.buildBetas = buildBetas;
5633
6178
  exports.classifyComplianceError = classifyComplianceError;
5634
6179
  exports.commerceScopes = commerceScopes;
5635
6180
  exports.completeWebAuthorizationRequest = completeWebAuthorizationRequest;
6181
+ exports.complianceErrorToRetryAdvice = complianceErrorToRetryAdvice;
5636
6182
  exports.complianceScopes = complianceScopes;
5637
6183
  exports.computeBackoff = computeBackoff;
5638
6184
  exports.createWebAuthorizationRequest = createWebAuthorizationRequest;
@@ -5667,6 +6213,8 @@ exports.parseSourcesEvent = parseSourcesEvent;
5667
6213
  exports.refreshToken = refreshToken;
5668
6214
  exports.register = register;
5669
6215
  exports.registerWebOAuthClient = registerWebOAuthClient;
6216
+ exports.retryReasonForComplianceKey = retryReasonForComplianceKey;
6217
+ exports.retryReasonForOAuthError = retryReasonForOAuthError;
5670
6218
  exports.revokeToken = revokeToken;
5671
6219
  exports.sanitize = sanitize_exports;
5672
6220
  exports.skillScopes = skillScopes;