dsh-model-think-level 2.4.0 → 2.5.1

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,145 @@ 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
+ if (stripSignatureId(signature) === void 0) return void 0;
3469
+ const copy = { ...block };
3470
+ delete copy["textSignature"];
3471
+ return copy;
3472
+ }
3473
+ if (type === "toolCall") {
3474
+ const id = block["id"];
3475
+ if (typeof id !== "string" || !id.includes("|")) return void 0;
3476
+ return { ...block, id: id.slice(0, id.indexOf("|")) };
3477
+ }
3478
+ return void 0;
3479
+ }
3480
+ function stripSignatureId(signature) {
3481
+ let parsed;
3482
+ try {
3483
+ parsed = JSON.parse(signature);
3484
+ } catch {
3485
+ return void 0;
3486
+ }
3487
+ if (!isRecord(parsed) || !Object.hasOwn(parsed, "id")) return void 0;
3488
+ const copy = { ...parsed };
3489
+ delete copy["id"];
3490
+ return JSON.stringify(copy);
3491
+ }
3492
+ function isHistoryRefusalCandidate(response) {
3493
+ return response.status === 400 || response.status >= 500;
3494
+ }
3495
+ async function reencodeHistoryRefusal(response) {
3496
+ if (!isHistoryRefusalCandidate(response)) return void 0;
3497
+ const text = await readErrorBody(response);
3498
+ if (text === void 0 || !isHistoryStateMismatch(text)) return void 0;
3499
+ return new Response(
3500
+ JSON.stringify({
3501
+ error: {
3502
+ type: response.status === 400 ? "invalid_request_error" : "server_error",
3503
+ message: text
3504
+ }
3505
+ }),
3506
+ {
3507
+ status: response.status,
3508
+ statusText: response.statusText,
3509
+ headers: { "content-type": "application/json" }
3510
+ }
3511
+ );
3512
+ }
3513
+ async function readErrorBody(response) {
3514
+ let clone;
3515
+ try {
3516
+ clone = response.clone();
3517
+ } catch {
3518
+ return void 0;
3519
+ }
3520
+ const reader = clone.body?.getReader();
3521
+ if (reader === void 0) return void 0;
3522
+ let expired = false;
3523
+ const timer = setTimeout(() => {
3524
+ expired = true;
3525
+ void reader.cancel().catch(() => {
3526
+ });
3527
+ }, HISTORY_INSPECT_TIMEOUT_MS);
3528
+ const chunks = [];
3529
+ let total = 0;
3530
+ try {
3531
+ for (; ; ) {
3532
+ const { done, value } = await reader.read();
3533
+ if (expired) return void 0;
3534
+ if (done) break;
3535
+ if (value === void 0) continue;
3536
+ total += value.byteLength;
3537
+ if (total > HISTORY_INSPECT_LIMIT) {
3538
+ return void 0;
3539
+ }
3540
+ chunks.push(value);
3541
+ }
3542
+ } catch {
3543
+ return void 0;
3544
+ } finally {
3545
+ clearTimeout(timer);
3546
+ }
3547
+ const merged = new Uint8Array(total);
3548
+ let offset = 0;
3549
+ for (const chunk of chunks) {
3550
+ merged.set(chunk, offset);
3551
+ offset += chunk.byteLength;
3552
+ }
3553
+ return new TextDecoder().decode(merged);
3554
+ }
3555
+
3346
3556
  // src/headers-fetch.ts
3347
3557
  var REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.fetch-overrides");
3348
3558
  var DISPATCH_REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.dispatch-overrides");
@@ -3503,9 +3713,15 @@ function makeWrapper(base, entries) {
3503
3713
  }
3504
3714
  return base(input, { ...init, headers });
3505
3715
  };
3716
+ const callerAborted = () => init?.signal?.aborted === true || typeof Request !== "undefined" && input instanceof Request && input.signal.aborted;
3717
+ const sendAttempt = async (keyValue) => {
3718
+ const response = await attempt(keyValue);
3719
+ if (override.historyCompat !== true) return response;
3720
+ return await reencodeHistoryRefusal(response) ?? response;
3721
+ };
3506
3722
  if (patched.get(WIRE_DISPATCH_HEADER) === "1") {
3507
3723
  patched.delete(WIRE_DISPATCH_HEADER);
3508
- return attempt(void 0);
3724
+ return sendAttempt(void 0);
3509
3725
  }
3510
3726
  const resolved = keyed ? await entry.keys({ route: override.route, model }) : [];
3511
3727
  const keyCandidates = restLast(
@@ -3547,7 +3763,9 @@ function makeWrapper(base, entries) {
3547
3763
  } catch {
3548
3764
  }
3549
3765
  }
3550
- if (!hasPatch && keyCandidates.length === 0) return base(input, passthroughInit(input, init));
3766
+ if (!hasPatch && keyCandidates.length === 0 && override.historyCompat !== true) {
3767
+ return base(input, passthroughInit(input, init));
3768
+ }
3551
3769
  const failureBody = async (response) => {
3552
3770
  try {
3553
3771
  return await readBoundedText(response, 4096);
@@ -3562,10 +3780,9 @@ function makeWrapper(base, entries) {
3562
3780
  const restKey = kind === "unserved" ? restKeyOf(override.route, candidate.ref, model) : restKeyOf(override.route, candidate.ref);
3563
3781
  keyRest.note(restKey, kind, retryAfterMs === void 0 ? void 0 : { retryAfterMs });
3564
3782
  };
3565
- const callerAborted = () => init?.signal?.aborted === true || typeof Request !== "undefined" && input instanceof Request && input.signal.aborted;
3566
3783
  if (keyCandidates.length <= 1) {
3567
3784
  const solo = keyCandidates[0];
3568
- const response = await attempt(solo?.value);
3785
+ const response = await sendAttempt(solo?.value);
3569
3786
  if (solo !== void 0) {
3570
3787
  if (response.status < 400) {
3571
3788
  clearRest(keyRest, override.route, solo.ref, model);
@@ -3586,7 +3803,7 @@ function makeWrapper(base, entries) {
3586
3803
  const candidate = keyCandidates[index];
3587
3804
  let response;
3588
3805
  try {
3589
- response = await attempt(candidate.value);
3806
+ response = await sendAttempt(candidate.value);
3590
3807
  } catch (error) {
3591
3808
  if (callerAborted()) throw error;
3592
3809
  lastFailure = error;
@@ -3602,6 +3819,7 @@ function makeWrapper(base, entries) {
3602
3819
  clearRest(keyRest, override.route, candidate.ref, model);
3603
3820
  return response;
3604
3821
  }
3822
+ if (response.status >= 500 && isHistoryStateMismatch(bodyText)) return response;
3605
3823
  const kind = classifyFailure(response.status, bodyText);
3606
3824
  if (kind === "unserved") unserved += 1;
3607
3825
  chargeFailure(candidate, response, kind);
@@ -3808,6 +4026,20 @@ function errorTextOf(event) {
3808
4026
  const parts = [error?.["message"], error?.["errorMessage"], event["reason"]];
3809
4027
  return parts.filter((part) => typeof part === "string").join(" ");
3810
4028
  }
4029
+ var CONTENT_EVENTS = /* @__PURE__ */ new Set([
4030
+ "thinking_start",
4031
+ "thinking_delta",
4032
+ "thinking_end",
4033
+ "text_start",
4034
+ "text_delta",
4035
+ "text_end",
4036
+ "toolcall_start",
4037
+ "toolcall_delta",
4038
+ "toolcall_end"
4039
+ ]);
4040
+ function isContentEvent(type) {
4041
+ return typeof type === "string" && CONTENT_EVENTS.has(type);
4042
+ }
3811
4043
  function modelsProxyOf(models, source) {
3812
4044
  return new Proxy(models, {
3813
4045
  get(target, property, receiver) {
@@ -3846,7 +4078,7 @@ function modelsProxyOf(models, source) {
3846
4078
  if (route === void 0) return Promise.resolve([]);
3847
4079
  return Promise.resolve(keyResolver({ route, model: modelId })).catch(() => []);
3848
4080
  };
3849
- const startAttempt = async (candidate, avoid) => {
4081
+ const startAttempt = async (candidate, avoid, requestContext = context) => {
3850
4082
  const api = typeof modelObject["api"] === "string" ? modelObject["api"] : "openai-completions";
3851
4083
  const protocol = wireOf(candidate, api, modelId, avoid);
3852
4084
  const honoured = isHonoured(candidate, api);
@@ -3855,7 +4087,7 @@ function modelsProxyOf(models, source) {
3855
4087
  const baseUrl = protocol === "anthropic-messages" ? anthropicRequestBaseUrl(selectedBaseUrl) : selectedBaseUrl;
3856
4088
  const switched = protocol !== api || baseUrl !== modelObject["baseUrl"];
3857
4089
  if (!switched) {
3858
- return streamSimple.call(target, model, context, {
4090
+ return streamSimple.call(target, model, requestContext, {
3859
4091
  ...options,
3860
4092
  apiKey: candidate.value,
3861
4093
  transformHeaders: markedTransformHeaders
@@ -3864,7 +4096,7 @@ function modelsProxyOf(models, source) {
3864
4096
  const mergedHeaders = await transformHeaders(isRecord(options["headers"]) ? options["headers"] : {});
3865
4097
  const implementation = await loadProtocol(protocol);
3866
4098
  const switchedToClaude = protocol === "anthropic-messages" && routeOverrideOf(source, model)?.camouflage === "claude";
3867
- const normalized2 = await normalizeDispatchedContext(context);
4099
+ const normalized2 = await normalizeDispatchedContext(requestContext);
3868
4100
  const dispatchedContext = switchedToClaude ? withClaudeIdentityContext(normalized2) : normalized2;
3869
4101
  const existingMetadata = isRecord(options["metadata"]) ? options["metadata"] : void 0;
3870
4102
  const suppliedUserId = existingMetadata?.["user_id"];
@@ -3905,42 +4137,76 @@ function modelsProxyOf(models, source) {
3905
4137
  isResting: (candidate) => isRestingFor(keyRest, route ?? "", candidate.ref, modelId, Date.now())
3906
4138
  });
3907
4139
  recordRoutePlan(route ?? "", plan, { model: modelId });
4140
+ const recoversHistory = routeOverrideOf(source, model)?.historyCompat === true;
3908
4141
  const wireOfAttempt = (candidate) => plan.entries.find((entry) => entry.candidate === candidate)?.wire ?? wireOf(candidate, api, modelId, avoidWire);
3909
4142
  const restKeyFor = (candidate, kind) => kind === "unserved" && modelId !== void 0 ? restKeyOf(route ?? "", candidate.ref, modelId) : restKeyOf(route ?? "", candidate.ref);
3910
4143
  let lastErrorEvent;
3911
4144
  let lastError;
3912
4145
  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;
4146
+ let attemptContext = context;
4147
+ let historyStage = -1;
4148
+ let historyExhausted = false;
4149
+ let setupFailed = false;
4150
+ while (true) {
4151
+ let stream;
4152
+ try {
4153
+ stream = await startAttempt(candidate, avoidWire, attemptContext);
4154
+ } catch (error) {
4155
+ lastError = error;
4156
+ if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
4157
+ const kind = classifyFailure(void 0, error instanceof Error ? error.message : "") ?? "refused";
4158
+ keyRest.note(restKeyFor(candidate, kind), kind);
4159
+ setupFailed = true;
4160
+ break;
4161
+ }
4162
+ let committed = false;
4163
+ let contentStarted = false;
4164
+ let failed = false;
4165
+ let retried = false;
4166
+ for await (const event of stream) {
4167
+ const type = isRecord(event) ? event["type"] : void 0;
4168
+ if (recoversHistory && type === "error" && !contentStarted) {
4169
+ const text = errorTextOf(event);
4170
+ if (isHistoryStateMismatch(text)) {
4171
+ for (let next = historyStage + 1; next < HISTORY_STAGES.length; next += 1) {
4172
+ const degraded = degradeForHistory(context, HISTORY_STAGES[next]);
4173
+ if (degraded === void 0) continue;
4174
+ attemptContext = degraded;
4175
+ historyStage = next;
4176
+ retried = true;
4177
+ break;
4178
+ }
4179
+ if (retried) break;
4180
+ lastErrorEvent = event;
4181
+ historyExhausted = true;
4182
+ break;
4183
+ }
4184
+ }
4185
+ if (!committed) {
4186
+ if (type === "error") {
4187
+ lastErrorEvent = event;
4188
+ failed = true;
4189
+ if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
4190
+ const kind = classifyFailure(void 0, errorTextOf(event)) ?? "refused";
4191
+ keyRest.note(restKeyFor(candidate, kind), kind);
4192
+ break;
4193
+ }
4194
+ committed = true;
4195
+ clearRest(keyRest, route ?? "", candidate.ref, modelId);
4196
+ rememberWireFact(servedWire, servedKey, wireOfAttempt(candidate));
3935
4197
  }
3936
- committed = true;
3937
- clearRest(keyRest, route ?? "", candidate.ref, modelId);
3938
- rememberWireFact(servedWire, servedKey, wireOfAttempt(candidate));
4198
+ yield event;
4199
+ if (isContentEvent(type)) contentStarted = true;
4200
+ }
4201
+ if (retried) continue;
4202
+ if (historyExhausted) {
4203
+ if (lastErrorEvent !== void 0) yield lastErrorEvent;
4204
+ return;
3939
4205
  }
3940
- yield event;
4206
+ if (failed) break;
4207
+ return;
3941
4208
  }
3942
- if (failed) continue;
3943
- return;
4209
+ if (setupFailed) continue;
3944
4210
  }
3945
4211
  if (lastErrorEvent !== void 0) {
3946
4212
  yield lastErrorEvent;
@@ -4143,9 +4409,9 @@ function installPiAiHeaderTransforms(llm, source) {
4143
4409
  }
4144
4410
 
4145
4411
  // src/headers-conflict.ts
4146
- import { existsSync, readFileSync as readFileSync5 } from "node:fs";
4412
+ import { existsSync, readFileSync as readFileSync6 } from "node:fs";
4147
4413
  import { createRequire } from "node:module";
4148
- import { dirname as dirname5, join as join5, resolve as resolve2 } from "node:path";
4414
+ import { dirname as dirname6, join as join6, resolve as resolve2 } from "node:path";
4149
4415
  var SIBLING_PACKAGES = [
4150
4416
  "dsh-client-masquerade",
4151
4417
  "dsh-llm-headers",
@@ -4157,20 +4423,20 @@ function searchRoots() {
4157
4423
  const roots = /* @__PURE__ */ new Set();
4158
4424
  const entry = process.argv[1];
4159
4425
  if (typeof entry === "string" && entry.length > 0) {
4160
- let dir = dirname5(resolve2(entry));
4426
+ let dir = dirname6(resolve2(entry));
4161
4427
  for (let depth = 0; depth < 8; depth += 1) {
4162
- roots.add(join5(dir, "node_modules"));
4163
- const parent = dirname5(dir);
4428
+ roots.add(join6(dir, "node_modules"));
4429
+ const parent = dirname6(dir);
4164
4430
  if (parent === dir) break;
4165
4431
  dir = parent;
4166
4432
  }
4167
4433
  }
4168
- roots.add(join5(process.cwd(), "node_modules"));
4434
+ roots.add(join6(process.cwd(), "node_modules"));
4169
4435
  try {
4170
4436
  const require2 = createRequire(import.meta.url);
4171
4437
  for (const name2 of SIBLING_PACKAGES) {
4172
4438
  try {
4173
- roots.add(join5(dirname5(dirname5(dirname5(require2.resolve(`${name2}/package.json`)))), "node_modules"));
4439
+ roots.add(join6(dirname6(dirname6(dirname6(require2.resolve(`${name2}/package.json`)))), "node_modules"));
4174
4440
  } catch {
4175
4441
  }
4176
4442
  }
@@ -4179,14 +4445,14 @@ function searchRoots() {
4179
4445
  return [...roots];
4180
4446
  }
4181
4447
  function findAdapterFile() {
4182
- const relative = join5("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
4448
+ const relative = join6("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
4183
4449
  const candidates = [];
4184
4450
  try {
4185
4451
  const require2 = createRequire(import.meta.url);
4186
4452
  candidates.push(require2.resolve("@deepseek-ai/dsh-llm-pi-ai"));
4187
4453
  } catch {
4188
4454
  }
4189
- for (const root of searchRoots()) candidates.push(join5(root, relative));
4455
+ for (const root of searchRoots()) candidates.push(join6(root, relative));
4190
4456
  for (const candidate of candidates) {
4191
4457
  if (existsSync(candidate)) return candidate;
4192
4458
  }
@@ -4197,7 +4463,7 @@ function adapterSourcePatched(source) {
4197
4463
  }
4198
4464
  function adapterPatchState(path) {
4199
4465
  try {
4200
- return adapterSourcePatched(readFileSync5(path, "utf8")) ? "patched" : "stock";
4466
+ return adapterSourcePatched(readFileSync6(path, "utf8")) ? "patched" : "stock";
4201
4467
  } catch {
4202
4468
  return "unknown";
4203
4469
  }
@@ -4208,8 +4474,8 @@ function findSiblings() {
4208
4474
  for (const root of searchRoots()) {
4209
4475
  for (const name2 of SIBLING_PACKAGES) {
4210
4476
  if (seen.has(name2)) continue;
4211
- const dir = join5(root, name2);
4212
- const manifest = join5(dir, "package.json");
4477
+ const dir = join6(root, name2);
4478
+ const manifest = join6(dir, "package.json");
4213
4479
  if (!existsSync(manifest)) continue;
4214
4480
  seen.add(name2);
4215
4481
  found.push({ name: name2, path: dir });
@@ -4241,8 +4507,8 @@ function detectHeaderConflicts() {
4241
4507
  }
4242
4508
 
4243
4509
  // 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";
4510
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync as renameSync6, unlinkSync as unlinkSync6, writeFileSync as writeFileSync6 } from "node:fs";
4511
+ import { dirname as dirname7, join as join7 } from "node:path";
4246
4512
 
4247
4513
  // src/image/sizes.ts
4248
4514
  var IMAGE_SIZE_TIERS = [
@@ -4259,7 +4525,7 @@ var IMAGE_FALLBACK_PARAMS = {
4259
4525
  responseFormat: "b64_json"
4260
4526
  };
4261
4527
  function imageConfigFilePath(home = harnessHome()) {
4262
- return join6(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
4528
+ return join7(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
4263
4529
  }
4264
4530
  function emptyImageConfig(now = () => /* @__PURE__ */ new Date()) {
4265
4531
  return {
@@ -4360,7 +4626,7 @@ function parseImageModel(raw) {
4360
4626
  function readImageConfig(file = imageConfigFilePath()) {
4361
4627
  let text;
4362
4628
  try {
4363
- text = readFileSync6(file, "utf8");
4629
+ text = readFileSync7(file, "utf8");
4364
4630
  } catch {
4365
4631
  return emptyImageConfig();
4366
4632
  }
@@ -4371,15 +4637,15 @@ function readImageConfig(file = imageConfigFilePath()) {
4371
4637
  }
4372
4638
  }
4373
4639
  function writeImageConfig(document, file = imageConfigFilePath()) {
4374
- mkdirSync5(dirname6(file), { recursive: true });
4640
+ mkdirSync6(dirname7(file), { recursive: true });
4375
4641
  const temporary = `${file}.${process.pid}.tmp`;
4376
- writeFileSync5(temporary, `${JSON.stringify(document, null, 2)}
4642
+ writeFileSync6(temporary, `${JSON.stringify(document, null, 2)}
4377
4643
  `, "utf8");
4378
4644
  try {
4379
- renameSync5(temporary, file);
4645
+ renameSync6(temporary, file);
4380
4646
  } catch (error) {
4381
4647
  try {
4382
- unlinkSync5(temporary);
4648
+ unlinkSync6(temporary);
4383
4649
  } catch {
4384
4650
  }
4385
4651
  throw error;
@@ -4467,8 +4733,8 @@ function updateImageConfig(mutate, file = imageConfigFilePath()) {
4467
4733
  }
4468
4734
 
4469
4735
  // 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";
4736
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync7, existsSync as existsSync2, statSync } from "node:fs";
4737
+ import { dirname as dirname8, join as join8, resolve as resolve3 } from "node:path";
4472
4738
 
4473
4739
  // src/image/deadline.ts
4474
4740
  function createImageDeadline(timeoutMs, caller, errorFor) {
@@ -4708,19 +4974,19 @@ function outputDirOf(deps, config) {
4708
4974
  const home = deps.home?.() ?? harnessHome();
4709
4975
  const dir = config.outputDir;
4710
4976
  if (/^([A-Za-z]:[\\/]|\/)/.test(dir)) return dir;
4711
- return join7(home, "dsh-model-think-level", dir);
4977
+ return join8(home, "dsh-model-think-level", dir);
4712
4978
  }
4713
4979
  function destinationOf(dir, slug, now) {
4714
- const base = join7(dir, `${slug}-${now()}.png`);
4980
+ const base = join8(dir, `${slug}-${now()}.png`);
4715
4981
  if (!existsSync2(base)) return base;
4716
4982
  for (let index = 2; ; index += 1) {
4717
- const candidate = join7(dir, `${slug}-${now()}-${index}.png`);
4983
+ const candidate = join8(dir, `${slug}-${now()}-${index}.png`);
4718
4984
  if (!existsSync2(candidate)) return candidate;
4719
4985
  }
4720
4986
  }
4721
4987
  function resolveDestination(requested, fallbackDir, slug, now) {
4722
4988
  if (requested === void 0 || requested.trim().length === 0) {
4723
- mkdirSync6(fallbackDir, { recursive: true });
4989
+ mkdirSync7(fallbackDir, { recursive: true });
4724
4990
  return destinationOf(fallbackDir, slug, now);
4725
4991
  }
4726
4992
  const target = resolve3(requested.trim());
@@ -4730,10 +4996,10 @@ function resolveDestination(requested, fallbackDir, slug, now) {
4730
4996
  } catch {
4731
4997
  }
4732
4998
  if (isDir || /[\\/]$/.test(target) || !target.toLowerCase().endsWith(".png")) {
4733
- mkdirSync6(target, { recursive: true });
4999
+ mkdirSync7(target, { recursive: true });
4734
5000
  return destinationOf(target, slug, now);
4735
5001
  }
4736
- mkdirSync6(dirname7(target), { recursive: true });
5002
+ mkdirSync7(dirname8(target), { recursive: true });
4737
5003
  if (!existsSync2(target)) return target;
4738
5004
  for (let index = 2; ; index += 1) {
4739
5005
  const candidate = target.replace(/\.png$/i, `-${index}.png`);
@@ -4823,7 +5089,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4823
5089
  const absolute = resolve3(path);
4824
5090
  if (!existsSync2(absolute)) throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4825
5091
  try {
4826
- return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync7(absolute), mime: mimeOfPath(absolute) };
5092
+ return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync8(absolute), mime: mimeOfPath(absolute) };
4827
5093
  } catch {
4828
5094
  throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4829
5095
  }
@@ -4900,7 +5166,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4900
5166
  const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now);
4901
5167
  const bytes = Uint8Array.from(atob(data), (ch) => ch.charCodeAt(0));
4902
5168
  deadline.check();
4903
- writeFileSync6(filePath, bytes);
5169
+ writeFileSync7(filePath, bytes);
4904
5170
  images.push({ filePath, data });
4905
5171
  }
4906
5172
  deadline.check();
@@ -5330,19 +5596,19 @@ function imageToolHint(config) {
5330
5596
  }
5331
5597
 
5332
5598
  // 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";
5599
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync8, readFileSync as readFileSync9, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync8 } from "node:fs";
5600
+ import { dirname as dirname9, join as join9 } from "node:path";
5335
5601
  var MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`;
5336
5602
  var MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`;
5337
5603
  function resolveLegacyPatchFile(home = harnessHome()) {
5338
5604
  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");
5605
+ if (explicit !== void 0 && explicit.length > 0) return join9(home, "profiles", explicit, "cordis.patch.yml");
5606
+ const profilesDir = join9(home, "profiles");
5341
5607
  try {
5342
5608
  if (existsSync3(profilesDir)) {
5343
5609
  const candidates = [];
5344
5610
  for (const name2 of readdirSync2(profilesDir)) {
5345
- const file = join8(profilesDir, name2, "cordis.patch.yml");
5611
+ const file = join9(profilesDir, name2, "cordis.patch.yml");
5346
5612
  if (!existsSync3(file)) continue;
5347
5613
  candidates.push({ file, mtime: statSync2(file).mtimeMs });
5348
5614
  }
@@ -5351,8 +5617,8 @@ function resolveLegacyPatchFile(home = harnessHome()) {
5351
5617
  }
5352
5618
  } catch {
5353
5619
  }
5354
- if (existsSync3(join8(home, "cordis.patch.yml"))) return join8(home, "cordis.patch.yml");
5355
- return join8(home, "profiles", "desktop", "cordis.patch.yml");
5620
+ if (existsSync3(join9(home, "cordis.patch.yml"))) return join9(home, "cordis.patch.yml");
5621
+ return join9(home, "profiles", "desktop", "cordis.patch.yml");
5356
5622
  }
5357
5623
  function markerRange(text) {
5358
5624
  const start = text.indexOf(MARK_BEGIN);
@@ -5413,7 +5679,7 @@ function mtimeOf(patchFile) {
5413
5679
  var ModifiedError = class extends Error {
5414
5680
  };
5415
5681
  function spliceOnce(patchFile, mtimeMs) {
5416
- const current = readFileSync8(patchFile, "utf8");
5682
+ const current = readFileSync9(patchFile, "utf8");
5417
5683
  const range = legacyRange(current);
5418
5684
  if (range === void 0) return;
5419
5685
  let next = current.slice(0, range.start) + current.slice(range.end);
@@ -5427,9 +5693,9 @@ function spliceOnce(patchFile, mtimeMs) {
5427
5693
  } catch {
5428
5694
  }
5429
5695
  }
5430
- mkdirSync7(dirname8(patchFile), { recursive: true });
5431
- writeFileSync7(patchFile, next, "utf8");
5432
- const written = readFileSync8(patchFile, "utf8");
5696
+ mkdirSync8(dirname9(patchFile), { recursive: true });
5697
+ writeFileSync8(patchFile, next, "utf8");
5698
+ const written = readFileSync9(patchFile, "utf8");
5433
5699
  if (written !== next) throw new Error("the patch file did not hold the written bytes after the write");
5434
5700
  }
5435
5701
  function removeLegacyImageMcpPatch(home, patchFile) {
@@ -5441,7 +5707,7 @@ function removeLegacyImageMcpPatch(home, patchFile) {
5441
5707
  }
5442
5708
  let text;
5443
5709
  try {
5444
- text = readFileSync8(file, "utf8");
5710
+ text = readFileSync9(file, "utf8");
5445
5711
  } catch {
5446
5712
  return void 0;
5447
5713
  }
@@ -5614,9 +5880,9 @@ function backfillRolePin(model, providers, route) {
5614
5880
  }
5615
5881
 
5616
5882
  // src/fingerprint/bank.ts
5617
- import { existsSync as existsSync4, readFileSync as readFileSync9 } from "node:fs";
5883
+ import { existsSync as existsSync4, readFileSync as readFileSync10 } from "node:fs";
5618
5884
  import { fileURLToPath } from "node:url";
5619
- import { dirname as dirname9, join as join9 } from "node:path";
5885
+ import { dirname as dirname10, join as join10 } from "node:path";
5620
5886
 
5621
5887
  // src/fingerprint/core.ts
5622
5888
  var VALUE_MIN = 1;
@@ -5901,10 +6167,10 @@ function parseBank(raw) {
5901
6167
  }
5902
6168
  function bankCandidates() {
5903
6169
  const candidates = [];
5904
- let dir = dirname9(fileURLToPath(import.meta.url));
6170
+ let dir = dirname10(fileURLToPath(import.meta.url));
5905
6171
  for (let depth = 0; depth < 5; depth += 1) {
5906
- candidates.push(join9(dir, "assets", "unified_bank.json"));
5907
- const parent = dirname9(dir);
6172
+ candidates.push(join10(dir, "assets", "unified_bank.json"));
6173
+ const parent = dirname10(dir);
5908
6174
  if (parent === dir) break;
5909
6175
  dir = parent;
5910
6176
  }
@@ -5921,7 +6187,7 @@ function bankPath() {
5921
6187
  var cached;
5922
6188
  function loadBankSync() {
5923
6189
  if (cached !== void 0) return cached;
5924
- cached = parseBank(JSON.parse(readFileSync9(bankPath(), "utf8")));
6190
+ cached = parseBank(JSON.parse(readFileSync10(bankPath(), "utf8")));
5925
6191
  return cached;
5926
6192
  }
5927
6193
  function summarizeBank(bank) {
@@ -6190,8 +6456,8 @@ async function runChallenge(options) {
6190
6456
  }
6191
6457
 
6192
6458
  // 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";
6459
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync11, renameSync as renameSync7, unlinkSync as unlinkSync7, writeFileSync as writeFileSync9 } from "node:fs";
6460
+ import { dirname as dirname11, join as join11 } from "node:path";
6195
6461
  var STATUSES = /* @__PURE__ */ new Set(["identified", "doubtful", "failed"]);
6196
6462
  function emptyFingerprintStore(bankBuiltAt2 = "") {
6197
6463
  return { version: 1, bankBuiltAt: bankBuiltAt2, records: {} };
@@ -6200,7 +6466,7 @@ function recordKeyOf(provider, model) {
6200
6466
  return `${provider}\0${model}`;
6201
6467
  }
6202
6468
  function fingerprintFilePath(home = harnessHome()) {
6203
- return join10(home, "dsh-model-think-level", "fingerprint.json");
6469
+ return join11(home, "dsh-model-think-level", "fingerprint.json");
6204
6470
  }
6205
6471
  function finiteNumber(value, fallback) {
6206
6472
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
@@ -6318,7 +6584,7 @@ function parseFingerprintStore(raw, bankBuiltAt2 = "") {
6318
6584
  function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
6319
6585
  let text;
6320
6586
  try {
6321
- text = readFileSync10(file, "utf8");
6587
+ text = readFileSync11(file, "utf8");
6322
6588
  } catch (error) {
6323
6589
  if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
6324
6590
  return emptyFingerprintStore(bankBuiltAt2);
@@ -6334,15 +6600,15 @@ function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
6334
6600
  return parseFingerprintStore(raw, bankBuiltAt2);
6335
6601
  }
6336
6602
  function writeFingerprintStore(document, file = fingerprintFilePath()) {
6337
- mkdirSync8(dirname10(file), { recursive: true });
6603
+ mkdirSync9(dirname11(file), { recursive: true });
6338
6604
  const temporary = `${file}.${process.pid}.tmp`;
6339
- writeFileSync8(temporary, `${JSON.stringify(document, null, 2)}
6605
+ writeFileSync9(temporary, `${JSON.stringify(document, null, 2)}
6340
6606
  `, "utf8");
6341
6607
  try {
6342
- renameSync6(temporary, file);
6608
+ renameSync7(temporary, file);
6343
6609
  } catch (error) {
6344
6610
  try {
6345
- unlinkSync6(temporary);
6611
+ unlinkSync7(temporary);
6346
6612
  } catch {
6347
6613
  }
6348
6614
  throw error;
@@ -7232,7 +7498,8 @@ function apply(ctx, config = {}) {
7232
7498
  };
7233
7499
  const refreshHeaders = () => {
7234
7500
  const camouflage = readCamouflage().providers;
7235
- if (!resolved.uaOverride && Object.keys(camouflage).length === 0) {
7501
+ const historyCompat = readHistoryCompat().providers;
7502
+ if (!resolved.uaOverride && Object.keys(camouflage).length === 0 && Object.keys(historyCompat).length === 0) {
7236
7503
  overlaySource.current = emptyIndex();
7237
7504
  stopHeaderRetries();
7238
7505
  return;
@@ -7245,7 +7512,7 @@ function apply(ctx, config = {}) {
7245
7512
  }
7246
7513
  stopHeaderRetries();
7247
7514
  const providers = isRecord(section) && isRecord(section["providers"]) ? section["providers"] : {};
7248
- overlaySource.current = buildHeaderIndex(providers, camouflage);
7515
+ overlaySource.current = buildHeaderIndex(providers, camouflage, historyCompat);
7249
7516
  };
7250
7517
  refreshHeaders();
7251
7518
  refreshKeyScopes();
@@ -8406,6 +8673,59 @@ function apply(ctx, config = {}) {
8406
8673
  }),
8407
8674
  "dsh-model-think-level: camouflage route"
8408
8675
  );
8676
+ ctx.effect(
8677
+ () => webServerCtx.webServer.register({
8678
+ kind: "exact",
8679
+ path: HISTORY_COMPAT_PATH,
8680
+ handler: async (req, res) => {
8681
+ res.setHeader("cache-control", "no-store");
8682
+ if (!isTrustedRequest(req)) {
8683
+ sendJson(res, 403, { ok: false, error: "forbidden" });
8684
+ return;
8685
+ }
8686
+ if (req.method === "GET") {
8687
+ sendJson(res, 200, {
8688
+ ok: true,
8689
+ data: {
8690
+ providers: readHistoryCompat().providers,
8691
+ installed: requestSeamsInstalled()
8692
+ }
8693
+ });
8694
+ return;
8695
+ }
8696
+ if (req.method !== "POST") {
8697
+ sendJson(res, 405, { ok: false, error: "method not allowed" });
8698
+ return;
8699
+ }
8700
+ const body = await readJsonBody(req, 16384);
8701
+ if (!isRecord(body)) {
8702
+ sendJson(res, 400, { ok: false, error: "the body is not a JSON document" });
8703
+ return;
8704
+ }
8705
+ const route = body["route"];
8706
+ const enabled = body["enabled"];
8707
+ if (typeof route !== "string" || route.length === 0) {
8708
+ sendJson(res, 400, { ok: false, error: "route is required" });
8709
+ return;
8710
+ }
8711
+ if (typeof enabled !== "boolean") {
8712
+ sendJson(res, 400, { ok: false, error: "enabled must be a boolean" });
8713
+ return;
8714
+ }
8715
+ try {
8716
+ const document = setRouteHistoryCompat(route, enabled);
8717
+ refreshHeaders();
8718
+ sendJson(res, 200, {
8719
+ ok: true,
8720
+ data: { providers: document.providers, installed: requestSeamsInstalled() }
8721
+ });
8722
+ } catch (error) {
8723
+ sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
8724
+ }
8725
+ }
8726
+ }),
8727
+ "dsh-model-think-level: history-compat route"
8728
+ );
8409
8729
  ctx.effect(
8410
8730
  () => webServerCtx.webServer.register({
8411
8731
  kind: "exact",