@codexhost/cli-linux-arm64 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
  }
@@ -1625,8 +1625,8 @@ function cleanEnum(obj) {
1625
1625
  return Number.isNaN(Number.parseInt(k, 10));
1626
1626
  }).map((el) => el[1]);
1627
1627
  }
1628
- function base64ToUint8Array(base643) {
1629
- const binaryString = atob(base643);
1628
+ function base64ToUint8Array(base644) {
1629
+ const binaryString = atob(base644);
1630
1630
  const bytes = new Uint8Array(binaryString.length);
1631
1631
  for (let i = 0; i < binaryString.length; i++) {
1632
1632
  bytes[i] = binaryString.charCodeAt(i);
@@ -1641,9 +1641,9 @@ function uint8ArrayToBase64(bytes) {
1641
1641
  return btoa(binaryString);
1642
1642
  }
1643
1643
  function base64urlToUint8Array(base64url3) {
1644
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1645
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1646
- return base64ToUint8Array(base643 + padding);
1644
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1645
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1646
+ return base64ToUint8Array(base644 + padding);
1647
1647
  }
1648
1648
  function uint8ArrayToBase64url(bytes) {
1649
1649
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -3009,8 +3009,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
3009
3009
  function isValidBase64URL(data) {
3010
3010
  if (!base64url.test(data))
3011
3011
  return false;
3012
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3013
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
3012
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3013
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
3014
3014
  return isValidBase64(padded);
3015
3015
  }
3016
3016
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -3464,42 +3464,42 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3464
3464
  }
3465
3465
  doc.write(`const newResult = {};`);
3466
3466
  for (const key of normalized.keys) {
3467
- const id = ids[key];
3467
+ const id2 = ids[key];
3468
3468
  const k = esc(key);
3469
3469
  const schema = shape[key];
3470
3470
  const isOptionalIn = schema?._zod?.optin === "optional";
3471
3471
  const isOptionalOut = schema?._zod?.optout === "optional";
3472
- doc.write(`const ${id} = ${parseStr(key)};`);
3472
+ doc.write(`const ${id2} = ${parseStr(key)};`);
3473
3473
  if (isOptionalIn && isOptionalOut) {
3474
3474
  doc.write(`
3475
- if (${id}.issues.length) {
3475
+ if (${id2}.issues.length) {
3476
3476
  if (${k} in input) {
3477
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3477
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3478
3478
  ...iss,
3479
3479
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3480
3480
  })));
3481
3481
  }
3482
3482
  }
3483
3483
 
3484
- if (${id}.value === undefined) {
3484
+ if (${id2}.value === undefined) {
3485
3485
  if (${k} in input) {
3486
3486
  newResult[${k}] = undefined;
3487
3487
  }
3488
3488
  } else {
3489
- newResult[${k}] = ${id}.value;
3489
+ newResult[${k}] = ${id2}.value;
3490
3490
  }
3491
3491
 
3492
3492
  `);
3493
3493
  } else if (!isOptionalIn) {
3494
3494
  doc.write(`
3495
- const ${id}_present = ${k} in input;
3496
- if (${id}.issues.length) {
3497
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3495
+ const ${id2}_present = ${k} in input;
3496
+ if (${id2}.issues.length) {
3497
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3498
3498
  ...iss,
3499
3499
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3500
3500
  })));
3501
3501
  }
3502
- if (!${id}_present && !${id}.issues.length) {
3502
+ if (!${id2}_present && !${id2}.issues.length) {
3503
3503
  payload.issues.push({
3504
3504
  code: "invalid_type",
3505
3505
  expected: "nonoptional",
@@ -3508,30 +3508,30 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3508
3508
  });
3509
3509
  }
3510
3510
 
3511
- if (${id}_present) {
3512
- if (${id}.value === undefined) {
3511
+ if (${id2}_present) {
3512
+ if (${id2}.value === undefined) {
3513
3513
  newResult[${k}] = undefined;
3514
3514
  } else {
3515
- newResult[${k}] = ${id}.value;
3515
+ newResult[${k}] = ${id2}.value;
3516
3516
  }
3517
3517
  }
3518
3518
 
3519
3519
  `);
3520
3520
  } else {
3521
3521
  doc.write(`
3522
- if (${id}.issues.length) {
3523
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3522
+ if (${id2}.issues.length) {
3523
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3524
3524
  ...iss,
3525
3525
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3526
3526
  })));
3527
3527
  }
3528
3528
 
3529
- if (${id}.value === undefined) {
3529
+ if (${id2}.value === undefined) {
3530
3530
  if (${k} in input) {
3531
3531
  newResult[${k}] = undefined;
3532
3532
  }
3533
3533
  } else {
3534
- newResult[${k}] = ${id}.value;
3534
+ newResult[${k}] = ${id2}.value;
3535
3535
  }
3536
3536
 
3537
3537
  `);
@@ -11863,26 +11863,26 @@ function extractDefs(ctx, schema) {
11863
11863
  throw new Error("Unprocessed schema. This is a bug in Zod.");
11864
11864
  const idToSchema = /* @__PURE__ */ new Map();
11865
11865
  for (const entry of ctx.seen.entries()) {
11866
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11867
- if (id) {
11868
- const existing = idToSchema.get(id);
11866
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11867
+ if (id2) {
11868
+ const existing = idToSchema.get(id2);
11869
11869
  if (existing && existing !== entry[0]) {
11870
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11870
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11871
11871
  }
11872
- idToSchema.set(id, entry[0]);
11872
+ idToSchema.set(id2, entry[0]);
11873
11873
  }
11874
11874
  }
11875
11875
  const makeURI = (entry) => {
11876
11876
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
11877
11877
  if (ctx.external) {
11878
11878
  const externalId = ctx.external.registry.get(entry[0])?.id;
11879
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
11879
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
11880
11880
  if (externalId) {
11881
11881
  return { ref: uriGenerator(externalId) };
11882
11882
  }
11883
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11884
- entry[1].defId = id;
11885
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
11883
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11884
+ entry[1].defId = id2;
11885
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
11886
11886
  }
11887
11887
  if (entry[1] === root) {
11888
11888
  return { ref: "#" };
@@ -11930,8 +11930,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11930
11930
  continue;
11931
11931
  }
11932
11932
  }
11933
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11934
- if (id) {
11933
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11934
+ if (id2) {
11935
11935
  extractToDef(entry);
11936
11936
  continue;
11937
11937
  }
@@ -12027,10 +12027,10 @@ function finalize(ctx, schema) {
12027
12027
  } else {
12028
12028
  }
12029
12029
  if (ctx.external?.uri) {
12030
- const id = ctx.external.registry.get(schema)?.id;
12031
- if (!id)
12030
+ const id2 = ctx.external.registry.get(schema)?.id;
12031
+ if (!id2)
12032
12032
  throw new Error("Schema is missing an `id` property");
12033
- result.$id = ctx.external.uri(id);
12033
+ result.$id = ctx.external.uri(id2);
12034
12034
  }
12035
12035
  Object.assign(result, root.def ?? root.schema);
12036
12036
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -12190,9 +12190,9 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12190
12190
  json2.type = "number";
12191
12191
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
12192
12192
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
12193
- const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12193
+ const legacy2 = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12194
12194
  if (exMin) {
12195
- if (legacy) {
12195
+ if (legacy2) {
12196
12196
  json2.minimum = exclusiveMinimum;
12197
12197
  json2.exclusiveMinimum = true;
12198
12198
  } else {
@@ -12202,7 +12202,7 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12202
12202
  json2.minimum = minimum;
12203
12203
  }
12204
12204
  if (exMax) {
12205
- if (legacy) {
12205
+ if (legacy2) {
12206
12206
  json2.maximum = exclusiveMaximum;
12207
12207
  json2.exclusiveMaximum = true;
12208
12208
  } else {
@@ -13064,7 +13064,7 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
13064
13064
 
13065
13065
  // ../../../node_modules/zod/v4/classic/schemas.js
13066
13066
  var _installedGroups = /* @__PURE__ */ new WeakMap();
13067
- function _installLazyMethods(inst, group, methods2) {
13067
+ function _installLazyMethods(inst, group, methods3) {
13068
13068
  const proto = Object.getPrototypeOf(inst);
13069
13069
  let installed = _installedGroups.get(proto);
13070
13070
  if (!installed) {
@@ -13074,8 +13074,8 @@ function _installLazyMethods(inst, group, methods2) {
13074
13074
  if (installed.has(group))
13075
13075
  return;
13076
13076
  installed.add(group);
13077
- for (const key in methods2) {
13078
- const fn = methods2[key];
13077
+ for (const key in methods3) {
13078
+ const fn = methods3[key];
13079
13079
  Object.defineProperty(proto, key, {
13080
13080
  configurable: true,
13081
13081
  enumerable: false,
@@ -15019,6 +15019,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15019
15019
  permissionModeId: harnessPermissionModeIdSchema
15020
15020
  }).strict();
15021
15021
 
15022
+ // ../../shared-contracts/dist/harness-route-limit.js
15023
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
15024
+
15022
15025
  // ../../shared-contracts/dist/thread-usage.js
15023
15026
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15024
15027
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -15051,7 +15054,7 @@ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15051
15054
  expiresAtUnix: nonNegativeSafeIntegerSchema,
15052
15055
  label: indicatorTextSchema(256).optional(),
15053
15056
  tooltip: indicatorTextSchema(1024).optional()
15054
- }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15057
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
15055
15058
  message: "Composer indicator IDs must be unique"
15056
15059
  });
15057
15060
  var threadUsageSnapshotSchema = external_exports.object({
@@ -15077,6 +15080,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15077
15080
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15078
15081
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15079
15082
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15083
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15080
15084
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15081
15085
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15082
15086
  }).strict().superRefine((usage, context) => {
@@ -15174,6 +15178,13 @@ var accountCreditsSnapshotSchema = external_exports.object({
15174
15178
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15175
15179
  resetCredits: accountResetCreditsSchema.optional()
15176
15180
  }).strict();
15181
+ var accountBalanceSnapshotSchema = external_exports.object({
15182
+ amount: external_exports.number().finite().nonnegative(),
15183
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15184
+ currency: external_exports.string().trim().min(1).max(8),
15185
+ /** Native label when the Harness exposes several Billing Sources. */
15186
+ label: external_exports.string().trim().min(1).max(128).optional()
15187
+ }).strict();
15177
15188
  var threadUsageInspectionParamsSchema = external_exports.object({
15178
15189
  threadId: hostThreadIdSchema,
15179
15190
  refresh: external_exports.literal("exact").optional()
@@ -15182,7 +15193,10 @@ var threadUsageInspectionSchema = external_exports.object({
15182
15193
  threadId: hostThreadIdSchema,
15183
15194
  usage: threadUsageSnapshotSchema.nullable(),
15184
15195
  accountCredits: accountCreditsSnapshotSchema.optional(),
15185
- /** Whether this source can provide cached account quota independently of usage. */
15196
+ /** Prepaid funds for the Thread's Billing Source; shown only when no percentage quota exists. */
15197
+ accountBalance: accountBalanceSnapshotSchema.optional(),
15198
+ /** Whether this source can provide cached account quota (credits or a prepaid balance)
15199
+ * independently of usage. */
15186
15200
  accountCreditsSupported: external_exports.boolean().optional()
15187
15201
  }).strict();
15188
15202
 
@@ -15194,10 +15208,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
15194
15208
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15195
15209
  message: "Value must not be empty or whitespace"
15196
15210
  });
15197
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
15211
+ 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();
15212
+ var harnessModelServiceTierSchema = external_exports.enum(["priority", "ultrafast"]);
15198
15213
  var harnessModelRefSchema = external_exports.object({
15199
- id: harnessModelRefIdSchema
15214
+ id: harnessModelRefIdSchema,
15215
+ serviceTier: harnessModelServiceTierSchema.optional()
15200
15216
  }).strict();
15217
+ function sameHarnessModelRef(left, right) {
15218
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
15219
+ }
15201
15220
  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();
15202
15221
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15203
15222
  var harnessThinkingOptionSchema = external_exports.object({
@@ -15211,7 +15230,15 @@ var harnessModelSchema = external_exports.object({
15211
15230
  /** Optional opaque selection for this same Model with priority processing enabled. */
15212
15231
  fastModel: harnessModelRefSchema.optional(),
15213
15232
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
15214
- }).strict();
15233
+ }).strict().refine((model2) => model2.fastModel?.serviceTier === void 0 || model2.fastModel.id === model2.ref.id, {
15234
+ path: ["fastModel", "id"],
15235
+ message: "A tiered Fast Model must share the base Model ID"
15236
+ });
15237
+ function catalogModelForRef(catalog, ref) {
15238
+ if (!ref)
15239
+ return void 0;
15240
+ return catalog?.models.find((model2) => sameHarnessModelRef(model2.ref, ref) || sameHarnessModelRef(model2.fastModel, ref));
15241
+ }
15215
15242
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
15216
15243
  const ids = /* @__PURE__ */ new Set();
15217
15244
  for (const [index, option] of options.entries()) {
@@ -15231,26 +15258,26 @@ var harnessModelCatalogSchema = external_exports.object({
15231
15258
  thinkingOptions: harnessThinkingOptionsSchema,
15232
15259
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
15233
15260
  }).strict().superRefine((catalog, context) => {
15234
- const refs = /* @__PURE__ */ new Set();
15235
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15261
+ const refs = [];
15262
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
15236
15263
  for (const [index, model2] of catalog.models.entries()) {
15237
- if (refs.has(model2.ref.id)) {
15264
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
15238
15265
  context.addIssue({
15239
15266
  code: "custom",
15240
15267
  message: "Model Catalog refs must be unique",
15241
15268
  path: ["models", index, "ref", "id"]
15242
15269
  });
15243
15270
  }
15244
- refs.add(model2.ref.id);
15271
+ refs.push(model2.ref);
15245
15272
  if (model2.fastModel) {
15246
- if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15273
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.fastModel))) {
15247
15274
  context.addIssue({
15248
15275
  code: "custom",
15249
15276
  message: "Fast Model refs must be distinct and unique",
15250
15277
  path: ["models", index, "fastModel"]
15251
15278
  });
15252
15279
  }
15253
- refs.add(model2.fastModel.id);
15280
+ refs.push(model2.fastModel);
15254
15281
  }
15255
15282
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15256
15283
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -15271,7 +15298,7 @@ var harnessModelCatalogSchema = external_exports.object({
15271
15298
  }
15272
15299
  }
15273
15300
  }
15274
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
15301
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
15275
15302
  context.addIssue({
15276
15303
  code: "custom",
15277
15304
  message: "Default Model must exist in the Model Catalog",
@@ -15311,7 +15338,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15311
15338
  observe: external_exports.boolean()
15312
15339
  }).strict().optional(),
15313
15340
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15314
- steer: external_exports.boolean().optional()
15341
+ steer: external_exports.boolean().optional(),
15342
+ /**
15343
+ * True when the native plan (task list) outlives the Turn that changed it, so a reopened
15344
+ * Thread gets its latest plan again. Otherwise a plan stays with the Turn that made it.
15345
+ */
15346
+ persistentPlan: external_exports.boolean().optional()
15315
15347
  }).strict();
15316
15348
  var harnessConfigurationStateSchema = external_exports.object({
15317
15349
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15320,7 +15352,7 @@ var harnessConfigurationStateSchema = external_exports.object({
15320
15352
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15321
15353
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
15322
15354
  }).strict().superRefine((state, context) => {
15323
- if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id }) => id === state.effectiveThinkingOptionId)) {
15355
+ if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id: id2 }) => id2 === state.effectiveThinkingOptionId)) {
15324
15356
  context.addIssue({
15325
15357
  code: "custom",
15326
15358
  message: "Effective Thinking option must be currently available",
@@ -15360,7 +15392,8 @@ var harnessInspectParamsSchema = external_exports.object({
15360
15392
  cwd: nonBlankTextSchema2.max(16384).optional(),
15361
15393
  refresh: external_exports.boolean().optional(),
15362
15394
  /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15363
- purpose: external_exports.literal("availability").optional()
15395
+ purpose: external_exports.literal("availability").optional(),
15396
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
15364
15397
  }).strict();
15365
15398
  var harnessWebUiOpenParamsSchema = external_exports.object({
15366
15399
  harnessId: harnessIdSchema
@@ -15391,7 +15424,7 @@ var codexThreadInspectionSchema = external_exports.object({
15391
15424
  var externalThreadInspectionSchema = external_exports.object({
15392
15425
  owner: external_exports.literal("external"),
15393
15426
  harnessId: nonBlankTextSchema2.max(256),
15394
- transportModelId: nonBlankTextSchema2.max(1024),
15427
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
15395
15428
  effectiveModel: harnessModelRefSchema.optional(),
15396
15429
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15397
15430
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15473,13 +15506,635 @@ var threadSteeringInspectResultSchema = external_exports.object({
15473
15506
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15474
15507
  }).strict();
15475
15508
 
15509
+ // ../../shared-contracts/dist/harness-plugins.js
15510
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15511
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15512
+ var HARNESS_PLUGIN_LIMIT = 128;
15513
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
15514
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
15515
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id2) => id2 !== "codex", "The official Codex identity is reserved");
15516
+ 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");
15517
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15518
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15519
+ var harnessInstallationGuideSchema = external_exports.object({
15520
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15521
+ before: localizedTextSchema.optional(),
15522
+ after: localizedTextSchema.optional(),
15523
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15524
+ }).strict();
15525
+ var pluginPresentationShape = {
15526
+ id: installedHarnessPluginIdSchema,
15527
+ name: external_exports.string().trim().min(1).max(128),
15528
+ version: external_exports.string().min(1).max(128),
15529
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15530
+ kind: external_exports.literal("usage").optional(),
15531
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15532
+ iconStyle: external_exports.object({
15533
+ vector: external_exports.object({
15534
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15535
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15536
+ paths: external_exports.array(external_exports.object({
15537
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15538
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15539
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15540
+ }).strict()).min(1).max(32)
15541
+ }).strict().optional(),
15542
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15543
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15544
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15545
+ }).strict().optional(),
15546
+ installation: harnessInstallationGuideSchema.optional(),
15547
+ notice: localizedTextSchema.optional(),
15548
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15549
+ launchCommand: external_exports.literal(true).optional(),
15550
+ links: external_exports.object({
15551
+ website: documentationUrlSchema.optional(),
15552
+ documentation: documentationUrlSchema.optional(),
15553
+ installation: documentationUrlSchema.optional()
15554
+ }).strict().optional()
15555
+ };
15556
+ var harnessPluginManifestSchema = external_exports.object({
15557
+ manifestVersion: external_exports.literal(1),
15558
+ ...pluginPresentationShape,
15559
+ adapterApiVersion: external_exports.number().int().positive(),
15560
+ entry: pluginRelativeResourceSchema,
15561
+ icon: pluginRelativeResourceSchema.optional()
15562
+ }).strict();
15563
+ 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);
15564
+ var harnessPluginDescriptorSchema = external_exports.object({
15565
+ ...pluginPresentationShape,
15566
+ icon: harnessPluginIconSchema.optional()
15567
+ }).strict();
15568
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15569
+ var harnessPluginListResultSchema = external_exports.object({
15570
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15571
+ }).strict();
15572
+ var harnessPluginConfigurationSchema = external_exports.object({
15573
+ version: external_exports.literal(1),
15574
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15575
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15576
+ message: "Enabled plugin IDs must be unique",
15577
+ path: ["enabled"]
15578
+ });
15579
+
15580
+ // ../../shared-contracts/dist/desktop-extensions.js
15581
+ var DESKTOP_EXTENSION_API_VERSION = 1;
15582
+ var DESKTOP_EXTENSION_LIMIT = 64;
15583
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15584
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15585
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15586
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15587
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15588
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15589
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15590
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15591
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15592
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15593
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15594
+ var desktopExtensionIdSchema = installedPluginIdSchema;
15595
+ var desktopExtensionSlotSchema = external_exports.enum([
15596
+ "sidebar.thread-layout",
15597
+ "sidebar.thread-badge",
15598
+ "appearance.theme"
15599
+ ]);
15600
+ var desktopExtensionCategorySchema = external_exports.enum([
15601
+ "appearance",
15602
+ "interface",
15603
+ "workflow",
15604
+ "analytics",
15605
+ "integrations",
15606
+ "tools"
15607
+ ]);
15608
+ var extensionName = external_exports.string().trim().min(1).max(128);
15609
+ function desktopExtensionScreenshotMimeType(resource) {
15610
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15611
+ case "png":
15612
+ return "image/png";
15613
+ case "jpg":
15614
+ case "jpeg":
15615
+ return "image/jpeg";
15616
+ case "webp":
15617
+ return "image/webp";
15618
+ default:
15619
+ return void 0;
15620
+ }
15621
+ }
15622
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15623
+ 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");
15624
+ 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) => {
15625
+ const { username, password } = new URL(value);
15626
+ return !username && !password && !/[\\\s]/u.test(value);
15627
+ }, "URL must not contain credentials, backslashes, or whitespace");
15628
+ function localizedText(text) {
15629
+ return external_exports.strictObject({ en: text, "zh-CN": text });
15630
+ }
15631
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15632
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15633
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15634
+ var settingField = {
15635
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15636
+ label: desktopExtensionLocalizedTextSchema,
15637
+ description: desktopExtensionLocalizedTextSchema.optional()
15638
+ };
15639
+ var numericSetting = {
15640
+ ...settingField,
15641
+ step: external_exports.number().positive().optional(),
15642
+ default: external_exports.number().optional()
15643
+ };
15644
+ var settingOption = external_exports.strictObject({
15645
+ value: external_exports.string(),
15646
+ label: desktopExtensionLocalizedTextSchema
15647
+ });
15648
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15649
+ external_exports.strictObject({
15650
+ ...settingField,
15651
+ type: external_exports.literal("boolean"),
15652
+ default: external_exports.boolean().optional()
15653
+ }),
15654
+ external_exports.strictObject({
15655
+ ...settingField,
15656
+ type: external_exports.literal("string"),
15657
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
15658
+ default: external_exports.string().optional()
15659
+ }),
15660
+ external_exports.strictObject({
15661
+ ...numericSetting,
15662
+ type: external_exports.literal("number"),
15663
+ min: external_exports.number().optional(),
15664
+ max: external_exports.number().optional()
15665
+ }),
15666
+ external_exports.strictObject({
15667
+ ...numericSetting,
15668
+ type: external_exports.literal("range"),
15669
+ min: external_exports.number(),
15670
+ max: external_exports.number()
15671
+ }),
15672
+ external_exports.strictObject({
15673
+ ...settingField,
15674
+ type: external_exports.literal("select"),
15675
+ options: external_exports.array(settingOption).min(1),
15676
+ default: external_exports.string().optional()
15677
+ })
15678
+ ]).superRefine((field2, ctx) => {
15679
+ const issue2 = (path17, message) => ctx.addIssue({ code: "custom", path: [path17], message });
15680
+ if (field2.type === "number" || field2.type === "range") {
15681
+ const { min = -Infinity, max = Infinity, default: value } = field2;
15682
+ if (min > max)
15683
+ issue2("max", "Must be at least min");
15684
+ if (value !== void 0 && (value < min || value > max))
15685
+ issue2("default", "Must be within min and max");
15686
+ } else if (field2.type === "select") {
15687
+ const values = new Set(field2.options.map(({ value }) => value));
15688
+ if (values.size !== field2.options.length)
15689
+ issue2("options", "Duplicate option values");
15690
+ if (field2.default !== void 0 && !values.has(field2.default))
15691
+ issue2("default", "Must match an option value");
15692
+ }
15693
+ });
15694
+ var manifestHeader = external_exports.object({
15695
+ manifestVersion: external_exports.int().positive(),
15696
+ id: desktopExtensionIdSchema,
15697
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
15698
+ version: external_exports.string().min(1).max(128),
15699
+ desktopApi: external_exports.int().positive()
15700
+ }).passthrough();
15701
+ var desktopExtensionManifestSchema = manifestHeader.extend({
15702
+ manifestVersion: external_exports.literal(1),
15703
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15704
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15705
+ author: external_exports.string().trim().min(1).max(128).optional(),
15706
+ repository: desktopExtensionHttpUrlSchema.optional(),
15707
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15708
+ icon: imagePathSchema.optional(),
15709
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15710
+ desktop: external_exports.strictObject({
15711
+ script: pluginRelativeResourceSchema,
15712
+ style: pluginRelativeResourceSchema.optional()
15713
+ }).optional(),
15714
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15715
+ slots: slotsSchema.default(() => []),
15716
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15717
+ categories: categoriesSchema.optional()
15718
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15719
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15720
+ var desktopExtensionStatusSchema = external_exports.strictObject({
15721
+ state: external_exports.enum([
15722
+ "running",
15723
+ "disabled",
15724
+ "invalid",
15725
+ "incompatible",
15726
+ "conflict",
15727
+ "failed",
15728
+ "waiting"
15729
+ ]),
15730
+ hash: desktopExtensionHashSchema.optional(),
15731
+ error: external_exports.string().optional(),
15732
+ conflictWith: desktopExtensionIdSchema.optional()
15733
+ });
15734
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15735
+ controllerPid: external_exports.int().positive(),
15736
+ targetId: external_exports.string().nullable(),
15737
+ updatedAt: external_exports.iso.datetime(),
15738
+ handledReloadToken: external_exports.uuid().optional(),
15739
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema),
15740
+ surfaces: external_exports.record(external_exports.string(), desktopExtensionStatusSchema).optional()
15741
+ });
15742
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15743
+ function isGitHubDesktopExtensionZipballUrl(url2) {
15744
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15745
+ }
15746
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15747
+ const url2 = new URL(input);
15748
+ 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);
15749
+ }, "Expected a .zip download URL or a GitHub zipball URL");
15750
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15751
+ id: desktopExtensionIdSchema,
15752
+ version: external_exports.string().trim().min(1).max(128),
15753
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15754
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
15755
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15756
+ author: external_exports.string().trim().min(1).max(128),
15757
+ repository: desktopExtensionHttpUrlSchema,
15758
+ stars: external_exports.number().int().min(0).optional(),
15759
+ downloads: external_exports.number().int().min(0).optional(),
15760
+ categories: categoriesSchema.optional(),
15761
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
15762
+ icon: desktopExtensionHttpUrlSchema.optional(),
15763
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15764
+ downloadUrl: desktopExtensionZipUrlSchema,
15765
+ sha256: desktopExtensionHashSchema,
15766
+ slots: slotsSchema.optional(),
15767
+ publishedAt: external_exports.string().optional(),
15768
+ updatedAt: external_exports.string().optional(),
15769
+ minCodexHostVersion: external_exports.string().optional()
15770
+ });
15771
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
15772
+ schemaVersion: external_exports.literal(1),
15773
+ generatedAt: external_exports.string(),
15774
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15775
+ });
15776
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15777
+
15778
+ // ../../shared-contracts/dist/host-extensions.js
15779
+ var reservedName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu;
15780
+ var HOST_EXTENSION_PAGE_API_VERSION = 1;
15781
+ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedName.test(id2), "Reserved extension ID");
15782
+ var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
15783
+ var hostExtensionDigestSchema = desktopExtensionHashSchema;
15784
+ var hostExtensionActivationIdSchema = external_exports.uuid();
15785
+ 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((path17) => path17.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
15786
+ var legacy = desktopExtensionManifestSchema.shape;
15787
+ var localized = (max, min = 0) => external_exports.strictObject({
15788
+ en: external_exports.string().trim().min(min).max(max),
15789
+ "zh-CN": external_exports.string().trim().min(min).max(max)
15790
+ });
15791
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path17) => path17.endsWith(suffix), `Expected a ${suffix} file`);
15792
+ var moduleEntry = resourceWithSuffix(".mjs");
15793
+ var style = resourceWithSuffix(".css").optional();
15794
+ var hostExtensionCanonicalPath = (path17) => path17.normalize("NFC").toLowerCase();
15795
+ var hostExtensionManifestV2Schema = external_exports.strictObject({
15796
+ manifestVersion: external_exports.literal(2),
15797
+ id: hostExtensionIdSchema,
15798
+ name: localized(128, 1),
15799
+ version: external_exports.string().trim().min(1).max(128),
15800
+ description: localized(4096),
15801
+ details: localized(16384).optional(),
15802
+ author: legacy.author,
15803
+ repository: legacy.repository,
15804
+ icon: legacy.icon.refine((path17) => path17 === void 0 || hostExtensionResourcePathSchema.safeParse(path17).success),
15805
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path17) => hostExtensionResourcePathSchema.safeParse(path17).success)),
15806
+ categories: legacy.categories,
15807
+ settingsSchema: legacy.settingsSchema,
15808
+ slots: legacy.slots.removeDefault().optional(),
15809
+ page: external_exports.strictObject({
15810
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15811
+ entry: moduleEntry,
15812
+ style,
15813
+ title: localized(128, 1).optional()
15814
+ }).optional(),
15815
+ widget: external_exports.strictObject({
15816
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15817
+ entry: moduleEntry,
15818
+ style
15819
+ }).optional(),
15820
+ desktop: external_exports.strictObject({ apiVersion: external_exports.literal(1), script: resourceWithSuffix(".js"), style }).optional(),
15821
+ 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(),
15822
+ backend: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry }).optional()
15823
+ }).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" });
15824
+ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBackend }) {
15825
+ if (hasPage || hasWidget || hasBackend && !hasDesktop && !hasWeb)
15826
+ return ["desktop", "web"];
15827
+ const targets = [];
15828
+ if (hasDesktop)
15829
+ targets.push("desktop");
15830
+ if (hasWeb)
15831
+ targets.push("web");
15832
+ return targets;
15833
+ }
15834
+ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
15835
+
15836
+ // ../../shared-contracts/dist/host-extension-management.js
15837
+ var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
15838
+ var hostExtensionRevisionSchema = external_exports.int().nonnegative();
15839
+ var hostExtensionConfigurationSchema = external_exports.strictObject({
15840
+ revision: hostExtensionRevisionSchema,
15841
+ enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
15842
+ });
15843
+ var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
15844
+ var hostExtensionCatalogEntrySchema = external_exports.object({
15845
+ ...catalogMetadata,
15846
+ id: hostExtensionIdSchema,
15847
+ format: external_exports.literal("codexhost"),
15848
+ targets: external_exports.array(hostExtensionTargetSchema).min(1).max(2).refine((targets) => new Set(targets).size === targets.length, "Duplicate targets"),
15849
+ apis: external_exports.strictObject({
15850
+ page: external_exports.int().positive().optional(),
15851
+ widget: external_exports.int().positive().optional(),
15852
+ desktop: external_exports.int().positive().optional(),
15853
+ web: external_exports.int().positive().optional(),
15854
+ backend: external_exports.int().positive().optional()
15855
+ }),
15856
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
15857
+ }).refine(({ targets, apis }) => {
15858
+ const derived = targetsForCapabilities({
15859
+ hasPage: Boolean(apis.page),
15860
+ hasWidget: Boolean(apis.widget),
15861
+ hasDesktop: Boolean(apis.desktop),
15862
+ hasWeb: Boolean(apis.web),
15863
+ hasBackend: Boolean(apis.backend)
15864
+ });
15865
+ return targets.length === derived.length && derived.every((target2) => targets.includes(target2));
15866
+ }, "Catalog targets must match the declared APIs");
15867
+ var hostExtensionCatalogSchema = external_exports.object({
15868
+ schemaVersion: external_exports.literal(2),
15869
+ generatedAt: external_exports.string().min(1),
15870
+ extensions: external_exports.array(hostExtensionCatalogEntrySchema).max(1e4).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15871
+ });
15872
+ var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
15873
+ catalogUrl: desktopExtensionHttpUrlSchema,
15874
+ fetchedAt: external_exports.iso.datetime(),
15875
+ cached: external_exports.boolean()
15876
+ });
15877
+ var id = { id: hostExtensionIdSchema };
15878
+ var active = {
15879
+ ...id,
15880
+ activationId: hostExtensionActivationIdSchema,
15881
+ digest: hostExtensionDigestSchema
15882
+ };
15883
+ var optionalActivation = { ...id, activationId: active.activationId.optional() };
15884
+ var filePath = external_exports.string().min(1).max(4096).refine((path17) => /^(?:\/|[a-z]:[/\\])/iu.test(path17) && !path17.includes("\0") && !path17.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
15885
+ 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");
15886
+ function base643(maxBytes) {
15887
+ return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
15888
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
15889
+ return value.length % 4 === 0 && value.length * 3 / 4 - padding <= maxBytes && /^[A-Za-z0-9+/]*={0,2}$/u.test(value);
15890
+ }, "Expected bounded standard padded base64");
15891
+ }
15892
+ var hostExtensionGitHubSourceSchema = external_exports.strictObject({
15893
+ type: external_exports.literal("github"),
15894
+ repository: external_exports.string().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),
15895
+ ref: gitRef.optional(),
15896
+ tag: gitRef.optional(),
15897
+ asset: external_exports.string().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),
15898
+ subpath: hostExtensionResourcePathSchema.optional()
15899
+ }).refine(({ ref, tag, asset }) => !ref || !tag && !asset, "Use either a zipball ref or a release tag/asset");
15900
+ var hostExtensionInstallSourceSchema = external_exports.union([
15901
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15902
+ hostExtensionGitHubSourceSchema,
15903
+ external_exports.strictObject({ type: external_exports.literal("zip"), base64: base643(HOST_EXTENSION_ZIP_MAX_BYTES).min(4) }),
15904
+ external_exports.strictObject({ type: external_exports.literal("zip"), localZipPath: filePath }),
15905
+ external_exports.strictObject({ type: external_exports.literal("localDir"), localDir: filePath })
15906
+ ]);
15907
+ var hostExtensionProvenanceSchema = external_exports.discriminatedUnion("type", [
15908
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15909
+ hostExtensionGitHubSourceSchema,
15910
+ external_exports.strictObject({ type: external_exports.literal("zip") }),
15911
+ external_exports.strictObject({ type: external_exports.literal("localDir") })
15912
+ ]);
15913
+ var hostExtensionInstallationSchema = external_exports.strictObject({
15914
+ ...active,
15915
+ manifest: hostExtensionManifestV2Schema,
15916
+ installedAt: external_exports.iso.datetime(),
15917
+ source: hostExtensionProvenanceSchema.optional()
15918
+ });
15919
+ 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);
15920
+ var desktopConflict = { desktopConflictWith: hostExtensionIdSchema.optional() };
15921
+ var backendState = external_exports.enum(["none", "inactive", "starting", "running", "failed"]);
15922
+ var hostExtensionListItemSchema = external_exports.discriminatedUnion("state", [
15923
+ hostExtensionInstallationSchema.extend({
15924
+ state: external_exports.literal("valid"),
15925
+ enabled: external_exports.boolean(),
15926
+ ...desktopConflict,
15927
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15928
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15929
+ backendState: backendState.optional(),
15930
+ backendError: external_exports.string().optional()
15931
+ }),
15932
+ external_exports.strictObject({
15933
+ state: external_exports.enum(["invalid", "incompatible"]),
15934
+ id: external_exports.string().min(1),
15935
+ enabled: external_exports.boolean(),
15936
+ error: external_exports.string()
15937
+ })
15938
+ ]);
15939
+ var hostExtensionsListResultSchema = external_exports.strictObject({
15940
+ revision: hostExtensionRevisionSchema,
15941
+ configuration: hostExtensionConfigurationSchema,
15942
+ diagnostics: external_exports.array(external_exports.string()),
15943
+ extensions: external_exports.array(hostExtensionListItemSchema)
15944
+ });
15945
+ var hostExtensionRuntimeEntrySchema = hostExtensionInstallationSchema.extend({
15946
+ ...desktopConflict,
15947
+ settingsRevision: hostExtensionRevisionSchema
15948
+ });
15949
+ var hostExtensionsSnapshotResultSchema = external_exports.strictObject({
15950
+ /** The Host publishes this revision in extensions-changed, independent of enabled.json's revision. */
15951
+ revision: hostExtensionRevisionSchema,
15952
+ // Enabled, valid activations only. A Desktop conflict does not hide other capabilities.
15953
+ extensions: external_exports.array(hostExtensionRuntimeEntrySchema).max(DESKTOP_EXTENSION_LIMIT)
15954
+ });
15955
+ var HOST_EXTENSIONS_RPC = {
15956
+ list: "codexhost/extensions/list",
15957
+ snapshot: "codexhost/extensions/snapshot",
15958
+ catalog: "codexhost/extensions/catalog",
15959
+ install: "codexhost/extensions/install",
15960
+ update: "codexhost/extensions/update",
15961
+ enable: "codexhost/extensions/enable",
15962
+ disable: "codexhost/extensions/disable",
15963
+ uninstall: "codexhost/extensions/uninstall",
15964
+ recover: "codexhost/extensions/recover",
15965
+ asset: "codexhost/extensions/asset",
15966
+ settingsGet: "codexhost/extensions/settings/get",
15967
+ settingsSet: "codexhost/extensions/settings/set",
15968
+ backendInvoke: "codexhost/extensions/backend/invoke"
15969
+ };
15970
+ var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
15971
+ var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
15972
+ var noParams = external_exports.strictObject({});
15973
+ var expectedRevision = { expectedRevision: hostExtensionRevisionSchema };
15974
+ var selection = external_exports.strictObject({ ...id, ...expectedRevision });
15975
+ var installationResult = hostExtensionInstallationSchema.extend({ replaced: external_exports.boolean() });
15976
+ var mutationResult = external_exports.discriminatedUnion("state", [
15977
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: hostExtensionConfigurationSchema }),
15978
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: hostExtensionRevisionSchema })
15979
+ ]);
15980
+ var hostExtensionsAssetParamsSchema = external_exports.strictObject({
15981
+ ...optionalActivation,
15982
+ digest: active.digest.optional(),
15983
+ path: hostExtensionResourcePathSchema
15984
+ });
15985
+ var hostExtensionsAssetResultSchema = external_exports.strictObject({
15986
+ mimeType: external_exports.string().min(1),
15987
+ base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
15988
+ digest: active.digest
15989
+ });
15990
+ var hostExtensionSettingsSchema = external_exports.strictObject({
15991
+ settingsRevision: hostExtensionRevisionSchema,
15992
+ values: jsonObjectSchema
15993
+ });
15994
+ var hostExtensionsRpcSchemas = {
15995
+ [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
15996
+ [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
15997
+ [HOST_EXTENSIONS_RPC.catalog]: {
15998
+ params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
15999
+ result: hostExtensionsCatalogResultSchema
16000
+ },
16001
+ [HOST_EXTENSIONS_RPC.install]: {
16002
+ params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
16003
+ result: installationResult
16004
+ },
16005
+ [HOST_EXTENSIONS_RPC.update]: {
16006
+ params: external_exports.strictObject({
16007
+ ...id,
16008
+ expectedDigest: active.digest,
16009
+ expectedActivationId: active.activationId.optional(),
16010
+ source: hostExtensionInstallSourceSchema.optional()
16011
+ }),
16012
+ result: installationResult
16013
+ },
16014
+ [HOST_EXTENSIONS_RPC.enable]: { params: selection, result: mutationResult },
16015
+ [HOST_EXTENSIONS_RPC.disable]: { params: selection, result: mutationResult },
16016
+ [HOST_EXTENSIONS_RPC.uninstall]: {
16017
+ params: external_exports.strictObject({
16018
+ ...id,
16019
+ removeData: external_exports.boolean().optional(),
16020
+ expectedDigest: active.digest.optional()
16021
+ }),
16022
+ result: external_exports.strictObject({ ...id, removed: external_exports.boolean() })
16023
+ },
16024
+ [HOST_EXTENSIONS_RPC.recover]: {
16025
+ params: external_exports.strictObject({ expectedRevision: expectedRevision.expectedRevision.optional() }),
16026
+ result: mutationResult
16027
+ },
16028
+ [HOST_EXTENSIONS_RPC.asset]: {
16029
+ params: hostExtensionsAssetParamsSchema,
16030
+ result: hostExtensionsAssetResultSchema
16031
+ },
16032
+ [HOST_EXTENSIONS_RPC.settingsGet]: {
16033
+ params: external_exports.strictObject(optionalActivation),
16034
+ result: hostExtensionSettingsSchema
16035
+ },
16036
+ [HOST_EXTENSIONS_RPC.settingsSet]: {
16037
+ params: external_exports.strictObject({
16038
+ ...optionalActivation,
16039
+ expectedSettingsRevision: hostExtensionRevisionSchema,
16040
+ values: jsonObjectSchema
16041
+ }),
16042
+ result: hostExtensionSettingsSchema
16043
+ },
16044
+ [HOST_EXTENSIONS_RPC.backendInvoke]: {
16045
+ params: external_exports.strictObject({
16046
+ ...optionalActivation,
16047
+ method: hostExtensionBackendMethodSchema,
16048
+ params: jsonValueSchema.optional()
16049
+ }),
16050
+ result: external_exports.strictObject({ result: jsonValueSchema })
16051
+ }
16052
+ };
16053
+
15476
16054
  // ../../shared-contracts/dist/thread-archive-confirm.js
16055
+ var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
15477
16056
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
15478
16057
  var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
15479
16058
 
15480
16059
  // ../../shared-contracts/dist/client-channel.js
15481
16060
  var CLIENT_CHANNEL_VERSION = 1;
15482
16061
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
16062
+ var CLIENT_CHANNEL_METHODS = [
16063
+ "codexhost/skills/list",
16064
+ "codexhost/voice/status",
16065
+ "codexhost/voice/transcribe",
16066
+ "codexhost/harness/display-settings/get",
16067
+ "codexhost/harness/display-settings/set",
16068
+ "codexhost/harness/display-settings/capabilities",
16069
+ "codexhost/harness/preferences/get",
16070
+ "codexhost/harness/preferences/patch",
16071
+ "thread/list",
16072
+ "codexhost/thread/catalog/read",
16073
+ "thread/read",
16074
+ "thread/resume",
16075
+ "thread/fork",
16076
+ "thread/turns/list",
16077
+ "thread/revert",
16078
+ "thread/items/list",
16079
+ "thread/start",
16080
+ "thread/name/set",
16081
+ "codexhost/thread/title/generate",
16082
+ "thread/archive",
16083
+ THREAD_ARCHIVE_CONFIRM_METHOD,
16084
+ "thread/unarchive",
16085
+ "turn/start",
16086
+ "turn/interrupt",
16087
+ "turn/steer",
16088
+ "thread/queue/list",
16089
+ "thread/queue/add",
16090
+ "thread/queue/update",
16091
+ "thread/queue/delete",
16092
+ "thread/queue/reorder",
16093
+ "thread/queue/start",
16094
+ "codexhost/thread/queue/send-now",
16095
+ "codexhost/workspace/read",
16096
+ "codexhost/thread/tree/read",
16097
+ "codexhost/thread/pins/list",
16098
+ "codexhost/thread/pins/set",
16099
+ "codexhost/harness/plugins/list",
16100
+ "codexhost/harness/inspect",
16101
+ "codexhost/thread/inspect",
16102
+ "codexhost/thread/usage/inspect",
16103
+ "codexhost/thread/ownership/list",
16104
+ "codexhost/thread/model/select",
16105
+ "codexhost/thread/thinking/select",
16106
+ "codexhost/thread/permission-mode/select",
16107
+ "codexhost/thread/commands/inspect",
16108
+ "codexhost/harness/commands/inspect",
16109
+ "codexhost/thread/command/execute",
16110
+ "codexhost/thread/fork",
16111
+ "codexhost/harness/session-import/sources",
16112
+ "codexhost/harness/session-import/list",
16113
+ "codexhost/harness/session-import/import",
16114
+ // Host settings shared across Desktop and Web.
16115
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
16116
+ "codexhost/harness/installation",
16117
+ "codexhost/harness/installation/start",
16118
+ "codexhost/harness/installation/status",
16119
+ "codexhost/harness/launch-settings/get",
16120
+ "codexhost/harness/launch-settings/set",
16121
+ "codexhost/harness/web-ui/open",
16122
+ "codexhost/harness/accounts/sources",
16123
+ "codexhost/harness/accounts/list",
16124
+ "codexhost/harness/accounts/inspect",
16125
+ "codexhost/harness/credential-imports",
16126
+ "codexhost/account/list",
16127
+ "codexhost/account/refresh",
16128
+ "codexhost/account/usage/inspect",
16129
+ "codexhost/usage/model-prices/get",
16130
+ "codexhost/usage/model-prices/set",
16131
+ "codexhost/usage/model-prices/default",
16132
+ "codexhost/usage/statistics/get",
16133
+ "codexhost/update/check",
16134
+ "codexhost/update/start",
16135
+ "codexhost/update/status",
16136
+ "codexhost/sessions/loaded/list"
16137
+ ];
15483
16138
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15484
16139
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15485
16140
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -15518,6 +16173,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15518
16173
  cursor: clientChannelCursorSchema,
15519
16174
  revision: external_exports.number().int().nonnegative()
15520
16175
  }),
16176
+ external_exports.object({
16177
+ type: external_exports.literal("extensions-changed"),
16178
+ cursor: clientChannelCursorSchema,
16179
+ revision: hostExtensionRevisionSchema
16180
+ }),
15521
16181
  external_exports.object({
15522
16182
  type: external_exports.literal("hello"),
15523
16183
  version: external_exports.literal(1),
@@ -15693,6 +16353,29 @@ var threadCatalogReadResultSchema = external_exports.object({
15693
16353
  officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15694
16354
  }).strict();
15695
16355
 
16356
+ // ../../shared-contracts/dist/thread-tree-watch.js
16357
+ var THREAD_TREE_MAX_NODES = 5e3;
16358
+ var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
16359
+ var threadTreeNodeSchema = external_exports.strictObject({
16360
+ harnessId: harnessIdSchema,
16361
+ title: external_exports.string().optional(),
16362
+ status: threadTreeStatusSchema,
16363
+ archived: external_exports.boolean()
16364
+ });
16365
+ var threadTreeSnapshotSchema = external_exports.strictObject({
16366
+ revision: external_exports.int().nonnegative(),
16367
+ parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
16368
+ nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
16369
+ truncated: external_exports.boolean()
16370
+ }).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");
16371
+ var subscriptionId = external_exports.string().min(1).max(128);
16372
+ var threadTreeWatchParamsSchema = external_exports.strictObject({});
16373
+ var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
16374
+ var threadTreeUnwatchResultSchema = external_exports.strictObject({});
16375
+ var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
16376
+ snapshot: threadTreeSnapshotSchema
16377
+ });
16378
+
15696
16379
  // ../../shared-contracts/dist/voice.js
15697
16380
  var VOICE_AUDIO_MAX_BYTES = 10 * 1024 * 1024;
15698
16381
  var voiceAudioMimeTypeSchema = external_exports.string().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);
@@ -15931,7 +16614,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
15931
16614
 
15932
16615
  // ../../shared-contracts/dist/harness-preferences.js
15933
16616
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
15934
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
16617
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
15935
16618
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
15936
16619
  model: harnessModelRefSchema.optional(),
15937
16620
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15941,11 +16624,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
15941
16624
  lastHarness: harnessIdSchema.optional(),
15942
16625
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
15943
16626
  });
16627
+ var harnessDelegationDefaultSchema = external_exports.strictObject({
16628
+ model: harnessModelRefSchema.optional(),
16629
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional()
16630
+ }).refine((value) => Boolean(value.model || value.thinkingOptionId), "A delegation default must contain a Model or Thinking option");
16631
+ var delegationDefaultsSchema = external_exports.strictObject({
16632
+ byHarness: external_exports.record(preferenceHarnessKey, harnessDelegationDefaultSchema)
16633
+ });
15944
16634
  var modelId = external_exports.string().min(1).max(1024);
15945
16635
  var harnessPreferenceValuesSchema = external_exports.strictObject({
15946
16636
  idleRelease: idleReleaseSettingsSchema.optional(),
15947
16637
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
15948
- newThread: newThreadDefaultsSchema.optional()
16638
+ newThread: newThreadDefaultsSchema.optional(),
16639
+ delegation: delegationDefaultsSchema.optional()
15949
16640
  });
15950
16641
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
15951
16642
  scope: harnessPreferenceScopeSchema,
@@ -15973,6 +16664,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
15973
16664
  lastHarness: harnessIdSchema.optional(),
15974
16665
  harnessId: harnessIdSchema.optional(),
15975
16666
  configuration: harnessDefaultConfigurationSchema.optional()
16667
+ }),
16668
+ external_exports.strictObject({
16669
+ kind: external_exports.literal("delegation"),
16670
+ harnessId: harnessIdSchema,
16671
+ configuration: harnessDelegationDefaultSchema.nullable()
15976
16672
  })
15977
16673
  ]);
15978
16674
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -16323,13 +17019,6 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
16323
17019
  });
16324
17020
 
16325
17021
  // ../../shared-contracts/dist/harness-accounts.js
16326
- var accountBalanceSnapshotSchema = external_exports.object({
16327
- amount: external_exports.number().finite().nonnegative(),
16328
- /** ISO 4217 code as reported by the Provider, for example `CNY`. */
16329
- currency: external_exports.string().trim().min(1).max(8),
16330
- /** Native label when the Harness exposes several Billing Sources. */
16331
- label: external_exports.string().trim().min(1).max(128).optional()
16332
- }).strict();
16333
17022
  var harnessAccountSnapshotObject = external_exports.object({
16334
17023
  email: external_exports.string().trim().min(1).max(320).optional(),
16335
17024
  label: external_exports.string().trim().min(1).max(256).optional(),
@@ -16363,76 +17052,6 @@ var harnessAccountListResultSchema = external_exports.object({
16363
17052
  accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
16364
17053
  }).strict();
16365
17054
 
16366
- // ../../shared-contracts/dist/harness-plugins.js
16367
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
16368
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
16369
- var HARNESS_PLUGIN_LIMIT = 128;
16370
- var installedHarnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(harnessIdSchema);
16371
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
16372
- 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");
16373
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
16374
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
16375
- var harnessInstallationGuideSchema = external_exports.object({
16376
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
16377
- before: localizedTextSchema.optional(),
16378
- after: localizedTextSchema.optional(),
16379
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
16380
- }).strict();
16381
- var pluginPresentationShape = {
16382
- id: installedHarnessPluginIdSchema,
16383
- name: external_exports.string().trim().min(1).max(128),
16384
- version: external_exports.string().min(1).max(128),
16385
- /** Capability-only plugin; omitted for existing session-capable plugins. */
16386
- kind: external_exports.literal("usage").optional(),
16387
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
16388
- iconStyle: external_exports.object({
16389
- vector: external_exports.object({
16390
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
16391
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
16392
- paths: external_exports.array(external_exports.object({
16393
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
16394
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
16395
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
16396
- }).strict()).min(1).max(32)
16397
- }).strict().optional(),
16398
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
16399
- borderRadius: external_exports.number().min(0).max(50).optional(),
16400
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
16401
- }).strict().optional(),
16402
- installation: harnessInstallationGuideSchema.optional(),
16403
- notice: localizedTextSchema.optional(),
16404
- /** The factory accepts a persisted local entrypoint through its construction context. */
16405
- launchCommand: external_exports.literal(true).optional(),
16406
- links: external_exports.object({
16407
- website: documentationUrlSchema.optional(),
16408
- documentation: documentationUrlSchema.optional(),
16409
- installation: documentationUrlSchema.optional()
16410
- }).strict().optional()
16411
- };
16412
- var harnessPluginManifestSchema = external_exports.object({
16413
- manifestVersion: external_exports.literal(1),
16414
- ...pluginPresentationShape,
16415
- adapterApiVersion: external_exports.number().int().positive(),
16416
- entry: relativeResourceSchema,
16417
- icon: relativeResourceSchema.optional()
16418
- }).strict();
16419
- 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);
16420
- var harnessPluginDescriptorSchema = external_exports.object({
16421
- ...pluginPresentationShape,
16422
- icon: harnessPluginIconSchema.optional()
16423
- }).strict();
16424
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
16425
- var harnessPluginListResultSchema = external_exports.object({
16426
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
16427
- }).strict();
16428
- var harnessPluginConfigurationSchema = external_exports.object({
16429
- version: external_exports.literal(1),
16430
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
16431
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
16432
- message: "Enabled plugin IDs must be unique",
16433
- path: ["enabled"]
16434
- });
16435
-
16436
17055
  // ../../shared-contracts/dist/harness-route.js
16437
17056
  var harnessPluginRouteSchema = external_exports.object({
16438
17057
  harnessId: harnessPluginIdSchema,
@@ -16873,9 +17492,12 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16873
17492
  ...thread,
16874
17493
  epoch: identity,
16875
17494
  modelId: identity.optional(),
17495
+ serviceTier: harnessModelServiceTierSchema.optional(),
16876
17496
  thinkingOptionId: identity.optional(),
16877
17497
  permissionModeId: identity.optional()
16878
- }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17498
+ }).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, {
17499
+ message: "A service tier requires a Model ID"
17500
+ }),
16879
17501
  external_exports.strictObject({
16880
17502
  kind: external_exports.literal("prompt"),
16881
17503
  ...thread,
@@ -16925,7 +17547,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
16925
17547
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
16926
17548
  external_exports.strictObject({
16927
17549
  action: external_exports.literal("read-thread"),
16928
- hostId: hostId.refine((id) => id !== "local"),
17550
+ hostId: hostId.refine((id2) => id2 !== "local"),
16929
17551
  input: delegationReadParamsSchema
16930
17552
  }),
16931
17553
  external_exports.strictObject({
@@ -16939,7 +17561,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
16939
17561
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
16940
17562
  external_exports.strictObject({
16941
17563
  action: external_exports.literal("update"),
16942
- hostId: hostId.refine((id) => id !== "local"),
17564
+ hostId: hostId.refine((id2) => id2 !== "local"),
16943
17565
  version: remoteUpdateParamsSchema.shape.version
16944
17566
  })
16945
17567
  ]);
@@ -17003,7 +17625,7 @@ function invalidRequest(message) {
17003
17625
  return { code: "invalidRequest", message, retryable: false };
17004
17626
  }
17005
17627
  function validateHostApprovalResponse(interaction, response) {
17006
- return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17628
+ return interaction.actions.some(({ id: id2 }) => id2 === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17007
17629
  }
17008
17630
 
17009
17631
  // ../../harness-adapter/dist/question.js
@@ -17011,7 +17633,7 @@ function invalidRequest2(message) {
17011
17633
  return { code: "invalidRequest", message, retryable: false };
17012
17634
  }
17013
17635
  function validateHostQuestionResponse(interaction, response) {
17014
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17636
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
17015
17637
  if (response.cancelled) {
17016
17638
  return Object.keys(response.answers).length === 0 ? null : invalidRequest2("Cancelled Question Response must not contain answers");
17017
17639
  }
@@ -17042,6 +17664,18 @@ function validateHostQuestionResponse(interaction, response) {
17042
17664
  return null;
17043
17665
  }
17044
17666
 
17667
+ // ../../harness-adapter/dist/legacy-model-ref.js
17668
+ import { Buffer as Buffer2 } from "node:buffer";
17669
+ function normalizeLegacyBase64ModelRef(ref, catalog, prefix) {
17670
+ if (ref.serviceTier || !ref.id.startsWith(prefix))
17671
+ return void 0;
17672
+ const encoded = ref.id.slice(prefix.length);
17673
+ const id2 = Buffer2.from(encoded, "base64url").toString("utf8");
17674
+ if (Buffer2.from(id2).toString("base64url") !== encoded)
17675
+ return void 0;
17676
+ return catalog.models.find(({ ref: ref2 }) => ref2.id === id2 && !ref2.serviceTier)?.ref;
17677
+ }
17678
+
17045
17679
  // ../../harness-adapter/dist/output-channel.js
17046
17680
  var HarnessOutputChannel = class {
17047
17681
  outputs;
@@ -17126,7 +17760,8 @@ var tokenFields = [
17126
17760
  var safeIntegerFields = [
17127
17761
  "planFiveHourResetsAtUnix",
17128
17762
  "planSevenDayResetsAtUnix",
17129
- "timeToFirstOutputMs"
17763
+ "timeToFirstOutputMs",
17764
+ "latestRequestTimeToFirstOutputMs"
17130
17765
  ];
17131
17766
  var percentFields = [
17132
17767
  "cacheHitRatePercent",
@@ -17334,7 +17969,7 @@ function isExcludedLiveCommand(name, extra = {}) {
17334
17969
  function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17335
17970
  if (!commandId.startsWith(idPrefix))
17336
17971
  return null;
17337
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
17972
+ const descriptor = catalog.commands.find(({ id: id2 }) => id2 === commandId);
17338
17973
  if (!descriptor)
17339
17974
  return null;
17340
17975
  const text = typeof argumentText === "string" ? argumentText.trim() : "";
@@ -17344,7 +17979,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17344
17979
  if (!live)
17345
17980
  return builtIns;
17346
17981
  const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17347
- const ids = new Set(builtIns.commands.map(({ id }) => id));
17982
+ const ids = new Set(builtIns.commands.map(({ id: id2 }) => id2));
17348
17983
  const dynamic = [];
17349
17984
  for (const command of live) {
17350
17985
  const name = command.name.trim().replace(/^\//u, "");
@@ -17353,12 +17988,12 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17353
17988
  if (isExcludedLiveCommand(name, exclusions))
17354
17989
  continue;
17355
17990
  const invocation = `/${name}`;
17356
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17357
- if (invocations.has(invocation) || ids.has(id))
17991
+ const id2 = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17992
+ if (invocations.has(invocation) || ids.has(id2))
17358
17993
  continue;
17359
17994
  const description = command.description?.trim().slice(0, 512);
17360
17995
  const parsed = harnessCommandDescriptorSchema.safeParse({
17361
- id,
17996
+ id: id2,
17362
17997
  invocation,
17363
17998
  label: name.slice(0, 128),
17364
17999
  ...description ? { description } : {},
@@ -17367,7 +18002,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17367
18002
  if (!parsed.success)
17368
18003
  continue;
17369
18004
  invocations.add(invocation);
17370
- ids.add(id);
18005
+ ids.add(id2);
17371
18006
  dynamic.push(parsed.data);
17372
18007
  }
17373
18008
  return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
@@ -17614,7 +18249,7 @@ function createGrokUsageStatistics(environment) {
17614
18249
  return Object.freeze({
17615
18250
  // sessions/<url-encoded cwd>/<session>/updates.jsonl; subagents are sessions of their own.
17616
18251
  listSources: async (signal) => (await jsonlUsageSources(path5.join(grokHome(environment), "sessions"), 2, signal)).filter((source) => path5.basename(source.id) === "updates.jsonl"),
17617
- readSource: (id, signal) => readGrokUsage(id, signal)
18252
+ readSource: (id2, signal) => readGrokUsage(id2, signal)
17618
18253
  });
17619
18254
  }
17620
18255
 
@@ -19880,8 +20515,8 @@ var RequestResponder = class {
19880
20515
  signal;
19881
20516
  finishRequest;
19882
20517
  didRespond = false;
19883
- constructor(id, sendResult, signal = new AbortController().signal, finishRequest) {
19884
- this.id = id;
20518
+ constructor(id2, sendResult, signal = new AbortController().signal, finishRequest) {
20519
+ this.id = id2;
19885
20520
  this.sendResult = sendResult;
19886
20521
  this.signal = signal;
19887
20522
  this.finishRequest = finishRequest;
@@ -20172,7 +20807,7 @@ var Connection = class {
20172
20807
  return this.sendWireMessage({ jsonrpc: "2.0", method, params });
20173
20808
  }
20174
20809
  prepareRequest(method, params, mapResponse, options = {}) {
20175
- const id = this.nextRequestId++;
20810
+ const id2 = this.nextRequestId++;
20176
20811
  let cancel = () => {
20177
20812
  };
20178
20813
  const response = new Promise((resolve, reject) => {
@@ -20192,7 +20827,7 @@ var Connection = class {
20192
20827
  }
20193
20828
  pendingResponse.cancellationSent = true;
20194
20829
  pendingResponse.cleanup?.();
20195
- void this.sendCancelRequest(id).catch(() => {
20830
+ void this.sendCancelRequest(id2).catch(() => {
20196
20831
  });
20197
20832
  };
20198
20833
  options.cancellationSignal?.addEventListener("abort", cancel, {
@@ -20201,12 +20836,12 @@ var Connection = class {
20201
20836
  pendingResponse.cleanup = () => {
20202
20837
  options.cancellationSignal?.removeEventListener("abort", cancel);
20203
20838
  };
20204
- this.pendingResponses.set(id, pendingResponse);
20839
+ this.pendingResponses.set(id2, pendingResponse);
20205
20840
  });
20206
20841
  response.catch(() => {
20207
20842
  });
20208
20843
  return {
20209
- message: { jsonrpc: "2.0", id, method, params },
20844
+ message: { jsonrpc: "2.0", id: id2, method, params },
20210
20845
  response,
20211
20846
  cancel: () => cancel()
20212
20847
  };
@@ -20843,7 +21478,7 @@ function memoryStreamPair() {
20843
21478
  }
20844
21479
  ];
20845
21480
  }
20846
- var methods = {
21481
+ var methods2 = {
20847
21482
  agent: {
20848
21483
  initialize: AGENT_METHODS.initialize,
20849
21484
  authenticate: AGENT_METHODS.authenticate,
@@ -22228,6 +22863,9 @@ function isRecord5(value) {
22228
22863
  function nonBlank(value) {
22229
22864
  return typeof value === "string" && value.trim().length > 0;
22230
22865
  }
22866
+ function normalizeStoredGrokModelRef(ref, catalog) {
22867
+ return normalizeLegacyBase64ModelRef(ref, catalog, "grok-model-v1.");
22868
+ }
22231
22869
  function thinkingOptions(value) {
22232
22870
  if (!Array.isArray(value))
22233
22871
  return [];
@@ -22236,65 +22874,71 @@ function thinkingOptions(value) {
22236
22874
  for (const candidate of value) {
22237
22875
  if (!isRecord5(candidate) || !nonBlank(candidate.label))
22238
22876
  continue;
22239
- const id = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
22240
- if (!id.success || seen.has(id.data))
22877
+ const id2 = harnessThinkingOptionIdSchema.safeParse(candidate.id ?? candidate.value);
22878
+ if (!id2.success || seen.has(id2.data))
22241
22879
  continue;
22242
- seen.add(id.data);
22243
- options.push({ id: id.data, label: candidate.label });
22880
+ seen.add(id2.data);
22881
+ options.push({ id: id2.data, label: candidate.label });
22244
22882
  }
22245
22883
  return options;
22246
22884
  }
22247
22885
  function parseGrokModelState(value) {
22248
- if (!isRecord5(value) || !nonBlank(value.currentModelId) || !Array.isArray(value.availableModels)) {
22886
+ if (!isRecord5(value) || typeof value.currentModelId !== "string" || !Array.isArray(value.availableModels)) {
22249
22887
  return null;
22250
22888
  }
22251
- const currentModel = harnessModelRefSchema.safeParse({ id: value.currentModelId });
22252
- if (!currentModel.success)
22889
+ let currentModel;
22890
+ try {
22891
+ currentModel = harnessModelRefSchema.parse({ id: value.currentModelId });
22892
+ } catch {
22253
22893
  return null;
22894
+ }
22254
22895
  const allThinking = /* @__PURE__ */ new Map();
22255
22896
  const contextWindowTokensByModel = /* @__PURE__ */ new Map();
22256
22897
  const defaultContextWindowTokensByModel = /* @__PURE__ */ new Map();
22257
22898
  const models = [];
22258
22899
  let currentThinkingOptionId;
22259
22900
  for (const candidate of value.availableModels) {
22260
- if (!isRecord5(candidate) || !nonBlank(candidate.modelId) || !nonBlank(candidate.name))
22901
+ if (!isRecord5(candidate) || !nonBlank(candidate.name))
22261
22902
  continue;
22262
- const ref = harnessModelRefSchema.safeParse({ id: candidate.modelId });
22263
- if (!ref.success)
22903
+ let ref;
22904
+ try {
22905
+ ref = harnessModelRefSchema.parse({ id: candidate.modelId });
22906
+ } catch {
22264
22907
  continue;
22908
+ }
22265
22909
  const metadata = isRecord5(candidate._meta) ? candidate._meta : {};
22266
22910
  const options2 = thinkingOptions(metadata.reasoningEfforts);
22267
22911
  if (Array.isArray(metadata.contextWindows) && metadata.contextWindows.includes(5e5)) {
22268
- defaultContextWindowTokensByModel.set(ref.data.id, 5e5);
22912
+ defaultContextWindowTokensByModel.set(ref.id, 5e5);
22269
22913
  }
22270
22914
  if (typeof metadata.totalContextTokens === "number" && Number.isSafeInteger(metadata.totalContextTokens) && metadata.totalContextTokens > 0) {
22271
- contextWindowTokensByModel.set(ref.data.id, metadata.totalContextTokens);
22915
+ contextWindowTokensByModel.set(ref.id, metadata.totalContextTokens);
22272
22916
  }
22273
22917
  for (const option of options2)
22274
22918
  allThinking.set(option.id, option);
22275
22919
  if (candidate.modelId === value.currentModelId && nonBlank(metadata.reasoningEffort)) {
22276
22920
  const parsed = harnessThinkingOptionIdSchema.safeParse(metadata.reasoningEffort);
22277
- if (parsed.success && options2.some(({ id }) => id === parsed.data)) {
22921
+ if (parsed.success && options2.some(({ id: id2 }) => id2 === parsed.data)) {
22278
22922
  currentThinkingOptionId = parsed.data;
22279
22923
  }
22280
22924
  }
22281
22925
  models.push({
22282
- ref: ref.data,
22926
+ ref,
22283
22927
  label: candidate.name,
22284
- ...options2.length > 0 ? { supportedThinkingOptionIds: options2.map(({ id }) => id) } : {}
22928
+ ...options2.length > 0 ? { supportedThinkingOptionIds: options2.map(({ id: id2 }) => id2) } : {}
22285
22929
  });
22286
22930
  }
22287
- if (!models.some(({ ref }) => ref.id === currentModel.data.id))
22931
+ if (!models.some(({ ref }) => ref.id === currentModel.id))
22288
22932
  return null;
22289
22933
  const options = [...allThinking.values()];
22290
22934
  return {
22291
- currentModel: currentModel.data,
22935
+ currentModel,
22292
22936
  contextWindowTokensByModel,
22293
22937
  defaultContextWindowTokensByModel,
22294
22938
  ...currentThinkingOptionId ? { currentThinkingOptionId } : {},
22295
22939
  catalog: {
22296
22940
  models,
22297
- defaultModel: currentModel.data,
22941
+ defaultModel: currentModel,
22298
22942
  thinkingOptions: options,
22299
22943
  ...currentThinkingOptionId ? { defaultThinkingOptionId: currentThinkingOptionId } : {}
22300
22944
  }
@@ -22308,9 +22952,9 @@ function modelStateFromSessionResponse(response) {
22308
22952
  }
22309
22953
  function stateForGrokModel(modelState, nativeState, model2 = modelState.currentModel, thinkingOptionId = modelState.currentThinkingOptionId, permissionModeId) {
22310
22954
  const selectedModel = model2;
22311
- const catalogModel = modelState.catalog.models.find(({ ref }) => ref.id === selectedModel.id);
22312
- const availableThinkingOptions = catalogModel?.supportedThinkingOptionIds?.flatMap((id) => {
22313
- const option = modelState.catalog.thinkingOptions.find((candidate) => candidate.id === id);
22955
+ const catalogModel = catalogModelForRef(modelState.catalog, selectedModel);
22956
+ const availableThinkingOptions = catalogModel?.supportedThinkingOptionIds?.flatMap((id2) => {
22957
+ const option = modelState.catalog.thinkingOptions.find((candidate) => candidate.id === id2);
22314
22958
  return option ? [option] : [];
22315
22959
  });
22316
22960
  return {
@@ -22356,9 +23000,8 @@ function resolveGrokExecutable(input = {}) {
22356
23000
  }
22357
23001
  function grokInvocation(command, platform = process.platform, modelId2) {
22358
23002
  const arguments_ = ["agent", "--no-leader"];
22359
- const trimmed = modelId2?.trim();
22360
- if (trimmed)
22361
- arguments_.push("--model", trimmed);
23003
+ if (modelId2 !== void 0)
23004
+ arguments_.push("--model", modelId2);
22362
23005
  arguments_.push("stdio");
22363
23006
  return commandInvocation(command, arguments_, process.env, platform);
22364
23007
  }
@@ -22368,7 +23011,7 @@ import { isDeepStrictEqual } from "node:util";
22368
23011
  import path11 from "node:path";
22369
23012
 
22370
23013
  // dist/grok-file-change.js
22371
- import { Buffer as Buffer2 } from "node:buffer";
23014
+ import { Buffer as Buffer3 } from "node:buffer";
22372
23015
  import path9 from "node:path";
22373
23016
 
22374
23017
  // ../../../node_modules/diff/libesm/diff/base.js
@@ -22815,7 +23458,7 @@ function projectDiff(value, cwd, remainingTextBytes) {
22815
23458
  if (typeof oldText === "string" && oldText === newText || oldText === null && newText === "") {
22816
23459
  return null;
22817
23460
  }
22818
- const textBytes = Buffer2.byteLength(oldText ?? "", "utf8") + Buffer2.byteLength(newText, "utf8");
23461
+ const textBytes = Buffer3.byteLength(oldText ?? "", "utf8") + Buffer3.byteLength(newText, "utf8");
22819
23462
  if (textBytes > remainingTextBytes)
22820
23463
  return null;
22821
23464
  const displayed = displayPath(value.path, cwd);
@@ -23133,12 +23776,12 @@ function collectIds(value) {
23133
23776
  return [...new Set(ids)];
23134
23777
  }
23135
23778
  function grokSubagentOperation(name, title, rawInput) {
23136
- const id = toolId(name, title);
23137
- if (WAIT_TOOL_NAMES.has(id) || KILL_TOOL_NAMES.has(id))
23779
+ const id2 = toolId(name, title);
23780
+ if (WAIT_TOOL_NAMES.has(id2) || KILL_TOOL_NAMES.has(id2))
23138
23781
  return null;
23139
- if (SEND_TOOL_NAMES.has(id))
23782
+ if (SEND_TOOL_NAMES.has(id2))
23140
23783
  return "send";
23141
- if (SPAWN_TOOL_NAMES.has(id))
23784
+ if (SPAWN_TOOL_NAMES.has(id2))
23142
23785
  return "spawn";
23143
23786
  if (isRecord8(rawInput) && rawInput.variant === "Task")
23144
23787
  return "spawn";
@@ -23236,7 +23879,7 @@ function grokSubagentEventFromUpdate(update) {
23236
23879
  function grokSubagentWaitSettlements(input) {
23237
23880
  const ids = grokSubagentWaitIds(input.name, input.title, input.rawInput);
23238
23881
  if (grokSubagentKill(input.name, input.title)) {
23239
- return ids.map((id) => ({ id, status: "interrupted" }));
23882
+ return ids.map((id2) => ({ id: id2, status: "interrupted" }));
23240
23883
  }
23241
23884
  if (ids.length === 0)
23242
23885
  return [];
@@ -23244,12 +23887,12 @@ function grokSubagentWaitSettlements(input) {
23244
23887
  if (resultEntries.length > 0) {
23245
23888
  const settled = [];
23246
23889
  for (const result of resultEntries) {
23247
- const id = idField(result, "task_id") ?? idField(result, "subagent_id");
23890
+ const id2 = idField(result, "task_id") ?? idField(result, "subagent_id");
23248
23891
  const status = mapTaskStatus(typeof result.status === "string" ? result.status : void 0);
23249
- if (!id || !status || status === "running" || status === "pending")
23892
+ if (!id2 || !status || status === "running" || status === "pending")
23250
23893
  continue;
23251
23894
  const resultSummary = bounded(typeof result.output === "string" ? result.output.trim() : void 0, SUMMARY_LIMIT);
23252
- settled.push({ id, status, ...resultSummary ? { resultSummary } : {} });
23895
+ settled.push({ id: id2, status, ...resultSummary ? { resultSummary } : {} });
23253
23896
  }
23254
23897
  return settled;
23255
23898
  }
@@ -23259,7 +23902,7 @@ function grokSubagentWaitSettlements(input) {
23259
23902
  const overall = mapTaskStatus(taskOutputStatus(input.rawOutput, input.content));
23260
23903
  if (!overall || overall === "running" || overall === "pending")
23261
23904
  return [];
23262
- return ids.map((id) => ({ id, status: overall }));
23905
+ return ids.map((id2) => ({ id: id2, status: overall }));
23263
23906
  }
23264
23907
  function taskOutputResults(rawOutput) {
23265
23908
  if (!isRecord8(rawOutput))
@@ -23292,13 +23935,13 @@ function taskOutputTextSettlements(rawOutput, content, ids) {
23292
23935
  const settled = [];
23293
23936
  const pattern = /---\s*Task\s+(\S+)\s+\[(completed|failed|interrupted|cancelled|canceled)\]\s*---/gi;
23294
23937
  for (const match of text.matchAll(pattern)) {
23295
- const id = match[1]?.trim();
23938
+ const id2 = match[1]?.trim();
23296
23939
  const status = mapTaskStatus(match[2]);
23297
- if (!id || !status || status === "running" || status === "pending")
23940
+ if (!id2 || !status || status === "running" || status === "pending")
23298
23941
  continue;
23299
- if (!ids.includes(id))
23942
+ if (!ids.includes(id2))
23300
23943
  continue;
23301
- settled.push({ id, status });
23944
+ settled.push({ id: id2, status });
23302
23945
  }
23303
23946
  return settled;
23304
23947
  }
@@ -25054,8 +25697,8 @@ var GrokAcpTransport = class {
25054
25697
  throw new Error("Grok ACP Session already has an active Prompt");
25055
25698
  if (this.#permissionConfirmation)
25056
25699
  throw new GrokTransportError("unavailable", "Grok ACP Session has an active operation");
25057
- const active = { onEvent, onPermission, onQuestion };
25058
- this.#activePrompt = active;
25700
+ const active2 = { onEvent, onPermission, onQuestion };
25701
+ this.#activePrompt = active2;
25059
25702
  try {
25060
25703
  return await connection.prompt({
25061
25704
  sessionId: this.#sessionId,
@@ -25063,7 +25706,7 @@ var GrokAcpTransport = class {
25063
25706
  });
25064
25707
  } finally {
25065
25708
  await yieldToEventLoop();
25066
- if (this.#activePrompt === active)
25709
+ if (this.#activePrompt === active2)
25067
25710
  this.#activePrompt = null;
25068
25711
  }
25069
25712
  }
@@ -25075,8 +25718,8 @@ var GrokAcpTransport = class {
25075
25718
  if (this.#activePrompt || this.#activeCompact || this.#permissionConfirmation) {
25076
25719
  throw new GrokTransportError("unavailable", "Grok ACP Session already has an active operation");
25077
25720
  }
25078
- const active = { onEvent, cancellationRequested: false };
25079
- this.#activeCompact = active;
25721
+ const active2 = { onEvent, cancellationRequested: false };
25722
+ this.#activeCompact = active2;
25080
25723
  try {
25081
25724
  const params = {
25082
25725
  sessionId: this.#sessionId,
@@ -25091,13 +25734,13 @@ var GrokAcpTransport = class {
25091
25734
  raw = await connection.request(GROK_COMPACT_CONVERSATION_FALLBACK_METHOD, params);
25092
25735
  }
25093
25736
  await yieldToEventLoop();
25094
- return parseGrokCompactResult(raw, active.cancellationRequested);
25737
+ return parseGrokCompactResult(raw, active2.cancellationRequested);
25095
25738
  } catch (error53) {
25096
25739
  if (error53 instanceof GrokTransportError)
25097
25740
  throw error53;
25098
25741
  throw new GrokTransportError("unavailable", "Grok Native Compact failed", { cause: error53 });
25099
25742
  } finally {
25100
- if (this.#activeCompact === active)
25743
+ if (this.#activeCompact === active2)
25101
25744
  this.#activeCompact = null;
25102
25745
  }
25103
25746
  }
@@ -25242,10 +25885,10 @@ var GrokAcpTransport = class {
25242
25885
  } catch (error53) {
25243
25886
  throw RequestError.invalidParams(void 0, errorText(error53));
25244
25887
  }
25245
- const active = this.#activePrompt;
25246
- if (!active || this.#closed || this.#closing || this.#replay !== null || this.#activeCompact !== null || request.sessionId !== this.#sessionId)
25888
+ const active2 = this.#activePrompt;
25889
+ if (!active2 || this.#closed || this.#closing || this.#replay !== null || this.#activeCompact !== null || request.sessionId !== this.#sessionId)
25247
25890
  return { outcome: "cancelled" };
25248
- return { ...await active.onQuestion(request) };
25891
+ return { ...await active2.onQuestion(request) };
25249
25892
  }
25250
25893
  #fault(error53) {
25251
25894
  this.#permissionConfirmation?.reject(error53);
@@ -25433,13 +26076,13 @@ var GrokSessionImport = class {
25433
26076
  }
25434
26077
  listCandidates() {
25435
26078
  return this.#scope.read(async (signal) => {
25436
- const active = await this.#activeSessions(signal);
26079
+ const active2 = await this.#activeSessions(signal);
25437
26080
  const candidates = [];
25438
26081
  for (const [, directories] of await this.#sessionDirectories(signal)) {
25439
26082
  if (directories.length !== 1 || !directories[0])
25440
26083
  continue;
25441
26084
  try {
25442
- const candidate = await this.#candidate(directories[0], active, signal);
26085
+ const candidate = await this.#candidate(directories[0], active2, signal);
25443
26086
  if (candidate)
25444
26087
  candidates.push(candidate);
25445
26088
  } catch (error53) {
@@ -25476,7 +26119,7 @@ var GrokSessionImport = class {
25476
26119
  }
25477
26120
  /** IDs a live Grok process currently holds open, from Grok's own registry. */
25478
26121
  async #activeSessions(signal) {
25479
- const active = /* @__PURE__ */ new Set();
26122
+ const active2 = /* @__PURE__ */ new Set();
25480
26123
  let entries;
25481
26124
  try {
25482
26125
  entries = await readJson(path14.join(this.#home(), "active_sessions.json"), signal);
@@ -25484,15 +26127,15 @@ var GrokSessionImport = class {
25484
26127
  signal.throwIfAborted();
25485
26128
  if (isStorageAccessError(error53))
25486
26129
  throw error53;
25487
- return active;
26130
+ return active2;
25488
26131
  }
25489
26132
  if (!Array.isArray(entries))
25490
- return active;
26133
+ return active2;
25491
26134
  for (const entry of entries) {
25492
26135
  if (isRecord15(entry) && typeof entry.session_id === "string" && processAlive(entry.pid))
25493
- active.add(entry.session_id);
26136
+ active2.add(entry.session_id);
25494
26137
  }
25495
- return active;
26138
+ return active2;
25496
26139
  }
25497
26140
  /** Session ID to every directory claiming it. Enumerated links are not followed. */
25498
26141
  async #sessionDirectories(signal) {
@@ -25526,7 +26169,7 @@ var GrokSessionImport = class {
25526
26169
  }
25527
26170
  return found;
25528
26171
  }
25529
- async #candidate(sessionDirectory, active, signal) {
26172
+ async #candidate(sessionDirectory, active2, signal) {
25530
26173
  signal.throwIfAborted();
25531
26174
  const nativeSessionId = path14.basename(sessionDirectory);
25532
26175
  const files = [
@@ -25560,7 +26203,7 @@ var GrokSessionImport = class {
25560
26203
  title: sessionImportTitle(summary.generated_title) ?? sessionImportTitle(summary.session_summary) ?? sessionImportTitle(prompt),
25561
26204
  updatedAt: updatedAt ?? updates.mtimeMs,
25562
26205
  // Grok registers open Sessions with their process. Absence is not proof of idleness.
25563
- running: active.has(nativeSessionId) ? true : null
26206
+ running: active2.has(nativeSessionId) ? true : null
25564
26207
  });
25565
26208
  } catch (error53) {
25566
26209
  signal.throwIfAborted();
@@ -25628,16 +26271,16 @@ var GrokSubagentLifecycle = class {
25628
26271
  return subagent;
25629
26272
  }
25630
26273
  bindNativeId(turnId, input) {
25631
- for (const [callId, active] of this.#delegations) {
25632
- const current = active.item.subagents[0];
26274
+ for (const [callId, active2] of this.#delegations) {
26275
+ const current = active2.item.subagents[0];
25633
26276
  if (!current)
25634
26277
  continue;
25635
26278
  if (current.nativeSubagentId === input.nativeSubagentId) {
25636
26279
  return this.update(turnId, callId, input);
25637
26280
  }
25638
26281
  }
25639
- for (const [callId, active] of this.#delegations) {
25640
- const current = active.item.subagents[0];
26282
+ for (const [callId, active2] of this.#delegations) {
26283
+ const current = active2.item.subagents[0];
25641
26284
  if (!current || current.nativeSubagentId)
25642
26285
  continue;
25643
26286
  if (input.description && current.description === input.description) {
@@ -25647,10 +26290,10 @@ var GrokSubagentLifecycle = class {
25647
26290
  return void 0;
25648
26291
  }
25649
26292
  update(turnId, callId, patch) {
25650
- const active = this.#delegations.get(callId);
25651
- if (!active)
26293
+ const active2 = this.#delegations.get(callId);
26294
+ if (!active2)
25652
26295
  return void 0;
25653
- const current = active.item.subagents[0];
26296
+ const current = active2.item.subagents[0];
25654
26297
  if (!current)
25655
26298
  throw new Error("Grok Subagent delegation has no Agent state");
25656
26299
  if (patch.nativeSubagentId)
@@ -25666,20 +26309,20 @@ var GrokSubagentLifecycle = class {
25666
26309
  ...patch.resultSummary ? { resultSummary: patch.resultSummary } : {},
25667
26310
  ...patch.status ? { status: patch.status } : {}
25668
26311
  };
25669
- active.item = { ...active.item, subagents: [subagent] };
26312
+ active2.item = { ...active2.item, subagents: [subagent] };
25670
26313
  this.#emit({
25671
26314
  type: "item.updated",
25672
26315
  turnId,
25673
- itemId: active.item.itemId,
25674
- update: { type: "subagents.replace", subagents: active.item.subagents }
26316
+ itemId: active2.item.itemId,
26317
+ update: { type: "subagents.replace", subagents: active2.item.subagents }
25675
26318
  });
25676
26319
  this.#emitState(subagent);
25677
26320
  return subagent;
25678
26321
  }
25679
26322
  completeSpawn(turnId, callId, input) {
25680
- const active = this.#delegations.get(callId);
25681
- const background = input.background ?? active?.item.subagents[0]?.background ?? true;
25682
- const keepRunning = !input.failed && !input.cancellationRequested && (background || active?.item.operation === "send");
26323
+ const active2 = this.#delegations.get(callId);
26324
+ const background = input.background ?? active2?.item.subagents[0]?.background ?? true;
26325
+ const keepRunning = !input.failed && !input.cancellationRequested && (background || active2?.item.operation === "send");
25683
26326
  if (keepRunning) {
25684
26327
  return this.update(turnId, callId, {
25685
26328
  status: "running",
@@ -25704,11 +26347,11 @@ var GrokSubagentLifecycle = class {
25704
26347
  return void 0;
25705
26348
  }
25706
26349
  complete(turnId, callId, input) {
25707
- const active = this.#delegations.get(callId);
25708
- if (!active)
26350
+ const active2 = this.#delegations.get(callId);
26351
+ if (!active2)
25709
26352
  return void 0;
25710
26353
  this.#delegations.delete(callId);
25711
- const current = active.item.subagents[0];
26354
+ const current = active2.item.subagents[0];
25712
26355
  if (!current)
25713
26356
  throw new Error("Grok Subagent delegation has no Agent state");
25714
26357
  const status = input.status ?? (input.cancellationRequested ? "interrupted" : input.failed ? "failed" : input.keepRunning ? "running" : "completed");
@@ -25721,7 +26364,7 @@ var GrokSubagentLifecycle = class {
25721
26364
  ...nativeSubagentId ? { nativeSubagentId, subagentId: nativeSubagentId } : {},
25722
26365
  ...input.resultSummary ? { resultSummary: input.resultSummary } : {}
25723
26366
  };
25724
- const item = { ...active.item, subagents: [subagent] };
26367
+ const item = { ...active2.item, subagents: [subagent] };
25725
26368
  this.#emit({
25726
26369
  type: "item.updated",
25727
26370
  turnId,
@@ -25734,20 +26377,20 @@ var GrokSubagentLifecycle = class {
25734
26377
  return subagent;
25735
26378
  }
25736
26379
  finalize(turnId, outcome) {
25737
- for (const [callId, active] of this.#delegations) {
26380
+ for (const [callId, active2] of this.#delegations) {
25738
26381
  this.#delegations.delete(callId);
25739
- const current = active.item.subagents[0];
26382
+ const current = active2.item.subagents[0];
25740
26383
  if (!current)
25741
26384
  continue;
25742
26385
  const status = outcome.status === "succeeded" ? current.status : outcome.status === "cancelled" ? "interrupted" : "failed";
25743
- const item = { ...active.item, subagents: [{ ...current, status }] };
26386
+ const item = { ...active2.item, subagents: [{ ...current, status }] };
25744
26387
  this.#emit({ type: "item.completed", turnId, snapshot: { item, outcome } });
25745
26388
  this.#emitState({ ...current, status });
25746
26389
  }
25747
26390
  }
25748
26391
  #callIdForNative(nativeSubagentId) {
25749
- for (const [callId, active] of this.#delegations) {
25750
- if (active.item.subagents[0]?.nativeSubagentId === nativeSubagentId)
26392
+ for (const [callId, active2] of this.#delegations) {
26393
+ if (active2.item.subagents[0]?.nativeSubagentId === nativeSubagentId)
25751
26394
  return callId;
25752
26395
  }
25753
26396
  return void 0;
@@ -26470,7 +27113,7 @@ var GrokHarnessSession = class {
26470
27113
  const completion = new Promise((resolve) => {
26471
27114
  resolveCompletion = resolve;
26472
27115
  });
26473
- const active = {
27116
+ const active2 = {
26474
27117
  command,
26475
27118
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
26476
27119
  usage: new GrokTurnUsage(this.#usage, this.#snapshot.turns.length === 0),
@@ -26491,9 +27134,9 @@ var GrokHarnessSession = class {
26491
27134
  completion,
26492
27135
  resolveCompletion
26493
27136
  };
26494
- this.#active = active;
27137
+ this.#active = active2;
26495
27138
  this.#event({ type: "turn.started", turnId: command.turnId });
26496
- void this.#transport.runTurn(text, (event) => this.#handleEvent(active, event), (request) => this.#requestPermission(active, request), (request) => this.#active === active && this.#phase === "open" && !active.cancellationRequested ? active.questions.ask(request) : Promise.resolve({ outcome: "cancelled" })).finally(() => active.questions.cancel()).then((response) => this.#settleFromHistory(active, terminalOutcome2(response, active.cancellationRequested), response), (error53) => this.#settleFromHistory(active, {
27139
+ void this.#transport.runTurn(text, (event) => this.#handleEvent(active2, event), (request) => this.#requestPermission(active2, request), (request) => this.#active === active2 && this.#phase === "open" && !active2.cancellationRequested ? active2.questions.ask(request) : Promise.resolve({ outcome: "cancelled" })).finally(() => active2.questions.cancel()).then((response) => this.#settleFromHistory(active2, terminalOutcome2(response, active2.cancellationRequested), response), (error53) => this.#settleFromHistory(active2, {
26497
27140
  status: "failed",
26498
27141
  error: normalizeError(error53, "nativeFailure")
26499
27142
  }));
@@ -26560,7 +27203,7 @@ var GrokHarnessSession = class {
26560
27203
  const completion = new Promise((resolve) => {
26561
27204
  resolveCompletion = resolve;
26562
27205
  });
26563
- const active = {
27206
+ const active2 = {
26564
27207
  command: { type: "turn.start", turnId: command.turnId, input: [] },
26565
27208
  questions: new GrokQuestions(command.turnId, this.#randomUUID, (output) => this.#channel.emit(output)),
26566
27209
  agent: null,
@@ -26580,20 +27223,20 @@ var GrokHarnessSession = class {
26580
27223
  completion,
26581
27224
  resolveCompletion
26582
27225
  };
26583
- this.#active = active;
27226
+ this.#active = active2;
26584
27227
  this.#event({ type: "turn.started", turnId: command.turnId });
26585
- void this.#transport.compact(userContext, (event) => this.#handleEvent(active, event)).then((result) => this.#settleManualCompact(active, result), (error53) => this.#finish(active, active.compactionTerminal ? this.#turnOutcomeFromCompaction(active.compactionTerminal) : {
27228
+ void this.#transport.compact(userContext, (event) => this.#handleEvent(active2, event)).then((result) => this.#settleManualCompact(active2, result), (error53) => this.#finish(active2, active2.compactionTerminal ? this.#turnOutcomeFromCompaction(active2.compactionTerminal) : {
26586
27229
  status: "failed",
26587
27230
  error: normalizeError(error53, "nativeFailure")
26588
27231
  }));
26589
27232
  return { ok: true, value: { turnId: command.turnId } };
26590
27233
  }
26591
- #settleManualCompact(active, result) {
26592
- if (this.#active !== active)
27234
+ #settleManualCompact(active2, result) {
27235
+ if (this.#active !== active2)
26593
27236
  return;
26594
- const terminal = active.compactionTerminal;
27237
+ const terminal = active2.compactionTerminal;
26595
27238
  if (!terminal) {
26596
- this.#completeCompaction(active, {
27239
+ this.#completeCompaction(active2, {
26597
27240
  type: "compaction.completed",
26598
27241
  outcome: result.outcome,
26599
27242
  ...result.tokensBefore !== void 0 ? { tokensBefore: result.tokensBefore } : {},
@@ -26602,7 +27245,7 @@ var GrokHarnessSession = class {
26602
27245
  ...result.errorMessage ? { errorMessage: result.errorMessage } : {}
26603
27246
  });
26604
27247
  }
26605
- this.#finish(active, terminal ? this.#turnOutcomeFromCompaction(terminal) : result.outcome === "succeeded" ? { status: "succeeded" } : result.outcome === "cancelled" ? { status: "cancelled", reason: "Context compaction was cancelled" } : {
27248
+ this.#finish(active2, terminal ? this.#turnOutcomeFromCompaction(terminal) : result.outcome === "succeeded" ? { status: "succeeded" } : result.outcome === "cancelled" ? { status: "cancelled", reason: "Context compaction was cancelled" } : {
26606
27249
  status: "failed",
26607
27250
  error: {
26608
27251
  code: "nativeFailure",
@@ -26734,15 +27377,15 @@ var GrokHarnessSession = class {
26734
27377
  }
26735
27378
  }
26736
27379
  async #cancel(command) {
26737
- const active = this.#active;
26738
- if (!active || active.command.turnId !== command.turnId) {
27380
+ const active2 = this.#active;
27381
+ if (!active2 || active2.command.turnId !== command.turnId) {
26739
27382
  return { ok: false, error: invalidState("Grok Turn Cancel must reference the active Turn") };
26740
27383
  }
26741
- if (active.cancellationRequested)
27384
+ if (active2.cancellationRequested)
26742
27385
  return { ok: true, value: { cancellationRequested: true } };
26743
- active.cancellationRequested = true;
26744
- active.questions.cancel();
26745
- for (const approval of active.approvals.values()) {
27386
+ active2.cancellationRequested = true;
27387
+ active2.questions.cancel();
27388
+ for (const approval of active2.approvals.values()) {
26746
27389
  approval.resolve({ outcome: { outcome: "cancelled" } });
26747
27390
  }
26748
27391
  try {
@@ -26753,11 +27396,11 @@ var GrokHarnessSession = class {
26753
27396
  }
26754
27397
  }
26755
27398
  async #respond(command) {
26756
- const active = this.#active;
26757
- if (active?.questions.has(command.interactionId))
26758
- return active.questions.respond(command);
26759
- const pending = active?.approvals.get(command.interactionId);
26760
- if (!active || !pending)
27399
+ const active2 = this.#active;
27400
+ if (active2?.questions.has(command.interactionId))
27401
+ return active2.questions.respond(command);
27402
+ const pending = active2?.approvals.get(command.interactionId);
27403
+ if (!active2 || !pending)
26761
27404
  return { ok: false, error: invalidState("Grok Interaction is not pending") };
26762
27405
  if (command.response.type !== "approval") {
26763
27406
  return {
@@ -26782,18 +27425,18 @@ var GrokHarnessSession = class {
26782
27425
  retryable: false
26783
27426
  }
26784
27427
  };
26785
- active.approvals.delete(command.interactionId);
27428
+ active2.approvals.delete(command.interactionId);
26786
27429
  pending.resolve({ outcome: { outcome: "selected", optionId: option.optionId } });
26787
27430
  this.#event({
26788
27431
  type: "interaction.closed",
26789
27432
  interactionId: command.interactionId,
26790
- turnId: active.command.turnId,
27433
+ turnId: active2.command.turnId,
26791
27434
  reason: "responded"
26792
27435
  });
26793
27436
  return { ok: true, value: { accepted: true } };
26794
27437
  }
26795
- #requestPermission(active, request) {
26796
- if (this.#active !== active || active.cancellationRequested) {
27438
+ #requestPermission(active2, request) {
27439
+ if (this.#active !== active2 || active2.cancellationRequested) {
26797
27440
  return Promise.resolve({ outcome: { outcome: "cancelled" } });
26798
27441
  }
26799
27442
  const projectedOptions = projectGrokPermissionOptions(request.options);
@@ -26801,95 +27444,95 @@ var GrokHarnessSession = class {
26801
27444
  return Promise.resolve({ outcome: { outcome: "cancelled" } });
26802
27445
  }
26803
27446
  const interactionId = hostInteractionIdSchema.parse(this.#randomUUID());
26804
- const options = new Map(projectedOptions.map(({ id, option }) => [id, option]));
26805
- const actions = projectedOptions.map(({ id, label, effect }) => ({ id, label, effect }));
27447
+ const options = new Map(projectedOptions.map(({ id: id2, option }) => [id2, option]));
27448
+ const actions = projectedOptions.map(({ id: id2, label, effect }) => ({ id: id2, label, effect }));
26806
27449
  const interaction = {
26807
27450
  type: "approval",
26808
27451
  interactionId,
26809
- turnId: active.command.turnId,
27452
+ turnId: active2.command.turnId,
26810
27453
  title: request.request.toolCall.title ?? "Grok Tool",
26811
27454
  subject: { type: "nativeAction" },
26812
27455
  actions
26813
27456
  };
26814
27457
  return new Promise((resolve) => {
26815
- active.approvals.set(interactionId, { interaction, options, resolve });
27458
+ active2.approvals.set(interactionId, { interaction, options, resolve });
26816
27459
  this.#channel.emit({ kind: "interaction", interaction });
26817
27460
  });
26818
27461
  }
26819
- #handleEvent(active, event) {
26820
- if (this.#active !== active || this.#phase !== "open")
27462
+ #handleEvent(active2, event) {
27463
+ if (this.#active !== active2 || this.#phase !== "open")
26821
27464
  return;
26822
27465
  if (event.type === "interaction.resolved") {
26823
- active.questions.withdraw(event.toolCallId);
27466
+ active2.questions.withdraw(event.toolCallId);
26824
27467
  return;
26825
27468
  }
26826
- const requestUsage = active.usage?.observe(event);
27469
+ const requestUsage = active2.usage?.observe(event);
26827
27470
  if (requestUsage) {
26828
- this.#publishUsage(requestUsage, active.command.turnId, true);
26829
- void this.#refreshCost(active);
27471
+ this.#publishUsage(requestUsage, active2.command.turnId, true);
27472
+ void this.#refreshCost(active2);
26830
27473
  }
26831
27474
  const contextUsage = usageFromUpdate(event.type === "usage" ? event.update : void 0, event.metadata, this.#state.effectiveModel ? this.#modelState.contextWindowTokensByModel.get(this.#state.effectiveModel.id) : void 0);
26832
27475
  if (contextUsage)
26833
- this.#publishUsage(contextUsage, active.command.turnId);
27476
+ this.#publishUsage(contextUsage, active2.command.turnId);
26834
27477
  if (event.type === "agent.text")
26835
- this.#appendAgent(active, event.text, event.messageId);
27478
+ this.#appendAgent(active2, event.text, event.messageId);
26836
27479
  else if (event.type === "agent.thought")
26837
- this.#appendReasoning(active, event.text, event.messageId);
27480
+ this.#appendReasoning(active2, event.text, event.messageId);
26838
27481
  else if (event.type === "tool.call")
26839
- this.#startTool(active, event);
27482
+ this.#startTool(active2, event);
26840
27483
  else if (event.type === "tool.update")
26841
- this.#updateTool(active, event);
27484
+ this.#updateTool(active2, event);
26842
27485
  else if (event.type === "subagent.spawned")
26843
- this.#bindSpawnedSubagent(active, event);
27486
+ this.#bindSpawnedSubagent(active2, event);
26844
27487
  else if (event.type === "subagent.finished")
26845
- this.#finishNativeSubagent(active, event);
27488
+ this.#finishNativeSubagent(active2, event);
26846
27489
  else if (event.type === "compaction.started")
26847
- this.#startCompaction(active, event);
27490
+ this.#startCompaction(active2, event);
26848
27491
  else if (event.type === "compaction.completed") {
26849
- active.compactionTerminal = event;
26850
- this.#completeCompaction(active, event);
27492
+ active2.compactionTerminal = event;
27493
+ this.#completeCompaction(active2, event);
26851
27494
  } else if (event.type === "usage" || event.type === "turn.completed")
26852
27495
  return;
26853
27496
  }
26854
- async #refreshCost(active) {
27497
+ async #refreshCost(active2) {
26855
27498
  const request = ++this.#costRequest;
26856
27499
  try {
26857
27500
  const totalCostUsd = sessionCostFromNative(await this.#transport.getUsage(), this.#initialCostUsd);
26858
- if (this.#active !== active || this.#phase !== "open" || request !== this.#costRequest)
27501
+ if (this.#active !== active2 || this.#phase !== "open" || request !== this.#costRequest)
26859
27502
  return;
26860
27503
  if (totalCostUsd !== void 0)
26861
- this.#publishUsage({ totalCostUsd }, active.command.turnId);
27504
+ this.#publishUsage({ totalCostUsd }, active2.command.turnId);
26862
27505
  } catch {
26863
27506
  }
26864
27507
  }
26865
- #startCompaction(active, event) {
26866
- if (active.compactionItem)
27508
+ #startCompaction(active2, event) {
27509
+ if (active2.compactionItem)
26867
27510
  return;
26868
- this.#completeReasoning(active, { status: "succeeded" });
26869
- this.#completeAgent(active, { status: "succeeded" });
27511
+ this.#completeReasoning(active2, { status: "succeeded" });
27512
+ this.#completeAgent(active2, { status: "succeeded" });
26870
27513
  if (event.contextWindowTokens !== void 0) {
26871
- active.compactionContextWindow = event.contextWindowTokens;
27514
+ active2.compactionContextWindow = event.contextWindowTokens;
26872
27515
  }
26873
27516
  const item = {
26874
27517
  type: "contextCompaction",
26875
27518
  itemId: hostItemIdSchema.parse(this.#randomUUID())
26876
27519
  };
26877
- active.compactionItem = item;
26878
- this.#event({ type: "item.started", turnId: active.command.turnId, item });
27520
+ active2.compactionItem = item;
27521
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item });
26879
27522
  }
26880
- #completeCompaction(active, event) {
26881
- if (!active.compactionItem) {
26882
- this.#startCompaction(active, {
27523
+ #completeCompaction(active2, event) {
27524
+ if (!active2.compactionItem) {
27525
+ this.#startCompaction(active2, {
26883
27526
  type: "compaction.started",
26884
27527
  ...event.contextWindowTokens !== void 0 ? { contextWindowTokens: event.contextWindowTokens } : {}
26885
27528
  });
26886
27529
  }
26887
- const item = active.compactionItem;
27530
+ const item = active2.compactionItem;
26888
27531
  if (!item)
26889
27532
  return;
26890
- active.compactionItem = null;
26891
- const contextWindowTokens = event.contextWindowTokens ?? active.compactionContextWindow ?? (this.#state.effectiveModel ? this.#modelState.contextWindowTokensByModel.get(this.#state.effectiveModel.id) : void 0);
26892
- active.compactionContextWindow = void 0;
27533
+ active2.compactionItem = null;
27534
+ const contextWindowTokens = event.contextWindowTokens ?? active2.compactionContextWindow ?? (this.#state.effectiveModel ? this.#modelState.contextWindowTokensByModel.get(this.#state.effectiveModel.id) : void 0);
27535
+ active2.compactionContextWindow = void 0;
26893
27536
  const outcome = event.outcome === "succeeded" ? { status: "succeeded" } : event.outcome === "cancelled" ? { status: "cancelled", reason: "Context compaction was cancelled" } : {
26894
27537
  status: "failed",
26895
27538
  error: {
@@ -26898,62 +27541,62 @@ var GrokHarnessSession = class {
26898
27541
  retryable: true
26899
27542
  }
26900
27543
  };
26901
- this.#completeItem(active, item, outcome);
27544
+ this.#completeItem(active2, item, outcome);
26902
27545
  if (event.outcome !== "succeeded")
26903
27546
  return;
26904
27547
  const usage = usageFromCompact(event.tokensAfter, contextWindowTokens);
26905
27548
  if (usage)
26906
- this.#publishUsage(usage, active.command.turnId);
27549
+ this.#publishUsage(usage, active2.command.turnId);
26907
27550
  }
26908
- #appendAgent(active, text, messageId) {
27551
+ #appendAgent(active2, text, messageId) {
26909
27552
  const identity2 = messageId ?? "agent";
26910
- if (active.agentMessageId !== identity2) {
26911
- this.#completeReasoning(active, { status: "succeeded" });
26912
- this.#completeAgent(active, { status: "succeeded" });
26913
- active.agentMessageId = identity2;
27553
+ if (active2.agentMessageId !== identity2) {
27554
+ this.#completeReasoning(active2, { status: "succeeded" });
27555
+ this.#completeAgent(active2, { status: "succeeded" });
27556
+ active2.agentMessageId = identity2;
26914
27557
  }
26915
- if (!active.agent) {
26916
- active.agent = {
27558
+ if (!active2.agent) {
27559
+ active2.agent = {
26917
27560
  type: "agentMessage",
26918
27561
  itemId: hostItemIdSchema.parse(this.#randomUUID()),
26919
27562
  text: ""
26920
27563
  };
26921
- active.agentMedia = new LocalMediaMarkdownStream(this.#mediaRoots);
26922
- this.#event({ type: "item.started", turnId: active.command.turnId, item: active.agent });
27564
+ active2.agentMedia = new LocalMediaMarkdownStream(this.#mediaRoots);
27565
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item: active2.agent });
26923
27566
  }
26924
- const delta = active.agentMedia?.append(text) ?? "";
26925
- this.#publishAgent(active, delta);
27567
+ const delta = active2.agentMedia?.append(text) ?? "";
27568
+ this.#publishAgent(active2, delta);
26926
27569
  }
26927
- #publishAgent(active, delta) {
26928
- if (!active.agent || !active.agentMedia || !delta)
27570
+ #publishAgent(active2, delta) {
27571
+ if (!active2.agent || !active2.agentMedia || !delta)
26929
27572
  return;
26930
- active.agent = { ...active.agent, text: active.agentMedia.text };
27573
+ active2.agent = { ...active2.agent, text: active2.agentMedia.text };
26931
27574
  this.#event({
26932
27575
  type: "item.updated",
26933
- turnId: active.command.turnId,
26934
- itemId: active.agent.itemId,
27576
+ turnId: active2.command.turnId,
27577
+ itemId: active2.agent.itemId,
26935
27578
  update: { type: "text.append", text: delta }
26936
27579
  });
26937
27580
  }
26938
- #appendReasoning(active, text, messageId) {
27581
+ #appendReasoning(active2, text, messageId) {
26939
27582
  const identity2 = messageId ?? "thought";
26940
- if (active.reasoningMessageId !== identity2) {
26941
- this.#completeReasoning(active, { status: "succeeded" });
26942
- active.reasoningMessageId = identity2;
27583
+ if (active2.reasoningMessageId !== identity2) {
27584
+ this.#completeReasoning(active2, { status: "succeeded" });
27585
+ active2.reasoningMessageId = identity2;
26943
27586
  }
26944
- if (!active.reasoning) {
26945
- active.reasoning = {
27587
+ if (!active2.reasoning) {
27588
+ active2.reasoning = {
26946
27589
  type: "reasoning",
26947
27590
  itemId: hostItemIdSchema.parse(this.#randomUUID()),
26948
27591
  text: ""
26949
27592
  };
26950
- this.#event({ type: "item.started", turnId: active.command.turnId, item: active.reasoning });
27593
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item: active2.reasoning });
26951
27594
  }
26952
- active.reasoning = { ...active.reasoning, text: active.reasoning.text + text };
27595
+ active2.reasoning = { ...active2.reasoning, text: active2.reasoning.text + text };
26953
27596
  this.#event({
26954
27597
  type: "item.updated",
26955
- turnId: active.command.turnId,
26956
- itemId: active.reasoning.itemId,
27598
+ turnId: active2.command.turnId,
27599
+ itemId: active2.reasoning.itemId,
26957
27600
  update: { type: "text.append", text }
26958
27601
  });
26959
27602
  }
@@ -26963,16 +27606,16 @@ var GrokHarnessSession = class {
26963
27606
  emit: (event) => this.#event(event)
26964
27607
  });
26965
27608
  }
26966
- #startTool(active, event) {
26967
- this.#completeReasoning(active, { status: "succeeded" });
26968
- this.#completeAgent(active, { status: "succeeded" });
27609
+ #startTool(active2, event) {
27610
+ this.#completeReasoning(active2, { status: "succeeded" });
27611
+ this.#completeAgent(active2, { status: "succeeded" });
26969
27612
  const operation = grokSubagentOperation(event.name, event.title, event.rawInput);
26970
27613
  if (operation) {
26971
27614
  const prompt = grokSubagentPrompt(event.rawInput);
26972
27615
  const role = grokSubagentRole(event.rawInput);
26973
27616
  const nativeSubagentId = grokNativeSubagentId(event.rawInput);
26974
27617
  const model2 = grokSubagentModel(event.rawInput);
26975
- active.subagents.start(active.command.turnId, {
27618
+ active2.subagents.start(active2.command.turnId, {
26976
27619
  callId: event.callId,
26977
27620
  operation,
26978
27621
  description: grokSubagentDescription(event.rawInput, event.title),
@@ -26984,7 +27627,7 @@ var GrokHarnessSession = class {
26984
27627
  ...nativeSubagentId ? { nativeSubagentId } : {}
26985
27628
  });
26986
27629
  if (event.status === "completed" || event.status === "failed") {
26987
- this.#completeSubagentTool(active, event.callId, event.status, event);
27630
+ this.#completeSubagentTool(active2, event.callId, event.status, event);
26988
27631
  }
26989
27632
  return;
26990
27633
  }
@@ -26999,15 +27642,15 @@ var GrokHarnessSession = class {
26999
27642
  const projection = projectGrokToolOutput(event.content, event.rawOutput, this.#toolOutputLimit);
27000
27643
  if (hasGrokToolProjection(projection))
27001
27644
  item = applyGrokToolProjection(item, projection);
27002
- active.tools.set(event.callId, { item, ...event.status ? { status: event.status } : {} });
27003
- this.#event({ type: "item.started", turnId: active.command.turnId, item });
27645
+ active2.tools.set(event.callId, { item, ...event.status ? { status: event.status } : {} });
27646
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item });
27004
27647
  if (event.status === "completed" || event.status === "failed") {
27005
- this.#completeTool(active, event.callId, event.status, event.content, event.rawOutput);
27648
+ this.#completeTool(active2, event.callId, event.status, event.content, event.rawOutput);
27006
27649
  }
27007
27650
  }
27008
- #updateTool(active, event) {
27009
- if (!active.subagents.has(event.callId) && !active.tools.has(event.callId) && grokSubagentOperation(event.name, event.title, event.rawInput)) {
27010
- this.#startTool(active, {
27651
+ #updateTool(active2, event) {
27652
+ if (!active2.subagents.has(event.callId) && !active2.tools.has(event.callId) && grokSubagentOperation(event.name, event.title, event.rawInput)) {
27653
+ this.#startTool(active2, {
27011
27654
  type: "tool.call",
27012
27655
  callId: event.callId,
27013
27656
  title: event.title ?? "Grok Subagent",
@@ -27020,14 +27663,14 @@ var GrokHarnessSession = class {
27020
27663
  });
27021
27664
  return;
27022
27665
  }
27023
- if (active.subagents.has(event.callId)) {
27666
+ if (active2.subagents.has(event.callId)) {
27024
27667
  if (event.status === "completed" || event.status === "failed") {
27025
- this.#completeSubagentTool(active, event.callId, event.status, event);
27668
+ this.#completeSubagentTool(active2, event.callId, event.status, event);
27026
27669
  return;
27027
27670
  }
27028
27671
  const role = grokSubagentRole(event.rawInput);
27029
27672
  const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
27030
- active.subagents.update(active.command.turnId, event.callId, {
27673
+ active2.subagents.update(active2.command.turnId, event.callId, {
27031
27674
  ...subagentConfiguration(event.rawInput),
27032
27675
  ...subagentConfiguration(event.rawOutput),
27033
27676
  ...event.title ? { description: grokSubagentDescription(event.rawInput, event.title) } : {},
@@ -27036,7 +27679,7 @@ var GrokHarnessSession = class {
27036
27679
  });
27037
27680
  return;
27038
27681
  }
27039
- const tool = active.tools.get(event.callId);
27682
+ const tool = active2.tools.get(event.callId);
27040
27683
  if (!tool)
27041
27684
  return;
27042
27685
  const projection = projectGrokToolOutput(event.content, event.rawOutput, this.#toolOutputLimit);
@@ -27050,7 +27693,7 @@ var GrokHarnessSession = class {
27050
27693
  if (delta.length > 0) {
27051
27694
  this.#event({
27052
27695
  type: "item.updated",
27053
- turnId: active.command.turnId,
27696
+ turnId: active2.command.turnId,
27054
27697
  itemId: tool.item.itemId,
27055
27698
  update: { type: "output.append", text: delta }
27056
27699
  });
@@ -27059,7 +27702,7 @@ var GrokHarnessSession = class {
27059
27702
  } else if (tool.item.type === "toolExecution" && projection.output) {
27060
27703
  this.#event({
27061
27704
  type: "item.updated",
27062
- turnId: active.command.turnId,
27705
+ turnId: active2.command.turnId,
27063
27706
  itemId: tool.item.itemId,
27064
27707
  update: { type: "output.replace", output: projection.output }
27065
27708
  });
@@ -27068,14 +27711,14 @@ var GrokHarnessSession = class {
27068
27711
  if (event.status)
27069
27712
  tool.status = event.status;
27070
27713
  if (event.status === "completed" || event.status === "failed") {
27071
- this.#completeTool(active, event.callId, event.status, event.content, event.rawOutput);
27714
+ this.#completeTool(active2, event.callId, event.status, event.content, event.rawOutput);
27072
27715
  }
27073
27716
  }
27074
- #completeTool(active, callId, status, content, rawOutput) {
27075
- const tool = active.tools.get(callId);
27717
+ #completeTool(active2, callId, status, content, rawOutput) {
27718
+ const tool = active2.tools.get(callId);
27076
27719
  if (!tool)
27077
27720
  return;
27078
- active.tools.delete(callId);
27721
+ active2.tools.delete(callId);
27079
27722
  const projection = projectGrokToolOutput(content, rawOutput, this.#toolOutputLimit);
27080
27723
  if (hasGrokToolProjection(projection)) {
27081
27724
  tool.item = applyGrokToolProjection(tool.item, projection);
@@ -27088,10 +27731,10 @@ var GrokHarnessSession = class {
27088
27731
  retryable: false
27089
27732
  }
27090
27733
  } : { status: "succeeded" };
27091
- this.#completeItem(active, tool.item, outcome);
27734
+ this.#completeItem(active2, tool.item, outcome);
27092
27735
  if (status !== "completed")
27093
27736
  return;
27094
- this.#completeWatchedSubagents(active, tool.item, content, rawOutput);
27737
+ this.#completeWatchedSubagents(active2, tool.item, content, rawOutput);
27095
27738
  const changes = projectGrokFileChanges(content, this.#cwd);
27096
27739
  if (!changes)
27097
27740
  return;
@@ -27101,20 +27744,20 @@ var GrokHarnessSession = class {
27101
27744
  sourceItemIds: [tool.item.itemId],
27102
27745
  changes
27103
27746
  };
27104
- this.#event({ type: "item.started", turnId: active.command.turnId, item: fileItem });
27105
- this.#completeItem(active, fileItem, { status: "succeeded" });
27747
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item: fileItem });
27748
+ this.#completeItem(active2, fileItem, { status: "succeeded" });
27106
27749
  }
27107
- #completeSubagentTool(active, callId, status, event) {
27750
+ #completeSubagentTool(active2, callId, status, event) {
27108
27751
  const nativeSubagentId = grokNativeSubagentId(event.rawInput, event.rawOutput, event.content);
27109
27752
  const resultSummary = grokSubagentResultSummary(event.content, event.rawOutput);
27110
- active.subagents.completeSpawn(active.command.turnId, callId, {
27753
+ active2.subagents.completeSpawn(active2.command.turnId, callId, {
27111
27754
  failed: status === "failed",
27112
- cancellationRequested: active.cancellationRequested,
27755
+ cancellationRequested: active2.cancellationRequested,
27113
27756
  ...nativeSubagentId ? { nativeSubagentId } : {},
27114
27757
  ...resultSummary ? { resultSummary } : {}
27115
27758
  });
27116
27759
  }
27117
- #completeWatchedSubagents(active, item, content, rawOutput) {
27760
+ #completeWatchedSubagents(active2, item, content, rawOutput) {
27118
27761
  const name = item.type === "toolExecution" ? item.toolName : item.command;
27119
27762
  const rawInput = item.type === "toolExecution" ? item.arguments : void 0;
27120
27763
  const resultSummary = grokSubagentResultSummary(content, rawOutput);
@@ -27125,64 +27768,64 @@ var GrokHarnessSession = class {
27125
27768
  content,
27126
27769
  rawOutput
27127
27770
  })) {
27128
- active.subagents.completeByNativeId(active.command.turnId, settlement.id, {
27771
+ active2.subagents.completeByNativeId(active2.command.turnId, settlement.id, {
27129
27772
  failed: settlement.status === "failed",
27130
- cancellationRequested: active.cancellationRequested || settlement.status === "interrupted",
27773
+ cancellationRequested: active2.cancellationRequested || settlement.status === "interrupted",
27131
27774
  status: settlement.status,
27132
27775
  ...settlement.resultSummary ? { resultSummary: settlement.resultSummary } : resultSummary ? { resultSummary } : {}
27133
27776
  });
27134
27777
  }
27135
27778
  }
27136
- #bindSpawnedSubagent(active, event) {
27137
- active.subagents.bindNativeId(active.command.turnId, {
27779
+ #bindSpawnedSubagent(active2, event) {
27780
+ active2.subagents.bindNativeId(active2.command.turnId, {
27138
27781
  nativeSubagentId: event.nativeSubagentId,
27139
27782
  ...event.description ? { description: event.description } : {},
27140
27783
  ...event.role ? { role: event.role } : {},
27141
27784
  ...event.model ? { model: event.model } : {}
27142
27785
  });
27143
27786
  }
27144
- #finishNativeSubagent(active, event) {
27145
- active.subagents.completeByNativeId(active.command.turnId, event.nativeSubagentId, {
27787
+ #finishNativeSubagent(active2, event) {
27788
+ active2.subagents.completeByNativeId(active2.command.turnId, event.nativeSubagentId, {
27146
27789
  failed: event.status === "failed",
27147
- cancellationRequested: active.cancellationRequested || event.status === "interrupted",
27790
+ cancellationRequested: active2.cancellationRequested || event.status === "interrupted",
27148
27791
  status: event.status,
27149
27792
  ...event.resultSummary ? { resultSummary: event.resultSummary } : {}
27150
27793
  });
27151
27794
  }
27152
- #completeAgent(active, outcome) {
27153
- const item = active.agent;
27154
- if (item && active.agentMedia)
27155
- this.#publishAgent(active, active.agentMedia.flush());
27156
- const completed = active.agent ?? item;
27157
- active.agent = null;
27158
- active.agentMessageId = null;
27159
- active.agentMedia = null;
27795
+ #completeAgent(active2, outcome) {
27796
+ const item = active2.agent;
27797
+ if (item && active2.agentMedia)
27798
+ this.#publishAgent(active2, active2.agentMedia.flush());
27799
+ const completed = active2.agent ?? item;
27800
+ active2.agent = null;
27801
+ active2.agentMessageId = null;
27802
+ active2.agentMedia = null;
27160
27803
  if (completed)
27161
- this.#completeItem(active, completed, outcome);
27804
+ this.#completeItem(active2, completed, outcome);
27162
27805
  }
27163
- #completeReasoning(active, outcome) {
27164
- const item = active.reasoning;
27165
- active.reasoning = null;
27166
- active.reasoningMessageId = null;
27806
+ #completeReasoning(active2, outcome) {
27807
+ const item = active2.reasoning;
27808
+ active2.reasoning = null;
27809
+ active2.reasoningMessageId = null;
27167
27810
  if (item)
27168
- this.#completeItem(active, item, outcome);
27811
+ this.#completeItem(active2, item, outcome);
27169
27812
  }
27170
- #completeItem(active, item, outcome) {
27813
+ #completeItem(active2, item, outcome) {
27171
27814
  const snapshot = { item, outcome };
27172
- active.completedItems.push(snapshot);
27815
+ active2.completedItems.push(snapshot);
27173
27816
  this.#event({
27174
27817
  type: "item.completed",
27175
- turnId: active.command.turnId,
27818
+ turnId: active2.command.turnId,
27176
27819
  snapshot
27177
27820
  });
27178
27821
  }
27179
- async #settleFromHistory(active, outcome, response) {
27822
+ async #settleFromHistory(active2, outcome, response) {
27180
27823
  let history = [];
27181
27824
  let nativeTurnRef;
27182
27825
  let checkpoint;
27183
27826
  try {
27184
27827
  history = await this.#refreshSnapshot();
27185
- const created = this.#snapshot.turns.filter((turn) => !active.beforeNativeTurnKeys.has(turn.nativeTurnRef.nativeTurnKey));
27828
+ const created = this.#snapshot.turns.filter((turn) => !active2.beforeNativeTurnKeys.has(turn.nativeTurnRef.nativeTurnKey));
27186
27829
  if (created.length !== 1) {
27187
27830
  throw new Error(`Grok Turn persisted ${created.length} new Native Turns; exactly one is required`);
27188
27831
  }
@@ -27204,43 +27847,43 @@ var GrokHarnessSession = class {
27204
27847
  }
27205
27848
  const usage = sessionUsageFromHistory(history);
27206
27849
  await this.#refreshCredits().catch(() => void 0);
27207
- this.#finish(active, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
27850
+ this.#finish(active2, checkpoint ? { ...outcome, checkpoint } : outcome, usage, nativeTurnRef);
27208
27851
  }
27209
- #finish(active, outcome, usage = null, nativeTurnRef) {
27210
- if (this.#active !== active)
27852
+ #finish(active2, outcome, usage = null, nativeTurnRef) {
27853
+ if (this.#active !== active2)
27211
27854
  return;
27212
- active.questions.cancel();
27855
+ active2.questions.cancel();
27213
27856
  const itemOutcome = outcome;
27214
- this.#completeReasoning(active, itemOutcome);
27215
- this.#completeAgent(active, itemOutcome);
27216
- active.subagents.finalize(active.command.turnId, itemOutcome);
27217
- if (active.compactionItem) {
27218
- this.#completeItem(active, active.compactionItem, itemOutcome);
27219
- active.compactionItem = null;
27220
- }
27221
- for (const tool of active.tools.values())
27222
- this.#completeItem(active, tool.item, itemOutcome);
27223
- active.tools.clear();
27224
- for (const [interactionId, pending] of active.approvals) {
27225
- active.approvals.delete(interactionId);
27857
+ this.#completeReasoning(active2, itemOutcome);
27858
+ this.#completeAgent(active2, itemOutcome);
27859
+ active2.subagents.finalize(active2.command.turnId, itemOutcome);
27860
+ if (active2.compactionItem) {
27861
+ this.#completeItem(active2, active2.compactionItem, itemOutcome);
27862
+ active2.compactionItem = null;
27863
+ }
27864
+ for (const tool of active2.tools.values())
27865
+ this.#completeItem(active2, tool.item, itemOutcome);
27866
+ active2.tools.clear();
27867
+ for (const [interactionId, pending] of active2.approvals) {
27868
+ active2.approvals.delete(interactionId);
27226
27869
  pending.resolve({ outcome: { outcome: "cancelled" } });
27227
27870
  this.#event({
27228
27871
  type: "interaction.closed",
27229
27872
  interactionId,
27230
- turnId: active.command.turnId,
27873
+ turnId: active2.command.turnId,
27231
27874
  reason: "cancelled"
27232
27875
  });
27233
27876
  }
27234
27877
  this.#active = null;
27235
27878
  if (usage || this.#usage)
27236
- this.#publishUsage({ ...usage, ...active.usage?.metrics() }, active.command.turnId, true);
27879
+ this.#publishUsage({ ...usage, ...active2.usage?.metrics() }, active2.command.turnId, true);
27237
27880
  this.#event({
27238
27881
  type: "turn.completed",
27239
- turnId: active.command.turnId,
27882
+ turnId: active2.command.turnId,
27240
27883
  ...nativeTurnRef ? { nativeTurnRef } : {},
27241
27884
  outcome
27242
27885
  });
27243
- active.resolveCompletion();
27886
+ active2.resolveCompletion();
27244
27887
  }
27245
27888
  #publishUsage(usage, observedForTurnId, replaceMetrics = false) {
27246
27889
  const base = this.#usage ? { ...this.#usage } : null;
@@ -27263,15 +27906,15 @@ var GrokHarnessSession = class {
27263
27906
  if (this.#phase === "closed")
27264
27907
  return;
27265
27908
  this.#phase = "closing";
27266
- const active = this.#active;
27267
- if (active) {
27268
- active.cancellationRequested = true;
27269
- active.questions.cancel();
27270
- for (const approval of active.approvals.values())
27909
+ const active2 = this.#active;
27910
+ if (active2) {
27911
+ active2.cancellationRequested = true;
27912
+ active2.questions.cancel();
27913
+ for (const approval of active2.approvals.values())
27271
27914
  approval.resolve({ outcome: { outcome: "cancelled" } });
27272
27915
  await this.#transport.cancel().catch(() => void 0);
27273
27916
  await Promise.race([
27274
- active.completion,
27917
+ active2.completion,
27275
27918
  new Promise((resolve) => setTimeout(resolve, this.#closeTimeoutMs))
27276
27919
  ]);
27277
27920
  }
@@ -27302,6 +27945,7 @@ var GrokHarnessSession = class {
27302
27945
  }
27303
27946
  };
27304
27947
  var GrokAdapter = class {
27948
+ normalizeStoredModelRef = normalizeStoredGrokModelRef;
27305
27949
  credentialExport = {
27306
27950
  read: () => this.#closePromise ? Promise.resolve([]) : readGrokCredentials(this.#environment ?? process.env)
27307
27951
  };
@@ -27404,15 +28048,19 @@ var GrokAdapter = class {
27404
28048
  }
27405
28049
  return this.#credits;
27406
28050
  }
28051
+ #inspectionGeneration = 0;
27407
28052
  async inspect(input = {}) {
27408
28053
  if (this.#closePromise)
27409
28054
  return { status: "unavailable", error: invalidState("Grok Adapter is closed") };
27410
28055
  const cwd = path16.resolve(input.cwd ?? process.cwd());
27411
- if (!input.refresh) {
27412
- const cached2 = this.#inspectionCache.get(cwd);
27413
- if (cached2 && Date.now() < cached2.expiresAt)
27414
- return cached2.inspection;
28056
+ if (input.refresh) {
28057
+ this.#inspectionCache.clear();
28058
+ this.#inspectionGeneration++;
27415
28059
  }
28060
+ const cached2 = this.#inspectionCache.get(cwd);
28061
+ if (cached2 && Date.now() < cached2.expiresAt)
28062
+ return cached2.inspection;
28063
+ const generation = this.#inspectionGeneration;
27416
28064
  let transport = null;
27417
28065
  const startedAt = Date.now();
27418
28066
  let stage = "spawn";
@@ -27431,10 +28079,12 @@ var GrokAdapter = class {
27431
28079
  permissionModes: GROK_PERMISSION_MODE_CATALOG,
27432
28080
  capabilities: capabilitiesForModels(modelState)
27433
28081
  };
27434
- this.#inspectionCache.set(cwd, {
27435
- inspection: ready,
27436
- expiresAt: Date.now() + INSPECTION_CACHE_TTL_MS
27437
- });
28082
+ if (!this.#closePromise && generation === this.#inspectionGeneration) {
28083
+ this.#inspectionCache.set(cwd, {
28084
+ inspection: ready,
28085
+ expiresAt: Date.now() + INSPECTION_CACHE_TTL_MS
28086
+ });
28087
+ }
27438
28088
  this.#scheduleCreditsRefresh();
27439
28089
  return ready;
27440
28090
  } catch (error53) {
@@ -27573,7 +28223,8 @@ var GrokAdapter = class {
27573
28223
  }
27574
28224
  };
27575
28225
  }
27576
- const modelState = modelStateFromSessionResponse(opened.session) ?? modelStateFromInitialize(opened.initialize);
28226
+ const sessionModelState = modelStateFromSessionResponse(opened.session);
28227
+ const modelState = sessionModelState ?? modelStateFromInitialize(opened.initialize);
27577
28228
  if (!modelState)
27578
28229
  throw new GrokTransportError("protocolError", "Grok returned an invalid Model catalog");
27579
28230
  const nativeModelId = modelState.currentModel.id;
@@ -27615,8 +28266,16 @@ var GrokAdapter = class {
27615
28266
  delete modelState.currentThinkingOptionId;
27616
28267
  }
27617
28268
  }
28269
+ const savedModel = input.kind === "resume" && !sessionModelState && input.model ? modelState.catalog.models.find(({ ref }) => ref.id === input.model?.id) : void 0;
28270
+ if (savedModel) {
28271
+ modelState.currentModel = savedModel.ref;
28272
+ const thinking = modelState.currentThinkingOptionId;
28273
+ if (thinking && !savedModel.supportedThinkingOptionIds?.includes(thinking)) {
28274
+ delete modelState.currentThinkingOptionId;
28275
+ }
28276
+ }
27618
28277
  const contextWindow = modelState.defaultContextWindowTokensByModel.get(modelState.currentModel.id);
27619
- if (modelState.currentModel.id !== nativeModelId || modelState.currentThinkingOptionId !== nativeThinkingOptionId || contextWindow !== void 0 && modelState.contextWindowTokensByModel.get(modelState.currentModel.id) !== contextWindow) {
28278
+ if (savedModel || modelState.currentModel.id !== nativeModelId || modelState.currentThinkingOptionId !== nativeThinkingOptionId || contextWindow !== void 0 && modelState.contextWindowTokensByModel.get(modelState.currentModel.id) !== contextWindow) {
27620
28279
  await transport.setModel(modelState.currentModel.id, modelState.currentThinkingOptionId, contextWindow);
27621
28280
  if (contextWindow !== void 0) {
27622
28281
  modelState.contextWindowTokensByModel = new Map([