dsh-model-think-level 2.4.0 → 2.5.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/lib/index.js CHANGED
@@ -20,6 +20,9 @@ var INPUT_IMAGE_GEN_MARKER = "inputImageGen";
20
20
  var AUTOFILL_MARKER = "reasoningEffortsAutofilled";
21
21
  var CAMOUFLAGE_PATH = "/dsh-model-think-level/camouflage";
22
22
  var CAMOUFLAGE_FILE = "camouflage.json";
23
+ var HISTORY_COMPAT_PATH = "/dsh-model-think-level/history-compat";
24
+ var HISTORY_COMPAT_FILE = "topic-recovery.json";
25
+ var HISTORY_COMPAT_LEGACY_FILE = "history-compat.json";
23
26
  var IMAGE_CONFIG_PATH = "/dsh-model-think-level/image-config";
24
27
  var IMAGE_CONFIG_FILE = "image.json";
25
28
  var IMAGE_MCP_PATCH_ID = "dsh-image-mcp";
@@ -1002,6 +1005,72 @@ function setRouteCamouflage(route, preset, file = camouflageFilePath()) {
1002
1005
  return next;
1003
1006
  }
1004
1007
 
1008
+ // src/history-compat-store.ts
1009
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync5, renameSync as renameSync5, unlinkSync as unlinkSync5, writeFileSync as writeFileSync5 } from "node:fs";
1010
+ import { dirname as dirname5, join as join5 } from "node:path";
1011
+ function emptyHistoryCompat() {
1012
+ return { version: 1, providers: {} };
1013
+ }
1014
+ function historyCompatFilePath(home = harnessHome()) {
1015
+ return join5(home, "dsh-model-think-level", HISTORY_COMPAT_FILE);
1016
+ }
1017
+ function parseHistoryCompat(raw) {
1018
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return emptyHistoryCompat();
1019
+ const providers = raw["providers"];
1020
+ if (typeof providers !== "object" || providers === null || Array.isArray(providers)) return emptyHistoryCompat();
1021
+ const out = {};
1022
+ for (const [route, value] of Object.entries(providers)) {
1023
+ if (route.length === 0) continue;
1024
+ if (value !== true) continue;
1025
+ Object.defineProperty(out, route, { value: true, enumerable: true, configurable: true, writable: true });
1026
+ }
1027
+ return { version: 1, providers: out };
1028
+ }
1029
+ function readHistoryCompat(file = historyCompatFilePath()) {
1030
+ const current = readDocument(file);
1031
+ if (current !== void 0) return current;
1032
+ const legacy = join5(dirname5(file), HISTORY_COMPAT_LEGACY_FILE);
1033
+ if (legacy === file) return emptyHistoryCompat();
1034
+ const previous = readDocument(legacy);
1035
+ if (previous === void 0) return emptyHistoryCompat();
1036
+ try {
1037
+ writeHistoryCompat(previous, file);
1038
+ } catch {
1039
+ }
1040
+ return previous;
1041
+ }
1042
+ function readDocument(file) {
1043
+ try {
1044
+ return parseHistoryCompat(JSON.parse(readFileSync5(file, "utf8")));
1045
+ } catch {
1046
+ return void 0;
1047
+ }
1048
+ }
1049
+ function writeHistoryCompat(document, file = historyCompatFilePath()) {
1050
+ mkdirSync5(dirname5(file), { recursive: true });
1051
+ const temporary = `${file}.${process.pid}.tmp`;
1052
+ writeFileSync5(temporary, `${JSON.stringify(document, null, 2)}
1053
+ `, "utf8");
1054
+ try {
1055
+ renameSync5(temporary, file);
1056
+ } catch (error) {
1057
+ try {
1058
+ unlinkSync5(temporary);
1059
+ } catch {
1060
+ }
1061
+ throw error;
1062
+ }
1063
+ }
1064
+ function setRouteHistoryCompat(route, enabled, file = historyCompatFilePath()) {
1065
+ const current = readHistoryCompat(file);
1066
+ const providers = { ...current.providers };
1067
+ if (enabled) Object.defineProperty(providers, route, { value: true, enumerable: true, configurable: true, writable: true });
1068
+ else delete providers[route];
1069
+ const next = { version: 1, providers };
1070
+ writeHistoryCompat(next, file);
1071
+ return next;
1072
+ }
1073
+
1005
1074
  // src/multi-key-listing.ts
1006
1075
  var DEFAULT_PROBE_CONCURRENCY = 4;
1007
1076
  var MODEL_ORDER = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
@@ -1215,7 +1284,7 @@ function recordHeaderConflicts(index, existing, route, headers) {
1215
1284
  }
1216
1285
  }
1217
1286
  }
1218
- function buildHeaderIndex(providers, camouflages) {
1287
+ function buildHeaderIndex(providers, camouflages, historyCompat) {
1219
1288
  const index = emptyIndex();
1220
1289
  const claimedUserAgents = /* @__PURE__ */ new Map();
1221
1290
  for (const [route, rawProfile] of Object.entries(providers)) {
@@ -1228,6 +1297,7 @@ function buildHeaderIndex(providers, camouflages) {
1228
1297
  const hasHeaders = Object.keys(sendable).length > 0;
1229
1298
  const userAgent = Object.entries(sendable).find(([name2]) => name2.toLowerCase() === "user-agent")?.[1];
1230
1299
  const camouflage = camouflages !== void 0 && Object.hasOwn(camouflages, route) ? camouflages[route] : void 0;
1300
+ const recoversHistory = historyCompat !== void 0 && Object.hasOwn(historyCompat, route) ? historyCompat[route] === true : false;
1231
1301
  const override = {
1232
1302
  origin,
1233
1303
  pathPrefix: pathPrefixOf(baseURL ?? origin),
@@ -1236,7 +1306,8 @@ function buildHeaderIndex(providers, camouflages) {
1236
1306
  modelIds: modelIdsOf(profile),
1237
1307
  hasHeaders,
1238
1308
  ...userAgent === void 0 ? {} : { userAgent },
1239
- ...camouflage === void 0 ? {} : { camouflage }
1309
+ ...camouflage === void 0 ? {} : { camouflage },
1310
+ ...recoversHistory ? { historyCompat: true } : {}
1240
1311
  };
1241
1312
  index.routes.push(override);
1242
1313
  if (!hasHeaders) continue;
@@ -3343,6 +3414,143 @@ function parseBalancePayload(text) {
3343
3414
  return readingOf(body);
3344
3415
  }
3345
3416
 
3417
+ // src/history-compat.ts
3418
+ var HISTORY_INSPECT_LIMIT = 65536;
3419
+ var HISTORY_INSPECT_TIMEOUT_MS = 2e3;
3420
+ var RESOURCE_MISMATCH = [
3421
+ /created under a different [a-z0-9 ._-]{0,48}?resource/i,
3422
+ /same resource that created the item/i
3423
+ ];
3424
+ function isHistoryStateMismatch(text) {
3425
+ return RESOURCE_MISMATCH.some((pattern) => pattern.test(text));
3426
+ }
3427
+ var HISTORY_STAGES = ["portable_ids", "drop_reasoning"];
3428
+ function degradeForHistory(context, stage) {
3429
+ if (!isRecord(context)) return void 0;
3430
+ const messages = context["messages"];
3431
+ if (!Array.isArray(messages)) return void 0;
3432
+ let changed = 0;
3433
+ const nextMessages = messages.map((message) => {
3434
+ if (!isRecord(message) || message["role"] !== "assistant") return message;
3435
+ const content = message["content"];
3436
+ if (!Array.isArray(content)) return message;
3437
+ let messageChanged = false;
3438
+ const nextContent = content.map((block) => {
3439
+ if (!isRecord(block)) return block;
3440
+ const degraded = degradeBlock(block, stage);
3441
+ if (degraded === void 0) return block;
3442
+ messageChanged = true;
3443
+ return degraded;
3444
+ });
3445
+ if (!messageChanged) return message;
3446
+ changed += 1;
3447
+ return { ...message, content: nextContent };
3448
+ });
3449
+ if (changed === 0) return void 0;
3450
+ return { ...context, messages: nextMessages };
3451
+ }
3452
+ function degradeBlock(block, stage) {
3453
+ const type = block["type"];
3454
+ if (type === "thinking") {
3455
+ const signature = block["thinkingSignature"];
3456
+ if (typeof signature !== "string") return void 0;
3457
+ if (stage === "drop_reasoning") {
3458
+ const copy = { ...block };
3459
+ delete copy["thinkingSignature"];
3460
+ return copy;
3461
+ }
3462
+ const stripped = stripSignatureId(signature);
3463
+ return stripped === void 0 ? void 0 : { ...block, thinkingSignature: stripped };
3464
+ }
3465
+ if (type === "text") {
3466
+ const signature = block["textSignature"];
3467
+ if (typeof signature !== "string") return void 0;
3468
+ const stripped = stripSignatureId(signature);
3469
+ return stripped === void 0 ? void 0 : { ...block, textSignature: stripped };
3470
+ }
3471
+ if (type === "toolCall") {
3472
+ const id = block["id"];
3473
+ if (typeof id !== "string" || !id.includes("|")) return void 0;
3474
+ return { ...block, id: id.slice(0, id.indexOf("|")) };
3475
+ }
3476
+ return void 0;
3477
+ }
3478
+ function stripSignatureId(signature) {
3479
+ let parsed;
3480
+ try {
3481
+ parsed = JSON.parse(signature);
3482
+ } catch {
3483
+ return void 0;
3484
+ }
3485
+ if (!isRecord(parsed) || !Object.hasOwn(parsed, "id")) return void 0;
3486
+ const copy = { ...parsed };
3487
+ delete copy["id"];
3488
+ return JSON.stringify(copy);
3489
+ }
3490
+ function isHistoryRefusalCandidate(response) {
3491
+ return response.status === 400 || response.status >= 500;
3492
+ }
3493
+ async function reencodeHistoryRefusal(response) {
3494
+ if (!isHistoryRefusalCandidate(response)) return void 0;
3495
+ const text = await readErrorBody(response);
3496
+ if (text === void 0 || !isHistoryStateMismatch(text)) return void 0;
3497
+ return new Response(
3498
+ JSON.stringify({
3499
+ error: {
3500
+ type: response.status === 400 ? "invalid_request_error" : "server_error",
3501
+ message: text
3502
+ }
3503
+ }),
3504
+ {
3505
+ status: response.status,
3506
+ statusText: response.statusText,
3507
+ headers: { "content-type": "application/json" }
3508
+ }
3509
+ );
3510
+ }
3511
+ async function readErrorBody(response) {
3512
+ let clone;
3513
+ try {
3514
+ clone = response.clone();
3515
+ } catch {
3516
+ return void 0;
3517
+ }
3518
+ const reader = clone.body?.getReader();
3519
+ if (reader === void 0) return void 0;
3520
+ let expired = false;
3521
+ const timer = setTimeout(() => {
3522
+ expired = true;
3523
+ void reader.cancel().catch(() => {
3524
+ });
3525
+ }, HISTORY_INSPECT_TIMEOUT_MS);
3526
+ const chunks = [];
3527
+ let total = 0;
3528
+ try {
3529
+ for (; ; ) {
3530
+ const { done, value } = await reader.read();
3531
+ if (expired) return void 0;
3532
+ if (done) break;
3533
+ if (value === void 0) continue;
3534
+ total += value.byteLength;
3535
+ if (total > HISTORY_INSPECT_LIMIT) {
3536
+ return void 0;
3537
+ }
3538
+ chunks.push(value);
3539
+ }
3540
+ } catch {
3541
+ return void 0;
3542
+ } finally {
3543
+ clearTimeout(timer);
3544
+ }
3545
+ const merged = new Uint8Array(total);
3546
+ let offset = 0;
3547
+ for (const chunk of chunks) {
3548
+ merged.set(chunk, offset);
3549
+ offset += chunk.byteLength;
3550
+ }
3551
+ return new TextDecoder().decode(merged);
3552
+ }
3553
+
3346
3554
  // src/headers-fetch.ts
3347
3555
  var REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.fetch-overrides");
3348
3556
  var DISPATCH_REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.dispatch-overrides");
@@ -3503,9 +3711,15 @@ function makeWrapper(base, entries) {
3503
3711
  }
3504
3712
  return base(input, { ...init, headers });
3505
3713
  };
3714
+ const callerAborted = () => init?.signal?.aborted === true || typeof Request !== "undefined" && input instanceof Request && input.signal.aborted;
3715
+ const sendAttempt = async (keyValue) => {
3716
+ const response = await attempt(keyValue);
3717
+ if (override.historyCompat !== true) return response;
3718
+ return await reencodeHistoryRefusal(response) ?? response;
3719
+ };
3506
3720
  if (patched.get(WIRE_DISPATCH_HEADER) === "1") {
3507
3721
  patched.delete(WIRE_DISPATCH_HEADER);
3508
- return attempt(void 0);
3722
+ return sendAttempt(void 0);
3509
3723
  }
3510
3724
  const resolved = keyed ? await entry.keys({ route: override.route, model }) : [];
3511
3725
  const keyCandidates = restLast(
@@ -3547,7 +3761,9 @@ function makeWrapper(base, entries) {
3547
3761
  } catch {
3548
3762
  }
3549
3763
  }
3550
- if (!hasPatch && keyCandidates.length === 0) return base(input, passthroughInit(input, init));
3764
+ if (!hasPatch && keyCandidates.length === 0 && override.historyCompat !== true) {
3765
+ return base(input, passthroughInit(input, init));
3766
+ }
3551
3767
  const failureBody = async (response) => {
3552
3768
  try {
3553
3769
  return await readBoundedText(response, 4096);
@@ -3562,10 +3778,9 @@ function makeWrapper(base, entries) {
3562
3778
  const restKey = kind === "unserved" ? restKeyOf(override.route, candidate.ref, model) : restKeyOf(override.route, candidate.ref);
3563
3779
  keyRest.note(restKey, kind, retryAfterMs === void 0 ? void 0 : { retryAfterMs });
3564
3780
  };
3565
- const callerAborted = () => init?.signal?.aborted === true || typeof Request !== "undefined" && input instanceof Request && input.signal.aborted;
3566
3781
  if (keyCandidates.length <= 1) {
3567
3782
  const solo = keyCandidates[0];
3568
- const response = await attempt(solo?.value);
3783
+ const response = await sendAttempt(solo?.value);
3569
3784
  if (solo !== void 0) {
3570
3785
  if (response.status < 400) {
3571
3786
  clearRest(keyRest, override.route, solo.ref, model);
@@ -3586,7 +3801,7 @@ function makeWrapper(base, entries) {
3586
3801
  const candidate = keyCandidates[index];
3587
3802
  let response;
3588
3803
  try {
3589
- response = await attempt(candidate.value);
3804
+ response = await sendAttempt(candidate.value);
3590
3805
  } catch (error) {
3591
3806
  if (callerAborted()) throw error;
3592
3807
  lastFailure = error;
@@ -3602,6 +3817,7 @@ function makeWrapper(base, entries) {
3602
3817
  clearRest(keyRest, override.route, candidate.ref, model);
3603
3818
  return response;
3604
3819
  }
3820
+ if (response.status >= 500 && isHistoryStateMismatch(bodyText)) return response;
3605
3821
  const kind = classifyFailure(response.status, bodyText);
3606
3822
  if (kind === "unserved") unserved += 1;
3607
3823
  chargeFailure(candidate, response, kind);
@@ -3808,6 +4024,20 @@ function errorTextOf(event) {
3808
4024
  const parts = [error?.["message"], error?.["errorMessage"], event["reason"]];
3809
4025
  return parts.filter((part) => typeof part === "string").join(" ");
3810
4026
  }
4027
+ var CONTENT_EVENTS = /* @__PURE__ */ new Set([
4028
+ "thinking_start",
4029
+ "thinking_delta",
4030
+ "thinking_end",
4031
+ "text_start",
4032
+ "text_delta",
4033
+ "text_end",
4034
+ "toolcall_start",
4035
+ "toolcall_delta",
4036
+ "toolcall_end"
4037
+ ]);
4038
+ function isContentEvent(type) {
4039
+ return typeof type === "string" && CONTENT_EVENTS.has(type);
4040
+ }
3811
4041
  function modelsProxyOf(models, source) {
3812
4042
  return new Proxy(models, {
3813
4043
  get(target, property, receiver) {
@@ -3846,7 +4076,7 @@ function modelsProxyOf(models, source) {
3846
4076
  if (route === void 0) return Promise.resolve([]);
3847
4077
  return Promise.resolve(keyResolver({ route, model: modelId })).catch(() => []);
3848
4078
  };
3849
- const startAttempt = async (candidate, avoid) => {
4079
+ const startAttempt = async (candidate, avoid, requestContext = context) => {
3850
4080
  const api = typeof modelObject["api"] === "string" ? modelObject["api"] : "openai-completions";
3851
4081
  const protocol = wireOf(candidate, api, modelId, avoid);
3852
4082
  const honoured = isHonoured(candidate, api);
@@ -3855,7 +4085,7 @@ function modelsProxyOf(models, source) {
3855
4085
  const baseUrl = protocol === "anthropic-messages" ? anthropicRequestBaseUrl(selectedBaseUrl) : selectedBaseUrl;
3856
4086
  const switched = protocol !== api || baseUrl !== modelObject["baseUrl"];
3857
4087
  if (!switched) {
3858
- return streamSimple.call(target, model, context, {
4088
+ return streamSimple.call(target, model, requestContext, {
3859
4089
  ...options,
3860
4090
  apiKey: candidate.value,
3861
4091
  transformHeaders: markedTransformHeaders
@@ -3864,7 +4094,7 @@ function modelsProxyOf(models, source) {
3864
4094
  const mergedHeaders = await transformHeaders(isRecord(options["headers"]) ? options["headers"] : {});
3865
4095
  const implementation = await loadProtocol(protocol);
3866
4096
  const switchedToClaude = protocol === "anthropic-messages" && routeOverrideOf(source, model)?.camouflage === "claude";
3867
- const normalized2 = await normalizeDispatchedContext(context);
4097
+ const normalized2 = await normalizeDispatchedContext(requestContext);
3868
4098
  const dispatchedContext = switchedToClaude ? withClaudeIdentityContext(normalized2) : normalized2;
3869
4099
  const existingMetadata = isRecord(options["metadata"]) ? options["metadata"] : void 0;
3870
4100
  const suppliedUserId = existingMetadata?.["user_id"];
@@ -3905,42 +4135,76 @@ function modelsProxyOf(models, source) {
3905
4135
  isResting: (candidate) => isRestingFor(keyRest, route ?? "", candidate.ref, modelId, Date.now())
3906
4136
  });
3907
4137
  recordRoutePlan(route ?? "", plan, { model: modelId });
4138
+ const recoversHistory = routeOverrideOf(source, model)?.historyCompat === true;
3908
4139
  const wireOfAttempt = (candidate) => plan.entries.find((entry) => entry.candidate === candidate)?.wire ?? wireOf(candidate, api, modelId, avoidWire);
3909
4140
  const restKeyFor = (candidate, kind) => kind === "unserved" && modelId !== void 0 ? restKeyOf(route ?? "", candidate.ref, modelId) : restKeyOf(route ?? "", candidate.ref);
3910
4141
  let lastErrorEvent;
3911
4142
  let lastError;
3912
4143
  for (const candidate of plan.ordered) {
3913
- let stream;
3914
- try {
3915
- stream = await startAttempt(candidate, avoidWire);
3916
- } catch (error) {
3917
- lastError = error;
3918
- if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
3919
- const kind = classifyFailure(void 0, error instanceof Error ? error.message : "") ?? "refused";
3920
- keyRest.note(restKeyFor(candidate, kind), kind);
3921
- continue;
3922
- }
3923
- let committed = false;
3924
- let failed = false;
3925
- for await (const event of stream) {
3926
- const type = isRecord(event) ? event["type"] : void 0;
3927
- if (!committed) {
3928
- if (type === "error") {
3929
- lastErrorEvent = event;
3930
- failed = true;
3931
- if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
3932
- const kind = classifyFailure(void 0, errorTextOf(event)) ?? "refused";
3933
- keyRest.note(restKeyFor(candidate, kind), kind);
3934
- break;
4144
+ let attemptContext = context;
4145
+ let historyStage = -1;
4146
+ let historyExhausted = false;
4147
+ let setupFailed = false;
4148
+ while (true) {
4149
+ let stream;
4150
+ try {
4151
+ stream = await startAttempt(candidate, avoidWire, attemptContext);
4152
+ } catch (error) {
4153
+ lastError = error;
4154
+ if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
4155
+ const kind = classifyFailure(void 0, error instanceof Error ? error.message : "") ?? "refused";
4156
+ keyRest.note(restKeyFor(candidate, kind), kind);
4157
+ setupFailed = true;
4158
+ break;
4159
+ }
4160
+ let committed = false;
4161
+ let contentStarted = false;
4162
+ let failed = false;
4163
+ let retried = false;
4164
+ for await (const event of stream) {
4165
+ const type = isRecord(event) ? event["type"] : void 0;
4166
+ if (recoversHistory && type === "error" && !contentStarted) {
4167
+ const text = errorTextOf(event);
4168
+ if (isHistoryStateMismatch(text)) {
4169
+ for (let next = historyStage + 1; next < HISTORY_STAGES.length; next += 1) {
4170
+ const degraded = degradeForHistory(context, HISTORY_STAGES[next]);
4171
+ if (degraded === void 0) continue;
4172
+ attemptContext = degraded;
4173
+ historyStage = next;
4174
+ retried = true;
4175
+ break;
4176
+ }
4177
+ if (retried) break;
4178
+ lastErrorEvent = event;
4179
+ historyExhausted = true;
4180
+ break;
4181
+ }
4182
+ }
4183
+ if (!committed) {
4184
+ if (type === "error") {
4185
+ lastErrorEvent = event;
4186
+ failed = true;
4187
+ if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
4188
+ const kind = classifyFailure(void 0, errorTextOf(event)) ?? "refused";
4189
+ keyRest.note(restKeyFor(candidate, kind), kind);
4190
+ break;
4191
+ }
4192
+ committed = true;
4193
+ clearRest(keyRest, route ?? "", candidate.ref, modelId);
4194
+ rememberWireFact(servedWire, servedKey, wireOfAttempt(candidate));
3935
4195
  }
3936
- committed = true;
3937
- clearRest(keyRest, route ?? "", candidate.ref, modelId);
3938
- rememberWireFact(servedWire, servedKey, wireOfAttempt(candidate));
4196
+ yield event;
4197
+ if (isContentEvent(type)) contentStarted = true;
4198
+ }
4199
+ if (retried) continue;
4200
+ if (historyExhausted) {
4201
+ if (lastErrorEvent !== void 0) yield lastErrorEvent;
4202
+ return;
3939
4203
  }
3940
- yield event;
4204
+ if (failed) break;
4205
+ return;
3941
4206
  }
3942
- if (failed) continue;
3943
- return;
4207
+ if (setupFailed) continue;
3944
4208
  }
3945
4209
  if (lastErrorEvent !== void 0) {
3946
4210
  yield lastErrorEvent;
@@ -4143,9 +4407,9 @@ function installPiAiHeaderTransforms(llm, source) {
4143
4407
  }
4144
4408
 
4145
4409
  // src/headers-conflict.ts
4146
- import { existsSync, readFileSync as readFileSync5 } from "node:fs";
4410
+ import { existsSync, readFileSync as readFileSync6 } from "node:fs";
4147
4411
  import { createRequire } from "node:module";
4148
- import { dirname as dirname5, join as join5, resolve as resolve2 } from "node:path";
4412
+ import { dirname as dirname6, join as join6, resolve as resolve2 } from "node:path";
4149
4413
  var SIBLING_PACKAGES = [
4150
4414
  "dsh-client-masquerade",
4151
4415
  "dsh-llm-headers",
@@ -4157,20 +4421,20 @@ function searchRoots() {
4157
4421
  const roots = /* @__PURE__ */ new Set();
4158
4422
  const entry = process.argv[1];
4159
4423
  if (typeof entry === "string" && entry.length > 0) {
4160
- let dir = dirname5(resolve2(entry));
4424
+ let dir = dirname6(resolve2(entry));
4161
4425
  for (let depth = 0; depth < 8; depth += 1) {
4162
- roots.add(join5(dir, "node_modules"));
4163
- const parent = dirname5(dir);
4426
+ roots.add(join6(dir, "node_modules"));
4427
+ const parent = dirname6(dir);
4164
4428
  if (parent === dir) break;
4165
4429
  dir = parent;
4166
4430
  }
4167
4431
  }
4168
- roots.add(join5(process.cwd(), "node_modules"));
4432
+ roots.add(join6(process.cwd(), "node_modules"));
4169
4433
  try {
4170
4434
  const require2 = createRequire(import.meta.url);
4171
4435
  for (const name2 of SIBLING_PACKAGES) {
4172
4436
  try {
4173
- roots.add(join5(dirname5(dirname5(dirname5(require2.resolve(`${name2}/package.json`)))), "node_modules"));
4437
+ roots.add(join6(dirname6(dirname6(dirname6(require2.resolve(`${name2}/package.json`)))), "node_modules"));
4174
4438
  } catch {
4175
4439
  }
4176
4440
  }
@@ -4179,14 +4443,14 @@ function searchRoots() {
4179
4443
  return [...roots];
4180
4444
  }
4181
4445
  function findAdapterFile() {
4182
- const relative = join5("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
4446
+ const relative = join6("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
4183
4447
  const candidates = [];
4184
4448
  try {
4185
4449
  const require2 = createRequire(import.meta.url);
4186
4450
  candidates.push(require2.resolve("@deepseek-ai/dsh-llm-pi-ai"));
4187
4451
  } catch {
4188
4452
  }
4189
- for (const root of searchRoots()) candidates.push(join5(root, relative));
4453
+ for (const root of searchRoots()) candidates.push(join6(root, relative));
4190
4454
  for (const candidate of candidates) {
4191
4455
  if (existsSync(candidate)) return candidate;
4192
4456
  }
@@ -4197,7 +4461,7 @@ function adapterSourcePatched(source) {
4197
4461
  }
4198
4462
  function adapterPatchState(path) {
4199
4463
  try {
4200
- return adapterSourcePatched(readFileSync5(path, "utf8")) ? "patched" : "stock";
4464
+ return adapterSourcePatched(readFileSync6(path, "utf8")) ? "patched" : "stock";
4201
4465
  } catch {
4202
4466
  return "unknown";
4203
4467
  }
@@ -4208,8 +4472,8 @@ function findSiblings() {
4208
4472
  for (const root of searchRoots()) {
4209
4473
  for (const name2 of SIBLING_PACKAGES) {
4210
4474
  if (seen.has(name2)) continue;
4211
- const dir = join5(root, name2);
4212
- const manifest = join5(dir, "package.json");
4475
+ const dir = join6(root, name2);
4476
+ const manifest = join6(dir, "package.json");
4213
4477
  if (!existsSync(manifest)) continue;
4214
4478
  seen.add(name2);
4215
4479
  found.push({ name: name2, path: dir });
@@ -4241,8 +4505,8 @@ function detectHeaderConflicts() {
4241
4505
  }
4242
4506
 
4243
4507
  // src/image/config.ts
4244
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync6, renameSync as renameSync5, unlinkSync as unlinkSync5, writeFileSync as writeFileSync5 } from "node:fs";
4245
- import { dirname as dirname6, join as join6 } from "node:path";
4508
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync as renameSync6, unlinkSync as unlinkSync6, writeFileSync as writeFileSync6 } from "node:fs";
4509
+ import { dirname as dirname7, join as join7 } from "node:path";
4246
4510
 
4247
4511
  // src/image/sizes.ts
4248
4512
  var IMAGE_SIZE_TIERS = [
@@ -4259,7 +4523,7 @@ var IMAGE_FALLBACK_PARAMS = {
4259
4523
  responseFormat: "b64_json"
4260
4524
  };
4261
4525
  function imageConfigFilePath(home = harnessHome()) {
4262
- return join6(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
4526
+ return join7(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
4263
4527
  }
4264
4528
  function emptyImageConfig(now = () => /* @__PURE__ */ new Date()) {
4265
4529
  return {
@@ -4360,7 +4624,7 @@ function parseImageModel(raw) {
4360
4624
  function readImageConfig(file = imageConfigFilePath()) {
4361
4625
  let text;
4362
4626
  try {
4363
- text = readFileSync6(file, "utf8");
4627
+ text = readFileSync7(file, "utf8");
4364
4628
  } catch {
4365
4629
  return emptyImageConfig();
4366
4630
  }
@@ -4371,15 +4635,15 @@ function readImageConfig(file = imageConfigFilePath()) {
4371
4635
  }
4372
4636
  }
4373
4637
  function writeImageConfig(document, file = imageConfigFilePath()) {
4374
- mkdirSync5(dirname6(file), { recursive: true });
4638
+ mkdirSync6(dirname7(file), { recursive: true });
4375
4639
  const temporary = `${file}.${process.pid}.tmp`;
4376
- writeFileSync5(temporary, `${JSON.stringify(document, null, 2)}
4640
+ writeFileSync6(temporary, `${JSON.stringify(document, null, 2)}
4377
4641
  `, "utf8");
4378
4642
  try {
4379
- renameSync5(temporary, file);
4643
+ renameSync6(temporary, file);
4380
4644
  } catch (error) {
4381
4645
  try {
4382
- unlinkSync5(temporary);
4646
+ unlinkSync6(temporary);
4383
4647
  } catch {
4384
4648
  }
4385
4649
  throw error;
@@ -4467,8 +4731,8 @@ function updateImageConfig(mutate, file = imageConfigFilePath()) {
4467
4731
  }
4468
4732
 
4469
4733
  // src/image/generate.ts
4470
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync6, existsSync as existsSync2, statSync } from "node:fs";
4471
- import { dirname as dirname7, join as join7, resolve as resolve3 } from "node:path";
4734
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync7, existsSync as existsSync2, statSync } from "node:fs";
4735
+ import { dirname as dirname8, join as join8, resolve as resolve3 } from "node:path";
4472
4736
 
4473
4737
  // src/image/deadline.ts
4474
4738
  function createImageDeadline(timeoutMs, caller, errorFor) {
@@ -4708,19 +4972,19 @@ function outputDirOf(deps, config) {
4708
4972
  const home = deps.home?.() ?? harnessHome();
4709
4973
  const dir = config.outputDir;
4710
4974
  if (/^([A-Za-z]:[\\/]|\/)/.test(dir)) return dir;
4711
- return join7(home, "dsh-model-think-level", dir);
4975
+ return join8(home, "dsh-model-think-level", dir);
4712
4976
  }
4713
4977
  function destinationOf(dir, slug, now) {
4714
- const base = join7(dir, `${slug}-${now()}.png`);
4978
+ const base = join8(dir, `${slug}-${now()}.png`);
4715
4979
  if (!existsSync2(base)) return base;
4716
4980
  for (let index = 2; ; index += 1) {
4717
- const candidate = join7(dir, `${slug}-${now()}-${index}.png`);
4981
+ const candidate = join8(dir, `${slug}-${now()}-${index}.png`);
4718
4982
  if (!existsSync2(candidate)) return candidate;
4719
4983
  }
4720
4984
  }
4721
4985
  function resolveDestination(requested, fallbackDir, slug, now) {
4722
4986
  if (requested === void 0 || requested.trim().length === 0) {
4723
- mkdirSync6(fallbackDir, { recursive: true });
4987
+ mkdirSync7(fallbackDir, { recursive: true });
4724
4988
  return destinationOf(fallbackDir, slug, now);
4725
4989
  }
4726
4990
  const target = resolve3(requested.trim());
@@ -4730,10 +4994,10 @@ function resolveDestination(requested, fallbackDir, slug, now) {
4730
4994
  } catch {
4731
4995
  }
4732
4996
  if (isDir || /[\\/]$/.test(target) || !target.toLowerCase().endsWith(".png")) {
4733
- mkdirSync6(target, { recursive: true });
4997
+ mkdirSync7(target, { recursive: true });
4734
4998
  return destinationOf(target, slug, now);
4735
4999
  }
4736
- mkdirSync6(dirname7(target), { recursive: true });
5000
+ mkdirSync7(dirname8(target), { recursive: true });
4737
5001
  if (!existsSync2(target)) return target;
4738
5002
  for (let index = 2; ; index += 1) {
4739
5003
  const candidate = target.replace(/\.png$/i, `-${index}.png`);
@@ -4823,7 +5087,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4823
5087
  const absolute = resolve3(path);
4824
5088
  if (!existsSync2(absolute)) throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4825
5089
  try {
4826
- return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync7(absolute), mime: mimeOfPath(absolute) };
5090
+ return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync8(absolute), mime: mimeOfPath(absolute) };
4827
5091
  } catch {
4828
5092
  throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4829
5093
  }
@@ -4900,7 +5164,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4900
5164
  const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now);
4901
5165
  const bytes = Uint8Array.from(atob(data), (ch) => ch.charCodeAt(0));
4902
5166
  deadline.check();
4903
- writeFileSync6(filePath, bytes);
5167
+ writeFileSync7(filePath, bytes);
4904
5168
  images.push({ filePath, data });
4905
5169
  }
4906
5170
  deadline.check();
@@ -5330,19 +5594,19 @@ function imageToolHint(config) {
5330
5594
  }
5331
5595
 
5332
5596
  // src/image/legacy-cleanup.ts
5333
- import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync7, readFileSync as readFileSync8, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync7 } from "node:fs";
5334
- import { dirname as dirname8, join as join8 } from "node:path";
5597
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync8, readFileSync as readFileSync9, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync8 } from "node:fs";
5598
+ import { dirname as dirname9, join as join9 } from "node:path";
5335
5599
  var MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`;
5336
5600
  var MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`;
5337
5601
  function resolveLegacyPatchFile(home = harnessHome()) {
5338
5602
  const explicit = process.env["DSH_PROFILE"];
5339
- if (explicit !== void 0 && explicit.length > 0) return join8(home, "profiles", explicit, "cordis.patch.yml");
5340
- const profilesDir = join8(home, "profiles");
5603
+ if (explicit !== void 0 && explicit.length > 0) return join9(home, "profiles", explicit, "cordis.patch.yml");
5604
+ const profilesDir = join9(home, "profiles");
5341
5605
  try {
5342
5606
  if (existsSync3(profilesDir)) {
5343
5607
  const candidates = [];
5344
5608
  for (const name2 of readdirSync2(profilesDir)) {
5345
- const file = join8(profilesDir, name2, "cordis.patch.yml");
5609
+ const file = join9(profilesDir, name2, "cordis.patch.yml");
5346
5610
  if (!existsSync3(file)) continue;
5347
5611
  candidates.push({ file, mtime: statSync2(file).mtimeMs });
5348
5612
  }
@@ -5351,8 +5615,8 @@ function resolveLegacyPatchFile(home = harnessHome()) {
5351
5615
  }
5352
5616
  } catch {
5353
5617
  }
5354
- if (existsSync3(join8(home, "cordis.patch.yml"))) return join8(home, "cordis.patch.yml");
5355
- return join8(home, "profiles", "desktop", "cordis.patch.yml");
5618
+ if (existsSync3(join9(home, "cordis.patch.yml"))) return join9(home, "cordis.patch.yml");
5619
+ return join9(home, "profiles", "desktop", "cordis.patch.yml");
5356
5620
  }
5357
5621
  function markerRange(text) {
5358
5622
  const start = text.indexOf(MARK_BEGIN);
@@ -5413,7 +5677,7 @@ function mtimeOf(patchFile) {
5413
5677
  var ModifiedError = class extends Error {
5414
5678
  };
5415
5679
  function spliceOnce(patchFile, mtimeMs) {
5416
- const current = readFileSync8(patchFile, "utf8");
5680
+ const current = readFileSync9(patchFile, "utf8");
5417
5681
  const range = legacyRange(current);
5418
5682
  if (range === void 0) return;
5419
5683
  let next = current.slice(0, range.start) + current.slice(range.end);
@@ -5427,9 +5691,9 @@ function spliceOnce(patchFile, mtimeMs) {
5427
5691
  } catch {
5428
5692
  }
5429
5693
  }
5430
- mkdirSync7(dirname8(patchFile), { recursive: true });
5431
- writeFileSync7(patchFile, next, "utf8");
5432
- const written = readFileSync8(patchFile, "utf8");
5694
+ mkdirSync8(dirname9(patchFile), { recursive: true });
5695
+ writeFileSync8(patchFile, next, "utf8");
5696
+ const written = readFileSync9(patchFile, "utf8");
5433
5697
  if (written !== next) throw new Error("the patch file did not hold the written bytes after the write");
5434
5698
  }
5435
5699
  function removeLegacyImageMcpPatch(home, patchFile) {
@@ -5441,7 +5705,7 @@ function removeLegacyImageMcpPatch(home, patchFile) {
5441
5705
  }
5442
5706
  let text;
5443
5707
  try {
5444
- text = readFileSync8(file, "utf8");
5708
+ text = readFileSync9(file, "utf8");
5445
5709
  } catch {
5446
5710
  return void 0;
5447
5711
  }
@@ -5614,9 +5878,9 @@ function backfillRolePin(model, providers, route) {
5614
5878
  }
5615
5879
 
5616
5880
  // src/fingerprint/bank.ts
5617
- import { existsSync as existsSync4, readFileSync as readFileSync9 } from "node:fs";
5881
+ import { existsSync as existsSync4, readFileSync as readFileSync10 } from "node:fs";
5618
5882
  import { fileURLToPath } from "node:url";
5619
- import { dirname as dirname9, join as join9 } from "node:path";
5883
+ import { dirname as dirname10, join as join10 } from "node:path";
5620
5884
 
5621
5885
  // src/fingerprint/core.ts
5622
5886
  var VALUE_MIN = 1;
@@ -5901,10 +6165,10 @@ function parseBank(raw) {
5901
6165
  }
5902
6166
  function bankCandidates() {
5903
6167
  const candidates = [];
5904
- let dir = dirname9(fileURLToPath(import.meta.url));
6168
+ let dir = dirname10(fileURLToPath(import.meta.url));
5905
6169
  for (let depth = 0; depth < 5; depth += 1) {
5906
- candidates.push(join9(dir, "assets", "unified_bank.json"));
5907
- const parent = dirname9(dir);
6170
+ candidates.push(join10(dir, "assets", "unified_bank.json"));
6171
+ const parent = dirname10(dir);
5908
6172
  if (parent === dir) break;
5909
6173
  dir = parent;
5910
6174
  }
@@ -5921,7 +6185,7 @@ function bankPath() {
5921
6185
  var cached;
5922
6186
  function loadBankSync() {
5923
6187
  if (cached !== void 0) return cached;
5924
- cached = parseBank(JSON.parse(readFileSync9(bankPath(), "utf8")));
6188
+ cached = parseBank(JSON.parse(readFileSync10(bankPath(), "utf8")));
5925
6189
  return cached;
5926
6190
  }
5927
6191
  function summarizeBank(bank) {
@@ -6190,8 +6454,8 @@ async function runChallenge(options) {
6190
6454
  }
6191
6455
 
6192
6456
  // src/fingerprint/store.ts
6193
- import { mkdirSync as mkdirSync8, readFileSync as readFileSync10, renameSync as renameSync6, unlinkSync as unlinkSync6, writeFileSync as writeFileSync8 } from "node:fs";
6194
- import { dirname as dirname10, join as join10 } from "node:path";
6457
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync11, renameSync as renameSync7, unlinkSync as unlinkSync7, writeFileSync as writeFileSync9 } from "node:fs";
6458
+ import { dirname as dirname11, join as join11 } from "node:path";
6195
6459
  var STATUSES = /* @__PURE__ */ new Set(["identified", "doubtful", "failed"]);
6196
6460
  function emptyFingerprintStore(bankBuiltAt2 = "") {
6197
6461
  return { version: 1, bankBuiltAt: bankBuiltAt2, records: {} };
@@ -6200,7 +6464,7 @@ function recordKeyOf(provider, model) {
6200
6464
  return `${provider}\0${model}`;
6201
6465
  }
6202
6466
  function fingerprintFilePath(home = harnessHome()) {
6203
- return join10(home, "dsh-model-think-level", "fingerprint.json");
6467
+ return join11(home, "dsh-model-think-level", "fingerprint.json");
6204
6468
  }
6205
6469
  function finiteNumber(value, fallback) {
6206
6470
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
@@ -6318,7 +6582,7 @@ function parseFingerprintStore(raw, bankBuiltAt2 = "") {
6318
6582
  function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
6319
6583
  let text;
6320
6584
  try {
6321
- text = readFileSync10(file, "utf8");
6585
+ text = readFileSync11(file, "utf8");
6322
6586
  } catch (error) {
6323
6587
  if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
6324
6588
  return emptyFingerprintStore(bankBuiltAt2);
@@ -6334,15 +6598,15 @@ function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
6334
6598
  return parseFingerprintStore(raw, bankBuiltAt2);
6335
6599
  }
6336
6600
  function writeFingerprintStore(document, file = fingerprintFilePath()) {
6337
- mkdirSync8(dirname10(file), { recursive: true });
6601
+ mkdirSync9(dirname11(file), { recursive: true });
6338
6602
  const temporary = `${file}.${process.pid}.tmp`;
6339
- writeFileSync8(temporary, `${JSON.stringify(document, null, 2)}
6603
+ writeFileSync9(temporary, `${JSON.stringify(document, null, 2)}
6340
6604
  `, "utf8");
6341
6605
  try {
6342
- renameSync6(temporary, file);
6606
+ renameSync7(temporary, file);
6343
6607
  } catch (error) {
6344
6608
  try {
6345
- unlinkSync6(temporary);
6609
+ unlinkSync7(temporary);
6346
6610
  } catch {
6347
6611
  }
6348
6612
  throw error;
@@ -7232,7 +7496,8 @@ function apply(ctx, config = {}) {
7232
7496
  };
7233
7497
  const refreshHeaders = () => {
7234
7498
  const camouflage = readCamouflage().providers;
7235
- if (!resolved.uaOverride && Object.keys(camouflage).length === 0) {
7499
+ const historyCompat = readHistoryCompat().providers;
7500
+ if (!resolved.uaOverride && Object.keys(camouflage).length === 0 && Object.keys(historyCompat).length === 0) {
7236
7501
  overlaySource.current = emptyIndex();
7237
7502
  stopHeaderRetries();
7238
7503
  return;
@@ -7245,7 +7510,7 @@ function apply(ctx, config = {}) {
7245
7510
  }
7246
7511
  stopHeaderRetries();
7247
7512
  const providers = isRecord(section) && isRecord(section["providers"]) ? section["providers"] : {};
7248
- overlaySource.current = buildHeaderIndex(providers, camouflage);
7513
+ overlaySource.current = buildHeaderIndex(providers, camouflage, historyCompat);
7249
7514
  };
7250
7515
  refreshHeaders();
7251
7516
  refreshKeyScopes();
@@ -8406,6 +8671,59 @@ function apply(ctx, config = {}) {
8406
8671
  }),
8407
8672
  "dsh-model-think-level: camouflage route"
8408
8673
  );
8674
+ ctx.effect(
8675
+ () => webServerCtx.webServer.register({
8676
+ kind: "exact",
8677
+ path: HISTORY_COMPAT_PATH,
8678
+ handler: async (req, res) => {
8679
+ res.setHeader("cache-control", "no-store");
8680
+ if (!isTrustedRequest(req)) {
8681
+ sendJson(res, 403, { ok: false, error: "forbidden" });
8682
+ return;
8683
+ }
8684
+ if (req.method === "GET") {
8685
+ sendJson(res, 200, {
8686
+ ok: true,
8687
+ data: {
8688
+ providers: readHistoryCompat().providers,
8689
+ installed: requestSeamsInstalled()
8690
+ }
8691
+ });
8692
+ return;
8693
+ }
8694
+ if (req.method !== "POST") {
8695
+ sendJson(res, 405, { ok: false, error: "method not allowed" });
8696
+ return;
8697
+ }
8698
+ const body = await readJsonBody(req, 16384);
8699
+ if (!isRecord(body)) {
8700
+ sendJson(res, 400, { ok: false, error: "the body is not a JSON document" });
8701
+ return;
8702
+ }
8703
+ const route = body["route"];
8704
+ const enabled = body["enabled"];
8705
+ if (typeof route !== "string" || route.length === 0) {
8706
+ sendJson(res, 400, { ok: false, error: "route is required" });
8707
+ return;
8708
+ }
8709
+ if (typeof enabled !== "boolean") {
8710
+ sendJson(res, 400, { ok: false, error: "enabled must be a boolean" });
8711
+ return;
8712
+ }
8713
+ try {
8714
+ const document = setRouteHistoryCompat(route, enabled);
8715
+ refreshHeaders();
8716
+ sendJson(res, 200, {
8717
+ ok: true,
8718
+ data: { providers: document.providers, installed: requestSeamsInstalled() }
8719
+ });
8720
+ } catch (error) {
8721
+ sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
8722
+ }
8723
+ }
8724
+ }),
8725
+ "dsh-model-think-level: history-compat route"
8726
+ );
8409
8727
  ctx.effect(
8410
8728
  () => webServerCtx.webServer.register({
8411
8729
  kind: "exact",