dsh-opendesign-corouter 0.1.9 → 0.1.11
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/README.md +4 -4
- package/lib/client.d.ts +22 -4
- package/lib/client.js +254 -52
- package/lib/device-auth.d.ts +1 -1
- package/lib/empty-turn.d.ts +11 -6
- package/lib/eot-code.d.ts +2 -0
- package/lib/eot-recovery.d.ts +33 -0
- package/lib/generated/typert.host.js +36 -0
- package/lib/generated/typert.remote-client.d.ts +2 -1
- package/lib/generated/typert.remote-client.js +36 -0
- package/lib/index.d.ts +7 -1
- package/lib/index.js +500 -25
- package/lib/index.js.map +4 -4
- package/lib/pricing.d.ts +149 -0
- package/lib/protocols/errors.d.ts +4 -0
- package/lib/remote.d.ts +21 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -48,7 +48,7 @@ var __privateSet = (obj, member2, value, setter) => (__accessCheck(obj, member2,
|
|
|
48
48
|
var __privateMethod = (obj, member2, method) => (__accessCheck(obj, member2, "access private method"), method);
|
|
49
49
|
|
|
50
50
|
// src/index.ts
|
|
51
|
-
import { randomUUID as
|
|
51
|
+
import { randomUUID as randomUUID3, createHash } from "node:crypto";
|
|
52
52
|
import { credentialKey, credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
53
53
|
import { launchEnvironmentOf } from "@deepseek-ai/dsh-launch-environment";
|
|
54
54
|
import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
@@ -327,7 +327,7 @@ var Config = Schema.object({
|
|
|
327
327
|
apiProtocol: Schema.union(API_PROTOCOL_IDS).default("chat-completions").description("\u7F51\u5173\u652F\u6301\u7684\u63A8\u7406\u534F\u8BAE\uFF1B\u6A21\u578B\u76EE\u5F55\u901A\u8FC7\u8BE5\u7F51\u5173\u7684\u517C\u5BB9\u63A5\u53E3\u8BFB\u53D6").volatile(),
|
|
328
328
|
modelSettings: Schema.transform(Schema.dict(Schema.any()), serializableTransform(parseModelSettingsMap)).default({}).description("\u9010\u6A21\u578B\u542F\u7528\u72B6\u6001\u548C\u8BF7\u6C42\u53C2\u6570").volatile(),
|
|
329
329
|
useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\u989D\u5EA6").volatile(),
|
|
330
|
-
emptyTurnGuard: Schema.boolean().default(true).description("\u68C0\u6D4B DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\u7684\u7A7A\u56DE\u7B54\uFF1B\
|
|
330
|
+
emptyTurnGuard: Schema.boolean().default(true).description("\u68C0\u6D4B DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\u7684\u7A7A\u56DE\u7B54\u548C\u5F02\u5E38\u7ED3\u675F\uFF1B\u6301\u7EED\u91CD\u8BD5\u76F4\u5230\u6210\u529F\u6216\u53D6\u6D88\uFF0C\u53EF\u80FD\u8BEF\u5224\u5E76\u989D\u5916\u6D88\u8017\u989D\u5EA6").volatile(),
|
|
331
331
|
quotaRefreshSeconds: Schema.natural().min(5).max(3600).default(60).description("\u989D\u5EA6\u81EA\u52A8\u5237\u65B0\u95F4\u9694\uFF08\u79D2\uFF09").volatile(),
|
|
332
332
|
requestTimeoutMs: Schema.natural().min(1e3).max(36e5).default(18e5).description("\u63A8\u7406\u8BF7\u6C42\u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile(),
|
|
333
333
|
streamIdleTimeoutMs: Schema.natural().min(1e3).max(18e5).default(3e5).description("\u6D41\u5F0F\u54CD\u5E94\u65E0\u6570\u636E\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09").volatile()
|
|
@@ -495,6 +495,11 @@ import {
|
|
|
495
495
|
isContextWindowExceededError,
|
|
496
496
|
isQuotaExceededError
|
|
497
497
|
} from "@deepseek-ai/dsh-llm";
|
|
498
|
+
var PrematureEndError = class extends LlmError2 {
|
|
499
|
+
constructor(message) {
|
|
500
|
+
super(message, "INVALID_RESPONSE");
|
|
501
|
+
}
|
|
502
|
+
};
|
|
498
503
|
var MESSAGES = {
|
|
499
504
|
[CONTEXT_WINDOW_EXCEEDED_CODE]: "OpenDesign\uFF1A\u8BF7\u6C42\u8D85\u51FA\u6A21\u578B\u4E0A\u4E0B\u6587\u957F\u5EA6\uFF0C\u8BF7\u7F29\u77ED\u8F93\u5165\u540E\u91CD\u8BD5",
|
|
500
505
|
[ACCOUNT_QUOTA_EXCEEDED_CODE]: "OpenDesign\uFF1A\u5957\u9910\u6216\u8D26\u6237\u989D\u5EA6\u4E0D\u8DB3\uFF0C\u8BF7\u68C0\u67E5\u5957\u9910\u989D\u5EA6\u540E\u91CD\u8BD5",
|
|
@@ -817,7 +822,7 @@ async function* consumeSse(body, signal, idleMs) {
|
|
|
817
822
|
if (done) break;
|
|
818
823
|
}
|
|
819
824
|
signal.throwIfAborted();
|
|
820
|
-
if (!finish) throw new
|
|
825
|
+
if (!finish) throw new PrematureEndError("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u539F\u56E0");
|
|
821
826
|
if (!count2) throw new LlmError4("OpenDesign\uFF1A\u6A21\u578B\u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
|
|
822
827
|
if (finish.kind === "tool-calls" && !sawTool) throw new LlmError4("OpenDesign\uFF1A\u54CD\u5E94\u58F0\u660E\u5DE5\u5177\u8C03\u7528\uFF0C\u4F46\u672A\u8FD4\u56DE\u4EFB\u4F55\u5DE5\u5177\u5757", "INVALID_RESPONSE");
|
|
823
828
|
if (usage) yield { type: "usage", usage };
|
|
@@ -825,11 +830,22 @@ async function* consumeSse(body, signal, idleMs) {
|
|
|
825
830
|
}
|
|
826
831
|
|
|
827
832
|
// src/empty-turn.ts
|
|
828
|
-
import
|
|
829
|
-
|
|
833
|
+
import "@deepseek-ai/dsh-llm";
|
|
834
|
+
|
|
835
|
+
// src/eot-code.ts
|
|
836
|
+
var OPENDESIGN_EOT = "OPENDESIGN_EOT";
|
|
837
|
+
|
|
838
|
+
// src/empty-turn.ts
|
|
839
|
+
var EMPTY_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u672A\u4EA7\u751F\u53EF\u7528\u56DE\u7B54\u6216\u6709\u6548\u5DE5\u5177\u8C03\u7528";
|
|
840
|
+
var INCOMPLETE_TURN_MESSAGE = "OpenDesign\uFF1A\u6A21\u578B\u505C\u5728\u64CD\u4F5C\u8BF4\u660E\uFF0C\u672A\u7EE7\u7EED\u53D1\u8D77\u5DE5\u5177\u8C03\u7528";
|
|
830
841
|
var RESIDUE_PATTERNS = [
|
|
842
|
+
/<\s*rea:tool_calls\s*>[\s\S]*?(?:<\s*\/\s*rea:tool_calls\s*>|$)/giu,
|
|
843
|
+
/<\s*rea:tool(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:tool\s*>|$)/giu,
|
|
844
|
+
/<\s*rea:parameter(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*rea:parameter\s*>|$)/giu,
|
|
845
|
+
/<\s*||DSML||\s*calls(?:\s+[^>]*)?>[\s\S]*?(?:<\s*\/\s*||DSML||\s*calls\s*>|$)/gu,
|
|
831
846
|
/<\s*\/?\s*||DSML||[^>]*>/gu,
|
|
832
|
-
/||DSML
|
|
847
|
+
/||DSML||\s*(?:calls|invoke|parameter)(?:\s+[^>\n]*)?>/giu,
|
|
848
|
+
/||DSML||(?:\s*(?:calls|invoke|parameter))?\s*$/giu,
|
|
833
849
|
/<\s*\/?\s*thinking\s*>/giu,
|
|
834
850
|
/<\s*\/?\s*rea:tool_calls\s*>/giu,
|
|
835
851
|
/<\s*\/?\s*返璞归真\s*>/gu
|
|
@@ -844,6 +860,20 @@ function stripProtocolResidue(text2) {
|
|
|
844
860
|
function isResidueOnly(text2) {
|
|
845
861
|
return text2 === void 0 || stripProtocolResidue(text2) === "";
|
|
846
862
|
}
|
|
863
|
+
var ACTION_PREAMBLE_ZH = /^(?:(?:好的?|明白|收到)[,,。]\s*)?(?:让我|我需要|我(?:先|再|将|会|来|要|这就|马上)|先|现在|接下来(?:我)?(?:将|会)?)(?:先|再|去|来|马上)?(?:看一看|看看|看下|查看|检查|核对|核验|核查|对照|比对|确认|验证|验收|测试|读取|读|打开|搜索|查找|定位|分析|排查|审查|检索|查询|运行|执行|修改|修复|调整|更新|编写|梳理|对比|比较)(?!了|过|到|出|完)[^,,。!?!?\n;;::]{1,100}[。!!…]?$/u;
|
|
864
|
+
var ACTION_PREAMBLE_EN = /^(?:(?:okay|sure|now)[,.]?\s+)?(?:let me|i(?:'ll| will)|i(?:'m| am) going to)\s+(?:check|inspect|review|verify|read|open|search|find|locate|analy[sz]e|test|run|execute|edit|fix|update|compare)\s+[^.!?,;:\n]{1,100}(?:\.{1,3}|!|…)?$/iu;
|
|
865
|
+
var FOLLOWUP_ACTION_ZH = /^(?:现在|接下来|下一步|随后|接着)(?:我)?(?:先|再|将|会|准备|重新)?(?:看一看|看看|看下|查看|检查|核对|核验|核查|对照|比对|确认|验证|验收|测试|读取|读|打开|搜索|查找|定位|分析|排查|审查|检索|查询|运行|执行|修改|修复|调整|更新|编写|梳理|对比|比较)(?!了|过|到|出|完|结果)[^。!?!?\n;;::]{1,100}[。!!…]?$/u;
|
|
866
|
+
var COMPLETED_ACTION_ZH = /(?:发现|结果(?:是|为|显示)|显示|得出|证明|确认了|已经完成|已完成|通过|没有问题|无误|正常)/u;
|
|
867
|
+
function isPendingActionTurn(text2) {
|
|
868
|
+
if (text2 === void 0) return false;
|
|
869
|
+
const content2 = stripProtocolResidue(text2);
|
|
870
|
+
if (ACTION_PREAMBLE_ZH.test(content2) || ACTION_PREAMBLE_EN.test(content2)) return true;
|
|
871
|
+
if (content2.length > 200 || /[\n`]/u.test(content2)) return false;
|
|
872
|
+
const sentences = content2.split(/(?<=[。!?])\s*/u).filter(Boolean);
|
|
873
|
+
if (sentences.length < 2 || sentences.length > 3) return false;
|
|
874
|
+
const last = sentences.at(-1) ?? "";
|
|
875
|
+
return FOLLOWUP_ACTION_ZH.test(last) && !COMPLETED_ACTION_ZH.test(last);
|
|
876
|
+
}
|
|
847
877
|
function isMarkupOnlyStop(reason, input) {
|
|
848
878
|
return reason.kind === "stop" && !input.sawToolCall && isResidueOnly(input.text);
|
|
849
879
|
}
|
|
@@ -912,24 +942,28 @@ var EmptyTurnTracker = class {
|
|
|
912
942
|
sawToolCall: this.#sawToolCall,
|
|
913
943
|
textLength: text2.length,
|
|
914
944
|
reasoningLength: reasoning.length,
|
|
915
|
-
markupOnly: isResidueOnly(text2)
|
|
945
|
+
markupOnly: isResidueOnly(text2),
|
|
946
|
+
pendingAction: isPendingActionTurn(text2)
|
|
916
947
|
};
|
|
917
948
|
}
|
|
918
949
|
/**
|
|
919
|
-
|
|
950
|
+
* Rewrite an eligible finish into the scoped EOT failure.
|
|
920
951
|
*
|
|
921
952
|
* The reason object is returned unchanged (same reference) whenever the monitor is off, the
|
|
922
|
-
* finish is not `stop`, a tool call was observed, or the visible text
|
|
923
|
-
* This method only decides and rewrites
|
|
953
|
+
* finish is not `stop`, a tool call was observed, or the visible text is a substantive answer.
|
|
954
|
+
* This method only decides and rewrites; scoped recovery runs at the host's request-error boundary.
|
|
924
955
|
* @param reason - the finish reason the adapter is about to yield.
|
|
925
956
|
* @returns a retryable `error` reason, or the given reason untouched.
|
|
926
957
|
*/
|
|
927
958
|
resolve(reason) {
|
|
928
|
-
|
|
959
|
+
const text2 = this.#text();
|
|
960
|
+
const markupOnly = isMarkupOnlyStop(reason, { sawToolCall: this.#sawToolCall, text: text2 });
|
|
961
|
+
const pendingAction = reason.kind === "stop" && !this.#sawToolCall && isPendingActionTurn(text2);
|
|
962
|
+
if (!this.#enabled || !markupOnly && !pendingAction) {
|
|
929
963
|
return reason;
|
|
930
964
|
}
|
|
931
965
|
this.#notify();
|
|
932
|
-
return { kind: "error", failure: { code:
|
|
966
|
+
return { kind: "error", failure: { code: OPENDESIGN_EOT, message: pendingAction ? INCOMPLETE_TURN_MESSAGE : EMPTY_TURN_MESSAGE } };
|
|
933
967
|
}
|
|
934
968
|
/** Report one rewrite to the telemetry hook; monitoring must never break the stream. */
|
|
935
969
|
#notify() {
|
|
@@ -1356,7 +1390,7 @@ async function* streamMessages(body, signal, idleMs) {
|
|
|
1356
1390
|
if (finish) break;
|
|
1357
1391
|
}
|
|
1358
1392
|
signal.throwIfAborted();
|
|
1359
|
-
if (!finish) throw new
|
|
1393
|
+
if (!finish) throw new PrematureEndError("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u4E8B\u4EF6");
|
|
1360
1394
|
}
|
|
1361
1395
|
var messages = {
|
|
1362
1396
|
id: "messages",
|
|
@@ -1705,7 +1739,7 @@ async function* streamResponses(body, signal, idleMs) {
|
|
|
1705
1739
|
if (finish) break;
|
|
1706
1740
|
}
|
|
1707
1741
|
signal.throwIfAborted();
|
|
1708
|
-
if (!finish) throw new
|
|
1742
|
+
if (!finish) throw new PrematureEndError("OpenDesign\uFF1A\u54CD\u5E94\u6D41\u63D0\u524D\u4E2D\u65AD\uFF0C\u672A\u6536\u5230\u7ED3\u675F\u4E8B\u4EF6");
|
|
1709
1743
|
}
|
|
1710
1744
|
var responses = {
|
|
1711
1745
|
id: "responses",
|
|
@@ -1883,9 +1917,18 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
1883
1917
|
}
|
|
1884
1918
|
throw gatewayError(response.status, error);
|
|
1885
1919
|
}
|
|
1886
|
-
if (!response.body) throw new LlmError10("CoRouter \u8FD4\u56DE\u7A7A\u54CD\u5E94", "EMPTY_RESPONSE");
|
|
1887
1920
|
const monitor = row.group === "plan" && row.id === "deepseek-v4.1-flash" && config.emptyTurnGuard && Boolean(options.tools?.length);
|
|
1888
|
-
const
|
|
1921
|
+
const reportEmptyTurn = () => {
|
|
1922
|
+
try {
|
|
1923
|
+
this.options.onEmptyTurn?.();
|
|
1924
|
+
} catch {
|
|
1925
|
+
}
|
|
1926
|
+
};
|
|
1927
|
+
if (!response.body) {
|
|
1928
|
+
if (monitor) reportEmptyTurn();
|
|
1929
|
+
throw new LlmError10("CoRouter \u8FD4\u56DE\u7A7A\u54CD\u5E94", monitor ? OPENDESIGN_EOT : "EMPTY_RESPONSE");
|
|
1930
|
+
}
|
|
1931
|
+
const tracker = new EmptyTurnTracker({ enabled: monitor, onEmptyTurn: reportEmptyTurn });
|
|
1889
1932
|
try {
|
|
1890
1933
|
for await (const chunk of protocol.stream(response.body, signal, config.streamIdleTimeoutMs)) {
|
|
1891
1934
|
tracker.observe(chunk);
|
|
@@ -1895,12 +1938,81 @@ var CoRouterAdapter = class extends LlmAdapter {
|
|
|
1895
1938
|
} catch (error) {
|
|
1896
1939
|
if (options.signal?.aborted || this.#lifetime.signal.aborted) signal.throwIfAborted();
|
|
1897
1940
|
if (signal.aborted) throw new LlmError10("CoRouter \u8BF7\u6C42\u8D85\u8FC7\u603B\u8D85\u65F6", "TIMEOUT");
|
|
1941
|
+
if (monitor && !tracker.sawToolCall && error instanceof PrematureEndError) throw new LlmError10(error.message, "TRANSPORT");
|
|
1942
|
+
if (monitor && !tracker.sawToolCall && error instanceof LlmError10 && error.code === "EMPTY_RESPONSE") {
|
|
1943
|
+
reportEmptyTurn();
|
|
1944
|
+
throw new LlmError10(error.message, OPENDESIGN_EOT);
|
|
1945
|
+
}
|
|
1898
1946
|
if (error instanceof LlmError10) throw error;
|
|
1899
1947
|
throw new LlmError10("CoRouter \u54CD\u5E94\u6D41\u8FDE\u63A5\u4E2D\u65AD", "SERVER");
|
|
1900
1948
|
}
|
|
1901
1949
|
}
|
|
1902
1950
|
};
|
|
1903
1951
|
|
|
1952
|
+
// src/eot-recovery.ts
|
|
1953
|
+
import { randomUUID } from "node:crypto";
|
|
1954
|
+
var POLICY_KEY = "opendesign-eot-unbounded-v1";
|
|
1955
|
+
var INITIAL_DELAY_MS = 500;
|
|
1956
|
+
var MAX_DELAY_MS = 1e4;
|
|
1957
|
+
function cancellableDelay(delay, signal) {
|
|
1958
|
+
if (signal.aborted) return Promise.resolve(false);
|
|
1959
|
+
return new Promise((resolve) => {
|
|
1960
|
+
const timer = setTimeout(() => {
|
|
1961
|
+
signal.removeEventListener("abort", onAbort);
|
|
1962
|
+
resolve(true);
|
|
1963
|
+
}, delay);
|
|
1964
|
+
const onAbort = () => {
|
|
1965
|
+
clearTimeout(timer);
|
|
1966
|
+
resolve(false);
|
|
1967
|
+
};
|
|
1968
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
var EotRecovery = class {
|
|
1972
|
+
constructor(enabled, wait = cancellableDelay) {
|
|
1973
|
+
this.enabled = enabled;
|
|
1974
|
+
this.wait = wait;
|
|
1975
|
+
}
|
|
1976
|
+
enabled;
|
|
1977
|
+
wait;
|
|
1978
|
+
#lifetime = new AbortController();
|
|
1979
|
+
#states = /* @__PURE__ */ new WeakMap();
|
|
1980
|
+
#active = /* @__PURE__ */ new Set();
|
|
1981
|
+
handle = (payload, next) => {
|
|
1982
|
+
if (payload.provider !== PLAN_PROVIDER || payload.failure.code !== OPENDESIGN_EOT || !this.enabled()) return next();
|
|
1983
|
+
if (payload.signal.aborted || this.#lifetime.signal.aborted) return Promise.resolve(void 0);
|
|
1984
|
+
const operation = this.#recover(payload);
|
|
1985
|
+
const tracked = operation.finally(() => this.#active.delete(tracked));
|
|
1986
|
+
this.#active.add(tracked);
|
|
1987
|
+
return tracked;
|
|
1988
|
+
};
|
|
1989
|
+
async #recover({ agent, turn, step, provider, failure, signal }) {
|
|
1990
|
+
const fused = AbortSignal.any([signal, this.#lifetime.signal]);
|
|
1991
|
+
if (fused.aborted) return;
|
|
1992
|
+
const previous = this.#states.get(agent);
|
|
1993
|
+
const state = previous?.turn === turn && previous.step === step ? { ...previous, retry: previous.retry + 1 } : { turn, step, retryId: randomUUID(), retry: 1 };
|
|
1994
|
+
this.#states.set(agent, state);
|
|
1995
|
+
const delayMs = Math.min(INITIAL_DELAY_MS * 2 ** Math.min(state.retry - 1, 8), MAX_DELAY_MS);
|
|
1996
|
+
agent.session.append("llm/retry", { retryId: state.retryId, turn, step, provider, mode: "always", policyKey: POLICY_KEY, retry: state.retry, delayMs, failure });
|
|
1997
|
+
if (!await this.wait(delayMs, fused) || fused.aborted || !this.enabled()) return;
|
|
1998
|
+
agent.session.append("llm/retry-started", { retryId: state.retryId, turn, step, retry: state.retry });
|
|
1999
|
+
return { kind: "retry" };
|
|
2000
|
+
}
|
|
2001
|
+
async dispose() {
|
|
2002
|
+
this.#lifetime.abort(new Error("EOT recovery disposed"));
|
|
2003
|
+
await Promise.allSettled([...this.#active]);
|
|
2004
|
+
}
|
|
2005
|
+
};
|
|
2006
|
+
function installEotRecovery(ctx, enabled) {
|
|
2007
|
+
const recovery = new EotRecovery(enabled);
|
|
2008
|
+
const events = ctx;
|
|
2009
|
+
const remove = events.on("agent/request-error", recovery.handle, { prepend: true });
|
|
2010
|
+
ctx.effect(() => async () => {
|
|
2011
|
+
remove();
|
|
2012
|
+
await recovery.dispose();
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
|
|
1904
2016
|
// src/model-discovery.ts
|
|
1905
2017
|
import { attributionHeaders as attributionHeaders2 } from "@deepseek-ai/dsh-llm";
|
|
1906
2018
|
var DISCOVERY_TIMEOUT_MS = 2e4;
|
|
@@ -2030,6 +2142,306 @@ async function fetchModelCatalog(openAiBaseURL2, key, signal, fetcher) {
|
|
|
2030
2142
|
return normalize(await boundedJson(response, signal, deadline));
|
|
2031
2143
|
}
|
|
2032
2144
|
|
|
2145
|
+
// src/pricing.ts
|
|
2146
|
+
var PRICING_ORIGIN = "https://corouter.open-design.ai";
|
|
2147
|
+
var PRICING_CATALOG_PATH = "/zh/models/";
|
|
2148
|
+
var PRICING_TIMEOUT_MS = 15e3;
|
|
2149
|
+
var MAX_PRICING_BODY_BYTES = 4 * 1024 * 1024;
|
|
2150
|
+
var MESSAGES3 = {
|
|
2151
|
+
timeout: "\u5B98\u7F51\u4EF7\u683C\u8BF7\u6C42\u8D85\u8FC7\u65F6\u9650",
|
|
2152
|
+
aborted: "\u5B98\u7F51\u4EF7\u683C\u8BF7\u6C42\u5DF2\u53D6\u6D88",
|
|
2153
|
+
network: "\u65E0\u6CD5\u8FDE\u63A5\u5B98\u7F51",
|
|
2154
|
+
status: "\u5B98\u7F51\u8FD4\u56DE\u4E86\u975E 200 \u72B6\u6001",
|
|
2155
|
+
"too-large": "\u5B98\u7F51\u4EF7\u683C\u54CD\u5E94\u4F53\u8D85\u8FC7\u4E0A\u9650",
|
|
2156
|
+
"invalid-page": "\u62FF\u5230\u7684\u9875\u9762\u4E0D\u662F\u5B98\u7F51\u6A21\u578B\u4EF7\u683C\u9875",
|
|
2157
|
+
"invalid-model": "\u62FF\u5230\u7684\u9875\u9762\u4E0D\u662F\u5B98\u7F51\u6A21\u578B\u4EF7\u683C\u8BE6\u60C5\u9875"
|
|
2158
|
+
};
|
|
2159
|
+
var PricingError = class extends Error {
|
|
2160
|
+
constructor(kind, status) {
|
|
2161
|
+
super(MESSAGES3[kind]);
|
|
2162
|
+
this.kind = kind;
|
|
2163
|
+
this.status = status;
|
|
2164
|
+
this.name = "PricingError";
|
|
2165
|
+
}
|
|
2166
|
+
kind;
|
|
2167
|
+
status;
|
|
2168
|
+
};
|
|
2169
|
+
var ENTITIES = {
|
|
2170
|
+
""": '"',
|
|
2171
|
+
"&": "&",
|
|
2172
|
+
"<": "<",
|
|
2173
|
+
">": ">",
|
|
2174
|
+
"'": "'",
|
|
2175
|
+
" ": " ",
|
|
2176
|
+
"—": "\u2014",
|
|
2177
|
+
"–": "\u2013"
|
|
2178
|
+
};
|
|
2179
|
+
function decodeEntities(text2) {
|
|
2180
|
+
return text2.replace(/&(?:quot|amp|lt|gt|apos|nbsp|mdash|ndash);/gu, (match) => ENTITIES[match] ?? match).replace(/&#(\d+);/gu, (_match, code) => {
|
|
2181
|
+
const point = Number(code);
|
|
2182
|
+
return Number.isInteger(point) && point > 0 && point <= 1114111 ? String.fromCodePoint(point) : "";
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
function stripTags(text2) {
|
|
2186
|
+
return decodeEntities(text2.replace(/<[^>]*>/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2187
|
+
}
|
|
2188
|
+
function metricOf(label) {
|
|
2189
|
+
if (/缓存读取|cache\s+read/iu.test(label)) return "cacheRead";
|
|
2190
|
+
if (/缓存写入|cache\s+write/iu.test(label)) return "cacheWrite";
|
|
2191
|
+
if (/^\s*(?:输入|input)/iu.test(label)) return "input";
|
|
2192
|
+
if (/^\s*(?:输出|output)/iu.test(label)) return "output";
|
|
2193
|
+
return void 0;
|
|
2194
|
+
}
|
|
2195
|
+
function unitOf(label) {
|
|
2196
|
+
if (/百万\s*token|1m\s*tokens?/iu.test(label)) return "per_1m_tokens";
|
|
2197
|
+
if (/千\s*token|1k\s*tokens?/iu.test(label)) return "per_1k_tokens";
|
|
2198
|
+
return null;
|
|
2199
|
+
}
|
|
2200
|
+
function currencyOf(value) {
|
|
2201
|
+
if (value.includes("$")) return "USD";
|
|
2202
|
+
return null;
|
|
2203
|
+
}
|
|
2204
|
+
function priceOf(value) {
|
|
2205
|
+
const text2 = value.replace(/[$\u20ac\u00a3\u00a5\u00a4,\s]/gu, "");
|
|
2206
|
+
if (text2 === "" || /^[–—−\-]+$/u.test(text2)) return null;
|
|
2207
|
+
const parsed = Number(text2);
|
|
2208
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
2209
|
+
}
|
|
2210
|
+
var MODEL_ID2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
2211
|
+
var SLUG = /^[a-z0-9][a-z0-9-]{0,127}$/u;
|
|
2212
|
+
function slugOf(href) {
|
|
2213
|
+
const match = /\/models\/([A-Za-z0-9._-]+)\/?(?:#.*)?$/u.exec(href);
|
|
2214
|
+
if (!match) return null;
|
|
2215
|
+
const slug = match[1];
|
|
2216
|
+
return SLUG.test(slug) ? slug : null;
|
|
2217
|
+
}
|
|
2218
|
+
function trimPanelBody(body) {
|
|
2219
|
+
const anchor = /<a\b[^>]*class="[^"]*\bmodel-explorer-detail-link\b[^"]*"[^>]*>/u.exec(body);
|
|
2220
|
+
if (!anchor) return body;
|
|
2221
|
+
const close = body.indexOf("</a>", anchor.index + anchor[0].length);
|
|
2222
|
+
if (close < 0) return body.slice(0, anchor.index);
|
|
2223
|
+
return body.slice(0, close + 4);
|
|
2224
|
+
}
|
|
2225
|
+
function collectPanels(html) {
|
|
2226
|
+
const openTag = /<div\b[^>]*class="[^"]*\bmodel-explorer-panel\b[^"]*"[^>]*>/gu;
|
|
2227
|
+
const opens = [];
|
|
2228
|
+
for (const match of html.matchAll(openTag)) {
|
|
2229
|
+
const id = /data-model-panel="([^"]*)"/u.exec(match[0])?.[1];
|
|
2230
|
+
if (!id || !MODEL_ID2.test(id)) continue;
|
|
2231
|
+
opens.push({ id, start: match.index, end: match.index + match[0].length });
|
|
2232
|
+
}
|
|
2233
|
+
const panels = [];
|
|
2234
|
+
for (let index = 0; index < opens.length; index += 1) {
|
|
2235
|
+
const open = opens[index];
|
|
2236
|
+
const next = opens[index + 1];
|
|
2237
|
+
const body = html.slice(open.end, next ? next.start : html.length);
|
|
2238
|
+
panels.push({ id: open.id, body: trimPanelBody(body) });
|
|
2239
|
+
}
|
|
2240
|
+
return panels;
|
|
2241
|
+
}
|
|
2242
|
+
function collectProviders(html) {
|
|
2243
|
+
const providers = /* @__PURE__ */ new Map();
|
|
2244
|
+
for (const match of html.matchAll(/<button\b[^>]*>/gu)) {
|
|
2245
|
+
const tag = match[0];
|
|
2246
|
+
const id = /data-model-tab="([^"]*)"/u.exec(tag)?.[1];
|
|
2247
|
+
const provider = /data-provider="([^"]*)"/u.exec(tag)?.[1];
|
|
2248
|
+
if (!id || !provider) continue;
|
|
2249
|
+
providers.set(id, provider.trim());
|
|
2250
|
+
}
|
|
2251
|
+
return providers;
|
|
2252
|
+
}
|
|
2253
|
+
function collectTiers(body) {
|
|
2254
|
+
const marker = /<div\b[^>]*class="[^"]*\bmodel-explorer-tier\b[^"]*"[^>]*>/gu;
|
|
2255
|
+
const starts = [];
|
|
2256
|
+
for (const match of body.matchAll(marker)) starts.push(match.index);
|
|
2257
|
+
const tiers = [];
|
|
2258
|
+
for (let index = 0; index < starts.length; index += 1) {
|
|
2259
|
+
const start = starts[index];
|
|
2260
|
+
const end = index + 1 < starts.length ? starts[index + 1] : body.length;
|
|
2261
|
+
const chunk = body.slice(start, end);
|
|
2262
|
+
const label = stripTags(/<h4[^>]*>([\s\S]*?)<\/h4>/u.exec(chunk)?.[1] ?? "");
|
|
2263
|
+
const metrics = /* @__PURE__ */ new Map();
|
|
2264
|
+
for (const metric of chunk.matchAll(/<dt[^>]*>([\s\S]*?)<\/dt>\s*<dd([^>]*)>([\s\S]*?)<\/dd>/gu)) {
|
|
2265
|
+
const labelText = stripTags(metric[1] ?? "");
|
|
2266
|
+
const key = metricOf(labelText);
|
|
2267
|
+
if (!key) continue;
|
|
2268
|
+
const value = stripTags(metric[3] ?? "");
|
|
2269
|
+
metrics.set(key, { price: priceOf(value), currency: currencyOf(value), unit: unitOf(labelText) });
|
|
2270
|
+
}
|
|
2271
|
+
tiers.push({ label, metrics });
|
|
2272
|
+
}
|
|
2273
|
+
return tiers;
|
|
2274
|
+
}
|
|
2275
|
+
function hasCatalogMarker(html) {
|
|
2276
|
+
return /data-page-name="corouter_models"/u.test(html);
|
|
2277
|
+
}
|
|
2278
|
+
function commonCurrency(values) {
|
|
2279
|
+
const seen = new Set(values.filter((value) => value !== null));
|
|
2280
|
+
if (seen.size !== 1) return null;
|
|
2281
|
+
return seen.values().next().value ?? null;
|
|
2282
|
+
}
|
|
2283
|
+
function commonUnit(values) {
|
|
2284
|
+
const seen = new Set(values.filter((value) => value !== null));
|
|
2285
|
+
if (seen.size !== 1) return null;
|
|
2286
|
+
return seen.values().next().value ?? null;
|
|
2287
|
+
}
|
|
2288
|
+
function parsePricingCatalog(html) {
|
|
2289
|
+
if (!hasCatalogMarker(html)) throw new PricingError("invalid-page");
|
|
2290
|
+
const panels = collectPanels(html);
|
|
2291
|
+
if (panels.length === 0) throw new PricingError("invalid-page");
|
|
2292
|
+
const providers = collectProviders(html);
|
|
2293
|
+
const models = [];
|
|
2294
|
+
for (const panel of panels) {
|
|
2295
|
+
const name2 = stripTags(/<h3[^>]*>([\s\S]*?)<\/h3>/u.exec(panel.body)?.[1] ?? "");
|
|
2296
|
+
const href = /<a\b[^>]*class="[^"]*\bmodel-explorer-detail-link\b[^"]*"[^>]*href="([^"]*)"/u.exec(panel.body)?.[1] ?? "";
|
|
2297
|
+
const slug = slugOf(href);
|
|
2298
|
+
const tiers = collectTiers(panel.body).map((draft, index) => {
|
|
2299
|
+
const input = draft.metrics.get("input");
|
|
2300
|
+
const output = draft.metrics.get("output");
|
|
2301
|
+
const cacheRead = draft.metrics.get("cacheRead");
|
|
2302
|
+
const cacheWrite = draft.metrics.get("cacheWrite");
|
|
2303
|
+
const priced = [input, output, cacheRead, cacheWrite].filter((value) => value !== void 0 && value.price !== null);
|
|
2304
|
+
if (!draft.label || new Set(priced.map((value) => value.currency)).size > 1 || new Set(priced.map((value) => value.unit)).size > 1) throw new PricingError("invalid-page");
|
|
2305
|
+
return {
|
|
2306
|
+
index,
|
|
2307
|
+
label: draft.label,
|
|
2308
|
+
input: input?.price ?? null,
|
|
2309
|
+
output: output?.price ?? null,
|
|
2310
|
+
cacheRead: cacheRead?.price ?? null,
|
|
2311
|
+
cacheWrite: cacheWrite?.price ?? null,
|
|
2312
|
+
currency: input?.currency ?? output?.currency ?? cacheRead?.currency ?? cacheWrite?.currency ?? null,
|
|
2313
|
+
unit: input?.unit ?? output?.unit ?? cacheRead?.unit ?? cacheWrite?.unit ?? null
|
|
2314
|
+
};
|
|
2315
|
+
});
|
|
2316
|
+
models.push({
|
|
2317
|
+
id: panel.id,
|
|
2318
|
+
name: name2 === "" ? panel.id : name2,
|
|
2319
|
+
provider: providers.get(panel.id) ?? null,
|
|
2320
|
+
slug,
|
|
2321
|
+
detailUrl: slug ? `${PRICING_ORIGIN}${PRICING_CATALOG_PATH}${slug}/` : null,
|
|
2322
|
+
tiers
|
|
2323
|
+
});
|
|
2324
|
+
}
|
|
2325
|
+
return {
|
|
2326
|
+
models,
|
|
2327
|
+
currency: commonCurrency(models.flatMap((model) => model.tiers.map((tier) => tier.currency))),
|
|
2328
|
+
unit: commonUnit(models.flatMap((model) => model.tiers.map((tier) => tier.unit)))
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
function classify2(error, signal, combined) {
|
|
2332
|
+
if (error instanceof PricingError) return error;
|
|
2333
|
+
const name2 = error?.name;
|
|
2334
|
+
if (signal?.aborted) return new PricingError("aborted");
|
|
2335
|
+
if (name2 === "TimeoutError" || combined.aborted) return new PricingError("timeout");
|
|
2336
|
+
return new PricingError("network");
|
|
2337
|
+
}
|
|
2338
|
+
async function readBounded(response, maxBytes, signal, combined) {
|
|
2339
|
+
const reader = response.body?.getReader();
|
|
2340
|
+
if (!reader) throw new PricingError("invalid-page");
|
|
2341
|
+
const declared = Number(response.headers.get("content-length"));
|
|
2342
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
2343
|
+
void reader.cancel().catch(() => void 0);
|
|
2344
|
+
reader.releaseLock();
|
|
2345
|
+
throw new PricingError("too-large");
|
|
2346
|
+
}
|
|
2347
|
+
let size = 0;
|
|
2348
|
+
let raw = "";
|
|
2349
|
+
const decoder = new TextDecoder();
|
|
2350
|
+
const cancel = () => {
|
|
2351
|
+
void reader.cancel().catch(() => void 0);
|
|
2352
|
+
};
|
|
2353
|
+
combined.addEventListener("abort", cancel, { once: true });
|
|
2354
|
+
try {
|
|
2355
|
+
if (combined.aborted) throw classify2(combined.reason, signal, combined);
|
|
2356
|
+
while (true) {
|
|
2357
|
+
const chunk = await reader.read();
|
|
2358
|
+
if (combined.aborted) throw classify2(combined.reason, signal, combined);
|
|
2359
|
+
if (chunk.done) break;
|
|
2360
|
+
size += chunk.value.byteLength;
|
|
2361
|
+
if (size > maxBytes) throw new PricingError("too-large");
|
|
2362
|
+
raw += decoder.decode(chunk.value, { stream: true });
|
|
2363
|
+
}
|
|
2364
|
+
raw += decoder.decode();
|
|
2365
|
+
} catch (error) {
|
|
2366
|
+
if (error instanceof PricingError) throw error;
|
|
2367
|
+
throw classify2(error, signal, combined);
|
|
2368
|
+
} finally {
|
|
2369
|
+
combined.removeEventListener("abort", cancel);
|
|
2370
|
+
cancel();
|
|
2371
|
+
reader.releaseLock();
|
|
2372
|
+
}
|
|
2373
|
+
return raw;
|
|
2374
|
+
}
|
|
2375
|
+
async function fetchHtml(url, options, timeoutMs, maxBytes) {
|
|
2376
|
+
const request = options.fetcher ?? fetch;
|
|
2377
|
+
const combined = combinedSignal(options.signal, timeoutMs);
|
|
2378
|
+
let response;
|
|
2379
|
+
try {
|
|
2380
|
+
response = await request(url, {
|
|
2381
|
+
method: "GET",
|
|
2382
|
+
headers: { accept: "text/html" },
|
|
2383
|
+
signal: combined,
|
|
2384
|
+
redirect: "error",
|
|
2385
|
+
credentials: "omit"
|
|
2386
|
+
});
|
|
2387
|
+
} catch (error) {
|
|
2388
|
+
throw classify2(error, options.signal, combined);
|
|
2389
|
+
}
|
|
2390
|
+
if (combined.aborted) {
|
|
2391
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2392
|
+
throw classify2(combined.reason, options.signal, combined);
|
|
2393
|
+
}
|
|
2394
|
+
if (response.redirected || response.url && response.url !== url) {
|
|
2395
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2396
|
+
throw new PricingError("invalid-page");
|
|
2397
|
+
}
|
|
2398
|
+
if (!response.ok) {
|
|
2399
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2400
|
+
throw new PricingError("status", response.status);
|
|
2401
|
+
}
|
|
2402
|
+
const contentType = response.headers.get("content-type");
|
|
2403
|
+
if (contentType !== null && !/text\/html|application\/xhtml\+xml/iu.test(contentType)) {
|
|
2404
|
+
void response.body?.cancel().catch(() => void 0);
|
|
2405
|
+
throw new PricingError("invalid-page");
|
|
2406
|
+
}
|
|
2407
|
+
return readBounded(response, maxBytes, options.signal, combined);
|
|
2408
|
+
}
|
|
2409
|
+
async function fetchPricingSnapshot(options = {}) {
|
|
2410
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
2411
|
+
const timeoutMs = options.timeoutMs ?? PRICING_TIMEOUT_MS;
|
|
2412
|
+
const maxBytes = options.maxBytes ?? MAX_PRICING_BODY_BYTES;
|
|
2413
|
+
const catalogUrl = `${PRICING_ORIGIN}${PRICING_CATALOG_PATH}`;
|
|
2414
|
+
const source = { kind: "official-website", origin: PRICING_ORIGIN, catalogUrl };
|
|
2415
|
+
const deadline = combinedSignal(options.signal, timeoutMs);
|
|
2416
|
+
let rejectAbort = () => void 0;
|
|
2417
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
2418
|
+
rejectAbort = reject;
|
|
2419
|
+
});
|
|
2420
|
+
const onAbort = () => rejectAbort(new PricingError(options.signal?.aborted ? "aborted" : "timeout"));
|
|
2421
|
+
deadline.addEventListener("abort", onAbort, { once: true });
|
|
2422
|
+
try {
|
|
2423
|
+
if (deadline.aborted) throw classify2(deadline.reason, options.signal, deadline);
|
|
2424
|
+
const html = await Promise.race([fetchHtml(catalogUrl, { ...options, signal: deadline }, timeoutMs, maxBytes), aborted]);
|
|
2425
|
+
const catalog = parsePricingCatalog(html);
|
|
2426
|
+
return {
|
|
2427
|
+
status: "ok",
|
|
2428
|
+
source,
|
|
2429
|
+
fetchedAt: now().toISOString(),
|
|
2430
|
+
currency: catalog.currency,
|
|
2431
|
+
unit: catalog.unit,
|
|
2432
|
+
models: catalog.models,
|
|
2433
|
+
issues: []
|
|
2434
|
+
};
|
|
2435
|
+
} catch (error) {
|
|
2436
|
+
const failure = deadline.aborted && !options.signal?.aborted ? new PricingError("timeout") : classify2(error, options.signal, deadline);
|
|
2437
|
+
const issue = { code: failure.kind, message: failure.message, url: catalogUrl };
|
|
2438
|
+
if (failure.status !== void 0) issue.status = failure.status;
|
|
2439
|
+
return { status: "failed", source, fetchedAt: now().toISOString(), currency: null, unit: null, models: [], issues: [issue] };
|
|
2440
|
+
} finally {
|
|
2441
|
+
deadline.removeEventListener("abort", onAbort);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2033
2445
|
// src/auth.ts
|
|
2034
2446
|
import { readFile as fsReadFile } from "node:fs/promises";
|
|
2035
2447
|
import { homedir as osHomedir } from "node:os";
|
|
@@ -2235,11 +2647,11 @@ async function resolveSession(deps = {}) {
|
|
|
2235
2647
|
}
|
|
2236
2648
|
|
|
2237
2649
|
// src/login.ts
|
|
2238
|
-
import { randomUUID } from "node:crypto";
|
|
2650
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
2239
2651
|
|
|
2240
2652
|
// src/device-auth.ts
|
|
2241
2653
|
var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
|
|
2242
|
-
var DEVICE_AUTH_PLUGIN_VERSION = "0.1.
|
|
2654
|
+
var DEVICE_AUTH_PLUGIN_VERSION = "0.1.11";
|
|
2243
2655
|
var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
|
|
2244
2656
|
var DEVICE_RESPONSE_MAX_BYTES = 65536;
|
|
2245
2657
|
var DEVICE_POLL_MIN_MS = 1e3;
|
|
@@ -2473,7 +2885,7 @@ var ConsoleLogin = class {
|
|
|
2473
2885
|
const requested = this.options.timeoutMs;
|
|
2474
2886
|
const timeoutMs = typeof requested === "number" && Number.isFinite(requested) && requested > 0 ? Math.min(MAX_TIMEOUT_MS, requested) : MAX_TIMEOUT_MS;
|
|
2475
2887
|
const job = {
|
|
2476
|
-
id:
|
|
2888
|
+
id: randomUUID2(),
|
|
2477
2889
|
controller: new AbortController(),
|
|
2478
2890
|
deadline: started + timeoutMs,
|
|
2479
2891
|
status: { jobId: null, state: "launching", startedAt: new Date(started).toISOString(), message: "\u6B63\u5728\u7533\u8BF7\u5B98\u65B9\u8BBE\u5907\u6388\u6743\u7801" },
|
|
@@ -3183,7 +3595,7 @@ var MAX_WINDOWS = 64;
|
|
|
3183
3595
|
var MAX_API_KEY = 16384;
|
|
3184
3596
|
var HTTP_ASCII = /^[\x21-\x7e]+$/u;
|
|
3185
3597
|
var ENV_REF = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
3186
|
-
var
|
|
3598
|
+
var MODEL_ID3 = /^[A-Za-z0-9._:/-]{1,128}$/u;
|
|
3187
3599
|
var ACTIVATION_OPEN_CODES = ["opened", "no-link", "invalid-url", "unavailable", "failed"];
|
|
3188
3600
|
var LOGIN_PHASES = ["idle", "launching", "waiting", "verifying", "success", "cancelled", "error"];
|
|
3189
3601
|
var QUOTA_STATES = ["ok", "partial", "need-login", "error"];
|
|
@@ -3224,6 +3636,40 @@ function member(value, allowed, label) {
|
|
|
3224
3636
|
if (hit === void 0) throw new Error(`${label} \u4E0D\u5728\u5141\u8BB8\u7684\u53D6\u503C\u5185`);
|
|
3225
3637
|
return hit;
|
|
3226
3638
|
}
|
|
3639
|
+
function parsePriceCatalog(value) {
|
|
3640
|
+
if (!record(value) || !Array.isArray(value.models) || value.models.length > MAX_MODELS2) throw new Error("\u4EF7\u683C\u76EE\u5F55\u683C\u5F0F\u65E0\u6548");
|
|
3641
|
+
const state = member(value.state, ["ok", "partial", "error"], "\u4EF7\u683C\u76EE\u5F55\u72B6\u6001");
|
|
3642
|
+
const stale = flag(value.stale, "\u4EF7\u683C\u7F13\u5B58\u72B6\u6001");
|
|
3643
|
+
const fetchedAt = value.fetchedAt === void 0 ? void 0 : isoTime(value.fetchedAt, "\u4EF7\u683C\u66F4\u65B0\u65F6\u95F4");
|
|
3644
|
+
if (stale && fetchedAt === void 0) throw new Error("\u8FC7\u671F\u4EF7\u683C\u5FC5\u987B\u6807\u6CE8\u66F4\u65B0\u65F6\u95F4");
|
|
3645
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3646
|
+
const nullableAmount = (item) => {
|
|
3647
|
+
if (item === null) return null;
|
|
3648
|
+
const result = amount(item, "\u4EF7\u683C");
|
|
3649
|
+
if (result > 1e6) throw new Error("\u4EF7\u683C\u8D85\u51FA\u8303\u56F4");
|
|
3650
|
+
return result;
|
|
3651
|
+
};
|
|
3652
|
+
const models = value.models.map((model) => {
|
|
3653
|
+
if (!record(model) || !Array.isArray(model.tiers) || model.tiers.length === 0 || model.tiers.length > 8) throw new Error("\u6A21\u578B\u4EF7\u683C\u683C\u5F0F\u65E0\u6548");
|
|
3654
|
+
const id = text(model.id, "\u6A21\u578B id", 128);
|
|
3655
|
+
if (!MODEL_ID3.test(id) || ids.has(id)) throw new Error("\u6A21\u578B\u4EF7\u683C id \u65E0\u6548\u6216\u91CD\u590D");
|
|
3656
|
+
ids.add(id);
|
|
3657
|
+
const tiers = model.tiers.map((tier) => {
|
|
3658
|
+
if (!record(tier)) throw new Error("\u4EF7\u683C\u6863\u4F4D\u683C\u5F0F\u65E0\u6548");
|
|
3659
|
+
return {
|
|
3660
|
+
label: text(tier.label, "\u4EF7\u683C\u6863\u4F4D", 128),
|
|
3661
|
+
currency: tier.currency === null ? null : member(tier.currency, ["USD"], "\u4EF7\u683C\u5E01\u79CD"),
|
|
3662
|
+
unit: tier.unit === null ? null : member(tier.unit, ["per_1m_tokens", "per_1k_tokens"], "\u4EF7\u683C\u5355\u4F4D"),
|
|
3663
|
+
input: nullableAmount(tier.input),
|
|
3664
|
+
output: nullableAmount(tier.output),
|
|
3665
|
+
cacheRead: nullableAmount(tier.cacheRead),
|
|
3666
|
+
cacheWrite: nullableAmount(tier.cacheWrite)
|
|
3667
|
+
};
|
|
3668
|
+
});
|
|
3669
|
+
return { id, tiers };
|
|
3670
|
+
});
|
|
3671
|
+
return { state, stale, ...fetchedAt === void 0 ? {} : { fetchedAt }, models };
|
|
3672
|
+
}
|
|
3227
3673
|
function parseQuotaWindow(value) {
|
|
3228
3674
|
if (!record(value)) throw new Error("\u989D\u5EA6\u7A97\u53E3\u5FC5\u987B\u662F\u5BF9\u8C61");
|
|
3229
3675
|
const durationSeconds = amount(value.durationSeconds, "\u989D\u5EA6\u7A97\u53E3\u65F6\u957F");
|
|
@@ -3293,7 +3739,7 @@ function parseLoginState(value) {
|
|
|
3293
3739
|
function parseStatusModel(value) {
|
|
3294
3740
|
if (!record(value)) throw new Error("\u6A21\u578B\u6761\u76EE\u5FC5\u987B\u662F\u5BF9\u8C61");
|
|
3295
3741
|
const id = text(value.id, "\u6A21\u578B id", 128);
|
|
3296
|
-
if (!
|
|
3742
|
+
if (!MODEL_ID3.test(id)) throw new Error("\u6A21\u578B id \u542B\u4E0D\u5141\u8BB8\u7684\u5B57\u7B26");
|
|
3297
3743
|
return {
|
|
3298
3744
|
id,
|
|
3299
3745
|
name: text(value.name, "\u6A21\u578B\u540D", 128),
|
|
@@ -3383,8 +3829,8 @@ function grantOf(value) {
|
|
|
3383
3829
|
if (typeof value.payload.cookie !== "string") return;
|
|
3384
3830
|
return { cookie: value.payload.cookie, ...typeof value.payload.expiresAt === "number" ? { expiresAt: value.payload.expiresAt } : {} };
|
|
3385
3831
|
}
|
|
3386
|
-
var _saveApiKey_dec, _openActivationPage_dec, _cancelLogin_dec, _loginStatus_dec, _startLogin_dec, _refreshQuotaNow_dec, _refreshQuota_dec, _refreshModels_dec, _status_dec, _a, _init;
|
|
3387
|
-
var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status_dec = [Remote("status")], _refreshModels_dec = [Remote("refreshModels")], _refreshQuota_dec = [Remote("refreshQuota")], _refreshQuotaNow_dec = [Remote("refreshQuotaNow")], _startLogin_dec = [Remote("startLogin")], _loginStatus_dec = [Remote("loginStatus")], _cancelLogin_dec = [Remote("cancelLogin")], _openActivationPage_dec = [Remote("openActivationPage")], _saveApiKey_dec = [Remote("saveApiKey")], _a) {
|
|
3832
|
+
var _saveApiKey_dec, _openActivationPage_dec, _cancelLogin_dec, _loginStatus_dec, _startLogin_dec, _refreshQuotaNow_dec, _refreshQuota_dec, _refreshPrices_dec, _refreshModels_dec, _status_dec, _a, _init;
|
|
3833
|
+
var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status_dec = [Remote("status")], _refreshModels_dec = [Remote("refreshModels")], _refreshPrices_dec = [Remote("refreshPrices")], _refreshQuota_dec = [Remote("refreshQuota")], _refreshQuotaNow_dec = [Remote("refreshQuotaNow")], _startLogin_dec = [Remote("startLogin")], _loginStatus_dec = [Remote("loginStatus")], _cancelLogin_dec = [Remote("cancelLogin")], _openActivationPage_dec = [Remote("openActivationPage")], _saveApiKey_dec = [Remote("saveApiKey")], _a) {
|
|
3388
3834
|
constructor(ctx, config, dependencies = { resolveSession, readQuota, readDesktopQuota }) {
|
|
3389
3835
|
super(ctx, "openDesignCoRouter");
|
|
3390
3836
|
this.dependencies = dependencies;
|
|
@@ -3393,7 +3839,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
3393
3839
|
__publicField(this, "_login");
|
|
3394
3840
|
__publicField(this, "_activation");
|
|
3395
3841
|
__publicField(this, "_lifetime", new AbortController());
|
|
3396
|
-
__publicField(this, "_revision",
|
|
3842
|
+
__publicField(this, "_revision", randomUUID3());
|
|
3397
3843
|
__publicField(this, "_fingerprint", "");
|
|
3398
3844
|
__publicField(this, "_quota", unreadQuota());
|
|
3399
3845
|
__publicField(this, "_quotaAt", 0);
|
|
@@ -3410,6 +3856,8 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
3410
3856
|
__publicField(this, "_modelsEpoch", 0);
|
|
3411
3857
|
__publicField(this, "_modelsPending");
|
|
3412
3858
|
__publicField(this, "_modelsController");
|
|
3859
|
+
__publicField(this, "_prices");
|
|
3860
|
+
__publicField(this, "_pricesPending");
|
|
3413
3861
|
this._config = config;
|
|
3414
3862
|
this._login = new ConsoleLogin({
|
|
3415
3863
|
capture: async (expectedRevision) => {
|
|
@@ -3500,7 +3948,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
3500
3948
|
const fingerprint = hash(state);
|
|
3501
3949
|
if (fingerprint !== this._fingerprint) {
|
|
3502
3950
|
this._fingerprint = fingerprint;
|
|
3503
|
-
this._revision =
|
|
3951
|
+
this._revision = randomUUID3();
|
|
3504
3952
|
}
|
|
3505
3953
|
return state;
|
|
3506
3954
|
}
|
|
@@ -3593,6 +4041,31 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
3593
4041
|
if (this._modelsPending === run) this._modelsPending = void 0;
|
|
3594
4042
|
}
|
|
3595
4043
|
}
|
|
4044
|
+
async refreshPrices() {
|
|
4045
|
+
if (this._pricesPending) return this._pricesPending;
|
|
4046
|
+
const run = (async () => {
|
|
4047
|
+
try {
|
|
4048
|
+
const result = await (this.dependencies.fetchPrices ?? fetchPricingSnapshot)({ signal: this._lifetime.signal });
|
|
4049
|
+
if (this._lifetime.signal.aborted || result.status === "failed") throw new Error("price unavailable");
|
|
4050
|
+
const next = parsePriceCatalog({
|
|
4051
|
+
state: result.status,
|
|
4052
|
+
stale: false,
|
|
4053
|
+
fetchedAt: result.fetchedAt,
|
|
4054
|
+
models: result.models.map(({ id, tiers }) => ({ id, tiers }))
|
|
4055
|
+
});
|
|
4056
|
+
this._prices = next;
|
|
4057
|
+
return next;
|
|
4058
|
+
} catch {
|
|
4059
|
+
return this._prices === void 0 ? { state: "error", stale: false, models: [] } : { ...this._prices, state: "error", stale: true };
|
|
4060
|
+
}
|
|
4061
|
+
})();
|
|
4062
|
+
this._pricesPending = run;
|
|
4063
|
+
try {
|
|
4064
|
+
return await run;
|
|
4065
|
+
} finally {
|
|
4066
|
+
if (this._pricesPending === run) this._pricesPending = void 0;
|
|
4067
|
+
}
|
|
4068
|
+
}
|
|
3596
4069
|
async refreshQuota() {
|
|
3597
4070
|
return this._refreshQuota(false);
|
|
3598
4071
|
}
|
|
@@ -3732,6 +4205,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
|
|
|
3732
4205
|
_init = __decoratorStart(_a);
|
|
3733
4206
|
__decorateElement(_init, 1, "status", _status_dec, OpenDesignCoRouterService);
|
|
3734
4207
|
__decorateElement(_init, 1, "refreshModels", _refreshModels_dec, OpenDesignCoRouterService);
|
|
4208
|
+
__decorateElement(_init, 1, "refreshPrices", _refreshPrices_dec, OpenDesignCoRouterService);
|
|
3735
4209
|
__decorateElement(_init, 1, "refreshQuota", _refreshQuota_dec, OpenDesignCoRouterService);
|
|
3736
4210
|
__decorateElement(_init, 1, "refreshQuotaNow", _refreshQuotaNow_dec, OpenDesignCoRouterService);
|
|
3737
4211
|
__decorateElement(_init, 1, "startLogin", _startLogin_dec, OpenDesignCoRouterService);
|
|
@@ -3743,6 +4217,7 @@ __decoratorMetadata(_init, OpenDesignCoRouterService);
|
|
|
3743
4217
|
function apply(ctx, config) {
|
|
3744
4218
|
const current = () => readConfig(config);
|
|
3745
4219
|
current();
|
|
4220
|
+
installEotRecovery(ctx, () => current().emptyTurnGuard);
|
|
3746
4221
|
ctx.inject(["settings"], (scope) => scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber)));
|
|
3747
4222
|
let modelsChanged = () => {
|
|
3748
4223
|
};
|