@liberseek/boft-cli-win32-arm64 0.7.5 → 0.7.6

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.
@@ -5,15 +5,10 @@ var __export = (target, all) => {
5
5
  __defProp(target, name, { get: all[name], enumerable: true });
6
6
  };
7
7
 
8
- // dist/pi-credential-imports.js
9
- import { randomUUID } from "node:crypto";
10
- import { execFile } from "node:child_process";
11
- import { promisify } from "node:util";
12
- import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
13
- import { realpath } from "node:fs/promises";
14
- import os2 from "node:os";
15
- import path3 from "node:path";
16
- import { pathToFileURL } from "node:url";
8
+ // dist/account-balance.js
9
+ import { readFile } from "node:fs/promises";
10
+ import { homedir } from "node:os";
11
+ import path from "node:path";
17
12
 
18
13
  // ../../../node_modules/zod/v4/classic/external.js
19
14
  var external_exports = {};
@@ -781,10 +776,10 @@ function mergeDefs(...defs) {
781
776
  function cloneDef(schema) {
782
777
  return mergeDefs(schema._zod.def);
783
778
  }
784
- function getElementAtPath(obj, path10) {
785
- if (!path10)
779
+ function getElementAtPath(obj, path13) {
780
+ if (!path13)
786
781
  return obj;
787
- return path10.reduce((acc, key) => acc?.[key], obj);
782
+ return path13.reduce((acc, key) => acc?.[key], obj);
788
783
  }
789
784
  function promiseAllObject(promisesObj) {
790
785
  const keys = Object.keys(promisesObj);
@@ -1193,11 +1188,11 @@ function explicitlyAborted(x, startIndex = 0) {
1193
1188
  }
1194
1189
  return false;
1195
1190
  }
1196
- function prefixIssues(path10, issues) {
1191
+ function prefixIssues(path13, issues) {
1197
1192
  return issues.map((iss) => {
1198
1193
  var _a3;
1199
1194
  (_a3 = iss).path ?? (_a3.path = []);
1200
- iss.path.unshift(path10);
1195
+ iss.path.unshift(path13);
1201
1196
  return iss;
1202
1197
  });
1203
1198
  }
@@ -1344,16 +1339,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1344
1339
  }
1345
1340
  function formatError(error51, mapper = (issue2) => issue2.message) {
1346
1341
  const fieldErrors = { _errors: [] };
1347
- const processError = (error52, path10 = []) => {
1342
+ const processError = (error52, path13 = []) => {
1348
1343
  for (const issue2 of error52.issues) {
1349
1344
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1350
- issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1345
+ issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1351
1346
  } else if (issue2.code === "invalid_key") {
1352
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1347
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1353
1348
  } else if (issue2.code === "invalid_element") {
1354
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1349
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1355
1350
  } else {
1356
- const fullpath = [...path10, ...issue2.path];
1351
+ const fullpath = [...path13, ...issue2.path];
1357
1352
  if (fullpath.length === 0) {
1358
1353
  fieldErrors._errors.push(mapper(issue2));
1359
1354
  } else {
@@ -1380,17 +1375,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1380
1375
  }
1381
1376
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1382
1377
  const result = { errors: [] };
1383
- const processError = (error52, path10 = []) => {
1378
+ const processError = (error52, path13 = []) => {
1384
1379
  var _a3, _b;
1385
1380
  for (const issue2 of error52.issues) {
1386
1381
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1387
- issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1382
+ issue2.errors.map((issues) => processError({ issues }, [...path13, ...issue2.path]));
1388
1383
  } else if (issue2.code === "invalid_key") {
1389
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1384
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1390
1385
  } else if (issue2.code === "invalid_element") {
1391
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1386
+ processError({ issues: issue2.issues }, [...path13, ...issue2.path]);
1392
1387
  } else {
1393
- const fullpath = [...path10, ...issue2.path];
1388
+ const fullpath = [...path13, ...issue2.path];
1394
1389
  if (fullpath.length === 0) {
1395
1390
  result.errors.push(mapper(issue2));
1396
1391
  continue;
@@ -1422,8 +1417,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1422
1417
  }
1423
1418
  function toDotPath(_path) {
1424
1419
  const segs = [];
1425
- const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1426
- for (const seg of path10) {
1420
+ const path13 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1421
+ for (const seg of path13) {
1427
1422
  if (typeof seg === "number")
1428
1423
  segs.push(`[${seg}]`);
1429
1424
  else if (typeof seg === "symbol")
@@ -14115,13 +14110,13 @@ function resolveRef(ref, ctx) {
14115
14110
  if (!ref.startsWith("#")) {
14116
14111
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14117
14112
  }
14118
- const path10 = ref.slice(1).split("/").filter(Boolean);
14119
- if (path10.length === 0) {
14113
+ const path13 = ref.slice(1).split("/").filter(Boolean);
14114
+ if (path13.length === 0) {
14120
14115
  return ctx.rootSchema;
14121
14116
  }
14122
14117
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14123
- if (path10[0] === defsKey) {
14124
- const key = path10[1];
14118
+ if (path13[0] === defsKey) {
14119
+ const key = path13[1];
14125
14120
  if (!key || !ctx.defs[key]) {
14126
14121
  throw new Error(`Reference not found: ${ref}`);
14127
14122
  }
@@ -14584,6 +14579,55 @@ var credentialImportsParamsSchema = external_exports.object({
14584
14579
  request: credentialImportsRequestSchema
14585
14580
  }).strict();
14586
14581
 
14582
+ // ../../shared-contracts/dist/harness-display-settings.js
14583
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
14584
+ agent: external_exports.string().min(1).max(128),
14585
+ section: external_exports.enum(["main", "more", "auto"])
14586
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
14587
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
14588
+ entries: harnessDisplayEntriesSchema.nullable()
14589
+ });
14590
+ var harnessDisplayGetSchema = external_exports.strictObject({});
14591
+ var harnessDisplaySetSchema = external_exports.strictObject({
14592
+ entries: harnessDisplayEntriesSchema,
14593
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
14594
+ initializeOnly: external_exports.boolean().optional()
14595
+ });
14596
+
14597
+ // ../../shared-contracts/dist/console.js
14598
+ var consoleAnnouncementSchema = external_exports.strictObject({
14599
+ title: external_exports.string().trim().min(1).max(200),
14600
+ type: external_exports.enum(["info", "warning", "danger"]),
14601
+ body: external_exports.string().trim().min(1).max(16 * 1024)
14602
+ });
14603
+ var consoleOpenParamsSchema = external_exports.strictObject({});
14604
+ var consoleOpenResultSchema = external_exports.strictObject({
14605
+ /** The console address. */
14606
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
14607
+ });
14608
+ var CONSOLE_HOST_METHODS = Object.freeze([
14609
+ "codexhost/harness/plugins/list",
14610
+ "codexhost/harness/display-settings/get",
14611
+ "codexhost/harness/display-settings/set",
14612
+ "codexhost/harness/inspect",
14613
+ "codexhost/harness/launch-settings/get",
14614
+ "codexhost/harness/launch-settings/set",
14615
+ "codexhost/harness/web-ui/open",
14616
+ "codexhost/harness/accounts/sources",
14617
+ "codexhost/harness/accounts/list",
14618
+ "codexhost/harness/accounts/inspect",
14619
+ "codexhost/harness/credential-imports",
14620
+ "codexhost/harness/session-import/sources",
14621
+ "codexhost/harness/session-import/list",
14622
+ "codexhost/harness/session-import/import",
14623
+ "codexhost/account/list",
14624
+ "codexhost/account/refresh",
14625
+ "codexhost/account/usage/inspect",
14626
+ "codexhost/update/check",
14627
+ "codexhost/update/start",
14628
+ "codexhost/update/status"
14629
+ ]);
14630
+
14587
14631
  // ../../shared-contracts/dist/version.js
14588
14632
  var WORKSPACE_CONTRACT_VERSION = 1;
14589
14633
 
@@ -14637,6 +14681,12 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
14637
14681
  var hostItemIdSchema = opaqueIdSchema.brand();
14638
14682
  var hostInteractionIdSchema = opaqueIdSchema.brand();
14639
14683
 
14684
+ // ../../shared-contracts/dist/manual-compaction.js
14685
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
14686
+ threadId: hostThreadIdSchema,
14687
+ turnId: hostTurnIdSchema
14688
+ });
14689
+
14640
14690
  // ../../shared-contracts/dist/thread-usage.js
14641
14691
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
14642
14692
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -14697,6 +14747,10 @@ var threadUsageSnapshotSchema = external_exports.object({
14697
14747
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
14698
14748
  var accountCreditsProductUsageSchema = external_exports.object({
14699
14749
  product: external_exports.string().min(1),
14750
+ used: external_exports.number().finite().nonnegative().optional(),
14751
+ // Zero is a real empty cap, not an absent field.
14752
+ limit: external_exports.number().finite().nonnegative().optional(),
14753
+ unit: external_exports.string().min(1).max(32).optional(),
14700
14754
  usagePercent: usagePercentSchema,
14701
14755
  resetsAt: external_exports.string().min(1).optional()
14702
14756
  }).strict();
@@ -14706,11 +14760,14 @@ var accountResetCreditsSchema = external_exports.object({
14706
14760
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
14707
14761
  }).strict();
14708
14762
  var accountCreditsSnapshotSchema = external_exports.object({
14763
+ used: external_exports.number().finite().nonnegative().optional(),
14764
+ // Zero is a real empty cap, not an absent field.
14765
+ limit: external_exports.number().finite().nonnegative().optional(),
14766
+ unit: external_exports.string().trim().min(1).max(32).optional(),
14709
14767
  /** Native label when the primary limit is scoped to a model or product group. */
14710
14768
  label: external_exports.string().min(1).optional(),
14711
14769
  usedPercent: usagePercentSchema.optional(),
14712
14770
  remaining: external_exports.number().finite().optional(),
14713
- unit: external_exports.string().trim().min(1).max(32).optional(),
14714
14771
  resetsAt: external_exports.string().min(1).optional(),
14715
14772
  periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
14716
14773
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
@@ -14741,12 +14798,27 @@ var threadUsageInspectionSchema = external_exports.object({
14741
14798
  }).strict();
14742
14799
 
14743
14800
  // ../../shared-contracts/dist/harness-accounts.js
14744
- var harnessAccountSnapshotSchema = external_exports.object({
14801
+ var accountBalanceSnapshotSchema = external_exports.object({
14802
+ amount: external_exports.number().finite().nonnegative(),
14803
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
14804
+ currency: external_exports.string().trim().min(1).max(8),
14805
+ /** Native label when the Harness exposes several Billing Sources. */
14806
+ label: external_exports.string().trim().min(1).max(128).optional()
14807
+ }).strict();
14808
+ var harnessAccountSnapshotObject = external_exports.object({
14745
14809
  email: external_exports.string().trim().min(1).max(320).optional(),
14746
14810
  label: external_exports.string().trim().min(1).max(256).optional(),
14747
14811
  plan: external_exports.string().trim().min(1).max(128).optional(),
14748
- credits: accountCreditsSnapshotSchema
14812
+ credits: accountCreditsSnapshotSchema.optional(),
14813
+ balance: accountBalanceSnapshotSchema.optional()
14749
14814
  }).strict();
14815
+ function requireReportedQuota(schema) {
14816
+ return schema.refine((value) => {
14817
+ const reported = value;
14818
+ return reported.credits !== void 0 || reported.balance !== void 0;
14819
+ }, { message: "Account must report either credits or a balance" });
14820
+ }
14821
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
14750
14822
  var harnessAccountIdentityShape = {
14751
14823
  harnessId: harnessIdSchema,
14752
14824
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -14757,11 +14829,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
14757
14829
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
14758
14830
  var harnessAccountInspectResultSchema = external_exports.object({
14759
14831
  ...harnessAccountIdentityShape,
14760
- account: harnessAccountSnapshotSchema.nullable()
14832
+ account: harnessAccountSnapshotSchema.nullable(),
14833
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
14834
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
14761
14835
  }).strict();
14762
14836
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
14763
14837
  var harnessAccountListResultSchema = external_exports.object({
14764
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
14838
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
14765
14839
  }).strict();
14766
14840
 
14767
14841
  // ../../shared-contracts/dist/json-value.js
@@ -14899,6 +14973,8 @@ var harnessModelSchema = external_exports.object({
14899
14973
  ref: harnessModelRefSchema,
14900
14974
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14901
14975
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
14976
+ /** Optional opaque selection for this same Model with priority processing enabled. */
14977
+ fastModel: harnessModelRefSchema.optional(),
14902
14978
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14903
14979
  }).strict();
14904
14980
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -14931,6 +15007,16 @@ var harnessModelCatalogSchema = external_exports.object({
14931
15007
  });
14932
15008
  }
14933
15009
  refs.add(model.ref.id);
15010
+ if (model.fastModel) {
15011
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
15012
+ context.addIssue({
15013
+ code: "custom",
15014
+ message: "Fast Model refs must be distinct and unique",
15015
+ path: ["models", index, "fastModel"]
15016
+ });
15017
+ }
15018
+ refs.add(model.fastModel.id);
15019
+ }
14934
15020
  const supportedThinkingIds = /* @__PURE__ */ new Set();
14935
15021
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
14936
15022
  if (supportedThinkingIds.has(optionId)) {
@@ -15053,11 +15139,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
15053
15139
  thinkingOptionId: harnessThinkingOptionIdSchema
15054
15140
  }).strict();
15055
15141
  var threadInspectionParamsSchema = external_exports.object({
15056
- threadId: hostThreadIdSchema
15142
+ threadId: hostThreadIdSchema,
15143
+ includeReferenceCapability: external_exports.boolean().optional()
15057
15144
  }).strict();
15058
15145
  var codexThreadInspectionSchema = external_exports.object({
15059
15146
  owner: external_exports.literal("codex"),
15060
- locked: external_exports.literal(true)
15147
+ locked: external_exports.literal(true),
15148
+ supportsThreadReferences: external_exports.literal(true).optional()
15061
15149
  }).strict();
15062
15150
  var externalThreadInspectionSchema = external_exports.object({
15063
15151
  owner: external_exports.literal("external"),
@@ -15185,10 +15273,31 @@ var harnessLaunchSettingsSchema = external_exports.object({
15185
15273
  restartRequired: external_exports.boolean()
15186
15274
  }).strict();
15187
15275
 
15276
+ // ../../shared-contracts/dist/harness-installation.js
15277
+ var harnessInstallationParamsSchema = external_exports.object({
15278
+ harnessId: harnessIdSchema,
15279
+ action: external_exports.enum(["check", "update"])
15280
+ }).strict();
15281
+ var harnessInstallationStateSchema = external_exports.object({
15282
+ currentVersion: external_exports.string().min(1).max(128),
15283
+ latestVersion: external_exports.string().min(1).max(128),
15284
+ updateAvailable: external_exports.boolean(),
15285
+ canUpdate: external_exports.boolean(),
15286
+ message: external_exports.string().max(2048).optional()
15287
+ }).strict();
15288
+
15188
15289
  // ../../shared-contracts/dist/codex-accounts.js
15189
15290
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15190
15291
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
15191
15292
  var codexAccountAuthKindSchema = external_exports.enum(["api", "chatgpt"]);
15293
+ var codexAccountSiteUrlPattern = /^https?:\/\/(?:\[[0-9a-fA-F:]+\]|[^/\s:@?#]+)(?::\d{1,5})?(?:[/?#][^\s]*)?$/u;
15294
+ function isCodexAccountSiteUrl(value) {
15295
+ return value.length > 0 && value.length <= 2048 && codexAccountSiteUrlPattern.test(value);
15296
+ }
15297
+ var externalUrlOpenParamsSchema = external_exports.object({
15298
+ url: external_exports.string().max(2048).refine(isCodexAccountSiteUrl, "External URL must be http(s)")
15299
+ }).strict();
15300
+ var externalUrlOpenResultSchema = external_exports.object({}).strict();
15192
15301
  var codexAccountPlanTypeSchema = external_exports.enum([
15193
15302
  "free",
15194
15303
  "go",
@@ -15214,7 +15323,8 @@ var codexAccountSchema = external_exports.object({
15214
15323
  email: external_exports.string().email().max(320).optional(),
15215
15324
  planType: codexAccountPlanTypeSchema.optional(),
15216
15325
  authKind: codexAccountAuthKindSchema.optional(),
15217
- authIdentity: nonBlankTextSchema3.max(256).optional()
15326
+ authIdentity: nonBlankTextSchema3.max(256).optional(),
15327
+ siteUrl: external_exports.string().refine(isCodexAccountSiteUrl, "Account site URL must be http(s)").optional()
15218
15328
  }).strict();
15219
15329
  var codexAccountPhaseSchema = external_exports.enum(["ready", "unavailable"]);
15220
15330
  var codexAccountListResultSchema = external_exports.object({
@@ -15490,11 +15600,164 @@ var updateStatusResultSchema = external_exports.strictObject({
15490
15600
  // ../../shared-contracts/dist/index.js
15491
15601
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
15492
15602
 
15603
+ // dist/account-balance.js
15604
+ var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
15605
+ var SUB2API_USAGE_PATH = "/v1/usage";
15606
+ var REQUEST_TIMEOUT_MS = 1e4;
15607
+ var MAX_PI_ACCOUNTS = 8;
15608
+ function agentDirectory(environment) {
15609
+ const configured = environment.PI_CODING_AGENT_DIR?.trim();
15610
+ if (configured)
15611
+ return configured;
15612
+ return path.join(environment.HOME ?? environment.USERPROFILE ?? homedir(), ".pi", "agent");
15613
+ }
15614
+ var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
15615
+ async function deepSeekApiKey(environment) {
15616
+ const auth = record2(JSON.parse(await readFile(path.join(agentDirectory(environment), "auth.json"), "utf8")));
15617
+ const deepseek = record2(auth.deepseek);
15618
+ if (deepseek.type !== "api_key")
15619
+ return void 0;
15620
+ return typeof deepseek.key === "string" && deepseek.key.trim() ? deepseek.key : void 0;
15621
+ }
15622
+ function projectSub2ApiUsage(payload, providerId) {
15623
+ const data = record2(payload);
15624
+ if (data.isValid === false)
15625
+ return null;
15626
+ if (data.mode !== "unrestricted" && data.mode !== "quota_limited")
15627
+ return null;
15628
+ const currency = typeof data.unit === "string" ? data.unit.trim() : "";
15629
+ if (!/^[A-Z]{3}$/u.test(currency))
15630
+ return null;
15631
+ const wallet = finiteAmount(data.balance);
15632
+ const remaining = finiteAmount(data.remaining);
15633
+ const quotaRemaining = finiteAmount(record2(data.quota).remaining);
15634
+ const amount = wallet ?? remaining ?? quotaRemaining;
15635
+ if (amount === null)
15636
+ return null;
15637
+ const planName = typeof data.planName === "string" ? data.planName.trim() : "";
15638
+ const label = providerId.trim();
15639
+ if (!label || label.length > 128)
15640
+ return null;
15641
+ const parsed = harnessAccountSnapshotSchema.safeParse({
15642
+ label,
15643
+ ...planName ? { plan: planName.slice(0, 128) } : {},
15644
+ balance: { amount, currency, label: planName || label }
15645
+ });
15646
+ return parsed.success ? parsed.data : null;
15647
+ }
15648
+ function finiteAmount(value) {
15649
+ const amount = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
15650
+ return Number.isFinite(amount) && amount >= 0 ? amount : null;
15651
+ }
15652
+ function projectDeepSeekBalance(payload) {
15653
+ const data = record2(payload);
15654
+ if (!Array.isArray(data.balance_infos))
15655
+ return null;
15656
+ const first = record2(data.balance_infos[0]);
15657
+ const amount = finiteAmount(first.total_balance);
15658
+ const currency = typeof first.currency === "string" ? first.currency.trim() : "";
15659
+ if (amount === null || !currency)
15660
+ return null;
15661
+ const parsed = harnessAccountSnapshotSchema.safeParse({
15662
+ label: "DeepSeek",
15663
+ balance: { amount, currency, label: "DeepSeek API" }
15664
+ });
15665
+ return parsed.success ? parsed.data : null;
15666
+ }
15667
+ function usageEndpoint(baseUrl) {
15668
+ let url2;
15669
+ try {
15670
+ url2 = new URL(baseUrl);
15671
+ } catch {
15672
+ return null;
15673
+ }
15674
+ if (url2.protocol !== "https:" && url2.protocol !== "http:" || !url2.hostname)
15675
+ return null;
15676
+ url2.username = "";
15677
+ url2.password = "";
15678
+ url2.pathname = SUB2API_USAGE_PATH;
15679
+ url2.search = "";
15680
+ url2.hash = "";
15681
+ return url2.toString();
15682
+ }
15683
+ async function configuredSub2ApiProviders(environment) {
15684
+ try {
15685
+ const models = record2(JSON.parse(await readFile(path.join(agentDirectory(environment), "models.json"), "utf8")));
15686
+ const providers = record2(models.providers);
15687
+ const found = [];
15688
+ for (const [id, definition] of Object.entries(providers)) {
15689
+ const provider = record2(definition);
15690
+ const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
15691
+ const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
15692
+ if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
15693
+ continue;
15694
+ found.push({ id, apiKey, baseUrl });
15695
+ }
15696
+ return found.sort((left, right) => left.id.localeCompare(right.id));
15697
+ } catch {
15698
+ return [];
15699
+ }
15700
+ }
15701
+ async function fetchSub2ApiBalance(provider, fetchImpl, signal) {
15702
+ const endpoint = usageEndpoint(provider.baseUrl);
15703
+ if (!endpoint)
15704
+ return null;
15705
+ const response = await fetchImpl(endpoint, {
15706
+ headers: { Authorization: `Bearer ${provider.apiKey}`, Accept: "application/json" },
15707
+ redirect: "error",
15708
+ signal
15709
+ });
15710
+ if (!response.ok)
15711
+ return null;
15712
+ return projectSub2ApiUsage(await response.json(), provider.id);
15713
+ }
15714
+ async function fetchPiAccounts(input = {}) {
15715
+ try {
15716
+ const environment = input.environment ?? process.env;
15717
+ const fetchImpl = input.fetch ?? fetch;
15718
+ const signal = input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]) : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
15719
+ const [providers, deepseek] = await Promise.all([
15720
+ input.readProviders ? input.readProviders() : configuredSub2ApiProviders(environment),
15721
+ fetchPiAccountBalance({ ...input, environment, fetch: fetchImpl, signal })
15722
+ ]);
15723
+ const wallets = await Promise.all(providers.filter((provider) => provider.apiKey.trim() && usageEndpoint(provider.baseUrl)).map((provider) => fetchSub2ApiBalance(provider, fetchImpl, signal).catch(() => null)));
15724
+ return [...wallets, deepseek].filter((account) => account !== null).slice(0, MAX_PI_ACCOUNTS);
15725
+ } catch {
15726
+ return [];
15727
+ }
15728
+ }
15729
+ async function fetchPiAccountBalance(input) {
15730
+ try {
15731
+ const key = await (input.readApiKey ? input.readApiKey() : deepSeekApiKey(input.environment));
15732
+ if (!key)
15733
+ return null;
15734
+ const response = await input.fetch(DEEPSEEK_BALANCE_ENDPOINT, {
15735
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
15736
+ signal: input.signal
15737
+ });
15738
+ if (!response.ok)
15739
+ return null;
15740
+ return projectDeepSeekBalance(await response.json());
15741
+ } catch {
15742
+ return null;
15743
+ }
15744
+ }
15745
+
15746
+ // dist/pi-credential-imports.js
15747
+ import { randomUUID } from "node:crypto";
15748
+ import { execFile as execFile2 } from "node:child_process";
15749
+ import { promisify } from "node:util";
15750
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
15751
+ import { realpath } from "node:fs/promises";
15752
+ import os2 from "node:os";
15753
+ import path5 from "node:path";
15754
+ import { pathToFileURL } from "node:url";
15755
+
15493
15756
  // ../../harness-discovery/dist/environment.js
15494
15757
  import fs from "node:fs";
15495
- import path from "node:path";
15758
+ import path2 from "node:path";
15496
15759
  function targetPath(platform) {
15497
- return platform === "win32" ? path.win32 : path.posix;
15760
+ return platform === "win32" ? path2.win32 : path2.posix;
15498
15761
  }
15499
15762
  function environmentValue(environment, name) {
15500
15763
  const lowered = name.toLowerCase();
@@ -15536,12 +15799,28 @@ function newestFirst(names) {
15536
15799
  return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
15537
15800
  }
15538
15801
 
15802
+ // ../../harness-discovery/dist/invocation.js
15803
+ import path3 from "node:path";
15804
+ function commandInvocation(command, arguments_, environment, platform = process.platform) {
15805
+ const extension = path3.win32.extname(command).toLowerCase();
15806
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
15807
+ return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
15808
+ }
15809
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
15810
+ const commandLine = [command, ...arguments_].map(quote).join(" ");
15811
+ return {
15812
+ command: environmentValue(environment, "ComSpec") ?? "cmd.exe",
15813
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
15814
+ windowsVerbatimArguments: true
15815
+ };
15816
+ }
15817
+
15539
15818
  // ../../harness-discovery/dist/node-runtime.js
15540
- import path2 from "node:path";
15819
+ import path4 from "node:path";
15541
15820
  function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
15542
15821
  const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
15543
15822
  const delimiter = platform === "win32" ? ";" : ":";
15544
- const runtimeDirectory = path2.dirname(runtimeExecutable);
15823
+ const runtimeDirectory = path4.dirname(runtimeExecutable);
15545
15824
  const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
15546
15825
  const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
15547
15826
  if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
@@ -15713,6 +15992,116 @@ function resolveHarnessExecutable(spec, input, dependencies = {}) {
15713
15992
  return void 0;
15714
15993
  }
15715
15994
 
15995
+ // ../../harness-discovery/dist/installation.js
15996
+ import { execFile } from "node:child_process";
15997
+ import { homedir as homedir2 } from "node:os";
15998
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
15999
+ const env = withNodeRuntimeOnPath(environment);
16000
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
16001
+ return new Promise((resolve, reject) => {
16002
+ const child = execFile(invocation.command, invocation.arguments, {
16003
+ env,
16004
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir2(),
16005
+ encoding: "utf8",
16006
+ timeout,
16007
+ killSignal: "SIGKILL",
16008
+ maxBuffer: 1024 * 1024,
16009
+ windowsHide: true,
16010
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
16011
+ }, (error51, stdout, stderr) => {
16012
+ if (error51)
16013
+ reject(new Error(error51.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
16014
+ else
16015
+ resolve((stdout || stderr).trim());
16016
+ });
16017
+ child.stdin?.end();
16018
+ });
16019
+ }
16020
+ function installationVersion(value) {
16021
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
16022
+ throw new Error("Harness returned an invalid version");
16023
+ return value.trim().replace(/^v/, "");
16024
+ }
16025
+ function versionFromOutput(output) {
16026
+ return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
16027
+ }
16028
+ function newerInstallationVersion(current, latest) {
16029
+ const a = installationVersion(current).replace(/\+.*/, "");
16030
+ const b = installationVersion(latest).replace(/\+.*/, "");
16031
+ const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
16032
+ const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
16033
+ for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
16034
+ if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
16035
+ return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
16036
+ }
16037
+ const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
16038
+ const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
16039
+ if (!preA.length || !preB.length)
16040
+ return !!preA.length && !preB.length;
16041
+ for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
16042
+ const x = preA[i];
16043
+ const y = preB[i];
16044
+ if (x === y)
16045
+ continue;
16046
+ if (x === void 0 || y === void 0)
16047
+ return x === void 0;
16048
+ const numericX = /^\d+$/.test(x);
16049
+ const numericY = /^\d+$/.test(y);
16050
+ if (numericX && numericY) {
16051
+ if (BigInt(x) === BigInt(y))
16052
+ continue;
16053
+ return BigInt(y) > BigInt(x);
16054
+ }
16055
+ if (numericX !== numericY)
16056
+ return numericX;
16057
+ return y > x;
16058
+ }
16059
+ return false;
16060
+ }
16061
+ function createInstallationManager(options) {
16062
+ let checking;
16063
+ let updating;
16064
+ const check2 = () => checking ??= options.check().finally(() => {
16065
+ checking = void 0;
16066
+ });
16067
+ return (action) => {
16068
+ if (updating)
16069
+ return updating;
16070
+ if (action === "check")
16071
+ return check2();
16072
+ updating = (async () => {
16073
+ const before = await check2();
16074
+ if (!before.updateAvailable)
16075
+ return before;
16076
+ if (!before.canUpdate)
16077
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
16078
+ await options.update(before);
16079
+ const after = await check2();
16080
+ if (after.currentVersion === before.currentVersion)
16081
+ throw new Error("The Harness version did not change; check the native updater and retry");
16082
+ return after;
16083
+ })().finally(() => {
16084
+ updating = void 0;
16085
+ });
16086
+ return updating;
16087
+ };
16088
+ }
16089
+ async function fetchInstallationText(url2) {
16090
+ const request = async () => {
16091
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
16092
+ if (!response.ok)
16093
+ throw new Error("Could not check the latest Harness version");
16094
+ return response.text();
16095
+ };
16096
+ try {
16097
+ return await request();
16098
+ } catch (error51) {
16099
+ if (error51 instanceof DOMException && (error51.name === "AbortError" || error51.name === "TimeoutError"))
16100
+ throw error51;
16101
+ return request();
16102
+ }
16103
+ }
16104
+
15716
16105
  // dist/command.js
15717
16106
  var piDiscoverySpec = {
15718
16107
  id: "pi",
@@ -15780,6 +16169,15 @@ function describeOauth(credential) {
15780
16169
  ...match ? { vendor: match.vendor } : {}
15781
16170
  };
15782
16171
  }
16172
+ function readPiCodexProviderNames(environment) {
16173
+ const agentDir = environment.PI_CODING_AGENT_DIR ?? path5.join(environment.HOME ?? environment.USERPROFILE ?? os2.homedir(), ".pi/agent");
16174
+ try {
16175
+ const auth = parseAuth(readFileSync(path5.join(agentDir, "auth.json"), "utf8"));
16176
+ return Object.entries(auth).filter(([, credential]) => describeOauth(credential).vendor === "openai-codex").map(([provider]) => provider);
16177
+ } catch {
16178
+ return [];
16179
+ }
16180
+ }
15783
16181
  function writeAuth(filename, content) {
15784
16182
  const temporary = `${filename}.${randomUUID()}.tmp`;
15785
16183
  try {
@@ -15790,8 +16188,8 @@ function writeAuth(filename, content) {
15790
16188
  }
15791
16189
  }
15792
16190
  function removeOwnedFiles(dir) {
15793
- rmSync(path3.join(dir, "index.ts"), { force: true });
15794
- rmSync(path3.join(dir, "import.json"), { force: true });
16191
+ rmSync(path5.join(dir, "index.ts"), { force: true });
16192
+ rmSync(path5.join(dir, "import.json"), { force: true });
15795
16193
  try {
15796
16194
  rmdirSync(dir);
15797
16195
  } catch {
@@ -15799,26 +16197,26 @@ function removeOwnedFiles(dir) {
15799
16197
  }
15800
16198
  async function installation(command, environment, authPath) {
15801
16199
  const executable = await realpath(resolvePiExecutable({ ...command ? { command } : {}, environment }));
15802
- let directory = path3.dirname(executable);
16200
+ let directory = path5.dirname(executable);
15803
16201
  while (true) {
15804
- const manifest = path3.join(directory, "package.json");
16202
+ const manifest = path5.join(directory, "package.json");
15805
16203
  if (existsSync(manifest)) {
15806
16204
  const pkg = JSON.parse(readFileSync(manifest, "utf8"));
15807
16205
  if (pkg.name === "@earendil-works/pi-coding-agent")
15808
16206
  break;
15809
16207
  }
15810
- const parent = path3.dirname(directory);
16208
+ const parent = path5.dirname(directory);
15811
16209
  if (parent === directory)
15812
16210
  throw new Error("Pi credential import requires a supported npm Pi installation");
15813
16211
  directory = parent;
15814
16212
  }
15815
- const storage = await import(pathToFileURL(path3.join(directory, "dist/core/auth-storage.js")).href);
15816
- const ai = path3.join(directory, "node_modules/@earendil-works/pi-ai/dist");
15817
- const all = await import(pathToFileURL(path3.join(ai, "providers/all.js")).href);
16213
+ const storage = await import(pathToFileURL(path5.join(directory, "dist/core/auth-storage.js")).href);
16214
+ const ai = path5.join(directory, "node_modules/@earendil-works/pi-ai/dist");
16215
+ const all = await import(pathToFileURL(path5.join(ai, "providers/all.js")).href);
15818
16216
  const providers = all.getBuiltinProviders();
15819
16217
  const providerModules = {
15820
- "openai-codex": pathToFileURL(path3.join(ai, "providers/openai-codex.js")).href,
15821
- xai: pathToFileURL(path3.join(ai, "providers/xai.js")).href
16218
+ "openai-codex": pathToFileURL(path5.join(ai, "providers/openai-codex.js")).href,
16219
+ xai: pathToFileURL(path5.join(ai, "providers/xai.js")).href
15822
16220
  };
15823
16221
  for (const [id, url2] of Object.entries(providerModules)) {
15824
16222
  const module = await import(url2);
@@ -15831,9 +16229,9 @@ async function installation(command, environment, authPath) {
15831
16229
  providerModules,
15832
16230
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
15833
16231
  async configuredProviderNames() {
15834
- const { stdout } = await promisify(execFile)(process.execPath, [executable, "--offline", "--no-approve", "--list-models"], {
15835
- cwd: existsSync(path3.dirname(authPath)) ? path3.dirname(authPath) : os2.homedir(),
15836
- env: { ...environment, PI_CODING_AGENT_DIR: path3.dirname(authPath), PI_OFFLINE: "1" },
16232
+ const { stdout } = await promisify(execFile2)(process.execPath, [executable, "--offline", "--no-approve", "--list-models"], {
16233
+ cwd: existsSync(path5.dirname(authPath)) ? path5.dirname(authPath) : os2.homedir(),
16234
+ env: { ...environment, PI_CODING_AGENT_DIR: path5.dirname(authPath), PI_OFFLINE: "1" },
15837
16235
  timeout: 15e3,
15838
16236
  maxBuffer: 4 * 1024 * 1024
15839
16237
  });
@@ -15863,26 +16261,26 @@ export default async function (pi) {
15863
16261
  }
15864
16262
  function createPiCredentialImports(options = {}) {
15865
16263
  const env = { ...process.env, ...options.environment };
15866
- const agentDir = env.PI_CODING_AGENT_DIR ?? path3.join(env.HOME ?? os2.homedir(), ".pi/agent");
15867
- const authPath = path3.join(agentDir, "auth.json");
15868
- const extensionsDir = path3.join(agentDir, "extensions");
16264
+ const agentDir = env.PI_CODING_AGENT_DIR ?? path5.join(env.HOME ?? os2.homedir(), ".pi/agent");
16265
+ const authPath = path5.join(agentDir, "auth.json");
16266
+ const extensionsDir = path5.join(agentDir, "extensions");
15869
16267
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
15870
16268
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
15871
- const location = (name) => path3.join(extensionsDir, `${PREFIX}${credentialImportNameSchema.parse(name)}`);
16269
+ const location = (name) => path5.join(extensionsDir, `${PREFIX}${credentialImportNameSchema.parse(name)}`);
15872
16270
  const readRecord = (name) => {
15873
16271
  const dir = location(name);
15874
16272
  if (lstatSync(dir).isSymbolicLink())
15875
16273
  throw new Error("Imported configuration was changed; manage it in Pi");
15876
- const value = JSON.parse(readFileSync(path3.join(dir, "import.json"), "utf8"));
16274
+ const value = JSON.parse(readFileSync(path5.join(dir, "import.json"), "utf8"));
15877
16275
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
15878
16276
  throw new Error("Invalid import metadata");
15879
- const record6 = value.record;
15880
- if (!object2(record6))
16277
+ const record7 = value.record;
16278
+ if (!object2(record7))
15881
16279
  throw new Error("Invalid import metadata");
15882
16280
  value.record = credentialImportRecordSchema.parse({
15883
- name: record6.name,
15884
- source: record6.source,
15885
- importedAt: record6.importedAt
16281
+ name: record7.name,
16282
+ source: record7.source,
16283
+ importedAt: record7.importedAt
15886
16284
  });
15887
16285
  if (value.record.name !== name)
15888
16286
  throw new Error("Import identity mismatch");
@@ -15890,7 +16288,7 @@ function createPiCredentialImports(options = {}) {
15890
16288
  };
15891
16289
  const owned = (meta3, auth) => {
15892
16290
  const credential = auth[meta3.record.name];
15893
- const file2 = path3.join(location(meta3.record.name), "index.ts");
16291
+ const file2 = path5.join(location(meta3.record.name), "index.ts");
15894
16292
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
15895
16293
  };
15896
16294
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -15904,7 +16302,7 @@ function createPiCredentialImports(options = {}) {
15904
16302
  const name = entry.slice(PREFIX.length);
15905
16303
  if (!credentialImportNameSchema.safeParse(name).success)
15906
16304
  continue;
15907
- if (!existsSync(path3.join(location(name), "import.json")))
16305
+ if (!existsSync(path5.join(location(name), "import.json")))
15908
16306
  continue;
15909
16307
  try {
15910
16308
  const meta3 = readRecord(name);
@@ -15925,7 +16323,7 @@ function createPiCredentialImports(options = {}) {
15925
16323
  },
15926
16324
  async listOthers() {
15927
16325
  const auth = readAuth();
15928
- const ours = new Set(ownedRecords(auth).map((record6) => record6.name));
16326
+ const ours = new Set(ownedRecords(auth).map((record7) => record7.name));
15929
16327
  const result = /* @__PURE__ */ new Map();
15930
16328
  const usable = (provider) => Boolean(provider) && provider.length <= 128 && !ours.has(provider) && !result.has(provider);
15931
16329
  for (const [provider, credential] of Object.entries(auth)) {
@@ -15938,7 +16336,7 @@ function createPiCredentialImports(options = {}) {
15938
16336
  ...describeOauth(credential)
15939
16337
  });
15940
16338
  }
15941
- const modelsPath = path3.join(agentDir, "models.json");
16339
+ const modelsPath = path5.join(agentDir, "models.json");
15942
16340
  if (existsSync(modelsPath)) {
15943
16341
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
15944
16342
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -15960,7 +16358,7 @@ function createPiCredentialImports(options = {}) {
15960
16358
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
15961
16359
  throw new Error("Provider name already exists; choose another name");
15962
16360
  const owner = randomUUID();
15963
- const record6 = credentialImportRecordSchema.parse({
16361
+ const record7 = credentialImportRecordSchema.parse({
15964
16362
  name,
15965
16363
  source: transfer.source,
15966
16364
  importedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -15972,15 +16370,15 @@ function createPiCredentialImports(options = {}) {
15972
16370
  try {
15973
16371
  sdk.backend.withLock((current) => {
15974
16372
  const auth = parseAuth(current);
15975
- const modelsPath = path3.join(agentDir, "models.json");
16373
+ const modelsPath = path5.join(agentDir, "models.json");
15976
16374
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
15977
- if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path3.join(extensionsDir, `${name}-provider.ts`)))
16375
+ if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path5.join(extensionsDir, `${name}-provider.ts`)))
15978
16376
  throw new Error("Provider name already exists; choose another name");
15979
16377
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
15980
16378
  mkdirSync(dir, { mode: 448 });
15981
16379
  created = true;
15982
- writeFileSync(path3.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record6, extension }), { flag: "wx", mode: 384 });
15983
- writeFileSync(path3.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
16380
+ writeFileSync(path5.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record7, extension }), { flag: "wx", mode: 384 });
16381
+ writeFileSync(path5.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
15984
16382
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
15985
16383
  saveAuth(auth);
15986
16384
  committed = true;
@@ -15999,7 +16397,7 @@ function createPiCredentialImports(options = {}) {
15999
16397
  const auth = parseAuth(current);
16000
16398
  if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
16001
16399
  throw new Error("Import ownership or source account changed; refusing replacement");
16002
- const metadataPath = path3.join(location(name), "import.json");
16400
+ const metadataPath = path5.join(location(name), "import.json");
16003
16401
  const previous = readFileSync(metadataPath, "utf8");
16004
16402
  const updated = {
16005
16403
  ...meta3,
@@ -16033,15 +16431,229 @@ function createPiCredentialImports(options = {}) {
16033
16431
  };
16034
16432
  }
16035
16433
 
16434
+ // dist/pi-fast-mode.js
16435
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
16436
+ import { mkdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
16437
+ import { homedir as homedir3 } from "node:os";
16438
+ import path6 from "node:path";
16439
+
16440
+ // dist/pi-model-catalog.js
16441
+ var PI_MODEL_REF_PREFIX = "pi-model-v1.";
16442
+ var PI_DRAFT_THINKING_OPTION_IDS = [
16443
+ "off",
16444
+ "minimal",
16445
+ "low",
16446
+ "medium",
16447
+ "high",
16448
+ "xhigh",
16449
+ "max"
16450
+ ].map((id) => harnessThinkingOptionIdSchema.parse(id));
16451
+ var PI_THINKING_LABELS = {
16452
+ off: "Off",
16453
+ minimal: "Minimal",
16454
+ low: "Low",
16455
+ medium: "Medium",
16456
+ high: "High",
16457
+ xhigh: "Extra High",
16458
+ max: "Max"
16459
+ };
16460
+ function compareText(left, right) {
16461
+ return left < right ? -1 : left > right ? 1 : 0;
16462
+ }
16463
+ function assertNativePart(value, name) {
16464
+ if (value.trim().length === 0)
16465
+ throw new Error(`Pi ${name} must not be empty`);
16466
+ }
16467
+ function encodePiModelRef(model) {
16468
+ assertNativePart(model.provider, "Model provider");
16469
+ assertNativePart(model.id, "Model id");
16470
+ const encoded = Buffer.from(JSON.stringify(model.fast ? [model.provider, model.id, true] : [model.provider, model.id]), "utf8").toString("base64url");
16471
+ return harnessModelRefSchema.parse({ id: `${PI_MODEL_REF_PREFIX}${encoded}` });
16472
+ }
16473
+ function decodePiModelRef(ref) {
16474
+ const parsedRef = harnessModelRefSchema.parse(ref);
16475
+ if (!parsedRef.id.startsWith(PI_MODEL_REF_PREFIX)) {
16476
+ throw new Error("Model Ref does not belong to PiAdapter");
16477
+ }
16478
+ const encoded = parsedRef.id.slice(PI_MODEL_REF_PREFIX.length);
16479
+ let decoded;
16480
+ try {
16481
+ decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
16482
+ } catch {
16483
+ throw new Error("Pi Model Ref is malformed");
16484
+ }
16485
+ if (!Array.isArray(decoded) || decoded.length !== 2 && !(decoded.length === 3 && decoded[2] === true) || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
16486
+ throw new Error("Pi Model Ref has an invalid native identity");
16487
+ }
16488
+ const native = {
16489
+ provider: decoded[0],
16490
+ id: decoded[1],
16491
+ ...decoded[2] === true ? { fast: true } : {}
16492
+ };
16493
+ assertNativePart(native.provider, "Model provider");
16494
+ assertNativePart(native.id, "Model id");
16495
+ if (encodePiModelRef(native).id !== parsedRef.id) {
16496
+ throw new Error("Pi Model Ref is not canonical");
16497
+ }
16498
+ return native;
16499
+ }
16500
+ function samePiModel(left, right) {
16501
+ return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
16502
+ }
16503
+ function fallbackThinkingLabel(id) {
16504
+ const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16505
+ return label || id;
16506
+ }
16507
+ function normalizePiThinkingOptions(levels) {
16508
+ return levels.map((id) => harnessThinkingOptionSchema.parse({
16509
+ id,
16510
+ label: PI_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
16511
+ }));
16512
+ }
16513
+ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
16514
+ const byRef = /* @__PURE__ */ new Map();
16515
+ for (const native of nativeModels) {
16516
+ const ref = encodePiModelRef(native);
16517
+ const existing = byRef.get(ref.id);
16518
+ if (existing) {
16519
+ if (existing.reasoning !== native.reasoning) {
16520
+ throw new Error("Pi duplicate Model entries disagree on reasoning capability");
16521
+ }
16522
+ continue;
16523
+ }
16524
+ byRef.set(ref.id, {
16525
+ model: {
16526
+ ref,
16527
+ label: `${native.provider} / ${native.id}`
16528
+ },
16529
+ reasoning: native.reasoning
16530
+ });
16531
+ }
16532
+ const defaultModel = effectiveModel ? encodePiModelRef(effectiveModel) : void 0;
16533
+ if (defaultModel && !byRef.has(defaultModel.id)) {
16534
+ throw new Error("Pi effective Model is absent from the available Model catalog");
16535
+ }
16536
+ if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
16537
+ throw new Error("Pi effective Thinking option is absent from the available option catalog");
16538
+ }
16539
+ if (thinkingLevels && !effectiveThinkingOptionId) {
16540
+ throw new Error("Pi did not report an effective Thinking option");
16541
+ }
16542
+ const thinkingOptions = thinkingLevels ? normalizePiThinkingOptions(PI_DRAFT_THINKING_OPTION_IDS) : [];
16543
+ const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
16544
+ const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
16545
+ const models = [...byRef.values()].map(({ model, reasoning }) => ({
16546
+ ...model,
16547
+ supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
16548
+ })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16549
+ const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
16550
+ return harnessModelCatalogSchema.parse({
16551
+ models,
16552
+ ...defaultModel ? { defaultModel } : {},
16553
+ thinkingOptions,
16554
+ ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
16555
+ });
16556
+ }
16557
+
16558
+ // dist/pi-fast-mode.js
16559
+ var PI_FAST_COMMAND = "codexhost-fast-mode";
16560
+ var PI_FAST_ACK = "codexhost-fast-mode:";
16561
+ var PI_FAST_EXTENSION = `export default function(pi) {
16562
+ let target;
16563
+ const wrapped = new Set();
16564
+ pi.on("model_select", (_event, ctx) => {
16565
+ if (target && (target.provider !== ctx.model?.provider || target.id !== ctx.model?.id || ctx.model?.api !== "openai-codex-responses")) target = undefined;
16566
+ });
16567
+ pi.on("session_start", (_event, ctx) => {
16568
+ if (typeof ctx.modelRegistry.getProvider !== "function") return;
16569
+ pi.registerCommand("${PI_FAST_COMMAND}", {
16570
+ description: "Codex Host Fast mode",
16571
+ handler: async (args, ctx) => {
16572
+ const [mode, nonce] = args.split(" ");
16573
+ if (!nonce || (mode !== "on" && mode !== "off")) throw new Error("Invalid Fast selection");
16574
+ if (mode === "on") {
16575
+ const model = ctx.model;
16576
+ if (!model || model.api !== "openai-codex-responses") throw new Error("Fast requires the Codex API");
16577
+ const original = ctx.modelRegistry.getProvider(model.provider);
16578
+ if (!original) throw new Error("Codex Provider is unavailable");
16579
+ if (!wrapped.has(model.provider)) {
16580
+ const options = (model, value) => target && model.api === "openai-codex-responses" && target.provider === model.provider && target.id === model.id
16581
+ ? {
16582
+ ...value,
16583
+ serviceTier: "priority",
16584
+ // Pi streamSimple drops serviceTier but preserves onPayload.
16585
+ onPayload: async (payload, requestModel) => {
16586
+ const request = { ...payload, service_tier: "priority" };
16587
+ const replacement = await value?.onPayload?.(request, requestModel);
16588
+ return { ...(replacement === undefined ? request : replacement), service_tier: "priority" };
16589
+ },
16590
+ } : value;
16591
+ pi.registerProvider({
16592
+ ...original,
16593
+ stream: (model, context, value) => original.stream(model, context, options(model, value)),
16594
+ streamSimple: (model, context, value) => original.streamSimple(model, context, options(model, value)),
16595
+ });
16596
+ wrapped.add(model.provider);
16597
+ }
16598
+ target = { provider: model.provider, id: model.id };
16599
+ } else target = undefined;
16600
+ ctx.ui.notify("${PI_FAST_ACK}" + nonce + ":" + mode, "info");
16601
+ },
16602
+ });
16603
+ });
16604
+ }
16605
+ `;
16606
+ async function ensurePiFastExtension(environment) {
16607
+ const digest = createHash("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
16608
+ const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path6.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".codexhost");
16609
+ const directory = path6.resolve(dataDirectory, "extensions", "pi-codex-fast");
16610
+ const file2 = path6.join(directory, `${digest}.mjs`);
16611
+ if (await readFile2(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
16612
+ return file2;
16613
+ await mkdir(directory, { recursive: true });
16614
+ const temporary = `${file2}.${randomUUID2()}.tmp`;
16615
+ try {
16616
+ await writeFile(temporary, PI_FAST_EXTENSION, { mode: 384 });
16617
+ try {
16618
+ await rename(temporary, file2);
16619
+ } catch (error51) {
16620
+ if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
16621
+ throw error51;
16622
+ }
16623
+ } finally {
16624
+ await rm(temporary, { force: true });
16625
+ }
16626
+ return file2;
16627
+ }
16628
+ async function piFastModelKeys(models, environment) {
16629
+ try {
16630
+ const codexHome = environment.CODEX_HOME ?? path6.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".codex");
16631
+ const cache = JSON.parse(await readFile2(path6.join(codexHome, "models_cache.json"), "utf8"));
16632
+ if (!cache || typeof cache !== "object" || !("models" in cache) || !Array.isArray(cache.models))
16633
+ return /* @__PURE__ */ new Set();
16634
+ const priority = new Set(cache.models.filter((model) => typeof model?.slug === "string" && Array.isArray(model.service_tiers) && model.service_tiers.some((tier) => tier?.id === "priority")).map((model) => model.slug));
16635
+ const codexProviders = new Set(readPiCodexProviderNames(environment));
16636
+ return new Set(models.filter((model) => model.api === "openai-codex-responses" && codexProviders.has(model.provider) && priority.has(model.id)).map((model) => encodePiModelRef(model).id));
16637
+ } catch {
16638
+ return /* @__PURE__ */ new Set();
16639
+ }
16640
+ }
16641
+ function withPiFast(catalog, supported) {
16642
+ return {
16643
+ ...catalog,
16644
+ models: catalog.models.map((model) => supported.has(model.ref.id) ? { ...model, fastModel: encodePiModelRef({ ...decodePiModelRef(model.ref), fast: true }) } : model)
16645
+ };
16646
+ }
16647
+
16036
16648
  // dist/pi-empty-session.js
16037
16649
  import { createReadStream } from "node:fs";
16038
16650
  import { createInterface } from "node:readline";
16039
- import { randomUUID as randomUUID2 } from "node:crypto";
16040
- import { link, open as open2, rm } from "node:fs/promises";
16041
- import path4 from "node:path";
16651
+ import { randomUUID as randomUUID3 } from "node:crypto";
16652
+ import { link, open as open2, rm as rm2 } from "node:fs/promises";
16653
+ import path7 from "node:path";
16042
16654
 
16043
16655
  // dist/pi-subagents.js
16044
- import { createHash } from "node:crypto";
16656
+ import { createHash as createHash2 } from "node:crypto";
16045
16657
 
16046
16658
  // dist/pi-subagent-workflow.js
16047
16659
  var PREFIX2 = "pi-subagents-workflow-v1:";
@@ -16055,23 +16667,23 @@ var STATES = {
16055
16667
  rejected: "failed",
16056
16668
  detached: "running"
16057
16669
  };
16058
- function record2(value) {
16670
+ function record3(value) {
16059
16671
  return typeof value === "object" && value !== null && !Array.isArray(value);
16060
16672
  }
16061
16673
  function text(value, limit = 256) {
16062
16674
  return typeof value === "string" && value.length > 0 && value.length <= limit;
16063
16675
  }
16064
16676
  function piWorkflowSummary(result) {
16065
- if (!record2(result) || !record2(result.details) || result.details.mode !== "workflow" || result.details.asyncId !== void 0)
16677
+ if (!record3(result) || !record3(result.details) || result.details.mode !== "workflow" || result.details.asyncId !== void 0)
16066
16678
  return null;
16067
16679
  const details = result.details;
16068
16680
  const summary = details.workflowChildren;
16069
- if (!record2(summary) || summary.version !== 1 || !text(summary.workflowRunId) || summary.workflowRunId !== details.runId || !text(summary.parentToolCallId) || typeof summary.inventoryComplete !== "boolean" || !Array.isArray(summary.children) || summary.children.length > 256)
16681
+ if (!record3(summary) || summary.version !== 1 || !text(summary.workflowRunId) || summary.workflowRunId !== details.runId || !text(summary.parentToolCallId) || typeof summary.inventoryComplete !== "boolean" || !Array.isArray(summary.children) || summary.children.length > 256)
16070
16682
  return null;
16071
16683
  const children = [];
16072
16684
  const seen = /* @__PURE__ */ new Set();
16073
16685
  for (const child of summary.children) {
16074
- if (!record2(child) || !text(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
16686
+ if (!record3(child) || !text(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
16075
16687
  return null;
16076
16688
  for (const key of ["agent", "sessionName", "model", "thinking"]) {
16077
16689
  if (child[key] !== void 0 && !text(child[key], 2048))
@@ -16144,7 +16756,7 @@ var STATUS_PREFIX = "PI_SUBAGENT_ASYNC_JSON:";
16144
16756
  var INSPECT_PREFIX = "PI_SUBAGENT_INSPECT_JSON:";
16145
16757
  var ID_PREFIX = "pi-subagents-v1:";
16146
16758
  var MAX_BYTES = 64 * 1024;
16147
- function record3(value) {
16759
+ function record4(value) {
16148
16760
  return typeof value === "object" && value !== null && !Array.isArray(value);
16149
16761
  }
16150
16762
  function token(value) {
@@ -16161,7 +16773,7 @@ var statuses = {
16161
16773
  rejected: "failed"
16162
16774
  };
16163
16775
  function node(value, depth, budget) {
16164
- if (!record3(value) || depth > 8 || ++budget.count > 256 || !token(value.id) || !["subagent", "workflow", "step", "host-step"].includes(String(value.kind)) || typeof value.label !== "string" || value.label.length > 2048 || typeof value.state !== "string" || !Object.hasOwn(statuses, value.state))
16776
+ if (!record4(value) || depth > 8 || ++budget.count > 256 || !token(value.id) || !["subagent", "workflow", "step", "host-step"].includes(String(value.kind)) || typeof value.label !== "string" || value.label.length > 2048 || typeof value.state !== "string" || !Object.hasOwn(statuses, value.state))
16165
16777
  return null;
16166
16778
  const children = [];
16167
16779
  if (value.children !== void 0) {
@@ -16183,14 +16795,14 @@ function node(value, depth, budget) {
16183
16795
  };
16184
16796
  }
16185
16797
  function widget(value, key, prefix) {
16186
- if (!record3(value) || value.type !== "extension_ui_request" || value.method !== "setWidget" || value.widgetKey !== key || !Array.isArray(value.widgetLines))
16798
+ if (!record4(value) || value.type !== "extension_ui_request" || value.method !== "setWidget" || value.widgetKey !== key || !Array.isArray(value.widgetLines))
16187
16799
  return null;
16188
16800
  const line = value.widgetLines.find((part) => typeof part === "string" && part.startsWith(prefix));
16189
16801
  if (!line || Buffer.byteLength(line) > MAX_BYTES + prefix.length)
16190
16802
  return null;
16191
16803
  try {
16192
16804
  const parsed = JSON.parse(line.slice(prefix.length));
16193
- return record3(parsed) && parsed.version === 1 ? parsed : null;
16805
+ return record4(parsed) && parsed.version === 1 ? parsed : null;
16194
16806
  } catch {
16195
16807
  return null;
16196
16808
  }
@@ -16254,7 +16866,7 @@ function states(run) {
16254
16866
  return result;
16255
16867
  }
16256
16868
  function asyncRunId(toolName, result) {
16257
- if (toolName !== "subagent" || !record3(result) || !record3(result.details))
16869
+ if (toolName !== "subagent" || !record4(result) || !record4(result.details))
16258
16870
  return null;
16259
16871
  const details = result.details;
16260
16872
  return ["single", "parallel", "chain", "workflow"].includes(String(details.mode)) && token(details.asyncId) && typeof details.asyncDir === "string" ? details.asyncId : null;
@@ -16394,15 +17006,15 @@ function parsePiSubagentInspection(value) {
16394
17006
  const parsed = widget(value, "subagent-inspect", INSPECT_PREFIX);
16395
17007
  if (!parsed || parsed.kind !== "pi-subagents.inspect-reply" || !token(parsed.requestId))
16396
17008
  return null;
16397
- if (parsed.error !== void 0 && (!record3(parsed.error) || typeof parsed.error.code !== "string" || typeof parsed.error.message !== "string"))
17009
+ if (parsed.error !== void 0 && (!record4(parsed.error) || typeof parsed.error.code !== "string" || typeof parsed.error.message !== "string"))
16398
17010
  return null;
16399
17011
  for (const field of ["asyncId", "childId", "status", "task", "finalOutput"]) {
16400
17012
  if (parsed[field] !== void 0 && typeof parsed[field] !== "string")
16401
17013
  return null;
16402
17014
  }
16403
- if (parsed.messages !== void 0 && (!Array.isArray(parsed.messages) || parsed.messages.length > 200 || parsed.messages.some((entry) => !record3(entry) || typeof entry.role !== "string" || typeof entry.text !== "string" || !["text", "toolCall", "toolResult"].includes(String(entry.kind)) || entry.name !== void 0 && typeof entry.name !== "string")))
17015
+ if (parsed.messages !== void 0 && (!Array.isArray(parsed.messages) || parsed.messages.length > 200 || parsed.messages.some((entry) => !record4(entry) || typeof entry.role !== "string" || typeof entry.text !== "string" || !["text", "toolCall", "toolResult"].includes(String(entry.kind)) || entry.name !== void 0 && typeof entry.name !== "string")))
16404
17016
  return null;
16405
- if (parsed.truncated !== void 0 && (!record3(parsed.truncated) || typeof parsed.truncated.task !== "boolean" || typeof parsed.truncated.finalOutput !== "boolean" || !Number.isSafeInteger(parsed.truncated.messages) || Number(parsed.truncated.messages) < 0))
17017
+ if (parsed.truncated !== void 0 && (!record4(parsed.truncated) || typeof parsed.truncated.task !== "boolean" || typeof parsed.truncated.finalOutput !== "boolean" || !Number.isSafeInteger(parsed.truncated.messages) || Number(parsed.truncated.messages) < 0))
16406
17018
  return null;
16407
17019
  return parsed;
16408
17020
  }
@@ -16421,7 +17033,7 @@ ${entry.text}`);
16421
17033
  nativeTurnRef: nativeTurnRefSchema.parse({
16422
17034
  harnessId: "pi",
16423
17035
  nativeSessionId: parentSessionId,
16424
- nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
17036
+ nativeTurnKey: `pi-subagent-${createHash2("sha256").update(id).digest("hex")}`,
16425
17037
  formatVersion: 1
16426
17038
  }),
16427
17039
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
@@ -16429,7 +17041,7 @@ ${entry.text}`);
16429
17041
  item: {
16430
17042
  type: "agentMessage",
16431
17043
  text: text2,
16432
- itemId: hostItemIdSchema.parse(`pi-subagent-${createHash("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
17044
+ itemId: hostItemIdSchema.parse(`pi-subagent-${createHash2("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
16433
17045
  },
16434
17046
  outcome: { status: "succeeded" }
16435
17047
  })),
@@ -16449,120 +17061,6 @@ ${entry.text}`);
16449
17061
  };
16450
17062
  }
16451
17063
 
16452
- // dist/pi-model-catalog.js
16453
- var PI_MODEL_REF_PREFIX = "pi-model-v1.";
16454
- var PI_DRAFT_THINKING_OPTION_IDS = [
16455
- "off",
16456
- "minimal",
16457
- "low",
16458
- "medium",
16459
- "high",
16460
- "xhigh",
16461
- "max"
16462
- ].map((id) => harnessThinkingOptionIdSchema.parse(id));
16463
- var PI_THINKING_LABELS = {
16464
- off: "Off",
16465
- minimal: "Minimal",
16466
- low: "Low",
16467
- medium: "Medium",
16468
- high: "High",
16469
- xhigh: "Extra High",
16470
- max: "Max"
16471
- };
16472
- function compareText(left, right) {
16473
- return left < right ? -1 : left > right ? 1 : 0;
16474
- }
16475
- function assertNativePart(value, name) {
16476
- if (value.trim().length === 0)
16477
- throw new Error(`Pi ${name} must not be empty`);
16478
- }
16479
- function encodePiModelRef(model) {
16480
- assertNativePart(model.provider, "Model provider");
16481
- assertNativePart(model.id, "Model id");
16482
- const encoded = Buffer.from(JSON.stringify([model.provider, model.id]), "utf8").toString("base64url");
16483
- return harnessModelRefSchema.parse({ id: `${PI_MODEL_REF_PREFIX}${encoded}` });
16484
- }
16485
- function decodePiModelRef(ref) {
16486
- const parsedRef = harnessModelRefSchema.parse(ref);
16487
- if (!parsedRef.id.startsWith(PI_MODEL_REF_PREFIX)) {
16488
- throw new Error("Model Ref does not belong to PiAdapter");
16489
- }
16490
- const encoded = parsedRef.id.slice(PI_MODEL_REF_PREFIX.length);
16491
- let decoded;
16492
- try {
16493
- decoded = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
16494
- } catch {
16495
- throw new Error("Pi Model Ref is malformed");
16496
- }
16497
- if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || typeof decoded[1] !== "string") {
16498
- throw new Error("Pi Model Ref has an invalid native identity");
16499
- }
16500
- const native = { provider: decoded[0], id: decoded[1] };
16501
- assertNativePart(native.provider, "Model provider");
16502
- assertNativePart(native.id, "Model id");
16503
- if (encodePiModelRef(native).id !== parsedRef.id) {
16504
- throw new Error("Pi Model Ref is not canonical");
16505
- }
16506
- return native;
16507
- }
16508
- function samePiModel(left, right) {
16509
- return left === null ? right === null : right !== null && left.provider === right.provider && left.id === right.id;
16510
- }
16511
- function fallbackThinkingLabel(id) {
16512
- const label = id.split(/[._~-]+/u).filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16513
- return label || id;
16514
- }
16515
- function normalizePiThinkingOptions(levels) {
16516
- return levels.map((id) => harnessThinkingOptionSchema.parse({
16517
- id,
16518
- label: PI_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
16519
- }));
16520
- }
16521
- function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
16522
- const byRef = /* @__PURE__ */ new Map();
16523
- for (const native of nativeModels) {
16524
- const ref = encodePiModelRef(native);
16525
- const existing = byRef.get(ref.id);
16526
- if (existing) {
16527
- if (existing.reasoning !== native.reasoning) {
16528
- throw new Error("Pi duplicate Model entries disagree on reasoning capability");
16529
- }
16530
- continue;
16531
- }
16532
- byRef.set(ref.id, {
16533
- model: {
16534
- ref,
16535
- label: `${native.provider} / ${native.id}`
16536
- },
16537
- reasoning: native.reasoning
16538
- });
16539
- }
16540
- const defaultModel = effectiveModel ? encodePiModelRef(effectiveModel) : void 0;
16541
- if (defaultModel && !byRef.has(defaultModel.id)) {
16542
- throw new Error("Pi effective Model is absent from the available Model catalog");
16543
- }
16544
- if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
16545
- throw new Error("Pi effective Thinking option is absent from the available option catalog");
16546
- }
16547
- if (thinkingLevels && !effectiveThinkingOptionId) {
16548
- throw new Error("Pi did not report an effective Thinking option");
16549
- }
16550
- const thinkingOptions = thinkingLevels ? normalizePiThinkingOptions(PI_DRAFT_THINKING_OPTION_IDS) : [];
16551
- const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
16552
- const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
16553
- const models = [...byRef.values()].map(({ model, reasoning }) => ({
16554
- ...model,
16555
- supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
16556
- })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
16557
- const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
16558
- return harnessModelCatalogSchema.parse({
16559
- models,
16560
- ...defaultModel ? { defaultModel } : {},
16561
- thinkingOptions,
16562
- ...defaultThinkingOptionId ? { defaultThinkingOptionId } : {}
16563
- });
16564
- }
16565
-
16566
17064
  // dist/pi-history.js
16567
17065
  var piHarnessId = harnessIdSchema.parse("pi");
16568
17066
  function isRecord(value) {
@@ -16868,7 +17366,7 @@ async function verifyPiSessionCwd(input) {
16868
17366
  async function persistEmptyPiSession(input) {
16869
17367
  const { state: state2, history, sourceSessionFile, sourceSessionId, cwd } = input;
16870
17368
  const destination = state2.sessionFile;
16871
- if (!destination || !path4.isAbsolute(destination) || path4.resolve(destination) === path4.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
17369
+ if (!destination || !path7.isAbsolute(destination) || path7.resolve(destination) === path7.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
16872
17370
  throw new Error("Pi empty Session is not an independent empty native fork");
16873
17371
  await verifyPiSessionCwd({
16874
17372
  sessionFile: sourceSessionFile,
@@ -16892,7 +17390,7 @@ async function persistEmptyPiSession(input) {
16892
17390
  cwd,
16893
17391
  parentSession: sourceSessionFile
16894
17392
  };
16895
- const temporary = path4.join(path4.dirname(destination), `.codexhost-${randomUUID2()}.tmp`);
17393
+ const temporary = path7.join(path7.dirname(destination), `.codexhost-${randomUUID3()}.tmp`);
16896
17394
  try {
16897
17395
  const file2 = await open2(temporary, "wx", 384);
16898
17396
  try {
@@ -16903,7 +17401,7 @@ async function persistEmptyPiSession(input) {
16903
17401
  }
16904
17402
  await link(temporary, destination);
16905
17403
  if (process.platform !== "win32") {
16906
- const directory = await open2(path4.dirname(destination), "r");
17404
+ const directory = await open2(path7.dirname(destination), "r");
16907
17405
  try {
16908
17406
  await directory.sync();
16909
17407
  } finally {
@@ -16911,7 +17409,7 @@ async function persistEmptyPiSession(input) {
16911
17409
  }
16912
17410
  }
16913
17411
  } finally {
16914
- await rm(temporary, { force: true });
17412
+ await rm2(temporary, { force: true });
16915
17413
  }
16916
17414
  }
16917
17415
  async function readPiEmptySessionConfiguration(sessionFile) {
@@ -17066,16 +17564,16 @@ var Diff = class {
17066
17564
  }
17067
17565
  }
17068
17566
  }
17069
- addToPath(path10, added, removed, oldPosInc, options) {
17070
- const last = path10.lastComponent;
17567
+ addToPath(path13, added, removed, oldPosInc, options) {
17568
+ const last = path13.lastComponent;
17071
17569
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17072
17570
  return {
17073
- oldPos: path10.oldPos + oldPosInc,
17571
+ oldPos: path13.oldPos + oldPosInc,
17074
17572
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17075
17573
  };
17076
17574
  } else {
17077
17575
  return {
17078
- oldPos: path10.oldPos + oldPosInc,
17576
+ oldPos: path13.oldPos + oldPosInc,
17079
17577
  lastComponent: { count: 1, added, removed, previousComponent: last }
17080
17578
  };
17081
17579
  }
@@ -17487,8 +17985,8 @@ function splitLines(text2) {
17487
17985
  }
17488
17986
 
17489
17987
  // dist/pi-adapter.js
17490
- import { randomUUID as randomUUID5 } from "node:crypto";
17491
- import path9 from "node:path";
17988
+ import { randomUUID as randomUUID6 } from "node:crypto";
17989
+ import path12 from "node:path";
17492
17990
 
17493
17991
  // ../../harness-adapter/dist/question.js
17494
17992
  function invalidRequest(message3) {
@@ -17799,16 +18297,16 @@ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17799
18297
  }
17800
18298
 
17801
18299
  // dist/pi-workflow-child-history.js
17802
- import { createHash as createHash2 } from "node:crypto";
18300
+ import { createHash as createHash3 } from "node:crypto";
17803
18301
  import { constants } from "node:fs";
17804
18302
  import { open as open3 } from "node:fs/promises";
17805
- import path5 from "node:path";
17806
- function record4(value) {
18303
+ import path8 from "node:path";
18304
+ function record5(value) {
17807
18305
  return typeof value === "object" && value !== null && !Array.isArray(value);
17808
18306
  }
17809
18307
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
17810
18308
  async function childHistory(file2, parentSessionId, identity) {
17811
- if (!path5.isAbsolute(file2))
18309
+ if (!path8.isAbsolute(file2))
17812
18310
  throw new Error("Pi child Session path is not absolute");
17813
18311
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
17814
18312
  try {
@@ -17821,18 +18319,18 @@ async function childHistory(file2, parentSessionId, identity) {
17821
18319
  throw new Error("Pi child Session exceeds read bounds");
17822
18320
  const values = buffer.subarray(0, bytesRead).toString("utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
17823
18321
  const header = values[0];
17824
- if (!record4(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
18322
+ if (!record5(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
17825
18323
  throw new Error("Unsupported Pi child Session header");
17826
18324
  const entries = [];
17827
18325
  for (const entry of values.slice(1)) {
17828
18326
  const parsed = jsonValueSchema.safeParse(entry);
17829
- if (!parsed.success || !record4(parsed.data) || typeof parsed.data.id !== "string")
18327
+ if (!parsed.success || !record5(parsed.data) || typeof parsed.data.id !== "string")
17830
18328
  throw new Error("Malformed Pi child Session entry");
17831
18329
  entries.push(parsed.data);
17832
18330
  }
17833
18331
  const history = { entries, leafId: String(entries.at(-1)?.id ?? "") || null };
17834
18332
  const snapshot = mapPiSnapshot(history, { sessionId: parentSessionId, model: null });
17835
- const prefix = createHash2("sha256").update(identity).digest("hex");
18333
+ const prefix = createHash3("sha256").update(identity).digest("hex");
17836
18334
  return {
17837
18335
  turns: snapshot.turns.map((turn) => {
17838
18336
  const readonlyTurn = {
@@ -17853,7 +18351,7 @@ async function childHistory(file2, parentSessionId, identity) {
17853
18351
  async function readPiWorkflowChild(history, parentSessionId, address) {
17854
18352
  for (const entry of activePiEntries(history).reverse()) {
17855
18353
  const message3 = entry.message;
17856
- if (!record4(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
18354
+ if (!record5(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
17857
18355
  continue;
17858
18356
  const summary = piWorkflowSummary(message3);
17859
18357
  if (!summary || summary.workflowRunId !== address.workflowRunId || summary.parentToolCallId !== message3.toolCallId)
@@ -17862,10 +18360,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
17862
18360
  if (!child)
17863
18361
  break;
17864
18362
  const details = message3.details;
17865
- if (!record4(details) || !Array.isArray(details.results))
18363
+ if (!record5(details) || !Array.isArray(details.results))
17866
18364
  break;
17867
- const result = details.results.findLast((candidate) => record4(candidate) && candidate.workflowKey === address.childId);
17868
- if (!record4(result))
18365
+ const result = details.results.findLast((candidate) => record5(candidate) && candidate.workflowKey === address.childId);
18366
+ if (!record5(result))
17869
18367
  break;
17870
18368
  const id = piWorkflowSubagentId(address);
17871
18369
  if (typeof result.sessionFile === "string") {
@@ -17911,22 +18409,22 @@ ${output}`,
17911
18409
  // dist/pi-subagent-history.js
17912
18410
  import { constants as constants2 } from "node:fs";
17913
18411
  import { open as open4 } from "node:fs/promises";
17914
- import path6 from "node:path";
17915
- function record5(value) {
18412
+ import path9 from "node:path";
18413
+ function record6(value) {
17916
18414
  return typeof value === "object" && value !== null && !Array.isArray(value);
17917
18415
  }
17918
18416
  function state(value) {
17919
18417
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
17920
18418
  }
17921
18419
  function piSubagentArtifact(value, runId, parentSessionId) {
17922
- if (!record5(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
18420
+ if (!record6(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
17923
18421
  return null;
17924
18422
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
17925
18423
  return null;
17926
18424
  const steps = Array.isArray(value.steps) ? value.steps : [];
17927
18425
  const children = [];
17928
18426
  for (const [index, step] of steps.entries()) {
17929
- if (!record5(step) || typeof step.agent !== "string")
18427
+ if (!record6(step) || typeof step.agent !== "string")
17930
18428
  return null;
17931
18429
  children.push({
17932
18430
  id: step.workflowKey ?? step.runId ?? `step:${index}`,
@@ -17959,17 +18457,17 @@ function piSubagentArtifact(value, runId, parentSessionId) {
17959
18457
  async function restorePiSubagents(history, parentSessionId, observer) {
17960
18458
  const receipts = /* @__PURE__ */ new Map();
17961
18459
  for (const entry of activePiEntries(history)) {
17962
- if (!record5(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record5(entry.message.details))
18460
+ if (!record6(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record6(entry.message.details))
17963
18461
  continue;
17964
18462
  const details = entry.message.details;
17965
- if (!["single", "parallel", "chain", "workflow"].includes(String(details.mode)) || typeof details.asyncId !== "string" || typeof details.asyncDir !== "string" || !path6.isAbsolute(details.asyncDir) || path6.basename(details.asyncDir) !== details.asyncId)
18463
+ if (!["single", "parallel", "chain", "workflow"].includes(String(details.mode)) || typeof details.asyncId !== "string" || typeof details.asyncDir !== "string" || !path9.isAbsolute(details.asyncDir) || path9.basename(details.asyncDir) !== details.asyncId)
17966
18464
  continue;
17967
18465
  receipts.set(details.asyncId, details.asyncDir);
17968
18466
  }
17969
18467
  for (const [id, directory] of [...receipts].slice(-128)) {
17970
18468
  let file2;
17971
18469
  try {
17972
- file2 = await open4(path6.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
18470
+ file2 = await open4(path9.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
17973
18471
  const stat2 = await file2.stat();
17974
18472
  if (!stat2.isFile() || stat2.size > 1024 * 1024)
17975
18473
  continue;
@@ -18051,7 +18549,7 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
18051
18549
  import { createReadStream as createReadStream2 } from "node:fs";
18052
18550
  import { opendir, realpath as realpath3, stat } from "node:fs/promises";
18053
18551
  import os3 from "node:os";
18054
- import path7 from "node:path";
18552
+ import path10 from "node:path";
18055
18553
  import { createInterface as createInterface2 } from "node:readline";
18056
18554
  var PiSessionChangedError = class extends Error {
18057
18555
  constructor() {
@@ -18068,7 +18566,7 @@ function missing(error51) {
18068
18566
  return isRecord4(error51) && error51.code === "ENOENT";
18069
18567
  }
18070
18568
  function expandDirectory(value, home) {
18071
- return path7.resolve(value === "~" ? home : value.startsWith(`~${path7.sep}`) || value.startsWith("~/") ? path7.join(home, value.slice(2)) : value);
18569
+ return path10.resolve(value === "~" ? home : value.startsWith(`~${path10.sep}`) || value.startsWith("~/") ? path10.join(home, value.slice(2)) : value);
18072
18570
  }
18073
18571
  function piSessionImportDirectory(environment) {
18074
18572
  const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os3.homedir();
@@ -18077,7 +18575,7 @@ function piSessionImportDirectory(environment) {
18077
18575
  return { directory: expandDirectory(custom2, home), flat: true };
18078
18576
  const agent = environment.PI_CODING_AGENT_DIR;
18079
18577
  return {
18080
- directory: path7.join(agent ? expandDirectory(agent, home) : path7.join(home, ".pi", "agent"), "sessions"),
18578
+ directory: path10.join(agent ? expandDirectory(agent, home) : path10.join(home, ".pi", "agent"), "sessions"),
18081
18579
  flat: false
18082
18580
  };
18083
18581
  }
@@ -18095,9 +18593,9 @@ async function sessionFiles(directory, flat, signal) {
18095
18593
  for await (const entry of entries) {
18096
18594
  signal.throwIfAborted();
18097
18595
  if (projectLevel && entry.isDirectory())
18098
- await visit(path7.join(dir, entry.name), false);
18596
+ await visit(path10.join(dir, entry.name), false);
18099
18597
  else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl")) {
18100
- files.push(path7.join(dir, entry.name));
18598
+ files.push(path10.join(dir, entry.name));
18101
18599
  }
18102
18600
  }
18103
18601
  };
@@ -18130,7 +18628,7 @@ async function readCandidate(file2, signal) {
18130
18628
  if (!isRecord4(entry))
18131
18629
  return null;
18132
18630
  if (!header) {
18133
- if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path7.isAbsolute(entry.cwd))
18631
+ if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path10.isAbsolute(entry.cwd))
18134
18632
  return null;
18135
18633
  header = entry;
18136
18634
  continue;
@@ -18280,8 +18778,8 @@ var PiSessionImportIndex = class {
18280
18778
 
18281
18779
  // dist/pi-rpc-session.js
18282
18780
  import { spawn, spawnSync } from "node:child_process";
18283
- import { randomUUID as randomUUID4 } from "node:crypto";
18284
- import path8 from "node:path";
18781
+ import { randomUUID as randomUUID5 } from "node:crypto";
18782
+ import path11 from "node:path";
18285
18783
 
18286
18784
  // dist/pi-slash-commands.js
18287
18785
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -18303,15 +18801,15 @@ function parsePiNativeCommands(response) {
18303
18801
  return data.commands.flatMap((entry) => {
18304
18802
  if (typeof entry !== "object" || entry === null)
18305
18803
  return [];
18306
- const record6 = entry;
18307
- const name = typeof record6.name === "string" ? record6.name.trim().replace(/^\//u, "") : "";
18804
+ const record7 = entry;
18805
+ const name = typeof record7.name === "string" ? record7.name.trim().replace(/^\//u, "") : "";
18308
18806
  if (!name)
18309
18807
  return [];
18310
18808
  return [
18311
18809
  {
18312
18810
  name,
18313
- ...typeof record6.description === "string" ? { description: record6.description } : {},
18314
- ...typeof record6.source === "string" ? { source: record6.source } : {}
18811
+ ...typeof record7.description === "string" ? { description: record7.description } : {},
18812
+ ...typeof record7.source === "string" ? { source: record7.source } : {}
18315
18813
  }
18316
18814
  ];
18317
18815
  });
@@ -18399,7 +18897,7 @@ function optionalPiStateContextUsage(value) {
18399
18897
  }
18400
18898
 
18401
18899
  // dist/pi-subagent-rpc.js
18402
- import { randomUUID as randomUUID3 } from "node:crypto";
18900
+ import { randomUUID as randomUUID4 } from "node:crypto";
18403
18901
  var PiSubagentRpc = class {
18404
18902
  send;
18405
18903
  timeoutMs;
@@ -18441,7 +18939,7 @@ var PiSubagentRpc = class {
18441
18939
  if (!Array.isArray(data?.commands) || !data.commands.some((command) => command?.name === "subagents-inspect-rpc" && command.source === "extension")) {
18442
18940
  throw new Error("Installed Pi has no pi-subagents Host inspection command");
18443
18941
  }
18444
- const requestId = randomUUID3();
18942
+ const requestId = randomUUID4();
18445
18943
  const reply = new Promise((resolve, reject) => {
18446
18944
  const timer = setTimeout(() => {
18447
18945
  this.#pending.delete(requestId);
@@ -18587,7 +19085,11 @@ function parseAvailableModels(response) {
18587
19085
  if (!parsed || !isRecord6(model) || typeof model.reasoning !== "boolean") {
18588
19086
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
18589
19087
  }
18590
- return { ...parsed, reasoning: model.reasoning };
19088
+ return {
19089
+ ...parsed,
19090
+ reasoning: model.reasoning,
19091
+ ...typeof model.api === "string" ? { api: model.api } : {}
19092
+ };
18591
19093
  });
18592
19094
  }
18593
19095
  function assistantText(value) {
@@ -18672,13 +19174,14 @@ function piRpcProcessCommand(options, dependencies = {}) {
18672
19174
  const modelArguments = startupModel ? ["--provider", startupModel.provider, "--model", startupModel.id] : [];
18673
19175
  const thinkingArguments = options.emptySessionConfiguration ? ["--thinking", options.emptySessionConfiguration.thinkingLevel] : [];
18674
19176
  const arguments_ = [
19177
+ ...options.fastExtension ? ["--extension", options.fastExtension] : [],
18675
19178
  "--mode",
18676
19179
  "rpc",
18677
19180
  ...modelArguments,
18678
19181
  ...thinkingArguments,
18679
19182
  ...sessionArguments
18680
19183
  ];
18681
- const extension = path8.win32.extname(command).toLowerCase();
19184
+ const extension = path11.win32.extname(command).toLowerCase();
18682
19185
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
18683
19186
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
18684
19187
  }
@@ -18717,6 +19220,8 @@ var PiRpcSession = class {
18717
19220
  #failed = false;
18718
19221
  #pending = /* @__PURE__ */ new Map();
18719
19222
  #state = null;
19223
+ #fast = null;
19224
+ #fastAcknowledgement = null;
18720
19225
  #latestCacheHitRatePercent;
18721
19226
  #manualCompaction = null;
18722
19227
  #stderrTail = "";
@@ -18743,7 +19248,9 @@ var PiRpcSession = class {
18743
19248
  get state() {
18744
19249
  if (!this.#state)
18745
19250
  throw new Error("Pi RPC Session has not started");
18746
- return this.#state;
19251
+ if (this.#fast && (this.#fast.provider !== this.#state.provider || this.#fast.id !== this.#state.modelId))
19252
+ this.#fast = null;
19253
+ return this.#fast ? { ...this.#state, fast: true } : this.#state;
18747
19254
  }
18748
19255
  get stderrTail() {
18749
19256
  return this.#stderrTail;
@@ -18760,8 +19267,10 @@ var PiRpcSession = class {
18760
19267
  async start() {
18761
19268
  if (this.#child || this.#closed)
18762
19269
  throw new Error("Pi RPC Session cannot be started twice");
19270
+ const fastExtension = this.#processAdapter === nodeProcessAdapter ? await ensurePiFastExtension({ ...process.env, ...this.#options.environment }) : void 0;
18763
19271
  const child = this.#processAdapter.spawn({
18764
19272
  cwd: this.#options.cwd,
19273
+ ...fastExtension ? { fastExtension } : {},
18765
19274
  ...this.#options.command ? { command: this.#options.command } : {},
18766
19275
  environment: withNodeRuntimeOnPath({
18767
19276
  ...process.env,
@@ -18908,7 +19417,36 @@ var PiRpcSession = class {
18908
19417
  throw error51;
18909
19418
  }
18910
19419
  }
19420
+ async supportsFastMode() {
19421
+ return (await this.getCommands()).some((command) => command.name === PI_FAST_COMMAND && command.source === "extension");
19422
+ }
19423
+ async selectFastMode(enabled) {
19424
+ if (!enabled && !this.#fast)
19425
+ return this.state;
19426
+ if (!await this.supportsFastMode())
19427
+ throw new Error("Installed Pi does not support the Host Fast extension");
19428
+ const nonce = randomUUID5();
19429
+ const mode = enabled ? "on" : "off";
19430
+ const acknowledgement = { message: `${PI_FAST_ACK}${nonce}:${mode}`, received: false };
19431
+ this.#fastAcknowledgement = acknowledgement;
19432
+ try {
19433
+ await this.#send("prompt", { message: `/${PI_FAST_COMMAND} ${mode} ${nonce}` });
19434
+ if (!acknowledgement.received)
19435
+ throw new Error("Pi did not confirm the Fast selection");
19436
+ this.#fast = enabled ? { provider: this.state.provider ?? "", id: this.state.modelId ?? "" } : null;
19437
+ return this.state;
19438
+ } catch (error51) {
19439
+ const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi Fast selection could not be confirmed: ${message2(error51)}`);
19440
+ this.#fail(fault);
19441
+ await this.close().catch(() => void 0);
19442
+ throw fault;
19443
+ } finally {
19444
+ this.#fastAcknowledgement = null;
19445
+ }
19446
+ }
18911
19447
  async selectModel(model) {
19448
+ if (this.#fast)
19449
+ await this.selectFastMode(false);
18912
19450
  await this.#send("set_model", { provider: model.provider, modelId: model.id });
18913
19451
  return this.#refreshState("Model");
18914
19452
  }
@@ -18920,7 +19458,7 @@ var PiRpcSession = class {
18920
19458
  async #refreshState(operation) {
18921
19459
  try {
18922
19460
  this.#state = parseSessionState(await this.#send("get_state", {}));
18923
- return this.#state;
19461
+ return this.state;
18924
19462
  } catch (error51) {
18925
19463
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi RPC ${operation} state could not be confirmed: ${message2(error51)}`);
18926
19464
  this.#fail(fault);
@@ -19076,6 +19614,11 @@ var PiRpcSession = class {
19076
19614
  }
19077
19615
  }
19078
19616
  #handle(value) {
19617
+ if (value.type === "extension_ui_request" && value.method === "notify" && typeof value.message === "string" && value.message.startsWith(PI_FAST_ACK)) {
19618
+ if (this.#fastAcknowledgement?.message === value.message)
19619
+ this.#fastAcknowledgement.received = true;
19620
+ return;
19621
+ }
19079
19622
  if (this.#closed || this.#failed)
19080
19623
  return;
19081
19624
  if (value.type === "response") {
@@ -19198,7 +19741,7 @@ var PiRpcSession = class {
19198
19741
  const active = {
19199
19742
  origin: "autonomous",
19200
19743
  autonomousEvents: events,
19201
- nativeTurnKey: assistantMessageId(value) ?? randomUUID4(),
19744
+ nativeTurnKey: assistantMessageId(value) ?? randomUUID5(),
19202
19745
  nativeCancellationObserved: false,
19203
19746
  text: "",
19204
19747
  assistantMessageId: null,
@@ -19461,7 +20004,7 @@ var PiRpcSession = class {
19461
20004
  if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
19462
20005
  active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
19463
20006
  }
19464
- const messageId = assistantMessageId(value) ?? randomUUID4();
20007
+ const messageId = assistantMessageId(value) ?? randomUUID5();
19465
20008
  active.assistantMessageId = messageId;
19466
20009
  active.sawStreamedMessageText = false;
19467
20010
  active.sawStreamedMessageReasoning = false;
@@ -19522,7 +20065,7 @@ var PiRpcSession = class {
19522
20065
  if (!child?.stdin.writable || this.#closed || this.#failed) {
19523
20066
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
19524
20067
  }
19525
- const id = `codexhost-${randomUUID4()}`;
20068
+ const id = `codexhost-${randomUUID5()}`;
19526
20069
  return new Promise((resolve, reject) => {
19527
20070
  const pending = {
19528
20071
  command: type,
@@ -19697,7 +20240,7 @@ function nativeModelFromState(state2) {
19697
20240
  }
19698
20241
  function effectiveModelFromState(state2) {
19699
20242
  const model = nativeModelFromState(state2);
19700
- return model ? encodePiModelRef(model) : void 0;
20243
+ return model ? encodePiModelRef({ ...model, ...state2.fast ? { fast: true } : {} }) : void 0;
19701
20244
  }
19702
20245
  function harnessStateFromPi(state2, thinkingLevels) {
19703
20246
  const effectiveModel = effectiveModelFromState(state2);
@@ -19783,10 +20326,10 @@ function stripDiffPrefix(pathString) {
19783
20326
  return pathString.startsWith("a/") || pathString.startsWith("b/") ? pathString.slice(2) : pathString;
19784
20327
  }
19785
20328
  function displayPath(nativePath, cwd) {
19786
- const resolvedCwd = path9.resolve(cwd);
19787
- const resolvedPath = path9.isAbsolute(nativePath) ? path9.resolve(nativePath) : path9.resolve(cwd, nativePath);
19788
- const relative = path9.relative(resolvedCwd, resolvedPath);
19789
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path9.sep}`);
20329
+ const resolvedCwd = path12.resolve(cwd);
20330
+ const resolvedPath = path12.isAbsolute(nativePath) ? path12.resolve(nativePath) : path12.resolve(cwd, nativePath);
20331
+ const relative = path12.relative(resolvedCwd, resolvedPath);
20332
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path12.sep}`);
19790
20333
  const selected = inside ? relative : resolvedPath;
19791
20334
  const normalized = selected.replaceAll("\\", "/");
19792
20335
  if (normalized.length === 0 || normalized === ".")
@@ -19985,6 +20528,7 @@ var PiHarnessSession = class {
19985
20528
  #requestedModel;
19986
20529
  #requestedThinkingOptionId;
19987
20530
  #toolOutputLimit;
20531
+ #isFastSupported;
19988
20532
  #acceptingTurn = false;
19989
20533
  #active = null;
19990
20534
  #closePromise = null;
@@ -20006,6 +20550,7 @@ var PiHarnessSession = class {
20006
20550
  this.#requestedModel = options.model;
20007
20551
  this.#requestedThinkingOptionId = options.thinkingOptionId;
20008
20552
  this.#toolOutputLimit = options.toolOutputLimit;
20553
+ this.#isFastSupported = options.isFastSupported;
20009
20554
  this.capabilities = {
20010
20555
  configuration: {
20011
20556
  selectModel: true,
@@ -20034,13 +20579,13 @@ var PiHarnessSession = class {
20034
20579
  return this.#transport?.state.sessionId === id;
20035
20580
  }
20036
20581
  async readSubagentHistory(cwd) {
20037
- if (this.#phase !== "open" || path9.resolve(cwd) !== path9.resolve(this.#cwd)) {
20582
+ if (this.#phase !== "open" || path12.resolve(cwd) !== path12.resolve(this.#cwd)) {
20038
20583
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
20039
20584
  }
20040
20585
  return (await this.#ensureTransport()).getEntries();
20041
20586
  }
20042
20587
  async inspectSubagent(id, cwd) {
20043
- if (this.#phase !== "open" || path9.resolve(cwd) !== path9.resolve(this.#cwd)) {
20588
+ if (this.#phase !== "open" || path12.resolve(cwd) !== path12.resolve(this.#cwd)) {
20044
20589
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
20045
20590
  }
20046
20591
  const transport = await this.#ensureTransport();
@@ -20286,20 +20831,27 @@ var PiHarnessSession = class {
20286
20831
  error: invalidState("Pi Model selection requires a started Native Session")
20287
20832
  };
20288
20833
  }
20289
- let requested;
20290
- try {
20291
- requested = decodePiModelRef(command.model);
20292
- } catch (error51) {
20293
- return { ok: false, error: normalizedError(error51, "invalidRequest") };
20294
- }
20295
20834
  const previousModel = this.#state.effectiveModel;
20296
20835
  this.#configuring = true;
20297
20836
  try {
20837
+ let requested;
20838
+ try {
20839
+ requested = decodePiModelRef(command.model);
20840
+ if (requested.fast && !await this.#isFastSupported(command.model, transport))
20841
+ throw new Error("Fast is unavailable for this Pi Model");
20842
+ } catch (error51) {
20843
+ return { ok: false, error: normalizedError(error51, "invalidRequest") };
20844
+ }
20298
20845
  let state2;
20299
20846
  let thinkingLevels;
20300
20847
  try {
20301
- state2 = await transport.selectModel(requested);
20848
+ state2 = samePiModel(nativeModelFromState(transport.state), requested) ? transport.state : await transport.selectModel(requested);
20302
20849
  thinkingLevels = await transport.getAvailableThinkingLevels();
20850
+ if (requested.fast || state2.fast) {
20851
+ if (!transport.selectFastMode)
20852
+ throw new Error("Pi Fast extension is unavailable");
20853
+ state2 = await transport.selectFastMode(requested.fast === true);
20854
+ }
20303
20855
  this.#publishTransportState(state2, thinkingLevels);
20304
20856
  } catch (error51) {
20305
20857
  if (error51 instanceof PiRpcFaultError)
@@ -20436,7 +20988,7 @@ var PiHarnessSession = class {
20436
20988
  const transport = this.#transport;
20437
20989
  if (this.#phase === "open" && transport?.getCommands) {
20438
20990
  try {
20439
- this.#liveCommands = piLiveCommandCatalog(piCommandCatalog, await transport.getCommands());
20991
+ this.#liveCommands = piLiveCommandCatalog(piCommandCatalog, (await transport.getCommands()).filter((command) => command.name !== PI_FAST_COMMAND));
20440
20992
  } catch {
20441
20993
  }
20442
20994
  }
@@ -20583,6 +21135,11 @@ var PiHarnessSession = class {
20583
21135
  this.#publishTransportState(state2, thinkingLevels);
20584
21136
  throw new Error("Pi did not activate the requested create Model");
20585
21137
  }
21138
+ if (requested.fast) {
21139
+ if (!await this.#isFastSupported(this.#requestedModel, transport) || !transport.selectFastMode)
21140
+ throw new Error("Fast is unavailable for this Pi Model");
21141
+ state2 = await transport.selectFastMode(true);
21142
+ }
20586
21143
  }
20587
21144
  if (this.#requestedThinkingOptionId) {
20588
21145
  if (!thinkingLevels) {
@@ -20663,7 +21220,7 @@ var PiHarnessSession = class {
20663
21220
  }));
20664
21221
  return;
20665
21222
  }
20666
- const turnId = hostTurnIdSchema.parse(randomUUID5());
21223
+ const turnId = hostTurnIdSchema.parse(randomUUID6());
20667
21224
  let resolveCompletion = () => void 0;
20668
21225
  const completion = new Promise((resolve) => {
20669
21226
  resolveCompletion = resolve;
@@ -20825,7 +21382,7 @@ var PiHarnessSession = class {
20825
21382
  if (active.interactionByNativeId.has(request.requestId)) {
20826
21383
  throw new Error("Pi Interaction started more than once");
20827
21384
  }
20828
- const interactionId = hostInteractionIdSchema.parse(randomUUID5());
21385
+ const interactionId = hostInteractionIdSchema.parse(randomUUID6());
20829
21386
  const question = request.method === "select" ? {
20830
21387
  id: "answer",
20831
21388
  type: "choice",
@@ -21172,7 +21729,7 @@ var PiHarnessSession = class {
21172
21729
  this.#channel.emit({ kind: "event", event });
21173
21730
  }
21174
21731
  #newItemId() {
21175
- return hostItemIdSchema.parse(randomUUID5());
21732
+ return hostItemIdSchema.parse(randomUUID6());
21176
21733
  }
21177
21734
  };
21178
21735
  var PiAdapter = class {
@@ -21263,6 +21820,7 @@ var PiAdapter = class {
21263
21820
  #inspections = /* @__PURE__ */ new Set();
21264
21821
  #sessions = /* @__PURE__ */ new Set();
21265
21822
  #toolOutputLimit;
21823
+ #environment;
21266
21824
  #closePromise = null;
21267
21825
  #thinkingSelectionSupported = null;
21268
21826
  constructor(options = {}, dependencies = {
@@ -21282,10 +21840,21 @@ var PiAdapter = class {
21282
21840
  remove: (name) => updateCatalog(imports.remove(name))
21283
21841
  };
21284
21842
  this.#createTransport = dependencies.createTransport;
21843
+ this.#environment = options.environment ?? process.env;
21285
21844
  this.#importIndex = new PiSessionImportIndex({ ...process.env, ...options.environment });
21286
21845
  this.#closeTimeoutMs = options.closeTimeoutMs ?? 2e3;
21287
21846
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
21288
21847
  }
21848
+ /** Pi itself holds no Account; this reports configured Provider balances. */
21849
+ async inspectAccounts() {
21850
+ if (this.#closePromise)
21851
+ return [];
21852
+ return fetchPiAccounts({ environment: this.#environment });
21853
+ }
21854
+ async inspectAccount() {
21855
+ const accounts = await this.inspectAccounts();
21856
+ return accounts[0] ?? null;
21857
+ }
21289
21858
  #readImport(operation) {
21290
21859
  if (this.#importAbort.signal.aborted)
21291
21860
  return Promise.resolve({ ok: false, error: invalidState("Pi Adapter is closed") });
@@ -21345,7 +21914,9 @@ var PiAdapter = class {
21345
21914
  stage = "capabilities";
21346
21915
  const thinkingLevels = await transport.getAvailableThinkingLevels();
21347
21916
  this.#thinkingSelectionSupported = thinkingLevels !== null;
21348
- const catalog = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel);
21917
+ const normalized = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel);
21918
+ const fastModels = await transport.supportsFastMode?.() ? await piFastModelKeys(models, this.#environment) : /* @__PURE__ */ new Set();
21919
+ const catalog = withPiFast(normalized, fastModels);
21349
21920
  await transport.close();
21350
21921
  return {
21351
21922
  status: "ready",
@@ -21382,6 +21953,27 @@ var PiAdapter = class {
21382
21953
  if (this.#closePromise) {
21383
21954
  return { ok: false, error: invalidState("Pi Adapter is closed") };
21384
21955
  }
21956
+ if ("model" in input && input.model) {
21957
+ let model;
21958
+ try {
21959
+ model = decodePiModelRef(input.model);
21960
+ } catch (error51) {
21961
+ return { ok: false, error: normalizedError(error51, "invalidRequest") };
21962
+ }
21963
+ if (model.fast) {
21964
+ if (!this.#isFastSupported(input.model, input.cwd))
21965
+ await this.inspect({ cwd: input.cwd });
21966
+ if (!this.#isFastSupported(input.model, input.cwd) && input.kind !== "resume")
21967
+ return {
21968
+ ok: false,
21969
+ error: {
21970
+ code: "unsupported",
21971
+ message: "Fast is unavailable for this Pi Model",
21972
+ retryable: false
21973
+ }
21974
+ };
21975
+ }
21976
+ }
21385
21977
  if (input.cwd.length === 0) {
21386
21978
  return {
21387
21979
  ok: false,
@@ -21552,6 +22144,11 @@ var PiAdapter = class {
21552
22144
  await transport.verifySessionCwd(input.cwd);
21553
22145
  }
21554
22146
  }
22147
+ if (input.kind === "resume" && input.model && this.#isFastSupported(input.model, input.cwd) && decodePiModelRef(input.model).fast && samePiModel(nativeModelFromState(transport.state), decodePiModelRef(input.model))) {
22148
+ if (!transport.selectFastMode)
22149
+ throw new Error("Pi Fast extension is unavailable");
22150
+ await transport.selectFastMode(true);
22151
+ }
21555
22152
  const startedThinkingLevels = await transport.getAvailableThinkingLevels();
21556
22153
  this.#thinkingSelectionSupported = startedThinkingLevels !== null;
21557
22154
  const initialUsage = await transport.getSessionUsage().catch(() => null);
@@ -21568,6 +22165,9 @@ var PiAdapter = class {
21568
22165
  return { ok: false, error: normalizedError(error51, "nativeFailure") };
21569
22166
  }
21570
22167
  }
22168
+ #isFastSupported(ref, cwd) {
22169
+ return this.#inspectionCache.get(cwd)?.catalog.models.some((model) => model.fastModel?.id === ref.id) ?? false;
22170
+ }
21571
22171
  #trackSession(cwd, options) {
21572
22172
  const environment = options.environment;
21573
22173
  const createTransport = environment ? (input) => this.#createTransport({ ...input, environment }) : this.#createTransport;
@@ -21579,6 +22179,14 @@ var PiAdapter = class {
21579
22179
  ...options.thinkingOptionId ? { thinkingOptionId: options.thinkingOptionId } : {},
21580
22180
  toolOutputLimit: this.#toolOutputLimit,
21581
22181
  supportsThinkingSelection: options.supportsThinkingSelection,
22182
+ isFastSupported: async (ref, transport) => {
22183
+ if (this.#inspectionCache.has(cwd))
22184
+ return this.#isFastSupported(ref, cwd);
22185
+ if (!await transport.supportsFastMode?.())
22186
+ return false;
22187
+ const fastModels = await piFastModelKeys(await transport.getAvailableModels(), environment ?? this.#environment);
22188
+ return fastModels.has(encodePiModelRef({ ...decodePiModelRef(ref), fast: false }).id);
22189
+ },
21582
22190
  ...options.startedTransport ? { startedTransport: options.startedTransport } : {},
21583
22191
  ...options.startedThinkingLevels !== void 0 ? { startedThinkingLevels: options.startedThinkingLevels } : {},
21584
22192
  ...options.initialUsage !== void 0 ? { initialUsage: options.initialUsage } : {}
@@ -21599,14 +22207,36 @@ var PiAdapter = class {
21599
22207
  }
21600
22208
  };
21601
22209
 
22210
+ // dist/installation.js
22211
+ var PI_LATEST_VERSION_URL = "https://pi.dev/api/latest-version";
22212
+ function createPiInstallation(environment, command) {
22213
+ const run = (args, timeout) => runInstallationCommand(resolvePiExecutable({ environment, ...command ? { command } : {} }), args, environment, timeout);
22214
+ return createInstallationManager({
22215
+ async check() {
22216
+ const currentVersion = versionFromOutput(await run(["--version"]));
22217
+ const payload = JSON.parse(await fetchInstallationText(PI_LATEST_VERSION_URL));
22218
+ const latestVersion = installationVersion(payload.version);
22219
+ return {
22220
+ currentVersion,
22221
+ latestVersion,
22222
+ updateAvailable: newerInstallationVersion(currentVersion, latestVersion),
22223
+ canUpdate: true
22224
+ };
22225
+ },
22226
+ async update() {
22227
+ await run(["update"], 3e5);
22228
+ }
22229
+ });
22230
+ }
22231
+
21602
22232
  // dist/plugin.js
21603
22233
  var PI_COMMAND_ENV = "CODEXHOST_PI_COMMAND";
21604
22234
  function createHarnessAdapter(context) {
21605
22235
  const environment = { ...context.environment };
21606
- return new PiAdapter({
22236
+ return Object.assign(new PiAdapter({
21607
22237
  ...environment[PI_COMMAND_ENV] ? { command: environment[PI_COMMAND_ENV] } : {},
21608
22238
  environment
21609
- });
22239
+ }), { installation: createPiInstallation(environment, environment[PI_COMMAND_ENV]) });
21610
22240
  }
21611
22241
  export {
21612
22242
  PI_COMMAND_ENV,