dsh-model-think-level 2.3.6 → 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
@@ -18,6 +18,11 @@ var UNSET_MARKER = "reasoningEffortsUnset";
18
18
  var INPUT_UNSET_MARKER = "inputUnset";
19
19
  var INPUT_IMAGE_GEN_MARKER = "inputImageGen";
20
20
  var AUTOFILL_MARKER = "reasoningEffortsAutofilled";
21
+ var CAMOUFLAGE_PATH = "/dsh-model-think-level/camouflage";
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";
21
26
  var IMAGE_CONFIG_PATH = "/dsh-model-think-level/image-config";
22
27
  var IMAGE_CONFIG_FILE = "image.json";
23
28
  var IMAGE_MCP_PATCH_ID = "dsh-image-mcp";
@@ -847,6 +852,225 @@ function commitUiOrderGuarded(patch, at, file = uiOrderFilePath()) {
847
852
  return { document, stale: false };
848
853
  }
849
854
 
855
+ // src/camouflage-store.ts
856
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "node:fs";
857
+ import { dirname as dirname4, join as join4 } from "node:path";
858
+
859
+ // src/camouflage.ts
860
+ import { randomUUID as randomUUID2 } from "node:crypto";
861
+ var CAMOUFLAGE_PRESETS = ["codex", "claude"];
862
+ function isCamouflagePreset(value) {
863
+ return value === "codex" || value === "claude";
864
+ }
865
+ var CLAUDE_CLI_VERSION = "2.1.251";
866
+ var CODEX_CLI_VERSION = "0.55.0";
867
+ var PROCESS_DEVICE_ID = randomUUID2().replace(/-/g, "");
868
+ var PROCESS_SESSION_ID = randomUUID2();
869
+ var PROCESS_CODEX_SESSION_ID = randomUUID2();
870
+ function camouflageUserAgent(preset) {
871
+ return preset === "codex" ? `codex_cli_rs/${CODEX_CLI_VERSION} (macOS 15.6; arm64)` : `claude-cli/${CLAUDE_CLI_VERSION} (external, cli)`;
872
+ }
873
+ function isAnthropicMessagesUrl(url) {
874
+ try {
875
+ const pathname = new URL(url).pathname.replace(/\/+$/, "");
876
+ return pathname.endsWith("/v1/messages") || pathname.endsWith("/messages");
877
+ } catch {
878
+ return false;
879
+ }
880
+ }
881
+ function camouflageHeaders(preset) {
882
+ if (preset === "codex") {
883
+ return {
884
+ "user-agent": camouflageUserAgent("codex"),
885
+ originator: "codex_cli_rs",
886
+ "x-codex-session-id": PROCESS_CODEX_SESSION_ID
887
+ };
888
+ }
889
+ return {
890
+ "user-agent": camouflageUserAgent("claude"),
891
+ "x-app": "cli",
892
+ "anthropic-version": "2023-06-01",
893
+ "anthropic-beta": "claude-code-20250219"
894
+ };
895
+ }
896
+ function applyCamouflageHeaders(headers, preset) {
897
+ let changed = false;
898
+ for (const [name2, value] of Object.entries(camouflageHeaders(preset))) {
899
+ if (name2 === "anthropic-version" && headers.has(name2)) continue;
900
+ if (headers.get(name2) === value) continue;
901
+ try {
902
+ headers.set(name2, value);
903
+ changed = true;
904
+ } catch {
905
+ }
906
+ }
907
+ return changed;
908
+ }
909
+ var CLAUDE_CODE_SYSTEM_TEXT = "You are Claude Code, Anthropic's CLI for Claude.";
910
+ function camouflageClaudeUserId() {
911
+ return `user_${PROCESS_DEVICE_ID}_account_${PROCESS_DEVICE_ID}_session_${PROCESS_SESSION_ID}`;
912
+ }
913
+ function patchCamouflageBody(text, preset, url) {
914
+ if (preset !== "claude") return void 0;
915
+ if (!isAnthropicMessagesUrl(url)) return void 0;
916
+ let body;
917
+ try {
918
+ body = JSON.parse(text);
919
+ } catch {
920
+ return void 0;
921
+ }
922
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
923
+ const record = body;
924
+ let changed = false;
925
+ const system = record["system"];
926
+ if (Array.isArray(system)) {
927
+ const first = system[0];
928
+ const firstText = typeof first === "object" && first !== null && !Array.isArray(first) ? first["text"] : void 0;
929
+ if (typeof firstText !== "string" || !firstText.startsWith("You are Claude Code")) {
930
+ system.unshift({ type: "text", text: CLAUDE_CODE_SYSTEM_TEXT });
931
+ changed = true;
932
+ }
933
+ } else if (typeof system === "string") {
934
+ if (!system.startsWith("You are Claude Code")) {
935
+ record["system"] = [
936
+ { type: "text", text: CLAUDE_CODE_SYSTEM_TEXT },
937
+ { type: "text", text: system }
938
+ ];
939
+ changed = true;
940
+ }
941
+ } else {
942
+ record["system"] = [{ type: "text", text: CLAUDE_CODE_SYSTEM_TEXT }];
943
+ changed = true;
944
+ }
945
+ const metadata = record["metadata"];
946
+ const existingUserId = typeof metadata === "object" && metadata !== null && !Array.isArray(metadata) ? metadata["user_id"] : void 0;
947
+ if (typeof existingUserId !== "string" || existingUserId.length === 0) {
948
+ record["metadata"] = {
949
+ ...typeof metadata === "object" && metadata !== null && !Array.isArray(metadata) ? metadata : {},
950
+ user_id: camouflageClaudeUserId()
951
+ };
952
+ changed = true;
953
+ }
954
+ return changed ? JSON.stringify(record) : void 0;
955
+ }
956
+
957
+ // src/camouflage-store.ts
958
+ function emptyCamouflage() {
959
+ return { version: 1, providers: {} };
960
+ }
961
+ function camouflageFilePath(home = harnessHome()) {
962
+ return join4(home, "dsh-model-think-level", CAMOUFLAGE_FILE);
963
+ }
964
+ function parseCamouflage(raw) {
965
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return emptyCamouflage();
966
+ const providers = raw["providers"];
967
+ if (typeof providers !== "object" || providers === null || Array.isArray(providers)) return emptyCamouflage();
968
+ const out = {};
969
+ for (const [route, value] of Object.entries(providers)) {
970
+ if (route.length === 0) continue;
971
+ if (!isCamouflagePreset(value)) continue;
972
+ Object.defineProperty(out, route, { value, enumerable: true, configurable: true, writable: true });
973
+ }
974
+ return { version: 1, providers: out };
975
+ }
976
+ function readCamouflage(file = camouflageFilePath()) {
977
+ try {
978
+ return parseCamouflage(JSON.parse(readFileSync4(file, "utf8")));
979
+ } catch {
980
+ return emptyCamouflage();
981
+ }
982
+ }
983
+ function writeCamouflage(document, file = camouflageFilePath()) {
984
+ mkdirSync4(dirname4(file), { recursive: true });
985
+ const temporary = `${file}.${process.pid}.tmp`;
986
+ writeFileSync4(temporary, `${JSON.stringify(document, null, 2)}
987
+ `, "utf8");
988
+ try {
989
+ renameSync4(temporary, file);
990
+ } catch (error) {
991
+ try {
992
+ unlinkSync4(temporary);
993
+ } catch {
994
+ }
995
+ throw error;
996
+ }
997
+ }
998
+ function setRouteCamouflage(route, preset, file = camouflageFilePath()) {
999
+ const current = readCamouflage(file);
1000
+ const providers = { ...current.providers };
1001
+ if (preset === void 0) delete providers[route];
1002
+ else Object.defineProperty(providers, route, { value: preset, enumerable: true, configurable: true, writable: true });
1003
+ const next = { version: 1, providers };
1004
+ writeCamouflage(next, file);
1005
+ return next;
1006
+ }
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
+
850
1074
  // src/multi-key-listing.ts
851
1075
  var DEFAULT_PROBE_CONCURRENCY = 4;
852
1076
  var MODEL_ORDER = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
@@ -1060,7 +1284,7 @@ function recordHeaderConflicts(index, existing, route, headers) {
1060
1284
  }
1061
1285
  }
1062
1286
  }
1063
- function buildHeaderIndex(providers) {
1287
+ function buildHeaderIndex(providers, camouflages, historyCompat) {
1064
1288
  const index = emptyIndex();
1065
1289
  const claimedUserAgents = /* @__PURE__ */ new Map();
1066
1290
  for (const [route, rawProfile] of Object.entries(providers)) {
@@ -1072,6 +1296,8 @@ function buildHeaderIndex(providers) {
1072
1296
  const sendable = sendableHeadersOf(profile) ?? {};
1073
1297
  const hasHeaders = Object.keys(sendable).length > 0;
1074
1298
  const userAgent = Object.entries(sendable).find(([name2]) => name2.toLowerCase() === "user-agent")?.[1];
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;
1075
1301
  const override = {
1076
1302
  origin,
1077
1303
  pathPrefix: pathPrefixOf(baseURL ?? origin),
@@ -1079,7 +1305,9 @@ function buildHeaderIndex(providers) {
1079
1305
  route,
1080
1306
  modelIds: modelIdsOf(profile),
1081
1307
  hasHeaders,
1082
- ...userAgent === void 0 ? {} : { userAgent }
1308
+ ...userAgent === void 0 ? {} : { userAgent },
1309
+ ...camouflage === void 0 ? {} : { camouflage },
1310
+ ...recoversHistory ? { historyCompat: true } : {}
1083
1311
  };
1084
1312
  index.routes.push(override);
1085
1313
  if (!hasHeaders) continue;
@@ -3186,6 +3414,143 @@ function parseBalancePayload(text) {
3186
3414
  return readingOf(body);
3187
3415
  }
3188
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
+
3189
3554
  // src/headers-fetch.ts
3190
3555
  var REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.fetch-overrides");
3191
3556
  var DISPATCH_REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.dispatch-overrides");
@@ -3261,6 +3626,9 @@ function passthroughInit(input, init) {
3261
3626
  headers.delete(WIRE_DISPATCH_HEADER);
3262
3627
  return { ...init, headers };
3263
3628
  }
3629
+ function textByteLength(text) {
3630
+ return new TextEncoder().encode(text).byteLength;
3631
+ }
3264
3632
  function makeWrapper(base, entries) {
3265
3633
  return async function fetchWithProviderHeaders(input, init) {
3266
3634
  const url = requestUrlOf(input);
@@ -3304,6 +3672,9 @@ function makeWrapper(base, entries) {
3304
3672
  if (override === void 0) return base(input, passthroughInit(input, init));
3305
3673
  const patched = seedHeaders(input, init);
3306
3674
  let hasPatch = false;
3675
+ if (override.camouflage !== void 0 && applyCamouflageHeaders(patched, override.camouflage)) {
3676
+ hasPatch = true;
3677
+ }
3307
3678
  if (override.hasHeaders) {
3308
3679
  for (const [name2, value] of Object.entries(override.headers)) {
3309
3680
  try {
@@ -3313,17 +3684,42 @@ function makeWrapper(base, entries) {
3313
3684
  }
3314
3685
  }
3315
3686
  }
3316
- const attempt = (keyValue) => {
3687
+ let camouflageBody;
3688
+ if (override.camouflage === "claude") {
3689
+ const text = await bodyTextOf(input, init);
3690
+ if (text !== void 0) {
3691
+ camouflageBody = patchCamouflageBody(text, "claude", url);
3692
+ if (camouflageBody !== void 0) hasPatch = true;
3693
+ }
3694
+ }
3695
+ const attempt = (keyValue, body = camouflageBody) => {
3317
3696
  const headers = new Headers(patched);
3318
3697
  if (keyValue !== void 0) applyKeyToHeaders(headers, keyValue);
3698
+ if (body !== void 0) {
3699
+ headers.set("content-length", String(textByteLength(body)));
3700
+ if (typeof Request !== "undefined" && input instanceof Request) {
3701
+ try {
3702
+ return base(new Request(input.clone(), { ...init, body, headers }), { ...init, body, headers });
3703
+ } catch {
3704
+ }
3705
+ } else {
3706
+ return base(input, { ...init, body, headers });
3707
+ }
3708
+ }
3319
3709
  if (typeof Request !== "undefined" && input instanceof Request) {
3320
3710
  return base(new Request(input.clone(), { headers }), { ...init, headers });
3321
3711
  }
3322
3712
  return base(input, { ...init, headers });
3323
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
+ };
3324
3720
  if (patched.get(WIRE_DISPATCH_HEADER) === "1") {
3325
3721
  patched.delete(WIRE_DISPATCH_HEADER);
3326
- return attempt(void 0);
3722
+ return sendAttempt(void 0);
3327
3723
  }
3328
3724
  const resolved = keyed ? await entry.keys({ route: override.route, model }) : [];
3329
3725
  const keyCandidates = restLast(
@@ -3365,7 +3761,9 @@ function makeWrapper(base, entries) {
3365
3761
  } catch {
3366
3762
  }
3367
3763
  }
3368
- 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
+ }
3369
3767
  const failureBody = async (response) => {
3370
3768
  try {
3371
3769
  return await readBoundedText(response, 4096);
@@ -3380,10 +3778,9 @@ function makeWrapper(base, entries) {
3380
3778
  const restKey = kind === "unserved" ? restKeyOf(override.route, candidate.ref, model) : restKeyOf(override.route, candidate.ref);
3381
3779
  keyRest.note(restKey, kind, retryAfterMs === void 0 ? void 0 : { retryAfterMs });
3382
3780
  };
3383
- const callerAborted = () => init?.signal?.aborted === true || typeof Request !== "undefined" && input instanceof Request && input.signal.aborted;
3384
3781
  if (keyCandidates.length <= 1) {
3385
3782
  const solo = keyCandidates[0];
3386
- const response = await attempt(solo?.value);
3783
+ const response = await sendAttempt(solo?.value);
3387
3784
  if (solo !== void 0) {
3388
3785
  if (response.status < 400) {
3389
3786
  clearRest(keyRest, override.route, solo.ref, model);
@@ -3404,7 +3801,7 @@ function makeWrapper(base, entries) {
3404
3801
  const candidate = keyCandidates[index];
3405
3802
  let response;
3406
3803
  try {
3407
- response = await attempt(candidate.value);
3804
+ response = await sendAttempt(candidate.value);
3408
3805
  } catch (error) {
3409
3806
  if (callerAborted()) throw error;
3410
3807
  lastFailure = error;
@@ -3420,6 +3817,7 @@ function makeWrapper(base, entries) {
3420
3817
  clearRest(keyRest, override.route, candidate.ref, model);
3421
3818
  return response;
3422
3819
  }
3820
+ if (response.status >= 500 && isHistoryStateMismatch(bodyText)) return response;
3423
3821
  const kind = classifyFailure(response.status, bodyText);
3424
3822
  if (kind === "unserved") unserved += 1;
3425
3823
  chargeFailure(candidate, response, kind);
@@ -3597,11 +3995,49 @@ function routeOverrideOf(source, model) {
3597
3995
  return void 0;
3598
3996
  }
3599
3997
  }
3998
+ function withCamouflageHeaders(merged, preset) {
3999
+ const identity = camouflageHeaders(preset);
4000
+ const present = new Set(Object.keys(merged).map((name2) => name2.toLowerCase()));
4001
+ const next = { ...merged };
4002
+ for (const [name2, value] of Object.entries(identity)) {
4003
+ if (!present.has(name2)) next[name2] = value;
4004
+ }
4005
+ next["user-agent"] = identity["user-agent"];
4006
+ return next;
4007
+ }
4008
+ function withClaudeIdentityContext(context) {
4009
+ if (!isRecord(context)) return context;
4010
+ const systemPrompt = context["systemPrompt"];
4011
+ if (typeof systemPrompt === "string") {
4012
+ if (systemPrompt.startsWith("You are Claude Code")) return context;
4013
+ return { ...context, systemPrompt: `${CLAUDE_CODE_SYSTEM_TEXT}
4014
+
4015
+ ${systemPrompt}` };
4016
+ }
4017
+ if (systemPrompt === void 0 || systemPrompt === null) {
4018
+ return { ...context, systemPrompt: CLAUDE_CODE_SYSTEM_TEXT };
4019
+ }
4020
+ return context;
4021
+ }
3600
4022
  function errorTextOf(event) {
3601
4023
  const error = isRecord(event["error"]) ? event["error"] : void 0;
3602
4024
  const parts = [error?.["message"], error?.["errorMessage"], event["reason"]];
3603
4025
  return parts.filter((part) => typeof part === "string").join(" ");
3604
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
+ }
3605
4041
  function modelsProxyOf(models, source) {
3606
4042
  return new Proxy(models, {
3607
4043
  get(target, property, receiver) {
@@ -3620,7 +4056,8 @@ function modelsProxyOf(models, source) {
3620
4056
  const transformHeaders = async (headers) => {
3621
4057
  const merged = existing === void 0 ? headers : await existing(headers);
3622
4058
  const override = routeOverrideOf(source, model);
3623
- return override?.hasHeaders ? { ...merged, ...override.headers } : merged;
4059
+ const identified = override?.camouflage === void 0 ? merged : withCamouflageHeaders(merged, override.camouflage);
4060
+ return override?.hasHeaders ? { ...identified, ...override.headers } : identified;
3624
4061
  };
3625
4062
  const markedTransformHeaders = async (headers) => ({
3626
4063
  ...await transformHeaders(headers),
@@ -3639,7 +4076,7 @@ function modelsProxyOf(models, source) {
3639
4076
  if (route === void 0) return Promise.resolve([]);
3640
4077
  return Promise.resolve(keyResolver({ route, model: modelId })).catch(() => []);
3641
4078
  };
3642
- const startAttempt = async (candidate, avoid) => {
4079
+ const startAttempt = async (candidate, avoid, requestContext = context) => {
3643
4080
  const api = typeof modelObject["api"] === "string" ? modelObject["api"] : "openai-completions";
3644
4081
  const protocol = wireOf(candidate, api, modelId, avoid);
3645
4082
  const honoured = isHonoured(candidate, api);
@@ -3648,7 +4085,7 @@ function modelsProxyOf(models, source) {
3648
4085
  const baseUrl = protocol === "anthropic-messages" ? anthropicRequestBaseUrl(selectedBaseUrl) : selectedBaseUrl;
3649
4086
  const switched = protocol !== api || baseUrl !== modelObject["baseUrl"];
3650
4087
  if (!switched) {
3651
- return streamSimple.call(target, model, context, {
4088
+ return streamSimple.call(target, model, requestContext, {
3652
4089
  ...options,
3653
4090
  apiKey: candidate.value,
3654
4091
  transformHeaders: markedTransformHeaders
@@ -3656,7 +4093,15 @@ function modelsProxyOf(models, source) {
3656
4093
  }
3657
4094
  const mergedHeaders = await transformHeaders(isRecord(options["headers"]) ? options["headers"] : {});
3658
4095
  const implementation = await loadProtocol(protocol);
3659
- const dispatchedContext = await normalizeDispatchedContext(context);
4096
+ const switchedToClaude = protocol === "anthropic-messages" && routeOverrideOf(source, model)?.camouflage === "claude";
4097
+ const normalized2 = await normalizeDispatchedContext(requestContext);
4098
+ const dispatchedContext = switchedToClaude ? withClaudeIdentityContext(normalized2) : normalized2;
4099
+ const existingMetadata = isRecord(options["metadata"]) ? options["metadata"] : void 0;
4100
+ const suppliedUserId = existingMetadata?.["user_id"];
4101
+ const metadata = switchedToClaude ? {
4102
+ ...existingMetadata ?? {},
4103
+ user_id: typeof suppliedUserId === "string" && suppliedUserId.length > 0 ? suppliedUserId : camouflageClaudeUserId()
4104
+ } : void 0;
3660
4105
  return implementation.streamSimple(
3661
4106
  { ...modelObject, api: protocol, baseUrl },
3662
4107
  dispatchedContext,
@@ -3664,6 +4109,7 @@ function modelsProxyOf(models, source) {
3664
4109
  ...options,
3665
4110
  apiKey: candidate.value,
3666
4111
  headers: { ...mergedHeaders, [WIRE_DISPATCH_HEADER]: "1" },
4112
+ ...metadata === void 0 ? {} : { metadata },
3667
4113
  transformHeaders: void 0
3668
4114
  }
3669
4115
  );
@@ -3689,42 +4135,76 @@ function modelsProxyOf(models, source) {
3689
4135
  isResting: (candidate) => isRestingFor(keyRest, route ?? "", candidate.ref, modelId, Date.now())
3690
4136
  });
3691
4137
  recordRoutePlan(route ?? "", plan, { model: modelId });
4138
+ const recoversHistory = routeOverrideOf(source, model)?.historyCompat === true;
3692
4139
  const wireOfAttempt = (candidate) => plan.entries.find((entry) => entry.candidate === candidate)?.wire ?? wireOf(candidate, api, modelId, avoidWire);
3693
4140
  const restKeyFor = (candidate, kind) => kind === "unserved" && modelId !== void 0 ? restKeyOf(route ?? "", candidate.ref, modelId) : restKeyOf(route ?? "", candidate.ref);
3694
4141
  let lastErrorEvent;
3695
4142
  let lastError;
3696
4143
  for (const candidate of plan.ordered) {
3697
- let stream;
3698
- try {
3699
- stream = await startAttempt(candidate, avoidWire);
3700
- } catch (error) {
3701
- lastError = error;
3702
- if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
3703
- const kind = classifyFailure(void 0, error instanceof Error ? error.message : "") ?? "refused";
3704
- keyRest.note(restKeyFor(candidate, kind), kind);
3705
- continue;
3706
- }
3707
- let committed = false;
3708
- let failed = false;
3709
- for await (const event of stream) {
3710
- const type = isRecord(event) ? event["type"] : void 0;
3711
- if (!committed) {
3712
- if (type === "error") {
3713
- lastErrorEvent = event;
3714
- failed = true;
3715
- if (candidate.protocol === void 0) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate));
3716
- const kind = classifyFailure(void 0, errorTextOf(event)) ?? "refused";
3717
- keyRest.note(restKeyFor(candidate, kind), kind);
3718
- 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));
3719
4195
  }
3720
- committed = true;
3721
- clearRest(keyRest, route ?? "", candidate.ref, modelId);
3722
- rememberWireFact(servedWire, servedKey, wireOfAttempt(candidate));
4196
+ yield event;
4197
+ if (isContentEvent(type)) contentStarted = true;
3723
4198
  }
3724
- yield event;
4199
+ if (retried) continue;
4200
+ if (historyExhausted) {
4201
+ if (lastErrorEvent !== void 0) yield lastErrorEvent;
4202
+ return;
4203
+ }
4204
+ if (failed) break;
4205
+ return;
3725
4206
  }
3726
- if (failed) continue;
3727
- return;
4207
+ if (setupFailed) continue;
3728
4208
  }
3729
4209
  if (lastErrorEvent !== void 0) {
3730
4210
  yield lastErrorEvent;
@@ -3927,9 +4407,9 @@ function installPiAiHeaderTransforms(llm, source) {
3927
4407
  }
3928
4408
 
3929
4409
  // src/headers-conflict.ts
3930
- import { existsSync, readFileSync as readFileSync4 } from "node:fs";
4410
+ import { existsSync, readFileSync as readFileSync6 } from "node:fs";
3931
4411
  import { createRequire } from "node:module";
3932
- import { dirname as dirname4, join as join4, resolve as resolve2 } from "node:path";
4412
+ import { dirname as dirname6, join as join6, resolve as resolve2 } from "node:path";
3933
4413
  var SIBLING_PACKAGES = [
3934
4414
  "dsh-client-masquerade",
3935
4415
  "dsh-llm-headers",
@@ -3941,20 +4421,20 @@ function searchRoots() {
3941
4421
  const roots = /* @__PURE__ */ new Set();
3942
4422
  const entry = process.argv[1];
3943
4423
  if (typeof entry === "string" && entry.length > 0) {
3944
- let dir = dirname4(resolve2(entry));
4424
+ let dir = dirname6(resolve2(entry));
3945
4425
  for (let depth = 0; depth < 8; depth += 1) {
3946
- roots.add(join4(dir, "node_modules"));
3947
- const parent = dirname4(dir);
4426
+ roots.add(join6(dir, "node_modules"));
4427
+ const parent = dirname6(dir);
3948
4428
  if (parent === dir) break;
3949
4429
  dir = parent;
3950
4430
  }
3951
4431
  }
3952
- roots.add(join4(process.cwd(), "node_modules"));
4432
+ roots.add(join6(process.cwd(), "node_modules"));
3953
4433
  try {
3954
4434
  const require2 = createRequire(import.meta.url);
3955
4435
  for (const name2 of SIBLING_PACKAGES) {
3956
4436
  try {
3957
- roots.add(join4(dirname4(dirname4(dirname4(require2.resolve(`${name2}/package.json`)))), "node_modules"));
4437
+ roots.add(join6(dirname6(dirname6(dirname6(require2.resolve(`${name2}/package.json`)))), "node_modules"));
3958
4438
  } catch {
3959
4439
  }
3960
4440
  }
@@ -3963,14 +4443,14 @@ function searchRoots() {
3963
4443
  return [...roots];
3964
4444
  }
3965
4445
  function findAdapterFile() {
3966
- const relative = join4("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
4446
+ const relative = join6("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
3967
4447
  const candidates = [];
3968
4448
  try {
3969
4449
  const require2 = createRequire(import.meta.url);
3970
4450
  candidates.push(require2.resolve("@deepseek-ai/dsh-llm-pi-ai"));
3971
4451
  } catch {
3972
4452
  }
3973
- for (const root of searchRoots()) candidates.push(join4(root, relative));
4453
+ for (const root of searchRoots()) candidates.push(join6(root, relative));
3974
4454
  for (const candidate of candidates) {
3975
4455
  if (existsSync(candidate)) return candidate;
3976
4456
  }
@@ -3981,7 +4461,7 @@ function adapterSourcePatched(source) {
3981
4461
  }
3982
4462
  function adapterPatchState(path) {
3983
4463
  try {
3984
- return adapterSourcePatched(readFileSync4(path, "utf8")) ? "patched" : "stock";
4464
+ return adapterSourcePatched(readFileSync6(path, "utf8")) ? "patched" : "stock";
3985
4465
  } catch {
3986
4466
  return "unknown";
3987
4467
  }
@@ -3992,8 +4472,8 @@ function findSiblings() {
3992
4472
  for (const root of searchRoots()) {
3993
4473
  for (const name2 of SIBLING_PACKAGES) {
3994
4474
  if (seen.has(name2)) continue;
3995
- const dir = join4(root, name2);
3996
- const manifest = join4(dir, "package.json");
4475
+ const dir = join6(root, name2);
4476
+ const manifest = join6(dir, "package.json");
3997
4477
  if (!existsSync(manifest)) continue;
3998
4478
  seen.add(name2);
3999
4479
  found.push({ name: name2, path: dir });
@@ -4025,8 +4505,8 @@ function detectHeaderConflicts() {
4025
4505
  }
4026
4506
 
4027
4507
  // src/image/config.ts
4028
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "node:fs";
4029
- import { dirname as dirname5, join as join5 } 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";
4030
4510
 
4031
4511
  // src/image/sizes.ts
4032
4512
  var IMAGE_SIZE_TIERS = [
@@ -4043,7 +4523,7 @@ var IMAGE_FALLBACK_PARAMS = {
4043
4523
  responseFormat: "b64_json"
4044
4524
  };
4045
4525
  function imageConfigFilePath(home = harnessHome()) {
4046
- return join5(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
4526
+ return join7(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
4047
4527
  }
4048
4528
  function emptyImageConfig(now = () => /* @__PURE__ */ new Date()) {
4049
4529
  return {
@@ -4144,7 +4624,7 @@ function parseImageModel(raw) {
4144
4624
  function readImageConfig(file = imageConfigFilePath()) {
4145
4625
  let text;
4146
4626
  try {
4147
- text = readFileSync5(file, "utf8");
4627
+ text = readFileSync7(file, "utf8");
4148
4628
  } catch {
4149
4629
  return emptyImageConfig();
4150
4630
  }
@@ -4155,15 +4635,15 @@ function readImageConfig(file = imageConfigFilePath()) {
4155
4635
  }
4156
4636
  }
4157
4637
  function writeImageConfig(document, file = imageConfigFilePath()) {
4158
- mkdirSync4(dirname5(file), { recursive: true });
4638
+ mkdirSync6(dirname7(file), { recursive: true });
4159
4639
  const temporary = `${file}.${process.pid}.tmp`;
4160
- writeFileSync4(temporary, `${JSON.stringify(document, null, 2)}
4640
+ writeFileSync6(temporary, `${JSON.stringify(document, null, 2)}
4161
4641
  `, "utf8");
4162
4642
  try {
4163
- renameSync4(temporary, file);
4643
+ renameSync6(temporary, file);
4164
4644
  } catch (error) {
4165
4645
  try {
4166
- unlinkSync4(temporary);
4646
+ unlinkSync6(temporary);
4167
4647
  } catch {
4168
4648
  }
4169
4649
  throw error;
@@ -4251,8 +4731,8 @@ function updateImageConfig(mutate, file = imageConfigFilePath()) {
4251
4731
  }
4252
4732
 
4253
4733
  // src/image/generate.ts
4254
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5, existsSync as existsSync2, statSync } from "node:fs";
4255
- import { dirname as dirname6, join as join6, 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";
4256
4736
 
4257
4737
  // src/image/deadline.ts
4258
4738
  function createImageDeadline(timeoutMs, caller, errorFor) {
@@ -4492,19 +4972,19 @@ function outputDirOf(deps, config) {
4492
4972
  const home = deps.home?.() ?? harnessHome();
4493
4973
  const dir = config.outputDir;
4494
4974
  if (/^([A-Za-z]:[\\/]|\/)/.test(dir)) return dir;
4495
- return join6(home, "dsh-model-think-level", dir);
4975
+ return join8(home, "dsh-model-think-level", dir);
4496
4976
  }
4497
4977
  function destinationOf(dir, slug, now) {
4498
- const base = join6(dir, `${slug}-${now()}.png`);
4978
+ const base = join8(dir, `${slug}-${now()}.png`);
4499
4979
  if (!existsSync2(base)) return base;
4500
4980
  for (let index = 2; ; index += 1) {
4501
- const candidate = join6(dir, `${slug}-${now()}-${index}.png`);
4981
+ const candidate = join8(dir, `${slug}-${now()}-${index}.png`);
4502
4982
  if (!existsSync2(candidate)) return candidate;
4503
4983
  }
4504
4984
  }
4505
4985
  function resolveDestination(requested, fallbackDir, slug, now) {
4506
4986
  if (requested === void 0 || requested.trim().length === 0) {
4507
- mkdirSync5(fallbackDir, { recursive: true });
4987
+ mkdirSync7(fallbackDir, { recursive: true });
4508
4988
  return destinationOf(fallbackDir, slug, now);
4509
4989
  }
4510
4990
  const target = resolve3(requested.trim());
@@ -4514,10 +4994,10 @@ function resolveDestination(requested, fallbackDir, slug, now) {
4514
4994
  } catch {
4515
4995
  }
4516
4996
  if (isDir || /[\\/]$/.test(target) || !target.toLowerCase().endsWith(".png")) {
4517
- mkdirSync5(target, { recursive: true });
4997
+ mkdirSync7(target, { recursive: true });
4518
4998
  return destinationOf(target, slug, now);
4519
4999
  }
4520
- mkdirSync5(dirname6(target), { recursive: true });
5000
+ mkdirSync7(dirname8(target), { recursive: true });
4521
5001
  if (!existsSync2(target)) return target;
4522
5002
  for (let index = 2; ; index += 1) {
4523
5003
  const candidate = target.replace(/\.png$/i, `-${index}.png`);
@@ -4607,7 +5087,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4607
5087
  const absolute = resolve3(path);
4608
5088
  if (!existsSync2(absolute)) throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4609
5089
  try {
4610
- return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync6(absolute), mime: mimeOfPath(absolute) };
5090
+ return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync8(absolute), mime: mimeOfPath(absolute) };
4611
5091
  } catch {
4612
5092
  throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4613
5093
  }
@@ -4684,7 +5164,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4684
5164
  const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now);
4685
5165
  const bytes = Uint8Array.from(atob(data), (ch) => ch.charCodeAt(0));
4686
5166
  deadline.check();
4687
- writeFileSync5(filePath, bytes);
5167
+ writeFileSync7(filePath, bytes);
4688
5168
  images.push({ filePath, data });
4689
5169
  }
4690
5170
  deadline.check();
@@ -5114,19 +5594,19 @@ function imageToolHint(config) {
5114
5594
  }
5115
5595
 
5116
5596
  // src/image/legacy-cleanup.ts
5117
- import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync7, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync6 } from "node:fs";
5118
- import { dirname as dirname7, join as join7 } 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";
5119
5599
  var MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`;
5120
5600
  var MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`;
5121
5601
  function resolveLegacyPatchFile(home = harnessHome()) {
5122
5602
  const explicit = process.env["DSH_PROFILE"];
5123
- if (explicit !== void 0 && explicit.length > 0) return join7(home, "profiles", explicit, "cordis.patch.yml");
5124
- const profilesDir = join7(home, "profiles");
5603
+ if (explicit !== void 0 && explicit.length > 0) return join9(home, "profiles", explicit, "cordis.patch.yml");
5604
+ const profilesDir = join9(home, "profiles");
5125
5605
  try {
5126
5606
  if (existsSync3(profilesDir)) {
5127
5607
  const candidates = [];
5128
5608
  for (const name2 of readdirSync2(profilesDir)) {
5129
- const file = join7(profilesDir, name2, "cordis.patch.yml");
5609
+ const file = join9(profilesDir, name2, "cordis.patch.yml");
5130
5610
  if (!existsSync3(file)) continue;
5131
5611
  candidates.push({ file, mtime: statSync2(file).mtimeMs });
5132
5612
  }
@@ -5135,8 +5615,8 @@ function resolveLegacyPatchFile(home = harnessHome()) {
5135
5615
  }
5136
5616
  } catch {
5137
5617
  }
5138
- if (existsSync3(join7(home, "cordis.patch.yml"))) return join7(home, "cordis.patch.yml");
5139
- return join7(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");
5140
5620
  }
5141
5621
  function markerRange(text) {
5142
5622
  const start = text.indexOf(MARK_BEGIN);
@@ -5197,7 +5677,7 @@ function mtimeOf(patchFile) {
5197
5677
  var ModifiedError = class extends Error {
5198
5678
  };
5199
5679
  function spliceOnce(patchFile, mtimeMs) {
5200
- const current = readFileSync7(patchFile, "utf8");
5680
+ const current = readFileSync9(patchFile, "utf8");
5201
5681
  const range = legacyRange(current);
5202
5682
  if (range === void 0) return;
5203
5683
  let next = current.slice(0, range.start) + current.slice(range.end);
@@ -5211,9 +5691,9 @@ function spliceOnce(patchFile, mtimeMs) {
5211
5691
  } catch {
5212
5692
  }
5213
5693
  }
5214
- mkdirSync6(dirname7(patchFile), { recursive: true });
5215
- writeFileSync6(patchFile, next, "utf8");
5216
- const written = readFileSync7(patchFile, "utf8");
5694
+ mkdirSync8(dirname9(patchFile), { recursive: true });
5695
+ writeFileSync8(patchFile, next, "utf8");
5696
+ const written = readFileSync9(patchFile, "utf8");
5217
5697
  if (written !== next) throw new Error("the patch file did not hold the written bytes after the write");
5218
5698
  }
5219
5699
  function removeLegacyImageMcpPatch(home, patchFile) {
@@ -5225,7 +5705,7 @@ function removeLegacyImageMcpPatch(home, patchFile) {
5225
5705
  }
5226
5706
  let text;
5227
5707
  try {
5228
- text = readFileSync7(file, "utf8");
5708
+ text = readFileSync9(file, "utf8");
5229
5709
  } catch {
5230
5710
  return void 0;
5231
5711
  }
@@ -5398,9 +5878,9 @@ function backfillRolePin(model, providers, route) {
5398
5878
  }
5399
5879
 
5400
5880
  // src/fingerprint/bank.ts
5401
- import { existsSync as existsSync4, readFileSync as readFileSync8 } from "node:fs";
5881
+ import { existsSync as existsSync4, readFileSync as readFileSync10 } from "node:fs";
5402
5882
  import { fileURLToPath } from "node:url";
5403
- import { dirname as dirname8, join as join8 } from "node:path";
5883
+ import { dirname as dirname10, join as join10 } from "node:path";
5404
5884
 
5405
5885
  // src/fingerprint/core.ts
5406
5886
  var VALUE_MIN = 1;
@@ -5685,10 +6165,10 @@ function parseBank(raw) {
5685
6165
  }
5686
6166
  function bankCandidates() {
5687
6167
  const candidates = [];
5688
- let dir = dirname8(fileURLToPath(import.meta.url));
6168
+ let dir = dirname10(fileURLToPath(import.meta.url));
5689
6169
  for (let depth = 0; depth < 5; depth += 1) {
5690
- candidates.push(join8(dir, "assets", "unified_bank.json"));
5691
- const parent = dirname8(dir);
6170
+ candidates.push(join10(dir, "assets", "unified_bank.json"));
6171
+ const parent = dirname10(dir);
5692
6172
  if (parent === dir) break;
5693
6173
  dir = parent;
5694
6174
  }
@@ -5705,7 +6185,7 @@ function bankPath() {
5705
6185
  var cached;
5706
6186
  function loadBankSync() {
5707
6187
  if (cached !== void 0) return cached;
5708
- cached = parseBank(JSON.parse(readFileSync8(bankPath(), "utf8")));
6188
+ cached = parseBank(JSON.parse(readFileSync10(bankPath(), "utf8")));
5709
6189
  return cached;
5710
6190
  }
5711
6191
  function summarizeBank(bank) {
@@ -5974,8 +6454,8 @@ async function runChallenge(options) {
5974
6454
  }
5975
6455
 
5976
6456
  // src/fingerprint/store.ts
5977
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync as renameSync5, unlinkSync as unlinkSync5, writeFileSync as writeFileSync7 } from "node:fs";
5978
- import { dirname as dirname9, join as join9 } 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";
5979
6459
  var STATUSES = /* @__PURE__ */ new Set(["identified", "doubtful", "failed"]);
5980
6460
  function emptyFingerprintStore(bankBuiltAt2 = "") {
5981
6461
  return { version: 1, bankBuiltAt: bankBuiltAt2, records: {} };
@@ -5984,7 +6464,7 @@ function recordKeyOf(provider, model) {
5984
6464
  return `${provider}\0${model}`;
5985
6465
  }
5986
6466
  function fingerprintFilePath(home = harnessHome()) {
5987
- return join9(home, "dsh-model-think-level", "fingerprint.json");
6467
+ return join11(home, "dsh-model-think-level", "fingerprint.json");
5988
6468
  }
5989
6469
  function finiteNumber(value, fallback) {
5990
6470
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
@@ -6102,7 +6582,7 @@ function parseFingerprintStore(raw, bankBuiltAt2 = "") {
6102
6582
  function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
6103
6583
  let text;
6104
6584
  try {
6105
- text = readFileSync9(file, "utf8");
6585
+ text = readFileSync11(file, "utf8");
6106
6586
  } catch (error) {
6107
6587
  if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
6108
6588
  return emptyFingerprintStore(bankBuiltAt2);
@@ -6118,15 +6598,15 @@ function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
6118
6598
  return parseFingerprintStore(raw, bankBuiltAt2);
6119
6599
  }
6120
6600
  function writeFingerprintStore(document, file = fingerprintFilePath()) {
6121
- mkdirSync7(dirname9(file), { recursive: true });
6601
+ mkdirSync9(dirname11(file), { recursive: true });
6122
6602
  const temporary = `${file}.${process.pid}.tmp`;
6123
- writeFileSync7(temporary, `${JSON.stringify(document, null, 2)}
6603
+ writeFileSync9(temporary, `${JSON.stringify(document, null, 2)}
6124
6604
  `, "utf8");
6125
6605
  try {
6126
- renameSync5(temporary, file);
6606
+ renameSync7(temporary, file);
6127
6607
  } catch (error) {
6128
6608
  try {
6129
- unlinkSync5(temporary);
6609
+ unlinkSync7(temporary);
6130
6610
  } catch {
6131
6611
  }
6132
6612
  throw error;
@@ -7015,7 +7495,9 @@ function apply(ctx, config = {}) {
7015
7495
  headerRetryTimers.add(timer);
7016
7496
  };
7017
7497
  const refreshHeaders = () => {
7018
- if (!resolved.uaOverride) {
7498
+ const camouflage = readCamouflage().providers;
7499
+ const historyCompat = readHistoryCompat().providers;
7500
+ if (!resolved.uaOverride && Object.keys(camouflage).length === 0 && Object.keys(historyCompat).length === 0) {
7019
7501
  overlaySource.current = emptyIndex();
7020
7502
  stopHeaderRetries();
7021
7503
  return;
@@ -7028,7 +7510,7 @@ function apply(ctx, config = {}) {
7028
7510
  }
7029
7511
  stopHeaderRetries();
7030
7512
  const providers = isRecord(section) && isRecord(section["providers"]) ? section["providers"] : {};
7031
- overlaySource.current = buildHeaderIndex(providers);
7513
+ overlaySource.current = buildHeaderIndex(providers, camouflage, historyCompat);
7032
7514
  };
7033
7515
  refreshHeaders();
7034
7516
  refreshKeyScopes();
@@ -8133,6 +8615,115 @@ function apply(ctx, config = {}) {
8133
8615
  }),
8134
8616
  "dsh-model-think-level: ui-order route"
8135
8617
  );
8618
+ const requestSeamsInstalled = () => {
8619
+ if (headerOverlayInstalled()) return true;
8620
+ const state = headerBridgeState();
8621
+ return isRecord(state) && typeof state["adaptersPatched"] === "number" && state["adaptersPatched"] > 0;
8622
+ };
8623
+ ctx.effect(
8624
+ () => webServerCtx.webServer.register({
8625
+ kind: "exact",
8626
+ path: CAMOUFLAGE_PATH,
8627
+ handler: async (req, res) => {
8628
+ res.setHeader("cache-control", "no-store");
8629
+ if (!isTrustedRequest(req)) {
8630
+ sendJson(res, 403, { ok: false, error: "forbidden" });
8631
+ return;
8632
+ }
8633
+ if (req.method === "GET") {
8634
+ sendJson(res, 200, {
8635
+ ok: true,
8636
+ data: {
8637
+ presets: CAMOUFLAGE_PRESETS,
8638
+ providers: readCamouflage().providers,
8639
+ installed: requestSeamsInstalled()
8640
+ }
8641
+ });
8642
+ return;
8643
+ }
8644
+ if (req.method !== "POST") {
8645
+ sendJson(res, 405, { ok: false, error: "method not allowed" });
8646
+ return;
8647
+ }
8648
+ const body = await readJsonBody(req, 16384);
8649
+ if (!isRecord(body)) {
8650
+ sendJson(res, 400, { ok: false, error: "the body is not a JSON document" });
8651
+ return;
8652
+ }
8653
+ const route = body["route"];
8654
+ const preset = body["preset"];
8655
+ if (typeof route !== "string" || route.length === 0) {
8656
+ sendJson(res, 400, { ok: false, error: "route is required" });
8657
+ return;
8658
+ }
8659
+ if (preset !== null && !isCamouflagePreset(preset)) {
8660
+ sendJson(res, 400, { ok: false, error: "preset must be codex, claude or null" });
8661
+ return;
8662
+ }
8663
+ try {
8664
+ const document = setRouteCamouflage(route, preset ?? void 0);
8665
+ refreshHeaders();
8666
+ sendJson(res, 200, { ok: true, data: document });
8667
+ } catch (error) {
8668
+ sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
8669
+ }
8670
+ }
8671
+ }),
8672
+ "dsh-model-think-level: camouflage route"
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
+ );
8136
8727
  ctx.effect(
8137
8728
  () => webServerCtx.webServer.register({
8138
8729
  kind: "exact",