@acosmi/sdk-ts 1.2.0 → 1.3.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.
@@ -1430,9 +1430,37 @@ var ScopeToolsExecute = "tools:execute";
1430
1430
  var ScopeWallet = "wallet";
1431
1431
  var ScopeWalletReadonly = "wallet:readonly";
1432
1432
  var ScopeProfile = "profile";
1433
+ var ScopeComplianceEvidenceRead = "compliance:evidence:read";
1434
+ var ScopeComplianceEvidenceWrite = "compliance:evidence:write";
1435
+ var ScopeComplianceTimestampIssue = "compliance:timestamp:issue";
1436
+ var ScopeComplianceTimestampVerify = "compliance:timestamp:verify";
1437
+ var ScopeComplianceContractSigningRead = "compliance:contract_signing:read";
1438
+ var ScopeComplianceContractSigningWrite = "compliance:contract_signing:write";
1439
+ var ScopeComplianceSealManage = "compliance:seal:manage";
1440
+ var ScopeComplianceSealApprovalRequest = "compliance:seal_approval:request";
1441
+ var ScopeComplianceSealApprovalApprove = "compliance:seal_approval:approve";
1442
+ var ScopeComplianceSealUseExecute = "compliance:seal_use:execute";
1443
+ var ScopeComplianceReportsRead = "compliance:reports:read";
1444
+ var ScopeComplianceReportsPublish = "compliance:reports:publish";
1433
1445
  function allScopes() {
1434
1446
  return [ScopeAI, ScopeSkills, ScopeAccount];
1435
1447
  }
1448
+ function complianceScopes() {
1449
+ return [
1450
+ ScopeComplianceEvidenceRead,
1451
+ ScopeComplianceEvidenceWrite,
1452
+ ScopeComplianceTimestampIssue,
1453
+ ScopeComplianceTimestampVerify,
1454
+ ScopeComplianceContractSigningRead,
1455
+ ScopeComplianceContractSigningWrite,
1456
+ ScopeComplianceSealManage,
1457
+ ScopeComplianceSealApprovalRequest,
1458
+ ScopeComplianceSealApprovalApprove,
1459
+ ScopeComplianceSealUseExecute,
1460
+ ScopeComplianceReportsRead,
1461
+ ScopeComplianceReportsPublish
1462
+ ];
1463
+ }
1436
1464
  function modelScopes() {
1437
1465
  return [ScopeAI];
1438
1466
  }
@@ -1443,6 +1471,171 @@ function skillScopes() {
1443
1471
  return [ScopeSkills];
1444
1472
  }
1445
1473
 
1474
+ // src/compliance-status.ts
1475
+ var ErrComplianceStepUpRequired = "COMPLIANCE_STEP_UP_REQUIRED";
1476
+ var ErrEnvelopeGateClosed = "ENVELOPE_GATE_CLOSED";
1477
+ var ErrProviderNotConfigured = "PROVIDER_NOT_CONFIGURED";
1478
+ var ErrProviderUnknownNoRetry = "PROVIDER_REQUEST_UNKNOWN_NO_RETRY";
1479
+ var ErrBillingCallbackCannotCommit = "BILLING_CALLBACK_CANNOT_COMMIT";
1480
+ var ErrBillingCommitRequiresLocalVerify = "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY";
1481
+ var ErrBillingS2sForbidden = "BILLING_S2S_FORBIDDEN";
1482
+ var ErrSealApprovalNotApproved = "SEAL_APPROVAL_STATE_NOT_APPROVED";
1483
+ var ErrSealApprovalExpired = "SEAL_APPROVAL_EXPIRED";
1484
+ var ErrSealApprovalNonceUsed = "SEAL_APPROVAL_NONCE_USED";
1485
+ var ErrSealApprovalContractHashMismatch = "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH";
1486
+ var ErrSealApprovalSealMismatch = "SEAL_APPROVAL_SEAL_MISMATCH";
1487
+ var ErrSealApprovalLocationMismatch = "SEAL_APPROVAL_LOCATION_MISMATCH";
1488
+ var ErrSealApprovalTransactorMismatch = "SEAL_APPROVAL_TRANSACTOR_MISMATCH";
1489
+ var ErrSealUseAlreadyConsumed = "SEAL_USE_ALREADY_CONSUMED";
1490
+ function isComplianceTerminalError(code) {
1491
+ switch (code) {
1492
+ case ErrEnvelopeGateClosed:
1493
+ case ErrProviderNotConfigured:
1494
+ case ErrProviderUnknownNoRetry:
1495
+ case ErrBillingCallbackCannotCommit:
1496
+ case ErrBillingCommitRequiresLocalVerify:
1497
+ case ErrBillingS2sForbidden:
1498
+ case ErrSealApprovalNonceUsed:
1499
+ case ErrSealApprovalExpired:
1500
+ case ErrSealApprovalContractHashMismatch:
1501
+ case ErrSealApprovalSealMismatch:
1502
+ case ErrSealApprovalLocationMismatch:
1503
+ case ErrSealApprovalTransactorMismatch:
1504
+ case ErrSealUseAlreadyConsumed:
1505
+ return true;
1506
+ default:
1507
+ return false;
1508
+ }
1509
+ }
1510
+ function isBillingConfirmable(providerStatus, billingStatus) {
1511
+ return providerStatus === "success" && billingStatus === "committed";
1512
+ }
1513
+
1514
+ // src/compliance-errors.ts
1515
+ var CODE_TO_KEY = {
1516
+ // 通用 / token / scope (1-031-000-xxx)
1517
+ 1031000001: "COMPLIANCE_UNAUTHORIZED",
1518
+ 1031000002: "COMPLIANCE_TOKEN_INVALID",
1519
+ 1031000003: "COMPLIANCE_TOKEN_INVALID",
1520
+ 1031000004: "COMPLIANCE_TOKEN_INVALID",
1521
+ 1031000005: "COMPLIANCE_TOKEN_INVALID",
1522
+ 1031000006: "COMPLIANCE_TOKEN_INVALID",
1523
+ 1031000007: "COMPLIANCE_TOKEN_INVALID",
1524
+ 1031000008: "COMPLIANCE_TOKEN_INVALID",
1525
+ 1031000009: "COMPLIANCE_TOKEN_INVALID",
1526
+ 1031000010: "COMPLIANCE_TOKEN_INVALID",
1527
+ 1031000011: "COMPLIANCE_TOKEN_INVALID",
1528
+ 1031000012: "COMPLIANCE_INSUFFICIENT_SCOPE",
1529
+ 1031000013: "COMPLIANCE_STEP_UP_REQUIRED",
1530
+ // Subject snapshot (1-031-001-xxx)
1531
+ 1031001001: "SUBJECT_SNAPSHOT_NOT_FOUND",
1532
+ 1031001002: "SUBJECT_SNAPSHOT_TENANT_MISMATCH",
1533
+ 1031001003: "SUBJECT_SNAPSHOT_REQUIRED",
1534
+ // Evidence / Timestamp / Package / Report (1-031-002-xxx)
1535
+ 1031002001: "EVIDENCE_ASSET_NOT_FOUND",
1536
+ 1031002002: "SUBJECT_SNAPSHOT_TENANT_MISMATCH",
1537
+ 1031002003: "EVIDENCE_ASSET_HASH_MISMATCH",
1538
+ 1031002004: "EVIDENCE_ASSET_PAYLOAD_REQUIRED",
1539
+ 1031002005: "EVIDENCE_ASSET_PAYLOAD_REQUIRED",
1540
+ 1031002006: "TIMESTAMP_TOKEN_NOT_FOUND",
1541
+ 1031002007: "TIMESTAMP_PROVIDER_FAILED",
1542
+ 1031002008: "TIMESTAMP_PROVIDER_UNKNOWN",
1543
+ 1031002009: "TIMESTAMP_LOCAL_VERIFY_FAILED",
1544
+ 1031002010: "TIMESTAMP_PROVIDER_NOT_AVAILABLE",
1545
+ 1031002011: "EVIDENCE_PACKAGE_NOT_FOUND",
1546
+ 1031002012: "EVIDENCE_PACKAGE_TIMESTAMP_REQUIRED",
1547
+ 1031002013: "EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH",
1548
+ 1031002014: "REPORT_NOT_FOUND",
1549
+ 1031002015: "REPORT_ALREADY_PUBLISHED",
1550
+ 1031002016: "REPORT_DRAFT_REQUIRED",
1551
+ 1031002017: "EVIDENCE_VERIFY_TARGET_REQUIRED",
1552
+ 1031002018: "EVIDENCE_VERIFY_TARGET_NOT_FOUND",
1553
+ // Provider request (1-031-003-xxx)
1554
+ 1031003001: "PROVIDER_REQUEST_UNKNOWN_NO_RETRY",
1555
+ 1031003002: "PROVIDER_CALLBACK_SOURCE_INVALID",
1556
+ 1031003003: "PROVIDER_NOT_CONFIGURED",
1557
+ 1031003010: "PROVIDER_REQUEST_NOT_FOUND",
1558
+ 1031003011: "PROVIDER_REQUEST_IDEMPOTENCY_REQUIRED",
1559
+ 1031003012: "PROVIDER_REQUEST_STATUS_NOT_TERMINAL",
1560
+ // Envelope (1-031-004-xxx)
1561
+ 1031004001: "ENVELOPE_NOT_FOUND",
1562
+ 1031004002: "ENVELOPE_TENANT_MISMATCH",
1563
+ 1031004003: "ENVELOPE_STATE_NOT_ALLOWED",
1564
+ 1031004004: "ENVELOPE_GATE_CLOSED",
1565
+ 1031004005: "CONTRACT_NOT_FOUND",
1566
+ 1031004006: "CONTRACT_HASH_MISMATCH",
1567
+ 1031004007: "CONTRACT_NOT_FOUND",
1568
+ 1031004008: "PROVIDER_AUTHORIZATION_NOT_CONFIRMED",
1569
+ 1031004009: "PROVIDER_AUTHORIZATION_NOT_CONFIRMED",
1570
+ 1031004010: "ENVELOPE_EVIDENCE_NOT_READY",
1571
+ // Seal approval / use (1-031-005-xxx)
1572
+ 1031005001: "SEAL_ASSET_NOT_FOUND",
1573
+ 1031005010: "SEAL_APPROVAL_NOT_FOUND",
1574
+ 1031005011: "SEAL_APPROVAL_NOT_FOUND",
1575
+ 1031005012: "SEAL_APPROVAL_STATE_NOT_APPROVED",
1576
+ 1031005013: "SEAL_APPROVAL_EXPIRED",
1577
+ 1031005014: "SEAL_APPROVAL_ALREADY_USED",
1578
+ 1031005015: "SEAL_APPROVAL_NONCE_USED",
1579
+ 1031005016: "SEAL_APPROVAL_SEAL_MISMATCH",
1580
+ 1031005017: "SEAL_APPROVAL_LOCATION_MISMATCH",
1581
+ 1031005018: "SEAL_APPROVAL_TRANSACTOR_MISMATCH",
1582
+ 1031005019: "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH",
1583
+ 1031005020: "SEAL_APPROVAL_INVALID_TRANSITION",
1584
+ 1031005030: "SEAL_USE_ALREADY_CONSUMED",
1585
+ // Billing (1-031-006-xxx)
1586
+ 1031006004: "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY",
1587
+ 1031006005: "BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS",
1588
+ 1031006007: "BILLING_CALLBACK_CANNOT_COMMIT",
1589
+ 1031006008: "BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE",
1590
+ 1031006009: "BILLING_S2S_FORBIDDEN",
1591
+ // Audit (1-031-007-xxx)
1592
+ 1031007011: "AUDIT_CHAIN_TAMPER_DETECTED"
1593
+ };
1594
+ var STEP_UP_KEYS = /* @__PURE__ */ new Set(["COMPLIANCE_STEP_UP_REQUIRED"]);
1595
+ var TERMINAL_KEYS = /* @__PURE__ */ new Set([
1596
+ "ENVELOPE_GATE_CLOSED",
1597
+ "PROVIDER_NOT_CONFIGURED",
1598
+ "PROVIDER_REQUEST_UNKNOWN_NO_RETRY",
1599
+ "BILLING_CALLBACK_CANNOT_COMMIT",
1600
+ "BILLING_COMMIT_REQUIRES_LOCAL_VERIFY",
1601
+ "BILLING_COMMIT_REQUIRES_PROVIDER_SUCCESS",
1602
+ "BILLING_PROVIDER_UNKNOWN_NOT_COMMITTABLE",
1603
+ "BILLING_S2S_FORBIDDEN",
1604
+ "SEAL_APPROVAL_NONCE_USED",
1605
+ "SEAL_APPROVAL_EXPIRED",
1606
+ "SEAL_APPROVAL_CONTRACT_HASH_MISMATCH",
1607
+ "SEAL_APPROVAL_SEAL_MISMATCH",
1608
+ "SEAL_APPROVAL_LOCATION_MISMATCH",
1609
+ "SEAL_APPROVAL_TRANSACTOR_MISMATCH",
1610
+ "SEAL_USE_ALREADY_CONSUMED",
1611
+ "CONTRACT_HASH_MISMATCH",
1612
+ "TIMESTAMP_LOCAL_VERIFY_FAILED",
1613
+ "EVIDENCE_PACKAGE_MANIFEST_HASH_MISMATCH",
1614
+ "AUDIT_CHAIN_TAMPER_DETECTED",
1615
+ "PROVIDER_REQUEST_NOT_FOUND",
1616
+ "EVIDENCE_ASSET_HASH_MISMATCH",
1617
+ "EVIDENCE_VERIFY_TARGET_NOT_FOUND",
1618
+ "REPORT_ALREADY_PUBLISHED"
1619
+ ]);
1620
+ var RETRYABLE_KEYS = /* @__PURE__ */ new Set([]);
1621
+ function classifyComplianceError(err) {
1622
+ const key = CODE_TO_KEY[err.code] ?? "UNKNOWN_COMPLIANCE_ERROR";
1623
+ return {
1624
+ code: err.code,
1625
+ message: err.message,
1626
+ key,
1627
+ retryable: RETRYABLE_KEYS.has(key),
1628
+ terminal: TERMINAL_KEYS.has(key),
1629
+ stepUpRequired: STEP_UP_KEYS.has(key)
1630
+ };
1631
+ }
1632
+ function isComplianceBusinessError(err) {
1633
+ return err.code >= 1031e6 && err.code <= 1031999999;
1634
+ }
1635
+
1636
+ // src/client.ts
1637
+ init_types();
1638
+
1446
1639
  // src/store.ts
1447
1640
  var fileLockDefaults = {
1448
1641
  /** 获取锁的超时上限 (毫秒). refresh 流程含网络 < 30s, 30s 已远超正常完成时间. */
@@ -1718,368 +1911,100 @@ function computeBackoff(p, attempt, err) {
1718
1911
  return d;
1719
1912
  }
1720
1913
 
1721
- // src/sanitize/index.ts
1722
- var sanitize_exports = {};
1723
- __export(sanitize_exports, {
1724
- BlockCodeExecutionToolResult: () => BlockCodeExecutionToolResult,
1725
- BlockContainerUpload: () => BlockContainerUpload,
1726
- BlockDeniedError: () => BlockDeniedError,
1727
- BlockDocument: () => BlockDocument,
1728
- BlockImage: () => BlockImage,
1729
- BlockMCPToolResult: () => BlockMCPToolResult,
1730
- BlockMCPToolUse: () => BlockMCPToolUse,
1731
- BlockRedactedThinking: () => BlockRedactedThinking,
1732
- BlockSearchResult: () => BlockSearchResult,
1733
- BlockServerToolUse: () => BlockServerToolUse,
1734
- BlockText: () => BlockText,
1735
- BlockThinking: () => BlockThinking,
1736
- BlockToolReference: () => BlockToolReference,
1737
- BlockToolResult: () => BlockToolResult,
1738
- BlockToolUse: () => BlockToolUse,
1739
- BlockVideo: () => BlockVideo,
1740
- BlockWebSearchToolResult: () => BlockWebSearchToolResult,
1741
- DeltaCitations: () => DeltaCitations,
1742
- DeltaInputJSON: () => DeltaInputJSON,
1743
- DeltaSignature: () => DeltaSignature,
1744
- DeltaText: () => DeltaText,
1745
- DeltaThinking: () => DeltaThinking,
1746
- EphemeralMarkerField: () => EphemeralMarkerField,
1747
- ErrBlockDenied: () => ErrBlockDenied,
1748
- ErrHistoryTooDeep: () => ErrHistoryTooDeep,
1749
- HistoryTooDeepError: () => HistoryTooDeepError,
1750
- SizeError: () => SizeError,
1751
- dropBlocks: () => dropBlocks,
1752
- sanitize: () => sanitize,
1753
- stripEphemeral: () => stripEphemeral
1754
- });
1755
-
1756
- // src/sanitize/types.ts
1757
- var BlockText = "text";
1758
- var BlockImage = "image";
1759
- var BlockVideo = "video";
1760
- var BlockDocument = "document";
1761
- var BlockSearchResult = "search_result";
1762
- var BlockThinking = "thinking";
1763
- var BlockRedactedThinking = "redacted_thinking";
1764
- var BlockToolUse = "tool_use";
1765
- var BlockToolResult = "tool_result";
1766
- var BlockToolReference = "tool_reference";
1767
- var BlockServerToolUse = "server_tool_use";
1768
- var BlockWebSearchToolResult = "web_search_tool_result";
1769
- var BlockCodeExecutionToolResult = "code_execution_tool_result";
1770
- var BlockMCPToolUse = "mcp_tool_use";
1771
- var BlockMCPToolResult = "mcp_tool_result";
1772
- var BlockContainerUpload = "container_upload";
1773
- var DeltaText = "text_delta";
1774
- var DeltaInputJSON = "input_json_delta";
1775
- var DeltaThinking = "thinking_delta";
1776
- var DeltaSignature = "signature_delta";
1777
- var DeltaCitations = "citations_delta";
1778
- var EphemeralMarkerField = "acosmi_ephemeral";
1779
-
1780
- // src/sanitize/config.ts
1781
- var HistoryTooDeepError = class extends Error {
1782
- constructor() {
1783
- super("sanitize: messages history exceeds configured depth");
1784
- this.name = "HistoryTooDeepError";
1785
- }
1786
- };
1787
- var BlockDeniedError = class extends Error {
1788
- constructor() {
1789
- super("sanitize: block type permanently denied");
1790
- this.name = "BlockDeniedError";
1791
- }
1792
- };
1793
- var SizeError = class extends Error {
1794
- blockType;
1795
- actual;
1796
- limit;
1797
- constructor(blockType, actual, limit) {
1798
- super(`sanitize: ${blockType} base64 size ${actual} exceeds limit ${limit}`);
1799
- this.name = "SizeError";
1800
- this.blockType = blockType;
1801
- this.actual = actual;
1802
- this.limit = limit;
1803
- }
1804
- };
1805
- var ErrHistoryTooDeep = new HistoryTooDeepError();
1806
- var ErrBlockDenied = new BlockDeniedError();
1914
+ // src/client.ts
1915
+ init_adapters();
1807
1916
 
1808
- // src/sanitize/history.ts
1809
- function dropBlocks(messages, pred) {
1810
- const droppedToolUseIDs = collectDroppedToolUseIDs(messages, pred);
1811
- const out = [];
1812
- for (const msg of messages) {
1813
- if (!isPlainObject(msg)) {
1814
- out.push(msg);
1815
- continue;
1816
- }
1817
- const content = msg["content"];
1818
- if (!Array.isArray(content)) {
1819
- out.push(msg);
1820
- continue;
1821
- }
1822
- const { kept, changed } = filterBlocks(content, pred, droppedToolUseIDs);
1823
- if (!changed) {
1824
- out.push(msg);
1825
- continue;
1917
+ // src/stream-meta.ts
1918
+ function extractAnthropicBlockMeta(eventType, data, blockTypeMap) {
1919
+ switch (eventType) {
1920
+ case "content_block_start": {
1921
+ let payload;
1922
+ try {
1923
+ payload = JSON.parse(data);
1924
+ } catch {
1925
+ return [0, "", false];
1926
+ }
1927
+ const index = payload.index ?? 0;
1928
+ const meta = {
1929
+ type: payload.content_block?.type ?? "",
1930
+ ephemeral: payload.content_block?.acosmi_ephemeral ?? false
1931
+ };
1932
+ blockTypeMap.set(index, meta);
1933
+ return [index, meta.type, meta.ephemeral];
1826
1934
  }
1827
- if (kept.length === 0) {
1828
- continue;
1935
+ case "content_block_delta": {
1936
+ let payload;
1937
+ try {
1938
+ payload = JSON.parse(data);
1939
+ } catch {
1940
+ return [0, "", false];
1941
+ }
1942
+ const index = payload.index ?? 0;
1943
+ const meta = blockTypeMap.get(index);
1944
+ return [index, meta?.type ?? "", meta?.ephemeral ?? false];
1829
1945
  }
1830
- const newMsg = { ...msg };
1831
- newMsg["content"] = kept;
1832
- out.push(newMsg);
1833
- }
1834
- return out;
1835
- }
1836
- function collectDroppedToolUseIDs(messages, pred) {
1837
- const ids = /* @__PURE__ */ new Set();
1838
- for (const msg of messages) {
1839
- if (!isPlainObject(msg)) continue;
1840
- const content = msg["content"];
1841
- if (!Array.isArray(content)) continue;
1842
- for (const raw of content) {
1843
- if (!isPlainObject(raw)) continue;
1844
- if (!pred(raw)) continue;
1845
- const t = raw["type"];
1846
- if (typeof t !== "string") continue;
1847
- if (t === "tool_use" || t === "server_tool_use" || t === "mcp_tool_use") {
1848
- const id = raw["id"];
1849
- if (typeof id === "string" && id !== "") ids.add(id);
1946
+ case "content_block_stop": {
1947
+ let payload;
1948
+ try {
1949
+ payload = JSON.parse(data);
1950
+ } catch {
1951
+ return [0, "", false];
1850
1952
  }
1953
+ const index = payload.index ?? 0;
1954
+ const meta = blockTypeMap.get(index);
1955
+ blockTypeMap.delete(index);
1956
+ return [index, meta?.type ?? "", meta?.ephemeral ?? false];
1851
1957
  }
1958
+ default:
1959
+ return [0, "", false];
1852
1960
  }
1853
- return ids;
1854
1961
  }
1855
- function filterBlocks(content, pred, droppedToolUseIDs) {
1856
- const kept = [];
1857
- let changed = false;
1858
- for (const raw of content) {
1859
- if (!isPlainObject(raw)) {
1860
- kept.push(raw);
1861
- continue;
1862
- }
1863
- if (pred(raw)) {
1864
- changed = true;
1865
- continue;
1962
+
1963
+ // src/client.ts
1964
+ init_openai();
1965
+
1966
+ // src/client-helpers.ts
1967
+ init_types();
1968
+ var maxDownloadSize = 50 * 1024 * 1024;
1969
+ var maxErrorBodySize = 1 * 1024 * 1024;
1970
+ var maxSSELineSize = 1 * 1024 * 1024;
1971
+ var modelCacheTTLMs = 5 * 60 * 1e3;
1972
+ var coefCacheTTLMs = 8 * 1e3;
1973
+ function parseHTTPErrorWithHeader(statusCode, body, header) {
1974
+ const bodyStr = typeof body === "string" ? body : new TextDecoder().decode(body);
1975
+ let retryAfter = 0;
1976
+ if (header) {
1977
+ const ra = header.get("Retry-After");
1978
+ if (ra) {
1979
+ const sec = parseInt(ra, 10);
1980
+ if (!isNaN(sec) && sec > 0) retryAfter = sec;
1866
1981
  }
1867
- if (droppedToolUseIDs.size > 0) {
1868
- const t = raw["type"];
1869
- if (t === "tool_result" || t === "mcp_tool_result") {
1870
- const id = raw["tool_use_id"];
1871
- if (typeof id === "string" && id !== "" && droppedToolUseIDs.has(id)) {
1872
- changed = true;
1873
- continue;
1874
- }
1982
+ }
1983
+ if (bodyStr.length === 0) {
1984
+ return new exports.HTTPError(statusCode, { retryAfter });
1985
+ }
1986
+ let type = "";
1987
+ let message = "";
1988
+ try {
1989
+ const obj = JSON.parse(bodyStr);
1990
+ if (obj && typeof obj === "object") {
1991
+ const errObj = obj.error;
1992
+ if (errObj && typeof errObj === "object") {
1993
+ const e = errObj;
1994
+ if (typeof e.message === "string") message = e.message;
1995
+ if (typeof e.type === "string") type = e.type;
1875
1996
  }
1876
1997
  }
1877
- kept.push(raw);
1998
+ } catch {
1878
1999
  }
1879
- return { kept, changed };
2000
+ return new exports.HTTPError(statusCode, { type, message, retryAfter, body: bodyStr });
1880
2001
  }
1881
- function stripEphemeral(messages) {
1882
- return dropBlocks(messages, (b) => {
1883
- const t = b["type"];
1884
- if (t === "thinking" || t === "redacted_thinking") {
1885
- return false;
1886
- }
1887
- const v = b[EphemeralMarkerField];
1888
- return v === true;
1889
- });
1890
- }
1891
- function isPlainObject(v) {
1892
- return typeof v === "object" && v !== null && !Array.isArray(v);
1893
- }
1894
-
1895
- // src/sanitize/defensive.ts
1896
- function sanitize(messages, cfg) {
1897
- if ((cfg.maxMessagesTurns ?? 0) > 0 && messages.length > cfg.maxMessagesTurns) {
1898
- throw ErrHistoryTooDeep;
1899
- }
1900
- if ((cfg.maxImageBytes ?? 0) > 0 || (cfg.maxVideoBytes ?? 0) > 0 || (cfg.maxPDFBytes ?? 0) > 0) {
1901
- checkMediaSizes(messages, cfg);
1902
- }
1903
- if (cfg.permanentDenyBlocks && cfg.permanentDenyBlocks.length > 0) {
1904
- const denySet = /* @__PURE__ */ new Set();
1905
- for (const bt of cfg.permanentDenyBlocks) denySet.add(bt);
1906
- messages = dropBlocks(messages, (b) => {
1907
- const t = b["type"];
1908
- return typeof t === "string" && denySet.has(t);
1909
- });
1910
- }
1911
- return messages;
1912
- }
1913
- function checkMediaSizes(messages, cfg) {
1914
- for (const msg of messages) {
1915
- if (!isPlainObject2(msg)) continue;
1916
- const content = msg["content"];
1917
- if (!Array.isArray(content)) continue;
1918
- for (const raw of content) {
1919
- if (!isPlainObject2(raw)) continue;
1920
- const bt = raw["type"];
1921
- if (typeof bt !== "string") continue;
1922
- let limit = 0;
1923
- switch (bt) {
1924
- case "image":
1925
- limit = cfg.maxImageBytes ?? 0;
1926
- break;
1927
- case "video":
1928
- limit = cfg.maxVideoBytes ?? 0;
1929
- break;
1930
- case "document":
1931
- limit = cfg.maxPDFBytes ?? 0;
1932
- break;
1933
- default:
1934
- continue;
1935
- }
1936
- if (limit <= 0) continue;
1937
- const data = extractBase64Data(raw);
1938
- if (data === "") continue;
1939
- const actual = base64DecodedLen(data);
1940
- if (actual > limit) {
1941
- throw new SizeError(bt, actual, limit);
1942
- }
1943
- }
1944
- }
1945
- }
1946
- function extractBase64Data(block) {
1947
- const src = block["source"];
1948
- if (!isPlainObject2(src)) return "";
1949
- if (src["type"] !== "base64") return "";
1950
- const dataRaw = src["data"];
1951
- if (typeof dataRaw !== "string") return "";
1952
- let data = dataRaw;
1953
- const i = data.indexOf("base64,");
1954
- if (i >= 0) {
1955
- data = data.slice(i + "base64,".length);
1956
- }
1957
- return data;
1958
- }
1959
- function base64DecodedLen(b64) {
1960
- const n = b64.length;
1961
- let pad = 0;
1962
- if (n >= 1 && b64[n - 1] === "=") pad++;
1963
- if (n >= 2 && b64[n - 2] === "=") pad++;
1964
- return Math.floor(n * 3 / 4) - pad;
1965
- }
1966
- function isPlainObject2(v) {
1967
- return typeof v === "object" && v !== null && !Array.isArray(v);
1968
- }
1969
-
1970
- // src/stream-meta.ts
1971
- function extractAnthropicBlockMeta(eventType, data, blockTypeMap) {
1972
- switch (eventType) {
1973
- case "content_block_start": {
1974
- let payload;
1975
- try {
1976
- payload = JSON.parse(data);
1977
- } catch {
1978
- return [0, "", false];
1979
- }
1980
- const index = payload.index ?? 0;
1981
- const meta = {
1982
- type: payload.content_block?.type ?? "",
1983
- ephemeral: payload.content_block?.acosmi_ephemeral ?? false
1984
- };
1985
- blockTypeMap.set(index, meta);
1986
- return [index, meta.type, meta.ephemeral];
1987
- }
1988
- case "content_block_delta": {
1989
- let payload;
1990
- try {
1991
- payload = JSON.parse(data);
1992
- } catch {
1993
- return [0, "", false];
1994
- }
1995
- const index = payload.index ?? 0;
1996
- const meta = blockTypeMap.get(index);
1997
- return [index, meta?.type ?? "", meta?.ephemeral ?? false];
1998
- }
1999
- case "content_block_stop": {
2000
- let payload;
2001
- try {
2002
- payload = JSON.parse(data);
2003
- } catch {
2004
- return [0, "", false];
2005
- }
2006
- const index = payload.index ?? 0;
2007
- const meta = blockTypeMap.get(index);
2008
- blockTypeMap.delete(index);
2009
- return [index, meta?.type ?? "", meta?.ephemeral ?? false];
2010
- }
2011
- default:
2012
- return [0, "", false];
2013
- }
2014
- }
2015
-
2016
- // src/agent-runs-types.ts
2017
- var AgentRunStreamError = class extends Error {
2018
- event;
2019
- code;
2020
- stage;
2021
- retryable;
2022
- constructor(event) {
2023
- const err = event.error;
2024
- super(err.stage ? `agent run failed: ${err.stage}: ${err.message}` : `agent run failed: ${err.message}`);
2025
- this.name = "AgentRunStreamError";
2026
- this.event = event;
2027
- this.code = err.code ?? "";
2028
- this.stage = err.stage ?? "";
2029
- this.retryable = err.retryable ?? false;
2030
- }
2031
- };
2032
-
2033
- // src/client/agent-runs.ts
2034
- init_types();
2035
-
2036
- // src/client.ts
2037
- init_types();
2038
- init_adapters();
2039
- init_openai();
2040
-
2041
- // src/client-helpers.ts
2042
- init_types();
2043
- var maxDownloadSize = 50 * 1024 * 1024;
2044
- var maxErrorBodySize = 1 * 1024 * 1024;
2045
- var maxSSELineSize = 1 * 1024 * 1024;
2046
- var modelCacheTTLMs = 5 * 60 * 1e3;
2047
- var coefCacheTTLMs = 8 * 1e3;
2048
- function parseHTTPErrorWithHeader(statusCode, body, header) {
2049
- const bodyStr = typeof body === "string" ? body : new TextDecoder().decode(body);
2050
- let retryAfter = 0;
2051
- if (header) {
2052
- const ra = header.get("Retry-After");
2053
- if (ra) {
2054
- const sec = parseInt(ra, 10);
2055
- if (!isNaN(sec) && sec > 0) retryAfter = sec;
2056
- }
2057
- }
2058
- if (bodyStr.length === 0) {
2059
- return new exports.HTTPError(statusCode, { retryAfter });
2060
- }
2061
- let type = "";
2062
- let message = "";
2063
- try {
2064
- const obj = JSON.parse(bodyStr);
2065
- if (obj && typeof obj === "object") {
2066
- const errObj = obj.error;
2067
- if (errObj && typeof errObj === "object") {
2068
- const e = errObj;
2069
- if (typeof e.message === "string") message = e.message;
2070
- if (typeof e.type === "string") type = e.type;
2071
- }
2072
- }
2073
- } catch {
2074
- }
2075
- return new exports.HTTPError(statusCode, { type, message, retryAfter, body: bodyStr });
2076
- }
2077
- function classifyTransport(op, urlStr, err) {
2078
- const ne = new exports.NetworkError(op, urlStr, err);
2079
- if (err instanceof Error) {
2080
- if (err.name === "AbortError") {
2081
- ne.timeout = true;
2082
- return ne;
2002
+ function classifyTransport(op, urlStr, err) {
2003
+ const ne = new exports.NetworkError(op, urlStr, err);
2004
+ if (err instanceof Error) {
2005
+ if (err.name === "AbortError") {
2006
+ ne.timeout = true;
2007
+ return ne;
2083
2008
  }
2084
2009
  const cause = err.cause;
2085
2010
  if (cause) {
@@ -2238,6 +2163,8 @@ var Client = class _Client {
2238
2163
  /** SDK 内部使用 — 业务方法 (mixin) 通过 this.* 访问以下字段 */
2239
2164
  /** 服务器根地址 (已 trim 尾随 /) */
2240
2165
  serverURL;
2166
+ /** Compliance API 根地址 (已 trim 尾随 /); null = 走默认 ${serverURL}/admin-api */
2167
+ complianceBaseURL;
2241
2168
  /** OAuth metadata (lazy loaded) */
2242
2169
  meta = null;
2243
2170
  /** 当前 token (内存) */
@@ -2271,6 +2198,7 @@ var Client = class _Client {
2271
2198
  coefMu = Promise.resolve();
2272
2199
  constructor(cfg = {}) {
2273
2200
  this.serverURL = (cfg.serverURL ?? "https://acosmi.com").replace(/\/+$/, "");
2201
+ this.complianceBaseURL = cfg.complianceBaseURL ? cfg.complianceBaseURL.replace(/\/+$/, "") : null;
2274
2202
  this.store = cfg.store ?? defaultTokenStore();
2275
2203
  this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);
2276
2204
  this.retryPolicy = effectivePolicy(cfg.retryPolicy ?? null);
@@ -3039,6 +2967,19 @@ var Client = class _Client {
3039
2967
  }
3040
2968
  return base + path;
3041
2969
  }
2970
+ /**
2971
+ * Compliance API URL 拼接。
2972
+ *
2973
+ * `complianceBaseURL` 已配置时直接拼接;未配置时默认
2974
+ * `${serverURL}/admin-api` + path,匹配 Java compliance controller 的
2975
+ * `/compliance/...` 路径。
2976
+ *
2977
+ * 不复用 `apiURL`:apiURL 强制追加 `/api/v4`,与 compliance 路径不同。
2978
+ */
2979
+ complianceURL(path) {
2980
+ const base = this.complianceBaseURL ?? this.serverURL + "/admin-api";
2981
+ return base + path;
2982
+ }
3042
2983
  /** GET/POST/... 通用 JSON 调用 (返回 result 已 typed) */
3043
2984
  async doJSON(method, path, body, signal) {
3044
2985
  const r = await this.doJSONFull(method, path, body, signal);
@@ -3328,7 +3269,753 @@ async function sleep(ms, signal) {
3328
3269
  });
3329
3270
  }
3330
3271
 
3331
- // src/client/agent-runs.ts
3272
+ // src/client/compliance.ts
3273
+ init_types();
3274
+ var cache = /* @__PURE__ */ new WeakMap();
3275
+ Object.defineProperty(Client.prototype, "compliance", {
3276
+ configurable: true,
3277
+ enumerable: false,
3278
+ get() {
3279
+ let existing = cache.get(this);
3280
+ if (!existing) {
3281
+ existing = new ComplianceClient(this);
3282
+ cache.set(this, existing);
3283
+ }
3284
+ return existing;
3285
+ }
3286
+ });
3287
+ var DEFAULT_POLL = {
3288
+ timeoutMs: 6e4,
3289
+ initialIntervalMs: 1e3,
3290
+ maxIntervalMs: 5e3,
3291
+ multiplier: 1.5
3292
+ };
3293
+ var CompliancePollError = class extends Error {
3294
+ kind;
3295
+ lastInfo;
3296
+ constructor(message, kind, lastInfo) {
3297
+ super(message);
3298
+ this.name = "CompliancePollError";
3299
+ this.kind = kind;
3300
+ this.lastInfo = lastInfo;
3301
+ }
3302
+ };
3303
+ var ComplianceClient = class {
3304
+ constructor(client) {
3305
+ this.client = client;
3306
+ }
3307
+ client;
3308
+ // =========================================================================
3309
+ // Evidence Asset
3310
+ // =========================================================================
3311
+ /** 创建证据资产(写)。 */
3312
+ createEvidenceAsset(req, opts = {}) {
3313
+ return this.write(
3314
+ "POST",
3315
+ "/compliance/evidence/assets",
3316
+ req,
3317
+ writeCtx(opts)
3318
+ );
3319
+ }
3320
+ /** 读 — 证据资产详情。 */
3321
+ getEvidenceAsset(id, signal) {
3322
+ return this.read(
3323
+ "GET",
3324
+ `/compliance/evidence/assets/${encodeURIComponent(id)}`,
3325
+ null,
3326
+ signal
3327
+ );
3328
+ }
3329
+ /**
3330
+ * 公开 verify。隐私边界:返回字段不含 PII / 合同原文 / storage / provider raw。
3331
+ * 服务端不要求 compliance scope(公开端点);但 SDK 仍带上 token 以便审计。
3332
+ */
3333
+ verifyEvidencePublic(params, signal) {
3334
+ const q = new URLSearchParams();
3335
+ if (params.evidenceNo) q.set("evidenceNo", params.evidenceNo);
3336
+ if (params.publicVerifyCode) q.set("publicVerifyCode", params.publicVerifyCode);
3337
+ const qs = q.toString();
3338
+ return this.read(
3339
+ "GET",
3340
+ `/compliance/evidence/verify${qs ? "?" + qs : ""}`,
3341
+ null,
3342
+ signal
3343
+ );
3344
+ }
3345
+ // =========================================================================
3346
+ // Timestamp
3347
+ // =========================================================================
3348
+ /** 申请时间章(写)。SDK 永远不传 provider 字段。 */
3349
+ issueTimestamp(req, opts = {}) {
3350
+ return this.write("POST", "/compliance/timestamps", req, writeCtx(opts));
3351
+ }
3352
+ /** 给已有资产申请时间章。SDK 永远不传 provider 字段。 */
3353
+ issueTimestampForAsset(assetId, opts = {}) {
3354
+ return this.write(
3355
+ "POST",
3356
+ `/compliance/evidence/assets/${encodeURIComponent(assetId)}/timestamp`,
3357
+ null,
3358
+ writeCtx(opts)
3359
+ );
3360
+ }
3361
+ /** 读 — 时间章 token 详情。 */
3362
+ getTimestamp(id, signal) {
3363
+ return this.read(
3364
+ "GET",
3365
+ `/compliance/timestamps/${encodeURIComponent(id)}`,
3366
+ null,
3367
+ signal
3368
+ );
3369
+ }
3370
+ /** verify — 本地离线校验已申请的时间章。 */
3371
+ verifyTimestamp(req, opts = {}) {
3372
+ return this.write(
3373
+ "POST",
3374
+ "/compliance/timestamps/verify",
3375
+ req,
3376
+ writeCtx(opts)
3377
+ );
3378
+ }
3379
+ /**
3380
+ * 轮询到 VERIFIED 终态。
3381
+ * - VERIFIED → 返回 token;
3382
+ * - FAILED / LOCAL_VERIFY_FAILED → 抛 {@link CompliancePollError} kind='terminal_failure';
3383
+ * - UNKNOWN / RETRYING / PENDING → 继续轮询直到 timeout;
3384
+ * - timeout → 抛 {@link CompliancePollError} kind='timeout'。
3385
+ */
3386
+ async waitForTimestampVerified(id, opts = {}) {
3387
+ return this.poll(
3388
+ () => this.getTimestamp(id, opts.signal),
3389
+ (t) => classifyTimestamp(t.verificationStatus),
3390
+ opts
3391
+ );
3392
+ }
3393
+ // =========================================================================
3394
+ // Evidence Package
3395
+ // =========================================================================
3396
+ /** 构建证据包(写)。 */
3397
+ buildEvidencePackage(assetId, timestampTokenId, opts = {}) {
3398
+ const tsParam = timestampTokenId == null ? "" : "?timestampTokenId=" + encodeURIComponent(timestampTokenId);
3399
+ return this.write(
3400
+ "POST",
3401
+ `/compliance/evidence/assets/${encodeURIComponent(assetId)}/packages${tsParam}`,
3402
+ null,
3403
+ writeCtx(opts)
3404
+ );
3405
+ }
3406
+ // =========================================================================
3407
+ // Report
3408
+ // =========================================================================
3409
+ /** 创建证据报告(写)。 */
3410
+ createReport(req, opts = {}) {
3411
+ return this.write("POST", "/compliance/reports", req, writeCtx(opts));
3412
+ }
3413
+ /** 读 — 报告详情。 */
3414
+ getReport(id, signal) {
3415
+ return this.read(
3416
+ "GET",
3417
+ `/compliance/reports/${encodeURIComponent(id)}`,
3418
+ null,
3419
+ signal
3420
+ );
3421
+ }
3422
+ /**
3423
+ * 发布报告(写,step-up 必须)。
3424
+ *
3425
+ * 缺少 step-up 时服务端会返回 `COMPLIANCE_STEP_UP_REQUIRED`(数值码
3426
+ * 1031000013)。SDK 不会自动重试;调用方需要引导用户重新做 OAuth introspection 或
3427
+ * 重新登录后再次调用本方法(使用同一 idempotency-key)。
3428
+ */
3429
+ publishReport(id, opts = {}) {
3430
+ return this.write(
3431
+ "POST",
3432
+ `/compliance/reports/${encodeURIComponent(id)}/publish`,
3433
+ null,
3434
+ writeCtx(opts)
3435
+ );
3436
+ }
3437
+ /**
3438
+ * 下载报告(读)。返回 {@link ReportDownload}:报告 hash + 资产 hash + 证据包 hash +
3439
+ * 时间章 serial/genTime,足以离线复核。
3440
+ * 不返回 bodyCanonicalJson / storage key / subject snapshot id。
3441
+ */
3442
+ downloadReport(id, signal) {
3443
+ return this.read(
3444
+ "GET",
3445
+ `/compliance/reports/${encodeURIComponent(id)}/download`,
3446
+ null,
3447
+ signal
3448
+ );
3449
+ }
3450
+ // =========================================================================
3451
+ // Signing Envelope
3452
+ // =========================================================================
3453
+ /** 创建 envelope(写)。返回 envelope id。 */
3454
+ createSigningEnvelope(req, opts = {}) {
3455
+ return this.write(
3456
+ "POST",
3457
+ "/compliance/signing-envelopes",
3458
+ req,
3459
+ writeCtx(opts)
3460
+ );
3461
+ }
3462
+ /** 读 — envelope 详情。租户由服务端从 compliance token principal 推导。 */
3463
+ getSigningEnvelope(envelopeId, signal) {
3464
+ return this.read(
3465
+ "GET",
3466
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}`,
3467
+ null,
3468
+ signal
3469
+ );
3470
+ }
3471
+ /**
3472
+ * 正式签署(写,step-up 必须)。
3473
+ *
3474
+ * 服务端闸门关闭时会一致返回 `ENVELOPE_GATE_CLOSED` (1031004004)。
3475
+ * SDK 不重试、不伪成功;调用方应该将该错误展示为"功能未开放"。
3476
+ */
3477
+ signEnvelope(envelopeId, req, opts = {}) {
3478
+ return this.write(
3479
+ "POST",
3480
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/sign`,
3481
+ req,
3482
+ writeCtx(opts)
3483
+ );
3484
+ }
3485
+ /**
3486
+ * 创建 H5 签署短链(写,step-up 必须)。
3487
+ *
3488
+ * 同上:服务端闸门关闭时 SDK 不重试。
3489
+ */
3490
+ createH5SigningUrl(envelopeId, req, opts = {}) {
3491
+ return this.write(
3492
+ "POST",
3493
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/h5-url`,
3494
+ req,
3495
+ writeCtx(opts)
3496
+ );
3497
+ }
3498
+ /** 同步 provider 状态(写但只读对账,不创建新 provider 请求)。 */
3499
+ syncSigningEnvelopeStatus(envelopeId, opts = {}) {
3500
+ return this.write(
3501
+ "POST",
3502
+ `/compliance/signing-envelopes/${encodeURIComponent(envelopeId)}/sync-provider-status`,
3503
+ null,
3504
+ writeCtx(opts)
3505
+ );
3506
+ }
3507
+ // =========================================================================
3508
+ // Seal Approval
3509
+ // =========================================================================
3510
+ submitSealApproval(req, opts = {}) {
3511
+ return this.write(
3512
+ "POST",
3513
+ "/compliance/seal-approvals",
3514
+ req,
3515
+ writeCtx(opts)
3516
+ );
3517
+ }
3518
+ approveSealApproval(id, query, opts = {}) {
3519
+ const q = new URLSearchParams();
3520
+ if (query.expiresAt) q.set("expiresAt", query.expiresAt);
3521
+ if (query.note) q.set("note", query.note);
3522
+ const qs = q.toString();
3523
+ return this.write(
3524
+ "POST",
3525
+ `/compliance/seal-approvals/${encodeURIComponent(id)}/approve${qs ? "?" + qs : ""}`,
3526
+ null,
3527
+ writeCtx(opts)
3528
+ );
3529
+ }
3530
+ rejectSealApproval(id, query, opts = {}) {
3531
+ const q = new URLSearchParams();
3532
+ if (query.reason) q.set("reason", query.reason);
3533
+ const qs = q.toString();
3534
+ return this.write(
3535
+ "POST",
3536
+ `/compliance/seal-approvals/${encodeURIComponent(id)}/reject${qs ? "?" + qs : ""}`,
3537
+ null,
3538
+ writeCtx(opts)
3539
+ );
3540
+ }
3541
+ cancelSealApproval(id, query, opts = {}) {
3542
+ const q = new URLSearchParams();
3543
+ if (query.reason) q.set("reason", query.reason);
3544
+ const qs = q.toString();
3545
+ return this.write(
3546
+ "POST",
3547
+ `/compliance/seal-approvals/${encodeURIComponent(id)}/cancel${qs ? "?" + qs : ""}`,
3548
+ null,
3549
+ writeCtx(opts)
3550
+ );
3551
+ }
3552
+ listPendingSealApprovals(signal) {
3553
+ return this.read(
3554
+ "GET",
3555
+ "/compliance/seal-approvals/pending",
3556
+ null,
3557
+ signal
3558
+ );
3559
+ }
3560
+ getSealApproval(id, signal) {
3561
+ return this.read(
3562
+ "GET",
3563
+ `/compliance/seal-approvals/${encodeURIComponent(id)}`,
3564
+ null,
3565
+ signal
3566
+ );
3567
+ }
3568
+ // =========================================================================
3569
+ // Provider Request (read-only)
3570
+ // =========================================================================
3571
+ getProviderRequest(id, signal) {
3572
+ return this.read(
3573
+ "GET",
3574
+ `/compliance/provider-requests/${encodeURIComponent(id)}`,
3575
+ null,
3576
+ signal
3577
+ );
3578
+ }
3579
+ /**
3580
+ * 轮询 provider request 到 SUCCESS / FAILED 终态。
3581
+ * - SUCCESS / FAILED → 返回最后视图;
3582
+ * - UNKNOWN / RETRYING / PENDING → 继续轮询;
3583
+ * - timeout → 抛 {@link CompliancePollError} kind='timeout',不自动重发原 provider 请求。
3584
+ *
3585
+ * SUCCESS 不代表 billing 已 commit;调用方仍需通过业务侧 envelope / asset 终态判断。
3586
+ */
3587
+ async waitForProviderRequestTerminal(id, opts = {}) {
3588
+ return this.poll(
3589
+ () => this.getProviderRequest(id, opts.signal),
3590
+ (v) => classifyProviderStatus(v.status),
3591
+ opts
3592
+ );
3593
+ }
3594
+ // =========================================================================
3595
+ // Error classification (re-export for convenience)
3596
+ // =========================================================================
3597
+ classifyError(err) {
3598
+ if (!isBusinessErrorLike(err)) return null;
3599
+ if (!isComplianceBusinessError(err)) return null;
3600
+ return classifyComplianceError(err);
3601
+ }
3602
+ // =========================================================================
3603
+ // Internal helpers
3604
+ // =========================================================================
3605
+ /**
3606
+ * 读路径:GET / 公开 verify。允许 401 单次刷新后重放(GET 幂等安全)。
3607
+ * 与 client.doJSONFullInternal 行为一致;不复用其代码因为 base URL 不同。
3608
+ */
3609
+ async read(method, path, body, signal, extraHeaders = {}) {
3610
+ return this.executeJson(method, path, body, signal, {
3611
+ retryOn401: true,
3612
+ extraHeaders
3613
+ });
3614
+ }
3615
+ /**
3616
+ * 写路径:POST。
3617
+ * - 发送前 ensureToken 一次确保 token fresh。
3618
+ * - 不自动 401 重放:401 → 抛 HTTPError;调用方必须自己刷新 token 后用同一
3619
+ * idempotency-key 重新发起,避免 provider 侧重复请求。
3620
+ * - 不走 doRequestWithRetry:写操作不允许 5xx/timeout 自动重试。
3621
+ */
3622
+ async write(method, path, body, ctx) {
3623
+ const headers = { ...ctx.extraHeaders ?? {} };
3624
+ if (ctx.idempotencyKey) headers["Idempotency-Key"] = ctx.idempotencyKey;
3625
+ return this.executeJson(method, path, body, ctx.signal, {
3626
+ retryOn401: false,
3627
+ extraHeaders: headers
3628
+ });
3629
+ }
3630
+ async executeJson(method, path, body, signal, opts, retried = false) {
3631
+ const token = await this.client.ensureToken(signal);
3632
+ const url = this.client.complianceURL(path);
3633
+ const headers = {
3634
+ Authorization: `Bearer ${token}`,
3635
+ Accept: "application/json",
3636
+ ...opts.extraHeaders
3637
+ };
3638
+ let bodyStr;
3639
+ if (body != null) {
3640
+ bodyStr = typeof body === "string" ? body : JSON.stringify(body);
3641
+ headers["Content-Type"] = "application/json";
3642
+ }
3643
+ const resp = await this.client.doRequest({ method, url, headers, body: bodyStr }, signal);
3644
+ if (resp.status === 401 && opts.retryOn401 && !retried) {
3645
+ try {
3646
+ await resp.body?.cancel();
3647
+ } catch {
3648
+ }
3649
+ await this.client.forceRefresh(signal);
3650
+ return this.executeJson(method, path, body, signal, opts, true);
3651
+ }
3652
+ if (resp.status < 200 || resp.status >= 300) {
3653
+ const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
3654
+ throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
3655
+ }
3656
+ const text = await resp.text();
3657
+ if (!text) return void 0;
3658
+ const parsed = JSON.parse(text);
3659
+ const bizErr = apiResponseBusinessError(parsed);
3660
+ if (bizErr) throw bizErr;
3661
+ return parsed.data;
3662
+ }
3663
+ async poll(fetcher, classify, opts) {
3664
+ const cfg = {
3665
+ timeoutMs: opts.timeoutMs ?? DEFAULT_POLL.timeoutMs,
3666
+ initialIntervalMs: opts.initialIntervalMs ?? DEFAULT_POLL.initialIntervalMs,
3667
+ maxIntervalMs: opts.maxIntervalMs ?? DEFAULT_POLL.maxIntervalMs,
3668
+ multiplier: opts.multiplier ?? DEFAULT_POLL.multiplier
3669
+ };
3670
+ const deadline = Date.now() + cfg.timeoutMs;
3671
+ let interval = cfg.initialIntervalMs;
3672
+ let lastValue;
3673
+ while (Date.now() < deadline) {
3674
+ if (opts.signal?.aborted) {
3675
+ throw new CompliancePollError("compliance poll aborted", "unknown");
3676
+ }
3677
+ lastValue = await fetcher();
3678
+ const decision = classify(lastValue);
3679
+ if (decision === "done") return lastValue;
3680
+ if (decision === "failed") {
3681
+ throw new CompliancePollError(
3682
+ "compliance poll observed terminal failure",
3683
+ "terminal_failure"
3684
+ );
3685
+ }
3686
+ const sleepMs = Math.min(interval, deadline - Date.now());
3687
+ if (sleepMs <= 0) break;
3688
+ await sleep2(sleepMs, opts.signal);
3689
+ interval = Math.min(Math.floor(interval * cfg.multiplier), cfg.maxIntervalMs);
3690
+ }
3691
+ throw new CompliancePollError("compliance poll timed out", "timeout");
3692
+ }
3693
+ };
3694
+ function classifyTimestamp(status) {
3695
+ switch (status) {
3696
+ case "VERIFIED":
3697
+ return "done";
3698
+ case "FAILED":
3699
+ case "LOCAL_VERIFY_FAILED":
3700
+ return "failed";
3701
+ case "PENDING":
3702
+ case "UNKNOWN":
3703
+ case "RETRYING":
3704
+ default:
3705
+ return "continue";
3706
+ }
3707
+ }
3708
+ function classifyProviderStatus(status) {
3709
+ switch (status) {
3710
+ case "SUCCESS":
3711
+ return "done";
3712
+ case "FAILED":
3713
+ return "failed";
3714
+ case "PENDING":
3715
+ case "UNKNOWN":
3716
+ case "RETRYING":
3717
+ default:
3718
+ return "continue";
3719
+ }
3720
+ }
3721
+ function writeCtx(opts, extraHeaders = {}) {
3722
+ return {
3723
+ idempotencyKey: opts.idempotencyKey,
3724
+ signal: opts.signal,
3725
+ extraHeaders
3726
+ };
3727
+ }
3728
+ function isBusinessErrorLike(err) {
3729
+ if (err == null || typeof err !== "object") return false;
3730
+ return typeof err.code === "number";
3731
+ }
3732
+ function sleep2(ms, signal) {
3733
+ return new Promise((resolve, reject) => {
3734
+ if (signal?.aborted) {
3735
+ reject(new CompliancePollError("compliance poll aborted", "unknown"));
3736
+ return;
3737
+ }
3738
+ const timer = setTimeout(() => {
3739
+ signal?.removeEventListener("abort", onAbort);
3740
+ resolve();
3741
+ }, ms);
3742
+ const onAbort = () => {
3743
+ clearTimeout(timer);
3744
+ signal?.removeEventListener("abort", onAbort);
3745
+ reject(new CompliancePollError("compliance poll aborted", "unknown"));
3746
+ };
3747
+ signal?.addEventListener("abort", onAbort, { once: true });
3748
+ });
3749
+ }
3750
+
3751
+ // src/sanitize/index.ts
3752
+ var sanitize_exports = {};
3753
+ __export(sanitize_exports, {
3754
+ BlockCodeExecutionToolResult: () => BlockCodeExecutionToolResult,
3755
+ BlockContainerUpload: () => BlockContainerUpload,
3756
+ BlockDeniedError: () => BlockDeniedError,
3757
+ BlockDocument: () => BlockDocument,
3758
+ BlockImage: () => BlockImage,
3759
+ BlockMCPToolResult: () => BlockMCPToolResult,
3760
+ BlockMCPToolUse: () => BlockMCPToolUse,
3761
+ BlockRedactedThinking: () => BlockRedactedThinking,
3762
+ BlockSearchResult: () => BlockSearchResult,
3763
+ BlockServerToolUse: () => BlockServerToolUse,
3764
+ BlockText: () => BlockText,
3765
+ BlockThinking: () => BlockThinking,
3766
+ BlockToolReference: () => BlockToolReference,
3767
+ BlockToolResult: () => BlockToolResult,
3768
+ BlockToolUse: () => BlockToolUse,
3769
+ BlockVideo: () => BlockVideo,
3770
+ BlockWebSearchToolResult: () => BlockWebSearchToolResult,
3771
+ DeltaCitations: () => DeltaCitations,
3772
+ DeltaInputJSON: () => DeltaInputJSON,
3773
+ DeltaSignature: () => DeltaSignature,
3774
+ DeltaText: () => DeltaText,
3775
+ DeltaThinking: () => DeltaThinking,
3776
+ EphemeralMarkerField: () => EphemeralMarkerField,
3777
+ ErrBlockDenied: () => ErrBlockDenied,
3778
+ ErrHistoryTooDeep: () => ErrHistoryTooDeep,
3779
+ HistoryTooDeepError: () => HistoryTooDeepError,
3780
+ SizeError: () => SizeError,
3781
+ dropBlocks: () => dropBlocks,
3782
+ sanitize: () => sanitize,
3783
+ stripEphemeral: () => stripEphemeral
3784
+ });
3785
+
3786
+ // src/sanitize/types.ts
3787
+ var BlockText = "text";
3788
+ var BlockImage = "image";
3789
+ var BlockVideo = "video";
3790
+ var BlockDocument = "document";
3791
+ var BlockSearchResult = "search_result";
3792
+ var BlockThinking = "thinking";
3793
+ var BlockRedactedThinking = "redacted_thinking";
3794
+ var BlockToolUse = "tool_use";
3795
+ var BlockToolResult = "tool_result";
3796
+ var BlockToolReference = "tool_reference";
3797
+ var BlockServerToolUse = "server_tool_use";
3798
+ var BlockWebSearchToolResult = "web_search_tool_result";
3799
+ var BlockCodeExecutionToolResult = "code_execution_tool_result";
3800
+ var BlockMCPToolUse = "mcp_tool_use";
3801
+ var BlockMCPToolResult = "mcp_tool_result";
3802
+ var BlockContainerUpload = "container_upload";
3803
+ var DeltaText = "text_delta";
3804
+ var DeltaInputJSON = "input_json_delta";
3805
+ var DeltaThinking = "thinking_delta";
3806
+ var DeltaSignature = "signature_delta";
3807
+ var DeltaCitations = "citations_delta";
3808
+ var EphemeralMarkerField = "acosmi_ephemeral";
3809
+
3810
+ // src/sanitize/config.ts
3811
+ var HistoryTooDeepError = class extends Error {
3812
+ constructor() {
3813
+ super("sanitize: messages history exceeds configured depth");
3814
+ this.name = "HistoryTooDeepError";
3815
+ }
3816
+ };
3817
+ var BlockDeniedError = class extends Error {
3818
+ constructor() {
3819
+ super("sanitize: block type permanently denied");
3820
+ this.name = "BlockDeniedError";
3821
+ }
3822
+ };
3823
+ var SizeError = class extends Error {
3824
+ blockType;
3825
+ actual;
3826
+ limit;
3827
+ constructor(blockType, actual, limit) {
3828
+ super(`sanitize: ${blockType} base64 size ${actual} exceeds limit ${limit}`);
3829
+ this.name = "SizeError";
3830
+ this.blockType = blockType;
3831
+ this.actual = actual;
3832
+ this.limit = limit;
3833
+ }
3834
+ };
3835
+ var ErrHistoryTooDeep = new HistoryTooDeepError();
3836
+ var ErrBlockDenied = new BlockDeniedError();
3837
+
3838
+ // src/sanitize/history.ts
3839
+ function dropBlocks(messages, pred) {
3840
+ const droppedToolUseIDs = collectDroppedToolUseIDs(messages, pred);
3841
+ const out = [];
3842
+ for (const msg of messages) {
3843
+ if (!isPlainObject(msg)) {
3844
+ out.push(msg);
3845
+ continue;
3846
+ }
3847
+ const content = msg["content"];
3848
+ if (!Array.isArray(content)) {
3849
+ out.push(msg);
3850
+ continue;
3851
+ }
3852
+ const { kept, changed } = filterBlocks(content, pred, droppedToolUseIDs);
3853
+ if (!changed) {
3854
+ out.push(msg);
3855
+ continue;
3856
+ }
3857
+ if (kept.length === 0) {
3858
+ continue;
3859
+ }
3860
+ const newMsg = { ...msg };
3861
+ newMsg["content"] = kept;
3862
+ out.push(newMsg);
3863
+ }
3864
+ return out;
3865
+ }
3866
+ function collectDroppedToolUseIDs(messages, pred) {
3867
+ const ids = /* @__PURE__ */ new Set();
3868
+ for (const msg of messages) {
3869
+ if (!isPlainObject(msg)) continue;
3870
+ const content = msg["content"];
3871
+ if (!Array.isArray(content)) continue;
3872
+ for (const raw of content) {
3873
+ if (!isPlainObject(raw)) continue;
3874
+ if (!pred(raw)) continue;
3875
+ const t = raw["type"];
3876
+ if (typeof t !== "string") continue;
3877
+ if (t === "tool_use" || t === "server_tool_use" || t === "mcp_tool_use") {
3878
+ const id = raw["id"];
3879
+ if (typeof id === "string" && id !== "") ids.add(id);
3880
+ }
3881
+ }
3882
+ }
3883
+ return ids;
3884
+ }
3885
+ function filterBlocks(content, pred, droppedToolUseIDs) {
3886
+ const kept = [];
3887
+ let changed = false;
3888
+ for (const raw of content) {
3889
+ if (!isPlainObject(raw)) {
3890
+ kept.push(raw);
3891
+ continue;
3892
+ }
3893
+ if (pred(raw)) {
3894
+ changed = true;
3895
+ continue;
3896
+ }
3897
+ if (droppedToolUseIDs.size > 0) {
3898
+ const t = raw["type"];
3899
+ if (t === "tool_result" || t === "mcp_tool_result") {
3900
+ const id = raw["tool_use_id"];
3901
+ if (typeof id === "string" && id !== "" && droppedToolUseIDs.has(id)) {
3902
+ changed = true;
3903
+ continue;
3904
+ }
3905
+ }
3906
+ }
3907
+ kept.push(raw);
3908
+ }
3909
+ return { kept, changed };
3910
+ }
3911
+ function stripEphemeral(messages) {
3912
+ return dropBlocks(messages, (b) => {
3913
+ const t = b["type"];
3914
+ if (t === "thinking" || t === "redacted_thinking") {
3915
+ return false;
3916
+ }
3917
+ const v = b[EphemeralMarkerField];
3918
+ return v === true;
3919
+ });
3920
+ }
3921
+ function isPlainObject(v) {
3922
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3923
+ }
3924
+
3925
+ // src/sanitize/defensive.ts
3926
+ function sanitize(messages, cfg) {
3927
+ if ((cfg.maxMessagesTurns ?? 0) > 0 && messages.length > cfg.maxMessagesTurns) {
3928
+ throw ErrHistoryTooDeep;
3929
+ }
3930
+ if ((cfg.maxImageBytes ?? 0) > 0 || (cfg.maxVideoBytes ?? 0) > 0 || (cfg.maxPDFBytes ?? 0) > 0) {
3931
+ checkMediaSizes(messages, cfg);
3932
+ }
3933
+ if (cfg.permanentDenyBlocks && cfg.permanentDenyBlocks.length > 0) {
3934
+ const denySet = /* @__PURE__ */ new Set();
3935
+ for (const bt of cfg.permanentDenyBlocks) denySet.add(bt);
3936
+ messages = dropBlocks(messages, (b) => {
3937
+ const t = b["type"];
3938
+ return typeof t === "string" && denySet.has(t);
3939
+ });
3940
+ }
3941
+ return messages;
3942
+ }
3943
+ function checkMediaSizes(messages, cfg) {
3944
+ for (const msg of messages) {
3945
+ if (!isPlainObject2(msg)) continue;
3946
+ const content = msg["content"];
3947
+ if (!Array.isArray(content)) continue;
3948
+ for (const raw of content) {
3949
+ if (!isPlainObject2(raw)) continue;
3950
+ const bt = raw["type"];
3951
+ if (typeof bt !== "string") continue;
3952
+ let limit = 0;
3953
+ switch (bt) {
3954
+ case "image":
3955
+ limit = cfg.maxImageBytes ?? 0;
3956
+ break;
3957
+ case "video":
3958
+ limit = cfg.maxVideoBytes ?? 0;
3959
+ break;
3960
+ case "document":
3961
+ limit = cfg.maxPDFBytes ?? 0;
3962
+ break;
3963
+ default:
3964
+ continue;
3965
+ }
3966
+ if (limit <= 0) continue;
3967
+ const data = extractBase64Data(raw);
3968
+ if (data === "") continue;
3969
+ const actual = base64DecodedLen(data);
3970
+ if (actual > limit) {
3971
+ throw new SizeError(bt, actual, limit);
3972
+ }
3973
+ }
3974
+ }
3975
+ }
3976
+ function extractBase64Data(block) {
3977
+ const src = block["source"];
3978
+ if (!isPlainObject2(src)) return "";
3979
+ if (src["type"] !== "base64") return "";
3980
+ const dataRaw = src["data"];
3981
+ if (typeof dataRaw !== "string") return "";
3982
+ let data = dataRaw;
3983
+ const i = data.indexOf("base64,");
3984
+ if (i >= 0) {
3985
+ data = data.slice(i + "base64,".length);
3986
+ }
3987
+ return data;
3988
+ }
3989
+ function base64DecodedLen(b64) {
3990
+ const n = b64.length;
3991
+ let pad = 0;
3992
+ if (n >= 1 && b64[n - 1] === "=") pad++;
3993
+ if (n >= 2 && b64[n - 2] === "=") pad++;
3994
+ return Math.floor(n * 3 / 4) - pad;
3995
+ }
3996
+ function isPlainObject2(v) {
3997
+ return typeof v === "object" && v !== null && !Array.isArray(v);
3998
+ }
3999
+
4000
+ // src/agent-runs-types.ts
4001
+ var AgentRunStreamError = class extends Error {
4002
+ event;
4003
+ code;
4004
+ stage;
4005
+ retryable;
4006
+ constructor(event) {
4007
+ const err = event.error;
4008
+ super(err.stage ? `agent run failed: ${err.stage}: ${err.message}` : `agent run failed: ${err.message}`);
4009
+ this.name = "AgentRunStreamError";
4010
+ this.event = event;
4011
+ this.code = err.code ?? "";
4012
+ this.stage = err.stage ?? "";
4013
+ this.retryable = err.retryable ?? false;
4014
+ }
4015
+ };
4016
+
4017
+ // src/client/agent-runs.ts
4018
+ init_types();
3332
4019
  var agentRunsByClient = /* @__PURE__ */ new WeakMap();
3333
4020
  Object.defineProperty(Client.prototype, "agentRuns", {
3334
4021
  configurable: true,
@@ -4636,12 +5323,29 @@ Client.prototype.getBugReport = async function(bugID, signal) {
4636
5323
  exports.AgentRunStreamError = AgentRunStreamError;
4637
5324
  exports.AgentRunsClient = AgentRunsClient;
4638
5325
  exports.Client = Client;
5326
+ exports.ComplianceClient = ComplianceClient;
5327
+ exports.CompliancePollError = CompliancePollError;
4639
5328
  exports.DefaultRetryPolicy = DefaultRetryPolicy;
4640
5329
  exports.ErrAuthDenied = ErrAuthDenied;
5330
+ exports.ErrBillingCallbackCannotCommit = ErrBillingCallbackCannotCommit;
5331
+ exports.ErrBillingCommitRequiresLocalVerify = ErrBillingCommitRequiresLocalVerify;
5332
+ exports.ErrBillingS2sForbidden = ErrBillingS2sForbidden;
4641
5333
  exports.ErrBrowserOpen = ErrBrowserOpen;
5334
+ exports.ErrComplianceStepUpRequired = ErrComplianceStepUpRequired;
4642
5335
  exports.ErrDiscovery = ErrDiscovery;
5336
+ exports.ErrEnvelopeGateClosed = ErrEnvelopeGateClosed;
5337
+ exports.ErrProviderNotConfigured = ErrProviderNotConfigured;
5338
+ exports.ErrProviderUnknownNoRetry = ErrProviderUnknownNoRetry;
4643
5339
  exports.ErrRegistration = ErrRegistration;
4644
5340
  exports.ErrSSLProxy = ErrSSLProxy;
5341
+ exports.ErrSealApprovalContractHashMismatch = ErrSealApprovalContractHashMismatch;
5342
+ exports.ErrSealApprovalExpired = ErrSealApprovalExpired;
5343
+ exports.ErrSealApprovalLocationMismatch = ErrSealApprovalLocationMismatch;
5344
+ exports.ErrSealApprovalNonceUsed = ErrSealApprovalNonceUsed;
5345
+ exports.ErrSealApprovalNotApproved = ErrSealApprovalNotApproved;
5346
+ exports.ErrSealApprovalSealMismatch = ErrSealApprovalSealMismatch;
5347
+ exports.ErrSealApprovalTransactorMismatch = ErrSealApprovalTransactorMismatch;
5348
+ exports.ErrSealUseAlreadyConsumed = ErrSealUseAlreadyConsumed;
4645
5349
  exports.ErrTimeout = ErrTimeout;
4646
5350
  exports.ErrTokenExchange = ErrTokenExchange;
4647
5351
  exports.EventAuthURL = EventAuthURL;
@@ -4661,6 +5365,18 @@ exports.InMemoryTokenStore = InMemoryTokenStore;
4661
5365
  exports.LocalStorageTokenStore = LocalStorageTokenStore;
4662
5366
  exports.ScopeAI = ScopeAI;
4663
5367
  exports.ScopeAccount = ScopeAccount;
5368
+ exports.ScopeComplianceContractSigningRead = ScopeComplianceContractSigningRead;
5369
+ exports.ScopeComplianceContractSigningWrite = ScopeComplianceContractSigningWrite;
5370
+ exports.ScopeComplianceEvidenceRead = ScopeComplianceEvidenceRead;
5371
+ exports.ScopeComplianceEvidenceWrite = ScopeComplianceEvidenceWrite;
5372
+ exports.ScopeComplianceReportsPublish = ScopeComplianceReportsPublish;
5373
+ exports.ScopeComplianceReportsRead = ScopeComplianceReportsRead;
5374
+ exports.ScopeComplianceSealApprovalApprove = ScopeComplianceSealApprovalApprove;
5375
+ exports.ScopeComplianceSealApprovalRequest = ScopeComplianceSealApprovalRequest;
5376
+ exports.ScopeComplianceSealManage = ScopeComplianceSealManage;
5377
+ exports.ScopeComplianceSealUseExecute = ScopeComplianceSealUseExecute;
5378
+ exports.ScopeComplianceTimestampIssue = ScopeComplianceTimestampIssue;
5379
+ exports.ScopeComplianceTimestampVerify = ScopeComplianceTimestampVerify;
4664
5380
  exports.ScopeEntitlements = ScopeEntitlements;
4665
5381
  exports.ScopeModels = ScopeModels;
4666
5382
  exports.ScopeModelsChat = ScopeModelsChat;
@@ -4682,7 +5398,9 @@ exports.authorize = authorize;
4682
5398
  exports.bucketInfoIsCommercial = bucketInfoIsCommercial;
4683
5399
  exports.bucketRowIsCommercial = bucketRowIsCommercial;
4684
5400
  exports.buildBetas = buildBetas;
5401
+ exports.classifyComplianceError = classifyComplianceError;
4685
5402
  exports.commerceScopes = commerceScopes;
5403
+ exports.complianceScopes = complianceScopes;
4686
5404
  exports.computeBackoff = computeBackoff;
4687
5405
  exports.defaultRetryable = defaultRetryable;
4688
5406
  exports.defaultSafeToRetry = defaultSafeToRetry;
@@ -4695,6 +5413,9 @@ exports.findDesktopVisualUnderstandingModel = findDesktopVisualUnderstandingMode
4695
5413
  exports.findFirstModelByInputModality = findFirstModelByInputModality;
4696
5414
  exports.getAdapter = getAdapter;
4697
5415
  exports.getAdapterForModel = getAdapterForModel;
5416
+ exports.isBillingConfirmable = isBillingConfirmable;
5417
+ exports.isComplianceBusinessError = isComplianceBusinessError;
5418
+ exports.isComplianceTerminalError = isComplianceTerminalError;
4698
5419
  exports.isSSLError = isSSLError;
4699
5420
  exports.modelScopes = modelScopes;
4700
5421
  exports.modelSupportsImageInput = modelSupportsImageInput;