@codexhost/cli-darwin-x64 0.22.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 (59) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +3117 -274
  4. package/app/console-web.js +15645 -4413
  5. package/app/desktop-controller.mjs +14057 -969
  6. package/app/host-runtime.mjs +11518 -8277
  7. package/app/plugins/antigravity/plugin.mjs +2030 -678
  8. package/app/plugins/claude-code/plugin.mjs +2116 -929
  9. package/app/plugins/codebuddy/plugin.mjs +1247 -353
  10. package/app/plugins/codex-usage/plugin.mjs +786 -163
  11. package/app/plugins/copilot/plugin.mjs +938 -296
  12. package/app/plugins/cursor-cli/plugin.mjs +1021 -232
  13. package/app/plugins/deepseek-harness/plugin.mjs +1552 -664
  14. package/app/plugins/devin/plugin.mjs +826 -185
  15. package/app/plugins/grok/plugin.mjs +1083 -424
  16. package/app/plugins/hermes/plugin.mjs +961 -338
  17. package/app/plugins/kimi-code/plugin.mjs +854 -237
  18. package/app/plugins/kiro-cli/plugin.mjs +821 -184
  19. package/app/plugins/omp/plugin.mjs +1316 -633
  20. package/app/plugins/opencode/plugin.mjs +1293 -606
  21. package/app/plugins/pi/plugin.mjs +1540 -867
  22. package/app/plugins/qoder/plugin.mjs +961 -332
  23. package/app/plugins/qoder-cn/plugin.mjs +961 -332
  24. package/app/plugins/qwen-code/plugin.mjs +937 -321
  25. package/app/plugins/workbuddy/plugin.mjs +1311 -370
  26. package/app/plugins/zcode/plugin.mjs +1516 -423
  27. package/app/renderer-extension.js +21297 -9060
  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 +6753 -31616
  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 +14 -14
  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 +94 -91
  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-browser/client.js +1 -1
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +79 -79
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +3 -3
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +7 -7
  50. package/app/web/sw.js +8 -1
  51. package/app/web-modules/licenses/werift-NOTICES.txt +123 -0
  52. package/app/web-modules/licenses/werift-libwebrtc-NOTICES.txt +58 -0
  53. package/app/web-modules/server.mjs +40416 -11283
  54. package/bin/codexhost +0 -0
  55. package/libexec/codexhost-shim +0 -0
  56. package/libexec/codexhost-updater +0 -0
  57. package/package.json +1 -1
  58. package/app/web/assets/index-CN4a4sj0.js +0 -201
  59. package/app/web/assets/index-DJW4bmyx.css +0 -1
@@ -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,
@@ -15198,6 +15201,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15198
15201
  permissionModeId: harnessPermissionModeIdSchema
15199
15202
  }).strict();
15200
15203
 
15204
+ // ../../shared-contracts/dist/harness-route-limit.js
15205
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
15206
+
15201
15207
  // ../../shared-contracts/dist/thread-usage.js
15202
15208
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15203
15209
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -15230,7 +15236,7 @@ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15230
15236
  expiresAtUnix: nonNegativeSafeIntegerSchema,
15231
15237
  label: indicatorTextSchema(256).optional(),
15232
15238
  tooltip: indicatorTextSchema(1024).optional()
15233
- }).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, {
15234
15240
  message: "Composer indicator IDs must be unique"
15235
15241
  });
15236
15242
  var threadUsageSnapshotSchema = external_exports.object({
@@ -15256,6 +15262,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15256
15262
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15257
15263
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15258
15264
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15265
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15259
15266
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15260
15267
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15261
15268
  }).strict().superRefine((usage, context) => {
@@ -15353,6 +15360,13 @@ var accountCreditsSnapshotSchema = external_exports.object({
15353
15360
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15354
15361
  resetCredits: accountResetCreditsSchema.optional()
15355
15362
  }).strict();
15363
+ var accountBalanceSnapshotSchema = external_exports.object({
15364
+ amount: external_exports.number().finite().nonnegative(),
15365
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15366
+ currency: external_exports.string().trim().min(1).max(8),
15367
+ /** Native label when the Harness exposes several Billing Sources. */
15368
+ label: external_exports.string().trim().min(1).max(128).optional()
15369
+ }).strict();
15356
15370
  var threadUsageInspectionParamsSchema = external_exports.object({
15357
15371
  threadId: hostThreadIdSchema,
15358
15372
  refresh: external_exports.literal("exact").optional()
@@ -15361,7 +15375,10 @@ var threadUsageInspectionSchema = external_exports.object({
15361
15375
  threadId: hostThreadIdSchema,
15362
15376
  usage: threadUsageSnapshotSchema.nullable(),
15363
15377
  accountCredits: accountCreditsSnapshotSchema.optional(),
15364
- /** Whether this source can provide cached account quota independently of usage. */
15378
+ /** Prepaid funds for the Thread's Billing Source; shown only when no percentage quota exists. */
15379
+ accountBalance: accountBalanceSnapshotSchema.optional(),
15380
+ /** Whether this source can provide cached account quota (credits or a prepaid balance)
15381
+ * independently of usage. */
15365
15382
  accountCreditsSupported: external_exports.boolean().optional()
15366
15383
  }).strict();
15367
15384
 
@@ -15373,10 +15390,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
15373
15390
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15374
15391
  message: "Value must not be empty or whitespace"
15375
15392
  });
15376
- 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"]);
15377
15395
  var harnessModelRefSchema = external_exports.object({
15378
- id: harnessModelRefIdSchema
15396
+ id: harnessModelRefIdSchema,
15397
+ serviceTier: harnessModelServiceTierSchema.optional()
15379
15398
  }).strict();
15399
+ function sameHarnessModelRef(left, right) {
15400
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
15401
+ }
15380
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();
15381
15403
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15382
15404
  var harnessThinkingOptionSchema = external_exports.object({
@@ -15390,7 +15412,15 @@ var harnessModelSchema = external_exports.object({
15390
15412
  /** Optional opaque selection for this same Model with priority processing enabled. */
15391
15413
  fastModel: harnessModelRefSchema.optional(),
15392
15414
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
15393
- }).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
+ }
15394
15424
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
15395
15425
  const ids = /* @__PURE__ */ new Set();
15396
15426
  for (const [index, option] of options.entries()) {
@@ -15410,26 +15440,26 @@ var harnessModelCatalogSchema = external_exports.object({
15410
15440
  thinkingOptions: harnessThinkingOptionsSchema,
15411
15441
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
15412
15442
  }).strict().superRefine((catalog, context) => {
15413
- const refs = /* @__PURE__ */ new Set();
15414
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15443
+ const refs = [];
15444
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
15415
15445
  for (const [index, model2] of catalog.models.entries()) {
15416
- if (refs.has(model2.ref.id)) {
15446
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
15417
15447
  context.addIssue({
15418
15448
  code: "custom",
15419
15449
  message: "Model Catalog refs must be unique",
15420
15450
  path: ["models", index, "ref", "id"]
15421
15451
  });
15422
15452
  }
15423
- refs.add(model2.ref.id);
15453
+ refs.push(model2.ref);
15424
15454
  if (model2.fastModel) {
15425
- 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))) {
15426
15456
  context.addIssue({
15427
15457
  code: "custom",
15428
15458
  message: "Fast Model refs must be distinct and unique",
15429
15459
  path: ["models", index, "fastModel"]
15430
15460
  });
15431
15461
  }
15432
- refs.add(model2.fastModel.id);
15462
+ refs.push(model2.fastModel);
15433
15463
  }
15434
15464
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15435
15465
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -15450,7 +15480,7 @@ var harnessModelCatalogSchema = external_exports.object({
15450
15480
  }
15451
15481
  }
15452
15482
  }
15453
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
15483
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
15454
15484
  context.addIssue({
15455
15485
  code: "custom",
15456
15486
  message: "Default Model must exist in the Model Catalog",
@@ -15490,7 +15520,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15490
15520
  observe: external_exports.boolean()
15491
15521
  }).strict().optional(),
15492
15522
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15493
- 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()
15494
15529
  }).strict();
15495
15530
  var harnessConfigurationStateSchema = external_exports.object({
15496
15531
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15499,7 +15534,7 @@ var harnessConfigurationStateSchema = external_exports.object({
15499
15534
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15500
15535
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
15501
15536
  }).strict().superRefine((state, context) => {
15502
- 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)) {
15503
15538
  context.addIssue({
15504
15539
  code: "custom",
15505
15540
  message: "Effective Thinking option must be currently available",
@@ -15539,7 +15574,8 @@ var harnessInspectParamsSchema = external_exports.object({
15539
15574
  cwd: nonBlankTextSchema2.max(16384).optional(),
15540
15575
  refresh: external_exports.boolean().optional(),
15541
15576
  /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15542
- purpose: external_exports.literal("availability").optional()
15577
+ purpose: external_exports.literal("availability").optional(),
15578
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
15543
15579
  }).strict();
15544
15580
  var harnessWebUiOpenParamsSchema = external_exports.object({
15545
15581
  harnessId: harnessIdSchema
@@ -15570,7 +15606,7 @@ var codexThreadInspectionSchema = external_exports.object({
15570
15606
  var externalThreadInspectionSchema = external_exports.object({
15571
15607
  owner: external_exports.literal("external"),
15572
15608
  harnessId: nonBlankTextSchema2.max(256),
15573
- transportModelId: nonBlankTextSchema2.max(1024),
15609
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
15574
15610
  effectiveModel: harnessModelRefSchema.optional(),
15575
15611
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15576
15612
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15652,13 +15688,635 @@ var threadSteeringInspectResultSchema = external_exports.object({
15652
15688
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15653
15689
  }).strict();
15654
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")
15957
+ });
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 })
16088
+ ]);
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") })
16094
+ ]);
16095
+ var hostExtensionInstallationSchema = external_exports.strictObject({
16096
+ ...active,
16097
+ manifest: hostExtensionManifestV2Schema,
16098
+ installedAt: external_exports.iso.datetime(),
16099
+ source: hostExtensionProvenanceSchema.optional()
16100
+ });
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
+ })
16120
+ ]);
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
16175
+ });
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
+ };
16235
+
15655
16236
  // ../../shared-contracts/dist/thread-archive-confirm.js
16237
+ var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
15656
16238
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
15657
16239
  var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
15658
16240
 
15659
16241
  // ../../shared-contracts/dist/client-channel.js
15660
16242
  var CLIENT_CHANNEL_VERSION = 1;
15661
16243
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
16244
+ var CLIENT_CHANNEL_METHODS = [
16245
+ "codexhost/skills/list",
16246
+ "codexhost/voice/status",
16247
+ "codexhost/voice/transcribe",
16248
+ "codexhost/harness/display-settings/get",
16249
+ "codexhost/harness/display-settings/set",
16250
+ "codexhost/harness/display-settings/capabilities",
16251
+ "codexhost/harness/preferences/get",
16252
+ "codexhost/harness/preferences/patch",
16253
+ "thread/list",
16254
+ "codexhost/thread/catalog/read",
16255
+ "thread/read",
16256
+ "thread/resume",
16257
+ "thread/fork",
16258
+ "thread/turns/list",
16259
+ "thread/revert",
16260
+ "thread/items/list",
16261
+ "thread/start",
16262
+ "thread/name/set",
16263
+ "codexhost/thread/title/generate",
16264
+ "thread/archive",
16265
+ THREAD_ARCHIVE_CONFIRM_METHOD,
16266
+ "thread/unarchive",
16267
+ "turn/start",
16268
+ "turn/interrupt",
16269
+ "turn/steer",
16270
+ "thread/queue/list",
16271
+ "thread/queue/add",
16272
+ "thread/queue/update",
16273
+ "thread/queue/delete",
16274
+ "thread/queue/reorder",
16275
+ "thread/queue/start",
16276
+ "codexhost/thread/queue/send-now",
16277
+ "codexhost/workspace/read",
16278
+ "codexhost/thread/tree/read",
16279
+ "codexhost/thread/pins/list",
16280
+ "codexhost/thread/pins/set",
16281
+ "codexhost/harness/plugins/list",
16282
+ "codexhost/harness/inspect",
16283
+ "codexhost/thread/inspect",
16284
+ "codexhost/thread/usage/inspect",
16285
+ "codexhost/thread/ownership/list",
16286
+ "codexhost/thread/model/select",
16287
+ "codexhost/thread/thinking/select",
16288
+ "codexhost/thread/permission-mode/select",
16289
+ "codexhost/thread/commands/inspect",
16290
+ "codexhost/harness/commands/inspect",
16291
+ "codexhost/thread/command/execute",
16292
+ "codexhost/thread/fork",
16293
+ "codexhost/harness/session-import/sources",
16294
+ "codexhost/harness/session-import/list",
16295
+ "codexhost/harness/session-import/import",
16296
+ // Host settings shared across Desktop and Web.
16297
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
16298
+ "codexhost/harness/installation",
16299
+ "codexhost/harness/installation/start",
16300
+ "codexhost/harness/installation/status",
16301
+ "codexhost/harness/launch-settings/get",
16302
+ "codexhost/harness/launch-settings/set",
16303
+ "codexhost/harness/web-ui/open",
16304
+ "codexhost/harness/accounts/sources",
16305
+ "codexhost/harness/accounts/list",
16306
+ "codexhost/harness/accounts/inspect",
16307
+ "codexhost/harness/credential-imports",
16308
+ "codexhost/account/list",
16309
+ "codexhost/account/refresh",
16310
+ "codexhost/account/usage/inspect",
16311
+ "codexhost/usage/model-prices/get",
16312
+ "codexhost/usage/model-prices/set",
16313
+ "codexhost/usage/model-prices/default",
16314
+ "codexhost/usage/statistics/get",
16315
+ "codexhost/update/check",
16316
+ "codexhost/update/start",
16317
+ "codexhost/update/status",
16318
+ "codexhost/sessions/loaded/list"
16319
+ ];
15662
16320
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15663
16321
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15664
16322
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -15697,6 +16355,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15697
16355
  cursor: clientChannelCursorSchema,
15698
16356
  revision: external_exports.number().int().nonnegative()
15699
16357
  }),
16358
+ external_exports.object({
16359
+ type: external_exports.literal("extensions-changed"),
16360
+ cursor: clientChannelCursorSchema,
16361
+ revision: hostExtensionRevisionSchema
16362
+ }),
15700
16363
  external_exports.object({
15701
16364
  type: external_exports.literal("hello"),
15702
16365
  version: external_exports.literal(1),
@@ -15872,6 +16535,29 @@ var threadCatalogReadResultSchema = external_exports.object({
15872
16535
  officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15873
16536
  }).strict();
15874
16537
 
16538
+ // ../../shared-contracts/dist/thread-tree-watch.js
16539
+ var THREAD_TREE_MAX_NODES = 5e3;
16540
+ var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
16541
+ var threadTreeNodeSchema = external_exports.strictObject({
16542
+ harnessId: harnessIdSchema,
16543
+ title: external_exports.string().optional(),
16544
+ status: threadTreeStatusSchema,
16545
+ archived: external_exports.boolean()
16546
+ });
16547
+ var threadTreeSnapshotSchema = external_exports.strictObject({
16548
+ revision: external_exports.int().nonnegative(),
16549
+ parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
16550
+ nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
16551
+ truncated: external_exports.boolean()
16552
+ }).refine((snapshot) => Object.keys(snapshot.nodes).length <= THREAD_TREE_MAX_NODES, "Too many Thread tree nodes").refine(({ parents, nodes }) => Object.entries(parents).every(([child, parent]) => Object.hasOwn(nodes, child) && Object.hasOwn(nodes, parent)), "Missing Thread tree node");
16553
+ var subscriptionId = external_exports.string().min(1).max(128);
16554
+ var threadTreeWatchParamsSchema = external_exports.strictObject({});
16555
+ var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
16556
+ var threadTreeUnwatchResultSchema = external_exports.strictObject({});
16557
+ var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
16558
+ snapshot: threadTreeSnapshotSchema
16559
+ });
16560
+
15875
16561
  // ../../shared-contracts/dist/voice.js
15876
16562
  var VOICE_AUDIO_MAX_BYTES = 10 * 1024 * 1024;
15877
16563
  var voiceAudioMimeTypeSchema = external_exports.string().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);
@@ -16110,7 +16796,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
16110
16796
 
16111
16797
  // ../../shared-contracts/dist/harness-preferences.js
16112
16798
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
16113
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
16799
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
16114
16800
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
16115
16801
  model: harnessModelRefSchema.optional(),
16116
16802
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -16120,11 +16806,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
16120
16806
  lastHarness: harnessIdSchema.optional(),
16121
16807
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
16122
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
+ });
16123
16816
  var modelId = external_exports.string().min(1).max(1024);
16124
16817
  var harnessPreferenceValuesSchema = external_exports.strictObject({
16125
16818
  idleRelease: idleReleaseSettingsSchema.optional(),
16126
16819
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
16127
- newThread: newThreadDefaultsSchema.optional()
16820
+ newThread: newThreadDefaultsSchema.optional(),
16821
+ delegation: delegationDefaultsSchema.optional()
16128
16822
  });
16129
16823
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
16130
16824
  scope: harnessPreferenceScopeSchema,
@@ -16152,6 +16846,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
16152
16846
  lastHarness: harnessIdSchema.optional(),
16153
16847
  harnessId: harnessIdSchema.optional(),
16154
16848
  configuration: harnessDefaultConfigurationSchema.optional()
16849
+ }),
16850
+ external_exports.strictObject({
16851
+ kind: external_exports.literal("delegation"),
16852
+ harnessId: harnessIdSchema,
16853
+ configuration: harnessDelegationDefaultSchema.nullable()
16155
16854
  })
16156
16855
  ]);
16157
16856
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -16502,13 +17201,6 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
16502
17201
  });
16503
17202
 
16504
17203
  // ../../shared-contracts/dist/harness-accounts.js
16505
- var accountBalanceSnapshotSchema = external_exports.object({
16506
- amount: external_exports.number().finite().nonnegative(),
16507
- /** ISO 4217 code as reported by the Provider, for example `CNY`. */
16508
- currency: external_exports.string().trim().min(1).max(8),
16509
- /** Native label when the Harness exposes several Billing Sources. */
16510
- label: external_exports.string().trim().min(1).max(128).optional()
16511
- }).strict();
16512
17204
  var harnessAccountSnapshotObject = external_exports.object({
16513
17205
  email: external_exports.string().trim().min(1).max(320).optional(),
16514
17206
  label: external_exports.string().trim().min(1).max(256).optional(),
@@ -16542,76 +17234,6 @@ var harnessAccountListResultSchema = external_exports.object({
16542
17234
  accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
16543
17235
  }).strict();
16544
17236
 
16545
- // ../../shared-contracts/dist/harness-plugins.js
16546
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
16547
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
16548
- var HARNESS_PLUGIN_LIMIT = 128;
16549
- var installedHarnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(harnessIdSchema);
16550
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
16551
- var relativeResourceSchema = 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");
16552
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
16553
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
16554
- var harnessInstallationGuideSchema = external_exports.object({
16555
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
16556
- before: localizedTextSchema.optional(),
16557
- after: localizedTextSchema.optional(),
16558
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
16559
- }).strict();
16560
- var pluginPresentationShape = {
16561
- id: installedHarnessPluginIdSchema,
16562
- name: external_exports.string().trim().min(1).max(128),
16563
- version: external_exports.string().min(1).max(128),
16564
- /** Capability-only plugin; omitted for existing session-capable plugins. */
16565
- kind: external_exports.literal("usage").optional(),
16566
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
16567
- iconStyle: external_exports.object({
16568
- vector: external_exports.object({
16569
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
16570
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
16571
- paths: external_exports.array(external_exports.object({
16572
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
16573
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
16574
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
16575
- }).strict()).min(1).max(32)
16576
- }).strict().optional(),
16577
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
16578
- borderRadius: external_exports.number().min(0).max(50).optional(),
16579
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
16580
- }).strict().optional(),
16581
- installation: harnessInstallationGuideSchema.optional(),
16582
- notice: localizedTextSchema.optional(),
16583
- /** The factory accepts a persisted local entrypoint through its construction context. */
16584
- launchCommand: external_exports.literal(true).optional(),
16585
- links: external_exports.object({
16586
- website: documentationUrlSchema.optional(),
16587
- documentation: documentationUrlSchema.optional(),
16588
- installation: documentationUrlSchema.optional()
16589
- }).strict().optional()
16590
- };
16591
- var harnessPluginManifestSchema = external_exports.object({
16592
- manifestVersion: external_exports.literal(1),
16593
- ...pluginPresentationShape,
16594
- adapterApiVersion: external_exports.number().int().positive(),
16595
- entry: relativeResourceSchema,
16596
- icon: relativeResourceSchema.optional()
16597
- }).strict();
16598
- 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);
16599
- var harnessPluginDescriptorSchema = external_exports.object({
16600
- ...pluginPresentationShape,
16601
- icon: harnessPluginIconSchema.optional()
16602
- }).strict();
16603
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
16604
- var harnessPluginListResultSchema = external_exports.object({
16605
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
16606
- }).strict();
16607
- var harnessPluginConfigurationSchema = external_exports.object({
16608
- version: external_exports.literal(1),
16609
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
16610
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
16611
- message: "Enabled plugin IDs must be unique",
16612
- path: ["enabled"]
16613
- });
16614
-
16615
17237
  // ../../shared-contracts/dist/harness-route.js
16616
17238
  var harnessPluginRouteSchema = external_exports.object({
16617
17239
  harnessId: harnessPluginIdSchema,
@@ -17052,9 +17674,12 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17052
17674
  ...thread,
17053
17675
  epoch: identity,
17054
17676
  modelId: identity.optional(),
17677
+ serviceTier: harnessModelServiceTierSchema.optional(),
17055
17678
  thinkingOptionId: identity.optional(),
17056
17679
  permissionModeId: identity.optional()
17057
- }).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
+ }),
17058
17683
  external_exports.strictObject({
17059
17684
  kind: external_exports.literal("prompt"),
17060
17685
  ...thread,
@@ -17104,7 +17729,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
17104
17729
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
17105
17730
  external_exports.strictObject({
17106
17731
  action: external_exports.literal("read-thread"),
17107
- hostId: hostId.refine((id) => id !== "local"),
17732
+ hostId: hostId.refine((id2) => id2 !== "local"),
17108
17733
  input: delegationReadParamsSchema
17109
17734
  }),
17110
17735
  external_exports.strictObject({
@@ -17118,7 +17743,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
17118
17743
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
17119
17744
  external_exports.strictObject({
17120
17745
  action: external_exports.literal("update"),
17121
- hostId: hostId.refine((id) => id !== "local"),
17746
+ hostId: hostId.refine((id2) => id2 !== "local"),
17122
17747
  version: remoteUpdateParamsSchema.shape.version
17123
17748
  })
17124
17749
  ]);
@@ -17182,7 +17807,7 @@ function invalidRequest(message) {
17182
17807
  return { code: "invalidRequest", message, retryable: false };
17183
17808
  }
17184
17809
  function validateHostApprovalResponse(interaction, response) {
17185
- 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");
17186
17811
  }
17187
17812
 
17188
17813
  // ../../harness-adapter/dist/question.js
@@ -17190,7 +17815,7 @@ function invalidRequest2(message) {
17190
17815
  return { code: "invalidRequest", message, retryable: false };
17191
17816
  }
17192
17817
  function validateHostQuestionResponse(interaction, response) {
17193
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17818
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
17194
17819
  if (response.cancelled) {
17195
17820
  return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17196
17821
  }
@@ -17221,6 +17846,21 @@ function validateHostQuestionResponse(interaction, response) {
17221
17846
  return null;
17222
17847
  }
17223
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
+
17224
17864
  // ../../harness-adapter/dist/output-channel.js
17225
17865
  var HarnessOutputChannel = class {
17226
17866
  outputs;
@@ -17305,7 +17945,8 @@ var tokenFields = [
17305
17945
  var safeIntegerFields = [
17306
17946
  "planFiveHourResetsAtUnix",
17307
17947
  "planSevenDayResetsAtUnix",
17308
- "timeToFirstOutputMs"
17948
+ "timeToFirstOutputMs",
17949
+ "latestRequestTimeToFirstOutputMs"
17309
17950
  ];
17310
17951
  var percentFields = [
17311
17952
  "cacheHitRatePercent",
@@ -17618,7 +18259,7 @@ function createOpenCodeUsageStatistics(environment) {
17618
18259
  const stamp = file2 ? await fingerprint(file2) : null;
17619
18260
  return file2 && stamp ? [{ id: file2, fingerprint: stamp }] : [];
17620
18261
  },
17621
- readSource: (id) => readOpenCodeUsage(id)
18262
+ readSource: (id2) => readOpenCodeUsage(id2)
17622
18263
  });
17623
18264
  }
17624
18265
 
@@ -17636,35 +18277,52 @@ function assertNonBlank(value, label) {
17636
18277
  if (!value.trim())
17637
18278
  throw new Error(`OpenCode ${label} must not be empty`);
17638
18279
  }
17639
- 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);
17640
18314
  assertNonBlank(model2.providerID, "Provider ID");
17641
18315
  assertNonBlank(model2.modelID, "Model ID");
17642
- const encoded = Buffer2.from(JSON.stringify([model2.providerID, model2.modelID]), "utf8").toString("base64url");
17643
- const id = `${MODEL_REF_PREFIX}${encoded}`;
17644
- if (id.length > HARNESS_MODEL_REF_MAX_LENGTH) {
17645
- throw new Error("OpenCode Model identity is too long for a Model Ref");
17646
- }
17647
- return harnessModelRefSchema.parse({ id });
18316
+ return harnessModelRefSchema.parse({ id: readableId(model2) });
17648
18317
  }
17649
- function decodeOpenCodeModelRef(ref) {
17650
- const parsed = harnessModelRefSchema.parse(ref);
17651
- if (!parsed.id.startsWith(MODEL_REF_PREFIX)) {
17652
- throw new Error("OpenCode Model Ref belongs to another Adapter");
17653
- }
17654
- let decoded;
17655
- try {
17656
- decoded = JSON.parse(Buffer2.from(parsed.id.slice(MODEL_REF_PREFIX.length), "base64url").toString("utf8"));
17657
- } catch {
17658
- throw new Error("OpenCode Model Ref is malformed");
17659
- }
17660
- if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
17661
- throw new Error("OpenCode Model Ref has an invalid native identity");
17662
- }
17663
- const native = { providerID: decoded[0], modelID: decoded[1] };
17664
- if (encodeOpenCodeModelRef(native).id !== parsed.id) {
17665
- throw new Error("OpenCode Model Ref is not canonical");
17666
- }
17667
- 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);
17668
18326
  }
17669
18327
  function encodeOpenCodeVariant(variant) {
17670
18328
  if (variant === void 0)
@@ -17672,8 +18330,8 @@ function encodeOpenCodeVariant(variant) {
17672
18330
  assertNonBlank(variant, "Model variant");
17673
18331
  return harnessThinkingOptionIdSchema.parse(`${VARIANT_REF_PREFIX}${Buffer2.from(variant, "utf8").toString("base64url")}`);
17674
18332
  }
17675
- function decodeOpenCodeVariant(id) {
17676
- const parsed = harnessThinkingOptionIdSchema.parse(id);
18333
+ function decodeOpenCodeVariant(id2) {
18334
+ const parsed = harnessThinkingOptionIdSchema.parse(id2);
17677
18335
  if (parsed === DEFAULT_VARIANT_ID)
17678
18336
  return void 0;
17679
18337
  if (!parsed.startsWith(VARIANT_REF_PREFIX)) {
@@ -17701,6 +18359,7 @@ function modelsForConnectedProviders(catalog) {
17701
18359
  }
17702
18360
  function normalizeOpenCodeModelCatalog(catalog) {
17703
18361
  const nativeModels = modelsForConnectedProviders(catalog);
18362
+ const index = openCodeModelIndex(nativeModels.map(({ provider, model: model2 }) => ({ providerID: provider.id, modelID: model2.id })));
17704
18363
  const variants = /* @__PURE__ */ new Set();
17705
18364
  for (const { model: model2 } of nativeModels) {
17706
18365
  for (const variant of Object.keys(model2.variants ?? {}))
@@ -17711,7 +18370,7 @@ function normalizeOpenCodeModelCatalog(catalog) {
17711
18370
  ...[...variants].sort(compareText).map((variant) => variantOption(variant))
17712
18371
  ];
17713
18372
  const models = nativeModels.map(({ provider, model: model2 }) => ({
17714
- ref: encodeOpenCodeModelRef({ providerID: provider.id, modelID: model2.id }),
18373
+ ref: index.encode({ providerID: provider.id, modelID: model2.id }),
17715
18374
  label: `${provider.name} / ${model2.name}`,
17716
18375
  resolvedModelLabel: `${provider.id}/${model2.id}`,
17717
18376
  supportedThinkingOptionIds: [
@@ -17720,16 +18379,19 @@ function normalizeOpenCodeModelCatalog(catalog) {
17720
18379
  ]
17721
18380
  })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
17722
18381
  const defaultNative = catalog.connected.map((providerID) => ({ providerID, modelID: catalog.default[providerID] })).find((candidate2) => typeof candidate2.modelID === "string" && candidate2.modelID.length > 0);
17723
- const defaultModel = defaultNative ? encodeOpenCodeModelRef(defaultNative) : void 0;
17724
- return harnessModelCatalogSchema.parse({
17725
- models,
17726
- ...defaultModel && models.some(({ ref }) => ref.id === defaultModel.id) ? { defaultModel } : {},
17727
- thinkingOptions,
17728
- defaultThinkingOptionId: DEFAULT_VARIANT_ID
17729
- });
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
+ };
17730
18392
  }
17731
18393
  function openCodeContextWindow(catalog, model2) {
17732
- const provider = catalog.all.find(({ id }) => id === model2.providerID);
18394
+ const provider = catalog.all.find(({ id: id2 }) => id2 === model2.providerID);
17733
18395
  const context = provider?.models[model2.modelID]?.limit.context;
17734
18396
  return typeof context === "number" && Number.isSafeInteger(context) && context > 0 ? context : void 0;
17735
18397
  }
@@ -17953,7 +18615,7 @@ function projectOpenCodeHistory(input) {
17953
18615
  input: [{ type: "text", text: userText(userEntry) }],
17954
18616
  items,
17955
18617
  outcome,
17956
- model: encodeOpenCodeModelRef(user.model)
18618
+ model: encodeOpenCodeModelRef(user.model, input.modelIndex)
17957
18619
  });
17958
18620
  index = end;
17959
18621
  }
@@ -17966,12 +18628,12 @@ function resolveOpenCodeForkBoundary(session, messages, checkpoint) {
17966
18628
  if (checkpoint.harnessId !== openCodeHarnessId || checkpoint.nativeSessionId !== session.id) {
17967
18629
  return null;
17968
18630
  }
17969
- const active = activeMessages(session, messages);
17970
- const checkpointIndex = active.findIndex(({ info }) => info.id === checkpoint.checkpointId);
17971
- 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")
17972
18634
  return null;
17973
- const targetUserCount = active.slice(0, checkpointIndex + 1).filter(({ info }) => info.role === "user").length;
17974
- 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;
17975
18637
  return {
17976
18638
  ...nextMessage ? { messageID: nextMessage } : {},
17977
18639
  sourceTurnCount: targetUserCount
@@ -18184,8 +18846,8 @@ var createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer,
18184
18846
  };
18185
18847
 
18186
18848
  // ../../../node_modules/@opencode-ai/sdk/dist/v2/gen/core/pathSerializer.gen.js
18187
- var separatorArrayExplode = (style) => {
18188
- switch (style) {
18849
+ var separatorArrayExplode = (style2) => {
18850
+ switch (style2) {
18189
18851
  case "label":
18190
18852
  return ".";
18191
18853
  case "matrix":
@@ -18196,8 +18858,8 @@ var separatorArrayExplode = (style) => {
18196
18858
  return "&";
18197
18859
  }
18198
18860
  };
18199
- var separatorArrayNoExplode = (style) => {
18200
- switch (style) {
18861
+ var separatorArrayNoExplode = (style2) => {
18862
+ switch (style2) {
18201
18863
  case "form":
18202
18864
  return ",";
18203
18865
  case "pipeDelimited":
@@ -18208,8 +18870,8 @@ var separatorArrayNoExplode = (style) => {
18208
18870
  return ",";
18209
18871
  }
18210
18872
  };
18211
- var separatorObjectExplode = (style) => {
18212
- switch (style) {
18873
+ var separatorObjectExplode = (style2) => {
18874
+ switch (style2) {
18213
18875
  case "label":
18214
18876
  return ".";
18215
18877
  case "matrix":
@@ -18220,10 +18882,10 @@ var separatorObjectExplode = (style) => {
18220
18882
  return "&";
18221
18883
  }
18222
18884
  };
18223
- var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
18885
+ var serializeArrayParam = ({ allowReserved, explode, name, style: style2, value }) => {
18224
18886
  if (!explode) {
18225
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
18226
- switch (style) {
18887
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style2));
18888
+ switch (style2) {
18227
18889
  case "label":
18228
18890
  return `.${joinedValues2}`;
18229
18891
  case "matrix":
@@ -18234,9 +18896,9 @@ var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
18234
18896
  return `${name}=${joinedValues2}`;
18235
18897
  }
18236
18898
  }
18237
- const separator = separatorArrayExplode(style);
18899
+ const separator = separatorArrayExplode(style2);
18238
18900
  const joinedValues = value.map((v) => {
18239
- if (style === "label" || style === "simple") {
18901
+ if (style2 === "label" || style2 === "simple") {
18240
18902
  return allowReserved ? v : encodeURIComponent(v);
18241
18903
  }
18242
18904
  return serializePrimitiveParam({
@@ -18245,7 +18907,7 @@ var serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
18245
18907
  value: v
18246
18908
  });
18247
18909
  }).join(separator);
18248
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
18910
+ return style2 === "label" || style2 === "matrix" ? separator + joinedValues : joinedValues;
18249
18911
  };
18250
18912
  var serializePrimitiveParam = ({ allowReserved, name, value }) => {
18251
18913
  if (value === void 0 || value === null) {
@@ -18256,17 +18918,17 @@ var serializePrimitiveParam = ({ allowReserved, name, value }) => {
18256
18918
  }
18257
18919
  return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
18258
18920
  };
18259
- var serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
18921
+ var serializeObjectParam = ({ allowReserved, explode, name, style: style2, value, valueOnly }) => {
18260
18922
  if (value instanceof Date) {
18261
18923
  return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
18262
18924
  }
18263
- if (style !== "deepObject" && !explode) {
18925
+ if (style2 !== "deepObject" && !explode) {
18264
18926
  let values = [];
18265
18927
  Object.entries(value).forEach(([key, v]) => {
18266
18928
  values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
18267
18929
  });
18268
18930
  const joinedValues2 = values.join(",");
18269
- switch (style) {
18931
+ switch (style2) {
18270
18932
  case "form":
18271
18933
  return `${name}=${joinedValues2}`;
18272
18934
  case "label":
@@ -18277,13 +18939,13 @@ var serializeObjectParam = ({ allowReserved, explode, name, style, value, valueO
18277
18939
  return joinedValues2;
18278
18940
  }
18279
18941
  }
18280
- const separator = separatorObjectExplode(style);
18942
+ const separator = separatorObjectExplode(style2);
18281
18943
  const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
18282
18944
  allowReserved,
18283
- name: style === "deepObject" ? `${name}[${key}]` : key,
18945
+ name: style2 === "deepObject" ? `${name}[${key}]` : key,
18284
18946
  value: v
18285
18947
  })).join(separator);
18286
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
18948
+ return style2 === "label" || style2 === "matrix" ? separator + joinedValues : joinedValues;
18287
18949
  };
18288
18950
 
18289
18951
  // ../../../node_modules/@opencode-ai/sdk/dist/v2/gen/core/utils.gen.js
@@ -18295,44 +18957,44 @@ var defaultPathSerializer = ({ path: path14, url: _url2 }) => {
18295
18957
  for (const match of matches) {
18296
18958
  let explode = false;
18297
18959
  let name = match.substring(1, match.length - 1);
18298
- let style = "simple";
18960
+ let style2 = "simple";
18299
18961
  if (name.endsWith("*")) {
18300
18962
  explode = true;
18301
18963
  name = name.substring(0, name.length - 1);
18302
18964
  }
18303
18965
  if (name.startsWith(".")) {
18304
18966
  name = name.substring(1);
18305
- style = "label";
18967
+ style2 = "label";
18306
18968
  } else if (name.startsWith(";")) {
18307
18969
  name = name.substring(1);
18308
- style = "matrix";
18970
+ style2 = "matrix";
18309
18971
  }
18310
18972
  const value = path14[name];
18311
18973
  if (value === void 0 || value === null) {
18312
18974
  continue;
18313
18975
  }
18314
18976
  if (Array.isArray(value)) {
18315
- url2 = url2.replace(match, serializeArrayParam({ explode, name, style, value }));
18977
+ url2 = url2.replace(match, serializeArrayParam({ explode, name, style: style2, value }));
18316
18978
  continue;
18317
18979
  }
18318
18980
  if (typeof value === "object") {
18319
18981
  url2 = url2.replace(match, serializeObjectParam({
18320
18982
  explode,
18321
18983
  name,
18322
- style,
18984
+ style: style2,
18323
18985
  value,
18324
18986
  valueOnly: true
18325
18987
  }));
18326
18988
  continue;
18327
18989
  }
18328
- if (style === "matrix") {
18990
+ if (style2 === "matrix") {
18329
18991
  url2 = url2.replace(match, `;${serializePrimitiveParam({
18330
18992
  name,
18331
18993
  value
18332
18994
  })}`);
18333
18995
  continue;
18334
18996
  }
18335
- const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
18997
+ const replaceValue = encodeURIComponent(style2 === "label" ? `.${value}` : value);
18336
18998
  url2 = url2.replace(match, replaceValue);
18337
18999
  }
18338
19000
  }
@@ -18543,27 +19205,27 @@ var Interceptors = class {
18543
19205
  clear() {
18544
19206
  this.fns = [];
18545
19207
  }
18546
- eject(id) {
18547
- const index = this.getInterceptorIndex(id);
19208
+ eject(id2) {
19209
+ const index = this.getInterceptorIndex(id2);
18548
19210
  if (this.fns[index]) {
18549
19211
  this.fns[index] = null;
18550
19212
  }
18551
19213
  }
18552
- exists(id) {
18553
- const index = this.getInterceptorIndex(id);
19214
+ exists(id2) {
19215
+ const index = this.getInterceptorIndex(id2);
18554
19216
  return Boolean(this.fns[index]);
18555
19217
  }
18556
- getInterceptorIndex(id) {
18557
- if (typeof id === "number") {
18558
- return this.fns[id] ? id : -1;
19218
+ getInterceptorIndex(id2) {
19219
+ if (typeof id2 === "number") {
19220
+ return this.fns[id2] ? id2 : -1;
18559
19221
  }
18560
- return this.fns.indexOf(id);
19222
+ return this.fns.indexOf(id2);
18561
19223
  }
18562
- update(id, fn) {
18563
- const index = this.getInterceptorIndex(id);
19224
+ update(id2, fn) {
19225
+ const index = this.getInterceptorIndex(id2);
18564
19226
  if (this.fns[index]) {
18565
19227
  this.fns[index] = fn;
18566
- return id;
19228
+ return id2;
18567
19229
  }
18568
19230
  return false;
18569
19231
  }
@@ -24233,7 +24895,7 @@ async function readTurnDiff(transport, sessionID, userMessageID, nativePatchFile
24233
24895
  await new Promise((resolve) => setTimeout(resolve, DIFF_RECONCILIATION_DELAYS_MS[attempt]));
24234
24896
  }
24235
24897
  }
24236
- async function readProjection(transport, sessionID, providerCatalog, toolOutputLimit, options = {}) {
24898
+ async function readProjection(transport, sessionID, providerCatalog, toolOutputLimit, modelIndex, options = {}) {
24237
24899
  const strictFileChanges = options.strictFileChanges === true;
24238
24900
  const [session, messages, paths] = await Promise.all([
24239
24901
  transport.getSession(sessionID),
@@ -24255,11 +24917,12 @@ async function readProjection(transport, sessionID, providerCatalog, toolOutputL
24255
24917
  session,
24256
24918
  messages,
24257
24919
  diffsByUserMessageId: new Map(diffEntries),
24258
- toolOutputLimit
24920
+ toolOutputLimit,
24921
+ modelIndex
24259
24922
  });
24260
24923
  const model2 = nativeModelFromSession(session, messages);
24261
24924
  const nativeVariant = nativeVariantFromSession(session, messages);
24262
- 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;
24263
24926
  const variant = nativeVariant === "default" && nativeModel && !Object.hasOwn(nativeModel.variants ?? {}, "default") ? void 0 : nativeVariant;
24264
24927
  const usage = projectOpenCodeUsage(openCodeAssistantMessages(session, messages), model2 ? openCodeContextWindow(providerCatalog, model2) : void 0);
24265
24928
  return {
@@ -24305,8 +24968,10 @@ function sourceState(projection) {
24305
24968
  };
24306
24969
  }
24307
24970
  async function deriveOpenCodeHistory(options) {
24308
- const { transport, source, input, providers, toolOutputLimit } = options;
24309
- 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
+ });
24310
24975
  if ((await transport.getStatus(source.id)).type !== "idle") {
24311
24976
  throw new Error("OpenCode source Session is busy");
24312
24977
  }
@@ -24398,10 +25063,10 @@ function sameCwd(left, right) {
24398
25063
  };
24399
25064
  return canonical(left) === canonical(right);
24400
25065
  }
24401
- function sessionState(session, modelCatalog, model2, variant, executionPolicy = "default", permissionModeId = OPENCODE_DEFAULT_PERMISSION_MODE_ID) {
24402
- 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;
24403
25068
  const modelEntry = effectiveModel ? modelCatalog.models.find(({ ref }) => ref.id === effectiveModel.id) : void 0;
24404
- 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));
24405
25070
  const effectiveThinkingOptionId = encodeOpenCodeVariant(variant);
24406
25071
  return {
24407
25072
  nativeRef: openCodeNativeSessionRef(session, executionPolicy),
@@ -24493,10 +25158,10 @@ var OpenCodeHarnessSession = class {
24493
25158
  this.initialState = this.#state;
24494
25159
  this.#usage = input.projection.usage;
24495
25160
  this.initialUsage = this.#usage;
24496
- const thinkingSelectable = this.#modelCatalog.thinkingOptions.length > 1;
25161
+ const thinkingSelectable = this.#modelCatalog.catalog.thinkingOptions.length > 1;
24497
25162
  this.capabilities = {
24498
25163
  configuration: {
24499
- selectModel: this.#modelCatalog.models.length > 0,
25164
+ selectModel: this.#modelCatalog.catalog.models.length > 0,
24500
25165
  selectThinkingOption: thinkingSelectable,
24501
25166
  selectPermissionMode: true,
24502
25167
  permissionModeScope: "live"
@@ -24531,7 +25196,7 @@ var OpenCodeHarnessSession = class {
24531
25196
  };
24532
25197
  }
24533
25198
  try {
24534
- 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);
24535
25200
  this.#applyProjection(projection);
24536
25201
  return { ok: true, value: { ...this.#snapshot, state: this.#state } };
24537
25202
  } catch (error51) {
@@ -24575,11 +25240,11 @@ var OpenCodeHarnessSession = class {
24575
25240
  }
24576
25241
  };
24577
25242
  }
24578
- const active = this.#createActive("prompt", command.turnId, null);
24579
- this.#active = active;
24580
- active.admissionBuffer.push({
25243
+ const active2 = this.#createActive("prompt", command.turnId, null);
25244
+ this.#active = active2;
25245
+ active2.admissionBuffer.push({
24581
25246
  output: { kind: "event", event: { type: "turn.started", turnId: command.turnId } },
24582
- sequence: active.admissionSequence++
25247
+ sequence: active2.admissionSequence++
24583
25248
  });
24584
25249
  try {
24585
25250
  const prompt = this.#transport.promptAsync({
@@ -24589,19 +25254,19 @@ var OpenCodeHarnessSession = class {
24589
25254
  ...this.#variant ? { variant: this.#variant } : {}
24590
25255
  });
24591
25256
  void prompt.catch(() => void 0);
24592
- await Promise.race([prompt, active.admissionFailurePromise]);
24593
- if (active.admissionFailure)
24594
- return { ok: false, error: active.admissionFailure };
24595
- active.admissionCompleted = true;
24596
- this.#flushAdmission(active);
24597
- 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);
24598
25263
  return { ok: true, value: { turnId: command.turnId } };
24599
25264
  } catch (error51) {
24600
25265
  const normalized = normalizeError(error51, "nativeFailure");
24601
- active.admissionBuffer.length = 0;
24602
- active.finished = true;
24603
- active.resolveCompletion();
24604
- if (this.#active === active)
25266
+ active2.admissionBuffer.length = 0;
25267
+ active2.finished = true;
25268
+ active2.resolveCompletion();
25269
+ if (this.#active === active2)
24605
25270
  this.#active = null;
24606
25271
  return { ok: false, error: normalized };
24607
25272
  }
@@ -24647,31 +25312,31 @@ var OpenCodeHarnessSession = class {
24647
25312
  }
24648
25313
  };
24649
25314
  }
24650
- const active = this.#createActive("compact", command.turnId, null);
24651
- this.#active = active;
24652
- active.admissionBuffer.push({
25315
+ const active2 = this.#createActive("compact", command.turnId, null);
25316
+ this.#active = active2;
25317
+ active2.admissionBuffer.push({
24653
25318
  output: { kind: "event", event: { type: "turn.started", turnId: command.turnId } },
24654
- sequence: active.admissionSequence++
25319
+ sequence: active2.admissionSequence++
24655
25320
  });
24656
25321
  const item = {
24657
25322
  type: "contextCompaction",
24658
25323
  itemId: hostItemIdSchema.parse(`opencode-compact:${this.#uuid()}`)
24659
25324
  };
24660
- active.items.set(item.itemId, { item, completed: false });
25325
+ active2.items.set(item.itemId, { item, completed: false });
24661
25326
  this.#event({ type: "item.started", turnId: command.turnId, item });
24662
25327
  try {
24663
25328
  await this.#transport.summarize(this.#session.id, this.#model);
24664
25329
  } catch (error51) {
24665
25330
  const normalized = normalizeError(error51, "nativeFailure");
24666
- this.#failAdmission(active, normalized);
25331
+ this.#failAdmission(active2, normalized);
24667
25332
  return { ok: false, error: normalized };
24668
25333
  }
24669
- if (active.admissionFailure)
24670
- return { ok: false, error: active.admissionFailure };
24671
- active.admissionCompleted = true;
24672
- active.nativeCompleted = true;
24673
- this.#flushAdmission(active);
24674
- 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" });
24675
25340
  void this.#refreshProjection(command.turnId);
24676
25341
  return { ok: true, value: { turnId: command.turnId } };
24677
25342
  }
@@ -24681,14 +25346,14 @@ var OpenCodeHarnessSession = class {
24681
25346
  };
24682
25347
  }
24683
25348
  async #cancel(command) {
24684
- const active = this.#active;
24685
- if (!active || active.turnId !== command.turnId) {
25349
+ const active2 = this.#active;
25350
+ if (!active2 || active2.turnId !== command.turnId) {
24686
25351
  return {
24687
25352
  ok: false,
24688
25353
  error: invalidState("OpenCode cancellation must reference the active Turn")
24689
25354
  };
24690
25355
  }
24691
- active.cancellationRequested = true;
25356
+ active2.cancellationRequested = true;
24692
25357
  try {
24693
25358
  await this.#transport.abort(this.#session.id);
24694
25359
  return { ok: true, value: { cancellationRequested: true } };
@@ -24697,9 +25362,9 @@ var OpenCodeHarnessSession = class {
24697
25362
  }
24698
25363
  }
24699
25364
  async #respond(command) {
24700
- const active = this.#active;
24701
- const pending = active?.interactions.get(command.interactionId);
24702
- if (!active || !pending) {
25365
+ const active2 = this.#active;
25366
+ const pending = active2?.interactions.get(command.interactionId);
25367
+ if (!active2 || !pending) {
24703
25368
  return {
24704
25369
  ok: false,
24705
25370
  error: invalidState("OpenCode Interaction Response must reference a pending Interaction")
@@ -24742,7 +25407,7 @@ var OpenCodeHarnessSession = class {
24742
25407
  return { ok: false, error: validation };
24743
25408
  await this.#transport.replyPermission(pending.nativeId, command.response.actionId === "allow-once" ? "once" : "reject");
24744
25409
  }
24745
- this.#closeInteraction(active, command.interactionId, "responded");
25410
+ this.#closeInteraction(active2, command.interactionId, "responded");
24746
25411
  return { ok: true, value: { accepted: true } };
24747
25412
  } catch (error51) {
24748
25413
  return { ok: false, error: normalizeError(error51, "nativeFailure") };
@@ -24761,21 +25426,10 @@ var OpenCodeHarnessSession = class {
24761
25426
  }
24762
25427
  let native;
24763
25428
  try {
24764
- native = decodeOpenCodeModelRef(command.model);
25429
+ native = decodeOpenCodeModelRef(command.model, this.#modelCatalog.index);
24765
25430
  } catch (error51) {
24766
25431
  return { ok: false, error: normalizeError(error51, "invalidRequest") };
24767
25432
  }
24768
- const entry = this.#modelCatalog.models.find(({ ref }) => ref.id === command.model.id);
24769
- if (!entry) {
24770
- return {
24771
- ok: false,
24772
- error: {
24773
- code: "invalidRequest",
24774
- message: "OpenCode Model is absent from the current catalog",
24775
- retryable: false
24776
- }
24777
- };
24778
- }
24779
25433
  this.#configuring = true;
24780
25434
  try {
24781
25435
  this.#session = await this.#transport.updateSessionMetadata(this.#session.id, selectionMetadata(this.#session, native, void 0));
@@ -24803,8 +25457,8 @@ var OpenCodeHarnessSession = class {
24803
25457
  }
24804
25458
  };
24805
25459
  }
24806
- const modelRef = this.#model ? encodeOpenCodeModelRef(this.#model) : void 0;
24807
- 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;
24808
25462
  if (!model2?.supportedThinkingOptionIds?.includes(command.thinkingOptionId)) {
24809
25463
  return {
24810
25464
  ok: false,
@@ -24885,24 +25539,24 @@ var OpenCodeHarnessSession = class {
24885
25539
  return;
24886
25540
  if (event.type === "server.connected") {
24887
25541
  this.#connectedCount += 1;
24888
- const active2 = this.#active;
24889
- if (this.#connectedCount > 1 && active2)
24890
- void this.#reconcileAfterReconnect(active2);
25542
+ const active3 = this.#active;
25543
+ if (this.#connectedCount > 1 && active3)
25544
+ void this.#reconcileAfterReconnect(active3);
24891
25545
  return;
24892
25546
  }
24893
- const active = this.#active;
25547
+ const active2 = this.#active;
24894
25548
  if (event.type === "session.status" && event.properties.sessionID === this.#session.id) {
24895
- if (!active)
25549
+ if (!active2)
24896
25550
  return;
24897
25551
  if (event.properties.status.type === "busy")
24898
- active.sawBusy = true;
25552
+ active2.sawBusy = true;
24899
25553
  if (event.properties.status.type === "idle")
24900
- void this.#reconcileAndFinish(active);
25554
+ void this.#reconcileAndFinish(active2);
24901
25555
  return;
24902
25556
  }
24903
25557
  if (event.type === "session.idle" && event.properties.sessionID === this.#session.id) {
24904
- if (active)
24905
- void this.#reconcileAndFinish(active);
25558
+ if (active2)
25559
+ void this.#reconcileAndFinish(active2);
24906
25560
  return;
24907
25561
  }
24908
25562
  if (event.type === "message.updated" && event.properties.sessionID === this.#session.id) {
@@ -24911,65 +25565,65 @@ var OpenCodeHarnessSession = class {
24911
25565
  this.#knownUserMessageIds.add(info.id);
24912
25566
  return;
24913
25567
  }
24914
- if (!active || !this.#bindUserMessage(active, info.parentID))
25568
+ if (!active2 || !this.#bindUserMessage(active2, info.parentID))
24915
25569
  return;
24916
- active.assistantMessageIds.add(info.id);
24917
- active.terminalAssistant = info;
25570
+ active2.assistantMessageIds.add(info.id);
25571
+ active2.terminalAssistant = info;
24918
25572
  if (info.time.completed !== void 0 || info.finish || info.error) {
24919
- void this.#reconcileAndFinish(active);
25573
+ void this.#reconcileAndFinish(active2);
24920
25574
  }
24921
25575
  return;
24922
25576
  }
24923
25577
  if (event.type === "message.part.updated") {
24924
25578
  const part = event.properties.part;
24925
- if (active && part.sessionID === this.#session.id && active.assistantMessageIds.has(part.messageID)) {
24926
- this.#projectPart(active, part);
25579
+ if (active2 && part.sessionID === this.#session.id && active2.assistantMessageIds.has(part.messageID)) {
25580
+ this.#projectPart(active2, part);
24927
25581
  }
24928
25582
  return;
24929
25583
  }
24930
25584
  if (event.type === "message.part.delta") {
24931
25585
  const properties = event.properties;
24932
- if (active && properties.sessionID === this.#session.id && active.assistantMessageIds.has(properties.messageID)) {
24933
- 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);
24934
25588
  }
24935
25589
  return;
24936
25590
  }
24937
25591
  if (event.type === "question.asked" && event.properties.sessionID === this.#session.id) {
24938
- if (active)
24939
- this.#openQuestion(active, event.properties);
25592
+ if (active2)
25593
+ this.#openQuestion(active2, event.properties);
24940
25594
  return;
24941
25595
  }
24942
25596
  if (event.type === "question.replied" || event.type === "question.rejected") {
24943
- if (event.properties.sessionID !== this.#session.id || !active)
25597
+ if (event.properties.sessionID !== this.#session.id || !active2)
24944
25598
  return;
24945
- const id = hostInteractionIdSchema.parse(event.properties.requestID);
24946
- if (active.interactions.has(id))
24947
- 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");
24948
25602
  return;
24949
25603
  }
24950
25604
  if (event.type === "permission.asked" && event.properties.sessionID === this.#session.id) {
24951
- if (active)
24952
- this.#openApproval(active, event.properties);
25605
+ if (active2)
25606
+ this.#openApproval(active2, event.properties);
24953
25607
  return;
24954
25608
  }
24955
25609
  if (event.type === "permission.replied") {
24956
- if (event.properties.sessionID !== this.#session.id || !active)
25610
+ if (event.properties.sessionID !== this.#session.id || !active2)
24957
25611
  return;
24958
- const id = hostInteractionIdSchema.parse(event.properties.requestID);
24959
- if (active.interactions.has(id))
24960
- 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");
24961
25615
  return;
24962
25616
  }
24963
- 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) {
24964
25618
  const error51 = event.properties.error;
24965
- if (active.cancellationRequested || error51?.name === "MessageAbortedError") {
24966
- active.cancellationRequested = true;
24967
- void this.#reconcileAndFinish(active);
25619
+ if (active2.cancellationRequested || error51?.name === "MessageAbortedError") {
25620
+ active2.cancellationRequested = true;
25621
+ void this.#reconcileAndFinish(active2);
24968
25622
  return;
24969
25623
  }
24970
- this.#completeTurn(active, {
24971
- status: active.cancellationRequested ? "cancelled" : "failed",
24972
- ...active.cancellationRequested ? { reason: "Cancelled by user" } : {
25624
+ this.#completeTurn(active2, {
25625
+ status: active2.cancellationRequested ? "cancelled" : "failed",
25626
+ ...active2.cancellationRequested ? { reason: "Cancelled by user" } : {
24973
25627
  error: {
24974
25628
  code: error51?.name === "ProviderAuthError" ? "authenticationRequired" : "nativeFailure",
24975
25629
  message: error51 && "message" in error51.data && typeof error51.data.message === "string" ? error51.data.message : "OpenCode Session failed",
@@ -24979,49 +25633,49 @@ var OpenCodeHarnessSession = class {
24979
25633
  });
24980
25634
  }
24981
25635
  }
24982
- #projectPart(active, part) {
25636
+ #projectPart(active2, part) {
24983
25637
  if (part.type === "text" || part.type === "reasoning") {
24984
25638
  if (part.type === "text" && part.ignored)
24985
25639
  return;
24986
- const existing = active.items.get(part.id);
25640
+ const existing = active2.items.get(part.id);
24987
25641
  if (!existing) {
24988
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 };
24989
- active.items.set(part.id, { item, content: part.text, completed: false });
24990
- 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 });
24991
25645
  } else if (typeof existing.content === "string" && part.text.startsWith(existing.content)) {
24992
25646
  const suffix = part.text.slice(existing.content.length);
24993
25647
  if (suffix)
24994
- this.#appendText(active, part.id, suffix);
25648
+ this.#appendText(active2, part.id, suffix);
24995
25649
  } else if (typeof existing.content === "string" && existing.content !== part.text) {
24996
25650
  throw new OpenCodeTransportError("protocolError", `OpenCode Part '${part.id}' returned inconsistent streamed text`);
24997
25651
  }
24998
25652
  if (part.time?.end !== void 0)
24999
- this.#completeLiveItem(active, part.id, { status: "succeeded" });
25653
+ this.#completeLiveItem(active2, part.id, { status: "succeeded" });
25000
25654
  return;
25001
25655
  }
25002
25656
  if (part.type === "tool") {
25003
- this.#projectTool(active, part);
25657
+ this.#projectTool(active2, part);
25004
25658
  return;
25005
25659
  }
25006
- if (part.type === "compaction" && !active.items.has(part.id)) {
25660
+ if (part.type === "compaction" && !active2.items.has(part.id)) {
25007
25661
  const item = {
25008
25662
  type: "contextCompaction",
25009
25663
  itemId: hostItemIdSchema.parse(part.id)
25010
25664
  };
25011
- active.items.set(part.id, { item, completed: false });
25012
- 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 });
25013
25667
  }
25014
25668
  }
25015
- #appendPartDelta(active, partID, field2, delta) {
25669
+ #appendPartDelta(active2, partID, field2, delta) {
25016
25670
  if (field2 !== "text" || !delta)
25017
25671
  return;
25018
- const existing = active.items.get(partID);
25672
+ const existing = active2.items.get(partID);
25019
25673
  if (!existing)
25020
25674
  return;
25021
- this.#appendText(active, partID, delta);
25675
+ this.#appendText(active2, partID, delta);
25022
25676
  }
25023
- #appendText(active, partID, delta) {
25024
- const live = active.items.get(partID);
25677
+ #appendText(active2, partID, delta) {
25678
+ const live = active2.items.get(partID);
25025
25679
  if (!live || live.completed || typeof live.content !== "string")
25026
25680
  return;
25027
25681
  live.content += delta;
@@ -25030,19 +25684,19 @@ var OpenCodeHarnessSession = class {
25030
25684
  }
25031
25685
  this.#event({
25032
25686
  type: "item.updated",
25033
- turnId: active.turnId,
25687
+ turnId: active2.turnId,
25034
25688
  itemId: live.item.itemId,
25035
25689
  update: { type: "text.append", text: delta }
25036
25690
  });
25037
25691
  }
25038
- #projectTool(active, part) {
25692
+ #projectTool(active2, part) {
25039
25693
  if (part.state.status === "pending")
25040
25694
  return;
25041
25695
  const arguments_ = jsonValueSchema.safeParse(part.state.input);
25042
25696
  if (!arguments_.success) {
25043
25697
  throw new OpenCodeTransportError("protocolError", `OpenCode Tool '${part.tool}' emitted invalid arguments`);
25044
25698
  }
25045
- let live = active.items.get(part.id);
25699
+ let live = active2.items.get(part.id);
25046
25700
  if (!live) {
25047
25701
  const item = {
25048
25702
  type: "toolExecution",
@@ -25051,9 +25705,9 @@ var OpenCodeHarnessSession = class {
25051
25705
  arguments: arguments_.data
25052
25706
  };
25053
25707
  live = { item, completed: false };
25054
- active.items.set(part.id, live);
25055
- active.toolItemByCallId.set(part.callID, item.itemId);
25056
- 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 });
25057
25711
  }
25058
25712
  if (live.item.type !== "toolExecution" || live.completed)
25059
25713
  return;
@@ -25067,18 +25721,18 @@ var OpenCodeHarnessSession = class {
25067
25721
  if (output) {
25068
25722
  this.#event({
25069
25723
  type: "item.updated",
25070
- turnId: active.turnId,
25724
+ turnId: active2.turnId,
25071
25725
  itemId: live.item.itemId,
25072
25726
  update: { type: "output.replace", output }
25073
25727
  });
25074
25728
  }
25075
- this.#completeLiveItem(active, part.id, { status: "succeeded" });
25729
+ this.#completeLiveItem(active2, part.id, { status: "succeeded" });
25076
25730
  } else if (part.state.status === "error") {
25077
25731
  live.item = {
25078
25732
  ...live.item,
25079
25733
  durationMs: Math.max(0, part.state.time.end - part.state.time.start)
25080
25734
  };
25081
- this.#completeLiveItem(active, part.id, {
25735
+ this.#completeLiveItem(active2, part.id, {
25082
25736
  status: "failed",
25083
25737
  error: {
25084
25738
  code: "nativeFailure",
@@ -25088,9 +25742,9 @@ var OpenCodeHarnessSession = class {
25088
25742
  });
25089
25743
  }
25090
25744
  }
25091
- #openQuestion(active, request) {
25745
+ #openQuestion(active2, request) {
25092
25746
  const interactionId = hostInteractionIdSchema.parse(request.id);
25093
- if (active.interactions.has(interactionId))
25747
+ if (active2.interactions.has(interactionId))
25094
25748
  return;
25095
25749
  const questions = request.questions.map((question, index) => ({
25096
25750
  id: `question-${index}`,
@@ -25105,31 +25759,31 @@ var OpenCodeHarnessSession = class {
25105
25759
  allowOther: question.custom ?? false,
25106
25760
  optional: false
25107
25761
  }));
25108
- 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;
25109
25763
  const interaction = {
25110
25764
  type: "question",
25111
25765
  interactionId,
25112
- turnId: active.turnId,
25766
+ turnId: active2.turnId,
25113
25767
  ...itemId2 ? { itemId: itemId2 } : {},
25114
25768
  title: request.questions.map(({ header }) => header).filter(Boolean).join(" / ") || "OpenCode",
25115
25769
  questions
25116
25770
  };
25117
- active.interactions.set(interactionId, {
25771
+ active2.interactions.set(interactionId, {
25118
25772
  type: "question",
25119
25773
  nativeId: request.id,
25120
25774
  interaction
25121
25775
  });
25122
25776
  this.#output({ kind: "interaction", interaction });
25123
25777
  }
25124
- #openApproval(active, request) {
25778
+ #openApproval(active2, request) {
25125
25779
  const interactionId = hostInteractionIdSchema.parse(request.id);
25126
- if (active.interactions.has(interactionId))
25780
+ if (active2.interactions.has(interactionId))
25127
25781
  return;
25128
- 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;
25129
25783
  const interaction = {
25130
25784
  type: "approval",
25131
25785
  interactionId,
25132
- turnId: active.turnId,
25786
+ turnId: active2.turnId,
25133
25787
  ...itemId2 ? { itemId: itemId2 } : {},
25134
25788
  title: `Allow OpenCode ${request.permission}?`,
25135
25789
  ...request.patterns.length > 0 ? { description: request.patterns.join("\n") } : {},
@@ -25139,78 +25793,78 @@ var OpenCodeHarnessSession = class {
25139
25793
  { id: "deny", label: "Deny", effect: "deny" }
25140
25794
  ]
25141
25795
  };
25142
- active.interactions.set(interactionId, {
25796
+ active2.interactions.set(interactionId, {
25143
25797
  type: "approval",
25144
25798
  nativeId: request.id,
25145
25799
  interaction
25146
25800
  });
25147
25801
  this.#output({ kind: "interaction", interaction });
25148
25802
  }
25149
- #closeInteraction(active, interactionId, reason) {
25150
- if (!active.interactions.delete(interactionId))
25803
+ #closeInteraction(active2, interactionId, reason) {
25804
+ if (!active2.interactions.delete(interactionId))
25151
25805
  return;
25152
25806
  this.#event({
25153
25807
  type: "interaction.closed",
25154
25808
  interactionId,
25155
- turnId: active.turnId,
25809
+ turnId: active2.turnId,
25156
25810
  reason
25157
25811
  });
25158
25812
  }
25159
- async #reconcileAfterReconnect(active) {
25813
+ async #reconcileAfterReconnect(active2) {
25160
25814
  try {
25161
25815
  const [status, questions, permissions] = await Promise.all([
25162
25816
  this.#transport.getStatus(this.#session.id),
25163
25817
  this.#transport.listQuestions(),
25164
25818
  this.#transport.listPermissions()
25165
25819
  ]);
25166
- if (this.#active !== active)
25820
+ if (this.#active !== active2)
25167
25821
  return;
25168
25822
  for (const question of questions) {
25169
25823
  if (question.sessionID === this.#session.id)
25170
- this.#openQuestion(active, question);
25824
+ this.#openQuestion(active2, question);
25171
25825
  }
25172
25826
  for (const permission of permissions) {
25173
25827
  if (permission.sessionID === this.#session.id)
25174
- this.#openApproval(active, permission);
25828
+ this.#openApproval(active2, permission);
25175
25829
  }
25176
25830
  const pending = /* @__PURE__ */ new Set([
25177
- ...questions.filter(({ sessionID }) => sessionID === this.#session.id).map(({ id }) => id),
25178
- ...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)
25179
25833
  ]);
25180
- for (const [interactionId, interaction] of active.interactions) {
25834
+ for (const [interactionId, interaction] of active2.interactions) {
25181
25835
  if (!pending.has(interaction.nativeId))
25182
- this.#closeInteraction(active, interactionId, "superseded");
25836
+ this.#closeInteraction(active2, interactionId, "superseded");
25183
25837
  }
25184
- active.reconciledAfterReconnect = true;
25838
+ active2.reconciledAfterReconnect = true;
25185
25839
  if (status.type === "idle")
25186
- await this.#reconcileAndFinish(active);
25840
+ await this.#reconcileAndFinish(active2);
25187
25841
  } catch (error51) {
25188
25842
  this.#fault(error51);
25189
25843
  }
25190
25844
  }
25191
- async #reconcileAndFinish(active) {
25192
- if (this.#active !== active || active.kind === "compact")
25845
+ async #reconcileAndFinish(active2) {
25846
+ if (this.#active !== active2 || active2.kind === "compact")
25193
25847
  return;
25194
- if (active.finishing) {
25195
- active.reconcilePending = true;
25848
+ if (active2.finishing) {
25849
+ active2.reconcilePending = true;
25196
25850
  return;
25197
25851
  }
25198
- active.finishing = true;
25852
+ active2.finishing = true;
25199
25853
  try {
25200
25854
  const [status, messages] = await Promise.all([
25201
25855
  this.#transport.getStatus(this.#session.id),
25202
25856
  this.#transport.getMessages(this.#session.id)
25203
25857
  ]);
25204
- if (this.#active !== active || status.type !== "idle")
25858
+ if (this.#active !== active2 || status.type !== "idle")
25205
25859
  return;
25206
- this.#resolveUserMessage(active, messages);
25207
- const lifecycleObserved = active.sawBusy || active.reconciledAfterReconnect || active.cancellationRequested;
25860
+ this.#resolveUserMessage(active2, messages);
25861
+ const lifecycleObserved = active2.sawBusy || active2.reconciledAfterReconnect || active2.cancellationRequested;
25208
25862
  if (!lifecycleObserved)
25209
25863
  return;
25210
- const userIndex = messages.findIndex(({ info }) => info.id === active.userMessageID);
25864
+ const userIndex = messages.findIndex(({ info }) => info.id === active2.userMessageID);
25211
25865
  if (userIndex < 0) {
25212
- if (active.cancellationRequested) {
25213
- this.#completeTurn(active, { status: "cancelled", reason: "Cancelled by user" });
25866
+ if (active2.cancellationRequested) {
25867
+ this.#completeTurn(active2, { status: "cancelled", reason: "Cancelled by user" });
25214
25868
  }
25215
25869
  return;
25216
25870
  }
@@ -25218,41 +25872,41 @@ var OpenCodeHarnessSession = class {
25218
25872
  while (end < messages.length && messages[end]?.info.role !== "user")
25219
25873
  end += 1;
25220
25874
  const assistants = messages.slice(userIndex + 1, end).filter((entry) => entry.info.role === "assistant");
25221
- const terminal = assistants.at(-1)?.info ?? active.terminalAssistant;
25222
- if (!terminal || terminal.time.completed === void 0 && !terminal.finish && !terminal.error && !active.nativeCompleted) {
25223
- 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) {
25224
25878
  for (const entry of assistants) {
25225
25879
  for (const part of entry.parts)
25226
- this.#projectPart(active, part);
25880
+ this.#projectPart(active2, part);
25227
25881
  }
25228
- this.#completeTurn(active, { status: "cancelled", reason: "Cancelled by user" }, {
25882
+ this.#completeTurn(active2, { status: "cancelled", reason: "Cancelled by user" }, {
25229
25883
  harnessId: this.harnessId,
25230
25884
  nativeSessionId: this.#session.id,
25231
- nativeTurnKey: active.userMessageID,
25885
+ nativeTurnKey: active2.userMessageID,
25232
25886
  formatVersion: 1
25233
25887
  });
25234
- void this.#refreshProjection(active.turnId);
25888
+ void this.#refreshProjection(active2.turnId);
25235
25889
  }
25236
25890
  return;
25237
25891
  }
25238
25892
  for (const entry of assistants) {
25239
25893
  for (const part of entry.parts)
25240
- this.#projectPart(active, part);
25894
+ this.#projectPart(active2, part);
25241
25895
  }
25242
- active.terminalAssistant = terminal;
25243
- const userMessageID = active.userMessageID;
25896
+ active2.terminalAssistant = terminal;
25897
+ const userMessageID = active2.userMessageID;
25244
25898
  const changes = reliableOpenCodeFileChanges(await readTurnDiff(this.#transport, this.#session.id, userMessageID, turnNativePatchFiles(messages, userMessageID)));
25245
25899
  if (changes.length > 0) {
25246
- const id = `opencode-live-diff:${active.userMessageID}`;
25247
- if (!active.items.has(id)) {
25900
+ const id2 = `opencode-live-diff:${active2.userMessageID}`;
25901
+ if (!active2.items.has(id2)) {
25248
25902
  const item = {
25249
25903
  type: "fileChange",
25250
- itemId: hostItemIdSchema.parse(id),
25251
- sourceItemIds: [...active.items.values()].map(({ item: item2 }) => item2.itemId),
25904
+ itemId: hostItemIdSchema.parse(id2),
25905
+ sourceItemIds: [...active2.items.values()].map(({ item: item2 }) => item2.itemId),
25252
25906
  changes
25253
25907
  };
25254
- active.items.set(id, { item, completed: false });
25255
- 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 });
25256
25910
  }
25257
25911
  }
25258
25912
  const checkpoint = nativeCheckpointRefSchema.parse({
@@ -25264,10 +25918,10 @@ var OpenCodeHarnessSession = class {
25264
25918
  const nativeTurnRef = {
25265
25919
  harnessId: this.harnessId,
25266
25920
  nativeSessionId: this.#session.id,
25267
- nativeTurnKey: active.userMessageID,
25921
+ nativeTurnKey: active2.userMessageID,
25268
25922
  formatVersion: 1
25269
25923
  };
25270
- 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 ? {
25271
25925
  status: "failed",
25272
25926
  error: {
25273
25927
  code: terminal.error.name === "ProviderAuthError" ? "authenticationRequired" : "nativeFailure",
@@ -25276,54 +25930,54 @@ var OpenCodeHarnessSession = class {
25276
25930
  },
25277
25931
  checkpoint
25278
25932
  } : { status: "succeeded", checkpoint };
25279
- this.#completeTurn(active, outcome, nativeTurnRef);
25280
- void this.#refreshProjection(active.turnId);
25933
+ this.#completeTurn(active2, outcome, nativeTurnRef);
25934
+ void this.#refreshProjection(active2.turnId);
25281
25935
  } catch (error51) {
25282
- if (this.#active === active) {
25283
- this.#completeTurn(active, {
25936
+ if (this.#active === active2) {
25937
+ this.#completeTurn(active2, {
25284
25938
  status: "failed",
25285
25939
  error: normalizeError(error51, "protocolError")
25286
25940
  });
25287
25941
  }
25288
25942
  } finally {
25289
- active.finishing = false;
25290
- if (active.reconcilePending && this.#active === active && !active.finished) {
25291
- active.reconcilePending = false;
25292
- 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);
25293
25947
  }
25294
25948
  }
25295
25949
  }
25296
- #completeLiveItem(active, key, outcome) {
25297
- const live = active.items.get(key);
25950
+ #completeLiveItem(active2, key, outcome) {
25951
+ const live = active2.items.get(key);
25298
25952
  if (!live || live.completed)
25299
25953
  return;
25300
25954
  live.completed = true;
25301
25955
  this.#event({
25302
25956
  type: "item.completed",
25303
- turnId: active.turnId,
25957
+ turnId: active2.turnId,
25304
25958
  snapshot: { item: live.item, outcome }
25305
25959
  });
25306
25960
  }
25307
- #completeTurn(active, outcome, nativeTurnRef) {
25308
- if (this.#active !== active || active.finished || !active.admissionCompleted)
25961
+ #completeTurn(active2, outcome, nativeTurnRef) {
25962
+ if (this.#active !== active2 || active2.finished || !active2.admissionCompleted)
25309
25963
  return;
25310
- active.finished = true;
25964
+ active2.finished = true;
25311
25965
  this.#active = null;
25312
- for (const interactionId of [...active.interactions.keys()]) {
25313
- 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");
25314
25968
  }
25315
25969
  const itemOutcome = itemOutcomeForTurn(outcome);
25316
- for (const [key, live] of active.items) {
25970
+ for (const [key, live] of active2.items) {
25317
25971
  if (!live.completed)
25318
- this.#completeLiveItem(active, key, itemOutcome);
25972
+ this.#completeLiveItem(active2, key, itemOutcome);
25319
25973
  }
25320
25974
  this.#event({
25321
25975
  type: "turn.completed",
25322
- turnId: active.turnId,
25976
+ turnId: active2.turnId,
25323
25977
  outcome,
25324
25978
  ...nativeTurnRef ? { nativeTurnRef } : {}
25325
25979
  });
25326
- active.resolveCompletion();
25980
+ active2.resolveCompletion();
25327
25981
  }
25328
25982
  #createActive(kind, turnId, userMessageID) {
25329
25983
  let resolveCompletion = () => void 0;
@@ -25361,26 +26015,26 @@ var OpenCodeHarnessSession = class {
25361
26015
  resolveCompletion
25362
26016
  };
25363
26017
  }
25364
- #flushAdmission(active) {
25365
- if (!active.admissionCompleted || this.#active !== active)
26018
+ #flushAdmission(active2) {
26019
+ if (!active2.admissionCompleted || this.#active !== active2)
25366
26020
  return;
25367
- active.admissionBuffer.sort((left, right) => left.sequence - right.sequence);
25368
- 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))
25369
26023
  this.#channel.emit(output);
25370
26024
  }
25371
- #failAdmission(active, error51) {
25372
- if (this.#active !== active || active.admissionCompleted || active.finished)
26025
+ #failAdmission(active2, error51) {
26026
+ if (this.#active !== active2 || active2.admissionCompleted || active2.finished)
25373
26027
  return;
25374
- active.admissionBuffer.length = 0;
25375
- active.admissionFailure = error51;
25376
- active.finished = true;
26028
+ active2.admissionBuffer.length = 0;
26029
+ active2.admissionFailure = error51;
26030
+ active2.finished = true;
25377
26031
  this.#active = null;
25378
- active.resolveAdmissionFailure(error51);
25379
- active.resolveCompletion();
26032
+ active2.resolveAdmissionFailure(error51);
26033
+ active2.resolveCompletion();
25380
26034
  }
25381
26035
  async #refreshProjection(observedForTurnId) {
25382
26036
  try {
25383
- 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);
25384
26038
  this.#applyProjection(projection, observedForTurnId);
25385
26039
  } catch {
25386
26040
  }
@@ -25418,12 +26072,12 @@ var OpenCodeHarnessSession = class {
25418
26072
  return;
25419
26073
  const normalized = normalizeError(error51, "internalError");
25420
26074
  if (this.#active && !this.#active.admissionCompleted) {
25421
- const active = this.#active;
25422
- active.admissionBuffer.length = 0;
25423
- active.admissionFailure = normalized;
25424
- active.resolveAdmissionFailure(normalized);
25425
- active.finished = true;
25426
- 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();
25427
26081
  this.#active = null;
25428
26082
  } else if (this.#active) {
25429
26083
  this.#completeTurn(this.#active, { status: "failed", error: normalized });
@@ -25438,12 +26092,12 @@ var OpenCodeHarnessSession = class {
25438
26092
  const faulted = this.#phase === "faulted";
25439
26093
  if (!faulted)
25440
26094
  this.#phase = "closing";
25441
- const active = this.#active;
25442
- if (active) {
25443
- active.cancellationRequested = true;
26095
+ const active2 = this.#active;
26096
+ if (active2) {
26097
+ active2.cancellationRequested = true;
25444
26098
  await this.#transport.abort(this.#session.id).catch(() => void 0);
25445
26099
  await Promise.race([
25446
- active.completion,
26100
+ active2.completion,
25447
26101
  new Promise((resolve) => setTimeout(resolve, this.#closeTimeoutMs))
25448
26102
  ]);
25449
26103
  }
@@ -25461,9 +26115,9 @@ var OpenCodeHarnessSession = class {
25461
26115
  }
25462
26116
  }
25463
26117
  #output(output) {
25464
- const active = this.#active;
25465
- if (active && !active.admissionCompleted) {
25466
- 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++ });
25467
26121
  return;
25468
26122
  }
25469
26123
  this.#channel.emit(output);
@@ -25471,29 +26125,29 @@ var OpenCodeHarnessSession = class {
25471
26125
  #event(event) {
25472
26126
  this.#output({ kind: "event", event });
25473
26127
  }
25474
- #bindUserMessage(active, messageID) {
25475
- if (active.userMessageID)
25476
- return active.userMessageID === messageID;
25477
- if (active.preexistingUserMessageIds.has(messageID))
26128
+ #bindUserMessage(active2, messageID) {
26129
+ if (active2.userMessageID)
26130
+ return active2.userMessageID === messageID;
26131
+ if (active2.preexistingUserMessageIds.has(messageID))
25478
26132
  return false;
25479
- active.userMessageID = messageID;
26133
+ active2.userMessageID = messageID;
25480
26134
  this.#knownUserMessageIds.add(messageID);
25481
26135
  return true;
25482
26136
  }
25483
- #resolveUserMessage(active, messages) {
25484
- if (active.userMessageID)
26137
+ #resolveUserMessage(active2, messages) {
26138
+ if (active2.userMessageID)
25485
26139
  return;
25486
- 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));
25487
26141
  const [candidate2] = candidates;
25488
26142
  if (candidates.length === 1 && candidate2) {
25489
- this.#bindUserMessage(active, candidate2.info.id);
26143
+ this.#bindUserMessage(active2, candidate2.info.id);
25490
26144
  return;
25491
26145
  }
25492
26146
  const parents = new Set(messages.filter(({ info }) => info.role === "assistant").map(({ info }) => info.parentID));
25493
26147
  const linked = candidates.filter(({ info }) => parents.has(info.id));
25494
26148
  const [linkedCandidate] = linked;
25495
26149
  if (linked.length === 1 && linkedCandidate) {
25496
- this.#bindUserMessage(active, linkedCandidate.info.id);
26150
+ this.#bindUserMessage(active2, linkedCandidate.info.id);
25497
26151
  return;
25498
26152
  }
25499
26153
  if (candidates.length > 1) {
@@ -25522,7 +26176,15 @@ var OpenCodeAdapter = class {
25522
26176
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
25523
26177
  this.#closeTimeoutMs = options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS2;
25524
26178
  }
25525
- 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) {
25526
26188
  if (this.#closePromise) {
25527
26189
  return {
25528
26190
  status: "unavailable",
@@ -25531,15 +26193,19 @@ var OpenCodeAdapter = class {
25531
26193
  }
25532
26194
  const cwd = input.cwd ?? process.cwd();
25533
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
+ }
25534
26202
  if (inFlight)
25535
26203
  return inFlight;
25536
- if (!input.refresh) {
25537
- const cached2 = this.#inspectionCache.get(cwd);
25538
- if (cached2)
25539
- return cached2;
25540
- }
26204
+ const cached2 = this.#inspectionCache.get(cwd);
26205
+ if (cached2)
26206
+ return cached2;
25541
26207
  const inspection = this.#inspectCwd(cwd).then((result) => {
25542
- if (result.status === "ready")
26208
+ if (result.status === "ready" && this.#inspectionInFlight.get(cwd) === inspection)
25543
26209
  this.#inspectionCache.set(cwd, result);
25544
26210
  return result;
25545
26211
  });
@@ -25561,10 +26227,11 @@ var OpenCodeAdapter = class {
25561
26227
  }
25562
26228
  stage = "model-catalog";
25563
26229
  const providers = await transport.providers();
25564
- const catalog = normalizeOpenCodeModelCatalog(providers);
26230
+ const { catalog, index } = normalizeOpenCodeModelCatalog(providers);
25565
26231
  return {
25566
26232
  status: "ready",
25567
26233
  catalog,
26234
+ index,
25568
26235
  capabilities: {
25569
26236
  configuration: {
25570
26237
  selectModel: catalog.models.length > 0,
@@ -25655,11 +26322,8 @@ var OpenCodeAdapter = class {
25655
26322
  const modelCatalog = normalizeOpenCodeModelCatalog(providers);
25656
26323
  let session;
25657
26324
  if (input.kind === "create") {
25658
- const model2 = input.model ? decodeOpenCodeModelRef(input.model) : void 0;
26325
+ const model2 = input.model ? decodeOpenCodeModelRef(input.model, modelCatalog.index) : void 0;
25659
26326
  const variant = input.thinkingOptionId ? decodeOpenCodeVariant(input.thinkingOptionId) : void 0;
25660
- if (input.model && !modelCatalog.models.some(({ ref }) => ref.id === input.model?.id)) {
25661
- throw new OpenCodeTransportError("protocolError", "Requested OpenCode Model is absent from the connected Provider catalog");
25662
- }
25663
26327
  const permission = requestedPermissionMode && requestedPermissionMode !== "default" ? requestedPermissionRules(void 0, requestedPermissionMode) : void 0;
25664
26328
  session = await transport.createSession({
25665
26329
  ...model2 ? { model: model2 } : {},
@@ -25703,6 +26367,7 @@ var OpenCodeAdapter = class {
25703
26367
  source,
25704
26368
  input,
25705
26369
  providers,
26370
+ modelIndex: modelCatalog.index,
25706
26371
  toolOutputLimit: this.#toolOutputLimit,
25707
26372
  onCreated: (candidate2) => {
25708
26373
  createdForCleanup = candidate2;
@@ -25710,7 +26375,7 @@ var OpenCodeAdapter = class {
25710
26375
  });
25711
26376
  }
25712
26377
  }
25713
- const projection = await readProjection(transport, session.id, providers, this.#toolOutputLimit);
26378
+ const projection = await readProjection(transport, session.id, providers, this.#toolOutputLimit, modelCatalog.index);
25714
26379
  const harnessSession = new OpenCodeHarnessSession({
25715
26380
  transport,
25716
26381
  connection,
@@ -25821,32 +26486,37 @@ function v2Locator(ref) {
25821
26486
  function v2Catalog(models, defaultModel) {
25822
26487
  const enabled = models.filter((model2) => model2.enabled);
25823
26488
  const variants = [...new Set(enabled.flatMap((model2) => model2.variants.map((v) => v.id)))].sort();
25824
- const ref = (model2) => encodeOpenCodeModelRef({ providerID: model2.providerID, modelID: model2.id });
25825
- return harnessModelCatalogSchema.parse({
25826
- models: enabled.map((model2) => ({
25827
- ref: ref(model2),
25828
- label: `${model2.providerID} / ${model2.name}`,
25829
- resolvedModelLabel: `${model2.providerID}/${model2.id}`,
25830
- supportedThinkingOptionIds: [
25831
- encodeOpenCodeVariant(void 0),
25832
- ...model2.variants.map((v) => encodeOpenCodeVariant(v.id))
25833
- ]
25834
- })),
25835
- ...defaultModel && enabled.some((m) => ref(m).id === ref(defaultModel).id) ? { defaultModel: ref(defaultModel) } : {},
25836
- thinkingOptions: [void 0, ...variants].map((v) => ({
25837
- id: encodeOpenCodeVariant(v),
25838
- label: v ?? "Default"
25839
- })),
25840
- defaultThinkingOptionId: encodeOpenCodeVariant(void 0)
25841
- });
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
+ };
25842
26512
  }
25843
26513
  function v2Permissions(current = [], mode) {
25844
26514
  const selected = decodeOpenCodePermissionModeId(mode);
25845
26515
  const rules = current.filter((rule) => !(rule.action === "*" && rule.resource === "*" && ["allow", "ask"].includes(rule.effect)));
25846
26516
  return selected === "default" ? rules : [...rules, { action: "*", resource: "*", effect: selected }];
25847
26517
  }
25848
- function v2State(session, catalog, policy) {
25849
- 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;
25850
26520
  const entry = catalog.models.find((candidate2) => candidate2.ref.id === model2?.id);
25851
26521
  const mode = session.permissions?.findLast((rule) => rule.action === "*" && rule.resource === "*");
25852
26522
  return {
@@ -25861,8 +26531,8 @@ function v2State(session, catalog, policy) {
25861
26531
  };
25862
26532
  }
25863
26533
  function effectiveVariant(variant, entry) {
25864
- const id = encodeOpenCodeVariant(variant);
25865
- 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;
25866
26536
  }
25867
26537
  function decodeMode(effect) {
25868
26538
  return effect === "allow" || effect === "ask" ? harnessPermissionModeIdSchema.parse(effect) : harnessPermissionModeIdSchema.parse("default");
@@ -25886,7 +26556,7 @@ async function readCatalog(client2, cwd, timeoutMs) {
25886
26556
  const required2 = ["opencode.config.provider", "opencode.config.agent", "opencode.config.policy"];
25887
26557
  while (true) {
25888
26558
  const { data: plugins } = await client2.plugin.list({ location });
25889
- const config2 = required2.map((id) => plugins.find((plugin) => plugin.id === id));
26559
+ const config2 = required2.map((id2) => plugins.find((plugin) => plugin.id === id2));
25890
26560
  const failed = config2.find((plugin) => plugin?.state.status === "failed");
25891
26561
  if (failed?.state.status === "failed")
25892
26562
  throw new Error(`OpenCode configuration failed: ${failed.state.error}`);
@@ -27770,7 +28440,7 @@ function assistantItems2(message, limit) {
27770
28440
  };
27771
28441
  });
27772
28442
  }
27773
- function projectHistory(session, messages, limit) {
28443
+ function projectHistory(session, messages, limit, index) {
27774
28444
  if (session.revert)
27775
28445
  throw new Error("Clear the staged OpenCode v2 revert before using this Session in codexhost");
27776
28446
  const turns = [];
@@ -27800,7 +28470,7 @@ function projectHistory(session, messages, limit) {
27800
28470
  turn.model = encodeOpenCodeModelRef({
27801
28471
  providerID: message.model.providerID,
27802
28472
  modelID: message.model.id
27803
- });
28473
+ }, index);
27804
28474
  } else if (message.type === "compaction") {
27805
28475
  turn.items.push({
27806
28476
  item: { type: "contextCompaction", itemId: hostItemIdSchema.parse(message.id) },
@@ -27861,9 +28531,9 @@ function fileChanges(session, turn, diffs) {
27861
28531
  outcome: { status: "succeeded" }
27862
28532
  };
27863
28533
  }
27864
- async function readHistory(client2, session, limit) {
28534
+ async function readHistory(client2, session, limit, index) {
27865
28535
  const messages = await readMessages(client2, session.id);
27866
- const snapshot = projectHistory(session, messages, limit);
28536
+ const snapshot = projectHistory(session, messages, limit, index);
27867
28537
  for (const turn of snapshot.turns) {
27868
28538
  if (!turn.checkpoint)
27869
28539
  continue;
@@ -27928,7 +28598,7 @@ function existingDirectory(directory) {
27928
28598
  return null;
27929
28599
  }
27930
28600
  }
27931
- function candidate(info, active) {
28601
+ function candidate(info, active2) {
27932
28602
  if (info.parentID || info.time.archived !== void 0)
27933
28603
  return null;
27934
28604
  const cwd = existingDirectory(info.location.directory);
@@ -27940,11 +28610,11 @@ function candidate(info, active) {
27940
28610
  title: sessionImportTitle(info.title),
27941
28611
  updatedAt: info.time.updated,
27942
28612
  // This server only knows its own executions; another process may still hold the Session.
27943
- running: active[info.id] ? true : null
28613
+ running: active2[info.id] ? true : null
27944
28614
  });
27945
28615
  }
27946
28616
  async function listV2SessionCandidates(client2) {
27947
- const active = await client2.session.active();
28617
+ const active2 = await client2.session.active();
27948
28618
  const candidates = /* @__PURE__ */ new Map();
27949
28619
  const cursors = /* @__PURE__ */ new Set();
27950
28620
  let cursor;
@@ -27954,7 +28624,7 @@ async function listV2SessionCandidates(client2) {
27954
28624
  ...cursor ? { cursor } : {}
27955
28625
  });
27956
28626
  for (const info of response.data) {
27957
- const entry = candidate(info, active);
28627
+ const entry = candidate(info, active2);
27958
28628
  if (entry)
27959
28629
  candidates.set(entry.nativeSessionId, entry);
27960
28630
  }
@@ -27967,7 +28637,7 @@ async function listV2SessionCandidates(client2) {
27967
28637
  return [...candidates.values()];
27968
28638
  }
27969
28639
  async function resolveV2SessionCandidate(client2, nativeSessionId) {
27970
- const active = await client2.session.active();
28640
+ const active2 = await client2.session.active();
27971
28641
  const cursors = /* @__PURE__ */ new Set();
27972
28642
  let cursor;
27973
28643
  for (let page = 0; page < MAX_PAGES; page += 1) {
@@ -27977,7 +28647,7 @@ async function resolveV2SessionCandidate(client2, nativeSessionId) {
27977
28647
  });
27978
28648
  const info = response.data.find((entry) => entry.id === nativeSessionId);
27979
28649
  if (info) {
27980
- const entry = candidate(info, active);
28650
+ const entry = candidate(info, active2);
27981
28651
  return entry ? { candidate: entry, nativeRef: v2Ref(info, "default") } : null;
27982
28652
  }
27983
28653
  const next = response.cursor.next;
@@ -28132,7 +28802,7 @@ var V2Session = class {
28132
28802
  client;
28133
28803
  connection;
28134
28804
  info;
28135
- catalog;
28805
+ models;
28136
28806
  policy;
28137
28807
  limit;
28138
28808
  onClosed;
@@ -28154,17 +28824,17 @@ var V2Session = class {
28154
28824
  #cacheHitRatePercent;
28155
28825
  /** Assistant messages already published as usage requests. */
28156
28826
  #meteredMessages = /* @__PURE__ */ new Set();
28157
- constructor(client2, connection, info, catalog, policy, limit, onClosed) {
28827
+ constructor(client2, connection, info, models, policy, limit, onClosed) {
28158
28828
  this.client = client2;
28159
28829
  this.connection = connection;
28160
28830
  this.info = info;
28161
- this.catalog = catalog;
28831
+ this.models = models;
28162
28832
  this.policy = policy;
28163
28833
  this.limit = limit;
28164
28834
  this.onClosed = onClosed;
28165
- this.initialState = v2State(info, catalog, policy);
28835
+ this.initialState = v2State(info, models, policy);
28166
28836
  this.initialUsage = v2Usage(info);
28167
- this.capabilities = v2Capabilities(catalog);
28837
+ this.capabilities = v2Capabilities(models.catalog);
28168
28838
  this.commands = {
28169
28839
  list: async () => ({ ok: true, value: openCodeCommandCatalog }),
28170
28840
  execute: async (command) => {
@@ -28210,10 +28880,10 @@ var V2Session = class {
28210
28880
  return { ok: false, error: failure("OpenCode Session is busy", "sessionBusy") };
28211
28881
  try {
28212
28882
  this.info = await this.client.session.get({ sessionID: this.info.id });
28213
- const { snapshot } = await readHistory(this.client, this.info, this.limit);
28883
+ const { snapshot } = await readHistory(this.client, this.info, this.limit, this.models.index);
28214
28884
  return {
28215
28885
  ok: true,
28216
- value: { ...snapshot, state: v2State(this.info, this.catalog, this.policy) }
28886
+ value: { ...snapshot, state: v2State(this.info, this.models, this.policy) }
28217
28887
  };
28218
28888
  } catch (error51) {
28219
28889
  return errorResult(error51);
@@ -28227,8 +28897,8 @@ var V2Session = class {
28227
28897
  if (command.type === "turn.start")
28228
28898
  return this.#start(command, false);
28229
28899
  if (command.type === "turn.cancel") {
28230
- const active = this.#active;
28231
- if (!active?.admitted || active.turnId !== command.turnId)
28900
+ const active2 = this.#active;
28901
+ if (!active2?.admitted || active2.turnId !== command.turnId)
28232
28902
  return { ok: false, error: failure("No matching OpenCode Turn", "invalidState") };
28233
28903
  try {
28234
28904
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false });
@@ -28239,22 +28909,22 @@ var V2Session = class {
28239
28909
  }
28240
28910
  }
28241
28911
  if (command.type === "interaction.respond") {
28242
- const active = this.#active;
28243
- const pending = active?.interactions.get(command.interactionId);
28244
- 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))
28245
28915
  return {
28246
28916
  ok: false,
28247
28917
  error: failure("OpenCode interaction is no longer pending", "invalidState")
28248
28918
  };
28249
- active.replying.add(command.interactionId);
28919
+ active2.replying.add(command.interactionId);
28250
28920
  try {
28251
28921
  await replyInteraction(this.client, pending, command);
28252
- 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");
28253
28923
  return { ok: true, value: { accepted: true } };
28254
28924
  } catch (error51) {
28255
28925
  return errorResult(error51);
28256
28926
  } finally {
28257
- active.replying.delete(command.interactionId);
28927
+ active2.replying.delete(command.interactionId);
28258
28928
  }
28259
28929
  }
28260
28930
  if (this.#active || this.#configuring)
@@ -28271,14 +28941,12 @@ var V2Session = class {
28271
28941
  } else {
28272
28942
  let model2 = this.info.model;
28273
28943
  if (command.type === "model.select") {
28274
- if (!this.catalog.models.some((m) => m.ref.id === command.model.id))
28275
- throw new Error("OpenCode Model is not available");
28276
- const decoded = decodeOpenCodeModelRef(command.model);
28944
+ const decoded = decodeOpenCodeModelRef(command.model, this.models.index);
28277
28945
  model2 = { providerID: decoded.providerID, id: decoded.modelID };
28278
28946
  } else {
28279
28947
  if (!model2)
28280
28948
  throw new Error("Select a Model before a Thinking option");
28281
- const state = v2State(this.info, this.catalog, this.policy);
28949
+ const state = v2State(this.info, this.models, this.policy);
28282
28950
  if (!state.availableThinkingOptions?.some((v) => v.id === command.thinkingOptionId))
28283
28951
  throw new Error("Thinking option is unavailable for this Model");
28284
28952
  const variant = decodeOpenCodeVariant(command.thinkingOptionId);
@@ -28289,7 +28957,7 @@ var V2Session = class {
28289
28957
  this.info = await this.client.session.get({ sessionID: this.info.id });
28290
28958
  this.#emit({
28291
28959
  type: "session.state.changed",
28292
- state: v2State(this.info, this.catalog, this.policy)
28960
+ state: v2State(this.info, this.models, this.policy)
28293
28961
  });
28294
28962
  return { ok: true, value: { completed: true } };
28295
28963
  } catch (error51) {
@@ -28310,7 +28978,7 @@ var V2Session = class {
28310
28978
  const done = new Promise((r) => {
28311
28979
  resolve = r;
28312
28980
  });
28313
- const active = {
28981
+ const active2 = {
28314
28982
  turnId: command.turnId,
28315
28983
  compact,
28316
28984
  admitted: false,
@@ -28325,16 +28993,16 @@ var V2Session = class {
28325
28993
  done,
28326
28994
  resolve
28327
28995
  };
28328
- this.#active = active;
28996
+ this.#active = active2;
28329
28997
  let attempted = false;
28330
28998
  try {
28331
28999
  if ((await this.client.session.active())[this.info.id])
28332
29000
  throw new Error("OpenCode Session is already running");
28333
29001
  this.info = await this.client.session.get({ sessionID: this.info.id });
28334
- const before = await readHistory(this.client, this.info, this.limit);
29002
+ const before = await readHistory(this.client, this.info, this.limit, this.models.index);
28335
29003
  if (before.snapshot.turns.some((turn) => turn.outcome.status === "unknown"))
28336
29004
  throw new Error("OpenCode history contains an incomplete execution");
28337
- 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));
28338
29006
  attempted = true;
28339
29007
  if (compact)
28340
29008
  await this.client.session.compact({ sessionID: this.info.id });
@@ -28343,56 +29011,56 @@ var V2Session = class {
28343
29011
  sessionID: this.info.id,
28344
29012
  text: command.input.map((p) => p.text).join("\n"),
28345
29013
  delivery: "queue",
28346
- metadata: { "codexhost.turnId": active.turnId }
29014
+ metadata: { "codexhost.turnId": active2.turnId }
28347
29015
  });
28348
29016
  if (this.#closed) {
28349
29017
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false });
28350
29018
  throw new Error("OpenCode Session closed during admission");
28351
29019
  }
28352
- active.admitted = true;
28353
- this.#emit({ type: "turn.started", turnId: active.turnId });
28354
- for (const item of active.transient.values())
28355
- 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);
28356
29024
  void this.#refresh();
28357
- return { ok: true, value: { turnId: active.turnId } };
29025
+ return { ok: true, value: { turnId: active2.turnId } };
28358
29026
  } catch (error51) {
28359
29027
  if (attempted)
28360
29028
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false }).catch((interruptError) => this.#fault(errorResult(interruptError).error));
28361
- if (this.#active === active)
29029
+ if (this.#active === active2)
28362
29030
  this.#active = void 0;
28363
- active.resolve();
29031
+ active2.resolve();
28364
29032
  return errorResult(error51);
28365
29033
  }
28366
29034
  }
28367
29035
  #onEvent(event) {
28368
- const active = this.#active;
28369
- 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)
28370
29038
  return;
28371
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)) {
28372
- const id = event.data.assistantMessageID;
28373
- const timing = active.outputTiming.get(id) ?? {
29040
+ const id2 = event.data.assistantMessageID;
29041
+ const timing = active2.outputTiming.get(id2) ?? {
28374
29042
  firstOutputAtMs: Date.now(),
28375
29043
  reasoningObserved: false
28376
29044
  };
28377
29045
  if (event.type === "session.reasoning.started" || event.type === "session.reasoning.delta")
28378
29046
  timing.reasoningObserved = true;
28379
- active.outputTiming.set(id, timing);
29047
+ active2.outputTiming.set(id2, timing);
28380
29048
  }
28381
29049
  if (event.type === "session.step.started")
28382
- active.assistants.add(event.data.assistantMessageID);
28383
- 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)) {
28384
29052
  const contentType = event.type === "session.text.delta" ? "text" : "reasoning";
28385
29053
  const itemId2 = contentId(event.data.assistantMessageID, contentType, event.data.ordinal);
28386
29054
  const type = contentType === "text" ? "agentMessage" : "reasoning";
28387
- const previous = active.transient.get(itemId2);
29055
+ const previous = active2.transient.get(itemId2);
28388
29056
  const item = {
28389
29057
  type,
28390
29058
  itemId: itemId2,
28391
29059
  text: (previous?.text ?? "") + event.data.delta
28392
29060
  };
28393
- active.transient.set(itemId2, item);
28394
- if (active.admitted)
28395
- 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);
28396
29064
  }
28397
29065
  if (!event.type.endsWith(".delta"))
28398
29066
  void this.#refresh();
@@ -28458,31 +29126,31 @@ var V2Session = class {
28458
29126
  });
28459
29127
  }
28460
29128
  async #reconcile() {
28461
- const active = this.#active;
28462
- if (!active?.admitted)
29129
+ const active2 = this.#active;
29130
+ if (!active2?.admitted)
28463
29131
  return;
28464
29132
  const info = await this.client.session.get({ sessionID: this.info.id });
28465
- const { snapshot, messages } = await readHistory(this.client, info, this.limit);
28466
- 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)
28467
29135
  return;
28468
29136
  this.info = info;
28469
29137
  this.#meterUsage(messages, false);
28470
- 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));
28471
29139
  if (turns.length > 1)
28472
29140
  throw new Error("Concurrent native prompts cannot be assigned to one Host Turn");
28473
29141
  const turn = turns[0];
28474
29142
  if (turn) {
28475
29143
  const prompt = messages.find((message) => message.id === turn.nativeTurnRef.nativeTurnKey);
28476
- 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)
28477
29145
  throw new Error("Concurrent native input cannot be assigned to this Host Turn");
28478
29146
  const terminal = turn.outcome.status !== "unknown";
28479
29147
  for (const item of turn.items)
28480
- 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");
28481
29149
  if (terminal) {
28482
29150
  if ((await this.client.session.active())[info.id])
28483
29151
  return;
28484
- if (this.#active === active)
28485
- this.#finish(active, turn);
29152
+ if (this.#active === active2)
29153
+ this.#finish(active2, turn);
28486
29154
  return;
28487
29155
  }
28488
29156
  }
@@ -28490,39 +29158,39 @@ var V2Session = class {
28490
29158
  this.client.permission.list({ sessionID: info.id }),
28491
29159
  this.client.session.form.list({ sessionID: info.id })
28492
29160
  ]);
28493
- if (this.#active !== active || this.#closed)
29161
+ if (this.#active !== active2 || this.#closed)
28494
29162
  return;
28495
29163
  const current = /* @__PURE__ */ new Map();
28496
29164
  for (const request of permissions) {
28497
- const pending = permissionInteraction(request, active.turnId);
29165
+ const pending = permissionInteraction(request, active2.turnId);
28498
29166
  current.set(pending.interaction.interactionId, pending);
28499
29167
  }
28500
29168
  for (const form of forms) {
28501
- const pending = formInteraction(form, active.turnId);
29169
+ const pending = formInteraction(form, active2.turnId);
28502
29170
  current.set(pending.interaction.interactionId, pending);
28503
29171
  }
28504
- for (const [id, pending] of current)
28505
- if (!active.interactions.has(id) && !active.settledInteractions.has(id)) {
28506
- 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);
28507
29175
  this.#channel.emit({ kind: "interaction", interaction: pending.interaction });
28508
29176
  }
28509
- for (const id of active.interactions.keys())
28510
- if (!current.has(id) && !active.replying.has(id))
28511
- 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");
28512
29180
  }
28513
- #projectItem(active, snapshot, terminal, interrupted = false) {
29181
+ #projectItem(active2, snapshot, terminal, interrupted = false) {
28514
29182
  const item = snapshot.item;
28515
- const old = active.live.get(item.itemId);
29183
+ const old = active2.live.get(item.itemId);
28516
29184
  if (!old) {
28517
- active.live.set(item.itemId, item);
28518
- 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 });
28519
29187
  return;
28520
29188
  }
28521
29189
  if ((item.type === "agentMessage" || item.type === "reasoning") && "text" in old) {
28522
29190
  if (old.text.startsWith(item.text) && !terminal)
28523
29191
  return;
28524
29192
  if (terminal && interrupted && old.text.startsWith(item.text)) {
28525
- active.live.set(item.itemId, item);
29193
+ active2.live.set(item.itemId, item);
28526
29194
  return;
28527
29195
  }
28528
29196
  if (!item.text.startsWith(old.text))
@@ -28531,60 +29199,60 @@ var V2Session = class {
28531
29199
  if (delta)
28532
29200
  this.#emit({
28533
29201
  type: "item.updated",
28534
- turnId: active.turnId,
29202
+ turnId: active2.turnId,
28535
29203
  itemId: item.itemId,
28536
29204
  update: { type: "text.append", text: delta }
28537
29205
  });
28538
29206
  } else if (item.type === "toolExecution" && item.output && JSON.stringify(item) !== JSON.stringify(old)) {
28539
29207
  this.#emit({
28540
29208
  type: "item.updated",
28541
- turnId: active.turnId,
29209
+ turnId: active2.turnId,
28542
29210
  itemId: item.itemId,
28543
29211
  update: { type: "output.replace", output: item.output }
28544
29212
  });
28545
29213
  }
28546
- active.live.set(item.itemId, item);
29214
+ active2.live.set(item.itemId, item);
28547
29215
  }
28548
- #finish(active, turn) {
28549
- if (this.#active !== active || turn.outcome.status === "unknown")
29216
+ #finish(active2, turn) {
29217
+ if (this.#active !== active2 || turn.outcome.status === "unknown")
28550
29218
  return;
28551
- for (const id of active.interactions.keys())
28552
- this.#closeInteraction(active, id, "cancelled");
28553
- for (const [id, item] of active.live) {
28554
- 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) ?? {
28555
29223
  item,
28556
29224
  outcome: terminalItemOutcome(turn.outcome)
28557
29225
  };
28558
- this.#emit({ type: "item.completed", turnId: active.turnId, snapshot });
29226
+ this.#emit({ type: "item.completed", turnId: active2.turnId, snapshot });
28559
29227
  }
28560
29228
  this.#emit({
28561
29229
  type: "session.state.changed",
28562
- state: v2State(this.info, this.catalog, this.policy)
29230
+ state: v2State(this.info, this.models, this.policy)
28563
29231
  });
28564
29232
  this.#emit({
28565
29233
  type: "session.usage.changed",
28566
29234
  usage: this.#usage(),
28567
- observedForTurnId: active.turnId
29235
+ observedForTurnId: active2.turnId
28568
29236
  });
28569
29237
  this.#active = void 0;
28570
29238
  this.#emit({
28571
29239
  type: "turn.completed",
28572
- turnId: active.turnId,
29240
+ turnId: active2.turnId,
28573
29241
  nativeTurnRef: turn.nativeTurnRef,
28574
29242
  outcome: { ...turn.outcome, ...turn.checkpoint ? { checkpoint: turn.checkpoint } : {} }
28575
29243
  });
28576
- active.resolve();
29244
+ active2.resolve();
28577
29245
  }
28578
- #closeInteraction(active, id, reason) {
28579
- const pending = active.interactions.get(id);
29246
+ #closeInteraction(active2, id2, reason) {
29247
+ const pending = active2.interactions.get(id2);
28580
29248
  if (!pending)
28581
29249
  return;
28582
- active.interactions.delete(id);
28583
- active.settledInteractions.add(id);
29250
+ active2.interactions.delete(id2);
29251
+ active2.settledInteractions.add(id2);
28584
29252
  this.#emit({
28585
29253
  type: "interaction.closed",
28586
29254
  interactionId: pending.interaction.interactionId,
28587
- turnId: active.turnId,
29255
+ turnId: active2.turnId,
28588
29256
  reason
28589
29257
  });
28590
29258
  }
@@ -28598,24 +29266,24 @@ var V2Session = class {
28598
29266
  if (this.#timer)
28599
29267
  clearInterval(this.#timer);
28600
29268
  this.#abort.abort();
28601
- const active = this.#active;
28602
- if (active?.admitted) {
28603
- for (const id of active.interactions.keys())
28604
- this.#closeInteraction(active, id, "cancelled");
28605
- 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())
28606
29274
  this.#emit({
28607
29275
  type: "item.completed",
28608
- turnId: active.turnId,
29276
+ turnId: active2.turnId,
28609
29277
  snapshot: { item, outcome: { status: "failed", error: error51 } }
28610
29278
  });
28611
29279
  this.#emit({
28612
29280
  type: "turn.completed",
28613
- turnId: active.turnId,
29281
+ turnId: active2.turnId,
28614
29282
  outcome: { status: "failed", error: error51 }
28615
29283
  });
28616
29284
  }
28617
29285
  this.#active = void 0;
28618
- active?.resolve();
29286
+ active2?.resolve();
28619
29287
  this.#emit({ type: "session.faulted", error: error51 });
28620
29288
  this.#channel.end();
28621
29289
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false }).catch(() => void 0);
@@ -28624,14 +29292,14 @@ var V2Session = class {
28624
29292
  }
28625
29293
  close() {
28626
29294
  return this.#closePromise ??= (async () => {
28627
- const active = this.#active;
28628
- if (active?.admitted && !this.#closed) {
29295
+ const active2 = this.#active;
29296
+ if (active2?.admitted && !this.#closed) {
28629
29297
  await this.client.session.interrupt({ sessionID: this.info.id, resume: false }).catch(() => void 0);
28630
29298
  await this.#refresh();
28631
29299
  if (this.#active) {
28632
29300
  let timer;
28633
29301
  await Promise.race([
28634
- active.done,
29302
+ active2.done,
28635
29303
  new Promise((resolve) => {
28636
29304
  timer = setTimeout(resolve, this.connection.options.closeTimeoutMs ?? 3e3);
28637
29305
  })
@@ -28669,7 +29337,7 @@ var V2Adapter = class {
28669
29337
  async #catalog(client2, cwd) {
28670
29338
  return readCatalog(client2, cwd, this.options.startupTimeoutMs ?? 2e4);
28671
29339
  }
28672
- async inspect(input = {}) {
29340
+ async inspect(input = {}, onModels) {
28673
29341
  const cwd = input.cwd ?? process.cwd();
28674
29342
  const connection = new V2Connection(this.options, cwd);
28675
29343
  this.#connections.add(connection);
@@ -28677,7 +29345,9 @@ var V2Adapter = class {
28677
29345
  if (this.#closed)
28678
29346
  throw new Error("OpenCode Adapter is closed");
28679
29347
  const client2 = await connection.client();
28680
- const catalog = await this.#catalog(client2, cwd);
29348
+ const models = await this.#catalog(client2, cwd);
29349
+ onModels?.(models);
29350
+ const { catalog } = models;
28681
29351
  return {
28682
29352
  status: "ready",
28683
29353
  catalog,
@@ -28756,10 +29426,10 @@ var V2Adapter = class {
28756
29426
  policy = locator.executionPolicy;
28757
29427
  }
28758
29428
  client2 = await connection.client();
28759
- const catalog = await this.#catalog(client2, input.cwd);
29429
+ const models = await this.#catalog(client2, input.cwd);
28760
29430
  let info;
28761
29431
  if (input.kind === "create") {
28762
- const model2 = selectedModel(input, catalog);
29432
+ const model2 = selectedModel(input, models);
28763
29433
  info = await client2.session.create({
28764
29434
  location: { directory: input.cwd },
28765
29435
  ...model2 ? { model: model2 } : {},
@@ -28773,7 +29443,7 @@ var V2Adapter = class {
28773
29443
  throw new Error("OpenCode returned a different Native Session or directory");
28774
29444
  if ((await client2.session.active())[info.id])
28775
29445
  throw new Error("OpenCode Session is already running");
28776
- const source = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3);
29446
+ const source = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3, models.index);
28777
29447
  if (source.snapshot.turns.some((turn) => turn.outcome.status === "unknown"))
28778
29448
  throw new Error("OpenCode history contains an incomplete execution");
28779
29449
  if (input.kind !== "resume") {
@@ -28805,7 +29475,7 @@ var V2Adapter = class {
28805
29475
  if (parent.model)
28806
29476
  await client2.session.switchModel({ sessionID: info.id, model: parent.model });
28807
29477
  info = await client2.session.get({ sessionID: info.id });
28808
- const derived = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3);
29478
+ const derived = await readHistory(client2, info, this.options.toolOutputLimit ?? 64e3, models.index);
28809
29479
  if (historyContent(derived.snapshot, false) !== historyContent({ turns: turns.slice(0, count2) }, false))
28810
29480
  throw new Error("OpenCode fork did not preserve the exact history prefix");
28811
29481
  if (!isDeepStrictEqual2(info.permissions ?? [], parent.permissions ?? []) || !isDeepStrictEqual2(info.model, parent.model))
@@ -28813,14 +29483,14 @@ var V2Adapter = class {
28813
29483
  const currentParent = await client2.session.get({ sessionID: parent.id });
28814
29484
  if (!isDeepStrictEqual2(currentParent.model, parent.model) || !isDeepStrictEqual2(currentParent.permissions, parent.permissions) || !sameDirectory(currentParent.location.directory, parent.location.directory))
28815
29485
  throw new Error("OpenCode source configuration changed during derivation");
28816
- const unchanged = await readHistory(client2, currentParent, this.options.toolOutputLimit ?? 64e3);
29486
+ const unchanged = await readHistory(client2, currentParent, this.options.toolOutputLimit ?? 64e3, models.index);
28817
29487
  if (historyContent(unchanged.snapshot) !== historyContent(source.snapshot))
28818
29488
  throw new Error("OpenCode source history changed during derivation");
28819
29489
  }
28820
29490
  }
28821
29491
  if (this.#closed)
28822
29492
  throw new Error("OpenCode Adapter closed during Session open");
28823
- 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, () => {
28824
29494
  this.#sessions.delete(session);
28825
29495
  this.#connections.delete(connection);
28826
29496
  });
@@ -28848,7 +29518,7 @@ var V2Adapter = class {
28848
29518
  this.#connections.clear();
28849
29519
  }
28850
29520
  };
28851
- function selectedModel(input, catalog) {
29521
+ function selectedModel(input, { catalog, index }) {
28852
29522
  const selected = input.model ?? catalog.defaultModel;
28853
29523
  if (!selected) {
28854
29524
  if (input.thinkingOptionId)
@@ -28860,7 +29530,7 @@ function selectedModel(input, catalog) {
28860
29530
  throw new Error("OpenCode Model is not available");
28861
29531
  if (input.thinkingOptionId && !entry.supportedThinkingOptionIds?.includes(input.thinkingOptionId))
28862
29532
  throw new Error("OpenCode Thinking option is not available for this Model");
28863
- const model2 = decodeOpenCodeModelRef(selected);
29533
+ const model2 = decodeOpenCodeModelRef(selected, index);
28864
29534
  const variant = input.thinkingOptionId ? decodeOpenCodeVariant(input.thinkingOptionId) : void 0;
28865
29535
  return { providerID: model2.providerID, id: model2.modelID, ...variant ? { variant } : {} };
28866
29536
  }
@@ -28884,6 +29554,19 @@ var OpenCodeAdapter2 = class {
28884
29554
  dependencies;
28885
29555
  harnessId = harnessId;
28886
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
+ };
28887
29570
  #adapters = /* @__PURE__ */ new Set();
28888
29571
  #closed = false;
28889
29572
  usageStatistics;
@@ -28948,7 +29631,10 @@ var OpenCodeAdapter2 = class {
28948
29631
  let adapter;
28949
29632
  try {
28950
29633
  adapter = await this.#select();
28951
- 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
+ });
28952
29638
  } catch (error51) {
28953
29639
  return {
28954
29640
  status: error51 instanceof OpenCodeExecutableError ? "notInstalled" : "error",
@@ -28989,6 +29675,7 @@ var OpenCodeAdapter2 = class {
28989
29675
  }
28990
29676
  async close() {
28991
29677
  this.#closed = true;
29678
+ this.#inspectedModels.clear();
28992
29679
  await Promise.all([...this.#adapters].map((adapter) => adapter.close()));
28993
29680
  this.#adapters.clear();
28994
29681
  }