@codexhost/cli-linux-arm64 0.23.0 → 0.24.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 (56) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +1565 -1805
  4. package/app/console-web.js +5786 -1600
  5. package/app/desktop-controller.mjs +13104 -2842
  6. package/app/host-runtime.mjs +50518 -51753
  7. package/app/plugins/antigravity/plugin.mjs +1932 -1148
  8. package/app/plugins/claude-code/plugin.mjs +1676 -1218
  9. package/app/plugins/codebuddy/plugin.mjs +1266 -850
  10. package/app/plugins/codex-usage/plugin.mjs +916 -737
  11. package/app/plugins/copilot/plugin.mjs +838 -640
  12. package/app/plugins/cursor-cli/plugin.mjs +1058 -747
  13. package/app/plugins/deepseek-harness/plugin.mjs +1302 -1070
  14. package/app/plugins/devin/plugin.mjs +949 -752
  15. package/app/plugins/grok/plugin.mjs +1132 -964
  16. package/app/plugins/hermes/plugin.mjs +1084 -905
  17. package/app/plugins/kimi-code/plugin.mjs +977 -804
  18. package/app/plugins/kiro-cli/plugin.mjs +951 -758
  19. package/app/plugins/omp/plugin.mjs +1408 -1169
  20. package/app/plugins/opencode/plugin.mjs +1385 -1142
  21. package/app/plugins/pi/plugin.mjs +1515 -1287
  22. package/app/plugins/qoder/plugin.mjs +861 -676
  23. package/app/plugins/qoder-cn/plugin.mjs +861 -676
  24. package/app/plugins/qwen-code/plugin.mjs +1060 -888
  25. package/app/plugins/workbuddy/plugin.mjs +1272 -856
  26. package/app/plugins/zcode/plugin.mjs +1529 -880
  27. package/app/renderer-extension.js +11568 -7827
  28. package/app/web/assets/index-CTCFIQbU.css +1 -0
  29. package/app/web/assets/index-IvFk9KT-.js +203 -0
  30. package/app/web/codexhost-settings.js +4472 -36194
  31. package/app/web/index.html +2 -2
  32. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  33. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-approval/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +74 -74
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +75 -64
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +19 -16
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +3 -3
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +7 -7
  49. package/app/web/sw.js +8 -1
  50. package/app/web-modules/server.mjs +2682 -5540
  51. package/bin/codexhost +0 -0
  52. package/libexec/codexhost-shim +0 -0
  53. package/libexec/codexhost-updater +0 -0
  54. package/package.json +1 -1
  55. package/app/web/assets/index-DJW4bmyx.css +0 -1
  56. package/app/web/assets/index-Dyh1KzAB.js +0 -201
@@ -32,10 +32,10 @@ function executableExtensions(command, platform, environment) {
32
32
  return [""];
33
33
  return (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim()).filter(Boolean);
34
34
  }
35
- function isExecutableFile(filePath, platform) {
35
+ function isExecutableFile(filePath2, platform) {
36
36
  try {
37
- fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
38
- return fs.statSync(filePath).isFile();
37
+ fs.accessSync(filePath2, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
38
+ return fs.statSync(filePath2).isFile();
39
39
  } catch {
40
40
  return false;
41
41
  }
@@ -487,6 +487,9 @@ function createHarnessInstaller(environment, source) {
487
487
  };
488
488
  }
489
489
 
490
+ // dist/versioned-adapter.js
491
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
492
+
490
493
  // dist/usage-statistics.js
491
494
  import os2 from "node:os";
492
495
  import path5 from "node:path";
@@ -1804,8 +1807,8 @@ function cleanEnum(obj) {
1804
1807
  return Number.isNaN(Number.parseInt(k, 10));
1805
1808
  }).map((el) => el[1]);
1806
1809
  }
1807
- function base64ToUint8Array(base643) {
1808
- const binaryString = atob(base643);
1810
+ function base64ToUint8Array(base644) {
1811
+ const binaryString = atob(base644);
1809
1812
  const bytes = new Uint8Array(binaryString.length);
1810
1813
  for (let i = 0; i < binaryString.length; i++) {
1811
1814
  bytes[i] = binaryString.charCodeAt(i);
@@ -1820,9 +1823,9 @@ function uint8ArrayToBase64(bytes) {
1820
1823
  return btoa(binaryString);
1821
1824
  }
1822
1825
  function base64urlToUint8Array(base64url3) {
1823
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1824
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1825
- return base64ToUint8Array(base643 + padding);
1826
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1827
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1828
+ return base64ToUint8Array(base644 + padding);
1826
1829
  }
1827
1830
  function uint8ArrayToBase64url(bytes) {
1828
1831
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -3188,8 +3191,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
3188
3191
  function isValidBase64URL(data) {
3189
3192
  if (!base64url.test(data))
3190
3193
  return false;
3191
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3192
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
3194
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3195
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
3193
3196
  return isValidBase64(padded);
3194
3197
  }
3195
3198
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -3643,42 +3646,42 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3643
3646
  }
3644
3647
  doc.write(`const newResult = {};`);
3645
3648
  for (const key of normalized.keys) {
3646
- const id = ids[key];
3649
+ const id2 = ids[key];
3647
3650
  const k = esc(key);
3648
3651
  const schema = shape[key];
3649
3652
  const isOptionalIn = schema?._zod?.optin === "optional";
3650
3653
  const isOptionalOut = schema?._zod?.optout === "optional";
3651
- doc.write(`const ${id} = ${parseStr(key)};`);
3654
+ doc.write(`const ${id2} = ${parseStr(key)};`);
3652
3655
  if (isOptionalIn && isOptionalOut) {
3653
3656
  doc.write(`
3654
- if (${id}.issues.length) {
3657
+ if (${id2}.issues.length) {
3655
3658
  if (${k} in input) {
3656
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3659
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3657
3660
  ...iss,
3658
3661
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3659
3662
  })));
3660
3663
  }
3661
3664
  }
3662
3665
 
3663
- if (${id}.value === undefined) {
3666
+ if (${id2}.value === undefined) {
3664
3667
  if (${k} in input) {
3665
3668
  newResult[${k}] = undefined;
3666
3669
  }
3667
3670
  } else {
3668
- newResult[${k}] = ${id}.value;
3671
+ newResult[${k}] = ${id2}.value;
3669
3672
  }
3670
3673
 
3671
3674
  `);
3672
3675
  } else if (!isOptionalIn) {
3673
3676
  doc.write(`
3674
- const ${id}_present = ${k} in input;
3675
- if (${id}.issues.length) {
3676
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3677
+ const ${id2}_present = ${k} in input;
3678
+ if (${id2}.issues.length) {
3679
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3677
3680
  ...iss,
3678
3681
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3679
3682
  })));
3680
3683
  }
3681
- if (!${id}_present && !${id}.issues.length) {
3684
+ if (!${id2}_present && !${id2}.issues.length) {
3682
3685
  payload.issues.push({
3683
3686
  code: "invalid_type",
3684
3687
  expected: "nonoptional",
@@ -3687,30 +3690,30 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3687
3690
  });
3688
3691
  }
3689
3692
 
3690
- if (${id}_present) {
3691
- if (${id}.value === undefined) {
3693
+ if (${id2}_present) {
3694
+ if (${id2}.value === undefined) {
3692
3695
  newResult[${k}] = undefined;
3693
3696
  } else {
3694
- newResult[${k}] = ${id}.value;
3697
+ newResult[${k}] = ${id2}.value;
3695
3698
  }
3696
3699
  }
3697
3700
 
3698
3701
  `);
3699
3702
  } else {
3700
3703
  doc.write(`
3701
- if (${id}.issues.length) {
3702
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3704
+ if (${id2}.issues.length) {
3705
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3703
3706
  ...iss,
3704
3707
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3705
3708
  })));
3706
3709
  }
3707
3710
 
3708
- if (${id}.value === undefined) {
3711
+ if (${id2}.value === undefined) {
3709
3712
  if (${k} in input) {
3710
3713
  newResult[${k}] = undefined;
3711
3714
  }
3712
3715
  } else {
3713
- newResult[${k}] = ${id}.value;
3716
+ newResult[${k}] = ${id2}.value;
3714
3717
  }
3715
3718
 
3716
3719
  `);
@@ -12042,26 +12045,26 @@ function extractDefs(ctx, schema) {
12042
12045
  throw new Error("Unprocessed schema. This is a bug in Zod.");
12043
12046
  const idToSchema = /* @__PURE__ */ new Map();
12044
12047
  for (const entry of ctx.seen.entries()) {
12045
- const id = ctx.metadataRegistry.get(entry[0])?.id;
12046
- if (id) {
12047
- const existing = idToSchema.get(id);
12048
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
12049
+ if (id2) {
12050
+ const existing = idToSchema.get(id2);
12048
12051
  if (existing && existing !== entry[0]) {
12049
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
12052
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
12050
12053
  }
12051
- idToSchema.set(id, entry[0]);
12054
+ idToSchema.set(id2, entry[0]);
12052
12055
  }
12053
12056
  }
12054
12057
  const makeURI = (entry) => {
12055
12058
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
12056
12059
  if (ctx.external) {
12057
12060
  const externalId = ctx.external.registry.get(entry[0])?.id;
12058
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
12061
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
12059
12062
  if (externalId) {
12060
12063
  return { ref: uriGenerator(externalId) };
12061
12064
  }
12062
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
12063
- entry[1].defId = id;
12064
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
12065
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
12066
+ entry[1].defId = id2;
12067
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
12065
12068
  }
12066
12069
  if (entry[1] === root) {
12067
12070
  return { ref: "#" };
@@ -12109,8 +12112,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
12109
12112
  continue;
12110
12113
  }
12111
12114
  }
12112
- const id = ctx.metadataRegistry.get(entry[0])?.id;
12113
- if (id) {
12115
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
12116
+ if (id2) {
12114
12117
  extractToDef(entry);
12115
12118
  continue;
12116
12119
  }
@@ -12206,10 +12209,10 @@ function finalize(ctx, schema) {
12206
12209
  } else {
12207
12210
  }
12208
12211
  if (ctx.external?.uri) {
12209
- const id = ctx.external.registry.get(schema)?.id;
12210
- if (!id)
12212
+ const id2 = ctx.external.registry.get(schema)?.id;
12213
+ if (!id2)
12211
12214
  throw new Error("Schema is missing an `id` property");
12212
- result.$id = ctx.external.uri(id);
12215
+ result.$id = ctx.external.uri(id2);
12213
12216
  }
12214
12217
  Object.assign(result, root.def ?? root.schema);
12215
12218
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -12369,9 +12372,9 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12369
12372
  json3.type = "number";
12370
12373
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
12371
12374
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
12372
- const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12375
+ const legacy2 = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12373
12376
  if (exMin) {
12374
- if (legacy) {
12377
+ if (legacy2) {
12375
12378
  json3.minimum = exclusiveMinimum;
12376
12379
  json3.exclusiveMinimum = true;
12377
12380
  } else {
@@ -12381,7 +12384,7 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12381
12384
  json3.minimum = minimum;
12382
12385
  }
12383
12386
  if (exMax) {
12384
- if (legacy) {
12387
+ if (legacy2) {
12385
12388
  json3.maximum = exclusiveMaximum;
12386
12389
  json3.exclusiveMaximum = true;
12387
12390
  } else {
@@ -13243,7 +13246,7 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
13243
13246
 
13244
13247
  // ../../../node_modules/zod/v4/classic/schemas.js
13245
13248
  var _installedGroups = /* @__PURE__ */ new WeakMap();
13246
- function _installLazyMethods(inst, group, methods) {
13249
+ function _installLazyMethods(inst, group, methods2) {
13247
13250
  const proto = Object.getPrototypeOf(inst);
13248
13251
  let installed = _installedGroups.get(proto);
13249
13252
  if (!installed) {
@@ -13253,8 +13256,8 @@ function _installLazyMethods(inst, group, methods) {
13253
13256
  if (installed.has(group))
13254
13257
  return;
13255
13258
  installed.add(group);
13256
- for (const key in methods) {
13257
- const fn = methods[key];
13259
+ for (const key in methods2) {
13260
+ const fn = methods2[key];
13258
13261
  Object.defineProperty(proto, key, {
13259
13262
  configurable: true,
13260
13263
  enumerable: false,
@@ -15065,87 +15068,6 @@ function date4(params) {
15065
15068
  // ../../../node_modules/zod/v4/classic/external.js
15066
15069
  config(en_default());
15067
15070
 
15068
- // ../../shared-contracts/dist/ids.js
15069
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15070
- message: "Identifier must not be empty or whitespace"
15071
- });
15072
- var harnessIdSchema = opaqueIdSchema.brand();
15073
- var hostThreadIdSchema = opaqueIdSchema.brand();
15074
- var hostTurnIdSchema = opaqueIdSchema.brand();
15075
- var hostItemIdSchema = opaqueIdSchema.brand();
15076
- var hostInteractionIdSchema = opaqueIdSchema.brand();
15077
-
15078
- // ../../shared-contracts/dist/harness-plugins.js
15079
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15080
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15081
- var HARNESS_PLUGIN_LIMIT = 128;
15082
- var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
15083
- var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
15084
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
15085
- 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");
15086
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15087
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15088
- var harnessInstallationGuideSchema = external_exports.object({
15089
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15090
- before: localizedTextSchema.optional(),
15091
- after: localizedTextSchema.optional(),
15092
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15093
- }).strict();
15094
- var pluginPresentationShape = {
15095
- id: installedHarnessPluginIdSchema,
15096
- name: external_exports.string().trim().min(1).max(128),
15097
- version: external_exports.string().min(1).max(128),
15098
- /** Capability-only plugin; omitted for existing session-capable plugins. */
15099
- kind: external_exports.literal("usage").optional(),
15100
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15101
- iconStyle: external_exports.object({
15102
- vector: external_exports.object({
15103
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15104
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15105
- paths: external_exports.array(external_exports.object({
15106
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15107
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15108
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15109
- }).strict()).min(1).max(32)
15110
- }).strict().optional(),
15111
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15112
- borderRadius: external_exports.number().min(0).max(50).optional(),
15113
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
15114
- }).strict().optional(),
15115
- installation: harnessInstallationGuideSchema.optional(),
15116
- notice: localizedTextSchema.optional(),
15117
- /** The factory accepts a persisted local entrypoint through its construction context. */
15118
- launchCommand: external_exports.literal(true).optional(),
15119
- links: external_exports.object({
15120
- website: documentationUrlSchema.optional(),
15121
- documentation: documentationUrlSchema.optional(),
15122
- installation: documentationUrlSchema.optional()
15123
- }).strict().optional()
15124
- };
15125
- var harnessPluginManifestSchema = external_exports.object({
15126
- manifestVersion: external_exports.literal(1),
15127
- ...pluginPresentationShape,
15128
- adapterApiVersion: external_exports.number().int().positive(),
15129
- entry: pluginRelativeResourceSchema,
15130
- icon: pluginRelativeResourceSchema.optional()
15131
- }).strict();
15132
- 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);
15133
- var harnessPluginDescriptorSchema = external_exports.object({
15134
- ...pluginPresentationShape,
15135
- icon: harnessPluginIconSchema.optional()
15136
- }).strict();
15137
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
15138
- var harnessPluginListResultSchema = external_exports.object({
15139
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15140
- }).strict();
15141
- var harnessPluginConfigurationSchema = external_exports.object({
15142
- version: external_exports.literal(1),
15143
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15144
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15145
- message: "Enabled plugin IDs must be unique",
15146
- path: ["enabled"]
15147
- });
15148
-
15149
15071
  // ../../shared-contracts/dist/json-value.js
15150
15072
  function rejectExplicitUndefined(keys) {
15151
15073
  return (value, context) => {
@@ -15205,403 +15127,73 @@ var jsonValueSchema = nonCircularSchema.pipe(recursiveJsonValueSchema);
15205
15127
  var jsonArraySchema = nonCircularSchema.pipe(external_exports.array(recursiveJsonValueSchema));
15206
15128
  var jsonObjectSchema = nonCircularSchema.pipe(external_exports.record(external_exports.string(), recursiveJsonValueSchema));
15207
15129
 
15208
- // ../../shared-contracts/dist/desktop-extensions.js
15209
- var DESKTOP_EXTENSION_API_VERSION = 1;
15210
- var DESKTOP_EXTENSION_LIMIT = 64;
15211
- var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15212
- var DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH = 4 * Math.ceil(DESKTOP_EXTENSION_ZIP_MAX_BYTES / 3);
15213
- var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15214
- var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15215
- var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15216
- var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15217
- var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15218
- var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15219
- var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15220
- var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15221
- var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15222
- var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15223
- var desktopExtensionIdSchema = installedPluginIdSchema;
15224
- var desktopExtensionSlotSchema = external_exports.enum([
15225
- "sidebar.thread-layout",
15226
- "sidebar.thread-badge",
15227
- "appearance.theme"
15228
- ]);
15229
- var desktopExtensionCategorySchema = external_exports.enum([
15230
- "appearance",
15231
- "interface",
15232
- "workflow",
15233
- "analytics",
15234
- "integrations",
15235
- "tools"
15236
- ]);
15237
- var extensionName = external_exports.string().trim().min(1).max(128);
15238
- function desktopExtensionScreenshotMimeType(resource) {
15239
- switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15240
- case "png":
15241
- return "image/png";
15242
- case "jpg":
15243
- case "jpeg":
15244
- return "image/jpeg";
15245
- case "webp":
15246
- return "image/webp";
15247
- default:
15248
- return void 0;
15130
+ // ../../shared-contracts/dist/errors.js
15131
+ var codexhostErrorSchema = external_exports.strictObject({
15132
+ code: external_exports.string().min(1),
15133
+ message: external_exports.string().min(1),
15134
+ retryable: external_exports.boolean(),
15135
+ diagnostic: external_exports.string().min(1).optional(),
15136
+ stage: external_exports.string().min(1).optional(),
15137
+ durationMs: external_exports.number().int().nonnegative().optional(),
15138
+ stderrTail: external_exports.string().min(1).optional()
15139
+ }).superRefine(rejectExplicitUndefined(["diagnostic", "stage", "durationMs", "stderrTail"]));
15140
+
15141
+ // ../../shared-contracts/dist/harness-presentation.js
15142
+ var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
15143
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text) => text.trim().length > 0);
15144
+ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
15145
+ label: displayText(256).optional(),
15146
+ description: displayText(1024).optional()
15147
+ }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15148
+ 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");
15149
+
15150
+ // ../../shared-contracts/dist/ids.js
15151
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15152
+ message: "Identifier must not be empty or whitespace"
15153
+ });
15154
+ var harnessIdSchema = opaqueIdSchema.brand();
15155
+ var hostThreadIdSchema = opaqueIdSchema.brand();
15156
+ var hostTurnIdSchema = opaqueIdSchema.brand();
15157
+ var hostItemIdSchema = opaqueIdSchema.brand();
15158
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
15159
+
15160
+ // ../../shared-contracts/dist/harness-permission-modes.js
15161
+ var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
15162
+ var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
15163
+ var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
15164
+ var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
15165
+ var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15166
+ message: "Value must not be empty or whitespace"
15167
+ });
15168
+ 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();
15169
+ var harnessPermissionModeSchema = external_exports.object({
15170
+ id: harnessPermissionModeIdSchema,
15171
+ label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
15172
+ description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
15173
+ dangerous: external_exports.boolean().optional(),
15174
+ localizations: harnessLocalizationsSchema.optional()
15175
+ }).strict();
15176
+ var harnessPermissionModeCatalogSchema = external_exports.object({
15177
+ modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
15178
+ defaultModeId: harnessPermissionModeIdSchema
15179
+ }).strict().superRefine((catalog, context) => {
15180
+ const ids = /* @__PURE__ */ new Set();
15181
+ for (const [index, mode] of catalog.modes.entries()) {
15182
+ if (ids.has(mode.id)) {
15183
+ context.addIssue({
15184
+ code: "custom",
15185
+ message: "Permission Mode IDs must be unique",
15186
+ path: ["modes", index, "id"]
15187
+ });
15188
+ }
15189
+ ids.add(mode.id);
15249
15190
  }
15250
- }
15251
- function desktopExtensionAssetMimeType(resource) {
15252
- switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15253
- case "gif":
15254
- return "image/gif";
15255
- case "svg":
15256
- return "image/svg+xml";
15257
- case "woff2":
15258
- return "font/woff2";
15259
- case "json":
15260
- return "application/json";
15261
- case "css":
15262
- return "text/css";
15263
- default:
15264
- return desktopExtensionScreenshotMimeType(resource);
15265
- }
15266
- }
15267
- var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15268
- var desktopExtensionAssetPathSchema = pluginRelativeResourceSchema.refine((resource) => hasPortableSegments(resource) && desktopExtensionAssetMimeType(resource) !== void 0, "Expected a relative Desktop extension asset path with a supported suffix");
15269
- 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");
15270
- 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) => {
15271
- const { username, password } = new URL(value);
15272
- return !username && !password && !/[\\\s]/u.test(value);
15273
- }, "URL must not contain credentials, backslashes, or whitespace");
15274
- function localizedText(text) {
15275
- return external_exports.strictObject({ en: text, "zh-CN": text });
15276
- }
15277
- var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15278
- var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15279
- var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15280
- var settingField = {
15281
- key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15282
- label: desktopExtensionLocalizedTextSchema,
15283
- description: desktopExtensionLocalizedTextSchema.optional()
15284
- };
15285
- var numericSetting = {
15286
- ...settingField,
15287
- step: external_exports.number().positive().optional(),
15288
- default: external_exports.number().optional()
15289
- };
15290
- var settingOption = external_exports.strictObject({
15291
- value: external_exports.string(),
15292
- label: desktopExtensionLocalizedTextSchema
15293
- });
15294
- var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15295
- external_exports.strictObject({
15296
- ...settingField,
15297
- type: external_exports.literal("boolean"),
15298
- default: external_exports.boolean().optional()
15299
- }),
15300
- external_exports.strictObject({
15301
- ...settingField,
15302
- type: external_exports.literal("string"),
15303
- placeholder: desktopExtensionLocalizedTextSchema.optional(),
15304
- default: external_exports.string().optional()
15305
- }),
15306
- external_exports.strictObject({
15307
- ...numericSetting,
15308
- type: external_exports.literal("number"),
15309
- min: external_exports.number().optional(),
15310
- max: external_exports.number().optional()
15311
- }),
15312
- external_exports.strictObject({
15313
- ...numericSetting,
15314
- type: external_exports.literal("range"),
15315
- min: external_exports.number(),
15316
- max: external_exports.number()
15317
- }),
15318
- external_exports.strictObject({
15319
- ...settingField,
15320
- type: external_exports.literal("select"),
15321
- options: external_exports.array(settingOption).min(1),
15322
- default: external_exports.string().optional()
15323
- })
15324
- ]).superRefine((field2, ctx) => {
15325
- const issue2 = (path14, message) => ctx.addIssue({ code: "custom", path: [path14], message });
15326
- if (field2.type === "number" || field2.type === "range") {
15327
- const { min = -Infinity, max = Infinity, default: value } = field2;
15328
- if (min > max)
15329
- issue2("max", "Must be at least min");
15330
- if (value !== void 0 && (value < min || value > max))
15331
- issue2("default", "Must be within min and max");
15332
- } else if (field2.type === "select") {
15333
- const values = new Set(field2.options.map(({ value }) => value));
15334
- if (values.size !== field2.options.length)
15335
- issue2("options", "Duplicate option values");
15336
- if (field2.default !== void 0 && !values.has(field2.default))
15337
- issue2("default", "Must match an option value");
15338
- }
15339
- });
15340
- var manifestHeader = external_exports.object({
15341
- manifestVersion: external_exports.int().positive(),
15342
- id: desktopExtensionIdSchema,
15343
- name: external_exports.union([extensionName, localizedText(extensionName)]),
15344
- version: external_exports.string().min(1).max(128),
15345
- desktopApi: external_exports.int().positive()
15346
- }).passthrough();
15347
- var desktopExtensionManifestSchema = manifestHeader.extend({
15348
- manifestVersion: external_exports.literal(1),
15349
- desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15350
- description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15351
- author: external_exports.string().trim().min(1).max(128).optional(),
15352
- repository: desktopExtensionHttpUrlSchema.optional(),
15353
- details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15354
- icon: imagePathSchema.optional(),
15355
- screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15356
- desktop: external_exports.strictObject({
15357
- script: pluginRelativeResourceSchema,
15358
- style: pluginRelativeResourceSchema.optional()
15359
- }).optional(),
15360
- backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15361
- slots: slotsSchema.default(() => []),
15362
- settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15363
- categories: categoriesSchema.optional()
15364
- }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15365
- var desktopExtensionConfigurationSchema = external_exports.strictObject({
15366
- version: external_exports.literal(1),
15367
- revision: external_exports.int().nonnegative(),
15368
- enabled: external_exports.array(desktopExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs"),
15369
- reloadToken: external_exports.uuid().optional()
15370
- });
15371
- var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15372
- var desktopExtensionStatusSchema = external_exports.strictObject({
15373
- state: external_exports.enum([
15374
- "running",
15375
- "disabled",
15376
- "invalid",
15377
- "incompatible",
15378
- "conflict",
15379
- "failed",
15380
- "waiting"
15381
- ]),
15382
- hash: desktopExtensionHashSchema.optional(),
15383
- error: external_exports.string().optional(),
15384
- conflictWith: desktopExtensionIdSchema.optional()
15385
- });
15386
- var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15387
- controllerPid: external_exports.int().positive(),
15388
- targetId: external_exports.string().nullable(),
15389
- updatedAt: external_exports.iso.datetime(),
15390
- handledReloadToken: external_exports.uuid().optional(),
15391
- extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema)
15392
- });
15393
- var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15394
- function isGitHubDesktopExtensionZipballUrl(url2) {
15395
- return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15396
- }
15397
- var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15398
- const url2 = new URL(input);
15399
- 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);
15400
- }, "Expected a .zip download URL or a GitHub zipball URL");
15401
- var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15402
- id: desktopExtensionIdSchema,
15403
- version: external_exports.string().trim().min(1).max(128),
15404
- name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15405
- description: localizedText(external_exports.string().trim().min(1).max(4096)),
15406
- details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15407
- author: external_exports.string().trim().min(1).max(128),
15408
- repository: desktopExtensionHttpUrlSchema,
15409
- stars: external_exports.number().int().min(0).optional(),
15410
- downloads: external_exports.number().int().min(0).optional(),
15411
- categories: categoriesSchema.optional(),
15412
- trustTier: desktopExtensionTrustTierSchema.default("community"),
15413
- icon: desktopExtensionHttpUrlSchema.optional(),
15414
- screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15415
- downloadUrl: desktopExtensionZipUrlSchema,
15416
- sha256: desktopExtensionHashSchema,
15417
- slots: slotsSchema.optional(),
15418
- publishedAt: external_exports.string().optional(),
15419
- updatedAt: external_exports.string().optional(),
15420
- minCodexHostVersion: external_exports.string().optional()
15421
- });
15422
- var desktopExtensionCatalogSchema = external_exports.strictObject({
15423
- schemaVersion: external_exports.literal(1),
15424
- generatedAt: external_exports.string(),
15425
- extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, "Duplicate extension IDs")
15426
- });
15427
- var DESKTOP_EXTENSIONS_ASSET_METHOD = "codexhost/desktop/extensions/asset";
15428
- var DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD = "codexhost/desktop/extensions/settings/get";
15429
- var DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD = "codexhost/desktop/extensions/settings/set";
15430
- var DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD = "codexhost/desktop/extensions/backend/invoke";
15431
- var extensionIdParams = { id: desktopExtensionIdSchema };
15432
- var desktopExtensionsAssetParamsSchema = external_exports.strictObject({
15433
- ...extensionIdParams,
15434
- path: desktopExtensionAssetPathSchema
15435
- });
15436
- var desktopExtensionsAssetResultSchema = external_exports.strictObject({
15437
- mimeType: external_exports.string(),
15438
- dataUrl: external_exports.string()
15439
- });
15440
- var desktopExtensionsSettingsGetParamsSchema = external_exports.strictObject(extensionIdParams);
15441
- var desktopExtensionsSettingsSetParamsSchema = external_exports.strictObject({
15442
- ...extensionIdParams,
15443
- values: jsonObjectSchema
15444
- });
15445
- var desktopExtensionsSettingsResultSchema = external_exports.strictObject({ values: jsonObjectSchema });
15446
- var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15447
- var desktopExtensionsBackendInvokeParamsSchema = external_exports.strictObject({
15448
- ...extensionIdParams,
15449
- method: desktopExtensionBackendMethodSchema,
15450
- params: jsonValueSchema.optional()
15451
- });
15452
- var desktopExtensionsBackendInvokeResultSchema = external_exports.strictObject({
15453
- result: jsonValueSchema
15454
- });
15455
-
15456
- // ../../shared-contracts/dist/desktop-extension-management.js
15457
- var DESKTOP_EXTENSIONS_LIST_METHOD = "codexhost/desktop/extensions/list";
15458
- var DESKTOP_EXTENSIONS_ENABLE_METHOD = "codexhost/desktop/extensions/enable";
15459
- var DESKTOP_EXTENSIONS_DISABLE_METHOD = "codexhost/desktop/extensions/disable";
15460
- var DESKTOP_EXTENSIONS_CATALOG_METHOD = "codexhost/desktop/extensions/catalog";
15461
- var DESKTOP_EXTENSIONS_INSTALL_METHOD = "codexhost/desktop/extensions/install";
15462
- var DESKTOP_EXTENSIONS_UNINSTALL_METHOD = "codexhost/desktop/extensions/uninstall";
15463
- var DESKTOP_EXTENSIONS_RECOVER_METHOD = "codexhost/desktop/extensions/disable-all-and-reload";
15464
- var DESKTOP_EXTENSION_MANAGEMENT_METHODS = [
15465
- DESKTOP_EXTENSIONS_LIST_METHOD,
15466
- DESKTOP_EXTENSIONS_ENABLE_METHOD,
15467
- DESKTOP_EXTENSIONS_DISABLE_METHOD,
15468
- DESKTOP_EXTENSIONS_RECOVER_METHOD,
15469
- DESKTOP_EXTENSIONS_CATALOG_METHOD,
15470
- DESKTOP_EXTENSIONS_INSTALL_METHOD,
15471
- DESKTOP_EXTENSIONS_UNINSTALL_METHOD,
15472
- DESKTOP_EXTENSIONS_ASSET_METHOD,
15473
- DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD,
15474
- DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD,
15475
- DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD
15476
- ];
15477
- var revisionSchema = external_exports.int().nonnegative();
15478
- var desktopExtensionsListParamsSchema = external_exports.strictObject({});
15479
- var desktopExtensionSelectionParamsSchema = external_exports.strictObject({
15480
- id: desktopExtensionIdSchema,
15481
- expectedRevision: revisionSchema
15482
- });
15483
- var desktopExtensionsRecoveryParamsSchema = external_exports.strictObject({
15484
- expectedRevision: revisionSchema.optional()
15485
- });
15486
- 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);
15487
- var desktopExtensionListItemSchema = external_exports.strictObject({
15488
- // An invalid discovery can have a directory name that isn't a valid extension ID.
15489
- id: external_exports.string().min(1),
15490
- manifest: desktopExtensionManifestSchema.optional(),
15491
- iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15492
- screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15493
- enabled: external_exports.boolean(),
15494
- status: desktopExtensionStatusSchema
15495
- });
15496
- var desktopExtensionsListResultSchema = external_exports.strictObject({
15497
- configuration: desktopExtensionConfigurationSchema,
15498
- desktopConnected: external_exports.boolean(),
15499
- diagnostics: external_exports.array(external_exports.string()),
15500
- extensions: external_exports.array(desktopExtensionListItemSchema)
15501
- });
15502
- var desktopExtensionsCatalogParamsSchema = external_exports.strictObject({
15503
- forceRefresh: external_exports.boolean().optional()
15504
- });
15505
- var desktopExtensionsCatalogResultSchema = external_exports.strictObject({
15506
- catalogUrl: external_exports.string(),
15507
- source: external_exports.enum(["remote", "fallback"]),
15508
- fetchedAt: external_exports.string(),
15509
- cached: external_exports.boolean(),
15510
- extensions: desktopExtensionCatalogSchema.shape.extensions,
15511
- error: external_exports.string().optional()
15512
- });
15513
- var desktopExtensionsInstallParamsSchema = external_exports.strictObject({
15514
- source: external_exports.discriminatedUnion("type", [
15515
- external_exports.strictObject({ type: external_exports.literal("catalog"), id: desktopExtensionIdSchema }),
15516
- external_exports.strictObject({
15517
- type: external_exports.literal("url"),
15518
- url: desktopExtensionHttpUrlSchema,
15519
- expectedSha256: desktopExtensionHashSchema.optional()
15520
- }),
15521
- external_exports.strictObject({
15522
- type: external_exports.literal("zip-base64"),
15523
- fileName: external_exports.string().trim().min(1).max(255),
15524
- 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")
15525
- })
15526
- ])
15527
- });
15528
- var desktopExtensionsInstallResultSchema = external_exports.strictObject({
15529
- extensionId: desktopExtensionIdSchema,
15530
- version: external_exports.string().min(1),
15531
- replaced: external_exports.boolean(),
15532
- installedPath: external_exports.string(),
15533
- list: desktopExtensionsListResultSchema
15534
- });
15535
- var desktopExtensionsUninstallParamsSchema = external_exports.strictObject({
15536
- id: desktopExtensionIdSchema
15537
- });
15538
- var desktopExtensionsUninstallResultSchema = external_exports.strictObject({
15539
- removedId: desktopExtensionIdSchema,
15540
- list: desktopExtensionsListResultSchema
15541
- });
15542
- var desktopExtensionMutationResultSchema = external_exports.discriminatedUnion("state", [
15543
- external_exports.strictObject({ state: external_exports.literal("saved"), configuration: desktopExtensionConfigurationSchema }),
15544
- external_exports.strictObject({ state: external_exports.literal("slot-conflict"), conflictWith: desktopExtensionIdSchema }),
15545
- external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: revisionSchema })
15546
- ]);
15547
-
15548
- // ../../shared-contracts/dist/errors.js
15549
- var codexhostErrorSchema = external_exports.strictObject({
15550
- code: external_exports.string().min(1),
15551
- message: external_exports.string().min(1),
15552
- retryable: external_exports.boolean(),
15553
- diagnostic: external_exports.string().min(1).optional(),
15554
- stage: external_exports.string().min(1).optional(),
15555
- durationMs: external_exports.number().int().nonnegative().optional(),
15556
- stderrTail: external_exports.string().min(1).optional()
15557
- }).superRefine(rejectExplicitUndefined(["diagnostic", "stage", "durationMs", "stderrTail"]));
15558
-
15559
- // ../../shared-contracts/dist/harness-presentation.js
15560
- var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
15561
- var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text) => text.trim().length > 0);
15562
- var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
15563
- label: displayText(256).optional(),
15564
- description: displayText(1024).optional()
15565
- }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15566
- 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");
15567
-
15568
- // ../../shared-contracts/dist/harness-permission-modes.js
15569
- var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
15570
- var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
15571
- var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
15572
- var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
15573
- var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15574
- message: "Value must not be empty or whitespace"
15575
- });
15576
- 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();
15577
- var harnessPermissionModeSchema = external_exports.object({
15578
- id: harnessPermissionModeIdSchema,
15579
- label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
15580
- description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
15581
- dangerous: external_exports.boolean().optional(),
15582
- localizations: harnessLocalizationsSchema.optional()
15583
- }).strict();
15584
- var harnessPermissionModeCatalogSchema = external_exports.object({
15585
- modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
15586
- defaultModeId: harnessPermissionModeIdSchema
15587
- }).strict().superRefine((catalog, context) => {
15588
- const ids = /* @__PURE__ */ new Set();
15589
- for (const [index, mode] of catalog.modes.entries()) {
15590
- if (ids.has(mode.id)) {
15591
- context.addIssue({
15592
- code: "custom",
15593
- message: "Permission Mode IDs must be unique",
15594
- path: ["modes", index, "id"]
15595
- });
15596
- }
15597
- ids.add(mode.id);
15598
- }
15599
- if (!ids.has(catalog.defaultModeId)) {
15600
- context.addIssue({
15601
- code: "custom",
15602
- message: "Default Permission Mode must exist in the catalog",
15603
- path: ["defaultModeId"]
15604
- });
15191
+ if (!ids.has(catalog.defaultModeId)) {
15192
+ context.addIssue({
15193
+ code: "custom",
15194
+ message: "Default Permission Mode must exist in the catalog",
15195
+ path: ["defaultModeId"]
15196
+ });
15605
15197
  }
15606
15198
  });
15607
15199
  var threadPermissionModeSelectParamsSchema = external_exports.object({
@@ -15609,6 +15201,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15609
15201
  permissionModeId: harnessPermissionModeIdSchema
15610
15202
  }).strict();
15611
15203
 
15204
+ // ../../shared-contracts/dist/harness-route-limit.js
15205
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
15206
+
15612
15207
  // ../../shared-contracts/dist/thread-usage.js
15613
15208
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15614
15209
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -15641,7 +15236,7 @@ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15641
15236
  expiresAtUnix: nonNegativeSafeIntegerSchema,
15642
15237
  label: indicatorTextSchema(256).optional(),
15643
15238
  tooltip: indicatorTextSchema(1024).optional()
15644
- }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15239
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
15645
15240
  message: "Composer indicator IDs must be unique"
15646
15241
  });
15647
15242
  var threadUsageSnapshotSchema = external_exports.object({
@@ -15667,6 +15262,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15667
15262
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15668
15263
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15669
15264
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15265
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15670
15266
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15671
15267
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15672
15268
  }).strict().superRefine((usage, context) => {
@@ -15794,10 +15390,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
15794
15390
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15795
15391
  message: "Value must not be empty or whitespace"
15796
15392
  });
15797
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
15393
+ 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();
15394
+ var harnessModelServiceTierSchema = external_exports.enum(["priority", "ultrafast"]);
15798
15395
  var harnessModelRefSchema = external_exports.object({
15799
- id: harnessModelRefIdSchema
15396
+ id: harnessModelRefIdSchema,
15397
+ serviceTier: harnessModelServiceTierSchema.optional()
15800
15398
  }).strict();
15399
+ function sameHarnessModelRef(left, right) {
15400
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
15401
+ }
15801
15402
  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();
15802
15403
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15803
15404
  var harnessThinkingOptionSchema = external_exports.object({
@@ -15811,7 +15412,15 @@ var harnessModelSchema = external_exports.object({
15811
15412
  /** Optional opaque selection for this same Model with priority processing enabled. */
15812
15413
  fastModel: harnessModelRefSchema.optional(),
15813
15414
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
15814
- }).strict();
15415
+ }).strict().refine((model2) => model2.fastModel?.serviceTier === void 0 || model2.fastModel.id === model2.ref.id, {
15416
+ path: ["fastModel", "id"],
15417
+ message: "A tiered Fast Model must share the base Model ID"
15418
+ });
15419
+ function catalogModelForRef(catalog, ref) {
15420
+ if (!ref)
15421
+ return void 0;
15422
+ return catalog?.models.find((model2) => sameHarnessModelRef(model2.ref, ref) || sameHarnessModelRef(model2.fastModel, ref));
15423
+ }
15815
15424
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
15816
15425
  const ids = /* @__PURE__ */ new Set();
15817
15426
  for (const [index, option] of options.entries()) {
@@ -15831,26 +15440,26 @@ var harnessModelCatalogSchema = external_exports.object({
15831
15440
  thinkingOptions: harnessThinkingOptionsSchema,
15832
15441
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
15833
15442
  }).strict().superRefine((catalog, context) => {
15834
- const refs = /* @__PURE__ */ new Set();
15835
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15443
+ const refs = [];
15444
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
15836
15445
  for (const [index, model2] of catalog.models.entries()) {
15837
- if (refs.has(model2.ref.id)) {
15446
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
15838
15447
  context.addIssue({
15839
15448
  code: "custom",
15840
15449
  message: "Model Catalog refs must be unique",
15841
15450
  path: ["models", index, "ref", "id"]
15842
15451
  });
15843
15452
  }
15844
- refs.add(model2.ref.id);
15453
+ refs.push(model2.ref);
15845
15454
  if (model2.fastModel) {
15846
- if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15455
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.fastModel))) {
15847
15456
  context.addIssue({
15848
15457
  code: "custom",
15849
15458
  message: "Fast Model refs must be distinct and unique",
15850
15459
  path: ["models", index, "fastModel"]
15851
15460
  });
15852
15461
  }
15853
- refs.add(model2.fastModel.id);
15462
+ refs.push(model2.fastModel);
15854
15463
  }
15855
15464
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15856
15465
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -15871,7 +15480,7 @@ var harnessModelCatalogSchema = external_exports.object({
15871
15480
  }
15872
15481
  }
15873
15482
  }
15874
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
15483
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
15875
15484
  context.addIssue({
15876
15485
  code: "custom",
15877
15486
  message: "Default Model must exist in the Model Catalog",
@@ -15911,7 +15520,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15911
15520
  observe: external_exports.boolean()
15912
15521
  }).strict().optional(),
15913
15522
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15914
- steer: external_exports.boolean().optional()
15523
+ steer: external_exports.boolean().optional(),
15524
+ /**
15525
+ * True when the native plan (task list) outlives the Turn that changed it, so a reopened
15526
+ * Thread gets its latest plan again. Otherwise a plan stays with the Turn that made it.
15527
+ */
15528
+ persistentPlan: external_exports.boolean().optional()
15915
15529
  }).strict();
15916
15530
  var harnessConfigurationStateSchema = external_exports.object({
15917
15531
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15920,7 +15534,7 @@ var harnessConfigurationStateSchema = external_exports.object({
15920
15534
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15921
15535
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
15922
15536
  }).strict().superRefine((state, context) => {
15923
- if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id }) => id === state.effectiveThinkingOptionId)) {
15537
+ if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id: id2 }) => id2 === state.effectiveThinkingOptionId)) {
15924
15538
  context.addIssue({
15925
15539
  code: "custom",
15926
15540
  message: "Effective Thinking option must be currently available",
@@ -15928,150 +15542,696 @@ var harnessConfigurationStateSchema = external_exports.object({
15928
15542
  });
15929
15543
  }
15930
15544
  });
15931
- var harnessWebUiCapabilitySchema = external_exports.object({
15932
- open: external_exports.literal(true)
15933
- }).strict();
15934
- var readyHarnessInspectionSchema = external_exports.object({
15935
- status: external_exports.literal("ready"),
15936
- catalog: harnessModelCatalogSchema,
15937
- permissionModes: harnessPermissionModeCatalogSchema.optional(),
15938
- capabilities: harnessSessionCapabilitiesSchema,
15939
- webUi: harnessWebUiCapabilitySchema.optional()
15940
- }).strict().superRefine((inspection, context) => {
15941
- const selectable = inspection.capabilities.configuration.selectPermissionMode;
15942
- if (selectable !== Boolean(inspection.permissionModes)) {
15943
- context.addIssue({
15944
- code: "custom",
15945
- message: "Permission Mode catalog and capability must agree",
15946
- path: selectable ? ["permissionModes"] : ["capabilities", "configuration", "selectPermissionMode"]
15947
- });
15948
- }
15545
+ var harnessWebUiCapabilitySchema = external_exports.object({
15546
+ open: external_exports.literal(true)
15547
+ }).strict();
15548
+ var readyHarnessInspectionSchema = external_exports.object({
15549
+ status: external_exports.literal("ready"),
15550
+ catalog: harnessModelCatalogSchema,
15551
+ permissionModes: harnessPermissionModeCatalogSchema.optional(),
15552
+ capabilities: harnessSessionCapabilitiesSchema,
15553
+ webUi: harnessWebUiCapabilitySchema.optional()
15554
+ }).strict().superRefine((inspection, context) => {
15555
+ const selectable = inspection.capabilities.configuration.selectPermissionMode;
15556
+ if (selectable !== Boolean(inspection.permissionModes)) {
15557
+ context.addIssue({
15558
+ code: "custom",
15559
+ message: "Permission Mode catalog and capability must agree",
15560
+ path: selectable ? ["permissionModes"] : ["capabilities", "configuration", "selectPermissionMode"]
15561
+ });
15562
+ }
15563
+ });
15564
+ var failedHarnessInspectionSchema = external_exports.object({
15565
+ status: external_exports.enum(["notInstalled", "unavailable", "error"]),
15566
+ error: codexhostErrorSchema
15567
+ }).strict();
15568
+ var harnessInspectionSchema = external_exports.union([
15569
+ readyHarnessInspectionSchema,
15570
+ failedHarnessInspectionSchema
15571
+ ]);
15572
+ var harnessInspectParamsSchema = external_exports.object({
15573
+ harnessId: harnessIdSchema,
15574
+ cwd: nonBlankTextSchema2.max(16384).optional(),
15575
+ refresh: external_exports.boolean().optional(),
15576
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15577
+ purpose: external_exports.literal("availability").optional(),
15578
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
15579
+ }).strict();
15580
+ var harnessWebUiOpenParamsSchema = external_exports.object({
15581
+ harnessId: harnessIdSchema
15582
+ }).strict();
15583
+ var harnessWebUiOpenResultSchema = external_exports.object({}).strict();
15584
+ var threadModelSelectParamsSchema = external_exports.object({
15585
+ threadId: hostThreadIdSchema,
15586
+ model: harnessModelRefSchema
15587
+ }).strict();
15588
+ var threadThinkingSelectParamsSchema = external_exports.object({
15589
+ threadId: hostThreadIdSchema,
15590
+ thinkingOptionId: harnessThinkingOptionIdSchema
15591
+ }).strict();
15592
+ var threadInspectionParamsSchema = external_exports.object({
15593
+ threadId: hostThreadIdSchema,
15594
+ includeReferenceCapability: external_exports.boolean().optional()
15595
+ }).strict();
15596
+ var codexThreadInspectionSchema = external_exports.object({
15597
+ owner: external_exports.literal("codex"),
15598
+ locked: external_exports.boolean(),
15599
+ effectiveModel: harnessModelRefSchema.optional(),
15600
+ resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15601
+ effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15602
+ effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
15603
+ history: harnessHistoryCapabilitiesSchema.optional(),
15604
+ supportsThreadReferences: external_exports.literal(true).optional()
15605
+ }).strict();
15606
+ var externalThreadInspectionSchema = external_exports.object({
15607
+ owner: external_exports.literal("external"),
15608
+ harnessId: nonBlankTextSchema2.max(256),
15609
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
15610
+ effectiveModel: harnessModelRefSchema.optional(),
15611
+ resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15612
+ effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15613
+ availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15614
+ effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
15615
+ history: harnessHistoryCapabilitiesSchema,
15616
+ usage: threadUsageSnapshotSchema.optional(),
15617
+ locked: external_exports.literal(true)
15618
+ }).strict();
15619
+ var threadInspectionSchema = external_exports.discriminatedUnion("owner", [
15620
+ codexThreadInspectionSchema,
15621
+ externalThreadInspectionSchema
15622
+ ]);
15623
+ var threadOwnershipListParamsSchema = external_exports.object({
15624
+ threadIds: external_exports.array(hostThreadIdSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
15625
+ }).strict().superRefine(({ threadIds }, context) => {
15626
+ const seen = /* @__PURE__ */ new Set();
15627
+ for (const [index, threadId] of threadIds.entries()) {
15628
+ if (seen.has(threadId)) {
15629
+ context.addIssue({
15630
+ code: "custom",
15631
+ message: "Thread ownership-list IDs must be unique",
15632
+ path: ["threadIds", index]
15633
+ });
15634
+ }
15635
+ seen.add(threadId);
15636
+ }
15637
+ });
15638
+ var codexThreadOwnershipSchema = external_exports.object({
15639
+ threadId: hostThreadIdSchema,
15640
+ owner: external_exports.literal("codex")
15641
+ }).strict();
15642
+ var externalThreadOwnershipSchema = external_exports.object({
15643
+ threadId: hostThreadIdSchema,
15644
+ owner: external_exports.literal("external"),
15645
+ harnessId: external_exports.string().max(256).pipe(harnessIdSchema)
15646
+ }).strict();
15647
+ var threadOwnershipSchema = external_exports.discriminatedUnion("owner", [
15648
+ codexThreadOwnershipSchema,
15649
+ externalThreadOwnershipSchema
15650
+ ]);
15651
+ var threadOwnershipListResultSchema = external_exports.object({
15652
+ threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
15653
+ }).strict().superRefine(({ threads }, context) => {
15654
+ const seen = /* @__PURE__ */ new Set();
15655
+ for (const [index, thread2] of threads.entries()) {
15656
+ if (seen.has(thread2.threadId)) {
15657
+ context.addIssue({
15658
+ code: "custom",
15659
+ message: "Thread ownership-list results must be unique",
15660
+ path: ["threads", index, "threadId"]
15661
+ });
15662
+ }
15663
+ seen.add(thread2.threadId);
15664
+ }
15665
+ });
15666
+ var threadSteeringInspectParamsSchema = external_exports.object({
15667
+ threadId: hostThreadIdSchema,
15668
+ /** The text about to be steered; a Harness command always stops and restarts. */
15669
+ text: external_exports.string().optional()
15670
+ }).strict();
15671
+ var threadSteeringContextSchema = external_exports.object({
15672
+ kind: external_exports.literal("application"),
15673
+ value: external_exports.string().transform((text, context) => {
15674
+ try {
15675
+ return JSON.parse(text);
15676
+ } catch {
15677
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15678
+ return external_exports.NEVER;
15679
+ }
15680
+ }).pipe(external_exports.object({
15681
+ expectedTurnId: hostTurnIdSchema,
15682
+ clientUserMessageId: external_exports.string().min(1),
15683
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15684
+ }).strict())
15685
+ }).strict().transform((context) => context.value);
15686
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15687
+ var threadSteeringInspectResultSchema = external_exports.object({
15688
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15689
+ }).strict();
15690
+
15691
+ // ../../shared-contracts/dist/harness-plugins.js
15692
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15693
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15694
+ var HARNESS_PLUGIN_LIMIT = 128;
15695
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
15696
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
15697
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id2) => id2 !== "codex", "The official Codex identity is reserved");
15698
+ 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");
15699
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15700
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15701
+ var harnessInstallationGuideSchema = external_exports.object({
15702
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15703
+ before: localizedTextSchema.optional(),
15704
+ after: localizedTextSchema.optional(),
15705
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15706
+ }).strict();
15707
+ var pluginPresentationShape = {
15708
+ id: installedHarnessPluginIdSchema,
15709
+ name: external_exports.string().trim().min(1).max(128),
15710
+ version: external_exports.string().min(1).max(128),
15711
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15712
+ kind: external_exports.literal("usage").optional(),
15713
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15714
+ iconStyle: external_exports.object({
15715
+ vector: external_exports.object({
15716
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15717
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15718
+ paths: external_exports.array(external_exports.object({
15719
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15720
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15721
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15722
+ }).strict()).min(1).max(32)
15723
+ }).strict().optional(),
15724
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15725
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15726
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15727
+ }).strict().optional(),
15728
+ installation: harnessInstallationGuideSchema.optional(),
15729
+ notice: localizedTextSchema.optional(),
15730
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15731
+ launchCommand: external_exports.literal(true).optional(),
15732
+ links: external_exports.object({
15733
+ website: documentationUrlSchema.optional(),
15734
+ documentation: documentationUrlSchema.optional(),
15735
+ installation: documentationUrlSchema.optional()
15736
+ }).strict().optional()
15737
+ };
15738
+ var harnessPluginManifestSchema = external_exports.object({
15739
+ manifestVersion: external_exports.literal(1),
15740
+ ...pluginPresentationShape,
15741
+ adapterApiVersion: external_exports.number().int().positive(),
15742
+ entry: pluginRelativeResourceSchema,
15743
+ icon: pluginRelativeResourceSchema.optional()
15744
+ }).strict();
15745
+ 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);
15746
+ var harnessPluginDescriptorSchema = external_exports.object({
15747
+ ...pluginPresentationShape,
15748
+ icon: harnessPluginIconSchema.optional()
15749
+ }).strict();
15750
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15751
+ var harnessPluginListResultSchema = external_exports.object({
15752
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15753
+ }).strict();
15754
+ var harnessPluginConfigurationSchema = external_exports.object({
15755
+ version: external_exports.literal(1),
15756
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15757
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15758
+ message: "Enabled plugin IDs must be unique",
15759
+ path: ["enabled"]
15760
+ });
15761
+
15762
+ // ../../shared-contracts/dist/desktop-extensions.js
15763
+ var DESKTOP_EXTENSION_API_VERSION = 1;
15764
+ var DESKTOP_EXTENSION_LIMIT = 64;
15765
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15766
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15767
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15768
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15769
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15770
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15771
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15772
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15773
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15774
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15775
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15776
+ var desktopExtensionIdSchema = installedPluginIdSchema;
15777
+ var desktopExtensionSlotSchema = external_exports.enum([
15778
+ "sidebar.thread-layout",
15779
+ "sidebar.thread-badge",
15780
+ "appearance.theme"
15781
+ ]);
15782
+ var desktopExtensionCategorySchema = external_exports.enum([
15783
+ "appearance",
15784
+ "interface",
15785
+ "workflow",
15786
+ "analytics",
15787
+ "integrations",
15788
+ "tools"
15789
+ ]);
15790
+ var extensionName = external_exports.string().trim().min(1).max(128);
15791
+ function desktopExtensionScreenshotMimeType(resource) {
15792
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15793
+ case "png":
15794
+ return "image/png";
15795
+ case "jpg":
15796
+ case "jpeg":
15797
+ return "image/jpeg";
15798
+ case "webp":
15799
+ return "image/webp";
15800
+ default:
15801
+ return void 0;
15802
+ }
15803
+ }
15804
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15805
+ 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");
15806
+ 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) => {
15807
+ const { username, password } = new URL(value);
15808
+ return !username && !password && !/[\\\s]/u.test(value);
15809
+ }, "URL must not contain credentials, backslashes, or whitespace");
15810
+ function localizedText(text) {
15811
+ return external_exports.strictObject({ en: text, "zh-CN": text });
15812
+ }
15813
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15814
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15815
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15816
+ var settingField = {
15817
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15818
+ label: desktopExtensionLocalizedTextSchema,
15819
+ description: desktopExtensionLocalizedTextSchema.optional()
15820
+ };
15821
+ var numericSetting = {
15822
+ ...settingField,
15823
+ step: external_exports.number().positive().optional(),
15824
+ default: external_exports.number().optional()
15825
+ };
15826
+ var settingOption = external_exports.strictObject({
15827
+ value: external_exports.string(),
15828
+ label: desktopExtensionLocalizedTextSchema
15829
+ });
15830
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15831
+ external_exports.strictObject({
15832
+ ...settingField,
15833
+ type: external_exports.literal("boolean"),
15834
+ default: external_exports.boolean().optional()
15835
+ }),
15836
+ external_exports.strictObject({
15837
+ ...settingField,
15838
+ type: external_exports.literal("string"),
15839
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
15840
+ default: external_exports.string().optional()
15841
+ }),
15842
+ external_exports.strictObject({
15843
+ ...numericSetting,
15844
+ type: external_exports.literal("number"),
15845
+ min: external_exports.number().optional(),
15846
+ max: external_exports.number().optional()
15847
+ }),
15848
+ external_exports.strictObject({
15849
+ ...numericSetting,
15850
+ type: external_exports.literal("range"),
15851
+ min: external_exports.number(),
15852
+ max: external_exports.number()
15853
+ }),
15854
+ external_exports.strictObject({
15855
+ ...settingField,
15856
+ type: external_exports.literal("select"),
15857
+ options: external_exports.array(settingOption).min(1),
15858
+ default: external_exports.string().optional()
15859
+ })
15860
+ ]).superRefine((field2, ctx) => {
15861
+ const issue2 = (path14, message) => ctx.addIssue({ code: "custom", path: [path14], message });
15862
+ if (field2.type === "number" || field2.type === "range") {
15863
+ const { min = -Infinity, max = Infinity, default: value } = field2;
15864
+ if (min > max)
15865
+ issue2("max", "Must be at least min");
15866
+ if (value !== void 0 && (value < min || value > max))
15867
+ issue2("default", "Must be within min and max");
15868
+ } else if (field2.type === "select") {
15869
+ const values = new Set(field2.options.map(({ value }) => value));
15870
+ if (values.size !== field2.options.length)
15871
+ issue2("options", "Duplicate option values");
15872
+ if (field2.default !== void 0 && !values.has(field2.default))
15873
+ issue2("default", "Must match an option value");
15874
+ }
15875
+ });
15876
+ var manifestHeader = external_exports.object({
15877
+ manifestVersion: external_exports.int().positive(),
15878
+ id: desktopExtensionIdSchema,
15879
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
15880
+ version: external_exports.string().min(1).max(128),
15881
+ desktopApi: external_exports.int().positive()
15882
+ }).passthrough();
15883
+ var desktopExtensionManifestSchema = manifestHeader.extend({
15884
+ manifestVersion: external_exports.literal(1),
15885
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15886
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15887
+ author: external_exports.string().trim().min(1).max(128).optional(),
15888
+ repository: desktopExtensionHttpUrlSchema.optional(),
15889
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15890
+ icon: imagePathSchema.optional(),
15891
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15892
+ desktop: external_exports.strictObject({
15893
+ script: pluginRelativeResourceSchema,
15894
+ style: pluginRelativeResourceSchema.optional()
15895
+ }).optional(),
15896
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15897
+ slots: slotsSchema.default(() => []),
15898
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15899
+ categories: categoriesSchema.optional()
15900
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15901
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15902
+ var desktopExtensionStatusSchema = external_exports.strictObject({
15903
+ state: external_exports.enum([
15904
+ "running",
15905
+ "disabled",
15906
+ "invalid",
15907
+ "incompatible",
15908
+ "conflict",
15909
+ "failed",
15910
+ "waiting"
15911
+ ]),
15912
+ hash: desktopExtensionHashSchema.optional(),
15913
+ error: external_exports.string().optional(),
15914
+ conflictWith: desktopExtensionIdSchema.optional()
15915
+ });
15916
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15917
+ controllerPid: external_exports.int().positive(),
15918
+ targetId: external_exports.string().nullable(),
15919
+ updatedAt: external_exports.iso.datetime(),
15920
+ handledReloadToken: external_exports.uuid().optional(),
15921
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema),
15922
+ surfaces: external_exports.record(external_exports.string(), desktopExtensionStatusSchema).optional()
15923
+ });
15924
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15925
+ function isGitHubDesktopExtensionZipballUrl(url2) {
15926
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15927
+ }
15928
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15929
+ const url2 = new URL(input);
15930
+ 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);
15931
+ }, "Expected a .zip download URL or a GitHub zipball URL");
15932
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15933
+ id: desktopExtensionIdSchema,
15934
+ version: external_exports.string().trim().min(1).max(128),
15935
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15936
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
15937
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15938
+ author: external_exports.string().trim().min(1).max(128),
15939
+ repository: desktopExtensionHttpUrlSchema,
15940
+ stars: external_exports.number().int().min(0).optional(),
15941
+ downloads: external_exports.number().int().min(0).optional(),
15942
+ categories: categoriesSchema.optional(),
15943
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
15944
+ icon: desktopExtensionHttpUrlSchema.optional(),
15945
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15946
+ downloadUrl: desktopExtensionZipUrlSchema,
15947
+ sha256: desktopExtensionHashSchema,
15948
+ slots: slotsSchema.optional(),
15949
+ publishedAt: external_exports.string().optional(),
15950
+ updatedAt: external_exports.string().optional(),
15951
+ minCodexHostVersion: external_exports.string().optional()
15952
+ });
15953
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
15954
+ schemaVersion: external_exports.literal(1),
15955
+ generatedAt: external_exports.string(),
15956
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15949
15957
  });
15950
- var failedHarnessInspectionSchema = external_exports.object({
15951
- status: external_exports.enum(["notInstalled", "unavailable", "error"]),
15952
- error: codexhostErrorSchema
15953
- }).strict();
15954
- var harnessInspectionSchema = external_exports.union([
15955
- readyHarnessInspectionSchema,
15956
- failedHarnessInspectionSchema
15958
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15959
+
15960
+ // ../../shared-contracts/dist/host-extensions.js
15961
+ var reservedName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu;
15962
+ var HOST_EXTENSION_PAGE_API_VERSION = 1;
15963
+ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedName.test(id2), "Reserved extension ID");
15964
+ var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
15965
+ var hostExtensionDigestSchema = desktopExtensionHashSchema;
15966
+ var hostExtensionActivationIdSchema = external_exports.uuid();
15967
+ 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((path14) => path14.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
15968
+ var legacy = desktopExtensionManifestSchema.shape;
15969
+ var localized = (max, min = 0) => external_exports.strictObject({
15970
+ en: external_exports.string().trim().min(min).max(max),
15971
+ "zh-CN": external_exports.string().trim().min(min).max(max)
15972
+ });
15973
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path14) => path14.endsWith(suffix), `Expected a ${suffix} file`);
15974
+ var moduleEntry = resourceWithSuffix(".mjs");
15975
+ var style = resourceWithSuffix(".css").optional();
15976
+ var hostExtensionCanonicalPath = (path14) => path14.normalize("NFC").toLowerCase();
15977
+ var hostExtensionManifestV2Schema = external_exports.strictObject({
15978
+ manifestVersion: external_exports.literal(2),
15979
+ id: hostExtensionIdSchema,
15980
+ name: localized(128, 1),
15981
+ version: external_exports.string().trim().min(1).max(128),
15982
+ description: localized(4096),
15983
+ details: localized(16384).optional(),
15984
+ author: legacy.author,
15985
+ repository: legacy.repository,
15986
+ icon: legacy.icon.refine((path14) => path14 === void 0 || hostExtensionResourcePathSchema.safeParse(path14).success),
15987
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path14) => hostExtensionResourcePathSchema.safeParse(path14).success)),
15988
+ categories: legacy.categories,
15989
+ settingsSchema: legacy.settingsSchema,
15990
+ slots: legacy.slots.removeDefault().optional(),
15991
+ page: external_exports.strictObject({
15992
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15993
+ entry: moduleEntry,
15994
+ style,
15995
+ title: localized(128, 1).optional()
15996
+ }).optional(),
15997
+ widget: external_exports.strictObject({
15998
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15999
+ entry: moduleEntry,
16000
+ style
16001
+ }).optional(),
16002
+ desktop: external_exports.strictObject({ apiVersion: external_exports.literal(1), script: resourceWithSuffix(".js"), style }).optional(),
16003
+ 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(),
16004
+ backend: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry }).optional()
16005
+ }).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" });
16006
+ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBackend }) {
16007
+ if (hasPage || hasWidget || hasBackend && !hasDesktop && !hasWeb)
16008
+ return ["desktop", "web"];
16009
+ const targets = [];
16010
+ if (hasDesktop)
16011
+ targets.push("desktop");
16012
+ if (hasWeb)
16013
+ targets.push("web");
16014
+ return targets;
16015
+ }
16016
+ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
16017
+
16018
+ // ../../shared-contracts/dist/host-extension-management.js
16019
+ var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
16020
+ var hostExtensionRevisionSchema = external_exports.int().nonnegative();
16021
+ var hostExtensionConfigurationSchema = external_exports.strictObject({
16022
+ revision: hostExtensionRevisionSchema,
16023
+ enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
16024
+ });
16025
+ var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
16026
+ var hostExtensionCatalogEntrySchema = external_exports.object({
16027
+ ...catalogMetadata,
16028
+ id: hostExtensionIdSchema,
16029
+ format: external_exports.literal("codexhost"),
16030
+ targets: external_exports.array(hostExtensionTargetSchema).min(1).max(2).refine((targets) => new Set(targets).size === targets.length, "Duplicate targets"),
16031
+ apis: external_exports.strictObject({
16032
+ page: external_exports.int().positive().optional(),
16033
+ widget: external_exports.int().positive().optional(),
16034
+ desktop: external_exports.int().positive().optional(),
16035
+ web: external_exports.int().positive().optional(),
16036
+ backend: external_exports.int().positive().optional()
16037
+ }),
16038
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
16039
+ }).refine(({ targets, apis }) => {
16040
+ const derived = targetsForCapabilities({
16041
+ hasPage: Boolean(apis.page),
16042
+ hasWidget: Boolean(apis.widget),
16043
+ hasDesktop: Boolean(apis.desktop),
16044
+ hasWeb: Boolean(apis.web),
16045
+ hasBackend: Boolean(apis.backend)
16046
+ });
16047
+ return targets.length === derived.length && derived.every((target2) => targets.includes(target2));
16048
+ }, "Catalog targets must match the declared APIs");
16049
+ var hostExtensionCatalogSchema = external_exports.object({
16050
+ schemaVersion: external_exports.literal(2),
16051
+ generatedAt: external_exports.string().min(1),
16052
+ extensions: external_exports.array(hostExtensionCatalogEntrySchema).max(1e4).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
16053
+ });
16054
+ var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
16055
+ catalogUrl: desktopExtensionHttpUrlSchema,
16056
+ fetchedAt: external_exports.iso.datetime(),
16057
+ cached: external_exports.boolean()
16058
+ });
16059
+ var id = { id: hostExtensionIdSchema };
16060
+ var active = {
16061
+ ...id,
16062
+ activationId: hostExtensionActivationIdSchema,
16063
+ digest: hostExtensionDigestSchema
16064
+ };
16065
+ var optionalActivation = { ...id, activationId: active.activationId.optional() };
16066
+ var filePath = external_exports.string().min(1).max(4096).refine((path14) => /^(?:\/|[a-z]:[/\\])/iu.test(path14) && !path14.includes("\0") && !path14.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
16067
+ 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");
16068
+ function base643(maxBytes) {
16069
+ return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
16070
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
16071
+ return value.length % 4 === 0 && value.length * 3 / 4 - padding <= maxBytes && /^[A-Za-z0-9+/]*={0,2}$/u.test(value);
16072
+ }, "Expected bounded standard padded base64");
16073
+ }
16074
+ var hostExtensionGitHubSourceSchema = external_exports.strictObject({
16075
+ type: external_exports.literal("github"),
16076
+ repository: external_exports.string().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),
16077
+ ref: gitRef.optional(),
16078
+ tag: gitRef.optional(),
16079
+ asset: external_exports.string().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),
16080
+ subpath: hostExtensionResourcePathSchema.optional()
16081
+ }).refine(({ ref, tag, asset }) => !ref || !tag && !asset, "Use either a zipball ref or a release tag/asset");
16082
+ var hostExtensionInstallSourceSchema = external_exports.union([
16083
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
16084
+ hostExtensionGitHubSourceSchema,
16085
+ external_exports.strictObject({ type: external_exports.literal("zip"), base64: base643(HOST_EXTENSION_ZIP_MAX_BYTES).min(4) }),
16086
+ external_exports.strictObject({ type: external_exports.literal("zip"), localZipPath: filePath }),
16087
+ external_exports.strictObject({ type: external_exports.literal("localDir"), localDir: filePath })
15957
16088
  ]);
15958
- var harnessInspectParamsSchema = external_exports.object({
15959
- harnessId: harnessIdSchema,
15960
- cwd: nonBlankTextSchema2.max(16384).optional(),
15961
- refresh: external_exports.boolean().optional(),
15962
- /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15963
- purpose: external_exports.literal("availability").optional()
15964
- }).strict();
15965
- var harnessWebUiOpenParamsSchema = external_exports.object({
15966
- harnessId: harnessIdSchema
15967
- }).strict();
15968
- var harnessWebUiOpenResultSchema = external_exports.object({}).strict();
15969
- var threadModelSelectParamsSchema = external_exports.object({
15970
- threadId: hostThreadIdSchema,
15971
- model: harnessModelRefSchema
15972
- }).strict();
15973
- var threadThinkingSelectParamsSchema = external_exports.object({
15974
- threadId: hostThreadIdSchema,
15975
- thinkingOptionId: harnessThinkingOptionIdSchema
15976
- }).strict();
15977
- var threadInspectionParamsSchema = external_exports.object({
15978
- threadId: hostThreadIdSchema,
15979
- includeReferenceCapability: external_exports.boolean().optional()
15980
- }).strict();
15981
- var codexThreadInspectionSchema = external_exports.object({
15982
- owner: external_exports.literal("codex"),
15983
- locked: external_exports.boolean(),
15984
- effectiveModel: harnessModelRefSchema.optional(),
15985
- resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15986
- effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15987
- effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
15988
- history: harnessHistoryCapabilitiesSchema.optional(),
15989
- supportsThreadReferences: external_exports.literal(true).optional()
15990
- }).strict();
15991
- var externalThreadInspectionSchema = external_exports.object({
15992
- owner: external_exports.literal("external"),
15993
- harnessId: nonBlankTextSchema2.max(256),
15994
- transportModelId: nonBlankTextSchema2.max(1024),
15995
- effectiveModel: harnessModelRefSchema.optional(),
15996
- resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15997
- effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15998
- availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15999
- effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
16000
- history: harnessHistoryCapabilitiesSchema,
16001
- usage: threadUsageSnapshotSchema.optional(),
16002
- locked: external_exports.literal(true)
16003
- }).strict();
16004
- var threadInspectionSchema = external_exports.discriminatedUnion("owner", [
16005
- codexThreadInspectionSchema,
16006
- externalThreadInspectionSchema
16089
+ var hostExtensionProvenanceSchema = external_exports.discriminatedUnion("type", [
16090
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
16091
+ hostExtensionGitHubSourceSchema,
16092
+ external_exports.strictObject({ type: external_exports.literal("zip") }),
16093
+ external_exports.strictObject({ type: external_exports.literal("localDir") })
16007
16094
  ]);
16008
- var threadOwnershipListParamsSchema = external_exports.object({
16009
- threadIds: external_exports.array(hostThreadIdSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
16010
- }).strict().superRefine(({ threadIds }, context) => {
16011
- const seen = /* @__PURE__ */ new Set();
16012
- for (const [index, threadId] of threadIds.entries()) {
16013
- if (seen.has(threadId)) {
16014
- context.addIssue({
16015
- code: "custom",
16016
- message: "Thread ownership-list IDs must be unique",
16017
- path: ["threadIds", index]
16018
- });
16019
- }
16020
- seen.add(threadId);
16021
- }
16095
+ var hostExtensionInstallationSchema = external_exports.strictObject({
16096
+ ...active,
16097
+ manifest: hostExtensionManifestV2Schema,
16098
+ installedAt: external_exports.iso.datetime(),
16099
+ source: hostExtensionProvenanceSchema.optional()
16022
16100
  });
16023
- var codexThreadOwnershipSchema = external_exports.object({
16024
- threadId: hostThreadIdSchema,
16025
- owner: external_exports.literal("codex")
16026
- }).strict();
16027
- var externalThreadOwnershipSchema = external_exports.object({
16028
- threadId: hostThreadIdSchema,
16029
- owner: external_exports.literal("external"),
16030
- harnessId: external_exports.string().max(256).pipe(harnessIdSchema)
16031
- }).strict();
16032
- var threadOwnershipSchema = external_exports.discriminatedUnion("owner", [
16033
- codexThreadOwnershipSchema,
16034
- externalThreadOwnershipSchema
16101
+ 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);
16102
+ var desktopConflict = { desktopConflictWith: hostExtensionIdSchema.optional() };
16103
+ var backendState = external_exports.enum(["none", "inactive", "starting", "running", "failed"]);
16104
+ var hostExtensionListItemSchema = external_exports.discriminatedUnion("state", [
16105
+ hostExtensionInstallationSchema.extend({
16106
+ state: external_exports.literal("valid"),
16107
+ enabled: external_exports.boolean(),
16108
+ ...desktopConflict,
16109
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
16110
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
16111
+ backendState: backendState.optional(),
16112
+ backendError: external_exports.string().optional()
16113
+ }),
16114
+ external_exports.strictObject({
16115
+ state: external_exports.enum(["invalid", "incompatible"]),
16116
+ id: external_exports.string().min(1),
16117
+ enabled: external_exports.boolean(),
16118
+ error: external_exports.string()
16119
+ })
16035
16120
  ]);
16036
- var threadOwnershipListResultSchema = external_exports.object({
16037
- threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
16038
- }).strict().superRefine(({ threads }, context) => {
16039
- const seen = /* @__PURE__ */ new Set();
16040
- for (const [index, thread2] of threads.entries()) {
16041
- if (seen.has(thread2.threadId)) {
16042
- context.addIssue({
16043
- code: "custom",
16044
- message: "Thread ownership-list results must be unique",
16045
- path: ["threads", index, "threadId"]
16046
- });
16047
- }
16048
- seen.add(thread2.threadId);
16049
- }
16121
+ var hostExtensionsListResultSchema = external_exports.strictObject({
16122
+ revision: hostExtensionRevisionSchema,
16123
+ configuration: hostExtensionConfigurationSchema,
16124
+ diagnostics: external_exports.array(external_exports.string()),
16125
+ extensions: external_exports.array(hostExtensionListItemSchema)
16126
+ });
16127
+ var hostExtensionRuntimeEntrySchema = hostExtensionInstallationSchema.extend({
16128
+ ...desktopConflict,
16129
+ settingsRevision: hostExtensionRevisionSchema
16130
+ });
16131
+ var hostExtensionsSnapshotResultSchema = external_exports.strictObject({
16132
+ /** The Host publishes this revision in extensions-changed, independent of enabled.json's revision. */
16133
+ revision: hostExtensionRevisionSchema,
16134
+ // Enabled, valid activations only. A Desktop conflict does not hide other capabilities.
16135
+ extensions: external_exports.array(hostExtensionRuntimeEntrySchema).max(DESKTOP_EXTENSION_LIMIT)
16136
+ });
16137
+ var HOST_EXTENSIONS_RPC = {
16138
+ list: "codexhost/extensions/list",
16139
+ snapshot: "codexhost/extensions/snapshot",
16140
+ catalog: "codexhost/extensions/catalog",
16141
+ install: "codexhost/extensions/install",
16142
+ update: "codexhost/extensions/update",
16143
+ enable: "codexhost/extensions/enable",
16144
+ disable: "codexhost/extensions/disable",
16145
+ uninstall: "codexhost/extensions/uninstall",
16146
+ recover: "codexhost/extensions/recover",
16147
+ asset: "codexhost/extensions/asset",
16148
+ settingsGet: "codexhost/extensions/settings/get",
16149
+ settingsSet: "codexhost/extensions/settings/set",
16150
+ backendInvoke: "codexhost/extensions/backend/invoke"
16151
+ };
16152
+ var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
16153
+ var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
16154
+ var noParams = external_exports.strictObject({});
16155
+ var expectedRevision = { expectedRevision: hostExtensionRevisionSchema };
16156
+ var selection = external_exports.strictObject({ ...id, ...expectedRevision });
16157
+ var installationResult = hostExtensionInstallationSchema.extend({ replaced: external_exports.boolean() });
16158
+ var mutationResult = external_exports.discriminatedUnion("state", [
16159
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: hostExtensionConfigurationSchema }),
16160
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: hostExtensionRevisionSchema })
16161
+ ]);
16162
+ var hostExtensionsAssetParamsSchema = external_exports.strictObject({
16163
+ ...optionalActivation,
16164
+ digest: active.digest.optional(),
16165
+ path: hostExtensionResourcePathSchema
16166
+ });
16167
+ var hostExtensionsAssetResultSchema = external_exports.strictObject({
16168
+ mimeType: external_exports.string().min(1),
16169
+ base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
16170
+ digest: active.digest
16171
+ });
16172
+ var hostExtensionSettingsSchema = external_exports.strictObject({
16173
+ settingsRevision: hostExtensionRevisionSchema,
16174
+ values: jsonObjectSchema
16050
16175
  });
16051
- var threadSteeringInspectParamsSchema = external_exports.object({
16052
- threadId: hostThreadIdSchema,
16053
- /** The text about to be steered; a Harness command always stops and restarts. */
16054
- text: external_exports.string().optional()
16055
- }).strict();
16056
- var threadSteeringContextSchema = external_exports.object({
16057
- kind: external_exports.literal("application"),
16058
- value: external_exports.string().transform((text, context) => {
16059
- try {
16060
- return JSON.parse(text);
16061
- } catch {
16062
- context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
16063
- return external_exports.NEVER;
16064
- }
16065
- }).pipe(external_exports.object({
16066
- expectedTurnId: hostTurnIdSchema,
16067
- clientUserMessageId: external_exports.string().min(1),
16068
- delivery: external_exports.enum(["newTurn", "activeTurn"])
16069
- }).strict())
16070
- }).strict().transform((context) => context.value);
16071
- var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
16072
- var threadSteeringInspectResultSchema = external_exports.object({
16073
- delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
16074
- }).strict();
16176
+ var hostExtensionsRpcSchemas = {
16177
+ [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
16178
+ [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
16179
+ [HOST_EXTENSIONS_RPC.catalog]: {
16180
+ params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
16181
+ result: hostExtensionsCatalogResultSchema
16182
+ },
16183
+ [HOST_EXTENSIONS_RPC.install]: {
16184
+ params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
16185
+ result: installationResult
16186
+ },
16187
+ [HOST_EXTENSIONS_RPC.update]: {
16188
+ params: external_exports.strictObject({
16189
+ ...id,
16190
+ expectedDigest: active.digest,
16191
+ expectedActivationId: active.activationId.optional(),
16192
+ source: hostExtensionInstallSourceSchema.optional()
16193
+ }),
16194
+ result: installationResult
16195
+ },
16196
+ [HOST_EXTENSIONS_RPC.enable]: { params: selection, result: mutationResult },
16197
+ [HOST_EXTENSIONS_RPC.disable]: { params: selection, result: mutationResult },
16198
+ [HOST_EXTENSIONS_RPC.uninstall]: {
16199
+ params: external_exports.strictObject({
16200
+ ...id,
16201
+ removeData: external_exports.boolean().optional(),
16202
+ expectedDigest: active.digest.optional()
16203
+ }),
16204
+ result: external_exports.strictObject({ ...id, removed: external_exports.boolean() })
16205
+ },
16206
+ [HOST_EXTENSIONS_RPC.recover]: {
16207
+ params: external_exports.strictObject({ expectedRevision: expectedRevision.expectedRevision.optional() }),
16208
+ result: mutationResult
16209
+ },
16210
+ [HOST_EXTENSIONS_RPC.asset]: {
16211
+ params: hostExtensionsAssetParamsSchema,
16212
+ result: hostExtensionsAssetResultSchema
16213
+ },
16214
+ [HOST_EXTENSIONS_RPC.settingsGet]: {
16215
+ params: external_exports.strictObject(optionalActivation),
16216
+ result: hostExtensionSettingsSchema
16217
+ },
16218
+ [HOST_EXTENSIONS_RPC.settingsSet]: {
16219
+ params: external_exports.strictObject({
16220
+ ...optionalActivation,
16221
+ expectedSettingsRevision: hostExtensionRevisionSchema,
16222
+ values: jsonObjectSchema
16223
+ }),
16224
+ result: hostExtensionSettingsSchema
16225
+ },
16226
+ [HOST_EXTENSIONS_RPC.backendInvoke]: {
16227
+ params: external_exports.strictObject({
16228
+ ...optionalActivation,
16229
+ method: hostExtensionBackendMethodSchema,
16230
+ params: jsonValueSchema.optional()
16231
+ }),
16232
+ result: external_exports.strictObject({ result: jsonValueSchema })
16233
+ }
16234
+ };
16075
16235
 
16076
16236
  // ../../shared-contracts/dist/thread-archive-confirm.js
16077
16237
  var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
@@ -16134,7 +16294,7 @@ var CLIENT_CHANNEL_METHODS = [
16134
16294
  "codexhost/harness/session-import/list",
16135
16295
  "codexhost/harness/session-import/import",
16136
16296
  // Host settings shared across Desktop and Web.
16137
- ...DESKTOP_EXTENSION_MANAGEMENT_METHODS,
16297
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
16138
16298
  "codexhost/harness/installation",
16139
16299
  "codexhost/harness/installation/start",
16140
16300
  "codexhost/harness/installation/status",
@@ -16195,6 +16355,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
16195
16355
  cursor: clientChannelCursorSchema,
16196
16356
  revision: external_exports.number().int().nonnegative()
16197
16357
  }),
16358
+ external_exports.object({
16359
+ type: external_exports.literal("extensions-changed"),
16360
+ cursor: clientChannelCursorSchema,
16361
+ revision: hostExtensionRevisionSchema
16362
+ }),
16198
16363
  external_exports.object({
16199
16364
  type: external_exports.literal("hello"),
16200
16365
  version: external_exports.literal(1),
@@ -16631,7 +16796,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
16631
16796
 
16632
16797
  // ../../shared-contracts/dist/harness-preferences.js
16633
16798
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
16634
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
16799
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
16635
16800
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
16636
16801
  model: harnessModelRefSchema.optional(),
16637
16802
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -16641,11 +16806,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
16641
16806
  lastHarness: harnessIdSchema.optional(),
16642
16807
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
16643
16808
  });
16809
+ var harnessDelegationDefaultSchema = external_exports.strictObject({
16810
+ model: harnessModelRefSchema.optional(),
16811
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional()
16812
+ }).refine((value) => Boolean(value.model || value.thinkingOptionId), "A delegation default must contain a Model or Thinking option");
16813
+ var delegationDefaultsSchema = external_exports.strictObject({
16814
+ byHarness: external_exports.record(preferenceHarnessKey, harnessDelegationDefaultSchema)
16815
+ });
16644
16816
  var modelId = external_exports.string().min(1).max(1024);
16645
16817
  var harnessPreferenceValuesSchema = external_exports.strictObject({
16646
16818
  idleRelease: idleReleaseSettingsSchema.optional(),
16647
16819
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
16648
- newThread: newThreadDefaultsSchema.optional()
16820
+ newThread: newThreadDefaultsSchema.optional(),
16821
+ delegation: delegationDefaultsSchema.optional()
16649
16822
  });
16650
16823
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
16651
16824
  scope: harnessPreferenceScopeSchema,
@@ -16673,6 +16846,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
16673
16846
  lastHarness: harnessIdSchema.optional(),
16674
16847
  harnessId: harnessIdSchema.optional(),
16675
16848
  configuration: harnessDefaultConfigurationSchema.optional()
16849
+ }),
16850
+ external_exports.strictObject({
16851
+ kind: external_exports.literal("delegation"),
16852
+ harnessId: harnessIdSchema,
16853
+ configuration: harnessDelegationDefaultSchema.nullable()
16676
16854
  })
16677
16855
  ]);
16678
16856
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -17496,9 +17674,12 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17496
17674
  ...thread,
17497
17675
  epoch: identity,
17498
17676
  modelId: identity.optional(),
17677
+ serviceTier: harnessModelServiceTierSchema.optional(),
17499
17678
  thinkingOptionId: identity.optional(),
17500
17679
  permissionModeId: identity.optional()
17501
- }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17680
+ }).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, {
17681
+ message: "A service tier requires a Model ID"
17682
+ }),
17502
17683
  external_exports.strictObject({
17503
17684
  kind: external_exports.literal("prompt"),
17504
17685
  ...thread,
@@ -17548,7 +17729,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
17548
17729
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
17549
17730
  external_exports.strictObject({
17550
17731
  action: external_exports.literal("read-thread"),
17551
- hostId: hostId.refine((id) => id !== "local"),
17732
+ hostId: hostId.refine((id2) => id2 !== "local"),
17552
17733
  input: delegationReadParamsSchema
17553
17734
  }),
17554
17735
  external_exports.strictObject({
@@ -17562,7 +17743,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
17562
17743
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
17563
17744
  external_exports.strictObject({
17564
17745
  action: external_exports.literal("update"),
17565
- hostId: hostId.refine((id) => id !== "local"),
17746
+ hostId: hostId.refine((id2) => id2 !== "local"),
17566
17747
  version: remoteUpdateParamsSchema.shape.version
17567
17748
  })
17568
17749
  ]);
@@ -17626,7 +17807,7 @@ function invalidRequest(message) {
17626
17807
  return { code: "invalidRequest", message, retryable: false };
17627
17808
  }
17628
17809
  function validateHostApprovalResponse(interaction, response) {
17629
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17810
+ return interaction.actions.some(({ id: id2 }) => id2 === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17630
17811
  }
17631
17812
 
17632
17813
  // ../../harness-adapter/dist/question.js
@@ -17634,7 +17815,7 @@ function invalidRequest2(message) {
17634
17815
  return { code: "invalidRequest", message, retryable: false };
17635
17816
  }
17636
17817
  function validateHostQuestionResponse(interaction, response) {
17637
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17818
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
17638
17819
  if (response.cancelled) {
17639
17820
  return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17640
17821
  }
@@ -17665,6 +17846,21 @@ function validateHostQuestionResponse(interaction, response) {
17665
17846
  return null;
17666
17847
  }
17667
17848
 
17849
+ // ../../harness-adapter/dist/composite-model-ref.js
17850
+ function compositeModelRefIds(entries, fallbackId) {
17851
+ const counts = /* @__PURE__ */ new Map();
17852
+ for (const entry of entries) {
17853
+ const id2 = `${entry.provider}/${entry.model}`;
17854
+ counts.set(id2, (counts.get(id2) ?? 0) + 1);
17855
+ }
17856
+ const ids = /* @__PURE__ */ new Map();
17857
+ for (const entry of entries) {
17858
+ const id2 = `${entry.provider}/${entry.model}`;
17859
+ ids.set(counts.get(id2) === 1 ? id2 : fallbackId(entry), entry);
17860
+ }
17861
+ return ids;
17862
+ }
17863
+
17668
17864
  // ../../harness-adapter/dist/output-channel.js
17669
17865
  var HarnessOutputChannel = class {
17670
17866
  outputs;
@@ -17749,7 +17945,8 @@ var tokenFields = [
17749
17945
  var safeIntegerFields = [
17750
17946
  "planFiveHourResetsAtUnix",
17751
17947
  "planSevenDayResetsAtUnix",
17752
- "timeToFirstOutputMs"
17948
+ "timeToFirstOutputMs",
17949
+ "latestRequestTimeToFirstOutputMs"
17753
17950
  ];
17754
17951
  var percentFields = [
17755
17952
  "cacheHitRatePercent",
@@ -18062,7 +18259,7 @@ function createOpenCodeUsageStatistics(environment) {
18062
18259
  const stamp = file2 ? await fingerprint(file2) : null;
18063
18260
  return file2 && stamp ? [{ id: file2, fingerprint: stamp }] : [];
18064
18261
  },
18065
- readSource: (id) => readOpenCodeUsage(id)
18262
+ readSource: (id2) => readOpenCodeUsage(id2)
18066
18263
  });
18067
18264
  }
18068
18265
 
@@ -18080,35 +18277,52 @@ function assertNonBlank(value, label) {
18080
18277
  if (!value.trim())
18081
18278
  throw new Error(`OpenCode ${label} must not be empty`);
18082
18279
  }
18083
- function encodeOpenCodeModelRef(model2) {
18280
+ function readableId({ providerID, modelID }) {
18281
+ return `${providerID}/${modelID}`;
18282
+ }
18283
+ function legacyId({ providerID, modelID }) {
18284
+ return MODEL_REF_PREFIX + Buffer2.from(JSON.stringify([providerID, modelID])).toString("base64url");
18285
+ }
18286
+ function openCodeModelIndex(models) {
18287
+ const entries = new Map(models.map((native) => [
18288
+ legacyId(native),
18289
+ {
18290
+ provider: native.providerID,
18291
+ model: native.modelID,
18292
+ native
18293
+ }
18294
+ ]));
18295
+ const ids = compositeModelRefIds([...entries.values()], ({ native }) => legacyId(native));
18296
+ const readable = new Set(models.map(readableId));
18297
+ const byLegacy = /* @__PURE__ */ new Map();
18298
+ for (const [id2, { native }] of ids) {
18299
+ byLegacy.set(legacyId(native), harnessModelRefSchema.parse({ id: id2 }));
18300
+ }
18301
+ const encode3 = (model2) => {
18302
+ assertNonBlank(model2.providerID, "Provider ID");
18303
+ assertNonBlank(model2.modelID, "Model ID");
18304
+ const id2 = readableId(model2);
18305
+ return byLegacy.get(legacyId(model2)) ?? harnessModelRefSchema.parse({
18306
+ id: readable.has(id2) ? legacyId(model2) : id2
18307
+ });
18308
+ };
18309
+ return { encode: encode3, ids, byLegacy };
18310
+ }
18311
+ function encodeOpenCodeModelRef(model2, index) {
18312
+ if (index)
18313
+ return index.encode(model2);
18084
18314
  assertNonBlank(model2.providerID, "Provider ID");
18085
18315
  assertNonBlank(model2.modelID, "Model ID");
18086
- const encoded = Buffer2.from(JSON.stringify([model2.providerID, model2.modelID]), "utf8").toString("base64url");
18087
- const id = `${MODEL_REF_PREFIX}${encoded}`;
18088
- if (id.length > HARNESS_MODEL_REF_MAX_LENGTH) {
18089
- throw new Error("OpenCode Model identity is too long for a Model Ref");
18090
- }
18091
- return harnessModelRefSchema.parse({ id });
18316
+ return harnessModelRefSchema.parse({ id: readableId(model2) });
18092
18317
  }
18093
- function decodeOpenCodeModelRef(ref) {
18094
- const parsed = harnessModelRefSchema.parse(ref);
18095
- if (!parsed.id.startsWith(MODEL_REF_PREFIX)) {
18096
- throw new Error("OpenCode Model Ref belongs to another Adapter");
18097
- }
18098
- let decoded;
18099
- try {
18100
- decoded = JSON.parse(Buffer2.from(parsed.id.slice(MODEL_REF_PREFIX.length), "base64url").toString("utf8"));
18101
- } catch {
18102
- throw new Error("OpenCode Model Ref is malformed");
18103
- }
18104
- if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
18105
- throw new Error("OpenCode Model Ref has an invalid native identity");
18106
- }
18107
- const native = { providerID: decoded[0], modelID: decoded[1] };
18108
- if (encodeOpenCodeModelRef(native).id !== parsed.id) {
18109
- throw new Error("OpenCode Model Ref is not canonical");
18110
- }
18111
- return native;
18318
+ function decodeOpenCodeModelRef(ref, index) {
18319
+ const model2 = !ref.serviceTier && index.ids.get(ref.id)?.native;
18320
+ if (!model2)
18321
+ throw new Error("OpenCode Model is absent from the connected Provider catalog");
18322
+ return model2;
18323
+ }
18324
+ function normalizeStoredOpenCodeModelRef(ref, index) {
18325
+ return ref.serviceTier ? void 0 : index.byLegacy.get(ref.id);
18112
18326
  }
18113
18327
  function encodeOpenCodeVariant(variant) {
18114
18328
  if (variant === void 0)
@@ -18116,8 +18330,8 @@ function encodeOpenCodeVariant(variant) {
18116
18330
  assertNonBlank(variant, "Model variant");
18117
18331
  return harnessThinkingOptionIdSchema.parse(`${VARIANT_REF_PREFIX}${Buffer2.from(variant, "utf8").toString("base64url")}`);
18118
18332
  }
18119
- function decodeOpenCodeVariant(id) {
18120
- const parsed = harnessThinkingOptionIdSchema.parse(id);
18333
+ function decodeOpenCodeVariant(id2) {
18334
+ const parsed = harnessThinkingOptionIdSchema.parse(id2);
18121
18335
  if (parsed === DEFAULT_VARIANT_ID)
18122
18336
  return void 0;
18123
18337
  if (!parsed.startsWith(VARIANT_REF_PREFIX)) {
@@ -18145,6 +18359,7 @@ function modelsForConnectedProviders(catalog) {
18145
18359
  }
18146
18360
  function normalizeOpenCodeModelCatalog(catalog) {
18147
18361
  const nativeModels = modelsForConnectedProviders(catalog);
18362
+ const index = openCodeModelIndex(nativeModels.map(({ provider, model: model2 }) => ({ providerID: provider.id, modelID: model2.id })));
18148
18363
  const variants = /* @__PURE__ */ new Set();
18149
18364
  for (const { model: model2 } of nativeModels) {
18150
18365
  for (const variant of Object.keys(model2.variants ?? {}))
@@ -18155,7 +18370,7 @@ function normalizeOpenCodeModelCatalog(catalog) {
18155
18370
  ...[...variants].sort(compareText).map((variant) => variantOption(variant))
18156
18371
  ];
18157
18372
  const models = nativeModels.map(({ provider, model: model2 }) => ({
18158
- ref: encodeOpenCodeModelRef({ providerID: provider.id, modelID: model2.id }),
18373
+ ref: index.encode({ providerID: provider.id, modelID: model2.id }),
18159
18374
  label: `${provider.name} / ${model2.name}`,
18160
18375
  resolvedModelLabel: `${provider.id}/${model2.id}`,
18161
18376
  supportedThinkingOptionIds: [
@@ -18164,16 +18379,19 @@ function normalizeOpenCodeModelCatalog(catalog) {
18164
18379
  ]
18165
18380
  })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
18166
18381
  const defaultNative = catalog.connected.map((providerID) => ({ providerID, modelID: catalog.default[providerID] })).find((candidate2) => typeof candidate2.modelID === "string" && candidate2.modelID.length > 0);
18167
- const defaultModel = defaultNative ? encodeOpenCodeModelRef(defaultNative) : void 0;
18168
- return harnessModelCatalogSchema.parse({
18169
- models,
18170
- ...defaultModel && models.some(({ ref }) => ref.id === defaultModel.id) ? { defaultModel } : {},
18171
- thinkingOptions,
18172
- defaultThinkingOptionId: DEFAULT_VARIANT_ID
18173
- });
18382
+ const defaultModel = defaultNative ? index.encode(defaultNative) : void 0;
18383
+ return {
18384
+ catalog: harnessModelCatalogSchema.parse({
18385
+ models,
18386
+ ...defaultModel && models.some(({ ref }) => ref.id === defaultModel.id) ? { defaultModel } : {},
18387
+ thinkingOptions,
18388
+ defaultThinkingOptionId: DEFAULT_VARIANT_ID
18389
+ }),
18390
+ index
18391
+ };
18174
18392
  }
18175
18393
  function openCodeContextWindow(catalog, model2) {
18176
- const provider = catalog.all.find(({ id }) => id === model2.providerID);
18394
+ const provider = catalog.all.find(({ id: id2 }) => id2 === model2.providerID);
18177
18395
  const context = provider?.models[model2.modelID]?.limit.context;
18178
18396
  return typeof context === "number" && Number.isSafeInteger(context) && context > 0 ? context : void 0;
18179
18397
  }
@@ -18397,7 +18615,7 @@ function projectOpenCodeHistory(input) {
18397
18615
  input: [{ type: "text", text: userText(userEntry) }],
18398
18616
  items,
18399
18617
  outcome,
18400
- model: encodeOpenCodeModelRef(user.model)
18618
+ model: encodeOpenCodeModelRef(user.model, input.modelIndex)
18401
18619
  });
18402
18620
  index = end;
18403
18621
  }
@@ -18410,12 +18628,12 @@ function resolveOpenCodeForkBoundary(session, messages, checkpoint) {
18410
18628
  if (checkpoint.harnessId !== openCodeHarnessId || checkpoint.nativeSessionId !== session.id) {
18411
18629
  return null;
18412
18630
  }
18413
- const active = activeMessages(session, messages);
18414
- const checkpointIndex = active.findIndex(({ info }) => info.id === checkpoint.checkpointId);
18415
- if (checkpointIndex < 0 || active[checkpointIndex]?.info.role !== "assistant")
18631
+ const active2 = activeMessages(session, messages);
18632
+ const checkpointIndex = active2.findIndex(({ info }) => info.id === checkpoint.checkpointId);
18633
+ if (checkpointIndex < 0 || active2[checkpointIndex]?.info.role !== "assistant")
18416
18634
  return null;
18417
- const targetUserCount = active.slice(0, checkpointIndex + 1).filter(({ info }) => info.role === "user").length;
18418
- const nextMessage = active[checkpointIndex + 1]?.info.id;
18635
+ const targetUserCount = active2.slice(0, checkpointIndex + 1).filter(({ info }) => info.role === "user").length;
18636
+ const nextMessage = active2[checkpointIndex + 1]?.info.id;
18419
18637
  return {
18420
18638
  ...nextMessage ? { messageID: nextMessage } : {},
18421
18639
  sourceTurnCount: targetUserCount
@@ -18628,8 +18846,8 @@ var createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer,
18628
18846
  };
18629
18847
 
18630
18848
  // ../../../node_modules/@opencode-ai/sdk/dist/v2/gen/core/pathSerializer.gen.js
18631
- var separatorArrayExplode = (style) => {
18632
- switch (style) {
18849
+ var separatorArrayExplode = (style2) => {
18850
+ switch (style2) {
18633
18851
  case "label":
18634
18852
  return ".";
18635
18853
  case "matrix":
@@ -18640,8 +18858,8 @@ var separatorArrayExplode = (style) => {
18640
18858
  return "&";
18641
18859
  }
18642
18860
  };
18643
- var separatorArrayNoExplode = (style) => {
18644
- switch (style) {
18861
+ var separatorArrayNoExplode = (style2) => {
18862
+ switch (style2) {
18645
18863
  case "form":
18646
18864
  return ",";
18647
18865
  case "pipeDelimited":
@@ -18652,8 +18870,8 @@ var separatorArrayNoExplode = (style) => {
18652
18870
  return ",";
18653
18871
  }
18654
18872
  };
18655
- var separatorObjectExplode = (style) => {
18656
- switch (style) {
18873
+ var separatorObjectExplode = (style2) => {
18874
+ switch (style2) {
18657
18875
  case "label":
18658
18876
  return ".";
18659
18877
  case "matrix":
@@ -18664,10 +18882,10 @@ var separatorObjectExplode = (style) => {
18664
18882
  return "&";
18665
18883
  }
18666
18884
  };
18667
- var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
18885
+ var serializeArrayParam = ({ allowReserved, explode, name, style: style2, value }) => {
18668
18886
  if (!explode) {
18669
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
18670
- switch (style) {
18887
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style2));
18888
+ switch (style2) {
18671
18889
  case "label":
18672
18890
  return `.${joinedValues2}`;
18673
18891
  case "matrix":
@@ -18678,9 +18896,9 @@ var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
18678
18896
  return `${name}=${joinedValues2}`;
18679
18897
  }
18680
18898
  }
18681
- const separator = separatorArrayExplode(style);
18899
+ const separator = separatorArrayExplode(style2);
18682
18900
  const joinedValues = value.map((v) => {
18683
- if (style === "label" || style === "simple") {
18901
+ if (style2 === "label" || style2 === "simple") {
18684
18902
  return allowReserved ? v : encodeURIComponent(v);
18685
18903
  }
18686
18904
  return serializePrimitiveParam({
@@ -18689,7 +18907,7 @@ var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
18689
18907
  value: v
18690
18908
  });
18691
18909
  }).join(separator);
18692
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
18910
+ return style2 === "label" || style2 === "matrix" ? separator + joinedValues : joinedValues;
18693
18911
  };
18694
18912
  var serializePrimitiveParam = ({ allowReserved, name, value }) => {
18695
18913
  if (value === void 0 || value === null) {
@@ -18700,17 +18918,17 @@ var serializePrimitiveParam = ({ allowReserved, name, value }) => {
18700
18918
  }
18701
18919
  return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
18702
18920
  };
18703
- var serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
18921
+ var serializeObjectParam = ({ allowReserved, explode, name, style: style2, value, valueOnly }) => {
18704
18922
  if (value instanceof Date) {
18705
18923
  return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
18706
18924
  }
18707
- if (style !== "deepObject" && !explode) {
18925
+ if (style2 !== "deepObject" && !explode) {
18708
18926
  let values = [];
18709
18927
  Object.entries(value).forEach(([key, v]) => {
18710
18928
  values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
18711
18929
  });
18712
18930
  const joinedValues2 = values.join(",");
18713
- switch (style) {
18931
+ switch (style2) {
18714
18932
  case "form":
18715
18933
  return `${name}=${joinedValues2}`;
18716
18934
  case "label":
@@ -18721,13 +18939,13 @@ var serializeObjectParam = ({ allowReserved, explode, name, style, value, valueO
18721
18939
  return joinedValues2;
18722
18940
  }
18723
18941
  }
18724
- const separator = separatorObjectExplode(style);
18942
+ const separator = separatorObjectExplode(style2);
18725
18943
  const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
18726
18944
  allowReserved,
18727
- name: style === "deepObject" ? `${name}[${key}]` : key,
18945
+ name: style2 === "deepObject" ? `${name}[${key}]` : key,
18728
18946
  value: v
18729
18947
  })).join(separator);
18730
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
18948
+ return style2 === "label" || style2 === "matrix" ? separator + joinedValues : joinedValues;
18731
18949
  };
18732
18950
 
18733
18951
  // ../../../node_modules/@opencode-ai/sdk/dist/v2/gen/core/utils.gen.js
@@ -18739,44 +18957,44 @@ var defaultPathSerializer = ({ path: path14, url: _url2 }) => {
18739
18957
  for (const match of matches) {
18740
18958
  let explode = false;
18741
18959
  let name = match.substring(1, match.length - 1);
18742
- let style = "simple";
18960
+ let style2 = "simple";
18743
18961
  if (name.endsWith("*")) {
18744
18962
  explode = true;
18745
18963
  name = name.substring(0, name.length - 1);
18746
18964
  }
18747
18965
  if (name.startsWith(".")) {
18748
18966
  name = name.substring(1);
18749
- style = "label";
18967
+ style2 = "label";
18750
18968
  } else if (name.startsWith(";")) {
18751
18969
  name = name.substring(1);
18752
- style = "matrix";
18970
+ style2 = "matrix";
18753
18971
  }
18754
18972
  const value = path14[name];
18755
18973
  if (value === void 0 || value === null) {
18756
18974
  continue;
18757
18975
  }
18758
18976
  if (Array.isArray(value)) {
18759
- url2 = url2.replace(match, serializeArrayParam({ explode, name, style, value }));
18977
+ url2 = url2.replace(match, serializeArrayParam({ explode, name, style: style2, value }));
18760
18978
  continue;
18761
18979
  }
18762
18980
  if (typeof value === "object") {
18763
18981
  url2 = url2.replace(match, serializeObjectParam({
18764
18982
  explode,
18765
18983
  name,
18766
- style,
18984
+ style: style2,
18767
18985
  value,
18768
18986
  valueOnly: true
18769
18987
  }));
18770
18988
  continue;
18771
18989
  }
18772
- if (style === "matrix") {
18990
+ if (style2 === "matrix") {
18773
18991
  url2 = url2.replace(match, `;${serializePrimitiveParam({
18774
18992
  name,
18775
18993
  value
18776
18994
  })}`);
18777
18995
  continue;
18778
18996
  }
18779
- const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
18997
+ const replaceValue = encodeURIComponent(style2 === "label" ? `.${value}` : value);
18780
18998
  url2 = url2.replace(match, replaceValue);
18781
18999
  }
18782
19000
  }
@@ -18987,27 +19205,27 @@ var Interceptors = class {
18987
19205
  clear() {
18988
19206
  this.fns = [];
18989
19207
  }
18990
- eject(id) {
18991
- const index = this.getInterceptorIndex(id);
19208
+ eject(id2) {
19209
+ const index = this.getInterceptorIndex(id2);
18992
19210
  if (this.fns[index]) {
18993
19211
  this.fns[index] = null;
18994
19212
  }
18995
19213
  }
18996
- exists(id) {
18997
- const index = this.getInterceptorIndex(id);
19214
+ exists(id2) {
19215
+ const index = this.getInterceptorIndex(id2);
18998
19216
  return Boolean(this.fns[index]);
18999
19217
  }
19000
- getInterceptorIndex(id) {
19001
- if (typeof id === "number") {
19002
- return this.fns[id] ? id : -1;
19218
+ getInterceptorIndex(id2) {
19219
+ if (typeof id2 === "number") {
19220
+ return this.fns[id2] ? id2 : -1;
19003
19221
  }
19004
- return this.fns.indexOf(id);
19222
+ return this.fns.indexOf(id2);
19005
19223
  }
19006
- update(id, fn) {
19007
- const index = this.getInterceptorIndex(id);
19224
+ update(id2, fn) {
19225
+ const index = this.getInterceptorIndex(id2);
19008
19226
  if (this.fns[index]) {
19009
19227
  this.fns[index] = fn;
19010
- return id;
19228
+ return id2;
19011
19229
  }
19012
19230
  return false;
19013
19231
  }
@@ -24677,7 +24895,7 @@ async function readTurnDiff(transport, sessionID, userMessageID, nativePatchFile
24677
24895
  await new Promise((resolve) => setTimeout(resolve, DIFF_RECONCILIATION_DELAYS_MS[attempt]));
24678
24896
  }
24679
24897
  }
24680
- async function readProjection(transport, sessionID, providerCatalog, toolOutputLimit, options = {}) {
24898
+ async function readProjection(transport, sessionID, providerCatalog, toolOutputLimit, modelIndex, options = {}) {
24681
24899
  const strictFileChanges = options.strictFileChanges === true;
24682
24900
  const [session, messages, paths] = await Promise.all([
24683
24901
  transport.getSession(sessionID),
@@ -24699,11 +24917,12 @@ async function readProjection(transport, sessionID, providerCatalog, toolOutputL
24699
24917
  session,
24700
24918
  messages,
24701
24919
  diffsByUserMessageId: new Map(diffEntries),
24702
- toolOutputLimit
24920
+ toolOutputLimit,
24921
+ modelIndex
24703
24922
  });
24704
24923
  const model2 = nativeModelFromSession(session, messages);
24705
24924
  const nativeVariant = nativeVariantFromSession(session, messages);
24706
- const nativeModel = model2 ? providerCatalog.all.find(({ id }) => id === model2.providerID)?.models[model2.modelID] : void 0;
24925
+ const nativeModel = model2 ? providerCatalog.all.find(({ id: id2 }) => id2 === model2.providerID)?.models[model2.modelID] : void 0;
24707
24926
  const variant = nativeVariant === "default" && nativeModel && !Object.hasOwn(nativeModel.variants ?? {}, "default") ? void 0 : nativeVariant;
24708
24927
  const usage = projectOpenCodeUsage(openCodeAssistantMessages(session, messages), model2 ? openCodeContextWindow(providerCatalog, model2) : void 0);
24709
24928
  return {
@@ -24749,8 +24968,10 @@ function sourceState(projection) {
24749
24968
  };
24750
24969
  }
24751
24970
  async function deriveOpenCodeHistory(options) {
24752
- const { transport, source, input, providers, toolOutputLimit } = options;
24753
- const read = (id) => readProjection(transport, id, providers, toolOutputLimit, { strictFileChanges: true });
24971
+ const { transport, source, input, providers, modelIndex, toolOutputLimit } = options;
24972
+ const read = (id2) => readProjection(transport, id2, providers, toolOutputLimit, modelIndex, {
24973
+ strictFileChanges: true
24974
+ });
24754
24975
  if ((await transport.getStatus(source.id)).type !== "idle") {
24755
24976
  throw new Error("OpenCode source Session is busy");
24756
24977
  }
@@ -24842,10 +25063,10 @@ function sameCwd(left, right) {
24842
25063
  };
24843
25064
  return canonical(left) === canonical(right);
24844
25065
  }
24845
- function sessionState(session, modelCatalog, model2, variant, executionPolicy = "default", permissionModeId = OPENCODE_DEFAULT_PERMISSION_MODE_ID) {
24846
- const effectiveModel = model2 ? encodeOpenCodeModelRef(model2) : void 0;
25066
+ function sessionState(session, { catalog: modelCatalog, index }, model2, variant, executionPolicy = "default", permissionModeId = OPENCODE_DEFAULT_PERMISSION_MODE_ID) {
25067
+ const effectiveModel = model2 ? encodeOpenCodeModelRef(model2, index) : void 0;
24847
25068
  const modelEntry = effectiveModel ? modelCatalog.models.find(({ ref }) => ref.id === effectiveModel.id) : void 0;
24848
- const availableThinkingOptions = modelEntry?.supportedThinkingOptionIds?.map((id) => modelCatalog.thinkingOptions.find((option) => option.id === id)).filter((option) => Boolean(option));
25069
+ const availableThinkingOptions = modelEntry?.supportedThinkingOptionIds?.map((id2) => modelCatalog.thinkingOptions.find((option) => option.id === id2)).filter((option) => Boolean(option));
24849
25070
  const effectiveThinkingOptionId = encodeOpenCodeVariant(variant);
24850
25071
  return {
24851
25072
  nativeRef: openCodeNativeSessionRef(session, executionPolicy),
@@ -24937,10 +25158,10 @@ var OpenCodeHarnessSession = class {
24937
25158
  this.initialState = this.#state;
24938
25159
  this.#usage = input.projection.usage;
24939
25160
  this.initialUsage = this.#usage;
24940
- const thinkingSelectable = this.#modelCatalog.thinkingOptions.length > 1;
25161
+ const thinkingSelectable = this.#modelCatalog.catalog.thinkingOptions.length > 1;
24941
25162
  this.capabilities = {
24942
25163
  configuration: {
24943
- selectModel: this.#modelCatalog.models.length > 0,
25164
+ selectModel: this.#modelCatalog.catalog.models.length > 0,
24944
25165
  selectThinkingOption: thinkingSelectable,
24945
25166
  selectPermissionMode: true,
24946
25167
  permissionModeScope: "live"
@@ -24975,7 +25196,7 @@ var OpenCodeHarnessSession = class {
24975
25196
  };
24976
25197
  }
24977
25198
  try {
24978
- const projection = await readProjection(this.#transport, this.#session.id, this.#providerCatalog, this.#toolOutputLimit);
25199
+ const projection = await readProjection(this.#transport, this.#session.id, this.#providerCatalog, this.#toolOutputLimit, this.#modelCatalog.index);
24979
25200
  this.#applyProjection(projection);
24980
25201
  return { ok: true, value: { ...this.#snapshot, state: this.#state } };
24981
25202
  } catch (error51) {
@@ -25019,11 +25240,11 @@ var OpenCodeHarnessSession = class {
25019
25240
  }
25020
25241
  };
25021
25242
  }
25022
- const active = this.#createActive("prompt", command.turnId, null);
25023
- this.#active = active;
25024
- active.admissionBuffer.push({
25243
+ const active2 = this.#createActive("prompt", command.turnId, null);
25244
+ this.#active = active2;
25245
+ active2.admissionBuffer.push({
25025
25246
  output: { kind: "event", event: { type: "turn.started", turnId: command.turnId } },
25026
- sequence: active.admissionSequence++
25247
+ sequence: active2.admissionSequence++
25027
25248
  });
25028
25249
  try {
25029
25250
  const prompt = this.#transport.promptAsync({
@@ -25033,19 +25254,19 @@ var OpenCodeHarnessSession = class {
25033
25254
  ...this.#variant ? { variant: this.#variant } : {}
25034
25255
  });
25035
25256
  void prompt.catch(() => void 0);
25036
- await Promise.race([prompt, active.admissionFailurePromise]);
25037
- if (active.admissionFailure)
25038
- return { ok: false, error: active.admissionFailure };
25039
- active.admissionCompleted = true;
25040
- this.#flushAdmission(active);
25041
- void this.#reconcileAndFinish(active);
25257
+ await Promise.race([prompt, active2.admissionFailurePromise]);
25258
+ if (active2.admissionFailure)
25259
+ return { ok: false, error: active2.admissionFailure };
25260
+ active2.admissionCompleted = true;
25261
+ this.#flushAdmission(active2);
25262
+ void this.#reconcileAndFinish(active2);
25042
25263
  return { ok: true, value: { turnId: command.turnId } };
25043
25264
  } catch (error51) {
25044
25265
  const normalized = normalizeError(error51, "nativeFailure");
25045
- active.admissionBuffer.length = 0;
25046
- active.finished = true;
25047
- active.resolveCompletion();
25048
- if (this.#active === active)
25266
+ active2.admissionBuffer.length = 0;
25267
+ active2.finished = true;
25268
+ active2.resolveCompletion();
25269
+ if (this.#active === active2)
25049
25270
  this.#active = null;
25050
25271
  return { ok: false, error: normalized };
25051
25272
  }
@@ -25091,31 +25312,31 @@ var OpenCodeHarnessSession = class {
25091
25312
  }
25092
25313
  };
25093
25314
  }
25094
- const active = this.#createActive("compact", command.turnId, null);
25095
- this.#active = active;
25096
- active.admissionBuffer.push({
25315
+ const active2 = this.#createActive("compact", command.turnId, null);
25316
+ this.#active = active2;
25317
+ active2.admissionBuffer.push({
25097
25318
  output: { kind: "event", event: { type: "turn.started", turnId: command.turnId } },
25098
- sequence: active.admissionSequence++
25319
+ sequence: active2.admissionSequence++
25099
25320
  });
25100
25321
  const item = {
25101
25322
  type: "contextCompaction",
25102
25323
  itemId: hostItemIdSchema.parse(`opencode-compact:${this.#uuid()}`)
25103
25324
  };
25104
- active.items.set(item.itemId, { item, completed: false });
25325
+ active2.items.set(item.itemId, { item, completed: false });
25105
25326
  this.#event({ type: "item.started", turnId: command.turnId, item });
25106
25327
  try {
25107
25328
  await this.#transport.summarize(this.#session.id, this.#model);
25108
25329
  } catch (error51) {
25109
25330
  const normalized = normalizeError(error51, "nativeFailure");
25110
- this.#failAdmission(active, normalized);
25331
+ this.#failAdmission(active2, normalized);
25111
25332
  return { ok: false, error: normalized };
25112
25333
  }
25113
- if (active.admissionFailure)
25114
- return { ok: false, error: active.admissionFailure };
25115
- active.admissionCompleted = true;
25116
- active.nativeCompleted = true;
25117
- this.#flushAdmission(active);
25118
- this.#completeTurn(active, { status: "succeeded" });
25334
+ if (active2.admissionFailure)
25335
+ return { ok: false, error: active2.admissionFailure };
25336
+ active2.admissionCompleted = true;
25337
+ active2.nativeCompleted = true;
25338
+ this.#flushAdmission(active2);
25339
+ this.#completeTurn(active2, { status: "succeeded" });
25119
25340
  void this.#refreshProjection(command.turnId);
25120
25341
  return { ok: true, value: { turnId: command.turnId } };
25121
25342
  }
@@ -25125,14 +25346,14 @@ var OpenCodeHarnessSession = class {
25125
25346
  };
25126
25347
  }
25127
25348
  async #cancel(command) {
25128
- const active = this.#active;
25129
- if (!active || active.turnId !== command.turnId) {
25349
+ const active2 = this.#active;
25350
+ if (!active2 || active2.turnId !== command.turnId) {
25130
25351
  return {
25131
25352
  ok: false,
25132
25353
  error: invalidState("OpenCode cancellation must reference the active Turn")
25133
25354
  };
25134
25355
  }
25135
- active.cancellationRequested = true;
25356
+ active2.cancellationRequested = true;
25136
25357
  try {
25137
25358
  await this.#transport.abort(this.#session.id);
25138
25359
  return { ok: true, value: { cancellationRequested: true } };
@@ -25141,9 +25362,9 @@ var OpenCodeHarnessSession = class {
25141
25362
  }
25142
25363
  }
25143
25364
  async #respond(command) {
25144
- const active = this.#active;
25145
- const pending = active?.interactions.get(command.interactionId);
25146
- if (!active || !pending) {
25365
+ const active2 = this.#active;
25366
+ const pending = active2?.interactions.get(command.interactionId);
25367
+ if (!active2 || !pending) {
25147
25368
  return {
25148
25369
  ok: false,
25149
25370
  error: invalidState("OpenCode Interaction Response must reference a pending Interaction")
@@ -25186,7 +25407,7 @@ var OpenCodeHarnessSession = class {
25186
25407
  return { ok: false, error: validation };
25187
25408
  await this.#transport.replyPermission(pending.nativeId, command.response.actionId === "allow-once" ? "once" : "reject");
25188
25409
  }
25189
- this.#closeInteraction(active, command.interactionId, "responded");
25410
+ this.#closeInteraction(active2, command.interactionId, "responded");
25190
25411
  return { ok: true, value: { accepted: true } };
25191
25412
  } catch (error51) {
25192
25413
  return { ok: false, error: normalizeError(error51, "nativeFailure") };
@@ -25205,21 +25426,10 @@ var OpenCodeHarnessSession = class {
25205
25426
  }
25206
25427
  let native;
25207
25428
  try {
25208
- native = decodeOpenCodeModelRef(command.model);
25429
+ native = decodeOpenCodeModelRef(command.model, this.#modelCatalog.index);
25209
25430
  } catch (error51) {
25210
25431
  return { ok: false, error: normalizeError(error51, "invalidRequest") };
25211
25432
  }
25212
- const entry = this.#modelCatalog.models.find(({ ref }) => ref.id === command.model.id);
25213
- if (!entry) {
25214
- return {
25215
- ok: false,
25216
- error: {
25217
- code: "invalidRequest",
25218
- message: "OpenCode Model is absent from the current catalog",
25219
- retryable: false
25220
- }
25221
- };
25222
- }
25223
25433
  this.#configuring = true;
25224
25434
  try {
25225
25435
  this.#session = await this.#transport.updateSessionMetadata(this.#session.id, selectionMetadata(this.#session, native, void 0));
@@ -25247,8 +25457,8 @@ var OpenCodeHarnessSession = class {
25247
25457
  }
25248
25458
  };
25249
25459
  }
25250
- const modelRef = this.#model ? encodeOpenCodeModelRef(this.#model) : void 0;
25251
- const model2 = modelRef ? this.#modelCatalog.models.find(({ ref }) => ref.id === modelRef.id) : void 0;
25460
+ const modelRef = this.#model ? encodeOpenCodeModelRef(this.#model, this.#modelCatalog.index) : void 0;
25461
+ const model2 = modelRef ? this.#modelCatalog.catalog.models.find(({ ref }) => ref.id === modelRef.id) : void 0;
25252
25462
  if (!model2?.supportedThinkingOptionIds?.includes(command.thinkingOptionId)) {
25253
25463
  return {
25254
25464
  ok: false,
@@ -25329,24 +25539,24 @@ var OpenCodeHarnessSession = class {
25329
25539
  return;
25330
25540
  if (event.type === "server.connected") {
25331
25541
  this.#connectedCount += 1;
25332
- const active2 = this.#active;
25333
- if (this.#connectedCount > 1 && active2)
25334
- void this.#reconcileAfterReconnect(active2);
25542
+ const active3 = this.#active;
25543
+ if (this.#connectedCount > 1 && active3)
25544
+ void this.#reconcileAfterReconnect(active3);
25335
25545
  return;
25336
25546
  }
25337
- const active = this.#active;
25547
+ const active2 = this.#active;
25338
25548
  if (event.type === "session.status" && event.properties.sessionID === this.#session.id) {
25339
- if (!active)
25549
+ if (!active2)
25340
25550
  return;
25341
25551
  if (event.properties.status.type === "busy")
25342
- active.sawBusy = true;
25552
+ active2.sawBusy = true;
25343
25553
  if (event.properties.status.type === "idle")
25344
- void this.#reconcileAndFinish(active);
25554
+ void this.#reconcileAndFinish(active2);
25345
25555
  return;
25346
25556
  }
25347
25557
  if (event.type === "session.idle" && event.properties.sessionID === this.#session.id) {
25348
- if (active)
25349
- void this.#reconcileAndFinish(active);
25558
+ if (active2)
25559
+ void this.#reconcileAndFinish(active2);
25350
25560
  return;
25351
25561
  }
25352
25562
  if (event.type === "message.updated" && event.properties.sessionID === this.#session.id) {
@@ -25355,65 +25565,65 @@ var OpenCodeHarnessSession = class {
25355
25565
  this.#knownUserMessageIds.add(info.id);
25356
25566
  return;
25357
25567
  }
25358
- if (!active || !this.#bindUserMessage(active, info.parentID))
25568
+ if (!active2 || !this.#bindUserMessage(active2, info.parentID))
25359
25569
  return;
25360
- active.assistantMessageIds.add(info.id);
25361
- active.terminalAssistant = info;
25570
+ active2.assistantMessageIds.add(info.id);
25571
+ active2.terminalAssistant = info;
25362
25572
  if (info.time.completed !== void 0 || info.finish || info.error) {
25363
- void this.#reconcileAndFinish(active);
25573
+ void this.#reconcileAndFinish(active2);
25364
25574
  }
25365
25575
  return;
25366
25576
  }
25367
25577
  if (event.type === "message.part.updated") {
25368
25578
  const part = event.properties.part;
25369
- if (active && part.sessionID === this.#session.id && active.assistantMessageIds.has(part.messageID)) {
25370
- this.#projectPart(active, part);
25579
+ if (active2 && part.sessionID === this.#session.id && active2.assistantMessageIds.has(part.messageID)) {
25580
+ this.#projectPart(active2, part);
25371
25581
  }
25372
25582
  return;
25373
25583
  }
25374
25584
  if (event.type === "message.part.delta") {
25375
25585
  const properties = event.properties;
25376
- if (active && properties.sessionID === this.#session.id && active.assistantMessageIds.has(properties.messageID)) {
25377
- this.#appendPartDelta(active, properties.partID, properties.field, properties.delta);
25586
+ if (active2 && properties.sessionID === this.#session.id && active2.assistantMessageIds.has(properties.messageID)) {
25587
+ this.#appendPartDelta(active2, properties.partID, properties.field, properties.delta);
25378
25588
  }
25379
25589
  return;
25380
25590
  }
25381
25591
  if (event.type === "question.asked" && event.properties.sessionID === this.#session.id) {
25382
- if (active)
25383
- this.#openQuestion(active, event.properties);
25592
+ if (active2)
25593
+ this.#openQuestion(active2, event.properties);
25384
25594
  return;
25385
25595
  }
25386
25596
  if (event.type === "question.replied" || event.type === "question.rejected") {
25387
- if (event.properties.sessionID !== this.#session.id || !active)
25597
+ if (event.properties.sessionID !== this.#session.id || !active2)
25388
25598
  return;
25389
- const id = hostInteractionIdSchema.parse(event.properties.requestID);
25390
- if (active.interactions.has(id))
25391
- this.#closeInteraction(active, id, "superseded");
25599
+ const id2 = hostInteractionIdSchema.parse(event.properties.requestID);
25600
+ if (active2.interactions.has(id2))
25601
+ this.#closeInteraction(active2, id2, "superseded");
25392
25602
  return;
25393
25603
  }
25394
25604
  if (event.type === "permission.asked" && event.properties.sessionID === this.#session.id) {
25395
- if (active)
25396
- this.#openApproval(active, event.properties);
25605
+ if (active2)
25606
+ this.#openApproval(active2, event.properties);
25397
25607
  return;
25398
25608
  }
25399
25609
  if (event.type === "permission.replied") {
25400
- if (event.properties.sessionID !== this.#session.id || !active)
25610
+ if (event.properties.sessionID !== this.#session.id || !active2)
25401
25611
  return;
25402
- const id = hostInteractionIdSchema.parse(event.properties.requestID);
25403
- if (active.interactions.has(id))
25404
- this.#closeInteraction(active, id, "superseded");
25612
+ const id2 = hostInteractionIdSchema.parse(event.properties.requestID);
25613
+ if (active2.interactions.has(id2))
25614
+ this.#closeInteraction(active2, id2, "superseded");
25405
25615
  return;
25406
25616
  }
25407
- if (event.type === "session.error" && event.properties.sessionID === this.#session.id && active) {
25617
+ if (event.type === "session.error" && event.properties.sessionID === this.#session.id && active2) {
25408
25618
  const error51 = event.properties.error;
25409
- if (active.cancellationRequested || error51?.name === "MessageAbortedError") {
25410
- active.cancellationRequested = true;
25411
- void this.#reconcileAndFinish(active);
25619
+ if (active2.cancellationRequested || error51?.name === "MessageAbortedError") {
25620
+ active2.cancellationRequested = true;
25621
+ void this.#reconcileAndFinish(active2);
25412
25622
  return;
25413
25623
  }
25414
- this.#completeTurn(active, {
25415
- status: active.cancellationRequested ? "cancelled" : "failed",
25416
- ...active.cancellationRequested ? { reason: "Cancelled by user" } : {
25624
+ this.#completeTurn(active2, {
25625
+ status: active2.cancellationRequested ? "cancelled" : "failed",
25626
+ ...active2.cancellationRequested ? { reason: "Cancelled by user" } : {
25417
25627
  error: {
25418
25628
  code: error51?.name === "ProviderAuthError" ? "authenticationRequired" : "nativeFailure",
25419
25629
  message: error51 && "message" in error51.data && typeof error51.data.message === "string" ? error51.data.message : "OpenCode Session failed",
@@ -25423,49 +25633,49 @@ var OpenCodeHarnessSession = class {
25423
25633
  });
25424
25634
  }
25425
25635
  }
25426
- #projectPart(active, part) {
25636
+ #projectPart(active2, part) {
25427
25637
  if (part.type === "text" || part.type === "reasoning") {
25428
25638
  if (part.type === "text" && part.ignored)
25429
25639
  return;
25430
- const existing = active.items.get(part.id);
25640
+ const existing = active2.items.get(part.id);
25431
25641
  if (!existing) {
25432
25642
  const item = part.type === "text" ? { type: "agentMessage", itemId: hostItemIdSchema.parse(part.id), text: part.text } : { type: "reasoning", itemId: hostItemIdSchema.parse(part.id), text: part.text };
25433
- active.items.set(part.id, { item, content: part.text, completed: false });
25434
- this.#event({ type: "item.started", turnId: active.turnId, item });
25643
+ active2.items.set(part.id, { item, content: part.text, completed: false });
25644
+ this.#event({ type: "item.started", turnId: active2.turnId, item });
25435
25645
  } else if (typeof existing.content === "string" && part.text.startsWith(existing.content)) {
25436
25646
  const suffix = part.text.slice(existing.content.length);
25437
25647
  if (suffix)
25438
- this.#appendText(active, part.id, suffix);
25648
+ this.#appendText(active2, part.id, suffix);
25439
25649
  } else if (typeof existing.content === "string" && existing.content !== part.text) {
25440
25650
  throw new OpenCodeTransportError("protocolError", `OpenCode Part '${part.id}' returned inconsistent streamed text`);
25441
25651
  }
25442
25652
  if (part.time?.end !== void 0)
25443
- this.#completeLiveItem(active, part.id, { status: "succeeded" });
25653
+ this.#completeLiveItem(active2, part.id, { status: "succeeded" });
25444
25654
  return;
25445
25655
  }
25446
25656
  if (part.type === "tool") {
25447
- this.#projectTool(active, part);
25657
+ this.#projectTool(active2, part);
25448
25658
  return;
25449
25659
  }
25450
- if (part.type === "compaction" && !active.items.has(part.id)) {
25660
+ if (part.type === "compaction" && !active2.items.has(part.id)) {
25451
25661
  const item = {
25452
25662
  type: "contextCompaction",
25453
25663
  itemId: hostItemIdSchema.parse(part.id)
25454
25664
  };
25455
- active.items.set(part.id, { item, completed: false });
25456
- this.#event({ type: "item.started", turnId: active.turnId, item });
25665
+ active2.items.set(part.id, { item, completed: false });
25666
+ this.#event({ type: "item.started", turnId: active2.turnId, item });
25457
25667
  }
25458
25668
  }
25459
- #appendPartDelta(active, partID, field2, delta) {
25669
+ #appendPartDelta(active2, partID, field2, delta) {
25460
25670
  if (field2 !== "text" || !delta)
25461
25671
  return;
25462
- const existing = active.items.get(partID);
25672
+ const existing = active2.items.get(partID);
25463
25673
  if (!existing)
25464
25674
  return;
25465
- this.#appendText(active, partID, delta);
25675
+ this.#appendText(active2, partID, delta);
25466
25676
  }
25467
- #appendText(active, partID, delta) {
25468
- const live = active.items.get(partID);
25677
+ #appendText(active2, partID, delta) {
25678
+ const live = active2.items.get(partID);
25469
25679
  if (!live || live.completed || typeof live.content !== "string")
25470
25680
  return;
25471
25681
  live.content += delta;
@@ -25474,19 +25684,19 @@ var OpenCodeHarnessSession = class {
25474
25684
  }
25475
25685
  this.#event({
25476
25686
  type: "item.updated",
25477
- turnId: active.turnId,
25687
+ turnId: active2.turnId,
25478
25688
  itemId: live.item.itemId,
25479
25689
  update: { type: "text.append", text: delta }
25480
25690
  });
25481
25691
  }
25482
- #projectTool(active, part) {
25692
+ #projectTool(active2, part) {
25483
25693
  if (part.state.status === "pending")
25484
25694
  return;
25485
25695
  const arguments_ = jsonValueSchema.safeParse(part.state.input);
25486
25696
  if (!arguments_.success) {
25487
25697
  throw new OpenCodeTransportError("protocolError", `OpenCode Tool '${part.tool}' emitted invalid arguments`);
25488
25698
  }
25489
- let live = active.items.get(part.id);
25699
+ let live = active2.items.get(part.id);
25490
25700
  if (!live) {
25491
25701
  const item = {
25492
25702
  type: "toolExecution",
@@ -25495,9 +25705,9 @@ var OpenCodeHarnessSession = class {
25495
25705
  arguments: arguments_.data
25496
25706
  };
25497
25707
  live = { item, completed: false };
25498
- active.items.set(part.id, live);
25499
- active.toolItemByCallId.set(part.callID, item.itemId);
25500
- this.#event({ type: "item.started", turnId: active.turnId, item });
25708
+ active2.items.set(part.id, live);
25709
+ active2.toolItemByCallId.set(part.callID, item.itemId);
25710
+ this.#event({ type: "item.started", turnId: active2.turnId, item });
25501
25711
  }
25502
25712
  if (live.item.type !== "toolExecution" || live.completed)
25503
25713
  return;
@@ -25511,18 +25721,18 @@ var OpenCodeHarnessSession = class {
25511
25721
  if (output) {
25512
25722
  this.#event({
25513
25723
  type: "item.updated",
25514
- turnId: active.turnId,
25724
+ turnId: active2.turnId,
25515
25725
  itemId: live.item.itemId,
25516
25726
  update: { type: "output.replace", output }
25517
25727
  });
25518
25728
  }
25519
- this.#completeLiveItem(active, part.id, { status: "succeeded" });
25729
+ this.#completeLiveItem(active2, part.id, { status: "succeeded" });
25520
25730
  } else if (part.state.status === "error") {
25521
25731
  live.item = {
25522
25732
  ...live.item,
25523
25733
  durationMs: Math.max(0, part.state.time.end - part.state.time.start)
25524
25734
  };
25525
- this.#completeLiveItem(active, part.id, {
25735
+ this.#completeLiveItem(active2, part.id, {
25526
25736
  status: "failed",
25527
25737
  error: {
25528
25738
  code: "nativeFailure",
@@ -25532,9 +25742,9 @@ var OpenCodeHarnessSession = class {
25532
25742
  });
25533
25743
  }
25534
25744
  }
25535
- #openQuestion(active, request) {
25745
+ #openQuestion(active2, request) {
25536
25746
  const interactionId = hostInteractionIdSchema.parse(request.id);
25537
- if (active.interactions.has(interactionId))
25747
+ if (active2.interactions.has(interactionId))
25538
25748
  return;
25539
25749
  const questions = request.questions.map((question, index) => ({
25540
25750
  id: `question-${index}`,
@@ -25549,31 +25759,31 @@ var OpenCodeHarnessSession = class {
25549
25759
  allowOther: question.custom ?? false,
25550
25760
  optional: false
25551
25761
  }));
25552
- const itemId2 = request.tool ? active.toolItemByCallId.get(request.tool.callID) : void 0;
25762
+ const itemId2 = request.tool ? active2.toolItemByCallId.get(request.tool.callID) : void 0;
25553
25763
  const interaction = {
25554
25764
  type: "question",
25555
25765
  interactionId,
25556
- turnId: active.turnId,
25766
+ turnId: active2.turnId,
25557
25767
  ...itemId2 ? { itemId: itemId2 } : {},
25558
25768
  title: request.questions.map(({ header }) => header).filter(Boolean).join(" / ") || "OpenCode",
25559
25769
  questions
25560
25770
  };
25561
- active.interactions.set(interactionId, {
25771
+ active2.interactions.set(interactionId, {
25562
25772
  type: "question",
25563
25773
  nativeId: request.id,
25564
25774
  interaction
25565
25775
  });
25566
25776
  this.#output({ kind: "interaction", interaction });
25567
25777
  }
25568
- #openApproval(active, request) {
25778
+ #openApproval(active2, request) {
25569
25779
  const interactionId = hostInteractionIdSchema.parse(request.id);
25570
- if (active.interactions.has(interactionId))
25780
+ if (active2.interactions.has(interactionId))
25571
25781
  return;
25572
- const itemId2 = request.tool ? active.toolItemByCallId.get(request.tool.callID) : void 0;
25782
+ const itemId2 = request.tool ? active2.toolItemByCallId.get(request.tool.callID) : void 0;
25573
25783
  const interaction = {
25574
25784
  type: "approval",
25575
25785
  interactionId,
25576
- turnId: active.turnId,
25786
+ turnId: active2.turnId,
25577
25787
  ...itemId2 ? { itemId: itemId2 } : {},
25578
25788
  title: `Allow OpenCode ${request.permission}?`,
25579
25789
  ...request.patterns.length > 0 ? { description: request.patterns.join("\n") } : {},
@@ -25583,78 +25793,78 @@ var OpenCodeHarnessSession = class {
25583
25793
  { id: "deny", label: "Deny", effect: "deny" }
25584
25794
  ]
25585
25795
  };
25586
- active.interactions.set(interactionId, {
25796
+ active2.interactions.set(interactionId, {
25587
25797
  type: "approval",
25588
25798
  nativeId: request.id,
25589
25799
  interaction
25590
25800
  });
25591
25801
  this.#output({ kind: "interaction", interaction });
25592
25802
  }
25593
- #closeInteraction(active, interactionId, reason) {
25594
- if (!active.interactions.delete(interactionId))
25803
+ #closeInteraction(active2, interactionId, reason) {
25804
+ if (!active2.interactions.delete(interactionId))
25595
25805
  return;
25596
25806
  this.#event({
25597
25807
  type: "interaction.closed",
25598
25808
  interactionId,
25599
- turnId: active.turnId,
25809
+ turnId: active2.turnId,
25600
25810
  reason
25601
25811
  });
25602
25812
  }
25603
- async #reconcileAfterReconnect(active) {
25813
+ async #reconcileAfterReconnect(active2) {
25604
25814
  try {
25605
25815
  const [status, questions, permissions] = await Promise.all([
25606
25816
  this.#transport.getStatus(this.#session.id),
25607
25817
  this.#transport.listQuestions(),
25608
25818
  this.#transport.listPermissions()
25609
25819
  ]);
25610
- if (this.#active !== active)
25820
+ if (this.#active !== active2)
25611
25821
  return;
25612
25822
  for (const question of questions) {
25613
25823
  if (question.sessionID === this.#session.id)
25614
- this.#openQuestion(active, question);
25824
+ this.#openQuestion(active2, question);
25615
25825
  }
25616
25826
  for (const permission of permissions) {
25617
25827
  if (permission.sessionID === this.#session.id)
25618
- this.#openApproval(active, permission);
25828
+ this.#openApproval(active2, permission);
25619
25829
  }
25620
25830
  const pending = /* @__PURE__ */ new Set([
25621
- ...questions.filter(({ sessionID }) => sessionID === this.#session.id).map(({ id }) => id),
25622
- ...permissions.filter(({ sessionID }) => sessionID === this.#session.id).map(({ id }) => id)
25831
+ ...questions.filter(({ sessionID }) => sessionID === this.#session.id).map(({ id: id2 }) => id2),
25832
+ ...permissions.filter(({ sessionID }) => sessionID === this.#session.id).map(({ id: id2 }) => id2)
25623
25833
  ]);
25624
- for (const [interactionId, interaction] of active.interactions) {
25834
+ for (const [interactionId, interaction] of active2.interactions) {
25625
25835
  if (!pending.has(interaction.nativeId))
25626
- this.#closeInteraction(active, interactionId, "superseded");
25836
+ this.#closeInteraction(active2, interactionId, "superseded");
25627
25837
  }
25628
- active.reconciledAfterReconnect = true;
25838
+ active2.reconciledAfterReconnect = true;
25629
25839
  if (status.type === "idle")
25630
- await this.#reconcileAndFinish(active);
25840
+ await this.#reconcileAndFinish(active2);
25631
25841
  } catch (error51) {
25632
25842
  this.#fault(error51);
25633
25843
  }
25634
25844
  }
25635
- async #reconcileAndFinish(active) {
25636
- if (this.#active !== active || active.kind === "compact")
25845
+ async #reconcileAndFinish(active2) {
25846
+ if (this.#active !== active2 || active2.kind === "compact")
25637
25847
  return;
25638
- if (active.finishing) {
25639
- active.reconcilePending = true;
25848
+ if (active2.finishing) {
25849
+ active2.reconcilePending = true;
25640
25850
  return;
25641
25851
  }
25642
- active.finishing = true;
25852
+ active2.finishing = true;
25643
25853
  try {
25644
25854
  const [status, messages] = await Promise.all([
25645
25855
  this.#transport.getStatus(this.#session.id),
25646
25856
  this.#transport.getMessages(this.#session.id)
25647
25857
  ]);
25648
- if (this.#active !== active || status.type !== "idle")
25858
+ if (this.#active !== active2 || status.type !== "idle")
25649
25859
  return;
25650
- this.#resolveUserMessage(active, messages);
25651
- const lifecycleObserved = active.sawBusy || active.reconciledAfterReconnect || active.cancellationRequested;
25860
+ this.#resolveUserMessage(active2, messages);
25861
+ const lifecycleObserved = active2.sawBusy || active2.reconciledAfterReconnect || active2.cancellationRequested;
25652
25862
  if (!lifecycleObserved)
25653
25863
  return;
25654
- const userIndex = messages.findIndex(({ info }) => info.id === active.userMessageID);
25864
+ const userIndex = messages.findIndex(({ info }) => info.id === active2.userMessageID);
25655
25865
  if (userIndex < 0) {
25656
- if (active.cancellationRequested) {
25657
- this.#completeTurn(active, { status: "cancelled", reason: "Cancelled by user" });
25866
+ if (active2.cancellationRequested) {
25867
+ this.#completeTurn(active2, { status: "cancelled", reason: "Cancelled by user" });
25658
25868
  }
25659
25869
  return;
25660
25870
  }
@@ -25662,41 +25872,41 @@ var OpenCodeHarnessSession = class {
25662
25872
  while (end < messages.length && messages[end]?.info.role !== "user")
25663
25873
  end += 1;
25664
25874
  const assistants = messages.slice(userIndex + 1, end).filter((entry) => entry.info.role === "assistant");
25665
- const terminal = assistants.at(-1)?.info ?? active.terminalAssistant;
25666
- if (!terminal || terminal.time.completed === void 0 && !terminal.finish && !terminal.error && !active.nativeCompleted) {
25667
- if (active.cancellationRequested) {
25875
+ const terminal = assistants.at(-1)?.info ?? active2.terminalAssistant;
25876
+ if (!terminal || terminal.time.completed === void 0 && !terminal.finish && !terminal.error && !active2.nativeCompleted) {
25877
+ if (active2.cancellationRequested) {
25668
25878
  for (const entry of assistants) {
25669
25879
  for (const part of entry.parts)
25670
- this.#projectPart(active, part);
25880
+ this.#projectPart(active2, part);
25671
25881
  }
25672
- this.#completeTurn(active, { status: "cancelled", reason: "Cancelled by user" }, {
25882
+ this.#completeTurn(active2, { status: "cancelled", reason: "Cancelled by user" }, {
25673
25883
  harnessId: this.harnessId,
25674
25884
  nativeSessionId: this.#session.id,
25675
- nativeTurnKey: active.userMessageID,
25885
+ nativeTurnKey: active2.userMessageID,
25676
25886
  formatVersion: 1
25677
25887
  });
25678
- void this.#refreshProjection(active.turnId);
25888
+ void this.#refreshProjection(active2.turnId);
25679
25889
  }
25680
25890
  return;
25681
25891
  }
25682
25892
  for (const entry of assistants) {
25683
25893
  for (const part of entry.parts)
25684
- this.#projectPart(active, part);
25894
+ this.#projectPart(active2, part);
25685
25895
  }
25686
- active.terminalAssistant = terminal;
25687
- const userMessageID = active.userMessageID;
25896
+ active2.terminalAssistant = terminal;
25897
+ const userMessageID = active2.userMessageID;
25688
25898
  const changes = reliableOpenCodeFileChanges(await readTurnDiff(this.#transport, this.#session.id, userMessageID, turnNativePatchFiles(messages, userMessageID)));
25689
25899
  if (changes.length > 0) {
25690
- const id = `opencode-live-diff:${active.userMessageID}`;
25691
- if (!active.items.has(id)) {
25900
+ const id2 = `opencode-live-diff:${active2.userMessageID}`;
25901
+ if (!active2.items.has(id2)) {
25692
25902
  const item = {
25693
25903
  type: "fileChange",
25694
- itemId: hostItemIdSchema.parse(id),
25695
- sourceItemIds: [...active.items.values()].map(({ item: item2 }) => item2.itemId),
25904
+ itemId: hostItemIdSchema.parse(id2),
25905
+ sourceItemIds: [...active2.items.values()].map(({ item: item2 }) => item2.itemId),
25696
25906
  changes
25697
25907
  };
25698
- active.items.set(id, { item, completed: false });
25699
- this.#event({ type: "item.started", turnId: active.turnId, item });
25908
+ active2.items.set(id2, { item, completed: false });
25909
+ this.#event({ type: "item.started", turnId: active2.turnId, item });
25700
25910
  }
25701
25911
  }
25702
25912
  const checkpoint = nativeCheckpointRefSchema.parse({
@@ -25708,10 +25918,10 @@ var OpenCodeHarnessSession = class {
25708
25918
  const nativeTurnRef = {
25709
25919
  harnessId: this.harnessId,
25710
25920
  nativeSessionId: this.#session.id,
25711
- nativeTurnKey: active.userMessageID,
25921
+ nativeTurnKey: active2.userMessageID,
25712
25922
  formatVersion: 1
25713
25923
  };
25714
- const outcome = active.cancellationRequested || terminal.error?.name === "MessageAbortedError" ? { status: "cancelled", reason: "Cancelled by user", checkpoint } : terminal.error ? {
25924
+ const outcome = active2.cancellationRequested || terminal.error?.name === "MessageAbortedError" ? { status: "cancelled", reason: "Cancelled by user", checkpoint } : terminal.error ? {
25715
25925
  status: "failed",
25716
25926
  error: {
25717
25927
  code: terminal.error.name === "ProviderAuthError" ? "authenticationRequired" : "nativeFailure",
@@ -25720,54 +25930,54 @@ var OpenCodeHarnessSession = class {
25720
25930
  },
25721
25931
  checkpoint
25722
25932
  } : { status: "succeeded", checkpoint };
25723
- this.#completeTurn(active, outcome, nativeTurnRef);
25724
- void this.#refreshProjection(active.turnId);
25933
+ this.#completeTurn(active2, outcome, nativeTurnRef);
25934
+ void this.#refreshProjection(active2.turnId);
25725
25935
  } catch (error51) {
25726
- if (this.#active === active) {
25727
- this.#completeTurn(active, {
25936
+ if (this.#active === active2) {
25937
+ this.#completeTurn(active2, {
25728
25938
  status: "failed",
25729
25939
  error: normalizeError(error51, "protocolError")
25730
25940
  });
25731
25941
  }
25732
25942
  } finally {
25733
- active.finishing = false;
25734
- if (active.reconcilePending && this.#active === active && !active.finished) {
25735
- active.reconcilePending = false;
25736
- void this.#reconcileAndFinish(active);
25943
+ active2.finishing = false;
25944
+ if (active2.reconcilePending && this.#active === active2 && !active2.finished) {
25945
+ active2.reconcilePending = false;
25946
+ void this.#reconcileAndFinish(active2);
25737
25947
  }
25738
25948
  }
25739
25949
  }
25740
- #completeLiveItem(active, key, outcome) {
25741
- const live = active.items.get(key);
25950
+ #completeLiveItem(active2, key, outcome) {
25951
+ const live = active2.items.get(key);
25742
25952
  if (!live || live.completed)
25743
25953
  return;
25744
25954
  live.completed = true;
25745
25955
  this.#event({
25746
25956
  type: "item.completed",
25747
- turnId: active.turnId,
25957
+ turnId: active2.turnId,
25748
25958
  snapshot: { item: live.item, outcome }
25749
25959
  });
25750
25960
  }
25751
- #completeTurn(active, outcome, nativeTurnRef) {
25752
- if (this.#active !== active || active.finished || !active.admissionCompleted)
25961
+ #completeTurn(active2, outcome, nativeTurnRef) {
25962
+ if (this.#active !== active2 || active2.finished || !active2.admissionCompleted)
25753
25963
  return;
25754
- active.finished = true;
25964
+ active2.finished = true;
25755
25965
  this.#active = null;
25756
- for (const interactionId of [...active.interactions.keys()]) {
25757
- this.#closeInteraction(active, interactionId, outcome.status === "succeeded" ? "superseded" : "cancelled");
25966
+ for (const interactionId of [...active2.interactions.keys()]) {
25967
+ this.#closeInteraction(active2, interactionId, outcome.status === "succeeded" ? "superseded" : "cancelled");
25758
25968
  }
25759
25969
  const itemOutcome = itemOutcomeForTurn(outcome);
25760
- for (const [key, live] of active.items) {
25970
+ for (const [key, live] of active2.items) {
25761
25971
  if (!live.completed)
25762
- this.#completeLiveItem(active, key, itemOutcome);
25972
+ this.#completeLiveItem(active2, key, itemOutcome);
25763
25973
  }
25764
25974
  this.#event({
25765
25975
  type: "turn.completed",
25766
- turnId: active.turnId,
25976
+ turnId: active2.turnId,
25767
25977
  outcome,
25768
25978
  ...nativeTurnRef ? { nativeTurnRef } : {}
25769
25979
  });
25770
- active.resolveCompletion();
25980
+ active2.resolveCompletion();
25771
25981
  }
25772
25982
  #createActive(kind, turnId, userMessageID) {
25773
25983
  let resolveCompletion = () => void 0;
@@ -25805,26 +26015,26 @@ var OpenCodeHarnessSession = class {
25805
26015
  resolveCompletion
25806
26016
  };
25807
26017
  }
25808
- #flushAdmission(active) {
25809
- if (!active.admissionCompleted || this.#active !== active)
26018
+ #flushAdmission(active2) {
26019
+ if (!active2.admissionCompleted || this.#active !== active2)
25810
26020
  return;
25811
- active.admissionBuffer.sort((left, right) => left.sequence - right.sequence);
25812
- for (const { output } of active.admissionBuffer.splice(0))
26021
+ active2.admissionBuffer.sort((left, right) => left.sequence - right.sequence);
26022
+ for (const { output } of active2.admissionBuffer.splice(0))
25813
26023
  this.#channel.emit(output);
25814
26024
  }
25815
- #failAdmission(active, error51) {
25816
- if (this.#active !== active || active.admissionCompleted || active.finished)
26025
+ #failAdmission(active2, error51) {
26026
+ if (this.#active !== active2 || active2.admissionCompleted || active2.finished)
25817
26027
  return;
25818
- active.admissionBuffer.length = 0;
25819
- active.admissionFailure = error51;
25820
- active.finished = true;
26028
+ active2.admissionBuffer.length = 0;
26029
+ active2.admissionFailure = error51;
26030
+ active2.finished = true;
25821
26031
  this.#active = null;
25822
- active.resolveAdmissionFailure(error51);
25823
- active.resolveCompletion();
26032
+ active2.resolveAdmissionFailure(error51);
26033
+ active2.resolveCompletion();
25824
26034
  }
25825
26035
  async #refreshProjection(observedForTurnId) {
25826
26036
  try {
25827
- const projection = await readProjection(this.#transport, this.#session.id, this.#providerCatalog, this.#toolOutputLimit);
26037
+ const projection = await readProjection(this.#transport, this.#session.id, this.#providerCatalog, this.#toolOutputLimit, this.#modelCatalog.index);
25828
26038
  this.#applyProjection(projection, observedForTurnId);
25829
26039
  } catch {
25830
26040
  }
@@ -25862,12 +26072,12 @@ var OpenCodeHarnessSession = class {
25862
26072
  return;
25863
26073
  const normalized = normalizeError(error51, "internalError");
25864
26074
  if (this.#active && !this.#active.admissionCompleted) {
25865
- const active = this.#active;
25866
- active.admissionBuffer.length = 0;
25867
- active.admissionFailure = normalized;
25868
- active.resolveAdmissionFailure(normalized);
25869
- active.finished = true;
25870
- active.resolveCompletion();
26075
+ const active2 = this.#active;
26076
+ active2.admissionBuffer.length = 0;
26077
+ active2.admissionFailure = normalized;
26078
+ active2.resolveAdmissionFailure(normalized);
26079
+ active2.finished = true;
26080
+ active2.resolveCompletion();
25871
26081
  this.#active = null;
25872
26082
  } else if (this.#active) {
25873
26083
  this.#completeTurn(this.#active, { status: "failed", error: normalized });
@@ -25882,12 +26092,12 @@ var OpenCodeHarnessSession = class {
25882
26092
  const faulted = this.#phase === "faulted";
25883
26093
  if (!faulted)
25884
26094
  this.#phase = "closing";
25885
- const active = this.#active;
25886
- if (active) {
25887
- active.cancellationRequested = true;
26095
+ const active2 = this.#active;
26096
+ if (active2) {
26097
+ active2.cancellationRequested = true;
25888
26098
  await this.#transport.abort(this.#session.id).catch(() => void 0);
25889
26099
  await Promise.race([
25890
- active.completion,
26100
+ active2.completion,
25891
26101
  new Promise((resolve) => setTimeout(resolve, this.#closeTimeoutMs))
25892
26102
  ]);
25893
26103
  }
@@ -25905,9 +26115,9 @@ var OpenCodeHarnessSession = class {
25905
26115
  }
25906
26116
  }
25907
26117
  #output(output) {
25908
- const active = this.#active;
25909
- if (active && !active.admissionCompleted) {
25910
- active.admissionBuffer.push({ output, sequence: active.admissionSequence++ });
26118
+ const active2 = this.#active;
26119
+ if (active2 && !active2.admissionCompleted) {
26120
+ active2.admissionBuffer.push({ output, sequence: active2.admissionSequence++ });
25911
26121
  return;
25912
26122
  }
25913
26123
  this.#channel.emit(output);
@@ -25915,29 +26125,29 @@ var OpenCodeHarnessSession = class {
25915
26125
  #event(event) {
25916
26126
  this.#output({ kind: "event", event });
25917
26127
  }
25918
- #bindUserMessage(active, messageID) {
25919
- if (active.userMessageID)
25920
- return active.userMessageID === messageID;
25921
- if (active.preexistingUserMessageIds.has(messageID))
26128
+ #bindUserMessage(active2, messageID) {
26129
+ if (active2.userMessageID)
26130
+ return active2.userMessageID === messageID;
26131
+ if (active2.preexistingUserMessageIds.has(messageID))
25922
26132
  return false;
25923
- active.userMessageID = messageID;
26133
+ active2.userMessageID = messageID;
25924
26134
  this.#knownUserMessageIds.add(messageID);
25925
26135
  return true;
25926
26136
  }
25927
- #resolveUserMessage(active, messages) {
25928
- if (active.userMessageID)
26137
+ #resolveUserMessage(active2, messages) {
26138
+ if (active2.userMessageID)
25929
26139
  return;
25930
- const candidates = messages.filter(({ info }) => info.role === "user" && !active.preexistingUserMessageIds.has(info.id));
26140
+ const candidates = messages.filter(({ info }) => info.role === "user" && !active2.preexistingUserMessageIds.has(info.id));
25931
26141
  const [candidate2] = candidates;
25932
26142
  if (candidates.length === 1 && candidate2) {
25933
- this.#bindUserMessage(active, candidate2.info.id);
26143
+ this.#bindUserMessage(active2, candidate2.info.id);
25934
26144
  return;
25935
26145
  }
25936
26146
  const parents = new Set(messages.filter(({ info }) => info.role === "assistant").map(({ info }) => info.parentID));
25937
26147
  const linked = candidates.filter(({ info }) => parents.has(info.id));
25938
26148
  const [linkedCandidate] = linked;
25939
26149
  if (linked.length === 1 && linkedCandidate) {
25940
- this.#bindUserMessage(active, linkedCandidate.info.id);
26150
+ this.#bindUserMessage(active2, linkedCandidate.info.id);
25941
26151
  return;
25942
26152
  }
25943
26153
  if (candidates.length > 1) {
@@ -25966,7 +26176,15 @@ var OpenCodeAdapter = class {
25966
26176
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
25967
26177
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS2;
25968
26178
  }
25969
- async inspect(input = {}) {
26179
+ async inspect(input = {}, onModels) {
26180
+ const result = await this.#inspect(input);
26181
+ if (result.status !== "ready")
26182
+ return result;
26183
+ const { index, ...inspection } = result;
26184
+ onModels?.({ catalog: result.catalog, index });
26185
+ return inspection;
26186
+ }
26187
+ async #inspect(input) {
25970
26188
  if (this.#closePromise) {
25971
26189
  return {
25972
26190
  status: "unavailable",
@@ -25975,15 +26193,19 @@ var OpenCodeAdapter = class {
25975
26193
  }
25976
26194
  const cwd = input.cwd ?? process.cwd();
25977
26195
  const inFlight = this.#inspectionInFlight.get(cwd);
26196
+ if (input.refresh) {
26197
+ this.#inspectionCache.clear();
26198
+ this.#inspectionInFlight.clear();
26199
+ if (inFlight)
26200
+ this.#inspectionInFlight.set(cwd, inFlight);
26201
+ }
25978
26202
  if (inFlight)
25979
26203
  return inFlight;
25980
- if (!input.refresh) {
25981
- const cached2 = this.#inspectionCache.get(cwd);
25982
- if (cached2)
25983
- return cached2;
25984
- }
26204
+ const cached2 = this.#inspectionCache.get(cwd);
26205
+ if (cached2)
26206
+ return cached2;
25985
26207
  const inspection = this.#inspectCwd(cwd).then((result) => {
25986
- if (result.status === "ready")
26208
+ if (result.status === "ready" && this.#inspectionInFlight.get(cwd) === inspection)
25987
26209
  this.#inspectionCache.set(cwd, result);
25988
26210
  return result;
25989
26211
  });
@@ -26005,10 +26227,11 @@ var OpenCodeAdapter = class {
26005
26227
  }
26006
26228
  stage = "model-catalog";
26007
26229
  const providers = await transport.providers();
26008
- const catalog = normalizeOpenCodeModelCatalog(providers);
26230
+ const { catalog, index } = normalizeOpenCodeModelCatalog(providers);
26009
26231
  return {
26010
26232
  status: "ready",
26011
26233
  catalog,
26234
+ index,
26012
26235
  capabilities: {
26013
26236
  configuration: {
26014
26237
  selectModel: catalog.models.length > 0,
@@ -26099,11 +26322,8 @@ var OpenCodeAdapter = class {
26099
26322
  const modelCatalog = normalizeOpenCodeModelCatalog(providers);
26100
26323
  let session;
26101
26324
  if (input.kind === "create") {
26102
- const model2 = input.model ? decodeOpenCodeModelRef(input.model) : void 0;
26325
+ const model2 = input.model ? decodeOpenCodeModelRef(input.model, modelCatalog.index) : void 0;
26103
26326
  const variant = input.thinkingOptionId ? decodeOpenCodeVariant(input.thinkingOptionId) : void 0;
26104
- if (input.model && !modelCatalog.models.some(({ ref }) => ref.id === input.model?.id)) {
26105
- throw new OpenCodeTransportError("protocolError", "Requested OpenCode Model is absent from the connected Provider catalog");
26106
- }
26107
26327
  const permission = requestedPermissionMode && requestedPermissionMode !== "default" ? requestedPermissionRules(void 0, requestedPermissionMode) : void 0;
26108
26328
  session = await transport.createSession({
26109
26329
  ...model2 ? { model: model2 } : {},
@@ -26147,6 +26367,7 @@ var OpenCodeAdapter = class {
26147
26367
  source,
26148
26368
  input,
26149
26369
  providers,
26370
+ modelIndex: modelCatalog.index,
26150
26371
  toolOutputLimit: this.#toolOutputLimit,
26151
26372
  onCreated: (candidate2) => {
26152
26373
  createdForCleanup = candidate2;
@@ -26154,7 +26375,7 @@ var OpenCodeAdapter = class {
26154
26375
  });
26155
26376
  }
26156
26377
  }
26157
- const projection = await readProjection(transport, session.id, providers, this.#toolOutputLimit);
26378
+ const projection = await readProjection(transport, session.id, providers, this.#toolOutputLimit, modelCatalog.index);
26158
26379
  const harnessSession = new OpenCodeHarnessSession({
26159
26380
  transport,
26160
26381
  connection,
@@ -26265,32 +26486,37 @@ function v2Locator(ref) {
26265
26486
  function v2Catalog(models, defaultModel) {
26266
26487
  const enabled = models.filter((model2) => model2.enabled);
26267
26488
  const variants = [...new Set(enabled.flatMap((model2) => model2.variants.map((v) => v.id)))].sort();
26268
- const ref = (model2) => encodeOpenCodeModelRef({ providerID: model2.providerID, modelID: model2.id });
26269
- return harnessModelCatalogSchema.parse({
26270
- models: enabled.map((model2) => ({
26271
- ref: ref(model2),
26272
- label: `${model2.providerID} / ${model2.name}`,
26273
- resolvedModelLabel: `${model2.providerID}/${model2.id}`,
26274
- supportedThinkingOptionIds: [
26275
- encodeOpenCodeVariant(void 0),
26276
- ...model2.variants.map((v) => encodeOpenCodeVariant(v.id))
26277
- ]
26278
- })),
26279
- ...defaultModel && enabled.some((m) => ref(m).id === ref(defaultModel).id) ? { defaultModel: ref(defaultModel) } : {},
26280
- thinkingOptions: [void 0, ...variants].map((v) => ({
26281
- id: encodeOpenCodeVariant(v),
26282
- label: v ?? "Default"
26283
- })),
26284
- defaultThinkingOptionId: encodeOpenCodeVariant(void 0)
26285
- });
26489
+ const identity2 = (model2) => ({ providerID: model2.providerID, modelID: model2.id });
26490
+ const index = openCodeModelIndex(enabled.map(identity2));
26491
+ const ref = (model2) => index.encode(identity2(model2));
26492
+ return {
26493
+ catalog: harnessModelCatalogSchema.parse({
26494
+ models: enabled.map((model2) => ({
26495
+ ref: ref(model2),
26496
+ label: `${model2.providerID} / ${model2.name}`,
26497
+ resolvedModelLabel: `${model2.providerID}/${model2.id}`,
26498
+ supportedThinkingOptionIds: [
26499
+ encodeOpenCodeVariant(void 0),
26500
+ ...model2.variants.map((v) => encodeOpenCodeVariant(v.id))
26501
+ ]
26502
+ })),
26503
+ ...defaultModel && enabled.some((m) => ref(m).id === ref(defaultModel).id) ? { defaultModel: ref(defaultModel) } : {},
26504
+ thinkingOptions: [void 0, ...variants].map((v) => ({
26505
+ id: encodeOpenCodeVariant(v),
26506
+ label: v ?? "Default"
26507
+ })),
26508
+ defaultThinkingOptionId: encodeOpenCodeVariant(void 0)
26509
+ }),
26510
+ index
26511
+ };
26286
26512
  }
26287
26513
  function v2Permissions(current = [], mode) {
26288
26514
  const selected = decodeOpenCodePermissionModeId(mode);
26289
26515
  const rules = current.filter((rule) => !(rule.action === "*" && rule.resource === "*" && ["allow", "ask"].includes(rule.effect)));
26290
26516
  return selected === "default" ? rules : [...rules, { action: "*", resource: "*", effect: selected }];
26291
26517
  }
26292
- function v2State(session, catalog, policy) {
26293
- const model2 = session.model ? encodeOpenCodeModelRef({ providerID: session.model.providerID, modelID: session.model.id }) : void 0;
26518
+ function v2State(session, { catalog, index }, policy) {
26519
+ const model2 = session.model ? encodeOpenCodeModelRef({ providerID: session.model.providerID, modelID: session.model.id }, index) : void 0;
26294
26520
  const entry = catalog.models.find((candidate2) => candidate2.ref.id === model2?.id);
26295
26521
  const mode = session.permissions?.findLast((rule) => rule.action === "*" && rule.resource === "*");
26296
26522
  return {
@@ -26305,8 +26531,8 @@ function v2State(session, catalog, policy) {
26305
26531
  };
26306
26532
  }
26307
26533
  function effectiveVariant(variant, entry) {
26308
- const id = encodeOpenCodeVariant(variant);
26309
- return variant === "default" && !entry.supportedThinkingOptionIds?.includes(id) ? encodeOpenCodeVariant(void 0) : id;
26534
+ const id2 = encodeOpenCodeVariant(variant);
26535
+ return variant === "default" && !entry.supportedThinkingOptionIds?.includes(id2) ? encodeOpenCodeVariant(void 0) : id2;
26310
26536
  }
26311
26537
  function decodeMode(effect) {
26312
26538
  return effect === "allow" || effect === "ask" ? harnessPermissionModeIdSchema.parse(effect) : harnessPermissionModeIdSchema.parse("default");
@@ -26330,7 +26556,7 @@ async function readCatalog(client2, cwd, timeoutMs) {
26330
26556
  const required2 = ["opencode.config.provider", "opencode.config.agent", "opencode.config.policy"];
26331
26557
  while (true) {
26332
26558
  const { data: plugins } = await client2.plugin.list({ location });
26333
- const config2 = required2.map((id) => plugins.find((plugin) => plugin.id === id));
26559
+ const config2 = required2.map((id2) => plugins.find((plugin) => plugin.id === id2));
26334
26560
  const failed = config2.find((plugin) => plugin?.state.status === "failed");
26335
26561
  if (failed?.state.status === "failed")
26336
26562
  throw new Error(`OpenCode configuration failed: ${failed.state.error}`);
@@ -28214,7 +28440,7 @@ function assistantItems2(message, limit) {
28214
28440
  };
28215
28441
  });
28216
28442
  }
28217
- function projectHistory(session, messages, limit) {
28443
+ function projectHistory(session, messages, limit, index) {
28218
28444
  if (session.revert)
28219
28445
  throw new Error("Clear the staged OpenCode v2 revert before using this Session in codexhost");
28220
28446
  const turns = [];
@@ -28244,7 +28470,7 @@ function projectHistory(session, messages, limit) {
28244
28470
  turn.model = encodeOpenCodeModelRef({
28245
28471
  providerID: message.model.providerID,
28246
28472
  modelID: message.model.id
28247
- });
28473
+ }, index);
28248
28474
  } else if (message.type === "compaction") {
28249
28475
  turn.items.push({
28250
28476
  item: { type: "contextCompaction", itemId: hostItemIdSchema.parse(message.id) },
@@ -28305,9 +28531,9 @@ function fileChanges(session, turn, diffs) {
28305
28531
  outcome: { status: "succeeded" }
28306
28532
  };
28307
28533
  }
28308
- async function readHistory(client2, session, limit) {
28534
+ async function readHistory(client2, session, limit, index) {
28309
28535
  const messages = await readMessages(client2, session.id);
28310
- const snapshot = projectHistory(session, messages, limit);
28536
+ const snapshot = projectHistory(session, messages, limit, index);
28311
28537
  for (const turn of snapshot.turns) {
28312
28538
  if (!turn.checkpoint)
28313
28539
  continue;
@@ -28372,7 +28598,7 @@ function existingDirectory(directory) {
28372
28598
  return null;
28373
28599
  }
28374
28600
  }
28375
- function candidate(info, active) {
28601
+ function candidate(info, active2) {
28376
28602
  if (info.parentID || info.time.archived !== void 0)
28377
28603
  return null;
28378
28604
  const cwd = existingDirectory(info.location.directory);
@@ -28384,11 +28610,11 @@ function candidate(info, active) {
28384
28610
  title: sessionImportTitle(info.title),
28385
28611
  updatedAt: info.time.updated,
28386
28612
  // This server only knows its own executions; another process may still hold the Session.
28387
- running: active[info.id] ? true : null
28613
+ running: active2[info.id] ? true : null
28388
28614
  });
28389
28615
  }
28390
28616
  async function listV2SessionCandidates(client2) {
28391
- const active = await client2.session.active();
28617
+ const active2 = await client2.session.active();
28392
28618
  const candidates = /* @__PURE__ */ new Map();
28393
28619
  const cursors = /* @__PURE__ */ new Set();
28394
28620
  let cursor;
@@ -28398,7 +28624,7 @@ async function listV2SessionCandidates(client2) {
28398
28624
  ...cursor ? { cursor } : {}
28399
28625
  });
28400
28626
  for (const info of response.data) {
28401
- const entry = candidate(info, active);
28627
+ const entry = candidate(info, active2);
28402
28628
  if (entry)
28403
28629
  candidates.set(entry.nativeSessionId, entry);
28404
28630
  }
@@ -28411,7 +28637,7 @@ async function listV2SessionCandidates(client2) {
28411
28637
  return [...candidates.values()];
28412
28638
  }
28413
28639
  async function resolveV2SessionCandidate(client2, nativeSessionId) {
28414
- const active = await client2.session.active();
28640
+ const active2 = await client2.session.active();
28415
28641
  const cursors = /* @__PURE__ */ new Set();
28416
28642
  let cursor;
28417
28643
  for (let page = 0; page < MAX_PAGES; page += 1) {
@@ -28421,7 +28647,7 @@ async function resolveV2SessionCandidate(client2, nativeSessionId) {
28421
28647
  });
28422
28648
  const info = response.data.find((entry) => entry.id === nativeSessionId);
28423
28649
  if (info) {
28424
- const entry = candidate(info, active);
28650
+ const entry = candidate(info, active2);
28425
28651
  return entry ? { candidate: entry, nativeRef: v2Ref(info, "default") } : null;
28426
28652
  }
28427
28653
  const next = response.cursor.next;
@@ -28576,7 +28802,7 @@ var V2Session = class {
28576
28802
  client;
28577
28803
  connection;
28578
28804
  info;
28579
- catalog;
28805
+ models;
28580
28806
  policy;
28581
28807
  limit;
28582
28808
  onClosed;
@@ -28598,17 +28824,17 @@ var V2Session = class {
28598
28824
  #cacheHitRatePercent;
28599
28825
  /** Assistant messages already published as usage requests. */
28600
28826
  #meteredMessages = /* @__PURE__ */ new Set();
28601
- constructor(client2, connection, info, catalog, policy, limit, onClosed) {
28827
+ constructor(client2, connection, info, models, policy, limit, onClosed) {
28602
28828
  this.client = client2;
28603
28829
  this.connection = connection;
28604
28830
  this.info = info;
28605
- this.catalog = catalog;
28831
+ this.models = models;
28606
28832
  this.policy = policy;
28607
28833
  this.limit = limit;
28608
28834
  this.onClosed = onClosed;
28609
- this.initialState = v2State(info, catalog, policy);
28835
+ this.initialState = v2State(info, models, policy);
28610
28836
  this.initialUsage = v2Usage(info);
28611
- this.capabilities = v2Capabilities(catalog);
28837
+ this.capabilities = v2Capabilities(models.catalog);
28612
28838
  this.commands = {
28613
28839
  list: async () => ({ ok: true, value: openCodeCommandCatalog }),
28614
28840
  execute: async (command) => {
@@ -28654,10 +28880,10 @@ var V2Session = class {
28654
28880
  return { ok: false, error: failure("OpenCode Session is busy", "sessionBusy") };
28655
28881
  try {
28656
28882
  this.info = await this.client.session.get({ sessionID: this.info.id });
28657
- const { snapshot } = await readHistory(this.client, this.info, this.limit);
28883
+ const { snapshot } = await readHistory(this.client, this.info, this.limit, this.models.index);
28658
28884
  return {
28659
28885
  ok: true,
28660
- value: { ...snapshot, state: v2State(this.info, this.catalog, this.policy) }
28886
+ value: { ...snapshot, state: v2State(this.info, this.models, this.policy) }
28661
28887
  };
28662
28888
  } catch (error51) {
28663
28889
  return errorResult(error51);
@@ -28671,8 +28897,8 @@ var V2Session = class {
28671
28897
  if (command.type === "turn.start")
28672
28898
  return this.#start(command, false);
28673
28899
  if (command.type === "turn.cancel") {
28674
- const active = this.#active;
28675
- if (!active?.admitted || active.turnId !== command.turnId)
28900
+ const active2 = this.#active;
28901
+ if (!active2?.admitted || active2.turnId !== command.turnId)
28676
28902
  return { ok: false, error: failure("No matching OpenCode Turn", "invalidState") };
28677
28903
  try {
28678
28904
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false });
@@ -28683,22 +28909,22 @@ var V2Session = class {
28683
28909
  }
28684
28910
  }
28685
28911
  if (command.type === "interaction.respond") {
28686
- const active = this.#active;
28687
- const pending = active?.interactions.get(command.interactionId);
28688
- if (!active || !pending || active.replying.has(command.interactionId))
28912
+ const active2 = this.#active;
28913
+ const pending = active2?.interactions.get(command.interactionId);
28914
+ if (!active2 || !pending || active2.replying.has(command.interactionId))
28689
28915
  return {
28690
28916
  ok: false,
28691
28917
  error: failure("OpenCode interaction is no longer pending", "invalidState")
28692
28918
  };
28693
- active.replying.add(command.interactionId);
28919
+ active2.replying.add(command.interactionId);
28694
28920
  try {
28695
28921
  await replyInteraction(this.client, pending, command);
28696
- this.#closeInteraction(active, command.interactionId, command.response.type === "question" && command.response.cancelled ? "cancelled" : "responded");
28922
+ this.#closeInteraction(active2, command.interactionId, command.response.type === "question" && command.response.cancelled ? "cancelled" : "responded");
28697
28923
  return { ok: true, value: { accepted: true } };
28698
28924
  } catch (error51) {
28699
28925
  return errorResult(error51);
28700
28926
  } finally {
28701
- active.replying.delete(command.interactionId);
28927
+ active2.replying.delete(command.interactionId);
28702
28928
  }
28703
28929
  }
28704
28930
  if (this.#active || this.#configuring)
@@ -28715,14 +28941,12 @@ var V2Session = class {
28715
28941
  } else {
28716
28942
  let model2 = this.info.model;
28717
28943
  if (command.type === "model.select") {
28718
- if (!this.catalog.models.some((m) => m.ref.id === command.model.id))
28719
- throw new Error("OpenCode Model is not available");
28720
- const decoded = decodeOpenCodeModelRef(command.model);
28944
+ const decoded = decodeOpenCodeModelRef(command.model, this.models.index);
28721
28945
  model2 = { providerID: decoded.providerID, id: decoded.modelID };
28722
28946
  } else {
28723
28947
  if (!model2)
28724
28948
  throw new Error("Select a Model before a Thinking option");
28725
- const state = v2State(this.info, this.catalog, this.policy);
28949
+ const state = v2State(this.info, this.models, this.policy);
28726
28950
  if (!state.availableThinkingOptions?.some((v) => v.id === command.thinkingOptionId))
28727
28951
  throw new Error("Thinking option is unavailable for this Model");
28728
28952
  const variant = decodeOpenCodeVariant(command.thinkingOptionId);
@@ -28733,7 +28957,7 @@ var V2Session = class {
28733
28957
  this.info = await this.client.session.get({ sessionID: this.info.id });
28734
28958
  this.#emit({
28735
28959
  type: "session.state.changed",
28736
- state: v2State(this.info, this.catalog, this.policy)
28960
+ state: v2State(this.info, this.models, this.policy)
28737
28961
  });
28738
28962
  return { ok: true, value: { completed: true } };
28739
28963
  } catch (error51) {
@@ -28754,7 +28978,7 @@ var V2Session = class {
28754
28978
  const done = new Promise((r) => {
28755
28979
  resolve = r;
28756
28980
  });
28757
- const active = {
28981
+ const active2 = {
28758
28982
  turnId: command.turnId,
28759
28983
  compact,
28760
28984
  admitted: false,
@@ -28769,16 +28993,16 @@ var V2Session = class {
28769
28993
  done,
28770
28994
  resolve
28771
28995
  };
28772
- this.#active = active;
28996
+ this.#active = active2;
28773
28997
  let attempted = false;
28774
28998
  try {
28775
28999
  if ((await this.client.session.active())[this.info.id])
28776
29000
  throw new Error("OpenCode Session is already running");
28777
29001
  this.info = await this.client.session.get({ sessionID: this.info.id });
28778
- const before = await readHistory(this.client, this.info, this.limit);
29002
+ const before = await readHistory(this.client, this.info, this.limit, this.models.index);
28779
29003
  if (before.snapshot.turns.some((turn) => turn.outcome.status === "unknown"))
28780
29004
  throw new Error("OpenCode history contains an incomplete execution");
28781
- active.baseline = new Set(before.snapshot.turns.map((t) => t.nativeTurnRef.nativeTurnKey));
29005
+ active2.baseline = new Set(before.snapshot.turns.map((t) => t.nativeTurnRef.nativeTurnKey));
28782
29006
  attempted = true;
28783
29007
  if (compact)
28784
29008
  await this.client.session.compact({ sessionID: this.info.id });
@@ -28787,56 +29011,56 @@ var V2Session = class {
28787
29011
  sessionID: this.info.id,
28788
29012
  text: command.input.map((p) => p.text).join("\n"),
28789
29013
  delivery: "queue",
28790
- metadata: { "codexhost.turnId": active.turnId }
29014
+ metadata: { "codexhost.turnId": active2.turnId }
28791
29015
  });
28792
29016
  if (this.#closed) {
28793
29017
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false });
28794
29018
  throw new Error("OpenCode Session closed during admission");
28795
29019
  }
28796
- active.admitted = true;
28797
- this.#emit({ type: "turn.started", turnId: active.turnId });
28798
- for (const item of active.transient.values())
28799
- this.#projectItem(active, { item, outcome: { status: "succeeded" } }, false);
29020
+ active2.admitted = true;
29021
+ this.#emit({ type: "turn.started", turnId: active2.turnId });
29022
+ for (const item of active2.transient.values())
29023
+ this.#projectItem(active2, { item, outcome: { status: "succeeded" } }, false);
28800
29024
  void this.#refresh();
28801
- return { ok: true, value: { turnId: active.turnId } };
29025
+ return { ok: true, value: { turnId: active2.turnId } };
28802
29026
  } catch (error51) {
28803
29027
  if (attempted)
28804
29028
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false }).catch((interruptError) => this.#fault(errorResult(interruptError).error));
28805
- if (this.#active === active)
29029
+ if (this.#active === active2)
28806
29030
  this.#active = void 0;
28807
- active.resolve();
29031
+ active2.resolve();
28808
29032
  return errorResult(error51);
28809
29033
  }
28810
29034
  }
28811
29035
  #onEvent(event) {
28812
- const active = this.#active;
28813
- if (!active || !("data" in event) || !("sessionID" in event.data) || event.data.sessionID !== this.info.id)
29036
+ const active2 = this.#active;
29037
+ if (!active2 || !("data" in event) || !("sessionID" in event.data) || event.data.sessionID !== this.info.id)
28814
29038
  return;
28815
29039
  if (FIRST_OUTPUT_EVENTS.has(event.type) && "assistantMessageID" in event.data && typeof event.data.assistantMessageID === "string" && !this.#meteredMessages.has(event.data.assistantMessageID) && (!event.type.endsWith(".delta") || "delta" in event.data && event.data.delta.length > 0)) {
28816
- const id = event.data.assistantMessageID;
28817
- const timing = active.outputTiming.get(id) ?? {
29040
+ const id2 = event.data.assistantMessageID;
29041
+ const timing = active2.outputTiming.get(id2) ?? {
28818
29042
  firstOutputAtMs: Date.now(),
28819
29043
  reasoningObserved: false
28820
29044
  };
28821
29045
  if (event.type === "session.reasoning.started" || event.type === "session.reasoning.delta")
28822
29046
  timing.reasoningObserved = true;
28823
- active.outputTiming.set(id, timing);
29047
+ active2.outputTiming.set(id2, timing);
28824
29048
  }
28825
29049
  if (event.type === "session.step.started")
28826
- active.assistants.add(event.data.assistantMessageID);
28827
- if ((event.type === "session.text.delta" || event.type === "session.reasoning.delta") && active.assistants.has(event.data.assistantMessageID)) {
29050
+ active2.assistants.add(event.data.assistantMessageID);
29051
+ if ((event.type === "session.text.delta" || event.type === "session.reasoning.delta") && active2.assistants.has(event.data.assistantMessageID)) {
28828
29052
  const contentType = event.type === "session.text.delta" ? "text" : "reasoning";
28829
29053
  const itemId2 = contentId(event.data.assistantMessageID, contentType, event.data.ordinal);
28830
29054
  const type = contentType === "text" ? "agentMessage" : "reasoning";
28831
- const previous = active.transient.get(itemId2);
29055
+ const previous = active2.transient.get(itemId2);
28832
29056
  const item = {
28833
29057
  type,
28834
29058
  itemId: itemId2,
28835
29059
  text: (previous?.text ?? "") + event.data.delta
28836
29060
  };
28837
- active.transient.set(itemId2, item);
28838
- if (active.admitted)
28839
- this.#projectItem(active, { item, outcome: { status: "succeeded" } }, false);
29061
+ active2.transient.set(itemId2, item);
29062
+ if (active2.admitted)
29063
+ this.#projectItem(active2, { item, outcome: { status: "succeeded" } }, false);
28840
29064
  }
28841
29065
  if (!event.type.endsWith(".delta"))
28842
29066
  void this.#refresh();
@@ -28902,31 +29126,31 @@ var V2Session = class {
28902
29126
  });
28903
29127
  }
28904
29128
  async #reconcile() {
28905
- const active = this.#active;
28906
- if (!active?.admitted)
29129
+ const active2 = this.#active;
29130
+ if (!active2?.admitted)
28907
29131
  return;
28908
29132
  const info = await this.client.session.get({ sessionID: this.info.id });
28909
- const { snapshot, messages } = await readHistory(this.client, info, this.limit);
28910
- if (this.#active !== active || this.#closed)
29133
+ const { snapshot, messages } = await readHistory(this.client, info, this.limit, this.models.index);
29134
+ if (this.#active !== active2 || this.#closed)
28911
29135
  return;
28912
29136
  this.info = info;
28913
29137
  this.#meterUsage(messages, false);
28914
- const turns = snapshot.turns.filter((t) => !active.baseline.has(t.nativeTurnRef.nativeTurnKey));
29138
+ const turns = snapshot.turns.filter((t) => !active2.baseline.has(t.nativeTurnRef.nativeTurnKey));
28915
29139
  if (turns.length > 1)
28916
29140
  throw new Error("Concurrent native prompts cannot be assigned to one Host Turn");
28917
29141
  const turn = turns[0];
28918
29142
  if (turn) {
28919
29143
  const prompt = messages.find((message) => message.id === turn.nativeTurnRef.nativeTurnKey);
28920
- if (active.compact ? turn.input.length !== 0 : prompt?.type !== "user" || prompt.metadata?.["codexhost.turnId"] !== active.turnId || turn.input.length !== 1)
29144
+ if (active2.compact ? turn.input.length !== 0 : prompt?.type !== "user" || prompt.metadata?.["codexhost.turnId"] !== active2.turnId || turn.input.length !== 1)
28921
29145
  throw new Error("Concurrent native input cannot be assigned to this Host Turn");
28922
29146
  const terminal = turn.outcome.status !== "unknown";
28923
29147
  for (const item of turn.items)
28924
- this.#projectItem(active, item, terminal, turn.outcome.status === "cancelled" || turn.outcome.status === "failed");
29148
+ this.#projectItem(active2, item, terminal, turn.outcome.status === "cancelled" || turn.outcome.status === "failed");
28925
29149
  if (terminal) {
28926
29150
  if ((await this.client.session.active())[info.id])
28927
29151
  return;
28928
- if (this.#active === active)
28929
- this.#finish(active, turn);
29152
+ if (this.#active === active2)
29153
+ this.#finish(active2, turn);
28930
29154
  return;
28931
29155
  }
28932
29156
  }
@@ -28934,39 +29158,39 @@ var V2Session = class {
28934
29158
  this.client.permission.list({ sessionID: info.id }),
28935
29159
  this.client.session.form.list({ sessionID: info.id })
28936
29160
  ]);
28937
- if (this.#active !== active || this.#closed)
29161
+ if (this.#active !== active2 || this.#closed)
28938
29162
  return;
28939
29163
  const current = /* @__PURE__ */ new Map();
28940
29164
  for (const request of permissions) {
28941
- const pending = permissionInteraction(request, active.turnId);
29165
+ const pending = permissionInteraction(request, active2.turnId);
28942
29166
  current.set(pending.interaction.interactionId, pending);
28943
29167
  }
28944
29168
  for (const form of forms) {
28945
- const pending = formInteraction(form, active.turnId);
29169
+ const pending = formInteraction(form, active2.turnId);
28946
29170
  current.set(pending.interaction.interactionId, pending);
28947
29171
  }
28948
- for (const [id, pending] of current)
28949
- if (!active.interactions.has(id) && !active.settledInteractions.has(id)) {
28950
- active.interactions.set(id, pending);
29172
+ for (const [id2, pending] of current)
29173
+ if (!active2.interactions.has(id2) && !active2.settledInteractions.has(id2)) {
29174
+ active2.interactions.set(id2, pending);
28951
29175
  this.#channel.emit({ kind: "interaction", interaction: pending.interaction });
28952
29176
  }
28953
- for (const id of active.interactions.keys())
28954
- if (!current.has(id) && !active.replying.has(id))
28955
- this.#closeInteraction(active, id, "expired");
29177
+ for (const id2 of active2.interactions.keys())
29178
+ if (!current.has(id2) && !active2.replying.has(id2))
29179
+ this.#closeInteraction(active2, id2, "expired");
28956
29180
  }
28957
- #projectItem(active, snapshot, terminal, interrupted = false) {
29181
+ #projectItem(active2, snapshot, terminal, interrupted = false) {
28958
29182
  const item = snapshot.item;
28959
- const old = active.live.get(item.itemId);
29183
+ const old = active2.live.get(item.itemId);
28960
29184
  if (!old) {
28961
- active.live.set(item.itemId, item);
28962
- this.#emit({ type: "item.started", turnId: active.turnId, item });
29185
+ active2.live.set(item.itemId, item);
29186
+ this.#emit({ type: "item.started", turnId: active2.turnId, item });
28963
29187
  return;
28964
29188
  }
28965
29189
  if ((item.type === "agentMessage" || item.type === "reasoning") && "text" in old) {
28966
29190
  if (old.text.startsWith(item.text) && !terminal)
28967
29191
  return;
28968
29192
  if (terminal && interrupted && old.text.startsWith(item.text)) {
28969
- active.live.set(item.itemId, item);
29193
+ active2.live.set(item.itemId, item);
28970
29194
  return;
28971
29195
  }
28972
29196
  if (!item.text.startsWith(old.text))
@@ -28975,60 +29199,60 @@ var V2Session = class {
28975
29199
  if (delta)
28976
29200
  this.#emit({
28977
29201
  type: "item.updated",
28978
- turnId: active.turnId,
29202
+ turnId: active2.turnId,
28979
29203
  itemId: item.itemId,
28980
29204
  update: { type: "text.append", text: delta }
28981
29205
  });
28982
29206
  } else if (item.type === "toolExecution" && item.output && JSON.stringify(item) !== JSON.stringify(old)) {
28983
29207
  this.#emit({
28984
29208
  type: "item.updated",
28985
- turnId: active.turnId,
29209
+ turnId: active2.turnId,
28986
29210
  itemId: item.itemId,
28987
29211
  update: { type: "output.replace", output: item.output }
28988
29212
  });
28989
29213
  }
28990
- active.live.set(item.itemId, item);
29214
+ active2.live.set(item.itemId, item);
28991
29215
  }
28992
- #finish(active, turn) {
28993
- if (this.#active !== active || turn.outcome.status === "unknown")
29216
+ #finish(active2, turn) {
29217
+ if (this.#active !== active2 || turn.outcome.status === "unknown")
28994
29218
  return;
28995
- for (const id of active.interactions.keys())
28996
- this.#closeInteraction(active, id, "cancelled");
28997
- for (const [id, item] of active.live) {
28998
- const snapshot = turn.items.find((entry) => entry.item.itemId === id) ?? {
29219
+ for (const id2 of active2.interactions.keys())
29220
+ this.#closeInteraction(active2, id2, "cancelled");
29221
+ for (const [id2, item] of active2.live) {
29222
+ const snapshot = turn.items.find((entry) => entry.item.itemId === id2) ?? {
28999
29223
  item,
29000
29224
  outcome: terminalItemOutcome(turn.outcome)
29001
29225
  };
29002
- this.#emit({ type: "item.completed", turnId: active.turnId, snapshot });
29226
+ this.#emit({ type: "item.completed", turnId: active2.turnId, snapshot });
29003
29227
  }
29004
29228
  this.#emit({
29005
29229
  type: "session.state.changed",
29006
- state: v2State(this.info, this.catalog, this.policy)
29230
+ state: v2State(this.info, this.models, this.policy)
29007
29231
  });
29008
29232
  this.#emit({
29009
29233
  type: "session.usage.changed",
29010
29234
  usage: this.#usage(),
29011
- observedForTurnId: active.turnId
29235
+ observedForTurnId: active2.turnId
29012
29236
  });
29013
29237
  this.#active = void 0;
29014
29238
  this.#emit({
29015
29239
  type: "turn.completed",
29016
- turnId: active.turnId,
29240
+ turnId: active2.turnId,
29017
29241
  nativeTurnRef: turn.nativeTurnRef,
29018
29242
  outcome: { ...turn.outcome, ...turn.checkpoint ? { checkpoint: turn.checkpoint } : {} }
29019
29243
  });
29020
- active.resolve();
29244
+ active2.resolve();
29021
29245
  }
29022
- #closeInteraction(active, id, reason) {
29023
- const pending = active.interactions.get(id);
29246
+ #closeInteraction(active2, id2, reason) {
29247
+ const pending = active2.interactions.get(id2);
29024
29248
  if (!pending)
29025
29249
  return;
29026
- active.interactions.delete(id);
29027
- active.settledInteractions.add(id);
29250
+ active2.interactions.delete(id2);
29251
+ active2.settledInteractions.add(id2);
29028
29252
  this.#emit({
29029
29253
  type: "interaction.closed",
29030
29254
  interactionId: pending.interaction.interactionId,
29031
- turnId: active.turnId,
29255
+ turnId: active2.turnId,
29032
29256
  reason
29033
29257
  });
29034
29258
  }
@@ -29042,24 +29266,24 @@ var V2Session = class {
29042
29266
  if (this.#timer)
29043
29267
  clearInterval(this.#timer);
29044
29268
  this.#abort.abort();
29045
- const active = this.#active;
29046
- if (active?.admitted) {
29047
- for (const id of active.interactions.keys())
29048
- this.#closeInteraction(active, id, "cancelled");
29049
- for (const item of active.live.values())
29269
+ const active2 = this.#active;
29270
+ if (active2?.admitted) {
29271
+ for (const id2 of active2.interactions.keys())
29272
+ this.#closeInteraction(active2, id2, "cancelled");
29273
+ for (const item of active2.live.values())
29050
29274
  this.#emit({
29051
29275
  type: "item.completed",
29052
- turnId: active.turnId,
29276
+ turnId: active2.turnId,
29053
29277
  snapshot: { item, outcome: { status: "failed", error: error51 } }
29054
29278
  });
29055
29279
  this.#emit({
29056
29280
  type: "turn.completed",
29057
- turnId: active.turnId,
29281
+ turnId: active2.turnId,
29058
29282
  outcome: { status: "failed", error: error51 }
29059
29283
  });
29060
29284
  }
29061
29285
  this.#active = void 0;
29062
- active?.resolve();
29286
+ active2?.resolve();
29063
29287
  this.#emit({ type: "session.faulted", error: error51 });
29064
29288
  this.#channel.end();
29065
29289
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false }).catch(() => void 0);
@@ -29068,14 +29292,14 @@ var V2Session = class {
29068
29292
  }
29069
29293
  close() {
29070
29294
  return this.#closePromise ??= (async () => {
29071
- const active = this.#active;
29072
- if (active?.admitted && !this.#closed) {
29295
+ const active2 = this.#active;
29296
+ if (active2?.admitted && !this.#closed) {
29073
29297
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false }).catch(() => void 0);
29074
29298
  await this.#refresh();
29075
29299
  if (this.#active) {
29076
29300
  let timer;
29077
29301
  await Promise.race([
29078
- active.done,
29302
+ active2.done,
29079
29303
  new Promise((resolve) => {
29080
29304
  timer = setTimeout(resolve, this.connection.options.closeTimeoutMs ?? 3e3);
29081
29305
  })
@@ -29113,7 +29337,7 @@ var V2Adapter = class {
29113
29337
  async #catalog(client2, cwd) {
29114
29338
  return readCatalog(client2, cwd, this.options.startupTimeoutMs ?? 2e4);
29115
29339
  }
29116
- async inspect(input = {}) {
29340
+ async inspect(input = {}, onModels) {
29117
29341
  const cwd = input.cwd ?? process.cwd();
29118
29342
  const connection = new V2Connection(this.options, cwd);
29119
29343
  this.#connections.add(connection);
@@ -29121,7 +29345,9 @@ var V2Adapter = class {
29121
29345
  if (this.#closed)
29122
29346
  throw new Error("OpenCode Adapter is closed");
29123
29347
  const client2 = await connection.client();
29124
- const catalog = await this.#catalog(client2, cwd);
29348
+ const models = await this.#catalog(client2, cwd);
29349
+ onModels?.(models);
29350
+ const { catalog } = models;
29125
29351
  return {
29126
29352
  status: "ready",
29127
29353
  catalog,
@@ -29200,10 +29426,10 @@ var V2Adapter = class {
29200
29426
  policy = locator.executionPolicy;
29201
29427
  }
29202
29428
  client2 = await connection.client();
29203
- const catalog = await this.#catalog(client2, input.cwd);
29429
+ const models = await this.#catalog(client2, input.cwd);
29204
29430
  let info;
29205
29431
  if (input.kind === "create") {
29206
- const model2 = selectedModel(input, catalog);
29432
+ const model2 = selectedModel(input, models);
29207
29433
  info = await client2.session.create({
29208
29434
  location: { directory: input.cwd },
29209
29435
  ...model2 ? { model: model2 } : {},
@@ -29217,7 +29443,7 @@ var V2Adapter = class {
29217
29443
  throw new Error("OpenCode returned a different Native Session or directory");
29218
29444
  if ((await client2.session.active())[info.id])
29219
29445
  throw new Error("OpenCode Session is already running");
29220
- const source = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3);
29446
+ const source = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3, models.index);
29221
29447
  if (source.snapshot.turns.some((turn) => turn.outcome.status === "unknown"))
29222
29448
  throw new Error("OpenCode history contains an incomplete execution");
29223
29449
  if (input.kind !== "resume") {
@@ -29249,7 +29475,7 @@ var V2Adapter = class {
29249
29475
  if (parent.model)
29250
29476
  await client2.session.switchModel({ sessionID: info.id, model: parent.model });
29251
29477
  info = await client2.session.get({ sessionID: info.id });
29252
- const derived = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3);
29478
+ const derived = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3, models.index);
29253
29479
  if (historyContent(derived.snapshot, false) !== historyContent({ turns: turns.slice(0, count2) }, false))
29254
29480
  throw new Error("OpenCode fork did not preserve the exact history prefix");
29255
29481
  if (!isDeepStrictEqual2(info.permissions ?? [], parent.permissions ?? []) || !isDeepStrictEqual2(info.model, parent.model))
@@ -29257,14 +29483,14 @@ var V2Adapter = class {
29257
29483
  const currentParent = await client2.session.get({ sessionID: parent.id });
29258
29484
  if (!isDeepStrictEqual2(currentParent.model, parent.model) || !isDeepStrictEqual2(currentParent.permissions, parent.permissions) || !sameDirectory(currentParent.location.directory, parent.location.directory))
29259
29485
  throw new Error("OpenCode source configuration changed during derivation");
29260
- const unchanged = await readHistory(client2, currentParent, this.options.toolOutputLimit ?? 64e3);
29486
+ const unchanged = await readHistory(client2, currentParent, this.options.toolOutputLimit ?? 64e3, models.index);
29261
29487
  if (historyContent(unchanged.snapshot) !== historyContent(source.snapshot))
29262
29488
  throw new Error("OpenCode source history changed during derivation");
29263
29489
  }
29264
29490
  }
29265
29491
  if (this.#closed)
29266
29492
  throw new Error("OpenCode Adapter closed during Session open");
29267
- const session = new V2Session(client2, connection, info, catalog, policy, this.options.toolOutputLimit ?? 64e3, () => {
29493
+ const session = new V2Session(client2, connection, info, models, policy, this.options.toolOutputLimit ?? 64e3, () => {
29268
29494
  this.#sessions.delete(session);
29269
29495
  this.#connections.delete(connection);
29270
29496
  });
@@ -29292,7 +29518,7 @@ var V2Adapter = class {
29292
29518
  this.#connections.clear();
29293
29519
  }
29294
29520
  };
29295
- function selectedModel(input, catalog) {
29521
+ function selectedModel(input, { catalog, index }) {
29296
29522
  const selected = input.model ?? catalog.defaultModel;
29297
29523
  if (!selected) {
29298
29524
  if (input.thinkingOptionId)
@@ -29304,7 +29530,7 @@ function selectedModel(input, catalog) {
29304
29530
  throw new Error("OpenCode Model is not available");
29305
29531
  if (input.thinkingOptionId && !entry.supportedThinkingOptionIds?.includes(input.thinkingOptionId))
29306
29532
  throw new Error("OpenCode Thinking option is not available for this Model");
29307
- const model2 = decodeOpenCodeModelRef(selected);
29533
+ const model2 = decodeOpenCodeModelRef(selected, index);
29308
29534
  const variant = input.thinkingOptionId ? decodeOpenCodeVariant(input.thinkingOptionId) : void 0;
29309
29535
  return { providerID: model2.providerID, id: model2.modelID, ...variant ? { variant } : {} };
29310
29536
  }
@@ -29328,6 +29554,19 @@ var OpenCodeAdapter2 = class {
29328
29554
  dependencies;
29329
29555
  harnessId = harnessId;
29330
29556
  commandCatalog = openCodeCommandCatalog;
29557
+ #inspectedModels = /* @__PURE__ */ new Map();
29558
+ normalizeStoredModelRef = (ref, catalog) => {
29559
+ let match;
29560
+ for (const models of this.#inspectedModels.values()) {
29561
+ if (!isDeepStrictEqual3(models.catalog, catalog))
29562
+ continue;
29563
+ const candidate2 = normalizeStoredOpenCodeModelRef(ref, models.index);
29564
+ if (!candidate2 || match && match.id !== candidate2.id)
29565
+ return void 0;
29566
+ match = candidate2;
29567
+ }
29568
+ return match;
29569
+ };
29331
29570
  #adapters = /* @__PURE__ */ new Set();
29332
29571
  #closed = false;
29333
29572
  usageStatistics;
@@ -29392,7 +29631,10 @@ var OpenCodeAdapter2 = class {
29392
29631
  let adapter;
29393
29632
  try {
29394
29633
  adapter = await this.#select();
29395
- return await adapter.inspect(input);
29634
+ const cwd = input.cwd ?? process.cwd();
29635
+ return await adapter.inspect({ ...input, cwd }, (models) => {
29636
+ this.#inspectedModels.set(cwd, models);
29637
+ });
29396
29638
  } catch (error51) {
29397
29639
  return {
29398
29640
  status: error51 instanceof OpenCodeExecutableError ? "notInstalled" : "error",
@@ -29433,6 +29675,7 @@ var OpenCodeAdapter2 = class {
29433
29675
  }
29434
29676
  async close() {
29435
29677
  this.#closed = true;
29678
+ this.#inspectedModels.clear();
29436
29679
  await Promise.all([...this.#adapters].map((adapter) => adapter.close()));
29437
29680
  this.#adapters.clear();
29438
29681
  }