@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
  }
@@ -1661,8 +1661,8 @@ function cleanEnum(obj) {
1661
1661
  return Number.isNaN(Number.parseInt(k, 10));
1662
1662
  }).map((el) => el[1]);
1663
1663
  }
1664
- function base64ToUint8Array(base643) {
1665
- const binaryString = atob(base643);
1664
+ function base64ToUint8Array(base644) {
1665
+ const binaryString = atob(base644);
1666
1666
  const bytes = new Uint8Array(binaryString.length);
1667
1667
  for (let i = 0; i < binaryString.length; i++) {
1668
1668
  bytes[i] = binaryString.charCodeAt(i);
@@ -1677,9 +1677,9 @@ function uint8ArrayToBase64(bytes) {
1677
1677
  return btoa(binaryString);
1678
1678
  }
1679
1679
  function base64urlToUint8Array(base64url3) {
1680
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1681
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1682
- return base64ToUint8Array(base643 + padding);
1680
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1681
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1682
+ return base64ToUint8Array(base644 + padding);
1683
1683
  }
1684
1684
  function uint8ArrayToBase64url(bytes) {
1685
1685
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -3045,8 +3045,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
3045
3045
  function isValidBase64URL(data) {
3046
3046
  if (!base64url.test(data))
3047
3047
  return false;
3048
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3049
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
3048
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
3049
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
3050
3050
  return isValidBase64(padded);
3051
3051
  }
3052
3052
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -3500,42 +3500,42 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3500
3500
  }
3501
3501
  doc.write(`const newResult = {};`);
3502
3502
  for (const key of normalized.keys) {
3503
- const id = ids[key];
3503
+ const id2 = ids[key];
3504
3504
  const k = esc(key);
3505
3505
  const schema = shape[key];
3506
3506
  const isOptionalIn = schema?._zod?.optin === "optional";
3507
3507
  const isOptionalOut = schema?._zod?.optout === "optional";
3508
- doc.write(`const ${id} = ${parseStr(key)};`);
3508
+ doc.write(`const ${id2} = ${parseStr(key)};`);
3509
3509
  if (isOptionalIn && isOptionalOut) {
3510
3510
  doc.write(`
3511
- if (${id}.issues.length) {
3511
+ if (${id2}.issues.length) {
3512
3512
  if (${k} in input) {
3513
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3513
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3514
3514
  ...iss,
3515
3515
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3516
3516
  })));
3517
3517
  }
3518
3518
  }
3519
3519
 
3520
- if (${id}.value === undefined) {
3520
+ if (${id2}.value === undefined) {
3521
3521
  if (${k} in input) {
3522
3522
  newResult[${k}] = undefined;
3523
3523
  }
3524
3524
  } else {
3525
- newResult[${k}] = ${id}.value;
3525
+ newResult[${k}] = ${id2}.value;
3526
3526
  }
3527
3527
 
3528
3528
  `);
3529
3529
  } else if (!isOptionalIn) {
3530
3530
  doc.write(`
3531
- const ${id}_present = ${k} in input;
3532
- if (${id}.issues.length) {
3533
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3531
+ const ${id2}_present = ${k} in input;
3532
+ if (${id2}.issues.length) {
3533
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3534
3534
  ...iss,
3535
3535
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3536
3536
  })));
3537
3537
  }
3538
- if (!${id}_present && !${id}.issues.length) {
3538
+ if (!${id2}_present && !${id2}.issues.length) {
3539
3539
  payload.issues.push({
3540
3540
  code: "invalid_type",
3541
3541
  expected: "nonoptional",
@@ -3544,30 +3544,30 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
3544
3544
  });
3545
3545
  }
3546
3546
 
3547
- if (${id}_present) {
3548
- if (${id}.value === undefined) {
3547
+ if (${id2}_present) {
3548
+ if (${id2}.value === undefined) {
3549
3549
  newResult[${k}] = undefined;
3550
3550
  } else {
3551
- newResult[${k}] = ${id}.value;
3551
+ newResult[${k}] = ${id2}.value;
3552
3552
  }
3553
3553
  }
3554
3554
 
3555
3555
  `);
3556
3556
  } else {
3557
3557
  doc.write(`
3558
- if (${id}.issues.length) {
3559
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
3558
+ if (${id2}.issues.length) {
3559
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
3560
3560
  ...iss,
3561
3561
  path: iss.path ? [${k}, ...iss.path] : [${k}]
3562
3562
  })));
3563
3563
  }
3564
3564
 
3565
- if (${id}.value === undefined) {
3565
+ if (${id2}.value === undefined) {
3566
3566
  if (${k} in input) {
3567
3567
  newResult[${k}] = undefined;
3568
3568
  }
3569
3569
  } else {
3570
- newResult[${k}] = ${id}.value;
3570
+ newResult[${k}] = ${id2}.value;
3571
3571
  }
3572
3572
 
3573
3573
  `);
@@ -11899,26 +11899,26 @@ function extractDefs(ctx, schema) {
11899
11899
  throw new Error("Unprocessed schema. This is a bug in Zod.");
11900
11900
  const idToSchema = /* @__PURE__ */ new Map();
11901
11901
  for (const entry of ctx.seen.entries()) {
11902
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11903
- if (id) {
11904
- const existing = idToSchema.get(id);
11902
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11903
+ if (id2) {
11904
+ const existing = idToSchema.get(id2);
11905
11905
  if (existing && existing !== entry[0]) {
11906
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11906
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
11907
11907
  }
11908
- idToSchema.set(id, entry[0]);
11908
+ idToSchema.set(id2, entry[0]);
11909
11909
  }
11910
11910
  }
11911
11911
  const makeURI = (entry) => {
11912
11912
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
11913
11913
  if (ctx.external) {
11914
11914
  const externalId = ctx.external.registry.get(entry[0])?.id;
11915
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
11915
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
11916
11916
  if (externalId) {
11917
11917
  return { ref: uriGenerator(externalId) };
11918
11918
  }
11919
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11920
- entry[1].defId = id;
11921
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
11919
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
11920
+ entry[1].defId = id2;
11921
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
11922
11922
  }
11923
11923
  if (entry[1] === root) {
11924
11924
  return { ref: "#" };
@@ -11966,8 +11966,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11966
11966
  continue;
11967
11967
  }
11968
11968
  }
11969
- const id = ctx.metadataRegistry.get(entry[0])?.id;
11970
- if (id) {
11969
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
11970
+ if (id2) {
11971
11971
  extractToDef(entry);
11972
11972
  continue;
11973
11973
  }
@@ -12063,10 +12063,10 @@ function finalize(ctx, schema) {
12063
12063
  } else {
12064
12064
  }
12065
12065
  if (ctx.external?.uri) {
12066
- const id = ctx.external.registry.get(schema)?.id;
12067
- if (!id)
12066
+ const id2 = ctx.external.registry.get(schema)?.id;
12067
+ if (!id2)
12068
12068
  throw new Error("Schema is missing an `id` property");
12069
- result.$id = ctx.external.uri(id);
12069
+ result.$id = ctx.external.uri(id2);
12070
12070
  }
12071
12071
  Object.assign(result, root.def ?? root.schema);
12072
12072
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -12226,9 +12226,9 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12226
12226
  json2.type = "number";
12227
12227
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
12228
12228
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
12229
- const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12229
+ const legacy2 = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
12230
12230
  if (exMin) {
12231
- if (legacy) {
12231
+ if (legacy2) {
12232
12232
  json2.minimum = exclusiveMinimum;
12233
12233
  json2.exclusiveMinimum = true;
12234
12234
  } else {
@@ -12238,7 +12238,7 @@ var numberProcessor = (schema, ctx, _json, _params) => {
12238
12238
  json2.minimum = minimum;
12239
12239
  }
12240
12240
  if (exMax) {
12241
- if (legacy) {
12241
+ if (legacy2) {
12242
12242
  json2.maximum = exclusiveMaximum;
12243
12243
  json2.exclusiveMaximum = true;
12244
12244
  } else {
@@ -13100,7 +13100,7 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
13100
13100
 
13101
13101
  // ../../../node_modules/zod/v4/classic/schemas.js
13102
13102
  var _installedGroups = /* @__PURE__ */ new WeakMap();
13103
- function _installLazyMethods(inst, group, methods) {
13103
+ function _installLazyMethods(inst, group, methods2) {
13104
13104
  const proto = Object.getPrototypeOf(inst);
13105
13105
  let installed = _installedGroups.get(proto);
13106
13106
  if (!installed) {
@@ -13110,8 +13110,8 @@ function _installLazyMethods(inst, group, methods) {
13110
13110
  if (installed.has(group))
13111
13111
  return;
13112
13112
  installed.add(group);
13113
- for (const key in methods) {
13114
- const fn = methods[key];
13113
+ for (const key in methods2) {
13114
+ const fn = methods2[key];
13115
13115
  Object.defineProperty(proto, key, {
13116
13116
  configurable: true,
13117
13117
  enumerable: false,
@@ -15055,6 +15055,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15055
15055
  permissionModeId: harnessPermissionModeIdSchema
15056
15056
  }).strict();
15057
15057
 
15058
+ // ../../shared-contracts/dist/harness-route-limit.js
15059
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
15060
+
15058
15061
  // ../../shared-contracts/dist/thread-usage.js
15059
15062
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15060
15063
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -15087,7 +15090,7 @@ var composerIndicatorsSchema = external_exports.array(external_exports.object({
15087
15090
  expiresAtUnix: nonNegativeSafeIntegerSchema,
15088
15091
  label: indicatorTextSchema(256).optional(),
15089
15092
  tooltip: indicatorTextSchema(1024).optional()
15090
- }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
15093
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
15091
15094
  message: "Composer indicator IDs must be unique"
15092
15095
  });
15093
15096
  var threadUsageSnapshotSchema = external_exports.object({
@@ -15113,6 +15116,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15113
15116
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
15114
15117
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
15115
15118
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15119
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
15116
15120
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
15117
15121
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
15118
15122
  }).strict().superRefine((usage, context) => {
@@ -15210,6 +15214,13 @@ var accountCreditsSnapshotSchema = external_exports.object({
15210
15214
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15211
15215
  resetCredits: accountResetCreditsSchema.optional()
15212
15216
  }).strict();
15217
+ var accountBalanceSnapshotSchema = external_exports.object({
15218
+ amount: external_exports.number().finite().nonnegative(),
15219
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15220
+ currency: external_exports.string().trim().min(1).max(8),
15221
+ /** Native label when the Harness exposes several Billing Sources. */
15222
+ label: external_exports.string().trim().min(1).max(128).optional()
15223
+ }).strict();
15213
15224
  var threadUsageInspectionParamsSchema = external_exports.object({
15214
15225
  threadId: hostThreadIdSchema,
15215
15226
  refresh: external_exports.literal("exact").optional()
@@ -15218,7 +15229,10 @@ var threadUsageInspectionSchema = external_exports.object({
15218
15229
  threadId: hostThreadIdSchema,
15219
15230
  usage: threadUsageSnapshotSchema.nullable(),
15220
15231
  accountCredits: accountCreditsSnapshotSchema.optional(),
15221
- /** Whether this source can provide cached account quota independently of usage. */
15232
+ /** Prepaid funds for the Thread's Billing Source; shown only when no percentage quota exists. */
15233
+ accountBalance: accountBalanceSnapshotSchema.optional(),
15234
+ /** Whether this source can provide cached account quota (credits or a prepaid balance)
15235
+ * independently of usage. */
15222
15236
  accountCreditsSupported: external_exports.boolean().optional()
15223
15237
  }).strict();
15224
15238
 
@@ -15230,10 +15244,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
15230
15244
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15231
15245
  message: "Value must not be empty or whitespace"
15232
15246
  });
15233
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
15247
+ 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();
15248
+ var harnessModelServiceTierSchema = external_exports.enum(["priority", "ultrafast"]);
15234
15249
  var harnessModelRefSchema = external_exports.object({
15235
- id: harnessModelRefIdSchema
15250
+ id: harnessModelRefIdSchema,
15251
+ serviceTier: harnessModelServiceTierSchema.optional()
15236
15252
  }).strict();
15253
+ function sameHarnessModelRef(left, right) {
15254
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
15255
+ }
15237
15256
  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();
15238
15257
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15239
15258
  var harnessThinkingOptionSchema = external_exports.object({
@@ -15247,7 +15266,15 @@ var harnessModelSchema = external_exports.object({
15247
15266
  /** Optional opaque selection for this same Model with priority processing enabled. */
15248
15267
  fastModel: harnessModelRefSchema.optional(),
15249
15268
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
15250
- }).strict();
15269
+ }).strict().refine((model2) => model2.fastModel?.serviceTier === void 0 || model2.fastModel.id === model2.ref.id, {
15270
+ path: ["fastModel", "id"],
15271
+ message: "A tiered Fast Model must share the base Model ID"
15272
+ });
15273
+ function catalogModelForRef(catalog, ref) {
15274
+ if (!ref)
15275
+ return void 0;
15276
+ return catalog?.models.find((model2) => sameHarnessModelRef(model2.ref, ref) || sameHarnessModelRef(model2.fastModel, ref));
15277
+ }
15251
15278
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
15252
15279
  const ids = /* @__PURE__ */ new Set();
15253
15280
  for (const [index, option] of options.entries()) {
@@ -15267,26 +15294,26 @@ var harnessModelCatalogSchema = external_exports.object({
15267
15294
  thinkingOptions: harnessThinkingOptionsSchema,
15268
15295
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
15269
15296
  }).strict().superRefine((catalog, context) => {
15270
- const refs = /* @__PURE__ */ new Set();
15271
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
15297
+ const refs = [];
15298
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
15272
15299
  for (const [index, model2] of catalog.models.entries()) {
15273
- if (refs.has(model2.ref.id)) {
15300
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
15274
15301
  context.addIssue({
15275
15302
  code: "custom",
15276
15303
  message: "Model Catalog refs must be unique",
15277
15304
  path: ["models", index, "ref", "id"]
15278
15305
  });
15279
15306
  }
15280
- refs.add(model2.ref.id);
15307
+ refs.push(model2.ref);
15281
15308
  if (model2.fastModel) {
15282
- if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
15309
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.fastModel))) {
15283
15310
  context.addIssue({
15284
15311
  code: "custom",
15285
15312
  message: "Fast Model refs must be distinct and unique",
15286
15313
  path: ["models", index, "fastModel"]
15287
15314
  });
15288
15315
  }
15289
- refs.add(model2.fastModel.id);
15316
+ refs.push(model2.fastModel);
15290
15317
  }
15291
15318
  const supportedThinkingIds = /* @__PURE__ */ new Set();
15292
15319
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -15307,7 +15334,7 @@ var harnessModelCatalogSchema = external_exports.object({
15307
15334
  }
15308
15335
  }
15309
15336
  }
15310
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
15337
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
15311
15338
  context.addIssue({
15312
15339
  code: "custom",
15313
15340
  message: "Default Model must exist in the Model Catalog",
@@ -15347,7 +15374,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
15347
15374
  observe: external_exports.boolean()
15348
15375
  }).strict().optional(),
15349
15376
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
15350
- steer: external_exports.boolean().optional()
15377
+ steer: external_exports.boolean().optional(),
15378
+ /**
15379
+ * True when the native plan (task list) outlives the Turn that changed it, so a reopened
15380
+ * Thread gets its latest plan again. Otherwise a plan stays with the Turn that made it.
15381
+ */
15382
+ persistentPlan: external_exports.boolean().optional()
15351
15383
  }).strict();
15352
15384
  var harnessConfigurationStateSchema = external_exports.object({
15353
15385
  effectiveModel: harnessModelRefSchema.optional(),
@@ -15356,7 +15388,7 @@ var harnessConfigurationStateSchema = external_exports.object({
15356
15388
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
15357
15389
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
15358
15390
  }).strict().superRefine((state2, context) => {
15359
- if (state2.effectiveThinkingOptionId && state2.availableThinkingOptions && !state2.availableThinkingOptions.some(({ id }) => id === state2.effectiveThinkingOptionId)) {
15391
+ if (state2.effectiveThinkingOptionId && state2.availableThinkingOptions && !state2.availableThinkingOptions.some(({ id: id2 }) => id2 === state2.effectiveThinkingOptionId)) {
15360
15392
  context.addIssue({
15361
15393
  code: "custom",
15362
15394
  message: "Effective Thinking option must be currently available",
@@ -15396,7 +15428,8 @@ var harnessInspectParamsSchema = external_exports.object({
15396
15428
  cwd: nonBlankTextSchema2.max(16384).optional(),
15397
15429
  refresh: external_exports.boolean().optional(),
15398
15430
  /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
15399
- purpose: external_exports.literal("availability").optional()
15431
+ purpose: external_exports.literal("availability").optional(),
15432
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
15400
15433
  }).strict();
15401
15434
  var harnessWebUiOpenParamsSchema = external_exports.object({
15402
15435
  harnessId: harnessIdSchema
@@ -15427,7 +15460,7 @@ var codexThreadInspectionSchema = external_exports.object({
15427
15460
  var externalThreadInspectionSchema = external_exports.object({
15428
15461
  owner: external_exports.literal("external"),
15429
15462
  harnessId: nonBlankTextSchema2.max(256),
15430
- transportModelId: nonBlankTextSchema2.max(1024),
15463
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
15431
15464
  effectiveModel: harnessModelRefSchema.optional(),
15432
15465
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15433
15466
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15509,13 +15542,635 @@ var threadSteeringInspectResultSchema = external_exports.object({
15509
15542
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15510
15543
  }).strict();
15511
15544
 
15545
+ // ../../shared-contracts/dist/harness-plugins.js
15546
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15547
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15548
+ var HARNESS_PLUGIN_LIMIT = 128;
15549
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
15550
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
15551
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id2) => id2 !== "codex", "The official Codex identity is reserved");
15552
+ 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");
15553
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15554
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
15555
+ var harnessInstallationGuideSchema = external_exports.object({
15556
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
15557
+ before: localizedTextSchema.optional(),
15558
+ after: localizedTextSchema.optional(),
15559
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
15560
+ }).strict();
15561
+ var pluginPresentationShape = {
15562
+ id: installedHarnessPluginIdSchema,
15563
+ name: external_exports.string().trim().min(1).max(128),
15564
+ version: external_exports.string().min(1).max(128),
15565
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
15566
+ kind: external_exports.literal("usage").optional(),
15567
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
15568
+ iconStyle: external_exports.object({
15569
+ vector: external_exports.object({
15570
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
15571
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
15572
+ paths: external_exports.array(external_exports.object({
15573
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
15574
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
15575
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
15576
+ }).strict()).min(1).max(32)
15577
+ }).strict().optional(),
15578
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
15579
+ borderRadius: external_exports.number().min(0).max(50).optional(),
15580
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
15581
+ }).strict().optional(),
15582
+ installation: harnessInstallationGuideSchema.optional(),
15583
+ notice: localizedTextSchema.optional(),
15584
+ /** The factory accepts a persisted local entrypoint through its construction context. */
15585
+ launchCommand: external_exports.literal(true).optional(),
15586
+ links: external_exports.object({
15587
+ website: documentationUrlSchema.optional(),
15588
+ documentation: documentationUrlSchema.optional(),
15589
+ installation: documentationUrlSchema.optional()
15590
+ }).strict().optional()
15591
+ };
15592
+ var harnessPluginManifestSchema = external_exports.object({
15593
+ manifestVersion: external_exports.literal(1),
15594
+ ...pluginPresentationShape,
15595
+ adapterApiVersion: external_exports.number().int().positive(),
15596
+ entry: pluginRelativeResourceSchema,
15597
+ icon: pluginRelativeResourceSchema.optional()
15598
+ }).strict();
15599
+ 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);
15600
+ var harnessPluginDescriptorSchema = external_exports.object({
15601
+ ...pluginPresentationShape,
15602
+ icon: harnessPluginIconSchema.optional()
15603
+ }).strict();
15604
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15605
+ var harnessPluginListResultSchema = external_exports.object({
15606
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15607
+ }).strict();
15608
+ var harnessPluginConfigurationSchema = external_exports.object({
15609
+ version: external_exports.literal(1),
15610
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15611
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15612
+ message: "Enabled plugin IDs must be unique",
15613
+ path: ["enabled"]
15614
+ });
15615
+
15616
+ // ../../shared-contracts/dist/desktop-extensions.js
15617
+ var DESKTOP_EXTENSION_API_VERSION = 1;
15618
+ var DESKTOP_EXTENSION_LIMIT = 64;
15619
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15620
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15621
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15622
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15623
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15624
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15625
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15626
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15627
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15628
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15629
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15630
+ var desktopExtensionIdSchema = installedPluginIdSchema;
15631
+ var desktopExtensionSlotSchema = external_exports.enum([
15632
+ "sidebar.thread-layout",
15633
+ "sidebar.thread-badge",
15634
+ "appearance.theme"
15635
+ ]);
15636
+ var desktopExtensionCategorySchema = external_exports.enum([
15637
+ "appearance",
15638
+ "interface",
15639
+ "workflow",
15640
+ "analytics",
15641
+ "integrations",
15642
+ "tools"
15643
+ ]);
15644
+ var extensionName = external_exports.string().trim().min(1).max(128);
15645
+ function desktopExtensionScreenshotMimeType(resource) {
15646
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15647
+ case "png":
15648
+ return "image/png";
15649
+ case "jpg":
15650
+ case "jpeg":
15651
+ return "image/jpeg";
15652
+ case "webp":
15653
+ return "image/webp";
15654
+ default:
15655
+ return void 0;
15656
+ }
15657
+ }
15658
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15659
+ 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");
15660
+ 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) => {
15661
+ const { username, password } = new URL(value);
15662
+ return !username && !password && !/[\\\s]/u.test(value);
15663
+ }, "URL must not contain credentials, backslashes, or whitespace");
15664
+ function localizedText(text4) {
15665
+ return external_exports.strictObject({ en: text4, "zh-CN": text4 });
15666
+ }
15667
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15668
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15669
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15670
+ var settingField = {
15671
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15672
+ label: desktopExtensionLocalizedTextSchema,
15673
+ description: desktopExtensionLocalizedTextSchema.optional()
15674
+ };
15675
+ var numericSetting = {
15676
+ ...settingField,
15677
+ step: external_exports.number().positive().optional(),
15678
+ default: external_exports.number().optional()
15679
+ };
15680
+ var settingOption = external_exports.strictObject({
15681
+ value: external_exports.string(),
15682
+ label: desktopExtensionLocalizedTextSchema
15683
+ });
15684
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15685
+ external_exports.strictObject({
15686
+ ...settingField,
15687
+ type: external_exports.literal("boolean"),
15688
+ default: external_exports.boolean().optional()
15689
+ }),
15690
+ external_exports.strictObject({
15691
+ ...settingField,
15692
+ type: external_exports.literal("string"),
15693
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
15694
+ default: external_exports.string().optional()
15695
+ }),
15696
+ external_exports.strictObject({
15697
+ ...numericSetting,
15698
+ type: external_exports.literal("number"),
15699
+ min: external_exports.number().optional(),
15700
+ max: external_exports.number().optional()
15701
+ }),
15702
+ external_exports.strictObject({
15703
+ ...numericSetting,
15704
+ type: external_exports.literal("range"),
15705
+ min: external_exports.number(),
15706
+ max: external_exports.number()
15707
+ }),
15708
+ external_exports.strictObject({
15709
+ ...settingField,
15710
+ type: external_exports.literal("select"),
15711
+ options: external_exports.array(settingOption).min(1),
15712
+ default: external_exports.string().optional()
15713
+ })
15714
+ ]).superRefine((field2, ctx) => {
15715
+ const issue2 = (path18, message3) => ctx.addIssue({ code: "custom", path: [path18], message: message3 });
15716
+ if (field2.type === "number" || field2.type === "range") {
15717
+ const { min = -Infinity, max = Infinity, default: value } = field2;
15718
+ if (min > max)
15719
+ issue2("max", "Must be at least min");
15720
+ if (value !== void 0 && (value < min || value > max))
15721
+ issue2("default", "Must be within min and max");
15722
+ } else if (field2.type === "select") {
15723
+ const values = new Set(field2.options.map(({ value }) => value));
15724
+ if (values.size !== field2.options.length)
15725
+ issue2("options", "Duplicate option values");
15726
+ if (field2.default !== void 0 && !values.has(field2.default))
15727
+ issue2("default", "Must match an option value");
15728
+ }
15729
+ });
15730
+ var manifestHeader = external_exports.object({
15731
+ manifestVersion: external_exports.int().positive(),
15732
+ id: desktopExtensionIdSchema,
15733
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
15734
+ version: external_exports.string().min(1).max(128),
15735
+ desktopApi: external_exports.int().positive()
15736
+ }).passthrough();
15737
+ var desktopExtensionManifestSchema = manifestHeader.extend({
15738
+ manifestVersion: external_exports.literal(1),
15739
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15740
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15741
+ author: external_exports.string().trim().min(1).max(128).optional(),
15742
+ repository: desktopExtensionHttpUrlSchema.optional(),
15743
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15744
+ icon: imagePathSchema.optional(),
15745
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15746
+ desktop: external_exports.strictObject({
15747
+ script: pluginRelativeResourceSchema,
15748
+ style: pluginRelativeResourceSchema.optional()
15749
+ }).optional(),
15750
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15751
+ slots: slotsSchema.default(() => []),
15752
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15753
+ categories: categoriesSchema.optional()
15754
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15755
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15756
+ var desktopExtensionStatusSchema = external_exports.strictObject({
15757
+ state: external_exports.enum([
15758
+ "running",
15759
+ "disabled",
15760
+ "invalid",
15761
+ "incompatible",
15762
+ "conflict",
15763
+ "failed",
15764
+ "waiting"
15765
+ ]),
15766
+ hash: desktopExtensionHashSchema.optional(),
15767
+ error: external_exports.string().optional(),
15768
+ conflictWith: desktopExtensionIdSchema.optional()
15769
+ });
15770
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15771
+ controllerPid: external_exports.int().positive(),
15772
+ targetId: external_exports.string().nullable(),
15773
+ updatedAt: external_exports.iso.datetime(),
15774
+ handledReloadToken: external_exports.uuid().optional(),
15775
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema),
15776
+ surfaces: external_exports.record(external_exports.string(), desktopExtensionStatusSchema).optional()
15777
+ });
15778
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15779
+ function isGitHubDesktopExtensionZipballUrl(url2) {
15780
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15781
+ }
15782
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15783
+ const url2 = new URL(input);
15784
+ 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);
15785
+ }, "Expected a .zip download URL or a GitHub zipball URL");
15786
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15787
+ id: desktopExtensionIdSchema,
15788
+ version: external_exports.string().trim().min(1).max(128),
15789
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15790
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
15791
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15792
+ author: external_exports.string().trim().min(1).max(128),
15793
+ repository: desktopExtensionHttpUrlSchema,
15794
+ stars: external_exports.number().int().min(0).optional(),
15795
+ downloads: external_exports.number().int().min(0).optional(),
15796
+ categories: categoriesSchema.optional(),
15797
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
15798
+ icon: desktopExtensionHttpUrlSchema.optional(),
15799
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15800
+ downloadUrl: desktopExtensionZipUrlSchema,
15801
+ sha256: desktopExtensionHashSchema,
15802
+ slots: slotsSchema.optional(),
15803
+ publishedAt: external_exports.string().optional(),
15804
+ updatedAt: external_exports.string().optional(),
15805
+ minCodexHostVersion: external_exports.string().optional()
15806
+ });
15807
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
15808
+ schemaVersion: external_exports.literal(1),
15809
+ generatedAt: external_exports.string(),
15810
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15811
+ });
15812
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15813
+
15814
+ // ../../shared-contracts/dist/host-extensions.js
15815
+ var reservedName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu;
15816
+ var HOST_EXTENSION_PAGE_API_VERSION = 1;
15817
+ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedName.test(id2), "Reserved extension ID");
15818
+ var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
15819
+ var hostExtensionDigestSchema = desktopExtensionHashSchema;
15820
+ var hostExtensionActivationIdSchema = external_exports.uuid();
15821
+ 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((path18) => path18.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
15822
+ var legacy = desktopExtensionManifestSchema.shape;
15823
+ var localized = (max, min = 0) => external_exports.strictObject({
15824
+ en: external_exports.string().trim().min(min).max(max),
15825
+ "zh-CN": external_exports.string().trim().min(min).max(max)
15826
+ });
15827
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path18) => path18.endsWith(suffix), `Expected a ${suffix} file`);
15828
+ var moduleEntry = resourceWithSuffix(".mjs");
15829
+ var style = resourceWithSuffix(".css").optional();
15830
+ var hostExtensionCanonicalPath = (path18) => path18.normalize("NFC").toLowerCase();
15831
+ var hostExtensionManifestV2Schema = external_exports.strictObject({
15832
+ manifestVersion: external_exports.literal(2),
15833
+ id: hostExtensionIdSchema,
15834
+ name: localized(128, 1),
15835
+ version: external_exports.string().trim().min(1).max(128),
15836
+ description: localized(4096),
15837
+ details: localized(16384).optional(),
15838
+ author: legacy.author,
15839
+ repository: legacy.repository,
15840
+ icon: legacy.icon.refine((path18) => path18 === void 0 || hostExtensionResourcePathSchema.safeParse(path18).success),
15841
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path18) => hostExtensionResourcePathSchema.safeParse(path18).success)),
15842
+ categories: legacy.categories,
15843
+ settingsSchema: legacy.settingsSchema,
15844
+ slots: legacy.slots.removeDefault().optional(),
15845
+ page: external_exports.strictObject({
15846
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15847
+ entry: moduleEntry,
15848
+ style,
15849
+ title: localized(128, 1).optional()
15850
+ }).optional(),
15851
+ widget: external_exports.strictObject({
15852
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
15853
+ entry: moduleEntry,
15854
+ style
15855
+ }).optional(),
15856
+ desktop: external_exports.strictObject({ apiVersion: external_exports.literal(1), script: resourceWithSuffix(".js"), style }).optional(),
15857
+ 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(),
15858
+ backend: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry }).optional()
15859
+ }).refine(({ page, widget: widget2, desktop, web, backend }) => Boolean(page || widget2 || desktop || web || backend), "Expected at least one page, widget, desktop, web, or backend entry").refine(({ page, widget: widget2, web, backend }) => !backend || [page?.entry, widget2?.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" });
15860
+ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBackend }) {
15861
+ if (hasPage || hasWidget || hasBackend && !hasDesktop && !hasWeb)
15862
+ return ["desktop", "web"];
15863
+ const targets = [];
15864
+ if (hasDesktop)
15865
+ targets.push("desktop");
15866
+ if (hasWeb)
15867
+ targets.push("web");
15868
+ return targets;
15869
+ }
15870
+ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
15871
+
15872
+ // ../../shared-contracts/dist/host-extension-management.js
15873
+ var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
15874
+ var hostExtensionRevisionSchema = external_exports.int().nonnegative();
15875
+ var hostExtensionConfigurationSchema = external_exports.strictObject({
15876
+ revision: hostExtensionRevisionSchema,
15877
+ enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
15878
+ });
15879
+ var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
15880
+ var hostExtensionCatalogEntrySchema = external_exports.object({
15881
+ ...catalogMetadata,
15882
+ id: hostExtensionIdSchema,
15883
+ format: external_exports.literal("codexhost"),
15884
+ targets: external_exports.array(hostExtensionTargetSchema).min(1).max(2).refine((targets) => new Set(targets).size === targets.length, "Duplicate targets"),
15885
+ apis: external_exports.strictObject({
15886
+ page: external_exports.int().positive().optional(),
15887
+ widget: external_exports.int().positive().optional(),
15888
+ desktop: external_exports.int().positive().optional(),
15889
+ web: external_exports.int().positive().optional(),
15890
+ backend: external_exports.int().positive().optional()
15891
+ }),
15892
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
15893
+ }).refine(({ targets, apis }) => {
15894
+ const derived = targetsForCapabilities({
15895
+ hasPage: Boolean(apis.page),
15896
+ hasWidget: Boolean(apis.widget),
15897
+ hasDesktop: Boolean(apis.desktop),
15898
+ hasWeb: Boolean(apis.web),
15899
+ hasBackend: Boolean(apis.backend)
15900
+ });
15901
+ return targets.length === derived.length && derived.every((target2) => targets.includes(target2));
15902
+ }, "Catalog targets must match the declared APIs");
15903
+ var hostExtensionCatalogSchema = external_exports.object({
15904
+ schemaVersion: external_exports.literal(2),
15905
+ generatedAt: external_exports.string().min(1),
15906
+ extensions: external_exports.array(hostExtensionCatalogEntrySchema).max(1e4).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
15907
+ });
15908
+ var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
15909
+ catalogUrl: desktopExtensionHttpUrlSchema,
15910
+ fetchedAt: external_exports.iso.datetime(),
15911
+ cached: external_exports.boolean()
15912
+ });
15913
+ var id = { id: hostExtensionIdSchema };
15914
+ var active = {
15915
+ ...id,
15916
+ activationId: hostExtensionActivationIdSchema,
15917
+ digest: hostExtensionDigestSchema
15918
+ };
15919
+ var optionalActivation = { ...id, activationId: active.activationId.optional() };
15920
+ var filePath = external_exports.string().min(1).max(4096).refine((path18) => /^(?:\/|[a-z]:[/\\])/iu.test(path18) && !path18.includes("\0") && !path18.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
15921
+ 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");
15922
+ function base643(maxBytes) {
15923
+ return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
15924
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
15925
+ return value.length % 4 === 0 && value.length * 3 / 4 - padding <= maxBytes && /^[A-Za-z0-9+/]*={0,2}$/u.test(value);
15926
+ }, "Expected bounded standard padded base64");
15927
+ }
15928
+ var hostExtensionGitHubSourceSchema = external_exports.strictObject({
15929
+ type: external_exports.literal("github"),
15930
+ repository: external_exports.string().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),
15931
+ ref: gitRef.optional(),
15932
+ tag: gitRef.optional(),
15933
+ asset: external_exports.string().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),
15934
+ subpath: hostExtensionResourcePathSchema.optional()
15935
+ }).refine(({ ref, tag, asset }) => !ref || !tag && !asset, "Use either a zipball ref or a release tag/asset");
15936
+ var hostExtensionInstallSourceSchema = external_exports.union([
15937
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15938
+ hostExtensionGitHubSourceSchema,
15939
+ external_exports.strictObject({ type: external_exports.literal("zip"), base64: base643(HOST_EXTENSION_ZIP_MAX_BYTES).min(4) }),
15940
+ external_exports.strictObject({ type: external_exports.literal("zip"), localZipPath: filePath }),
15941
+ external_exports.strictObject({ type: external_exports.literal("localDir"), localDir: filePath })
15942
+ ]);
15943
+ var hostExtensionProvenanceSchema = external_exports.discriminatedUnion("type", [
15944
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
15945
+ hostExtensionGitHubSourceSchema,
15946
+ external_exports.strictObject({ type: external_exports.literal("zip") }),
15947
+ external_exports.strictObject({ type: external_exports.literal("localDir") })
15948
+ ]);
15949
+ var hostExtensionInstallationSchema = external_exports.strictObject({
15950
+ ...active,
15951
+ manifest: hostExtensionManifestV2Schema,
15952
+ installedAt: external_exports.iso.datetime(),
15953
+ source: hostExtensionProvenanceSchema.optional()
15954
+ });
15955
+ 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);
15956
+ var desktopConflict = { desktopConflictWith: hostExtensionIdSchema.optional() };
15957
+ var backendState = external_exports.enum(["none", "inactive", "starting", "running", "failed"]);
15958
+ var hostExtensionListItemSchema = external_exports.discriminatedUnion("state", [
15959
+ hostExtensionInstallationSchema.extend({
15960
+ state: external_exports.literal("valid"),
15961
+ enabled: external_exports.boolean(),
15962
+ ...desktopConflict,
15963
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15964
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15965
+ backendState: backendState.optional(),
15966
+ backendError: external_exports.string().optional()
15967
+ }),
15968
+ external_exports.strictObject({
15969
+ state: external_exports.enum(["invalid", "incompatible"]),
15970
+ id: external_exports.string().min(1),
15971
+ enabled: external_exports.boolean(),
15972
+ error: external_exports.string()
15973
+ })
15974
+ ]);
15975
+ var hostExtensionsListResultSchema = external_exports.strictObject({
15976
+ revision: hostExtensionRevisionSchema,
15977
+ configuration: hostExtensionConfigurationSchema,
15978
+ diagnostics: external_exports.array(external_exports.string()),
15979
+ extensions: external_exports.array(hostExtensionListItemSchema)
15980
+ });
15981
+ var hostExtensionRuntimeEntrySchema = hostExtensionInstallationSchema.extend({
15982
+ ...desktopConflict,
15983
+ settingsRevision: hostExtensionRevisionSchema
15984
+ });
15985
+ var hostExtensionsSnapshotResultSchema = external_exports.strictObject({
15986
+ /** The Host publishes this revision in extensions-changed, independent of enabled.json's revision. */
15987
+ revision: hostExtensionRevisionSchema,
15988
+ // Enabled, valid activations only. A Desktop conflict does not hide other capabilities.
15989
+ extensions: external_exports.array(hostExtensionRuntimeEntrySchema).max(DESKTOP_EXTENSION_LIMIT)
15990
+ });
15991
+ var HOST_EXTENSIONS_RPC = {
15992
+ list: "codexhost/extensions/list",
15993
+ snapshot: "codexhost/extensions/snapshot",
15994
+ catalog: "codexhost/extensions/catalog",
15995
+ install: "codexhost/extensions/install",
15996
+ update: "codexhost/extensions/update",
15997
+ enable: "codexhost/extensions/enable",
15998
+ disable: "codexhost/extensions/disable",
15999
+ uninstall: "codexhost/extensions/uninstall",
16000
+ recover: "codexhost/extensions/recover",
16001
+ asset: "codexhost/extensions/asset",
16002
+ settingsGet: "codexhost/extensions/settings/get",
16003
+ settingsSet: "codexhost/extensions/settings/set",
16004
+ backendInvoke: "codexhost/extensions/backend/invoke"
16005
+ };
16006
+ var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
16007
+ var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
16008
+ var noParams = external_exports.strictObject({});
16009
+ var expectedRevision = { expectedRevision: hostExtensionRevisionSchema };
16010
+ var selection = external_exports.strictObject({ ...id, ...expectedRevision });
16011
+ var installationResult = hostExtensionInstallationSchema.extend({ replaced: external_exports.boolean() });
16012
+ var mutationResult = external_exports.discriminatedUnion("state", [
16013
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: hostExtensionConfigurationSchema }),
16014
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: hostExtensionRevisionSchema })
16015
+ ]);
16016
+ var hostExtensionsAssetParamsSchema = external_exports.strictObject({
16017
+ ...optionalActivation,
16018
+ digest: active.digest.optional(),
16019
+ path: hostExtensionResourcePathSchema
16020
+ });
16021
+ var hostExtensionsAssetResultSchema = external_exports.strictObject({
16022
+ mimeType: external_exports.string().min(1),
16023
+ base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
16024
+ digest: active.digest
16025
+ });
16026
+ var hostExtensionSettingsSchema = external_exports.strictObject({
16027
+ settingsRevision: hostExtensionRevisionSchema,
16028
+ values: jsonObjectSchema
16029
+ });
16030
+ var hostExtensionsRpcSchemas = {
16031
+ [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
16032
+ [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
16033
+ [HOST_EXTENSIONS_RPC.catalog]: {
16034
+ params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
16035
+ result: hostExtensionsCatalogResultSchema
16036
+ },
16037
+ [HOST_EXTENSIONS_RPC.install]: {
16038
+ params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
16039
+ result: installationResult
16040
+ },
16041
+ [HOST_EXTENSIONS_RPC.update]: {
16042
+ params: external_exports.strictObject({
16043
+ ...id,
16044
+ expectedDigest: active.digest,
16045
+ expectedActivationId: active.activationId.optional(),
16046
+ source: hostExtensionInstallSourceSchema.optional()
16047
+ }),
16048
+ result: installationResult
16049
+ },
16050
+ [HOST_EXTENSIONS_RPC.enable]: { params: selection, result: mutationResult },
16051
+ [HOST_EXTENSIONS_RPC.disable]: { params: selection, result: mutationResult },
16052
+ [HOST_EXTENSIONS_RPC.uninstall]: {
16053
+ params: external_exports.strictObject({
16054
+ ...id,
16055
+ removeData: external_exports.boolean().optional(),
16056
+ expectedDigest: active.digest.optional()
16057
+ }),
16058
+ result: external_exports.strictObject({ ...id, removed: external_exports.boolean() })
16059
+ },
16060
+ [HOST_EXTENSIONS_RPC.recover]: {
16061
+ params: external_exports.strictObject({ expectedRevision: expectedRevision.expectedRevision.optional() }),
16062
+ result: mutationResult
16063
+ },
16064
+ [HOST_EXTENSIONS_RPC.asset]: {
16065
+ params: hostExtensionsAssetParamsSchema,
16066
+ result: hostExtensionsAssetResultSchema
16067
+ },
16068
+ [HOST_EXTENSIONS_RPC.settingsGet]: {
16069
+ params: external_exports.strictObject(optionalActivation),
16070
+ result: hostExtensionSettingsSchema
16071
+ },
16072
+ [HOST_EXTENSIONS_RPC.settingsSet]: {
16073
+ params: external_exports.strictObject({
16074
+ ...optionalActivation,
16075
+ expectedSettingsRevision: hostExtensionRevisionSchema,
16076
+ values: jsonObjectSchema
16077
+ }),
16078
+ result: hostExtensionSettingsSchema
16079
+ },
16080
+ [HOST_EXTENSIONS_RPC.backendInvoke]: {
16081
+ params: external_exports.strictObject({
16082
+ ...optionalActivation,
16083
+ method: hostExtensionBackendMethodSchema,
16084
+ params: jsonValueSchema.optional()
16085
+ }),
16086
+ result: external_exports.strictObject({ result: jsonValueSchema })
16087
+ }
16088
+ };
16089
+
15512
16090
  // ../../shared-contracts/dist/thread-archive-confirm.js
16091
+ var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
15513
16092
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
15514
16093
  var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
15515
16094
 
15516
16095
  // ../../shared-contracts/dist/client-channel.js
15517
16096
  var CLIENT_CHANNEL_VERSION = 1;
15518
16097
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
16098
+ var CLIENT_CHANNEL_METHODS = [
16099
+ "codexhost/skills/list",
16100
+ "codexhost/voice/status",
16101
+ "codexhost/voice/transcribe",
16102
+ "codexhost/harness/display-settings/get",
16103
+ "codexhost/harness/display-settings/set",
16104
+ "codexhost/harness/display-settings/capabilities",
16105
+ "codexhost/harness/preferences/get",
16106
+ "codexhost/harness/preferences/patch",
16107
+ "thread/list",
16108
+ "codexhost/thread/catalog/read",
16109
+ "thread/read",
16110
+ "thread/resume",
16111
+ "thread/fork",
16112
+ "thread/turns/list",
16113
+ "thread/revert",
16114
+ "thread/items/list",
16115
+ "thread/start",
16116
+ "thread/name/set",
16117
+ "codexhost/thread/title/generate",
16118
+ "thread/archive",
16119
+ THREAD_ARCHIVE_CONFIRM_METHOD,
16120
+ "thread/unarchive",
16121
+ "turn/start",
16122
+ "turn/interrupt",
16123
+ "turn/steer",
16124
+ "thread/queue/list",
16125
+ "thread/queue/add",
16126
+ "thread/queue/update",
16127
+ "thread/queue/delete",
16128
+ "thread/queue/reorder",
16129
+ "thread/queue/start",
16130
+ "codexhost/thread/queue/send-now",
16131
+ "codexhost/workspace/read",
16132
+ "codexhost/thread/tree/read",
16133
+ "codexhost/thread/pins/list",
16134
+ "codexhost/thread/pins/set",
16135
+ "codexhost/harness/plugins/list",
16136
+ "codexhost/harness/inspect",
16137
+ "codexhost/thread/inspect",
16138
+ "codexhost/thread/usage/inspect",
16139
+ "codexhost/thread/ownership/list",
16140
+ "codexhost/thread/model/select",
16141
+ "codexhost/thread/thinking/select",
16142
+ "codexhost/thread/permission-mode/select",
16143
+ "codexhost/thread/commands/inspect",
16144
+ "codexhost/harness/commands/inspect",
16145
+ "codexhost/thread/command/execute",
16146
+ "codexhost/thread/fork",
16147
+ "codexhost/harness/session-import/sources",
16148
+ "codexhost/harness/session-import/list",
16149
+ "codexhost/harness/session-import/import",
16150
+ // Host settings shared across Desktop and Web.
16151
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
16152
+ "codexhost/harness/installation",
16153
+ "codexhost/harness/installation/start",
16154
+ "codexhost/harness/installation/status",
16155
+ "codexhost/harness/launch-settings/get",
16156
+ "codexhost/harness/launch-settings/set",
16157
+ "codexhost/harness/web-ui/open",
16158
+ "codexhost/harness/accounts/sources",
16159
+ "codexhost/harness/accounts/list",
16160
+ "codexhost/harness/accounts/inspect",
16161
+ "codexhost/harness/credential-imports",
16162
+ "codexhost/account/list",
16163
+ "codexhost/account/refresh",
16164
+ "codexhost/account/usage/inspect",
16165
+ "codexhost/usage/model-prices/get",
16166
+ "codexhost/usage/model-prices/set",
16167
+ "codexhost/usage/model-prices/default",
16168
+ "codexhost/usage/statistics/get",
16169
+ "codexhost/update/check",
16170
+ "codexhost/update/start",
16171
+ "codexhost/update/status",
16172
+ "codexhost/sessions/loaded/list"
16173
+ ];
15519
16174
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15520
16175
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15521
16176
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -15554,6 +16209,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15554
16209
  cursor: clientChannelCursorSchema,
15555
16210
  revision: external_exports.number().int().nonnegative()
15556
16211
  }),
16212
+ external_exports.object({
16213
+ type: external_exports.literal("extensions-changed"),
16214
+ cursor: clientChannelCursorSchema,
16215
+ revision: hostExtensionRevisionSchema
16216
+ }),
15557
16217
  external_exports.object({
15558
16218
  type: external_exports.literal("hello"),
15559
16219
  version: external_exports.literal(1),
@@ -15729,6 +16389,29 @@ var threadCatalogReadResultSchema = external_exports.object({
15729
16389
  officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15730
16390
  }).strict();
15731
16391
 
16392
+ // ../../shared-contracts/dist/thread-tree-watch.js
16393
+ var THREAD_TREE_MAX_NODES = 5e3;
16394
+ var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
16395
+ var threadTreeNodeSchema = external_exports.strictObject({
16396
+ harnessId: harnessIdSchema,
16397
+ title: external_exports.string().optional(),
16398
+ status: threadTreeStatusSchema,
16399
+ archived: external_exports.boolean()
16400
+ });
16401
+ var threadTreeSnapshotSchema = external_exports.strictObject({
16402
+ revision: external_exports.int().nonnegative(),
16403
+ parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
16404
+ nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
16405
+ truncated: external_exports.boolean()
16406
+ }).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");
16407
+ var subscriptionId = external_exports.string().min(1).max(128);
16408
+ var threadTreeWatchParamsSchema = external_exports.strictObject({});
16409
+ var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
16410
+ var threadTreeUnwatchResultSchema = external_exports.strictObject({});
16411
+ var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
16412
+ snapshot: threadTreeSnapshotSchema
16413
+ });
16414
+
15732
16415
  // ../../shared-contracts/dist/voice.js
15733
16416
  var VOICE_AUDIO_MAX_BYTES = 10 * 1024 * 1024;
15734
16417
  var voiceAudioMimeTypeSchema = external_exports.string().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);
@@ -15967,7 +16650,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
15967
16650
 
15968
16651
  // ../../shared-contracts/dist/harness-preferences.js
15969
16652
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
15970
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
16653
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
15971
16654
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
15972
16655
  model: harnessModelRefSchema.optional(),
15973
16656
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15977,11 +16660,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
15977
16660
  lastHarness: harnessIdSchema.optional(),
15978
16661
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
15979
16662
  });
16663
+ var harnessDelegationDefaultSchema = external_exports.strictObject({
16664
+ model: harnessModelRefSchema.optional(),
16665
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional()
16666
+ }).refine((value) => Boolean(value.model || value.thinkingOptionId), "A delegation default must contain a Model or Thinking option");
16667
+ var delegationDefaultsSchema = external_exports.strictObject({
16668
+ byHarness: external_exports.record(preferenceHarnessKey, harnessDelegationDefaultSchema)
16669
+ });
15980
16670
  var modelId = external_exports.string().min(1).max(1024);
15981
16671
  var harnessPreferenceValuesSchema = external_exports.strictObject({
15982
16672
  idleRelease: idleReleaseSettingsSchema.optional(),
15983
16673
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
15984
- newThread: newThreadDefaultsSchema.optional()
16674
+ newThread: newThreadDefaultsSchema.optional(),
16675
+ delegation: delegationDefaultsSchema.optional()
15985
16676
  });
15986
16677
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
15987
16678
  scope: harnessPreferenceScopeSchema,
@@ -16009,6 +16700,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
16009
16700
  lastHarness: harnessIdSchema.optional(),
16010
16701
  harnessId: harnessIdSchema.optional(),
16011
16702
  configuration: harnessDefaultConfigurationSchema.optional()
16703
+ }),
16704
+ external_exports.strictObject({
16705
+ kind: external_exports.literal("delegation"),
16706
+ harnessId: harnessIdSchema,
16707
+ configuration: harnessDelegationDefaultSchema.nullable()
16012
16708
  })
16013
16709
  ]);
16014
16710
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -16359,13 +17055,6 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
16359
17055
  });
16360
17056
 
16361
17057
  // ../../shared-contracts/dist/harness-accounts.js
16362
- var accountBalanceSnapshotSchema = external_exports.object({
16363
- amount: external_exports.number().finite().nonnegative(),
16364
- /** ISO 4217 code as reported by the Provider, for example `CNY`. */
16365
- currency: external_exports.string().trim().min(1).max(8),
16366
- /** Native label when the Harness exposes several Billing Sources. */
16367
- label: external_exports.string().trim().min(1).max(128).optional()
16368
- }).strict();
16369
17058
  var harnessAccountSnapshotObject = external_exports.object({
16370
17059
  email: external_exports.string().trim().min(1).max(320).optional(),
16371
17060
  label: external_exports.string().trim().min(1).max(256).optional(),
@@ -16399,76 +17088,6 @@ var harnessAccountListResultSchema = external_exports.object({
16399
17088
  accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
16400
17089
  }).strict();
16401
17090
 
16402
- // ../../shared-contracts/dist/harness-plugins.js
16403
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
16404
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
16405
- var HARNESS_PLUGIN_LIMIT = 128;
16406
- var installedHarnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(harnessIdSchema);
16407
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
16408
- 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");
16409
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
16410
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
16411
- var harnessInstallationGuideSchema = external_exports.object({
16412
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
16413
- before: localizedTextSchema.optional(),
16414
- after: localizedTextSchema.optional(),
16415
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
16416
- }).strict();
16417
- var pluginPresentationShape = {
16418
- id: installedHarnessPluginIdSchema,
16419
- name: external_exports.string().trim().min(1).max(128),
16420
- version: external_exports.string().min(1).max(128),
16421
- /** Capability-only plugin; omitted for existing session-capable plugins. */
16422
- kind: external_exports.literal("usage").optional(),
16423
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
16424
- iconStyle: external_exports.object({
16425
- vector: external_exports.object({
16426
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
16427
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
16428
- paths: external_exports.array(external_exports.object({
16429
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
16430
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
16431
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
16432
- }).strict()).min(1).max(32)
16433
- }).strict().optional(),
16434
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
16435
- borderRadius: external_exports.number().min(0).max(50).optional(),
16436
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
16437
- }).strict().optional(),
16438
- installation: harnessInstallationGuideSchema.optional(),
16439
- notice: localizedTextSchema.optional(),
16440
- /** The factory accepts a persisted local entrypoint through its construction context. */
16441
- launchCommand: external_exports.literal(true).optional(),
16442
- links: external_exports.object({
16443
- website: documentationUrlSchema.optional(),
16444
- documentation: documentationUrlSchema.optional(),
16445
- installation: documentationUrlSchema.optional()
16446
- }).strict().optional()
16447
- };
16448
- var harnessPluginManifestSchema = external_exports.object({
16449
- manifestVersion: external_exports.literal(1),
16450
- ...pluginPresentationShape,
16451
- adapterApiVersion: external_exports.number().int().positive(),
16452
- entry: relativeResourceSchema,
16453
- icon: relativeResourceSchema.optional()
16454
- }).strict();
16455
- 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);
16456
- var harnessPluginDescriptorSchema = external_exports.object({
16457
- ...pluginPresentationShape,
16458
- icon: harnessPluginIconSchema.optional()
16459
- }).strict();
16460
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
16461
- var harnessPluginListResultSchema = external_exports.object({
16462
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
16463
- }).strict();
16464
- var harnessPluginConfigurationSchema = external_exports.object({
16465
- version: external_exports.literal(1),
16466
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
16467
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
16468
- message: "Enabled plugin IDs must be unique",
16469
- path: ["enabled"]
16470
- });
16471
-
16472
17091
  // ../../shared-contracts/dist/harness-route.js
16473
17092
  var harnessPluginRouteSchema = external_exports.object({
16474
17093
  harnessId: harnessPluginIdSchema,
@@ -16909,9 +17528,12 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16909
17528
  ...thread,
16910
17529
  epoch: identity,
16911
17530
  modelId: identity.optional(),
17531
+ serviceTier: harnessModelServiceTierSchema.optional(),
16912
17532
  thinkingOptionId: identity.optional(),
16913
17533
  permissionModeId: identity.optional()
16914
- }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17534
+ }).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, {
17535
+ message: "A service tier requires a Model ID"
17536
+ }),
16915
17537
  external_exports.strictObject({
16916
17538
  kind: external_exports.literal("prompt"),
16917
17539
  ...thread,
@@ -16961,7 +17583,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
16961
17583
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
16962
17584
  external_exports.strictObject({
16963
17585
  action: external_exports.literal("read-thread"),
16964
- hostId: hostId.refine((id) => id !== "local"),
17586
+ hostId: hostId.refine((id2) => id2 !== "local"),
16965
17587
  input: delegationReadParamsSchema
16966
17588
  }),
16967
17589
  external_exports.strictObject({
@@ -16975,7 +17597,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
16975
17597
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
16976
17598
  external_exports.strictObject({
16977
17599
  action: external_exports.literal("update"),
16978
- hostId: hostId.refine((id) => id !== "local"),
17600
+ hostId: hostId.refine((id2) => id2 !== "local"),
16979
17601
  version: remoteUpdateParamsSchema.shape.version
16980
17602
  })
16981
17603
  ]);
@@ -17039,7 +17661,7 @@ function invalidRequest(message3) {
17039
17661
  return { code: "invalidRequest", message: message3, retryable: false };
17040
17662
  }
17041
17663
  function validateHostQuestionResponse(interaction, response) {
17042
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17664
+ const questionIds = new Set(interaction.questions.map(({ id: id2 }) => id2));
17043
17665
  if (response.cancelled) {
17044
17666
  return Object.keys(response.answers).length === 0 ? null : invalidRequest("Cancelled Question Response must not contain answers");
17045
17667
  }
@@ -17070,6 +17692,21 @@ function validateHostQuestionResponse(interaction, response) {
17070
17692
  return null;
17071
17693
  }
17072
17694
 
17695
+ // ../../harness-adapter/dist/composite-model-ref.js
17696
+ function compositeModelRefIds(entries, fallbackId) {
17697
+ const counts = /* @__PURE__ */ new Map();
17698
+ for (const entry of entries) {
17699
+ const id2 = `${entry.provider}/${entry.model}`;
17700
+ counts.set(id2, (counts.get(id2) ?? 0) + 1);
17701
+ }
17702
+ const ids = /* @__PURE__ */ new Map();
17703
+ for (const entry of entries) {
17704
+ const id2 = `${entry.provider}/${entry.model}`;
17705
+ ids.set(counts.get(id2) === 1 ? id2 : fallbackId(entry), entry);
17706
+ }
17707
+ return ids;
17708
+ }
17709
+
17073
17710
  // ../../harness-adapter/dist/output-channel.js
17074
17711
  var HarnessOutputChannel = class {
17075
17712
  outputs;
@@ -17142,7 +17779,8 @@ var tokenFields = [
17142
17779
  var safeIntegerFields = [
17143
17780
  "planFiveHourResetsAtUnix",
17144
17781
  "planSevenDayResetsAtUnix",
17145
- "timeToFirstOutputMs"
17782
+ "timeToFirstOutputMs",
17783
+ "latestRequestTimeToFirstOutputMs"
17146
17784
  ];
17147
17785
  var percentFields = [
17148
17786
  "cacheHitRatePercent",
@@ -17405,7 +18043,7 @@ function isExcludedLiveCommand(name, extra = {}) {
17405
18043
  function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17406
18044
  if (!commandId.startsWith(idPrefix))
17407
18045
  return null;
17408
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
18046
+ const descriptor = catalog.commands.find(({ id: id2 }) => id2 === commandId);
17409
18047
  if (!descriptor)
17410
18048
  return null;
17411
18049
  const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
@@ -17415,7 +18053,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17415
18053
  if (!live)
17416
18054
  return builtIns;
17417
18055
  const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17418
- const ids = new Set(builtIns.commands.map(({ id }) => id));
18056
+ const ids = new Set(builtIns.commands.map(({ id: id2 }) => id2));
17419
18057
  const dynamic = [];
17420
18058
  for (const command of live) {
17421
18059
  const name = command.name.trim().replace(/^\//u, "");
@@ -17424,12 +18062,12 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17424
18062
  if (isExcludedLiveCommand(name, exclusions))
17425
18063
  continue;
17426
18064
  const invocation = `/${name}`;
17427
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17428
- if (invocations.has(invocation) || ids.has(id))
18065
+ const id2 = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18066
+ if (invocations.has(invocation) || ids.has(id2))
17429
18067
  continue;
17430
18068
  const description = command.description?.trim().slice(0, 512);
17431
18069
  const parsed = harnessCommandDescriptorSchema.safeParse({
17432
- id,
18070
+ id: id2,
17433
18071
  invocation,
17434
18072
  label: name.slice(0, 128),
17435
18073
  ...description ? { description } : {},
@@ -17438,7 +18076,7 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17438
18076
  if (!parsed.success)
17439
18077
  continue;
17440
18078
  invocations.add(invocation);
17441
- ids.add(id);
18079
+ ids.add(id2);
17442
18080
  dynamic.push(parsed.data);
17443
18081
  }
17444
18082
  return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
@@ -17925,8 +18563,8 @@ var PiSessionImportIndex = class {
17925
18563
  try {
17926
18564
  const fingerprint = await stat(file2);
17927
18565
  const cached2 = this.#cache.get(file2);
17928
- const id = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source.nativeRef.nativeSessionId : await readIdentity(file2, signal);
17929
- if (id !== nativeSessionId)
18566
+ const id2 = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source.nativeRef.nativeSessionId : await readIdentity(file2, signal);
18567
+ if (id2 !== nativeSessionId)
17930
18568
  continue;
17931
18569
  if (selected)
17932
18570
  throw new Error("Pi Session identity is ambiguous across files");
@@ -18587,10 +19225,10 @@ function fileChangeFromPatch(patch, cwd) {
18587
19225
  return [{ path: displayed.path, kind, unifiedDiff: patch }];
18588
19226
  }
18589
19227
  function synthesizeFileChange(kind, args, cwd) {
18590
- const filePath = nestedToolString(args, ["path", "file_path", "filePath", "file"]);
18591
- if (!filePath)
19228
+ const filePath2 = nestedToolString(args, ["path", "file_path", "filePath", "file"]);
19229
+ if (!filePath2)
18592
19230
  return null;
18593
- const displayed = displayPath(filePath, cwd);
19231
+ const displayed = displayPath(filePath2, cwd);
18594
19232
  if (!displayed)
18595
19233
  return null;
18596
19234
  if (kind === "write") {
@@ -18663,8 +19301,8 @@ function argumentFileChange(kind, args, cwd) {
18663
19301
  function hostDerivesFileChange(kind, args, cwd) {
18664
19302
  if (kind === "edit" && isRecord3(args) && args.edits !== void 0)
18665
19303
  return false;
18666
- const filePath = nestedToolString(args, ["path", "file_path", "filePath", "file"]);
18667
- return filePath !== void 0 && piToolPath(filePath) === filePath && synthesizeFileChange(kind, args, cwd) !== null;
19304
+ const filePath2 = nestedToolString(args, ["path", "file_path", "filePath", "file"]);
19305
+ return filePath2 !== void 0 && piToolPath(filePath2) === filePath2 && synthesizeFileChange(kind, args, cwd) !== null;
18668
19306
  }
18669
19307
  function piToolFileChanges(toolName, args, result, cwd) {
18670
19308
  const kind = fileMutatingKind(toolName);
@@ -18845,16 +19483,16 @@ function isRecord4(value) {
18845
19483
  function text(value, limit = 2048) {
18846
19484
  return typeof value === "string" && value.length > 0 && value.length <= limit;
18847
19485
  }
18848
- function gotgenesId(id) {
18849
- return PREFIX + Buffer.from(id).toString("base64url");
19486
+ function gotgenesId(id2) {
19487
+ return PREFIX + Buffer.from(id2).toString("base64url");
18850
19488
  }
18851
19489
  function parseGotgenesId(value) {
18852
19490
  if (!value.startsWith(PREFIX))
18853
19491
  return null;
18854
- const id = Buffer.from(value.slice(PREFIX.length), "base64url").toString("utf8");
18855
- if (!text(id, 256) || /[\s/\\]/u.test(id) || gotgenesId(id) !== value)
19492
+ const id2 = Buffer.from(value.slice(PREFIX.length), "base64url").toString("utf8");
19493
+ if (!text(id2, 256) || /[\s/\\]/u.test(id2) || gotgenesId(id2) !== value)
18856
19494
  throw new Error("Invalid gotgenes subagent identity");
18857
- return id;
19495
+ return id2;
18858
19496
  }
18859
19497
  function gotgenesRecord(value) {
18860
19498
  if (!isRecord4(value) || !text(value.id, 256) || /[\s/\\]/u.test(value.id) || !text(value.type) || !text(value.description) || typeof value.status !== "string" || !Object.hasOwn(STATUSES, value.status))
@@ -18862,7 +19500,7 @@ function gotgenesRecord(value) {
18862
19500
  const status = STATUSES[value.status];
18863
19501
  if (!status)
18864
19502
  return null;
18865
- const id = gotgenesId(value.id);
19503
+ const id2 = gotgenesId(value.id);
18866
19504
  const progress = typeof value.toolUses === "number" ? `${value.toolUses} tool uses` : void 0;
18867
19505
  const result = typeof value.error === "string" ? value.error : typeof value.result === "string" ? value.result : progress;
18868
19506
  return {
@@ -18870,8 +19508,8 @@ function gotgenesRecord(value) {
18870
19508
  roleKnown: value.roleKnown !== false,
18871
19509
  backgroundKnown: typeof value.isBackground === "boolean",
18872
19510
  child: {
18873
- subagentId: id,
18874
- nativeSubagentId: id,
19511
+ subagentId: id2,
19512
+ nativeSubagentId: id2,
18875
19513
  description: value.description,
18876
19514
  role: value.type,
18877
19515
  status,
@@ -18968,13 +19606,13 @@ var GotgenesSubagents = class {
18968
19606
  }
18969
19607
  if (!publish || JSON.stringify(previous) === JSON.stringify(merged))
18970
19608
  continue;
18971
- const active = this.#active.get(record10.id);
18972
- if (active) {
18973
- active.item = { ...active.item, subagents: [merged.child] };
19609
+ const active2 = this.#active.get(record10.id);
19610
+ if (active2) {
19611
+ active2.item = { ...active2.item, subagents: [merged.child] };
18974
19612
  this.emit({
18975
19613
  type: "item.updated",
18976
- turnId: active.turnId,
18977
- itemId: active.item.itemId,
19614
+ turnId: active2.turnId,
19615
+ itemId: active2.item.itemId,
18978
19616
  update: { type: "subagents.replace", subagents: [merged.child] }
18979
19617
  });
18980
19618
  }
@@ -19018,14 +19656,14 @@ var GotgenesSubagents = class {
19018
19656
  return true;
19019
19657
  }
19020
19658
  finish(turnId) {
19021
- for (const [id, active] of this.#active) {
19022
- if (active.turnId !== turnId)
19659
+ for (const [id2, active2] of this.#active) {
19660
+ if (active2.turnId !== turnId)
19023
19661
  continue;
19024
- this.#active.delete(id);
19662
+ this.#active.delete(id2);
19025
19663
  this.emit({
19026
19664
  type: "item.completed",
19027
19665
  turnId,
19028
- snapshot: { item: active.item, outcome: { status: "succeeded" } }
19666
+ snapshot: { item: active2.item, outcome: { status: "succeeded" } }
19029
19667
  });
19030
19668
  }
19031
19669
  }
@@ -19088,16 +19726,16 @@ function piWorkflowSummary(result) {
19088
19726
  function piWorkflowSubagentId(address) {
19089
19727
  return PREFIX2 + Buffer.from(JSON.stringify([address.workflowRunId, address.childId])).toString("base64url");
19090
19728
  }
19091
- function parsePiWorkflowSubagentId(id) {
19092
- if (!id.startsWith(PREFIX2))
19729
+ function parsePiWorkflowSubagentId(id2) {
19730
+ if (!id2.startsWith(PREFIX2))
19093
19731
  return null;
19094
- if (id.length > 3e3)
19732
+ if (id2.length > 3e3)
19095
19733
  throw new Error("Invalid Pi workflow child identity");
19096
- const value = JSON.parse(Buffer.from(id.slice(PREFIX2.length), "base64url").toString("utf8"));
19734
+ const value = JSON.parse(Buffer.from(id2.slice(PREFIX2.length), "base64url").toString("utf8"));
19097
19735
  if (!Array.isArray(value) || value.length !== 2 || !text2(value[0]) || !text2(value[1]))
19098
19736
  throw new Error("Invalid Pi workflow child identity");
19099
19737
  const address = { workflowRunId: value[0], childId: value[1] };
19100
- if (piWorkflowSubagentId(address) !== id)
19738
+ if (piWorkflowSubagentId(address) !== id2)
19101
19739
  throw new Error("Non-canonical Pi workflow child identity");
19102
19740
  return address;
19103
19741
  }
@@ -19109,13 +19747,13 @@ function projectPiWorkflow(summary, itemId2) {
19109
19747
  itemId: itemId2,
19110
19748
  operation: "spawn",
19111
19749
  subagents: summary.children.map((child) => {
19112
- const id = piWorkflowSubagentId({
19750
+ const id2 = piWorkflowSubagentId({
19113
19751
  workflowRunId: summary.workflowRunId,
19114
19752
  childId: child.childId
19115
19753
  });
19116
19754
  return {
19117
- subagentId: id,
19118
- nativeSubagentId: id,
19755
+ subagentId: id2,
19756
+ nativeSubagentId: id2,
19119
19757
  description: child.sessionName ?? child.agent ?? child.childId,
19120
19758
  status: child.state,
19121
19759
  background: child.background,
@@ -19201,14 +19839,14 @@ function parsePiSubagentStatus(value) {
19201
19839
  function piSubagentId(address) {
19202
19840
  return ID_PREFIX + Buffer.from(JSON.stringify([address.runId, address.childId ?? null])).toString("base64url");
19203
19841
  }
19204
- function parsePiSubagentId(id) {
19205
- if (!id.startsWith(ID_PREFIX) || id.length > 1500)
19842
+ function parsePiSubagentId(id2) {
19843
+ if (!id2.startsWith(ID_PREFIX) || id2.length > 1500)
19206
19844
  throw new Error("Invalid Pi Subagent identity");
19207
- const value = JSON.parse(Buffer.from(id.slice(ID_PREFIX.length), "base64url").toString("utf8"));
19845
+ const value = JSON.parse(Buffer.from(id2.slice(ID_PREFIX.length), "base64url").toString("utf8"));
19208
19846
  if (!Array.isArray(value) || value.length !== 2 || !token(value[0]) || value[1] !== null && !token(value[1]))
19209
19847
  throw new Error("Invalid Pi Subagent identity");
19210
19848
  const address = { runId: value[0], ...value[1] === null ? {} : { childId: value[1] } };
19211
- if (piSubagentId(address) !== id)
19849
+ if (piSubagentId(address) !== id2)
19212
19850
  throw new Error("Non-canonical Pi Subagent identity");
19213
19851
  return address;
19214
19852
  }
@@ -19219,12 +19857,12 @@ function states(run) {
19219
19857
  if (entry.kind === "host-step" || !root && entry.kind === "workflow")
19220
19858
  return;
19221
19859
  if (entry.kind !== "workflow") {
19222
- const id = piSubagentId({ runId: run.id, ...!root ? { childId: entry.id } : {} });
19223
- if (!seen.has(id)) {
19224
- seen.add(id);
19860
+ const id2 = piSubagentId({ runId: run.id, ...!root ? { childId: entry.id } : {} });
19861
+ if (!seen.has(id2)) {
19862
+ seen.add(id2);
19225
19863
  result.push({
19226
- subagentId: id,
19227
- nativeSubagentId: id,
19864
+ subagentId: id2,
19865
+ nativeSubagentId: id2,
19228
19866
  description: entry.label,
19229
19867
  ...subagentConfiguration(entry),
19230
19868
  background: true,
@@ -19290,17 +19928,17 @@ var PiSubagents = class {
19290
19928
  this.#active.set(run.id, { turnId: waiting.turnId, item });
19291
19929
  this.emit({ type: "item.started", turnId: waiting.turnId, item });
19292
19930
  }
19293
- const active = this.#active.get(run.id);
19294
- if (active && children.length) {
19295
- const merged = new Map(active.item.subagents.map((child) => [child.nativeSubagentId, child]));
19931
+ const active2 = this.#active.get(run.id);
19932
+ if (active2 && children.length) {
19933
+ const merged = new Map(active2.item.subagents.map((child) => [child.nativeSubagentId, child]));
19296
19934
  for (const child of children)
19297
19935
  merged.set(child.nativeSubagentId, child);
19298
- active.item = { ...active.item, subagents: [...merged.values()] };
19936
+ active2.item = { ...active2.item, subagents: [...merged.values()] };
19299
19937
  this.emit({
19300
19938
  type: "item.updated",
19301
- turnId: active.turnId,
19302
- itemId: active.item.itemId,
19303
- update: { type: "subagents.replace", subagents: active.item.subagents }
19939
+ turnId: active2.turnId,
19940
+ itemId: active2.item.itemId,
19941
+ update: { type: "subagents.replace", subagents: active2.item.subagents }
19304
19942
  });
19305
19943
  }
19306
19944
  for (const child of observed) {
@@ -19379,14 +20017,14 @@ var PiSubagents = class {
19379
20017
  if (waiting.turnId === turnId)
19380
20018
  this.#waiting.delete(runId);
19381
20019
  }
19382
- for (const [runId, active] of this.#active) {
19383
- if (active.turnId !== turnId)
20020
+ for (const [runId, active2] of this.#active) {
20021
+ if (active2.turnId !== turnId)
19384
20022
  continue;
19385
20023
  this.#active.delete(runId);
19386
20024
  this.emit({
19387
20025
  type: "item.completed",
19388
20026
  turnId,
19389
- snapshot: { item: active.item, outcome: { status: "succeeded" } }
20027
+ snapshot: { item: active2.item, outcome: { status: "succeeded" } }
19390
20028
  });
19391
20029
  }
19392
20030
  }
@@ -19407,7 +20045,7 @@ function parsePiSubagentInspection(value) {
19407
20045
  return null;
19408
20046
  return parsed;
19409
20047
  }
19410
- function piSubagentSnapshot(parentSessionId, id, reply) {
20048
+ function piSubagentSnapshot(parentSessionId, id2, reply) {
19411
20049
  const messages = reply.messages ?? [];
19412
20050
  const texts = messages.map((entry) => entry.kind === "text" && entry.role === "assistant" ? entry.text : `[${entry.role}${entry.name ? `: ${entry.name}` : ""} / ${entry.kind}]
19413
20051
  ${entry.text}`);
@@ -19422,7 +20060,7 @@ ${entry.text}`);
19422
20060
  nativeTurnRef: nativeTurnRefSchema.parse({
19423
20061
  harnessId: "pi",
19424
20062
  nativeSessionId: parentSessionId,
19425
- nativeTurnKey: `pi-subagent-${createHash3("sha256").update(id).digest("hex")}`,
20063
+ nativeTurnKey: `pi-subagent-${createHash3("sha256").update(id2).digest("hex")}`,
19426
20064
  formatVersion: 1
19427
20065
  }),
19428
20066
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
@@ -19430,7 +20068,7 @@ ${entry.text}`);
19430
20068
  item: {
19431
20069
  type: "agentMessage",
19432
20070
  text: text4,
19433
- itemId: hostItemIdSchema.parse(`pi-subagent-${createHash3("sha256").update(`${id}:${index}:${text4}`).digest("hex")}`)
20071
+ itemId: hostItemIdSchema.parse(`pi-subagent-${createHash3("sha256").update(`${id2}:${index}:${text4}`).digest("hex")}`)
19434
20072
  },
19435
20073
  outcome: { status: "succeeded" }
19436
20074
  })),
@@ -19450,6 +20088,85 @@ ${entry.text}`);
19450
20088
  };
19451
20089
  }
19452
20090
 
20091
+ // dist/pi-fast-mode.js
20092
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
20093
+ import { mkdir as mkdir2, readFile as readFile2, rename as rename2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
20094
+ import { homedir as homedir3 } from "node:os";
20095
+ import path8 from "node:path";
20096
+ var PI_FAST_COMMAND = "codexhost-fast-mode";
20097
+ var PI_FAST_ACK = "codexhost-fast-mode:";
20098
+ var PI_FAST_EXTENSION = `export default function(pi) {
20099
+ let target;
20100
+ const wrapped = new Set();
20101
+ const supportsModel = (model) => model && (model.api === "openai-codex-responses" || model.api === "openai-responses") && /gpt/i.test(model.id);
20102
+ pi.on("model_select", (_event, ctx) => {
20103
+ if (target && (target.provider !== ctx.model?.provider || target.id !== ctx.model?.id || !supportsModel(ctx.model))) target = undefined;
20104
+ });
20105
+ pi.on("session_start", (_event, ctx) => {
20106
+ if (typeof ctx.modelRegistry.getProvider !== "function" || typeof pi.registerProvider !== "function") return;
20107
+ pi.registerCommand("${PI_FAST_COMMAND}", {
20108
+ description: "Codex Host Fast mode",
20109
+ handler: async (args, ctx) => {
20110
+ const [mode, nonce] = args.split(" ");
20111
+ if (!nonce || (mode !== "on" && mode !== "off")) throw new Error("Invalid Fast selection");
20112
+ if (mode === "on") {
20113
+ const model = ctx.model;
20114
+ if (!supportsModel(model)) throw new Error("Fast requires a GPT model using the Codex or OpenAI Responses API");
20115
+ const original = ctx.modelRegistry.getProvider(model.provider);
20116
+ if (!original) throw new Error("Provider is unavailable");
20117
+ if (!wrapped.has(model.provider)) {
20118
+ const options = (model, value) => target && supportsModel(model) && target.provider === model.provider && target.id === model.id
20119
+ ? {
20120
+ ...value,
20121
+ serviceTier: "priority",
20122
+ // Pi streamSimple drops serviceTier but preserves onPayload.
20123
+ onPayload: async (payload, requestModel) => {
20124
+ const request = { ...payload, service_tier: "priority" };
20125
+ const replacement = await value?.onPayload?.(request, requestModel);
20126
+ return { ...(replacement === undefined ? request : replacement), service_tier: "priority" };
20127
+ },
20128
+ } : value;
20129
+ pi.registerProvider({
20130
+ ...original,
20131
+ stream: (model, context, value) => original.stream(model, context, options(model, value)),
20132
+ streamSimple: (model, context, value) => original.streamSimple(model, context, options(model, value)),
20133
+ });
20134
+ wrapped.add(model.provider);
20135
+ }
20136
+ target = { provider: model.provider, id: model.id };
20137
+ } else target = undefined;
20138
+ ctx.ui.notify("${PI_FAST_ACK}" + nonce + ":" + mode, "info");
20139
+ },
20140
+ });
20141
+ });
20142
+ }
20143
+ `;
20144
+ async function ensurePiFastExtension(environment) {
20145
+ const digest = createHash4("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
20146
+ const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path8.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".codexhost");
20147
+ const directory = path8.resolve(dataDirectory, "extensions", "pi-codex-fast");
20148
+ const file2 = path8.join(directory, `${digest}.mjs`);
20149
+ if (await readFile2(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
20150
+ return file2;
20151
+ await mkdir2(directory, { recursive: true });
20152
+ const temporary = `${file2}.${randomUUID2()}.tmp`;
20153
+ try {
20154
+ await writeFile3(temporary, PI_FAST_EXTENSION, { mode: 384 });
20155
+ try {
20156
+ await rename2(temporary, file2);
20157
+ } catch (error51) {
20158
+ if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
20159
+ throw error51;
20160
+ }
20161
+ } finally {
20162
+ await rm3(temporary, { force: true });
20163
+ }
20164
+ return file2;
20165
+ }
20166
+ function supportsPiFastModel(model2) {
20167
+ return (model2.api === "openai-codex-responses" || model2.api === "openai-responses") && /gpt/i.test(model2.id);
20168
+ }
20169
+
19453
20170
  // dist/pi-model-catalog.js
19454
20171
  var PI_MODEL_REF_PREFIX = "pi-model-v1.";
19455
20172
  var PI_DRAFT_THINKING_OPTION_IDS = [
@@ -19460,7 +20177,7 @@ var PI_DRAFT_THINKING_OPTION_IDS = [
19460
20177
  "high",
19461
20178
  "xhigh",
19462
20179
  "max"
19463
- ].map((id) => harnessThinkingOptionIdSchema.parse(id));
20180
+ ].map((id2) => harnessThinkingOptionIdSchema.parse(id2));
19464
20181
  var PI_THINKING_LABELS = {
19465
20182
  off: "Off",
19466
20183
  minimal: "Minimal",
@@ -19477,79 +20194,110 @@ function assertNativePart(value, name) {
19477
20194
  if (value.trim().length === 0)
19478
20195
  throw new Error(`Pi ${name} must not be empty`);
19479
20196
  }
19480
- function encodePiModelRef(model2) {
20197
+ function readableId({ provider, id: id2 }) {
20198
+ return `${provider}/${id2}`;
20199
+ }
20200
+ function modelLabel({ provider, id: id2 }) {
20201
+ return `${provider} / ${id2}`;
20202
+ }
20203
+ function encodedId({ provider, id: id2 }, legacyFast = false) {
20204
+ const tuple2 = legacyFast ? [provider, id2, true] : [provider, id2];
20205
+ return `${PI_MODEL_REF_PREFIX}${Buffer.from(JSON.stringify(tuple2)).toString("base64url")}`;
20206
+ }
20207
+ function encodePiModelRef(model2, id2 = readableId(model2)) {
19481
20208
  assertNativePart(model2.provider, "Model provider");
19482
20209
  assertNativePart(model2.id, "Model id");
19483
- const encoded = Buffer.from(JSON.stringify(model2.fast ? [model2.provider, model2.id, true] : [model2.provider, model2.id]), "utf8").toString("base64url");
19484
- return harnessModelRefSchema.parse({ id: `${PI_MODEL_REF_PREFIX}${encoded}` });
20210
+ return harnessModelRefSchema.parse({
20211
+ id: id2,
20212
+ ...model2.fast ? { serviceTier: "priority" } : {}
20213
+ });
20214
+ }
20215
+ function createPiModelIndex(models) {
20216
+ const entries = new Map(models.map(({ provider, id: id2 }) => [JSON.stringify([provider, id2]), { provider, model: id2, id: id2 }]));
20217
+ const byId = compositeModelRefIds([...entries.values()], (entry) => encodedId(entry));
20218
+ const idsByPair = new Map([...byId].map(([id2, entry]) => [JSON.stringify([entry.provider, entry.model]), id2]));
20219
+ return {
20220
+ models,
20221
+ byId,
20222
+ ref: (model2) => {
20223
+ const id2 = idsByPair.get(JSON.stringify([model2.provider, model2.id]));
20224
+ return encodePiModelRef(model2, id2 ?? (byId.has(readableId(model2)) ? encodedId(model2) : readableId(model2)));
20225
+ }
20226
+ };
19485
20227
  }
19486
- function decodePiModelRef(ref) {
19487
- const parsedRef = harnessModelRefSchema.parse(ref);
19488
- if (!parsedRef.id.startsWith(PI_MODEL_REF_PREFIX)) {
19489
- throw new Error("Model Ref does not belong to PiAdapter");
20228
+ function resolvePiModelRef(ref, index) {
20229
+ const model2 = index.byId.get(ref.id);
20230
+ if (!model2 || ref.serviceTier === "ultrafast") {
20231
+ throw new Error("Model Ref is not in the current Pi Model catalog");
19490
20232
  }
19491
- const encoded = parsedRef.id.slice(PI_MODEL_REF_PREFIX.length);
19492
- let decoded;
20233
+ return { provider: model2.provider, id: model2.id, ...ref.serviceTier ? { fast: true } : {} };
20234
+ }
20235
+ function normalizeStoredPiModelRef(ref, catalog) {
20236
+ if (!ref.id.startsWith(PI_MODEL_REF_PREFIX) || ref.serviceTier === "ultrafast")
20237
+ return void 0;
20238
+ let tuple2;
19493
20239
  try {
19494
- decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
20240
+ tuple2 = JSON.parse(Buffer.from(ref.id.slice(PI_MODEL_REF_PREFIX.length), "base64url").toString("utf8"));
19495
20241
  } catch {
19496
- throw new Error("Pi Model Ref is malformed");
19497
- }
19498
- if (!Array.isArray(decoded) || decoded.length !== 2 && !(decoded.length === 3 && decoded[2] === true) || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
19499
- throw new Error("Pi Model Ref has an invalid native identity");
19500
- }
19501
- const native = {
19502
- provider: decoded[0],
19503
- id: decoded[1],
19504
- ...decoded[2] === true ? { fast: true } : {}
19505
- };
19506
- assertNativePart(native.provider, "Model provider");
19507
- assertNativePart(native.id, "Model id");
19508
- if (encodePiModelRef(native).id !== parsedRef.id) {
19509
- throw new Error("Pi Model Ref is not canonical");
20242
+ return void 0;
19510
20243
  }
19511
- return native;
20244
+ if (!Array.isArray(tuple2) || tuple2.length !== 2 && !(tuple2.length === 3 && tuple2[2] === true) || typeof tuple2[0] !== "string" || typeof tuple2[1] !== "string")
20245
+ return void 0;
20246
+ const native = { provider: tuple2[0], id: tuple2[1] };
20247
+ const legacyFast = tuple2[2] === true;
20248
+ if (encodedId(native, legacyFast) !== ref.id || legacyFast && ref.serviceTier)
20249
+ return void 0;
20250
+ const fast = legacyFast || ref.serviceTier === "priority";
20251
+ const encoded = encodedId(native);
20252
+ const readable = readableId(native);
20253
+ const entry = catalog.models.find(({ ref: ref2, label }) => ref2.id === encoded || ref2.id === readable && label === modelLabel(native));
20254
+ return fast ? entry?.fastModel : entry?.ref;
19512
20255
  }
19513
20256
  function samePiModel(left, right) {
19514
20257
  return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
19515
20258
  }
19516
- function fallbackThinkingLabel(id) {
19517
- const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
19518
- return label || id;
20259
+ function fallbackThinkingLabel(id2) {
20260
+ const label = id2.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
20261
+ return label || id2;
19519
20262
  }
19520
20263
  function normalizePiThinkingOptions(levels) {
19521
- return levels.map((id) => harnessThinkingOptionSchema.parse({
19522
- id,
19523
- label: PI_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
20264
+ return levels.map((id2) => harnessThinkingOptionSchema.parse({
20265
+ id: id2,
20266
+ label: PI_THINKING_LABELS[id2] ?? fallbackThinkingLabel(id2)
19524
20267
  }));
19525
20268
  }
19526
- function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId, effectiveModelReasoning = null) {
20269
+ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId, effectiveModelReasoning = null, fastSupported = false) {
20270
+ const index = createPiModelIndex(effectiveModel ? [...nativeModels, effectiveModel] : nativeModels);
19527
20271
  const byRef = /* @__PURE__ */ new Map();
19528
20272
  for (const native of nativeModels) {
19529
- const ref = encodePiModelRef(native);
20273
+ const ref = index.ref(native);
20274
+ const fastModel = fastSupported && supportsPiFastModel(native) ? { id: ref.id, serviceTier: "priority" } : void 0;
19530
20275
  const existing = byRef.get(ref.id);
19531
20276
  if (existing) {
19532
20277
  if (existing.reasoning !== native.reasoning) {
19533
20278
  throw new Error("Pi duplicate Model entries disagree on reasoning capability");
19534
20279
  }
20280
+ if (fastModel)
20281
+ existing.model.fastModel = fastModel;
19535
20282
  continue;
19536
20283
  }
19537
20284
  byRef.set(ref.id, {
19538
20285
  model: {
19539
20286
  ref,
19540
- label: `${native.provider} / ${native.id}`
20287
+ label: modelLabel(native),
20288
+ ...fastModel ? { fastModel } : {}
19541
20289
  },
19542
20290
  reasoning: native.reasoning,
19543
20291
  synthesized: false
19544
20292
  });
19545
20293
  }
19546
- const defaultModel = effectiveModel ? encodePiModelRef(effectiveModel) : void 0;
20294
+ const defaultModel = effectiveModel ? index.ref(effectiveModel) : void 0;
19547
20295
  if (effectiveModel && defaultModel && !byRef.has(defaultModel.id)) {
19548
20296
  const reasoning = effectiveThinkingOptionId && effectiveThinkingOptionId !== "off" || (effectiveModelReasoning ?? Boolean(thinkingLevels && thinkingLevels.some((level) => level !== "off")));
19549
20297
  byRef.set(defaultModel.id, {
19550
20298
  model: {
19551
20299
  ref: defaultModel,
19552
- label: `${effectiveModel.provider} / ${effectiveModel.id}`
20300
+ label: modelLabel(effectiveModel)
19553
20301
  },
19554
20302
  reasoning,
19555
20303
  synthesized: true
@@ -19562,14 +20310,14 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
19562
20310
  throw new Error("Pi did not report an effective Thinking option");
19563
20311
  }
19564
20312
  const thinkingOptions = thinkingLevels ? normalizePiThinkingOptions(PI_DRAFT_THINKING_OPTION_IDS) : [];
19565
- const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
19566
- const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
19567
- const effectiveThinkingOptionIds = thinkingLevels ? allThinkingOptionIds.filter((id) => thinkingLevels.includes(id)) : allThinkingOptionIds;
20313
+ const allThinkingOptionIds = thinkingOptions.map(({ id: id2 }) => id2);
20314
+ const offThinkingOptionId = thinkingOptions.find(({ id: id2 }) => id2 === "off")?.id;
20315
+ const effectiveThinkingOptionIds = thinkingLevels ? allThinkingOptionIds.filter((id2) => thinkingLevels.includes(id2)) : allThinkingOptionIds;
19568
20316
  const models = [...byRef.values()].map(({ model: model2, reasoning, synthesized }) => ({
19569
20317
  ...model2,
19570
20318
  supportedThinkingOptionIds: reasoning ? synthesized ? effectiveThinkingOptionIds : allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
19571
20319
  })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
19572
- const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
20320
+ const defaultThinkingOptionId = thinkingOptions.find(({ id: id2 }) => id2 === effectiveThinkingOptionId)?.id;
19573
20321
  return harnessModelCatalogSchema.parse({
19574
20322
  models,
19575
20323
  ...defaultModel ? { defaultModel } : {},
@@ -19579,7 +20327,7 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
19579
20327
  }
19580
20328
 
19581
20329
  // dist/pi-progress.js
19582
- import { createHash as createHash4 } from "node:crypto";
20330
+ import { createHash as createHash5 } from "node:crypto";
19583
20331
  function record5(value) {
19584
20332
  return typeof value === "object" && value !== null && !Array.isArray(value);
19585
20333
  }
@@ -19628,7 +20376,7 @@ function piCustomNotice(value, sessionId, occurrences) {
19628
20376
  return null;
19629
20377
  const occurrence = occurrences.get(key) ?? 0;
19630
20378
  occurrences.set(key, occurrence + 1);
19631
- const digest = createHash4("sha256").update(JSON.stringify([sessionId, key, occurrence])).digest("hex");
20379
+ const digest = createHash5("sha256").update(JSON.stringify([sessionId, key, occurrence])).digest("hex");
19632
20380
  const [customType, text4] = JSON.parse(key);
19633
20381
  return {
19634
20382
  type: "progress.message",
@@ -19953,11 +20701,11 @@ function isEmptyWakeup(entry) {
19953
20701
  const content = message(entry)?.content;
19954
20702
  return content === "" || Array.isArray(content) && content.every((part) => isRecord5(part) && part.type === "text" && part.text === "");
19955
20703
  }
19956
- function turnStarts(active) {
20704
+ function turnStarts(active2) {
19957
20705
  const starts = [];
19958
20706
  let terminal = true;
19959
20707
  let pending = null;
19960
- for (const [index, entry] of active.entries()) {
20708
+ for (const [index, entry] of active2.entries()) {
19961
20709
  const role = messageRole(entry);
19962
20710
  if (role === "user") {
19963
20711
  if (pending && isEmptyWakeup(entry))
@@ -19977,29 +20725,34 @@ function turnStarts(active) {
19977
20725
  return starts;
19978
20726
  }
19979
20727
  function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0)) {
19980
- const active = activePiEntries(history);
19981
- const { identities } = piHistoryMessageIdentities(state2.sessionId, active);
19982
- const { notices } = piHistoryNotices(state2.sessionId, active);
20728
+ const active2 = activePiEntries(history);
20729
+ const { identities } = piHistoryMessageIdentities(state2.sessionId, active2);
20730
+ const { notices } = piHistoryNotices(state2.sessionId, active2);
19983
20731
  const turns = [];
19984
- const starts = turnStarts(active);
20732
+ const starts = turnStarts(active2);
19985
20733
  const byIndex = new Map(starts.map((start, ordinal) => [start.index, ordinal]));
20734
+ const models = createPiModelIndex([
20735
+ ...state2.models ?? [],
20736
+ ...state2.model ? [state2.model] : [],
20737
+ ...active2.map(modelChange).filter((model2) => model2 !== null)
20738
+ ]);
19986
20739
  let effectiveModel = state2.model;
19987
- for (let index = 0; index < active.length; ) {
19988
- const model2 = modelChange(active[index]);
20740
+ for (let index = 0; index < active2.length; ) {
20741
+ const model2 = modelChange(active2[index]);
19989
20742
  if (model2) {
19990
20743
  effectiveModel = model2;
19991
20744
  index += 1;
19992
20745
  continue;
19993
20746
  }
19994
- const user = active[index];
20747
+ const user = active2[index];
19995
20748
  const ordinal = byIndex.get(index);
19996
20749
  if (ordinal === void 0) {
19997
20750
  index += 1;
19998
20751
  continue;
19999
20752
  }
20000
20753
  const next = starts[ordinal + 1];
20001
- const end = next?.index ?? active.length;
20002
- const entries = active.slice(index, end);
20754
+ const end = next?.index ?? active2.length;
20755
+ const entries = active2.slice(index, end);
20003
20756
  const outcome = assistantOutcome(entries);
20004
20757
  const userText = textContent2(message(user)?.content);
20005
20758
  const nativeTurnRef = nativeTurnRefSchema.parse({
@@ -20020,7 +20773,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
20020
20773
  input: messageRole(user) === "user" ? [{ type: "text", text: userText }] : [],
20021
20774
  items: snapshotItems(entries, identities, notices, outcome, subagents, state2.cwd),
20022
20775
  outcome,
20023
- ...effectiveModel ? { model: encodePiModelRef(effectiveModel) } : {}
20776
+ ...effectiveModel ? { model: models.ref(effectiveModel) } : {}
20024
20777
  });
20025
20778
  for (const entry of entries) {
20026
20779
  const changed = modelChange(entry);
@@ -20040,8 +20793,8 @@ function resolvePiLastTurnBoundary(history) {
20040
20793
  } : null;
20041
20794
  }
20042
20795
  function resolvePiForkBoundary(history, checkpointId) {
20043
- const active = activePiEntries(history);
20044
- const starts = turnStarts(active);
20796
+ const active2 = activePiEntries(history);
20797
+ const starts = turnStarts(active2);
20045
20798
  const targetTurnIndex = starts.findIndex(({ entry }) => entry.id === checkpointId);
20046
20799
  if (targetTurnIndex < 0)
20047
20800
  throw new Error("Pi Checkpoint is not on the active branch");
@@ -20226,14 +20979,14 @@ function createPiUsageStatistics(environment) {
20226
20979
  return Object.freeze({
20227
20980
  // <project>/<session>.jsonl and its subagents' <session>/<id>/run-*/session.jsonl
20228
20981
  listSources: (signal) => jsonlUsageSources(piSessionImportDirectory(environment).directory, 4, signal),
20229
- readSource: (id, signal) => readPiUsage(id, signal)
20982
+ readSource: (id2, signal) => readPiUsage(id2, signal)
20230
20983
  });
20231
20984
  }
20232
20985
 
20233
20986
  // dist/account-balance.js
20234
- import { readFile as readFile2 } from "node:fs/promises";
20235
- import { homedir as homedir3 } from "node:os";
20236
- import path8 from "node:path";
20987
+ import { readFile as readFile3 } from "node:fs/promises";
20988
+ import { homedir as homedir4 } from "node:os";
20989
+ import path9 from "node:path";
20237
20990
  var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
20238
20991
  var SUB2API_USAGE_PATH = "/v1/usage";
20239
20992
  var REQUEST_TIMEOUT_MS = 1e4;
@@ -20242,11 +20995,11 @@ function agentDirectory(environment) {
20242
20995
  const configured = environment.PI_CODING_AGENT_DIR?.trim();
20243
20996
  if (configured)
20244
20997
  return configured;
20245
- return path8.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".pi", "agent");
20998
+ return path9.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".pi", "agent");
20246
20999
  }
20247
21000
  var record7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
20248
21001
  async function deepSeekApiKey(environment) {
20249
- const auth = record7(JSON.parse(await readFile2(path8.join(agentDirectory(environment), "auth.json"), "utf8")));
21002
+ const auth = record7(JSON.parse(await readFile3(path9.join(agentDirectory(environment), "auth.json"), "utf8")));
20250
21003
  const deepseek = record7(auth.deepseek);
20251
21004
  if (deepseek.type !== "api_key")
20252
21005
  return void 0;
@@ -20315,16 +21068,16 @@ function usageEndpoint(baseUrl) {
20315
21068
  }
20316
21069
  async function configuredSub2ApiProviders(environment) {
20317
21070
  try {
20318
- const models = record7(JSON.parse(await readFile2(path8.join(agentDirectory(environment), "models.json"), "utf8")));
21071
+ const models = record7(JSON.parse(await readFile3(path9.join(agentDirectory(environment), "models.json"), "utf8")));
20319
21072
  const providers = record7(models.providers);
20320
21073
  const found = [];
20321
- for (const [id, definition] of Object.entries(providers)) {
21074
+ for (const [id2, definition] of Object.entries(providers)) {
20322
21075
  const provider = record7(definition);
20323
21076
  const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
20324
21077
  const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
20325
- if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
21078
+ if (!id2.trim() || id2.length > 128 || !apiKey || !usageEndpoint(baseUrl))
20326
21079
  continue;
20327
- found.push({ id, apiKey, baseUrl });
21080
+ found.push({ id: id2, apiKey, baseUrl });
20328
21081
  }
20329
21082
  return found.sort((left, right) => left.id.localeCompare(right.id));
20330
21083
  } catch {
@@ -20377,21 +21130,21 @@ async function fetchPiAccountBalance(input) {
20377
21130
  }
20378
21131
 
20379
21132
  // dist/pi-credential-imports.js
20380
- import { randomUUID as randomUUID2 } from "node:crypto";
21133
+ import { randomUUID as randomUUID3 } from "node:crypto";
20381
21134
  import { execFile as execFile2 } from "node:child_process";
20382
21135
  import { promisify } from "node:util";
20383
21136
  import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
20384
21137
  import { realpath as realpath2 } from "node:fs/promises";
20385
21138
  import os4 from "node:os";
20386
- import path10 from "node:path";
21139
+ import path11 from "node:path";
20387
21140
  import { pathToFileURL } from "node:url";
20388
21141
 
20389
21142
  // dist/command.js
20390
21143
  import fs2 from "node:fs";
20391
- import { homedir as homedir4, tmpdir as tmpdir2 } from "node:os";
20392
- import path9 from "node:path";
21144
+ import { homedir as homedir5, tmpdir as tmpdir2 } from "node:os";
21145
+ import path10 from "node:path";
20393
21146
  var PI_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
20394
- var PI_PACKAGE_PATH = path9.join("node_modules", "@earendil-works", "pi-coding-agent");
21147
+ var PI_PACKAGE_PATH = path10.join("node_modules", "@earendil-works", "pi-coding-agent");
20395
21148
  var piDiscoverySpec = {
20396
21149
  id: "pi",
20397
21150
  command: "pi",
@@ -20417,18 +21170,18 @@ function resolvePiExecutable(input, dependencies = {}) {
20417
21170
  return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
20418
21171
  }
20419
21172
  function findPiPackageDirectory(executable) {
20420
- let directory = path9.dirname(executable);
21173
+ let directory = path10.dirname(executable);
20421
21174
  while (true) {
20422
- for (const candidate of [directory, path9.join(directory, PI_PACKAGE_PATH)]) {
21175
+ for (const candidate of [directory, path10.join(directory, PI_PACKAGE_PATH)]) {
20423
21176
  try {
20424
- const manifest = JSON.parse(fs2.readFileSync(path9.join(candidate, "package.json"), "utf8"));
21177
+ const manifest = JSON.parse(fs2.readFileSync(path10.join(candidate, "package.json"), "utf8"));
20425
21178
  if (typeof manifest === "object" && manifest !== null && "name" in manifest && manifest.name === PI_PACKAGE_NAME) {
20426
21179
  return candidate;
20427
21180
  }
20428
21181
  } catch {
20429
21182
  }
20430
21183
  }
20431
- const parent = path9.dirname(directory);
21184
+ const parent = path10.dirname(directory);
20432
21185
  if (parent === directory)
20433
21186
  return void 0;
20434
21187
  directory = parent;
@@ -20436,16 +21189,16 @@ function findPiPackageDirectory(executable) {
20436
21189
  }
20437
21190
  function findPiCliEntry(packageDirectory) {
20438
21191
  try {
20439
- const manifest = JSON.parse(fs2.readFileSync(path9.join(packageDirectory, "package.json"), "utf8"));
21192
+ const manifest = JSON.parse(fs2.readFileSync(path10.join(packageDirectory, "package.json"), "utf8"));
20440
21193
  if (typeof manifest !== "object" || manifest === null || !("bin" in manifest))
20441
21194
  return void 0;
20442
21195
  const bin = manifest.bin;
20443
21196
  const entry = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && "pi" in bin ? bin.pi : void 0;
20444
21197
  if (typeof entry !== "string" || !entry.trim())
20445
21198
  return void 0;
20446
- const resolved = path9.resolve(packageDirectory, entry);
20447
- const relative = path9.relative(packageDirectory, resolved);
20448
- if (relative === ".." || relative.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative) || !fs2.statSync(resolved).isFile()) {
21199
+ const resolved = path10.resolve(packageDirectory, entry);
21200
+ const relative = path10.relative(packageDirectory, resolved);
21201
+ if (relative === ".." || relative.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative) || !fs2.statSync(resolved).isFile()) {
20449
21202
  return void 0;
20450
21203
  }
20451
21204
  return resolved;
@@ -20454,11 +21207,11 @@ function findPiCliEntry(packageDirectory) {
20454
21207
  }
20455
21208
  }
20456
21209
  function isFilesystemRoot(cwd) {
20457
- const resolved = path9.resolve(cwd);
20458
- return resolved === path9.parse(resolved).root;
21210
+ const resolved = path10.resolve(cwd);
21211
+ return resolved === path10.parse(resolved).root;
20459
21212
  }
20460
21213
  function writableDirectory(candidate) {
20461
- if (!candidate || !path9.isAbsolute(candidate) || isFilesystemRoot(candidate))
21214
+ if (!candidate || !path10.isAbsolute(candidate) || isFilesystemRoot(candidate))
20462
21215
  return void 0;
20463
21216
  try {
20464
21217
  if (!fs2.statSync(candidate).isDirectory())
@@ -20471,15 +21224,15 @@ function writableDirectory(candidate) {
20471
21224
  }
20472
21225
  function resolvePiInspectCwd(inputCwd, environment = process.env) {
20473
21226
  if (typeof inputCwd === "string" && inputCwd.length > 0 && !isFilesystemRoot(inputCwd)) {
20474
- return path9.resolve(inputCwd);
21227
+ return path10.resolve(inputCwd);
20475
21228
  }
20476
- const candidates = [environment.USERPROFILE, environment.HOME, homedir4(), tmpdir2()];
21229
+ const candidates = [environment.USERPROFILE, environment.HOME, homedir5(), tmpdir2()];
20477
21230
  for (const candidate of candidates) {
20478
21231
  const usable = writableDirectory(candidate);
20479
21232
  if (usable)
20480
21233
  return usable;
20481
21234
  }
20482
- return inputCwd && inputCwd.length > 0 ? path9.resolve(inputCwd) : process.cwd();
21235
+ return inputCwd && inputCwd.length > 0 ? path10.resolve(inputCwd) : process.cwd();
20483
21236
  }
20484
21237
 
20485
21238
  // dist/pi-credential-imports.js
@@ -20524,7 +21277,7 @@ function describeOauth(credential) {
20524
21277
  };
20525
21278
  }
20526
21279
  function writeAuth(filename, content) {
20527
- const temporary = `${filename}.${randomUUID2()}.tmp`;
21280
+ const temporary = `${filename}.${randomUUID3()}.tmp`;
20528
21281
  try {
20529
21282
  writeFileSync(temporary, content, { flag: "wx", mode: 384 });
20530
21283
  renameSync(temporary, filename);
@@ -20533,8 +21286,8 @@ function writeAuth(filename, content) {
20533
21286
  }
20534
21287
  }
20535
21288
  function removeOwnedFiles(dir) {
20536
- rmSync(path10.join(dir, "index.ts"), { force: true });
20537
- rmSync(path10.join(dir, "import.json"), { force: true });
21289
+ rmSync(path11.join(dir, "index.ts"), { force: true });
21290
+ rmSync(path11.join(dir, "import.json"), { force: true });
20538
21291
  try {
20539
21292
  rmdirSync(dir);
20540
21293
  } catch {
@@ -20546,17 +21299,17 @@ async function installation(command, environment, authPath) {
20546
21299
  const cliEntry = directory ? findPiCliEntry(directory) : void 0;
20547
21300
  if (!directory || !cliEntry)
20548
21301
  throw new Error("Pi credential import requires a supported npm Pi installation");
20549
- const storage = await import(pathToFileURL(path10.join(directory, "dist/core/auth-storage.js")).href);
20550
- const ai = path10.join(directory, "node_modules/@earendil-works/pi-ai/dist");
20551
- const all = await import(pathToFileURL(path10.join(ai, "providers/all.js")).href);
21302
+ const storage = await import(pathToFileURL(path11.join(directory, "dist/core/auth-storage.js")).href);
21303
+ const ai = path11.join(directory, "node_modules/@earendil-works/pi-ai/dist");
21304
+ const all = await import(pathToFileURL(path11.join(ai, "providers/all.js")).href);
20552
21305
  const providers = all.getBuiltinProviders();
20553
21306
  const providerModules = {
20554
- "openai-codex": pathToFileURL(path10.join(ai, "providers/openai-codex.js")).href,
20555
- xai: pathToFileURL(path10.join(ai, "providers/xai.js")).href
21307
+ "openai-codex": pathToFileURL(path11.join(ai, "providers/openai-codex.js")).href,
21308
+ xai: pathToFileURL(path11.join(ai, "providers/xai.js")).href
20556
21309
  };
20557
- for (const [id, url2] of Object.entries(providerModules)) {
21310
+ for (const [id2, url2] of Object.entries(providerModules)) {
20558
21311
  const module = await import(url2);
20559
- const provider = id === "xai" ? module.xaiProvider() : module.openaiCodexProvider();
21312
+ const provider = id2 === "xai" ? module.xaiProvider() : module.openaiCodexProvider();
20560
21313
  if (!provider.auth?.oauth || !provider.getModels().length)
20561
21314
  throw new Error("Pi version does not support subscription imports");
20562
21315
  }
@@ -20566,8 +21319,8 @@ async function installation(command, environment, authPath) {
20566
21319
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
20567
21320
  async configuredProviderNames() {
20568
21321
  const { stdout } = await promisify(execFile2)(process.execPath, [cliEntry, "--offline", "--no-approve", "--list-models"], {
20569
- cwd: existsSync(path10.dirname(authPath)) ? path10.dirname(authPath) : os4.homedir(),
20570
- env: { ...environment, PI_CODING_AGENT_DIR: path10.dirname(authPath), PI_OFFLINE: "1" },
21322
+ cwd: existsSync(path11.dirname(authPath)) ? path11.dirname(authPath) : os4.homedir(),
21323
+ env: { ...environment, PI_CODING_AGENT_DIR: path11.dirname(authPath), PI_OFFLINE: "1" },
20571
21324
  timeout: 15e3,
20572
21325
  maxBuffer: 4 * 1024 * 1024
20573
21326
  });
@@ -20597,17 +21350,17 @@ export default async function (pi) {
20597
21350
  }
20598
21351
  function createPiCredentialImports(options = {}) {
20599
21352
  const env = { ...process.env, ...options.environment };
20600
- const agentDir = env.PI_CODING_AGENT_DIR ?? path10.join(env.HOME ?? os4.homedir(), ".pi/agent");
20601
- const authPath = path10.join(agentDir, "auth.json");
20602
- const extensionsDir = path10.join(agentDir, "extensions");
21353
+ const agentDir = env.PI_CODING_AGENT_DIR ?? path11.join(env.HOME ?? os4.homedir(), ".pi/agent");
21354
+ const authPath = path11.join(agentDir, "auth.json");
21355
+ const extensionsDir = path11.join(agentDir, "extensions");
20603
21356
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
20604
21357
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
20605
- const location = (name) => path10.join(extensionsDir, `${PREFIX3}${credentialImportNameSchema.parse(name)}`);
21358
+ const location = (name) => path11.join(extensionsDir, `${PREFIX3}${credentialImportNameSchema.parse(name)}`);
20606
21359
  const readRecord = (name) => {
20607
21360
  const dir = location(name);
20608
21361
  if (lstatSync(dir).isSymbolicLink())
20609
21362
  throw new Error("Imported configuration was changed; manage it in Pi");
20610
- const value = JSON.parse(readFileSync(path10.join(dir, "import.json"), "utf8"));
21363
+ const value = JSON.parse(readFileSync(path11.join(dir, "import.json"), "utf8"));
20611
21364
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
20612
21365
  throw new Error("Invalid import metadata");
20613
21366
  const record10 = value.record;
@@ -20624,7 +21377,7 @@ function createPiCredentialImports(options = {}) {
20624
21377
  };
20625
21378
  const owned = (meta3, auth) => {
20626
21379
  const credential = auth[meta3.record.name];
20627
- const file2 = path10.join(location(meta3.record.name), "index.ts");
21380
+ const file2 = path11.join(location(meta3.record.name), "index.ts");
20628
21381
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
20629
21382
  };
20630
21383
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -20638,7 +21391,7 @@ function createPiCredentialImports(options = {}) {
20638
21391
  const name = entry.slice(PREFIX3.length);
20639
21392
  if (!credentialImportNameSchema.safeParse(name).success)
20640
21393
  continue;
20641
- if (!existsSync(path10.join(location(name), "import.json")))
21394
+ if (!existsSync(path11.join(location(name), "import.json")))
20642
21395
  continue;
20643
21396
  try {
20644
21397
  const meta3 = readRecord(name);
@@ -20672,7 +21425,7 @@ function createPiCredentialImports(options = {}) {
20672
21425
  ...describeOauth(credential)
20673
21426
  });
20674
21427
  }
20675
- const modelsPath = path10.join(agentDir, "models.json");
21428
+ const modelsPath = path11.join(agentDir, "models.json");
20676
21429
  if (existsSync(modelsPath)) {
20677
21430
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
20678
21431
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -20693,7 +21446,7 @@ function createPiCredentialImports(options = {}) {
20693
21446
  throw new Error("Unsupported credential source");
20694
21447
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
20695
21448
  throw new Error("Provider name already exists; choose another name");
20696
- const owner = randomUUID2();
21449
+ const owner = randomUUID3();
20697
21450
  const record10 = credentialImportRecordSchema.parse({
20698
21451
  name,
20699
21452
  source: transfer.source,
@@ -20706,15 +21459,15 @@ function createPiCredentialImports(options = {}) {
20706
21459
  try {
20707
21460
  sdk.backend.withLock((current) => {
20708
21461
  const auth = parseAuth(current);
20709
- const modelsPath = path10.join(agentDir, "models.json");
21462
+ const modelsPath = path11.join(agentDir, "models.json");
20710
21463
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
20711
- if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path10.join(extensionsDir, `${name}-provider.ts`)))
21464
+ if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path11.join(extensionsDir, `${name}-provider.ts`)))
20712
21465
  throw new Error("Provider name already exists; choose another name");
20713
21466
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
20714
21467
  mkdirSync(dir, { mode: 448 });
20715
21468
  created = true;
20716
- writeFileSync(path10.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record10, extension }), { flag: "wx", mode: 384 });
20717
- writeFileSync(path10.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
21469
+ writeFileSync(path11.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record10, extension }), { flag: "wx", mode: 384 });
21470
+ writeFileSync(path11.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
20718
21471
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
20719
21472
  saveAuth(auth);
20720
21473
  committed = true;
@@ -20733,7 +21486,7 @@ function createPiCredentialImports(options = {}) {
20733
21486
  const auth = parseAuth(current);
20734
21487
  if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
20735
21488
  throw new Error("Import ownership or source account changed; refusing replacement");
20736
- const metadataPath = path10.join(location(name), "import.json");
21489
+ const metadataPath = path11.join(location(name), "import.json");
20737
21490
  const previous = readFileSync(metadataPath, "utf8");
20738
21491
  const updated = {
20739
21492
  ...meta3,
@@ -20767,91 +21520,6 @@ function createPiCredentialImports(options = {}) {
20767
21520
  };
20768
21521
  }
20769
21522
 
20770
- // dist/pi-fast-mode.js
20771
- import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
20772
- import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
20773
- import { homedir as homedir5 } from "node:os";
20774
- import path11 from "node:path";
20775
- var PI_FAST_COMMAND = "codexhost-fast-mode";
20776
- var PI_FAST_ACK = "codexhost-fast-mode:";
20777
- var PI_FAST_EXTENSION = `export default function(pi) {
20778
- let target;
20779
- const wrapped = new Set();
20780
- const supportsModel = (model) => model && (model.api === "openai-codex-responses" || model.api === "openai-responses") && /gpt/i.test(model.id);
20781
- pi.on("model_select", (_event, ctx) => {
20782
- if (target && (target.provider !== ctx.model?.provider || target.id !== ctx.model?.id || !supportsModel(ctx.model))) target = undefined;
20783
- });
20784
- pi.on("session_start", (_event, ctx) => {
20785
- if (typeof ctx.modelRegistry.getProvider !== "function" || typeof pi.registerProvider !== "function") return;
20786
- pi.registerCommand("${PI_FAST_COMMAND}", {
20787
- description: "Codex Host Fast mode",
20788
- handler: async (args, ctx) => {
20789
- const [mode, nonce] = args.split(" ");
20790
- if (!nonce || (mode !== "on" && mode !== "off")) throw new Error("Invalid Fast selection");
20791
- if (mode === "on") {
20792
- const model = ctx.model;
20793
- if (!supportsModel(model)) throw new Error("Fast requires a GPT model using the Codex or OpenAI Responses API");
20794
- const original = ctx.modelRegistry.getProvider(model.provider);
20795
- if (!original) throw new Error("Provider is unavailable");
20796
- if (!wrapped.has(model.provider)) {
20797
- const options = (model, value) => target && supportsModel(model) && target.provider === model.provider && target.id === model.id
20798
- ? {
20799
- ...value,
20800
- serviceTier: "priority",
20801
- // Pi streamSimple drops serviceTier but preserves onPayload.
20802
- onPayload: async (payload, requestModel) => {
20803
- const request = { ...payload, service_tier: "priority" };
20804
- const replacement = await value?.onPayload?.(request, requestModel);
20805
- return { ...(replacement === undefined ? request : replacement), service_tier: "priority" };
20806
- },
20807
- } : value;
20808
- pi.registerProvider({
20809
- ...original,
20810
- stream: (model, context, value) => original.stream(model, context, options(model, value)),
20811
- streamSimple: (model, context, value) => original.streamSimple(model, context, options(model, value)),
20812
- });
20813
- wrapped.add(model.provider);
20814
- }
20815
- target = { provider: model.provider, id: model.id };
20816
- } else target = undefined;
20817
- ctx.ui.notify("${PI_FAST_ACK}" + nonce + ":" + mode, "info");
20818
- },
20819
- });
20820
- });
20821
- }
20822
- `;
20823
- async function ensurePiFastExtension(environment) {
20824
- const digest = createHash5("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
20825
- const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path11.join(environment.HOME ?? environment.USERPROFILE ?? homedir5(), ".codexhost");
20826
- const directory = path11.resolve(dataDirectory, "extensions", "pi-codex-fast");
20827
- const file2 = path11.join(directory, `${digest}.mjs`);
20828
- if (await readFile3(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
20829
- return file2;
20830
- await mkdir2(directory, { recursive: true });
20831
- const temporary = `${file2}.${randomUUID3()}.tmp`;
20832
- try {
20833
- await writeFile3(temporary, PI_FAST_EXTENSION, { mode: 384 });
20834
- try {
20835
- await rename2(temporary, file2);
20836
- } catch (error51) {
20837
- if (await readFile3(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
20838
- throw error51;
20839
- }
20840
- } finally {
20841
- await rm3(temporary, { force: true });
20842
- }
20843
- return file2;
20844
- }
20845
- function piFastModelKeys(models) {
20846
- return new Set(models.filter((model2) => (model2.api === "openai-codex-responses" || model2.api === "openai-responses") && /gpt/i.test(model2.id)).map((model2) => encodePiModelRef(model2).id));
20847
- }
20848
- function withPiFast(catalog, supported) {
20849
- return {
20850
- ...catalog,
20851
- models: catalog.models.map((model2) => supported.has(model2.ref.id) ? { ...model2, fastModel: encodePiModelRef({ ...decodePiModelRef(model2.ref), fast: true }) } : model2)
20852
- };
20853
- }
20854
-
20855
21523
  // dist/pi-empty-session.js
20856
21524
  import { createReadStream as createReadStream3 } from "node:fs";
20857
21525
  import { createInterface as createInterface3 } from "node:readline";
@@ -20928,8 +21596,8 @@ async function persistEmptyPiSession(input) {
20928
21596
  throw new Error("Pi empty Session persistence requires native v3 history");
20929
21597
  }
20930
21598
  const entries = history.entries;
20931
- const active = activePiEntries(history);
20932
- if (active.length !== entries.length || active.some((entry, index) => entry.id !== entries[index]?.id)) {
21599
+ const active2 = activePiEntries(history);
21600
+ if (active2.length !== entries.length || active2.some((entry, index) => entry.id !== entries[index]?.id)) {
20933
21601
  throw new Error("Pi empty Session must expose its complete active branch");
20934
21602
  }
20935
21603
  const header = {
@@ -21093,10 +21761,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
21093
21761
  const result = details.results.findLast((candidate) => record8(candidate) && candidate.workflowKey === address.childId);
21094
21762
  if (!record8(result))
21095
21763
  break;
21096
- const id = piWorkflowSubagentId(address);
21764
+ const id2 = piWorkflowSubagentId(address);
21097
21765
  if (typeof result.sessionFile === "string") {
21098
21766
  try {
21099
- const snapshot = await childHistory(result.sessionFile, parentSessionId, id);
21767
+ const snapshot = await childHistory(result.sessionFile, parentSessionId, id2);
21100
21768
  if (snapshot.turns.length)
21101
21769
  return { ok: true, value: snapshot };
21102
21770
  } catch {
@@ -21106,7 +21774,7 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
21106
21774
  const output = result.finalOutput.slice(0, 64 * 1024);
21107
21775
  return {
21108
21776
  ok: true,
21109
- value: piSubagentSnapshot(parentSessionId, id, {
21777
+ value: piSubagentSnapshot(parentSessionId, id2, {
21110
21778
  kind: "pi-subagents.inspect-reply",
21111
21779
  version: 1,
21112
21780
  requestId: "native-workflow-result",
@@ -21149,8 +21817,8 @@ function gotgenesHistory(history) {
21149
21817
  function restoreGotgenes(history, observer) {
21150
21818
  observer.observe(gotgenesHistory(history), false);
21151
21819
  }
21152
- async function readGotgenesChild(history, parentSessionId, id, live) {
21153
- const saved = gotgenesHistory(history).find((entry) => entry.id === id);
21820
+ async function readGotgenesChild(history, parentSessionId, id2, live) {
21821
+ const saved = gotgenesHistory(history).find((entry) => entry.id === id2);
21154
21822
  const record10 = live?.outputFile ? live : saved;
21155
21823
  if (!record10?.outputFile)
21156
21824
  return {
@@ -21164,7 +21832,7 @@ async function readGotgenesChild(history, parentSessionId, id, live) {
21164
21832
  try {
21165
21833
  return {
21166
21834
  ok: true,
21167
- value: await childHistory(record10.outputFile, parentSessionId, gotgenesId(id), true)
21835
+ value: await childHistory(record10.outputFile, parentSessionId, gotgenesId(id2), true)
21168
21836
  };
21169
21837
  } catch (error51) {
21170
21838
  return {
@@ -21188,8 +21856,8 @@ function record9(value) {
21188
21856
  function state(value) {
21189
21857
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
21190
21858
  }
21191
- function piSubagentArtifact(value, runId, parentSessionId) {
21192
- if (!record9(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
21859
+ function piSubagentArtifact(value, runId, owners) {
21860
+ if (!record9(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || typeof value.sessionId !== "string" || !owners.has(value.sessionId) || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
21193
21861
  return null;
21194
21862
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
21195
21863
  return null;
@@ -21226,7 +21894,7 @@ function piSubagentArtifact(value, runId, parentSessionId) {
21226
21894
  ]
21227
21895
  });
21228
21896
  }
21229
- async function restorePiSubagents(history, parentSessionId, observer) {
21897
+ async function restorePiSubagents(history, owners, observer) {
21230
21898
  restoreGotgenes(history, observer.gotgenes);
21231
21899
  const receipts = /* @__PURE__ */ new Map();
21232
21900
  for (const entry of activePiEntries(history)) {
@@ -21237,7 +21905,7 @@ async function restorePiSubagents(history, parentSessionId, observer) {
21237
21905
  continue;
21238
21906
  receipts.set(details.asyncId, details.asyncDir);
21239
21907
  }
21240
- for (const [id, directory] of [...receipts].slice(-128)) {
21908
+ for (const [id2, directory] of [...receipts].slice(-128)) {
21241
21909
  let file2;
21242
21910
  try {
21243
21911
  file2 = await open4(path14.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
@@ -21249,7 +21917,7 @@ async function restorePiSubagents(history, parentSessionId, observer) {
21249
21917
  if (bytesRead > 1024 * 1024)
21250
21918
  continue;
21251
21919
  const value = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8"));
21252
- const runs = piSubagentArtifact(value, id, parentSessionId);
21920
+ const runs = piSubagentArtifact(value, id2, owners);
21253
21921
  if (runs)
21254
21922
  observer.restore(runs);
21255
21923
  } catch {
@@ -21688,8 +22356,8 @@ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
21688
22356
  "get_available_thinking_levels"
21689
22357
  ]);
21690
22358
  var MAX_EXPIRED_IDS = 64;
21691
- function nativeMessageIdentity(active) {
21692
- return active.assistantNativeMessageIdentity ? { nativeMessageIdentity: active.assistantNativeMessageIdentity } : {};
22359
+ function nativeMessageIdentity(active2) {
22360
+ return active2.assistantNativeMessageIdentity ? { nativeMessageIdentity: active2.assistantNativeMessageIdentity } : {};
21693
22361
  }
21694
22362
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
21695
22363
  function isRecord9(value) {
@@ -21996,8 +22664,8 @@ var PiRpcSession = class {
21996
22664
  if (this.#gotgenesLatest)
21997
22665
  handler(this.#gotgenesLatest, "idle");
21998
22666
  }
21999
- inspectSubagent(id) {
22000
- return this.#subagents.inspect(id);
22667
+ inspectSubagent(id2) {
22668
+ return this.#subagents.inspect(id2);
22001
22669
  }
22002
22670
  setUsageHandler(handler) {
22003
22671
  this.#usageHandler = handler;
@@ -22350,9 +23018,9 @@ var PiRpcSession = class {
22350
23018
  return this.#resolveInteraction(response, "cancelled" in response ? "cancelled" : "responded");
22351
23019
  }
22352
23020
  async #resolveInteraction(response, reason) {
22353
- const active = this.#activeTurn;
22354
- const pending = active?.interactions.get(response.requestId);
22355
- if (!active || !pending || this.#closed || this.#failed) {
23021
+ const active2 = this.#activeTurn;
23022
+ const pending = active2?.interactions.get(response.requestId);
23023
+ if (!active2 || !pending || this.#closed || this.#failed) {
22356
23024
  throw new Error("Pi RPC interaction is not pending");
22357
23025
  }
22358
23026
  if ("value" in response && !["select", "input", "editor"].includes(pending.request.method)) {
@@ -22362,12 +23030,12 @@ var PiRpcSession = class {
22362
23030
  throw new Error("Pi RPC confirmation does not match the request");
22363
23031
  }
22364
23032
  const frame = "cancelled" in response ? { type: "extension_ui_response", id: response.requestId, cancelled: true } : "confirmed" in response ? { type: "extension_ui_response", id: response.requestId, confirmed: response.confirmed } : { type: "extension_ui_response", id: response.requestId, value: response.value };
22365
- if (!active.interactions.delete(response.requestId)) {
23033
+ if (!active2.interactions.delete(response.requestId)) {
22366
23034
  throw new Error("Pi RPC interaction is not pending");
22367
23035
  }
22368
23036
  if (pending.timeout)
22369
23037
  clearTimeout(pending.timeout);
22370
- active.onEvent({ type: "interaction.closed", requestId: response.requestId, reason });
23038
+ active2.onEvent({ type: "interaction.closed", requestId: response.requestId, reason });
22371
23039
  try {
22372
23040
  await this.#write(frame);
22373
23041
  } catch (error51) {
@@ -22377,37 +23045,37 @@ var PiRpcSession = class {
22377
23045
  }
22378
23046
  }
22379
23047
  abort() {
22380
- const active = this.#activeTurn;
22381
- if (!active || this.#closed || this.#failed) {
23048
+ const active2 = this.#activeTurn;
23049
+ if (!active2 || this.#closed || this.#failed) {
22382
23050
  return Promise.reject(new Error("Pi RPC Session has no cancellable Turn"));
22383
23051
  }
22384
- if (active.abortPromise)
22385
- return active.abortPromise;
22386
- active.cancellation = "requesting";
22387
- active.cancellationTimeout = setTimeout(() => {
22388
- this.#terminateFailedCancellation(active, new PiRpcFaultError("protocolError", "Pi Turn cancellation did not settle within its bound"));
23052
+ if (active2.abortPromise)
23053
+ return active2.abortPromise;
23054
+ active2.cancellation = "requesting";
23055
+ active2.cancellationTimeout = setTimeout(() => {
23056
+ this.#terminateFailedCancellation(active2, new PiRpcFaultError("protocolError", "Pi Turn cancellation did not settle within its bound"));
22389
23057
  }, this.#options.cancelTimeoutMs);
22390
23058
  const aborting = this.#send("abort", {}).then(() => {
22391
- if (this.#activeTurn !== active)
23059
+ if (this.#activeTurn !== active2)
22392
23060
  return;
22393
- active.cancellation = "accepted";
22394
- this.#finishSettledTurn(active);
23061
+ active2.cancellation = "accepted";
23062
+ this.#finishSettledTurn(active2);
22395
23063
  }).catch((error51) => {
22396
- if (this.#activeTurn !== active)
23064
+ if (this.#activeTurn !== active2)
22397
23065
  throw error51;
22398
23066
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi RPC Abort failed: ${message2(error51)}`);
22399
- this.#terminateFailedCancellation(active, fault);
23067
+ this.#terminateFailedCancellation(active2, fault);
22400
23068
  throw fault;
22401
23069
  });
22402
- active.abortPromise = aborting;
23070
+ active2.abortPromise = aborting;
22403
23071
  return aborting;
22404
23072
  }
22405
- #terminateFailedCancellation(active, fault) {
22406
- if (this.#activeTurn !== active)
23073
+ #terminateFailedCancellation(active2, fault) {
23074
+ if (this.#activeTurn !== active2)
22407
23075
  return;
22408
- if (active.cancellationTimeout)
22409
- clearTimeout(active.cancellationTimeout);
22410
- active.cancellationTimeout = null;
23076
+ if (active2.cancellationTimeout)
23077
+ clearTimeout(active2.cancellationTimeout);
23078
+ active2.cancellationTimeout = null;
22411
23079
  this.#fail(fault);
22412
23080
  void this.close().catch(() => void 0);
22413
23081
  }
@@ -22526,9 +23194,9 @@ var PiRpcSession = class {
22526
23194
  this.#compactionActive = false;
22527
23195
  const compactionTurn = this.#compactionTurn;
22528
23196
  this.#compactionTurn = null;
22529
- for (const [id, pending] of this.#pending) {
23197
+ for (const [id2, pending] of this.#pending) {
22530
23198
  if (pending.command === "prompt" || pending.command === "compact") {
22531
- this.#armCommandTimeout(id, pending);
23199
+ this.#armCommandTimeout(id2, pending);
22532
23200
  }
22533
23201
  }
22534
23202
  const outcome = value.aborted === true ? "cancelled" : isRecord9(value.result) ? "succeeded" : "failed";
@@ -22547,26 +23215,26 @@ var PiRpcSession = class {
22547
23215
  });
22548
23216
  return;
22549
23217
  }
22550
- let active = this.#activeTurn;
22551
- if (!active && !this.#manualCompaction && !this.#compactionActive && (this.#autonomousTurnHandler || this.#autonomousLifecycleHandler) && value.type === "message_start" && assistantText(value.message) !== null) {
22552
- active = this.#startAutonomousTurn(value.message, generation);
23218
+ let active2 = this.#activeTurn;
23219
+ if (!active2 && !this.#manualCompaction && !this.#compactionActive && (this.#autonomousTurnHandler || this.#autonomousLifecycleHandler) && value.type === "message_start" && assistantText(value.message) !== null) {
23220
+ active2 = this.#startAutonomousTurn(value.message, generation);
22553
23221
  }
22554
- if (!active) {
23222
+ if (!active2) {
22555
23223
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
22556
23224
  this.#fail(new PiRpcFaultError("protocolError", "Pi RPC requested blocking Extension UI outside an active Turn"));
22557
23225
  }
22558
23226
  return;
22559
23227
  }
22560
23228
  if (value.type === "extension_ui_request") {
22561
- if (active.origin === "autonomous" && this.#isBlockingInteraction(value)) {
23229
+ if (active2.origin === "autonomous" && this.#isBlockingInteraction(value)) {
22562
23230
  this.#fail(new PiRpcFaultError("protocolError", "Pi RPC requested blocking Extension UI during an autonomous Turn"));
22563
23231
  return;
22564
23232
  }
22565
- this.#startInteraction(active, value);
23233
+ this.#startInteraction(active2, value);
22566
23234
  return;
22567
23235
  }
22568
23236
  if (value.type === "message_start" && assistantText(value.message) !== null) {
22569
- this.#startAssistantMessage(active, value.message);
23237
+ this.#startAssistantMessage(active2, value.message);
22570
23238
  return;
22571
23239
  }
22572
23240
  if (value.type === "message_update" && isRecord9(value.assistantMessageEvent)) {
@@ -22578,54 +23246,54 @@ var PiRpcSession = class {
22578
23246
  const endingReasoning = eventType === "thinking_end" || eventType === "reasoning_end";
22579
23247
  const endingText = eventType === "text_end";
22580
23248
  if ((endingReasoning || endingText) && typeof event.content === "string") {
22581
- this.#ensureAssistantMessage(active, value.message);
22582
- const stream = endingReasoning ? active.reasoningStream : active.textStream;
22583
- this.#emitContent(active, endingReasoning, stream.complete(event.contentIndex, event.content));
23249
+ this.#ensureAssistantMessage(active2, value.message);
23250
+ const stream = endingReasoning ? active2.reasoningStream : active2.textStream;
23251
+ this.#emitContent(active2, endingReasoning, stream.complete(event.contentIndex, event.content));
22584
23252
  } else if ((isThinking || isText) && delta !== null && delta.length > 0) {
22585
- this.#ensureAssistantMessage(active, value.message);
23253
+ this.#ensureAssistantMessage(active2, value.message);
22586
23254
  if (isThinking)
22587
- active.sawStreamedMessageReasoning = true;
23255
+ active2.sawStreamedMessageReasoning = true;
22588
23256
  else
22589
- active.sawStreamedMessageText = true;
22590
- const stream = isThinking ? active.reasoningStream : active.textStream;
22591
- this.#emitContent(active, isThinking, stream.append(event.contentIndex, delta));
23257
+ active2.sawStreamedMessageText = true;
23258
+ const stream = isThinking ? active2.reasoningStream : active2.textStream;
23259
+ this.#emitContent(active2, isThinking, stream.append(event.contentIndex, delta));
22592
23260
  } else if (event.type === "error") {
22593
- this.#ensureAssistantMessage(active, value.message);
22594
- active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Pi assistant message failed");
23261
+ this.#ensureAssistantMessage(active2, value.message);
23262
+ active2.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Pi assistant message failed");
22595
23263
  }
22596
23264
  return;
22597
23265
  }
22598
23266
  if (value.type === "message_end") {
22599
- this.#finalizeAssistantMessage(active, value.message);
23267
+ this.#finalizeAssistantMessage(active2, value.message);
22600
23268
  return;
22601
23269
  }
22602
23270
  if (value.type === "turn_end") {
22603
- this.#finalizeAssistantMessage(active, value.message);
23271
+ this.#finalizeAssistantMessage(active2, value.message);
22604
23272
  return;
22605
23273
  }
22606
23274
  if (value.type === "tool_execution_start") {
22607
- this.#startTool(active, value);
23275
+ this.#startTool(active2, value);
22608
23276
  return;
22609
23277
  }
22610
23278
  if (value.type === "tool_execution_update") {
22611
- this.#updateTool(active, value);
23279
+ this.#updateTool(active2, value);
22612
23280
  return;
22613
23281
  }
22614
23282
  if (value.type === "tool_execution_end") {
22615
- this.#completeTool(active, value);
23283
+ this.#completeTool(active2, value);
22616
23284
  return;
22617
23285
  }
22618
23286
  if (value.type === "agent_settled") {
22619
- if (active.settlement !== "pending")
23287
+ if (active2.settlement !== "pending")
22620
23288
  return;
22621
- active.settlement = "confirming";
22622
- void this.#confirmSettledTurn(active, active.runGeneration);
23289
+ active2.settlement = "confirming";
23290
+ void this.#confirmSettledTurn(active2, active2.runGeneration);
22623
23291
  }
22624
23292
  }
22625
23293
  #startAutonomousTurn(value, generation) {
22626
23294
  const events = [];
22627
23295
  const runId = randomUUID6();
22628
- const active = {
23296
+ const active2 = {
22629
23297
  origin: "autonomous",
22630
23298
  autonomousRunId: runId,
22631
23299
  runGeneration: generation,
@@ -22660,10 +23328,10 @@ var PiRpcSession = class {
22660
23328
  cancellationTimeout: null,
22661
23329
  abortPromise: null
22662
23330
  };
22663
- this.#activeTurn = active;
23331
+ this.#activeTurn = active2;
22664
23332
  this.#autonomousLifecycleHandler?.({ type: "started", runId });
22665
- this.#drainProgress(active.onEvent);
22666
- return active;
23333
+ this.#drainProgress(active2.onEvent);
23334
+ return active2;
22667
23335
  }
22668
23336
  #handleProgress(value) {
22669
23337
  if ((value.type === "message_start" || value.type === "message_end") && isRecord9(value.message) && value.message.role === "custom") {
@@ -22745,21 +23413,21 @@ var PiRpcSession = class {
22745
23413
  for (const pending of this.#pendingProgress.splice(0))
22746
23414
  onEvent(pending.event);
22747
23415
  }
22748
- #emitAutonomousTurn(active, result) {
23416
+ #emitAutonomousTurn(active2, result) {
22749
23417
  const handler = this.#autonomousTurnHandler;
22750
- if (active.origin !== "autonomous" || !active.autonomousEvents || !active.autonomousRunId) {
23418
+ if (active2.origin !== "autonomous" || !active2.autonomousEvents || !active2.autonomousRunId) {
22751
23419
  return;
22752
23420
  }
22753
23421
  try {
22754
23422
  const turn = {
22755
- nativeTurnKey: active.nativeTurnKey,
22756
- events: [...active.autonomousEvents],
23423
+ nativeTurnKey: active2.nativeTurnKey,
23424
+ events: [...active2.autonomousEvents],
22757
23425
  result
22758
23426
  };
22759
23427
  if (this.#autonomousLifecycleHandler)
22760
23428
  this.#autonomousLifecycleHandler({
22761
23429
  type: "completed",
22762
- runId: active.autonomousRunId,
23430
+ runId: active2.autonomousRunId,
22763
23431
  turn
22764
23432
  });
22765
23433
  else
@@ -22771,14 +23439,14 @@ var PiRpcSession = class {
22771
23439
  #isBlockingInteraction(value) {
22772
23440
  return ["select", "confirm", "input", "editor"].includes(String(value.method));
22773
23441
  }
22774
- #startInteraction(active, value) {
23442
+ #startInteraction(active2, value) {
22775
23443
  if (!this.#isBlockingInteraction(value))
22776
23444
  return;
22777
23445
  const requestId = value.id;
22778
23446
  const method = value.method;
22779
23447
  const title = value.title;
22780
23448
  const timeoutMs = value.timeout;
22781
- if (typeof requestId !== "string" || requestId.length === 0 || typeof method !== "string" || typeof title !== "string" || title.length === 0 || timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) || active.interactions.has(requestId)) {
23449
+ if (typeof requestId !== "string" || requestId.length === 0 || typeof method !== "string" || typeof title !== "string" || title.length === 0 || timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) || active2.interactions.has(requestId)) {
22782
23450
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid Interaction request");
22783
23451
  }
22784
23452
  let request;
@@ -22830,7 +23498,7 @@ var PiRpcSession = class {
22830
23498
  const pending = { request, timeout: null };
22831
23499
  if (request.timeoutMs !== void 0) {
22832
23500
  pending.timeout = setTimeout(() => {
22833
- if (this.#activeTurn !== active || !active.interactions.has(requestId))
23501
+ if (this.#activeTurn !== active2 || !active2.interactions.has(requestId))
22834
23502
  return;
22835
23503
  void this.#resolveInteraction({ requestId, cancelled: true }, "expired").catch((error51) => {
22836
23504
  if (this.#closed || this.#failed)
@@ -22839,17 +23507,17 @@ var PiRpcSession = class {
22839
23507
  });
22840
23508
  }, request.timeoutMs);
22841
23509
  }
22842
- active.interactions.set(requestId, pending);
22843
- active.onEvent({ type: "interaction.requested", request });
23510
+ active2.interactions.set(requestId, pending);
23511
+ active2.onEvent({ type: "interaction.requested", request });
22844
23512
  }
22845
23513
  #handleResponse(value) {
22846
- const id = value.id;
22847
- if (typeof id !== "string") {
23514
+ const id2 = value.id;
23515
+ if (typeof id2 !== "string") {
22848
23516
  this.#fail(new PiRpcFaultError("protocolError", "Pi RPC response has no id"));
22849
23517
  return;
22850
23518
  }
22851
- const pending = this.#pending.get(id);
22852
- if (!pending && this.#expired.delete(id))
23519
+ const pending = this.#pending.get(id2);
23520
+ if (!pending && this.#expired.delete(id2))
22853
23521
  return;
22854
23522
  if (!pending) {
22855
23523
  this.#fail(new PiRpcFaultError("protocolError", "Pi RPC response id is not pending"));
@@ -22857,7 +23525,7 @@ var PiRpcSession = class {
22857
23525
  }
22858
23526
  if (pending.timeout)
22859
23527
  clearTimeout(pending.timeout);
22860
- this.#pending.delete(id);
23528
+ this.#pending.delete(id2);
22861
23529
  if (value.success === true)
22862
23530
  pending.resolve(value);
22863
23531
  else {
@@ -22871,40 +23539,40 @@ var PiRpcSession = class {
22871
23539
  }
22872
23540
  }
22873
23541
  }
22874
- #startTool(active, value) {
23542
+ #startTool(active2, value) {
22875
23543
  const callId = value.toolCallId;
22876
23544
  const toolName = value.toolName;
22877
23545
  const argumentsResult = jsonValueSchema.safeParse(value.args);
22878
- if (typeof callId !== "string" || callId.length === 0 || typeof toolName !== "string" || toolName.length === 0 || !argumentsResult.success || active.tools.has(callId)) {
23546
+ if (typeof callId !== "string" || callId.length === 0 || typeof toolName !== "string" || toolName.length === 0 || !argumentsResult.success || active2.tools.has(callId)) {
22879
23547
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid Tool start");
22880
23548
  }
22881
- active.sawTool = true;
22882
- active.tools.set(callId, toolName);
22883
- active.onEvent({
23549
+ active2.sawTool = true;
23550
+ active2.tools.set(callId, toolName);
23551
+ active2.onEvent({
22884
23552
  type: "tool.started",
22885
23553
  callId,
22886
23554
  toolName,
22887
23555
  arguments: argumentsResult.data
22888
23556
  });
22889
23557
  }
22890
- #updateTool(active, value) {
23558
+ #updateTool(active2, value) {
22891
23559
  const callId = value.toolCallId;
22892
23560
  const outputResult = jsonValueSchema.safeParse(value.partialResult);
22893
- if (typeof callId !== "string" || !active.tools.has(callId) || !outputResult.success) {
23561
+ if (typeof callId !== "string" || !active2.tools.has(callId) || !outputResult.success) {
22894
23562
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid Tool update");
22895
23563
  }
22896
- active.onEvent({ type: "tool.updated", callId, output: outputResult.data });
23564
+ active2.onEvent({ type: "tool.updated", callId, output: outputResult.data });
22897
23565
  }
22898
- #completeTool(active, value) {
23566
+ #completeTool(active2, value) {
22899
23567
  const callId = value.toolCallId;
22900
23568
  const toolName = value.toolName;
22901
23569
  const result = jsonValueSchema.safeParse(value.result);
22902
- const expectedName = typeof callId === "string" ? active.tools.get(callId) : void 0;
23570
+ const expectedName = typeof callId === "string" ? active2.tools.get(callId) : void 0;
22903
23571
  if (typeof callId !== "string" || typeof toolName !== "string" || expectedName !== toolName || typeof value.isError !== "boolean" || !result.success) {
22904
23572
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid Tool end");
22905
23573
  }
22906
- active.tools.delete(callId);
22907
- active.onEvent({
23574
+ active2.tools.delete(callId);
23575
+ active2.onEvent({
22908
23576
  type: "tool.completed",
22909
23577
  callId,
22910
23578
  toolName,
@@ -22912,8 +23580,8 @@ var PiRpcSession = class {
22912
23580
  isError: value.isError
22913
23581
  });
22914
23582
  }
22915
- #isSettlementCurrent(active, generation) {
22916
- return this.#activeTurn === active && active.runGeneration === generation && active.settlement === "confirming";
23583
+ #isSettlementCurrent(active2, generation) {
23584
+ return this.#activeTurn === active2 && active2.runGeneration === generation && active2.settlement === "confirming";
22917
23585
  }
22918
23586
  #waitForNextRun(generation) {
22919
23587
  if (this.#runGeneration > generation)
@@ -22948,23 +23616,23 @@ var PiRpcSession = class {
22948
23616
  this.#handle(frame.value, frame.generation);
22949
23617
  }
22950
23618
  }
22951
- async #confirmSettledTurn(active, generation) {
23619
+ async #confirmSettledTurn(active2, generation) {
22952
23620
  try {
22953
23621
  const response = await this.#send("get_state", {});
22954
23622
  const state2 = parseSessionState(response);
22955
- if (!this.#isSettlementCurrent(active, generation))
23623
+ if (!this.#isSettlementCurrent(active2, generation))
22956
23624
  return;
22957
23625
  if (parseSessionStreaming(response))
22958
23626
  await this.#waitForNextRun(generation);
22959
- if (!this.#isSettlementCurrent(active, generation))
23627
+ if (!this.#isSettlementCurrent(active2, generation))
22960
23628
  return;
22961
- if (active.origin === "autonomous" && active.autonomousMessage) {
23629
+ if (active2.origin === "autonomous" && active2.autonomousMessage) {
22962
23630
  const history = await this.getEntries();
22963
23631
  const snapshot = mapPiSnapshot(history, { sessionId: state2.sessionId, model: null });
22964
- if (!this.#isSettlementCurrent(active, generation))
23632
+ if (!this.#isSettlementCurrent(active2, generation))
22965
23633
  return;
22966
23634
  const entries = activePiEntries(history);
22967
- const live = active.autonomousMessage;
23635
+ const live = active2.autonomousMessage;
22968
23636
  const responseId = assistantMessageId(live);
22969
23637
  const matches = snapshot.turns.filter((turn2) => {
22970
23638
  if (turn2.input.length !== 0)
@@ -22976,156 +23644,156 @@ var PiRpcSession = class {
22976
23644
  const turn = matches.length === 1 ? matches[0] : void 0;
22977
23645
  if (!turn)
22978
23646
  throw new PiRpcFaultError("protocolError", "Pi autonomous Turn has no matching persisted custom Entry");
22979
- active.nativeTurnKey = turn.nativeTurnRef.nativeTurnKey;
23647
+ active2.nativeTurnKey = turn.nativeTurnRef.nativeTurnKey;
22980
23648
  }
22981
- if (!this.#isSettlementCurrent(active, generation))
23649
+ if (!this.#isSettlementCurrent(active2, generation))
22982
23650
  return;
22983
23651
  this.#state = state2;
22984
- active.settlement = "confirmed";
22985
- this.#finishSettledTurn(active);
23652
+ active2.settlement = "confirmed";
23653
+ this.#finishSettledTurn(active2);
22986
23654
  } catch (error51) {
22987
- if (this.#activeTurn !== active)
23655
+ if (this.#activeTurn !== active2)
22988
23656
  return;
22989
23657
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi RPC stable Turn state could not be confirmed: ${message2(error51)}`);
22990
23658
  this.#fail(fault);
22991
23659
  }
22992
23660
  }
22993
- #finishSettledTurn(active) {
22994
- if (this.#activeTurn !== active || active.settlement !== "confirmed" || active.cancellation === "requesting") {
23661
+ #finishSettledTurn(active2) {
23662
+ if (this.#activeTurn !== active2 || active2.settlement !== "confirmed" || active2.cancellation === "requesting") {
22995
23663
  return;
22996
23664
  }
22997
- if (active.cancellationTimeout)
22998
- clearTimeout(active.cancellationTimeout);
22999
- active.cancellationTimeout = null;
23000
- this.#closeInteractions(active, active.cancellation === "accepted" ? "cancelled" : "superseded");
23001
- if (active.tools.size > 0) {
23665
+ if (active2.cancellationTimeout)
23666
+ clearTimeout(active2.cancellationTimeout);
23667
+ active2.cancellationTimeout = null;
23668
+ this.#closeInteractions(active2, active2.cancellation === "accepted" ? "cancelled" : "superseded");
23669
+ if (active2.tools.size > 0) {
23002
23670
  this.#fail(new PiRpcFaultError("protocolError", "Pi RPC settled with active Tool executions"));
23003
23671
  return;
23004
23672
  }
23005
23673
  this.#activeTurn = null;
23006
- if (active.origin === "autonomous") {
23007
- if (active.cancellation === "accepted") {
23008
- this.#emitAutonomousTurn(active, {
23674
+ if (active2.origin === "autonomous") {
23675
+ if (active2.cancellation === "accepted") {
23676
+ this.#emitAutonomousTurn(active2, {
23009
23677
  status: "cancelled",
23010
- text: active.text,
23678
+ text: active2.text,
23011
23679
  reason: "Cancelled by user"
23012
23680
  });
23013
- } else if (active.failure) {
23014
- this.#emitAutonomousTurn(active, active.nativeCancellationObserved ? {
23681
+ } else if (active2.failure) {
23682
+ this.#emitAutonomousTurn(active2, active2.nativeCancellationObserved ? {
23015
23683
  status: "cancelled",
23016
- text: active.text,
23684
+ text: active2.text,
23017
23685
  reason: "Pi autonomous Assistant was aborted"
23018
- } : { status: "failed", text: active.text, error: active.failure });
23019
- } else if (active.text.trim().length === 0 && !active.sawTool) {
23020
- this.#emitAutonomousTurn(active, {
23686
+ } : { status: "failed", text: active2.text, error: active2.failure });
23687
+ } else if (active2.text.trim().length === 0 && !active2.sawTool) {
23688
+ this.#emitAutonomousTurn(active2, {
23021
23689
  status: "failed",
23022
- text: active.text,
23690
+ text: active2.text,
23023
23691
  error: new Error("Pi RPC autonomous Turn settled without displayable output")
23024
23692
  });
23025
23693
  } else {
23026
- this.#emitAutonomousTurn(active, { status: "succeeded", text: active.text });
23694
+ this.#emitAutonomousTurn(active2, { status: "succeeded", text: active2.text });
23027
23695
  }
23028
23696
  this.#drainDeferredRunFrames();
23029
23697
  return;
23030
23698
  }
23031
- if (active.cancellation === "accepted") {
23032
- active.resolve({ text: active.text, cancelled: true });
23033
- } else if (active.failure) {
23034
- active.reject(active.failure);
23035
- } else if (active.text.trim().length === 0 && !active.sawTool) {
23036
- active.reject(new Error("Pi RPC settled without displayable output"));
23699
+ if (active2.cancellation === "accepted") {
23700
+ active2.resolve({ text: active2.text, cancelled: true });
23701
+ } else if (active2.failure) {
23702
+ active2.reject(active2.failure);
23703
+ } else if (active2.text.trim().length === 0 && !active2.sawTool) {
23704
+ active2.reject(new Error("Pi RPC settled without displayable output"));
23037
23705
  } else {
23038
- active.resolve({ text: active.text, cancelled: false });
23706
+ active2.resolve({ text: active2.text, cancelled: false });
23039
23707
  }
23040
23708
  this.#drainDeferredRunFrames();
23041
23709
  }
23042
- #emitContent(active, reasoning, delta) {
23710
+ #emitContent(active2, reasoning, delta) {
23043
23711
  if (delta.length === 0)
23044
23712
  return;
23045
- const messageId = active.assistantMessageId;
23713
+ const messageId = active2.assistantMessageId;
23046
23714
  if (messageId === null)
23047
23715
  throw new Error("Pi content arrived outside an Assistant message");
23048
23716
  if (reasoning) {
23049
- active.reasoningMessageOpen = true;
23050
- active.sawStreamedMessageReasoning = true;
23717
+ active2.reasoningMessageOpen = true;
23718
+ active2.sawStreamedMessageReasoning = true;
23051
23719
  } else {
23052
- active.text += delta;
23053
- active.sawStreamedMessageText = true;
23720
+ active2.text += delta;
23721
+ active2.sawStreamedMessageText = true;
23054
23722
  }
23055
- active.onEvent({
23723
+ active2.onEvent({
23056
23724
  type: reasoning ? "reasoning.delta" : "text.delta",
23057
23725
  messageId,
23058
- ...nativeMessageIdentity(active),
23726
+ ...nativeMessageIdentity(active2),
23059
23727
  delta
23060
23728
  });
23061
23729
  }
23062
- #startAssistantMessage(active, value) {
23063
- if (active.origin === "autonomous" && !active.autonomousMessage && isRecord9(value))
23064
- active.autonomousMessage = value;
23065
- if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
23066
- active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
23730
+ #startAssistantMessage(active2, value) {
23731
+ if (active2.origin === "autonomous" && !active2.autonomousMessage && isRecord9(value))
23732
+ active2.autonomousMessage = value;
23733
+ if (active2.assistantMessageId !== null && active2.reasoningMessageOpen) {
23734
+ active2.onEvent({ type: "reasoning.completed", messageId: active2.assistantMessageId });
23067
23735
  }
23068
23736
  const nativeResponseId = assistantMessageId(value);
23069
23737
  const messageId = nativeResponseId ?? randomUUID6();
23070
- active.assistantMessageId = messageId;
23071
- active.assistantNativeMessageIdentity = piMessageIdentity(this.state.sessionId, value, this.#messageTimestampCounts);
23072
- active.textStream = new PiContentStream("text");
23073
- active.reasoningStream = new PiContentStream("reasoning");
23074
- active.sawStreamedMessageText = false;
23075
- active.sawStreamedMessageReasoning = false;
23076
- active.reasoningMessageOpen = false;
23738
+ active2.assistantMessageId = messageId;
23739
+ active2.assistantNativeMessageIdentity = piMessageIdentity(this.state.sessionId, value, this.#messageTimestampCounts);
23740
+ active2.textStream = new PiContentStream("text");
23741
+ active2.reasoningStream = new PiContentStream("reasoning");
23742
+ active2.sawStreamedMessageText = false;
23743
+ active2.sawStreamedMessageReasoning = false;
23744
+ active2.reasoningMessageOpen = false;
23077
23745
  return messageId;
23078
23746
  }
23079
- #ensureAssistantMessage(active, value) {
23080
- if (active.assistantMessageId === null)
23081
- return this.#startAssistantMessage(active, value);
23082
- if (!active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
23747
+ #ensureAssistantMessage(active2, value) {
23748
+ if (active2.assistantMessageId === null)
23749
+ return this.#startAssistantMessage(active2, value);
23750
+ if (!active2.sawStreamedMessageText && !active2.sawStreamedMessageReasoning) {
23083
23751
  const nativeResponseId = assistantMessageId(value);
23084
23752
  if (nativeResponseId) {
23085
- active.assistantMessageId = nativeResponseId;
23086
- active.assistantNativeMessageIdentity ??= { responseId: nativeResponseId };
23753
+ active2.assistantMessageId = nativeResponseId;
23754
+ active2.assistantNativeMessageIdentity ??= { responseId: nativeResponseId };
23087
23755
  }
23088
23756
  }
23089
- return active.assistantMessageId;
23757
+ return active2.assistantMessageId;
23090
23758
  }
23091
- #finalizeAssistantMessage(active, value) {
23759
+ #finalizeAssistantMessage(active2, value) {
23092
23760
  const finalText = assistantText(value);
23093
23761
  const finalReasoning = assistantReasoning(value);
23094
23762
  const failure = assistantFailure(value);
23095
23763
  const cacheHitRatePercent = optionalPiCacheHitRatePercent(value);
23096
23764
  if (finalText === null || finalReasoning === null || failure === void 0)
23097
23765
  return;
23098
- if (active.assistantMessageId === null && finalText === active.lastFinalizedMessageText && finalReasoning === active.lastFinalizedMessageReasoning && !active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
23766
+ if (active2.assistantMessageId === null && finalText === active2.lastFinalizedMessageText && finalReasoning === active2.lastFinalizedMessageReasoning && !active2.sawStreamedMessageText && !active2.sawStreamedMessageReasoning) {
23099
23767
  return;
23100
23768
  }
23101
- active.failure = failure;
23102
- if (active.origin === "autonomous" && piAssistantWasAborted(value)) {
23103
- active.nativeCancellationObserved = true;
23769
+ active2.failure = failure;
23770
+ if (active2.origin === "autonomous" && piAssistantWasAborted(value)) {
23771
+ active2.nativeCancellationObserved = true;
23104
23772
  }
23105
23773
  this.#latestCacheHitRatePercent = cacheHitRatePercent;
23106
- const messageId = this.#ensureAssistantMessage(active, value);
23774
+ const messageId = this.#ensureAssistantMessage(active2, value);
23107
23775
  const content = value.content;
23108
- if (failure === null || !active.sawStreamedMessageReasoning) {
23109
- this.#emitContent(active, true, active.reasoningStream.finalize(content.flatMap((part, index) => {
23776
+ if (failure === null || !active2.sawStreamedMessageReasoning) {
23777
+ this.#emitContent(active2, true, active2.reasoningStream.finalize(content.flatMap((part, index) => {
23110
23778
  const text4 = extractReasoningText(part);
23111
23779
  return text4 === null ? [] : [{ index, text: text4 }];
23112
23780
  })));
23113
23781
  }
23114
- if (active.reasoningMessageOpen && active.failure === null) {
23115
- active.onEvent({ type: "reasoning.completed", messageId });
23782
+ if (active2.reasoningMessageOpen && active2.failure === null) {
23783
+ active2.onEvent({ type: "reasoning.completed", messageId });
23116
23784
  }
23117
- if (failure === null || !active.sawStreamedMessageText) {
23118
- this.#emitContent(active, false, active.textStream.finalize(content.flatMap((part, index) => isRecord9(part) && part.type === "text" && typeof part.text === "string" ? [{ index, text: part.text }] : [])));
23785
+ if (failure === null || !active2.sawStreamedMessageText) {
23786
+ this.#emitContent(active2, false, active2.textStream.finalize(content.flatMap((part, index) => isRecord9(part) && part.type === "text" && typeof part.text === "string" ? [{ index, text: part.text }] : [])));
23119
23787
  }
23120
- active.assistantMessageId = null;
23121
- active.assistantNativeMessageIdentity = void 0;
23122
- active.sawStreamedMessageText = false;
23123
- active.sawStreamedMessageReasoning = false;
23124
- active.reasoningMessageOpen = false;
23125
- active.lastFinalizedMessageText = finalText;
23126
- active.lastFinalizedMessageReasoning = finalReasoning;
23788
+ active2.assistantMessageId = null;
23789
+ active2.assistantNativeMessageIdentity = void 0;
23790
+ active2.sawStreamedMessageText = false;
23791
+ active2.sawStreamedMessageReasoning = false;
23792
+ active2.reasoningMessageOpen = false;
23793
+ active2.lastFinalizedMessageText = finalText;
23794
+ active2.lastFinalizedMessageReasoning = finalReasoning;
23127
23795
  const phase = piAssistantPhase(value);
23128
- active.onEvent({ type: "message.completed", messageId, ...phase ? { phase } : {} });
23796
+ active2.onEvent({ type: "message.completed", messageId, ...phase ? { phase } : {} });
23129
23797
  }
23130
23798
  #write(value) {
23131
23799
  const child = this.#child;
@@ -23143,7 +23811,7 @@ var PiRpcSession = class {
23143
23811
  if (!child?.stdin.writable || this.#closed || this.#failed) {
23144
23812
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
23145
23813
  }
23146
- const id = `codexhost-${randomUUID6()}`;
23814
+ const id2 = `codexhost-${randomUUID6()}`;
23147
23815
  return new Promise((resolve, reject) => {
23148
23816
  const pending = {
23149
23817
  command: type,
@@ -23154,33 +23822,33 @@ var PiRpcSession = class {
23154
23822
  reject,
23155
23823
  timeout: null
23156
23824
  };
23157
- this.#pending.set(id, pending);
23158
- this.#armCommandTimeout(id, pending);
23159
- const frame = Buffer.from(`${JSON.stringify({ id, type, ...payload })}
23825
+ this.#pending.set(id2, pending);
23826
+ this.#armCommandTimeout(id2, pending);
23827
+ const frame = Buffer.from(`${JSON.stringify({ id: id2, type, ...payload })}
23160
23828
  `, "utf8");
23161
23829
  child.stdin.write(frame, (error51) => {
23162
23830
  if (error51) {
23163
23831
  if (pending.timeout)
23164
23832
  clearTimeout(pending.timeout);
23165
- this.#pending.delete(id);
23833
+ this.#pending.delete(id2);
23166
23834
  reject(error51);
23167
23835
  }
23168
23836
  });
23169
23837
  });
23170
23838
  }
23171
- #armCommandTimeout(id, pending) {
23172
- if (pending.timeout || this.#pending.get(id) !== pending || (pending.command === "prompt" || pending.command === "compact") && this.#compactionActive) {
23839
+ #armCommandTimeout(id2, pending) {
23840
+ if (pending.timeout || this.#pending.get(id2) !== pending || (pending.command === "prompt" || pending.command === "compact") && this.#compactionActive) {
23173
23841
  return;
23174
23842
  }
23175
23843
  pending.timeout = setTimeout(() => {
23176
- if (this.#pending.get(id) !== pending)
23844
+ if (this.#pending.get(id2) !== pending)
23177
23845
  return;
23178
23846
  pending.timeout = null;
23179
23847
  const error51 = new Error(`Pi RPC '${pending.command}' command timed out`);
23180
23848
  if (pending.command !== "prompt") {
23181
- this.#pending.delete(id);
23849
+ this.#pending.delete(id2);
23182
23850
  if (READ_ONLY_COMMANDS.has(pending.command)) {
23183
- this.#expired.add(id);
23851
+ this.#expired.add(id2);
23184
23852
  if (this.#expired.size > MAX_EXPIRED_IDS) {
23185
23853
  this.#expired.delete(this.#expired.values().next().value);
23186
23854
  }
@@ -23211,12 +23879,12 @@ var PiRpcSession = class {
23211
23879
  this.#rejectAll(finalFault);
23212
23880
  this.#options.onFault?.(finalFault);
23213
23881
  }
23214
- #closeInteractions(active, reason) {
23215
- for (const [requestId, pending] of active.interactions) {
23216
- active.interactions.delete(requestId);
23882
+ #closeInteractions(active2, reason) {
23883
+ for (const [requestId, pending] of active2.interactions) {
23884
+ active2.interactions.delete(requestId);
23217
23885
  if (pending.timeout)
23218
23886
  clearTimeout(pending.timeout);
23219
- active.onEvent({
23887
+ active2.onEvent({
23220
23888
  type: "interaction.closed",
23221
23889
  requestId,
23222
23890
  reason
@@ -23224,17 +23892,17 @@ var PiRpcSession = class {
23224
23892
  }
23225
23893
  }
23226
23894
  #rejectActiveTurn(error51) {
23227
- const active = this.#activeTurn;
23228
- if (!active)
23895
+ const active2 = this.#activeTurn;
23896
+ if (!active2)
23229
23897
  return;
23230
- if (active.cancellationTimeout)
23231
- clearTimeout(active.cancellationTimeout);
23232
- this.#closeInteractions(active, "cancelled");
23898
+ if (active2.cancellationTimeout)
23899
+ clearTimeout(active2.cancellationTimeout);
23900
+ this.#closeInteractions(active2, "cancelled");
23233
23901
  this.#activeTurn = null;
23234
- if (active.origin === "autonomous") {
23235
- this.#emitAutonomousTurn(active, { status: "failed", text: active.text, error: error51 });
23902
+ if (active2.origin === "autonomous") {
23903
+ this.#emitAutonomousTurn(active2, { status: "failed", text: active2.text, error: error51 });
23236
23904
  } else {
23237
- active.reject(error51);
23905
+ active2.reject(error51);
23238
23906
  }
23239
23907
  this.#drainDeferredRunFrames();
23240
23908
  }
@@ -23335,12 +24003,16 @@ function nativeModelFromState(state2) {
23335
24003
  }
23336
24004
  return { provider: state2.provider, id: state2.modelId };
23337
24005
  }
23338
- function effectiveModelFromState(state2) {
23339
- const model2 = nativeModelFromState(state2);
23340
- return model2 ? encodePiModelRef({ ...model2, ...state2.fast ? { fast: true } : {} }) : void 0;
24006
+ function livePiModelIndex(models, state2) {
24007
+ const current = nativeModelFromState(state2);
24008
+ return createPiModelIndex(current ? [...models, current] : models);
23341
24009
  }
23342
- function harnessStateFromPi(state2, thinkingLevels) {
23343
- const effectiveModel = effectiveModelFromState(state2);
24010
+ async function isFastSupported(model2, models, transport) {
24011
+ return models.some((entry) => samePiModel(entry, model2) && supportsPiFastModel(entry)) && await transport.supportsFastMode?.() === true;
24012
+ }
24013
+ function harnessStateFromPi(state2, thinkingLevels, index) {
24014
+ const model2 = nativeModelFromState(state2);
24015
+ const effectiveModel = model2 ? index.ref({ ...model2, ...state2.fast ? { fast: true } : {} }) : void 0;
23344
24016
  const availableThinkingOptions = thinkingLevels ? normalizePiThinkingOptions(thinkingLevels) : void 0;
23345
24017
  if (availableThinkingOptions && (!state2.thinkingLevel || !thinkingLevels?.includes(state2.thinkingLevel))) {
23346
24018
  throw new PiRpcFaultError("protocolError", "Pi effective Thinking level is absent from its available levels");
@@ -23419,7 +24091,7 @@ var PiHarnessSession = class {
23419
24091
  #requestedModel;
23420
24092
  #requestedThinkingOptionId;
23421
24093
  #toolOutputLimit;
23422
- #isFastSupported;
24094
+ #modelIndex;
23423
24095
  #acceptingTurn = false;
23424
24096
  #active = null;
23425
24097
  #closePromise = null;
@@ -23443,7 +24115,6 @@ var PiHarnessSession = class {
23443
24115
  this.#requestedModel = options.model;
23444
24116
  this.#requestedThinkingOptionId = options.thinkingOptionId;
23445
24117
  this.#toolOutputLimit = options.toolOutputLimit;
23446
- this.#isFastSupported = options.isFastSupported;
23447
24118
  this.capabilities = ((session) => ({
23448
24119
  configuration: {
23449
24120
  selectModel: true,
@@ -23464,7 +24135,8 @@ var PiHarnessSession = class {
23464
24135
  execute: (command) => this.#executeHarnessCommand(command)
23465
24136
  };
23466
24137
  this.#transport = options.startedTransport ?? null;
23467
- this.initialState = options.startedTransport ? harnessStateFromPi(options.startedTransport.state, options.startedThinkingLevels ?? null) : {};
24138
+ this.#modelIndex = this.#transport ? livePiModelIndex(options.startedModels ?? [], this.#transport.state) : createPiModelIndex([]);
24139
+ this.initialState = this.#transport ? harnessStateFromPi(this.#transport.state, options.startedThinkingLevels ?? null, this.#modelIndex) : {};
23468
24140
  this.initialUsage = options.initialUsage ?? null;
23469
24141
  this.#usage = this.initialUsage;
23470
24142
  this.#state = this.initialState;
@@ -23476,8 +24148,8 @@ var PiHarnessSession = class {
23476
24148
  if (this.#transport)
23477
24149
  this.#bindAutonomousTurnHandler(this.#transport);
23478
24150
  }
23479
- ownsNativeSession(id) {
23480
- return this.#transport?.state.sessionId === id;
24151
+ ownsNativeSession(id2) {
24152
+ return this.#transport?.state.sessionId === id2;
23481
24153
  }
23482
24154
  async readSubagentHistory(cwd) {
23483
24155
  if (this.#phase !== "open" || path17.resolve(cwd) !== path17.resolve(this.#cwd)) {
@@ -23485,28 +24157,28 @@ var PiHarnessSession = class {
23485
24157
  }
23486
24158
  return (await this.#ensureTransport()).getEntries();
23487
24159
  }
23488
- async readGotgenesChild(id, cwd) {
24160
+ async readGotgenesChild(id2, cwd) {
23489
24161
  const history = await this.readSubagentHistory(cwd);
23490
24162
  const transport = this.#transport;
23491
24163
  if (!transport)
23492
24164
  throw new Error("Pi parent Session is closed");
23493
- return readGotgenesChild(history, transport.state.sessionId, id, this.#subagents.gotgenes.records.get(id));
24165
+ return readGotgenesChild(history, transport.state.sessionId, id2, this.#subagents.gotgenes.records.get(id2));
23494
24166
  }
23495
- async inspectSubagent(id, cwd) {
24167
+ async inspectSubagent(id2, cwd) {
23496
24168
  if (this.#phase !== "open" || path17.resolve(cwd) !== path17.resolve(this.#cwd)) {
23497
24169
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
23498
24170
  }
23499
24171
  const transport = await this.#ensureTransport();
23500
24172
  if (!transport.inspectSubagent)
23501
24173
  throw new Error("Pi transport does not support Subagent inspection");
23502
- return transport.inspectSubagent(id);
24174
+ return transport.inspectSubagent(id2);
23503
24175
  }
23504
24176
  handleTransportFault(error51) {
23505
24177
  queueMicrotask(() => this.#fault(error51));
23506
24178
  }
23507
24179
  #subagentConfiguration() {
23508
24180
  const state2 = this.#state;
23509
- const model2 = state2.effectiveModel ? decodePiModelRef(state2.effectiveModel).id : void 0;
24181
+ const model2 = this.#transport?.state.modelId;
23510
24182
  return {
23511
24183
  ...model2 ? { model: model2 } : {},
23512
24184
  ...state2.effectiveThinkingOptionId ? { reasoningEffort: state2.effectiveThinkingOptionId } : {}
@@ -23533,13 +24205,15 @@ var PiHarnessSession = class {
23533
24205
  try {
23534
24206
  const transport = await this.#ensureTransport();
23535
24207
  const history = await transport.getEntries();
23536
- await restorePiSubagents(history, transport.state.sessionId, this.#subagents);
24208
+ const { sessionId, sessionFile } = transport.state;
24209
+ await restorePiSubagents(history, new Set(sessionFile ? [sessionId, sessionFile] : [sessionId]), this.#subagents);
23537
24210
  return {
23538
24211
  ok: true,
23539
24212
  value: {
23540
24213
  ...mapPiSnapshot(history, {
23541
24214
  sessionId: transport.state.sessionId,
23542
24215
  model: nativeModelForHistory(transport.state),
24216
+ models: this.#modelIndex.models,
23543
24217
  cwd: this.#cwd
23544
24218
  }, this.#subagents),
23545
24219
  state: this.#state
@@ -23626,7 +24300,7 @@ var PiHarnessSession = class {
23626
24300
  itemId: this.#newItemId(),
23627
24301
  text: ""
23628
24302
  };
23629
- const active = {
24303
+ const active2 = {
23630
24304
  command,
23631
24305
  agentItem: item,
23632
24306
  agentMessageId: null,
@@ -23646,14 +24320,14 @@ var PiHarnessSession = class {
23646
24320
  completion,
23647
24321
  resolveCompletion
23648
24322
  };
23649
- this.#active = active;
24323
+ this.#active = active2;
23650
24324
  this.#event({ type: "turn.started", turnId: command.turnId });
23651
24325
  this.#event({ type: "item.started", turnId: command.turnId, item });
23652
- void transport.runTurn(text4, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
23653
- active.settling = true;
24326
+ void transport.runTurn(text4, (event) => this.#handleTurnEvent(active2, event)).then(async (result) => {
24327
+ active2.settling = true;
23654
24328
  try {
23655
- const identity2 = await this.#completedTurnIdentity(active, transport);
23656
- this.#completeTurn(active, result.cancelled ? {
24329
+ const identity2 = await this.#completedTurnIdentity(active2, transport);
24330
+ this.#completeTurn(active2, result.cancelled ? {
23657
24331
  status: "cancelled",
23658
24332
  reason: "Cancelled by user",
23659
24333
  ...identity2.checkpoint ? { checkpoint: identity2.checkpoint } : {}
@@ -23662,19 +24336,19 @@ var PiHarnessSession = class {
23662
24336
  ...identity2.checkpoint ? { checkpoint: identity2.checkpoint } : {}
23663
24337
  }, result.text, identity2.nativeTurnRef);
23664
24338
  } catch (error51) {
23665
- this.#completeTurn(active, {
24339
+ this.#completeTurn(active2, {
23666
24340
  status: "failed",
23667
24341
  error: normalizedError(error51, "protocolError")
23668
24342
  });
23669
24343
  }
23670
24344
  }).catch(async (error51) => {
23671
- active.settling = true;
24345
+ active2.settling = true;
23672
24346
  let identity2;
23673
24347
  try {
23674
- identity2 = await this.#completedTurnIdentity(active, transport);
24348
+ identity2 = await this.#completedTurnIdentity(active2, transport);
23675
24349
  } catch {
23676
24350
  }
23677
- this.#completeTurn(active, active.cancellationRequested ? {
24351
+ this.#completeTurn(active2, active2.cancellationRequested ? {
23678
24352
  status: "cancelled",
23679
24353
  reason: "Cancelled by user",
23680
24354
  ...identity2?.checkpoint ? { checkpoint: identity2.checkpoint } : {}
@@ -23698,9 +24372,9 @@ var PiHarnessSession = class {
23698
24372
  return this.#closePromise;
23699
24373
  }
23700
24374
  async #respond(command) {
23701
- const active = this.#active;
23702
- const pending = active?.interactions.get(command.interactionId);
23703
- if (!active || !pending) {
24375
+ const active2 = this.#active;
24376
+ const pending = active2?.interactions.get(command.interactionId);
24377
+ if (!active2 || !pending) {
23704
24378
  return {
23705
24379
  ok: false,
23706
24380
  error: invalidState("Pi Interaction Response must reference a pending Question")
@@ -23775,9 +24449,12 @@ var PiHarnessSession = class {
23775
24449
  try {
23776
24450
  let requested;
23777
24451
  try {
23778
- requested = decodePiModelRef(command.model);
23779
- if (requested.fast && !await this.#isFastSupported(command.model, transport))
24452
+ const models = await transport.getAvailableModels();
24453
+ const index = livePiModelIndex(models, transport.state);
24454
+ requested = resolvePiModelRef(harnessModelRefSchema.parse(command.model), index);
24455
+ if (requested.fast && !await isFastSupported(requested, models, transport))
23780
24456
  throw new Error("Fast is unavailable for this Pi Model");
24457
+ this.#modelIndex = index;
23781
24458
  } catch (error51) {
23782
24459
  return { ok: false, error: normalizedError(error51, "invalidRequest") };
23783
24460
  }
@@ -23798,8 +24475,7 @@ var PiHarnessSession = class {
23798
24475
  return { ok: false, error: normalizedError(error51, "nativeFailure") };
23799
24476
  }
23800
24477
  const actual = nativeModelFromState(state2);
23801
- const nextModel = effectiveModelFromState(state2);
23802
- if (previousModel?.id !== nextModel?.id) {
24478
+ if (!sameHarnessModelRef(previousModel, this.#state.effectiveModel)) {
23803
24479
  this.#invalidateUsage();
23804
24480
  void this.#refreshUsage();
23805
24481
  }
@@ -23897,8 +24573,8 @@ var PiHarnessSession = class {
23897
24573
  }
23898
24574
  }
23899
24575
  #canSteerActiveTurn() {
23900
- const active = this.#active;
23901
- return Boolean(this.#phase === "open" && active && !active.cancellationRequested && active.acceptingSteers && active.tools.size > 0 && this.#transport);
24576
+ const active2 = this.#active;
24577
+ return Boolean(this.#phase === "open" && active2 && !active2.cancellationRequested && active2.acceptingSteers && active2.tools.size > 0 && this.#transport);
23902
24578
  }
23903
24579
  async #steer(command) {
23904
24580
  const text4 = command.input.map((input) => input.text).join("\n");
@@ -23912,17 +24588,17 @@ var PiHarnessSession = class {
23912
24588
  }
23913
24589
  };
23914
24590
  }
23915
- const active = this.#active;
24591
+ const active2 = this.#active;
23916
24592
  const transport = this.#transport;
23917
- if (!active || !transport || active.command.turnId !== command.turnId || !this.#canSteerActiveTurn()) {
24593
+ if (!active2 || !transport || active2.command.turnId !== command.turnId || !this.#canSteerActiveTurn()) {
23918
24594
  return { ok: false, error: invalidState("Pi Turn is not accepting native input") };
23919
24595
  }
23920
24596
  let accepted;
23921
24597
  try {
23922
24598
  accepted = transport.steer(text4).then(() => {
23923
- active.acceptedSteerCount += 1;
24599
+ active2.acceptedSteerCount += 1;
23924
24600
  });
23925
- active.pendingSteers.add(accepted);
24601
+ active2.pendingSteers.add(accepted);
23926
24602
  await accepted;
23927
24603
  return { ok: true, value: { accepted: true } };
23928
24604
  } catch (error51) {
@@ -23930,40 +24606,40 @@ var PiHarnessSession = class {
23930
24606
  return { ok: false, error: invalidState(error51.message) };
23931
24607
  }
23932
24608
  if (error51 instanceof PiRpcSteerTargetEndedError)
23933
- active.steerFailure = error51;
24609
+ active2.steerFailure = error51;
23934
24610
  throw error51;
23935
24611
  } finally {
23936
24612
  if (accepted)
23937
- active.pendingSteers.delete(accepted);
24613
+ active2.pendingSteers.delete(accepted);
23938
24614
  }
23939
24615
  }
23940
24616
  async #cancel(command) {
23941
- const active = this.#active;
23942
- if (!active || active.command.turnId !== command.turnId) {
24617
+ const active2 = this.#active;
24618
+ if (!active2 || active2.command.turnId !== command.turnId) {
23943
24619
  return {
23944
24620
  ok: false,
23945
24621
  error: invalidState("Pi Turn Cancel must reference the active Turn")
23946
24622
  };
23947
24623
  }
23948
- if (active.settling) {
24624
+ if (active2.settling) {
23949
24625
  return {
23950
24626
  ok: false,
23951
24627
  error: invalidState("Pi Turn has finished native execution and is recording its completion")
23952
24628
  };
23953
24629
  }
23954
- if (active.cancellationRequested) {
24630
+ if (active2.cancellationRequested) {
23955
24631
  return { ok: true, value: { cancellationRequested: true } };
23956
24632
  }
23957
24633
  const transport = this.#transport;
23958
24634
  if (!transport)
23959
24635
  return { ok: false, error: invalidState("Pi transport is unavailable") };
23960
- active.cancellationRequested = true;
24636
+ active2.cancellationRequested = true;
23961
24637
  try {
23962
24638
  await transport.abort();
23963
24639
  return { ok: true, value: { cancellationRequested: true } };
23964
24640
  } catch (error51) {
23965
24641
  const normalized = normalizedError(error51, "nativeFailure");
23966
- if (this.#active === active) {
24642
+ if (this.#active === active2) {
23967
24643
  this.#fault(new PiAdapterFaultError(normalized));
23968
24644
  void transport.close().catch(() => void 0);
23969
24645
  }
@@ -24054,7 +24730,7 @@ var PiHarnessSession = class {
24054
24730
  const completion = new Promise((resolve) => {
24055
24731
  resolveCompletion = resolve;
24056
24732
  });
24057
- const active = {
24733
+ const active2 = {
24058
24734
  command: turnCommand,
24059
24735
  agentItem: null,
24060
24736
  agentMessageId: null,
@@ -24074,18 +24750,18 @@ var PiHarnessSession = class {
24074
24750
  completion,
24075
24751
  resolveCompletion
24076
24752
  };
24077
- this.#active = active;
24753
+ this.#active = active2;
24078
24754
  this.#event({ type: "turn.started", turnId: command.turnId });
24079
- void transport.compact(customInstructions, (event) => this.#handleTurnEvent(active, event)).then((result) => {
24755
+ void transport.compact(customInstructions, (event) => this.#handleTurnEvent(active2, event)).then((result) => {
24080
24756
  if (result.outcome === "succeeded") {
24081
- this.#completeTurn(active, { status: "succeeded" });
24757
+ this.#completeTurn(active2, { status: "succeeded" });
24082
24758
  } else if (result.outcome === "cancelled") {
24083
- this.#completeTurn(active, {
24759
+ this.#completeTurn(active2, {
24084
24760
  status: "cancelled",
24085
24761
  reason: "Context compaction was cancelled"
24086
24762
  });
24087
24763
  } else {
24088
- this.#completeTurn(active, {
24764
+ this.#completeTurn(active2, {
24089
24765
  status: "failed",
24090
24766
  error: {
24091
24767
  code: "nativeFailure",
@@ -24095,7 +24771,7 @@ var PiHarnessSession = class {
24095
24771
  });
24096
24772
  }
24097
24773
  }).catch((error51) => {
24098
- this.#completeTurn(active, {
24774
+ this.#completeTurn(active2, {
24099
24775
  status: "failed",
24100
24776
  error: normalizedError(error51, "nativeFailure")
24101
24777
  });
@@ -24121,9 +24797,14 @@ var PiHarnessSession = class {
24121
24797
  if (this.#phase !== "open")
24122
24798
  throw new Error("Pi Session closed during startup");
24123
24799
  let state2 = transport.state;
24800
+ const models = await transport.getAvailableModels();
24801
+ this.#modelIndex = livePiModelIndex(models, state2);
24124
24802
  let thinkingLevels = await transport.getAvailableThinkingLevels();
24125
24803
  if (this.#requestedModel) {
24126
- const requested = decodePiModelRef(this.#requestedModel);
24804
+ const requested = resolvePiModelRef(this.#requestedModel, this.#modelIndex);
24805
+ if (requested.fast && !await isFastSupported(requested, models, transport)) {
24806
+ throw new Error("Fast is unavailable for this Pi Model");
24807
+ }
24127
24808
  const current = nativeModelFromState(state2);
24128
24809
  if (!samePiModel(current, requested))
24129
24810
  state2 = await transport.selectModel(requested);
@@ -24133,8 +24814,8 @@ var PiHarnessSession = class {
24133
24814
  throw new Error("Pi did not activate the requested create Model");
24134
24815
  }
24135
24816
  if (requested.fast) {
24136
- if (!await this.#isFastSupported(this.#requestedModel, transport) || !transport.selectFastMode)
24137
- throw new Error("Fast is unavailable for this Pi Model");
24817
+ if (!transport.selectFastMode)
24818
+ throw new Error("Pi Fast extension is unavailable");
24138
24819
  state2 = await transport.selectFastMode(true);
24139
24820
  }
24140
24821
  }
@@ -24262,8 +24943,8 @@ var PiHarnessSession = class {
24262
24943
  this.#startAutonomousHostTurn(update.runId);
24263
24944
  return;
24264
24945
  }
24265
- const active = this.#active;
24266
- if (!active || active.autonomousRunId !== update.runId || update.type === "started") {
24946
+ const active2 = this.#active;
24947
+ if (!active2 || active2.autonomousRunId !== update.runId || update.type === "started") {
24267
24948
  this.#fault(new PiAdapterFaultError({
24268
24949
  code: "protocolError",
24269
24950
  message: "Pi autonomous event has no matching active run",
@@ -24272,10 +24953,10 @@ var PiHarnessSession = class {
24272
24953
  return;
24273
24954
  }
24274
24955
  if (update.type === "event")
24275
- this.#handleTurnEvent(active, update.event);
24956
+ this.#handleTurnEvent(active2, update.event);
24276
24957
  else {
24277
- active.settling = true;
24278
- this.#finishAutonomousHostTurn(transport, active, update.turn);
24958
+ active2.settling = true;
24959
+ this.#finishAutonomousHostTurn(transport, active2, update.turn);
24279
24960
  }
24280
24961
  }
24281
24962
  #handleAutonomousTurn(transport, turn) {
@@ -24308,8 +24989,8 @@ var PiHarnessSession = class {
24308
24989
  this.#pendingAutonomousTurns.push({ transport, turn });
24309
24990
  return;
24310
24991
  }
24311
- const active = this.#startAutonomousHostTurn();
24312
- this.#finishAutonomousHostTurn(transport, active, turn);
24992
+ const active2 = this.#startAutonomousHostTurn();
24993
+ this.#finishAutonomousHostTurn(transport, active2, turn);
24313
24994
  }
24314
24995
  #startAutonomousHostTurn(runId) {
24315
24996
  const turnId = hostTurnIdSchema.parse(randomUUID7());
@@ -24322,7 +25003,7 @@ var PiHarnessSession = class {
24322
25003
  itemId: this.#newItemId(),
24323
25004
  text: ""
24324
25005
  };
24325
- const active = {
25006
+ const active2 = {
24326
25007
  command: { type: "turn.start", turnId, input: [] },
24327
25008
  ...runId ? { autonomousRunId: runId } : {},
24328
25009
  agentItem: item,
@@ -24343,13 +25024,13 @@ var PiHarnessSession = class {
24343
25024
  completion,
24344
25025
  resolveCompletion
24345
25026
  };
24346
- this.#active = active;
25027
+ this.#active = active2;
24347
25028
  this.#event({ type: "turn.autonomous.started", turnId, input: [] });
24348
25029
  this.#event({ type: "turn.started", turnId });
24349
25030
  this.#event({ type: "item.started", turnId, item });
24350
- return active;
25031
+ return active2;
24351
25032
  }
24352
- #finishAutonomousHostTurn(transport, active, turn) {
25033
+ #finishAutonomousHostTurn(transport, active2, turn) {
24353
25034
  const nativeTurnRef = turn.nativeTurnKey ? nativeTurnRefSchema.parse({
24354
25035
  harnessId: this.harnessId,
24355
25036
  nativeSessionId: transport.state.sessionId,
@@ -24364,19 +25045,19 @@ var PiHarnessSession = class {
24364
25045
  }) : void 0;
24365
25046
  try {
24366
25047
  for (const event of turn.events)
24367
- this.#handleTurnEvent(active, event);
25048
+ this.#handleTurnEvent(active2, event);
24368
25049
  if (turn.result.status === "succeeded") {
24369
25050
  if (!nativeTurnRef)
24370
25051
  throw new Error("Pi autonomous Turn has no native identity");
24371
- this.#completeTurn(active, { status: "succeeded", ...checkpoint ? { checkpoint } : {} }, turn.result.text, nativeTurnRef);
25052
+ this.#completeTurn(active2, { status: "succeeded", ...checkpoint ? { checkpoint } : {} }, turn.result.text, nativeTurnRef);
24372
25053
  } else if (turn.result.status === "cancelled") {
24373
- this.#completeTurn(active, {
25054
+ this.#completeTurn(active2, {
24374
25055
  status: "cancelled",
24375
25056
  reason: turn.result.reason,
24376
25057
  ...checkpoint ? { checkpoint } : {}
24377
25058
  }, turn.result.text, nativeTurnRef);
24378
25059
  } else {
24379
- this.#completeTurn(active, {
25060
+ this.#completeTurn(active2, {
24380
25061
  status: "failed",
24381
25062
  error: normalizedError(turn.result.error, "nativeFailure"),
24382
25063
  ...checkpoint ? { checkpoint } : {}
@@ -24384,14 +25065,14 @@ var PiHarnessSession = class {
24384
25065
  }
24385
25066
  } catch (error51) {
24386
25067
  const normalized = normalizedError(error51, "protocolError");
24387
- if (this.#active === active) {
24388
- this.#completeTurn(active, { status: "failed", error: normalized }, void 0, nativeTurnRef);
25068
+ if (this.#active === active2) {
25069
+ this.#completeTurn(active2, { status: "failed", error: normalized }, void 0, nativeTurnRef);
24389
25070
  }
24390
25071
  this.#fault(new PiAdapterFaultError(normalized));
24391
25072
  }
24392
25073
  }
24393
25074
  #publishTransportState(state2, thinkingLevels) {
24394
- this.#state = harnessStateFromPi(state2, thinkingLevels);
25075
+ this.#state = harnessStateFromPi(state2, thinkingLevels, this.#modelIndex);
24395
25076
  this.#event({ type: "session.state.changed", state: this.#state });
24396
25077
  }
24397
25078
  #invalidateUsage() {
@@ -24427,80 +25108,80 @@ var PiHarnessSession = class {
24427
25108
  ...observedForTurnId ? { observedForTurnId } : {}
24428
25109
  });
24429
25110
  }
24430
- #handleTurnEvent(active, event) {
24431
- if (this.#active !== active || this.#phase === "closed" || this.#phase === "faulted")
25111
+ #handleTurnEvent(active2, event) {
25112
+ if (this.#active !== active2 || this.#phase === "closed" || this.#phase === "faulted")
24432
25113
  return;
24433
25114
  switch (event.type) {
24434
25115
  case "progress.message": {
24435
- if (active.progressItems.has(event.itemId))
25116
+ if (active2.progressItems.has(event.itemId))
24436
25117
  return;
24437
- active.progressItems.add(event.itemId);
25118
+ active2.progressItems.add(event.itemId);
24438
25119
  const item = {
24439
25120
  type: "agentMessage",
24440
25121
  itemId: event.itemId,
24441
25122
  text: event.text,
24442
25123
  phase: "commentary"
24443
25124
  };
24444
- this.#event({ type: "item.started", turnId: active.command.turnId, item });
24445
- this.#completeItem(active, item, { status: "succeeded" });
25125
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item });
25126
+ this.#completeItem(active2, item, { status: "succeeded" });
24446
25127
  return;
24447
25128
  }
24448
25129
  case "text.delta":
24449
- this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
24450
- active.sawAssistantMessage = true;
24451
- this.#appendText(active, event.delta);
25130
+ this.#activateAgentMessage(active2, event.messageId, event.nativeMessageIdentity);
25131
+ active2.sawAssistantMessage = true;
25132
+ this.#appendText(active2, event.delta);
24452
25133
  return;
24453
25134
  case "reasoning.delta":
24454
- this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
24455
- this.#appendReasoning(active, event.delta, event.nativeMessageIdentity);
25135
+ this.#activateAgentMessage(active2, event.messageId, event.nativeMessageIdentity);
25136
+ this.#appendReasoning(active2, event.delta, event.nativeMessageIdentity);
24456
25137
  return;
24457
25138
  case "reasoning.completed":
24458
- this.#completeReasoning(active, { status: "succeeded" });
25139
+ this.#completeReasoning(active2, { status: "succeeded" });
24459
25140
  return;
24460
25141
  case "message.completed":
24461
- if (event.phase && active.agentMessageId === event.messageId && active.agentItem)
24462
- active.agentItem = { ...active.agentItem, phase: event.phase };
24463
- void this.#refreshUsage(active.command.turnId);
25142
+ if (event.phase && active2.agentMessageId === event.messageId && active2.agentItem)
25143
+ active2.agentItem = { ...active2.agentItem, phase: event.phase };
25144
+ void this.#refreshUsage(active2.command.turnId);
24464
25145
  return;
24465
25146
  case "compaction.started":
24466
- this.#startCompaction(active);
25147
+ this.#startCompaction(active2);
24467
25148
  return;
24468
25149
  case "compaction.completed":
24469
- this.#completeCompaction(active, event);
25150
+ this.#completeCompaction(active2, event);
24470
25151
  return;
24471
25152
  case "interaction.requested":
24472
- this.#startInteraction(active, event.request);
25153
+ this.#startInteraction(active2, event.request);
24473
25154
  return;
24474
25155
  case "interaction.closed":
24475
- this.#closeInteraction(active, event.requestId, event.reason);
25156
+ this.#closeInteraction(active2, event.requestId, event.reason);
24476
25157
  return;
24477
25158
  case "tool.started":
24478
- this.#completeReasoning(active, { status: "succeeded" });
24479
- this.#completeAgentItem(active, { status: "succeeded" }, false);
24480
- this.#startTool(active, event);
25159
+ this.#completeReasoning(active2, { status: "succeeded" });
25160
+ this.#completeAgentItem(active2, { status: "succeeded" }, false);
25161
+ this.#startTool(active2, event);
24481
25162
  return;
24482
25163
  case "tool.updated":
24483
- this.#updateTool(active, event);
25164
+ this.#updateTool(active2, event);
24484
25165
  return;
24485
25166
  case "tool.completed":
24486
- this.#completeTool(active, event);
25167
+ this.#completeTool(active2, event);
24487
25168
  }
24488
25169
  }
24489
- #startCompaction(active) {
24490
- if (active.compactionItem)
25170
+ #startCompaction(active2) {
25171
+ if (active2.compactionItem)
24491
25172
  throw new Error("Pi Compaction started more than once");
24492
25173
  const item = {
24493
25174
  type: "contextCompaction",
24494
25175
  itemId: this.#newItemId()
24495
25176
  };
24496
- active.compactionItem = item;
24497
- this.#event({ type: "item.started", turnId: active.command.turnId, item });
25177
+ active2.compactionItem = item;
25178
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item });
24498
25179
  }
24499
- #completeCompaction(active, event) {
24500
- const item = active.compactionItem;
25180
+ #completeCompaction(active2, event) {
25181
+ const item = active2.compactionItem;
24501
25182
  if (!item)
24502
25183
  throw new Error("Pi Compaction completed without starting");
24503
- active.compactionItem = null;
25184
+ active2.compactionItem = null;
24504
25185
  const outcome = event.outcome === "succeeded" ? { status: "succeeded" } : event.outcome === "cancelled" ? { status: "cancelled", reason: "Context compaction was cancelled" } : {
24505
25186
  status: "failed",
24506
25187
  error: {
@@ -24509,12 +25190,12 @@ var PiHarnessSession = class {
24509
25190
  retryable: true
24510
25191
  }
24511
25192
  };
24512
- this.#completeItem(active, item, outcome);
25193
+ this.#completeItem(active2, item, outcome);
24513
25194
  if (event.outcome === "succeeded")
24514
- void this.#refreshUsage(active.command.turnId);
25195
+ void this.#refreshUsage(active2.command.turnId);
24515
25196
  }
24516
- #startInteraction(active, request) {
24517
- if (active.interactionByNativeId.has(request.requestId)) {
25197
+ #startInteraction(active2, request) {
25198
+ if (active2.interactionByNativeId.has(request.requestId)) {
24518
25199
  throw new Error("Pi Interaction started more than once");
24519
25200
  }
24520
25201
  const interactionId = hostInteractionIdSchema.parse(randomUUID7());
@@ -24547,113 +25228,113 @@ var PiHarnessSession = class {
24547
25228
  ...request.method === "input" && request.placeholder ? { placeholder: request.placeholder } : {},
24548
25229
  ...request.method === "editor" && request.prefill ? { prefill: request.prefill } : {}
24549
25230
  };
24550
- const associatedTool = active.tools.size === 1 ? [...active.tools.values()][0] : void 0;
25231
+ const associatedTool = active2.tools.size === 1 ? [...active2.tools.values()][0] : void 0;
24551
25232
  const interaction = {
24552
25233
  type: "question",
24553
25234
  interactionId,
24554
- turnId: active.command.turnId,
25235
+ turnId: active2.command.turnId,
24555
25236
  ...associatedTool?.item.type === "toolExecution" ? { itemId: associatedTool.item.itemId } : {},
24556
25237
  title: "Pi",
24557
25238
  questions: [question],
24558
25239
  ...request.timeoutMs !== void 0 ? { expiresAt: new Date(Date.now() + request.timeoutMs).toISOString() } : {}
24559
25240
  };
24560
- active.interactions.set(interactionId, { interaction, nativeRequest: request });
24561
- active.interactionByNativeId.set(request.requestId, interactionId);
25241
+ active2.interactions.set(interactionId, { interaction, nativeRequest: request });
25242
+ active2.interactionByNativeId.set(request.requestId, interactionId);
24562
25243
  this.#channel.emit({ kind: "interaction", interaction });
24563
25244
  }
24564
- #closeInteraction(active, nativeRequestId, reason) {
24565
- const interactionId = active.interactionByNativeId.get(nativeRequestId);
25245
+ #closeInteraction(active2, nativeRequestId, reason) {
25246
+ const interactionId = active2.interactionByNativeId.get(nativeRequestId);
24566
25247
  if (!interactionId)
24567
25248
  throw new Error("Pi Interaction close references an unknown request");
24568
- active.interactionByNativeId.delete(nativeRequestId);
24569
- active.interactions.delete(interactionId);
25249
+ active2.interactionByNativeId.delete(nativeRequestId);
25250
+ active2.interactions.delete(interactionId);
24570
25251
  this.#event({
24571
25252
  type: "interaction.closed",
24572
25253
  interactionId,
24573
- turnId: active.command.turnId,
25254
+ turnId: active2.command.turnId,
24574
25255
  reason
24575
25256
  });
24576
25257
  }
24577
- #activateAgentMessage(active, messageId, nativeMessageIdentity2) {
24578
- if (active.agentMessageId === messageId)
25258
+ #activateAgentMessage(active2, messageId, nativeMessageIdentity2) {
25259
+ if (active2.agentMessageId === messageId)
24579
25260
  return;
24580
25261
  const nativeItemId = piMessageItemId(nativeMessageIdentity2, "assistant");
24581
- if (nativeItemId && active.agentMessageId === null && active.agentItem?.text === "") {
24582
- this.#completeAgentItem(active, { status: "succeeded" }, true);
25262
+ if (nativeItemId && active2.agentMessageId === null && active2.agentItem?.text === "") {
25263
+ this.#completeAgentItem(active2, { status: "succeeded" }, true);
24583
25264
  }
24584
- if (active.agentMessageId !== null) {
24585
- this.#completeReasoning(active, { status: "succeeded" });
24586
- this.#completeAgentItem(active, { status: "succeeded" }, true);
25265
+ if (active2.agentMessageId !== null) {
25266
+ this.#completeReasoning(active2, { status: "succeeded" });
25267
+ this.#completeAgentItem(active2, { status: "succeeded" }, true);
24587
25268
  }
24588
- if (!active.agentItem) {
24589
- active.agentItem = {
25269
+ if (!active2.agentItem) {
25270
+ active2.agentItem = {
24590
25271
  type: "agentMessage",
24591
25272
  itemId: nativeItemId ?? this.#newItemId(),
24592
25273
  text: ""
24593
25274
  };
24594
25275
  this.#event({
24595
25276
  type: "item.started",
24596
- turnId: active.command.turnId,
24597
- item: active.agentItem
25277
+ turnId: active2.command.turnId,
25278
+ item: active2.agentItem
24598
25279
  });
24599
25280
  }
24600
- active.agentMessageId = messageId;
25281
+ active2.agentMessageId = messageId;
24601
25282
  }
24602
- #appendText(active, text4) {
24603
- if (active.agentMessageId === null || !active.agentItem) {
25283
+ #appendText(active2, text4) {
25284
+ if (active2.agentMessageId === null || !active2.agentItem) {
24604
25285
  throw new Error("Pi Assistant text arrived outside an active message");
24605
25286
  }
24606
- active.agentItem = { ...active.agentItem, text: active.agentItem.text + text4 };
25287
+ active2.agentItem = { ...active2.agentItem, text: active2.agentItem.text + text4 };
24607
25288
  this.#event({
24608
25289
  type: "item.updated",
24609
- turnId: active.command.turnId,
24610
- itemId: active.agentItem.itemId,
25290
+ turnId: active2.command.turnId,
25291
+ itemId: active2.agentItem.itemId,
24611
25292
  update: { type: "text.append", text: text4 }
24612
25293
  });
24613
25294
  }
24614
- #completeAgentItem(active, outcome, completeEmpty) {
24615
- active.agentMessageId = null;
24616
- const item = active.agentItem;
25295
+ #completeAgentItem(active2, outcome, completeEmpty) {
25296
+ active2.agentMessageId = null;
25297
+ const item = active2.agentItem;
24617
25298
  if (!item || !completeEmpty && item.text.length === 0)
24618
25299
  return;
24619
- active.agentItem = null;
24620
- this.#completeItem(active, item, outcome);
25300
+ active2.agentItem = null;
25301
+ this.#completeItem(active2, item, outcome);
24621
25302
  }
24622
- #appendReasoning(active, text4, nativeMessageIdentity2) {
25303
+ #appendReasoning(active2, text4, nativeMessageIdentity2) {
24623
25304
  if (text4.length === 0)
24624
25305
  return;
24625
- if (!active.reasoningItem) {
24626
- active.reasoningItem = {
25306
+ if (!active2.reasoningItem) {
25307
+ active2.reasoningItem = {
24627
25308
  type: "reasoning",
24628
25309
  itemId: piMessageItemId(nativeMessageIdentity2, "reasoning") ?? this.#newItemId(),
24629
25310
  text: ""
24630
25311
  };
24631
25312
  this.#event({
24632
25313
  type: "item.started",
24633
- turnId: active.command.turnId,
24634
- item: active.reasoningItem
25314
+ turnId: active2.command.turnId,
25315
+ item: active2.reasoningItem
24635
25316
  });
24636
25317
  }
24637
- active.reasoningItem = {
24638
- ...active.reasoningItem,
24639
- text: active.reasoningItem.text + text4
25318
+ active2.reasoningItem = {
25319
+ ...active2.reasoningItem,
25320
+ text: active2.reasoningItem.text + text4
24640
25321
  };
24641
25322
  this.#event({
24642
25323
  type: "item.updated",
24643
- turnId: active.command.turnId,
24644
- itemId: active.reasoningItem.itemId,
25324
+ turnId: active2.command.turnId,
25325
+ itemId: active2.reasoningItem.itemId,
24645
25326
  update: { type: "text.append", text: text4 }
24646
25327
  });
24647
25328
  }
24648
- #completeReasoning(active, outcome) {
24649
- const item = active.reasoningItem;
25329
+ #completeReasoning(active2, outcome) {
25330
+ const item = active2.reasoningItem;
24650
25331
  if (!item)
24651
25332
  return;
24652
- active.reasoningItem = null;
24653
- this.#completeItem(active, item, outcome);
25333
+ active2.reasoningItem = null;
25334
+ this.#completeItem(active2, item, outcome);
24654
25335
  }
24655
- #startTool(active, event) {
24656
- if (active.tools.has(event.callId))
25336
+ #startTool(active2, event) {
25337
+ if (active2.tools.has(event.callId))
24657
25338
  throw new Error("Pi Tool started more than once");
24658
25339
  const shell = piToolCommand(event.toolName, event.arguments);
24659
25340
  const item = shell ? {
@@ -24667,18 +25348,18 @@ var PiHarnessSession = class {
24667
25348
  toolName: event.toolName,
24668
25349
  arguments: event.arguments
24669
25350
  };
24670
- active.tools.set(event.callId, {
25351
+ active2.tools.set(event.callId, {
24671
25352
  item,
24672
25353
  nativeName: event.toolName,
24673
25354
  startedAtMs: Date.now()
24674
25355
  });
24675
- this.#event({ type: "item.started", turnId: active.command.turnId, item });
25356
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item });
24676
25357
  }
24677
- #updateTool(active, event) {
24678
- const tool = active.tools.get(event.callId);
25358
+ #updateTool(active2, event) {
25359
+ const tool = active2.tools.get(event.callId);
24679
25360
  if (!tool)
24680
25361
  throw new Error("Pi Tool update references an unknown Tool Call");
24681
- this.#subagents.start(active.command.turnId, tool.nativeName, event.output, this.#newItemId(), event.callId);
25362
+ this.#subagents.start(active2.command.turnId, tool.nativeName, event.output, this.#newItemId(), event.callId);
24682
25363
  const output = boundedOutput(event.output, this.#toolOutputLimit);
24683
25364
  if (!output)
24684
25365
  return;
@@ -24695,7 +25376,7 @@ var PiHarnessSession = class {
24695
25376
  if (delta.length > 0) {
24696
25377
  this.#event({
24697
25378
  type: "item.updated",
24698
- turnId: active.command.turnId,
25379
+ turnId: active2.command.turnId,
24699
25380
  itemId: tool.item.itemId,
24700
25381
  update: { type: "output.append", text: delta }
24701
25382
  });
@@ -24706,17 +25387,17 @@ var PiHarnessSession = class {
24706
25387
  tool.item = { ...tool.item, output };
24707
25388
  this.#event({
24708
25389
  type: "item.updated",
24709
- turnId: active.command.turnId,
25390
+ turnId: active2.command.turnId,
24710
25391
  itemId: tool.item.itemId,
24711
25392
  update: { type: "output.replace", output }
24712
25393
  });
24713
25394
  }
24714
- #completeTool(active, event) {
24715
- const tool = active.tools.get(event.callId);
25395
+ #completeTool(active2, event) {
25396
+ const tool = active2.tools.get(event.callId);
24716
25397
  if (!tool || tool.nativeName !== event.toolName) {
24717
25398
  throw new Error("Pi Tool completion references an unknown Tool Call");
24718
25399
  }
24719
- active.tools.delete(event.callId);
25400
+ active2.tools.delete(event.callId);
24720
25401
  const durationMs = Math.max(0, Date.now() - tool.startedAtMs);
24721
25402
  const output = boundedOutput(event.result, this.#toolOutputLimit);
24722
25403
  if (tool.item.type === "commandExecution") {
@@ -24733,9 +25414,9 @@ var PiHarnessSession = class {
24733
25414
  } else {
24734
25415
  tool.item = { ...tool.item, ...output ? { output } : {}, durationMs };
24735
25416
  }
24736
- const outcome = active.cancellationRequested ? { status: "cancelled", reason: "Cancelled by user" } : event.isError ? { status: "failed", error: toolFailure(event.toolName) } : { status: "succeeded" };
24737
- this.#completeItem(active, tool.item, outcome);
24738
- this.#subagents.start(active.command.turnId, event.toolName, event.result, this.#newItemId(), event.callId);
25417
+ const outcome = active2.cancellationRequested ? { status: "cancelled", reason: "Cancelled by user" } : event.isError ? { status: "failed", error: toolFailure(event.toolName) } : { status: "succeeded" };
25418
+ this.#completeItem(active2, tool.item, outcome);
25419
+ this.#subagents.start(active2.command.turnId, event.toolName, event.result, this.#newItemId(), event.callId);
24739
25420
  if (!event.isError) {
24740
25421
  try {
24741
25422
  const args = tool.item.type === "toolExecution" ? tool.item.arguments : {};
@@ -24747,41 +25428,41 @@ var PiHarnessSession = class {
24747
25428
  sourceItemIds: [tool.item.itemId],
24748
25429
  changes
24749
25430
  };
24750
- this.#event({ type: "item.started", turnId: active.command.turnId, item: fileItem });
24751
- this.#completeItem(active, fileItem, { status: "succeeded" });
25431
+ this.#event({ type: "item.started", turnId: active2.command.turnId, item: fileItem });
25432
+ this.#completeItem(active2, fileItem, { status: "succeeded" });
24752
25433
  }
24753
25434
  } catch {
24754
25435
  }
24755
25436
  }
24756
25437
  }
24757
- #completeItem(active, item, outcome) {
25438
+ #completeItem(active2, item, outcome) {
24758
25439
  this.#event({
24759
25440
  type: "item.completed",
24760
- turnId: active.command.turnId,
25441
+ turnId: active2.command.turnId,
24761
25442
  snapshot: { item, outcome }
24762
25443
  });
24763
25444
  }
24764
- #closeActiveInteractions(active, reason) {
24765
- for (const [interactionId, pending] of active.interactions) {
24766
- active.interactions.delete(interactionId);
24767
- active.interactionByNativeId.delete(pending.nativeRequest.requestId);
25445
+ #closeActiveInteractions(active2, reason) {
25446
+ for (const [interactionId, pending] of active2.interactions) {
25447
+ active2.interactions.delete(interactionId);
25448
+ active2.interactionByNativeId.delete(pending.nativeRequest.requestId);
24768
25449
  this.#event({
24769
25450
  type: "interaction.closed",
24770
25451
  interactionId,
24771
- turnId: active.command.turnId,
25452
+ turnId: active2.command.turnId,
24772
25453
  reason
24773
25454
  });
24774
25455
  }
24775
25456
  }
24776
- async #completedTurnIdentity(active, transport) {
24777
- active.acceptingSteers = false;
24778
- await Promise.allSettled([...active.pendingSteers]);
24779
- const snapshot = mapPiSnapshot(active.steerFailure?.history ?? await transport.getEntries(), {
25457
+ async #completedTurnIdentity(active2, transport) {
25458
+ active2.acceptingSteers = false;
25459
+ await Promise.allSettled([...active2.pendingSteers]);
25460
+ const snapshot = mapPiSnapshot(active2.steerFailure?.history ?? await transport.getEntries(), {
24780
25461
  sessionId: transport.state.sessionId,
24781
25462
  model: nativeModelForHistory(transport.state)
24782
25463
  });
24783
- const created = snapshot.turns.filter((turn2) => turn2.input.length > 0 && !active.beforeNativeTurnKeys.has(turn2.nativeTurnRef.nativeTurnKey));
24784
- const expected = 1 + active.acceptedSteerCount;
25464
+ const created = snapshot.turns.filter((turn2) => turn2.input.length > 0 && !active2.beforeNativeTurnKeys.has(turn2.nativeTurnRef.nativeTurnKey));
25465
+ const expected = 1 + active2.acceptedSteerCount;
24785
25466
  if (created.length !== expected) {
24786
25467
  throw new Error(`Pi Turn persisted ${created.length} new User Entries; exactly ${expected} is required`);
24787
25468
  }
@@ -24793,34 +25474,34 @@ var PiHarnessSession = class {
24793
25474
  ...turn.checkpoint ? { checkpoint: turn.checkpoint } : {}
24794
25475
  };
24795
25476
  }
24796
- #completeTurn(active, outcome, finalText, nativeTurnRef) {
24797
- if (this.#active !== active)
25477
+ #completeTurn(active2, outcome, finalText, nativeTurnRef) {
25478
+ if (this.#active !== active2)
24798
25479
  return;
24799
- this.#closeActiveInteractions(active, outcome.status === "succeeded" ? "superseded" : "cancelled");
25480
+ this.#closeActiveInteractions(active2, outcome.status === "succeeded" ? "superseded" : "cancelled");
24800
25481
  this.#active = null;
24801
25482
  const itemOutcome2 = outcome.status === "failed" ? { status: "failed", error: outcome.error } : outcome.status === "cancelled" ? { status: "cancelled", ...outcome.reason ? { reason: outcome.reason } : {} } : { status: "succeeded" };
24802
- this.#completeReasoning(active, itemOutcome2);
24803
- if (active.compactionItem) {
24804
- this.#completeItem(active, active.compactionItem, itemOutcome2);
24805
- active.compactionItem = null;
24806
- }
24807
- for (const tool of active.tools.values())
24808
- this.#completeItem(active, tool.item, itemOutcome2);
24809
- active.tools.clear();
24810
- this.#subagents.finish(active.command.turnId);
24811
- if (!active.sawAssistantMessage && finalText !== void 0 && active.agentItem) {
24812
- active.agentItem = { ...active.agentItem, text: finalText };
24813
- }
24814
- this.#completeAgentItem(active, itemOutcome2, true);
25483
+ this.#completeReasoning(active2, itemOutcome2);
25484
+ if (active2.compactionItem) {
25485
+ this.#completeItem(active2, active2.compactionItem, itemOutcome2);
25486
+ active2.compactionItem = null;
25487
+ }
25488
+ for (const tool of active2.tools.values())
25489
+ this.#completeItem(active2, tool.item, itemOutcome2);
25490
+ active2.tools.clear();
25491
+ this.#subagents.finish(active2.command.turnId);
25492
+ if (!active2.sawAssistantMessage && finalText !== void 0 && active2.agentItem) {
25493
+ active2.agentItem = { ...active2.agentItem, text: finalText };
25494
+ }
25495
+ this.#completeAgentItem(active2, itemOutcome2, true);
24815
25496
  this.#event({
24816
25497
  type: "turn.completed",
24817
- turnId: active.command.turnId,
25498
+ turnId: active2.command.turnId,
24818
25499
  outcome,
24819
25500
  ...nativeTurnRef ? { nativeTurnRef } : {}
24820
25501
  });
24821
- active.resolveCompletion();
24822
- if (active.steerFailure) {
24823
- this.#fault(active.steerFailure);
25502
+ active2.resolveCompletion();
25503
+ if (active2.steerFailure) {
25504
+ this.#fault(active2.steerFailure);
24824
25505
  return;
24825
25506
  }
24826
25507
  queueMicrotask(() => {
@@ -24828,7 +25509,7 @@ var PiHarnessSession = class {
24828
25509
  return;
24829
25510
  if (this.#transport)
24830
25511
  this.#drainPendingAutonomousTurns(this.#transport);
24831
- void this.#refreshUsage(active.command.turnId);
25512
+ void this.#refreshUsage(active2.command.turnId);
24832
25513
  });
24833
25514
  }
24834
25515
  #fault(error51) {
@@ -24855,11 +25536,11 @@ var PiHarnessSession = class {
24855
25536
  if (!wasFaulted)
24856
25537
  this.#phase = "closing";
24857
25538
  const transport = this.#transport ?? (this.#starting ? await this.#starting.catch(() => null) : null);
24858
- const active = this.#active;
24859
- if (transport && active) {
24860
- active.cancellationRequested = true;
25539
+ const active2 = this.#active;
25540
+ if (transport && active2) {
25541
+ active2.cancellationRequested = true;
24861
25542
  await transport.abort().catch(() => void 0);
24862
- await Promise.race([active.completion, delay(this.#closeTimeoutMs)]);
25543
+ await Promise.race([active2.completion, delay(this.#closeTimeoutMs)]);
24863
25544
  }
24864
25545
  try {
24865
25546
  if (transport)
@@ -24886,6 +25567,7 @@ var PiHarnessSession = class {
24886
25567
  }
24887
25568
  };
24888
25569
  var PiAdapter = class {
25570
+ normalizeStoredModelRef = normalizeStoredPiModelRef;
24889
25571
  credentialImports;
24890
25572
  commandCatalog = piCommandCatalog;
24891
25573
  liveCommandCatalog = true;
@@ -24979,6 +25661,7 @@ var PiAdapter = class {
24979
25661
  const updateCatalog = async (operation) => {
24980
25662
  await operation;
24981
25663
  this.#inspectionCache.clear();
25664
+ this.#inspectionInFlight.clear();
24982
25665
  };
24983
25666
  this.credentialImports = {
24984
25667
  providers: imports.providers,
@@ -25018,16 +25701,22 @@ var PiAdapter = class {
25018
25701
  }
25019
25702
  const cwd = resolvePiInspectCwd(input.cwd);
25020
25703
  const inFlight = this.#inspectionInFlight.get(cwd);
25704
+ if (input.refresh) {
25705
+ this.#inspectionCache.clear();
25706
+ this.#inspectionInFlight.clear();
25707
+ if (inFlight)
25708
+ this.#inspectionInFlight.set(cwd, inFlight);
25709
+ }
25021
25710
  if (inFlight)
25022
25711
  return inFlight;
25023
- if (!input.refresh) {
25024
- const cached2 = this.#inspectionCache.get(cwd);
25025
- if (cached2)
25026
- return cached2;
25027
- }
25712
+ const cached2 = this.#inspectionCache.get(cwd);
25713
+ if (cached2)
25714
+ return cached2;
25028
25715
  const inspection = this.#inspectCwd(cwd).then((result) => {
25029
- if (result.status === "ready")
25716
+ if (result.status === "ready" && this.#inspectionInFlight.get(cwd) === inspection) {
25030
25717
  this.#inspectionCache.set(cwd, result);
25718
+ this.#thinkingSelectionSupported = result.capabilities.configuration.selectThinkingOption;
25719
+ }
25031
25720
  return result;
25032
25721
  });
25033
25722
  this.#inspectionInFlight.set(cwd, inspection);
@@ -25049,10 +25738,7 @@ var PiAdapter = class {
25049
25738
  const models = await transport.getAvailableModels();
25050
25739
  stage = "capabilities";
25051
25740
  const thinkingLevels = await transport.getAvailableThinkingLevels();
25052
- this.#thinkingSelectionSupported = thinkingLevels !== null;
25053
- const normalized = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel, transport.state.modelReasoning ?? null);
25054
- const fastModels = await transport.supportsFastMode?.() ? piFastModelKeys(models) : /* @__PURE__ */ new Set();
25055
- const catalog = withPiFast(normalized, fastModels);
25741
+ const catalog = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel, transport.state.modelReasoning ?? null, await transport.supportsFastMode?.());
25056
25742
  await transport.close();
25057
25743
  return {
25058
25744
  status: "ready",
@@ -25089,27 +25775,6 @@ var PiAdapter = class {
25089
25775
  if (this.#closePromise) {
25090
25776
  return { ok: false, error: invalidState("Pi Adapter is closed") };
25091
25777
  }
25092
- if ("model" in input && input.model) {
25093
- let model2;
25094
- try {
25095
- model2 = decodePiModelRef(input.model);
25096
- } catch (error51) {
25097
- return { ok: false, error: normalizedError(error51, "invalidRequest") };
25098
- }
25099
- if (model2.fast) {
25100
- if (!this.#isFastSupported(input.model, input.cwd))
25101
- await this.inspect({ cwd: input.cwd });
25102
- if (!this.#isFastSupported(input.model, input.cwd) && input.kind !== "resume")
25103
- return {
25104
- ok: false,
25105
- error: {
25106
- code: "unsupported",
25107
- message: "Fast is unavailable for this Pi Model",
25108
- retryable: false
25109
- }
25110
- };
25111
- }
25112
- }
25113
25778
  if (input.cwd.length === 0) {
25114
25779
  return {
25115
25780
  ok: false,
@@ -25132,10 +25797,25 @@ var PiAdapter = class {
25132
25797
  };
25133
25798
  }
25134
25799
  if (input.model) {
25135
- try {
25136
- decodePiModelRef(input.model);
25137
- } catch (error51) {
25138
- return { ok: false, error: normalizedError(error51, "invalidRequest") };
25800
+ const parsed = harnessModelRefSchema.safeParse(input.model);
25801
+ if (!parsed.success || parsed.data.serviceTier === "ultrafast") {
25802
+ return {
25803
+ ok: false,
25804
+ error: { code: "invalidRequest", message: "Invalid Pi Model Ref", retryable: false }
25805
+ };
25806
+ }
25807
+ if (parsed.data.serviceTier === "priority") {
25808
+ const inspection = await this.inspect({ cwd: input.cwd });
25809
+ if (inspection.status !== "ready" || !inspection.catalog.models.some(({ fastModel }) => sameHarnessModelRef(fastModel, parsed.data))) {
25810
+ return {
25811
+ ok: false,
25812
+ error: {
25813
+ code: "unsupported",
25814
+ message: "Fast is unavailable for this Pi Model",
25815
+ retryable: false
25816
+ }
25817
+ };
25818
+ }
25139
25819
  }
25140
25820
  }
25141
25821
  const thinkingOptionId = input.thinkingOptionId ? harnessThinkingOptionIdSchema.safeParse(input.thinkingOptionId) : null;
@@ -25280,7 +25960,9 @@ var PiAdapter = class {
25280
25960
  await transport.verifySessionCwd(input.cwd);
25281
25961
  }
25282
25962
  }
25283
- if (input.kind === "resume" && input.model && this.#isFastSupported(input.model, input.cwd) && decodePiModelRef(input.model).fast && samePiModel(nativeModelFromState(transport.state), decodePiModelRef(input.model))) {
25963
+ const startedModels = await transport.getAvailableModels();
25964
+ const current = nativeModelFromState(transport.state);
25965
+ if (input.kind === "resume" && input.model && current && sameHarnessModelRef(input.model, livePiModelIndex(startedModels, transport.state).ref({ ...current, fast: true })) && await isFastSupported(current, startedModels, transport)) {
25284
25966
  if (!transport.selectFastMode)
25285
25967
  throw new Error("Pi Fast extension is unavailable");
25286
25968
  await transport.selectFastMode(true);
@@ -25293,6 +25975,7 @@ var PiAdapter = class {
25293
25975
  usageHistory,
25294
25976
  ...input.environment ? { environment: input.environment } : {},
25295
25977
  startedTransport: transport,
25978
+ startedModels,
25296
25979
  startedThinkingLevels,
25297
25980
  initialUsage,
25298
25981
  supportsThinkingSelection: startedThinkingLevels !== null
@@ -25303,9 +25986,6 @@ var PiAdapter = class {
25303
25986
  return { ok: false, error: normalizedError(error51, "nativeFailure") };
25304
25987
  }
25305
25988
  }
25306
- #isFastSupported(ref, cwd) {
25307
- return this.#inspectionCache.get(cwd)?.catalog.models.some((model2) => model2.fastModel?.id === ref.id) ?? false;
25308
- }
25309
25989
  #trackSession(cwd, options) {
25310
25990
  const environment = options.environment;
25311
25991
  const createTransport = environment ? (input) => this.#createTransport({ ...input, environment }) : this.#createTransport;
@@ -25317,15 +25997,8 @@ var PiAdapter = class {
25317
25997
  ...options.thinkingOptionId ? { thinkingOptionId: options.thinkingOptionId } : {},
25318
25998
  toolOutputLimit: this.#toolOutputLimit,
25319
25999
  supportsThinkingSelection: options.supportsThinkingSelection,
25320
- isFastSupported: async (ref, transport) => {
25321
- if (this.#inspectionCache.has(cwd))
25322
- return this.#isFastSupported(ref, cwd);
25323
- if (!await transport.supportsFastMode?.())
25324
- return false;
25325
- const fastModels = piFastModelKeys(await transport.getAvailableModels());
25326
- return fastModels.has(encodePiModelRef({ ...decodePiModelRef(ref), fast: false }).id);
25327
- },
25328
26000
  ...options.startedTransport ? { startedTransport: options.startedTransport } : {},
26001
+ ...options.startedModels ? { startedModels: options.startedModels } : {},
25329
26002
  ...options.startedThinkingLevels !== void 0 ? { startedThinkingLevels: options.startedThinkingLevels } : {},
25330
26003
  ...options.initialUsage !== void 0 ? { initialUsage: options.initialUsage } : {},
25331
26004
  ...options.usageHistory ? { usageHistory: options.usageHistory } : {}