dsh-model-think-level 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -4
- package/lib/autofill.d.ts +20 -2
- package/lib/client/ConfigPane.d.ts +6 -6
- package/lib/client/image-config-client.d.ts +6 -23
- package/lib/client/index.d.ts +1 -0
- package/lib/client/injection/compat-guard.d.ts +33 -0
- package/lib/client/injection/image-card.d.ts +19 -7
- package/lib/client/injection/key-prefetch.d.ts +13 -1
- package/lib/client/injection/model-order-drag.d.ts +1 -1
- package/lib/client/injection/models-page-editor.d.ts +1 -2
- package/lib/client/injection/models-page-mutation.d.ts +6 -0
- package/lib/client/injection/provider-balance.d.ts +12 -1
- package/lib/client/injection/provider-delete-seat.d.ts +4 -1
- package/lib/client/injection/provider-disabled-group.d.ts +4 -1
- package/lib/client/injection/provider-order-drag.d.ts +5 -1
- package/lib/client/injection/provider-toggle.d.ts +4 -1
- package/lib/client/key-manager-client.d.ts +21 -9
- package/lib/client/locales.d.ts +7 -25
- package/lib/client/model-order.d.ts +9 -0
- package/lib/client/order-sync.d.ts +74 -0
- package/lib/client/provider-enabled.d.ts +11 -0
- package/lib/client/styles.d.ts +1 -1
- package/lib/client.js +22 -166
- package/lib/client.js.map +4 -4
- package/lib/constants.d.ts +15 -7
- package/lib/image/command.d.ts +1 -1
- package/lib/image/deadline.d.ts +13 -0
- package/lib/image/generate.d.ts +8 -5
- package/lib/image/tool.d.ts +12 -3
- package/lib/index.js +848 -334
- package/lib/index.js.map +4 -4
- package/lib/key-index.d.ts +11 -0
- package/lib/knowledge.d.ts +26 -0
- package/lib/order-store.d.ts +100 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -11,13 +11,14 @@ var BALANCE_PATH = "/dsh-model-think-level/balance";
|
|
|
11
11
|
var AUTOFILL_CONFIG_PATH = "/dsh-model-think-level/autofill-config";
|
|
12
12
|
var HEADERS_CONFIG_PATH = "/dsh-model-think-level/headers-config";
|
|
13
13
|
var FINGERPRINT_PATH = "/dsh-model-think-level/fingerprint";
|
|
14
|
+
var ORDER_PATH = "/dsh-model-think-level/ui-order";
|
|
15
|
+
var ORDER_FILE = "ui-order.json";
|
|
14
16
|
var PI_AI_NS = "llm-pi-ai";
|
|
15
17
|
var UNSET_MARKER = "reasoningEffortsUnset";
|
|
16
18
|
var INPUT_UNSET_MARKER = "inputUnset";
|
|
17
19
|
var INPUT_IMAGE_GEN_MARKER = "inputImageGen";
|
|
18
20
|
var AUTOFILL_MARKER = "reasoningEffortsAutofilled";
|
|
19
21
|
var IMAGE_CONFIG_PATH = "/dsh-model-think-level/image-config";
|
|
20
|
-
var IMAGE_GENERATE_PATH = "/dsh-model-think-level/image-generate";
|
|
21
22
|
var IMAGE_CONFIG_FILE = "image.json";
|
|
22
23
|
var IMAGE_MCP_PATCH_ID = "dsh-image-mcp";
|
|
23
24
|
var IMAGE_MCP_PATCH_MARK = "dsh-model-think-level:image-mcp";
|
|
@@ -325,6 +326,18 @@ function withoutKeyEntry(document, route, ref) {
|
|
|
325
326
|
else providers[route] = list;
|
|
326
327
|
return { version: 1, providers, ...endpointsOf(document), ...balancesOf(document) };
|
|
327
328
|
}
|
|
329
|
+
function withoutRoute(document, route) {
|
|
330
|
+
const providers = { ...document.providers };
|
|
331
|
+
delete providers[route];
|
|
332
|
+
const endpoints = document.endpoints === void 0 ? void 0 : { ...document.endpoints };
|
|
333
|
+
if (endpoints !== void 0) delete endpoints[route];
|
|
334
|
+
const balances = document.balances === void 0 ? void 0 : { ...document.balances };
|
|
335
|
+
if (balances !== void 0) delete balances[route];
|
|
336
|
+
let next = { version: 1, providers };
|
|
337
|
+
if (endpoints !== void 0 && Object.keys(endpoints).length > 0) next = { ...next, endpoints };
|
|
338
|
+
if (balances !== void 0 && Object.keys(balances).length > 0) next = { ...next, balances };
|
|
339
|
+
return next;
|
|
340
|
+
}
|
|
328
341
|
|
|
329
342
|
// src/key-route-core.ts
|
|
330
343
|
function canServe(key, model, knowledge) {
|
|
@@ -666,6 +679,110 @@ function withoutServes(document, route, ref) {
|
|
|
666
679
|
return { version: 1, providers };
|
|
667
680
|
}
|
|
668
681
|
|
|
682
|
+
// src/order-store.ts
|
|
683
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
684
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
685
|
+
function emptyUiOrder() {
|
|
686
|
+
return { version: 1, savedAt: 0, providerOrder: [], modelOrder: {}, providersDisabled: [] };
|
|
687
|
+
}
|
|
688
|
+
function uiOrderFilePath(home = harnessHome()) {
|
|
689
|
+
return join3(home, "dsh-model-think-level", ORDER_FILE);
|
|
690
|
+
}
|
|
691
|
+
function normalizeId(value) {
|
|
692
|
+
if (typeof value !== "string") return void 0;
|
|
693
|
+
const id = value.trim();
|
|
694
|
+
return id.length === 0 ? void 0 : id;
|
|
695
|
+
}
|
|
696
|
+
function normalizeIds(value) {
|
|
697
|
+
if (!Array.isArray(value)) return [];
|
|
698
|
+
return [...new Set(value.map(normalizeId).filter((id) => id !== void 0))];
|
|
699
|
+
}
|
|
700
|
+
function parseUiOrder(raw) {
|
|
701
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return emptyUiOrder();
|
|
702
|
+
const record = raw;
|
|
703
|
+
const savedAt = typeof record["savedAt"] === "number" && Number.isFinite(record["savedAt"]) ? record["savedAt"] : 0;
|
|
704
|
+
const rawProviders = record["providerOrder"];
|
|
705
|
+
const rawModels = record["modelOrder"];
|
|
706
|
+
const modelOrder = {};
|
|
707
|
+
if (typeof rawModels === "object" && rawModels !== null && !Array.isArray(rawModels)) {
|
|
708
|
+
for (const [provider, value] of Object.entries(rawModels)) {
|
|
709
|
+
if (provider.length === 0) continue;
|
|
710
|
+
const ids = normalizeIds(value);
|
|
711
|
+
if (ids.length > 0) modelOrder[provider] = ids;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return {
|
|
715
|
+
version: 1,
|
|
716
|
+
savedAt,
|
|
717
|
+
providerOrder: normalizeIds(rawProviders),
|
|
718
|
+
modelOrder,
|
|
719
|
+
providersDisabled: normalizeIds(record["providersDisabled"])
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
function mergeUiOrder(current, patch, at) {
|
|
723
|
+
if (typeof patch !== "object" || patch === null || Array.isArray(patch)) return current;
|
|
724
|
+
const record = patch;
|
|
725
|
+
const providers = record["providerOrder"];
|
|
726
|
+
const models = record["modelOrder"];
|
|
727
|
+
const disabled = record["providersDisabled"];
|
|
728
|
+
const savedAt = typeof record["savedAt"] === "number" && Number.isFinite(record["savedAt"]) ? record["savedAt"] : at;
|
|
729
|
+
const parsedModels = parseUiOrder({
|
|
730
|
+
version: 1,
|
|
731
|
+
savedAt,
|
|
732
|
+
providerOrder: Array.isArray(providers) ? providers : current.providerOrder,
|
|
733
|
+
modelOrder: typeof models === "object" && models !== null && !Array.isArray(models) ? models : current.modelOrder,
|
|
734
|
+
// An absent field keeps the stored set; an explicit empty ARRAY is a real
|
|
735
|
+
// "everything is on" and replaces it.
|
|
736
|
+
providersDisabled: Array.isArray(disabled) ? disabled : current.providersDisabled
|
|
737
|
+
});
|
|
738
|
+
return parsedModels;
|
|
739
|
+
}
|
|
740
|
+
function readUiOrder(file = uiOrderFilePath()) {
|
|
741
|
+
try {
|
|
742
|
+
return parseUiOrder(JSON.parse(readFileSync3(file, "utf8")));
|
|
743
|
+
} catch {
|
|
744
|
+
return emptyUiOrder();
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
function writeUiOrder(document, file = uiOrderFilePath()) {
|
|
748
|
+
mkdirSync3(dirname3(file), { recursive: true });
|
|
749
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
750
|
+
writeFileSync3(temporary, `${JSON.stringify(document, null, 2)}
|
|
751
|
+
`, "utf8");
|
|
752
|
+
try {
|
|
753
|
+
renameSync3(temporary, file);
|
|
754
|
+
} catch (error) {
|
|
755
|
+
try {
|
|
756
|
+
unlinkSync3(temporary);
|
|
757
|
+
} catch {
|
|
758
|
+
}
|
|
759
|
+
throw error;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
function savedAtOf(patch) {
|
|
763
|
+
if (typeof patch !== "object" || patch === null) return void 0;
|
|
764
|
+
const at = patch["savedAt"];
|
|
765
|
+
return typeof at === "number" && Number.isFinite(at) && at > 0 ? at : void 0;
|
|
766
|
+
}
|
|
767
|
+
function sameUiOrderContent(left, right) {
|
|
768
|
+
const shape = (document) => JSON.stringify([
|
|
769
|
+
document.providerOrder,
|
|
770
|
+
document.modelOrder,
|
|
771
|
+
document.providersDisabled
|
|
772
|
+
]);
|
|
773
|
+
return shape(left) === shape(right);
|
|
774
|
+
}
|
|
775
|
+
function commitUiOrderGuarded(patch, at, file = uiOrderFilePath()) {
|
|
776
|
+
const current = readUiOrder(file);
|
|
777
|
+
const incoming = savedAtOf(patch);
|
|
778
|
+
const merged = mergeUiOrder(current, patch, at);
|
|
779
|
+
if (incoming !== void 0 && incoming <= current.savedAt && !sameUiOrderContent(merged, current)) {
|
|
780
|
+
return { document: current, stale: true };
|
|
781
|
+
}
|
|
782
|
+
writeUiOrder(merged, file);
|
|
783
|
+
return { document: merged, stale: false };
|
|
784
|
+
}
|
|
785
|
+
|
|
669
786
|
// src/multi-key-listing.ts
|
|
670
787
|
var DEFAULT_PROBE_CONCURRENCY = 4;
|
|
671
788
|
var MODEL_ORDER = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
|
|
@@ -2570,6 +2687,7 @@ function inferProtocol(route) {
|
|
|
2570
2687
|
return "openai-completions";
|
|
2571
2688
|
}
|
|
2572
2689
|
var COMPAT_CAPABLE_PROTOCOL = "openai-completions";
|
|
2690
|
+
var RESPONSES_PROTOCOL = "openai-responses";
|
|
2573
2691
|
var ANTHROPIC_PROTOCOL = "anthropic-messages";
|
|
2574
2692
|
function isSelfHostedEndpoint(baseURL) {
|
|
2575
2693
|
if (baseURL === void 0 || baseURL.length === 0) return false;
|
|
@@ -2602,6 +2720,31 @@ function sanitizeCompatForProtocol(compat, api) {
|
|
|
2602
2720
|
delete copy["forceAdaptiveThinking"];
|
|
2603
2721
|
return Object.keys(copy).length === 0 ? void 0 : copy;
|
|
2604
2722
|
}
|
|
2723
|
+
var COMPLETIONS_ONLY_COMPAT = [
|
|
2724
|
+
"supportsReasoningEffort",
|
|
2725
|
+
"thinkingFormat",
|
|
2726
|
+
"thinkingTokenBudgetField",
|
|
2727
|
+
"supportsThinkingTokenBudget",
|
|
2728
|
+
"vllmPriority"
|
|
2729
|
+
];
|
|
2730
|
+
var ANTHROPIC_ONLY_COMPAT = ["forceAdaptiveThinking"];
|
|
2731
|
+
function stripForeignCompat(compat, api) {
|
|
2732
|
+
const norm2 = normalize(api);
|
|
2733
|
+
let foreign;
|
|
2734
|
+
if (norm2 === COMPAT_CAPABLE_PROTOCOL) foreign = ANTHROPIC_ONLY_COMPAT;
|
|
2735
|
+
else if (norm2 === RESPONSES_PROTOCOL) foreign = [...COMPLETIONS_ONLY_COMPAT, ...ANTHROPIC_ONLY_COMPAT];
|
|
2736
|
+
else if (norm2 === ANTHROPIC_PROTOCOL) foreign = COMPLETIONS_ONLY_COMPAT;
|
|
2737
|
+
else return void 0;
|
|
2738
|
+
let stripped = false;
|
|
2739
|
+
const copy = { ...compat };
|
|
2740
|
+
for (const key of foreign) {
|
|
2741
|
+
if (key in copy) {
|
|
2742
|
+
delete copy[key];
|
|
2743
|
+
stripped = true;
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
return stripped ? copy : void 0;
|
|
2747
|
+
}
|
|
2605
2748
|
function compatForRoute(entry, route) {
|
|
2606
2749
|
const api = normalize(route.api);
|
|
2607
2750
|
if (api === COMPAT_CAPABLE_PROTOCOL) {
|
|
@@ -3173,7 +3316,7 @@ function makeWrapper(base, entries) {
|
|
|
3173
3316
|
const restKey = kind === "unserved" ? restKeyOf(override.route, candidate.ref, model) : restKeyOf(override.route, candidate.ref);
|
|
3174
3317
|
keyRest.note(restKey, kind, retryAfterMs === void 0 ? void 0 : { retryAfterMs });
|
|
3175
3318
|
};
|
|
3176
|
-
const
|
|
3319
|
+
const callerAborted = () => init?.signal?.aborted === true || typeof Request !== "undefined" && input instanceof Request && input.signal.aborted;
|
|
3177
3320
|
if (keyCandidates.length <= 1) {
|
|
3178
3321
|
const solo = keyCandidates[0];
|
|
3179
3322
|
const response = await attempt(solo?.value);
|
|
@@ -3199,7 +3342,7 @@ function makeWrapper(base, entries) {
|
|
|
3199
3342
|
try {
|
|
3200
3343
|
response = await attempt(candidate.value);
|
|
3201
3344
|
} catch (error) {
|
|
3202
|
-
if (
|
|
3345
|
+
if (callerAborted()) throw error;
|
|
3203
3346
|
lastFailure = error;
|
|
3204
3347
|
keyRest.note(restKeyOf(override.route, candidate.ref), "refused");
|
|
3205
3348
|
continue;
|
|
@@ -3720,9 +3863,9 @@ function installPiAiHeaderTransforms(llm, source) {
|
|
|
3720
3863
|
}
|
|
3721
3864
|
|
|
3722
3865
|
// src/headers-conflict.ts
|
|
3723
|
-
import { existsSync, readFileSync as
|
|
3866
|
+
import { existsSync, readFileSync as readFileSync4 } from "node:fs";
|
|
3724
3867
|
import { createRequire } from "node:module";
|
|
3725
|
-
import { dirname as
|
|
3868
|
+
import { dirname as dirname4, join as join4, resolve } from "node:path";
|
|
3726
3869
|
var SIBLING_PACKAGES = [
|
|
3727
3870
|
"dsh-client-masquerade",
|
|
3728
3871
|
"dsh-llm-headers",
|
|
@@ -3734,20 +3877,20 @@ function searchRoots() {
|
|
|
3734
3877
|
const roots = /* @__PURE__ */ new Set();
|
|
3735
3878
|
const entry = process.argv[1];
|
|
3736
3879
|
if (typeof entry === "string" && entry.length > 0) {
|
|
3737
|
-
let dir =
|
|
3880
|
+
let dir = dirname4(resolve(entry));
|
|
3738
3881
|
for (let depth = 0; depth < 8; depth += 1) {
|
|
3739
|
-
roots.add(
|
|
3740
|
-
const parent =
|
|
3882
|
+
roots.add(join4(dir, "node_modules"));
|
|
3883
|
+
const parent = dirname4(dir);
|
|
3741
3884
|
if (parent === dir) break;
|
|
3742
3885
|
dir = parent;
|
|
3743
3886
|
}
|
|
3744
3887
|
}
|
|
3745
|
-
roots.add(
|
|
3888
|
+
roots.add(join4(process.cwd(), "node_modules"));
|
|
3746
3889
|
try {
|
|
3747
3890
|
const require2 = createRequire(import.meta.url);
|
|
3748
3891
|
for (const name2 of SIBLING_PACKAGES) {
|
|
3749
3892
|
try {
|
|
3750
|
-
roots.add(
|
|
3893
|
+
roots.add(join4(dirname4(dirname4(dirname4(require2.resolve(`${name2}/package.json`)))), "node_modules"));
|
|
3751
3894
|
} catch {
|
|
3752
3895
|
}
|
|
3753
3896
|
}
|
|
@@ -3756,14 +3899,14 @@ function searchRoots() {
|
|
|
3756
3899
|
return [...roots];
|
|
3757
3900
|
}
|
|
3758
3901
|
function findAdapterFile() {
|
|
3759
|
-
const relative =
|
|
3902
|
+
const relative = join4("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
|
|
3760
3903
|
const candidates = [];
|
|
3761
3904
|
try {
|
|
3762
3905
|
const require2 = createRequire(import.meta.url);
|
|
3763
3906
|
candidates.push(require2.resolve("@deepseek-ai/dsh-llm-pi-ai"));
|
|
3764
3907
|
} catch {
|
|
3765
3908
|
}
|
|
3766
|
-
for (const root of searchRoots()) candidates.push(
|
|
3909
|
+
for (const root of searchRoots()) candidates.push(join4(root, relative));
|
|
3767
3910
|
for (const candidate of candidates) {
|
|
3768
3911
|
if (existsSync(candidate)) return candidate;
|
|
3769
3912
|
}
|
|
@@ -3774,7 +3917,7 @@ function adapterSourcePatched(source) {
|
|
|
3774
3917
|
}
|
|
3775
3918
|
function adapterPatchState(path) {
|
|
3776
3919
|
try {
|
|
3777
|
-
return adapterSourcePatched(
|
|
3920
|
+
return adapterSourcePatched(readFileSync4(path, "utf8")) ? "patched" : "stock";
|
|
3778
3921
|
} catch {
|
|
3779
3922
|
return "unknown";
|
|
3780
3923
|
}
|
|
@@ -3785,8 +3928,8 @@ function findSiblings() {
|
|
|
3785
3928
|
for (const root of searchRoots()) {
|
|
3786
3929
|
for (const name2 of SIBLING_PACKAGES) {
|
|
3787
3930
|
if (seen.has(name2)) continue;
|
|
3788
|
-
const dir =
|
|
3789
|
-
const manifest =
|
|
3931
|
+
const dir = join4(root, name2);
|
|
3932
|
+
const manifest = join4(dir, "package.json");
|
|
3790
3933
|
if (!existsSync(manifest)) continue;
|
|
3791
3934
|
seen.add(name2);
|
|
3792
3935
|
found.push({ name: name2, path: dir });
|
|
@@ -3818,8 +3961,8 @@ function detectHeaderConflicts() {
|
|
|
3818
3961
|
}
|
|
3819
3962
|
|
|
3820
3963
|
// src/image/config.ts
|
|
3821
|
-
import { mkdirSync as
|
|
3822
|
-
import { dirname as
|
|
3964
|
+
import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
3965
|
+
import { dirname as dirname5, join as join5 } from "node:path";
|
|
3823
3966
|
|
|
3824
3967
|
// src/image/sizes.ts
|
|
3825
3968
|
var IMAGE_SIZE_TIERS = [
|
|
@@ -3836,7 +3979,7 @@ var IMAGE_FALLBACK_PARAMS = {
|
|
|
3836
3979
|
responseFormat: "b64_json"
|
|
3837
3980
|
};
|
|
3838
3981
|
function imageConfigFilePath(home = harnessHome()) {
|
|
3839
|
-
return
|
|
3982
|
+
return join5(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
|
|
3840
3983
|
}
|
|
3841
3984
|
function emptyImageConfig(now = () => /* @__PURE__ */ new Date()) {
|
|
3842
3985
|
return {
|
|
@@ -3933,7 +4076,7 @@ function parseImageModel(raw) {
|
|
|
3933
4076
|
function readImageConfig(file = imageConfigFilePath()) {
|
|
3934
4077
|
let text;
|
|
3935
4078
|
try {
|
|
3936
|
-
text =
|
|
4079
|
+
text = readFileSync5(file, "utf8");
|
|
3937
4080
|
} catch {
|
|
3938
4081
|
return emptyImageConfig();
|
|
3939
4082
|
}
|
|
@@ -3944,15 +4087,15 @@ function readImageConfig(file = imageConfigFilePath()) {
|
|
|
3944
4087
|
}
|
|
3945
4088
|
}
|
|
3946
4089
|
function writeImageConfig(document, file = imageConfigFilePath()) {
|
|
3947
|
-
|
|
4090
|
+
mkdirSync4(dirname5(file), { recursive: true });
|
|
3948
4091
|
const temporary = `${file}.${process.pid}.tmp`;
|
|
3949
|
-
|
|
4092
|
+
writeFileSync4(temporary, `${JSON.stringify(document, null, 2)}
|
|
3950
4093
|
`, "utf8");
|
|
3951
4094
|
try {
|
|
3952
|
-
|
|
4095
|
+
renameSync4(temporary, file);
|
|
3953
4096
|
} catch (error) {
|
|
3954
4097
|
try {
|
|
3955
|
-
|
|
4098
|
+
unlinkSync4(temporary);
|
|
3956
4099
|
} catch {
|
|
3957
4100
|
}
|
|
3958
4101
|
throw error;
|
|
@@ -4001,10 +4144,11 @@ function syncImageConfig(stored, providers, now = () => /* @__PURE__ */ new Date
|
|
|
4001
4144
|
};
|
|
4002
4145
|
});
|
|
4003
4146
|
const ids = new Set(models.map((model) => model.id));
|
|
4147
|
+
const keepDefault = stored.defaultModel !== null && (models.length === 0 || ids.has(stored.defaultModel));
|
|
4004
4148
|
return {
|
|
4005
4149
|
...stored,
|
|
4006
4150
|
syncedAt: now().toISOString(),
|
|
4007
|
-
defaultModel:
|
|
4151
|
+
defaultModel: keepDefault ? stored.defaultModel : null,
|
|
4008
4152
|
models
|
|
4009
4153
|
};
|
|
4010
4154
|
}
|
|
@@ -4039,8 +4183,84 @@ function updateImageConfig(mutate, file = imageConfigFilePath()) {
|
|
|
4039
4183
|
}
|
|
4040
4184
|
|
|
4041
4185
|
// src/image/generate.ts
|
|
4042
|
-
import { mkdirSync as
|
|
4043
|
-
import { dirname as
|
|
4186
|
+
import { mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5, existsSync as existsSync2, statSync } from "node:fs";
|
|
4187
|
+
import { dirname as dirname6, join as join6, resolve as resolve2 } from "node:path";
|
|
4188
|
+
|
|
4189
|
+
// src/image/deadline.ts
|
|
4190
|
+
function createImageDeadline(timeoutMs, caller, errorFor) {
|
|
4191
|
+
const controller = new AbortController();
|
|
4192
|
+
const expiresAt = Date.now() + timeoutMs;
|
|
4193
|
+
let timer;
|
|
4194
|
+
const forwardAbort = () => {
|
|
4195
|
+
controller.abort(caller?.reason);
|
|
4196
|
+
};
|
|
4197
|
+
const cleanup = () => {
|
|
4198
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
4199
|
+
timer = void 0;
|
|
4200
|
+
caller?.removeEventListener("abort", forwardAbort);
|
|
4201
|
+
};
|
|
4202
|
+
controller.signal.addEventListener("abort", cleanup, { once: true });
|
|
4203
|
+
if (caller?.aborted === true) forwardAbort();
|
|
4204
|
+
else {
|
|
4205
|
+
caller?.addEventListener("abort", forwardAbort, { once: true });
|
|
4206
|
+
timer = setTimeout(() => controller.abort(new DOMException("Image deadline exceeded", "TimeoutError")), timeoutMs);
|
|
4207
|
+
}
|
|
4208
|
+
const check = () => {
|
|
4209
|
+
if (caller?.aborted === true) forwardAbort();
|
|
4210
|
+
if (!controller.signal.aborted && Date.now() >= expiresAt) {
|
|
4211
|
+
controller.abort(new DOMException("Image deadline exceeded", "TimeoutError"));
|
|
4212
|
+
}
|
|
4213
|
+
if (controller.signal.aborted) throw errorFor(caller?.aborted === true ? "aborted" : "timeout");
|
|
4214
|
+
};
|
|
4215
|
+
return {
|
|
4216
|
+
signal: controller.signal,
|
|
4217
|
+
check,
|
|
4218
|
+
run: (work) => new Promise((resolve3, reject) => {
|
|
4219
|
+
let settled = false;
|
|
4220
|
+
const finish = (done) => {
|
|
4221
|
+
if (settled) return;
|
|
4222
|
+
settled = true;
|
|
4223
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
4224
|
+
done();
|
|
4225
|
+
};
|
|
4226
|
+
const onAbort = () => {
|
|
4227
|
+
try {
|
|
4228
|
+
check();
|
|
4229
|
+
} catch (error) {
|
|
4230
|
+
finish(() => reject(error));
|
|
4231
|
+
}
|
|
4232
|
+
};
|
|
4233
|
+
try {
|
|
4234
|
+
check();
|
|
4235
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
4236
|
+
check();
|
|
4237
|
+
Promise.resolve(work()).then((value) => {
|
|
4238
|
+
try {
|
|
4239
|
+
check();
|
|
4240
|
+
finish(() => resolve3(value));
|
|
4241
|
+
} catch (error) {
|
|
4242
|
+
finish(() => reject(error));
|
|
4243
|
+
}
|
|
4244
|
+
}, (error) => {
|
|
4245
|
+
try {
|
|
4246
|
+
check();
|
|
4247
|
+
} catch (cancelled) {
|
|
4248
|
+
error = cancelled;
|
|
4249
|
+
}
|
|
4250
|
+
finish(() => reject(error));
|
|
4251
|
+
});
|
|
4252
|
+
} catch (error) {
|
|
4253
|
+
finish(() => reject(error));
|
|
4254
|
+
}
|
|
4255
|
+
}),
|
|
4256
|
+
dispose: () => {
|
|
4257
|
+
cleanup();
|
|
4258
|
+
controller.signal.removeEventListener("abort", cleanup);
|
|
4259
|
+
}
|
|
4260
|
+
};
|
|
4261
|
+
}
|
|
4262
|
+
|
|
4263
|
+
// src/image/generate.ts
|
|
4044
4264
|
var GenerateError = class extends Error {
|
|
4045
4265
|
kind;
|
|
4046
4266
|
status;
|
|
@@ -4071,11 +4291,43 @@ function sanitize(text, key) {
|
|
|
4071
4291
|
out = out.replace(/(?:Bearer\s+|sk-)[A-Za-z0-9_\-=.]{8,}/g, "***");
|
|
4072
4292
|
return out;
|
|
4073
4293
|
}
|
|
4074
|
-
async function
|
|
4294
|
+
async function responseBytes(response, deadline, limit = Infinity) {
|
|
4295
|
+
deadline.check();
|
|
4296
|
+
const reader = response.body?.getReader();
|
|
4297
|
+
if (reader === void 0) return new Uint8Array();
|
|
4298
|
+
const chunks = [];
|
|
4299
|
+
let length = 0;
|
|
4300
|
+
let complete = false;
|
|
4301
|
+
try {
|
|
4302
|
+
while (length < limit) {
|
|
4303
|
+
const { done, value } = await deadline.run(() => reader.read());
|
|
4304
|
+
if (done) {
|
|
4305
|
+
complete = true;
|
|
4306
|
+
break;
|
|
4307
|
+
}
|
|
4308
|
+
const chunk = value.subarray(0, limit - length);
|
|
4309
|
+
chunks.push(chunk);
|
|
4310
|
+
length += chunk.length;
|
|
4311
|
+
}
|
|
4312
|
+
deadline.check();
|
|
4313
|
+
const bytes = new Uint8Array(length);
|
|
4314
|
+
let offset = 0;
|
|
4315
|
+
for (const chunk of chunks) {
|
|
4316
|
+
bytes.set(chunk, offset);
|
|
4317
|
+
offset += chunk.length;
|
|
4318
|
+
}
|
|
4319
|
+
return bytes;
|
|
4320
|
+
} finally {
|
|
4321
|
+
if (!complete) void reader.cancel().catch(() => {
|
|
4322
|
+
});
|
|
4323
|
+
reader.releaseLock();
|
|
4324
|
+
}
|
|
4325
|
+
}
|
|
4326
|
+
async function boundedText(response, deadline, limit = 4096) {
|
|
4075
4327
|
try {
|
|
4076
|
-
|
|
4077
|
-
return text.length > limit ? text.slice(0, limit) : text;
|
|
4328
|
+
return new TextDecoder().decode(await responseBytes(response, deadline, limit));
|
|
4078
4329
|
} catch {
|
|
4330
|
+
deadline.check();
|
|
4079
4331
|
return "";
|
|
4080
4332
|
}
|
|
4081
4333
|
}
|
|
@@ -4172,19 +4424,19 @@ function outputDirOf(deps, config) {
|
|
|
4172
4424
|
const home = deps.home?.() ?? harnessHome();
|
|
4173
4425
|
const dir = config.outputDir;
|
|
4174
4426
|
if (/^([A-Za-z]:[\\/]|\/)/.test(dir)) return dir;
|
|
4175
|
-
return
|
|
4427
|
+
return join6(home, "dsh-model-think-level", dir);
|
|
4176
4428
|
}
|
|
4177
4429
|
function destinationOf(dir, slug, now) {
|
|
4178
|
-
const base =
|
|
4430
|
+
const base = join6(dir, `${slug}-${now()}.png`);
|
|
4179
4431
|
if (!existsSync2(base)) return base;
|
|
4180
4432
|
for (let index = 2; ; index += 1) {
|
|
4181
|
-
const candidate =
|
|
4433
|
+
const candidate = join6(dir, `${slug}-${now()}-${index}.png`);
|
|
4182
4434
|
if (!existsSync2(candidate)) return candidate;
|
|
4183
4435
|
}
|
|
4184
4436
|
}
|
|
4185
4437
|
function resolveDestination(requested, fallbackDir, slug, now) {
|
|
4186
4438
|
if (requested === void 0 || requested.trim().length === 0) {
|
|
4187
|
-
|
|
4439
|
+
mkdirSync5(fallbackDir, { recursive: true });
|
|
4188
4440
|
return destinationOf(fallbackDir, slug, now);
|
|
4189
4441
|
}
|
|
4190
4442
|
const target = resolve2(requested.trim());
|
|
@@ -4194,23 +4446,23 @@ function resolveDestination(requested, fallbackDir, slug, now) {
|
|
|
4194
4446
|
} catch {
|
|
4195
4447
|
}
|
|
4196
4448
|
if (isDir || /[\\/]$/.test(target) || !target.toLowerCase().endsWith(".png")) {
|
|
4197
|
-
|
|
4449
|
+
mkdirSync5(target, { recursive: true });
|
|
4198
4450
|
return destinationOf(target, slug, now);
|
|
4199
4451
|
}
|
|
4200
|
-
|
|
4452
|
+
mkdirSync5(dirname6(target), { recursive: true });
|
|
4201
4453
|
if (!existsSync2(target)) return target;
|
|
4202
4454
|
for (let index = 2; ; index += 1) {
|
|
4203
4455
|
const candidate = target.replace(/\.png$/i, `-${index}.png`);
|
|
4204
4456
|
if (!existsSync2(candidate)) return candidate;
|
|
4205
4457
|
}
|
|
4206
4458
|
}
|
|
4207
|
-
async function imagesOfAnswer(answer, send) {
|
|
4459
|
+
async function imagesOfAnswer(answer, send, deadline, key) {
|
|
4208
4460
|
if (typeof answer !== "object" || answer === null) throw new GenerateError("upstream", "\u4E0A\u6E38\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u5E94\u7B54\u7ED3\u6784");
|
|
4209
4461
|
const data = answer["data"];
|
|
4210
4462
|
if (!Array.isArray(data) || data.length === 0) {
|
|
4211
|
-
for (const
|
|
4212
|
-
const nested = answer[
|
|
4213
|
-
if (Array.isArray(nested) && nested.length > 0) return imagesOfAnswer({ data: nested }, send);
|
|
4463
|
+
for (const nestedKey of ["images", "output", "result"]) {
|
|
4464
|
+
const nested = answer[nestedKey];
|
|
4465
|
+
if (Array.isArray(nested) && nested.length > 0) return imagesOfAnswer({ data: nested }, send, deadline, key);
|
|
4214
4466
|
}
|
|
4215
4467
|
throw new GenerateError("upstream", "\u4E0A\u6E38\u5E94\u7B54\u7F3A\u5C11 data \u6570\u7EC4");
|
|
4216
4468
|
}
|
|
@@ -4222,29 +4474,49 @@ async function imagesOfAnswer(answer, send) {
|
|
|
4222
4474
|
images.push(record["b64_json"]);
|
|
4223
4475
|
continue;
|
|
4224
4476
|
}
|
|
4477
|
+
deadline.check();
|
|
4225
4478
|
if (typeof record["url"] === "string" && record["url"].length > 0) {
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4479
|
+
try {
|
|
4480
|
+
const response = await deadline.run(() => send(record["url"], { redirect: "follow", signal: deadline.signal }));
|
|
4481
|
+
if (!response.ok) throw new GenerateError("upstream", `\u4E0B\u8F7D\u4E0A\u6E38\u56FE\u7247\u5931\u8D25\uFF08${response.status}\uFF09`);
|
|
4482
|
+
const bytes = await responseBytes(response, deadline);
|
|
4483
|
+
let binary = "";
|
|
4484
|
+
for (let index = 0; index < bytes.length; index += 1) binary += String.fromCharCode(bytes[index]);
|
|
4485
|
+
deadline.check();
|
|
4486
|
+
images.push(btoa(binary));
|
|
4487
|
+
} catch (error) {
|
|
4488
|
+
deadline.check();
|
|
4489
|
+
if (error instanceof GenerateError) throw error;
|
|
4490
|
+
throw new GenerateError("upstream", `\u4E0B\u8F7D\u4E0A\u6E38\u56FE\u7247\u5931\u8D25\uFF1A${sanitize(error instanceof Error ? error.message : String(error), key)}`);
|
|
4491
|
+
}
|
|
4232
4492
|
continue;
|
|
4233
4493
|
}
|
|
4234
4494
|
throw new GenerateError("upstream", "\u4E0A\u6E38\u5E94\u7B54\u65E2\u65E0 b64_json \u4E5F\u65E0 url");
|
|
4235
4495
|
}
|
|
4236
4496
|
return images;
|
|
4237
4497
|
}
|
|
4238
|
-
function
|
|
4239
|
-
return signal
|
|
4498
|
+
function createGenerateDeadline(timeoutMs, signal) {
|
|
4499
|
+
return createImageDeadline(timeoutMs, signal, (kind) => new GenerateError(kind, kind === "aborted" ? "\u751F\u6210\u5DF2\u53D6\u6D88" : `\u751F\u6210\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09\u2014\u2014\u53EF\u5728\u914D\u7F6E\u9875\u8C03\u5927\u8D85\u65F6`));
|
|
4240
4500
|
}
|
|
4241
|
-
async function generateImage(deps, request) {
|
|
4501
|
+
async function generateImage(deps, request, sharedDeadline) {
|
|
4242
4502
|
const config = deps.config?.() ?? readImageConfig();
|
|
4503
|
+
const deadline = sharedDeadline ?? createGenerateDeadline(deps.timeoutMs ?? config.defaults.timeoutMs, request.signal);
|
|
4504
|
+
try {
|
|
4505
|
+
deadline.check();
|
|
4506
|
+
return await generateWithinDeadline(deps, request, config, deadline);
|
|
4507
|
+
} catch (error) {
|
|
4508
|
+
deadline.check();
|
|
4509
|
+
throw error;
|
|
4510
|
+
} finally {
|
|
4511
|
+
if (sharedDeadline === void 0) deadline.dispose();
|
|
4512
|
+
}
|
|
4513
|
+
}
|
|
4514
|
+
async function generateWithinDeadline(deps, request, config, deadline) {
|
|
4243
4515
|
const prompt = request.prompt.trim();
|
|
4244
4516
|
if (prompt.length === 0) throw new GenerateError("param", "\u63D0\u793A\u8BCD\u4E3A\u7A7A");
|
|
4245
4517
|
const model = resolveImageModel(config, request.model);
|
|
4246
4518
|
if (model === void 0) {
|
|
4247
|
-
throw new GenerateError("config", config.models.length === 0 ? "\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u2014\u2014\u8BF7\u5230 \u6A21\u578B\u914D\u7F6E \u2192 \u8F93\u5165\u6A21\u6001 \u52FE\u9009\u300C\u751F\u56FE\u300D\uFF0C\u6216\u5728\u63D2\u4EF6\u914D\u7F6E\u9875\u6DFB\u52A0" : `\u751F\u56FE\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u552F\u4E00\u5B9A\u4F4D\uFF1A${request.model ?? config.defaultModel ??
|
|
4519
|
+
throw new GenerateError("config", config.models.length === 0 ? "\u6CA1\u6709\u5DF2\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u2014\u2014\u8BF7\u5230 \u6A21\u578B\u914D\u7F6E \u2192 \u8F93\u5165\u6A21\u6001 \u52FE\u9009\u300C\u751F\u56FE\u300D\uFF0C\u6216\u5728\u63D2\u4EF6\u914D\u7F6E\u9875\u6DFB\u52A0" : `\u751F\u56FE\u6A21\u578B\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u552F\u4E00\u5B9A\u4F4D\uFF1A${request.model ?? config.defaultModel ?? `(\u672A\u8BBE\u9ED8\u8BA4\uFF0C\u5019\u9009 ${config.models.map((candidate) => candidate.id).join("\u3001")})`}\u3002\u8BF7\u5E26\u4E0A model \u53C2\u6570\uFF0C\u6216\u5230\u63D2\u4EF6\u914D\u7F6E\u9875\u628A\u5176\u4E2D\u4E00\u4E2A\u8BBE\u4E3A\u9ED8\u8BA4\u6A21\u578B`);
|
|
4248
4520
|
}
|
|
4249
4521
|
if (model.api !== "images") {
|
|
4250
4522
|
throw new GenerateError("endpoint", `\u8BE5\u6A21\u578B\uFF08${model.id}\uFF09\u7684\u534F\u8BAE\u6CA1\u6709\u517C\u5BB9\u7684 images \u7AEF\u70B9\uFF0C\u751F\u6210\u5DF2\u7981\u7528`);
|
|
@@ -4253,7 +4525,7 @@ async function generateImage(deps, request) {
|
|
|
4253
4525
|
throw new GenerateError("config", `\u6A21\u578B ${model.id} \u6240\u5728\u4F9B\u5E94\u5546\u672A\u914D\u7F6E baseURL`);
|
|
4254
4526
|
}
|
|
4255
4527
|
const params = effectiveParams(config, model, request);
|
|
4256
|
-
const key = model.keyRef === void 0 ? void 0 : await deps.resolveKey(model.keyRef);
|
|
4528
|
+
const key = model.keyRef === void 0 ? void 0 : await deadline.run(() => deps.resolveKey(model.keyRef, deadline.signal));
|
|
4257
4529
|
if (model.keyRef !== void 0 && key === void 0) {
|
|
4258
4530
|
throw new GenerateError("auth", `\u8BE5 route\uFF08${model.route}\uFF09\u672A\u914D\u7F6E\u5BC6\u94A5\uFF08\u5F15\u7528 ${model.keyRef}\uFF09\u2014\u2014\u8BF7\u5230\u6A21\u578B\u914D\u7F6E\u9875\u586B\u5199`);
|
|
4259
4531
|
}
|
|
@@ -4262,10 +4534,11 @@ async function generateImage(deps, request) {
|
|
|
4262
4534
|
const referenceReads = [
|
|
4263
4535
|
...(request.referenceFiles ?? []).map((file) => ({ name: file.name, bytes: file.bytes, mime: file.mime })),
|
|
4264
4536
|
...(request.referenceImages ?? []).map((path) => {
|
|
4537
|
+
deadline.check();
|
|
4265
4538
|
const absolute = resolve2(path);
|
|
4266
4539
|
if (!existsSync2(absolute)) throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
|
|
4267
4540
|
try {
|
|
4268
|
-
return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes:
|
|
4541
|
+
return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync6(absolute), mime: mimeOfPath(absolute) };
|
|
4269
4542
|
} catch {
|
|
4270
4543
|
throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
|
|
4271
4544
|
}
|
|
@@ -4278,10 +4551,8 @@ async function generateImage(deps, request) {
|
|
|
4278
4551
|
let count = params.n;
|
|
4279
4552
|
let lastFailure;
|
|
4280
4553
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
4281
|
-
|
|
4282
|
-
const
|
|
4283
|
-
const deadline = AbortSignal.timeout(timeoutMs);
|
|
4284
|
-
const signal = request.signal === void 0 ? deadline : AbortSignal.any([deadline, request.signal]);
|
|
4554
|
+
deadline.check();
|
|
4555
|
+
const signal = deadline.signal;
|
|
4285
4556
|
let response;
|
|
4286
4557
|
try {
|
|
4287
4558
|
if (referenceReads.length > 0) {
|
|
@@ -4294,7 +4565,7 @@ async function generateImage(deps, request) {
|
|
|
4294
4565
|
};
|
|
4295
4566
|
if (format !== "none") fields["output_format"] = "png";
|
|
4296
4567
|
const { body: body2, contentType } = buildMultipart(boundary, fields, referenceReads);
|
|
4297
|
-
response = await deps.send(`${base}/images/edits`, {
|
|
4568
|
+
response = await deadline.run(() => deps.send(`${base}/images/edits`, {
|
|
4298
4569
|
method: "POST",
|
|
4299
4570
|
headers: {
|
|
4300
4571
|
"content-type": contentType,
|
|
@@ -4302,7 +4573,7 @@ async function generateImage(deps, request) {
|
|
|
4302
4573
|
},
|
|
4303
4574
|
body: body2,
|
|
4304
4575
|
signal
|
|
4305
|
-
});
|
|
4576
|
+
}));
|
|
4306
4577
|
} else {
|
|
4307
4578
|
const payload = {
|
|
4308
4579
|
model: model.modelId,
|
|
@@ -4313,7 +4584,7 @@ async function generateImage(deps, request) {
|
|
|
4313
4584
|
};
|
|
4314
4585
|
if (format === "b64_json") payload["response_format"] = "b64_json";
|
|
4315
4586
|
if (format === "output_format") payload["output_format"] = "png";
|
|
4316
|
-
response = await deps.send(`${base}/images/generations`, {
|
|
4587
|
+
response = await deadline.run(() => deps.send(`${base}/images/generations`, {
|
|
4317
4588
|
method: "POST",
|
|
4318
4589
|
headers: {
|
|
4319
4590
|
"content-type": "application/json",
|
|
@@ -4321,30 +4592,33 @@ async function generateImage(deps, request) {
|
|
|
4321
4592
|
},
|
|
4322
4593
|
body: JSON.stringify(payload),
|
|
4323
4594
|
signal
|
|
4324
|
-
});
|
|
4595
|
+
}));
|
|
4325
4596
|
}
|
|
4326
4597
|
} catch (error) {
|
|
4598
|
+
deadline.check();
|
|
4327
4599
|
if (error instanceof GenerateError) throw error;
|
|
4328
|
-
if (callerAborted(request.signal)) throw new GenerateError("aborted", "\u751F\u6210\u5DF2\u53D6\u6D88");
|
|
4329
4600
|
const message = error instanceof Error ? error.message : String(error);
|
|
4330
|
-
if (/abort|timeout/i.test(message)) throw new GenerateError("timeout", `\u751F\u6210\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09\u2014\u2014\u53EF\u5728\u914D\u7F6E\u9875\u8C03\u5927\u8D85\u65F6`);
|
|
4331
4601
|
throw new GenerateError("upstream", `\u65E0\u6CD5\u8FDE\u63A5 ${base}\uFF1A${sanitize(message, key)}`);
|
|
4332
4602
|
}
|
|
4333
4603
|
if (response.ok) {
|
|
4334
4604
|
let answer;
|
|
4335
4605
|
try {
|
|
4336
|
-
answer = JSON.parse(await
|
|
4606
|
+
answer = JSON.parse(new TextDecoder().decode(await responseBytes(response, deadline)));
|
|
4337
4607
|
} catch {
|
|
4608
|
+
deadline.check();
|
|
4338
4609
|
throw new GenerateError("upstream", "\u4E0A\u6E38\u5E94\u7B54\u4E0D\u662F\u5408\u6CD5 JSON");
|
|
4339
4610
|
}
|
|
4340
|
-
const payloads = await imagesOfAnswer(answer, deps.send);
|
|
4611
|
+
const payloads = await imagesOfAnswer(answer, deps.send, deadline, key);
|
|
4341
4612
|
const images = [];
|
|
4342
4613
|
for (const data of payloads) {
|
|
4614
|
+
deadline.check();
|
|
4343
4615
|
const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now);
|
|
4344
4616
|
const bytes = Uint8Array.from(atob(data), (ch) => ch.charCodeAt(0));
|
|
4345
|
-
|
|
4617
|
+
deadline.check();
|
|
4618
|
+
writeFileSync5(filePath, bytes);
|
|
4346
4619
|
images.push({ filePath, data });
|
|
4347
4620
|
}
|
|
4621
|
+
deadline.check();
|
|
4348
4622
|
if (revisions.length > 0 && deps.persistLastGood !== void 0) {
|
|
4349
4623
|
deps.persistLastGood(model.id, {
|
|
4350
4624
|
...model.params,
|
|
@@ -4354,6 +4628,7 @@ async function generateImage(deps, request) {
|
|
|
4354
4628
|
maxN: model.params.maxN
|
|
4355
4629
|
});
|
|
4356
4630
|
}
|
|
4631
|
+
deadline.check();
|
|
4357
4632
|
return {
|
|
4358
4633
|
images,
|
|
4359
4634
|
mime: "image/png",
|
|
@@ -4363,7 +4638,7 @@ async function generateImage(deps, request) {
|
|
|
4363
4638
|
revisions: [...revisions]
|
|
4364
4639
|
};
|
|
4365
4640
|
}
|
|
4366
|
-
const bodyText = await boundedText(response);
|
|
4641
|
+
const bodyText = await boundedText(response, deadline);
|
|
4367
4642
|
let body;
|
|
4368
4643
|
try {
|
|
4369
4644
|
body = JSON.parse(bodyText);
|
|
@@ -4536,49 +4811,61 @@ function attachmentRefOf(id) {
|
|
|
4536
4811
|
var OUTPUT_SCHEMA = {
|
|
4537
4812
|
type: "object",
|
|
4538
4813
|
additionalProperties: false,
|
|
4814
|
+
required: ["images", "model", "prompt", "paramsUsed"],
|
|
4539
4815
|
properties: {
|
|
4540
4816
|
images: {
|
|
4541
4817
|
type: "array",
|
|
4542
|
-
required: true,
|
|
4543
4818
|
items: {
|
|
4544
4819
|
type: "object",
|
|
4545
4820
|
additionalProperties: false,
|
|
4821
|
+
required: ["attachment", "filePath"],
|
|
4546
4822
|
properties: {
|
|
4547
|
-
attachment: {
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
width: { type: "integer"
|
|
4556
|
-
height: { type: "integer"
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4823
|
+
attachment: {
|
|
4824
|
+
type: "object",
|
|
4825
|
+
additionalProperties: false,
|
|
4826
|
+
required: ["attachmentId", "mediaType", "bytes", "width", "height"],
|
|
4827
|
+
properties: {
|
|
4828
|
+
attachmentId: { type: "string" },
|
|
4829
|
+
mediaType: { type: "string" },
|
|
4830
|
+
bytes: { type: "integer" },
|
|
4831
|
+
width: { type: "integer" },
|
|
4832
|
+
height: { type: "integer" },
|
|
4833
|
+
name: { type: "string" }
|
|
4834
|
+
}
|
|
4835
|
+
},
|
|
4836
|
+
filePath: { type: "string" }
|
|
4560
4837
|
}
|
|
4561
4838
|
}
|
|
4562
4839
|
},
|
|
4563
|
-
model: { type: "string"
|
|
4564
|
-
prompt: { type: "string"
|
|
4565
|
-
paramsUsed: {
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
|
|
4569
|
-
|
|
4840
|
+
model: { type: "string" },
|
|
4841
|
+
prompt: { type: "string" },
|
|
4842
|
+
paramsUsed: {
|
|
4843
|
+
type: "object",
|
|
4844
|
+
additionalProperties: false,
|
|
4845
|
+
required: ["size", "quality", "n"],
|
|
4846
|
+
properties: {
|
|
4847
|
+
size: { type: "string" },
|
|
4848
|
+
quality: { type: "string" },
|
|
4849
|
+
n: { type: "integer" }
|
|
4850
|
+
}
|
|
4851
|
+
},
|
|
4570
4852
|
revisions: { type: "array", items: { type: "string" } }
|
|
4571
4853
|
}
|
|
4572
4854
|
};
|
|
4573
4855
|
var TOOL_PARAMETERS = {
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4856
|
+
type: "object",
|
|
4857
|
+
additionalProperties: false,
|
|
4858
|
+
required: ["prompt"],
|
|
4859
|
+
properties: {
|
|
4860
|
+
prompt: { type: "string", description: "\u5B8C\u6574\u753B\u9762\u63CF\u8FF0\uFF1A\u4E3B\u4F53\u3001\u6784\u56FE\u3001\u98CE\u683C\u3001\u5149\u7167\uFF0C\u4EE5\u53CA\u9700\u8981\u51FA\u73B0\u7684\u6587\u5B57\u3002" },
|
|
4861
|
+
model: { type: "string", description: "\u751F\u56FE\u6A21\u578B\uFF08route/modelId \u6216\u663E\u793A\u540D\uFF09\uFF1B\u7F3A\u7701\u7528\u914D\u7F6E\u9875\u7684\u9ED8\u8BA4\u6A21\u578B\uFF0C\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002" },
|
|
4862
|
+
size: { type: "string", description: "\u5982 1024x1024\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\u3002\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002" },
|
|
4863
|
+
quality: { type: "string", description: "\u5982 high\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\u3002\u7528\u6237\u6CA1\u6709\u70B9\u540D\u65F6\u7701\u7565\u3002" },
|
|
4864
|
+
n: { type: "integer", description: "\u751F\u6210\u5F20\u6570\uFF1B\u7F3A\u7701\u53D6\u6A21\u578B\u884C \u2192 \u9ED8\u8BA4\u53C2\u6570\uFF0C\u8D85\u8FC7\u8BE5\u6A21\u578B\u4E0A\u9650\u65F6\u62A5\u9519\u5E76\u5217\u51FA\u5141\u8BB8\u503C\u3002" },
|
|
4865
|
+
reference_images: { type: "array", items: { type: "string" }, description: "\u672C\u5730\u53C2\u8003\u56FE\u8DEF\u5F84\uFF1B\u975E\u7A7A\u8D70 /images/edits\u3002" },
|
|
4866
|
+
reference_attachments: { type: "array", items: { type: "string" }, description: "\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID\uFF08sha256:\u2026 \u6216\u88F8\u6458\u8981\uFF09\uFF1B\u4E0E\u672C\u5730\u8DEF\u5F84\u53EF\u6DF7\u7528\u3002" },
|
|
4867
|
+
path: { type: "string", description: "\u843D\u76D8\u6587\u4EF6\uFF08\u4EE5 .png \u7ED3\u5C3E\uFF0C\u5B58\u5728\u5219\u81EA\u52A8\u52A0 -2 \u540E\u7F00\uFF0C\u4E0D\u8986\u76D6\uFF09\u6216\u76EE\u5F55\uFF1B\u7F3A\u7701 generated-images/<slug>-<ts>.png\u3002" }
|
|
4868
|
+
}
|
|
4582
4869
|
};
|
|
4583
4870
|
function parseArgs(raw) {
|
|
4584
4871
|
if (typeof raw !== "object" || raw === null) return "\u53C2\u6570\u4E0D\u662F\u5BF9\u8C61\uFF1Bprompt \u4E3A\u5FC5\u586B\u5B57\u7B26\u4E32";
|
|
@@ -4613,6 +4900,7 @@ function attachmentValueOf(ref) {
|
|
|
4613
4900
|
...ref.name === void 0 ? {} : { name: ref.name }
|
|
4614
4901
|
};
|
|
4615
4902
|
}
|
|
4903
|
+
var IMAGE_REPLY_HINT = "\u751F\u56FE\u6210\u529F\u540E\uFF0C\u6700\u7EC8\u56DE\u590D\u5FC5\u987B\u9010\u5F20\u76F4\u63A5\u5D4C\u5165\u6240\u6709\u751F\u6210\u7684\u56FE\u7247\uFF1A\u7528\u8FD4\u56DE\u7684\u771F\u5B9E filePath \u5199 \uFF0CWindows \u8DEF\u5F84\u7528 /\u3002\u4E0D\u80FD\u53EA\u8BF4\u201C\u56FE\u7247\u5DF2\u751F\u6210/\u5DF2\u9644\u5230\u5BF9\u8BDD\u201D\uFF0C\u4E0D\u80FD\u53EA\u653E\u6587\u4EF6\u94FE\u63A5\u6216\u4F9D\u8D56\u5DE5\u5177\u5361\u7247\u3002";
|
|
4616
4904
|
function summaryText(value) {
|
|
4617
4905
|
const paths = value.images.map((image) => image.filePath);
|
|
4618
4906
|
const lines = [
|
|
@@ -4620,7 +4908,10 @@ function summaryText(value) {
|
|
|
4620
4908
|
`size ${value.paramsUsed.size} \xB7 quality ${value.paramsUsed.quality} \xB7 n ${value.paramsUsed.n}`,
|
|
4621
4909
|
`\u843D\u76D8\uFF1A${paths.join("\u3001")}`,
|
|
4622
4910
|
value.revisions.length > 0 ? `\u53C2\u6570\u56DE\u9000\uFF1A${value.revisions.join("\u3001")}` : "",
|
|
4623
|
-
|
|
4911
|
+
IMAGE_REPLY_HINT,
|
|
4912
|
+
"\u53EF\u76F4\u63A5\u590D\u5236\u5230\u6700\u7EC8\u56DE\u590D\u7684\u56FE\u7247 Markdown\uFF1A",
|
|
4913
|
+
...paths.map((path, index) => `}>)`),
|
|
4914
|
+
"\u4E0D\u8981\u865A\u6784\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u8C03\u7528 read\u3001glob \u6216\u5176\u4ED6\u5DE5\u5177\u53BB\u627E\u6216\u9A8C\u8BC1\u56FE\u7247\uFF1B\u76F4\u63A5\u4F7F\u7528\u4E0A\u9762\u7684\u771F\u5B9E\u8DEF\u5F84\u5D4C\u56FE\u3002"
|
|
4624
4915
|
];
|
|
4625
4916
|
return lines.filter((line) => line.length > 0).join("\n");
|
|
4626
4917
|
}
|
|
@@ -4628,7 +4919,7 @@ function registerGenerateImageTool(ctx, deps) {
|
|
|
4628
4919
|
const tools = ctx.tools;
|
|
4629
4920
|
const definitionFor = (name3) => ({
|
|
4630
4921
|
name: name3,
|
|
4631
|
-
description:
|
|
4922
|
+
description: `\u7528\u5F53\u524D\u914D\u7F6E\u7684\u751F\u56FE\u6A21\u578B\u751F\u6210\u56FE\u7247\u5E76\u76F4\u63A5\u9644\u5230\u5BF9\u8BDD\u3002\u7528\u6237\u8981\u753B\u56FE\u3001\u751F\u6210\u3001\u51FA\u56FE\u65F6\u8C03\u7528\uFF1B\u6539\u56FE\u8BF7\u5E26\u53C2\u8003\u56FE\u3002\u53C2\u6570\u4E00\u5F8B\u7F3A\u7701\uFF08\u8BFB\u914D\u7F6E\u9ED8\u8BA4\uFF09\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u70B9\u540D\u3002\u4E0D\u8981\u865A\u6784\u56FE\u7247 URL\u3002${IMAGE_REPLY_HINT}`,
|
|
4632
4923
|
parameters: TOOL_PARAMETERS,
|
|
4633
4924
|
output: {
|
|
4634
4925
|
schema: OUTPUT_SCHEMA,
|
|
@@ -4648,40 +4939,53 @@ function registerGenerateImageTool(ctx, deps) {
|
|
|
4648
4939
|
async execute(rawArgs, exec) {
|
|
4649
4940
|
const parsed = parseArgs(rawArgs);
|
|
4650
4941
|
if (typeof parsed === "string") throw new Error(parsed);
|
|
4651
|
-
const
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4942
|
+
const config = deps.generateDeps.config?.() ?? deps.readConfig();
|
|
4943
|
+
const deadline = createGenerateDeadline(deps.generateDeps.timeoutMs ?? config.defaults.timeoutMs, exec.signal);
|
|
4944
|
+
try {
|
|
4945
|
+
deadline.check();
|
|
4946
|
+
const referenceFiles = [];
|
|
4947
|
+
for (const [index, id] of (parsed.referenceAttachments ?? []).entries()) {
|
|
4948
|
+
try {
|
|
4949
|
+
const stored = await deadline.run(() => deps.attachments.readImage(attachmentRefOf(id), deadline.signal));
|
|
4950
|
+
const name4 = stored.ref?.name ?? `reference-${index + 1}.png`;
|
|
4951
|
+
referenceFiles.push({ name: name4, mime: stored.ref?.mediaType ?? "image/png", bytes: stored.data });
|
|
4952
|
+
} catch (error) {
|
|
4953
|
+
deadline.check();
|
|
4954
|
+
throw new Error(`\u53C2\u8003\u56FE\uFF08\u9644\u4EF6 ${id}\uFF09\u4E0D\u53EF\u8BFB\uFF1A${error instanceof Error ? error.message : String(error)}`);
|
|
4955
|
+
}
|
|
4659
4956
|
}
|
|
4957
|
+
const result = await generateImage({ ...deps.generateDeps, config: () => config }, {
|
|
4958
|
+
prompt: parsed.prompt,
|
|
4959
|
+
...parsed.model === void 0 ? {} : { model: parsed.model },
|
|
4960
|
+
...parsed.size === void 0 ? {} : { size: parsed.size },
|
|
4961
|
+
...parsed.quality === void 0 ? {} : { quality: parsed.quality },
|
|
4962
|
+
...parsed.n === void 0 ? {} : { n: parsed.n },
|
|
4963
|
+
...parsed.referenceImages === void 0 ? {} : { referenceImages: parsed.referenceImages },
|
|
4964
|
+
...referenceFiles.length > 0 ? { referenceFiles } : {},
|
|
4965
|
+
...parsed.outputPath === void 0 ? {} : { outputPath: parsed.outputPath },
|
|
4966
|
+
signal: deadline.signal
|
|
4967
|
+
}, deadline);
|
|
4968
|
+
const images = [];
|
|
4969
|
+
for (const image of result.images) {
|
|
4970
|
+
deadline.check();
|
|
4971
|
+
const bytes = Uint8Array.from(atob(image.data), (ch) => ch.charCodeAt(0));
|
|
4972
|
+
const attachment = await deadline.run(() => deps.attachments.saveImage({ data: bytes, mediaType: result.mime, name: "generated-image" }, deadline.signal));
|
|
4973
|
+
images.push({ attachment: attachmentValueOf(attachment), filePath: image.filePath });
|
|
4974
|
+
}
|
|
4975
|
+
deadline.check();
|
|
4976
|
+
return {
|
|
4977
|
+
images,
|
|
4978
|
+
model: result.model,
|
|
4979
|
+
prompt: result.prompt,
|
|
4980
|
+
paramsUsed: result.paramsUsed,
|
|
4981
|
+
revisions: result.revisions
|
|
4982
|
+
};
|
|
4983
|
+
} catch (error) {
|
|
4984
|
+
deadline.check();
|
|
4985
|
+
throw error;
|
|
4986
|
+
} finally {
|
|
4987
|
+
deadline.dispose();
|
|
4660
4988
|
}
|
|
4661
|
-
const result = await generateImage(deps.generateDeps, {
|
|
4662
|
-
prompt: parsed.prompt,
|
|
4663
|
-
...parsed.model === void 0 ? {} : { model: parsed.model },
|
|
4664
|
-
...parsed.size === void 0 ? {} : { size: parsed.size },
|
|
4665
|
-
...parsed.quality === void 0 ? {} : { quality: parsed.quality },
|
|
4666
|
-
...parsed.n === void 0 ? {} : { n: parsed.n },
|
|
4667
|
-
...parsed.referenceImages === void 0 ? {} : { referenceImages: parsed.referenceImages },
|
|
4668
|
-
...referenceFiles.length > 0 ? { referenceFiles } : {},
|
|
4669
|
-
...parsed.outputPath === void 0 ? {} : { outputPath: parsed.outputPath },
|
|
4670
|
-
signal: exec.signal
|
|
4671
|
-
});
|
|
4672
|
-
const images = [];
|
|
4673
|
-
for (const image of result.images) {
|
|
4674
|
-
const bytes = Uint8Array.from(atob(image.data), (ch) => ch.charCodeAt(0));
|
|
4675
|
-
const attachment = await deps.attachments.saveImage({ data: bytes, mediaType: result.mime, name: "generated-image" });
|
|
4676
|
-
images.push({ attachment: attachmentValueOf(attachment), filePath: image.filePath });
|
|
4677
|
-
}
|
|
4678
|
-
return {
|
|
4679
|
-
images,
|
|
4680
|
-
model: result.model,
|
|
4681
|
-
prompt: result.prompt,
|
|
4682
|
-
paramsUsed: result.paramsUsed,
|
|
4683
|
-
revisions: result.revisions
|
|
4684
|
-
};
|
|
4685
4989
|
},
|
|
4686
4990
|
presentCall: (args) => {
|
|
4687
4991
|
const record = typeof args === "object" && args !== null ? args : {};
|
|
@@ -4726,29 +5030,32 @@ function registerGenerateImageTool(ctx, deps) {
|
|
|
4726
5030
|
}
|
|
4727
5031
|
function imageToolHint(config) {
|
|
4728
5032
|
if (config.models.length === 0) return "";
|
|
4729
|
-
const
|
|
5033
|
+
const defaults = `size ${config.defaults.size}\uFF0Cquality ${config.defaults.quality}\uFF0Cn ${config.defaults.n}`;
|
|
5034
|
+
const resolved = resolveImageModel(config);
|
|
5035
|
+
const opening = resolved === void 0 ? `\u751F\u56FE\u8BF7\u8C03\u7528 generate_image \u5DE5\u5177\u3002\u5F53\u524D\u6CA1\u6709\u552F\u4E00\u7684\u9ED8\u8BA4\u751F\u56FE\u6A21\u578B\uFF08\u5171 ${config.models.length} \u4E2A\u5019\u9009\uFF09\uFF0C\u8C03\u7528\u65F6\u5FC5\u987B\u663E\u5F0F\u586B model\uFF0C\u53EF\u9009\u503C\uFF1A${config.models.map((model) => model.id).join("\u3001")}\uFF1Bsize/quality/n \u53EF\u7F3A\u7701\uFF08\u9ED8\u8BA4 ${defaults}\uFF09\u3002` : `\u751F\u56FE\u8BF7\u8C03\u7528 generate_image \u5DE5\u5177\uFF08\u7F3A\u7701\u53C2\u6570\u5373\u53EF\uFF1A\u9ED8\u8BA4\u6A21\u578B ${resolved.id}\uFF0C${defaults}\uFF09\u3002`;
|
|
4730
5036
|
const lines = [
|
|
4731
|
-
|
|
4732
|
-
"\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u6216\u53C2\u6570\u65F6\uFF0C\u4E0D\u8981\u586B model/size/quality/n\uFF1B\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002",
|
|
4733
|
-
"\u4E0D\u8981\u81EA\u5DF1\u7F16\u9020\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u7528\u522B\u7684\u5DE5\u5177\u627E\u751F\u6210\u7684\u56FE\u7247\u2014\u2014\u6210\u529F\u540E\
|
|
5037
|
+
opening,
|
|
5038
|
+
resolved === void 0 ? "\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u65F6\uFF0C\u5148\u95EE\u6E05\u7528\u54EA\u4E2A\u6A21\u578B\uFF0C\u4E0D\u8981\u81EA\u5DF1\u6311\u4E00\u4E2A\u2014\u2014\u731C\u9519\u7684\u6A21\u578B\u4F1A\u76F4\u63A5\u751F\u6210\u5931\u8D25\u3002\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002" : "\u7528\u6237\u6CA1\u6709\u70B9\u540D\u6A21\u578B\u6216\u53C2\u6570\u65F6\uFF0C\u4E0D\u8981\u586B model/size/quality/n\uFF1B\u6539\u56FE\u7528\u5BF9\u8BDD\u5185\u56FE\u7247\u7684\u9644\u4EF6 ID \u586B reference_attachments\uFF0C\u672C\u5730\u6587\u4EF6\u586B reference_images\u3002",
|
|
5039
|
+
"\u4E0D\u8981\u81EA\u5DF1\u7F16\u9020\u56FE\u7247 URL\uFF0C\u4E5F\u4E0D\u8981\u7528\u522B\u7684\u5DE5\u5177\u627E\u751F\u6210\u7684\u56FE\u7247\u2014\u2014\u6210\u529F\u540E\u5DE5\u5177\u4F1A\u8FD4\u56DE\u9644\u4EF6\u548C\u771F\u5B9E filePath\u3002",
|
|
5040
|
+
IMAGE_REPLY_HINT
|
|
4734
5041
|
];
|
|
4735
5042
|
return lines.join("\n");
|
|
4736
5043
|
}
|
|
4737
5044
|
|
|
4738
5045
|
// src/image/legacy-cleanup.ts
|
|
4739
|
-
import { copyFileSync, existsSync as existsSync3, mkdirSync as
|
|
4740
|
-
import { dirname as
|
|
5046
|
+
import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync7, readdirSync, statSync as statSync2, writeFileSync as writeFileSync6 } from "node:fs";
|
|
5047
|
+
import { dirname as dirname7, join as join7 } from "node:path";
|
|
4741
5048
|
var MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`;
|
|
4742
5049
|
var MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`;
|
|
4743
5050
|
function resolveLegacyPatchFile(home = harnessHome()) {
|
|
4744
5051
|
const explicit = process.env["DSH_PROFILE"];
|
|
4745
|
-
if (explicit !== void 0 && explicit.length > 0) return
|
|
4746
|
-
const profilesDir =
|
|
5052
|
+
if (explicit !== void 0 && explicit.length > 0) return join7(home, "profiles", explicit, "cordis.patch.yml");
|
|
5053
|
+
const profilesDir = join7(home, "profiles");
|
|
4747
5054
|
try {
|
|
4748
5055
|
if (existsSync3(profilesDir)) {
|
|
4749
5056
|
const candidates = [];
|
|
4750
5057
|
for (const name2 of readdirSync(profilesDir)) {
|
|
4751
|
-
const file =
|
|
5058
|
+
const file = join7(profilesDir, name2, "cordis.patch.yml");
|
|
4752
5059
|
if (!existsSync3(file)) continue;
|
|
4753
5060
|
candidates.push({ file, mtime: statSync2(file).mtimeMs });
|
|
4754
5061
|
}
|
|
@@ -4757,8 +5064,8 @@ function resolveLegacyPatchFile(home = harnessHome()) {
|
|
|
4757
5064
|
}
|
|
4758
5065
|
} catch {
|
|
4759
5066
|
}
|
|
4760
|
-
if (existsSync3(
|
|
4761
|
-
return
|
|
5067
|
+
if (existsSync3(join7(home, "cordis.patch.yml"))) return join7(home, "cordis.patch.yml");
|
|
5068
|
+
return join7(home, "profiles", "desktop", "cordis.patch.yml");
|
|
4762
5069
|
}
|
|
4763
5070
|
function markerRange(text) {
|
|
4764
5071
|
const start = text.indexOf(MARK_BEGIN);
|
|
@@ -4768,6 +5075,40 @@ function markerRange(text) {
|
|
|
4768
5075
|
const lineEnd = text.indexOf("\n", endMarker);
|
|
4769
5076
|
return { start, end: lineEnd === -1 ? text.length : lineEnd + 1 };
|
|
4770
5077
|
}
|
|
5078
|
+
function linesOf(text) {
|
|
5079
|
+
const out = [];
|
|
5080
|
+
let start = 0;
|
|
5081
|
+
for (const line of text.split("\n")) {
|
|
5082
|
+
out.push({ text: line, start });
|
|
5083
|
+
start += line.length + 1;
|
|
5084
|
+
}
|
|
5085
|
+
return out;
|
|
5086
|
+
}
|
|
5087
|
+
function staleEntryRange(text) {
|
|
5088
|
+
const lines = linesOf(text);
|
|
5089
|
+
const ownId = new RegExp(`^\\s*-\\s+id:\\s*['"]?${IMAGE_MCP_PATCH_ID}['"]?\\s*$`);
|
|
5090
|
+
const anyId = /^\s*-\s+id:/;
|
|
5091
|
+
for (const [index, line] of lines.entries()) {
|
|
5092
|
+
if (!/^-(\s|$)/.test(line.text)) continue;
|
|
5093
|
+
let end = lines.length;
|
|
5094
|
+
for (let probe = index + 1; probe < lines.length; probe += 1) {
|
|
5095
|
+
const candidate = lines[probe];
|
|
5096
|
+
if (candidate.text.trim().length === 0) continue;
|
|
5097
|
+
if (!/^\s/.test(candidate.text)) {
|
|
5098
|
+
end = probe;
|
|
5099
|
+
break;
|
|
5100
|
+
}
|
|
5101
|
+
}
|
|
5102
|
+
const body = lines.slice(index + 1, end);
|
|
5103
|
+
const owned = /^-\s*insert:\s*$/.test(line.text) ? body.some((entry) => ownId.test(entry.text)) && !body.some((entry) => anyId.test(entry.text) && !ownId.test(entry.text)) : ownId.test(line.text);
|
|
5104
|
+
if (!owned) continue;
|
|
5105
|
+
return { start: line.start, end: end < lines.length ? lines[end].start : text.length };
|
|
5106
|
+
}
|
|
5107
|
+
return void 0;
|
|
5108
|
+
}
|
|
5109
|
+
function legacyRange(text) {
|
|
5110
|
+
return markerRange(text) ?? staleEntryRange(text);
|
|
5111
|
+
}
|
|
4771
5112
|
function validateAfterSplice(text) {
|
|
4772
5113
|
const begins = text.split(MARK_BEGIN).length - 1;
|
|
4773
5114
|
const ends = text.split(MARK_END).length - 1;
|
|
@@ -4785,8 +5126,8 @@ function mtimeOf(patchFile) {
|
|
|
4785
5126
|
var ModifiedError = class extends Error {
|
|
4786
5127
|
};
|
|
4787
5128
|
function spliceOnce(patchFile, mtimeMs) {
|
|
4788
|
-
const current =
|
|
4789
|
-
const range =
|
|
5129
|
+
const current = readFileSync7(patchFile, "utf8");
|
|
5130
|
+
const range = legacyRange(current);
|
|
4790
5131
|
if (range === void 0) return;
|
|
4791
5132
|
let next = current.slice(0, range.start) + current.slice(range.end);
|
|
4792
5133
|
if (current.slice(range.end).trim().length === 0) next = next.replace(/\n+$/, "\n");
|
|
@@ -4799,9 +5140,9 @@ function spliceOnce(patchFile, mtimeMs) {
|
|
|
4799
5140
|
} catch {
|
|
4800
5141
|
}
|
|
4801
5142
|
}
|
|
4802
|
-
|
|
4803
|
-
|
|
4804
|
-
const written =
|
|
5143
|
+
mkdirSync6(dirname7(patchFile), { recursive: true });
|
|
5144
|
+
writeFileSync6(patchFile, next, "utf8");
|
|
5145
|
+
const written = readFileSync7(patchFile, "utf8");
|
|
4805
5146
|
if (written !== next) throw new Error("the patch file did not hold the written bytes after the write");
|
|
4806
5147
|
}
|
|
4807
5148
|
function removeLegacyImageMcpPatch(home, patchFile) {
|
|
@@ -4813,11 +5154,11 @@ function removeLegacyImageMcpPatch(home, patchFile) {
|
|
|
4813
5154
|
}
|
|
4814
5155
|
let text;
|
|
4815
5156
|
try {
|
|
4816
|
-
text =
|
|
5157
|
+
text = readFileSync7(file, "utf8");
|
|
4817
5158
|
} catch {
|
|
4818
5159
|
return void 0;
|
|
4819
5160
|
}
|
|
4820
|
-
if (
|
|
5161
|
+
if (legacyRange(text) === void 0) return void 0;
|
|
4821
5162
|
if (!text.includes(`- id: ${IMAGE_MCP_PATCH_ID}`)) {
|
|
4822
5163
|
return void 0;
|
|
4823
5164
|
}
|
|
@@ -4914,6 +5255,39 @@ function buildAutofillPatch(providers, routeFilter = () => true, options = {}, r
|
|
|
4914
5255
|
}
|
|
4915
5256
|
return Object.keys(patchRoutes).length === 0 ? void 0 : { providers: patchRoutes };
|
|
4916
5257
|
}
|
|
5258
|
+
function buildCompatCleanupPatch(providers) {
|
|
5259
|
+
if (!isRecord(providers)) return void 0;
|
|
5260
|
+
const patchRoutes = {};
|
|
5261
|
+
for (const [route, profile] of Object.entries(providers)) {
|
|
5262
|
+
if (!isRecord(profile)) continue;
|
|
5263
|
+
const api = typeof profile["api"] === "string" ? profile["api"] : "";
|
|
5264
|
+
if (api.length === 0) continue;
|
|
5265
|
+
const patchProfile = {};
|
|
5266
|
+
const routeCompat = isRecord(profile["compat"]) ? stripForeignCompat(profile["compat"], api) : void 0;
|
|
5267
|
+
if (routeCompat !== void 0) patchProfile["compat"] = routeCompat;
|
|
5268
|
+
const rawModels = Array.isArray(profile["models"]) ? profile["models"] : void 0;
|
|
5269
|
+
if (rawModels !== void 0 && rawModels.length > 0) {
|
|
5270
|
+
const nextModels = [];
|
|
5271
|
+
let changed = false;
|
|
5272
|
+
for (const row of rawModels) {
|
|
5273
|
+
if (!isRecord(row) || !isRecord(row["compat"])) {
|
|
5274
|
+
nextModels.push(row);
|
|
5275
|
+
continue;
|
|
5276
|
+
}
|
|
5277
|
+
const cleaned = stripForeignCompat(row["compat"], api);
|
|
5278
|
+
if (cleaned === void 0) {
|
|
5279
|
+
nextModels.push(row);
|
|
5280
|
+
continue;
|
|
5281
|
+
}
|
|
5282
|
+
changed = true;
|
|
5283
|
+
nextModels.push({ ...row, compat: cleaned });
|
|
5284
|
+
}
|
|
5285
|
+
if (changed) patchProfile["models"] = nextModels;
|
|
5286
|
+
}
|
|
5287
|
+
if (Object.keys(patchProfile).length > 0) patchRoutes[route] = patchProfile;
|
|
5288
|
+
}
|
|
5289
|
+
return Object.keys(patchRoutes).length === 0 ? void 0 : { providers: patchRoutes };
|
|
5290
|
+
}
|
|
4917
5291
|
function stripNewCompatKeysDeep(patch) {
|
|
4918
5292
|
const providers = isRecord(patch["providers"]) ? patch["providers"] : void 0;
|
|
4919
5293
|
if (providers === void 0) return void 0;
|
|
@@ -4953,9 +5327,9 @@ function backfillRolePin(model, providers, route) {
|
|
|
4953
5327
|
}
|
|
4954
5328
|
|
|
4955
5329
|
// src/fingerprint/bank.ts
|
|
4956
|
-
import { existsSync as existsSync4, readFileSync as
|
|
5330
|
+
import { existsSync as existsSync4, readFileSync as readFileSync8 } from "node:fs";
|
|
4957
5331
|
import { fileURLToPath } from "node:url";
|
|
4958
|
-
import { dirname as
|
|
5332
|
+
import { dirname as dirname8, join as join8 } from "node:path";
|
|
4959
5333
|
|
|
4960
5334
|
// src/fingerprint/core.ts
|
|
4961
5335
|
var VALUE_MIN = 1;
|
|
@@ -5240,10 +5614,10 @@ function parseBank(raw) {
|
|
|
5240
5614
|
}
|
|
5241
5615
|
function bankCandidates() {
|
|
5242
5616
|
const candidates = [];
|
|
5243
|
-
let dir =
|
|
5617
|
+
let dir = dirname8(fileURLToPath(import.meta.url));
|
|
5244
5618
|
for (let depth = 0; depth < 5; depth += 1) {
|
|
5245
|
-
candidates.push(
|
|
5246
|
-
const parent =
|
|
5619
|
+
candidates.push(join8(dir, "assets", "unified_bank.json"));
|
|
5620
|
+
const parent = dirname8(dir);
|
|
5247
5621
|
if (parent === dir) break;
|
|
5248
5622
|
dir = parent;
|
|
5249
5623
|
}
|
|
@@ -5260,7 +5634,7 @@ function bankPath() {
|
|
|
5260
5634
|
var cached;
|
|
5261
5635
|
function loadBankSync() {
|
|
5262
5636
|
if (cached !== void 0) return cached;
|
|
5263
|
-
cached = parseBank(JSON.parse(
|
|
5637
|
+
cached = parseBank(JSON.parse(readFileSync8(bankPath(), "utf8")));
|
|
5264
5638
|
return cached;
|
|
5265
5639
|
}
|
|
5266
5640
|
function summarizeBank(bank) {
|
|
@@ -5529,8 +5903,8 @@ async function runChallenge(options) {
|
|
|
5529
5903
|
}
|
|
5530
5904
|
|
|
5531
5905
|
// src/fingerprint/store.ts
|
|
5532
|
-
import { mkdirSync as
|
|
5533
|
-
import { dirname as
|
|
5906
|
+
import { mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync as renameSync5, unlinkSync as unlinkSync5, writeFileSync as writeFileSync7 } from "node:fs";
|
|
5907
|
+
import { dirname as dirname9, join as join9 } from "node:path";
|
|
5534
5908
|
var STATUSES = /* @__PURE__ */ new Set(["identified", "doubtful", "failed"]);
|
|
5535
5909
|
function emptyFingerprintStore(bankBuiltAt2 = "") {
|
|
5536
5910
|
return { version: 1, bankBuiltAt: bankBuiltAt2, records: {} };
|
|
@@ -5539,7 +5913,7 @@ function recordKeyOf(provider, model) {
|
|
|
5539
5913
|
return `${provider}\0${model}`;
|
|
5540
5914
|
}
|
|
5541
5915
|
function fingerprintFilePath(home = harnessHome()) {
|
|
5542
|
-
return
|
|
5916
|
+
return join9(home, "dsh-model-think-level", "fingerprint.json");
|
|
5543
5917
|
}
|
|
5544
5918
|
function finiteNumber(value, fallback) {
|
|
5545
5919
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
@@ -5657,7 +6031,7 @@ function parseFingerprintStore(raw, bankBuiltAt2 = "") {
|
|
|
5657
6031
|
function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
|
|
5658
6032
|
let text;
|
|
5659
6033
|
try {
|
|
5660
|
-
text =
|
|
6034
|
+
text = readFileSync9(file, "utf8");
|
|
5661
6035
|
} catch (error) {
|
|
5662
6036
|
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
|
|
5663
6037
|
return emptyFingerprintStore(bankBuiltAt2);
|
|
@@ -5673,15 +6047,15 @@ function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
|
|
|
5673
6047
|
return parseFingerprintStore(raw, bankBuiltAt2);
|
|
5674
6048
|
}
|
|
5675
6049
|
function writeFingerprintStore(document, file = fingerprintFilePath()) {
|
|
5676
|
-
|
|
6050
|
+
mkdirSync7(dirname9(file), { recursive: true });
|
|
5677
6051
|
const temporary = `${file}.${process.pid}.tmp`;
|
|
5678
|
-
|
|
6052
|
+
writeFileSync7(temporary, `${JSON.stringify(document, null, 2)}
|
|
5679
6053
|
`, "utf8");
|
|
5680
6054
|
try {
|
|
5681
|
-
|
|
6055
|
+
renameSync5(temporary, file);
|
|
5682
6056
|
} catch (error) {
|
|
5683
6057
|
try {
|
|
5684
|
-
|
|
6058
|
+
unlinkSync5(temporary);
|
|
5685
6059
|
} catch {
|
|
5686
6060
|
}
|
|
5687
6061
|
throw error;
|
|
@@ -5739,7 +6113,8 @@ var inject = ["settings", "llm"];
|
|
|
5739
6113
|
var PI_NS = PI_AI_NS;
|
|
5740
6114
|
var BOOT_RETRY_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
|
|
5741
6115
|
var PROBE_TIMEOUT_MS = 15e3;
|
|
5742
|
-
var BALANCE_TIMEOUT_MS =
|
|
6116
|
+
var BALANCE_TIMEOUT_MS = 8e3;
|
|
6117
|
+
var CREDENTIAL_IPC_BUDGET_MS = 1e4;
|
|
5743
6118
|
var FINGERPRINT_CHALLENGE_TIMEOUT_MS = 12e4;
|
|
5744
6119
|
function fingerprintTimingOf(outcomes) {
|
|
5745
6120
|
const accepted = outcomes.filter((outcome) => outcome.ok && typeof outcome.durationMs === "number");
|
|
@@ -5858,25 +6233,42 @@ async function storeCredential(credentials, ref, value) {
|
|
|
5858
6233
|
if (credentials === void 0 || typeof set !== "function") {
|
|
5859
6234
|
return "this deployment cannot write the credential store";
|
|
5860
6235
|
}
|
|
6236
|
+
invalidateCredentialDisplay(credentials, ref);
|
|
5861
6237
|
try {
|
|
5862
6238
|
const answer = await set.call(credentials, ref, value);
|
|
5863
6239
|
if (!isRefusal(answer)) return void 0;
|
|
5864
6240
|
return refusalMessage(answer) ?? `the credential store refused ${ref}`;
|
|
5865
6241
|
} catch (error) {
|
|
5866
6242
|
return error instanceof Error ? error.message : String(error);
|
|
6243
|
+
} finally {
|
|
6244
|
+
invalidateCredentialDisplay(credentials, ref);
|
|
5867
6245
|
}
|
|
5868
6246
|
}
|
|
5869
|
-
async function forgetCredential(credentials, ref) {
|
|
6247
|
+
async function forgetCredential(credentials, ref, budgetMs) {
|
|
5870
6248
|
const unset = credentials?.unset;
|
|
5871
6249
|
if (credentials === void 0 || typeof unset !== "function") {
|
|
5872
6250
|
return "this deployment cannot write the credential store";
|
|
5873
6251
|
}
|
|
6252
|
+
invalidateCredentialDisplay(credentials, ref);
|
|
6253
|
+
let timer;
|
|
5874
6254
|
try {
|
|
5875
|
-
const answer = await
|
|
6255
|
+
const answer = await Promise.race([
|
|
6256
|
+
unset.call(credentials, ref),
|
|
6257
|
+
budgetMs === void 0 ? new Promise(() => {
|
|
6258
|
+
}) : new Promise((_, reject) => {
|
|
6259
|
+
timer = setTimeout(
|
|
6260
|
+
() => reject(new Error(`the credential store did not answer within ${Math.round(budgetMs / 1e3)}s`)),
|
|
6261
|
+
budgetMs
|
|
6262
|
+
);
|
|
6263
|
+
})
|
|
6264
|
+
]);
|
|
5876
6265
|
if (!isRefusal(answer)) return void 0;
|
|
5877
6266
|
return refusalMessage(answer) ?? `the credential store refused to forget ${ref}`;
|
|
5878
6267
|
} catch (error) {
|
|
5879
6268
|
return error instanceof Error ? error.message : String(error);
|
|
6269
|
+
} finally {
|
|
6270
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
6271
|
+
invalidateCredentialDisplay(credentials, ref);
|
|
5880
6272
|
}
|
|
5881
6273
|
}
|
|
5882
6274
|
var HostReadError = class extends Error {
|
|
@@ -5904,6 +6296,87 @@ async function resolveCredential(credentials, ref) {
|
|
|
5904
6296
|
function holdsNothing(fact) {
|
|
5905
6297
|
return fact !== void 0 && fact.configured === false && fact.masked === void 0;
|
|
5906
6298
|
}
|
|
6299
|
+
var CREDENTIAL_DISPLAY_TTL_MS = 5e3;
|
|
6300
|
+
var CREDENTIAL_DISPLAY_MAX_REFS = 512;
|
|
6301
|
+
var credentialDisplayReads = /* @__PURE__ */ new WeakMap();
|
|
6302
|
+
function invalidateCredentialDisplay(credentials, ref) {
|
|
6303
|
+
if (credentials !== void 0) credentialDisplayReads.get(credentials)?.delete(ref);
|
|
6304
|
+
}
|
|
6305
|
+
async function displayCredentialFacts(credentials, refs, budgetMs) {
|
|
6306
|
+
if (credentials === void 0 || refs.length === 0) return {};
|
|
6307
|
+
let cache = credentialDisplayReads.get(credentials);
|
|
6308
|
+
if (cache === void 0) {
|
|
6309
|
+
cache = /* @__PURE__ */ new Map();
|
|
6310
|
+
credentialDisplayReads.set(credentials, cache);
|
|
6311
|
+
}
|
|
6312
|
+
const now = Date.now();
|
|
6313
|
+
for (const [ref, read] of cache) if (read.expiresAt <= now) cache.delete(ref);
|
|
6314
|
+
const selected = /* @__PURE__ */ new Map();
|
|
6315
|
+
const missing = [];
|
|
6316
|
+
for (const ref of new Set(refs)) {
|
|
6317
|
+
let read = cache.get(ref);
|
|
6318
|
+
if (read === void 0) {
|
|
6319
|
+
read = { expiresAt: now + CREDENTIAL_DISPLAY_TTL_MS, settled: Promise.resolve() };
|
|
6320
|
+
cache.set(ref, read);
|
|
6321
|
+
missing.push(ref);
|
|
6322
|
+
}
|
|
6323
|
+
selected.set(ref, read);
|
|
6324
|
+
}
|
|
6325
|
+
const described = missing.length === 0 || typeof credentials.describe !== "function" ? Promise.resolve(void 0) : (async () => {
|
|
6326
|
+
try {
|
|
6327
|
+
const answer = await credentials.describe?.(missing);
|
|
6328
|
+
return isRefusal(answer) ? void 0 : describeRecords(answer);
|
|
6329
|
+
} catch {
|
|
6330
|
+
return void 0;
|
|
6331
|
+
}
|
|
6332
|
+
})();
|
|
6333
|
+
for (const ref of missing) {
|
|
6334
|
+
const read = selected.get(ref);
|
|
6335
|
+
const resolved = (async () => {
|
|
6336
|
+
try {
|
|
6337
|
+
const value = await resolveCredential(credentials, ref);
|
|
6338
|
+
const masked = value === void 0 ? void 0 : maskKeyValue(value);
|
|
6339
|
+
read.resolved = masked === void 0 || masked.length === 0 ? { configured: value !== void 0 } : { configured: true, masked };
|
|
6340
|
+
return true;
|
|
6341
|
+
} catch {
|
|
6342
|
+
return false;
|
|
6343
|
+
}
|
|
6344
|
+
})();
|
|
6345
|
+
const metadata = described.then((records) => {
|
|
6346
|
+
const info = records?.[ref];
|
|
6347
|
+
if (isRecord(info) && typeof info["configured"] === "boolean") read.described = info["configured"];
|
|
6348
|
+
return typeof credentials.describe !== "function" || read.described !== void 0;
|
|
6349
|
+
});
|
|
6350
|
+
read.settled = Promise.all([resolved, metadata]).then(([resolvedOK, describedOK]) => {
|
|
6351
|
+
if (cache.get(ref) !== read) return;
|
|
6352
|
+
read.expiresAt = resolvedOK && describedOK ? Date.now() + CREDENTIAL_DISPLAY_TTL_MS : 0;
|
|
6353
|
+
});
|
|
6354
|
+
}
|
|
6355
|
+
while (cache.size > CREDENTIAL_DISPLAY_MAX_REFS) {
|
|
6356
|
+
const oldest = cache.keys().next().value;
|
|
6357
|
+
if (oldest === void 0) break;
|
|
6358
|
+
cache.delete(oldest);
|
|
6359
|
+
}
|
|
6360
|
+
let timer;
|
|
6361
|
+
try {
|
|
6362
|
+
await Promise.race([
|
|
6363
|
+
Promise.all([...selected.values()].map((read) => read.settled)),
|
|
6364
|
+
new Promise((resolve3) => {
|
|
6365
|
+
timer = setTimeout(resolve3, budgetMs);
|
|
6366
|
+
})
|
|
6367
|
+
]);
|
|
6368
|
+
} finally {
|
|
6369
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
6370
|
+
}
|
|
6371
|
+
const out = {};
|
|
6372
|
+
for (const [ref, read] of selected) {
|
|
6373
|
+
if (cache.get(ref) !== read) continue;
|
|
6374
|
+
const configured = read.described ?? read.resolved?.configured;
|
|
6375
|
+
if (configured === void 0) continue;
|
|
6376
|
+
out[ref] = read.resolved?.masked === void 0 ? { configured } : { configured, masked: read.resolved.masked };
|
|
6377
|
+
}
|
|
6378
|
+
return out;
|
|
6379
|
+
}
|
|
5907
6380
|
async function credentialFacts(credentials, refs, budgetMs) {
|
|
5908
6381
|
const described = {};
|
|
5909
6382
|
const resolvedFacts = {};
|
|
@@ -5948,8 +6421,8 @@ async function credentialFacts(credentials, refs, budgetMs) {
|
|
|
5948
6421
|
}
|
|
5949
6422
|
return out;
|
|
5950
6423
|
}
|
|
5951
|
-
async function credentialConfigured(credentials, refs) {
|
|
5952
|
-
const facts = await credentialFacts(credentials, refs);
|
|
6424
|
+
async function credentialConfigured(credentials, refs, budgetMs) {
|
|
6425
|
+
const facts = await credentialFacts(credentials, refs, budgetMs);
|
|
5953
6426
|
const out = {};
|
|
5954
6427
|
for (const ref of refs) {
|
|
5955
6428
|
const configured = facts[ref]?.configured;
|
|
@@ -6065,32 +6538,33 @@ function apply(ctx, config = {}) {
|
|
|
6065
6538
|
uaOverride: config.uaOverride !== false
|
|
6066
6539
|
};
|
|
6067
6540
|
const settings = ctx.settings;
|
|
6068
|
-
let
|
|
6069
|
-
let
|
|
6070
|
-
const
|
|
6071
|
-
if (
|
|
6072
|
-
let
|
|
6541
|
+
let piDescriptorCache;
|
|
6542
|
+
let piDescriptorCached = false;
|
|
6543
|
+
const piDescriptor = (required = false) => {
|
|
6544
|
+
if (piDescriptorCached) return piDescriptorCache;
|
|
6545
|
+
let descriptor;
|
|
6073
6546
|
try {
|
|
6074
|
-
|
|
6547
|
+
descriptor = settings.describe().find((entry) => entry.ns === PI_NS);
|
|
6075
6548
|
} catch {
|
|
6076
6549
|
if (required) throw new HostReadError("the llm-pi-ai settings could not be read");
|
|
6077
6550
|
return void 0;
|
|
6078
6551
|
}
|
|
6079
|
-
if (
|
|
6552
|
+
if (descriptor === void 0 || !isRecord(descriptor.value)) {
|
|
6080
6553
|
if (required) throw new HostReadError("the llm-pi-ai settings entry is unavailable");
|
|
6081
6554
|
return void 0;
|
|
6082
6555
|
}
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
return
|
|
6556
|
+
piDescriptorCache = descriptor;
|
|
6557
|
+
piDescriptorCached = true;
|
|
6558
|
+
return descriptor;
|
|
6086
6559
|
};
|
|
6560
|
+
const piSection = (required = false) => piDescriptor(required)?.value;
|
|
6087
6561
|
ctx.on("settings/document-updated", (ns) => {
|
|
6088
|
-
if (ns === PI_NS)
|
|
6562
|
+
if (ns === PI_NS) piDescriptorCached = false;
|
|
6089
6563
|
});
|
|
6090
6564
|
if (resolved.autofill) {
|
|
6091
6565
|
const autofillOnce = async () => {
|
|
6092
|
-
const descriptor =
|
|
6093
|
-
if (
|
|
6566
|
+
const descriptor = piDescriptor();
|
|
6567
|
+
if (descriptor === void 0) return false;
|
|
6094
6568
|
const user = descriptor?.user;
|
|
6095
6569
|
const userProviders = isRecord(user) && isRecord(user["providers"]) ? user["providers"] : void 0;
|
|
6096
6570
|
if (userProviders === void 0) return true;
|
|
@@ -6127,6 +6601,44 @@ function apply(ctx, config = {}) {
|
|
|
6127
6601
|
};
|
|
6128
6602
|
bootFill(0);
|
|
6129
6603
|
}
|
|
6604
|
+
{
|
|
6605
|
+
const logGuardFailure = (error) => {
|
|
6606
|
+
console.error(`[dsh-model-think-level] compat cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
6607
|
+
};
|
|
6608
|
+
const guardTimers = /* @__PURE__ */ new Set();
|
|
6609
|
+
ctx.effect(() => () => {
|
|
6610
|
+
for (const timer of guardTimers) clearTimeout(timer);
|
|
6611
|
+
guardTimers.clear();
|
|
6612
|
+
}, "dsh-model-think-level: compat-guard boot retries");
|
|
6613
|
+
const sweepOnce = async () => {
|
|
6614
|
+
const descriptor = piDescriptor();
|
|
6615
|
+
if (descriptor === void 0) return false;
|
|
6616
|
+
const user = descriptor.user;
|
|
6617
|
+
const userProviders = isRecord(user) && isRecord(user["providers"]) ? user["providers"] : void 0;
|
|
6618
|
+
if (userProviders === void 0) return true;
|
|
6619
|
+
const patch = buildCompatCleanupPatch(userProviders);
|
|
6620
|
+
if (patch === void 0) return true;
|
|
6621
|
+
try {
|
|
6622
|
+
await settings.update(PI_NS, patch, descriptor.revision);
|
|
6623
|
+
} catch (error) {
|
|
6624
|
+
logGuardFailure(error);
|
|
6625
|
+
piDescriptorCached = false;
|
|
6626
|
+
return false;
|
|
6627
|
+
}
|
|
6628
|
+
return true;
|
|
6629
|
+
};
|
|
6630
|
+
const bootSweep = (attempt) => {
|
|
6631
|
+
void sweepOnce().then((ready) => {
|
|
6632
|
+
if (ready || attempt >= resolved.bootRetryDelaysMs.length) return;
|
|
6633
|
+
const timer = setTimeout(() => {
|
|
6634
|
+
guardTimers.delete(timer);
|
|
6635
|
+
bootSweep(attempt + 1);
|
|
6636
|
+
}, resolved.bootRetryDelaysMs[attempt]);
|
|
6637
|
+
guardTimers.add(timer);
|
|
6638
|
+
}, logGuardFailure);
|
|
6639
|
+
};
|
|
6640
|
+
bootSweep(0);
|
|
6641
|
+
}
|
|
6130
6642
|
if (resolved.defaultGuard) {
|
|
6131
6643
|
ctx.inject(["llm"], (llmCtx) => {
|
|
6132
6644
|
const llm = llmCtx.llm;
|
|
@@ -6193,46 +6705,71 @@ function apply(ctx, config = {}) {
|
|
|
6193
6705
|
profile["headers"]
|
|
6194
6706
|
]).sort(([a], [b]) => String(a).localeCompare(String(b))));
|
|
6195
6707
|
let catalogueSourceStamp = catalogueSource();
|
|
6196
|
-
const invalidateListings = () => {
|
|
6197
|
-
|
|
6198
|
-
|
|
6199
|
-
|
|
6200
|
-
const keyProbeRuns = /* @__PURE__ */ new Map();
|
|
6201
|
-
const keyProbeTimers = /* @__PURE__ */ new Map();
|
|
6202
|
-
ctx.effect(() => () => {
|
|
6203
|
-
for (const timer of keyProbeTimers.values()) clearTimeout(timer);
|
|
6204
|
-
keyProbeTimers.clear();
|
|
6205
|
-
}, "dsh-model-think-level: scope probe timers");
|
|
6206
|
-
const KEY_PROBE_DELAY_MS = 600;
|
|
6207
|
-
const keyProbeStamps = /* @__PURE__ */ new Map();
|
|
6208
|
-
let keyProbeStampsReady = false;
|
|
6209
|
-
const keyProbeSignature = (profile) => JSON.stringify([
|
|
6210
|
-
profile["api"],
|
|
6211
|
-
profile["baseURL"],
|
|
6212
|
-
profile["apiKeyEnv"],
|
|
6213
|
-
profile["headers"],
|
|
6214
|
-
Array.isArray(profile["models"]) ? profile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean) : []
|
|
6215
|
-
]);
|
|
6216
|
-
const reconcileKeyProbeStamps = () => {
|
|
6217
|
-
const providers = providersOf();
|
|
6218
|
-
if (!keyProbeStampsReady) {
|
|
6219
|
-
keyProbeStampsReady = true;
|
|
6220
|
-
for (const [route, profile] of Object.entries(providers)) {
|
|
6221
|
-
if (isRecord(profile)) keyProbeStamps.set(route, keyProbeSignature(profile));
|
|
6222
|
-
}
|
|
6708
|
+
const invalidateListings = (route) => {
|
|
6709
|
+
if (route === void 0) {
|
|
6710
|
+
probeRouteCache.clear();
|
|
6711
|
+
listingCache.clear();
|
|
6223
6712
|
return;
|
|
6224
6713
|
}
|
|
6225
|
-
|
|
6226
|
-
|
|
6714
|
+
const prefix = `${route}\0`;
|
|
6715
|
+
for (const key of Array.from(listingCache.keys())) {
|
|
6716
|
+
if (key.startsWith(prefix)) listingCache.delete(key);
|
|
6717
|
+
}
|
|
6718
|
+
};
|
|
6719
|
+
const sweepVanishedRoutes = () => {
|
|
6720
|
+
if (piSection() === void 0) return false;
|
|
6721
|
+
const live = providersOf();
|
|
6722
|
+
const indexFile = keyIndexFilePath();
|
|
6723
|
+
let index;
|
|
6724
|
+
try {
|
|
6725
|
+
index = readKeyIndex(indexFile);
|
|
6726
|
+
} catch {
|
|
6727
|
+
return true;
|
|
6728
|
+
}
|
|
6729
|
+
const stale = /* @__PURE__ */ new Set();
|
|
6730
|
+
for (const route of Object.keys(index.providers)) if (!(route in live)) stale.add(route);
|
|
6731
|
+
for (const route of Object.keys(index.endpoints ?? {})) if (!(route in live)) stale.add(route);
|
|
6732
|
+
for (const route of Object.keys(index.balances ?? {})) if (!(route in live)) stale.add(route);
|
|
6733
|
+
if (stale.size === 0) return true;
|
|
6734
|
+
const survivors = /* @__PURE__ */ new Set();
|
|
6735
|
+
for (const [route, entries] of Object.entries(index.providers)) {
|
|
6736
|
+
if (stale.has(route)) continue;
|
|
6737
|
+
for (const entry of entries) survivors.add(entry.ref);
|
|
6227
6738
|
}
|
|
6228
|
-
for (const
|
|
6739
|
+
for (const profile of Object.values(live)) {
|
|
6229
6740
|
if (!isRecord(profile)) continue;
|
|
6230
|
-
const
|
|
6231
|
-
if (
|
|
6232
|
-
keyProbeStamps.set(route, signature);
|
|
6233
|
-
scheduleKeyProbe(route);
|
|
6741
|
+
const seat = enabledRefOf(profile);
|
|
6742
|
+
if (seat !== void 0) survivors.add(seat);
|
|
6234
6743
|
}
|
|
6744
|
+
const credentials = ctx.get("credentials");
|
|
6745
|
+
let swept = false;
|
|
6746
|
+
for (const route of stale) {
|
|
6747
|
+
const refs = keyEntriesOf(index, route).map((entry) => entry.ref);
|
|
6748
|
+
try {
|
|
6749
|
+
updateKeyIndex((current) => withoutRoute(current, route), indexFile);
|
|
6750
|
+
} catch (error) {
|
|
6751
|
+
console.error(`[dsh-model-think-level] key route cleanup for "${route}" failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
6752
|
+
continue;
|
|
6753
|
+
}
|
|
6754
|
+
swept = true;
|
|
6755
|
+
for (const ref of refs) {
|
|
6756
|
+
forgetServes(route, ref);
|
|
6757
|
+
const here = `${route}\0${ref}`;
|
|
6758
|
+
lastKnownScopes.delete(here);
|
|
6759
|
+
lastKnownRecords.delete(here);
|
|
6760
|
+
if (survivors.has(ref)) continue;
|
|
6761
|
+
void forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS).then((refused) => {
|
|
6762
|
+
if (refused !== void 0) {
|
|
6763
|
+
console.error(`[dsh-model-think-level] credential cleanup for "${ref}" failed: ${refused}`);
|
|
6764
|
+
}
|
|
6765
|
+
});
|
|
6766
|
+
}
|
|
6767
|
+
invalidateListings(route);
|
|
6768
|
+
}
|
|
6769
|
+
if (swept) refreshKeyScopes();
|
|
6770
|
+
return true;
|
|
6235
6771
|
};
|
|
6772
|
+
const keyProbeRuns = /* @__PURE__ */ new Map();
|
|
6236
6773
|
const probeRouteKeys = async (route) => {
|
|
6237
6774
|
let profile;
|
|
6238
6775
|
try {
|
|
@@ -6255,7 +6792,7 @@ function apply(ctx, config = {}) {
|
|
|
6255
6792
|
const seat = enabledRefOf(profile);
|
|
6256
6793
|
const keys = listed.map((entry) => ({ ref: entry.ref, entry }));
|
|
6257
6794
|
if (seat !== void 0 && !listed.some((entry) => entry.ref === seat)) keys.push({ ref: seat, entry: void 0 });
|
|
6258
|
-
if (keys.length
|
|
6795
|
+
if (keys.length < 2) return;
|
|
6259
6796
|
const credentials = ctx.get("credentials");
|
|
6260
6797
|
const values = await Promise.all(keys.map(async (key) => {
|
|
6261
6798
|
try {
|
|
@@ -6332,14 +6869,6 @@ function apply(ctx, config = {}) {
|
|
|
6332
6869
|
keyProbeRuns.set(route, run);
|
|
6333
6870
|
return run;
|
|
6334
6871
|
};
|
|
6335
|
-
const scheduleKeyProbe = (route) => {
|
|
6336
|
-
if (keyProbeTimers.has(route)) return;
|
|
6337
|
-
const timer = setTimeout(() => {
|
|
6338
|
-
keyProbeTimers.delete(route);
|
|
6339
|
-
void runKeyProbe(route);
|
|
6340
|
-
}, KEY_PROBE_DELAY_MS);
|
|
6341
|
-
keyProbeTimers.set(route, timer);
|
|
6342
|
-
};
|
|
6343
6872
|
const headerRetryTimers = /* @__PURE__ */ new Set();
|
|
6344
6873
|
let headerRetryAttempt = 0;
|
|
6345
6874
|
const stopHeaderRetries = () => {
|
|
@@ -6380,15 +6909,35 @@ function apply(ctx, config = {}) {
|
|
|
6380
6909
|
if (ns === PI_NS) {
|
|
6381
6910
|
refreshHeaders();
|
|
6382
6911
|
refreshKeyScopes();
|
|
6912
|
+
sweepVanishedRoutes();
|
|
6383
6913
|
syncImageConfigNow();
|
|
6384
6914
|
const source = catalogueSource();
|
|
6385
6915
|
if (source !== catalogueSourceStamp) {
|
|
6386
6916
|
catalogueSourceStamp = source;
|
|
6387
6917
|
invalidateListings();
|
|
6388
6918
|
}
|
|
6389
|
-
reconcileKeyProbeStamps();
|
|
6390
6919
|
}
|
|
6391
6920
|
});
|
|
6921
|
+
{
|
|
6922
|
+
const sweepTimers = /* @__PURE__ */ new Set();
|
|
6923
|
+
ctx.effect(() => () => {
|
|
6924
|
+
for (const timer of sweepTimers) clearTimeout(timer);
|
|
6925
|
+
sweepTimers.clear();
|
|
6926
|
+
}, "dsh-model-think-level: route-sweep boot retries");
|
|
6927
|
+
const bootRouteSweep = (attempt) => {
|
|
6928
|
+
void Promise.resolve().then(() => sweepVanishedRoutes()).then((ready) => {
|
|
6929
|
+
if (ready || attempt >= resolved.bootRetryDelaysMs.length) return;
|
|
6930
|
+
const timer = setTimeout(() => {
|
|
6931
|
+
sweepTimers.delete(timer);
|
|
6932
|
+
bootRouteSweep(attempt + 1);
|
|
6933
|
+
}, resolved.bootRetryDelaysMs[attempt]);
|
|
6934
|
+
sweepTimers.add(timer);
|
|
6935
|
+
}, (error) => {
|
|
6936
|
+
console.error(`[dsh-model-think-level] route sweep failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
6937
|
+
});
|
|
6938
|
+
};
|
|
6939
|
+
bootRouteSweep(0);
|
|
6940
|
+
}
|
|
6392
6941
|
overlaySource.keys = async ({ route, model }) => {
|
|
6393
6942
|
const scopes = keyScopes.current[route] ?? [];
|
|
6394
6943
|
if (scopes.length === 0) return [];
|
|
@@ -6514,6 +7063,7 @@ function apply(ctx, config = {}) {
|
|
|
6514
7063
|
try {
|
|
6515
7064
|
if (piSection() === void 0) return;
|
|
6516
7065
|
const providers = providersOf();
|
|
7066
|
+
if (Object.keys(providers).length === 0) return;
|
|
6517
7067
|
updateImageConfig((document) => syncImageConfig(document, providers));
|
|
6518
7068
|
} catch {
|
|
6519
7069
|
}
|
|
@@ -6561,16 +7111,26 @@ function apply(ctx, config = {}) {
|
|
|
6561
7111
|
generateDeps: imageGenerateDeps
|
|
6562
7112
|
}
|
|
6563
7113
|
);
|
|
6564
|
-
const imageToolState = { name: void 0 };
|
|
7114
|
+
const imageToolState = { name: void 0, error: void 0 };
|
|
6565
7115
|
ctx.inject(["tools", "attachments"], (toolCtx) => {
|
|
6566
7116
|
toolCtx.effect(
|
|
6567
7117
|
() => {
|
|
6568
|
-
|
|
6569
|
-
|
|
6570
|
-
|
|
6571
|
-
|
|
6572
|
-
|
|
7118
|
+
let registered;
|
|
7119
|
+
try {
|
|
7120
|
+
registered = registerGenerateImageTool(toolCtx, {
|
|
7121
|
+
generateDeps: imageGenerateDeps,
|
|
7122
|
+
attachments: toolCtx.attachments,
|
|
7123
|
+
readConfig: () => readImageConfig()
|
|
7124
|
+
});
|
|
7125
|
+
} catch (error) {
|
|
7126
|
+
imageToolState.name = void 0;
|
|
7127
|
+
imageToolState.error = error instanceof Error ? error.message : String(error);
|
|
7128
|
+
console.warn(`[dsh-model-think-level] \u5185\u5EFA\u751F\u56FE\u5DE5\u5177\u6CE8\u518C\u5931\u8D25\uFF08\u8BCA\u65AD\u8DEF\u7531 ${IMAGE_CONFIG_PATH} \u7684 tool.error \u4F1A\u5E26\u56DE\u8FD9\u6761\u539F\u56E0\uFF09\uFF1A${imageToolState.error}`);
|
|
7129
|
+
throw error;
|
|
7130
|
+
}
|
|
7131
|
+
const { name: name2, dispose } = registered;
|
|
6573
7132
|
imageToolState.name = name2;
|
|
7133
|
+
imageToolState.error = void 0;
|
|
6574
7134
|
return () => {
|
|
6575
7135
|
imageToolState.name = void 0;
|
|
6576
7136
|
dispose();
|
|
@@ -6933,7 +7493,7 @@ function apply(ctx, config = {}) {
|
|
|
6933
7493
|
const listed = keyEntriesOf(document, route);
|
|
6934
7494
|
const refs = listed.map((entry) => entry.ref);
|
|
6935
7495
|
const probed = seat !== void 0 && !refs.includes(seat) ? [...refs, seat] : refs;
|
|
6936
|
-
const facts = await
|
|
7496
|
+
const facts = await displayCredentialFacts(credentials, probed, 250);
|
|
6937
7497
|
if (seat !== void 0 && !refs.includes(seat) && !holdsNothing(facts[seat])) refs.push(seat);
|
|
6938
7498
|
const now = Date.now();
|
|
6939
7499
|
const entries = refs.map((ref2) => {
|
|
@@ -6967,7 +7527,7 @@ function apply(ctx, config = {}) {
|
|
|
6967
7527
|
return view;
|
|
6968
7528
|
});
|
|
6969
7529
|
const endpoints = document.endpoints?.[route];
|
|
6970
|
-
const probing =
|
|
7530
|
+
const probing = keyProbeRuns.has(route);
|
|
6971
7531
|
return {
|
|
6972
7532
|
ok: true,
|
|
6973
7533
|
route,
|
|
@@ -7021,7 +7581,7 @@ function apply(ctx, config = {}) {
|
|
|
7021
7581
|
let seatEmpty = false;
|
|
7022
7582
|
if (active !== void 0) {
|
|
7023
7583
|
try {
|
|
7024
|
-
seatEmpty = holdsNothing((await credentialFacts(credentials, [active]))[active]);
|
|
7584
|
+
seatEmpty = holdsNothing((await credentialFacts(credentials, [active], CREDENTIAL_IPC_BUDGET_MS))[active]);
|
|
7025
7585
|
} catch {
|
|
7026
7586
|
seatEmpty = false;
|
|
7027
7587
|
}
|
|
@@ -7039,13 +7599,13 @@ function apply(ctx, config = {}) {
|
|
|
7039
7599
|
}
|
|
7040
7600
|
const listedRefs = keyEntriesOf(readKeyIndex(indexFile), route).map((entry) => entry.ref);
|
|
7041
7601
|
const slotCandidates = active !== void 0 && listedRefs.includes(active) ? [active, ...listedRefs.filter((candidate) => candidate !== active)] : listedRefs;
|
|
7042
|
-
const slotFacts = slotCandidates.length > 0 ? await credentialFacts(credentials, slotCandidates) : {};
|
|
7602
|
+
const slotFacts = slotCandidates.length > 0 ? await credentialFacts(credentials, slotCandidates, CREDENTIAL_IPC_BUDGET_MS) : {};
|
|
7043
7603
|
const emptySlot = slotCandidates.find((candidate) => holdsNothing(slotFacts[candidate]));
|
|
7044
7604
|
let created = emptySlot !== void 0 && await resolveCredential(credentials, emptySlot) === void 0 ? emptySlot : void 0;
|
|
7045
7605
|
if (created === void 0) {
|
|
7046
7606
|
created = nextKeyRef(route, taken);
|
|
7047
7607
|
for (; ; ) {
|
|
7048
|
-
const facts = await credentialFacts(credentials, [created]);
|
|
7608
|
+
const facts = await credentialFacts(credentials, [created], CREDENTIAL_IPC_BUDGET_MS);
|
|
7049
7609
|
const configured = facts[created]?.configured;
|
|
7050
7610
|
if (configured === void 0) throw new HostReadError("the credential store could not confirm a free reference");
|
|
7051
7611
|
if (!configured && await resolveCredential(credentials, created) === void 0) break;
|
|
@@ -7054,7 +7614,7 @@ function apply(ctx, config = {}) {
|
|
|
7054
7614
|
}
|
|
7055
7615
|
}
|
|
7056
7616
|
const seatBefore = active;
|
|
7057
|
-
const seatIsEmpty = seatBefore !== void 0 && seatBefore !== created && holdsNothing((await credentialFacts(credentials, [seatBefore]))[seatBefore]);
|
|
7617
|
+
const seatIsEmpty = seatBefore !== void 0 && seatBefore !== created && holdsNothing((await credentialFacts(credentials, [seatBefore], CREDENTIAL_IPC_BUDGET_MS))[seatBefore]);
|
|
7058
7618
|
const refused = await storeCredential(credentials, created, value);
|
|
7059
7619
|
if (refused !== void 0) {
|
|
7060
7620
|
refuse(refused);
|
|
@@ -7069,7 +7629,7 @@ function apply(ctx, config = {}) {
|
|
|
7069
7629
|
if (failed !== void 0) throw new Error(failed);
|
|
7070
7630
|
}
|
|
7071
7631
|
} catch (error) {
|
|
7072
|
-
const rollback = await forgetCredential(credentials, created);
|
|
7632
|
+
const rollback = await forgetCredential(credentials, created, CREDENTIAL_IPC_BUDGET_MS);
|
|
7073
7633
|
if (rollback === void 0 && indexed) {
|
|
7074
7634
|
updateKeyIndex((document) => withoutKeyEntry(document, route, created), indexFile);
|
|
7075
7635
|
}
|
|
@@ -7204,7 +7764,7 @@ function apply(ctx, config = {}) {
|
|
|
7204
7764
|
refuse("that key is not listed for this provider");
|
|
7205
7765
|
return;
|
|
7206
7766
|
}
|
|
7207
|
-
const configured = (await credentialConfigured(credentials, [ref]))[ref];
|
|
7767
|
+
const configured = (await credentialConfigured(credentials, [ref], CREDENTIAL_IPC_BUDGET_MS))[ref];
|
|
7208
7768
|
if (configured === void 0) throw new HostReadError("the credential store could not read the reference");
|
|
7209
7769
|
const wasEnabled = ref === enabledNow();
|
|
7210
7770
|
const remaining = keyEntriesOf(document, route).map((candidate) => candidate.ref).filter((candidate) => candidate !== ref);
|
|
@@ -7219,8 +7779,9 @@ function apply(ctx, config = {}) {
|
|
|
7219
7779
|
try {
|
|
7220
7780
|
updateKeyIndex((document2) => withoutKeyEntry(document2, route, ref), indexFile);
|
|
7221
7781
|
forgetServes(route, ref);
|
|
7782
|
+
invalidateCredentialDisplay(credentials, ref);
|
|
7222
7783
|
if (configured) {
|
|
7223
|
-
const refused = await forgetCredential(credentials, ref);
|
|
7784
|
+
const refused = await forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS);
|
|
7224
7785
|
if (refused !== void 0) throw new Error(refused);
|
|
7225
7786
|
}
|
|
7226
7787
|
} catch (error) {
|
|
@@ -7242,16 +7803,23 @@ function apply(ctx, config = {}) {
|
|
|
7242
7803
|
}
|
|
7243
7804
|
throw new Error([error instanceof Error ? error.message : String(error), ...failures].join("; "));
|
|
7244
7805
|
}
|
|
7806
|
+
} else if (op === "probe") {
|
|
7807
|
+
const listed = keyEntriesOf(readKeyIndex(indexFile), route);
|
|
7808
|
+
const seat = enabledNow();
|
|
7809
|
+
const distinct = new Set(listed.map((entry) => entry.ref));
|
|
7810
|
+
if (seat !== void 0) distinct.add(seat);
|
|
7811
|
+
if (distinct.size < 2) {
|
|
7812
|
+
refuse("a scope probe needs a second key; a single key serves whatever it serves");
|
|
7813
|
+
return;
|
|
7814
|
+
}
|
|
7815
|
+
void runKeyProbe(route);
|
|
7245
7816
|
} else {
|
|
7246
7817
|
refuse(`unknown key operation "${op}"`);
|
|
7247
7818
|
return;
|
|
7248
7819
|
}
|
|
7249
7820
|
refreshKeyScopes();
|
|
7250
7821
|
if (["add", "remove", "value", "protocol", "endpoints", "enable"].includes(op)) {
|
|
7251
|
-
invalidateListings();
|
|
7252
|
-
}
|
|
7253
|
-
if (["add", "value", "protocol", "endpoints"].includes(op)) {
|
|
7254
|
-
scheduleKeyProbe(route);
|
|
7822
|
+
invalidateListings(route);
|
|
7255
7823
|
}
|
|
7256
7824
|
releaseMutation?.();
|
|
7257
7825
|
releaseMutation = void 0;
|
|
@@ -7402,6 +7970,43 @@ function apply(ctx, config = {}) {
|
|
|
7402
7970
|
}),
|
|
7403
7971
|
"dsh-model-think-level: autofill config route"
|
|
7404
7972
|
);
|
|
7973
|
+
ctx.effect(
|
|
7974
|
+
() => webServerCtx.webServer.register({
|
|
7975
|
+
kind: "exact",
|
|
7976
|
+
path: ORDER_PATH,
|
|
7977
|
+
handler: async (req, res) => {
|
|
7978
|
+
res.setHeader("cache-control", "no-store");
|
|
7979
|
+
if (!isTrustedRequest(req)) {
|
|
7980
|
+
sendJson(res, 403, { ok: false, error: "forbidden" });
|
|
7981
|
+
return;
|
|
7982
|
+
}
|
|
7983
|
+
if (req.method === "GET") {
|
|
7984
|
+
sendJson(res, 200, { ok: true, data: readUiOrder(uiOrderFilePath()) });
|
|
7985
|
+
return;
|
|
7986
|
+
}
|
|
7987
|
+
if (req.method !== "POST") {
|
|
7988
|
+
sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
7989
|
+
return;
|
|
7990
|
+
}
|
|
7991
|
+
const body = await readJsonBody(req, 65536);
|
|
7992
|
+
if (body === void 0) {
|
|
7993
|
+
sendJson(res, 400, { ok: false, error: "the body is not a JSON document" });
|
|
7994
|
+
return;
|
|
7995
|
+
}
|
|
7996
|
+
try {
|
|
7997
|
+
const { document, stale } = commitUiOrderGuarded(body, Date.now());
|
|
7998
|
+
if (stale) {
|
|
7999
|
+
sendJson(res, 409, { ok: false, error: "stale", data: document });
|
|
8000
|
+
return;
|
|
8001
|
+
}
|
|
8002
|
+
sendJson(res, 200, { ok: true, data: document });
|
|
8003
|
+
} catch (error) {
|
|
8004
|
+
sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
8005
|
+
}
|
|
8006
|
+
}
|
|
8007
|
+
}),
|
|
8008
|
+
"dsh-model-think-level: ui-order route"
|
|
8009
|
+
);
|
|
7405
8010
|
ctx.effect(
|
|
7406
8011
|
() => webServerCtx.webServer.register({
|
|
7407
8012
|
kind: "exact",
|
|
@@ -7688,7 +8293,8 @@ function apply(ctx, config = {}) {
|
|
|
7688
8293
|
// and the client's keyed image card both read this name back.
|
|
7689
8294
|
tool: {
|
|
7690
8295
|
registered: imageToolState.name !== void 0,
|
|
7691
|
-
name: imageToolState.name ?? null
|
|
8296
|
+
name: imageToolState.name ?? null,
|
|
8297
|
+
...imageToolState.error === void 0 ? {} : { error: imageToolState.error }
|
|
7692
8298
|
}
|
|
7693
8299
|
});
|
|
7694
8300
|
return;
|
|
@@ -7698,53 +8304,6 @@ function apply(ctx, config = {}) {
|
|
|
7698
8304
|
sendJson(res, 400, { ok: false, error: "a JSON body is required" });
|
|
7699
8305
|
return;
|
|
7700
8306
|
}
|
|
7701
|
-
const op = typeof body["op"] === "string" ? body["op"] : "save";
|
|
7702
|
-
if (op === "test") {
|
|
7703
|
-
const id = typeof body["id"] === "string" ? body["id"] : "";
|
|
7704
|
-
const config2 = readImageConfig();
|
|
7705
|
-
const model = resolveImageModel(config2, id);
|
|
7706
|
-
if (model === void 0) {
|
|
7707
|
-
sendJson(res, 400, { ok: false, error: `no image model "${id}"` });
|
|
7708
|
-
return;
|
|
7709
|
-
}
|
|
7710
|
-
if (model.api !== "images") {
|
|
7711
|
-
sendJson(res, 200, { ok: true, status: "unsupported", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
7712
|
-
return;
|
|
7713
|
-
}
|
|
7714
|
-
const smallest = [...model.params.sizes].sort((a, b) => {
|
|
7715
|
-
const area = (size) => size.split("x").reduce((sum, part) => sum * (Number(part) || 0), 1);
|
|
7716
|
-
return area(a) - area(b);
|
|
7717
|
-
})[0] ?? "1024x1024";
|
|
7718
|
-
try {
|
|
7719
|
-
await generateImage(imageGenerateDeps, {
|
|
7720
|
-
model: model.id,
|
|
7721
|
-
prompt: "endpoint test",
|
|
7722
|
-
size: smallest,
|
|
7723
|
-
n: 1
|
|
7724
|
-
});
|
|
7725
|
-
updateImageConfig((document) => ({
|
|
7726
|
-
...document,
|
|
7727
|
-
models: document.models.map((entry) => entry.id === model.id ? { ...entry, endpoint: { kind: "images", status: "ok", checkedAt: (/* @__PURE__ */ new Date()).toISOString() } } : entry)
|
|
7728
|
-
}));
|
|
7729
|
-
sendJson(res, 200, { ok: true, status: "ok", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
7730
|
-
} catch (error) {
|
|
7731
|
-
const kind = error instanceof Error && "kind" in error ? String(error.kind) : "upstream";
|
|
7732
|
-
if (kind === "endpoint") {
|
|
7733
|
-
updateImageConfig((document) => ({
|
|
7734
|
-
...document,
|
|
7735
|
-
models: document.models.map((entry) => entry.id === model.id ? { ...entry, endpoint: { kind: "images", status: "unsupported", checkedAt: (/* @__PURE__ */ new Date()).toISOString() } } : entry)
|
|
7736
|
-
}));
|
|
7737
|
-
sendJson(res, 200, { ok: true, status: "unsupported", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
7738
|
-
return;
|
|
7739
|
-
}
|
|
7740
|
-
sendJson(res, 200, {
|
|
7741
|
-
ok: false,
|
|
7742
|
-
error: error instanceof Error ? error.message : String(error),
|
|
7743
|
-
status: model.endpoint.status
|
|
7744
|
-
});
|
|
7745
|
-
}
|
|
7746
|
-
return;
|
|
7747
|
-
}
|
|
7748
8307
|
try {
|
|
7749
8308
|
updateImageConfig((document) => {
|
|
7750
8309
|
let next = document;
|
|
@@ -7778,51 +8337,6 @@ function apply(ctx, config = {}) {
|
|
|
7778
8337
|
}),
|
|
7779
8338
|
"dsh-model-think-level: image config route"
|
|
7780
8339
|
);
|
|
7781
|
-
ctx.effect(
|
|
7782
|
-
() => webServerCtx.webServer.register({
|
|
7783
|
-
kind: "exact",
|
|
7784
|
-
path: IMAGE_GENERATE_PATH,
|
|
7785
|
-
handler: async (req, res) => {
|
|
7786
|
-
res.setHeader("cache-control", "no-store");
|
|
7787
|
-
if (!isTrustedRequest(req)) {
|
|
7788
|
-
sendJson(res, 403, { ok: false, error: "forbidden" });
|
|
7789
|
-
return;
|
|
7790
|
-
}
|
|
7791
|
-
if (req.method !== "POST") {
|
|
7792
|
-
sendJson(res, 405, { ok: false, error: "method not allowed" });
|
|
7793
|
-
return;
|
|
7794
|
-
}
|
|
7795
|
-
const body = await readJsonBody(req, 65536);
|
|
7796
|
-
if (!isRecord(body) || typeof body["prompt"] !== "string" || body["prompt"].trim().length === 0) {
|
|
7797
|
-
sendJson(res, 400, { ok: false, error: 'a "prompt" string is required' });
|
|
7798
|
-
return;
|
|
7799
|
-
}
|
|
7800
|
-
const referenceImages = Array.isArray(body["referenceImages"]) ? body["referenceImages"].filter((entry) => typeof entry === "string") : void 0;
|
|
7801
|
-
try {
|
|
7802
|
-
const result = await generateImage(imageGenerateDeps, {
|
|
7803
|
-
...typeof body["model"] === "string" ? { model: body["model"] } : {},
|
|
7804
|
-
prompt: body["prompt"],
|
|
7805
|
-
...typeof body["size"] === "string" ? { size: body["size"] } : {},
|
|
7806
|
-
...typeof body["quality"] === "string" ? { quality: body["quality"] } : {},
|
|
7807
|
-
...typeof body["n"] === "number" ? { n: body["n"] } : {},
|
|
7808
|
-
...referenceImages !== void 0 && referenceImages.length > 0 ? { referenceImages } : {}
|
|
7809
|
-
});
|
|
7810
|
-
sendJson(res, 200, {
|
|
7811
|
-
ok: true,
|
|
7812
|
-
// Every image this run produced, in order — the pane's preview
|
|
7813
|
-
// and scripted callers read the paths from here.
|
|
7814
|
-
images: result.images.map((image) => image.filePath),
|
|
7815
|
-
model: result.model,
|
|
7816
|
-
paramsUsed: result.paramsUsed,
|
|
7817
|
-
...result.revisions.length > 0 ? { warning: `\u53C2\u6570\u56DE\u9000\uFF1A${result.revisions.join("\u3001")}` } : {}
|
|
7818
|
-
});
|
|
7819
|
-
} catch (error) {
|
|
7820
|
-
sendJson(res, 200, { ok: false, error: error instanceof Error ? error.message : String(error) });
|
|
7821
|
-
}
|
|
7822
|
-
}
|
|
7823
|
-
}),
|
|
7824
|
-
"dsh-model-think-level: image generate route"
|
|
7825
|
-
);
|
|
7826
8340
|
});
|
|
7827
8341
|
}
|
|
7828
8342
|
export {
|