@acosmi/sdk-ts 2.4.0 → 2.6.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/CHANGELOG.md +77 -0
- package/README.md +40 -12
- package/dist/browser/index.mjs +293 -77
- package/dist/browser/index.mjs.map +1 -1
- package/dist/index.mjs +293 -77
- package/dist/index.mjs.map +1 -1
- package/dist/node/adapters/anthropic.cjs +13 -0
- package/dist/node/adapters/anthropic.cjs.map +1 -1
- package/dist/node/adapters/anthropic.d.cts +1 -1
- package/dist/node/adapters/anthropic.d.ts +1 -1
- package/dist/node/adapters/anthropic.mjs +13 -0
- package/dist/node/adapters/anthropic.mjs.map +1 -1
- package/dist/node/adapters/openai.cjs +17 -3
- package/dist/node/adapters/openai.cjs.map +1 -1
- package/dist/node/adapters/openai.d.cts +2 -2
- package/dist/node/adapters/openai.d.ts +2 -2
- package/dist/node/adapters/openai.mjs +17 -3
- package/dist/node/adapters/openai.mjs.map +1 -1
- package/dist/node/{index-CI7FM3xe.d.cts → index-BrbgHn0E.d.cts} +19 -1
- package/dist/node/{index-CI7FM3xe.d.ts → index-BrbgHn0E.d.ts} +19 -1
- package/dist/node/index.cjs +300 -76
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +254 -72
- package/dist/node/index.d.ts +254 -72
- package/dist/node/index.mjs +293 -77
- package/dist/node/index.mjs.map +1 -1
- package/dist/node/{openai-xKHChcmG.d.cts → openai-CeM2k04b.d.cts} +4 -1
- package/dist/node/{openai-oeY7dGNW.d.ts → openai-DoPpzZmv.d.ts} +4 -1
- package/docs//345/274/200/345/217/221/344/270/216/345/217/221/345/270/203/346/211/213/345/206/214.md +27 -5
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -320,13 +320,20 @@ function resolveThinkingLevel(body, req, caps) {
|
|
|
320
320
|
}
|
|
321
321
|
delete body["temperature"];
|
|
322
322
|
}
|
|
323
|
-
var AnthropicAdapter;
|
|
323
|
+
var ANTHROPIC_SDK_MANAGED_BODY_KEYS, AnthropicAdapter;
|
|
324
324
|
var init_anthropic = __esm({
|
|
325
325
|
"src/models/adapters/anthropic.ts"() {
|
|
326
326
|
init_types();
|
|
327
327
|
init_errors();
|
|
328
328
|
init_betas();
|
|
329
329
|
init_adapters();
|
|
330
|
+
ANTHROPIC_SDK_MANAGED_BODY_KEYS = /* @__PURE__ */ new Set([
|
|
331
|
+
"thinking",
|
|
332
|
+
"effort",
|
|
333
|
+
"max_tokens",
|
|
334
|
+
"temperature",
|
|
335
|
+
"betas"
|
|
336
|
+
]);
|
|
330
337
|
AnthropicAdapter = class {
|
|
331
338
|
format() {
|
|
332
339
|
return 0 /* Anthropic */;
|
|
@@ -414,6 +421,12 @@ var init_anthropic = __esm({
|
|
|
414
421
|
}
|
|
415
422
|
if (req.extraBody) {
|
|
416
423
|
for (const [k, v] of Object.entries(req.extraBody)) {
|
|
424
|
+
if (ANTHROPIC_SDK_MANAGED_BODY_KEYS.has(k)) {
|
|
425
|
+
console.warn(
|
|
426
|
+
`acosmi-sdk: extraBody key "${k}" is SDK-managed and was ignored (use the dedicated request field instead).`
|
|
427
|
+
);
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
417
430
|
body[k] = v;
|
|
418
431
|
}
|
|
419
432
|
}
|
|
@@ -773,6 +786,9 @@ var init_openai = __esm({
|
|
|
773
786
|
messageStarted = false;
|
|
774
787
|
thinkingStarted = false;
|
|
775
788
|
thinkingStopped = false;
|
|
789
|
+
/** thinking block 打开时占用的 Anthropic block index — 关闭时必须用它, 不能用
|
|
790
|
+
* 可能已被 text/tool 推进的 this.blockIndex (否则 content_block_stop 索引错配)。 */
|
|
791
|
+
thinkingBlockIndex = 0;
|
|
776
792
|
textStarted = false;
|
|
777
793
|
/** OpenAI tool_call index → Anthropic block index */
|
|
778
794
|
toolBlockIndex = /* @__PURE__ */ new Map();
|
|
@@ -813,6 +829,7 @@ var init_openai = __esm({
|
|
|
813
829
|
if (choice.delta.reasoning_content && choice.delta.reasoning_content !== "") {
|
|
814
830
|
if (!this.thinkingStarted) {
|
|
815
831
|
this.thinkingStarted = true;
|
|
832
|
+
this.thinkingBlockIndex = this.blockIndex;
|
|
816
833
|
const blockJSON = JSON.stringify({
|
|
817
834
|
type: "content_block_start",
|
|
818
835
|
index: this.blockIndex,
|
|
@@ -822,7 +839,7 @@ var init_openai = __esm({
|
|
|
822
839
|
}
|
|
823
840
|
const deltaJSON = JSON.stringify({
|
|
824
841
|
type: "content_block_delta",
|
|
825
|
-
index: this.
|
|
842
|
+
index: this.thinkingBlockIndex,
|
|
826
843
|
delta: { type: "thinking_delta", thinking: choice.delta.reasoning_content }
|
|
827
844
|
});
|
|
828
845
|
events.push({ event: "content_block_delta", data: deltaJSON });
|
|
@@ -832,7 +849,7 @@ var init_openai = __esm({
|
|
|
832
849
|
this.thinkingStopped = true;
|
|
833
850
|
const stopJSON = JSON.stringify({
|
|
834
851
|
type: "content_block_stop",
|
|
835
|
-
index: this.
|
|
852
|
+
index: this.thinkingBlockIndex
|
|
836
853
|
});
|
|
837
854
|
events.push({ event: "content_block_stop", data: stopJSON });
|
|
838
855
|
this.blockIndex++;
|
|
@@ -855,6 +872,15 @@ var init_openai = __esm({
|
|
|
855
872
|
}
|
|
856
873
|
for (const tc of choice.delta.tool_calls ?? []) {
|
|
857
874
|
if (!this.toolBlockIndex.has(tc.index)) {
|
|
875
|
+
if (this.thinkingStarted && !this.thinkingStopped) {
|
|
876
|
+
this.thinkingStopped = true;
|
|
877
|
+
const stopJSON = JSON.stringify({
|
|
878
|
+
type: "content_block_stop",
|
|
879
|
+
index: this.thinkingBlockIndex
|
|
880
|
+
});
|
|
881
|
+
events.push({ event: "content_block_stop", data: stopJSON });
|
|
882
|
+
this.blockIndex++;
|
|
883
|
+
}
|
|
858
884
|
if (this.textStarted) {
|
|
859
885
|
const stopJSON = JSON.stringify({
|
|
860
886
|
type: "content_block_stop",
|
|
@@ -899,9 +925,10 @@ var init_openai = __esm({
|
|
|
899
925
|
});
|
|
900
926
|
events.push({ event: "content_block_stop", data: stopJSON2 });
|
|
901
927
|
} else if (this.thinkingStarted && !this.thinkingStopped) {
|
|
928
|
+
this.thinkingStopped = true;
|
|
902
929
|
const stopJSON2 = JSON.stringify({
|
|
903
930
|
type: "content_block_stop",
|
|
904
|
-
index: this.
|
|
931
|
+
index: this.thinkingBlockIndex
|
|
905
932
|
});
|
|
906
933
|
events.push({ event: "content_block_stop", data: stopJSON2 });
|
|
907
934
|
}
|
|
@@ -942,13 +969,6 @@ function getAdapter(provider) {
|
|
|
942
969
|
return defaultOpenAIAdapter;
|
|
943
970
|
}
|
|
944
971
|
function getAdapterForModel(m) {
|
|
945
|
-
const pref = (m.preferred_format ?? "").trim().toLowerCase();
|
|
946
|
-
switch (pref) {
|
|
947
|
-
case "anthropic":
|
|
948
|
-
return new AnthropicAdapter();
|
|
949
|
-
case "openai":
|
|
950
|
-
return new OpenAIAdapter();
|
|
951
|
-
}
|
|
952
972
|
let hasAnthropic = false;
|
|
953
973
|
let hasOpenAI = false;
|
|
954
974
|
for (const f of m.supported_formats ?? []) {
|
|
@@ -961,6 +981,16 @@ function getAdapterForModel(m) {
|
|
|
961
981
|
break;
|
|
962
982
|
}
|
|
963
983
|
}
|
|
984
|
+
const declared = hasAnthropic || hasOpenAI;
|
|
985
|
+
const pref = (m.preferred_format ?? "").trim().toLowerCase();
|
|
986
|
+
switch (pref) {
|
|
987
|
+
case "anthropic":
|
|
988
|
+
if (!declared || hasAnthropic) return new AnthropicAdapter();
|
|
989
|
+
break;
|
|
990
|
+
case "openai":
|
|
991
|
+
if (!declared || hasOpenAI) return new OpenAIAdapter();
|
|
992
|
+
break;
|
|
993
|
+
}
|
|
964
994
|
if (hasAnthropic) return new AnthropicAdapter();
|
|
965
995
|
if (hasOpenAI) return new OpenAIAdapter();
|
|
966
996
|
return getAdapter((m.provider ?? "").toLowerCase());
|
|
@@ -970,6 +1000,7 @@ var init_adapters = __esm({
|
|
|
970
1000
|
"src/models/adapters/index.ts"() {
|
|
971
1001
|
init_anthropic();
|
|
972
1002
|
init_openai();
|
|
1003
|
+
init_openai();
|
|
973
1004
|
ProviderFormat = /* @__PURE__ */ ((ProviderFormat2) => {
|
|
974
1005
|
ProviderFormat2[ProviderFormat2["Anthropic"] = 0] = "Anthropic";
|
|
975
1006
|
ProviderFormat2[ProviderFormat2["OpenAI"] = 1] = "OpenAI";
|
|
@@ -990,8 +1021,14 @@ init_types();
|
|
|
990
1021
|
// src/auth/types.ts
|
|
991
1022
|
function tokenSetIsExpired(t) {
|
|
992
1023
|
const expiresAt = new Date(t.expires_at).getTime();
|
|
1024
|
+
if (!Number.isFinite(expiresAt)) return true;
|
|
993
1025
|
return Date.now() > expiresAt - 3e4;
|
|
994
1026
|
}
|
|
1027
|
+
function isValidTokenSet(x) {
|
|
1028
|
+
if (typeof x !== "object" || x === null) return false;
|
|
1029
|
+
const t = x;
|
|
1030
|
+
return typeof t.access_token === "string" && typeof t.refresh_token === "string" && typeof t.expires_at === "string" && typeof t.scope === "string" && typeof t.client_id === "string" && typeof t.server_url === "string";
|
|
1031
|
+
}
|
|
995
1032
|
|
|
996
1033
|
// src/core/client.ts
|
|
997
1034
|
init_errors();
|
|
@@ -1025,7 +1062,7 @@ var OAuthTokenEndpointError = class extends Error {
|
|
|
1025
1062
|
function isInvalidGrantError(err) {
|
|
1026
1063
|
return err instanceof OAuthTokenEndpointError && err.oauthError === "invalid_grant";
|
|
1027
1064
|
}
|
|
1028
|
-
async function discoverWithProfile(serverURL, profile, signal) {
|
|
1065
|
+
async function discoverWithProfile(serverURL, profile, signal, fetchImpl = globalThis.fetch) {
|
|
1029
1066
|
let parsed;
|
|
1030
1067
|
try {
|
|
1031
1068
|
parsed = new URL(serverURL.replace(/\/+$/, ""));
|
|
@@ -1037,7 +1074,7 @@ async function discoverWithProfile(serverURL, profile, signal) {
|
|
|
1037
1074
|
const ctl = withTimeout(authTimeoutMs, signal);
|
|
1038
1075
|
let resp;
|
|
1039
1076
|
try {
|
|
1040
|
-
resp = await
|
|
1077
|
+
resp = await fetchImpl(endpoint, { method: "GET", signal: ctl.signal });
|
|
1041
1078
|
} catch (e) {
|
|
1042
1079
|
throw new Error(`discover: ${e instanceof Error ? e.message : String(e)}`);
|
|
1043
1080
|
} finally {
|
|
@@ -1059,13 +1096,13 @@ async function discoverWithProfile(serverURL, profile, signal) {
|
|
|
1059
1096
|
}
|
|
1060
1097
|
return meta;
|
|
1061
1098
|
}
|
|
1062
|
-
async function discover(serverURL, signal) {
|
|
1063
|
-
return discoverWithProfile(serverURL, "desktop", signal);
|
|
1099
|
+
async function discover(serverURL, signal, fetchImpl = globalThis.fetch) {
|
|
1100
|
+
return discoverWithProfile(serverURL, "desktop", signal, fetchImpl);
|
|
1064
1101
|
}
|
|
1065
|
-
async function discoverWebOAuthMetadata(serverURL, signal) {
|
|
1066
|
-
return discoverWithProfile(serverURL, "web", signal);
|
|
1102
|
+
async function discoverWebOAuthMetadata(serverURL, signal, fetchImpl = globalThis.fetch) {
|
|
1103
|
+
return discoverWithProfile(serverURL, "web", signal, fetchImpl);
|
|
1067
1104
|
}
|
|
1068
|
-
async function register(meta, appName, signal) {
|
|
1105
|
+
async function register(meta, appName, signal, fetchImpl = globalThis.fetch) {
|
|
1069
1106
|
const regReq = {
|
|
1070
1107
|
client_name: appName,
|
|
1071
1108
|
token_endpoint_auth_method: "none",
|
|
@@ -1076,7 +1113,7 @@ async function register(meta, appName, signal) {
|
|
|
1076
1113
|
const ctl = withTimeout(authTimeoutMs, signal);
|
|
1077
1114
|
let resp;
|
|
1078
1115
|
try {
|
|
1079
|
-
resp = await
|
|
1116
|
+
resp = await fetchImpl(meta.registration_endpoint, {
|
|
1080
1117
|
method: "POST",
|
|
1081
1118
|
headers: { "Content-Type": "application/json" },
|
|
1082
1119
|
body: JSON.stringify(regReq),
|
|
@@ -1096,7 +1133,7 @@ async function register(meta, appName, signal) {
|
|
|
1096
1133
|
throw new Error(`register: decode: ${e instanceof Error ? e.message : String(e)}`);
|
|
1097
1134
|
}
|
|
1098
1135
|
}
|
|
1099
|
-
async function registerWebOAuthClient(meta, opts, signal) {
|
|
1136
|
+
async function registerWebOAuthClient(meta, opts, signal, fetchImpl = globalThis.fetch) {
|
|
1100
1137
|
const regReq = {
|
|
1101
1138
|
client_name: opts.clientName,
|
|
1102
1139
|
token_endpoint_auth_method: "none",
|
|
@@ -1108,7 +1145,7 @@ async function registerWebOAuthClient(meta, opts, signal) {
|
|
|
1108
1145
|
const ctl = withTimeout(authTimeoutMs, signal);
|
|
1109
1146
|
let resp;
|
|
1110
1147
|
try {
|
|
1111
|
-
resp = await
|
|
1148
|
+
resp = await fetchImpl(meta.registration_endpoint, {
|
|
1112
1149
|
method: "POST",
|
|
1113
1150
|
headers: { "Content-Type": "application/json" },
|
|
1114
1151
|
body: JSON.stringify(regReq),
|
|
@@ -1312,7 +1349,7 @@ async function createWebAuthorizationRequest(meta, opts) {
|
|
|
1312
1349
|
createdAt: Date.now()
|
|
1313
1350
|
};
|
|
1314
1351
|
}
|
|
1315
|
-
async function completeWebAuthorizationRequest(pending, params, signal) {
|
|
1352
|
+
async function completeWebAuthorizationRequest(pending, params, signal, fetchImpl = globalThis.fetch) {
|
|
1316
1353
|
if (!params.code) {
|
|
1317
1354
|
throw new Error("completeWebAuthorizationRequest: missing authorization code");
|
|
1318
1355
|
}
|
|
@@ -1321,18 +1358,19 @@ async function completeWebAuthorizationRequest(pending, params, signal) {
|
|
|
1321
1358
|
`completeWebAuthorizationRequest: ${ErrStateMismatch}: callback state does not match pending state (possible CSRF)`
|
|
1322
1359
|
);
|
|
1323
1360
|
}
|
|
1324
|
-
const meta = await discoverWebOAuthMetadata(pending.serverURL, signal);
|
|
1361
|
+
const meta = await discoverWebOAuthMetadata(pending.serverURL, signal, fetchImpl);
|
|
1325
1362
|
const resp = await exchangeCode(
|
|
1326
1363
|
meta,
|
|
1327
1364
|
pending.clientID,
|
|
1328
1365
|
params.code,
|
|
1329
1366
|
pending.redirectURI,
|
|
1330
1367
|
pending.verifier,
|
|
1331
|
-
signal
|
|
1368
|
+
signal,
|
|
1369
|
+
fetchImpl
|
|
1332
1370
|
);
|
|
1333
1371
|
return newTokenSet(resp, pending.clientID, pending.serverURL);
|
|
1334
1372
|
}
|
|
1335
|
-
async function exchangeCode(meta, clientID, code, redirectURI, codeVerifier, signal) {
|
|
1373
|
+
async function exchangeCode(meta, clientID, code, redirectURI, codeVerifier, signal, fetchImpl = globalThis.fetch) {
|
|
1336
1374
|
const data = new URLSearchParams({
|
|
1337
1375
|
grant_type: "authorization_code",
|
|
1338
1376
|
client_id: clientID,
|
|
@@ -1340,9 +1378,9 @@ async function exchangeCode(meta, clientID, code, redirectURI, codeVerifier, sig
|
|
|
1340
1378
|
redirect_uri: redirectURI,
|
|
1341
1379
|
code_verifier: codeVerifier
|
|
1342
1380
|
});
|
|
1343
|
-
return postToken(meta.token_endpoint, data, signal);
|
|
1381
|
+
return postToken(meta.token_endpoint, data, signal, fetchImpl);
|
|
1344
1382
|
}
|
|
1345
|
-
async function exchangeCodeWithExpiry(meta, clientID, code, redirectURI, codeVerifier, expiresIn, signal) {
|
|
1383
|
+
async function exchangeCodeWithExpiry(meta, clientID, code, redirectURI, codeVerifier, expiresIn, signal, fetchImpl = globalThis.fetch) {
|
|
1346
1384
|
const data = new URLSearchParams({
|
|
1347
1385
|
grant_type: "authorization_code",
|
|
1348
1386
|
client_id: clientID,
|
|
@@ -1351,24 +1389,24 @@ async function exchangeCodeWithExpiry(meta, clientID, code, redirectURI, codeVer
|
|
|
1351
1389
|
code_verifier: codeVerifier,
|
|
1352
1390
|
expires_in: String(expiresIn)
|
|
1353
1391
|
});
|
|
1354
|
-
return postToken(meta.token_endpoint, data, signal);
|
|
1392
|
+
return postToken(meta.token_endpoint, data, signal, fetchImpl);
|
|
1355
1393
|
}
|
|
1356
|
-
async function refreshToken(meta, clientID, refreshTokenValue, signal) {
|
|
1394
|
+
async function refreshToken(meta, clientID, refreshTokenValue, signal, fetchImpl = globalThis.fetch) {
|
|
1357
1395
|
const data = new URLSearchParams({
|
|
1358
1396
|
grant_type: "refresh_token",
|
|
1359
1397
|
client_id: clientID,
|
|
1360
1398
|
refresh_token: refreshTokenValue
|
|
1361
1399
|
});
|
|
1362
|
-
return postToken(meta.token_endpoint, data, signal);
|
|
1400
|
+
return postToken(meta.token_endpoint, data, signal, fetchImpl);
|
|
1363
1401
|
}
|
|
1364
|
-
async function revokeToken(meta, token, signal) {
|
|
1402
|
+
async function revokeToken(meta, token, signal, fetchImpl = globalThis.fetch) {
|
|
1365
1403
|
if (!meta.revocation_endpoint || meta.revocation_endpoint === "") {
|
|
1366
1404
|
return;
|
|
1367
1405
|
}
|
|
1368
1406
|
const data = new URLSearchParams({ token });
|
|
1369
1407
|
const ctl = withTimeout(authTimeoutMs, signal);
|
|
1370
1408
|
try {
|
|
1371
|
-
await
|
|
1409
|
+
await fetchImpl(meta.revocation_endpoint, {
|
|
1372
1410
|
method: "POST",
|
|
1373
1411
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1374
1412
|
body: data,
|
|
@@ -1380,11 +1418,11 @@ async function revokeToken(meta, token, signal) {
|
|
|
1380
1418
|
ctl.dispose();
|
|
1381
1419
|
}
|
|
1382
1420
|
}
|
|
1383
|
-
async function postToken(endpoint, data, signal) {
|
|
1421
|
+
async function postToken(endpoint, data, signal, fetchImpl = globalThis.fetch) {
|
|
1384
1422
|
const ctl = withTimeout(authTimeoutMs, signal);
|
|
1385
1423
|
let resp;
|
|
1386
1424
|
try {
|
|
1387
|
-
resp = await
|
|
1425
|
+
resp = await fetchImpl(endpoint, {
|
|
1388
1426
|
method: "POST",
|
|
1389
1427
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1390
1428
|
body: data,
|
|
@@ -1602,7 +1640,15 @@ ${Date.now()}
|
|
|
1602
1640
|
await fs.mkdir(dir, { recursive: true, mode: 448 });
|
|
1603
1641
|
const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${Math.floor(Math.random() * 1e6)}`;
|
|
1604
1642
|
const data = JSON.stringify(tokens, null, 2);
|
|
1605
|
-
|
|
1643
|
+
{
|
|
1644
|
+
const fh = await fs.open(tmp, "w", 384);
|
|
1645
|
+
try {
|
|
1646
|
+
await fh.writeFile(data, { encoding: "utf8" });
|
|
1647
|
+
await fh.sync();
|
|
1648
|
+
} finally {
|
|
1649
|
+
await fh.close();
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1606
1652
|
try {
|
|
1607
1653
|
await fs.rename(tmp, p);
|
|
1608
1654
|
} catch (e) {
|
|
@@ -1612,6 +1658,15 @@ ${Date.now()}
|
|
|
1612
1658
|
}
|
|
1613
1659
|
throw e;
|
|
1614
1660
|
}
|
|
1661
|
+
try {
|
|
1662
|
+
const dirHandle = await fs.open(dir, "r");
|
|
1663
|
+
try {
|
|
1664
|
+
await dirHandle.sync();
|
|
1665
|
+
} finally {
|
|
1666
|
+
await dirHandle.close();
|
|
1667
|
+
}
|
|
1668
|
+
} catch {
|
|
1669
|
+
}
|
|
1615
1670
|
});
|
|
1616
1671
|
}
|
|
1617
1672
|
load() {
|
|
@@ -1620,7 +1675,14 @@ ${Date.now()}
|
|
|
1620
1675
|
const p = await this.resolvePath();
|
|
1621
1676
|
try {
|
|
1622
1677
|
const data = await fs.readFile(p, "utf8");
|
|
1623
|
-
|
|
1678
|
+
let parsed;
|
|
1679
|
+
try {
|
|
1680
|
+
parsed = JSON.parse(data);
|
|
1681
|
+
} catch {
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
if (!isValidTokenSet(parsed)) return null;
|
|
1685
|
+
return parsed;
|
|
1624
1686
|
} catch (e) {
|
|
1625
1687
|
if (isNotExistError(e)) return null;
|
|
1626
1688
|
throw new Error(
|
|
@@ -1671,11 +1733,14 @@ var LocalStorageTokenStore = class {
|
|
|
1671
1733
|
async load() {
|
|
1672
1734
|
const data = globalThis.localStorage.getItem(this.key);
|
|
1673
1735
|
if (data == null || data === "") return null;
|
|
1736
|
+
let parsed;
|
|
1674
1737
|
try {
|
|
1675
|
-
|
|
1738
|
+
parsed = JSON.parse(data);
|
|
1676
1739
|
} catch {
|
|
1677
1740
|
return null;
|
|
1678
1741
|
}
|
|
1742
|
+
if (!isValidTokenSet(parsed)) return null;
|
|
1743
|
+
return parsed;
|
|
1679
1744
|
}
|
|
1680
1745
|
async clear() {
|
|
1681
1746
|
globalThis.localStorage.removeItem(this.key);
|
|
@@ -2044,6 +2109,32 @@ function normalizeGatewayBaseURL(input) {
|
|
|
2044
2109
|
const path = parsed.pathname.replace(/\/+$/, "");
|
|
2045
2110
|
return path ? `${parsed.origin}${path}` : parsed.origin;
|
|
2046
2111
|
}
|
|
2112
|
+
function normalizeOverrideBaseURL(raw, label) {
|
|
2113
|
+
if (typeof raw !== "string") {
|
|
2114
|
+
throw new TypeError(`${label} must be a string`);
|
|
2115
|
+
}
|
|
2116
|
+
const trimmed = raw.trim();
|
|
2117
|
+
if (trimmed.length === 0) {
|
|
2118
|
+
throw new Error(`${label} is empty`);
|
|
2119
|
+
}
|
|
2120
|
+
let parsed;
|
|
2121
|
+
try {
|
|
2122
|
+
parsed = new URL(trimmed);
|
|
2123
|
+
} catch {
|
|
2124
|
+
throw new Error(`${label} is not a valid URL: ${trimmed}`);
|
|
2125
|
+
}
|
|
2126
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
2127
|
+
throw new Error(`${label} only allows http/https, got ${parsed.protocol} (${trimmed})`);
|
|
2128
|
+
}
|
|
2129
|
+
if (!parsed.host) {
|
|
2130
|
+
throw new Error(`${label} has empty host: ${trimmed}`);
|
|
2131
|
+
}
|
|
2132
|
+
if (parsed.search.length > 0 || parsed.hash.length > 0) {
|
|
2133
|
+
throw new Error(`${label} must not contain query or hash: ${trimmed}`);
|
|
2134
|
+
}
|
|
2135
|
+
const path = parsed.pathname.replace(/\/+$/, "");
|
|
2136
|
+
return path ? `${parsed.origin}${path}` : parsed.origin;
|
|
2137
|
+
}
|
|
2047
2138
|
function pickAndNormalizeGatewayURL(cfg) {
|
|
2048
2139
|
const inputs = [];
|
|
2049
2140
|
if (cfg.serverURL !== void 0) inputs.push(["serverURL", cfg.serverURL]);
|
|
@@ -2064,6 +2155,7 @@ var ErrOAuthCORSBlocked = "oauth_cors_blocked";
|
|
|
2064
2155
|
var ErrRefreshProxyFailed = "refresh_proxy_failed";
|
|
2065
2156
|
var ErrTokenExpired = "token_expired";
|
|
2066
2157
|
var CHAT_REQUEST_TIMEOUT_MS = 11 * 60 * 1e3;
|
|
2158
|
+
var DEFAULT_API_TIMEOUT_MS = 6e4;
|
|
2067
2159
|
function newDeferred() {
|
|
2068
2160
|
let resolve;
|
|
2069
2161
|
let reject;
|
|
@@ -2121,8 +2213,8 @@ var Client = class _Client {
|
|
|
2121
2213
|
constructor(cfg = {}) {
|
|
2122
2214
|
const picked = pickAndNormalizeGatewayURL(cfg);
|
|
2123
2215
|
this.serverURL = picked ?? DEFAULT_GATEWAY_BASE_URL;
|
|
2124
|
-
this.complianceBaseURL = cfg.complianceBaseURL ? cfg.complianceBaseURL
|
|
2125
|
-
this.apiBaseURL = cfg.apiBaseURL ? cfg.apiBaseURL
|
|
2216
|
+
this.complianceBaseURL = cfg.complianceBaseURL ? normalizeOverrideBaseURL(cfg.complianceBaseURL, "complianceBaseURL") : null;
|
|
2217
|
+
this.apiBaseURL = cfg.apiBaseURL ? normalizeOverrideBaseURL(cfg.apiBaseURL, "apiBaseURL") : null;
|
|
2126
2218
|
this.oauthMetadataProfile = cfg.oauthMetadataProfile ?? "desktop";
|
|
2127
2219
|
this.browserRefreshMode = cfg.browserRefreshMode ?? "direct";
|
|
2128
2220
|
this.refreshProxyURL = cfg.refreshProxyURL ?? null;
|
|
@@ -2214,7 +2306,7 @@ var Client = class _Client {
|
|
|
2214
2306
|
try {
|
|
2215
2307
|
let meta;
|
|
2216
2308
|
try {
|
|
2217
|
-
meta = await discover(this.serverURL, signal);
|
|
2309
|
+
meta = await discover(this.serverURL, signal, this.fetchImpl);
|
|
2218
2310
|
} catch (err) {
|
|
2219
2311
|
emitError(ErrDiscovery, err);
|
|
2220
2312
|
throw new Error(`discovery failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -2223,7 +2315,7 @@ var Client = class _Client {
|
|
|
2223
2315
|
let clientID = this.getCachedClientID();
|
|
2224
2316
|
if (clientID === "") {
|
|
2225
2317
|
try {
|
|
2226
|
-
const reg = await register(meta, appName, signal);
|
|
2318
|
+
const reg = await register(meta, appName, signal, this.fetchImpl);
|
|
2227
2319
|
clientID = reg.client_id;
|
|
2228
2320
|
} catch (err) {
|
|
2229
2321
|
emitError(ErrRegistration, err);
|
|
@@ -2240,7 +2332,7 @@ var Client = class _Client {
|
|
|
2240
2332
|
verifier = r.verifier;
|
|
2241
2333
|
} catch (err) {
|
|
2242
2334
|
try {
|
|
2243
|
-
const reg = await register(meta, appName, signal);
|
|
2335
|
+
const reg = await register(meta, appName, signal, this.fetchImpl);
|
|
2244
2336
|
clientID = reg.client_id;
|
|
2245
2337
|
} catch (regErr) {
|
|
2246
2338
|
emitError(ErrRegistration, regErr);
|
|
@@ -2268,7 +2360,8 @@ var Client = class _Client {
|
|
|
2268
2360
|
result.redirectURI,
|
|
2269
2361
|
verifier,
|
|
2270
2362
|
opts.expiresIn,
|
|
2271
|
-
signal
|
|
2363
|
+
signal,
|
|
2364
|
+
this.fetchImpl
|
|
2272
2365
|
);
|
|
2273
2366
|
} else {
|
|
2274
2367
|
tokenResp = await exchangeCode(
|
|
@@ -2277,7 +2370,8 @@ var Client = class _Client {
|
|
|
2277
2370
|
result.code,
|
|
2278
2371
|
result.redirectURI,
|
|
2279
2372
|
verifier,
|
|
2280
|
-
signal
|
|
2373
|
+
signal,
|
|
2374
|
+
this.fetchImpl
|
|
2281
2375
|
);
|
|
2282
2376
|
}
|
|
2283
2377
|
} catch (err) {
|
|
@@ -2314,18 +2408,18 @@ var Client = class _Client {
|
|
|
2314
2408
|
if (tokens) {
|
|
2315
2409
|
if (!meta) {
|
|
2316
2410
|
try {
|
|
2317
|
-
meta = await discoverWithProfile(this.serverURL, this.oauthMetadataProfile, signal);
|
|
2411
|
+
meta = await discoverWithProfile(this.serverURL, this.oauthMetadataProfile, signal, this.fetchImpl);
|
|
2318
2412
|
} catch (e) {
|
|
2319
2413
|
console.warn(`[acosmi-sdk] warning: discover for revocation failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
2320
2414
|
}
|
|
2321
2415
|
}
|
|
2322
2416
|
if (meta) {
|
|
2323
2417
|
try {
|
|
2324
|
-
await revokeToken(meta, tokens.access_token, signal);
|
|
2418
|
+
await revokeToken(meta, tokens.access_token, signal, this.fetchImpl);
|
|
2325
2419
|
} catch {
|
|
2326
2420
|
}
|
|
2327
2421
|
try {
|
|
2328
|
-
await revokeToken(meta, tokens.refresh_token, signal);
|
|
2422
|
+
await revokeToken(meta, tokens.refresh_token, signal, this.fetchImpl);
|
|
2329
2423
|
} catch {
|
|
2330
2424
|
}
|
|
2331
2425
|
}
|
|
@@ -2419,7 +2513,7 @@ var Client = class _Client {
|
|
|
2419
2513
|
}
|
|
2420
2514
|
if (this.meta == null) {
|
|
2421
2515
|
try {
|
|
2422
|
-
this.meta = await discoverWithProfile(this.serverURL, this.oauthMetadataProfile, signal);
|
|
2516
|
+
this.meta = await discoverWithProfile(this.serverURL, this.oauthMetadataProfile, signal, this.fetchImpl);
|
|
2423
2517
|
} catch (e) {
|
|
2424
2518
|
throw new Error(
|
|
2425
2519
|
`discover for refresh: ${e instanceof Error ? e.message : String(e)}`
|
|
@@ -2432,7 +2526,8 @@ var Client = class _Client {
|
|
|
2432
2526
|
this.meta,
|
|
2433
2527
|
this.tokens.client_id,
|
|
2434
2528
|
this.tokens.refresh_token,
|
|
2435
|
-
signal
|
|
2529
|
+
signal,
|
|
2530
|
+
this.fetchImpl
|
|
2436
2531
|
);
|
|
2437
2532
|
} catch (e) {
|
|
2438
2533
|
const message = e instanceof Error ? e.message : String(e);
|
|
@@ -2699,10 +2794,10 @@ var Client = class _Client {
|
|
|
2699
2794
|
* v0.5.0: 根据 provider 自动路由到 /anthropic 或 /chat 端点
|
|
2700
2795
|
*/
|
|
2701
2796
|
async chat(modelID, req, signal) {
|
|
2702
|
-
req
|
|
2797
|
+
const r = { ...req, stream: false };
|
|
2703
2798
|
const ctl = withRequestTimeout(CHAT_REQUEST_TIMEOUT_MS, signal);
|
|
2704
2799
|
try {
|
|
2705
|
-
const { body, adapter } = await this.buildChatRequest(modelID,
|
|
2800
|
+
const { body, adapter } = await this.buildChatRequest(modelID, r, ctl.signal);
|
|
2706
2801
|
const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
|
|
2707
2802
|
const { result, headers } = await this.doJSONFullRaw("POST", endpoint, body, ctl.signal);
|
|
2708
2803
|
const resp = adapter.parseResponse(result);
|
|
@@ -2800,11 +2895,11 @@ var Client = class _Client {
|
|
|
2800
2895
|
return this.chatMessagesOpenAI(modelID, req, adapter, signal);
|
|
2801
2896
|
}
|
|
2802
2897
|
async chatMessagesAnthropic(modelID, req, adapter, signal) {
|
|
2803
|
-
req
|
|
2898
|
+
const r = { ...req, stream: false };
|
|
2804
2899
|
const ctl = withRequestTimeout(CHAT_REQUEST_TIMEOUT_MS, signal);
|
|
2805
2900
|
try {
|
|
2806
2901
|
const caps = this.getCachedCapabilities(modelID) ?? zeroModelCapabilities();
|
|
2807
|
-
const body = adapter.buildRequestBody(caps,
|
|
2902
|
+
const body = adapter.buildRequestBody(caps, r);
|
|
2808
2903
|
const data = JSON.stringify(body);
|
|
2809
2904
|
const { result } = await this.doJSONFullRaw(
|
|
2810
2905
|
"POST",
|
|
@@ -2837,11 +2932,11 @@ var Client = class _Client {
|
|
|
2837
2932
|
}
|
|
2838
2933
|
}
|
|
2839
2934
|
async chatMessagesOpenAI(modelID, req, adapter, signal) {
|
|
2840
|
-
req
|
|
2935
|
+
const r = { ...req, stream: false };
|
|
2841
2936
|
const ctl = withRequestTimeout(CHAT_REQUEST_TIMEOUT_MS, signal);
|
|
2842
2937
|
try {
|
|
2843
2938
|
const caps = this.getCachedCapabilities(modelID) ?? zeroModelCapabilities();
|
|
2844
|
-
const body = adapter.buildRequestBody(caps,
|
|
2939
|
+
const body = adapter.buildRequestBody(caps, r);
|
|
2845
2940
|
const data = JSON.stringify(body);
|
|
2846
2941
|
const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
|
|
2847
2942
|
const { result } = await this.doJSONFullRaw("POST", endpoint, data, ctl.signal);
|
|
@@ -2871,8 +2966,8 @@ var Client = class _Client {
|
|
|
2871
2966
|
};
|
|
2872
2967
|
}
|
|
2873
2968
|
async *chatStreamGen(modelID, req, signal, retried) {
|
|
2874
|
-
req
|
|
2875
|
-
const { body, adapter } = await this.buildChatRequest(modelID,
|
|
2969
|
+
const r = { ...req, stream: true };
|
|
2970
|
+
const { body, adapter } = await this.buildChatRequest(modelID, r, signal);
|
|
2876
2971
|
const token = await this.ensureToken(signal);
|
|
2877
2972
|
const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
|
|
2878
2973
|
const url = this.apiURL(endpoint);
|
|
@@ -2940,8 +3035,8 @@ var Client = class _Client {
|
|
|
2940
3035
|
}
|
|
2941
3036
|
}
|
|
2942
3037
|
async *chatMessagesStreamGen(modelID, req, signal, retried) {
|
|
2943
|
-
req
|
|
2944
|
-
const { body, adapter } = await this.buildChatRequest(modelID,
|
|
3038
|
+
const r = { ...req, stream: true };
|
|
3039
|
+
const { body, adapter } = await this.buildChatRequest(modelID, r, signal);
|
|
2945
3040
|
const token = await this.ensureToken(signal);
|
|
2946
3041
|
const endpoint = `/managed-models/${encodeURIComponent(modelID)}${adapter.endpointSuffix()}`;
|
|
2947
3042
|
const url = this.apiURL(endpoint);
|
|
@@ -3113,6 +3208,9 @@ var Client = class _Client {
|
|
|
3113
3208
|
throw parseHTTPErrorWithHeader(resp.status, bodyBytes, resp.headers);
|
|
3114
3209
|
}
|
|
3115
3210
|
const text = await resp.text();
|
|
3211
|
+
if (!text) {
|
|
3212
|
+
return { result: void 0, headers: resp.headers };
|
|
3213
|
+
}
|
|
3116
3214
|
const result = JSON.parse(text);
|
|
3117
3215
|
if (result && typeof result === "object" && "code" in result) {
|
|
3118
3216
|
const bizErr = apiResponseBusinessError(result);
|
|
@@ -3213,6 +3311,18 @@ var Client = class _Client {
|
|
|
3213
3311
|
ctl.dispose();
|
|
3214
3312
|
}
|
|
3215
3313
|
}
|
|
3314
|
+
/**
|
|
3315
|
+
* 给子 client (agent-runs / compliance) 用的请求超时组合器。
|
|
3316
|
+
*
|
|
3317
|
+
* 返回一个 controller, 其 `signal` 同时受默认/指定超时与外部 `parent` signal 约束 —
|
|
3318
|
+
* 二者任一触发都会 abort (用户传入的 signal 仍然生效)。调用方**必须**在 finally 里
|
|
3319
|
+
* `dispose()` 清掉定时器与监听, 否则 timer 泄漏。
|
|
3320
|
+
*
|
|
3321
|
+
* 仅用于非流式 JSON 请求; 流式 (SSE) / 下载路径不应套短超时 (会切断长连接)。
|
|
3322
|
+
*/
|
|
3323
|
+
withRequestTimeout(ms, parent) {
|
|
3324
|
+
return withRequestTimeout(ms, parent);
|
|
3325
|
+
}
|
|
3216
3326
|
/**
|
|
3217
3327
|
* fetch 包装 — 错误经 classifyTransport 转 NetworkError
|
|
3218
3328
|
* 6 处原始 fetch() 全部走此 helper
|
|
@@ -3782,6 +3892,10 @@ var ScopeRemoteControl = "remote_control";
|
|
|
3782
3892
|
var ScopeRemoteControlAgentRun = "remote_control:agent-run";
|
|
3783
3893
|
var ScopeRemoteControlSessionControl = "remote_control:session-control";
|
|
3784
3894
|
var ScopeRemoteControlPermissionResponse = "remote_control:permission-response";
|
|
3895
|
+
var ScopeChatBridge = "chat_bridge";
|
|
3896
|
+
var ScopeChatBridgeRead = "chat_bridge:read";
|
|
3897
|
+
var ScopeChatBridgeWrite = "chat_bridge:write";
|
|
3898
|
+
var ScopeChatBridgeRotate = "chat_bridge:rotate";
|
|
3785
3899
|
var ScopeModels = "models";
|
|
3786
3900
|
var ScopeModelsChat = "models:chat";
|
|
3787
3901
|
var ScopeEntitlements = "entitlements";
|
|
@@ -3807,6 +3921,9 @@ function skillScopes() {
|
|
|
3807
3921
|
function remoteControlScopes() {
|
|
3808
3922
|
return [ScopeRemoteControl];
|
|
3809
3923
|
}
|
|
3924
|
+
function chatBridgeScopes() {
|
|
3925
|
+
return [ScopeChatBridge];
|
|
3926
|
+
}
|
|
3810
3927
|
|
|
3811
3928
|
// src/models/index.ts
|
|
3812
3929
|
init_types();
|
|
@@ -3998,9 +4115,10 @@ Client.prototype.waitForPayment = async function(orderID, pollIntervalMs, signal
|
|
|
3998
4115
|
if (pollIntervalMs <= 0) pollIntervalMs = 2e3;
|
|
3999
4116
|
while (true) {
|
|
4000
4117
|
const status = await this.getOrderStatus(orderID, signal);
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
|
|
4118
|
+
const st = status.paymentStatus ?? status.orderStatus;
|
|
4119
|
+
if (isOrderTerminal(st)) {
|
|
4120
|
+
if (isOrderSuccess(st)) return status;
|
|
4121
|
+
throw new OrderTerminalError(orderID, st);
|
|
4004
4122
|
}
|
|
4005
4123
|
await sleepWithSignal(pollIntervalMs, signal);
|
|
4006
4124
|
}
|
|
@@ -4381,6 +4499,9 @@ Client.prototype.updateNotificationPreference = async function(typeCode, pref, s
|
|
|
4381
4499
|
|
|
4382
4500
|
// src/notifications/ws.ts
|
|
4383
4501
|
Client.prototype.connect = async function(cfg, signal) {
|
|
4502
|
+
if (this.ws) {
|
|
4503
|
+
await this.disconnect();
|
|
4504
|
+
}
|
|
4384
4505
|
const noop = () => {
|
|
4385
4506
|
};
|
|
4386
4507
|
const filledCfg = {
|
|
@@ -4449,11 +4570,17 @@ function getWebSocketCtor() {
|
|
|
4449
4570
|
return WSCtor;
|
|
4450
4571
|
}
|
|
4451
4572
|
async function wsConnectOnce(c, ws) {
|
|
4452
|
-
const token = await c.ensureToken(ws.abort.signal);
|
|
4453
4573
|
const url = wsURL(c);
|
|
4454
4574
|
const WSCtor = getWebSocketCtor();
|
|
4575
|
+
const ticketResp = await c.doJSON(
|
|
4576
|
+
"POST",
|
|
4577
|
+
"/ws/stream-ticket",
|
|
4578
|
+
null,
|
|
4579
|
+
ws.abort.signal
|
|
4580
|
+
);
|
|
4581
|
+
const ticket = ticketResp.data.ticket;
|
|
4455
4582
|
const u = new URL(url);
|
|
4456
|
-
u.searchParams.set("
|
|
4583
|
+
u.searchParams.set("ticket", ticket);
|
|
4457
4584
|
let conn;
|
|
4458
4585
|
try {
|
|
4459
4586
|
conn = new WSCtor(u.toString());
|
|
@@ -4909,7 +5036,10 @@ var AgentRunsClient = class {
|
|
|
4909
5036
|
);
|
|
4910
5037
|
const contentType = resp.headers.get("Content-Type") ?? void 0;
|
|
4911
5038
|
const filename = filenameFromContentDisposition(resp.headers.get("Content-Disposition")) ?? artifactId;
|
|
4912
|
-
const data = await readLimited(resp.body, maxDownloadSize);
|
|
5039
|
+
const data = await readLimited(resp.body, maxDownloadSize + 1);
|
|
5040
|
+
if (data.byteLength > maxDownloadSize) {
|
|
5041
|
+
throw new Error(`download artifact: response exceeds ${maxDownloadSize >> 20}MB limit`);
|
|
5042
|
+
}
|
|
4913
5043
|
return { data, filename, contentType };
|
|
4914
5044
|
}
|
|
4915
5045
|
submitLocalToolResult(runId, result, signal) {
|
|
@@ -4965,7 +5095,6 @@ var AgentRunsClient = class {
|
|
|
4965
5095
|
};
|
|
4966
5096
|
}
|
|
4967
5097
|
const ctl = new AbortController();
|
|
4968
|
-
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
|
4969
5098
|
let parentAbort;
|
|
4970
5099
|
if (signal) {
|
|
4971
5100
|
if (signal.aborted) ctl.abort();
|
|
@@ -4974,7 +5103,18 @@ var AgentRunsClient = class {
|
|
|
4974
5103
|
signal.addEventListener("abort", parentAbort);
|
|
4975
5104
|
}
|
|
4976
5105
|
}
|
|
4977
|
-
|
|
5106
|
+
let timer;
|
|
5107
|
+
const timeoutResult = new Promise((resolve) => {
|
|
5108
|
+
timer = setTimeout(() => {
|
|
5109
|
+
ctl.abort();
|
|
5110
|
+
resolve({
|
|
5111
|
+
requestId: event.requestId,
|
|
5112
|
+
ok: false,
|
|
5113
|
+
error: `local tool timed out after ${timeoutMs}ms`
|
|
5114
|
+
});
|
|
5115
|
+
}, timeoutMs);
|
|
5116
|
+
});
|
|
5117
|
+
const handlerTask = (async () => {
|
|
4978
5118
|
const content = await handler(event.input, {
|
|
4979
5119
|
runId,
|
|
4980
5120
|
requestId: event.requestId,
|
|
@@ -4982,6 +5122,11 @@ var AgentRunsClient = class {
|
|
|
4982
5122
|
signal: ctl.signal
|
|
4983
5123
|
});
|
|
4984
5124
|
return { requestId: event.requestId, ok: true, content };
|
|
5125
|
+
})();
|
|
5126
|
+
handlerTask.catch(() => {
|
|
5127
|
+
});
|
|
5128
|
+
try {
|
|
5129
|
+
return await Promise.race([handlerTask, timeoutResult]);
|
|
4985
5130
|
} catch (e) {
|
|
4986
5131
|
if (signal?.aborted) throw e;
|
|
4987
5132
|
const timedOut = ctl.signal.aborted;
|
|
@@ -5014,14 +5159,29 @@ var AgentRunsClient = class {
|
|
|
5014
5159
|
}
|
|
5015
5160
|
}
|
|
5016
5161
|
async requestAPI(method, path, body, signal, opts) {
|
|
5017
|
-
const resp = await this.requestRaw(method, path, body, signal,
|
|
5162
|
+
const resp = await this.requestRaw(method, path, body, signal, {
|
|
5163
|
+
...opts,
|
|
5164
|
+
timeoutMs: opts.timeoutMs ?? DEFAULT_API_TIMEOUT_MS
|
|
5165
|
+
});
|
|
5018
5166
|
const text = await resp.text();
|
|
5167
|
+
if (!text) return void 0;
|
|
5019
5168
|
const result = JSON.parse(text);
|
|
5020
5169
|
const bizErr = apiResponseBusinessError(result);
|
|
5021
5170
|
if (bizErr) throw bizErr;
|
|
5022
5171
|
return result.data;
|
|
5023
5172
|
}
|
|
5024
5173
|
async requestRaw(method, path, body, signal, opts, retried = false) {
|
|
5174
|
+
if (opts.timeoutMs != null && opts.timeoutMs > 0) {
|
|
5175
|
+
const ctl = this.client.withRequestTimeout(opts.timeoutMs, signal);
|
|
5176
|
+
try {
|
|
5177
|
+
return await this.requestRawInner(method, path, body, ctl.signal, opts, retried);
|
|
5178
|
+
} finally {
|
|
5179
|
+
ctl.dispose();
|
|
5180
|
+
}
|
|
5181
|
+
}
|
|
5182
|
+
return this.requestRawInner(method, path, body, signal, opts, retried);
|
|
5183
|
+
}
|
|
5184
|
+
async requestRawInner(method, path, body, signal, opts, retried) {
|
|
5025
5185
|
const token = await this.client.ensureToken(signal);
|
|
5026
5186
|
const url = this.client.apiURL(path);
|
|
5027
5187
|
const headers = {
|
|
@@ -5040,7 +5200,7 @@ var AgentRunsClient = class {
|
|
|
5040
5200
|
} catch {
|
|
5041
5201
|
}
|
|
5042
5202
|
await this.client.forceRefresh(signal);
|
|
5043
|
-
return this.
|
|
5203
|
+
return this.requestRawInner(method, path, body, signal, opts, true);
|
|
5044
5204
|
}
|
|
5045
5205
|
if (resp.status < 200 || resp.status >= 300) {
|
|
5046
5206
|
const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
|
|
@@ -6372,6 +6532,14 @@ var ComplianceClient = class {
|
|
|
6372
6532
|
});
|
|
6373
6533
|
}
|
|
6374
6534
|
async executeJson(method, path, body, signal, opts, retried = false) {
|
|
6535
|
+
const ctl = this.client.withRequestTimeout(DEFAULT_API_TIMEOUT_MS, signal);
|
|
6536
|
+
try {
|
|
6537
|
+
return await this.executeJsonInner(method, path, body, ctl.signal, opts, retried);
|
|
6538
|
+
} finally {
|
|
6539
|
+
ctl.dispose();
|
|
6540
|
+
}
|
|
6541
|
+
}
|
|
6542
|
+
async executeJsonInner(method, path, body, signal, opts, retried) {
|
|
6375
6543
|
const token = await this.client.ensureToken(signal);
|
|
6376
6544
|
const url = this.client.complianceURL(path);
|
|
6377
6545
|
const headers = {
|
|
@@ -6391,7 +6559,7 @@ var ComplianceClient = class {
|
|
|
6391
6559
|
} catch {
|
|
6392
6560
|
}
|
|
6393
6561
|
await this.client.forceRefresh(signal);
|
|
6394
|
-
return this.
|
|
6562
|
+
return this.executeJsonInner(method, path, body, signal, opts, true);
|
|
6395
6563
|
}
|
|
6396
6564
|
if (resp.status < 200 || resp.status >= 300) {
|
|
6397
6565
|
const bodyBytes = resp.body ? await readLimited(resp.body, maxErrorBodySize) : new Uint8Array();
|
|
@@ -6416,7 +6584,11 @@ var ComplianceClient = class {
|
|
|
6416
6584
|
let lastValue;
|
|
6417
6585
|
while (Date.now() < deadline) {
|
|
6418
6586
|
if (opts.signal?.aborted) {
|
|
6419
|
-
throw new CompliancePollError(
|
|
6587
|
+
throw new CompliancePollError(
|
|
6588
|
+
"compliance poll aborted",
|
|
6589
|
+
"unknown",
|
|
6590
|
+
deriveLastInfo(lastValue, false)
|
|
6591
|
+
);
|
|
6420
6592
|
}
|
|
6421
6593
|
lastValue = await fetcher();
|
|
6422
6594
|
const decision = classify(lastValue);
|
|
@@ -6424,7 +6596,8 @@ var ComplianceClient = class {
|
|
|
6424
6596
|
if (decision === "failed") {
|
|
6425
6597
|
throw new CompliancePollError(
|
|
6426
6598
|
"compliance poll observed terminal failure",
|
|
6427
|
-
"terminal_failure"
|
|
6599
|
+
"terminal_failure",
|
|
6600
|
+
deriveLastInfo(lastValue, true)
|
|
6428
6601
|
);
|
|
6429
6602
|
}
|
|
6430
6603
|
const sleepMs = Math.min(interval, deadline - Date.now());
|
|
@@ -6432,9 +6605,30 @@ var ComplianceClient = class {
|
|
|
6432
6605
|
await sleep2(sleepMs, opts.signal);
|
|
6433
6606
|
interval = Math.min(Math.floor(interval * cfg.multiplier), cfg.maxIntervalMs);
|
|
6434
6607
|
}
|
|
6435
|
-
throw new CompliancePollError(
|
|
6608
|
+
throw new CompliancePollError(
|
|
6609
|
+
"compliance poll timed out",
|
|
6610
|
+
"timeout",
|
|
6611
|
+
deriveLastInfo(lastValue, false)
|
|
6612
|
+
);
|
|
6436
6613
|
}
|
|
6437
6614
|
};
|
|
6615
|
+
function deriveLastInfo(value, terminal) {
|
|
6616
|
+
if (value == null || typeof value !== "object") return void 0;
|
|
6617
|
+
const v = value;
|
|
6618
|
+
const statusStr = typeof v["status"] === "string" && v["status"] || typeof v["verificationStatus"] === "string" && v["verificationStatus"] || "";
|
|
6619
|
+
const rawCode = v["errorCode"] ?? v["code"];
|
|
6620
|
+
const code = typeof rawCode === "number" ? rawCode : 0;
|
|
6621
|
+
const rawMsg = v["errorMessage"] ?? v["message"];
|
|
6622
|
+
const message = typeof rawMsg === "string" && rawMsg || (statusStr ? `last polled status: ${statusStr}` : "") || "compliance poll: last observed status (no detail)";
|
|
6623
|
+
return {
|
|
6624
|
+
code,
|
|
6625
|
+
message,
|
|
6626
|
+
key: "UNKNOWN_COMPLIANCE_ERROR",
|
|
6627
|
+
retryable: false,
|
|
6628
|
+
terminal,
|
|
6629
|
+
stepUpRequired: false
|
|
6630
|
+
};
|
|
6631
|
+
}
|
|
6438
6632
|
function classifyTimestamp(status) {
|
|
6439
6633
|
switch (status) {
|
|
6440
6634
|
case "VERIFIED":
|
|
@@ -6554,14 +6748,36 @@ Client.prototype.listPlans = async function(audience, signal) {
|
|
|
6554
6748
|
);
|
|
6555
6749
|
return Array.isArray(resp.data) ? resp.data : [];
|
|
6556
6750
|
};
|
|
6557
|
-
Client.prototype.
|
|
6751
|
+
Client.prototype.getMembership = async function(signal) {
|
|
6558
6752
|
const resp = await this.doJSON(
|
|
6559
6753
|
"GET",
|
|
6560
|
-
"/
|
|
6754
|
+
"/entitlements/membership",
|
|
6561
6755
|
null,
|
|
6562
6756
|
signal
|
|
6563
6757
|
);
|
|
6564
|
-
return
|
|
6758
|
+
return resp.data;
|
|
6759
|
+
};
|
|
6760
|
+
Client.prototype.getSubscriptionTier = async function(signal) {
|
|
6761
|
+
const resp = await this.doJSON(
|
|
6762
|
+
"GET",
|
|
6763
|
+
"/entitlements/subscription",
|
|
6764
|
+
null,
|
|
6765
|
+
signal
|
|
6766
|
+
);
|
|
6767
|
+
return resp.data;
|
|
6768
|
+
};
|
|
6769
|
+
Client.prototype.subscriptionPrecheck = async function(signal) {
|
|
6770
|
+
const resp = await this.doJSON(
|
|
6771
|
+
"GET",
|
|
6772
|
+
"/consumer/subscriptions/precheck",
|
|
6773
|
+
null,
|
|
6774
|
+
signal
|
|
6775
|
+
);
|
|
6776
|
+
return resp.data;
|
|
6777
|
+
};
|
|
6778
|
+
Client.prototype.listUserSubscriptions = async function(signal) {
|
|
6779
|
+
const m = await this.getMembership(signal);
|
|
6780
|
+
return m.hasActive ? [m] : [];
|
|
6565
6781
|
};
|
|
6566
6782
|
Client.prototype.getPlanByCode = async function(planCode, signal) {
|
|
6567
6783
|
if (!planCode) return null;
|
|
@@ -6976,6 +7192,6 @@ function asCredentialRef(s) {
|
|
|
6976
7192
|
return s;
|
|
6977
7193
|
}
|
|
6978
7194
|
|
|
6979
|
-
export { ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, AgentRunStreamError, AgentRunsClient, AnthropicAdapter, AudienceEnum, BillingModeEnum, BucketClassCommercial, BucketClassGeneric, BusinessError, Client, ComplianceClient, CompliancePollError, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, FileTokenStore, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OAuthTokenEndpointError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, ServerToolTypeWebSearch, StreamError, ThinkingHigh, ThinkingHighMinMaxTokens, ThinkingMax, ThinkingMaxFallbackMaxTokens, ThinkingOff, allScopes, anthropicResponseTextContent, anthropicResponseThinkingContent, anthropicResponseToolUseBlocks, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, bucketInfoIsCommercial, bucketRowIsCommercial, buildBetas, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getAdapter, getAdapterForModel, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newThinkingConfig, newTokenSet, newWebSearchTool, normalizeGatewayBaseURL, parseNotificationEvent, parseRemoteControlEvent, parseSettlement, parseSourcesEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, sanitize_exports as sanitize, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
|
|
7195
|
+
export { ALL_INTEGRATION_STATUS, ALL_PLATFORMS, ALL_REGIONS, AgentRunStreamError, AgentRunsClient, AnthropicAdapter, AudienceEnum, BillingModeEnum, BucketClassCommercial, BucketClassGeneric, BusinessError, Client, ComplianceClient, CompliancePollError, DEFAULT_API_TIMEOUT_MS, DEFAULT_GATEWAY_BASE_URL, DefaultRetryPolicy, ErrAuthDenied, ErrBillingCallbackCannotCommit, ErrBillingCommitRequiresLocalVerify, ErrBillingS2sForbidden, ErrBrowserOpen, ErrComplianceStepUpRequired, ErrDiscovery, ErrEnvelopeGateClosed, ErrOAuthCORSBlocked, ErrProviderNotConfigured, ErrProviderUnknownNoRetry, ErrRefreshProxyFailed, ErrRegistration, ErrSSLProxy, ErrSealApprovalContractHashMismatch, ErrSealApprovalExpired, ErrSealApprovalLocationMismatch, ErrSealApprovalNonceUsed, ErrSealApprovalNotApproved, ErrSealApprovalSealMismatch, ErrSealApprovalTransactorMismatch, ErrSealUseAlreadyConsumed, ErrStateMismatch, ErrTimeout, ErrTokenExchange, ErrTokenExpired, EventAuthURL, EventComplete, EventError, FileTokenStore, FilterStatusAdminBypass, FilterStatusDisabledByFlag, FilterStatusFallbackMissingUser, FilterStatusFallbackNoBuckets, FilterStatusFallbackTkdistError, FilterStatusFallbackTkdistSkew, FilterStatusInternalBypass, FilterStatusOK, FilterStatusUnknown, HTTPError, IdempotencyKeyHeader, InMemoryTokenStore, LocalStorageTokenStore, ModelNotFoundError, NetworkError, OAuthTokenEndpointError, OpenAIAdapter, OrderTerminalError, ProductFamilyEnum, ProviderFormat, RETRY_ADVICE_REASONS, RateLimitError, RegionScopeEnum, ScopeAI, ScopeAccount, ScopeChatBridge, ScopeChatBridgeRead, ScopeChatBridgeRotate, ScopeChatBridgeWrite, ScopeComplianceContractSigningRead, ScopeComplianceContractSigningWrite, ScopeComplianceContractTemplateRead, ScopeComplianceContractTemplateWrite, ScopeComplianceEvidenceRead, ScopeComplianceEvidenceWrite, ScopeComplianceReportsPublish, ScopeComplianceReportsRead, ScopeComplianceReportsWrite, ScopeComplianceSealApprovalApprove, ScopeComplianceSealApprovalRequest, ScopeComplianceSealManage, ScopeComplianceSealUseExecute, ScopeComplianceTimestampIssue, ScopeComplianceTimestampVerify, ScopeEntitlements, ScopeModels, ScopeModelsChat, ScopeProfile, ScopeRemoteControl, ScopeRemoteControlAgentRun, ScopeRemoteControlPermissionResponse, ScopeRemoteControlSessionControl, ScopeSkillStore, ScopeSkills, ScopeTokenPackages, ScopeTools, ScopeToolsExecute, ScopeWallet, ScopeWalletReadonly, ServerToolTypeWebSearch, StreamError, ThinkingHigh, ThinkingHighMinMaxTokens, ThinkingMax, ThinkingMaxFallbackMaxTokens, ThinkingOff, allScopes, anthropicResponseTextContent, anthropicResponseThinkingContent, anthropicResponseToolUseBlocks, apiResponseBusinessError, apiResponseGetMessage, asCredentialRef, authorize, bucketInfoIsCommercial, bucketRowIsCommercial, buildBetas, chatBridgeScopes, classifyComplianceError, commerceScopes, completeWebAuthorizationRequest, complianceErrorToRetryAdvice, complianceScopes, computeBackoff, createWebAuthorizationRequest, defaultRetryable, defaultSafeToRetry, discover, discoverWebOAuthMetadata, discoverWithProfile, effectivePolicy, exchangeCode, extractAnthropicBlockMeta, fileLockDefaults, findDesktopVisualUnderstandingModel, findFirstModelByInputModality, generateState, getAdapter, getAdapterForModel, isBillingConfirmable, isChannelInboundEvent, isComplianceBusinessError, isComplianceTerminalError, isIntegrationStatus, isInvalidGrantError, isPlatform, isRegion, isSSECommentLine, isSSLError, isTerminalRemoteEvent, isValidTokenSet, maxEndUserIdLength, modelScopes, modelSupportsImageInput, modelSupportsInputModality, newFileTokenStore, newThinkingConfig, newTokenSet, newWebSearchTool, normalizeGatewayBaseURL, normalizeOverrideBaseURL, parseNotificationEvent, parseRemoteControlEvent, parseSettlement, parseSourcesEvent, refreshToken, register, registerWebOAuthClient, remoteControlScopes, retryReasonForComplianceKey, retryReasonForOAuthError, revokeToken, sanitize_exports as sanitize, skillScopes, tokenSetIsExpired, uniqueMerge, validateEndUserId };
|
|
6980
7196
|
//# sourceMappingURL=index.mjs.map
|
|
6981
7197
|
//# sourceMappingURL=index.mjs.map
|