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