@codexhost/cli-linux-arm64 0.23.0 → 0.25.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.
Files changed (60) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +3968 -4082
  4. package/app/console-web.js +6822 -2065
  5. package/app/desktop-controller.mjs +13620 -2977
  6. package/app/host-runtime.mjs +12025 -12636
  7. package/app/plugins/antigravity/plugin.mjs +2382 -1452
  8. package/app/plugins/claude-code/plugin.mjs +2248 -1645
  9. package/app/plugins/codebuddy/plugin.mjs +1753 -1215
  10. package/app/plugins/codex-usage/plugin.mjs +1214 -915
  11. package/app/plugins/copilot/plugin.mjs +1239 -919
  12. package/app/plugins/cursor-cli/plugin.mjs +1549 -1099
  13. package/app/plugins/deepseek-harness/plugin.mjs +1955 -1484
  14. package/app/plugins/devin/plugin.mjs +1295 -978
  15. package/app/plugins/grok/plugin.mjs +1772 -1482
  16. package/app/plugins/hermes/plugin.mjs +1485 -1184
  17. package/app/plugins/kimi-code/plugin.mjs +1388 -1093
  18. package/app/plugins/kiro-cli/plugin.mjs +1349 -1036
  19. package/app/plugins/omp/plugin.mjs +2027 -1420
  20. package/app/plugins/opencode/plugin.mjs +2219 -1844
  21. package/app/plugins/pi/plugin.mjs +1956 -1606
  22. package/app/plugins/qoder/plugin.mjs +1536 -1229
  23. package/app/plugins/qoder-cn/plugin.mjs +1536 -1229
  24. package/app/plugins/qwen-code/plugin.mjs +1490 -1198
  25. package/app/plugins/workbuddy/plugin.mjs +1757 -1221
  26. package/app/plugins/zcode/plugin.mjs +1841 -1072
  27. package/app/renderer-extension.js +12894 -8392
  28. package/app/web/assets/index-CTCFIQbU.css +1 -0
  29. package/app/web/assets/index-DUOvhHbV.js +203 -0
  30. package/app/web/codexhost-settings.js +4811 -36168
  31. package/app/web/index.html +2 -2
  32. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +64 -64
  33. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  34. package/app/web/plugins/deepseek-ai__dsh-api-workspace-controller/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-client-shortcuts/client.js +1 -1
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-approval/client.js +1 -1
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-brand-official/client.js +1 -1
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +74 -74
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +75 -64
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +98 -95
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +1 -1
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  50. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  51. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +3 -3
  52. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +9 -9
  53. package/app/web/sw.js +8 -1
  54. package/app/web-modules/server.mjs +4752 -6790
  55. package/bin/codexhost +0 -0
  56. package/libexec/codexhost-shim +0 -0
  57. package/libexec/codexhost-updater +0 -0
  58. package/package.json +1 -1
  59. package/app/web/assets/index-DJW4bmyx.css +0 -1
  60. package/app/web/assets/index-Dyh1KzAB.js +0 -201
@@ -774,8 +774,8 @@ function cached(getter) {
774
774
  }
775
775
  };
776
776
  }
777
- function nullish(input) {
778
- return input === null || input === void 0;
777
+ function nullish(input2) {
778
+ return input2 === null || input2 === void 0;
779
779
  }
780
780
  function cleanRegex(source) {
781
781
  const start = source.startsWith("^") ? 1 : 0;
@@ -835,10 +835,10 @@ function mergeDefs(...defs) {
835
835
  function cloneDef(schema) {
836
836
  return mergeDefs(schema._zod.def);
837
837
  }
838
- function getElementAtPath(obj, path7) {
839
- if (!path7)
838
+ function getElementAtPath(obj, path8) {
839
+ if (!path8)
840
840
  return obj;
841
- return path7.reduce((acc, key) => acc?.[key], obj);
841
+ return path8.reduce((acc, key) => acc?.[key], obj);
842
842
  }
843
843
  function promiseAllObject(promisesObj) {
844
844
  const keys = Object.keys(promisesObj);
@@ -862,8 +862,8 @@ function randomString(length = 10) {
862
862
  function esc(str) {
863
863
  return JSON.stringify(str);
864
864
  }
865
- function slugify(input) {
866
- return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
865
+ function slugify(input2) {
866
+ return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
867
867
  }
868
868
  var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
869
869
  };
@@ -1247,11 +1247,11 @@ function explicitlyAborted(x, startIndex = 0) {
1247
1247
  }
1248
1248
  return false;
1249
1249
  }
1250
- function prefixIssues(path7, issues) {
1250
+ function prefixIssues(path8, issues) {
1251
1251
  return issues.map((iss) => {
1252
1252
  var _a3;
1253
1253
  (_a3 = iss).path ?? (_a3.path = []);
1254
- iss.path.unshift(path7);
1254
+ iss.path.unshift(path8);
1255
1255
  return iss;
1256
1256
  });
1257
1257
  }
@@ -1268,19 +1268,19 @@ function finalizeIssue(iss, ctx, config2) {
1268
1268
  }
1269
1269
  return rest;
1270
1270
  }
1271
- function getSizableOrigin(input) {
1272
- if (input instanceof Set)
1271
+ function getSizableOrigin(input2) {
1272
+ if (input2 instanceof Set)
1273
1273
  return "set";
1274
- if (input instanceof Map)
1274
+ if (input2 instanceof Map)
1275
1275
  return "map";
1276
- if (input instanceof File)
1276
+ if (input2 instanceof File)
1277
1277
  return "file";
1278
1278
  return "unknown";
1279
1279
  }
1280
- function getLengthableOrigin(input) {
1281
- if (Array.isArray(input))
1280
+ function getLengthableOrigin(input2) {
1281
+ if (Array.isArray(input2))
1282
1282
  return "array";
1283
- if (typeof input === "string")
1283
+ if (typeof input2 === "string")
1284
1284
  return "string";
1285
1285
  return "unknown";
1286
1286
  }
@@ -1306,12 +1306,12 @@ function parsedType(data) {
1306
1306
  return t;
1307
1307
  }
1308
1308
  function issue(...args) {
1309
- const [iss, input, inst] = args;
1309
+ const [iss, input2, inst] = args;
1310
1310
  if (typeof iss === "string") {
1311
1311
  return {
1312
1312
  message: iss,
1313
1313
  code: "custom",
1314
- input,
1314
+ input: input2,
1315
1315
  inst
1316
1316
  };
1317
1317
  }
@@ -1322,8 +1322,8 @@ function cleanEnum(obj) {
1322
1322
  return Number.isNaN(Number.parseInt(k, 10));
1323
1323
  }).map((el) => el[1]);
1324
1324
  }
1325
- function base64ToUint8Array(base643) {
1326
- const binaryString = atob(base643);
1325
+ function base64ToUint8Array(base644) {
1326
+ const binaryString = atob(base644);
1327
1327
  const bytes = new Uint8Array(binaryString.length);
1328
1328
  for (let i = 0; i < binaryString.length; i++) {
1329
1329
  bytes[i] = binaryString.charCodeAt(i);
@@ -1338,9 +1338,9 @@ function uint8ArrayToBase64(bytes) {
1338
1338
  return btoa(binaryString);
1339
1339
  }
1340
1340
  function base64urlToUint8Array(base64url3) {
1341
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1342
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1343
- return base64ToUint8Array(base643 + padding);
1341
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1342
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1343
+ return base64ToUint8Array(base644 + padding);
1344
1344
  }
1345
1345
  function uint8ArrayToBase64url(bytes) {
1346
1346
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -1398,16 +1398,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1398
1398
  }
1399
1399
  function formatError(error51, mapper = (issue2) => issue2.message) {
1400
1400
  const fieldErrors = { _errors: [] };
1401
- const processError = (error52, path7 = []) => {
1401
+ const processError = (error52, path8 = []) => {
1402
1402
  for (const issue2 of error52.issues) {
1403
1403
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1404
- issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1404
+ issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
1405
1405
  } else if (issue2.code === "invalid_key") {
1406
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1406
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1407
1407
  } else if (issue2.code === "invalid_element") {
1408
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1408
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1409
1409
  } else {
1410
- const fullpath = [...path7, ...issue2.path];
1410
+ const fullpath = [...path8, ...issue2.path];
1411
1411
  if (fullpath.length === 0) {
1412
1412
  fieldErrors._errors.push(mapper(issue2));
1413
1413
  } else {
@@ -1434,17 +1434,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1434
1434
  }
1435
1435
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1436
1436
  const result = { errors: [] };
1437
- const processError = (error52, path7 = []) => {
1437
+ const processError = (error52, path8 = []) => {
1438
1438
  var _a3, _b;
1439
1439
  for (const issue2 of error52.issues) {
1440
1440
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1441
- issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1441
+ issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
1442
1442
  } else if (issue2.code === "invalid_key") {
1443
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1443
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1444
1444
  } else if (issue2.code === "invalid_element") {
1445
- processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1445
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
1446
1446
  } else {
1447
- const fullpath = [...path7, ...issue2.path];
1447
+ const fullpath = [...path8, ...issue2.path];
1448
1448
  if (fullpath.length === 0) {
1449
1449
  result.errors.push(mapper(issue2));
1450
1450
  continue;
@@ -1476,8 +1476,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1476
1476
  }
1477
1477
  function toDotPath(_path) {
1478
1478
  const segs = [];
1479
- const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1480
- for (const seg of path7) {
1479
+ const path8 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1480
+ for (const seg of path8) {
1481
1481
  if (typeof seg === "number")
1482
1482
  segs.push(`[${seg}]`);
1483
1483
  else if (typeof seg === "symbol")
@@ -1855,23 +1855,23 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
1855
1855
  bag.pattern = integer;
1856
1856
  });
1857
1857
  inst._zod.check = (payload) => {
1858
- const input = payload.value;
1858
+ const input2 = payload.value;
1859
1859
  if (isInt) {
1860
- if (!Number.isInteger(input)) {
1860
+ if (!Number.isInteger(input2)) {
1861
1861
  payload.issues.push({
1862
1862
  expected: origin,
1863
1863
  format: def.format,
1864
1864
  code: "invalid_type",
1865
1865
  continue: false,
1866
- input,
1866
+ input: input2,
1867
1867
  inst
1868
1868
  });
1869
1869
  return;
1870
1870
  }
1871
- if (!Number.isSafeInteger(input)) {
1872
- if (input > 0) {
1871
+ if (!Number.isSafeInteger(input2)) {
1872
+ if (input2 > 0) {
1873
1873
  payload.issues.push({
1874
- input,
1874
+ input: input2,
1875
1875
  code: "too_big",
1876
1876
  maximum: Number.MAX_SAFE_INTEGER,
1877
1877
  note: "Integers must be within the safe integer range.",
@@ -1882,7 +1882,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
1882
1882
  });
1883
1883
  } else {
1884
1884
  payload.issues.push({
1885
- input,
1885
+ input: input2,
1886
1886
  code: "too_small",
1887
1887
  minimum: Number.MIN_SAFE_INTEGER,
1888
1888
  note: "Integers must be within the safe integer range.",
@@ -1895,10 +1895,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
1895
1895
  return;
1896
1896
  }
1897
1897
  }
1898
- if (input < minimum) {
1898
+ if (input2 < minimum) {
1899
1899
  payload.issues.push({
1900
1900
  origin: "number",
1901
- input,
1901
+ input: input2,
1902
1902
  code: "too_small",
1903
1903
  minimum,
1904
1904
  inclusive: true,
@@ -1906,10 +1906,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
1906
1906
  continue: !def.abort
1907
1907
  });
1908
1908
  }
1909
- if (input > maximum) {
1909
+ if (input2 > maximum) {
1910
1910
  payload.issues.push({
1911
1911
  origin: "number",
1912
- input,
1912
+ input: input2,
1913
1913
  code: "too_big",
1914
1914
  maximum,
1915
1915
  inclusive: true,
@@ -1929,11 +1929,11 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat"
1929
1929
  bag.maximum = maximum;
1930
1930
  });
1931
1931
  inst._zod.check = (payload) => {
1932
- const input = payload.value;
1933
- if (input < minimum) {
1932
+ const input2 = payload.value;
1933
+ if (input2 < minimum) {
1934
1934
  payload.issues.push({
1935
1935
  origin: "bigint",
1936
- input,
1936
+ input: input2,
1937
1937
  code: "too_small",
1938
1938
  minimum,
1939
1939
  inclusive: true,
@@ -1941,10 +1941,10 @@ var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat"
1941
1941
  continue: !def.abort
1942
1942
  });
1943
1943
  }
1944
- if (input > maximum) {
1944
+ if (input2 > maximum) {
1945
1945
  payload.issues.push({
1946
1946
  origin: "bigint",
1947
- input,
1947
+ input: input2,
1948
1948
  code: "too_big",
1949
1949
  maximum,
1950
1950
  inclusive: true,
@@ -1967,16 +1967,16 @@ var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, d
1967
1967
  inst2._zod.bag.maximum = def.maximum;
1968
1968
  });
1969
1969
  inst._zod.check = (payload) => {
1970
- const input = payload.value;
1971
- const size = input.size;
1970
+ const input2 = payload.value;
1971
+ const size = input2.size;
1972
1972
  if (size <= def.maximum)
1973
1973
  return;
1974
1974
  payload.issues.push({
1975
- origin: getSizableOrigin(input),
1975
+ origin: getSizableOrigin(input2),
1976
1976
  code: "too_big",
1977
1977
  maximum: def.maximum,
1978
1978
  inclusive: true,
1979
- input,
1979
+ input: input2,
1980
1980
  inst,
1981
1981
  continue: !def.abort
1982
1982
  });
@@ -1995,16 +1995,16 @@ var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, d
1995
1995
  inst2._zod.bag.minimum = def.minimum;
1996
1996
  });
1997
1997
  inst._zod.check = (payload) => {
1998
- const input = payload.value;
1999
- const size = input.size;
1998
+ const input2 = payload.value;
1999
+ const size = input2.size;
2000
2000
  if (size >= def.minimum)
2001
2001
  return;
2002
2002
  payload.issues.push({
2003
- origin: getSizableOrigin(input),
2003
+ origin: getSizableOrigin(input2),
2004
2004
  code: "too_small",
2005
2005
  minimum: def.minimum,
2006
2006
  inclusive: true,
2007
- input,
2007
+ input: input2,
2008
2008
  inst,
2009
2009
  continue: !def.abort
2010
2010
  });
@@ -2024,13 +2024,13 @@ var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (i
2024
2024
  bag.size = def.size;
2025
2025
  });
2026
2026
  inst._zod.check = (payload) => {
2027
- const input = payload.value;
2028
- const size = input.size;
2027
+ const input2 = payload.value;
2028
+ const size = input2.size;
2029
2029
  if (size === def.size)
2030
2030
  return;
2031
2031
  const tooBig = size > def.size;
2032
2032
  payload.issues.push({
2033
- origin: getSizableOrigin(input),
2033
+ origin: getSizableOrigin(input2),
2034
2034
  ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
2035
2035
  inclusive: true,
2036
2036
  exact: true,
@@ -2053,17 +2053,17 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins
2053
2053
  inst2._zod.bag.maximum = def.maximum;
2054
2054
  });
2055
2055
  inst._zod.check = (payload) => {
2056
- const input = payload.value;
2057
- const length = input.length;
2056
+ const input2 = payload.value;
2057
+ const length = input2.length;
2058
2058
  if (length <= def.maximum)
2059
2059
  return;
2060
- const origin = getLengthableOrigin(input);
2060
+ const origin = getLengthableOrigin(input2);
2061
2061
  payload.issues.push({
2062
2062
  origin,
2063
2063
  code: "too_big",
2064
2064
  maximum: def.maximum,
2065
2065
  inclusive: true,
2066
- input,
2066
+ input: input2,
2067
2067
  inst,
2068
2068
  continue: !def.abort
2069
2069
  });
@@ -2082,17 +2082,17 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins
2082
2082
  inst2._zod.bag.minimum = def.minimum;
2083
2083
  });
2084
2084
  inst._zod.check = (payload) => {
2085
- const input = payload.value;
2086
- const length = input.length;
2085
+ const input2 = payload.value;
2086
+ const length = input2.length;
2087
2087
  if (length >= def.minimum)
2088
2088
  return;
2089
- const origin = getLengthableOrigin(input);
2089
+ const origin = getLengthableOrigin(input2);
2090
2090
  payload.issues.push({
2091
2091
  origin,
2092
2092
  code: "too_small",
2093
2093
  minimum: def.minimum,
2094
2094
  inclusive: true,
2095
- input,
2095
+ input: input2,
2096
2096
  inst,
2097
2097
  continue: !def.abort
2098
2098
  });
@@ -2112,11 +2112,11 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals"
2112
2112
  bag.length = def.length;
2113
2113
  });
2114
2114
  inst._zod.check = (payload) => {
2115
- const input = payload.value;
2116
- const length = input.length;
2115
+ const input2 = payload.value;
2116
+ const length = input2.length;
2117
2117
  if (length === def.length)
2118
2118
  return;
2119
- const origin = getLengthableOrigin(input);
2119
+ const origin = getLengthableOrigin(input2);
2120
2120
  const tooBig = length > def.length;
2121
2121
  payload.issues.push({
2122
2122
  origin,
@@ -2706,8 +2706,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
2706
2706
  function isValidBase64URL(data) {
2707
2707
  if (!base64url.test(data))
2708
2708
  return false;
2709
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
2710
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
2709
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
2710
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
2711
2711
  return isValidBase64(padded);
2712
2712
  }
2713
2713
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -2787,15 +2787,15 @@ var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
2787
2787
  payload.value = Number(payload.value);
2788
2788
  } catch (_) {
2789
2789
  }
2790
- const input = payload.value;
2791
- if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
2790
+ const input2 = payload.value;
2791
+ if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) {
2792
2792
  return payload;
2793
2793
  }
2794
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
2794
+ const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? "Infinity" : void 0 : void 0;
2795
2795
  payload.issues.push({
2796
2796
  expected: "number",
2797
2797
  code: "invalid_type",
2798
- input,
2798
+ input: input2,
2799
2799
  inst,
2800
2800
  ...received ? { received } : {}
2801
2801
  });
@@ -2815,13 +2815,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
2815
2815
  payload.value = Boolean(payload.value);
2816
2816
  } catch (_) {
2817
2817
  }
2818
- const input = payload.value;
2819
- if (typeof input === "boolean")
2818
+ const input2 = payload.value;
2819
+ if (typeof input2 === "boolean")
2820
2820
  return payload;
2821
2821
  payload.issues.push({
2822
2822
  expected: "boolean",
2823
2823
  code: "invalid_type",
2824
- input,
2824
+ input: input2,
2825
2825
  inst
2826
2826
  });
2827
2827
  return payload;
@@ -2854,13 +2854,13 @@ var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, d
2854
2854
  var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
2855
2855
  $ZodType.init(inst, def);
2856
2856
  inst._zod.parse = (payload, _ctx) => {
2857
- const input = payload.value;
2858
- if (typeof input === "symbol")
2857
+ const input2 = payload.value;
2858
+ if (typeof input2 === "symbol")
2859
2859
  return payload;
2860
2860
  payload.issues.push({
2861
2861
  expected: "symbol",
2862
2862
  code: "invalid_type",
2863
- input,
2863
+ input: input2,
2864
2864
  inst
2865
2865
  });
2866
2866
  return payload;
@@ -2871,13 +2871,13 @@ var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) =>
2871
2871
  inst._zod.pattern = _undefined;
2872
2872
  inst._zod.values = /* @__PURE__ */ new Set([void 0]);
2873
2873
  inst._zod.parse = (payload, _ctx) => {
2874
- const input = payload.value;
2875
- if (typeof input === "undefined")
2874
+ const input2 = payload.value;
2875
+ if (typeof input2 === "undefined")
2876
2876
  return payload;
2877
2877
  payload.issues.push({
2878
2878
  expected: "undefined",
2879
2879
  code: "invalid_type",
2880
- input,
2880
+ input: input2,
2881
2881
  inst
2882
2882
  });
2883
2883
  return payload;
@@ -2888,13 +2888,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
2888
2888
  inst._zod.pattern = _null;
2889
2889
  inst._zod.values = /* @__PURE__ */ new Set([null]);
2890
2890
  inst._zod.parse = (payload, _ctx) => {
2891
- const input = payload.value;
2892
- if (input === null)
2891
+ const input2 = payload.value;
2892
+ if (input2 === null)
2893
2893
  return payload;
2894
2894
  payload.issues.push({
2895
2895
  expected: "null",
2896
2896
  code: "invalid_type",
2897
- input,
2897
+ input: input2,
2898
2898
  inst
2899
2899
  });
2900
2900
  return payload;
@@ -2923,13 +2923,13 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
2923
2923
  var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
2924
2924
  $ZodType.init(inst, def);
2925
2925
  inst._zod.parse = (payload, _ctx) => {
2926
- const input = payload.value;
2927
- if (typeof input === "undefined")
2926
+ const input2 = payload.value;
2927
+ if (typeof input2 === "undefined")
2928
2928
  return payload;
2929
2929
  payload.issues.push({
2930
2930
  expected: "void",
2931
2931
  code: "invalid_type",
2932
- input,
2932
+ input: input2,
2933
2933
  inst
2934
2934
  });
2935
2935
  return payload;
@@ -2944,15 +2944,15 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
2944
2944
  } catch (_err) {
2945
2945
  }
2946
2946
  }
2947
- const input = payload.value;
2948
- const isDate = input instanceof Date;
2949
- const isValidDate = isDate && !Number.isNaN(input.getTime());
2947
+ const input2 = payload.value;
2948
+ const isDate = input2 instanceof Date;
2949
+ const isValidDate = isDate && !Number.isNaN(input2.getTime());
2950
2950
  if (isValidDate)
2951
2951
  return payload;
2952
2952
  payload.issues.push({
2953
2953
  expected: "date",
2954
2954
  code: "invalid_type",
2955
- input,
2955
+ input: input2,
2956
2956
  ...isDate ? { received: "Invalid Date" } : {},
2957
2957
  inst
2958
2958
  });
@@ -2968,20 +2968,20 @@ function handleArrayResult(result, final, index) {
2968
2968
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
2969
2969
  $ZodType.init(inst, def);
2970
2970
  inst._zod.parse = (payload, ctx) => {
2971
- const input = payload.value;
2972
- if (!Array.isArray(input)) {
2971
+ const input2 = payload.value;
2972
+ if (!Array.isArray(input2)) {
2973
2973
  payload.issues.push({
2974
2974
  expected: "array",
2975
2975
  code: "invalid_type",
2976
- input,
2976
+ input: input2,
2977
2977
  inst
2978
2978
  });
2979
2979
  return payload;
2980
2980
  }
2981
- payload.value = Array(input.length);
2981
+ payload.value = Array(input2.length);
2982
2982
  const proms = [];
2983
- for (let i = 0; i < input.length; i++) {
2984
- const item = input[i];
2983
+ for (let i = 0; i < input2.length; i++) {
2984
+ const item = input2[i];
2985
2985
  const result = def.element._zod.run({
2986
2986
  value: item,
2987
2987
  issues: []
@@ -2998,8 +2998,8 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
2998
2998
  return payload;
2999
2999
  };
3000
3000
  });
3001
- function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
3002
- const isPresent = key in input;
3001
+ function handlePropertyResult(result, final, key, input2, isOptionalIn, isOptionalOut) {
3002
+ const isPresent = key in input2;
3003
3003
  if (result.issues.length) {
3004
3004
  if (isOptionalIn && isOptionalOut && !isPresent) {
3005
3005
  return;
@@ -3041,14 +3041,14 @@ function normalizeDef(def) {
3041
3041
  optionalKeys: new Set(okeys)
3042
3042
  };
3043
3043
  }
3044
- function handleCatchall(proms, input, payload, ctx, def, inst) {
3044
+ function handleCatchall(proms, input2, payload, ctx, def, inst) {
3045
3045
  const unrecognized = [];
3046
3046
  const keySet = def.keySet;
3047
3047
  const _catchall = def.catchall._zod;
3048
3048
  const t = _catchall.def.type;
3049
3049
  const isOptionalIn = _catchall.optin === "optional";
3050
3050
  const isOptionalOut = _catchall.optout === "optional";
3051
- for (const key in input) {
3051
+ for (const key in input2) {
3052
3052
  if (key === "__proto__")
3053
3053
  continue;
3054
3054
  if (keySet.has(key))
@@ -3057,18 +3057,18 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
3057
3057
  unrecognized.push(key);
3058
3058
  continue;
3059
3059
  }
3060
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
3060
+ const r = _catchall.run({ value: input2[key], issues: [] }, ctx);
3061
3061
  if (r instanceof Promise) {
3062
- proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
3062
+ proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, isOptionalIn, isOptionalOut)));
3063
3063
  } else {
3064
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
3064
+ handlePropertyResult(r, payload, key, input2, isOptionalIn, isOptionalOut);
3065
3065
  }
3066
3066
  }
3067
3067
  if (unrecognized.length) {
3068
3068
  payload.issues.push({
3069
3069
  code: "unrecognized_keys",
3070
3070
  keys: unrecognized,
3071
- input,
3071
+ input: input2,
3072
3072
  inst
3073
3073
  });
3074
3074
  }
@@ -3112,12 +3112,12 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3112
3112
  let value;
3113
3113
  inst._zod.parse = (payload, ctx) => {
3114
3114
  value ?? (value = _normalized.value);
3115
- const input = payload.value;
3116
- if (!isObject2(input)) {
3115
+ const input2 = payload.value;
3116
+ if (!isObject2(input2)) {
3117
3117
  payload.issues.push({
3118
3118
  expected: "object",
3119
3119
  code: "invalid_type",
3120
- input,
3120
+ input: input2,
3121
3121
  inst
3122
3122
  });
3123
3123
  return payload;
@@ -3129,17 +3129,17 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3129
3129
  const el = shape[key];
3130
3130
  const isOptionalIn = el._zod.optin === "optional";
3131
3131
  const isOptionalOut = el._zod.optout === "optional";
3132
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
3132
+ const r = el._zod.run({ value: input2[key], issues: [] }, ctx);
3133
3133
  if (r instanceof Promise) {
3134
- proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
3134
+ proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input2, isOptionalIn, isOptionalOut)));
3135
3135
  } else {
3136
- handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
3136
+ handlePropertyResult(r, payload, key, input2, isOptionalIn, isOptionalOut);
3137
3137
  }
3138
3138
  }
3139
3139
  if (!catchall) {
3140
3140
  return proms.length ? Promise.all(proms).then(() => payload) : payload;
3141
3141
  }
3142
- return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
3142
+ return handleCatchall(proms, input2, payload, ctx, _normalized.value, inst);
3143
3143
  };
3144
3144
  });
3145
3145
  var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
@@ -3161,42 +3161,42 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3161
3161
  }
3162
3162
  doc.write(`const newResult = {};`);
3163
3163
  for (const key of normalized.keys) {
3164
- const id = ids[key];
3164
+ const id2 = ids[key];
3165
3165
  const k = esc(key);
3166
3166
  const schema = shape[key];
3167
3167
  const isOptionalIn = schema?._zod?.optin === "optional";
3168
3168
  const isOptionalOut = schema?._zod?.optout === "optional";
3169
- doc.write(`const ${id} = ${parseStr(key)};`);
3169
+ doc.write(`const ${id2} = ${parseStr(key)};`);
3170
3170
  if (isOptionalIn && isOptionalOut) {
3171
3171
  doc.write(`
3172
- if (${id}.issues.length) {
3172
+ if (${id2}.issues.length) {
3173
3173
  if (${k} in input) {
3174
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3174
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3175
3175
  ...iss,
3176
3176
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3177
3177
  })));
3178
3178
  }
3179
3179
  }
3180
3180
 
3181
- if (${id}.value === undefined) {
3181
+ if (${id2}.value === undefined) {
3182
3182
  if (${k} in input) {
3183
3183
  newResult[${k}] = undefined;
3184
3184
  }
3185
3185
  } else {
3186
- newResult[${k}] = ${id}.value;
3186
+ newResult[${k}] = ${id2}.value;
3187
3187
  }
3188
3188
 
3189
3189
  `);
3190
3190
  } else if (!isOptionalIn) {
3191
3191
  doc.write(`
3192
- const ${id}_present = ${k} in input;
3193
- if (${id}.issues.length) {
3194
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3192
+ const ${id2}_present = ${k} in input;
3193
+ if (${id2}.issues.length) {
3194
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3195
3195
  ...iss,
3196
3196
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3197
3197
  })));
3198
3198
  }
3199
- if (!${id}_present && !${id}.issues.length) {
3199
+ if (!${id2}_present && !${id2}.issues.length) {
3200
3200
  payload.issues.push({
3201
3201
  code: "invalid_type",
3202
3202
  expected: "nonoptional",
@@ -3205,30 +3205,30 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3205
3205
  });
3206
3206
  }
3207
3207
 
3208
- if (${id}_present) {
3209
- if (${id}.value === undefined) {
3208
+ if (${id2}_present) {
3209
+ if (${id2}.value === undefined) {
3210
3210
  newResult[${k}] = undefined;
3211
3211
  } else {
3212
- newResult[${k}] = ${id}.value;
3212
+ newResult[${k}] = ${id2}.value;
3213
3213
  }
3214
3214
  }
3215
3215
 
3216
3216
  `);
3217
3217
  } else {
3218
3218
  doc.write(`
3219
- if (${id}.issues.length) {
3220
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3219
+ if (${id2}.issues.length) {
3220
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3221
3221
  ...iss,
3222
3222
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3223
3223
  })));
3224
3224
  }
3225
3225
 
3226
- if (${id}.value === undefined) {
3226
+ if (${id2}.value === undefined) {
3227
3227
  if (${k} in input) {
3228
3228
  newResult[${k}] = undefined;
3229
3229
  }
3230
3230
  } else {
3231
- newResult[${k}] = ${id}.value;
3231
+ newResult[${k}] = ${id2}.value;
3232
3232
  }
3233
3233
 
3234
3234
  `);
@@ -3248,12 +3248,12 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3248
3248
  let value;
3249
3249
  inst._zod.parse = (payload, ctx) => {
3250
3250
  value ?? (value = _normalized.value);
3251
- const input = payload.value;
3252
- if (!isObject2(input)) {
3251
+ const input2 = payload.value;
3252
+ if (!isObject2(input2)) {
3253
3253
  payload.issues.push({
3254
3254
  expected: "object",
3255
3255
  code: "invalid_type",
3256
- input,
3256
+ input: input2,
3257
3257
  inst
3258
3258
  });
3259
3259
  return payload;
@@ -3264,7 +3264,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3264
3264
  payload = fastpass(payload, ctx);
3265
3265
  if (!catchall)
3266
3266
  return payload;
3267
- return handleCatchall([], input, payload, ctx, value, inst);
3267
+ return handleCatchall([], input2, payload, ctx, value, inst);
3268
3268
  }
3269
3269
  return superParse(payload, ctx);
3270
3270
  };
@@ -3424,17 +3424,17 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
3424
3424
  return map2;
3425
3425
  });
3426
3426
  inst._zod.parse = (payload, ctx) => {
3427
- const input = payload.value;
3428
- if (!isObject(input)) {
3427
+ const input2 = payload.value;
3428
+ if (!isObject(input2)) {
3429
3429
  payload.issues.push({
3430
3430
  code: "invalid_type",
3431
3431
  expected: "object",
3432
- input,
3432
+ input: input2,
3433
3433
  inst
3434
3434
  });
3435
3435
  return payload;
3436
3436
  }
3437
- const opt = disc.value.get(input?.[def.discriminator]);
3437
+ const opt = disc.value.get(input2?.[def.discriminator]);
3438
3438
  if (opt) {
3439
3439
  return opt._zod.run(payload, ctx);
3440
3440
  }
@@ -3447,7 +3447,7 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
3447
3447
  note: "No matching discriminator",
3448
3448
  discriminator: def.discriminator,
3449
3449
  options: Array.from(disc.value.keys()),
3450
- input,
3450
+ input: input2,
3451
3451
  path: [def.discriminator],
3452
3452
  inst
3453
3453
  });
@@ -3457,9 +3457,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
3457
3457
  var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
3458
3458
  $ZodType.init(inst, def);
3459
3459
  inst._zod.parse = (payload, ctx) => {
3460
- const input = payload.value;
3461
- const left = def.left._zod.run({ value: input, issues: [] }, ctx);
3462
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
3460
+ const input2 = payload.value;
3461
+ const left = def.left._zod.run({ value: input2, issues: [] }, ctx);
3462
+ const right = def.right._zod.run({ value: input2, issues: [] }, ctx);
3463
3463
  const async = left instanceof Promise || right instanceof Promise;
3464
3464
  if (async) {
3465
3465
  return Promise.all([left, right]).then(([left2, right2]) => {
@@ -3556,10 +3556,10 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
3556
3556
  $ZodType.init(inst, def);
3557
3557
  const items = def.items;
3558
3558
  inst._zod.parse = (payload, ctx) => {
3559
- const input = payload.value;
3560
- if (!Array.isArray(input)) {
3559
+ const input2 = payload.value;
3560
+ if (!Array.isArray(input2)) {
3561
3561
  payload.issues.push({
3562
- input,
3562
+ input: input2,
3563
3563
  inst,
3564
3564
  expected: "tuple",
3565
3565
  code: "invalid_type"
@@ -3571,23 +3571,23 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
3571
3571
  const optinStart = getTupleOptStart(items, "optin");
3572
3572
  const optoutStart = getTupleOptStart(items, "optout");
3573
3573
  if (!def.rest) {
3574
- if (input.length < optinStart) {
3574
+ if (input2.length < optinStart) {
3575
3575
  payload.issues.push({
3576
3576
  code: "too_small",
3577
3577
  minimum: optinStart,
3578
3578
  inclusive: true,
3579
- input,
3579
+ input: input2,
3580
3580
  inst,
3581
3581
  origin: "array"
3582
3582
  });
3583
3583
  return payload;
3584
3584
  }
3585
- if (input.length > items.length) {
3585
+ if (input2.length > items.length) {
3586
3586
  payload.issues.push({
3587
3587
  code: "too_big",
3588
3588
  maximum: items.length,
3589
3589
  inclusive: true,
3590
- input,
3590
+ input: input2,
3591
3591
  inst,
3592
3592
  origin: "array"
3593
3593
  });
@@ -3595,7 +3595,7 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
3595
3595
  }
3596
3596
  const itemResults = new Array(items.length);
3597
3597
  for (let i = 0; i < items.length; i++) {
3598
- const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
3598
+ const r = items[i]._zod.run({ value: input2[i], issues: [] }, ctx);
3599
3599
  if (r instanceof Promise) {
3600
3600
  proms.push(r.then((rr) => {
3601
3601
  itemResults[i] = rr;
@@ -3606,7 +3606,7 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
3606
3606
  }
3607
3607
  if (def.rest) {
3608
3608
  let i = items.length - 1;
3609
- const rest = input.slice(items.length);
3609
+ const rest = input2.slice(items.length);
3610
3610
  for (const el of rest) {
3611
3611
  i++;
3612
3612
  const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
@@ -3618,9 +3618,9 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
3618
3618
  }
3619
3619
  }
3620
3620
  if (proms.length) {
3621
- return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
3621
+ return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input2, optoutStart));
3622
3622
  }
3623
- return handleTupleResults(itemResults, payload, items, input, optoutStart);
3623
+ return handleTupleResults(itemResults, payload, items, input2, optoutStart);
3624
3624
  };
3625
3625
  });
3626
3626
  function getTupleOptStart(items, key) {
@@ -3636,10 +3636,10 @@ function handleTupleResult(result, final, index) {
3636
3636
  }
3637
3637
  final.value[index] = result.value;
3638
3638
  }
3639
- function handleTupleResults(itemResults, final, items, input, optoutStart) {
3639
+ function handleTupleResults(itemResults, final, items, input2, optoutStart) {
3640
3640
  for (let i = 0; i < items.length; i++) {
3641
3641
  const r = itemResults[i];
3642
- const isPresent = i < input.length;
3642
+ const isPresent = i < input2.length;
3643
3643
  if (r.issues.length) {
3644
3644
  if (!isPresent && i >= optoutStart) {
3645
3645
  final.value.length = i;
@@ -3649,7 +3649,7 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) {
3649
3649
  }
3650
3650
  final.value[i] = r.value;
3651
3651
  }
3652
- for (let i = final.value.length - 1; i >= input.length; i--) {
3652
+ for (let i = final.value.length - 1; i >= input2.length; i--) {
3653
3653
  if (items[i]._zod.optout === "optional" && final.value[i] === void 0) {
3654
3654
  final.value.length = i;
3655
3655
  } else {
@@ -3661,12 +3661,12 @@ function handleTupleResults(itemResults, final, items, input, optoutStart) {
3661
3661
  var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3662
3662
  $ZodType.init(inst, def);
3663
3663
  inst._zod.parse = (payload, ctx) => {
3664
- const input = payload.value;
3665
- if (!isPlainObject(input)) {
3664
+ const input2 = payload.value;
3665
+ if (!isPlainObject(input2)) {
3666
3666
  payload.issues.push({
3667
3667
  expected: "record",
3668
3668
  code: "invalid_type",
3669
- input,
3669
+ input: input2,
3670
3670
  inst
3671
3671
  });
3672
3672
  return payload;
@@ -3695,7 +3695,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3695
3695
  continue;
3696
3696
  }
3697
3697
  const outKey = keyResult.value;
3698
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
3698
+ const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx);
3699
3699
  if (result instanceof Promise) {
3700
3700
  proms.push(result.then((result2) => {
3701
3701
  if (result2.issues.length) {
@@ -3712,7 +3712,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3712
3712
  }
3713
3713
  }
3714
3714
  let unrecognized;
3715
- for (const key in input) {
3715
+ for (const key in input2) {
3716
3716
  if (!recordKeys.has(key)) {
3717
3717
  unrecognized = unrecognized ?? [];
3718
3718
  unrecognized.push(key);
@@ -3721,17 +3721,17 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3721
3721
  if (unrecognized && unrecognized.length > 0) {
3722
3722
  payload.issues.push({
3723
3723
  code: "unrecognized_keys",
3724
- input,
3724
+ input: input2,
3725
3725
  inst,
3726
3726
  keys: unrecognized
3727
3727
  });
3728
3728
  }
3729
3729
  } else {
3730
3730
  payload.value = {};
3731
- for (const key of Reflect.ownKeys(input)) {
3731
+ for (const key of Reflect.ownKeys(input2)) {
3732
3732
  if (key === "__proto__")
3733
3733
  continue;
3734
- if (!Object.prototype.propertyIsEnumerable.call(input, key))
3734
+ if (!Object.prototype.propertyIsEnumerable.call(input2, key))
3735
3735
  continue;
3736
3736
  let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
3737
3737
  if (keyResult instanceof Promise) {
@@ -3749,7 +3749,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3749
3749
  }
3750
3750
  if (keyResult.issues.length) {
3751
3751
  if (def.mode === "loose") {
3752
- payload.value[key] = input[key];
3752
+ payload.value[key] = input2[key];
3753
3753
  } else {
3754
3754
  payload.issues.push({
3755
3755
  code: "invalid_key",
@@ -3762,7 +3762,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3762
3762
  }
3763
3763
  continue;
3764
3764
  }
3765
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
3765
+ const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx);
3766
3766
  if (result instanceof Promise) {
3767
3767
  proms.push(result.then((result2) => {
3768
3768
  if (result2.issues.length) {
@@ -3787,27 +3787,27 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
3787
3787
  var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
3788
3788
  $ZodType.init(inst, def);
3789
3789
  inst._zod.parse = (payload, ctx) => {
3790
- const input = payload.value;
3791
- if (!(input instanceof Map)) {
3790
+ const input2 = payload.value;
3791
+ if (!(input2 instanceof Map)) {
3792
3792
  payload.issues.push({
3793
3793
  expected: "map",
3794
3794
  code: "invalid_type",
3795
- input,
3795
+ input: input2,
3796
3796
  inst
3797
3797
  });
3798
3798
  return payload;
3799
3799
  }
3800
3800
  const proms = [];
3801
3801
  payload.value = /* @__PURE__ */ new Map();
3802
- for (const [key, value] of input) {
3802
+ for (const [key, value] of input2) {
3803
3803
  const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
3804
3804
  const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
3805
3805
  if (keyResult instanceof Promise || valueResult instanceof Promise) {
3806
3806
  proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
3807
- handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
3807
+ handleMapResult(keyResult2, valueResult2, payload, key, input2, inst, ctx);
3808
3808
  }));
3809
3809
  } else {
3810
- handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
3810
+ handleMapResult(keyResult, valueResult, payload, key, input2, inst, ctx);
3811
3811
  }
3812
3812
  }
3813
3813
  if (proms.length)
@@ -3815,7 +3815,7 @@ var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
3815
3815
  return payload;
3816
3816
  };
3817
3817
  });
3818
- function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
3818
+ function handleMapResult(keyResult, valueResult, final, key, input2, inst, ctx) {
3819
3819
  if (keyResult.issues.length) {
3820
3820
  if (propertyKeyTypes.has(typeof key)) {
3821
3821
  final.issues.push(...prefixIssues(key, keyResult.issues));
@@ -3823,7 +3823,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
3823
3823
  final.issues.push({
3824
3824
  code: "invalid_key",
3825
3825
  origin: "map",
3826
- input,
3826
+ input: input2,
3827
3827
  inst,
3828
3828
  issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
3829
3829
  });
@@ -3836,7 +3836,7 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
3836
3836
  final.issues.push({
3837
3837
  origin: "map",
3838
3838
  code: "invalid_element",
3839
- input,
3839
+ input: input2,
3840
3840
  inst,
3841
3841
  key,
3842
3842
  issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
@@ -3848,10 +3848,10 @@ function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
3848
3848
  var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
3849
3849
  $ZodType.init(inst, def);
3850
3850
  inst._zod.parse = (payload, ctx) => {
3851
- const input = payload.value;
3852
- if (!(input instanceof Set)) {
3851
+ const input2 = payload.value;
3852
+ if (!(input2 instanceof Set)) {
3853
3853
  payload.issues.push({
3854
- input,
3854
+ input: input2,
3855
3855
  inst,
3856
3856
  expected: "set",
3857
3857
  code: "invalid_type"
@@ -3860,7 +3860,7 @@ var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
3860
3860
  }
3861
3861
  const proms = [];
3862
3862
  payload.value = /* @__PURE__ */ new Set();
3863
- for (const item of input) {
3863
+ for (const item of input2) {
3864
3864
  const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
3865
3865
  if (result instanceof Promise) {
3866
3866
  proms.push(result.then((result2) => handleSetResult(result2, payload)));
@@ -3885,14 +3885,14 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
3885
3885
  inst._zod.values = valuesSet;
3886
3886
  inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
3887
3887
  inst._zod.parse = (payload, _ctx) => {
3888
- const input = payload.value;
3889
- if (valuesSet.has(input)) {
3888
+ const input2 = payload.value;
3889
+ if (valuesSet.has(input2)) {
3890
3890
  return payload;
3891
3891
  }
3892
3892
  payload.issues.push({
3893
3893
  code: "invalid_value",
3894
3894
  values,
3895
- input,
3895
+ input: input2,
3896
3896
  inst
3897
3897
  });
3898
3898
  return payload;
@@ -3907,14 +3907,14 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
3907
3907
  inst._zod.values = values;
3908
3908
  inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
3909
3909
  inst._zod.parse = (payload, _ctx) => {
3910
- const input = payload.value;
3911
- if (values.has(input)) {
3910
+ const input2 = payload.value;
3911
+ if (values.has(input2)) {
3912
3912
  return payload;
3913
3913
  }
3914
3914
  payload.issues.push({
3915
3915
  code: "invalid_value",
3916
3916
  values: def.values,
3917
- input,
3917
+ input: input2,
3918
3918
  inst
3919
3919
  });
3920
3920
  return payload;
@@ -3923,13 +3923,13 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
3923
3923
  var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
3924
3924
  $ZodType.init(inst, def);
3925
3925
  inst._zod.parse = (payload, _ctx) => {
3926
- const input = payload.value;
3927
- if (input instanceof File)
3926
+ const input2 = payload.value;
3927
+ if (input2 instanceof File)
3928
3928
  return payload;
3929
3929
  payload.issues.push({
3930
3930
  expected: "file",
3931
3931
  code: "invalid_type",
3932
- input,
3932
+ input: input2,
3933
3933
  inst
3934
3934
  });
3935
3935
  return payload;
@@ -3959,8 +3959,8 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) =>
3959
3959
  return payload;
3960
3960
  };
3961
3961
  });
3962
- function handleOptionalResult(result, input) {
3963
- if (input === void 0 && (result.issues.length || result.fallback)) {
3962
+ function handleOptionalResult(result, input2) {
3963
+ if (input2 === void 0 && (result.issues.length || result.fallback)) {
3964
3964
  return { issues: [], value: void 0 };
3965
3965
  }
3966
3966
  return result;
@@ -3978,11 +3978,11 @@ var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
3978
3978
  });
3979
3979
  inst._zod.parse = (payload, ctx) => {
3980
3980
  if (def.innerType._zod.optin === "optional") {
3981
- const input = payload.value;
3981
+ const input2 = payload.value;
3982
3982
  const result = def.innerType._zod.run(payload, ctx);
3983
3983
  if (result instanceof Promise)
3984
- return result.then((r) => handleOptionalResult(r, input));
3985
- return handleOptionalResult(result, input);
3984
+ return result.then((r) => handleOptionalResult(r, input2));
3985
+ return handleOptionalResult(result, input2);
3986
3986
  }
3987
3987
  if (payload.value === void 0) {
3988
3988
  return payload;
@@ -4407,20 +4407,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
4407
4407
  return payload;
4408
4408
  };
4409
4409
  inst._zod.check = (payload) => {
4410
- const input = payload.value;
4411
- const r = def.fn(input);
4410
+ const input2 = payload.value;
4411
+ const r = def.fn(input2);
4412
4412
  if (r instanceof Promise) {
4413
- return r.then((r2) => handleRefineResult(r2, payload, input, inst));
4413
+ return r.then((r2) => handleRefineResult(r2, payload, input2, inst));
4414
4414
  }
4415
- handleRefineResult(r, payload, input, inst);
4415
+ handleRefineResult(r, payload, input2, inst);
4416
4416
  return;
4417
4417
  };
4418
4418
  });
4419
- function handleRefineResult(result, payload, input, inst) {
4419
+ function handleRefineResult(result, payload, input2, inst) {
4420
4420
  if (!result) {
4421
4421
  const _iss = {
4422
4422
  code: "custom",
4423
- input,
4423
+ input: input2,
4424
4424
  inst,
4425
4425
  // incorporates params.error into issue reporting
4426
4426
  path: [...inst._zod.def.path ?? []],
@@ -7707,8 +7707,8 @@ function ko_default() {
7707
7707
  }
7708
7708
 
7709
7709
  // ../../../node_modules/zod/v4/locales/lt.js
7710
- var capitalizeFirstCharacter = (text2) => {
7711
- return text2.charAt(0).toUpperCase() + text2.slice(1);
7710
+ var capitalizeFirstCharacter = (text3) => {
7711
+ return text3.charAt(0).toUpperCase() + text3.slice(1);
7712
7712
  };
7713
7713
  function getUnitTypeFromNumber(number4) {
7714
7714
  const abs = Math.abs(number4);
@@ -11108,23 +11108,23 @@ function _overwrite(tx) {
11108
11108
  }
11109
11109
  // @__NO_SIDE_EFFECTS__
11110
11110
  function _normalize(form) {
11111
- return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
11111
+ return /* @__PURE__ */ _overwrite((input2) => input2.normalize(form));
11112
11112
  }
11113
11113
  // @__NO_SIDE_EFFECTS__
11114
11114
  function _trim() {
11115
- return /* @__PURE__ */ _overwrite((input) => input.trim());
11115
+ return /* @__PURE__ */ _overwrite((input2) => input2.trim());
11116
11116
  }
11117
11117
  // @__NO_SIDE_EFFECTS__
11118
11118
  function _toLowerCase() {
11119
- return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
11119
+ return /* @__PURE__ */ _overwrite((input2) => input2.toLowerCase());
11120
11120
  }
11121
11121
  // @__NO_SIDE_EFFECTS__
11122
11122
  function _toUpperCase() {
11123
- return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
11123
+ return /* @__PURE__ */ _overwrite((input2) => input2.toUpperCase());
11124
11124
  }
11125
11125
  // @__NO_SIDE_EFFECTS__
11126
11126
  function _slugify() {
11127
- return /* @__PURE__ */ _overwrite((input) => slugify(input));
11127
+ return /* @__PURE__ */ _overwrite((input2) => slugify(input2));
11128
11128
  }
11129
11129
  // @__NO_SIDE_EFFECTS__
11130
11130
  function _array(Class2, element, params) {
@@ -11429,8 +11429,8 @@ function _stringbool(Classes, _params) {
11429
11429
  type: "pipe",
11430
11430
  in: stringSchema,
11431
11431
  out: booleanSchema,
11432
- transform: ((input, payload) => {
11433
- let data = input;
11432
+ transform: ((input2, payload) => {
11433
+ let data = input2;
11434
11434
  if (params.case !== "sensitive")
11435
11435
  data = data.toLowerCase();
11436
11436
  if (truthySet.has(data)) {
@@ -11449,8 +11449,8 @@ function _stringbool(Classes, _params) {
11449
11449
  return {};
11450
11450
  }
11451
11451
  }),
11452
- reverseTransform: ((input, _payload) => {
11453
- if (input === true) {
11452
+ reverseTransform: ((input2, _payload) => {
11453
+ if (input2 === true) {
11454
11454
  return truthyArray[0] || "true";
11455
11455
  } else {
11456
11456
  return falsyArray[0] || "false";
@@ -11560,26 +11560,26 @@ function extractDefs(ctx, schema) {
11560
11560
  throw new Error("Unprocessed schema. This is a bug in Zod.");
11561
11561
  const idToSchema = /* @__PURE__ */ new Map();
11562
11562
  for (const entry of ctx.seen.entries()) {
11563
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11564
- if (id) {
11565
- const existing = idToSchema.get(id);
11563
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11564
+ if (id2) {
11565
+ const existing = idToSchema.get(id2);
11566
11566
  if (existing && existing !== entry[0]) {
11567
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11567
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11568
11568
  }
11569
- idToSchema.set(id, entry[0]);
11569
+ idToSchema.set(id2, entry[0]);
11570
11570
  }
11571
11571
  }
11572
11572
  const makeURI = (entry) => {
11573
11573
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
11574
11574
  if (ctx.external) {
11575
11575
  const externalId = ctx.external.registry.get(entry[0])?.id;
11576
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
11576
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
11577
11577
  if (externalId) {
11578
11578
  return { ref: uriGenerator(externalId) };
11579
11579
  }
11580
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11581
- entry[1].defId = id;
11582
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
11580
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11581
+ entry[1].defId = id2;
11582
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
11583
11583
  }
11584
11584
  if (entry[1] === root) {
11585
11585
  return { ref: "#" };
@@ -11627,8 +11627,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11627
11627
  continue;
11628
11628
  }
11629
11629
  }
11630
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11631
- if (id) {
11630
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11631
+ if (id2) {
11632
11632
  extractToDef(entry);
11633
11633
  continue;
11634
11634
  }
@@ -11724,10 +11724,10 @@ function finalize(ctx, schema) {
11724
11724
  } else {
11725
11725
  }
11726
11726
  if (ctx.external?.uri) {
11727
- const id = ctx.external.registry.get(schema)?.id;
11728
- if (!id)
11727
+ const id2 = ctx.external.registry.get(schema)?.id;
11728
+ if (!id2)
11729
11729
  throw new Error("Schema is missing an `id` property");
11730
- result.$id = ctx.external.uri(id);
11730
+ result.$id = ctx.external.uri(id2);
11731
11731
  }
11732
11732
  Object.assign(result, root.def ?? root.schema);
11733
11733
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -11887,9 +11887,9 @@ var numberProcessor = (schema, ctx, _json, _params) => {
11887
11887
  json2.type = "number";
11888
11888
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
11889
11889
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
11890
- const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
11890
+ const legacy2 = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
11891
11891
  if (exMin) {
11892
- if (legacy) {
11892
+ if (legacy2) {
11893
11893
  json2.minimum = exclusiveMinimum;
11894
11894
  json2.exclusiveMinimum = true;
11895
11895
  } else {
@@ -11899,7 +11899,7 @@ var numberProcessor = (schema, ctx, _json, _params) => {
11899
11899
  json2.minimum = minimum;
11900
11900
  }
11901
11901
  if (exMax) {
11902
- if (legacy) {
11902
+ if (legacy2) {
11903
11903
  json2.maximum = exclusiveMaximum;
11904
11904
  json2.exclusiveMaximum = true;
11905
11905
  } else {
@@ -12346,9 +12346,9 @@ var allProcessors = {
12346
12346
  optional: optionalProcessor,
12347
12347
  lazy: lazyProcessor
12348
12348
  };
12349
- function toJSONSchema(input, params) {
12350
- if ("_idmap" in input) {
12351
- const registry2 = input;
12349
+ function toJSONSchema(input2, params) {
12350
+ if ("_idmap" in input2) {
12351
+ const registry2 = input2;
12352
12352
  const ctx2 = initializeContext({ ...params, processors: allProcessors });
12353
12353
  const defs = {};
12354
12354
  for (const entry of registry2._idmap.entries()) {
@@ -12376,9 +12376,9 @@ function toJSONSchema(input, params) {
12376
12376
  return { schemas };
12377
12377
  }
12378
12378
  const ctx = initializeContext({ ...params, processors: allProcessors });
12379
- process2(input, ctx);
12380
- extractDefs(ctx, input);
12381
- return finalize(ctx, input);
12379
+ process2(input2, ctx);
12380
+ extractDefs(ctx, input2);
12381
+ return finalize(ctx, input2);
12382
12382
  }
12383
12383
 
12384
12384
  // ../../../node_modules/zod/v4/core/json-schema-generator.js
@@ -12761,7 +12761,7 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
12761
12761
 
12762
12762
  // ../../../node_modules/zod/v4/classic/schemas.js
12763
12763
  var _installedGroups = /* @__PURE__ */ new WeakMap();
12764
- function _installLazyMethods(inst, group, methods) {
12764
+ function _installLazyMethods(inst, group, methods2) {
12765
12765
  const proto = Object.getPrototypeOf(inst);
12766
12766
  let installed = _installedGroups.get(proto);
12767
12767
  if (!installed) {
@@ -12771,8 +12771,8 @@ function _installLazyMethods(inst, group, methods) {
12771
12771
  if (installed.has(group))
12772
12772
  return;
12773
12773
  installed.add(group);
12774
- for (const key in methods) {
12775
- const fn = methods[key];
12774
+ for (const key in methods2) {
12775
+ const fn = methods2[key];
12776
12776
  Object.defineProperty(proto, key, {
12777
12777
  configurable: true,
12778
12778
  enumerable: false,
@@ -14169,13 +14169,13 @@ function resolveRef(ref, ctx) {
14169
14169
  if (!ref.startsWith("#")) {
14170
14170
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14171
14171
  }
14172
- const path7 = ref.slice(1).split("/").filter(Boolean);
14173
- if (path7.length === 0) {
14172
+ const path8 = ref.slice(1).split("/").filter(Boolean);
14173
+ if (path8.length === 0) {
14174
14174
  return ctx.rootSchema;
14175
14175
  }
14176
14176
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14177
- if (path7[0] === defsKey) {
14178
- const key = path7[1];
14177
+ if (path8[0] === defsKey) {
14178
+ const key = path8[1];
14179
14179
  if (!key || !ctx.defs[key]) {
14180
14180
  throw new Error(`Reference not found: ${ref}`);
14181
14181
  }
@@ -14711,87 +14711,6 @@ function text(value) {
14711
14711
  return typeof value === "string" ? value : "";
14712
14712
  }
14713
14713
 
14714
- // ../../shared-contracts/dist/ids.js
14715
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14716
- message: "Identifier must not be empty or whitespace"
14717
- });
14718
- var harnessIdSchema = opaqueIdSchema.brand();
14719
- var hostThreadIdSchema = opaqueIdSchema.brand();
14720
- var hostTurnIdSchema = opaqueIdSchema.brand();
14721
- var hostItemIdSchema = opaqueIdSchema.brand();
14722
- var hostInteractionIdSchema = opaqueIdSchema.brand();
14723
-
14724
- // ../../shared-contracts/dist/harness-plugins.js
14725
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
14726
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
14727
- var HARNESS_PLUGIN_LIMIT = 128;
14728
- var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
14729
- var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
14730
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
14731
- var pluginRelativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
14732
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
14733
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
14734
- var harnessInstallationGuideSchema = external_exports.object({
14735
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
14736
- before: localizedTextSchema.optional(),
14737
- after: localizedTextSchema.optional(),
14738
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
14739
- }).strict();
14740
- var pluginPresentationShape = {
14741
- id: installedHarnessPluginIdSchema,
14742
- name: external_exports.string().trim().min(1).max(128),
14743
- version: external_exports.string().min(1).max(128),
14744
- /** Capability-only plugin; omitted for existing session-capable plugins. */
14745
- kind: external_exports.literal("usage").optional(),
14746
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
14747
- iconStyle: external_exports.object({
14748
- vector: external_exports.object({
14749
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
14750
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
14751
- paths: external_exports.array(external_exports.object({
14752
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
14753
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
14754
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
14755
- }).strict()).min(1).max(32)
14756
- }).strict().optional(),
14757
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
14758
- borderRadius: external_exports.number().min(0).max(50).optional(),
14759
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
14760
- }).strict().optional(),
14761
- installation: harnessInstallationGuideSchema.optional(),
14762
- notice: localizedTextSchema.optional(),
14763
- /** The factory accepts a persisted local entrypoint through its construction context. */
14764
- launchCommand: external_exports.literal(true).optional(),
14765
- links: external_exports.object({
14766
- website: documentationUrlSchema.optional(),
14767
- documentation: documentationUrlSchema.optional(),
14768
- installation: documentationUrlSchema.optional()
14769
- }).strict().optional()
14770
- };
14771
- var harnessPluginManifestSchema = external_exports.object({
14772
- manifestVersion: external_exports.literal(1),
14773
- ...pluginPresentationShape,
14774
- adapterApiVersion: external_exports.number().int().positive(),
14775
- entry: pluginRelativeResourceSchema,
14776
- icon: pluginRelativeResourceSchema.optional()
14777
- }).strict();
14778
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
14779
- var harnessPluginDescriptorSchema = external_exports.object({
14780
- ...pluginPresentationShape,
14781
- icon: harnessPluginIconSchema.optional()
14782
- }).strict();
14783
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
14784
- var harnessPluginListResultSchema = external_exports.object({
14785
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
14786
- }).strict();
14787
- var harnessPluginConfigurationSchema = external_exports.object({
14788
- version: external_exports.literal(1),
14789
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
14790
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
14791
- message: "Enabled plugin IDs must be unique",
14792
- path: ["enabled"]
14793
- });
14794
-
14795
14714
  // ../../shared-contracts/dist/json-value.js
14796
14715
  function rejectExplicitUndefined(keys) {
14797
14716
  return (value, context) => {
@@ -14851,403 +14770,73 @@ var jsonValueSchema = nonCircularSchema.pipe(recursiveJsonValueSchema);
14851
14770
  var jsonArraySchema = nonCircularSchema.pipe(external_exports.array(recursiveJsonValueSchema));
14852
14771
  var jsonObjectSchema = nonCircularSchema.pipe(external_exports.record(external_exports.string(), recursiveJsonValueSchema));
14853
14772
 
14854
- // ../../shared-contracts/dist/desktop-extensions.js
14855
- var DESKTOP_EXTENSION_API_VERSION = 1;
14856
- var DESKTOP_EXTENSION_LIMIT = 64;
14857
- var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
14858
- var DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH = 4 * Math.ceil(DESKTOP_EXTENSION_ZIP_MAX_BYTES / 3);
14859
- var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
14860
- var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
14861
- var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
14862
- var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
14863
- var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
14864
- var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
14865
- var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
14866
- var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
14867
- var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
14868
- var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
14869
- var desktopExtensionIdSchema = installedPluginIdSchema;
14870
- var desktopExtensionSlotSchema = external_exports.enum([
14871
- "sidebar.thread-layout",
14872
- "sidebar.thread-badge",
14873
- "appearance.theme"
14874
- ]);
14875
- var desktopExtensionCategorySchema = external_exports.enum([
14876
- "appearance",
14877
- "interface",
14878
- "workflow",
14879
- "analytics",
14880
- "integrations",
14881
- "tools"
14882
- ]);
14883
- var extensionName = external_exports.string().trim().min(1).max(128);
14884
- function desktopExtensionScreenshotMimeType(resource) {
14885
- switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
14886
- case "png":
14887
- return "image/png";
14888
- case "jpg":
14889
- case "jpeg":
14890
- return "image/jpeg";
14891
- case "webp":
14892
- return "image/webp";
14893
- default:
14894
- return void 0;
14773
+ // ../../shared-contracts/dist/errors.js
14774
+ var codexhostErrorSchema = external_exports.strictObject({
14775
+ code: external_exports.string().min(1),
14776
+ message: external_exports.string().min(1),
14777
+ retryable: external_exports.boolean(),
14778
+ diagnostic: external_exports.string().min(1).optional(),
14779
+ stage: external_exports.string().min(1).optional(),
14780
+ durationMs: external_exports.number().int().nonnegative().optional(),
14781
+ stderrTail: external_exports.string().min(1).optional()
14782
+ }).superRefine(rejectExplicitUndefined(["diagnostic", "stage", "durationMs", "stderrTail"]));
14783
+
14784
+ // ../../shared-contracts/dist/harness-presentation.js
14785
+ var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
14786
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text3) => text3.trim().length > 0);
14787
+ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
14788
+ label: displayText(256).optional(),
14789
+ description: displayText(1024).optional()
14790
+ }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
14791
+ var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
14792
+
14793
+ // ../../shared-contracts/dist/ids.js
14794
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14795
+ message: "Identifier must not be empty or whitespace"
14796
+ });
14797
+ var harnessIdSchema = opaqueIdSchema.brand();
14798
+ var hostThreadIdSchema = opaqueIdSchema.brand();
14799
+ var hostTurnIdSchema = opaqueIdSchema.brand();
14800
+ var hostItemIdSchema = opaqueIdSchema.brand();
14801
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
14802
+
14803
+ // ../../shared-contracts/dist/harness-permission-modes.js
14804
+ var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
14805
+ var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
14806
+ var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
14807
+ var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
14808
+ var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14809
+ message: "Value must not be empty or whitespace"
14810
+ });
14811
+ var harnessPermissionModeIdSchema = nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~:-]+$/u, "Permission Mode ID must use transport-safe characters").brand();
14812
+ var harnessPermissionModeSchema = external_exports.object({
14813
+ id: harnessPermissionModeIdSchema,
14814
+ label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
14815
+ description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
14816
+ dangerous: external_exports.boolean().optional(),
14817
+ localizations: harnessLocalizationsSchema.optional()
14818
+ }).strict();
14819
+ var harnessPermissionModeCatalogSchema = external_exports.object({
14820
+ modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
14821
+ defaultModeId: harnessPermissionModeIdSchema
14822
+ }).strict().superRefine((catalog, context) => {
14823
+ const ids = /* @__PURE__ */ new Set();
14824
+ for (const [index, mode] of catalog.modes.entries()) {
14825
+ if (ids.has(mode.id)) {
14826
+ context.addIssue({
14827
+ code: "custom",
14828
+ message: "Permission Mode IDs must be unique",
14829
+ path: ["modes", index, "id"]
14830
+ });
14831
+ }
14832
+ ids.add(mode.id);
14895
14833
  }
14896
- }
14897
- function desktopExtensionAssetMimeType(resource) {
14898
- switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
14899
- case "gif":
14900
- return "image/gif";
14901
- case "svg":
14902
- return "image/svg+xml";
14903
- case "woff2":
14904
- return "font/woff2";
14905
- case "json":
14906
- return "application/json";
14907
- case "css":
14908
- return "text/css";
14909
- default:
14910
- return desktopExtensionScreenshotMimeType(resource);
14911
- }
14912
- }
14913
- var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
14914
- var desktopExtensionAssetPathSchema = pluginRelativeResourceSchema.refine((resource) => hasPortableSegments(resource) && desktopExtensionAssetMimeType(resource) !== void 0, "Expected a relative Desktop extension asset path with a supported suffix");
14915
- var imagePathSchema = pluginRelativeResourceSchema.refine((resource) => desktopExtensionScreenshotMimeType(resource) !== void 0 && hasPortableSegments(resource), "Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space");
14916
- var desktopExtensionHttpUrlSchema = external_exports.string().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu, "Expected an HTTP(S) URL").pipe(external_exports.url({ protocol: /^https?$/u })).refine((value) => {
14917
- const { username, password } = new URL(value);
14918
- return !username && !password && !/[\\\s]/u.test(value);
14919
- }, "URL must not contain credentials, backslashes, or whitespace");
14920
- function localizedText(text2) {
14921
- return external_exports.strictObject({ en: text2, "zh-CN": text2 });
14922
- }
14923
- var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
14924
- var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
14925
- var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
14926
- var settingField = {
14927
- key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
14928
- label: desktopExtensionLocalizedTextSchema,
14929
- description: desktopExtensionLocalizedTextSchema.optional()
14930
- };
14931
- var numericSetting = {
14932
- ...settingField,
14933
- step: external_exports.number().positive().optional(),
14934
- default: external_exports.number().optional()
14935
- };
14936
- var settingOption = external_exports.strictObject({
14937
- value: external_exports.string(),
14938
- label: desktopExtensionLocalizedTextSchema
14939
- });
14940
- var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
14941
- external_exports.strictObject({
14942
- ...settingField,
14943
- type: external_exports.literal("boolean"),
14944
- default: external_exports.boolean().optional()
14945
- }),
14946
- external_exports.strictObject({
14947
- ...settingField,
14948
- type: external_exports.literal("string"),
14949
- placeholder: desktopExtensionLocalizedTextSchema.optional(),
14950
- default: external_exports.string().optional()
14951
- }),
14952
- external_exports.strictObject({
14953
- ...numericSetting,
14954
- type: external_exports.literal("number"),
14955
- min: external_exports.number().optional(),
14956
- max: external_exports.number().optional()
14957
- }),
14958
- external_exports.strictObject({
14959
- ...numericSetting,
14960
- type: external_exports.literal("range"),
14961
- min: external_exports.number(),
14962
- max: external_exports.number()
14963
- }),
14964
- external_exports.strictObject({
14965
- ...settingField,
14966
- type: external_exports.literal("select"),
14967
- options: external_exports.array(settingOption).min(1),
14968
- default: external_exports.string().optional()
14969
- })
14970
- ]).superRefine((field3, ctx) => {
14971
- const issue2 = (path7, message) => ctx.addIssue({ code: "custom", path: [path7], message });
14972
- if (field3.type === "number" || field3.type === "range") {
14973
- const { min = -Infinity, max = Infinity, default: value } = field3;
14974
- if (min > max)
14975
- issue2("max", "Must be at least min");
14976
- if (value !== void 0 && (value < min || value > max))
14977
- issue2("default", "Must be within min and max");
14978
- } else if (field3.type === "select") {
14979
- const values = new Set(field3.options.map(({ value }) => value));
14980
- if (values.size !== field3.options.length)
14981
- issue2("options", "Duplicate option values");
14982
- if (field3.default !== void 0 && !values.has(field3.default))
14983
- issue2("default", "Must match an option value");
14984
- }
14985
- });
14986
- var manifestHeader = external_exports.object({
14987
- manifestVersion: external_exports.int().positive(),
14988
- id: desktopExtensionIdSchema,
14989
- name: external_exports.union([extensionName, localizedText(extensionName)]),
14990
- version: external_exports.string().min(1).max(128),
14991
- desktopApi: external_exports.int().positive()
14992
- }).passthrough();
14993
- var desktopExtensionManifestSchema = manifestHeader.extend({
14994
- manifestVersion: external_exports.literal(1),
14995
- desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
14996
- description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
14997
- author: external_exports.string().trim().min(1).max(128).optional(),
14998
- repository: desktopExtensionHttpUrlSchema.optional(),
14999
- details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15000
- icon: imagePathSchema.optional(),
15001
- screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15002
- desktop: external_exports.strictObject({
15003
- script: pluginRelativeResourceSchema,
15004
- style: pluginRelativeResourceSchema.optional()
15005
- }).optional(),
15006
- backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15007
- slots: slotsSchema.default(() => []),
15008
- settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15009
- categories: categoriesSchema.optional()
15010
- }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15011
- var desktopExtensionConfigurationSchema = external_exports.strictObject({
15012
- version: external_exports.literal(1),
15013
- revision: external_exports.int().nonnegative(),
15014
- enabled: external_exports.array(desktopExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs"),
15015
- reloadToken: external_exports.uuid().optional()
15016
- });
15017
- var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15018
- var desktopExtensionStatusSchema = external_exports.strictObject({
15019
- state: external_exports.enum([
15020
- "running",
15021
- "disabled",
15022
- "invalid",
15023
- "incompatible",
15024
- "conflict",
15025
- "failed",
15026
- "waiting"
15027
- ]),
15028
- hash: desktopExtensionHashSchema.optional(),
15029
- error: external_exports.string().optional(),
15030
- conflictWith: desktopExtensionIdSchema.optional()
15031
- });
15032
- var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15033
- controllerPid: external_exports.int().positive(),
15034
- targetId: external_exports.string().nullable(),
15035
- updatedAt: external_exports.iso.datetime(),
15036
- handledReloadToken: external_exports.uuid().optional(),
15037
- extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema)
15038
- });
15039
- var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15040
- function isGitHubDesktopExtensionZipballUrl(url2) {
15041
- return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15042
- }
15043
- var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15044
- const url2 = new URL(input);
15045
- return /\.zip$/iu.test(url2.pathname) || isGitHubDesktopExtensionZipballUrl(url2) || url2.origin === "https://github.com" && /^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(url2.pathname) || url2.origin === "https://codeload.github.com" && /^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(url2.pathname);
15046
- }, "Expected a .zip download URL or a GitHub zipball URL");
15047
- var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15048
- id: desktopExtensionIdSchema,
15049
- version: external_exports.string().trim().min(1).max(128),
15050
- name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15051
- description: localizedText(external_exports.string().trim().min(1).max(4096)),
15052
- details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15053
- author: external_exports.string().trim().min(1).max(128),
15054
- repository: desktopExtensionHttpUrlSchema,
15055
- stars: external_exports.number().int().min(0).optional(),
15056
- downloads: external_exports.number().int().min(0).optional(),
15057
- categories: categoriesSchema.optional(),
15058
- trustTier: desktopExtensionTrustTierSchema.default("community"),
15059
- icon: desktopExtensionHttpUrlSchema.optional(),
15060
- screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15061
- downloadUrl: desktopExtensionZipUrlSchema,
15062
- sha256: desktopExtensionHashSchema,
15063
- slots: slotsSchema.optional(),
15064
- publishedAt: external_exports.string().optional(),
15065
- updatedAt: external_exports.string().optional(),
15066
- minCodexHostVersion: external_exports.string().optional()
15067
- });
15068
- var desktopExtensionCatalogSchema = external_exports.strictObject({
15069
- schemaVersion: external_exports.literal(1),
15070
- generatedAt: external_exports.string(),
15071
- extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, "Duplicate extension IDs")
15072
- });
15073
- var DESKTOP_EXTENSIONS_ASSET_METHOD = "codexhost/desktop/extensions/asset";
15074
- var DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD = "codexhost/desktop/extensions/settings/get";
15075
- var DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD = "codexhost/desktop/extensions/settings/set";
15076
- var DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD = "codexhost/desktop/extensions/backend/invoke";
15077
- var extensionIdParams = { id: desktopExtensionIdSchema };
15078
- var desktopExtensionsAssetParamsSchema = external_exports.strictObject({
15079
- ...extensionIdParams,
15080
- path: desktopExtensionAssetPathSchema
15081
- });
15082
- var desktopExtensionsAssetResultSchema = external_exports.strictObject({
15083
- mimeType: external_exports.string(),
15084
- dataUrl: external_exports.string()
15085
- });
15086
- var desktopExtensionsSettingsGetParamsSchema = external_exports.strictObject(extensionIdParams);
15087
- var desktopExtensionsSettingsSetParamsSchema = external_exports.strictObject({
15088
- ...extensionIdParams,
15089
- values: jsonObjectSchema
15090
- });
15091
- var desktopExtensionsSettingsResultSchema = external_exports.strictObject({ values: jsonObjectSchema });
15092
- var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15093
- var desktopExtensionsBackendInvokeParamsSchema = external_exports.strictObject({
15094
- ...extensionIdParams,
15095
- method: desktopExtensionBackendMethodSchema,
15096
- params: jsonValueSchema.optional()
15097
- });
15098
- var desktopExtensionsBackendInvokeResultSchema = external_exports.strictObject({
15099
- result: jsonValueSchema
15100
- });
15101
-
15102
- // ../../shared-contracts/dist/desktop-extension-management.js
15103
- var DESKTOP_EXTENSIONS_LIST_METHOD = "codexhost/desktop/extensions/list";
15104
- var DESKTOP_EXTENSIONS_ENABLE_METHOD = "codexhost/desktop/extensions/enable";
15105
- var DESKTOP_EXTENSIONS_DISABLE_METHOD = "codexhost/desktop/extensions/disable";
15106
- var DESKTOP_EXTENSIONS_CATALOG_METHOD = "codexhost/desktop/extensions/catalog";
15107
- var DESKTOP_EXTENSIONS_INSTALL_METHOD = "codexhost/desktop/extensions/install";
15108
- var DESKTOP_EXTENSIONS_UNINSTALL_METHOD = "codexhost/desktop/extensions/uninstall";
15109
- var DESKTOP_EXTENSIONS_RECOVER_METHOD = "codexhost/desktop/extensions/disable-all-and-reload";
15110
- var DESKTOP_EXTENSION_MANAGEMENT_METHODS = [
15111
- DESKTOP_EXTENSIONS_LIST_METHOD,
15112
- DESKTOP_EXTENSIONS_ENABLE_METHOD,
15113
- DESKTOP_EXTENSIONS_DISABLE_METHOD,
15114
- DESKTOP_EXTENSIONS_RECOVER_METHOD,
15115
- DESKTOP_EXTENSIONS_CATALOG_METHOD,
15116
- DESKTOP_EXTENSIONS_INSTALL_METHOD,
15117
- DESKTOP_EXTENSIONS_UNINSTALL_METHOD,
15118
- DESKTOP_EXTENSIONS_ASSET_METHOD,
15119
- DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD,
15120
- DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD,
15121
- DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD
15122
- ];
15123
- var revisionSchema = external_exports.int().nonnegative();
15124
- var desktopExtensionsListParamsSchema = external_exports.strictObject({});
15125
- var desktopExtensionSelectionParamsSchema = external_exports.strictObject({
15126
- id: desktopExtensionIdSchema,
15127
- expectedRevision: revisionSchema
15128
- });
15129
- var desktopExtensionsRecoveryParamsSchema = external_exports.strictObject({
15130
- expectedRevision: revisionSchema.optional()
15131
- });
15132
- var rasterDataUrlSchema = (maxBytes) => external_exports.string().max("data:image/jpeg;base64,".length + 4 * Math.ceil(maxBytes / 3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u);
15133
- var desktopExtensionListItemSchema = external_exports.strictObject({
15134
- // An invalid discovery can have a directory name that isn't a valid extension ID.
15135
- id: external_exports.string().min(1),
15136
- manifest: desktopExtensionManifestSchema.optional(),
15137
- iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15138
- screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15139
- enabled: external_exports.boolean(),
15140
- status: desktopExtensionStatusSchema
15141
- });
15142
- var desktopExtensionsListResultSchema = external_exports.strictObject({
15143
- configuration: desktopExtensionConfigurationSchema,
15144
- desktopConnected: external_exports.boolean(),
15145
- diagnostics: external_exports.array(external_exports.string()),
15146
- extensions: external_exports.array(desktopExtensionListItemSchema)
15147
- });
15148
- var desktopExtensionsCatalogParamsSchema = external_exports.strictObject({
15149
- forceRefresh: external_exports.boolean().optional()
15150
- });
15151
- var desktopExtensionsCatalogResultSchema = external_exports.strictObject({
15152
- catalogUrl: external_exports.string(),
15153
- source: external_exports.enum(["remote", "fallback"]),
15154
- fetchedAt: external_exports.string(),
15155
- cached: external_exports.boolean(),
15156
- extensions: desktopExtensionCatalogSchema.shape.extensions,
15157
- error: external_exports.string().optional()
15158
- });
15159
- var desktopExtensionsInstallParamsSchema = external_exports.strictObject({
15160
- source: external_exports.discriminatedUnion("type", [
15161
- external_exports.strictObject({ type: external_exports.literal("catalog"), id: desktopExtensionIdSchema }),
15162
- external_exports.strictObject({
15163
- type: external_exports.literal("url"),
15164
- url: desktopExtensionHttpUrlSchema,
15165
- expectedSha256: desktopExtensionHashSchema.optional()
15166
- }),
15167
- external_exports.strictObject({
15168
- type: external_exports.literal("zip-base64"),
15169
- fileName: external_exports.string().trim().min(1).max(255),
15170
- contentBase64: external_exports.string().min(4).max(DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH).refine((value) => value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/u.test(value), "Expected standard padded base64")
15171
- })
15172
- ])
15173
- });
15174
- var desktopExtensionsInstallResultSchema = external_exports.strictObject({
15175
- extensionId: desktopExtensionIdSchema,
15176
- version: external_exports.string().min(1),
15177
- replaced: external_exports.boolean(),
15178
- installedPath: external_exports.string(),
15179
- list: desktopExtensionsListResultSchema
15180
- });
15181
- var desktopExtensionsUninstallParamsSchema = external_exports.strictObject({
15182
- id: desktopExtensionIdSchema
15183
- });
15184
- var desktopExtensionsUninstallResultSchema = external_exports.strictObject({
15185
- removedId: desktopExtensionIdSchema,
15186
- list: desktopExtensionsListResultSchema
15187
- });
15188
- var desktopExtensionMutationResultSchema = external_exports.discriminatedUnion("state", [
15189
- external_exports.strictObject({ state: external_exports.literal("saved"), configuration: desktopExtensionConfigurationSchema }),
15190
- external_exports.strictObject({ state: external_exports.literal("slot-conflict"), conflictWith: desktopExtensionIdSchema }),
15191
- external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: revisionSchema })
15192
- ]);
15193
-
15194
- // ../../shared-contracts/dist/errors.js
15195
- var codexhostErrorSchema = external_exports.strictObject({
15196
- code: external_exports.string().min(1),
15197
- message: external_exports.string().min(1),
15198
- retryable: external_exports.boolean(),
15199
- diagnostic: external_exports.string().min(1).optional(),
15200
- stage: external_exports.string().min(1).optional(),
15201
- durationMs: external_exports.number().int().nonnegative().optional(),
15202
- stderrTail: external_exports.string().min(1).optional()
15203
- }).superRefine(rejectExplicitUndefined(["diagnostic", "stage", "durationMs", "stderrTail"]));
15204
-
15205
- // ../../shared-contracts/dist/harness-presentation.js
15206
- var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
15207
- var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text2) => text2.trim().length > 0);
15208
- var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
15209
- label: displayText(256).optional(),
15210
- description: displayText(1024).optional()
15211
- }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15212
- var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15213
-
15214
- // ../../shared-contracts/dist/harness-permission-modes.js
15215
- var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
15216
- var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
15217
- var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
15218
- var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
15219
- var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15220
- message: "Value must not be empty or whitespace"
15221
- });
15222
- var harnessPermissionModeIdSchema = nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~:-]+$/u, "Permission Mode ID must use transport-safe characters").brand();
15223
- var harnessPermissionModeSchema = external_exports.object({
15224
- id: harnessPermissionModeIdSchema,
15225
- label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
15226
- description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
15227
- dangerous: external_exports.boolean().optional(),
15228
- localizations: harnessLocalizationsSchema.optional()
15229
- }).strict();
15230
- var harnessPermissionModeCatalogSchema = external_exports.object({
15231
- modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
15232
- defaultModeId: harnessPermissionModeIdSchema
15233
- }).strict().superRefine((catalog, context) => {
15234
- const ids = /* @__PURE__ */ new Set();
15235
- for (const [index, mode] of catalog.modes.entries()) {
15236
- if (ids.has(mode.id)) {
15237
- context.addIssue({
15238
- code: "custom",
15239
- message: "Permission Mode IDs must be unique",
15240
- path: ["modes", index, "id"]
15241
- });
15242
- }
15243
- ids.add(mode.id);
15244
- }
15245
- if (!ids.has(catalog.defaultModeId)) {
15246
- context.addIssue({
15247
- code: "custom",
15248
- message: "Default Permission Mode must exist in the catalog",
15249
- path: ["defaultModeId"]
15250
- });
14834
+ if (!ids.has(catalog.defaultModeId)) {
14835
+ context.addIssue({
14836
+ code: "custom",
14837
+ message: "Default Permission Mode must exist in the catalog",
14838
+ path: ["defaultModeId"]
14839
+ });
15251
14840
  }
15252
14841
  });
15253
14842
  var threadPermissionModeSelectParamsSchema = external_exports.object({
@@ -15255,6 +14844,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15255
14844
  permissionModeId: harnessPermissionModeIdSchema
15256
14845
  }).strict();
15257
14846
 
14847
+ // ../../shared-contracts/dist/harness-route-limit.js
14848
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
14849
+
15258
14850
  // ../../shared-contracts/dist/thread-usage.js
15259
14851
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15260
14852
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -15280,14 +14872,14 @@ var usageMeasurementsSchema = external_exports.object({
15280
14872
  outputTokensPerSecond: usageMeasurementSchema.refine((value) => value.version === 4).optional().catch(void 0),
15281
14873
  timeToFirstOutputMs: usageMeasurementSchema.extend({ value: nonNegativeSafeIntegerSchema }).optional()
15282
14874
  }).strict();
15283
- var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text2) => text2.length <= maximum));
14875
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text3) => text3.length <= maximum));
15284
14876
  var composerIndicatorsSchema = external_exports.array(external_exports.object({
15285
14877
  kind: external_exports.literal("countdown"),
15286
14878
  id: external_exports.string().min(1).max(64),
15287
14879
  expiresAtUnix: nonNegativeSafeIntegerSchema,
15288
14880
  label: indicatorTextSchema(256).optional(),
15289
14881
  tooltip: indicatorTextSchema(1024).optional()
15290
- }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
14882
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
15291
14883
  message: "Composer indicator IDs must be unique"
15292
14884
  });
15293
14885
  var threadUsageSnapshotSchema = external_exports.object({
@@ -15313,6 +14905,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15313
14905
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15314
14906
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15315
14907
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
14908
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15316
14909
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15317
14910
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15318
14911
  }).strict().superRefine((usage, context) => {
@@ -15440,10 +15033,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
15440
15033
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15441
15034
  message: "Value must not be empty or whitespace"
15442
15035
  });
15443
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
15036
+ var harnessModelRefIdSchema = external_exports.string().min(1).max(HARNESS_MODEL_REF_MAX_LENGTH).refine((id2) => !new RegExp("\\p{Cc}", "u").test(id2), "Model Ref must not contain control characters").brand();
15037
+ var harnessModelServiceTierSchema = external_exports.enum(["priority", "ultrafast"]);
15444
15038
  var harnessModelRefSchema = external_exports.object({
15445
- id: harnessModelRefIdSchema
15039
+ id: harnessModelRefIdSchema,
15040
+ serviceTier: harnessModelServiceTierSchema.optional()
15446
15041
  }).strict();
15042
+ function sameHarnessModelRef(left, right) {
15043
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
15044
+ }
15447
15045
  var harnessThinkingOptionIdSchema = nonBlankTextSchema2.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
15448
15046
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15449
15047
  var harnessThinkingOptionSchema = external_exports.object({
@@ -15457,7 +15055,15 @@ var harnessModelSchema = external_exports.object({
15457
15055
  /** Optional opaque selection for this same Model with priority processing enabled. */
15458
15056
  fastModel: harnessModelRefSchema.optional(),
15459
15057
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
15460
- }).strict();
15058
+ }).strict().refine((model2) => model2.fastModel?.serviceTier === void 0 || model2.fastModel.id === model2.ref.id, {
15059
+ path: ["fastModel", "id"],
15060
+ message: "A tiered Fast Model must share the base Model ID"
15061
+ });
15062
+ function catalogModelForRef(catalog, ref) {
15063
+ if (!ref)
15064
+ return void 0;
15065
+ return catalog?.models.find((model2) => sameHarnessModelRef(model2.ref, ref) || sameHarnessModelRef(model2.fastModel, ref));
15066
+ }
15461
15067
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
15462
15068
  const ids = /* @__PURE__ */ new Set();
15463
15069
  for (const [index, option] of options.entries()) {
@@ -15477,26 +15083,26 @@ var harnessModelCatalogSchema = external_exports.object({
15477
15083
  thinkingOptions: harnessThinkingOptionsSchema,
15478
15084
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
15479
15085
  }).strict().superRefine((catalog, context) => {
15480
- const refs = /* @__PURE__ */ new Set();
15481
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15086
+ const refs = [];
15087
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
15482
15088
  for (const [index, model2] of catalog.models.entries()) {
15483
- if (refs.has(model2.ref.id)) {
15089
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
15484
15090
  context.addIssue({
15485
15091
  code: "custom",
15486
15092
  message: "Model Catalog refs must be unique",
15487
15093
  path: ["models", index, "ref", "id"]
15488
15094
  });
15489
15095
  }
15490
- refs.add(model2.ref.id);
15096
+ refs.push(model2.ref);
15491
15097
  if (model2.fastModel) {
15492
- if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15098
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.fastModel))) {
15493
15099
  context.addIssue({
15494
15100
  code: "custom",
15495
15101
  message: "Fast Model refs must be distinct and unique",
15496
15102
  path: ["models", index, "fastModel"]
15497
15103
  });
15498
15104
  }
15499
- refs.add(model2.fastModel.id);
15105
+ refs.push(model2.fastModel);
15500
15106
  }
15501
15107
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15502
15108
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -15517,7 +15123,7 @@ var harnessModelCatalogSchema = external_exports.object({
15517
15123
  }
15518
15124
  }
15519
15125
  }
15520
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
15126
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
15521
15127
  context.addIssue({
15522
15128
  code: "custom",
15523
15129
  message: "Default Model must exist in the Model Catalog",
@@ -15557,7 +15163,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15557
15163
  observe: external_exports.boolean()
15558
15164
  }).strict().optional(),
15559
15165
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15560
- steer: external_exports.boolean().optional()
15166
+ steer: external_exports.boolean().optional(),
15167
+ /**
15168
+ * True when the native plan (task list) outlives the Turn that changed it, so a reopened
15169
+ * Thread gets its latest plan again. Otherwise a plan stays with the Turn that made it.
15170
+ */
15171
+ persistentPlan: external_exports.boolean().optional()
15561
15172
  }).strict();
15562
15173
  var harnessConfigurationStateSchema = external_exports.object({
15563
15174
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15566,7 +15177,7 @@ var harnessConfigurationStateSchema = external_exports.object({
15566
15177
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15567
15178
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
15568
15179
  }).strict().superRefine((state, context) => {
15569
- if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id }) => id === state.effectiveThinkingOptionId)) {
15180
+ if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id: id2 }) => id2 === state.effectiveThinkingOptionId)) {
15570
15181
  context.addIssue({
15571
15182
  code: "custom",
15572
15183
  message: "Effective Thinking option must be currently available",
@@ -15606,7 +15217,8 @@ var harnessInspectParamsSchema = external_exports.object({
15606
15217
  cwd: nonBlankTextSchema2.max(16384).optional(),
15607
15218
  refresh: external_exports.boolean().optional(),
15608
15219
  /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15609
- purpose: external_exports.literal("availability").optional()
15220
+ purpose: external_exports.literal("availability").optional(),
15221
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
15610
15222
  }).strict();
15611
15223
  var harnessWebUiOpenParamsSchema = external_exports.object({
15612
15224
  harnessId: harnessIdSchema
@@ -15637,12 +15249,14 @@ var codexThreadInspectionSchema = external_exports.object({
15637
15249
  var externalThreadInspectionSchema = external_exports.object({
15638
15250
  owner: external_exports.literal("external"),
15639
15251
  harnessId: nonBlankTextSchema2.max(256),
15640
- transportModelId: nonBlankTextSchema2.max(1024),
15252
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
15641
15253
  effectiveModel: harnessModelRefSchema.optional(),
15642
15254
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15643
15255
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15644
15256
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15645
15257
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
15258
+ /** Live Session catalog when it, not the Adapter inspection, contains `effectiveModel`. */
15259
+ catalog: harnessModelCatalogSchema.optional(),
15646
15260
  history: harnessHistoryCapabilitiesSchema,
15647
15261
  usage: threadUsageSnapshotSchema.optional(),
15648
15262
  locked: external_exports.literal(true)
@@ -15679,45 +15293,590 @@ var threadOwnershipSchema = external_exports.discriminatedUnion("owner", [
15679
15293
  codexThreadOwnershipSchema,
15680
15294
  externalThreadOwnershipSchema
15681
15295
  ]);
15682
- var threadOwnershipListResultSchema = external_exports.object({
15683
- threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
15684
- }).strict().superRefine(({ threads }, context) => {
15685
- const seen = /* @__PURE__ */ new Set();
15686
- for (const [index, thread2] of threads.entries()) {
15687
- if (seen.has(thread2.threadId)) {
15688
- context.addIssue({
15689
- code: "custom",
15690
- message: "Thread ownership-list results must be unique",
15691
- path: ["threads", index, "threadId"]
15692
- });
15693
- }
15694
- seen.add(thread2.threadId);
15695
- }
15296
+ var threadOwnershipListResultSchema = external_exports.object({
15297
+ threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
15298
+ }).strict().superRefine(({ threads }, context) => {
15299
+ const seen = /* @__PURE__ */ new Set();
15300
+ for (const [index, thread2] of threads.entries()) {
15301
+ if (seen.has(thread2.threadId)) {
15302
+ context.addIssue({
15303
+ code: "custom",
15304
+ message: "Thread ownership-list results must be unique",
15305
+ path: ["threads", index, "threadId"]
15306
+ });
15307
+ }
15308
+ seen.add(thread2.threadId);
15309
+ }
15310
+ });
15311
+ var threadSteeringInspectParamsSchema = external_exports.object({
15312
+ threadId: hostThreadIdSchema,
15313
+ /** The text about to be steered; a Harness command always stops and restarts. */
15314
+ text: external_exports.string().optional()
15315
+ }).strict();
15316
+ var threadSteeringContextSchema = external_exports.object({
15317
+ kind: external_exports.literal("application"),
15318
+ value: external_exports.string().transform((text3, context) => {
15319
+ try {
15320
+ return JSON.parse(text3);
15321
+ } catch {
15322
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15323
+ return external_exports.NEVER;
15324
+ }
15325
+ }).pipe(external_exports.object({
15326
+ expectedTurnId: hostTurnIdSchema,
15327
+ clientUserMessageId: external_exports.string().min(1),
15328
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15329
+ }).strict())
15330
+ }).strict().transform((context) => context.value);
15331
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15332
+ var threadSteeringInspectResultSchema = external_exports.object({
15333
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15334
+ }).strict();
15335
+
15336
+ // ../../shared-contracts/dist/harness-plugins.js
15337
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15338
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15339
+ var HARNESS_PLUGIN_LIMIT = 128;
15340
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
15341
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
15342
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id2) => id2 !== "codex", "The official Codex identity is reserved");
15343
+ var pluginRelativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15344
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15345
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15346
+ var harnessInstallationGuideSchema = external_exports.object({
15347
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15348
+ before: localizedTextSchema.optional(),
15349
+ after: localizedTextSchema.optional(),
15350
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15351
+ }).strict();
15352
+ var pluginPresentationShape = {
15353
+ id: installedHarnessPluginIdSchema,
15354
+ name: external_exports.string().trim().min(1).max(128),
15355
+ version: external_exports.string().min(1).max(128),
15356
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15357
+ kind: external_exports.literal("usage").optional(),
15358
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15359
+ iconStyle: external_exports.object({
15360
+ vector: external_exports.object({
15361
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15362
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15363
+ paths: external_exports.array(external_exports.object({
15364
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15365
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15366
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15367
+ }).strict()).min(1).max(32)
15368
+ }).strict().optional(),
15369
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15370
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15371
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15372
+ }).strict().optional(),
15373
+ installation: harnessInstallationGuideSchema.optional(),
15374
+ notice: localizedTextSchema.optional(),
15375
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15376
+ launchCommand: external_exports.literal(true).optional(),
15377
+ links: external_exports.object({
15378
+ website: documentationUrlSchema.optional(),
15379
+ documentation: documentationUrlSchema.optional(),
15380
+ installation: documentationUrlSchema.optional()
15381
+ }).strict().optional()
15382
+ };
15383
+ var harnessPluginManifestSchema = external_exports.object({
15384
+ manifestVersion: external_exports.literal(1),
15385
+ ...pluginPresentationShape,
15386
+ adapterApiVersion: external_exports.number().int().positive(),
15387
+ entry: pluginRelativeResourceSchema,
15388
+ icon: pluginRelativeResourceSchema.optional()
15389
+ }).strict();
15390
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15391
+ var harnessPluginDescriptorSchema = external_exports.object({
15392
+ ...pluginPresentationShape,
15393
+ icon: harnessPluginIconSchema.optional()
15394
+ }).strict();
15395
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15396
+ var harnessPluginListResultSchema = external_exports.object({
15397
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15398
+ }).strict();
15399
+ var harnessPluginConfigurationSchema = external_exports.object({
15400
+ version: external_exports.literal(1),
15401
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15402
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15403
+ message: "Enabled plugin IDs must be unique",
15404
+ path: ["enabled"]
15405
+ });
15406
+
15407
+ // ../../shared-contracts/dist/desktop-extensions.js
15408
+ var DESKTOP_EXTENSION_API_VERSION = 1;
15409
+ var DESKTOP_EXTENSION_LIMIT = 64;
15410
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15411
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15412
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15413
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15414
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15415
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15416
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15417
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15418
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15419
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15420
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15421
+ var desktopExtensionIdSchema = installedPluginIdSchema;
15422
+ var desktopExtensionSlotSchema = external_exports.enum([
15423
+ "sidebar.thread-layout",
15424
+ "sidebar.thread-badge",
15425
+ "appearance.theme"
15426
+ ]);
15427
+ var desktopExtensionCategorySchema = external_exports.enum([
15428
+ "appearance",
15429
+ "interface",
15430
+ "workflow",
15431
+ "analytics",
15432
+ "integrations",
15433
+ "tools"
15434
+ ]);
15435
+ var extensionName = external_exports.string().trim().min(1).max(128);
15436
+ function desktopExtensionScreenshotMimeType(resource) {
15437
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15438
+ case "png":
15439
+ return "image/png";
15440
+ case "jpg":
15441
+ case "jpeg":
15442
+ return "image/jpeg";
15443
+ case "webp":
15444
+ return "image/webp";
15445
+ default:
15446
+ return void 0;
15447
+ }
15448
+ }
15449
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15450
+ var imagePathSchema = pluginRelativeResourceSchema.refine((resource) => desktopExtensionScreenshotMimeType(resource) !== void 0 && hasPortableSegments(resource), "Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space");
15451
+ var desktopExtensionHttpUrlSchema = external_exports.string().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu, "Expected an HTTP(S) URL").pipe(external_exports.url({ protocol: /^https?$/u })).refine((value) => {
15452
+ const { username, password } = new URL(value);
15453
+ return !username && !password && !/[\\\s]/u.test(value);
15454
+ }, "URL must not contain credentials, backslashes, or whitespace");
15455
+ function localizedText(text3) {
15456
+ return external_exports.strictObject({ en: text3, "zh-CN": text3 });
15457
+ }
15458
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15459
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15460
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15461
+ var settingField = {
15462
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15463
+ label: desktopExtensionLocalizedTextSchema,
15464
+ description: desktopExtensionLocalizedTextSchema.optional()
15465
+ };
15466
+ var numericSetting = {
15467
+ ...settingField,
15468
+ step: external_exports.number().positive().optional(),
15469
+ default: external_exports.number().optional()
15470
+ };
15471
+ var settingOption = external_exports.strictObject({
15472
+ value: external_exports.string(),
15473
+ label: desktopExtensionLocalizedTextSchema
15474
+ });
15475
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15476
+ external_exports.strictObject({
15477
+ ...settingField,
15478
+ type: external_exports.literal("boolean"),
15479
+ default: external_exports.boolean().optional()
15480
+ }),
15481
+ external_exports.strictObject({
15482
+ ...settingField,
15483
+ type: external_exports.literal("string"),
15484
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
15485
+ default: external_exports.string().optional()
15486
+ }),
15487
+ external_exports.strictObject({
15488
+ ...numericSetting,
15489
+ type: external_exports.literal("number"),
15490
+ min: external_exports.number().optional(),
15491
+ max: external_exports.number().optional()
15492
+ }),
15493
+ external_exports.strictObject({
15494
+ ...numericSetting,
15495
+ type: external_exports.literal("range"),
15496
+ min: external_exports.number(),
15497
+ max: external_exports.number()
15498
+ }),
15499
+ external_exports.strictObject({
15500
+ ...settingField,
15501
+ type: external_exports.literal("select"),
15502
+ options: external_exports.array(settingOption).min(1),
15503
+ default: external_exports.string().optional()
15504
+ })
15505
+ ]).superRefine((field3, ctx) => {
15506
+ const issue2 = (path8, message) => ctx.addIssue({ code: "custom", path: [path8], message });
15507
+ if (field3.type === "number" || field3.type === "range") {
15508
+ const { min = -Infinity, max = Infinity, default: value } = field3;
15509
+ if (min > max)
15510
+ issue2("max", "Must be at least min");
15511
+ if (value !== void 0 && (value < min || value > max))
15512
+ issue2("default", "Must be within min and max");
15513
+ } else if (field3.type === "select") {
15514
+ const values = new Set(field3.options.map(({ value }) => value));
15515
+ if (values.size !== field3.options.length)
15516
+ issue2("options", "Duplicate option values");
15517
+ if (field3.default !== void 0 && !values.has(field3.default))
15518
+ issue2("default", "Must match an option value");
15519
+ }
15520
+ });
15521
+ var manifestHeader = external_exports.object({
15522
+ manifestVersion: external_exports.int().positive(),
15523
+ id: desktopExtensionIdSchema,
15524
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
15525
+ version: external_exports.string().min(1).max(128),
15526
+ desktopApi: external_exports.int().positive()
15527
+ }).passthrough();
15528
+ var desktopExtensionManifestSchema = manifestHeader.extend({
15529
+ manifestVersion: external_exports.literal(1),
15530
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15531
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15532
+ author: external_exports.string().trim().min(1).max(128).optional(),
15533
+ repository: desktopExtensionHttpUrlSchema.optional(),
15534
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15535
+ icon: imagePathSchema.optional(),
15536
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15537
+ desktop: external_exports.strictObject({
15538
+ script: pluginRelativeResourceSchema,
15539
+ style: pluginRelativeResourceSchema.optional()
15540
+ }).optional(),
15541
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15542
+ slots: slotsSchema.default(() => []),
15543
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15544
+ categories: categoriesSchema.optional()
15545
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15546
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15547
+ var desktopExtensionStatusSchema = external_exports.strictObject({
15548
+ state: external_exports.enum([
15549
+ "running",
15550
+ "disabled",
15551
+ "invalid",
15552
+ "incompatible",
15553
+ "conflict",
15554
+ "failed",
15555
+ "waiting"
15556
+ ]),
15557
+ hash: desktopExtensionHashSchema.optional(),
15558
+ error: external_exports.string().optional(),
15559
+ conflictWith: desktopExtensionIdSchema.optional()
15560
+ });
15561
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15562
+ controllerPid: external_exports.int().positive(),
15563
+ targetId: external_exports.string().nullable(),
15564
+ updatedAt: external_exports.iso.datetime(),
15565
+ handledReloadToken: external_exports.uuid().optional(),
15566
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema),
15567
+ surfaces: external_exports.record(external_exports.string(), desktopExtensionStatusSchema).optional()
15568
+ });
15569
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15570
+ function isGitHubDesktopExtensionZipballUrl(url2) {
15571
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15572
+ }
15573
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input2) => {
15574
+ const url2 = new URL(input2);
15575
+ return /\.zip$/iu.test(url2.pathname) || isGitHubDesktopExtensionZipballUrl(url2) || url2.origin === "https://github.com" && /^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(url2.pathname) || url2.origin === "https://codeload.github.com" && /^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(url2.pathname);
15576
+ }, "Expected a .zip download URL or a GitHub zipball URL");
15577
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15578
+ id: desktopExtensionIdSchema,
15579
+ version: external_exports.string().trim().min(1).max(128),
15580
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15581
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
15582
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15583
+ author: external_exports.string().trim().min(1).max(128),
15584
+ repository: desktopExtensionHttpUrlSchema,
15585
+ stars: external_exports.number().int().min(0).optional(),
15586
+ downloads: external_exports.number().int().min(0).optional(),
15587
+ categories: categoriesSchema.optional(),
15588
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
15589
+ icon: desktopExtensionHttpUrlSchema.optional(),
15590
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15591
+ downloadUrl: desktopExtensionZipUrlSchema,
15592
+ sha256: desktopExtensionHashSchema,
15593
+ slots: slotsSchema.optional(),
15594
+ publishedAt: external_exports.string().optional(),
15595
+ updatedAt: external_exports.string().optional(),
15596
+ minCodexHostVersion: external_exports.string().optional()
15597
+ });
15598
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
15599
+ schemaVersion: external_exports.literal(1),
15600
+ generatedAt: external_exports.string(),
15601
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15602
+ });
15603
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15604
+
15605
+ // ../../shared-contracts/dist/host-extensions.js
15606
+ var reservedName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu;
15607
+ var HOST_EXTENSION_PAGE_API_VERSION = 1;
15608
+ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedName.test(id2), "Reserved extension ID");
15609
+ var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
15610
+ var hostExtensionDigestSchema = desktopExtensionHashSchema;
15611
+ var hostExtensionActivationIdSchema = external_exports.uuid();
15612
+ var hostExtensionResourcePathSchema = pluginRelativeResourceSchema.refine((resource) => !/[\x00-\x1f\x7f<>"|*]/u.test(resource) && resource.split("/").every((part) => !/[. ]$/u.test(part) && !reservedName.test(part)), "Expected a portable relative resource path").refine((path8) => path8.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
15613
+ var legacy = desktopExtensionManifestSchema.shape;
15614
+ var localized = (max, min = 0) => external_exports.strictObject({
15615
+ en: external_exports.string().trim().min(min).max(max),
15616
+ "zh-CN": external_exports.string().trim().min(min).max(max)
15617
+ });
15618
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path8) => path8.endsWith(suffix), `Expected a ${suffix} file`);
15619
+ var moduleEntry = resourceWithSuffix(".mjs");
15620
+ var style = resourceWithSuffix(".css").optional();
15621
+ var hostExtensionCanonicalPath = (path8) => path8.normalize("NFC").toLowerCase();
15622
+ var hostExtensionManifestV2Schema = external_exports.strictObject({
15623
+ manifestVersion: external_exports.literal(2),
15624
+ id: hostExtensionIdSchema,
15625
+ name: localized(128, 1),
15626
+ version: external_exports.string().trim().min(1).max(128),
15627
+ description: localized(4096),
15628
+ details: localized(16384).optional(),
15629
+ author: legacy.author,
15630
+ repository: legacy.repository,
15631
+ icon: legacy.icon.refine((path8) => path8 === void 0 || hostExtensionResourcePathSchema.safeParse(path8).success),
15632
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path8) => hostExtensionResourcePathSchema.safeParse(path8).success)),
15633
+ categories: legacy.categories,
15634
+ settingsSchema: legacy.settingsSchema,
15635
+ slots: legacy.slots.removeDefault().optional(),
15636
+ page: external_exports.strictObject({
15637
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15638
+ entry: moduleEntry,
15639
+ style,
15640
+ title: localized(128, 1).optional()
15641
+ }).optional(),
15642
+ widget: external_exports.strictObject({
15643
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15644
+ entry: moduleEntry,
15645
+ style
15646
+ }).optional(),
15647
+ desktop: external_exports.strictObject({ apiVersion: external_exports.literal(1), script: resourceWithSuffix(".js"), style }).optional(),
15648
+ web: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry.optional(), style }).refine(({ entry, style: style2 }) => entry !== void 0 || style2 !== void 0, "Expected a Web entry or style").optional(),
15649
+ backend: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry }).optional()
15650
+ }).refine(({ page, widget, desktop, web, backend }) => Boolean(page || widget || desktop || web || backend), "Expected at least one page, widget, desktop, web, or backend entry").refine(({ page, widget, web, backend }) => !backend || [page?.entry, widget?.entry, web?.entry].every((entry) => entry === void 0 || hostExtensionCanonicalPath(entry) !== hostExtensionCanonicalPath(backend.entry)), { path: ["backend", "entry"], message: "A backend entry cannot also be a frontend entry" });
15651
+ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBackend }) {
15652
+ if (hasPage || hasWidget || hasBackend && !hasDesktop && !hasWeb)
15653
+ return ["desktop", "web"];
15654
+ const targets = [];
15655
+ if (hasDesktop)
15656
+ targets.push("desktop");
15657
+ if (hasWeb)
15658
+ targets.push("web");
15659
+ return targets;
15660
+ }
15661
+ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
15662
+
15663
+ // ../../shared-contracts/dist/host-extension-management.js
15664
+ var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
15665
+ var hostExtensionRevisionSchema = external_exports.int().nonnegative();
15666
+ var hostExtensionConfigurationSchema = external_exports.strictObject({
15667
+ revision: hostExtensionRevisionSchema,
15668
+ enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
15669
+ });
15670
+ var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
15671
+ var hostExtensionCatalogEntrySchema = external_exports.object({
15672
+ ...catalogMetadata,
15673
+ id: hostExtensionIdSchema,
15674
+ format: external_exports.literal("codexhost"),
15675
+ targets: external_exports.array(hostExtensionTargetSchema).min(1).max(2).refine((targets) => new Set(targets).size === targets.length, "Duplicate targets"),
15676
+ apis: external_exports.strictObject({
15677
+ page: external_exports.int().positive().optional(),
15678
+ widget: external_exports.int().positive().optional(),
15679
+ desktop: external_exports.int().positive().optional(),
15680
+ web: external_exports.int().positive().optional(),
15681
+ backend: external_exports.int().positive().optional()
15682
+ }),
15683
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
15684
+ }).refine(({ targets, apis }) => {
15685
+ const derived = targetsForCapabilities({
15686
+ hasPage: Boolean(apis.page),
15687
+ hasWidget: Boolean(apis.widget),
15688
+ hasDesktop: Boolean(apis.desktop),
15689
+ hasWeb: Boolean(apis.web),
15690
+ hasBackend: Boolean(apis.backend)
15691
+ });
15692
+ return targets.length === derived.length && derived.every((target2) => targets.includes(target2));
15693
+ }, "Catalog targets must match the declared APIs");
15694
+ var hostExtensionCatalogSchema = external_exports.object({
15695
+ schemaVersion: external_exports.literal(2),
15696
+ generatedAt: external_exports.string().min(1),
15697
+ extensions: external_exports.array(hostExtensionCatalogEntrySchema).max(1e4).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15698
+ });
15699
+ var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
15700
+ catalogUrl: desktopExtensionHttpUrlSchema,
15701
+ fetchedAt: external_exports.iso.datetime(),
15702
+ cached: external_exports.boolean()
15703
+ });
15704
+ var id = { id: hostExtensionIdSchema };
15705
+ var active = {
15706
+ ...id,
15707
+ activationId: hostExtensionActivationIdSchema,
15708
+ digest: hostExtensionDigestSchema
15709
+ };
15710
+ var optionalActivation = { ...id, activationId: active.activationId.optional() };
15711
+ var filePath = external_exports.string().min(1).max(4096).refine((path8) => /^(?:\/|[a-z]:[/\\])/iu.test(path8) && !path8.includes("\0") && !path8.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
15712
+ var gitRef = external_exports.string().min(1).max(256).refine((ref) => ref.split("/").every((part) => part && /^[a-z0-9_.-]+$/iu.test(part) && part !== "." && part !== ".."), "Invalid GitHub ref");
15713
+ function base643(maxBytes) {
15714
+ return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
15715
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
15716
+ return value.length % 4 === 0 && value.length * 3 / 4 - padding <= maxBytes && /^[A-Za-z0-9+/]*={0,2}$/u.test(value);
15717
+ }, "Expected bounded standard padded base64");
15718
+ }
15719
+ var hostExtensionGitHubSourceSchema = external_exports.strictObject({
15720
+ type: external_exports.literal("github"),
15721
+ repository: external_exports.string().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),
15722
+ ref: gitRef.optional(),
15723
+ tag: gitRef.optional(),
15724
+ asset: external_exports.string().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),
15725
+ subpath: hostExtensionResourcePathSchema.optional()
15726
+ }).refine(({ ref, tag, asset }) => !ref || !tag && !asset, "Use either a zipball ref or a release tag/asset");
15727
+ var hostExtensionInstallSourceSchema = external_exports.union([
15728
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15729
+ hostExtensionGitHubSourceSchema,
15730
+ external_exports.strictObject({ type: external_exports.literal("zip"), base64: base643(HOST_EXTENSION_ZIP_MAX_BYTES).min(4) }),
15731
+ external_exports.strictObject({ type: external_exports.literal("zip"), localZipPath: filePath }),
15732
+ external_exports.strictObject({ type: external_exports.literal("localDir"), localDir: filePath })
15733
+ ]);
15734
+ var hostExtensionProvenanceSchema = external_exports.discriminatedUnion("type", [
15735
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15736
+ hostExtensionGitHubSourceSchema,
15737
+ external_exports.strictObject({ type: external_exports.literal("zip") }),
15738
+ external_exports.strictObject({ type: external_exports.literal("localDir") })
15739
+ ]);
15740
+ var hostExtensionInstallationSchema = external_exports.strictObject({
15741
+ ...active,
15742
+ manifest: hostExtensionManifestV2Schema,
15743
+ installedAt: external_exports.iso.datetime(),
15744
+ source: hostExtensionProvenanceSchema.optional()
15696
15745
  });
15697
- var threadSteeringInspectParamsSchema = external_exports.object({
15698
- threadId: hostThreadIdSchema,
15699
- /** The text about to be steered; a Harness command always stops and restarts. */
15700
- text: external_exports.string().optional()
15701
- }).strict();
15702
- var threadSteeringContextSchema = external_exports.object({
15703
- kind: external_exports.literal("application"),
15704
- value: external_exports.string().transform((text2, context) => {
15705
- try {
15706
- return JSON.parse(text2);
15707
- } catch {
15708
- context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15709
- return external_exports.NEVER;
15710
- }
15711
- }).pipe(external_exports.object({
15712
- expectedTurnId: hostTurnIdSchema,
15713
- clientUserMessageId: external_exports.string().min(1),
15714
- delivery: external_exports.enum(["newTurn", "activeTurn"])
15715
- }).strict())
15716
- }).strict().transform((context) => context.value);
15717
- var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15718
- var threadSteeringInspectResultSchema = external_exports.object({
15719
- delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15720
- }).strict();
15746
+ var rasterDataUrlSchema = (maxBytes) => external_exports.string().max("data:image/jpeg;base64,".length + 4 * Math.ceil(maxBytes / 3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u);
15747
+ var desktopConflict = { desktopConflictWith: hostExtensionIdSchema.optional() };
15748
+ var backendState = external_exports.enum(["none", "inactive", "starting", "running", "failed"]);
15749
+ var hostExtensionListItemSchema = external_exports.discriminatedUnion("state", [
15750
+ hostExtensionInstallationSchema.extend({
15751
+ state: external_exports.literal("valid"),
15752
+ enabled: external_exports.boolean(),
15753
+ ...desktopConflict,
15754
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15755
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15756
+ backendState: backendState.optional(),
15757
+ backendError: external_exports.string().optional()
15758
+ }),
15759
+ external_exports.strictObject({
15760
+ state: external_exports.enum(["invalid", "incompatible"]),
15761
+ id: external_exports.string().min(1),
15762
+ enabled: external_exports.boolean(),
15763
+ error: external_exports.string()
15764
+ })
15765
+ ]);
15766
+ var hostExtensionsListResultSchema = external_exports.strictObject({
15767
+ revision: hostExtensionRevisionSchema,
15768
+ configuration: hostExtensionConfigurationSchema,
15769
+ diagnostics: external_exports.array(external_exports.string()),
15770
+ extensions: external_exports.array(hostExtensionListItemSchema)
15771
+ });
15772
+ var hostExtensionRuntimeEntrySchema = hostExtensionInstallationSchema.extend({
15773
+ ...desktopConflict,
15774
+ settingsRevision: hostExtensionRevisionSchema
15775
+ });
15776
+ var hostExtensionsSnapshotResultSchema = external_exports.strictObject({
15777
+ /** The Host publishes this revision in extensions-changed, independent of enabled.json's revision. */
15778
+ revision: hostExtensionRevisionSchema,
15779
+ // Enabled, valid activations only. A Desktop conflict does not hide other capabilities.
15780
+ extensions: external_exports.array(hostExtensionRuntimeEntrySchema).max(DESKTOP_EXTENSION_LIMIT)
15781
+ });
15782
+ var HOST_EXTENSIONS_RPC = {
15783
+ list: "codexhost/extensions/list",
15784
+ snapshot: "codexhost/extensions/snapshot",
15785
+ catalog: "codexhost/extensions/catalog",
15786
+ install: "codexhost/extensions/install",
15787
+ update: "codexhost/extensions/update",
15788
+ enable: "codexhost/extensions/enable",
15789
+ disable: "codexhost/extensions/disable",
15790
+ uninstall: "codexhost/extensions/uninstall",
15791
+ recover: "codexhost/extensions/recover",
15792
+ asset: "codexhost/extensions/asset",
15793
+ settingsGet: "codexhost/extensions/settings/get",
15794
+ settingsSet: "codexhost/extensions/settings/set",
15795
+ backendInvoke: "codexhost/extensions/backend/invoke"
15796
+ };
15797
+ var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
15798
+ var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
15799
+ var noParams = external_exports.strictObject({});
15800
+ var expectedRevision = { expectedRevision: hostExtensionRevisionSchema };
15801
+ var selection = external_exports.strictObject({ ...id, ...expectedRevision });
15802
+ var installationResult = hostExtensionInstallationSchema.extend({ replaced: external_exports.boolean() });
15803
+ var mutationResult = external_exports.discriminatedUnion("state", [
15804
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: hostExtensionConfigurationSchema }),
15805
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: hostExtensionRevisionSchema })
15806
+ ]);
15807
+ var hostExtensionsAssetParamsSchema = external_exports.strictObject({
15808
+ ...optionalActivation,
15809
+ digest: active.digest.optional(),
15810
+ path: hostExtensionResourcePathSchema
15811
+ });
15812
+ var hostExtensionsAssetResultSchema = external_exports.strictObject({
15813
+ mimeType: external_exports.string().min(1),
15814
+ base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
15815
+ digest: active.digest
15816
+ });
15817
+ var hostExtensionSettingsSchema = external_exports.strictObject({
15818
+ settingsRevision: hostExtensionRevisionSchema,
15819
+ values: jsonObjectSchema
15820
+ });
15821
+ var hostExtensionsRpcSchemas = {
15822
+ [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
15823
+ [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
15824
+ [HOST_EXTENSIONS_RPC.catalog]: {
15825
+ params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
15826
+ result: hostExtensionsCatalogResultSchema
15827
+ },
15828
+ [HOST_EXTENSIONS_RPC.install]: {
15829
+ params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
15830
+ result: installationResult
15831
+ },
15832
+ [HOST_EXTENSIONS_RPC.update]: {
15833
+ params: external_exports.strictObject({
15834
+ ...id,
15835
+ expectedDigest: active.digest,
15836
+ expectedActivationId: active.activationId.optional(),
15837
+ source: hostExtensionInstallSourceSchema.optional()
15838
+ }),
15839
+ result: installationResult
15840
+ },
15841
+ [HOST_EXTENSIONS_RPC.enable]: { params: selection, result: mutationResult },
15842
+ [HOST_EXTENSIONS_RPC.disable]: { params: selection, result: mutationResult },
15843
+ [HOST_EXTENSIONS_RPC.uninstall]: {
15844
+ params: external_exports.strictObject({
15845
+ ...id,
15846
+ removeData: external_exports.boolean().optional(),
15847
+ expectedDigest: active.digest.optional()
15848
+ }),
15849
+ result: external_exports.strictObject({ ...id, removed: external_exports.boolean() })
15850
+ },
15851
+ [HOST_EXTENSIONS_RPC.recover]: {
15852
+ params: external_exports.strictObject({ expectedRevision: expectedRevision.expectedRevision.optional() }),
15853
+ result: mutationResult
15854
+ },
15855
+ [HOST_EXTENSIONS_RPC.asset]: {
15856
+ params: hostExtensionsAssetParamsSchema,
15857
+ result: hostExtensionsAssetResultSchema
15858
+ },
15859
+ [HOST_EXTENSIONS_RPC.settingsGet]: {
15860
+ params: external_exports.strictObject(optionalActivation),
15861
+ result: hostExtensionSettingsSchema
15862
+ },
15863
+ [HOST_EXTENSIONS_RPC.settingsSet]: {
15864
+ params: external_exports.strictObject({
15865
+ ...optionalActivation,
15866
+ expectedSettingsRevision: hostExtensionRevisionSchema,
15867
+ values: jsonObjectSchema
15868
+ }),
15869
+ result: hostExtensionSettingsSchema
15870
+ },
15871
+ [HOST_EXTENSIONS_RPC.backendInvoke]: {
15872
+ params: external_exports.strictObject({
15873
+ ...optionalActivation,
15874
+ method: hostExtensionBackendMethodSchema,
15875
+ params: jsonValueSchema.optional()
15876
+ }),
15877
+ result: external_exports.strictObject({ result: jsonValueSchema })
15878
+ }
15879
+ };
15721
15880
 
15722
15881
  // ../../shared-contracts/dist/thread-archive-confirm.js
15723
15882
  var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
@@ -15763,6 +15922,8 @@ var CLIENT_CHANNEL_METHODS = [
15763
15922
  "codexhost/workspace/read",
15764
15923
  "codexhost/thread/tree/read",
15765
15924
  "codexhost/thread/pins/list",
15925
+ "codexhost/thread/sections/list",
15926
+ "codexhost/thread/sections/move",
15766
15927
  "codexhost/thread/pins/set",
15767
15928
  "codexhost/harness/plugins/list",
15768
15929
  "codexhost/harness/inspect",
@@ -15780,7 +15941,7 @@ var CLIENT_CHANNEL_METHODS = [
15780
15941
  "codexhost/harness/session-import/list",
15781
15942
  "codexhost/harness/session-import/import",
15782
15943
  // Host settings shared across Desktop and Web.
15783
- ...DESKTOP_EXTENSION_MANAGEMENT_METHODS,
15944
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
15784
15945
  "codexhost/harness/installation",
15785
15946
  "codexhost/harness/installation/start",
15786
15947
  "codexhost/harness/installation/status",
@@ -15801,8 +15962,21 @@ var CLIENT_CHANNEL_METHODS = [
15801
15962
  "codexhost/update/check",
15802
15963
  "codexhost/update/start",
15803
15964
  "codexhost/update/status",
15965
+ "codexhost/announcement/get",
15966
+ "codexhost/announcement/acknowledge",
15804
15967
  "codexhost/sessions/loaded/list"
15805
15968
  ];
15969
+ var clientThreadSectionsSchema = external_exports.object({
15970
+ sections: external_exports.array(external_exports.object({
15971
+ id: external_exports.string().min(1),
15972
+ name: external_exports.string().min(1),
15973
+ threads: external_exports.array(jsonObjectSchema)
15974
+ }).strict())
15975
+ }).strict();
15976
+ var clientThreadSectionMoveSchema = external_exports.object({
15977
+ threadId: external_exports.string().min(1).max(1024),
15978
+ sectionId: external_exports.string().min(1).max(1024).nullable()
15979
+ }).strict();
15806
15980
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15807
15981
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15808
15982
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -15841,6 +16015,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15841
16015
  cursor: clientChannelCursorSchema,
15842
16016
  revision: external_exports.number().int().nonnegative()
15843
16017
  }),
16018
+ external_exports.object({
16019
+ type: external_exports.literal("extensions-changed"),
16020
+ cursor: clientChannelCursorSchema,
16021
+ revision: hostExtensionRevisionSchema
16022
+ }),
15844
16023
  external_exports.object({
15845
16024
  type: external_exports.literal("hello"),
15846
16025
  version: external_exports.literal(1),
@@ -16277,7 +16456,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
16277
16456
 
16278
16457
  // ../../shared-contracts/dist/harness-preferences.js
16279
16458
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
16280
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
16459
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
16281
16460
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
16282
16461
  model: harnessModelRefSchema.optional(),
16283
16462
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -16287,11 +16466,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
16287
16466
  lastHarness: harnessIdSchema.optional(),
16288
16467
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
16289
16468
  });
16469
+ var harnessDelegationDefaultSchema = external_exports.strictObject({
16470
+ model: harnessModelRefSchema.optional(),
16471
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional()
16472
+ }).refine((value) => Boolean(value.model || value.thinkingOptionId), "A delegation default must contain a Model or Thinking option");
16473
+ var delegationDefaultsSchema = external_exports.strictObject({
16474
+ byHarness: external_exports.record(preferenceHarnessKey, harnessDelegationDefaultSchema)
16475
+ });
16290
16476
  var modelId = external_exports.string().min(1).max(1024);
16291
16477
  var harnessPreferenceValuesSchema = external_exports.strictObject({
16292
16478
  idleRelease: idleReleaseSettingsSchema.optional(),
16293
16479
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
16294
- newThread: newThreadDefaultsSchema.optional()
16480
+ newThread: newThreadDefaultsSchema.optional(),
16481
+ delegation: delegationDefaultsSchema.optional()
16295
16482
  });
16296
16483
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
16297
16484
  scope: harnessPreferenceScopeSchema,
@@ -16319,6 +16506,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
16319
16506
  lastHarness: harnessIdSchema.optional(),
16320
16507
  harnessId: harnessIdSchema.optional(),
16321
16508
  configuration: harnessDefaultConfigurationSchema.optional()
16509
+ }),
16510
+ external_exports.strictObject({
16511
+ kind: external_exports.literal("delegation"),
16512
+ harnessId: harnessIdSchema,
16513
+ configuration: harnessDelegationDefaultSchema.nullable()
16322
16514
  })
16323
16515
  ]);
16324
16516
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -16326,8 +16518,8 @@ var harnessPreferencePatchSchema = external_exports.strictObject({
16326
16518
  operations: external_exports.array(harnessPreferenceOperationSchema).min(1).max(256),
16327
16519
  initializeOnly: external_exports.boolean().optional(),
16328
16520
  expectedRevision: external_exports.number().int().nonnegative().optional()
16329
- }).superRefine((input, ctx) => {
16330
- for (const operation of input.operations) {
16521
+ }).superRefine((input2, ctx) => {
16522
+ for (const operation of input2.operations) {
16331
16523
  if (operation.kind === "newThread" && (!operation.lastHarness && !operation.configuration || Boolean(operation.harnessId) !== Boolean(operation.configuration)))
16332
16524
  ctx.addIssue({
16333
16525
  code: "custom",
@@ -16729,13 +16921,18 @@ var harnessLaunchSettingsSchema = external_exports.object({
16729
16921
  // ../../shared-contracts/dist/harness-installation.js
16730
16922
  var harnessInstallationParamsSchema = external_exports.object({
16731
16923
  harnessId: harnessIdSchema,
16732
- action: external_exports.enum(["check", "update", "install"])
16733
- }).strict();
16924
+ action: external_exports.enum(["check", "update", "install"]),
16925
+ confirmedVersion: external_exports.string().min(1).max(128).optional()
16926
+ }).strict().refine(({ action, confirmedVersion }) => action === "update" || confirmedVersion === void 0);
16734
16927
  var harnessInstallationStateSchema = external_exports.object({
16735
16928
  currentVersion: external_exports.string().min(1).max(128),
16736
16929
  latestVersion: external_exports.string().min(1).max(128),
16737
16930
  updateAvailable: external_exports.boolean(),
16738
16931
  canUpdate: external_exports.boolean(),
16932
+ /** Present when the Adapter has a verified list and the available target is outside it. */
16933
+ latestVerifiedVersion: external_exports.string().min(1).max(128).optional(),
16934
+ /** Update preflight stopped before running the installer; latestVersion needs confirmation. */
16935
+ confirmationRequired: external_exports.literal(true).optional(),
16739
16936
  /** Defaults to CLI; some Harnesses ship only inside a desktop application. */
16740
16937
  versionKind: external_exports.enum(["cli", "application"]).optional(),
16741
16938
  /** Official download opened by the user; does not imply an automatic installation. */
@@ -17065,6 +17262,38 @@ var updateStatusResultSchema = external_exports.strictObject({
17065
17262
  status: updateStatusSchema.nullable()
17066
17263
  });
17067
17264
 
17265
+ // ../../shared-contracts/dist/release-announcement.js
17266
+ var RELEASE_ANNOUNCEMENT_MAX_THEMES = 12;
17267
+ var releaseAnnouncementThemeSchema = external_exports.strictObject({
17268
+ icon: external_exports.string().min(1).max(16).optional(),
17269
+ title: external_exports.string().min(1).max(120),
17270
+ body: external_exports.string().min(1).max(1200),
17271
+ contributors: external_exports.array(external_exports.string().min(1).max(39)).max(30)
17272
+ });
17273
+ var releaseAnnouncementContentSchema = external_exports.strictObject({
17274
+ summary: external_exports.string().min(1).max(600).optional(),
17275
+ themes: external_exports.array(releaseAnnouncementThemeSchema).min(1).max(RELEASE_ANNOUNCEMENT_MAX_THEMES)
17276
+ });
17277
+ var releaseAnnouncementSchema = external_exports.strictObject({
17278
+ version: updateSemanticVersionSchema,
17279
+ publishedAt: external_exports.iso.datetime(),
17280
+ url: external_exports.string().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),
17281
+ zh: releaseAnnouncementContentSchema.nullable(),
17282
+ en: releaseAnnouncementContentSchema.nullable()
17283
+ }).refine((value) => value.zh !== null || value.en !== null, {
17284
+ message: "an announcement needs at least one language"
17285
+ });
17286
+ var releaseAnnouncementGetParamsSchema = external_exports.strictObject({
17287
+ manual: external_exports.boolean().optional()
17288
+ });
17289
+ var releaseAnnouncementGetResultSchema = external_exports.strictObject({
17290
+ announcement: releaseAnnouncementSchema.nullable(),
17291
+ unread: external_exports.boolean()
17292
+ });
17293
+ var releaseAnnouncementAcknowledgeParamsSchema = external_exports.strictObject({
17294
+ version: updateSemanticVersionSchema
17295
+ });
17296
+
17068
17297
  // ../../shared-contracts/dist/thread-watch-notice.js
17069
17298
  var THREAD_WATCH_NOTICE_OUTCOMES = [
17070
17299
  "completed",
@@ -17112,17 +17341,67 @@ var remoteSshSetupResultSchema = external_exports.object({ state: external_expor
17112
17341
 
17113
17342
  // ../../shared-contracts/dist/remote-sessions.js
17114
17343
  var REMOTE_CONTROLLER_REQUEST_MAX_BYTES = 16 * 1024;
17115
- var identity = external_exports.string().min(1).max(1024);
17344
+ var REMOTE_IDENTITY_MAX_LENGTH = 1024;
17345
+ var identity = external_exports.string().min(1).max(REMOTE_IDENTITY_MAX_LENGTH);
17116
17346
  var target = { hostId: identity.regex(/^remote-(?:ssh(?:-|:)|control:)/u) };
17117
17347
  var thread = { ...target, threadId: identity };
17348
+ var text2 = external_exports.string().min(1).max(8e3);
17349
+ var input = { text: text2, requestId: identity };
17350
+ var remoteDeliveryReplySchema = external_exports.discriminatedUnion("accepted", [
17351
+ external_exports.object({ accepted: external_exports.literal(true), startQueuedItemId: identity.optional() }),
17352
+ external_exports.object({
17353
+ accepted: external_exports.literal(false),
17354
+ code: external_exports.enum([
17355
+ "remote/queue-unavailable",
17356
+ "remote/steer-unavailable",
17357
+ "remote/turn-changed",
17358
+ "remote/send-rejected",
17359
+ "session/queue-item-not-found",
17360
+ "session/queue-item-starting"
17361
+ ]),
17362
+ message: external_exports.string()
17363
+ })
17364
+ ]);
17365
+ var remoteQueueSnapshotSchema = external_exports.discriminatedUnion("available", [
17366
+ external_exports.object({ available: external_exports.literal(false) }),
17367
+ external_exports.object({
17368
+ available: external_exports.literal(true),
17369
+ items: external_exports.array(external_exports.object({ id: identity, clientUserMessageId: identity, preview: external_exports.string().max(801) })).max(100)
17370
+ })
17371
+ ]);
17118
17372
  var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17119
17373
  external_exports.strictObject({ kind: external_exports.literal("hosts") }),
17374
+ external_exports.strictObject({
17375
+ kind: external_exports.literal("create"),
17376
+ ...target,
17377
+ cwd: external_exports.string().min(1).max(8192),
17378
+ epoch: identity
17379
+ }),
17380
+ external_exports.strictObject({ kind: external_exports.literal("projectHarnesses"), ...target, epoch: identity }),
17381
+ external_exports.strictObject({
17382
+ kind: external_exports.literal("inspectHarness"),
17383
+ ...target,
17384
+ epoch: identity,
17385
+ cwd: external_exports.string().min(1).max(8192),
17386
+ harnessId: identity
17387
+ }),
17388
+ external_exports.strictObject({
17389
+ kind: external_exports.literal("startSelected"),
17390
+ ...target,
17391
+ epoch: identity,
17392
+ cwd: external_exports.string().min(1).max(8192),
17393
+ harnessId: identity,
17394
+ model: external_exports.string().min(1).max(4096),
17395
+ serviceTier: external_exports.enum(["priority", "ultrafast"]).optional(),
17396
+ reasoningEffort: identity.optional()
17397
+ }),
17120
17398
  external_exports.strictObject({ kind: external_exports.literal("status"), ...thread }),
17121
17399
  external_exports.strictObject({
17122
17400
  kind: external_exports.literal("list"),
17123
17401
  ...target,
17124
17402
  cursor: external_exports.string().nullable(),
17125
- archived: external_exports.boolean()
17403
+ archived: external_exports.boolean(),
17404
+ includeLoaded: external_exports.literal(true).optional()
17126
17405
  }),
17127
17406
  external_exports.strictObject({
17128
17407
  kind: external_exports.literal("read"),
@@ -17142,16 +17421,35 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17142
17421
  ...thread,
17143
17422
  epoch: identity,
17144
17423
  modelId: identity.optional(),
17424
+ serviceTier: harnessModelServiceTierSchema.optional(),
17145
17425
  thinkingOptionId: identity.optional(),
17146
17426
  permissionModeId: identity.optional()
17147
- }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17427
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting").refine((value) => value.serviceTier === void 0 || value.modelId !== void 0, {
17428
+ message: "A service tier requires a Model ID"
17429
+ }),
17148
17430
  external_exports.strictObject({
17149
17431
  kind: external_exports.literal("prompt"),
17150
17432
  ...thread,
17151
17433
  epoch: identity,
17152
- text: external_exports.string().min(1).max(8e3),
17434
+ text: text2,
17153
17435
  requestId: identity.optional()
17154
17436
  }),
17437
+ external_exports.strictObject({ kind: external_exports.literal("queue"), ...thread, epoch: identity }),
17438
+ external_exports.strictObject({
17439
+ kind: external_exports.literal("delivery"),
17440
+ ...thread,
17441
+ epoch: identity,
17442
+ action: external_exports.discriminatedUnion("kind", [
17443
+ external_exports.strictObject({ kind: external_exports.literal("enqueue"), ...input }),
17444
+ external_exports.strictObject({ kind: external_exports.literal("steer"), ...input, turnId: identity }),
17445
+ external_exports.strictObject({ kind: external_exports.literal("remove"), itemId: identity }),
17446
+ external_exports.strictObject({
17447
+ kind: external_exports.literal("start"),
17448
+ itemId: identity,
17449
+ onlyIfHead: external_exports.literal(true).optional()
17450
+ })
17451
+ ])
17452
+ }),
17155
17453
  external_exports.strictObject({ kind: external_exports.literal("interrupt"), ...thread, epoch: identity, turnId: identity }),
17156
17454
  external_exports.strictObject({
17157
17455
  kind: external_exports.literal("rename"),
@@ -17194,7 +17492,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
17194
17492
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
17195
17493
  external_exports.strictObject({
17196
17494
  action: external_exports.literal("read-thread"),
17197
- hostId: hostId.refine((id) => id !== "local"),
17495
+ hostId: hostId.refine((id2) => id2 !== "local"),
17198
17496
  input: delegationReadParamsSchema
17199
17497
  }),
17200
17498
  external_exports.strictObject({
@@ -17208,7 +17506,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
17208
17506
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
17209
17507
  external_exports.strictObject({
17210
17508
  action: external_exports.literal("update"),
17211
- hostId: hostId.refine((id) => id !== "local"),
17509
+ hostId: hostId.refine((id2) => id2 !== "local"),
17212
17510
  version: remoteUpdateParamsSchema.shape.version
17213
17511
  })
17214
17512
  ]);
@@ -17272,7 +17570,7 @@ function invalidRequest(message) {
17272
17570
  return { code: "invalidRequest", message, retryable: false };
17273
17571
  }
17274
17572
  function validateHostApprovalResponse(interaction, response) {
17275
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17573
+ return interaction.actions.some(({ id: id2 }) => id2 === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17276
17574
  }
17277
17575
 
17278
17576
  // ../../harness-adapter/dist/question.js
@@ -17280,7 +17578,7 @@ function invalidRequest2(message) {
17280
17578
  return { code: "invalidRequest", message, retryable: false };
17281
17579
  }
17282
17580
  function validateHostQuestionResponse(interaction, response) {
17283
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17581
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
17284
17582
  if (response.cancelled) {
17285
17583
  return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17286
17584
  }
@@ -17311,6 +17609,21 @@ function validateHostQuestionResponse(interaction, response) {
17311
17609
  return null;
17312
17610
  }
17313
17611
 
17612
+ // ../../harness-adapter/dist/composite-model-ref.js
17613
+ function compositeModelRefIds(entries, fallbackId) {
17614
+ const counts = /* @__PURE__ */ new Map();
17615
+ for (const entry of entries) {
17616
+ const id2 = `${entry.provider}/${entry.model}`;
17617
+ counts.set(id2, (counts.get(id2) ?? 0) + 1);
17618
+ }
17619
+ const ids = /* @__PURE__ */ new Map();
17620
+ for (const entry of entries) {
17621
+ const id2 = `${entry.provider}/${entry.model}`;
17622
+ ids.set(counts.get(id2) === 1 ? id2 : fallbackId(entry), entry);
17623
+ }
17624
+ return ids;
17625
+ }
17626
+
17314
17627
  // ../../harness-adapter/dist/output-channel.js
17315
17628
  var HarnessOutputChannel = class {
17316
17629
  outputs;
@@ -17395,7 +17708,8 @@ var tokenFields = [
17395
17708
  var safeIntegerFields = [
17396
17709
  "planFiveHourResetsAtUnix",
17397
17710
  "planSevenDayResetsAtUnix",
17398
- "timeToFirstOutputMs"
17711
+ "timeToFirstOutputMs",
17712
+ "latestRequestTimeToFirstOutputMs"
17399
17713
  ];
17400
17714
  var percentFields = [
17401
17715
  "cacheHitRatePercent",
@@ -17587,9 +17901,9 @@ function subagentConfiguration(value) {
17587
17901
  if (typeof value !== "object" || value === null || Array.isArray(value))
17588
17902
  return {};
17589
17903
  const row = value;
17590
- const text2 = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
17591
- const model2 = row.model === "inherit" ? void 0 : text2(row.model);
17592
- const reasoningEffort = text2(row.reasoningEffort) ?? text2(row.reasoning_effort) ?? text2(row.thinking);
17904
+ const text3 = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
17905
+ const model2 = row.model === "inherit" ? void 0 : text3(row.model);
17906
+ const reasoningEffort = text3(row.reasoningEffort) ?? text3(row.reasoning_effort) ?? text3(row.thinking);
17593
17907
  return { ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17594
17908
  }
17595
17909
  function inheritSubagentConfiguration(child, parent) {
@@ -17637,10 +17951,10 @@ function configureSubagentSnapshot(snapshot, parent) {
17637
17951
  }
17638
17952
 
17639
17953
  // dist/usage.js
17640
- function requestTokens(id, model2, value) {
17954
+ function requestTokens(id2, model2, value) {
17641
17955
  const tokens = record2(value), cache = record2(tokens.cache);
17642
17956
  const request = parseHostUsageRequest({
17643
- requestId: id,
17957
+ requestId: id2,
17644
17958
  ...model2 ? { model: model2 } : {},
17645
17959
  inputTokens: tokens.input,
17646
17960
  outputTokens: tokens.output,
@@ -17734,12 +18048,12 @@ var ZcodeUsage = class {
17734
18048
  const pending2 = this.#pending;
17735
18049
  if (!pending2 || pending2.turnId !== event.turnId || p.source === "subagent")
17736
18050
  return;
17737
- const id = text(p.assistantMessageId);
17738
- if (!id)
18051
+ const id2 = text(p.assistantMessageId);
18052
+ if (!id2)
17739
18053
  return;
17740
- if (pending2.messageId && pending2.messageId !== id)
18054
+ if (pending2.messageId && pending2.messageId !== id2)
17741
18055
  pending2.ambiguous = true;
17742
- pending2.messageId = id;
18056
+ pending2.messageId = id2;
17743
18057
  if (pending2.startedAtMs === void 0 && ((p.kind === "text_delta" || p.kind === "reasoning_delta") && text(p.delta) || p.kind === "tool_input_start" || p.kind === "tool_input_delta" && text(p.delta) || p.kind === "tool_call"))
17744
18058
  pending2.startedAtMs = event.timestamp;
17745
18059
  return;
@@ -17747,11 +18061,11 @@ var ZcodeUsage = class {
17747
18061
  if (event.type !== "session.updated" || p.querySource !== "main_turn")
17748
18062
  return;
17749
18063
  if (p.type === "model_request_started") {
17750
- const id = text(p.requestId), model2 = text(p.modelId);
17751
- if (!id || !model2)
18064
+ const id2 = text(p.requestId), model2 = text(p.modelId);
18065
+ if (!id2 || !model2)
17752
18066
  return;
17753
18067
  this.#pending = {
17754
- id,
18068
+ id: id2,
17755
18069
  model: model2,
17756
18070
  turnId: event.turnId,
17757
18071
  ambiguous: this.#pending !== void 0
@@ -17867,12 +18181,13 @@ function createZcodeUsageStatistics(environment) {
17867
18181
  }
17868
18182
  ];
17869
18183
  },
17870
- readSource: (id) => readZcodeUsage(id)
18184
+ readSource: (id2) => readZcodeUsage(id2)
17871
18185
  });
17872
18186
  }
17873
18187
 
17874
18188
  // dist/adapter.js
17875
- import path6 from "node:path";
18189
+ import path7 from "node:path";
18190
+ import { isDeepStrictEqual } from "node:util";
17876
18191
  import { stat as stat2 } from "node:fs/promises";
17877
18192
 
17878
18193
  // dist/transport.js
@@ -18019,57 +18334,374 @@ function createZcodeInstallation(environment, app) {
18019
18334
  // dist/account.js
18020
18335
  import { createHash as createHash4 } from "node:crypto";
18021
18336
  import { readFile as readFile3 } from "node:fs/promises";
18022
- import path5 from "node:path";
18337
+ import path6 from "node:path";
18023
18338
 
18024
18339
  // dist/credentials.js
18025
18340
  import { createDecipheriv, createHash } from "node:crypto";
18026
- import { readFile } from "node:fs/promises";
18341
+ import { constants } from "node:fs";
18342
+ import { open as open2, readFile } from "node:fs/promises";
18027
18343
  import { homedir as homedir2, platform, userInfo } from "node:os";
18344
+ import path4 from "node:path";
18345
+
18346
+ // dist/credential-keyring.js
18347
+ import { execFile } from "node:child_process";
18028
18348
  import path3 from "node:path";
18029
- function decrypt(value, environment) {
18030
- if (!value.startsWith("enc:v1:"))
18031
- return value;
18349
+ import { promisify } from "node:util";
18350
+ var execute = promisify(execFile);
18351
+ var SERVICE = "ZCode Credential Encryption";
18352
+ var KEYCHAIN_PASSWORD_TIMEOUT_MS = 3e4;
18353
+ var KeychainReadTimeout = class extends Error {
18354
+ };
18355
+ var KeychainAccessDeferred = class extends Error {
18356
+ };
18357
+ var cachedKeys = /* @__PURE__ */ new Map();
18358
+ var deniedReads = /* @__PURE__ */ new Map();
18359
+ var inFlightReads = /* @__PURE__ */ new Map();
18360
+ function invalidateSystemCredentialKey(account, value) {
18361
+ const key = `${process.platform}:${account}`;
18362
+ const cached2 = cachedKeys.get(key);
18363
+ if (cached2?.value !== value)
18364
+ return;
18365
+ if (process.platform === "darwin")
18366
+ cached2.mismatched = true;
18367
+ else
18368
+ cachedKeys.delete(key);
18369
+ }
18370
+ var WIN32_READER = String.raw`
18371
+ $ErrorActionPreference = 'Stop'
18372
+ Add-Type -TypeDefinition @'
18373
+ using System;
18374
+ using System.Runtime.InteropServices;
18375
+
18376
+ public static class ZCodeKeyReader {
18377
+ [StructLayout(LayoutKind.Sequential)]
18378
+ private struct Credential {
18379
+ public uint Flags, Type;
18380
+ public IntPtr TargetName, Comment;
18381
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
18382
+ public uint BlobSize;
18383
+ public IntPtr Blob;
18384
+ }
18385
+
18386
+ [DllImport("advapi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
18387
+ [return: MarshalAs(UnmanagedType.Bool)]
18388
+ private static extern bool CredReadW(string target, uint type, uint flags, out IntPtr result);
18389
+
18390
+ [DllImport("advapi32.dll", ExactSpelling = true)]
18391
+ private static extern void CredFree(IntPtr credential);
18392
+
18393
+ public static string Read(string target) {
18394
+ IntPtr result;
18395
+ if (!CredReadW(target, 1, 0, out result)) return null; // CRED_TYPE_GENERIC
18396
+ try {
18397
+ var credential = (Credential)Marshal.PtrToStructure(result, typeof(Credential));
18398
+ if (credential.Blob == IntPtr.Zero || credential.BlobSize != 86) return null;
18399
+ return Marshal.PtrToStringUni(credential.Blob, 43);
18400
+ } finally { CredFree(result); }
18401
+ }
18402
+ }
18403
+ '@
18404
+ `;
18405
+ var readSystemCredentialKey = async (account, options = {}) => {
18406
+ if (!/^[a-f0-9]{64}$/.test(account))
18407
+ return;
18408
+ const cacheKey = `${process.platform}:${account}`;
18409
+ const existing = inFlightReads.get(cacheKey);
18410
+ if (existing)
18411
+ return existing;
18412
+ const mayRetry = (readAt) => options.access === "retry" && (options.requestedAt ?? Infinity) >= readAt;
18413
+ const cached2 = cachedKeys.get(cacheKey);
18414
+ if (cached2 && (!cached2.mismatched || !mayRetry(cached2.readAt))) {
18415
+ if (cached2.mismatched && options.access !== "retry")
18416
+ options.skipped = "retry";
18417
+ return cached2.value;
18418
+ }
18419
+ const denied = deniedReads.get(cacheKey);
18420
+ if (denied && !mayRetry(denied.readAt)) {
18421
+ if (options.access !== "retry")
18422
+ options.skipped = "retry";
18423
+ if (denied.reason === "timeout")
18424
+ throw new KeychainReadTimeout();
18425
+ return void 0;
18426
+ }
18427
+ if (process.platform === "darwin" && !options.access) {
18428
+ options.skipped = "allow";
18429
+ throw new KeychainAccessDeferred();
18430
+ }
18431
+ cachedKeys.delete(cacheKey);
18432
+ deniedReads.delete(cacheKey);
18433
+ const read = (async () => {
18434
+ const env = {
18435
+ ...process.env,
18436
+ ZCODE_CREDENTIAL_SECRET: void 0,
18437
+ ZCODE_CREDENTIAL_SECRET_FILE: void 0
18438
+ };
18439
+ const run = async (file2, args, timeout = 5e3) => (await execute(file2, args, { env, timeout, maxBuffer: 4096, windowsHide: true })).stdout;
18440
+ try {
18441
+ let value;
18442
+ if (process.platform === "win32") {
18443
+ const root = process.env.SystemRoot;
18444
+ if (!root || !path3.isAbsolute(root))
18445
+ return;
18446
+ const powershell = path3.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
18447
+ const command = `${WIN32_READER}
18448
+ [Console]::Write([ZCodeKeyReader]::Read('${account}.${SERVICE}'))`;
18449
+ value = (await run(powershell, [
18450
+ "-NoLogo",
18451
+ "-NoProfile",
18452
+ "-NonInteractive",
18453
+ "-EncodedCommand",
18454
+ Buffer.from(command, "utf16le").toString("base64")
18455
+ ])).replace(/\r?\n$/, "");
18456
+ } else if (process.platform === "darwin") {
18457
+ const security = "/usr/bin/security";
18458
+ const keychain = /^\s*"([^"\r\n]+)"\s*$/.exec(await run(security, ["default-keychain", "-d", "user"]))?.[1];
18459
+ if (!keychain || !path3.isAbsolute(keychain)) {
18460
+ deniedReads.set(cacheKey, { reason: "denied", readAt: performance.now() });
18461
+ return;
18462
+ }
18463
+ const raw = await run(security, ["find-generic-password", "-s", SERVICE, "-a", account, "-w", keychain], KEYCHAIN_PASSWORD_TIMEOUT_MS).catch((error51) => {
18464
+ const failure2 = error51;
18465
+ if (failure2?.killed && failure2.code === null && failure2.signal === "SIGTERM")
18466
+ throw new KeychainReadTimeout();
18467
+ return void 0;
18468
+ });
18469
+ value = raw?.replace(/\r?\n$/, "");
18470
+ } else if (process.platform === "linux") {
18471
+ value = await run("/usr/bin/secret-tool", [
18472
+ "lookup",
18473
+ "service",
18474
+ SERVICE,
18475
+ "username",
18476
+ account
18477
+ ]);
18478
+ }
18479
+ if (value) {
18480
+ cachedKeys.set(cacheKey, { value, readAt: performance.now() });
18481
+ deniedReads.delete(cacheKey);
18482
+ return value;
18483
+ }
18484
+ deniedReads.set(cacheKey, { reason: "denied", readAt: performance.now() });
18485
+ return value;
18486
+ } catch (error51) {
18487
+ if (error51 instanceof KeychainReadTimeout) {
18488
+ deniedReads.set(cacheKey, { reason: "timeout", readAt: performance.now() });
18489
+ throw error51;
18490
+ }
18491
+ deniedReads.set(cacheKey, { reason: "denied", readAt: performance.now() });
18492
+ }
18493
+ })();
18494
+ inFlightReads.set(cacheKey, read);
18495
+ try {
18496
+ return await read;
18497
+ } finally {
18498
+ inFlightReads.delete(cacheKey);
18499
+ }
18500
+ };
18501
+
18502
+ // dist/credentials.js
18503
+ var V1 = "enc:v1:";
18504
+ var V2 = "enc:v2:";
18505
+ var digest = (value) => createHash("sha256").update(value).digest();
18506
+ var storeSchema = external_exports.record(external_exports.string(), external_exports.string());
18507
+ var ZcodeCredentialError = class extends ZcodeError {
18508
+ constructor(message, code = "authenticationRequired") {
18509
+ super(code, message, code !== "credentialAccessRequired");
18510
+ }
18511
+ };
18512
+ var invalidV2 = () => new ZcodeCredentialError("Cannot decrypt ZCode enc:v2: credentials: invalid or damaged encrypted record.");
18513
+ var unavailableV2 = () => new ZcodeCredentialError("Cannot read ZCode enc:v2: credentials: the original key is unavailable or does not match. Check the ZCode credential storage in the Host user's session.");
18514
+ function decryptGcm(iv, tag, data, key) {
18515
+ const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: tag.length });
18516
+ decipher.setAuthTag(tag);
18517
+ return Buffer.concat([decipher.update(data), decipher.final()]).toString("utf8");
18518
+ }
18519
+ function decryptV1(value, environment) {
18032
18520
  let username = "unknown";
18033
18521
  try {
18034
18522
  username = userInfo().username;
18035
18523
  } catch {
18036
18524
  }
18037
18525
  const secret = environment.ZCODE_CREDENTIAL_SECRET || `zcode-credential-fallback:${platform()}:${environment.HOME || homedir2()}:${username}`;
18038
- const [iv, tag, data, extra] = value.slice(7).split(".");
18526
+ const [iv, tag, data, extra] = value.slice(V1.length).split(".");
18039
18527
  try {
18040
18528
  if (!iv || !tag || !data || extra !== void 0)
18041
18529
  throw new Error();
18042
- const decipher = createDecipheriv("aes-256-gcm", createHash("sha256").update(secret).digest(), Buffer.from(iv, "base64url"));
18043
- decipher.setAuthTag(Buffer.from(tag, "base64url"));
18044
- return Buffer.concat([decipher.update(Buffer.from(data, "base64url")), decipher.final()]).toString("utf8").trim();
18530
+ const authTag = Buffer.from(tag, "base64url");
18531
+ if (authTag.length !== 16)
18532
+ throw new Error();
18533
+ return decryptGcm(Buffer.from(iv, "base64url"), authTag, Buffer.from(data, "base64url"), digest(secret)).trim();
18045
18534
  } catch {
18046
- throw new ZcodeError("authenticationRequired", "Cannot decrypt ZCode credentials; ZCODE_CREDENTIAL_SECRET must match ZCode Desktop");
18535
+ throw new ZcodeCredentialError("Cannot decrypt ZCode credentials; ZCODE_CREDENTIAL_SECRET must match ZCode Desktop");
18047
18536
  }
18048
18537
  }
18049
- async function readCredentials(installation, environment) {
18050
- let store;
18538
+ function decodeSegment(value) {
18539
+ if (!/^[A-Za-z0-9_-]*$/.test(value))
18540
+ throw invalidV2();
18541
+ const bytes = Buffer.from(value, "base64url");
18542
+ if (bytes.toString("base64url") !== value)
18543
+ throw invalidV2();
18544
+ return bytes;
18545
+ }
18546
+ async function decryptV2(value, getKey) {
18547
+ const [source, fingerprint, payload, extra] = value.slice(V2.length).split(":");
18548
+ if (source !== "os" && source !== "env" || !fingerprint || !/^[a-f0-9]{24}$/.test(fingerprint) || !payload || extra !== void 0)
18549
+ throw invalidV2();
18550
+ const [encodedIv, encodedTag, encodedData, extraSegment] = payload.split(".");
18551
+ if (!encodedIv || !encodedTag || encodedData === void 0 || extraSegment !== void 0)
18552
+ throw invalidV2();
18553
+ const iv = decodeSegment(encodedIv);
18554
+ const tag = decodeSegment(encodedTag);
18555
+ const data = decodeSegment(encodedData);
18556
+ if (iv.length !== 12 || tag.length !== 16)
18557
+ throw invalidV2();
18558
+ const material = await getKey(source);
18559
+ const { key } = material;
18560
+ if (source !== material.source)
18561
+ throw unavailableV2();
18562
+ if (digest(key).toString("hex").slice(0, 24) !== fingerprint) {
18563
+ if (material.account) {
18564
+ invalidateSystemCredentialKey(material.account, key.toString("base64url"));
18565
+ if (process.platform === "darwin")
18566
+ throw new ZcodeCredentialError(`${unavailableV2().message} Re-detect ZCode in Connections to authorize the macOS Keychain read again.`, "credentialAccessRequired");
18567
+ }
18568
+ throw unavailableV2();
18569
+ }
18570
+ try {
18571
+ return decryptGcm(iv, tag, data, key);
18572
+ } catch {
18573
+ throw invalidV2();
18574
+ }
18575
+ }
18576
+ async function readSecretFile(file2, implicit) {
18577
+ const handle = await open2(file2, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
18578
+ try {
18579
+ const stat3 = await handle.stat();
18580
+ if (!stat3.isFile() || stat3.size < 32 || stat3.size > 4096 || implicit && process.platform !== "win32" && (stat3.mode & 63) !== 0)
18581
+ throw unavailableV2();
18582
+ const secret = await handle.readFile("utf8");
18583
+ const length = Buffer.byteLength(secret, "utf8");
18584
+ if (length < 32 || length > 4096)
18585
+ throw unavailableV2();
18586
+ return secret;
18587
+ } finally {
18588
+ await handle.close();
18589
+ }
18590
+ }
18591
+ async function loadV2Key(file2, values, environment, readSystemKey, source, readSystemKeyOptions) {
18592
+ try {
18593
+ const secret = environment.ZCODE_CREDENTIAL_SECRET;
18594
+ const explicitFile = environment.ZCODE_CREDENTIAL_SECRET_FILE;
18595
+ if (secret && explicitFile)
18596
+ throw unavailableV2();
18597
+ if (secret)
18598
+ return { source: "env", key: digest(secret) };
18599
+ if (explicitFile)
18600
+ return { source: "env", key: digest(await readSecretFile(explicitFile, false)) };
18601
+ const directory = path4.dirname(file2);
18602
+ const marker = await readFile(path4.join(directory, "credential-source"), "utf8").catch((error51) => {
18603
+ if (error51.code === "ENOENT")
18604
+ return void 0;
18605
+ throw error51;
18606
+ });
18607
+ if (marker !== void 0 && marker !== "os\n")
18608
+ throw unavailableV2();
18609
+ const hasOsEnvelope = Object.values(values).some((value) => value.startsWith(`${V2}os:`));
18610
+ if (!hasOsEnvelope) {
18611
+ if (marker)
18612
+ throw unavailableV2();
18613
+ return {
18614
+ source: "env",
18615
+ key: digest(await readSecretFile(path4.join(directory, "credential-secret"), true))
18616
+ };
18617
+ }
18618
+ if (source !== "os")
18619
+ throw unavailableV2();
18620
+ const account = digest(file2).toString("hex");
18621
+ const encoded = readSystemKeyOptions ? await readSystemKey(account, readSystemKeyOptions) : await readSystemKey(account);
18622
+ if (!encoded && process.platform === "darwin")
18623
+ throw new ZcodeCredentialError(`${unavailableV2().message} Re-detect ZCode in Connections to authorize the macOS Keychain read again.`, "credentialAccessRequired");
18624
+ if (!encoded || encoded.length !== 43)
18625
+ throw unavailableV2();
18626
+ const key = decodeSegment(encoded);
18627
+ if (key.length !== 32)
18628
+ throw unavailableV2();
18629
+ return { source: "os", key, account };
18630
+ } catch (error51) {
18631
+ if (error51 instanceof ZcodeCredentialError && error51.code === "credentialAccessRequired")
18632
+ throw error51;
18633
+ if (error51 instanceof KeychainAccessDeferred)
18634
+ throw new ZcodeCredentialError("ZCode account models require macOS Keychain access. Select ZCode or re-detect it in Connections to authorize access.", "credentialAccessRequired");
18635
+ if (error51 instanceof KeychainReadTimeout)
18636
+ throw new ZcodeCredentialError("ZCode could not read credentials: macOS Keychain read timed out. Re-detect ZCode in Connections and allow access to ZCode Credential Encryption.", "credentialAccessRequired");
18637
+ throw unavailableV2();
18638
+ }
18639
+ }
18640
+ function plaintextCredential(value) {
18641
+ if (/^\s*(?:Bearer\s+)*enc:/i.test(value))
18642
+ throw new ZcodeCredentialError("Cannot read ZCode credentials: unsupported encrypted credential format (enc:).");
18643
+ return value;
18644
+ }
18645
+ async function readCredentials(installation, environment, readSystemKey = readSystemCredentialKey, readSystemKeyOptions) {
18646
+ const file2 = path4.resolve(installation.dataRoot, "credentials.json");
18647
+ let values;
18051
18648
  try {
18052
- store = JSON.parse(await readFile(path3.join(installation.dataRoot, "credentials.json"), "utf8"));
18649
+ values = storeSchema.parse(JSON.parse(await readFile(file2, "utf8")));
18053
18650
  } catch (error51) {
18054
18651
  if (error51.code === "ENOENT")
18055
- return () => "";
18056
- throw new ZcodeError("authenticationRequired", "Cannot read ZCode credentials");
18057
- }
18058
- const values = external_exports.record(external_exports.string(), external_exports.string()).safeParse(store).data;
18059
- return (key) => {
18060
- const value = values?.[key];
18061
- return value ? decrypt(value, environment) : "";
18652
+ return async () => "";
18653
+ throw new ZcodeCredentialError("Cannot read ZCode credentials.");
18654
+ }
18655
+ const keys = /* @__PURE__ */ new Map();
18656
+ return async (key) => {
18657
+ const value = Object.hasOwn(values, key) ? values[key] : void 0;
18658
+ if (value === void 0)
18659
+ return "";
18660
+ return plaintextCredential(value.startsWith(V1) ? decryptV1(value, environment) : value.startsWith(V2) ? await decryptV2(value, (source) => {
18661
+ const existing = keys.get(source);
18662
+ if (existing)
18663
+ return existing;
18664
+ const key2 = loadV2Key(file2, values, environment, readSystemKey, source, readSystemKeyOptions);
18665
+ keys.set(source, key2);
18666
+ return key2;
18667
+ }) : value);
18062
18668
  };
18063
18669
  }
18064
- async function readCredential(installation, environment, key) {
18065
- return (await readCredentials(installation, environment))(key);
18670
+
18671
+ // dist/oauth-account.js
18672
+ async function readLoginChannel(credential) {
18673
+ const active2 = await credential("oauth:active_provider");
18674
+ if (active2 === "zai" || active2 === "zai_cn" || active2 === "bigmodel")
18675
+ return active2;
18676
+ if (active2)
18677
+ throw new ZcodeCredentialError("The active ZCode login channel is not supported by CodexHost.");
18678
+ }
18679
+ var normalizedProfile = external_exports.object({
18680
+ id: external_exports.string(),
18681
+ username: external_exports.string(),
18682
+ displayName: external_exports.string()
18683
+ });
18684
+ var rawZaiProfile = external_exports.object({ user_id: external_exports.string() });
18685
+ async function readOAuthUserId(credential, channel) {
18686
+ const raw = await credential(`oauth:${channel}:user_info`);
18687
+ if (!raw)
18688
+ return;
18689
+ let profile;
18690
+ try {
18691
+ profile = JSON.parse(raw);
18692
+ } catch {
18693
+ throw new ZcodeCredentialError("Cannot read the ZCode login profile.");
18694
+ }
18695
+ const id2 = normalizedProfile.safeParse(profile).data?.id ?? (channel === "bigmodel" ? void 0 : rawZaiProfile.safeParse(profile).data?.user_id);
18696
+ if (id2?.trim() && id2.trim() !== "unknown")
18697
+ return id2;
18066
18698
  }
18067
18699
 
18068
18700
  // dist/personal-coding-plan.js
18069
18701
  import { createHash as createHash3 } from "node:crypto";
18070
18702
  import { readFile as readFile2 } from "node:fs/promises";
18071
18703
  import { homedir as homedir3 } from "node:os";
18072
- import path4 from "node:path";
18704
+ import path5 from "node:path";
18073
18705
 
18074
18706
  // dist/project-token.js
18075
18707
  import { createHash as createHash2 } from "node:crypto";
@@ -18078,13 +18710,13 @@ var locationSchema = external_exports.object({
18078
18710
  projectId: external_exports.string().trim().min(1),
18079
18711
  apiKeyId: external_exports.string().trim().min(1)
18080
18712
  });
18081
- function readProjectCredential(credential, family, identity2, origin) {
18713
+ async function readProjectCredential(credential, family, identity2, origin, account) {
18082
18714
  const key = `project-key-location:v1:${encodeURIComponent(JSON.stringify([origin, family, identity2, null, 1, "non-team"]))}`;
18083
- const raw = credential(key);
18715
+ const raw = await credential(key);
18084
18716
  if (!raw)
18085
18717
  return void 0;
18086
18718
  const location = locationSchema.parse(JSON.parse(raw));
18087
- const login = credential(`oauth:${family}:access_token`).trim();
18719
+ const login = (account.linkedAccessToken ?? await credential(`oauth:${family}:access_token`)).trim();
18088
18720
  const loginToken = login.replace(/^Bearer\s+/i, "").trim();
18089
18721
  if (!loginToken)
18090
18722
  throw projectCredentialError();
@@ -18093,7 +18725,10 @@ function readProjectCredential(credential, family, identity2, origin) {
18093
18725
  "individual-coding-plan",
18094
18726
  null,
18095
18727
  login,
18096
- credential("zcodejwttoken").trim() || null
18728
+ (await credential("zcodejwttoken")).trim() || null,
18729
+ account.sessionRevision || null,
18730
+ identity2,
18731
+ account.userId
18097
18732
  ])).digest("hex");
18098
18733
  return { origin, loginToken, location, accountScope };
18099
18734
  }
@@ -18137,17 +18772,18 @@ var ProjectToken = class {
18137
18772
  if (!parsed.success || parsed.data.success === false || parsed.data.data.enable === false)
18138
18773
  throw projectCredentialError();
18139
18774
  const data = parsed.data.data;
18775
+ const token = plaintextCredential(data.accessToken);
18140
18776
  const expiresAt = Math.min(data.expiresAt * 1e3, started + data.expiresIn * 1e3);
18141
18777
  signal.throwIfAborted();
18142
18778
  if (expiresAt <= Date.now())
18143
18779
  throw projectCredentialError();
18144
18780
  this.#cached = {
18145
18781
  scope,
18146
- token: data.accessToken,
18782
+ token,
18147
18783
  expiresAt,
18148
- fingerprint: createHash2("sha256").update(data.accessToken).digest("hex")
18784
+ fingerprint: createHash2("sha256").update(token).digest("hex")
18149
18785
  };
18150
- return data.accessToken;
18786
+ return token;
18151
18787
  } catch (error51) {
18152
18788
  signal.throwIfAborted();
18153
18789
  if (error51 instanceof ZcodeError)
@@ -18163,6 +18799,18 @@ var ProjectToken = class {
18163
18799
  var familySchema = external_exports.enum(["zai", "bigmodel"]);
18164
18800
  var recordSchema2 = external_exports.record(external_exports.string(), external_exports.unknown());
18165
18801
  var CONNECT = "Connect Personal Coding Plan in ZCode Desktop, then re-detect ZCode and reopen the Thread";
18802
+ var linkedBigModelSchema = external_exports.object({
18803
+ userId: external_exports.string(),
18804
+ customerId: external_exports.string().trim().min(1),
18805
+ accessToken: external_exports.string().trim().min(1)
18806
+ });
18807
+ function parseBigModelLink(raw) {
18808
+ try {
18809
+ return linkedBigModelSchema.safeParse(JSON.parse(raw)).data;
18810
+ } catch {
18811
+ return void 0;
18812
+ }
18813
+ }
18166
18814
  function personalCodingPlanOrigin(family, environment) {
18167
18815
  const test = environment.ZCODE_ENV?.trim().toLowerCase() === "test";
18168
18816
  const prefix = family === "zai" ? "ZAI" : "BIGMODEL";
@@ -18177,7 +18825,7 @@ async function readSelection(environment, family) {
18177
18825
  const home = environment.ZCODE_DESKTOP_HOME_DIR?.trim() || environment.HOME?.trim() || environment.USERPROFILE?.trim() || homedir3();
18178
18826
  let raw;
18179
18827
  try {
18180
- raw = JSON.parse(await readFile2(path4.join(home, ".zcode", "v2", "setting.json"), "utf8"));
18828
+ raw = JSON.parse(await readFile2(path5.join(home, ".zcode", "v2", "setting.json"), "utf8"));
18181
18829
  } catch (error51) {
18182
18830
  if (error51.code === "ENOENT")
18183
18831
  return false;
@@ -18213,8 +18861,10 @@ async function queryEntitlement(family, apiKey, environment) {
18213
18861
  try {
18214
18862
  const response = await fetch(`${personalCodingPlanOrigin(family, environment)}/api/biz/subscription/list`, {
18215
18863
  method: "GET",
18216
- // Legacy Desktop uses a personal API Key; project-token Desktop uses its OAuth login.
18217
- headers: { Authorization: apiKey.trim() },
18864
+ // Desktop checks the model credential: a personal API Key or a project token.
18865
+ headers: {
18866
+ Authorization: apiKey.trim().replace(/^Bearer\s+/i, "").trim()
18867
+ },
18218
18868
  redirect: "error",
18219
18869
  signal: AbortSignal.timeout(15e3)
18220
18870
  });
@@ -18249,38 +18899,52 @@ var PersonalCodingPlanAccount = class {
18249
18899
  #authorized = /* @__PURE__ */ new Map();
18250
18900
  #projectToken = new ProjectToken();
18251
18901
  issue;
18902
+ credentialIssue;
18903
+ credentialAccessRequired = false;
18252
18904
  constructor(installation, environment) {
18253
18905
  this.installation = installation;
18254
18906
  this.environment = environment;
18255
18907
  }
18256
- async #context(providerId, family) {
18908
+ async #context(providerId, family, existingCredential) {
18257
18909
  const [credential, current] = await Promise.all([
18258
- readCredentials(this.installation, this.environment),
18910
+ existingCredential ?? readCredentials(this.installation, this.environment),
18259
18911
  readSelection(this.environment, family)
18260
18912
  ]);
18261
- if (credential("oauth:active_provider") !== family)
18262
- return void 0;
18263
- const raw = credential(`oauth:${family}:user_info`);
18264
- if (!raw)
18265
- return void 0;
18266
- const profile = recordSchema2.parse(JSON.parse(raw));
18267
- const normalized = external_exports.object({ id: external_exports.string(), username: external_exports.string(), displayName: external_exports.string() }).safeParse(profile).data;
18268
- const identity2 = normalized ? normalized.id.trim() : family === "zai" && typeof profile.user_id === "string" ? profile.user_id.trim() : "";
18269
- if (!identity2 || identity2 === "unknown")
18270
- return void 0;
18271
- const project2 = readProjectCredential(credential, family, identity2, personalCodingPlanOrigin(family, this.environment));
18913
+ const channel = await readLoginChannel(credential);
18914
+ if (!channel || channel !== family && !(channel === "zai_cn" && family === "bigmodel"))
18915
+ return;
18916
+ const userId = await readOAuthUserId(credential, channel);
18917
+ if (!userId)
18918
+ return;
18919
+ let identity2 = userId.trim();
18920
+ let linkedAccessToken;
18921
+ if (channel === "zai_cn") {
18922
+ if (!await credential("oauth:zai_cn:access_token"))
18923
+ return;
18924
+ const link = parseBigModelLink(await credential("oauth:linked_bigmodel"));
18925
+ if (link?.userId !== userId)
18926
+ return;
18927
+ identity2 = link.customerId;
18928
+ linkedAccessToken = plaintextCredential(link.accessToken);
18929
+ }
18930
+ const sessionRevision = await credential("oauth:session_revision");
18931
+ const account = JSON.stringify([channel, userId, identity2, sessionRevision]);
18932
+ const project2 = await readProjectCredential(credential, family, identity2, personalCodingPlanOrigin(family, this.environment), { userId, sessionRevision, linkedAccessToken });
18933
+ const base = { identity: identity2, account, current };
18272
18934
  if (project2)
18273
- return { identity: identity2, current, apiKey: project2.loginToken, project: project2 };
18935
+ return { ...base, project: project2 };
18274
18936
  const key = `account-provider:coding-plan:${providerId}:account:${encodeURIComponent(identity2)}:api-key`;
18275
- return { identity: identity2, current, apiKey: credential(key).trim() };
18937
+ return { ...base, apiKey: (await credential(key)).trim() };
18276
18938
  }
18277
- async inspect(providerId, accountType) {
18939
+ async inspect(providerId, accountType, existingCredential) {
18278
18940
  const family = familySchema.parse(accountType);
18279
18941
  this.#authorized.delete(providerId);
18280
18942
  this.issue = void 0;
18943
+ this.credentialIssue = void 0;
18944
+ this.credentialAccessRequired = false;
18281
18945
  let current = false;
18282
18946
  try {
18283
- const context = await this.#context(providerId, family);
18947
+ const context = await this.#context(providerId, family, existingCredential);
18284
18948
  if (!context)
18285
18949
  return {
18286
18950
  availability: "unavailable",
@@ -18291,7 +18955,7 @@ var PersonalCodingPlanAccount = class {
18291
18955
  current = context.current;
18292
18956
  const connectionKey = createHash3("sha256").update(JSON.stringify([family, context.identity, "individual-coding-plan"])).digest("hex");
18293
18957
  const base = { current, connectionKey };
18294
- if (!context.apiKey) {
18958
+ if (!context.project && !context.apiKey) {
18295
18959
  if (current)
18296
18960
  this.issue = "ZCode is signed in, but its Personal Coding Plan credentials are not initialized. Open the personal plan in ZCode Desktop, then re-detect ZCode. This does not mean the subscription is inactive.";
18297
18961
  return {
@@ -18301,13 +18965,14 @@ var PersonalCodingPlanAccount = class {
18301
18965
  unavailableReason: "credential-failed"
18302
18966
  };
18303
18967
  }
18304
- const entitlement = await queryEntitlement(family, context.apiKey, this.environment);
18968
+ const apiKey = context.project ? await this.#projectToken.resolve(context.project, this.installation.version, new AbortController().signal) : context.apiKey;
18969
+ const entitlement = await queryEntitlement(family, apiKey, this.environment);
18305
18970
  const after = await this.#context(providerId, family);
18306
- if (!after || after.identity !== context.identity || after.current !== current || after.apiKey !== context.apiKey || JSON.stringify(after.project) !== JSON.stringify(context.project))
18971
+ if (!after || after.account !== context.account || after.current !== current || after.apiKey !== context.apiKey || JSON.stringify(after.project) !== JSON.stringify(context.project))
18307
18972
  return { availability: "unknown", entitled: false, current: false };
18308
18973
  if (entitlement === "available") {
18309
18974
  if (current)
18310
- this.#authorized.set(providerId, { family, identity: context.identity });
18975
+ this.#authorized.set(providerId, { family, account: context.account });
18311
18976
  return { ...base, availability: "available", entitled: true };
18312
18977
  }
18313
18978
  if (current)
@@ -18320,10 +18985,15 @@ var PersonalCodingPlanAccount = class {
18320
18985
  unavailableReason: entitlement === "unavailable" ? "not-entitled" : "credential-failed"
18321
18986
  }
18322
18987
  };
18323
- } catch {
18988
+ } catch (error51) {
18324
18989
  current = await readSelection(this.environment, family).catch(() => false);
18325
- if (current)
18326
- this.issue = "ZCode Personal Coding Plan credentials could not be read or verified. Open the personal plan in ZCode Desktop, then re-detect ZCode; subscription status is unknown.";
18990
+ if (current) {
18991
+ if (error51 instanceof ZcodeCredentialError) {
18992
+ this.credentialIssue = `${error51.message} Personal Coding Plan subscription status is unknown.`;
18993
+ this.credentialAccessRequired = error51.code === "credentialAccessRequired";
18994
+ }
18995
+ this.issue = this.credentialIssue ?? "ZCode Personal Coding Plan credentials could not be read or verified. Open the personal plan in ZCode Desktop, then re-detect ZCode; subscription status is unknown.";
18996
+ }
18327
18997
  return { availability: "unknown", entitled: false, current };
18328
18998
  }
18329
18999
  }
@@ -18348,7 +19018,7 @@ var PersonalCodingPlanAccount = class {
18348
19018
  signal.throwIfAborted();
18349
19019
  const context = await this.#context(providerId, authorized.family);
18350
19020
  signal.throwIfAborted();
18351
- if (!context?.current || context.identity !== authorized.identity || !context.apiKey)
19021
+ if (!context?.current || context.account !== authorized.account)
18352
19022
  throw new ZcodeError("authenticationRequired", CONNECT);
18353
19023
  if (context.project) {
18354
19024
  const { expectedAccountScope, rejectedProjectTokenFingerprint } = parsed.data;
@@ -18357,7 +19027,7 @@ var PersonalCodingPlanAccount = class {
18357
19027
  const apiKey = await this.#projectToken.resolve(context.project, this.installation.version, signal, rejectedProjectTokenFingerprint);
18358
19028
  const after = await this.#context(providerId, authorized.family);
18359
19029
  signal.throwIfAborted();
18360
- if (!after?.current || after.identity !== context.identity || JSON.stringify(after.project) !== JSON.stringify(context.project))
19030
+ if (!after?.current || after.account !== context.account || JSON.stringify(after.project) !== JSON.stringify(context.project))
18361
19031
  throw new ZcodeError("authenticationRequired", CONNECT);
18362
19032
  return {
18363
19033
  apiKey,
@@ -18365,7 +19035,7 @@ var PersonalCodingPlanAccount = class {
18365
19035
  accountScope: context.project.accountScope
18366
19036
  };
18367
19037
  }
18368
- if (parsed.data.expectedAccountScope !== void 0 || parsed.data.rejectedProjectTokenFingerprint)
19038
+ if (!context.apiKey || parsed.data.expectedAccountScope !== void 0 || parsed.data.rejectedProjectTokenFingerprint)
18369
19039
  throw new ZcodeError("authenticationRequired", CONNECT);
18370
19040
  return { apiKey: context.apiKey };
18371
19041
  }
@@ -18392,7 +19062,7 @@ function resolveEndpointOrigin(environment) {
18392
19062
  }
18393
19063
  async function readDeviceMid(installation) {
18394
19064
  try {
18395
- const file2 = path5.join(installation.dataRoot, "telemetry-state.json");
19065
+ const file2 = path6.join(installation.dataRoot, "telemetry-state.json");
18396
19066
  const parsed = JSON.parse(await readFile3(file2, "utf8"));
18397
19067
  return typeof parsed?.deviceMid === "string" ? parsed.deviceMid.trim() : "";
18398
19068
  } catch {
@@ -18426,9 +19096,9 @@ function resolveStartPlanModels(data, builtinModelIds) {
18426
19096
  const validPlans = data.plans.filter((plan) => {
18427
19097
  if (plan.status?.trim().toLowerCase() !== "active")
18428
19098
  return false;
18429
- const id = plan.plan_id?.trim().toLowerCase();
19099
+ const id2 = plan.plan_id?.trim().toLowerCase();
18430
19100
  const name = plan.name?.trim().toLowerCase();
18431
- const isStart = !id && !name || id?.includes("start-plan") || id?.includes("start plan") || name?.includes("start-plan") || name?.includes("start plan");
19101
+ const isStart = !id2 && !name || id2?.includes("start-plan") || id2?.includes("start plan") || name?.includes("start-plan") || name?.includes("start plan");
18432
19102
  if (!isStart)
18433
19103
  return false;
18434
19104
  const ends = Number(plan.ends_at);
@@ -18453,7 +19123,7 @@ function resolveStartPlanModels(data, builtinModelIds) {
18453
19123
  for (const raw of candidates) {
18454
19124
  if (!raw)
18455
19125
  continue;
18456
- const normalized = builtinModelIds?.find((id) => id.toLowerCase() === raw.toLowerCase()) ?? raw;
19126
+ const normalized = builtinModelIds?.find((id2) => id2.toLowerCase() === raw.toLowerCase()) ?? raw;
18457
19127
  const key = normalized.toLowerCase();
18458
19128
  if (!seen.has(key)) {
18459
19129
  seen.add(key);
@@ -18463,6 +19133,12 @@ function resolveStartPlanModels(data, builtinModelIds) {
18463
19133
  }
18464
19134
  return models;
18465
19135
  }
19136
+ var startFamily = (channel) => channel === "zai_cn" ? "bigmodel" : channel;
19137
+ async function readStartJwt(credential, channel) {
19138
+ if (channel === "zai_cn" && !(await readOAuthUserId(credential, channel) && await credential("oauth:zai_cn:access_token")))
19139
+ return "";
19140
+ return credential("zcodejwttoken");
19141
+ }
18466
19142
  async function queryStartPlanBalance(origin, appVersion, jwt2, deviceMid) {
18467
19143
  try {
18468
19144
  const url2 = new URL(`${origin}/api/v1/zcode-plan/billing/balance`);
@@ -18489,22 +19165,31 @@ async function queryStartPlanBalance(origin, appVersion, jwt2, deviceMid) {
18489
19165
  return void 0;
18490
19166
  }
18491
19167
  }
18492
- async function accountConfig(installation, environment) {
19168
+ async function accountConfig(installation, environment, readSystemKeyOptions) {
18493
19169
  const file2 = installation.builtinProviderConfig;
18494
19170
  const builtin = builtinSchema.parse(JSON.parse(await readFile3(file2, "utf8")));
18495
- const basedOnZCodeBuiltinRevision = `zcode-builtin:${builtin.revision}:${createHash4("sha256").update(path5.resolve(file2)).digest("hex")}`;
18496
- const family = await readCredential(installation, environment, "oauth:active_provider");
19171
+ const basedOnZCodeBuiltinRevision = `zcode-builtin:${builtin.revision}:${createHash4("sha256").update(path6.resolve(file2)).digest("hex")}`;
19172
+ let channel;
19173
+ let credentialIssue;
19174
+ let credentialAccessRequired = false;
18497
19175
  let balanceData;
18498
- if (family) {
18499
- try {
18500
- const jwt2 = await readCredential(installation, environment, "zcodejwttoken");
19176
+ let credential;
19177
+ try {
19178
+ credential = await readCredentials(installation, environment, void 0, readSystemKeyOptions);
19179
+ channel = await readLoginChannel(credential);
19180
+ if (channel) {
19181
+ const jwt2 = await readStartJwt(credential, channel);
18501
19182
  const deviceMid = await readDeviceMid(installation);
18502
19183
  if (jwt2 && deviceMid) {
18503
19184
  const origin = resolveEndpointOrigin(environment);
18504
19185
  balanceData = await queryStartPlanBalance(origin, installation.version, jwt2, deviceMid);
18505
19186
  }
18506
- } catch {
18507
19187
  }
19188
+ } catch (error51) {
19189
+ if (!(error51 instanceof ZcodeCredentialError))
19190
+ throw error51;
19191
+ credentialAccessRequired = error51.code === "credentialAccessRequired";
19192
+ credentialIssue = channel ? error51.message : `${error51.message} Personal Coding Plan subscription status is unknown.`;
18508
19193
  }
18509
19194
  let startPlan = false;
18510
19195
  const codingPlan = new PersonalCodingPlanAccount(installation, environment);
@@ -18512,10 +19197,10 @@ async function accountConfig(installation, environment) {
18512
19197
  const states = {};
18513
19198
  for (const rule of builtin.config.providerConfigRules.providerRules) {
18514
19199
  const access = rule.config.access;
18515
- if (!family || access?.accountType !== family)
19200
+ if (!channel || access?.accountType !== startFamily(channel))
18516
19201
  continue;
18517
- if (access.mode === "individual-coding-plan" && (family === "zai" || family === "bigmodel")) {
18518
- const state = await codingPlan.inspect(rule.providerId, family);
19202
+ if (access.mode === "individual-coding-plan") {
19203
+ const state = await codingPlan.inspect(rule.providerId, access.accountType, credential);
18519
19204
  providers[rule.providerId] = {
18520
19205
  access: { type: "zhipu-account", entitled: state.entitled }
18521
19206
  };
@@ -18547,19 +19232,22 @@ async function accountConfig(installation, environment) {
18547
19232
  const overlayDigest = createHash4("sha256").update(JSON.stringify([providers, states])).digest("hex").slice(0, 16);
18548
19233
  return {
18549
19234
  params: {
18550
- revision: `codexhost:${family || "signed-out"}:${builtin.revision}:${overlayDigest}`,
19235
+ revision: `codexhost:${channel ?? (credentialIssue ? "credentials-unavailable" : "signed-out")}:${builtin.revision}:${overlayDigest}`,
18551
19236
  basedOnZCodeBuiltinRevision,
18552
19237
  providers,
18553
19238
  states
18554
19239
  },
18555
19240
  startPlan,
18556
- signedIn: Boolean(family),
18557
- startPlanChecked: !family || balanceData !== void 0,
19241
+ signedIn: Boolean(channel),
19242
+ startPlanChecked: !credentialIssue && (!channel || balanceData !== void 0),
19243
+ ...credentialIssue ? { credentialIssue } : {},
19244
+ credentialAccessRequired,
18558
19245
  codingPlan
18559
19246
  };
18560
19247
  }
18561
19248
  async function providerRuntimeHeaders(request, signal, installation, environment, verifier, codingPlan) {
18562
- const mode = external_exports.object({ mode: external_exports.string() }).safeParse(request.accountAccess).data?.mode;
19249
+ const access = external_exports.object({ mode: external_exports.string(), accountType: external_exports.string().optional() }).safeParse(request.accountAccess).data;
19250
+ const mode = access?.mode;
18563
19251
  try {
18564
19252
  signal.throwIfAborted();
18565
19253
  if (mode === "individual-coding-plan")
@@ -18569,7 +19257,11 @@ async function providerRuntimeHeaders(request, signal, installation, environment
18569
19257
  headersApplied: false,
18570
19258
  errorMessage: "codexhost supports ZCode Start Plan and Personal Coding Plan; Team Coding Plan is not supported"
18571
19259
  };
18572
- const apiKey = await readCredential(installation, environment, "zcodejwttoken");
19260
+ const credential = await readCredentials(installation, environment);
19261
+ const channel = await readLoginChannel(credential);
19262
+ if (!channel || access?.accountType !== void 0 && access.accountType !== startFamily(channel))
19263
+ return { headersApplied: false, errorMessage: SIGN_IN };
19264
+ const apiKey = await readStartJwt(credential, channel);
18573
19265
  if (!apiKey)
18574
19266
  return { headersApplied: false, errorMessage: SIGN_IN };
18575
19267
  const headers = await verifier().verify(signal);
@@ -18665,6 +19357,8 @@ var CliTransport = class {
18665
19357
  #startPlan = false;
18666
19358
  #signedIn = false;
18667
19359
  #startPlanChecked = true;
19360
+ #credentialIssue;
19361
+ #credentialAccessRequired = false;
18668
19362
  #codingPlan;
18669
19363
  #fault;
18670
19364
  #closed = false;
@@ -18685,6 +19379,12 @@ var CliTransport = class {
18685
19379
  get startPlanChecked() {
18686
19380
  return this.#startPlanChecked;
18687
19381
  }
19382
+ get credentialIssue() {
19383
+ return this.#credentialIssue ?? this.#codingPlan?.credentialIssue;
19384
+ }
19385
+ get credentialAccessRequired() {
19386
+ return this.#credentialAccessRequired || this.#codingPlan?.credentialAccessRequired === true;
19387
+ }
18688
19388
  get codingPlanIssue() {
18689
19389
  return this.#codingPlan?.issue;
18690
19390
  }
@@ -18699,11 +19399,13 @@ var CliTransport = class {
18699
19399
  if (this.#child || this.#closed)
18700
19400
  throw new ZcodeError("invalidState", "ZCode transport already started or closed");
18701
19401
  const installation = await resolveInstallation(this.options.environment, this.options.app);
18702
- const { params: accountParams, startPlan, signedIn, startPlanChecked, codingPlan } = await accountConfig(installation, this.options.environment);
19402
+ const { params: accountParams, startPlan, signedIn, startPlanChecked, credentialIssue, credentialAccessRequired, codingPlan } = await accountConfig(installation, this.options.environment, this.options.keyOptions);
18703
19403
  this.#installation = installation;
18704
19404
  this.#startPlan = startPlan;
18705
19405
  this.#signedIn = signedIn;
18706
19406
  this.#startPlanChecked = startPlanChecked;
19407
+ this.#credentialIssue = credentialIssue;
19408
+ this.#credentialAccessRequired = credentialAccessRequired;
18707
19409
  this.#codingPlan = codingPlan;
18708
19410
  const child = spawn(installation.runtime, [installation.cli, "app-server", "--stdio", "--surface", "desktop"], {
18709
19411
  cwd: this.options.cwd,
@@ -18810,12 +19512,12 @@ var CliTransport = class {
18810
19512
  listener(params);
18811
19513
  }
18812
19514
  #emitSession(sessionId, value) {
18813
- for (const [listener, id] of this.#sessionListeners)
18814
- if (id === sessionId)
19515
+ for (const [listener, id2] of this.#sessionListeners)
19516
+ if (id2 === sessionId)
18815
19517
  listener(value);
18816
19518
  }
18817
- async #answer(id, method, params) {
18818
- const reply = (body) => this.#write({ id, ...body });
19519
+ async #answer(id2, method, params) {
19520
+ const reply = (body) => this.#write({ id: id2, ...body });
18819
19521
  if (method === "session/requestRuntimePreferences")
18820
19522
  reply({ result: RUNTIME_PREFERENCES });
18821
19523
  else if (method === "interaction/requestPermission" || method === "interaction/requestUserInput") {
@@ -18861,11 +19563,11 @@ var CliTransport = class {
18861
19563
  #call(method, params, timeoutMs) {
18862
19564
  if (!this.#child || this.#closed || this.#fault)
18863
19565
  return Promise.reject(this.#fault ?? new ZcodeError("invalidState", "ZCode is closed"));
18864
- const id = ++this.#nextId;
19566
+ const id2 = ++this.#nextId;
18865
19567
  return new Promise((resolve, reject) => {
18866
19568
  const timer = setTimeout(() => this.#fail(new ZcodeError("unavailable", "ZCode request timed out; delivery is unconfirmed")), timeoutMs ?? this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
18867
- this.#pending.set(id, { resolve, reject, timer });
18868
- this.#write({ id, method, params });
19569
+ this.#pending.set(id2, { resolve, reject, timer });
19570
+ this.#write({ id: id2, method, params });
18869
19571
  });
18870
19572
  }
18871
19573
  request(method, params = {}) {
@@ -19559,34 +20261,56 @@ function createZcodeVerifier(options) {
19559
20261
  };
19560
20262
  }
19561
20263
 
20264
+ // dist/session.js
20265
+ import { randomUUID as randomUUID2 } from "node:crypto";
20266
+
19562
20267
  // dist/models.js
19563
20268
  var ZCODE_ID = harnessIdSchema.parse("zcode");
19564
- function encodeModel(model2) {
19565
- return harnessModelRefSchema.parse({
19566
- id: `zcode-local-v1.${Buffer.from(JSON.stringify([model2.providerId, model2.modelId])).toString("base64url")}`
19567
- });
20269
+ function readableId({ providerId, modelId: modelId2 }) {
20270
+ return `${providerId}/${modelId2}`;
19568
20271
  }
19569
- function decodeModel(model2) {
19570
- try {
19571
- const prefix = "zcode-local-v1.";
19572
- const value = JSON.parse(Buffer.from(model2.id.slice(prefix.length), "base64url").toString("utf8"));
19573
- if (!model2.id.startsWith(prefix) || !Array.isArray(value) || value.length !== 2)
19574
- throw new Error();
19575
- const native = nativeModelSchema.parse({ providerId: value[0], modelId: value[1] });
19576
- if (encodeModel(native).id !== model2.id)
19577
- throw new Error();
19578
- return native;
19579
- } catch {
19580
- throw new ZcodeError("invalidRequest", "Invalid ZCode model reference");
19581
- }
20272
+ function legacyId({ providerId, modelId: modelId2 }) {
20273
+ return `zcode-local-v1.${Buffer.from(JSON.stringify([providerId, modelId2])).toString("base64url")}`;
20274
+ }
20275
+ function sameNativeModel(a, b) {
20276
+ return a.providerId === b.providerId && a.modelId === b.modelId;
20277
+ }
20278
+ function modelIndex(models) {
20279
+ const entries = new Map(models.map((entry) => [
20280
+ legacyId(entry.ref),
20281
+ {
20282
+ provider: entry.ref.providerId,
20283
+ model: entry.ref.modelId,
20284
+ entry
20285
+ }
20286
+ ]));
20287
+ const ids = compositeModelRefIds([...entries.values()], ({ entry }) => legacyId(entry.ref));
20288
+ const readable = new Set(models.map(({ ref }) => readableId(ref)));
20289
+ const byLegacy = /* @__PURE__ */ new Map();
20290
+ for (const [id2, { entry }] of ids) {
20291
+ byLegacy.set(legacyId(entry.ref), harnessModelRefSchema.parse({ id: id2 }));
20292
+ }
20293
+ const encode3 = (model2) => {
20294
+ const id2 = readableId(model2);
20295
+ return byLegacy.get(legacyId(model2)) ?? harnessModelRefSchema.parse({
20296
+ id: readable.has(id2) ? legacyId(model2) : id2
20297
+ });
20298
+ };
20299
+ return { encode: encode3, ids, byLegacy };
20300
+ }
20301
+ function encodeModel(model2, index) {
20302
+ return index?.encode(model2) ?? harnessModelRefSchema.parse({ id: readableId(model2) });
19582
20303
  }
19583
- function selectNativeModel(model2, settings, thinkingOption) {
19584
- const native = decodeModel(model2);
19585
- const entry = settings.model.available.find((entry2) => encodeModel(entry2.ref).id === model2.id && !entry2.disabledReason);
20304
+ function normalizeStoredZcodeModelRef(ref, index) {
20305
+ return ref.serviceTier ? void 0 : index.byLegacy.get(ref.id);
20306
+ }
20307
+ function selectNativeModel(model2, index, current, thinkingOption) {
20308
+ const entry = !model2.serviceTier && index.ids.get(model2.id)?.entry;
19586
20309
  if (!entry)
19587
20310
  throw new ZcodeError("invalidRequest", "ZCode model is not available");
19588
- const current = settings.model.current;
19589
- const level = thinkingOption ?? (current && encodeModel(current).id === model2.id ? current.options?.reasoningLevel : void 0) ?? entry.reasoning?.defaultLevel;
20311
+ const { providerId, modelId: modelId2 } = entry.ref;
20312
+ const native = { providerId, modelId: modelId2 };
20313
+ const level = thinkingOption ?? (current && sameNativeModel(current, native) ? current.options?.reasoningLevel : void 0) ?? entry.reasoning?.defaultLevel;
19590
20314
  if (level === void 0)
19591
20315
  return native;
19592
20316
  if (!entry.reasoning?.levels.some((option) => option.value === level))
@@ -19599,18 +20323,20 @@ function modelCatalog(settings) {
19599
20323
  for (const model2 of available)
19600
20324
  for (const level of model2.reasoning?.levels ?? [])
19601
20325
  levels.set(level.value, level);
19602
- const current = settings.model.current ? encodeModel(settings.model.current) : void 0;
20326
+ const index = modelIndex(available);
20327
+ const current = settings.model.current ? index.encode(settings.model.current) : void 0;
19603
20328
  const defaultThinking = settings.thoughtLevel.current ?? settings.thoughtLevel.defaultLevel;
19604
- return harnessModelCatalogSchema.parse({
20329
+ const catalog = harnessModelCatalogSchema.parse({
19605
20330
  models: available.map((model2) => ({
19606
- ref: encodeModel(model2.ref),
20331
+ ref: index.encode(model2.ref),
19607
20332
  label: model2.label,
19608
20333
  supportedThinkingOptionIds: model2.reasoning?.enabled ? model2.reasoning.levels.map((level) => level.value) : []
19609
20334
  })),
19610
- ...current && available.some((model2) => encodeModel(model2.ref).id === current.id) ? { defaultModel: current } : {},
20335
+ ...current && index.ids.has(current.id) ? { defaultModel: current } : {},
19611
20336
  thinkingOptions: [...levels.values()].map((level) => ({ id: level.value, label: level.label })),
19612
20337
  ...defaultThinking && levels.has(defaultThinking) ? { defaultThinkingOptionId: defaultThinking } : {}
19613
20338
  });
20339
+ return { catalog, index };
19614
20340
  }
19615
20341
  var modeLabels = {
19616
20342
  build: "Confirm changes",
@@ -19628,19 +20354,20 @@ var chineseModeLabels = {
19628
20354
  };
19629
20355
  function permissionModes(current = "build") {
19630
20356
  return harnessPermissionModeCatalogSchema.parse({
19631
- modes: Object.entries(modeLabels).map(([id, label]) => ({
19632
- id,
20357
+ modes: Object.entries(modeLabels).map(([id2, label]) => ({
20358
+ id: id2,
19633
20359
  label,
19634
- localizations: { "zh-CN": { label: chineseModeLabels[id] } },
19635
- ...id === "yolo" ? { dangerous: true } : {}
20360
+ localizations: { "zh-CN": { label: chineseModeLabels[id2] } },
20361
+ ...id2 === "yolo" ? { dangerous: true } : {}
19636
20362
  })),
19637
20363
  defaultModeId: current
19638
20364
  });
19639
20365
  }
19640
- function sessionState(snapshot, locator) {
20366
+ function sessionState(snapshot, locator, index = modelCatalog(snapshot.settings).index) {
19641
20367
  const settings = snapshot.settings;
19642
- const current = settings.model.current ? encodeModel(settings.model.current) : void 0;
19643
- const model2 = settings.model.available.find((candidate) => encodeModel(candidate.ref).id === current?.id);
20368
+ const native = settings.model.current;
20369
+ const current = native ? encodeModel(native, index) : void 0;
20370
+ const model2 = native && settings.model.available.find((candidate) => sameNativeModel(candidate.ref, native));
19644
20371
  return {
19645
20372
  nativeRef: nativeSessionRefSchema.parse({
19646
20373
  harnessId: ZCODE_ID,
@@ -19679,9 +20406,6 @@ function sessionUsage(snapshot, catalog) {
19679
20406
  return Object.keys(usage).length > 0 ? parseHostUsage(usage) : null;
19680
20407
  }
19681
20408
 
19682
- // dist/session.js
19683
- import { randomUUID as randomUUID2 } from "node:crypto";
19684
-
19685
20409
  // ../../../node_modules/diff/libesm/diff/base.js
19686
20410
  var Diff = class {
19687
20411
  diff(oldStr, newStr, options = {}) {
@@ -19782,16 +20506,16 @@ var Diff = class {
19782
20506
  }
19783
20507
  }
19784
20508
  }
19785
- addToPath(path7, added, removed, oldPosInc, options) {
19786
- const last = path7.lastComponent;
20509
+ addToPath(path8, added, removed, oldPosInc, options) {
20510
+ const last = path8.lastComponent;
19787
20511
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
19788
20512
  return {
19789
- oldPos: path7.oldPos + oldPosInc,
20513
+ oldPos: path8.oldPos + oldPosInc,
19790
20514
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
19791
20515
  };
19792
20516
  } else {
19793
20517
  return {
19794
- oldPos: path7.oldPos + oldPosInc,
20518
+ oldPos: path8.oldPos + oldPosInc,
19795
20519
  lastComponent: { count: 1, added, removed, previousComponent: last }
19796
20520
  };
19797
20521
  }
@@ -20089,9 +20813,9 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader
20089
20813
  function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
20090
20814
  return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
20091
20815
  }
20092
- function splitLines(text2) {
20093
- const hasTrailingNl = text2.endsWith("\n");
20094
- const result = text2.split("\n").map((line) => line + "\n");
20816
+ function splitLines(text3) {
20817
+ const hasTrailingNl = text3.endsWith("\n");
20818
+ const result = text3.split("\n").map((line) => line + "\n");
20095
20819
  if (hasTrailingNl) {
20096
20820
  result.pop();
20097
20821
  } else {
@@ -20119,15 +20843,15 @@ function toolOutput(value) {
20119
20843
  function fileChanges(value) {
20120
20844
  const result = record2(value), nested = record2(result.data);
20121
20845
  const data = typeof result.filePath === "string" ? result : nested;
20122
- const filePath = text(data.filePath);
20123
- if (!filePath)
20846
+ const filePath2 = text(data.filePath);
20847
+ if (!filePath2)
20124
20848
  return [];
20125
20849
  if ((typeof data.originalFile === "string" || data.originalFile === null) && typeof data.content === "string") {
20126
- const diff = createPatch(filePath, data.originalFile ?? "", data.content);
20850
+ const diff = createPatch(filePath2, data.originalFile ?? "", data.content);
20127
20851
  if (diff.length > OUTPUT_LIMIT)
20128
20852
  return [];
20129
20853
  return [
20130
- { path: filePath, kind: data.originalFile === null ? "add" : "update", unifiedDiff: diff }
20854
+ { path: filePath2, kind: data.originalFile === null ? "add" : "update", unifiedDiff: diff }
20131
20855
  ];
20132
20856
  }
20133
20857
  if (Array.isArray(data.structuredPatch)) {
@@ -20135,26 +20859,26 @@ function fileChanges(value) {
20135
20859
  if (!hunks.every((hunk) => typeof hunk.oldStart === "number" && typeof hunk.oldLines === "number" && typeof hunk.newStart === "number" && typeof hunk.newLines === "number" && Array.isArray(hunk.lines) && hunk.lines.every((line) => typeof line === "string")))
20136
20860
  return [];
20137
20861
  const diff = [
20138
- `--- a/${filePath}`,
20139
- `+++ b/${filePath}`,
20862
+ `--- a/${filePath2}`,
20863
+ `+++ b/${filePath2}`,
20140
20864
  ...hunks.flatMap((hunk) => [
20141
20865
  `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
20142
20866
  ...hunk.lines
20143
20867
  ])
20144
20868
  ].join("\n") + "\n";
20145
- return diff.length <= OUTPUT_LIMIT ? [{ path: filePath, kind: data.originalFile === null ? "add" : "update", unifiedDiff: diff }] : [];
20869
+ return diff.length <= OUTPUT_LIMIT ? [{ path: filePath2, kind: data.originalFile === null ? "add" : "update", unifiedDiff: diff }] : [];
20146
20870
  }
20147
20871
  return [];
20148
20872
  }
20149
- function subagent(value, input, fallback) {
20150
- const result = record2(value), data = record2(result.data), args = record2(input);
20151
- const id = text(result.childSessionId) || text(data.childSessionId) || text(result.agentId) || text(data.agentId);
20152
- if (!id)
20873
+ function subagent(value, input2, fallback) {
20874
+ const result = record2(value), data = record2(result.data), args = record2(input2);
20875
+ const id2 = text(result.childSessionId) || text(data.childSessionId) || text(result.agentId) || text(data.agentId);
20876
+ if (!id2)
20153
20877
  return;
20154
20878
  const status = text(result.status) || text(data.status);
20155
20879
  return {
20156
- subagentId: id,
20157
- nativeSubagentId: id,
20880
+ subagentId: id2,
20881
+ nativeSubagentId: id2,
20158
20882
  description: text(args.description) || text(args.prompt) || fallback,
20159
20883
  ...text(args.subagent_type) || text(args.agentType) ? { role: text(args.subagent_type) || text(args.agentType) } : {},
20160
20884
  ...subagentConfiguration(args),
@@ -20165,15 +20889,15 @@ function subagent(value, input, fallback) {
20165
20889
  ...text(result.output) ? { resultSummary: text(result.output).slice(0, OUTPUT_LIMIT) } : {}
20166
20890
  };
20167
20891
  }
20168
- function makeTool(id, name, input, cwd) {
20169
- const itemId = hostItemIdSchema.parse(id), args = record2(input);
20892
+ function makeTool(id2, name, input2, cwd) {
20893
+ const itemId = hostItemIdSchema.parse(id2), args = record2(input2);
20170
20894
  if (name.toLowerCase() === "bash")
20171
20895
  return { type: "commandExecution", itemId, command: text(args.command), cwd };
20172
20896
  return {
20173
20897
  type: "toolExecution",
20174
20898
  itemId,
20175
20899
  toolName: name,
20176
- arguments: jsonValueSchema.parse(input ?? {})
20900
+ arguments: jsonValueSchema.parse(input2 ?? {})
20177
20901
  };
20178
20902
  }
20179
20903
  function projectPart(part, cwd) {
@@ -20206,8 +20930,8 @@ function projectPart(part, cwd) {
20206
20930
  ];
20207
20931
  if (part.type !== "tool")
20208
20932
  return [];
20209
- const state = record2(part.state), input = state.input ?? {}, name = text(part.tool);
20210
- const item = makeTool(itemId, name, input, cwd);
20933
+ const state = record2(part.state), input2 = state.input ?? {}, name = text(part.tool);
20934
+ const item = makeTool(itemId, name, input2, cwd);
20211
20935
  const output = toolOutput(state.output ?? state.error ?? "");
20212
20936
  const outcome = state.status === "completed" ? succeeded : state.status === "error" ? {
20213
20937
  status: "failed",
@@ -20237,14 +20961,14 @@ function projectPart(part, cwd) {
20237
20961
  },
20238
20962
  outcome: succeeded
20239
20963
  });
20240
- const child = subagent(record2(state.metadata), input, name);
20964
+ const child = subagent(record2(state.metadata), input2, name);
20241
20965
  if (child)
20242
20966
  snapshots.push({
20243
20967
  item: {
20244
20968
  type: "subagentDelegation",
20245
20969
  itemId: hostItemIdSchema.parse(`${itemId}:agent`),
20246
20970
  operation: name === "SendMessage" ? "send" : "spawn",
20247
- prompt: text(record2(input).prompt),
20971
+ prompt: text(record2(input2).prompt),
20248
20972
  subagents: [child]
20249
20973
  },
20250
20974
  outcome
@@ -20289,21 +21013,21 @@ var TurnProjection = class {
20289
21013
  }
20290
21014
  if (!kind.startsWith("text_") && !reasoning)
20291
21015
  return;
20292
- let id2 = text(p.partId) || (text(p.assistantMessageId) ? `stream:${text(p.assistantMessageId)}:${reasoning ? "reasoning" : "text"}` : reasoning ? this.#reasoningId : this.#textId);
20293
- if (kind.endsWith("_start") || !id2 || !this.items.has(id2)) {
20294
- id2 ||= `stream:${this.turnId}:${++this.#streamNumber}`;
21016
+ let id3 = text(p.partId) || (text(p.assistantMessageId) ? `stream:${text(p.assistantMessageId)}:${reasoning ? "reasoning" : "text"}` : reasoning ? this.#reasoningId : this.#textId);
21017
+ if (kind.endsWith("_start") || !id3 || !this.items.has(id3)) {
21018
+ id3 ||= `stream:${this.turnId}:${++this.#streamNumber}`;
20295
21019
  if (reasoning)
20296
- this.#reasoningId = id2;
21020
+ this.#reasoningId = id3;
20297
21021
  else
20298
- this.#textId = id2;
21022
+ this.#textId = id3;
20299
21023
  this.start({
20300
21024
  type: reasoning ? "reasoning" : "agentMessage",
20301
- itemId: hostItemIdSchema.parse(id2),
21025
+ itemId: hostItemIdSchema.parse(id3),
20302
21026
  text: ""
20303
21027
  });
20304
21028
  }
20305
- const item2 = this.items.get(id2);
20306
- if (!item2 || this.completed.has(id2) || item2.type !== "agentMessage" && item2.type !== "reasoning")
21029
+ const item2 = this.items.get(id3);
21030
+ if (!item2 || this.completed.has(id3) || item2.type !== "agentMessage" && item2.type !== "reasoning")
20307
21031
  return;
20308
21032
  if (typeof p.delta === "string" && p.delta) {
20309
21033
  item2.text += p.delta;
@@ -20324,7 +21048,7 @@ var TurnProjection = class {
20324
21048
  return;
20325
21049
  }
20326
21050
  if (event.type === "session.updated" && text(p.childSessionId) && text(p.parentToolCallId)) {
20327
- const id2 = `${text(p.parentToolCallId)}:agent`, existing = this.items.get(id2);
21051
+ const id3 = `${text(p.parentToolCallId)}:agent`, existing = this.items.get(id3);
20328
21052
  const child2 = subagent(p, p, text(p.agentType));
20329
21053
  if (!child2)
20330
21054
  return;
@@ -20348,7 +21072,7 @@ var TurnProjection = class {
20348
21072
  } else
20349
21073
  this.start({
20350
21074
  type: "subagentDelegation",
20351
- itemId: hostItemIdSchema.parse(id2),
21075
+ itemId: hostItemIdSchema.parse(id3),
20352
21076
  operation: "spawn",
20353
21077
  prompt: text(p.prompt),
20354
21078
  subagents: [child2]
@@ -20368,15 +21092,15 @@ var TurnProjection = class {
20368
21092
  }
20369
21093
  if (event.type !== "tool.updated" || p.source === "subagent")
20370
21094
  return;
20371
- const id = text(p.toolCallId);
20372
- if (!id)
21095
+ const id2 = text(p.toolCallId);
21096
+ if (!id2)
20373
21097
  return;
20374
21098
  if (p.kind === "scheduled") {
20375
- this.start(makeTool(id, text(p.toolName), p.input, this.cwd));
21099
+ this.start(makeTool(id2, text(p.toolName), p.input, this.cwd));
20376
21100
  return;
20377
21101
  }
20378
- const item = this.items.get(id);
20379
- if (!item || this.completed.has(id))
21102
+ const item = this.items.get(id2);
21103
+ if (!item || this.completed.has(id2))
20380
21104
  return;
20381
21105
  if (p.kind === "progress" && item.type === "commandExecution") {
20382
21106
  const next = (text(p.stdoutTail) + text(p.stderrTail)).slice(-OUTPUT_LIMIT);
@@ -20425,7 +21149,7 @@ var TurnProjection = class {
20425
21149
  this.complete({
20426
21150
  item: {
20427
21151
  type: "fileChange",
20428
- itemId: hostItemIdSchema.parse(`${id}:files`),
21152
+ itemId: hostItemIdSchema.parse(`${id2}:files`),
20429
21153
  changes,
20430
21154
  sourceItemIds: [item.itemId]
20431
21155
  },
@@ -20436,7 +21160,7 @@ var TurnProjection = class {
20436
21160
  this.complete({
20437
21161
  item: {
20438
21162
  type: "subagentDelegation",
20439
- itemId: hostItemIdSchema.parse(`${id}:agent`),
21163
+ itemId: hostItemIdSchema.parse(`${id2}:agent`),
20440
21164
  operation: "spawn",
20441
21165
  subagents: [child]
20442
21166
  },
@@ -20518,7 +21242,7 @@ function messageOutcome(message) {
20518
21242
  return { status: "succeeded" };
20519
21243
  return { status: "unknown", reason: "The persisted ZCode turn has no terminal result" };
20520
21244
  }
20521
- function history(snapshot, events = [], locator) {
21245
+ function history(snapshot, events = [], locator, index = modelCatalog(snapshot.settings).index) {
20522
21246
  const outcomes = /* @__PURE__ */ new Map();
20523
21247
  const nativeKeys = /* @__PURE__ */ new Map();
20524
21248
  for (const event of events) {
@@ -20549,7 +21273,7 @@ function history(snapshot, events = [], locator) {
20549
21273
  items: assistants.flatMap((message) => message.parts.flatMap((part) => projectPart(part, snapshot.session.workspace.workspacePath))),
20550
21274
  outcome,
20551
21275
  ...user.info.model ? {
20552
- model: encodeModel(user.info.model)
21276
+ model: encodeModel(user.info.model, index)
20553
21277
  } : {},
20554
21278
  startedAtMs: user.info.time.created,
20555
21279
  ...completedAtMs !== void 0 ? { completedAtMs } : {}
@@ -20565,7 +21289,7 @@ function history(snapshot, events = [], locator) {
20565
21289
  current.assistants.push(message);
20566
21290
  }
20567
21291
  finish();
20568
- return { turns, state: sessionState(snapshot, locator) };
21292
+ return { turns, state: sessionState(snapshot, locator, index) };
20569
21293
  }
20570
21294
 
20571
21295
  // dist/interactions.js
@@ -20732,7 +21456,7 @@ async function withConversation(transport, source, work) {
20732
21456
  rows.unshift(...incoming);
20733
21457
  if (batch.hasMore !== true)
20734
21458
  return await work({ ...state, rows });
20735
- const next = incoming.map((row) => row.rowId).filter((id) => typeof id === "number").sort((a, b) => a - b)[0];
21459
+ const next = incoming.map((row) => row.rowId).filter((id2) => typeof id2 === "number").sort((a, b) => a - b)[0];
20736
21460
  if (next === void 0 || next === beforeRowId)
20737
21461
  break;
20738
21462
  beforeRowId = next;
@@ -20747,8 +21471,8 @@ async function withConversation(transport, source, work) {
20747
21471
  }
20748
21472
 
20749
21473
  // dist/read-history.js
20750
- async function readHistory(transport, snapshot, events = []) {
20751
- const result = history(snapshot, events, transport.locator);
21474
+ async function readHistory(transport, snapshot, index, events = []) {
21475
+ const result = history(snapshot, events, transport.locator, index);
20752
21476
  const tools = result.turns.flatMap((turn) => turn.items).filter(({ item }) => item.type === "toolExecution");
20753
21477
  if (tools.some(({ item }) => item.type === "toolExecution" && ["Write", "Edit", "MultiEdit"].includes(item.toolName))) {
20754
21478
  await withConversation(transport, snapshot, async (view) => {
@@ -20867,18 +21591,18 @@ var ZcodeSession = class {
20867
21591
  #lastSeq = 0;
20868
21592
  #closePromise;
20869
21593
  #terminalTask;
20870
- catalog;
21594
+ #models;
20871
21595
  constructor(transport, snapshot, onClose, nativeCatalog = snapshot.settings, isLocked = () => false) {
20872
21596
  this.transport = transport;
20873
21597
  this.onClose = onClose;
20874
21598
  this.nativeCatalog = nativeCatalog;
20875
21599
  this.isLocked = isLocked;
20876
21600
  this.capabilities = ZCODE_CAPABILITIES;
20877
- this.catalog = modelCatalog(nativeCatalog);
21601
+ this.#models = modelCatalog(nativeCatalog);
20878
21602
  this.#snapshot = snapshot;
20879
21603
  this.#usage = new ZcodeUsage(snapshot.session.sessionId, (event) => this.#emit(event));
20880
21604
  this.#goalActive = (snapshot.target === void 0 ? snapshot.projection.target : snapshot.target)?.status === "active";
20881
- this.#state = sessionState(snapshot, transport.locator);
21605
+ this.#state = sessionState(snapshot, transport.locator, this.#models.index);
20882
21606
  this.initialState = structuredClone(this.#state);
20883
21607
  this.initialUsage = sessionUsage(snapshot, nativeCatalog);
20884
21608
  this.#lastSeq = typeof snapshot.runtime.eventSeq === "number" ? snapshot.runtime.eventSeq : 0;
@@ -20960,7 +21684,7 @@ var ZcodeSession = class {
20960
21684
  throw new ZcodeError("protocolError", "ZCode changed the native session identity");
20961
21685
  this.#snapshot = snapshot;
20962
21686
  this.#goalActive = (snapshot.target === void 0 ? snapshot.projection.target : snapshot.target)?.status === "active";
20963
- this.#state = sessionState(snapshot, this.transport.locator);
21687
+ this.#state = sessionState(snapshot, this.transport.locator, this.#models.index);
20964
21688
  this.#emit({ type: "session.state.changed", state: structuredClone(this.#state) });
20965
21689
  }
20966
21690
  async refreshUsage() {
@@ -20988,7 +21712,7 @@ var ZcodeSession = class {
20988
21712
  }
20989
21713
  #subagentConfiguration() {
20990
21714
  const state = this.#state;
20991
- const model2 = state.effectiveModel ? decodeModel(state.effectiveModel).modelId : void 0;
21715
+ const model2 = state.effectiveModel ? this.#snapshot.settings.model.current?.modelId : void 0;
20992
21716
  return {
20993
21717
  ...model2 ? { model: model2 } : {},
20994
21718
  ...state.effectiveThinkingOptionId ? { reasoningEffort: state.effectiveThinkingOptionId } : {}
@@ -21006,7 +21730,7 @@ var ZcodeSession = class {
21006
21730
  try {
21007
21731
  const snapshot = await this.#readNative();
21008
21732
  this.#apply(snapshot);
21009
- return { ok: true, value: await readHistory(this.transport, snapshot) };
21733
+ return { ok: true, value: await readHistory(this.transport, snapshot, this.#models.index) };
21010
21734
  } catch (error51) {
21011
21735
  return { ok: false, error: nativeError(error51) };
21012
21736
  }
@@ -21053,17 +21777,9 @@ var ZcodeSession = class {
21053
21777
  try {
21054
21778
  let method, params;
21055
21779
  if (command.type === "model.select") {
21056
- if (!this.catalog.models.some((model2) => model2.ref.id === command.model.id))
21057
- return failure("invalidRequest", "ZCode model is not available");
21058
21780
  method = "setModel";
21059
21781
  params = {
21060
- model: selectNativeModel(command.model, {
21061
- ...this.#snapshot.settings,
21062
- model: {
21063
- ...this.#snapshot.settings.model,
21064
- available: this.nativeCatalog.model.available
21065
- }
21066
- }),
21782
+ model: selectNativeModel(command.model, this.#models.index, this.#snapshot.settings.model.current),
21067
21783
  persistAsWorkspaceLastUsed: false
21068
21784
  };
21069
21785
  } else if (command.type === "thinking.select") {
@@ -21103,51 +21819,51 @@ var ZcodeSession = class {
21103
21819
  return { ok: false, error: nativeError(error51) };
21104
21820
  }
21105
21821
  }
21106
- async #start(id, method, params) {
21822
+ async #start(id2, method, params) {
21107
21823
  if (this.busy)
21108
21824
  return failure("sessionBusy", "ZCode already has an active operation", true);
21109
21825
  const previousGoalActive = this.#goalActive;
21110
21826
  if (method === "goalSession" && ["set", "replace", "resume"].includes(text(params.action)))
21111
21827
  this.#goalActive = true;
21112
- const active = {
21113
- id,
21828
+ const active2 = {
21829
+ id: id2,
21114
21830
  accepted: false,
21115
21831
  pending: [],
21116
21832
  finishing: false,
21117
- projection: new TurnProjection(id, this.transport.options.cwd, (event) => this.#emit(event))
21833
+ projection: new TurnProjection(id2, this.transport.options.cwd, (event) => this.#emit(event))
21118
21834
  };
21119
- this.#active = active;
21835
+ this.#active = active2;
21120
21836
  let result;
21121
21837
  try {
21122
- result = record2(method === "sendText" ? await this.transport.command(this.sessionId, "sendText", params, id) : await this.transport.request(method, { sessionId: this.sessionId, ...params }));
21838
+ result = record2(method === "sendText" ? await this.transport.command(this.sessionId, "sendText", params, id2) : await this.transport.request(method, { sessionId: this.sessionId, ...params }));
21123
21839
  } catch (error51) {
21124
- if (this.#active === active)
21840
+ if (this.#active === active2)
21125
21841
  this.#active = void 0;
21126
21842
  this.#goalActive = previousGoalActive;
21127
21843
  throw error51;
21128
21844
  }
21129
21845
  if (this.#closed || this.#faulted)
21130
21846
  return failure("invalidState", "ZCode closed before confirming the turn");
21131
- active.accepted = true;
21132
- this.#emit({ type: "turn.started", turnId: id });
21133
- for (const message of active.pending.splice(0))
21847
+ active2.accepted = true;
21848
+ this.#emit({ type: "turn.started", turnId: id2 });
21849
+ for (const message of active2.pending.splice(0))
21134
21850
  this.#message(message);
21135
21851
  if (method === "goalSession" && result.startedTurn !== true) {
21136
21852
  const response = text(result.response);
21137
21853
  if (response)
21138
- active.projection.complete({
21854
+ active2.projection.complete({
21139
21855
  item: {
21140
21856
  type: "agentMessage",
21141
- itemId: hostItemIdSchema.parse(`command:${id}`),
21857
+ itemId: hostItemIdSchema.parse(`command:${id2}`),
21142
21858
  text: response
21143
21859
  },
21144
21860
  outcome: { status: "succeeded" }
21145
21861
  });
21146
21862
  if (result.snapshot)
21147
21863
  this.#apply(snapshotSchema.parse(result.snapshot));
21148
- this.#finish(active, { status: "succeeded" });
21864
+ this.#finish(active2, { status: "succeeded" });
21149
21865
  }
21150
- return { ok: true, value: { turnId: id } };
21866
+ return { ok: true, value: { turnId: id2 } };
21151
21867
  }
21152
21868
  #message(message) {
21153
21869
  if (this.#closed || this.#faulted)
@@ -21199,17 +21915,17 @@ var ZcodeSession = class {
21199
21915
  if (this.#active?.terminal && this.#active.nativeId !== event.turnId)
21200
21916
  this.#finish(this.#active, eventOutcome(this.#active.terminal));
21201
21917
  if (!this.#active) {
21202
- const id = hostTurnIdSchema.parse(`zcode-autonomous-${randomUUID2()}`);
21918
+ const id2 = hostTurnIdSchema.parse(`zcode-autonomous-${randomUUID2()}`);
21203
21919
  this.#active = {
21204
- id,
21920
+ id: id2,
21205
21921
  accepted: true,
21206
21922
  pending: [],
21207
21923
  finishing: false,
21208
- projection: new TurnProjection(id, this.transport.options.cwd, (event2) => this.#emit(event2))
21924
+ projection: new TurnProjection(id2, this.transport.options.cwd, (event2) => this.#emit(event2))
21209
21925
  };
21210
21926
  this.#emit({
21211
21927
  type: "turn.autonomous.started",
21212
- turnId: id,
21928
+ turnId: id2,
21213
21929
  input: text(event.payload?.input) ? [{ type: "text", text: text(event.payload?.input) }] : []
21214
21930
  });
21215
21931
  }
@@ -21229,35 +21945,35 @@ var ZcodeSession = class {
21229
21945
  nativeSubagentId: p2.childSessionId
21230
21946
  });
21231
21947
  }
21232
- const active = this.#active;
21233
- if (!active || event.turnId && active.nativeId && event.turnId !== active.nativeId)
21948
+ const active2 = this.#active;
21949
+ if (!active2 || event.turnId && active2.nativeId && event.turnId !== active2.nativeId)
21234
21950
  return;
21235
21951
  if (event.type === "permission.resolved" || event.type === "userInput.resolved") {
21236
- const id = `zcode:${text(event.payload?.requestId)}`;
21237
- this.#closeInteraction(id, "superseded");
21952
+ const id2 = `zcode:${text(event.payload?.requestId)}`;
21953
+ this.#closeInteraction(id2, "superseded");
21238
21954
  }
21239
21955
  if (event.type === "turn.completed" || event.type === "turn.failed") {
21240
- active.terminal = event;
21956
+ active2.terminal = event;
21241
21957
  if (!this.#goalActive)
21242
- active.timer = setTimeout(() => this.#fault(new ZcodeError("unavailable", "ZCode did not confirm that the turn stopped")), this.transport.options.timeoutMs ?? 3e4);
21243
- } else if (!active.terminal)
21244
- active.projection.event(event);
21958
+ active2.timer = setTimeout(() => this.#fault(new ZcodeError("unavailable", "ZCode did not confirm that the turn stopped")), this.transport.options.timeoutMs ?? 3e4);
21959
+ } else if (!active2.terminal)
21960
+ active2.projection.event(event);
21245
21961
  }
21246
- #settle(active, reason) {
21247
- if (active.finishing)
21962
+ #settle(active2, reason) {
21963
+ if (active2.finishing)
21248
21964
  return;
21249
- active.finishing = true;
21965
+ active2.finishing = true;
21250
21966
  this.#terminalTask = (async () => {
21251
21967
  const snapshot = await this.#readNative();
21252
- if (this.#active !== active || this.#closed || this.#faulted)
21968
+ if (this.#active !== active2 || this.#closed || this.#faulted)
21253
21969
  return;
21254
- const turns = (await readHistory(this.transport, snapshot, active.terminal ? [active.terminal] : [])).turns;
21255
- const turn = turns.find((turn2) => turn2.nativeTurnRef.nativeTurnKey === active.messageId);
21970
+ const turns = (await readHistory(this.transport, snapshot, this.#models.index, active2.terminal ? [active2.terminal] : [])).turns;
21971
+ const turn = turns.find((turn2) => turn2.nativeTurnRef.nativeTurnKey === active2.messageId);
21256
21972
  if (turn)
21257
- active.projection.reconcile(turn.items);
21973
+ active2.projection.reconcile(turn.items);
21258
21974
  this.#apply(snapshot);
21259
- const cancelledBeforeTurnStarted = !active.nativeId && await active.cancellation;
21260
- const outcome = active.terminal ? eventOutcome(active.terminal) : turn?.outcome.status === "cancelled" ? turn.outcome : cancelledBeforeTurnStarted ? { status: "cancelled" } : reason === "session_compacted" ? { status: "succeeded" } : reason === "session_compact_cancelled" ? { status: "cancelled" } : reason.endsWith("failed") ? {
21975
+ const cancelledBeforeTurnStarted = !active2.nativeId && await active2.cancellation;
21976
+ const outcome = active2.terminal ? eventOutcome(active2.terminal) : turn?.outcome.status === "cancelled" ? turn.outcome : cancelledBeforeTurnStarted ? { status: "cancelled" } : reason === "session_compacted" ? { status: "succeeded" } : reason === "session_compact_cancelled" ? { status: "cancelled" } : reason.endsWith("failed") ? {
21261
21977
  status: "failed",
21262
21978
  error: {
21263
21979
  code: "nativeFailure",
@@ -21267,21 +21983,21 @@ var ZcodeSession = class {
21267
21983
  } : turn?.outcome;
21268
21984
  if (!outcome || outcome.status === "unknown")
21269
21985
  throw new ZcodeError("protocolError", "ZCode completed without a confirmed turn outcome");
21270
- if (this.#active !== active || this.#closed || this.#faulted)
21986
+ if (this.#active !== active2 || this.#closed || this.#faulted)
21271
21987
  return;
21272
21988
  this.#usage.replay(snapshot.messages, false);
21273
- this.#finish(active, {
21989
+ this.#finish(active2, {
21274
21990
  ...outcome,
21275
21991
  ...turn?.checkpoint ? { checkpoint: turn.checkpoint } : {}
21276
21992
  });
21277
21993
  await this.refreshUsage();
21278
21994
  })().catch((error51) => this.#fault(error51));
21279
21995
  }
21280
- #closeInteraction(id, reason) {
21281
- const pending = this.#pendingInteractions.get(id);
21996
+ #closeInteraction(id2, reason) {
21997
+ const pending = this.#pendingInteractions.get(id2);
21282
21998
  if (!pending)
21283
21999
  return;
21284
- this.#pendingInteractions.delete(id);
22000
+ this.#pendingInteractions.delete(id2);
21285
22001
  this.#emit({
21286
22002
  type: "interaction.closed",
21287
22003
  interactionId: pending.interaction.interactionId,
@@ -21289,21 +22005,21 @@ var ZcodeSession = class {
21289
22005
  reason
21290
22006
  });
21291
22007
  }
21292
- #finish(active, outcome) {
21293
- if (this.#active !== active)
22008
+ #finish(active2, outcome) {
22009
+ if (this.#active !== active2)
21294
22010
  return;
21295
- clearTimeout(active.timer);
21296
- for (const [id, pending] of this.#pendingInteractions) {
22011
+ clearTimeout(active2.timer);
22012
+ for (const [id2, pending] of this.#pendingInteractions) {
21297
22013
  void this.#respond(pending.requestId, pending.interaction.type === "approval" ? { decision: "deny" } : { action: "cancel" }).catch(() => {
21298
22014
  });
21299
- this.#closeInteraction(id, "cancelled");
22015
+ this.#closeInteraction(id2, "cancelled");
21300
22016
  }
21301
- active.projection.finish(outcome.status === "succeeded" ? { status: "succeeded" } : outcome);
22017
+ active2.projection.finish(outcome.status === "succeeded" ? { status: "succeeded" } : outcome);
21302
22018
  this.#active = void 0;
21303
22019
  this.#emit({
21304
22020
  type: "turn.completed",
21305
- turnId: active.id,
21306
- ...active.messageId ? { nativeTurnRef: nativeTurnRef(this.sessionId, active.messageId) } : {},
22021
+ turnId: active2.id,
22022
+ ...active2.messageId ? { nativeTurnRef: nativeTurnRef(this.sessionId, active2.messageId) } : {},
21307
22023
  outcome
21308
22024
  });
21309
22025
  }
@@ -21377,10 +22093,24 @@ var ZcodeAdapter = class {
21377
22093
  options;
21378
22094
  harnessId = ZCODE_ID;
21379
22095
  commandCatalog = COMMAND_CATALOG;
22096
+ #inspectedModels = /* @__PURE__ */ new Map();
22097
+ normalizeStoredModelRef = (ref, catalog) => {
22098
+ let match;
22099
+ for (const models of this.#inspectedModels.values()) {
22100
+ if (!isDeepStrictEqual(models.catalog, catalog))
22101
+ continue;
22102
+ const candidate = normalizeStoredZcodeModelRef(ref, models.index);
22103
+ if (!candidate || match && match.id !== candidate.id)
22104
+ return void 0;
22105
+ match = candidate;
22106
+ }
22107
+ return match;
22108
+ };
21380
22109
  #closed = false;
21381
22110
  #sessions = /* @__PURE__ */ new Set();
21382
22111
  #transports = /* @__PURE__ */ new Set();
21383
22112
  #opening = /* @__PURE__ */ new Set();
22113
+ #inflightInspect = /* @__PURE__ */ new Map();
21384
22114
  // One verification page and SDK instance for the whole Host, as in ZCode Desktop.
21385
22115
  #verifier;
21386
22116
  #prewarmed = false;
@@ -21393,7 +22123,7 @@ var ZcodeAdapter = class {
21393
22123
  appVersion,
21394
22124
  ...this.options.openLocalPage ? { openLocalPage: this.options.openLocalPage } : {}
21395
22125
  });
21396
- async #transport(cwd, environment) {
22126
+ async #transport(cwd, environment, keyOptions) {
21397
22127
  if (this.#closed)
21398
22128
  throw new ZcodeError("invalidState", "ZCode Adapter is closed");
21399
22129
  if (!(await stat2(cwd)).isDirectory())
@@ -21403,6 +22133,7 @@ var ZcodeAdapter = class {
21403
22133
  environment: { ...this.options.environment ?? process.env, ...environment },
21404
22134
  ...this.options.app ? { app: this.options.app } : {},
21405
22135
  ...this.options.timeoutMs ? { timeoutMs: this.options.timeoutMs } : {},
22136
+ ...keyOptions ? { keyOptions } : {},
21406
22137
  verifier: this.#sharedVerifier
21407
22138
  };
21408
22139
  const transport = this.options.createTransport ? this.options.createTransport(options) : new CliTransport(options);
@@ -21416,25 +22147,52 @@ var ZcodeAdapter = class {
21416
22147
  throw error51;
21417
22148
  }
21418
22149
  }
21419
- async inspect(input = {}) {
22150
+ async inspect(input2 = {}) {
22151
+ const cwd = path7.resolve(input2.cwd ?? process.cwd());
22152
+ const access = input2.credentialAccess;
22153
+ return this.#inspect(cwd, access ? { access, requestedAt: performance.now() } : {});
22154
+ }
22155
+ async #inspect(cwd, keyOptions) {
22156
+ const { access } = keyOptions;
22157
+ const existing = this.#inflightInspect.get(cwd);
22158
+ if (existing) {
22159
+ if (access) {
22160
+ const { skipped } = existing.keyOptions;
22161
+ if (skipped && (skipped === "allow" || access === "retry")) {
22162
+ await existing.task;
22163
+ return this.#inspect(cwd, keyOptions);
22164
+ }
22165
+ if (!existing.keyOptions.access || access === "retry" && existing.keyOptions.access !== "retry")
22166
+ Object.assign(existing.keyOptions, keyOptions);
22167
+ }
22168
+ return existing.task;
22169
+ }
22170
+ const task = this.#runInspect(cwd, keyOptions).finally(() => this.#inflightInspect.delete(cwd));
22171
+ this.#inflightInspect.set(cwd, { keyOptions, task });
22172
+ return task;
22173
+ }
22174
+ async #runInspect(cwd, keyOptions) {
21420
22175
  let transport;
21421
22176
  try {
21422
- transport = await this.#transport(path6.resolve(input.cwd ?? process.cwd()));
22177
+ transport = await this.#transport(cwd, void 0, keyOptions);
21423
22178
  const settings = await readCatalog(transport);
21424
- const catalog = modelCatalog(settings);
21425
- if (!catalog.models.length)
22179
+ const models = modelCatalog(settings);
22180
+ const { catalog } = models;
22181
+ if (!catalog.models.length) {
22182
+ const issue2 = transport.codingPlanIssue ?? transport.credentialIssue;
22183
+ const retryable = !transport.credentialIssue;
21426
22184
  return {
21427
22185
  status: "unavailable",
21428
22186
  // A signed-in account without an active plan is not a login problem; only a signed-out
21429
22187
  // ZCode Desktop needs the login prompt.
21430
- error: !transport.signedIn ? {
22188
+ error: issue2 ? {
22189
+ code: transport.credentialAccessRequired ? "credentialAccessRequired" : "configurationRequired",
22190
+ message: issue2,
22191
+ retryable
22192
+ } : !transport.signedIn ? {
21431
22193
  code: "authenticationRequired",
21432
22194
  message: "ZCode has no available models. Sign in to ZCode Desktop with a Start Plan or Personal Coding Plan account, or add a personal provider, then re-detect ZCode. Team Coding Plan is not supported.",
21433
22195
  retryable: true
21434
- } : transport.codingPlanIssue ? {
21435
- code: "configurationRequired",
21436
- message: transport.codingPlanIssue,
21437
- retryable: true
21438
22196
  } : transport.startPlanChecked ? {
21439
22197
  code: "configurationRequired",
21440
22198
  message: "ZCode is signed in, but the account has no available models: no active Start Plan or event quota, no Personal Coding Plan, and no personal provider. Free trial and event quotas expire; subscribe to GLM Coding Plan or add a personal provider (API Key) in ZCode Desktop, then re-detect ZCode. Team Coding Plan is not supported.",
@@ -21446,6 +22204,8 @@ var ZcodeAdapter = class {
21446
22204
  retryable: true
21447
22205
  }
21448
22206
  };
22207
+ }
22208
+ this.#inspectedModels.set(cwd, models);
21449
22209
  return {
21450
22210
  status: "ready",
21451
22211
  catalog,
@@ -21462,15 +22222,15 @@ var ZcodeAdapter = class {
21462
22222
  }
21463
22223
  }
21464
22224
  }
21465
- async open(input) {
21466
- if (input.kind === "fork" || input.kind === "rollbackLastTurn")
22225
+ async open(input2) {
22226
+ if (input2.kind === "fork" || input2.kind === "rollbackLastTurn")
21467
22227
  return failure("unsupported", "ZCode history derivation is not enabled for the ZCode Adapter");
21468
- const parsedRef = input.kind === "resume" ? nativeSessionRefSchema.safeParse(input.nativeRef) : void 0;
22228
+ const parsedRef = input2.kind === "resume" ? nativeSessionRefSchema.safeParse(input2.nativeRef) : void 0;
21469
22229
  if (parsedRef && !parsedRef.success)
21470
22230
  return failure("invalidRequest", "Invalid ZCode Session reference");
21471
22231
  const nativeRef = parsedRef?.data;
21472
22232
  const locator = record2(nativeRef?.locator);
21473
- if (nativeRef && (nativeRef.harnessId !== ZCODE_ID || nativeRef.formatVersion !== 1 || locator.backend !== "local-service" || typeof locator.cwd !== "string" || !sameWorkspaceDirectory(locator.cwd, input.cwd)))
22233
+ if (nativeRef && (nativeRef.harnessId !== ZCODE_ID || nativeRef.formatVersion !== 1 || locator.backend !== "local-service" || typeof locator.cwd !== "string" || !sameWorkspaceDirectory(locator.cwd, input2.cwd)))
21474
22234
  return failure("invalidRequest", "ZCode Session identity or workspace does not match");
21475
22235
  const key = nativeRef?.nativeSessionId;
21476
22236
  if (key && (this.#opening.has(key) || [...this.#sessions].some((s) => s.sessionId === key)))
@@ -21480,20 +22240,28 @@ var ZcodeAdapter = class {
21480
22240
  let transport;
21481
22241
  let createdId;
21482
22242
  try {
21483
- transport = await this.#transport(path6.resolve(input.cwd), input.environment);
22243
+ const prewarm = input2.kind === "create" && input2.prewarm === true;
22244
+ transport = await this.#transport(path7.resolve(input2.cwd), input2.environment, prewarm ? void 0 : { access: "allow" });
22245
+ const credentialIssue = transport.credentialIssue ?? "ZCode credential access is required";
22246
+ if (prewarm && transport.credentialAccessRequired)
22247
+ throw new ZcodeError("credentialAccessRequired", credentialIssue);
21484
22248
  let snapshot, settings;
21485
- if (input.kind === "create") {
22249
+ let requestedModel;
22250
+ if (input2.kind === "create") {
21486
22251
  settings = await readCatalog(transport);
21487
- if (input.permissionModeId && !permissionModes().modes.some((m) => m.id === input.permissionModeId))
22252
+ const { catalog, index } = modelCatalog(settings);
22253
+ if (transport.credentialAccessRequired && !catalog.models.length)
22254
+ throw new ZcodeError("credentialAccessRequired", credentialIssue);
22255
+ if (input2.permissionModeId && !permissionModes().modes.some((m) => m.id === input2.permissionModeId))
21488
22256
  throw new ZcodeError("invalidRequest", "Unknown ZCode permission mode");
21489
- const model2 = input.model ? selectNativeModel(input.model, settings, input.thinkingOptionId) : void 0;
21490
- const mode = input.executionPolicy === "unattended-full-access" ? "yolo" : input.permissionModeId;
22257
+ requestedModel = input2.model ? selectNativeModel(input2.model, index, settings.model.current, input2.thinkingOptionId) : void 0;
22258
+ const mode = input2.executionPolicy === "unattended-full-access" ? "yolo" : input2.permissionModeId;
21491
22259
  const created = await transport.command(null, "createSession", {
21492
- workspaceId: input.cwd,
22260
+ workspaceId: input2.cwd,
21493
22261
  config: {
21494
- ...model2 ? { modelSelection: model2 } : {},
22262
+ ...requestedModel ? { modelSelection: requestedModel } : {},
21495
22263
  ...mode ? { mode } : {},
21496
- ...input.thinkingOptionId ? { thought: input.thinkingOptionId } : {}
22264
+ ...input2.thinkingOptionId ? { thought: input2.thinkingOptionId } : {}
21497
22265
  }
21498
22266
  });
21499
22267
  const result = record2(created.result);
@@ -21502,21 +22270,21 @@ var ZcodeAdapter = class {
21502
22270
  createdId = result.sessionId;
21503
22271
  snapshot = snapshotSchema.parse(await transport.request("readSession", { sessionId: createdId }));
21504
22272
  } else {
21505
- snapshot = snapshotSchema.parse(await transport.request("resumeSession", { sessionId: input.nativeRef.nativeSessionId }));
21506
- if (snapshot.session.sessionId !== input.nativeRef.nativeSessionId)
22273
+ snapshot = snapshotSchema.parse(await transport.request("resumeSession", { sessionId: input2.nativeRef.nativeSessionId }));
22274
+ if (snapshot.session.sessionId !== input2.nativeRef.nativeSessionId)
21507
22275
  throw new ZcodeError("protocolError", "ZCode resumed a different Session");
21508
22276
  settings = snapshot.settings;
21509
22277
  }
21510
- if (!sameWorkspaceDirectory(snapshot.session.workspace.workspacePath, input.cwd))
22278
+ if (!sameWorkspaceDirectory(snapshot.session.workspace.workspacePath, input2.cwd))
21511
22279
  throw new ZcodeError("protocolError", "ZCode Session belongs to a different workspace");
21512
22280
  if (snapshot.projection.currentTurnId || snapshot.session.status === "running")
21513
22281
  throw new ZcodeError("sessionBusy", "ZCode Session is executing native work", true);
21514
- if (input.kind === "create") {
21515
- if (input.model && (!snapshot.settings.model.current || encodeModel(snapshot.settings.model.current).id !== input.model.id))
22282
+ if (input2.kind === "create") {
22283
+ if (requestedModel && (!snapshot.settings.model.current || !sameNativeModel(snapshot.settings.model.current, requestedModel)))
21516
22284
  throw new ZcodeError("nativeFailure", "ZCode did not apply the requested model");
21517
- if (input.thinkingOptionId && snapshot.settings.thoughtLevel.current !== input.thinkingOptionId)
22285
+ if (input2.thinkingOptionId && snapshot.settings.thoughtLevel.current !== input2.thinkingOptionId)
21518
22286
  throw new ZcodeError("nativeFailure", "ZCode did not apply the requested thinking option");
21519
- const requestedMode = input.executionPolicy === "unattended-full-access" ? "yolo" : input.permissionModeId;
22287
+ const requestedMode = input2.executionPolicy === "unattended-full-access" ? "yolo" : input2.permissionModeId;
21520
22288
  if (requestedMode && snapshot.settings.mode.current !== requestedMode)
21521
22289
  throw new ZcodeError("nativeFailure", "ZCode did not apply the requested permission mode");
21522
22290
  }
@@ -21549,6 +22317,7 @@ var ZcodeAdapter = class {
21549
22317
  }
21550
22318
  async close() {
21551
22319
  this.#closed = true;
22320
+ this.#inspectedModels.clear();
21552
22321
  await Promise.all([...this.#sessions].map((session) => session.close()));
21553
22322
  await Promise.all([...this.#transports].map((transport) => transport.close()));
21554
22323
  this.#sessions.clear();