@chinhae/codex-connect-linux-x64 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -781,10 +781,10 @@ function mergeDefs(...defs) {
781
781
  function cloneDef(schema) {
782
782
  return mergeDefs(schema._zod.def);
783
783
  }
784
- function getElementAtPath(obj, path10) {
785
- if (!path10)
784
+ function getElementAtPath(obj, path11) {
785
+ if (!path11)
786
786
  return obj;
787
- return path10.reduce((acc, key) => acc?.[key], obj);
787
+ return path11.reduce((acc, key) => acc?.[key], obj);
788
788
  }
789
789
  function promiseAllObject(promisesObj) {
790
790
  const keys = Object.keys(promisesObj);
@@ -1193,11 +1193,11 @@ function explicitlyAborted(x, startIndex = 0) {
1193
1193
  }
1194
1194
  return false;
1195
1195
  }
1196
- function prefixIssues(path10, issues) {
1196
+ function prefixIssues(path11, issues) {
1197
1197
  return issues.map((iss) => {
1198
1198
  var _a3;
1199
1199
  (_a3 = iss).path ?? (_a3.path = []);
1200
- iss.path.unshift(path10);
1200
+ iss.path.unshift(path11);
1201
1201
  return iss;
1202
1202
  });
1203
1203
  }
@@ -1344,16 +1344,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1344
1344
  }
1345
1345
  function formatError(error51, mapper = (issue2) => issue2.message) {
1346
1346
  const fieldErrors = { _errors: [] };
1347
- const processError = (error52, path10 = []) => {
1347
+ const processError = (error52, path11 = []) => {
1348
1348
  for (const issue2 of error52.issues) {
1349
1349
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1350
- issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1350
+ issue2.errors.map((issues) => processError({ issues }, [...path11, ...issue2.path]));
1351
1351
  } else if (issue2.code === "invalid_key") {
1352
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1352
+ processError({ issues: issue2.issues }, [...path11, ...issue2.path]);
1353
1353
  } else if (issue2.code === "invalid_element") {
1354
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1354
+ processError({ issues: issue2.issues }, [...path11, ...issue2.path]);
1355
1355
  } else {
1356
- const fullpath = [...path10, ...issue2.path];
1356
+ const fullpath = [...path11, ...issue2.path];
1357
1357
  if (fullpath.length === 0) {
1358
1358
  fieldErrors._errors.push(mapper(issue2));
1359
1359
  } else {
@@ -1380,17 +1380,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1380
1380
  }
1381
1381
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1382
1382
  const result = { errors: [] };
1383
- const processError = (error52, path10 = []) => {
1383
+ const processError = (error52, path11 = []) => {
1384
1384
  var _a3, _b;
1385
1385
  for (const issue2 of error52.issues) {
1386
1386
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1387
- issue2.errors.map((issues) => processError({ issues }, [...path10, ...issue2.path]));
1387
+ issue2.errors.map((issues) => processError({ issues }, [...path11, ...issue2.path]));
1388
1388
  } else if (issue2.code === "invalid_key") {
1389
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1389
+ processError({ issues: issue2.issues }, [...path11, ...issue2.path]);
1390
1390
  } else if (issue2.code === "invalid_element") {
1391
- processError({ issues: issue2.issues }, [...path10, ...issue2.path]);
1391
+ processError({ issues: issue2.issues }, [...path11, ...issue2.path]);
1392
1392
  } else {
1393
- const fullpath = [...path10, ...issue2.path];
1393
+ const fullpath = [...path11, ...issue2.path];
1394
1394
  if (fullpath.length === 0) {
1395
1395
  result.errors.push(mapper(issue2));
1396
1396
  continue;
@@ -1422,8 +1422,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1422
1422
  }
1423
1423
  function toDotPath(_path) {
1424
1424
  const segs = [];
1425
- const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1426
- for (const seg of path10) {
1425
+ const path11 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1426
+ for (const seg of path11) {
1427
1427
  if (typeof seg === "number")
1428
1428
  segs.push(`[${seg}]`);
1429
1429
  else if (typeof seg === "symbol")
@@ -4651,8 +4651,8 @@ function az_default() {
4651
4651
  }
4652
4652
 
4653
4653
  // ../../../node_modules/zod/v4/locales/be.js
4654
- function getBelarusianPlural(count, one, few, many) {
4655
- const absCount = Math.abs(count);
4654
+ function getBelarusianPlural(count3, one, few, many) {
4655
+ const absCount = Math.abs(count3);
4656
4656
  const lastDigit = absCount % 10;
4657
4657
  const lastTwoDigits = absCount % 100;
4658
4658
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -6730,8 +6730,8 @@ function hu_default() {
6730
6730
  }
6731
6731
 
6732
6732
  // ../../../node_modules/zod/v4/locales/hy.js
6733
- function getArmenianPlural(count, one, many) {
6734
- return Math.abs(count) === 1 ? one : many;
6733
+ function getArmenianPlural(count3, one, many) {
6734
+ return Math.abs(count3) === 1 ? one : many;
6735
6735
  }
6736
6736
  function withDefiniteArticle(word) {
6737
6737
  if (!word)
@@ -7653,8 +7653,8 @@ function ko_default() {
7653
7653
  }
7654
7654
 
7655
7655
  // ../../../node_modules/zod/v4/locales/lt.js
7656
- var capitalizeFirstCharacter = (text2) => {
7657
- return text2.charAt(0).toUpperCase() + text2.slice(1);
7656
+ var capitalizeFirstCharacter = (text3) => {
7657
+ return text3.charAt(0).toUpperCase() + text3.slice(1);
7658
7658
  };
7659
7659
  function getUnitTypeFromNumber(number4) {
7660
7660
  const abs = Math.abs(number4);
@@ -8859,8 +8859,8 @@ function ro_default() {
8859
8859
  }
8860
8860
 
8861
8861
  // ../../../node_modules/zod/v4/locales/ru.js
8862
- function getRussianPlural(count, one, few, many) {
8863
- const absCount = Math.abs(count);
8862
+ function getRussianPlural(count3, one, few, many) {
8863
+ const absCount = Math.abs(count3);
8864
8864
  const lastDigit = absCount % 10;
8865
8865
  const lastTwoDigits = absCount % 100;
8866
8866
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -14115,13 +14115,13 @@ function resolveRef(ref, ctx) {
14115
14115
  if (!ref.startsWith("#")) {
14116
14116
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14117
14117
  }
14118
- const path10 = ref.slice(1).split("/").filter(Boolean);
14119
- if (path10.length === 0) {
14118
+ const path11 = ref.slice(1).split("/").filter(Boolean);
14119
+ if (path11.length === 0) {
14120
14120
  return ctx.rootSchema;
14121
14121
  }
14122
14122
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14123
- if (path10[0] === defsKey) {
14124
- const key = path10[1];
14123
+ if (path11[0] === defsKey) {
14124
+ const key = path11[1];
14125
14125
  if (!key || !ctx.defs[key]) {
14126
14126
  throw new Error(`Reference not found: ${ref}`);
14127
14127
  }
@@ -14637,6 +14637,304 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
14637
14637
  var hostItemIdSchema = opaqueIdSchema.brand();
14638
14638
  var hostInteractionIdSchema = opaqueIdSchema.brand();
14639
14639
 
14640
+ // ../../shared-contracts/dist/harness-plugins.js
14641
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
14642
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
14643
+ var HARNESS_PLUGIN_LIMIT = 128;
14644
+ var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
14645
+ var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
14646
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
14647
+ var pluginPresentationShape = {
14648
+ id: harnessPluginIdSchema,
14649
+ name: external_exports.string().trim().min(1).max(128),
14650
+ version: external_exports.string().min(1).max(128),
14651
+ /** The factory accepts a persisted local entrypoint through its construction context. */
14652
+ launchCommand: external_exports.literal(true).optional(),
14653
+ links: external_exports.object({
14654
+ documentation: documentationUrlSchema.optional(),
14655
+ installation: documentationUrlSchema.optional()
14656
+ }).strict().optional()
14657
+ };
14658
+ var harnessPluginManifestSchema = external_exports.object({
14659
+ manifestVersion: external_exports.literal(1),
14660
+ ...pluginPresentationShape,
14661
+ adapterApiVersion: external_exports.number().int().positive(),
14662
+ entry: relativeResourceSchema,
14663
+ icon: relativeResourceSchema.optional()
14664
+ }).strict();
14665
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
14666
+ var harnessPluginDescriptorSchema = external_exports.object({
14667
+ ...pluginPresentationShape,
14668
+ icon: harnessPluginIconSchema.optional()
14669
+ }).strict();
14670
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
14671
+ var harnessPluginListResultSchema = external_exports.object({
14672
+ plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
14673
+ }).strict();
14674
+ var harnessPluginConfigurationSchema = external_exports.object({
14675
+ version: external_exports.literal(1),
14676
+ enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
14677
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
14678
+ message: "Enabled plugin IDs must be unique",
14679
+ path: ["enabled"]
14680
+ });
14681
+
14682
+ // ../../shared-contracts/dist/local-usage.js
14683
+ var LOCAL_USAGE_CUSTOM_RANGE_MAX_DAYS = 3660;
14684
+ var LOCAL_USAGE_DAILY_MAX_LENGTH = LOCAL_USAGE_CUSTOM_RANGE_MAX_DAYS + 1;
14685
+ var LOCAL_USAGE_HARNESS_MAX_LENGTH = 128;
14686
+ var LOCAL_USAGE_HARNESS_NAME_MAX_LENGTH = 128;
14687
+ var LOCAL_USAGE_PROVIDER_MAX_LENGTH = 128;
14688
+ var LOCAL_USAGE_PROVIDER_NAME_MAX_LENGTH = 1024;
14689
+ var LOCAL_USAGE_PROJECT_MAX_LENGTH = 1e3;
14690
+ var LOCAL_USAGE_PROJECT_NAME_MAX_LENGTH = 1024;
14691
+ var LOCAL_USAGE_TIME_ZONE_MAX_LENGTH = 64;
14692
+ var DAY_MS = 864e5;
14693
+ function dateValue(value) {
14694
+ return Date.parse(`${value}T00:00:00.000Z`);
14695
+ }
14696
+ var localUsageDateSchema = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u).refine((value) => {
14697
+ const time3 = dateValue(value);
14698
+ return Number.isFinite(time3) && new Date(time3).toISOString().slice(0, 10) === value;
14699
+ }, "Invalid calendar date");
14700
+ var timeZoneSchema = external_exports.string().min(1).max(LOCAL_USAGE_TIME_ZONE_MAX_LENGTH).refine((value) => {
14701
+ try {
14702
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
14703
+ return true;
14704
+ } catch {
14705
+ return false;
14706
+ }
14707
+ }, "Unknown time zone");
14708
+ var localUsagePeriodSchema = external_exports.discriminatedUnion("kind", [
14709
+ external_exports.strictObject({ kind: external_exports.literal("day") }),
14710
+ // Weeks start on Monday.
14711
+ external_exports.strictObject({ kind: external_exports.literal("week") }),
14712
+ external_exports.strictObject({ kind: external_exports.literal("month") }),
14713
+ // The first day of the month 23 months ago through today.
14714
+ external_exports.strictObject({ kind: external_exports.literal("total") }),
14715
+ external_exports.strictObject({
14716
+ kind: external_exports.literal("custom"),
14717
+ from: localUsageDateSchema,
14718
+ to: localUsageDateSchema
14719
+ }).superRefine((period, context) => {
14720
+ const days = (dateValue(period.to) - dateValue(period.from)) / DAY_MS;
14721
+ if (days < 0) {
14722
+ context.addIssue({ code: "custom", path: ["to"], message: "Range ends before it starts" });
14723
+ } else if (days >= LOCAL_USAGE_CUSTOM_RANGE_MAX_DAYS) {
14724
+ context.addIssue({ code: "custom", path: ["to"], message: "Range is too long" });
14725
+ }
14726
+ })
14727
+ ]);
14728
+ var localUsageQueryParamsSchema = external_exports.strictObject({
14729
+ period: localUsagePeriodSchema,
14730
+ /** IANA zone used to assign usage to calendar days. */
14731
+ timeZone: timeZoneSchema,
14732
+ /** Read new native records before answering; otherwise reuse this Host's last read. */
14733
+ refresh: external_exports.boolean()
14734
+ });
14735
+ var countSchema = external_exports.number().int().nonnegative().safe();
14736
+ var tokenTotalsShape = {
14737
+ total: countSchema,
14738
+ /** Input tokens excluding cache reads and writes. */
14739
+ input: countSchema,
14740
+ cacheRead: countSchema,
14741
+ cacheWrite: countSchema,
14742
+ output: countSchema,
14743
+ reasoning: countSchema
14744
+ };
14745
+ var usageHarnessIdSchema = external_exports.union([external_exports.literal("codex"), harnessPluginIdSchema]);
14746
+ var localUsageViewSchema = external_exports.strictObject({
14747
+ status: external_exports.literal("ready"),
14748
+ range: external_exports.strictObject({ from: localUsageDateSchema, to: localUsageDateSchema }),
14749
+ totals: external_exports.strictObject({ ...tokenTotalsShape, conversations: countSchema }).refine((totals) => totals.total === totals.input + totals.cacheRead + totals.cacheWrite + totals.output + totals.reasoning, { path: ["total"], message: "Total must equal its parts" }),
14750
+ /**
14751
+ * Estimated Cost of the range in USD: Harness-reported cost where present, otherwise public
14752
+ * model prices applied when queried. Models without a price add 0.
14753
+ */
14754
+ estimatedCostUsd: external_exports.number().nonnegative().finite(),
14755
+ /** Distinct Models with usage in the range, across Harnesses. */
14756
+ models: countSchema,
14757
+ harnesses: external_exports.array(external_exports.strictObject({
14758
+ harnessId: usageHarnessIdSchema,
14759
+ name: external_exports.string().trim().min(1).max(LOCAL_USAGE_HARNESS_NAME_MAX_LENGTH),
14760
+ totalTokens: countSchema,
14761
+ models: countSchema,
14762
+ /** Providers the Harness recorded, by usage; empty when it records none. */
14763
+ providers: external_exports.array(external_exports.strictObject({
14764
+ provider: external_exports.string().min(1).max(LOCAL_USAGE_PROVIDER_NAME_MAX_LENGTH),
14765
+ totalTokens: countSchema,
14766
+ models: countSchema
14767
+ })).max(LOCAL_USAGE_PROVIDER_MAX_LENGTH)
14768
+ }).refine((harness) => harness.providers.reduce((sum, provider) => sum + provider.totalTokens, 0) <= harness.totalTokens, { path: ["providers"], message: "Providers are part of their Harness" })).max(LOCAL_USAGE_HARNESS_MAX_LENGTH),
14769
+ /** Days with usage, newest first. `cacheRead` is the daily cache column. */
14770
+ daily: external_exports.array(external_exports.strictObject({
14771
+ date: localUsageDateSchema,
14772
+ total: countSchema,
14773
+ input: countSchema,
14774
+ output: countSchema,
14775
+ cacheRead: countSchema,
14776
+ reasoning: countSchema,
14777
+ conversations: countSchema
14778
+ })).max(LOCAL_USAGE_DAILY_MAX_LENGTH),
14779
+ /**
14780
+ * Usage with a known working directory, by project, most used first: `owner/repo` from the Git
14781
+ * remote, otherwise the folder name. Only the most used projects are listed.
14782
+ */
14783
+ projects: external_exports.array(external_exports.strictObject({
14784
+ project: external_exports.string().min(1).max(LOCAL_USAGE_PROJECT_NAME_MAX_LENGTH),
14785
+ totalTokens: countSchema,
14786
+ /** Harnesses used in the project, most used first. */
14787
+ harnessIds: external_exports.array(usageHarnessIdSchema).min(1).max(LOCAL_USAGE_HARNESS_MAX_LENGTH)
14788
+ })).max(LOCAL_USAGE_PROJECT_MAX_LENGTH),
14789
+ /** Harnesses whose last read failed; their totals are from their last successful read. */
14790
+ failures: external_exports.array(external_exports.strictObject({
14791
+ harnessId: usageHarnessIdSchema,
14792
+ name: external_exports.string().trim().min(1).max(LOCAL_USAGE_HARNESS_NAME_MAX_LENGTH)
14793
+ })).max(LOCAL_USAGE_HARNESS_MAX_LENGTH),
14794
+ /**
14795
+ * Independent of the selected period. Windows end today; an active day has tokens.
14796
+ * `dailyAverage` is the last 30 days' total over their active days, rounded.
14797
+ */
14798
+ stats: external_exports.strictObject({
14799
+ last7Days: countSchema,
14800
+ last30Days: countSchema,
14801
+ dailyAverage: countSchema,
14802
+ /** Active days across all counted history, not only the "total" period. */
14803
+ activeDays: countSchema,
14804
+ firstActiveDate: localUsageDateSchema.nullable()
14805
+ }).superRefine((stats, context) => {
14806
+ if (stats.firstActiveDate === null !== (stats.activeDays === 0)) {
14807
+ context.addIssue({
14808
+ code: "custom",
14809
+ path: ["firstActiveDate"],
14810
+ message: "First active date exists exactly when there are active days"
14811
+ });
14812
+ }
14813
+ if (stats.last7Days > stats.last30Days) {
14814
+ context.addIssue({
14815
+ code: "custom",
14816
+ path: ["last7Days"],
14817
+ message: "The last 7 days are part of the last 30 days"
14818
+ });
14819
+ }
14820
+ })
14821
+ });
14822
+ var localUsageReadingSchema = external_exports.strictObject({
14823
+ status: external_exports.literal("reading"),
14824
+ /** Native record files read so far by the sources that report progress. */
14825
+ progress: external_exports.strictObject({ processed: countSchema, total: countSchema }).refine((progress) => progress.processed <= progress.total, {
14826
+ path: ["processed"],
14827
+ message: "Processed files are part of the total"
14828
+ })
14829
+ });
14830
+ var localUsageQueryResultSchema = external_exports.discriminatedUnion("status", [
14831
+ localUsageReadingSchema,
14832
+ localUsageViewSchema
14833
+ ]);
14834
+
14835
+ // ../../shared-contracts/dist/harness-session-import.js
14836
+ var HARNESS_SESSION_IMPORT_ID_MAX_LENGTH = 1024;
14837
+ var HARNESS_SESSION_IMPORT_CWD_MAX_LENGTH = 16384;
14838
+ var HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH = 4096;
14839
+ var HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH = 1e3;
14840
+ var HARNESS_SESSION_IMPORT_UPDATED_AT_MAX = 864e13;
14841
+ var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, "Value must not be empty or whitespace").refine((value) => !value.includes("\0"), "Value must not contain NUL");
14842
+ var harnessSessionImportIdSchema = nonBlankTextSchema.max(HARNESS_SESSION_IMPORT_ID_MAX_LENGTH);
14843
+ var harnessSessionImportCandidateSchema = external_exports.object({
14844
+ nativeSessionId: harnessSessionImportIdSchema,
14845
+ title: nonBlankTextSchema.max(HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH).nullable(),
14846
+ updatedAt: external_exports.number().int().nonnegative().max(HARNESS_SESSION_IMPORT_UPDATED_AT_MAX),
14847
+ cwd: nonBlankTextSchema.max(HARNESS_SESSION_IMPORT_CWD_MAX_LENGTH),
14848
+ // Native file discovery cannot reliably observe another process's activity.
14849
+ running: external_exports.boolean().nullable()
14850
+ }).strict();
14851
+ var harnessSessionImportSourcesParamsSchema = external_exports.object({}).strict();
14852
+ var harnessSessionImportSourcesResultSchema = external_exports.object({
14853
+ harnesses: external_exports.array(external_exports.object({
14854
+ harnessId: harnessPluginIdSchema,
14855
+ name: nonBlankTextSchema.max(128)
14856
+ }).strict()).max(128)
14857
+ }).strict();
14858
+ var harnessSessionListParamsSchema = external_exports.object({
14859
+ harnessId: harnessPluginIdSchema,
14860
+ query: external_exports.string().trim().max(4096).refine((value) => !value.includes("\0")).optional(),
14861
+ offset: external_exports.number().int().nonnegative().safe().optional(),
14862
+ limit: external_exports.number().int().min(1).max(HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH).optional()
14863
+ }).strict();
14864
+ var harnessSessionListResultSchema = external_exports.object({
14865
+ candidates: external_exports.array(harnessSessionImportCandidateSchema).max(HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH),
14866
+ total: external_exports.number().int().nonnegative().safe()
14867
+ }).strict();
14868
+ var harnessSessionImportParamsSchema = external_exports.object({
14869
+ harnessId: harnessPluginIdSchema,
14870
+ nativeSessionId: harnessSessionImportIdSchema
14871
+ }).strict();
14872
+ var harnessSessionImportResultSchema = external_exports.object({
14873
+ threadId: nonBlankTextSchema.max(1024).pipe(hostThreadIdSchema)
14874
+ }).strict();
14875
+
14876
+ // ../../shared-contracts/dist/local-sessions.js
14877
+ var LOCAL_SESSIONS_MAX_LENGTH = 1e5;
14878
+ var LOCAL_SESSIONS_MODEL_MAX_LENGTH = 1024;
14879
+ var LOCAL_SESSIONS_RESUME_COMMAND_MAX_LENGTH = 256;
14880
+ var LOCAL_SESSIONS_RESUME_COMMAND_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._:=/-]*$/u;
14881
+ var countSchema2 = external_exports.number().int().nonnegative().safe();
14882
+ var timeSchema = countSchema2;
14883
+ var sessionHarnessIdSchema = external_exports.union([external_exports.literal("codex"), harnessPluginIdSchema]);
14884
+ var harnessNameSchema = external_exports.string().trim().min(1).max(LOCAL_USAGE_HARNESS_NAME_MAX_LENGTH);
14885
+ var localSessionsQueryParamsSchema = external_exports.strictObject({
14886
+ /** Read native records added since the last read before answering. */
14887
+ refresh: external_exports.boolean()
14888
+ });
14889
+ var localSessionSchema = external_exports.strictObject({
14890
+ harnessId: sessionHarnessIdSchema,
14891
+ nativeSessionId: harnessSessionImportIdSchema,
14892
+ /** The Harness's own name for the Session; null shows the project instead. */
14893
+ title: external_exports.string().min(1).max(HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH).nullable(),
14894
+ /** Working directory, used to copy the project path or a resume command. */
14895
+ cwd: external_exports.string().min(1).max(HARNESS_SESSION_IMPORT_CWD_MAX_LENGTH).nullable(),
14896
+ /** `owner/repo` from the Git remote, otherwise the folder name. */
14897
+ project: external_exports.string().min(1).max(LOCAL_USAGE_PROJECT_NAME_MAX_LENGTH).nullable(),
14898
+ model: external_exports.string().min(1).max(LOCAL_SESSIONS_MODEL_MAX_LENGTH).nullable(),
14899
+ startedAt: timeSchema.nullable(),
14900
+ lastActivityAt: timeSchema,
14901
+ /** Null for Sessions known only from Session import, which has no native usage. */
14902
+ activeMs: countSchema2.nullable(),
14903
+ usage: external_exports.strictObject({
14904
+ /** Includes folded subagents. */
14905
+ totalTokens: countSchema2,
14906
+ estimatedCostUsd: external_exports.number().nonnegative().finite()
14907
+ }).nullable(),
14908
+ turns: countSchema2.nullable(),
14909
+ edits: countSchema2.nullable(),
14910
+ /** Subagent and child Sessions folded into this one. */
14911
+ subagents: countSchema2,
14912
+ /** The Thread this Session is already mapped to. */
14913
+ threadId: hostThreadIdSchema.nullable(),
14914
+ /** Whether Resume can open it as a Thread. */
14915
+ resumable: external_exports.boolean(),
14916
+ /** Null when the Harness cannot tell whether another client is running it. */
14917
+ running: external_exports.boolean().nullable(),
14918
+ /**
14919
+ * Resumes the Session in its Harness's own CLI when run from `cwd`; null when the Harness has
14920
+ * no such command or the Session ID is not safe to paste into a terminal.
14921
+ */
14922
+ resumeCommand: external_exports.string().max(LOCAL_SESSIONS_RESUME_COMMAND_MAX_LENGTH).regex(LOCAL_SESSIONS_RESUME_COMMAND_PATTERN).nullable()
14923
+ });
14924
+ var localSessionsViewSchema = external_exports.strictObject({
14925
+ status: external_exports.literal("ready"),
14926
+ /** Most recently active first. */
14927
+ sessions: external_exports.array(localSessionSchema).max(LOCAL_SESSIONS_MAX_LENGTH),
14928
+ /** Harnesses with listed Sessions, by name. */
14929
+ harnesses: external_exports.array(external_exports.strictObject({ harnessId: sessionHarnessIdSchema, name: harnessNameSchema })).max(LOCAL_USAGE_HARNESS_MAX_LENGTH),
14930
+ /** Sources whose last read failed; their Sessions are from their last successful read. */
14931
+ failures: external_exports.array(external_exports.strictObject({ harnessId: sessionHarnessIdSchema, name: harnessNameSchema })).max(LOCAL_USAGE_HARNESS_MAX_LENGTH)
14932
+ });
14933
+ var localSessionsQueryResultSchema = external_exports.discriminatedUnion("status", [
14934
+ localUsageReadingSchema,
14935
+ localSessionsViewSchema
14936
+ ]);
14937
+
14640
14938
  // ../../shared-contracts/dist/thread-usage.js
14641
14939
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
14642
14940
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -14700,10 +14998,18 @@ var accountCreditsProductUsageSchema = external_exports.object({
14700
14998
  usagePercent: usagePercentSchema,
14701
14999
  resetsAt: external_exports.string().min(1).optional()
14702
15000
  }).strict();
15001
+ var ACCOUNT_RESET_CREDITS_MAX_LENGTH = 32;
15002
+ var ACCOUNT_RESET_CREDIT_TIME_MAX_LENGTH = 64;
15003
+ var resetCreditTimeSchema = external_exports.string().min(1).max(ACCOUNT_RESET_CREDIT_TIME_MAX_LENGTH);
15004
+ var accountResetCreditSchema = external_exports.object({
15005
+ expiresAt: resetCreditTimeSchema,
15006
+ grantedAt: resetCreditTimeSchema.optional()
15007
+ }).strict();
14703
15008
  var accountResetCreditsSchema = external_exports.object({
14704
15009
  availableCount: external_exports.number().int().safe().positive(),
14705
15010
  nextExpiresAt: external_exports.string().min(1).optional(),
14706
- expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
15011
+ expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(ACCOUNT_RESET_CREDITS_MAX_LENGTH).optional(),
15012
+ credits: external_exports.array(accountResetCreditSchema).min(1).max(ACCOUNT_RESET_CREDITS_MAX_LENGTH).optional()
14707
15013
  }).strict();
14708
15014
  var accountCreditsSnapshotSchema = external_exports.object({
14709
15015
  /** Native label when the primary limit is scoped to a model or product group. */
@@ -14823,14 +15129,14 @@ var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
14823
15129
  var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
14824
15130
  var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
14825
15131
  var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
14826
- var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15132
+ var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
14827
15133
  message: "Value must not be empty or whitespace"
14828
15134
  });
14829
- var harnessPermissionModeIdSchema = nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Permission Mode ID must use transport-safe characters").brand();
15135
+ var harnessPermissionModeIdSchema = nonBlankTextSchema2.max(HARNESS_PERMISSION_MODE_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Permission Mode ID must use transport-safe characters").brand();
14830
15136
  var harnessPermissionModeSchema = external_exports.object({
14831
15137
  id: harnessPermissionModeIdSchema,
14832
- label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
14833
- description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
15138
+ label: nonBlankTextSchema2.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
15139
+ description: nonBlankTextSchema2.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
14834
15140
  dangerous: external_exports.boolean().optional()
14835
15141
  }).strict();
14836
15142
  var harnessPermissionModeCatalogSchema = external_exports.object({
@@ -14866,22 +15172,22 @@ var HARNESS_MODEL_REF_MAX_LENGTH = 512;
14866
15172
  var HARNESS_MODEL_LABEL_MAX_LENGTH = 256;
14867
15173
  var HARNESS_THINKING_OPTION_ID_MAX_LENGTH = 128;
14868
15174
  var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
14869
- var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
15175
+ var nonBlankTextSchema3 = external_exports.string().refine((value) => value.trim().length > 0, {
14870
15176
  message: "Value must not be empty or whitespace"
14871
15177
  });
14872
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
15178
+ var harnessModelRefIdSchema = nonBlankTextSchema3.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
14873
15179
  var harnessModelRefSchema = external_exports.object({
14874
15180
  id: harnessModelRefIdSchema
14875
15181
  }).strict();
14876
- var harnessThinkingOptionIdSchema = nonBlankTextSchema2.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
14877
- var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
15182
+ var harnessThinkingOptionIdSchema = nonBlankTextSchema3.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
15183
+ var harnessResolvedModelLabelSchema = nonBlankTextSchema3.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
14878
15184
  var harnessThinkingOptionSchema = external_exports.object({
14879
15185
  id: harnessThinkingOptionIdSchema,
14880
- label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH)
15186
+ label: nonBlankTextSchema3.max(HARNESS_MODEL_LABEL_MAX_LENGTH)
14881
15187
  }).strict();
14882
15188
  var harnessModelSchema = external_exports.object({
14883
15189
  ref: harnessModelRefSchema,
14884
- label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
15190
+ label: nonBlankTextSchema3.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
14885
15191
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
14886
15192
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
14887
15193
  }).strict();
@@ -15018,7 +15324,7 @@ var harnessInspectionSchema = external_exports.union([
15018
15324
  ]);
15019
15325
  var harnessInspectParamsSchema = external_exports.object({
15020
15326
  harnessId: harnessIdSchema,
15021
- cwd: nonBlankTextSchema2.max(16384).optional(),
15327
+ cwd: nonBlankTextSchema3.max(16384).optional(),
15022
15328
  refresh: external_exports.boolean().optional()
15023
15329
  }).strict();
15024
15330
  var harnessWebUiOpenParamsSchema = external_exports.object({
@@ -15042,8 +15348,8 @@ var codexThreadInspectionSchema = external_exports.object({
15042
15348
  }).strict();
15043
15349
  var externalThreadInspectionSchema = external_exports.object({
15044
15350
  owner: external_exports.literal("external"),
15045
- harnessId: nonBlankTextSchema2.max(256),
15046
- transportModelId: nonBlankTextSchema2.max(1024),
15351
+ harnessId: nonBlankTextSchema3.max(256),
15352
+ transportModelId: nonBlankTextSchema3.max(1024),
15047
15353
  effectiveModel: harnessModelRefSchema.optional(),
15048
15354
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
15049
15355
  effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -15101,48 +15407,6 @@ var threadOwnershipListResultSchema = external_exports.object({
15101
15407
  }
15102
15408
  });
15103
15409
 
15104
- // ../../shared-contracts/dist/harness-plugins.js
15105
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15106
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
15107
- var HARNESS_PLUGIN_LIMIT = 128;
15108
- var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
15109
- var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
15110
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
15111
- var pluginPresentationShape = {
15112
- id: harnessPluginIdSchema,
15113
- name: external_exports.string().trim().min(1).max(128),
15114
- version: external_exports.string().min(1).max(128),
15115
- /** The factory accepts a persisted local entrypoint through its construction context. */
15116
- launchCommand: external_exports.literal(true).optional(),
15117
- links: external_exports.object({
15118
- documentation: documentationUrlSchema.optional(),
15119
- installation: documentationUrlSchema.optional()
15120
- }).strict().optional()
15121
- };
15122
- var harnessPluginManifestSchema = external_exports.object({
15123
- manifestVersion: external_exports.literal(1),
15124
- ...pluginPresentationShape,
15125
- adapterApiVersion: external_exports.number().int().positive(),
15126
- entry: relativeResourceSchema,
15127
- icon: relativeResourceSchema.optional()
15128
- }).strict();
15129
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
15130
- var harnessPluginDescriptorSchema = external_exports.object({
15131
- ...pluginPresentationShape,
15132
- icon: harnessPluginIconSchema.optional()
15133
- }).strict();
15134
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
15135
- var harnessPluginListResultSchema = external_exports.object({
15136
- plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
15137
- }).strict();
15138
- var harnessPluginConfigurationSchema = external_exports.object({
15139
- version: external_exports.literal(1),
15140
- enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15141
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15142
- message: "Enabled plugin IDs must be unique",
15143
- path: ["enabled"]
15144
- });
15145
-
15146
15410
  // ../../shared-contracts/dist/harness-route.js
15147
15411
  var harnessPluginRouteSchema = external_exports.object({
15148
15412
  harnessId: harnessPluginIdSchema,
@@ -15166,7 +15430,7 @@ var harnessLaunchSettingsSchema = external_exports.object({
15166
15430
 
15167
15431
  // ../../shared-contracts/dist/codex-accounts.js
15168
15432
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
15169
- var nonBlankTextSchema3 = external_exports.string().trim().min(1);
15433
+ var nonBlankTextSchema4 = external_exports.string().trim().min(1);
15170
15434
  var codexAccountPlanTypeSchema = external_exports.enum([
15171
15435
  "free",
15172
15436
  "go",
@@ -15188,7 +15452,7 @@ var codexAccountPlanTypeSchema = external_exports.enum([
15188
15452
  ]);
15189
15453
  var codexAccountSchema = external_exports.object({
15190
15454
  accountId: accountIdSchema,
15191
- label: nonBlankTextSchema3.max(256),
15455
+ label: nonBlankTextSchema4.max(256),
15192
15456
  email: external_exports.string().email().max(320).optional(),
15193
15457
  planType: codexAccountPlanTypeSchema.optional()
15194
15458
  }).strict();
@@ -15198,7 +15462,7 @@ var codexAccountListResultSchema = external_exports.object({
15198
15462
  currentAccountId: accountIdSchema.nullable(),
15199
15463
  phase: codexAccountPhaseSchema,
15200
15464
  revision: external_exports.number().int().nonnegative(),
15201
- instanceId: nonBlankTextSchema3.max(1024).optional(),
15465
+ instanceId: nonBlankTextSchema4.max(1024).optional(),
15202
15466
  accounts: external_exports.array(codexAccountSchema).max(1)
15203
15467
  }).strict();
15204
15468
  var codexAccountUsageParamsSchema = external_exports.object({ accountId: accountIdSchema, refresh: external_exports.boolean().optional() }).strict();
@@ -15210,47 +15474,6 @@ var codexAccountUsageResultSchema = external_exports.object({
15210
15474
  observedAt: external_exports.string().datetime().nullable()
15211
15475
  }).strict();
15212
15476
 
15213
- // ../../shared-contracts/dist/harness-session-import.js
15214
- var HARNESS_SESSION_IMPORT_ID_MAX_LENGTH = 1024;
15215
- var HARNESS_SESSION_IMPORT_CWD_MAX_LENGTH = 16384;
15216
- var HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH = 4096;
15217
- var HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH = 1e3;
15218
- var HARNESS_SESSION_IMPORT_UPDATED_AT_MAX = 864e13;
15219
- var nonBlankTextSchema4 = external_exports.string().refine((value) => value.trim().length > 0, "Value must not be empty or whitespace").refine((value) => !value.includes("\0"), "Value must not contain NUL");
15220
- var harnessSessionImportIdSchema = nonBlankTextSchema4.max(HARNESS_SESSION_IMPORT_ID_MAX_LENGTH);
15221
- var harnessSessionImportCandidateSchema = external_exports.object({
15222
- nativeSessionId: harnessSessionImportIdSchema,
15223
- title: nonBlankTextSchema4.max(HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH).nullable(),
15224
- updatedAt: external_exports.number().int().nonnegative().max(HARNESS_SESSION_IMPORT_UPDATED_AT_MAX),
15225
- cwd: nonBlankTextSchema4.max(HARNESS_SESSION_IMPORT_CWD_MAX_LENGTH),
15226
- // Native file discovery cannot reliably observe another process's activity.
15227
- running: external_exports.boolean().nullable()
15228
- }).strict();
15229
- var harnessSessionImportSourcesParamsSchema = external_exports.object({}).strict();
15230
- var harnessSessionImportSourcesResultSchema = external_exports.object({
15231
- harnesses: external_exports.array(external_exports.object({
15232
- harnessId: harnessPluginIdSchema,
15233
- name: nonBlankTextSchema4.max(128)
15234
- }).strict()).max(128)
15235
- }).strict();
15236
- var harnessSessionListParamsSchema = external_exports.object({
15237
- harnessId: harnessPluginIdSchema,
15238
- query: external_exports.string().trim().max(4096).refine((value) => !value.includes("\0")).optional(),
15239
- offset: external_exports.number().int().nonnegative().safe().optional(),
15240
- limit: external_exports.number().int().min(1).max(HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH).optional()
15241
- }).strict();
15242
- var harnessSessionListResultSchema = external_exports.object({
15243
- candidates: external_exports.array(harnessSessionImportCandidateSchema).max(HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH),
15244
- total: external_exports.number().int().nonnegative().safe()
15245
- }).strict();
15246
- var harnessSessionImportParamsSchema = external_exports.object({
15247
- harnessId: harnessPluginIdSchema,
15248
- nativeSessionId: harnessSessionImportIdSchema
15249
- }).strict();
15250
- var harnessSessionImportResultSchema = external_exports.object({
15251
- threadId: nonBlankTextSchema4.max(1024).pipe(hostThreadIdSchema)
15252
- }).strict();
15253
-
15254
15477
  // ../../shared-contracts/dist/deepseek-modern-sessions.js
15255
15478
  var DEEPSEEK_MODERN_SESSION_LIST_MAX_LENGTH = HARNESS_SESSION_IMPORT_LIST_MAX_LENGTH;
15256
15479
  var DEEPSEEK_MODERN_HOST_THREAD_ID_MAX_LENGTH = 1024;
@@ -16382,7 +16605,7 @@ function parsePiSubagentInspection(value) {
16382
16605
  return null;
16383
16606
  return parsed;
16384
16607
  }
16385
- function piSubagentSnapshot(parentSessionId, id, reply) {
16608
+ function piSubagentSnapshot(parentSessionId2, id, reply) {
16386
16609
  const messages = reply.messages ?? [];
16387
16610
  const texts = messages.map((entry) => entry.kind === "text" && entry.role === "assistant" ? entry.text : `[${entry.role}${entry.name ? `: ${entry.name}` : ""} / ${entry.kind}]
16388
16611
  ${entry.text}`);
@@ -16396,16 +16619,16 @@ ${entry.text}`);
16396
16619
  {
16397
16620
  nativeTurnRef: nativeTurnRefSchema.parse({
16398
16621
  harnessId: "pi",
16399
- nativeSessionId: parentSessionId,
16622
+ nativeSessionId: parentSessionId2,
16400
16623
  nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
16401
16624
  formatVersion: 1
16402
16625
  }),
16403
16626
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
16404
- items: texts.map((text2, index) => ({
16627
+ items: texts.map((text3, index) => ({
16405
16628
  item: {
16406
16629
  type: "agentMessage",
16407
- text: text2,
16408
- itemId: hostItemIdSchema.parse(`pi-subagent-${createHash("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
16630
+ text: text3,
16631
+ itemId: hostItemIdSchema.parse(`pi-subagent-${createHash("sha256").update(`${id}:${index}:${text3}`).digest("hex")}`)
16409
16632
  },
16410
16633
  outcome: { status: "succeeded" }
16411
16634
  })),
@@ -16630,8 +16853,8 @@ function itemOutcome(outcome) {
16630
16853
  return { status: "succeeded" };
16631
16854
  }
16632
16855
  function toolOutput(value) {
16633
- const text2 = textContent(value);
16634
- return text2.length > 0 ? { content: [{ type: "text", text: text2 }] } : void 0;
16856
+ const text3 = textContent(value);
16857
+ return text3.length > 0 ? { content: [{ type: "text", text: text3 }] } : void 0;
16635
16858
  }
16636
16859
  function snapshotItems(entries, outcome, subagents) {
16637
16860
  const snapshots = [];
@@ -16642,7 +16865,7 @@ function snapshotItems(entries, outcome, subagents) {
16642
16865
  continue;
16643
16866
  const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
16644
16867
  if (nativeMessage.role === "assistant") {
16645
- const text2 = textContent(content);
16868
+ const text3 = textContent(content);
16646
16869
  const reasoning = thinkingContent(content);
16647
16870
  let projectedText = false;
16648
16871
  let projectedReasoning = false;
@@ -16659,11 +16882,11 @@ function snapshotItems(entries, outcome, subagents) {
16659
16882
  projectedReasoning = true;
16660
16883
  continue;
16661
16884
  }
16662
- if (part.type === "text" && !projectedText && text2.length > 0) {
16885
+ if (part.type === "text" && !projectedText && text3.length > 0) {
16663
16886
  const item2 = {
16664
16887
  type: "agentMessage",
16665
16888
  itemId: itemId(entry.id, "assistant", 0),
16666
- text: text2
16889
+ text: text3
16667
16890
  };
16668
16891
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
16669
16892
  projectedText = true;
@@ -17042,16 +17265,16 @@ var Diff = class {
17042
17265
  }
17043
17266
  }
17044
17267
  }
17045
- addToPath(path10, added, removed, oldPosInc, options) {
17046
- const last = path10.lastComponent;
17268
+ addToPath(path11, added, removed, oldPosInc, options) {
17269
+ const last = path11.lastComponent;
17047
17270
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17048
17271
  return {
17049
- oldPos: path10.oldPos + oldPosInc,
17272
+ oldPos: path11.oldPos + oldPosInc,
17050
17273
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17051
17274
  };
17052
17275
  } else {
17053
17276
  return {
17054
- oldPos: path10.oldPos + oldPosInc,
17277
+ oldPos: path11.oldPos + oldPosInc,
17055
17278
  lastComponent: { count: 1, added, removed, previousComponent: last }
17056
17279
  };
17057
17280
  }
@@ -17451,9 +17674,9 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader
17451
17674
  } }));
17452
17675
  }
17453
17676
  }
17454
- function splitLines(text2) {
17455
- const hasTrailingNl = text2.endsWith("\n");
17456
- const result = text2.split("\n").map((line) => line + "\n");
17677
+ function splitLines(text3) {
17678
+ const hasTrailingNl = text3.endsWith("\n");
17679
+ const result = text3.split("\n").map((line) => line + "\n");
17457
17680
  if (hasTrailingNl) {
17458
17681
  result.pop();
17459
17682
  } else {
@@ -17464,7 +17687,7 @@ function splitLines(text2) {
17464
17687
 
17465
17688
  // dist/pi-adapter.js
17466
17689
  import { randomUUID as randomUUID5 } from "node:crypto";
17467
- import path9 from "node:path";
17690
+ import path10 from "node:path";
17468
17691
 
17469
17692
  // ../../harness-adapter/dist/question.js
17470
17693
  function invalidRequest(message3) {
@@ -17650,6 +17873,61 @@ function parseHostUsage(value) {
17650
17873
  return { ...value };
17651
17874
  }
17652
17875
 
17876
+ // ../../harness-adapter/dist/native-session-summary.js
17877
+ var NATIVE_SESSION_IDLE_GAP_MS = 30 * 6e4;
17878
+ function emptyNativeSessionActivity() {
17879
+ return {
17880
+ firstActivityAt: null,
17881
+ lastActivityAt: null,
17882
+ activeMs: 0,
17883
+ turns: 0,
17884
+ edits: 0,
17885
+ editing: false
17886
+ };
17887
+ }
17888
+ function count(value) {
17889
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
17890
+ }
17891
+ function parseNativeSessionActivity(value) {
17892
+ if (typeof value !== "object" || value === null)
17893
+ return null;
17894
+ const activity = value;
17895
+ const time3 = (field) => field === null || count(field);
17896
+ return time3(activity.firstActivityAt) && time3(activity.lastActivityAt) && count(activity.activeMs) && count(activity.turns) && count(activity.edits) && typeof activity.editing === "boolean" ? {
17897
+ firstActivityAt: activity.firstActivityAt,
17898
+ lastActivityAt: activity.lastActivityAt,
17899
+ activeMs: activity.activeMs,
17900
+ turns: activity.turns,
17901
+ edits: activity.edits,
17902
+ editing: activity.editing
17903
+ } : null;
17904
+ }
17905
+ function recordNativeSessionActivity(activity, time3) {
17906
+ if (activity.firstActivityAt === null || time3 < activity.firstActivityAt) {
17907
+ activity.firstActivityAt = time3;
17908
+ }
17909
+ if (activity.lastActivityAt !== null) {
17910
+ const gap = time3 - activity.lastActivityAt;
17911
+ if (gap > 0 && gap <= NATIVE_SESSION_IDLE_GAP_MS)
17912
+ activity.activeMs += gap;
17913
+ if (gap <= 0)
17914
+ return;
17915
+ }
17916
+ activity.lastActivityAt = time3;
17917
+ }
17918
+ function startNativeSessionTurn(activity) {
17919
+ if (activity.editing)
17920
+ activity.edits += 1;
17921
+ activity.editing = false;
17922
+ activity.turns += 1;
17923
+ }
17924
+ function recordNativeSessionEdit(activity) {
17925
+ activity.editing = true;
17926
+ }
17927
+ function nativeSessionEdits(activity) {
17928
+ return activity.edits + (activity.editing ? 1 : 0);
17929
+ }
17930
+
17653
17931
  // ../../harness-adapter/dist/live-command-catalog.js
17654
17932
  var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17655
17933
  // Session lifecycle
@@ -17731,8 +18009,8 @@ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17731
18009
  const descriptor = catalog.commands.find(({ id }) => id === commandId);
17732
18010
  if (!descriptor)
17733
18011
  return null;
17734
- const text2 = typeof argumentText === "string" ? argumentText.trim() : "";
17735
- return text2 ? `${descriptor.invocation} ${text2}` : descriptor.invocation;
18012
+ const text3 = typeof argumentText === "string" ? argumentText.trim() : "";
18013
+ return text3 ? `${descriptor.invocation} ${text3}` : descriptor.invocation;
17736
18014
  }
17737
18015
  function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17738
18016
  if (!live)
@@ -17777,13 +18055,13 @@ function record4(value) {
17777
18055
  return typeof value === "object" && value !== null && !Array.isArray(value);
17778
18056
  }
17779
18057
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
17780
- async function childHistory(file2, parentSessionId, identity) {
18058
+ async function childHistory(file2, parentSessionId2, identity) {
17781
18059
  if (!path5.isAbsolute(file2))
17782
18060
  throw new Error("Pi child Session path is not absolute");
17783
18061
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
17784
18062
  try {
17785
- const stat2 = await handle.stat();
17786
- if (!stat2.isFile() || stat2.size > MAX_SESSION_BYTES)
18063
+ const stat3 = await handle.stat();
18064
+ if (!stat3.isFile() || stat3.size > MAX_SESSION_BYTES)
17787
18065
  throw new Error("Pi child Session exceeds read bounds");
17788
18066
  const buffer = Buffer.alloc(MAX_SESSION_BYTES + 1);
17789
18067
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
@@ -17801,7 +18079,7 @@ async function childHistory(file2, parentSessionId, identity) {
17801
18079
  entries.push(parsed.data);
17802
18080
  }
17803
18081
  const history = { entries, leafId: String(entries.at(-1)?.id ?? "") || null };
17804
- const snapshot = mapPiSnapshot(history, { sessionId: parentSessionId, model: null });
18082
+ const snapshot = mapPiSnapshot(history, { sessionId: parentSessionId2, model: null });
17805
18083
  const prefix = createHash2("sha256").update(identity).digest("hex");
17806
18084
  return {
17807
18085
  turns: snapshot.turns.map((turn) => {
@@ -17820,7 +18098,7 @@ async function childHistory(file2, parentSessionId, identity) {
17820
18098
  await handle.close();
17821
18099
  }
17822
18100
  }
17823
- async function readPiWorkflowChild(history, parentSessionId, address) {
18101
+ async function readPiWorkflowChild(history, parentSessionId2, address) {
17824
18102
  for (const entry of activePiEntries(history).reverse()) {
17825
18103
  const message3 = entry.message;
17826
18104
  if (!record4(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
@@ -17840,7 +18118,7 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
17840
18118
  const id = piWorkflowSubagentId(address);
17841
18119
  if (typeof result.sessionFile === "string") {
17842
18120
  try {
17843
- const snapshot = await childHistory(result.sessionFile, parentSessionId, id);
18121
+ const snapshot = await childHistory(result.sessionFile, parentSessionId2, id);
17844
18122
  if (snapshot.turns.length)
17845
18123
  return { ok: true, value: snapshot };
17846
18124
  } catch {
@@ -17850,7 +18128,7 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
17850
18128
  const output = result.finalOutput.slice(0, 64 * 1024);
17851
18129
  return {
17852
18130
  ok: true,
17853
- value: piSubagentSnapshot(parentSessionId, id, {
18131
+ value: piSubagentSnapshot(parentSessionId2, id, {
17854
18132
  kind: "pi-subagents.inspect-reply",
17855
18133
  version: 1,
17856
18134
  requestId: "native-workflow-result",
@@ -17888,8 +18166,8 @@ function record5(value) {
17888
18166
  function state(value) {
17889
18167
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
17890
18168
  }
17891
- function piSubagentArtifact(value, runId, parentSessionId) {
17892
- if (!record5(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
18169
+ function piSubagentArtifact(value, runId, parentSessionId2) {
18170
+ if (!record5(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId2 || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
17893
18171
  return null;
17894
18172
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
17895
18173
  return null;
@@ -17926,7 +18204,7 @@ function piSubagentArtifact(value, runId, parentSessionId) {
17926
18204
  ]
17927
18205
  });
17928
18206
  }
17929
- async function restorePiSubagents(history, parentSessionId, observer) {
18207
+ async function restorePiSubagents(history, parentSessionId2, observer) {
17930
18208
  const receipts = /* @__PURE__ */ new Map();
17931
18209
  for (const entry of activePiEntries(history)) {
17932
18210
  if (!record5(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record5(entry.message.details))
@@ -17940,15 +18218,15 @@ async function restorePiSubagents(history, parentSessionId, observer) {
17940
18218
  let file2;
17941
18219
  try {
17942
18220
  file2 = await open4(path6.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
17943
- const stat2 = await file2.stat();
17944
- if (!stat2.isFile() || stat2.size > 1024 * 1024)
18221
+ const stat3 = await file2.stat();
18222
+ if (!stat3.isFile() || stat3.size > 1024 * 1024)
17945
18223
  continue;
17946
18224
  const buffer = Buffer.alloc(1024 * 1024 + 1);
17947
18225
  const { bytesRead } = await file2.read(buffer, 0, buffer.length, 0);
17948
18226
  if (bytesRead > 1024 * 1024)
17949
18227
  continue;
17950
18228
  const value = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8"));
17951
- const runs = piSubagentArtifact(value, id, parentSessionId);
18229
+ const runs = piSubagentArtifact(value, id, parentSessionId2);
17952
18230
  if (runs)
17953
18231
  observer.restore(runs);
17954
18232
  } catch {
@@ -18017,6 +18295,11 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
18017
18295
  }
18018
18296
  }
18019
18297
 
18298
+ // dist/pi-native-usage.js
18299
+ import { createReadStream as createReadStream3 } from "node:fs";
18300
+ import { opendir as opendir2, stat as stat2 } from "node:fs/promises";
18301
+ import path8 from "node:path";
18302
+
18020
18303
  // dist/pi-session-import.js
18021
18304
  import { createReadStream as createReadStream2 } from "node:fs";
18022
18305
  import { opendir, realpath as realpath3, stat } from "node:fs/promises";
@@ -18074,6 +18357,11 @@ async function sessionFiles(directory, flat, signal) {
18074
18357
  await visit(directory, !flat);
18075
18358
  return files;
18076
18359
  }
18360
+ function piUserMessageTitle(message3) {
18361
+ const content = message3.content;
18362
+ const text3 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord4(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
18363
+ return text3.replaceAll("\0", "").trim().slice(0, HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) || null;
18364
+ }
18077
18365
  async function readCandidate(file2, signal) {
18078
18366
  const before = await stat(file2);
18079
18367
  if (!before.isFile() || before.size === 0)
@@ -18109,9 +18397,7 @@ async function readCandidate(file2, signal) {
18109
18397
  return null;
18110
18398
  const message3 = isRecord4(entry.message) ? entry.message : null;
18111
18399
  if (!firstMessage && entry.type === "message" && message3?.role === "user") {
18112
- const content = message3.content;
18113
- const text2 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord4(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
18114
- firstMessage = text2.replaceAll("\0", "").trim().slice(0, HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) || null;
18400
+ firstMessage = piUserMessageTitle(message3);
18115
18401
  }
18116
18402
  hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
18117
18403
  entries.set(entry.id, hasUser);
@@ -18248,10 +18534,284 @@ var PiSessionImportIndex = class {
18248
18534
  }
18249
18535
  };
18250
18536
 
18537
+ // dist/pi-native-usage.js
18538
+ var NEWLINE = 10;
18539
+ var ENTRY_TIMESTAMP = /"timestamp":"([^"]+)"/u;
18540
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
18541
+ var TITLE_MAX_LENGTH = 120;
18542
+ function isRecord5(value) {
18543
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18544
+ }
18545
+ function missing2(error51) {
18546
+ return isRecord5(error51) && error51.code === "ENOENT";
18547
+ }
18548
+ function count2(value) {
18549
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
18550
+ }
18551
+ function text2(value) {
18552
+ return typeof value === "string" && value.length > 0 ? value : void 0;
18553
+ }
18554
+ function sessionContext(value) {
18555
+ if (value === null)
18556
+ return null;
18557
+ if (!isRecord5(value) || typeof value.id !== "string")
18558
+ return void 0;
18559
+ if (value.cwd !== void 0 && typeof value.cwd !== "string")
18560
+ return void 0;
18561
+ return value.cwd === void 0 ? { id: value.id } : { id: value.id, cwd: value.cwd };
18562
+ }
18563
+ function emptySummary() {
18564
+ return {
18565
+ parentSessionId: null,
18566
+ name: null,
18567
+ firstMessage: null,
18568
+ model: null,
18569
+ activity: emptyNativeSessionActivity()
18570
+ };
18571
+ }
18572
+ function nullableText(value) {
18573
+ return value === null || typeof value === "string" && value.length > 0;
18574
+ }
18575
+ function fileSummary(value) {
18576
+ if (!isRecord5(value))
18577
+ return void 0;
18578
+ const { parentSessionId: parentSessionId2, name, firstMessage, model } = value;
18579
+ const activity = parseNativeSessionActivity(value.activity);
18580
+ return nullableText(parentSessionId2) && nullableText(name) && nullableText(firstMessage) && nullableText(model) && activity ? { parentSessionId: parentSessionId2, name, firstMessage, model, activity } : void 0;
18581
+ }
18582
+ function parseCursor(value) {
18583
+ const empty = { formatVersion: 2, files: {} };
18584
+ if (!isRecord5(value) || value.formatVersion !== 2 || !isRecord5(value.files))
18585
+ return empty;
18586
+ const files = {};
18587
+ for (const [relative, file2] of Object.entries(value.files)) {
18588
+ if (!isRecord5(file2))
18589
+ return empty;
18590
+ const session = sessionContext(file2.session);
18591
+ const summary = fileSummary(file2.summary);
18592
+ const { ino, offset } = file2;
18593
+ if (typeof ino !== "string" || typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 || session === void 0 || summary === void 0) {
18594
+ return empty;
18595
+ }
18596
+ files[relative] = { ino, offset, session, summary };
18597
+ }
18598
+ return { formatVersion: 2, files };
18599
+ }
18600
+ async function sessionFiles2(directory, signal) {
18601
+ const files = [];
18602
+ const visit = async (dir) => {
18603
+ signal.throwIfAborted();
18604
+ const entries = await opendir2(dir).catch((error51) => {
18605
+ if (missing2(error51))
18606
+ return null;
18607
+ throw error51;
18608
+ });
18609
+ if (!entries)
18610
+ return;
18611
+ for await (const entry of entries) {
18612
+ const child = path8.join(dir, entry.name);
18613
+ if (entry.isDirectory())
18614
+ await visit(child);
18615
+ else if (entry.isFile() && entry.name.endsWith(".jsonl"))
18616
+ files.push(child);
18617
+ }
18618
+ };
18619
+ await visit(directory);
18620
+ return files;
18621
+ }
18622
+ async function* completeLines(file2, start, end) {
18623
+ if (end <= start)
18624
+ return;
18625
+ let carry = Buffer.alloc(0);
18626
+ let carryStart = start;
18627
+ for await (const chunk of createReadStream3(file2, { start, end: end - 1 })) {
18628
+ const buffer = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
18629
+ let lineStart = 0;
18630
+ let newline = buffer.indexOf(NEWLINE, lineStart);
18631
+ while (newline !== -1) {
18632
+ yield { line: buffer.toString("utf8", lineStart, newline), end: carryStart + newline + 1 };
18633
+ lineStart = newline + 1;
18634
+ newline = buffer.indexOf(NEWLINE, lineStart);
18635
+ }
18636
+ carry = buffer.subarray(lineStart);
18637
+ carryStart += lineStart;
18638
+ }
18639
+ }
18640
+ function usageTokens(usage) {
18641
+ const output = count2(usage.output);
18642
+ const reasoning = Math.min(count2(usage.reasoning), output);
18643
+ return {
18644
+ input: count2(usage.input),
18645
+ cacheRead: count2(usage.cacheRead),
18646
+ cacheWrite: count2(usage.cacheWrite),
18647
+ output: output - reasoning,
18648
+ reasoning
18649
+ };
18650
+ }
18651
+ function reportedCost(usage) {
18652
+ const total = isRecord5(usage.cost) ? usage.cost.total : void 0;
18653
+ return typeof total === "number" && Number.isFinite(total) && total > 0 ? total : void 0;
18654
+ }
18655
+ function parentSessionId(header) {
18656
+ const parent = text2(header.parentSession);
18657
+ return parent && !parent.endsWith(".jsonl") ? parent : null;
18658
+ }
18659
+ function shortTitle(value) {
18660
+ const title = value?.replaceAll(/\s+/gu, " ").trim();
18661
+ if (!title)
18662
+ return null;
18663
+ const characters = [...title];
18664
+ return characters.length <= TITLE_MAX_LENGTH ? title : `${characters.slice(0, TITLE_MAX_LENGTH - 1).join("").trimEnd()}…`;
18665
+ }
18666
+ function summarize(summary, entry) {
18667
+ if (entry.type === "session_info") {
18668
+ summary.name = typeof entry.name === "string" ? shortTitle(entry.name) : null;
18669
+ return;
18670
+ }
18671
+ const message3 = isRecord5(entry.message) ? entry.message : null;
18672
+ if (entry.type !== "message" || !message3)
18673
+ return;
18674
+ if (message3.role === "user") {
18675
+ summary.firstMessage ??= shortTitle(piUserMessageTitle(message3));
18676
+ startNativeSessionTurn(summary.activity);
18677
+ } else if (message3.role === "assistant") {
18678
+ summary.model = text2(message3.model) ?? summary.model;
18679
+ if (Array.isArray(message3.content) && message3.content.some((block) => isRecord5(block) && block.type === "toolCall" && typeof block.name === "string" && EDIT_TOOLS.has(block.name))) {
18680
+ recordNativeSessionEdit(summary.activity);
18681
+ }
18682
+ }
18683
+ }
18684
+ function sessionSummary(relative, session, summary) {
18685
+ const { activity } = summary;
18686
+ if (!session || activity.firstActivityAt === null || activity.lastActivityAt === null) {
18687
+ return null;
18688
+ }
18689
+ const title = summary.name ?? summary.firstMessage;
18690
+ return {
18691
+ key: relative,
18692
+ nativeSessionId: session.id,
18693
+ ...summary.parentSessionId ? { parentSessionId: summary.parentSessionId } : {},
18694
+ ...title ? { title } : {},
18695
+ ...session.cwd ? { cwd: session.cwd } : {},
18696
+ ...summary.model ? { model: summary.model } : {},
18697
+ firstActivityAt: activity.firstActivityAt,
18698
+ lastActivityAt: activity.lastActivityAt,
18699
+ activeMs: activity.activeMs,
18700
+ turns: activity.turns,
18701
+ edits: nativeSessionEdits(activity)
18702
+ };
18703
+ }
18704
+ function sessionHeader(entry) {
18705
+ const id = text2(entry.id);
18706
+ if (entry.type !== "session" || !id)
18707
+ return null;
18708
+ const cwd = text2(entry.cwd);
18709
+ return { id, ...cwd ? { cwd } : {} };
18710
+ }
18711
+ function assistantRecord(entry, session) {
18712
+ const message3 = isRecord5(entry.message) ? entry.message : null;
18713
+ if (entry.type !== "message" || message3?.role !== "assistant" || !isRecord5(message3.usage)) {
18714
+ return null;
18715
+ }
18716
+ const entryId = text2(entry.id);
18717
+ const timestamp = text2(entry.timestamp);
18718
+ const time3 = timestamp === void 0 ? Number.NaN : Date.parse(timestamp);
18719
+ if (!entryId || !timestamp || !Number.isFinite(time3))
18720
+ return null;
18721
+ const tokens = usageTokens(message3.usage);
18722
+ const hasTokens = Object.values(tokens).some((value) => value > 0);
18723
+ const provider = text2(message3.provider);
18724
+ const model = text2(message3.model);
18725
+ const cost = reportedCost(message3.usage);
18726
+ return {
18727
+ // Forks copy entries with their id and timestamp; the pair also avoids short-id collisions.
18728
+ dedupeKey: `message:${entryId}:${timestamp}`,
18729
+ occurredAt: time3,
18730
+ nativeSessionId: session.id,
18731
+ ...provider ? { provider } : {},
18732
+ // A reply without tokens (for example a failed request) only counts as a conversation.
18733
+ ...model && hasTokens ? { model } : {},
18734
+ ...session.cwd ? { cwd: session.cwd } : {},
18735
+ tokens,
18736
+ conversations: 1,
18737
+ ...cost !== void 0 && hasTokens ? { reportedCostUsd: cost } : {}
18738
+ };
18739
+ }
18740
+ async function readFileUsage(file2, input, records) {
18741
+ const { summary } = input;
18742
+ let { session } = input;
18743
+ let offset = input.start;
18744
+ for await (const { line, end } of completeLines(file2, input.start, input.end)) {
18745
+ const first = offset === 0;
18746
+ offset = end;
18747
+ const timestamp = ENTRY_TIMESTAMP.exec(line)?.[1];
18748
+ const time3 = timestamp === void 0 ? Number.NaN : Date.parse(timestamp);
18749
+ if ((first || session) && Number.isFinite(time3)) {
18750
+ recordNativeSessionActivity(summary.activity, time3);
18751
+ }
18752
+ if (!first && !line.includes('"usage"') && !line.includes('"role":"user"') && !line.includes('"session_info"')) {
18753
+ continue;
18754
+ }
18755
+ let entry;
18756
+ try {
18757
+ entry = JSON.parse(line);
18758
+ } catch {
18759
+ continue;
18760
+ }
18761
+ if (!isRecord5(entry))
18762
+ continue;
18763
+ if (first) {
18764
+ session = sessionHeader(entry);
18765
+ summary.parentSessionId = session ? parentSessionId(entry) : null;
18766
+ continue;
18767
+ }
18768
+ if (!session)
18769
+ continue;
18770
+ summarize(summary, entry);
18771
+ const record6 = assistantRecord(entry, session);
18772
+ if (record6)
18773
+ records.push(record6);
18774
+ }
18775
+ return { offset, session };
18776
+ }
18777
+ async function readPiNativeUsage(environment, cursor, signal, onProgress) {
18778
+ const { directory } = piSessionImportDirectory(environment);
18779
+ const previous = parseCursor(cursor);
18780
+ const next = { formatVersion: 2, files: {} };
18781
+ const records = [];
18782
+ const sessions = [];
18783
+ const files = await sessionFiles2(directory, signal);
18784
+ onProgress?.({ processed: 0, total: files.length });
18785
+ for (const [index, file2] of files.entries()) {
18786
+ signal.throwIfAborted();
18787
+ const relative = path8.relative(directory, file2);
18788
+ try {
18789
+ const metadata = await stat2(file2, { bigint: true });
18790
+ const ino = metadata.ino.toString();
18791
+ const size = Number(metadata.size);
18792
+ const known = previous.files[relative];
18793
+ const resume = known && known.ino === ino && known.offset <= size ? known : null;
18794
+ const summary = resume ? structuredClone(resume.summary) : emptySummary();
18795
+ const { offset, session } = await readFileUsage(file2, { start: resume?.offset ?? 0, end: size, session: resume?.session ?? null, summary }, records);
18796
+ next.files[relative] = { ino, offset, session, summary };
18797
+ if (!resume || offset > resume.offset) {
18798
+ const changed = sessionSummary(relative, session, summary);
18799
+ if (changed)
18800
+ sessions.push(changed);
18801
+ }
18802
+ } catch (error51) {
18803
+ if (!missing2(error51))
18804
+ throw error51;
18805
+ }
18806
+ onProgress?.({ processed: index + 1, total: files.length });
18807
+ }
18808
+ return { records, sessions, cursor: next };
18809
+ }
18810
+
18251
18811
  // dist/pi-rpc-session.js
18252
18812
  import { spawn, spawnSync } from "node:child_process";
18253
18813
  import { randomUUID as randomUUID4 } from "node:crypto";
18254
- import path8 from "node:path";
18814
+ import path9 from "node:path";
18255
18815
 
18256
18816
  // dist/pi-slash-commands.js
18257
18817
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -18298,14 +18858,14 @@ function piDynamicCommandPrompt(catalog, commandId, argumentText) {
18298
18858
  }
18299
18859
 
18300
18860
  // dist/pi-usage.js
18301
- function isRecord5(value) {
18861
+ function isRecord6(value) {
18302
18862
  return typeof value === "object" && value !== null && !Array.isArray(value);
18303
18863
  }
18304
18864
  function nonNegativeSafeInteger(value) {
18305
18865
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
18306
18866
  }
18307
18867
  function optionalPiCacheHitRatePercent(value) {
18308
- if (!isRecord5(value) || value.role !== "assistant" || !isRecord5(value.usage))
18868
+ if (!isRecord6(value) || value.role !== "assistant" || !isRecord6(value.usage))
18309
18869
  return null;
18310
18870
  const input = nonNegativeSafeInteger(value.usage.input);
18311
18871
  const cacheRead = nonNegativeSafeInteger(value.usage.cacheRead);
@@ -18318,20 +18878,20 @@ function optionalPiCacheHitRatePercent(value) {
18318
18878
  function latestPiCacheHitRatePercent(history) {
18319
18879
  let latest = null;
18320
18880
  for (const entry of activePiEntries(history)) {
18321
- if (entry.type === "message" && isRecord5(entry.message) && entry.message.role === "assistant") {
18881
+ if (entry.type === "message" && isRecord6(entry.message) && entry.message.role === "assistant") {
18322
18882
  latest = optionalPiCacheHitRatePercent(entry.message);
18323
18883
  }
18324
18884
  }
18325
18885
  return latest;
18326
18886
  }
18327
18887
  function responseData(response, operation) {
18328
- if (!isRecord5(response.data)) {
18888
+ if (!isRecord6(response.data)) {
18329
18889
  throw new Error(`Pi RPC ${operation} response has no data`);
18330
18890
  }
18331
18891
  return response.data;
18332
18892
  }
18333
18893
  function contextUsage(value) {
18334
- if (!isRecord5(value))
18894
+ if (!isRecord6(value))
18335
18895
  throw new Error("Pi RPC context Usage is invalid");
18336
18896
  return parseHostUsage({
18337
18897
  contextUsedTokens: value.tokens,
@@ -18341,15 +18901,15 @@ function contextUsage(value) {
18341
18901
  function parsePiSessionUsage(response) {
18342
18902
  const data = responseData(response, "Session stats");
18343
18903
  const tokens = data.tokens;
18344
- if (tokens !== void 0 && !isRecord5(tokens)) {
18904
+ if (tokens !== void 0 && !isRecord6(tokens)) {
18345
18905
  throw new Error("Pi RPC Session stats tokens are invalid");
18346
18906
  }
18347
18907
  return parseHostUsage({
18348
- ...isRecord5(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
18349
- ...isRecord5(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
18350
- ...isRecord5(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
18351
- ...isRecord5(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
18352
- ...isRecord5(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
18908
+ ...isRecord6(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
18909
+ ...isRecord6(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
18910
+ ...isRecord6(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
18911
+ ...isRecord6(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
18912
+ ...isRecord6(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
18353
18913
  ...data.cost !== void 0 ? { totalCostUsd: data.cost } : {},
18354
18914
  ...data.contextUsage !== void 0 ? contextUsage(data.contextUsage) : {}
18355
18915
  });
@@ -18464,7 +19024,7 @@ var PiRpcUnsupportedCommandError = class extends Error {
18464
19024
  }
18465
19025
  };
18466
19026
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
18467
- function isRecord6(value) {
19027
+ function isRecord7(value) {
18468
19028
  return typeof value === "object" && value !== null && !Array.isArray(value);
18469
19029
  }
18470
19030
  function message2(value) {
@@ -18476,13 +19036,13 @@ function nonBlankString(value) {
18476
19036
  function parseNativeModel(value, context) {
18477
19037
  if (value === null || value === void 0)
18478
19038
  return null;
18479
- if (!isRecord6(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
19039
+ if (!isRecord7(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
18480
19040
  throw new PiRpcFaultError("protocolError", `Pi RPC returned an invalid ${context} Model`);
18481
19041
  }
18482
19042
  return { provider: value.provider, id: value.id };
18483
19043
  }
18484
19044
  function sessionStateData(response) {
18485
- const data = isRecord6(response.data) ? response.data : null;
19045
+ const data = isRecord7(response.data) ? response.data : null;
18486
19046
  if (!data)
18487
19047
  throw new PiRpcFaultError("protocolError", "Pi RPC state response has no data");
18488
19048
  return data;
@@ -18514,13 +19074,13 @@ function parseSessionStreaming(response) {
18514
19074
  return isStreaming;
18515
19075
  }
18516
19076
  function parseSessionHistory(response) {
18517
- const data = isRecord6(response.data) ? response.data : null;
19077
+ const data = isRecord7(response.data) ? response.data : null;
18518
19078
  if (!data || !Array.isArray(data.entries)) {
18519
19079
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response has no Entries");
18520
19080
  }
18521
19081
  const entries = data.entries.map((entry) => {
18522
19082
  const parsed = jsonValueSchema.safeParse(entry);
18523
- if (!parsed.success || !isRecord6(parsed.data)) {
19083
+ if (!parsed.success || !isRecord7(parsed.data)) {
18524
19084
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response contains an invalid Entry");
18525
19085
  }
18526
19086
  return parsed.data;
@@ -18531,7 +19091,7 @@ function parseSessionHistory(response) {
18531
19091
  return { entries, leafId: data.leafId };
18532
19092
  }
18533
19093
  function parseAvailableThinkingLevels(response) {
18534
- const data = isRecord6(response.data) ? response.data : null;
19094
+ const data = isRecord7(response.data) ? response.data : null;
18535
19095
  if (!data || !Array.isArray(data.levels) || data.levels.length === 0) {
18536
19096
  throw new PiRpcFaultError("protocolError", "Pi RPC Thinking catalog response has no levels");
18537
19097
  }
@@ -18548,45 +19108,45 @@ function parseAvailableThinkingLevels(response) {
18548
19108
  return levels;
18549
19109
  }
18550
19110
  function parseAvailableModels(response) {
18551
- const data = isRecord6(response.data) ? response.data : null;
19111
+ const data = isRecord7(response.data) ? response.data : null;
18552
19112
  if (!data || !Array.isArray(data.models)) {
18553
19113
  throw new PiRpcFaultError("protocolError", "Pi RPC Model catalog response has no models");
18554
19114
  }
18555
19115
  return data.models.map((model) => {
18556
19116
  const parsed = parseNativeModel(model, "catalog");
18557
- if (!parsed || !isRecord6(model) || typeof model.reasoning !== "boolean") {
19117
+ if (!parsed || !isRecord7(model) || typeof model.reasoning !== "boolean") {
18558
19118
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
18559
19119
  }
18560
19120
  return { ...parsed, reasoning: model.reasoning };
18561
19121
  });
18562
19122
  }
18563
19123
  function assistantText(value) {
18564
- if (!isRecord6(value) || value.role !== "assistant" || !Array.isArray(value.content))
19124
+ if (!isRecord7(value) || value.role !== "assistant" || !Array.isArray(value.content))
18565
19125
  return null;
18566
- return value.content.filter((content) => isRecord6(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
19126
+ return value.content.filter((content) => isRecord7(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
18567
19127
  }
18568
19128
  function assistantMessageId(value) {
18569
- if (!isRecord6(value) || value.role !== "assistant")
19129
+ if (!isRecord7(value) || value.role !== "assistant")
18570
19130
  return null;
18571
19131
  return nonBlankString(value.responseId) ? value.responseId : null;
18572
19132
  }
18573
19133
  function extractReasoningText(content) {
18574
- if (!isRecord6(content))
19134
+ if (!isRecord7(content))
18575
19135
  return null;
18576
19136
  const type = String(content.type ?? "");
18577
19137
  if (type === "thinking" || type === "reasoning" || type === "thought") {
18578
- const text2 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
18579
- return typeof text2 === "string" ? text2 : null;
19138
+ const text3 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
19139
+ return typeof text3 === "string" ? text3 : null;
18580
19140
  }
18581
19141
  return null;
18582
19142
  }
18583
19143
  function assistantReasoning(value) {
18584
- if (!isRecord6(value) || value.role !== "assistant" || !Array.isArray(value.content))
19144
+ if (!isRecord7(value) || value.role !== "assistant" || !Array.isArray(value.content))
18585
19145
  return null;
18586
- return value.content.map(extractReasoningText).filter((text2) => typeof text2 === "string").join("");
19146
+ return value.content.map(extractReasoningText).filter((text3) => typeof text3 === "string").join("");
18587
19147
  }
18588
19148
  function assistantFailure(value) {
18589
- if (!isRecord6(value) || value.role !== "assistant")
19149
+ if (!isRecord7(value) || value.role !== "assistant")
18590
19150
  return void 0;
18591
19151
  if (value.stopReason !== "error" && value.stopReason !== "aborted")
18592
19152
  return null;
@@ -18606,7 +19166,7 @@ function signalProcessTree(child, signal) {
18606
19166
  try {
18607
19167
  process.kill(-child.pid, signal);
18608
19168
  } catch (error51) {
18609
- if (!isRecord6(error51) || error51.code !== "ESRCH")
19169
+ if (!isRecord7(error51) || error51.code !== "ESRCH")
18610
19170
  throw error51;
18611
19171
  }
18612
19172
  }
@@ -18648,7 +19208,7 @@ function piRpcProcessCommand(options, dependencies = {}) {
18648
19208
  ...thinkingArguments,
18649
19209
  ...sessionArguments
18650
19210
  ];
18651
- const extension = path8.win32.extname(command).toLowerCase();
19211
+ const extension = path9.win32.extname(command).toLowerCase();
18652
19212
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
18653
19213
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
18654
19214
  }
@@ -18752,7 +19312,7 @@ var PiRpcSession = class {
18752
19312
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
18753
19313
  });
18754
19314
  child.once("error", (error51) => {
18755
- const kind = isRecord6(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
19315
+ const kind = isRecord7(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
18756
19316
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
18757
19317
  });
18758
19318
  child.once("exit", (code, signal) => {
@@ -18894,13 +19454,13 @@ var PiRpcSession = class {
18894
19454
  throw fault;
18895
19455
  }
18896
19456
  }
18897
- async runTurn(text2, onEvent) {
19457
+ async runTurn(text3, onEvent) {
18898
19458
  if (!this.#child || !this.#state || this.#closed || this.#failed) {
18899
19459
  throw new Error("Pi RPC Session is unavailable");
18900
19460
  }
18901
19461
  if (this.#activeTurn)
18902
19462
  throw new Error("Pi RPC Session already has an active Turn");
18903
- if (text2.length === 0)
19463
+ if (text3.length === 0)
18904
19464
  throw new Error("Pi text Turn must not be empty");
18905
19465
  const settled = new Promise((resolve, reject) => {
18906
19466
  this.#activeTurn = {
@@ -18929,7 +19489,7 @@ var PiRpcSession = class {
18929
19489
  };
18930
19490
  });
18931
19491
  try {
18932
- await this.#send("prompt", { message: text2 });
19492
+ await this.#send("prompt", { message: text3 });
18933
19493
  } catch (error51) {
18934
19494
  this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
18935
19495
  }
@@ -19032,7 +19592,7 @@ var PiRpcSession = class {
19032
19592
  this.#buffer = this.#buffer.subarray(newline + 1);
19033
19593
  try {
19034
19594
  const value = JSON.parse(textDecoder.decode(frame));
19035
- if (!isRecord6(value) || typeof value.type !== "string") {
19595
+ if (!isRecord7(value) || typeof value.type !== "string") {
19036
19596
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid envelope");
19037
19597
  }
19038
19598
  this.#handle(value);
@@ -19073,7 +19633,7 @@ var PiRpcSession = class {
19073
19633
  this.#armCommandTimeout(id, pending);
19074
19634
  }
19075
19635
  }
19076
- const outcome = value.aborted === true ? "cancelled" : isRecord6(value.result) ? "succeeded" : "failed";
19636
+ const outcome = value.aborted === true ? "cancelled" : isRecord7(value.result) ? "succeeded" : "failed";
19077
19637
  const event = {
19078
19638
  type: "compaction.completed",
19079
19639
  outcome,
@@ -19111,12 +19671,12 @@ var PiRpcSession = class {
19111
19671
  this.#startAssistantMessage(active, value.message);
19112
19672
  return;
19113
19673
  }
19114
- if (value.type === "message_update" && isRecord6(value.assistantMessageEvent)) {
19674
+ if (value.type === "message_update" && isRecord7(value.assistantMessageEvent)) {
19115
19675
  const event = value.assistantMessageEvent;
19116
19676
  const eventType = String(event.type ?? "");
19117
19677
  const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
19118
19678
  const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
19119
- const delta = typeof event.delta === "string" ? event.delta : typeof event.thinking === "string" ? event.thinking : typeof event.reasoning === "string" ? event.reasoning : typeof event.text === "string" ? event.text : isRecord6(event.delta) && typeof event.delta.thinking === "string" ? event.delta.thinking : isRecord6(event.delta) && typeof event.delta.text === "string" ? event.delta.text : null;
19679
+ const delta = typeof event.delta === "string" ? event.delta : typeof event.thinking === "string" ? event.thinking : typeof event.reasoning === "string" ? event.reasoning : typeof event.text === "string" ? event.text : isRecord7(event.delta) && typeof event.delta.thinking === "string" ? event.delta.thinking : isRecord7(event.delta) && typeof event.delta.text === "string" ? event.delta.text : null;
19120
19680
  if (isThinking && delta !== null && delta.length > 0) {
19121
19681
  const messageId = this.#ensureAssistantMessage(active, value.message);
19122
19682
  active.reasoningMessageOpen = true;
@@ -19429,7 +19989,7 @@ var PiRpcSession = class {
19429
19989
  return;
19430
19990
  }
19431
19991
  active.failure = failure;
19432
- if (active.origin === "autonomous" && isRecord6(value) && value.stopReason === "aborted") {
19992
+ if (active.origin === "autonomous" && isRecord7(value) && value.stopReason === "aborted") {
19433
19993
  active.nativeCancellationObserved = true;
19434
19994
  }
19435
19995
  this.#latestCacheHitRatePercent = cacheHitRatePercent;
@@ -19590,7 +20150,7 @@ var piCommandCatalog = harnessCommandCatalogSchema.parse({
19590
20150
  ]
19591
20151
  });
19592
20152
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
19593
- function isRecord7(value) {
20153
+ function isRecord8(value) {
19594
20154
  return typeof value === "object" && value !== null && !Array.isArray(value);
19595
20155
  }
19596
20156
  function errorMessage(error51) {
@@ -19605,7 +20165,7 @@ var PiAdapterFaultError = class extends Error {
19605
20165
  }
19606
20166
  };
19607
20167
  function normalizedError(error51, fallbackCode) {
19608
- if (isRecord7(error51) && error51.code === "ENOENT") {
20168
+ if (isRecord8(error51) && error51.code === "ENOENT") {
19609
20169
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
19610
20170
  }
19611
20171
  if (error51 instanceof PiAdapterFaultError)
@@ -19668,7 +20228,7 @@ function nativeModelForHistory(state2) {
19668
20228
  return nativeModelFromState(state2);
19669
20229
  }
19670
20230
  function sessionFileFromRef(ref) {
19671
- if (ref.harnessId !== piHarnessId2 || !isRecord7(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
20231
+ if (ref.harnessId !== piHarnessId2 || !isRecord8(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
19672
20232
  throw new Error("Pi Native Session Ref has no resumable Session file");
19673
20233
  }
19674
20234
  return ref.locator.sessionFile;
@@ -19683,35 +20243,35 @@ function toolFailure(toolName) {
19683
20243
  function nativeText(value) {
19684
20244
  if (typeof value === "string")
19685
20245
  return value;
19686
- if (!isRecord7(value) || !Array.isArray(value.content))
20246
+ if (!isRecord8(value) || !Array.isArray(value.content))
19687
20247
  return "";
19688
- return value.content.filter((content) => isRecord7(content) && content.type === "text" && typeof content.text === "string").map(({ text: text2 }) => text2).join("");
20248
+ return value.content.filter((content) => isRecord8(content) && content.type === "text" && typeof content.text === "string").map(({ text: text3 }) => text3).join("");
19689
20249
  }
19690
20250
  function boundedOutput(value, limit) {
19691
- const text2 = nativeText(value);
19692
- if (text2.length === 0)
20251
+ const text3 = nativeText(value);
20252
+ if (text3.length === 0)
19693
20253
  return void 0;
19694
- const truncated = text2.length > limit;
20254
+ const truncated = text3.length > limit;
19695
20255
  return {
19696
- content: [{ type: "text", text: truncated ? text2.slice(0, limit) : text2 }],
20256
+ content: [{ type: "text", text: truncated ? text3.slice(0, limit) : text3 }],
19697
20257
  ...truncated ? { truncated: true } : {}
19698
20258
  };
19699
20259
  }
19700
20260
  function outputText(output) {
19701
- return output?.content.filter((content) => content.type === "text").map(({ text: text2 }) => text2).join("") ?? "";
20261
+ return output?.content.filter((content) => content.type === "text").map(({ text: text3 }) => text3).join("") ?? "";
19702
20262
  }
19703
20263
  function stringField(value, key) {
19704
- if (!isRecord7(value))
20264
+ if (!isRecord8(value))
19705
20265
  return void 0;
19706
20266
  const field = value[key];
19707
20267
  if (typeof field === "string" && field.length > 0)
19708
20268
  return field;
19709
- if (isRecord7(value.input)) {
20269
+ if (isRecord8(value.input)) {
19710
20270
  const nested = value.input[key];
19711
20271
  if (typeof nested === "string" && nested.length > 0)
19712
20272
  return nested;
19713
20273
  }
19714
- if (isRecord7(value.arguments)) {
20274
+ if (isRecord8(value.arguments)) {
19715
20275
  const nested = value.arguments[key];
19716
20276
  if (typeof nested === "string" && nested.length > 0)
19717
20277
  return nested;
@@ -19719,7 +20279,7 @@ function stringField(value, key) {
19719
20279
  return void 0;
19720
20280
  }
19721
20281
  function numberField(value, key) {
19722
- if (!isRecord7(value))
20282
+ if (!isRecord8(value))
19723
20283
  return void 0;
19724
20284
  const field = value[key];
19725
20285
  return typeof field === "number" || field === null ? field : void 0;
@@ -19730,10 +20290,10 @@ function stripDiffPrefix(pathString) {
19730
20290
  return pathString.startsWith("a/") || pathString.startsWith("b/") ? pathString.slice(2) : pathString;
19731
20291
  }
19732
20292
  function displayPath(nativePath, cwd) {
19733
- const resolvedCwd = path9.resolve(cwd);
19734
- const resolvedPath = path9.isAbsolute(nativePath) ? path9.resolve(nativePath) : path9.resolve(cwd, nativePath);
19735
- const relative = path9.relative(resolvedCwd, resolvedPath);
19736
- const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path9.sep}`);
20293
+ const resolvedCwd = path10.resolve(cwd);
20294
+ const resolvedPath = path10.isAbsolute(nativePath) ? path10.resolve(nativePath) : path10.resolve(cwd, nativePath);
20295
+ const relative = path10.relative(resolvedCwd, resolvedPath);
20296
+ const inside = relative.length > 0 && relative !== ".." && !relative.startsWith(`..${path10.sep}`);
19737
20297
  const selected = inside ? relative : resolvedPath;
19738
20298
  const normalized = selected.replaceAll("\\", "/");
19739
20299
  if (normalized.length === 0 || normalized === ".")
@@ -19794,7 +20354,7 @@ function fileMutatingKind(toolName) {
19794
20354
  return null;
19795
20355
  }
19796
20356
  function nestedToolString(value, keys) {
19797
- if (!isRecord7(value))
20357
+ if (!isRecord8(value))
19798
20358
  return void 0;
19799
20359
  for (const key of keys) {
19800
20360
  const field = value[key];
@@ -19809,14 +20369,14 @@ function nestedToolString(value, keys) {
19809
20369
  return void 0;
19810
20370
  }
19811
20371
  function patchFromResult(result) {
19812
- if (!isRecord7(result))
20372
+ if (!isRecord8(result))
19813
20373
  return void 0;
19814
20374
  for (const key of ["patch", "diff", "unifiedDiff"]) {
19815
20375
  const field = result[key];
19816
20376
  if (typeof field === "string" && field.length > 0)
19817
20377
  return field;
19818
20378
  }
19819
- if (isRecord7(result.details)) {
20379
+ if (isRecord8(result.details)) {
19820
20380
  for (const key of ["patch", "diff", "unifiedDiff"]) {
19821
20381
  const field = result.details[key];
19822
20382
  if (typeof field === "string" && field.length > 0)
@@ -19981,13 +20541,13 @@ var PiHarnessSession = class {
19981
20541
  return this.#transport?.state.sessionId === id;
19982
20542
  }
19983
20543
  async readSubagentHistory(cwd) {
19984
- if (this.#phase !== "open" || path9.resolve(cwd) !== path9.resolve(this.#cwd)) {
20544
+ if (this.#phase !== "open" || path10.resolve(cwd) !== path10.resolve(this.#cwd)) {
19985
20545
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
19986
20546
  }
19987
20547
  return (await this.#ensureTransport()).getEntries();
19988
20548
  }
19989
20549
  async inspectSubagent(id, cwd) {
19990
- if (this.#phase !== "open" || path9.resolve(cwd) !== path9.resolve(this.#cwd)) {
20550
+ if (this.#phase !== "open" || path10.resolve(cwd) !== path10.resolve(this.#cwd)) {
19991
20551
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
19992
20552
  }
19993
20553
  const transport = await this.#ensureTransport();
@@ -20062,8 +20622,8 @@ var PiHarnessSession = class {
20062
20622
  }
20063
20623
  };
20064
20624
  }
20065
- const text2 = command.input.map((input) => input.text).join("\n");
20066
- if (text2.length === 0) {
20625
+ const text3 = command.input.map((input) => input.text).join("\n");
20626
+ if (text3.length === 0) {
20067
20627
  return {
20068
20628
  ok: false,
20069
20629
  error: {
@@ -20120,7 +20680,7 @@ var PiHarnessSession = class {
20120
20680
  this.#active = active;
20121
20681
  this.#event({ type: "turn.started", turnId: command.turnId });
20122
20682
  this.#event({ type: "item.started", turnId: command.turnId, item });
20123
- void transport.runTurn(text2, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
20683
+ void transport.runTurn(text3, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
20124
20684
  try {
20125
20685
  const identity = await this.#completedTurnIdentity(active, transport);
20126
20686
  this.#completeTurn(active, result.cancelled ? {
@@ -20848,16 +21408,16 @@ var PiHarnessSession = class {
20848
21408
  active.agentMessageId = messageId;
20849
21409
  active.sawAssistantMessage = true;
20850
21410
  }
20851
- #appendText(active, text2) {
21411
+ #appendText(active, text3) {
20852
21412
  if (active.agentMessageId === null || !active.agentItem) {
20853
21413
  throw new Error("Pi Assistant text arrived outside an active message");
20854
21414
  }
20855
- active.agentItem = { ...active.agentItem, text: active.agentItem.text + text2 };
21415
+ active.agentItem = { ...active.agentItem, text: active.agentItem.text + text3 };
20856
21416
  this.#event({
20857
21417
  type: "item.updated",
20858
21418
  turnId: active.command.turnId,
20859
21419
  itemId: active.agentItem.itemId,
20860
- update: { type: "text.append", text: text2 }
21420
+ update: { type: "text.append", text: text3 }
20861
21421
  });
20862
21422
  }
20863
21423
  #completeAgentItem(active, outcome, completeEmpty) {
@@ -20868,8 +21428,8 @@ var PiHarnessSession = class {
20868
21428
  active.agentItem = null;
20869
21429
  this.#completeItem(active, item, outcome);
20870
21430
  }
20871
- #appendReasoning(active, text2) {
20872
- if (text2.length === 0)
21431
+ #appendReasoning(active, text3) {
21432
+ if (text3.length === 0)
20873
21433
  return;
20874
21434
  if (!active.reasoningItem) {
20875
21435
  active.reasoningItem = {
@@ -20885,13 +21445,13 @@ var PiHarnessSession = class {
20885
21445
  }
20886
21446
  active.reasoningItem = {
20887
21447
  ...active.reasoningItem,
20888
- text: active.reasoningItem.text + text2
21448
+ text: active.reasoningItem.text + text3
20889
21449
  };
20890
21450
  this.#event({
20891
21451
  type: "item.updated",
20892
21452
  turnId: active.command.turnId,
20893
21453
  itemId: active.reasoningItem.itemId,
20894
- update: { type: "text.append", text: text2 }
21454
+ update: { type: "text.append", text: text3 }
20895
21455
  });
20896
21456
  }
20897
21457
  #completeReasoning(active, outcome) {
@@ -21197,6 +21757,11 @@ var PiAdapter = class {
21197
21757
  };
21198
21758
  }
21199
21759
  });
21760
+ nativeUsage = Object.freeze({
21761
+ read: (cursor, onProgress) => this.#readImport((signal) => readPiNativeUsage(this.#environment, cursor, signal, onProgress), "Pi usage records could not be read; check storage access and retry"),
21762
+ resumeCommand: (nativeSessionId) => `pi --session ${nativeSessionId}`
21763
+ });
21764
+ #environment;
21200
21765
  #importIndex;
21201
21766
  #importAbort = new AbortController();
21202
21767
  #importRequests = /* @__PURE__ */ new Set();
@@ -21226,20 +21791,17 @@ var PiAdapter = class {
21226
21791
  remove: (name) => updateCatalog(imports.remove(name))
21227
21792
  };
21228
21793
  this.#createTransport = dependencies.createTransport;
21229
- this.#importIndex = new PiSessionImportIndex({ ...process.env, ...options.environment });
21794
+ this.#environment = { ...process.env, ...options.environment };
21795
+ this.#importIndex = new PiSessionImportIndex(this.#environment);
21230
21796
  this.#closeTimeoutMs = options.closeTimeoutMs ?? 2e3;
21231
21797
  this.#toolOutputLimit = options.toolOutputLimit ?? DEFAULT_TOOL_OUTPUT_LIMIT;
21232
21798
  }
21233
- #readImport(operation) {
21799
+ #readImport(operation, failureMessage = "Pi Session discovery failed; check storage access and duplicate Session identities, then retry after closing native clients") {
21234
21800
  if (this.#importAbort.signal.aborted)
21235
21801
  return Promise.resolve({ ok: false, error: invalidState("Pi Adapter is closed") });
21236
21802
  const request = operation(this.#importAbort.signal).then((value) => ({ ok: true, value })).catch(() => ({
21237
21803
  ok: false,
21238
- error: {
21239
- code: "unavailable",
21240
- message: "Pi Session discovery failed; check storage access and duplicate Session identities, then retry after closing native clients",
21241
- retryable: true
21242
- }
21804
+ error: { code: "unavailable", message: failureMessage, retryable: true }
21243
21805
  })).finally(() => this.#importRequests.delete(request));
21244
21806
  this.#importRequests.add(request);
21245
21807
  return request;