@liberseek/boft-cli-win32-arm64 0.8.4 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +2 -2
  2. package/THIRD_PARTY_NOTICES.txt +6 -2
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +129 -28
  5. package/app/console-web.js +336 -78
  6. package/app/desktop-controller.mjs +1741 -60
  7. package/app/host-runtime.mjs +4983 -2002
  8. package/app/plugins/antigravity/plugin.mjs +423 -63
  9. package/app/plugins/claude-code/plugin.mjs +417 -264
  10. package/app/plugins/codebuddy/plugin.mjs +256 -134
  11. package/app/plugins/codex-usage/plugin.mjs +97 -32
  12. package/app/plugins/copilot/plugin.mjs +122 -57
  13. package/app/plugins/cursor-cli/plugin.mjs +236 -139
  14. package/app/plugins/deepseek-harness/plugin.mjs +584 -86
  15. package/app/plugins/devin/assets/icon.svg +1 -0
  16. package/app/plugins/devin/manifest.json +30 -0
  17. package/app/plugins/devin/plugin.mjs +23425 -0
  18. package/app/plugins/enabled.json +2 -0
  19. package/app/plugins/grok/plugin.mjs +839 -500
  20. package/app/plugins/hermes/plugin.mjs +522 -200
  21. package/app/plugins/kimi-code/plugin.mjs +134 -22
  22. package/app/plugins/kiro-cli/plugin.mjs +84 -19
  23. package/app/plugins/muse/plugin.mjs +74 -9
  24. package/app/plugins/omp/plugin.mjs +104 -39
  25. package/app/plugins/opencode/plugin.mjs +126 -61
  26. package/app/plugins/pi/plugin.mjs +1769 -468
  27. package/app/plugins/qoder/plugin.mjs +9617 -8682
  28. package/app/plugins/qoder-cn/plugin.mjs +9617 -8682
  29. package/app/plugins/qwen-code/assets/icon.svg +1 -0
  30. package/app/plugins/qwen-code/manifest.json +29 -0
  31. package/app/plugins/qwen-code/plugin.mjs +29366 -0
  32. package/app/plugins/workbuddy/plugin.mjs +256 -134
  33. package/app/plugins/zcode/plugin.mjs +265 -42
  34. package/app/renderer-extension.js +3286 -528
  35. package/bin/boft.exe +0 -0
  36. package/libexec/boft-node-repl.exe +0 -0
  37. package/libexec/boft-shim.exe +0 -0
  38. package/libexec/boft-updater.exe +0 -0
  39. package/licenses/Qwen-Code-SDK-LICENSE.txt +203 -0
  40. package/package.json +2 -2
@@ -528,9 +528,9 @@ async function jsonlHeader(file2, match, signal, maxLines = 4) {
528
528
  continue;
529
529
  }
530
530
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
531
- const record7 = value;
532
- if (match(record7))
533
- return record7;
531
+ const record9 = value;
532
+ if (match(record9))
533
+ return record9;
534
534
  }
535
535
  }
536
536
  return null;
@@ -1317,10 +1317,10 @@ function mergeDefs(...defs) {
1317
1317
  function cloneDef(schema) {
1318
1318
  return mergeDefs(schema._zod.def);
1319
1319
  }
1320
- function getElementAtPath(obj, path16) {
1321
- if (!path16)
1320
+ function getElementAtPath(obj, path18) {
1321
+ if (!path18)
1322
1322
  return obj;
1323
- return path16.reduce((acc, key) => acc?.[key], obj);
1323
+ return path18.reduce((acc, key) => acc?.[key], obj);
1324
1324
  }
1325
1325
  function promiseAllObject(promisesObj) {
1326
1326
  const keys = Object.keys(promisesObj);
@@ -1729,11 +1729,11 @@ function explicitlyAborted(x, startIndex = 0) {
1729
1729
  }
1730
1730
  return false;
1731
1731
  }
1732
- function prefixIssues(path16, issues) {
1732
+ function prefixIssues(path18, issues) {
1733
1733
  return issues.map((iss) => {
1734
1734
  var _a3;
1735
1735
  (_a3 = iss).path ?? (_a3.path = []);
1736
- iss.path.unshift(path16);
1736
+ iss.path.unshift(path18);
1737
1737
  return iss;
1738
1738
  });
1739
1739
  }
@@ -1880,16 +1880,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1880
1880
  }
1881
1881
  function formatError(error51, mapper = (issue2) => issue2.message) {
1882
1882
  const fieldErrors = { _errors: [] };
1883
- const processError = (error52, path16 = []) => {
1883
+ const processError = (error52, path18 = []) => {
1884
1884
  for (const issue2 of error52.issues) {
1885
1885
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1886
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1886
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1887
1887
  } else if (issue2.code === "invalid_key") {
1888
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1888
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1889
1889
  } else if (issue2.code === "invalid_element") {
1890
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1890
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1891
1891
  } else {
1892
- const fullpath = [...path16, ...issue2.path];
1892
+ const fullpath = [...path18, ...issue2.path];
1893
1893
  if (fullpath.length === 0) {
1894
1894
  fieldErrors._errors.push(mapper(issue2));
1895
1895
  } else {
@@ -1916,17 +1916,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1916
1916
  }
1917
1917
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1918
1918
  const result = { errors: [] };
1919
- const processError = (error52, path16 = []) => {
1919
+ const processError = (error52, path18 = []) => {
1920
1920
  var _a3, _b;
1921
1921
  for (const issue2 of error52.issues) {
1922
1922
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1923
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1923
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
1924
1924
  } else if (issue2.code === "invalid_key") {
1925
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1925
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1926
1926
  } else if (issue2.code === "invalid_element") {
1927
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1927
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
1928
1928
  } else {
1929
- const fullpath = [...path16, ...issue2.path];
1929
+ const fullpath = [...path18, ...issue2.path];
1930
1930
  if (fullpath.length === 0) {
1931
1931
  result.errors.push(mapper(issue2));
1932
1932
  continue;
@@ -1958,8 +1958,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1958
1958
  }
1959
1959
  function toDotPath(_path) {
1960
1960
  const segs = [];
1961
- const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1962
- for (const seg of path16) {
1961
+ const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1962
+ for (const seg of path18) {
1963
1963
  if (typeof seg === "number")
1964
1964
  segs.push(`[${seg}]`);
1965
1965
  else if (typeof seg === "symbol")
@@ -3580,10 +3580,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3580
3580
  const shape = def.shape;
3581
3581
  const propValues = {};
3582
3582
  for (const key in shape) {
3583
- const field = shape[key]._zod;
3584
- if (field.values) {
3583
+ const field2 = shape[key]._zod;
3584
+ if (field2.values) {
3585
3585
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
3586
- for (const v of field.values)
3586
+ for (const v of field2.values)
3587
3587
  propValues[key].add(v);
3588
3588
  }
3589
3589
  }
@@ -8189,8 +8189,8 @@ function ko_default() {
8189
8189
  }
8190
8190
 
8191
8191
  // ../../../node_modules/zod/v4/locales/lt.js
8192
- var capitalizeFirstCharacter = (text2) => {
8193
- return text2.charAt(0).toUpperCase() + text2.slice(1);
8192
+ var capitalizeFirstCharacter = (text4) => {
8193
+ return text4.charAt(0).toUpperCase() + text4.slice(1);
8194
8194
  };
8195
8195
  function getUnitTypeFromNumber(number4) {
8196
8196
  const abs = Math.abs(number4);
@@ -14651,13 +14651,13 @@ function resolveRef(ref, ctx) {
14651
14651
  if (!ref.startsWith("#")) {
14652
14652
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14653
14653
  }
14654
- const path16 = ref.slice(1).split("/").filter(Boolean);
14655
- if (path16.length === 0) {
14654
+ const path18 = ref.slice(1).split("/").filter(Boolean);
14655
+ if (path18.length === 0) {
14656
14656
  return ctx.rootSchema;
14657
14657
  }
14658
14658
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14659
- if (path16[0] === defsKey) {
14660
- const key = path16[1];
14659
+ if (path18[0] === defsKey) {
14660
+ const key = path18[1];
14661
14661
  if (!key || !ctx.defs[key]) {
14662
14662
  throw new Error(`Reference not found: ${ref}`);
14663
14663
  }
@@ -15146,7 +15146,7 @@ var harnessDisplaySetSchema = external_exports.strictObject({
15146
15146
 
15147
15147
  // ../../shared-contracts/dist/harness-presentation.js
15148
15148
  var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
15149
- var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text2) => text2.trim().length > 0);
15149
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text4) => text4.trim().length > 0);
15150
15150
  var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
15151
15151
  label: displayText(256).optional(),
15152
15152
  description: displayText(1024).optional()
@@ -15223,6 +15223,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
15223
15223
  cachedInputTokens: count,
15224
15224
  cacheWriteInputTokens: count,
15225
15225
  cacheKnownInputTokens: count,
15226
+ cacheHitCachedInputTokens: count,
15227
+ cacheHitInputTokens: count,
15226
15228
  outputTokens: count,
15227
15229
  reasoningOutputTokens: count,
15228
15230
  /** USD at the public price, summed over the priced requests only. */
@@ -15330,6 +15332,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
15330
15332
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
15331
15333
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
15332
15334
 
15335
+ // ../../shared-contracts/dist/thread-questions.js
15336
+ var field = external_exports.discriminatedUnion("type", [
15337
+ external_exports.object({
15338
+ id: external_exports.string().min(1),
15339
+ type: external_exports.literal("choice"),
15340
+ prompt: external_exports.string(),
15341
+ options: external_exports.array(external_exports.object({
15342
+ value: external_exports.string().min(1),
15343
+ label: external_exports.string(),
15344
+ description: external_exports.string().optional()
15345
+ })).min(1),
15346
+ multiple: external_exports.boolean(),
15347
+ allowOther: external_exports.boolean(),
15348
+ optional: external_exports.boolean()
15349
+ }),
15350
+ external_exports.object({
15351
+ id: external_exports.string().min(1),
15352
+ type: external_exports.literal("text"),
15353
+ prompt: external_exports.string(),
15354
+ multiline: external_exports.boolean(),
15355
+ secret: external_exports.literal(false),
15356
+ optional: external_exports.boolean(),
15357
+ placeholder: external_exports.string().optional(),
15358
+ prefill: external_exports.string().optional()
15359
+ })
15360
+ ]);
15361
+ var threadQuestionSchema = external_exports.object({
15362
+ interactionId: external_exports.string().min(1),
15363
+ turnId: external_exports.string().min(1),
15364
+ title: external_exports.string().optional(),
15365
+ questions: external_exports.array(field).min(1)
15366
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
15367
+ message: "Shared cards require at least one multi-select question"
15368
+ });
15369
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
15370
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
15371
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
15372
+ threadId: external_exports.string().min(1),
15373
+ turnId: external_exports.string().min(1),
15374
+ interactionId: external_exports.string().min(1),
15375
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
15376
+ cancelled: external_exports.boolean().default(false)
15377
+ });
15378
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
15379
+
15333
15380
  // ../../shared-contracts/dist/harness-plugins.js
15334
15381
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15335
15382
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -15511,7 +15558,7 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
15511
15558
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15512
15559
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15513
15560
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15514
- var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text2) => text2.length <= maximum));
15561
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text4) => text4.length <= maximum));
15515
15562
  var composerIndicatorsSchema = external_exports.array(external_exports.object({
15516
15563
  kind: external_exports.literal("countdown"),
15517
15564
  id: external_exports.string().min(1).max(64),
@@ -16089,6 +16136,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
16089
16136
  /** The text about to be steered; a Harness command always stops and restarts. */
16090
16137
  text: external_exports.string().optional()
16091
16138
  }).strict();
16139
+ var threadSteeringContextSchema = external_exports.object({
16140
+ kind: external_exports.literal("application"),
16141
+ value: external_exports.string().transform((text4, context) => {
16142
+ try {
16143
+ return JSON.parse(text4);
16144
+ } catch {
16145
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
16146
+ return external_exports.NEVER;
16147
+ }
16148
+ }).pipe(external_exports.object({
16149
+ expectedTurnId: hostTurnIdSchema,
16150
+ clientUserMessageId: external_exports.string().min(1),
16151
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
16152
+ }).strict())
16153
+ }).strict().transform((context) => context.value);
16092
16154
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
16093
16155
  var threadSteeringInspectResultSchema = external_exports.object({
16094
16156
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -16099,7 +16161,10 @@ var harnessPluginRouteSchema = external_exports.object({
16099
16161
  harnessId: harnessPluginIdSchema,
16100
16162
  model: harnessModelRefSchema.optional(),
16101
16163
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
16102
- permissionModeId: harnessPermissionModeIdSchema.optional()
16164
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
16165
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
16166
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
16167
+ prewarm: external_exports.literal(true).optional()
16103
16168
  }).strict();
16104
16169
 
16105
16170
  // ../../shared-contracts/dist/harness-launch-settings.js
@@ -16716,8 +16781,8 @@ async function readCandidate(file2, signal) {
16716
16781
  const message3 = isRecord(entry.message) ? entry.message : null;
16717
16782
  if (!firstMessage && entry.type === "message" && message3?.role === "user") {
16718
16783
  const content = message3.content;
16719
- const text2 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
16720
- firstMessage = sessionImportTitle(text2);
16784
+ const text4 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
16785
+ firstMessage = sessionImportTitle(text4);
16721
16786
  }
16722
16787
  hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
16723
16788
  entries.set(entry.id, hasUser);
@@ -17010,26 +17075,26 @@ function parseHostUsage(value) {
17010
17075
  }
17011
17076
  }
17012
17077
  const indicators = value.composerIndicators === void 0 ? {} : { composerIndicators: composerIndicatorsSchema.parse(value.composerIndicators) };
17013
- for (const field of [
17078
+ for (const field2 of [
17014
17079
  "totalCredits",
17015
17080
  "contextUsagePercent",
17016
17081
  "apiOutputTokensPerSecond"
17017
17082
  ]) {
17018
- const candidate = value[field];
17083
+ const candidate = value[field2];
17019
17084
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17020
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
17085
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17021
17086
  }
17022
17087
  }
17023
- for (const field of tokenFields) {
17024
- const candidate = value[field];
17088
+ for (const field2 of tokenFields) {
17089
+ const candidate = value[field2];
17025
17090
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17026
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
17091
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17027
17092
  }
17028
17093
  }
17029
- for (const field of safeIntegerFields) {
17030
- const candidate = value[field];
17094
+ for (const field2 of safeIntegerFields) {
17095
+ const candidate = value[field2];
17031
17096
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17032
- throw new Error(`Harness Usage '${field}' must be a non-negative safe integer`);
17097
+ throw new Error(`Harness Usage '${field2}' must be a non-negative safe integer`);
17033
17098
  }
17034
17099
  }
17035
17100
  if (value.outputTokensPerSecond !== void 0 && (typeof value.outputTokensPerSecond !== "number" || !Number.isFinite(value.outputTokensPerSecond) || value.outputTokensPerSecond < 0)) {
@@ -17038,16 +17103,16 @@ function parseHostUsage(value) {
17038
17103
  if (value.totalCostUsd !== void 0 && (typeof value.totalCostUsd !== "number" || !Number.isFinite(value.totalCostUsd) || value.totalCostUsd < 0)) {
17039
17104
  throw new Error("Harness Usage 'totalCostUsd' must be a finite non-negative number");
17040
17105
  }
17041
- for (const field of ["totalCredits", "contextUsagePercent"]) {
17042
- const candidate = value[field];
17106
+ for (const field2 of ["totalCredits", "contextUsagePercent"]) {
17107
+ const candidate = value[field2];
17043
17108
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
17044
- throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
17109
+ throw new Error(`Harness Usage '${field2}' must be a finite non-negative number`);
17045
17110
  }
17046
17111
  }
17047
- for (const field of percentFields) {
17048
- const candidate = value[field];
17112
+ for (const field2 of percentFields) {
17113
+ const candidate = value[field2];
17049
17114
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0 || candidate > 100)) {
17050
- throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
17115
+ throw new Error(`Harness Usage '${field2}' must be between 0 and 100`);
17051
17116
  }
17052
17117
  }
17053
17118
  if (value.sessionCacheUsage !== void 0) {
@@ -17118,19 +17183,19 @@ function parseHostUsageRequest(value) {
17118
17183
  if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17119
17184
  throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17120
17185
  }
17121
- for (const field of ["model", "provider"]) {
17122
- const candidate = value[field];
17186
+ for (const field2 of ["model", "provider"]) {
17187
+ const candidate = value[field2];
17123
17188
  if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17124
- throw new Error(`Harness Usage request '${field}' must be a non-empty string`);
17189
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
17125
17190
  }
17126
17191
  }
17127
17192
  if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17128
17193
  throw new Error("Harness Usage request 'historical' must be a boolean");
17129
17194
  }
17130
- for (const field of requestTokenFields) {
17131
- const candidate = value[field];
17195
+ for (const field2 of requestTokenFields) {
17196
+ const candidate = value[field2];
17132
17197
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17133
- throw new Error(`Harness Usage request '${field}' must be a non-negative safe integer`);
17198
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
17134
17199
  }
17135
17200
  }
17136
17201
  if (value.inputTokens === void 0 || value.outputTokens === void 0) {
@@ -17236,8 +17301,8 @@ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17236
17301
  const descriptor = catalog.commands.find(({ id }) => id === commandId);
17237
17302
  if (!descriptor)
17238
17303
  return null;
17239
- const text2 = typeof argumentText === "string" ? argumentText.trim() : "";
17240
- return text2 ? `${descriptor.invocation} ${text2}` : descriptor.invocation;
17304
+ const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
17305
+ return text4 ? `${descriptor.invocation} ${text4}` : descriptor.invocation;
17241
17306
  }
17242
17307
  function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17243
17308
  if (!live)
@@ -17373,16 +17438,16 @@ var Diff = class {
17373
17438
  }
17374
17439
  }
17375
17440
  }
17376
- addToPath(path16, added, removed, oldPosInc, options) {
17377
- const last = path16.lastComponent;
17441
+ addToPath(path18, added, removed, oldPosInc, options) {
17442
+ const last = path18.lastComponent;
17378
17443
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17379
17444
  return {
17380
- oldPos: path16.oldPos + oldPosInc,
17445
+ oldPos: path18.oldPos + oldPosInc,
17381
17446
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17382
17447
  };
17383
17448
  } else {
17384
17449
  return {
17385
- oldPos: path16.oldPos + oldPosInc,
17450
+ oldPos: path18.oldPos + oldPosInc,
17386
17451
  lastComponent: { count: 1, added, removed, previousComponent: last }
17387
17452
  };
17388
17453
  }
@@ -17782,9 +17847,9 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader
17782
17847
  } }));
17783
17848
  }
17784
17849
  }
17785
- function splitLines(text2) {
17786
- const hasTrailingNl = text2.endsWith("\n");
17787
- const result = text2.split("\n").map((line) => line + "\n");
17850
+ function splitLines(text4) {
17851
+ const hasTrailingNl = text4.endsWith("\n");
17852
+ const result = text4.split("\n").map((line) => line + "\n");
17788
17853
  if (hasTrailingNl) {
17789
17854
  result.pop();
17790
17855
  } else {
@@ -17857,9 +17922,9 @@ function nestedToolString(value, keys, allowEmpty = false) {
17857
17922
  if (!isRecord3(value))
17858
17923
  return void 0;
17859
17924
  for (const key of keys) {
17860
- const field = value[key];
17861
- if (typeof field === "string" && (allowEmpty || field.length > 0))
17862
- return field;
17925
+ const field2 = value[key];
17926
+ if (typeof field2 === "string" && (allowEmpty || field2.length > 0))
17927
+ return field2;
17863
17928
  }
17864
17929
  for (const wrapper of ["input", "arguments", "params", "details"]) {
17865
17930
  const nested = nestedToolString(value[wrapper], keys, allowEmpty);
@@ -17872,15 +17937,15 @@ function patchFromResult(result) {
17872
17937
  if (!isRecord3(result))
17873
17938
  return void 0;
17874
17939
  for (const key of ["patch", "diff", "unifiedDiff"]) {
17875
- const field = result[key];
17876
- if (typeof field === "string" && field.length > 0)
17877
- return field;
17940
+ const field2 = result[key];
17941
+ if (typeof field2 === "string" && field2.length > 0)
17942
+ return field2;
17878
17943
  }
17879
17944
  if (isRecord3(result.details)) {
17880
17945
  for (const key of ["patch", "diff", "unifiedDiff"]) {
17881
- const field = result.details[key];
17882
- if (typeof field === "string" && field.length > 0)
17883
- return field;
17946
+ const field2 = result.details[key];
17947
+ if (typeof field2 === "string" && field2.length > 0)
17948
+ return field2;
17884
17949
  }
17885
17950
  }
17886
17951
  return void 0;
@@ -18018,11 +18083,344 @@ function piNestedCallFileChanges(nestedCalls, cwd) {
18018
18083
  return projected;
18019
18084
  }
18020
18085
 
18021
- // dist/pi-subagents.js
18086
+ // dist/pi-message-item-id.js
18022
18087
  import { createHash } from "node:crypto";
18088
+ function piMessageIdentity(sessionId, message3, timestampCounts) {
18089
+ if (typeof message3 !== "object" || message3 === null || !("role" in message3) || message3.role !== "assistant")
18090
+ return void 0;
18091
+ if ("timestamp" in message3 && typeof message3.timestamp === "number" && Number.isSafeInteger(message3.timestamp) && message3.timestamp >= 0) {
18092
+ const occurrence = timestampCounts.get(message3.timestamp) ?? 0;
18093
+ timestampCounts.set(message3.timestamp, occurrence + 1);
18094
+ return { sessionId, timestamp: message3.timestamp, occurrence };
18095
+ }
18096
+ if ("responseId" in message3 && typeof message3.responseId === "string" && message3.responseId.trim().length > 0)
18097
+ return { responseId: message3.responseId };
18098
+ return void 0;
18099
+ }
18100
+ function piHistoryMessageIdentities(sessionId, entries) {
18101
+ const timestampCounts = /* @__PURE__ */ new Map();
18102
+ const identities = /* @__PURE__ */ new Map();
18103
+ for (const entry of entries) {
18104
+ const identity = piMessageIdentity(sessionId, entry.message, timestampCounts);
18105
+ if (identity)
18106
+ identities.set(entry.id, identity);
18107
+ }
18108
+ return { identities, timestampCounts };
18109
+ }
18110
+ function piMessageItemId(identity, kind) {
18111
+ if (!identity)
18112
+ return null;
18113
+ const timestampIdentity = "timestamp" in identity;
18114
+ const value = timestampIdentity ? JSON.stringify([identity.sessionId, identity.timestamp, identity.occurrence]) : identity.responseId;
18115
+ const digest = createHash("sha256").update(value).digest("hex");
18116
+ return hostItemIdSchema.parse(`pi-${timestampIdentity ? "message" : "response"}-v1-${digest}-${kind}`);
18117
+ }
18118
+
18119
+ // dist/pi-assistant-outcome.js
18120
+ function piAssistantWasAborted(value) {
18121
+ if (typeof value !== "object" || value === null || Array.isArray(value))
18122
+ return false;
18123
+ const message3 = value;
18124
+ return message3.role === "assistant" && (message3.stopReason === "aborted" || message3.stopReason === "error" && message3.errorMessage === "This operation was aborted");
18125
+ }
18126
+ function piAssistantPhase(value) {
18127
+ if (typeof value !== "object" || value === null || Array.isArray(value))
18128
+ return void 0;
18129
+ const message3 = value;
18130
+ if (message3.role !== "assistant")
18131
+ return void 0;
18132
+ const lastText = Array.isArray(message3.content) ? message3.content.findLast((part) => typeof part === "object" && part !== null && !Array.isArray(part) && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" && part.text.trim().length > 0) : void 0;
18133
+ if (!lastText && !(typeof message3.content === "string" && message3.content.trim()))
18134
+ return void 0;
18135
+ if (typeof lastText?.textSignature === "string") {
18136
+ try {
18137
+ const signature = JSON.parse(lastText.textSignature);
18138
+ if (typeof signature === "object" && signature !== null && !Array.isArray(signature) && "v" in signature && signature.v === 1 && "id" in signature && typeof signature.id === "string" && "phase" in signature && (signature.phase === "commentary" || signature.phase === "final_answer"))
18139
+ return signature.phase;
18140
+ } catch {
18141
+ }
18142
+ }
18143
+ if (message3.stopReason === "toolUse")
18144
+ return "commentary";
18145
+ if (message3.stopReason === "stop")
18146
+ return "final_answer";
18147
+ return void 0;
18148
+ }
18149
+
18150
+ // dist/pi-subagents.js
18151
+ import { createHash as createHash3 } from "node:crypto";
18152
+
18153
+ // dist/pi-gotgenes-extension.js
18154
+ import { createHash as createHash2, randomUUID } from "node:crypto";
18155
+ import { mkdir, readFile, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
18156
+ import { homedir as homedir2 } from "node:os";
18157
+ import path7 from "node:path";
18158
+ var GOTGENES_WIDGET = "codexhost-gotgenes-subagents";
18159
+ var GOTGENES_PREFIX = "CODEXHOST_GOTGENES_SUBAGENTS_V1:";
18160
+ var GOTGENES_EXTENSION = `export default function(pi) {
18161
+ let ctx, timer, service, previous = "";
18162
+ const publish = () => {
18163
+ if (!ctx) return;
18164
+ // Child SDK sessions can publish their own process-global service. Bind this parent once.
18165
+ if (!service) {
18166
+ const candidate = globalThis[Symbol.for("@gotgenes/pi-subagents:service")];
18167
+ if (typeof candidate?.listAgents !== "function") return;
18168
+ service = candidate;
18169
+ }
18170
+ const agents = service.listAgents().slice(0, 128).map((r) => ({
18171
+ id: r.id, type: r.type, description: r.description?.slice(0, 2048),
18172
+ status: r.status, isBackground: r.isBackground, outputFile: r.outputFile,
18173
+ toolUses: r.toolUses, startedAt: r.startedAt, completedAt: r.completedAt,
18174
+ result: r.result?.slice(0, 2048), error: r.error?.slice(0, 2048),
18175
+ turnBudget: r.turnBudget, lifetimeUsage: r.lifetimeUsage,
18176
+ }));
18177
+ const payload = JSON.stringify({version: 1, agents});
18178
+ if (payload === previous) return;
18179
+ previous = payload;
18180
+ ctx.ui.setWidget("${GOTGENES_WIDGET}", ["${GOTGENES_PREFIX}" + payload]);
18181
+ };
18182
+ const schedule = () => queueMicrotask(publish);
18183
+ for (const name of ["created", "started", "completed", "failed", "resuming", "resumed", "compacted", "steered", "update"]) {
18184
+ pi.events.on("subagents:" + name, schedule);
18185
+ }
18186
+ pi.on("session_start", (_event, context) => {
18187
+ // A session switch keeps this extension's manager/service; only reload creates a new instance.
18188
+ ctx = context; previous = ""; clearInterval(timer);
18189
+ schedule();
18190
+ // The public service publishes outputFile only after queued session creation and has no progress event.
18191
+ timer = setInterval(publish, 1000);
18192
+ timer.unref?.();
18193
+ });
18194
+ pi.on("session_shutdown", () => { clearInterval(timer); timer = undefined; ctx = undefined; service = undefined; });
18195
+ }
18196
+ `;
18197
+ async function ensureGotgenesExtension(environment) {
18198
+ const digest = createHash2("sha256").update(GOTGENES_EXTENSION).digest("hex").slice(0, 16);
18199
+ const root = environment.CODEXHOST_DATA_DIR ?? path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".codexhost");
18200
+ const directory = path7.resolve(root, "extensions", "pi-subagent-observer");
18201
+ const file2 = path7.join(directory, `${digest}.mjs`);
18202
+ if (await readFile(file2, "utf8").catch(() => "") === GOTGENES_EXTENSION)
18203
+ return file2;
18204
+ await mkdir(directory, { recursive: true });
18205
+ const temporary = `${file2}.${randomUUID()}.tmp`;
18206
+ try {
18207
+ await writeFile2(temporary, GOTGENES_EXTENSION, { mode: 384 });
18208
+ try {
18209
+ await rename(temporary, file2);
18210
+ } catch (error51) {
18211
+ if (await readFile(file2, "utf8").catch(() => "") !== GOTGENES_EXTENSION)
18212
+ throw error51;
18213
+ }
18214
+ } finally {
18215
+ await rm2(temporary, { force: true });
18216
+ }
18217
+ return file2;
18218
+ }
18219
+
18220
+ // dist/pi-gotgenes-subagents.js
18221
+ var PREFIX = "pi-gotgenes-v1:";
18222
+ var STATUSES = {
18223
+ queued: "pending",
18224
+ running: "running",
18225
+ background: "pending",
18226
+ completed: "completed",
18227
+ aborted: "interrupted",
18228
+ stopped: "interrupted",
18229
+ error: "failed"
18230
+ };
18231
+ function isRecord4(value) {
18232
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18233
+ }
18234
+ function text(value, limit = 2048) {
18235
+ return typeof value === "string" && value.length > 0 && value.length <= limit;
18236
+ }
18237
+ function gotgenesId(id) {
18238
+ return PREFIX + Buffer.from(id).toString("base64url");
18239
+ }
18240
+ function parseGotgenesId(value) {
18241
+ if (!value.startsWith(PREFIX))
18242
+ return null;
18243
+ const id = Buffer.from(value.slice(PREFIX.length), "base64url").toString("utf8");
18244
+ if (!text(id, 256) || /[\s/\\]/u.test(id) || gotgenesId(id) !== value)
18245
+ throw new Error("Invalid gotgenes subagent identity");
18246
+ return id;
18247
+ }
18248
+ function gotgenesRecord(value) {
18249
+ if (!isRecord4(value) || !text(value.id, 256) || /[\s/\\]/u.test(value.id) || !text(value.type) || !text(value.description) || typeof value.status !== "string" || !Object.hasOwn(STATUSES, value.status))
18250
+ return null;
18251
+ const status = STATUSES[value.status];
18252
+ if (!status)
18253
+ return null;
18254
+ const id = gotgenesId(value.id);
18255
+ const progress = typeof value.toolUses === "number" ? `${value.toolUses} tool uses` : void 0;
18256
+ const result = typeof value.error === "string" ? value.error : typeof value.result === "string" ? value.result : progress;
18257
+ return {
18258
+ id: value.id,
18259
+ roleKnown: value.roleKnown !== false,
18260
+ backgroundKnown: typeof value.isBackground === "boolean",
18261
+ child: {
18262
+ subagentId: id,
18263
+ nativeSubagentId: id,
18264
+ description: value.description,
18265
+ role: value.type,
18266
+ status,
18267
+ background: value.isBackground === true,
18268
+ ...text(value.modelName) ? { model: value.modelName } : {},
18269
+ ...result ? { resultSummary: result.slice(0, 2048) } : {}
18270
+ },
18271
+ ...text(value.outputFile, 8192) ? { outputFile: value.outputFile } : {},
18272
+ revision: JSON.stringify([
18273
+ value.toolUses,
18274
+ value.turnBudget,
18275
+ value.lifetimeUsage,
18276
+ value.outputFile
18277
+ ])
18278
+ };
18279
+ }
18280
+ function gotgenesToolRecord(toolName, result) {
18281
+ if (!["subagent", "get_subagent_result"].includes(toolName) || !isRecord4(result) || !isRecord4(result.details))
18282
+ return null;
18283
+ const d = result.details;
18284
+ if (!text(d.agentId, 256) || !text(d.displayName) || !text(d.description))
18285
+ return null;
18286
+ return gotgenesRecord({
18287
+ ...d,
18288
+ id: d.agentId,
18289
+ type: d.subagentType ?? d.displayName,
18290
+ roleKnown: text(d.subagentType),
18291
+ isBackground: toolName === "subagent" ? d.status === "background" || Array.isArray(d.tags) && d.tags.includes("background") : void 0,
18292
+ outputFile: d.transcriptPath,
18293
+ result: d.preview
18294
+ });
18295
+ }
18296
+ function parseGotgenesWidget(value) {
18297
+ if (!isRecord4(value) || value.type !== "extension_ui_request" || value.method !== "setWidget" || value.widgetKey !== GOTGENES_WIDGET || !Array.isArray(value.widgetLines))
18298
+ return null;
18299
+ const line = value.widgetLines.find((x) => typeof x === "string" && x.startsWith(GOTGENES_PREFIX));
18300
+ if (!line || Buffer.byteLength(line) > 1024 * 1024)
18301
+ return null;
18302
+ try {
18303
+ const payload = JSON.parse(line.slice(GOTGENES_PREFIX.length));
18304
+ if (!isRecord4(payload) || payload.version !== 1 || !Array.isArray(payload.agents) || payload.agents.length > 128)
18305
+ return null;
18306
+ const records = payload.agents.map(gotgenesRecord);
18307
+ return records.every((r) => r !== null) ? records : null;
18308
+ } catch {
18309
+ return null;
18310
+ }
18311
+ }
18312
+ function mergeGotgenesRecord(previous, record9) {
18313
+ const model2 = record9.child.model ?? previous?.child.model;
18314
+ const role = record9.roleKnown ? record9.child.role : previous?.child.role ?? record9.child.role;
18315
+ return {
18316
+ ...previous,
18317
+ ...record9,
18318
+ roleKnown: record9.roleKnown || previous?.roleKnown === true,
18319
+ backgroundKnown: record9.backgroundKnown || previous?.backgroundKnown === true,
18320
+ outputFile: record9.outputFile ?? previous?.outputFile,
18321
+ child: {
18322
+ ...previous?.child,
18323
+ ...record9.child,
18324
+ ...model2 ? { model: model2 } : {},
18325
+ ...role ? { role } : {},
18326
+ background: record9.backgroundKnown ? record9.child.background : previous?.child.background ?? record9.child.background
18327
+ }
18328
+ };
18329
+ }
18330
+ var GotgenesSubagents = class {
18331
+ emit;
18332
+ records = /* @__PURE__ */ new Map();
18333
+ #nativeObserved = /* @__PURE__ */ new Set();
18334
+ #active = /* @__PURE__ */ new Map();
18335
+ constructor(emit) {
18336
+ this.emit = emit;
18337
+ }
18338
+ observe(records, publish = true, activeTurn, nativeObservation = false) {
18339
+ for (const record9 of records) {
18340
+ if (!publish && this.#nativeObserved.has(record9.id))
18341
+ continue;
18342
+ if (nativeObservation)
18343
+ this.#nativeObserved.add(record9.id);
18344
+ const previous = this.records.get(record9.id);
18345
+ const merged = mergeGotgenesRecord(previous, record9);
18346
+ this.records.set(record9.id, merged);
18347
+ if (publish && !previous && activeTurn && !this.#active.has(record9.id)) {
18348
+ const item = {
18349
+ type: "subagentDelegation",
18350
+ itemId: activeTurn.nextItemId(),
18351
+ operation: "spawn",
18352
+ subagents: [merged.child]
18353
+ };
18354
+ this.#active.set(record9.id, { turnId: activeTurn.turnId, item });
18355
+ this.emit({ type: "item.started", turnId: activeTurn.turnId, item });
18356
+ }
18357
+ if (!publish || JSON.stringify(previous) === JSON.stringify(merged))
18358
+ continue;
18359
+ const active = this.#active.get(record9.id);
18360
+ if (active) {
18361
+ active.item = { ...active.item, subagents: [merged.child] };
18362
+ this.emit({
18363
+ type: "item.updated",
18364
+ turnId: active.turnId,
18365
+ itemId: active.item.itemId,
18366
+ update: { type: "subagents.replace", subagents: [merged.child] }
18367
+ });
18368
+ }
18369
+ this.emit({
18370
+ type: "subagent.state.changed",
18371
+ nativeSubagentId: merged.child.subagentId,
18372
+ status: merged.child.status
18373
+ });
18374
+ this.emit({ type: "subagent.transcript.changed", nativeSubagentId: merged.child.subagentId });
18375
+ }
18376
+ }
18377
+ project(toolName, result, itemId2) {
18378
+ const parsed = gotgenesToolRecord(toolName, result);
18379
+ if (!parsed || toolName !== "subagent")
18380
+ return null;
18381
+ const child = this.records.get(parsed.id)?.child ?? parsed.child;
18382
+ return { type: "subagentDelegation", itemId: itemId2, operation: "spawn", subagents: [child] };
18383
+ }
18384
+ start(turnId, toolName, result, itemId2) {
18385
+ const parsed = gotgenesToolRecord(toolName, result);
18386
+ if (!parsed)
18387
+ return false;
18388
+ const prior = this.records.get(parsed.id);
18389
+ if (!prior || !this.#nativeObserved.has(parsed.id))
18390
+ this.observe([parsed]);
18391
+ else {
18392
+ this.observe([
18393
+ {
18394
+ ...prior,
18395
+ child: { ...prior.child, ...parsed.child.model ? { model: parsed.child.model } : {} }
18396
+ }
18397
+ ]);
18398
+ }
18399
+ if (toolName === "subagent" && !this.#active.has(parsed.id)) {
18400
+ const item = this.project(toolName, result, itemId2);
18401
+ if (!item)
18402
+ return false;
18403
+ this.#active.set(parsed.id, { turnId, item });
18404
+ this.emit({ type: "item.started", turnId, item });
18405
+ }
18406
+ return true;
18407
+ }
18408
+ finish(turnId) {
18409
+ for (const [id, active] of this.#active) {
18410
+ if (active.turnId !== turnId)
18411
+ continue;
18412
+ this.#active.delete(id);
18413
+ this.emit({
18414
+ type: "item.completed",
18415
+ turnId,
18416
+ snapshot: { item: active.item, outcome: { status: "succeeded" } }
18417
+ });
18418
+ }
18419
+ }
18420
+ };
18023
18421
 
18024
18422
  // dist/pi-subagent-workflow.js
18025
- var PREFIX = "pi-subagents-workflow-v1:";
18423
+ var PREFIX2 = "pi-subagents-workflow-v1:";
18026
18424
  var STATES = {
18027
18425
  pending: "pending",
18028
18426
  running: "running",
@@ -18036,7 +18434,7 @@ var STATES = {
18036
18434
  function record2(value) {
18037
18435
  return typeof value === "object" && value !== null && !Array.isArray(value);
18038
18436
  }
18039
- function text(value, limit = 256) {
18437
+ function text2(value, limit = 256) {
18040
18438
  return typeof value === "string" && value.length > 0 && value.length <= limit;
18041
18439
  }
18042
18440
  function piWorkflowSummary(result) {
@@ -18044,15 +18442,15 @@ function piWorkflowSummary(result) {
18044
18442
  return null;
18045
18443
  const details = result.details;
18046
18444
  const summary = details.workflowChildren;
18047
- if (!record2(summary) || summary.version !== 1 || !text(summary.workflowRunId) || summary.workflowRunId !== details.runId || !text(summary.parentToolCallId) || typeof summary.inventoryComplete !== "boolean" || !Array.isArray(summary.children) || summary.children.length > 256)
18445
+ if (!record2(summary) || summary.version !== 1 || !text2(summary.workflowRunId) || summary.workflowRunId !== details.runId || !text2(summary.parentToolCallId) || typeof summary.inventoryComplete !== "boolean" || !Array.isArray(summary.children) || summary.children.length > 256)
18048
18446
  return null;
18049
18447
  const children = [];
18050
18448
  const seen = /* @__PURE__ */ new Set();
18051
18449
  for (const child of summary.children) {
18052
- if (!record2(child) || !text(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
18450
+ if (!record2(child) || !text2(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
18053
18451
  return null;
18054
18452
  for (const key of ["agent", "sessionName", "model", "thinking"]) {
18055
- if (child[key] !== void 0 && !text(child[key], 2048))
18453
+ if (child[key] !== void 0 && !text2(child[key], 2048))
18056
18454
  return null;
18057
18455
  }
18058
18456
  const mappedState = STATES[child.state];
@@ -18076,15 +18474,15 @@ function piWorkflowSummary(result) {
18076
18474
  };
18077
18475
  }
18078
18476
  function piWorkflowSubagentId(address) {
18079
- return PREFIX + Buffer.from(JSON.stringify([address.workflowRunId, address.childId])).toString("base64url");
18477
+ return PREFIX2 + Buffer.from(JSON.stringify([address.workflowRunId, address.childId])).toString("base64url");
18080
18478
  }
18081
18479
  function parsePiWorkflowSubagentId(id) {
18082
- if (!id.startsWith(PREFIX))
18480
+ if (!id.startsWith(PREFIX2))
18083
18481
  return null;
18084
18482
  if (id.length > 3e3)
18085
18483
  throw new Error("Invalid Pi workflow child identity");
18086
- const value = JSON.parse(Buffer.from(id.slice(PREFIX.length), "base64url").toString("utf8"));
18087
- if (!Array.isArray(value) || value.length !== 2 || !text(value[0]) || !text(value[1]))
18484
+ const value = JSON.parse(Buffer.from(id.slice(PREFIX2.length), "base64url").toString("utf8"));
18485
+ if (!Array.isArray(value) || value.length !== 2 || !text2(value[0]) || !text2(value[1]))
18088
18486
  throw new Error("Invalid Pi workflow child identity");
18089
18487
  const address = { workflowRunId: value[0], childId: value[1] };
18090
18488
  if (piWorkflowSubagentId(address) !== id)
@@ -18242,8 +18640,13 @@ var PiSubagents = class {
18242
18640
  #children = /* @__PURE__ */ new Map();
18243
18641
  #active = /* @__PURE__ */ new Map();
18244
18642
  #waiting = /* @__PURE__ */ new Map();
18643
+ gotgenes;
18245
18644
  constructor(emit) {
18246
18645
  this.emit = emit;
18646
+ this.gotgenes = new GotgenesSubagents(emit);
18647
+ }
18648
+ observeGotgenes(records, activeTurn) {
18649
+ this.gotgenes.observe(records, true, activeTurn, true);
18247
18650
  }
18248
18651
  observe(runs) {
18249
18652
  this.#apply(runs, true);
@@ -18297,6 +18700,9 @@ var PiSubagents = class {
18297
18700
  }
18298
18701
  }
18299
18702
  project(toolName, result, itemId2, callId) {
18703
+ const gotgenes = this.gotgenes.project(toolName, result, itemId2);
18704
+ if (gotgenes)
18705
+ return gotgenes;
18300
18706
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18301
18707
  if (workflow && (!callId || workflow.parentToolCallId === callId))
18302
18708
  return projectPiWorkflow(workflow, itemId2);
@@ -18307,6 +18713,8 @@ var PiSubagents = class {
18307
18713
  return children.length ? { type: "subagentDelegation", itemId: itemId2, operation: "spawn", subagents: children } : null;
18308
18714
  }
18309
18715
  start(turnId, toolName, result, itemId2, callId) {
18716
+ if (this.gotgenes.start(turnId, toolName, result, itemId2))
18717
+ return;
18310
18718
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18311
18719
  if (workflow && (!callId || workflow.parentToolCallId === callId)) {
18312
18720
  const key = `workflow:${workflow.workflowRunId}`;
@@ -18352,6 +18760,7 @@ var PiSubagents = class {
18352
18760
  this.emit({ type: "item.started", turnId, item });
18353
18761
  }
18354
18762
  finish(turnId) {
18763
+ this.gotgenes.finish(turnId);
18355
18764
  for (const [runId, waiting] of this.#waiting) {
18356
18765
  if (waiting.turnId === turnId)
18357
18766
  this.#waiting.delete(runId);
@@ -18374,8 +18783,8 @@ function parsePiSubagentInspection(value) {
18374
18783
  return null;
18375
18784
  if (parsed.error !== void 0 && (!record3(parsed.error) || typeof parsed.error.code !== "string" || typeof parsed.error.message !== "string"))
18376
18785
  return null;
18377
- for (const field of ["asyncId", "childId", "status", "task", "finalOutput"]) {
18378
- if (parsed[field] !== void 0 && typeof parsed[field] !== "string")
18786
+ for (const field2 of ["asyncId", "childId", "status", "task", "finalOutput"]) {
18787
+ if (parsed[field2] !== void 0 && typeof parsed[field2] !== "string")
18379
18788
  return null;
18380
18789
  }
18381
18790
  if (parsed.messages !== void 0 && (!Array.isArray(parsed.messages) || parsed.messages.length > 200 || parsed.messages.some((entry) => !record3(entry) || typeof entry.role !== "string" || typeof entry.text !== "string" || !["text", "toolCall", "toolResult"].includes(String(entry.kind)) || entry.name !== void 0 && typeof entry.name !== "string")))
@@ -18399,15 +18808,15 @@ ${entry.text}`);
18399
18808
  nativeTurnRef: nativeTurnRefSchema.parse({
18400
18809
  harnessId: "pi",
18401
18810
  nativeSessionId: parentSessionId,
18402
- nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
18811
+ nativeTurnKey: `pi-subagent-${createHash3("sha256").update(id).digest("hex")}`,
18403
18812
  formatVersion: 1
18404
18813
  }),
18405
18814
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
18406
- items: texts.map((text2, index) => ({
18815
+ items: texts.map((text4, index) => ({
18407
18816
  item: {
18408
18817
  type: "agentMessage",
18409
- text: text2,
18410
- itemId: hostItemIdSchema.parse(`pi-subagent-${createHash("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
18818
+ text: text4,
18819
+ itemId: hostItemIdSchema.parse(`pi-subagent-${createHash3("sha256").update(`${id}:${index}:${text4}`).digest("hex")}`)
18411
18820
  },
18412
18821
  outcome: { status: "succeeded" }
18413
18822
  })),
@@ -18500,7 +18909,7 @@ function normalizePiThinkingOptions(levels) {
18500
18909
  label: PI_THINKING_LABELS[id] ?? fallbackThinkingLabel(id)
18501
18910
  }));
18502
18911
  }
18503
- function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId) {
18912
+ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, effectiveThinkingOptionId, effectiveModelReasoning = null) {
18504
18913
  const byRef = /* @__PURE__ */ new Map();
18505
18914
  for (const native of nativeModels) {
18506
18915
  const ref = encodePiModelRef(native);
@@ -18516,12 +18925,21 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
18516
18925
  ref,
18517
18926
  label: `${native.provider} / ${native.id}`
18518
18927
  },
18519
- reasoning: native.reasoning
18928
+ reasoning: native.reasoning,
18929
+ synthesized: false
18520
18930
  });
18521
18931
  }
18522
18932
  const defaultModel = effectiveModel ? encodePiModelRef(effectiveModel) : void 0;
18523
- if (defaultModel && !byRef.has(defaultModel.id)) {
18524
- throw new Error("Pi effective Model is absent from the available Model catalog");
18933
+ if (effectiveModel && defaultModel && !byRef.has(defaultModel.id)) {
18934
+ const reasoning = effectiveThinkingOptionId && effectiveThinkingOptionId !== "off" || (effectiveModelReasoning ?? Boolean(thinkingLevels && thinkingLevels.some((level) => level !== "off")));
18935
+ byRef.set(defaultModel.id, {
18936
+ model: {
18937
+ ref: defaultModel,
18938
+ label: `${effectiveModel.provider} / ${effectiveModel.id}`
18939
+ },
18940
+ reasoning,
18941
+ synthesized: true
18942
+ });
18525
18943
  }
18526
18944
  if (thinkingLevels && effectiveThinkingOptionId && !thinkingLevels.includes(effectiveThinkingOptionId)) {
18527
18945
  throw new Error("Pi effective Thinking option is absent from the available option catalog");
@@ -18532,9 +18950,10 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
18532
18950
  const thinkingOptions = thinkingLevels ? normalizePiThinkingOptions(PI_DRAFT_THINKING_OPTION_IDS) : [];
18533
18951
  const allThinkingOptionIds = thinkingOptions.map(({ id }) => id);
18534
18952
  const offThinkingOptionId = thinkingOptions.find(({ id }) => id === "off")?.id;
18535
- const models = [...byRef.values()].map(({ model: model2, reasoning }) => ({
18953
+ const effectiveThinkingOptionIds = thinkingLevels ? allThinkingOptionIds.filter((id) => thinkingLevels.includes(id)) : allThinkingOptionIds;
18954
+ const models = [...byRef.values()].map(({ model: model2, reasoning, synthesized }) => ({
18536
18955
  ...model2,
18537
- supportedThinkingOptionIds: reasoning ? allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
18956
+ supportedThinkingOptionIds: reasoning ? synthesized ? effectiveThinkingOptionIds : allThinkingOptionIds : offThinkingOptionId ? [offThinkingOptionId] : []
18538
18957
  })).sort((left, right) => compareText(left.label, right.label) || compareText(left.ref.id, right.ref.id));
18539
18958
  const defaultThinkingOptionId = thinkingOptions.find(({ id }) => id === effectiveThinkingOptionId)?.id;
18540
18959
  return harnessModelCatalogSchema.parse({
@@ -18545,22 +18964,149 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
18545
18964
  });
18546
18965
  }
18547
18966
 
18967
+ // dist/pi-progress.js
18968
+ import { createHash as createHash4 } from "node:crypto";
18969
+ function record4(value) {
18970
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18971
+ }
18972
+ function textContent(content) {
18973
+ if (typeof content === "string")
18974
+ return content;
18975
+ if (!Array.isArray(content))
18976
+ return "";
18977
+ return content.filter((part) => record4(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
18978
+ }
18979
+ function boundedPiProgress(text4) {
18980
+ const limit = 64e3;
18981
+ return text4.length <= limit ? text4 : `${text4.slice(0, limit)}
18982
+ [Pi notification truncated]`;
18983
+ }
18984
+ function visibleText(text4) {
18985
+ return text4.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
18986
+ }
18987
+ function noticeDisplay(value, fallback) {
18988
+ if (!record4(value) || !record4(value.details) || typeof value.details.summary !== "string")
18989
+ return visibleText(fallback);
18990
+ const details = value.details;
18991
+ const parts = [visibleText(details.summary)];
18992
+ if (typeof details.exitCode === "number")
18993
+ parts.push(`Exit code: ${details.exitCode}`);
18994
+ for (const key of ["signal", "error", "errorMessage"])
18995
+ if (typeof details[key] === "string" && details[key])
18996
+ parts.push(`${key}: ${visibleText(details[key])}`);
18997
+ if (record4(details.logMatch) && typeof details.logMatch.line === "string")
18998
+ parts.push(`Log: ${visibleText(details.logMatch.line)}`);
18999
+ if (typeof details.command === "string" && details.command)
19000
+ parts.push(`Command: ${visibleText(details.command)}`);
19001
+ return parts.join("\n\n");
19002
+ }
19003
+ function piCustomNoticeKey(value) {
19004
+ if (!record4(value) || value.type !== "custom_message" && value.role !== "custom" || value.display !== true || typeof value.customType !== "string")
19005
+ return null;
19006
+ const text4 = textContent(value.content);
19007
+ if (text4.trim().length === 0)
19008
+ return null;
19009
+ return JSON.stringify([value.customType, text4]);
19010
+ }
19011
+ function piCustomNotice(value, sessionId, occurrences) {
19012
+ const key = piCustomNoticeKey(value);
19013
+ if (!key)
19014
+ return null;
19015
+ const occurrence = occurrences.get(key) ?? 0;
19016
+ occurrences.set(key, occurrence + 1);
19017
+ const digest = createHash4("sha256").update(JSON.stringify([sessionId, key, occurrence])).digest("hex");
19018
+ const [customType, text4] = JSON.parse(key);
19019
+ return {
19020
+ type: "progress.message",
19021
+ itemId: hostItemIdSchema.parse(`pi-notice-v1-${digest}`),
19022
+ text: boundedPiProgress(`Pi notification (${visibleText(customType)})
19023
+
19024
+ ${noticeDisplay(value, text4)}`)
19025
+ };
19026
+ }
19027
+ function piHistoryNotices(sessionId, entries) {
19028
+ const occurrences = /* @__PURE__ */ new Map();
19029
+ const notices = /* @__PURE__ */ new Map();
19030
+ for (const entry of entries) {
19031
+ const notice = piCustomNotice(entry.message ?? entry, sessionId, occurrences);
19032
+ if (notice)
19033
+ notices.set(entry.id, notice);
19034
+ }
19035
+ return { notices, occurrences };
19036
+ }
19037
+ function piStatusText(value) {
19038
+ if (value.type === "auto_retry_start") {
19039
+ const attempt = typeof value.attempt === "number" ? ` ${value.attempt}` : "";
19040
+ const maximum = typeof value.maxAttempts === "number" ? `/${value.maxAttempts}` : "";
19041
+ const delay2 = typeof value.delayMs === "number" && value.delayMs >= 0 ? ` Waiting ${value.delayMs / 1e3} s before retrying.` : "";
19042
+ const reason = typeof value.errorMessage === "string" ? `
19043
+
19044
+ ${visibleText(value.errorMessage)}` : "";
19045
+ return boundedPiProgress(`Pi retry${attempt}${maximum}.${delay2}${reason}`);
19046
+ }
19047
+ if (value.type === "auto_retry_end") {
19048
+ if (typeof value.success !== "boolean")
19049
+ return null;
19050
+ const reason = typeof value.finalError === "string" ? `
19051
+
19052
+ ${visibleText(value.finalError)}` : "";
19053
+ return boundedPiProgress(`Pi retry ${value.success ? "succeeded" : "ended without success"}.${reason}`);
19054
+ }
19055
+ if (value.type !== "extension_ui_request")
19056
+ return null;
19057
+ if (value.method === "notify" && typeof value.message === "string" && value.message.trim()) {
19058
+ const level = typeof value.notifyType === "string" ? ` (${value.notifyType})` : "";
19059
+ return boundedPiProgress(`Pi notification${level}
19060
+
19061
+ ${visibleText(value.message)}`);
19062
+ }
19063
+ if (value.method === "setStatus" && typeof value.statusKey === "string") {
19064
+ return typeof value.statusText === "string" && value.statusText.trim() ? boundedPiProgress(`Pi status (${visibleText(value.statusKey)})
19065
+
19066
+ ${visibleText(value.statusText)}`) : `Pi status (${visibleText(value.statusKey)}) cleared.`;
19067
+ }
19068
+ return null;
19069
+ }
19070
+
19071
+ // dist/pi-tool-command.js
19072
+ function record5(value) {
19073
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19074
+ }
19075
+ function stringField(value, key) {
19076
+ if (!record5(value))
19077
+ return void 0;
19078
+ for (const source of [value, value.input, value.arguments]) {
19079
+ if (record5(source) && typeof source[key] === "string" && source[key].length > 0)
19080
+ return source[key];
19081
+ }
19082
+ return void 0;
19083
+ }
19084
+ function piToolCommand(name, arguments_) {
19085
+ if (!["bash", "exec", "terminal", "run"].includes(name.toLowerCase()))
19086
+ return null;
19087
+ const command = ["command", "cmd", "script", "commandLine", "command_line"].map((key) => stringField(arguments_, key)).find((value) => value !== void 0);
19088
+ if (!command)
19089
+ return null;
19090
+ const cwd = stringField(arguments_, "cwd");
19091
+ return { command, ...cwd ? { cwd } : {} };
19092
+ }
19093
+
18548
19094
  // dist/pi-history.js
18549
19095
  var piHarnessId = harnessIdSchema.parse("pi");
18550
- function isRecord4(value) {
19096
+ function isRecord5(value) {
18551
19097
  return typeof value === "object" && value !== null && !Array.isArray(value);
18552
19098
  }
18553
- function textContent(value) {
19099
+ function textContent2(value) {
18554
19100
  if (typeof value === "string")
18555
19101
  return value;
18556
19102
  if (!Array.isArray(value))
18557
19103
  return "";
18558
- return value.filter((part) => isRecord4(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
19104
+ return value.filter((part) => isRecord5(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
18559
19105
  }
18560
19106
  function thinkingContent(value) {
18561
19107
  if (!Array.isArray(value))
18562
19108
  return "";
18563
- return value.filter((part) => isRecord4(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
19109
+ return value.filter((part) => isRecord5(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
18564
19110
  }
18565
19111
  function validatedEntry(value) {
18566
19112
  if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
@@ -18591,7 +19137,7 @@ function activePiEntries(history) {
18591
19137
  return reversed.reverse();
18592
19138
  }
18593
19139
  function message(entry) {
18594
- return entry.type === "message" && isRecord4(entry.message) ? entry.message : null;
19140
+ return entry.type === "message" && isRecord5(entry.message) ? entry.message : null;
18595
19141
  }
18596
19142
  function messageRole(entry) {
18597
19143
  const value = message(entry)?.role;
@@ -18606,7 +19152,7 @@ function assistantOutcome(entries) {
18606
19152
  if (!final)
18607
19153
  return { status: "unknown", reason: "Pi history has no Assistant terminal" };
18608
19154
  const stopReason = final.stopReason;
18609
- if (stopReason === "aborted") {
19155
+ if (piAssistantWasAborted(final)) {
18610
19156
  return { status: "cancelled", reason: "Pi Assistant was aborted" };
18611
19157
  }
18612
19158
  if (stopReason === "error") {
@@ -18619,7 +19165,7 @@ function assistantOutcome(entries) {
18619
19165
  }
18620
19166
  };
18621
19167
  }
18622
- if (typeof stopReason === "string" || textContent(final.content).length > 0) {
19168
+ if (typeof stopReason === "string" || textContent2(final.content).length > 0) {
18623
19169
  return { status: "succeeded" };
18624
19170
  }
18625
19171
  return { status: "unknown", reason: "Pi Assistant terminal is not classifiable" };
@@ -18636,8 +19182,8 @@ function itemOutcome(outcome) {
18636
19182
  return { status: "succeeded" };
18637
19183
  }
18638
19184
  function toolOutput(value) {
18639
- const text2 = textContent(value);
18640
- return text2.length > 0 ? { content: [{ type: "text", text: text2 }] } : void 0;
19185
+ const text4 = textContent2(value);
19186
+ return text4.length > 0 ? { content: [{ type: "text", text: text4 }] } : void 0;
18641
19187
  }
18642
19188
  function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18643
19189
  const items = [];
@@ -18660,37 +19206,52 @@ function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18660
19206
  }
18661
19207
  return items;
18662
19208
  }
18663
- function snapshotItems(entries, outcome, subagents, cwd) {
19209
+ function snapshotItems(entries, messageIdentities, notices, outcome, subagents, cwd) {
18664
19210
  const snapshots = [];
18665
19211
  const toolCalls = /* @__PURE__ */ new Map();
18666
19212
  for (const entry of entries) {
19213
+ const notice = notices.get(entry.id);
19214
+ if (notice) {
19215
+ snapshots.push({
19216
+ item: {
19217
+ type: "agentMessage",
19218
+ itemId: notice.itemId,
19219
+ text: notice.text,
19220
+ phase: "commentary"
19221
+ },
19222
+ outcome: { status: "succeeded" }
19223
+ });
19224
+ continue;
19225
+ }
18667
19226
  const nativeMessage = message(entry);
18668
19227
  if (!nativeMessage)
18669
19228
  continue;
18670
19229
  const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
18671
19230
  if (nativeMessage.role === "assistant") {
18672
- const text2 = textContent(content);
19231
+ const text4 = textContent2(content);
18673
19232
  const reasoning = thinkingContent(content);
18674
19233
  let projectedText = false;
18675
19234
  let projectedReasoning = false;
18676
19235
  for (const [ordinal, part] of content.entries()) {
18677
- if (!isRecord4(part))
19236
+ if (!isRecord5(part))
18678
19237
  continue;
18679
19238
  if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
18680
19239
  const item2 = {
18681
19240
  type: "reasoning",
18682
- itemId: itemId(entry.id, "reasoning", 0),
19241
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "reasoning") ?? itemId(entry.id, "reasoning", 0),
18683
19242
  text: reasoning
18684
19243
  };
18685
19244
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18686
19245
  projectedReasoning = true;
18687
19246
  continue;
18688
19247
  }
18689
- if (part.type === "text" && !projectedText && text2.length > 0) {
19248
+ if (part.type === "text" && !projectedText && text4.length > 0) {
19249
+ const phase = piAssistantPhase(nativeMessage);
18690
19250
  const item2 = {
18691
19251
  type: "agentMessage",
18692
- itemId: itemId(entry.id, "assistant", 0),
18693
- text: text2
19252
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "assistant") ?? itemId(entry.id, "assistant", 0),
19253
+ text: text4,
19254
+ ...phase ? { phase } : {}
18694
19255
  };
18695
19256
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18696
19257
  projectedText = true;
@@ -18718,9 +19279,24 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18718
19279
  if (!call || call.name !== nativeMessage.toolName)
18719
19280
  continue;
18720
19281
  const output = toolOutput(nativeMessage.content);
18721
- const item = {
18722
- type: "toolExecution",
19282
+ const shell = piToolCommand(call.name, call.arguments);
19283
+ const commandCwd = shell?.cwd ?? cwd;
19284
+ const durationMs = typeof nativeMessage.durationMs === "number" && Number.isFinite(nativeMessage.durationMs) && nativeMessage.durationMs >= 0 ? nativeMessage.durationMs : void 0;
19285
+ const base = {
18723
19286
  itemId: itemId(call.entryId, "tool", call.ordinal),
19287
+ ...durationMs !== void 0 ? { durationMs } : {}
19288
+ };
19289
+ const exitCode = typeof nativeMessage.exitCode === "number" && Number.isInteger(nativeMessage.exitCode) ? nativeMessage.exitCode : void 0;
19290
+ const item = shell ? {
19291
+ ...base,
19292
+ type: "commandExecution",
19293
+ command: shell.command,
19294
+ ...commandCwd ? { cwd: commandCwd } : {},
19295
+ ...output ? { output: textContent2(nativeMessage.content) } : {},
19296
+ ...exitCode !== void 0 ? { exitCode } : {}
19297
+ } : {
19298
+ ...base,
19299
+ type: "toolExecution",
18724
19300
  toolName: call.name,
18725
19301
  arguments: call.arguments,
18726
19302
  ...output ? { output } : {}
@@ -18751,6 +19327,10 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18751
19327
  function modelChange(entry) {
18752
19328
  return entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string" ? { provider: entry.provider, id: entry.modelId } : null;
18753
19329
  }
19330
+ function isEmptyWakeup(entry) {
19331
+ const content = message(entry)?.content;
19332
+ return content === "" || Array.isArray(content) && content.every((part) => isRecord5(part) && part.type === "text" && part.text === "");
19333
+ }
18754
19334
  function turnStarts(active) {
18755
19335
  const starts = [];
18756
19336
  let terminal = true;
@@ -18758,6 +19338,8 @@ function turnStarts(active) {
18758
19338
  for (const [index, entry] of active.entries()) {
18759
19339
  const role = messageRole(entry);
18760
19340
  if (role === "user") {
19341
+ if (pending && isEmptyWakeup(entry))
19342
+ continue;
18761
19343
  starts.push({ entry, index });
18762
19344
  pending = null;
18763
19345
  terminal = false;
@@ -18774,6 +19356,8 @@ function turnStarts(active) {
18774
19356
  }
18775
19357
  function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0)) {
18776
19358
  const active = activePiEntries(history);
19359
+ const { identities } = piHistoryMessageIdentities(state2.sessionId, active);
19360
+ const { notices } = piHistoryNotices(state2.sessionId, active);
18777
19361
  const turns = [];
18778
19362
  const starts = turnStarts(active);
18779
19363
  const byIndex = new Map(starts.map((start, ordinal) => [start.index, ordinal]));
@@ -18795,7 +19379,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18795
19379
  const end = next?.index ?? active.length;
18796
19380
  const entries = active.slice(index, end);
18797
19381
  const outcome = assistantOutcome(entries);
18798
- const userText = textContent(message(user)?.content);
19382
+ const userText = textContent2(message(user)?.content);
18799
19383
  const nativeTurnRef = nativeTurnRefSchema.parse({
18800
19384
  harnessId: piHarnessId,
18801
19385
  nativeSessionId: state2.sessionId,
@@ -18812,7 +19396,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18812
19396
  nativeTurnRef,
18813
19397
  ...!next || messageRole(next.entry) === "user" ? { checkpoint } : {},
18814
19398
  input: messageRole(user) === "user" ? [{ type: "text", text: userText }] : [],
18815
- items: snapshotItems(entries, outcome, subagents, state2.cwd),
19399
+ items: snapshotItems(entries, identities, notices, outcome, subagents, state2.cwd),
18816
19400
  outcome,
18817
19401
  ...effectiveModel ? { model: encodePiModelRef(effectiveModel) } : {}
18818
19402
  });
@@ -18847,14 +19431,14 @@ function resolvePiForkBoundary(history, checkpointId) {
18847
19431
  }
18848
19432
 
18849
19433
  // dist/pi-usage.js
18850
- function isRecord5(value) {
19434
+ function isRecord6(value) {
18851
19435
  return typeof value === "object" && value !== null && !Array.isArray(value);
18852
19436
  }
18853
19437
  function nonNegativeSafeInteger(value) {
18854
19438
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
18855
19439
  }
18856
19440
  function optionalPiCacheHitRatePercent(value) {
18857
- if (!isRecord5(value) || value.role !== "assistant" || !isRecord5(value.usage))
19441
+ if (!isRecord6(value) || value.role !== "assistant" || !isRecord6(value.usage))
18858
19442
  return null;
18859
19443
  const input = nonNegativeSafeInteger(value.usage.input);
18860
19444
  const cacheRead = nonNegativeSafeInteger(value.usage.cacheRead);
@@ -18867,20 +19451,20 @@ function optionalPiCacheHitRatePercent(value) {
18867
19451
  function latestPiCacheHitRatePercent(history) {
18868
19452
  let latest = null;
18869
19453
  for (const entry of activePiEntries(history)) {
18870
- if (entry.type === "message" && isRecord5(entry.message) && entry.message.role === "assistant") {
19454
+ if (entry.type === "message" && isRecord6(entry.message) && entry.message.role === "assistant") {
18871
19455
  latest = optionalPiCacheHitRatePercent(entry.message);
18872
19456
  }
18873
19457
  }
18874
19458
  return latest;
18875
19459
  }
18876
19460
  function responseData(response, operation) {
18877
- if (!isRecord5(response.data)) {
19461
+ if (!isRecord6(response.data)) {
18878
19462
  throw new Error(`Pi RPC ${operation} response has no data`);
18879
19463
  }
18880
19464
  return response.data;
18881
19465
  }
18882
19466
  function contextUsage(value) {
18883
- if (!isRecord5(value))
19467
+ if (!isRecord6(value))
18884
19468
  throw new Error("Pi RPC context Usage is invalid");
18885
19469
  return parseHostUsage({
18886
19470
  contextUsedTokens: value.tokens,
@@ -18890,15 +19474,15 @@ function contextUsage(value) {
18890
19474
  function parsePiSessionUsage(response) {
18891
19475
  const data = responseData(response, "Session stats");
18892
19476
  const tokens = data.tokens;
18893
- if (tokens !== void 0 && !isRecord5(tokens)) {
19477
+ if (tokens !== void 0 && !isRecord6(tokens)) {
18894
19478
  throw new Error("Pi RPC Session stats tokens are invalid");
18895
19479
  }
18896
19480
  return parseHostUsage({
18897
- ...isRecord5(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
18898
- ...isRecord5(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
18899
- ...isRecord5(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
18900
- ...isRecord5(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
18901
- ...isRecord5(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
19481
+ ...isRecord6(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
19482
+ ...isRecord6(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
19483
+ ...isRecord6(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
19484
+ ...isRecord6(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
19485
+ ...isRecord6(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
18902
19486
  ...data.cost !== void 0 ? { totalCostUsd: data.cost } : {},
18903
19487
  ...data.contextUsage !== void 0 ? contextUsage(data.contextUsage) : {}
18904
19488
  });
@@ -18917,9 +19501,9 @@ function optionalPiStateContextUsage(value) {
18917
19501
  }
18918
19502
  }
18919
19503
  function piUsageRecord(message3, extra = {}) {
18920
- if (!isRecord5(message3) || message3.role !== "assistant")
19504
+ if (!isRecord6(message3) || message3.role !== "assistant")
18921
19505
  return null;
18922
- const usage = isRecord5(message3.usage) ? message3.usage : null;
19506
+ const usage = isRecord6(message3.usage) ? message3.usage : null;
18923
19507
  const input = nonNegativeSafeInteger(usage?.input);
18924
19508
  const output = nonNegativeSafeInteger(usage?.output);
18925
19509
  const requestId = typeof message3.responseId === "string" && message3.responseId.length > 0 ? message3.responseId : typeof message3.timestamp === "number" && Number.isSafeInteger(message3.timestamp) ? `t${message3.timestamp}` : null;
@@ -18956,17 +19540,17 @@ function piUsageHistory(history) {
18956
19540
  for (const entry of history.entries) {
18957
19541
  if (entry.type !== "message")
18958
19542
  continue;
18959
- const record7 = piUsageRecord(entry.message, { historical: true });
18960
- if (record7?.kind === "request")
18961
- requests.push(record7.request);
18962
- else if (record7?.kind === "missing")
19543
+ const record9 = piUsageRecord(entry.message, { historical: true });
19544
+ if (record9?.kind === "request")
19545
+ requests.push(record9.request);
19546
+ else if (record9?.kind === "missing")
18963
19547
  complete = false;
18964
19548
  }
18965
19549
  return { requests, complete };
18966
19550
  }
18967
19551
 
18968
19552
  // dist/pi-usage-statistics.js
18969
- function isRecord6(value) {
19553
+ function isRecord7(value) {
18970
19554
  return typeof value === "object" && value !== null && !Array.isArray(value);
18971
19555
  }
18972
19556
  function piUserText(content) {
@@ -18974,11 +19558,11 @@ function piUserText(content) {
18974
19558
  return content;
18975
19559
  if (!Array.isArray(content))
18976
19560
  return void 0;
18977
- return content.filter((block) => isRecord6(block) && block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join(" ");
19561
+ return content.filter((block) => isRecord7(block) && block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join(" ");
18978
19562
  }
18979
19563
  async function readPiUsage(file2, signal) {
18980
19564
  const entries = [];
18981
- const header = await jsonlHeader(file2, (record7) => record7.type === "session", signal);
19565
+ const header = await jsonlHeader(file2, (record9) => record9.type === "session", signal);
18982
19566
  let name;
18983
19567
  const session = {
18984
19568
  sessionId: typeof header?.id === "string" ? header.id : void 0,
@@ -18995,11 +19579,11 @@ async function readPiUsage(file2, signal) {
18995
19579
  if (!name && message3?.role === "user") {
18996
19580
  name = usageSessionTitle(piUserText(message3.content));
18997
19581
  }
18998
- const record7 = piUsageRecord(line.message);
18999
- if (record7?.kind !== "request")
19582
+ const record9 = piUsageRecord(line.message);
19583
+ if (record9?.kind !== "request")
19000
19584
  continue;
19001
19585
  const at = nativeTimeMs(message3.timestamp) ?? nativeTimeMs(line.timestamp);
19002
- const entry = at !== null && usageEntryFromRequest(record7.request, at);
19586
+ const entry = at !== null && usageEntryFromRequest(record9.request, at);
19003
19587
  if (!entry)
19004
19588
  continue;
19005
19589
  if (!(typeof message3.responseId === "string" && message3.responseId.length > 0)) {
@@ -19020,9 +19604,9 @@ function createPiUsageStatistics(environment) {
19020
19604
  }
19021
19605
 
19022
19606
  // dist/account-balance.js
19023
- import { readFile } from "node:fs/promises";
19024
- import { homedir as homedir2 } from "node:os";
19025
- import path7 from "node:path";
19607
+ import { readFile as readFile2 } from "node:fs/promises";
19608
+ import { homedir as homedir3 } from "node:os";
19609
+ import path8 from "node:path";
19026
19610
  var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
19027
19611
  var SUB2API_USAGE_PATH = "/v1/usage";
19028
19612
  var REQUEST_TIMEOUT_MS = 1e4;
@@ -19031,18 +19615,18 @@ function agentDirectory(environment) {
19031
19615
  const configured = environment.PI_CODING_AGENT_DIR?.trim();
19032
19616
  if (configured)
19033
19617
  return configured;
19034
- return path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".pi", "agent");
19618
+ return path8.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".pi", "agent");
19035
19619
  }
19036
- var record4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
19620
+ var record6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
19037
19621
  async function deepSeekApiKey(environment) {
19038
- const auth = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "auth.json"), "utf8")));
19039
- const deepseek = record4(auth.deepseek);
19622
+ const auth = record6(JSON.parse(await readFile2(path8.join(agentDirectory(environment), "auth.json"), "utf8")));
19623
+ const deepseek = record6(auth.deepseek);
19040
19624
  if (deepseek.type !== "api_key")
19041
19625
  return void 0;
19042
19626
  return typeof deepseek.key === "string" && deepseek.key.trim() ? deepseek.key : void 0;
19043
19627
  }
19044
19628
  function projectSub2ApiUsage(payload, providerId) {
19045
- const data = record4(payload);
19629
+ const data = record6(payload);
19046
19630
  if (data.isValid === false)
19047
19631
  return null;
19048
19632
  if (data.mode !== "unrestricted" && data.mode !== "quota_limited")
@@ -19052,7 +19636,7 @@ function projectSub2ApiUsage(payload, providerId) {
19052
19636
  return null;
19053
19637
  const wallet = finiteAmount(data.balance);
19054
19638
  const remaining = finiteAmount(data.remaining);
19055
- const quotaRemaining = finiteAmount(record4(data.quota).remaining);
19639
+ const quotaRemaining = finiteAmount(record6(data.quota).remaining);
19056
19640
  const amount = wallet ?? remaining ?? quotaRemaining;
19057
19641
  if (amount === null)
19058
19642
  return null;
@@ -19072,10 +19656,10 @@ function finiteAmount(value) {
19072
19656
  return Number.isFinite(amount) && amount >= 0 ? amount : null;
19073
19657
  }
19074
19658
  function projectDeepSeekBalance(payload) {
19075
- const data = record4(payload);
19659
+ const data = record6(payload);
19076
19660
  if (!Array.isArray(data.balance_infos))
19077
19661
  return null;
19078
- const first = record4(data.balance_infos[0]);
19662
+ const first = record6(data.balance_infos[0]);
19079
19663
  const amount = finiteAmount(first.total_balance);
19080
19664
  const currency = typeof first.currency === "string" ? first.currency.trim() : "";
19081
19665
  if (amount === null || !currency)
@@ -19104,11 +19688,11 @@ function usageEndpoint(baseUrl) {
19104
19688
  }
19105
19689
  async function configuredSub2ApiProviders(environment) {
19106
19690
  try {
19107
- const models = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "models.json"), "utf8")));
19108
- const providers = record4(models.providers);
19691
+ const models = record6(JSON.parse(await readFile2(path8.join(agentDirectory(environment), "models.json"), "utf8")));
19692
+ const providers = record6(models.providers);
19109
19693
  const found = [];
19110
19694
  for (const [id, definition] of Object.entries(providers)) {
19111
- const provider = record4(definition);
19695
+ const provider = record6(definition);
19112
19696
  const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
19113
19697
  const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
19114
19698
  if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
@@ -19166,19 +19750,21 @@ async function fetchPiAccountBalance(input) {
19166
19750
  }
19167
19751
 
19168
19752
  // dist/pi-credential-imports.js
19169
- import { randomUUID } from "node:crypto";
19753
+ import { randomUUID as randomUUID2 } from "node:crypto";
19170
19754
  import { execFile as execFile2 } from "node:child_process";
19171
19755
  import { promisify } from "node:util";
19172
19756
  import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
19173
19757
  import { realpath as realpath2 } from "node:fs/promises";
19174
19758
  import os4 from "node:os";
19175
- import path9 from "node:path";
19759
+ import path10 from "node:path";
19176
19760
  import { pathToFileURL } from "node:url";
19177
19761
 
19178
19762
  // dist/command.js
19179
19763
  import fs2 from "node:fs";
19180
- import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
19181
- import path8 from "node:path";
19764
+ import { homedir as homedir4, tmpdir as tmpdir2 } from "node:os";
19765
+ import path9 from "node:path";
19766
+ var PI_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
19767
+ var PI_PACKAGE_PATH = path9.join("node_modules", "@earendil-works", "pi-coding-agent");
19182
19768
  var piDiscoverySpec = {
19183
19769
  id: "pi",
19184
19770
  command: "pi",
@@ -19203,12 +19789,49 @@ function resolvePiExecutable(input, dependencies = {}) {
19203
19789
  }, { ...dependencies.isExecutable ? { isExecutable: dependencies.isExecutable } : {} });
19204
19790
  return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
19205
19791
  }
19792
+ function findPiPackageDirectory(executable) {
19793
+ let directory = path9.dirname(executable);
19794
+ while (true) {
19795
+ for (const candidate of [directory, path9.join(directory, PI_PACKAGE_PATH)]) {
19796
+ try {
19797
+ const manifest = JSON.parse(fs2.readFileSync(path9.join(candidate, "package.json"), "utf8"));
19798
+ if (typeof manifest === "object" && manifest !== null && "name" in manifest && manifest.name === PI_PACKAGE_NAME) {
19799
+ return candidate;
19800
+ }
19801
+ } catch {
19802
+ }
19803
+ }
19804
+ const parent = path9.dirname(directory);
19805
+ if (parent === directory)
19806
+ return void 0;
19807
+ directory = parent;
19808
+ }
19809
+ }
19810
+ function findPiCliEntry(packageDirectory) {
19811
+ try {
19812
+ const manifest = JSON.parse(fs2.readFileSync(path9.join(packageDirectory, "package.json"), "utf8"));
19813
+ if (typeof manifest !== "object" || manifest === null || !("bin" in manifest))
19814
+ return void 0;
19815
+ const bin = manifest.bin;
19816
+ const entry = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && "pi" in bin ? bin.pi : void 0;
19817
+ if (typeof entry !== "string" || !entry.trim())
19818
+ return void 0;
19819
+ const resolved = path9.resolve(packageDirectory, entry);
19820
+ const relative = path9.relative(packageDirectory, resolved);
19821
+ if (relative === ".." || relative.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative) || !fs2.statSync(resolved).isFile()) {
19822
+ return void 0;
19823
+ }
19824
+ return resolved;
19825
+ } catch {
19826
+ return void 0;
19827
+ }
19828
+ }
19206
19829
  function isFilesystemRoot(cwd) {
19207
- const resolved = path8.resolve(cwd);
19208
- return resolved === path8.parse(resolved).root;
19830
+ const resolved = path9.resolve(cwd);
19831
+ return resolved === path9.parse(resolved).root;
19209
19832
  }
19210
19833
  function writableDirectory(candidate) {
19211
- if (!candidate || !path8.isAbsolute(candidate) || isFilesystemRoot(candidate))
19834
+ if (!candidate || !path9.isAbsolute(candidate) || isFilesystemRoot(candidate))
19212
19835
  return void 0;
19213
19836
  try {
19214
19837
  if (!fs2.statSync(candidate).isDirectory())
@@ -19221,19 +19844,19 @@ function writableDirectory(candidate) {
19221
19844
  }
19222
19845
  function resolvePiInspectCwd(inputCwd, environment = process.env) {
19223
19846
  if (typeof inputCwd === "string" && inputCwd.length > 0 && !isFilesystemRoot(inputCwd)) {
19224
- return path8.resolve(inputCwd);
19847
+ return path9.resolve(inputCwd);
19225
19848
  }
19226
- const candidates = [environment.USERPROFILE, environment.HOME, homedir3(), tmpdir2()];
19849
+ const candidates = [environment.USERPROFILE, environment.HOME, homedir4(), tmpdir2()];
19227
19850
  for (const candidate of candidates) {
19228
19851
  const usable = writableDirectory(candidate);
19229
19852
  if (usable)
19230
19853
  return usable;
19231
19854
  }
19232
- return inputCwd && inputCwd.length > 0 ? path8.resolve(inputCwd) : process.cwd();
19855
+ return inputCwd && inputCwd.length > 0 ? path9.resolve(inputCwd) : process.cwd();
19233
19856
  }
19234
19857
 
19235
19858
  // dist/pi-credential-imports.js
19236
- var PREFIX2 = "codexhost-account-";
19859
+ var PREFIX3 = "codexhost-account-";
19237
19860
  function object2(value) {
19238
19861
  return typeof value === "object" && value !== null && !Array.isArray(value);
19239
19862
  }
@@ -19274,7 +19897,7 @@ function describeOauth(credential) {
19274
19897
  };
19275
19898
  }
19276
19899
  function writeAuth(filename, content) {
19277
- const temporary = `${filename}.${randomUUID()}.tmp`;
19900
+ const temporary = `${filename}.${randomUUID2()}.tmp`;
19278
19901
  try {
19279
19902
  writeFileSync(temporary, content, { flag: "wx", mode: 384 });
19280
19903
  renameSync(temporary, filename);
@@ -19283,8 +19906,8 @@ function writeAuth(filename, content) {
19283
19906
  }
19284
19907
  }
19285
19908
  function removeOwnedFiles(dir) {
19286
- rmSync(path9.join(dir, "index.ts"), { force: true });
19287
- rmSync(path9.join(dir, "import.json"), { force: true });
19909
+ rmSync(path10.join(dir, "index.ts"), { force: true });
19910
+ rmSync(path10.join(dir, "import.json"), { force: true });
19288
19911
  try {
19289
19912
  rmdirSync(dir);
19290
19913
  } catch {
@@ -19292,26 +19915,17 @@ function removeOwnedFiles(dir) {
19292
19915
  }
19293
19916
  async function installation(command, environment, authPath) {
19294
19917
  const executable = await realpath2(resolvePiExecutable({ ...command ? { command } : {}, environment }));
19295
- let directory = path9.dirname(executable);
19296
- while (true) {
19297
- const manifest = path9.join(directory, "package.json");
19298
- if (existsSync(manifest)) {
19299
- const pkg = JSON.parse(readFileSync(manifest, "utf8"));
19300
- if (pkg.name === "@earendil-works/pi-coding-agent")
19301
- break;
19302
- }
19303
- const parent = path9.dirname(directory);
19304
- if (parent === directory)
19305
- throw new Error("Pi credential import requires a supported npm Pi installation");
19306
- directory = parent;
19307
- }
19308
- const storage = await import(pathToFileURL(path9.join(directory, "dist/core/auth-storage.js")).href);
19309
- const ai = path9.join(directory, "node_modules/@earendil-works/pi-ai/dist");
19310
- const all = await import(pathToFileURL(path9.join(ai, "providers/all.js")).href);
19918
+ const directory = findPiPackageDirectory(executable);
19919
+ const cliEntry = directory ? findPiCliEntry(directory) : void 0;
19920
+ if (!directory || !cliEntry)
19921
+ throw new Error("Pi credential import requires a supported npm Pi installation");
19922
+ const storage = await import(pathToFileURL(path10.join(directory, "dist/core/auth-storage.js")).href);
19923
+ const ai = path10.join(directory, "node_modules/@earendil-works/pi-ai/dist");
19924
+ const all = await import(pathToFileURL(path10.join(ai, "providers/all.js")).href);
19311
19925
  const providers = all.getBuiltinProviders();
19312
19926
  const providerModules = {
19313
- "openai-codex": pathToFileURL(path9.join(ai, "providers/openai-codex.js")).href,
19314
- xai: pathToFileURL(path9.join(ai, "providers/xai.js")).href
19927
+ "openai-codex": pathToFileURL(path10.join(ai, "providers/openai-codex.js")).href,
19928
+ xai: pathToFileURL(path10.join(ai, "providers/xai.js")).href
19315
19929
  };
19316
19930
  for (const [id, url2] of Object.entries(providerModules)) {
19317
19931
  const module = await import(url2);
@@ -19324,9 +19938,9 @@ async function installation(command, environment, authPath) {
19324
19938
  providerModules,
19325
19939
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
19326
19940
  async configuredProviderNames() {
19327
- const { stdout } = await promisify(execFile2)(process.execPath, [executable, "--offline", "--no-approve", "--list-models"], {
19328
- cwd: existsSync(path9.dirname(authPath)) ? path9.dirname(authPath) : os4.homedir(),
19329
- env: { ...environment, PI_CODING_AGENT_DIR: path9.dirname(authPath), PI_OFFLINE: "1" },
19941
+ const { stdout } = await promisify(execFile2)(process.execPath, [cliEntry, "--offline", "--no-approve", "--list-models"], {
19942
+ cwd: existsSync(path10.dirname(authPath)) ? path10.dirname(authPath) : os4.homedir(),
19943
+ env: { ...environment, PI_CODING_AGENT_DIR: path10.dirname(authPath), PI_OFFLINE: "1" },
19330
19944
  timeout: 15e3,
19331
19945
  maxBuffer: 4 * 1024 * 1024
19332
19946
  });
@@ -19356,26 +19970,26 @@ export default async function (pi) {
19356
19970
  }
19357
19971
  function createPiCredentialImports(options = {}) {
19358
19972
  const env = { ...process.env, ...options.environment };
19359
- const agentDir = env.PI_CODING_AGENT_DIR ?? path9.join(env.HOME ?? os4.homedir(), ".pi/agent");
19360
- const authPath = path9.join(agentDir, "auth.json");
19361
- const extensionsDir = path9.join(agentDir, "extensions");
19973
+ const agentDir = env.PI_CODING_AGENT_DIR ?? path10.join(env.HOME ?? os4.homedir(), ".pi/agent");
19974
+ const authPath = path10.join(agentDir, "auth.json");
19975
+ const extensionsDir = path10.join(agentDir, "extensions");
19362
19976
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
19363
19977
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
19364
- const location = (name) => path9.join(extensionsDir, `${PREFIX2}${credentialImportNameSchema.parse(name)}`);
19978
+ const location = (name) => path10.join(extensionsDir, `${PREFIX3}${credentialImportNameSchema.parse(name)}`);
19365
19979
  const readRecord = (name) => {
19366
19980
  const dir = location(name);
19367
19981
  if (lstatSync(dir).isSymbolicLink())
19368
19982
  throw new Error("Imported configuration was changed; manage it in Pi");
19369
- const value = JSON.parse(readFileSync(path9.join(dir, "import.json"), "utf8"));
19983
+ const value = JSON.parse(readFileSync(path10.join(dir, "import.json"), "utf8"));
19370
19984
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
19371
19985
  throw new Error("Invalid import metadata");
19372
- const record7 = value.record;
19373
- if (!object2(record7))
19986
+ const record9 = value.record;
19987
+ if (!object2(record9))
19374
19988
  throw new Error("Invalid import metadata");
19375
19989
  value.record = credentialImportRecordSchema.parse({
19376
- name: record7.name,
19377
- source: record7.source,
19378
- importedAt: record7.importedAt
19990
+ name: record9.name,
19991
+ source: record9.source,
19992
+ importedAt: record9.importedAt
19379
19993
  });
19380
19994
  if (value.record.name !== name)
19381
19995
  throw new Error("Import identity mismatch");
@@ -19383,7 +19997,7 @@ function createPiCredentialImports(options = {}) {
19383
19997
  };
19384
19998
  const owned = (meta3, auth) => {
19385
19999
  const credential = auth[meta3.record.name];
19386
- const file2 = path9.join(location(meta3.record.name), "index.ts");
20000
+ const file2 = path10.join(location(meta3.record.name), "index.ts");
19387
20001
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
19388
20002
  };
19389
20003
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -19392,12 +20006,12 @@ function createPiCredentialImports(options = {}) {
19392
20006
  return [];
19393
20007
  const result = [];
19394
20008
  for (const entry of readdirSync(extensionsDir)) {
19395
- if (!entry.startsWith(PREFIX2))
20009
+ if (!entry.startsWith(PREFIX3))
19396
20010
  continue;
19397
- const name = entry.slice(PREFIX2.length);
20011
+ const name = entry.slice(PREFIX3.length);
19398
20012
  if (!credentialImportNameSchema.safeParse(name).success)
19399
20013
  continue;
19400
- if (!existsSync(path9.join(location(name), "import.json")))
20014
+ if (!existsSync(path10.join(location(name), "import.json")))
19401
20015
  continue;
19402
20016
  try {
19403
20017
  const meta3 = readRecord(name);
@@ -19418,7 +20032,7 @@ function createPiCredentialImports(options = {}) {
19418
20032
  },
19419
20033
  async listOthers() {
19420
20034
  const auth = readAuth();
19421
- const ours = new Set(ownedRecords(auth).map((record7) => record7.name));
20035
+ const ours = new Set(ownedRecords(auth).map((record9) => record9.name));
19422
20036
  const result = /* @__PURE__ */ new Map();
19423
20037
  const usable = (provider) => Boolean(provider) && provider.length <= 128 && !ours.has(provider) && !result.has(provider);
19424
20038
  for (const [provider, credential] of Object.entries(auth)) {
@@ -19431,7 +20045,7 @@ function createPiCredentialImports(options = {}) {
19431
20045
  ...describeOauth(credential)
19432
20046
  });
19433
20047
  }
19434
- const modelsPath = path9.join(agentDir, "models.json");
20048
+ const modelsPath = path10.join(agentDir, "models.json");
19435
20049
  if (existsSync(modelsPath)) {
19436
20050
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
19437
20051
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -19452,8 +20066,8 @@ function createPiCredentialImports(options = {}) {
19452
20066
  throw new Error("Unsupported credential source");
19453
20067
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
19454
20068
  throw new Error("Provider name already exists; choose another name");
19455
- const owner = randomUUID();
19456
- const record7 = credentialImportRecordSchema.parse({
20069
+ const owner = randomUUID2();
20070
+ const record9 = credentialImportRecordSchema.parse({
19457
20071
  name,
19458
20072
  source: transfer.source,
19459
20073
  importedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -19465,15 +20079,15 @@ function createPiCredentialImports(options = {}) {
19465
20079
  try {
19466
20080
  sdk.backend.withLock((current) => {
19467
20081
  const auth = parseAuth(current);
19468
- const modelsPath = path9.join(agentDir, "models.json");
20082
+ const modelsPath = path10.join(agentDir, "models.json");
19469
20083
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
19470
- if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path9.join(extensionsDir, `${name}-provider.ts`)))
20084
+ if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path10.join(extensionsDir, `${name}-provider.ts`)))
19471
20085
  throw new Error("Provider name already exists; choose another name");
19472
20086
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
19473
20087
  mkdirSync(dir, { mode: 448 });
19474
20088
  created = true;
19475
- writeFileSync(path9.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record7, extension }), { flag: "wx", mode: 384 });
19476
- writeFileSync(path9.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
20089
+ writeFileSync(path10.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record9, extension }), { flag: "wx", mode: 384 });
20090
+ writeFileSync(path10.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
19477
20091
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
19478
20092
  saveAuth(auth);
19479
20093
  committed = true;
@@ -19492,7 +20106,7 @@ function createPiCredentialImports(options = {}) {
19492
20106
  const auth = parseAuth(current);
19493
20107
  if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
19494
20108
  throw new Error("Import ownership or source account changed; refusing replacement");
19495
- const metadataPath = path9.join(location(name), "import.json");
20109
+ const metadataPath = path10.join(location(name), "import.json");
19496
20110
  const previous = readFileSync(metadataPath, "utf8");
19497
20111
  const updated = {
19498
20112
  ...meta3,
@@ -19527,10 +20141,10 @@ function createPiCredentialImports(options = {}) {
19527
20141
  }
19528
20142
 
19529
20143
  // dist/pi-fast-mode.js
19530
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
19531
- import { mkdir, readFile as readFile2, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
19532
- import { homedir as homedir4 } from "node:os";
19533
- import path10 from "node:path";
20144
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
20145
+ import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
20146
+ import { homedir as homedir5 } from "node:os";
20147
+ import path11 from "node:path";
19534
20148
  var PI_FAST_COMMAND = "codexhost-fast-mode";
19535
20149
  var PI_FAST_ACK = "codexhost-fast-mode:";
19536
20150
  var PI_FAST_EXTENSION = `export default function(pi) {
@@ -19580,24 +20194,24 @@ var PI_FAST_EXTENSION = `export default function(pi) {
19580
20194
  }
19581
20195
  `;
19582
20196
  async function ensurePiFastExtension(environment) {
19583
- const digest = createHash2("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
19584
- const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path10.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".codexhost");
19585
- const directory = path10.resolve(dataDirectory, "extensions", "pi-codex-fast");
19586
- const file2 = path10.join(directory, `${digest}.mjs`);
19587
- if (await readFile2(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
20197
+ const digest = createHash5("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
20198
+ const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path11.join(environment.HOME ?? environment.USERPROFILE ?? homedir5(), ".codexhost");
20199
+ const directory = path11.resolve(dataDirectory, "extensions", "pi-codex-fast");
20200
+ const file2 = path11.join(directory, `${digest}.mjs`);
20201
+ if (await readFile3(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
19588
20202
  return file2;
19589
- await mkdir(directory, { recursive: true });
19590
- const temporary = `${file2}.${randomUUID2()}.tmp`;
20203
+ await mkdir2(directory, { recursive: true });
20204
+ const temporary = `${file2}.${randomUUID3()}.tmp`;
19591
20205
  try {
19592
- await writeFile2(temporary, PI_FAST_EXTENSION, { mode: 384 });
20206
+ await writeFile3(temporary, PI_FAST_EXTENSION, { mode: 384 });
19593
20207
  try {
19594
- await rename(temporary, file2);
20208
+ await rename2(temporary, file2);
19595
20209
  } catch (error51) {
19596
- if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
20210
+ if (await readFile3(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
19597
20211
  throw error51;
19598
20212
  }
19599
20213
  } finally {
19600
- await rm2(temporary, { force: true });
20214
+ await rm3(temporary, { force: true });
19601
20215
  }
19602
20216
  return file2;
19603
20217
  }
@@ -19614,15 +20228,15 @@ function withPiFast(catalog, supported) {
19614
20228
  // dist/pi-empty-session.js
19615
20229
  import { createReadStream as createReadStream3 } from "node:fs";
19616
20230
  import { createInterface as createInterface3 } from "node:readline";
19617
- import { randomUUID as randomUUID3 } from "node:crypto";
19618
- import { link, open as open2, rm as rm3 } from "node:fs/promises";
19619
- import path11 from "node:path";
20231
+ import { randomUUID as randomUUID4 } from "node:crypto";
20232
+ import { link, open as open2, rm as rm4 } from "node:fs/promises";
20233
+ import path12 from "node:path";
19620
20234
 
19621
20235
  // dist/pi-session-file.js
19622
20236
  import { open, realpath as realpath3 } from "node:fs/promises";
19623
20237
  var MAX_SESSION_HEADER_BYTES = 64 * 1024;
19624
20238
  var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
19625
- function isRecord7(value) {
20239
+ function isRecord8(value) {
19626
20240
  return typeof value === "object" && value !== null && !Array.isArray(value);
19627
20241
  }
19628
20242
  async function readPiSessionHeader(sessionFile) {
@@ -19642,7 +20256,7 @@ async function readPiSessionHeader(sessionFile) {
19642
20256
  } catch {
19643
20257
  throw new Error("Pi Session header is not valid JSON");
19644
20258
  }
19645
- if (!isRecord7(parsed) || parsed.type !== "session" || typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
20259
+ if (!isRecord8(parsed) || parsed.type !== "session" || typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
19646
20260
  throw new Error("Pi Session header is invalid");
19647
20261
  }
19648
20262
  return {
@@ -19675,7 +20289,7 @@ async function verifyPiSessionCwd(input) {
19675
20289
  async function persistEmptyPiSession(input) {
19676
20290
  const { state: state2, history, sourceSessionFile, sourceSessionId, cwd } = input;
19677
20291
  const destination = state2.sessionFile;
19678
- if (!destination || !path11.isAbsolute(destination) || path11.resolve(destination) === path11.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
20292
+ if (!destination || !path12.isAbsolute(destination) || path12.resolve(destination) === path12.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
19679
20293
  throw new Error("Pi empty Session is not an independent empty native fork");
19680
20294
  await verifyPiSessionCwd({
19681
20295
  sessionFile: sourceSessionFile,
@@ -19699,7 +20313,7 @@ async function persistEmptyPiSession(input) {
19699
20313
  cwd,
19700
20314
  parentSession: sourceSessionFile
19701
20315
  };
19702
- const temporary = path11.join(path11.dirname(destination), `.codexhost-${randomUUID3()}.tmp`);
20316
+ const temporary = path12.join(path12.dirname(destination), `.codexhost-${randomUUID4()}.tmp`);
19703
20317
  try {
19704
20318
  const file2 = await open2(temporary, "wx", 384);
19705
20319
  try {
@@ -19710,7 +20324,7 @@ async function persistEmptyPiSession(input) {
19710
20324
  }
19711
20325
  await link(temporary, destination);
19712
20326
  if (process.platform !== "win32") {
19713
- const directory = await open2(path11.dirname(destination), "r");
20327
+ const directory = await open2(path12.dirname(destination), "r");
19714
20328
  try {
19715
20329
  await directory.sync();
19716
20330
  } finally {
@@ -19718,7 +20332,7 @@ async function persistEmptyPiSession(input) {
19718
20332
  }
19719
20333
  }
19720
20334
  } finally {
19721
- await rm3(temporary, { force: true });
20335
+ await rm4(temporary, { force: true });
19722
20336
  }
19723
20337
  }
19724
20338
  async function readPiEmptySessionConfiguration(sessionFile) {
@@ -19774,20 +20388,20 @@ async function readPiEmptySessionConfiguration(sessionFile) {
19774
20388
  }
19775
20389
 
19776
20390
  // dist/pi-adapter.js
19777
- import { randomUUID as randomUUID6 } from "node:crypto";
19778
- import path15 from "node:path";
20391
+ import { randomUUID as randomUUID7 } from "node:crypto";
20392
+ import path17 from "node:path";
19779
20393
 
19780
20394
  // dist/pi-workflow-child-history.js
19781
- import { createHash as createHash3 } from "node:crypto";
20395
+ import { createHash as createHash6 } from "node:crypto";
19782
20396
  import { constants } from "node:fs";
19783
20397
  import { open as open3 } from "node:fs/promises";
19784
- import path12 from "node:path";
19785
- function record5(value) {
20398
+ import path13 from "node:path";
20399
+ function record7(value) {
19786
20400
  return typeof value === "object" && value !== null && !Array.isArray(value);
19787
20401
  }
19788
20402
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
19789
- async function childHistory(file2, parentSessionId, identity) {
19790
- if (!path12.isAbsolute(file2))
20403
+ async function childHistory(file2, parentSessionId, identity, validateParent = false) {
20404
+ if (!path13.isAbsolute(file2))
19791
20405
  throw new Error("Pi child Session path is not absolute");
19792
20406
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
19793
20407
  try {
@@ -19800,12 +20414,14 @@ async function childHistory(file2, parentSessionId, identity) {
19800
20414
  throw new Error("Pi child Session exceeds read bounds");
19801
20415
  const values = buffer.subarray(0, bytesRead).toString("utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
19802
20416
  const header = values[0];
19803
- if (!record5(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
20417
+ if (!record7(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
19804
20418
  throw new Error("Unsupported Pi child Session header");
20419
+ if (validateParent && header.parentSession !== parentSessionId)
20420
+ throw new Error("Pi child Session parent identity mismatch");
19805
20421
  const entries = [];
19806
20422
  for (const entry of values.slice(1)) {
19807
20423
  const parsed = jsonValueSchema.safeParse(entry);
19808
- if (!parsed.success || !record5(parsed.data) || typeof parsed.data.id !== "string")
20424
+ if (!parsed.success || !record7(parsed.data) || typeof parsed.data.id !== "string")
19809
20425
  throw new Error("Malformed Pi child Session entry");
19810
20426
  entries.push(parsed.data);
19811
20427
  }
@@ -19815,7 +20431,7 @@ async function childHistory(file2, parentSessionId, identity) {
19815
20431
  model: null,
19816
20432
  ...typeof header.cwd === "string" ? { cwd: header.cwd } : {}
19817
20433
  });
19818
- const prefix = createHash3("sha256").update(identity).digest("hex");
20434
+ const prefix = createHash6("sha256").update(identity).digest("hex");
19819
20435
  return {
19820
20436
  turns: snapshot.turns.map((turn) => {
19821
20437
  const readonlyTurn = {
@@ -19836,7 +20452,7 @@ async function childHistory(file2, parentSessionId, identity) {
19836
20452
  async function readPiWorkflowChild(history, parentSessionId, address) {
19837
20453
  for (const entry of activePiEntries(history).reverse()) {
19838
20454
  const message3 = entry.message;
19839
- if (!record5(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
20455
+ if (!record7(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
19840
20456
  continue;
19841
20457
  const summary = piWorkflowSummary(message3);
19842
20458
  if (!summary || summary.workflowRunId !== address.workflowRunId || summary.parentToolCallId !== message3.toolCallId)
@@ -19845,10 +20461,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
19845
20461
  if (!child)
19846
20462
  break;
19847
20463
  const details = message3.details;
19848
- if (!record5(details) || !Array.isArray(details.results))
20464
+ if (!record7(details) || !Array.isArray(details.results))
19849
20465
  break;
19850
- const result = details.results.findLast((candidate) => record5(candidate) && candidate.workflowKey === address.childId);
19851
- if (!record5(result))
20466
+ const result = details.results.findLast((candidate) => record7(candidate) && candidate.workflowKey === address.childId);
20467
+ if (!record7(result))
19852
20468
  break;
19853
20469
  const id = piWorkflowSubagentId(address);
19854
20470
  if (typeof result.sessionFile === "string") {
@@ -19891,25 +20507,69 @@ ${output}`,
19891
20507
  };
19892
20508
  }
19893
20509
 
19894
- // dist/pi-subagent-history.js
19895
- import { constants as constants2 } from "node:fs";
20510
+ // dist/pi-gotgenes-history.js
20511
+ function gotgenesHistory(history) {
20512
+ const records = /* @__PURE__ */ new Map();
20513
+ for (const entry of activePiEntries(history)) {
20514
+ const message3 = entry.message;
20515
+ const parsed = entry.type === "custom" && entry.customType === "subagents:record" ? gotgenesRecord(entry.data) : isRecord4(message3) && message3.role === "toolResult" && typeof message3.toolName === "string" ? gotgenesToolRecord(message3.toolName, message3) : null;
20516
+ if (!parsed)
20517
+ continue;
20518
+ records.set(parsed.id, mergeGotgenesRecord(records.get(parsed.id), parsed));
20519
+ }
20520
+ return [...records.values()];
20521
+ }
20522
+ function restoreGotgenes(history, observer) {
20523
+ observer.observe(gotgenesHistory(history), false);
20524
+ }
20525
+ async function readGotgenesChild(history, parentSessionId, id, live) {
20526
+ const saved = gotgenesHistory(history).find((entry) => entry.id === id);
20527
+ const record9 = live?.outputFile ? live : saved;
20528
+ if (!record9?.outputFile)
20529
+ return {
20530
+ ok: false,
20531
+ error: {
20532
+ code: "sessionNotFound",
20533
+ message: "Pi subagent has not published its Session transcript path",
20534
+ retryable: true
20535
+ }
20536
+ };
20537
+ try {
20538
+ return {
20539
+ ok: true,
20540
+ value: await childHistory(record9.outputFile, parentSessionId, gotgenesId(id), true)
20541
+ };
20542
+ } catch (error51) {
20543
+ return {
20544
+ ok: false,
20545
+ error: {
20546
+ code: "unavailable",
20547
+ message: error51 instanceof Error ? error51.message : "Pi child transcript unavailable",
20548
+ retryable: true
20549
+ }
20550
+ };
20551
+ }
20552
+ }
20553
+
20554
+ // dist/pi-subagent-history.js
20555
+ import { constants as constants2 } from "node:fs";
19896
20556
  import { open as open4 } from "node:fs/promises";
19897
- import path13 from "node:path";
19898
- function record6(value) {
20557
+ import path14 from "node:path";
20558
+ function record8(value) {
19899
20559
  return typeof value === "object" && value !== null && !Array.isArray(value);
19900
20560
  }
19901
20561
  function state(value) {
19902
20562
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
19903
20563
  }
19904
20564
  function piSubagentArtifact(value, runId, parentSessionId) {
19905
- if (!record6(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
20565
+ if (!record8(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
19906
20566
  return null;
19907
20567
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
19908
20568
  return null;
19909
20569
  const steps = Array.isArray(value.steps) ? value.steps : [];
19910
20570
  const children = [];
19911
20571
  for (const [index, step] of steps.entries()) {
19912
- if (!record6(step) || typeof step.agent !== "string")
20572
+ if (!record8(step) || typeof step.agent !== "string")
19913
20573
  return null;
19914
20574
  children.push({
19915
20575
  id: step.workflowKey ?? step.runId ?? `step:${index}`,
@@ -19940,19 +20600,20 @@ function piSubagentArtifact(value, runId, parentSessionId) {
19940
20600
  });
19941
20601
  }
19942
20602
  async function restorePiSubagents(history, parentSessionId, observer) {
20603
+ restoreGotgenes(history, observer.gotgenes);
19943
20604
  const receipts = /* @__PURE__ */ new Map();
19944
20605
  for (const entry of activePiEntries(history)) {
19945
- if (!record6(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record6(entry.message.details))
20606
+ if (!record8(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record8(entry.message.details))
19946
20607
  continue;
19947
20608
  const details = entry.message.details;
19948
- if (!["single", "parallel", "chain", "workflow"].includes(String(details.mode)) || typeof details.asyncId !== "string" || typeof details.asyncDir !== "string" || !path13.isAbsolute(details.asyncDir) || path13.basename(details.asyncDir) !== details.asyncId)
20609
+ if (!["single", "parallel", "chain", "workflow"].includes(String(details.mode)) || typeof details.asyncId !== "string" || typeof details.asyncDir !== "string" || !path14.isAbsolute(details.asyncDir) || path14.basename(details.asyncDir) !== details.asyncId)
19949
20610
  continue;
19950
20611
  receipts.set(details.asyncId, details.asyncDir);
19951
20612
  }
19952
20613
  for (const [id, directory] of [...receipts].slice(-128)) {
19953
20614
  let file2;
19954
20615
  try {
19955
- file2 = await open4(path13.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
20616
+ file2 = await open4(path14.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
19956
20617
  const stat2 = await file2.stat();
19957
20618
  if (!stat2.isFile() || stat2.size > 1024 * 1024)
19958
20619
  continue;
@@ -20034,8 +20695,8 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
20034
20695
 
20035
20696
  // dist/pi-rpc-session.js
20036
20697
  import { spawn, spawnSync } from "node:child_process";
20037
- import { randomUUID as randomUUID5 } from "node:crypto";
20038
- import path14 from "node:path";
20698
+ import { randomUUID as randomUUID6 } from "node:crypto";
20699
+ import path16 from "node:path";
20039
20700
 
20040
20701
  // dist/pi-slash-commands.js
20041
20702
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -20057,15 +20718,15 @@ function parsePiNativeCommands(response) {
20057
20718
  return data.commands.flatMap((entry) => {
20058
20719
  if (typeof entry !== "object" || entry === null)
20059
20720
  return [];
20060
- const record7 = entry;
20061
- const name = typeof record7.name === "string" ? record7.name.trim().replace(/^\//u, "") : "";
20721
+ const record9 = entry;
20722
+ const name = typeof record9.name === "string" ? record9.name.trim().replace(/^\//u, "") : "";
20062
20723
  if (!name)
20063
20724
  return [];
20064
20725
  return [
20065
20726
  {
20066
20727
  name,
20067
- ...typeof record7.description === "string" ? { description: record7.description } : {},
20068
- ...typeof record7.source === "string" ? { source: record7.source } : {}
20728
+ ...typeof record9.description === "string" ? { description: record9.description } : {},
20729
+ ...typeof record9.source === "string" ? { source: record9.source } : {}
20069
20730
  }
20070
20731
  ];
20071
20732
  });
@@ -20081,8 +20742,209 @@ function piDynamicCommandPrompt(catalog, commandId, argumentText) {
20081
20742
  return liveHarnessCommandPrompt(catalog, DYNAMIC_ID_PREFIX, commandId, argumentText);
20082
20743
  }
20083
20744
 
20745
+ // dist/pi-unc-launch.js
20746
+ import fs3 from "node:fs";
20747
+ import path15 from "node:path";
20748
+ function isWindowsUncDirectory(directory) {
20749
+ return /^\\\\(?:\?\\UNC\\)?(?![?.]\\)[^\\]+\\[^\\]+(?:\\|$)/iu.test(path15.win32.normalize(directory));
20750
+ }
20751
+ function text3(file2) {
20752
+ try {
20753
+ return fs3.readFileSync(file2, "utf8").replace(/^\uFEFF/u, "").replaceAll("\r\n", "\n").trim();
20754
+ } catch {
20755
+ return void 0;
20756
+ }
20757
+ }
20758
+ function isFile(file2) {
20759
+ try {
20760
+ return fs3.statSync(file2).isFile();
20761
+ } catch {
20762
+ return false;
20763
+ }
20764
+ }
20765
+ function nodeOnPath(environment) {
20766
+ for (const directory of pathDirectories(environment, "win32")) {
20767
+ for (const extension of executableExtensions("node", "win32", environment)) {
20768
+ const suffix = extension.toLowerCase();
20769
+ const candidate = path15.join(directory, `node${suffix}`);
20770
+ if (!isFile(candidate))
20771
+ continue;
20772
+ if (suffix !== ".exe" && suffix !== ".com") {
20773
+ throw new Error("Pi PATH Node launcher cannot safely bypass CMD in a UNC directory");
20774
+ }
20775
+ return candidate;
20776
+ }
20777
+ }
20778
+ return process.execPath;
20779
+ }
20780
+ function npmShim(target, pathExtFix = false) {
20781
+ return `@ECHO off
20782
+ GOTO start
20783
+ :find_dp0
20784
+ SET dp0=%~dp0
20785
+ EXIT /b
20786
+ :start
20787
+ SETLOCAL
20788
+ CALL :find_dp0
20789
+
20790
+ IF EXIST "%dp0%\\node.exe" (
20791
+ SET "_prog=%dp0%\\node.exe"
20792
+ ) ELSE (
20793
+ SET "_prog=node"
20794
+ ${pathExtFix ? "" : " SET PATHEXT=%PATHEXT:;.JS;=;%\n"})
20795
+
20796
+ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & ${pathExtFix ? "set PATHEXT=%PATHEXT:;.JS;=;% & " : ""}"%_prog%" "%dp0%\\${target}" %*`;
20797
+ }
20798
+ var standaloneNodeSetup = 'IF EXIST "%LOCALAPPDATA%\\pi-node\\current\\node.exe" SET "node=%LOCALAPPDATA%\\pi-node\\current\\node.exe"';
20799
+ function managedShim(standalone) {
20800
+ return `@ECHO off
20801
+ SETLOCAL
20802
+ SET "node=node"
20803
+ ${standalone ? `${standaloneNodeSetup}
20804
+ ` : ""}"%node%" "%~dp0pi-launcher.js" %*
20805
+ SET "pi_exit_code=%ERRORLEVEL%"
20806
+ IF "%pi_exit_code%"=="9009" (
20807
+ IF "%node%"=="node" (
20808
+ "%SystemRoot%\\System32\\where.exe" /Q node
20809
+ IF ERRORLEVEL 1 GOTO node_missing
20810
+ ) ELSE IF NOT EXIST "%node%" GOTO node_missing
20811
+ )
20812
+ EXIT /B %pi_exit_code%
20813
+ :node_missing
20814
+ ECHO Pi could not find Node.js. Install Node.js 22.19.0 or newer, or rerun the installer at https://pi.dev. 1>&2
20815
+ EXIT /B %pi_exit_code%`;
20816
+ }
20817
+ function piUncNodeInvocation(command, arguments_, environment) {
20818
+ const directory = path15.dirname(command);
20819
+ const source = text3(command);
20820
+ if (path15.isAbsolute(command) && path15.win32.basename(command).toLowerCase() === "pi.cmd" && source !== void 0) {
20821
+ const packageDirectory = path15.join(directory, "node_modules", "@earendil-works", "pi-coding-agent");
20822
+ try {
20823
+ const manifest = JSON.parse(text3(path15.join(packageDirectory, "package.json")) ?? "");
20824
+ if (typeof manifest === "object" && manifest !== null && "name" in manifest && manifest.name === "@earendil-works/pi-coding-agent") {
20825
+ const entry = findPiCliEntry(packageDirectory);
20826
+ const target = entry && path15.relative(directory, entry).replaceAll("/", "\\");
20827
+ if (entry && target && [npmShim(target), npmShim(target, true)].includes(source)) {
20828
+ const localNode = path15.join(directory, "node.exe");
20829
+ return {
20830
+ command: isFile(localNode) ? localNode : nodeOnPath(environment),
20831
+ arguments: [entry, ...arguments_],
20832
+ windowsVerbatimArguments: false
20833
+ };
20834
+ }
20835
+ }
20836
+ } catch {
20837
+ }
20838
+ const launcher = path15.join(directory, "pi-launcher.js");
20839
+ try {
20840
+ const marker = JSON.parse(text3(path15.join(path15.dirname(directory), "install", "managed-install.json")) ?? "");
20841
+ if (typeof marker === "object" && marker !== null && "kind" in marker && marker.kind === "pi-managed-install" && "schemaVersion" in marker && marker.schemaVersion === 1 && "layout" in marker && marker.layout === "releases-v1" && "entrypoint" in marker && typeof marker.entrypoint === "object" && marker.entrypoint !== null && "type" in marker.entrypoint && marker.entrypoint.type === "script" && "path" in marker.entrypoint && typeof marker.entrypoint.path === "string" && path15.isAbsolute(marker.entrypoint.path) && path15.resolve(marker.entrypoint.path).toLowerCase() === path15.resolve(command).toLowerCase() && isFile(launcher) && (source === managedShim(false) || source === managedShim(true))) {
20842
+ const localAppData = environmentValue(environment, "LOCALAPPDATA");
20843
+ const standaloneNode = localAppData ? path15.join(localAppData, "pi-node", "current", "node.exe") : void 0;
20844
+ return {
20845
+ command: source === managedShim(true) && standaloneNode && isFile(standaloneNode) ? standaloneNode : nodeOnPath(environment),
20846
+ // The native launcher reads current-version and sets PI_MANAGED_INSTALL_ROOT itself.
20847
+ arguments: [launcher, ...arguments_],
20848
+ windowsVerbatimArguments: false
20849
+ };
20850
+ }
20851
+ } catch {
20852
+ }
20853
+ }
20854
+ throw new Error("Pi batch launcher cannot safely start in a UNC working directory. Use a standard npm or managed Pi installation, a native Pi executable, or a Host running inside WSL; custom Pi or PATH Node batch launchers are not bypassed.");
20855
+ }
20856
+
20857
+ // dist/pi-content-stream.js
20858
+ var PiContentStreamConflictError = class extends Error {
20859
+ };
20860
+ var PiContentStream = class {
20861
+ kind;
20862
+ #blocks = /* @__PURE__ */ new Map();
20863
+ #indexed;
20864
+ #legacyBlockIndex = 0;
20865
+ #lastEmittedIndex = -Infinity;
20866
+ constructor(kind) {
20867
+ this.kind = kind;
20868
+ }
20869
+ append(index, delta) {
20870
+ const block = this.#block(this.#key(index));
20871
+ if (block.ended && delta.length > 0)
20872
+ this.#conflict();
20873
+ block.received += delta;
20874
+ return this.#flush();
20875
+ }
20876
+ complete(index, content) {
20877
+ this.#finish(this.#key(index), content);
20878
+ if (this.#indexed === false)
20879
+ this.#legacyBlockIndex += 1;
20880
+ return this.#flush();
20881
+ }
20882
+ finalize(blocks) {
20883
+ if (this.#indexed !== true) {
20884
+ blocks = this.#legacyBlockIndex > 0 ? blocks.map(({ text: text4 }, index) => ({ index, text: text4 })) : [{ index: 0, text: blocks.map(({ text: text4 }) => text4).join("") }];
20885
+ }
20886
+ const indices = new Set(blocks.map(({ index }) => index));
20887
+ for (const [index, block] of this.#blocks) {
20888
+ if (indices.has(index))
20889
+ continue;
20890
+ if (block.emitted.length > 0)
20891
+ this.#conflict();
20892
+ this.#blocks.delete(index);
20893
+ }
20894
+ for (const { index, text: text4 } of blocks)
20895
+ this.#finish(index, text4);
20896
+ return this.#flush();
20897
+ }
20898
+ #key(index) {
20899
+ const indexed = typeof index === "number" && Number.isInteger(index) && index >= 0;
20900
+ this.#indexed ??= indexed;
20901
+ if (!this.#indexed)
20902
+ return this.#legacyBlockIndex;
20903
+ if (!indexed)
20904
+ this.#conflict();
20905
+ return index;
20906
+ }
20907
+ #block(index) {
20908
+ let block = this.#blocks.get(index);
20909
+ if (!block) {
20910
+ block = { received: "", emitted: "", ended: false };
20911
+ this.#blocks.set(index, block);
20912
+ }
20913
+ return block;
20914
+ }
20915
+ #finish(index, content) {
20916
+ const block = this.#block(index);
20917
+ if (!content.startsWith(block.emitted))
20918
+ this.#conflict();
20919
+ block.received = content;
20920
+ block.ended = true;
20921
+ }
20922
+ #flush() {
20923
+ let delta = "";
20924
+ for (const [index, block] of [...this.#blocks].sort(([left], [right]) => left - right)) {
20925
+ const visible = this.kind === "reasoning" && !block.ended ? block.received.replace(/[\r\n]+$/u, "") : block.received;
20926
+ if (!visible.startsWith(block.emitted))
20927
+ this.#conflict();
20928
+ const suffix = visible.slice(block.emitted.length);
20929
+ if (suffix.length > 0) {
20930
+ if (index < this.#lastEmittedIndex)
20931
+ this.#conflict();
20932
+ this.#lastEmittedIndex = index;
20933
+ block.emitted = visible;
20934
+ delta += suffix;
20935
+ }
20936
+ if (!block.ended)
20937
+ break;
20938
+ }
20939
+ return delta;
20940
+ }
20941
+ #conflict() {
20942
+ throw new PiContentStreamConflictError(`Pi ${this.kind} final content conflicts with already streamed content`);
20943
+ }
20944
+ };
20945
+
20084
20946
  // dist/pi-subagent-rpc.js
20085
- import { randomUUID as randomUUID4 } from "node:crypto";
20947
+ import { randomUUID as randomUUID5 } from "node:crypto";
20086
20948
  var PiSubagentRpc = class {
20087
20949
  send;
20088
20950
  timeoutMs;
@@ -20124,7 +20986,7 @@ var PiSubagentRpc = class {
20124
20986
  if (!Array.isArray(data?.commands) || !data.commands.some((command) => command?.name === "subagents-inspect-rpc" && command.source === "extension")) {
20125
20987
  throw new Error("Installed Pi has no pi-subagents Host inspection command");
20126
20988
  }
20127
- const requestId = randomUUID4();
20989
+ const requestId = randomUUID5();
20128
20990
  const reply = new Promise((resolve, reject) => {
20129
20991
  const timer = setTimeout(() => {
20130
20992
  this.#pending.delete(requestId);
@@ -20158,6 +21020,12 @@ var PiSubagentRpc = class {
20158
21020
  };
20159
21021
 
20160
21022
  // dist/pi-rpc-session.js
21023
+ var PiRpcBusyError = class extends Error {
21024
+ constructor() {
21025
+ super("Pi is still running a native Turn; wait for completion or use the active Turn's stop/steer action");
21026
+ this.name = "PiRpcBusyError";
21027
+ }
21028
+ };
20161
21029
  var PiRpcFaultError = class extends Error {
20162
21030
  kind;
20163
21031
  diagnostic;
@@ -20176,8 +21044,20 @@ var PiRpcUnsupportedCommandError = class extends Error {
20176
21044
  this.name = "PiRpcUnsupportedCommandError";
20177
21045
  }
20178
21046
  };
21047
+ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
21048
+ "get_state",
21049
+ "get_commands",
21050
+ "get_entries",
21051
+ "get_session_stats",
21052
+ "get_available_models",
21053
+ "get_available_thinking_levels"
21054
+ ]);
21055
+ var MAX_EXPIRED_IDS = 64;
21056
+ function nativeMessageIdentity(active) {
21057
+ return active.assistantNativeMessageIdentity ? { nativeMessageIdentity: active.assistantNativeMessageIdentity } : {};
21058
+ }
20179
21059
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
20180
- function isRecord8(value) {
21060
+ function isRecord9(value) {
20181
21061
  return typeof value === "object" && value !== null && !Array.isArray(value);
20182
21062
  }
20183
21063
  function message2(value) {
@@ -20189,13 +21069,13 @@ function nonBlankString(value) {
20189
21069
  function parseNativeModel(value, context) {
20190
21070
  if (value === null || value === void 0)
20191
21071
  return null;
20192
- if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
21072
+ if (!isRecord9(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
20193
21073
  throw new PiRpcFaultError("protocolError", `Pi RPC returned an invalid ${context} Model`);
20194
21074
  }
20195
21075
  return { provider: value.provider, id: value.id };
20196
21076
  }
20197
21077
  function sessionStateData(response) {
20198
- const data = isRecord8(response.data) ? response.data : null;
21078
+ const data = isRecord9(response.data) ? response.data : null;
20199
21079
  if (!data)
20200
21080
  throw new PiRpcFaultError("protocolError", "Pi RPC state response has no data");
20201
21081
  return data;
@@ -20203,6 +21083,7 @@ function sessionStateData(response) {
20203
21083
  function parseSessionState(response) {
20204
21084
  const data = sessionStateData(response);
20205
21085
  const model2 = parseNativeModel(data.model, "state");
21086
+ const modelReasoning = isRecord9(data.model) && typeof data.model.reasoning === "boolean" ? data.model.reasoning : null;
20206
21087
  if (!nonBlankString(data.sessionId)) {
20207
21088
  throw new PiRpcFaultError("protocolError", "Pi RPC state has no stable Session identity");
20208
21089
  }
@@ -20215,6 +21096,7 @@ function parseSessionState(response) {
20215
21096
  sessionFile: typeof data.sessionFile === "string" ? data.sessionFile : null,
20216
21097
  provider: model2?.provider ?? null,
20217
21098
  modelId: model2?.id ?? null,
21099
+ ...modelReasoning === null ? {} : { modelReasoning },
20218
21100
  thinkingLevel: thinkingLevel?.data ?? null,
20219
21101
  contextUsage: optionalPiStateContextUsage(data.contextUsage)
20220
21102
  };
@@ -20227,13 +21109,13 @@ function parseSessionStreaming(response) {
20227
21109
  return isStreaming;
20228
21110
  }
20229
21111
  function parseSessionHistory(response) {
20230
- const data = isRecord8(response.data) ? response.data : null;
21112
+ const data = isRecord9(response.data) ? response.data : null;
20231
21113
  if (!data || !Array.isArray(data.entries)) {
20232
21114
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response has no Entries");
20233
21115
  }
20234
21116
  const entries = data.entries.map((entry) => {
20235
21117
  const parsed = jsonValueSchema.safeParse(entry);
20236
- if (!parsed.success || !isRecord8(parsed.data)) {
21118
+ if (!parsed.success || !isRecord9(parsed.data)) {
20237
21119
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response contains an invalid Entry");
20238
21120
  }
20239
21121
  return parsed.data;
@@ -20244,7 +21126,7 @@ function parseSessionHistory(response) {
20244
21126
  return { entries, leafId: data.leafId };
20245
21127
  }
20246
21128
  function parseAvailableThinkingLevels(response) {
20247
- const data = isRecord8(response.data) ? response.data : null;
21129
+ const data = isRecord9(response.data) ? response.data : null;
20248
21130
  if (!data || !Array.isArray(data.levels) || data.levels.length === 0) {
20249
21131
  throw new PiRpcFaultError("protocolError", "Pi RPC Thinking catalog response has no levels");
20250
21132
  }
@@ -20261,13 +21143,13 @@ function parseAvailableThinkingLevels(response) {
20261
21143
  return levels;
20262
21144
  }
20263
21145
  function parseAvailableModels(response) {
20264
- const data = isRecord8(response.data) ? response.data : null;
21146
+ const data = isRecord9(response.data) ? response.data : null;
20265
21147
  if (!data || !Array.isArray(data.models)) {
20266
21148
  throw new PiRpcFaultError("protocolError", "Pi RPC Model catalog response has no models");
20267
21149
  }
20268
21150
  return data.models.map((model2) => {
20269
21151
  const parsed = parseNativeModel(model2, "catalog");
20270
- if (!parsed || !isRecord8(model2) || typeof model2.reasoning !== "boolean") {
21152
+ if (!parsed || !isRecord9(model2) || typeof model2.reasoning !== "boolean") {
20271
21153
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
20272
21154
  }
20273
21155
  return {
@@ -20278,32 +21160,32 @@ function parseAvailableModels(response) {
20278
21160
  });
20279
21161
  }
20280
21162
  function assistantText(value) {
20281
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21163
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20282
21164
  return null;
20283
- return value.content.filter((content) => isRecord8(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
21165
+ return value.content.filter((content) => isRecord9(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
20284
21166
  }
20285
21167
  function assistantMessageId(value) {
20286
- if (!isRecord8(value) || value.role !== "assistant")
21168
+ if (!isRecord9(value) || value.role !== "assistant")
20287
21169
  return null;
20288
21170
  return nonBlankString(value.responseId) ? value.responseId : null;
20289
21171
  }
20290
21172
  function extractReasoningText(content) {
20291
- if (!isRecord8(content))
21173
+ if (!isRecord9(content))
20292
21174
  return null;
20293
21175
  const type = String(content.type ?? "");
20294
21176
  if (type === "thinking" || type === "reasoning" || type === "thought") {
20295
- const text2 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
20296
- return typeof text2 === "string" ? text2 : null;
21177
+ const text4 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
21178
+ return typeof text4 === "string" ? text4 : null;
20297
21179
  }
20298
21180
  return null;
20299
21181
  }
20300
21182
  function assistantReasoning(value) {
20301
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21183
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20302
21184
  return null;
20303
- return value.content.map(extractReasoningText).filter((text2) => typeof text2 === "string").join("");
21185
+ return value.content.map(extractReasoningText).filter((text4) => typeof text4 === "string").join("");
20304
21186
  }
20305
21187
  function assistantFailure(value) {
20306
- if (!isRecord8(value) || value.role !== "assistant")
21188
+ if (!isRecord9(value) || value.role !== "assistant")
20307
21189
  return void 0;
20308
21190
  if (value.stopReason !== "error" && value.stopReason !== "aborted")
20309
21191
  return null;
@@ -20323,7 +21205,7 @@ function signalProcessTree(child, signal) {
20323
21205
  try {
20324
21206
  process.kill(-child.pid, signal);
20325
21207
  } catch (error51) {
20326
- if (!isRecord8(error51) || error51.code !== "ESRCH")
21208
+ if (!isRecord9(error51) || error51.code !== "ESRCH")
20327
21209
  throw error51;
20328
21210
  }
20329
21211
  }
@@ -20360,16 +21242,24 @@ function piRpcProcessCommand(options, dependencies = {}) {
20360
21242
  const thinkingArguments = options.emptySessionConfiguration ? ["--thinking", options.emptySessionConfiguration.thinkingLevel] : [];
20361
21243
  const arguments_ = [
20362
21244
  ...options.fastExtension ? ["--extension", options.fastExtension] : [],
21245
+ ...options.subagentExtension ? ["--extension", options.subagentExtension] : [],
20363
21246
  "--mode",
20364
21247
  "rpc",
20365
21248
  ...modelArguments,
20366
21249
  ...thinkingArguments,
20367
21250
  ...sessionArguments
20368
21251
  ];
20369
- const extension = path14.win32.extname(command).toLowerCase();
21252
+ const extension = path16.win32.extname(command).toLowerCase();
20370
21253
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
20371
21254
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
20372
21255
  }
21256
+ if (isWindowsUncDirectory(options.cwd)) {
21257
+ try {
21258
+ return piUncNodeInvocation(command, arguments_, options.environment);
21259
+ } catch (error51) {
21260
+ throw new PiRpcFaultError("unavailable", message2(error51));
21261
+ }
21262
+ }
20373
21263
  const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
20374
21264
  const commandLine = [command, ...arguments_].map(quote).join(" ");
20375
21265
  return {
@@ -20395,10 +21285,20 @@ var PiRpcSession = class {
20395
21285
  #options;
20396
21286
  #processAdapter;
20397
21287
  #activeTurn = null;
21288
+ #runGeneration = 0;
21289
+ #deferredRunFrames = [];
21290
+ #deferredRunBytes = 0;
21291
+ #runWaiters = /* @__PURE__ */ new Set();
21292
+ #messageTimestampCounts = /* @__PURE__ */ new Map();
20398
21293
  #autonomousTurnHandler = null;
21294
+ #autonomousLifecycleHandler = null;
20399
21295
  #usageHandler = null;
20400
21296
  #usageRequestStartedAtMs = null;
20401
- #buffer = Buffer.alloc(0);
21297
+ // Pieces of the unterminated frame; joined once at its newline so a large frame (a long
21298
+ // Session's get_entries) costs linear rather than quadratic copying on the Host event loop.
21299
+ #buffer = [];
21300
+ // Ids whose read-only command timed out; Pi may still answer them late.
21301
+ #expired = /* @__PURE__ */ new Set();
20402
21302
  #child = null;
20403
21303
  #closed = false;
20404
21304
  #closePromise = null;
@@ -20411,8 +21311,15 @@ var PiRpcSession = class {
20411
21311
  #fastAcknowledgement = null;
20412
21312
  #latestCacheHitRatePercent;
20413
21313
  #manualCompaction = null;
21314
+ #noticeOccurrences = /* @__PURE__ */ new Map();
21315
+ #seenNoticeFrames = /* @__PURE__ */ new Set();
21316
+ #pendingProgress = [];
21317
+ #omittedProgress = 0;
21318
+ #extensionStatuses = /* @__PURE__ */ new Map();
20414
21319
  #stderrTail = "";
20415
21320
  #subagents;
21321
+ #gotgenesHandler;
21322
+ #gotgenesLatest;
20416
21323
  constructor(options, processAdapter = nodeProcessAdapter) {
20417
21324
  if (options.sessionFile && options.forkSessionFile) {
20418
21325
  throw new Error("Pi RPC cannot combine Session resume and Fork startup");
@@ -20442,9 +21349,17 @@ var PiRpcSession = class {
20442
21349
  get stderrTail() {
20443
21350
  return this.#stderrTail;
20444
21351
  }
21352
+ get isBusy() {
21353
+ return this.#activeTurn !== null || this.#manualCompaction !== null || this.#compactionActive || this.#deferredRunFrames.length > 0;
21354
+ }
20445
21355
  setSubagentStatusHandler(handler) {
20446
21356
  this.#subagents.setHandler(handler);
20447
21357
  }
21358
+ setGotgenesStatusHandler(handler) {
21359
+ this.#gotgenesHandler = handler;
21360
+ if (this.#gotgenesLatest)
21361
+ handler(this.#gotgenesLatest, "idle");
21362
+ }
20448
21363
  inspectSubagent(id) {
20449
21364
  return this.#subagents.inspect(id);
20450
21365
  }
@@ -20454,17 +21369,18 @@ var PiRpcSession = class {
20454
21369
  /** Every finished assistant message is one model request, with or without an active Turn. */
20455
21370
  #observeUsage(value) {
20456
21371
  if (value.type === "message_start") {
20457
- this.#usageRequestStartedAtMs = null;
21372
+ if (isRecord9(value.message) && value.message.role === "assistant")
21373
+ this.#usageRequestStartedAtMs = null;
20458
21374
  return;
20459
21375
  }
20460
21376
  if (value.type === "message_update") {
20461
21377
  const event = value.assistantMessageEvent;
20462
- if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
21378
+ if (this.#usageRequestStartedAtMs === null && isRecord9(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
20463
21379
  this.#usageRequestStartedAtMs = Date.now();
20464
21380
  }
20465
21381
  return;
20466
21382
  }
20467
- if (value.type === "message_end" && isRecord8(value.message)) {
21383
+ if (value.type === "message_end" && isRecord9(value.message)) {
20468
21384
  if (value.message.role !== "assistant")
20469
21385
  return;
20470
21386
  const startedAtMs = this.#usageRequestStartedAtMs;
@@ -20478,14 +21394,21 @@ var PiRpcSession = class {
20478
21394
  }
20479
21395
  setAutonomousTurnHandler(handler) {
20480
21396
  this.#autonomousTurnHandler = handler;
21397
+ this.#autonomousLifecycleHandler = null;
21398
+ }
21399
+ setAutonomousTurnLifecycleHandler(handler) {
21400
+ this.#autonomousLifecycleHandler = handler;
21401
+ this.#autonomousTurnHandler = null;
20481
21402
  }
20482
21403
  async start() {
20483
21404
  if (this.#child || this.#closed)
20484
21405
  throw new Error("Pi RPC Session cannot be started twice");
20485
21406
  const fastExtension = this.#processAdapter === nodeProcessAdapter ? await ensurePiFastExtension({ ...process.env, ...this.#options.environment }) : void 0;
21407
+ const subagentExtension = this.#processAdapter === nodeProcessAdapter ? await ensureGotgenesExtension({ ...process.env, ...this.#options.environment }) : void 0;
20486
21408
  const child = this.#processAdapter.spawn({
20487
21409
  cwd: this.#options.cwd,
20488
21410
  ...fastExtension ? { fastExtension } : {},
21411
+ ...subagentExtension ? { subagentExtension } : {},
20489
21412
  ...this.#options.command ? { command: this.#options.command } : {},
20490
21413
  environment: withNodeRuntimeOnPath({
20491
21414
  ...process.env,
@@ -20509,7 +21432,7 @@ var PiRpcSession = class {
20509
21432
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
20510
21433
  });
20511
21434
  child.once("error", (error51) => {
20512
- const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
21435
+ const kind = isRecord9(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
20513
21436
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
20514
21437
  });
20515
21438
  child.once("exit", (code, signal) => {
@@ -20526,6 +21449,7 @@ var PiRpcSession = class {
20526
21449
  ]);
20527
21450
  try {
20528
21451
  this.#state = parseSessionState(await this.#send("get_state", {}));
21452
+ await this.getEntries();
20529
21453
  } catch (error51) {
20530
21454
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("unavailable", `Pi RPC state unavailable: ${message2(error51)}`);
20531
21455
  this.#fail(fault);
@@ -20539,7 +21463,12 @@ var PiRpcSession = class {
20539
21463
  }
20540
21464
  async getEntries() {
20541
21465
  try {
20542
- return parseSessionHistory(await this.#send("get_entries", {}));
21466
+ const history = parseSessionHistory(await this.#send("get_entries", {}));
21467
+ if (!this.#activeTurn && this.#state) {
21468
+ this.#messageTimestampCounts = piHistoryMessageIdentities(this.state.sessionId, activePiEntries(history)).timestampCounts;
21469
+ this.#noticeOccurrences = piHistoryNotices(this.state.sessionId, activePiEntries(history)).occurrences;
21470
+ }
21471
+ return history;
20543
21472
  } catch (error51) {
20544
21473
  if (error51 instanceof PiRpcFaultError)
20545
21474
  this.#fail(error51);
@@ -20599,11 +21528,15 @@ var PiRpcSession = class {
20599
21528
  if (entryId.length === 0)
20600
21529
  throw new Error("Pi Fork Entry ID must not be empty");
20601
21530
  await this.#send("fork", { entryId });
20602
- return this.#refreshState("Fork");
21531
+ const state2 = await this.#refreshState("Fork");
21532
+ await this.getEntries();
21533
+ return state2;
20603
21534
  }
20604
21535
  async clone() {
20605
21536
  await this.#send("clone", {});
20606
- return this.#refreshState("Clone");
21537
+ const state2 = await this.#refreshState("Clone");
21538
+ await this.getEntries();
21539
+ return state2;
20607
21540
  }
20608
21541
  verifySessionCwd(expectedCwd) {
20609
21542
  return verifyPiSessionCwd({
@@ -20640,7 +21573,7 @@ var PiRpcSession = class {
20640
21573
  return this.state;
20641
21574
  if (!await this.supportsFastMode())
20642
21575
  throw new Error("Installed Pi does not support the Host Fast extension");
20643
- const nonce = randomUUID5();
21576
+ const nonce = randomUUID6();
20644
21577
  const mode = enabled ? "on" : "off";
20645
21578
  const acknowledgement = { message: `${PI_FAST_ACK}${nonce}:${mode}`, received: false };
20646
21579
  this.#fastAcknowledgement = acknowledgement;
@@ -20680,22 +21613,27 @@ var PiRpcSession = class {
20680
21613
  throw fault;
20681
21614
  }
20682
21615
  }
20683
- async runTurn(text2, onEvent) {
21616
+ async runTurn(text4, onEvent) {
20684
21617
  if (!this.#child || !this.#state || this.#closed || this.#failed) {
20685
21618
  throw new Error("Pi RPC Session is unavailable");
20686
21619
  }
20687
- if (this.#activeTurn)
20688
- throw new Error("Pi RPC Session already has an active Turn");
20689
- if (text2.length === 0)
21620
+ if (this.isBusy)
21621
+ throw new PiRpcBusyError();
21622
+ if (text4.length === 0)
20690
21623
  throw new Error("Pi text Turn must not be empty");
20691
21624
  const settled = new Promise((resolve, reject) => {
20692
21625
  this.#activeTurn = {
20693
21626
  origin: "requested",
21627
+ autonomousRunId: null,
21628
+ runGeneration: this.#runGeneration,
20694
21629
  autonomousEvents: null,
20695
21630
  nativeTurnKey: null,
20696
21631
  nativeCancellationObserved: false,
20697
21632
  text: "",
20698
21633
  assistantMessageId: null,
21634
+ assistantNativeMessageIdentity: void 0,
21635
+ textStream: new PiContentStream("text"),
21636
+ reasoningStream: new PiContentStream("reasoning"),
20699
21637
  sawStreamedMessageText: false,
20700
21638
  sawStreamedMessageReasoning: false,
20701
21639
  lastFinalizedMessageText: null,
@@ -20715,7 +21653,8 @@ var PiRpcSession = class {
20715
21653
  };
20716
21654
  });
20717
21655
  try {
20718
- await this.#send("prompt", { message: text2 });
21656
+ this.#drainProgress(onEvent);
21657
+ await this.#send("prompt", { message: text4 });
20719
21658
  } catch (error51) {
20720
21659
  this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
20721
21660
  }
@@ -20787,6 +21726,10 @@ var PiRpcSession = class {
20787
21726
  void this.close().catch(() => void 0);
20788
21727
  }
20789
21728
  close() {
21729
+ this.#pendingProgress = [];
21730
+ this.#omittedProgress = 0;
21731
+ this.#seenNoticeFrames.clear();
21732
+ this.#extensionStatuses.clear();
20790
21733
  if (!this.#closed) {
20791
21734
  this.#closed = true;
20792
21735
  this.#rejectAll(new Error("Pi RPC Session closed"));
@@ -20811,24 +21754,34 @@ var PiRpcSession = class {
20811
21754
  }
20812
21755
  }
20813
21756
  #push(chunk) {
20814
- this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
20815
- let newline = this.#buffer.indexOf(10);
21757
+ let rest = chunk;
21758
+ let newline = rest.indexOf(10);
20816
21759
  while (newline >= 0) {
20817
- const frame = this.#buffer.subarray(0, newline);
20818
- this.#buffer = this.#buffer.subarray(newline + 1);
21760
+ const tail = rest.subarray(0, newline);
21761
+ const frame = this.#buffer.length === 0 ? tail : Buffer.concat([...this.#buffer, tail]);
21762
+ this.#buffer = [];
21763
+ rest = rest.subarray(newline + 1);
20819
21764
  try {
20820
21765
  const value = JSON.parse(textDecoder.decode(frame));
20821
- if (!isRecord8(value) || typeof value.type !== "string") {
21766
+ if (!isRecord9(value) || typeof value.type !== "string") {
20822
21767
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid envelope");
20823
21768
  }
20824
21769
  this.#handle(value);
20825
21770
  } catch (error51) {
20826
- this.#fail(error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi RPC returned invalid JSONL: ${message2(error51)}`));
21771
+ this.#fail(error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", error51 instanceof PiContentStreamConflictError ? error51.message : `Pi RPC returned invalid JSONL: ${message2(error51)}`));
20827
21772
  }
20828
- newline = this.#buffer.indexOf(10);
21773
+ newline = rest.indexOf(10);
20829
21774
  }
21775
+ if (rest.length !== 0)
21776
+ this.#buffer.push(rest);
20830
21777
  }
20831
- #handle(value) {
21778
+ #handle(value, observedGeneration) {
21779
+ if (observedGeneration === void 0 && value.type === "agent_start") {
21780
+ this.#runGeneration += 1;
21781
+ for (const waiter of this.#runWaiters)
21782
+ waiter.check();
21783
+ }
21784
+ const generation = observedGeneration ?? this.#runGeneration;
20832
21785
  if (value.type === "extension_ui_request" && value.method === "notify" && typeof value.message === "string" && value.message.startsWith(PI_FAST_ACK)) {
20833
21786
  if (this.#fastAcknowledgement?.message === value.message)
20834
21787
  this.#fastAcknowledgement.received = true;
@@ -20842,6 +21795,33 @@ var PiRpcSession = class {
20842
21795
  }
20843
21796
  if (this.#subagents.handle(value))
20844
21797
  return;
21798
+ const settling = this.#activeTurn;
21799
+ if (settling && settling.settlement !== "pending" && generation > settling.runGeneration) {
21800
+ this.#deferredRunBytes += Buffer.byteLength(JSON.stringify(value));
21801
+ if (this.#deferredRunBytes > 8 * 1024 * 1024) {
21802
+ this.#fail(new PiRpcFaultError("protocolError", "Pi deferred run exceeded its event buffer bound"));
21803
+ return;
21804
+ }
21805
+ this.#deferredRunFrames.push({ value, generation });
21806
+ return;
21807
+ }
21808
+ if (value.type === "agent_start") {
21809
+ if (this.#activeTurn)
21810
+ this.#activeTurn.runGeneration = generation;
21811
+ else if (!this.#manualCompaction && !this.#compactionActive && (this.#autonomousTurnHandler || this.#autonomousLifecycleHandler))
21812
+ this.#startAutonomousTurn(void 0, generation);
21813
+ return;
21814
+ }
21815
+ if (value.type === "extension_ui_request" && value.method === "setWidget" && value.widgetKey === GOTGENES_WIDGET) {
21816
+ const records = parseGotgenesWidget(value);
21817
+ if (records) {
21818
+ this.#gotgenesLatest = records;
21819
+ this.#gotgenesHandler?.(records, this.#activeTurn?.origin ?? "idle");
21820
+ }
21821
+ return;
21822
+ }
21823
+ if (this.#handleProgress(value))
21824
+ return;
20845
21825
  this.#observeUsage(value);
20846
21826
  if (value.type === "compaction_start") {
20847
21827
  this.#compactionActive = true;
@@ -20865,7 +21845,7 @@ var PiRpcSession = class {
20865
21845
  this.#armCommandTimeout(id, pending);
20866
21846
  }
20867
21847
  }
20868
- const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
21848
+ const outcome = value.aborted === true ? "cancelled" : isRecord9(value.result) ? "succeeded" : "failed";
20869
21849
  const event = {
20870
21850
  type: "compaction.completed",
20871
21851
  outcome,
@@ -20882,8 +21862,8 @@ var PiRpcSession = class {
20882
21862
  return;
20883
21863
  }
20884
21864
  let active = this.#activeTurn;
20885
- if (!active && !this.#manualCompaction && !this.#compactionActive && this.#autonomousTurnHandler && value.type === "message_start" && assistantText(value.message) !== null) {
20886
- active = this.#startAutonomousTurn(value.message);
21865
+ if (!active && !this.#manualCompaction && !this.#compactionActive && (this.#autonomousTurnHandler || this.#autonomousLifecycleHandler) && value.type === "message_start" && assistantText(value.message) !== null) {
21866
+ active = this.#startAutonomousTurn(value.message, generation);
20887
21867
  }
20888
21868
  if (!active) {
20889
21869
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
@@ -20903,22 +21883,26 @@ var PiRpcSession = class {
20903
21883
  this.#startAssistantMessage(active, value.message);
20904
21884
  return;
20905
21885
  }
20906
- if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
21886
+ if (value.type === "message_update" && isRecord9(value.assistantMessageEvent)) {
20907
21887
  const event = value.assistantMessageEvent;
20908
21888
  const eventType = String(event.type ?? "");
20909
21889
  const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
20910
21890
  const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
20911
- 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 : isRecord8(event.delta) && typeof event.delta.thinking === "string" ? event.delta.thinking : isRecord8(event.delta) && typeof event.delta.text === "string" ? event.delta.text : null;
20912
- if (isThinking && delta !== null && delta.length > 0) {
20913
- const messageId = this.#ensureAssistantMessage(active, value.message);
20914
- active.reasoningMessageOpen = true;
20915
- active.sawStreamedMessageReasoning = true;
20916
- active.onEvent({ type: "reasoning.delta", messageId, delta });
20917
- } else if (isText && delta !== null && delta.length > 0) {
20918
- const messageId = this.#ensureAssistantMessage(active, value.message);
20919
- active.text += delta;
20920
- active.sawStreamedMessageText = true;
20921
- active.onEvent({ type: "text.delta", messageId, delta });
21891
+ 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 : isRecord9(event.delta) && typeof event.delta.thinking === "string" ? event.delta.thinking : isRecord9(event.delta) && typeof event.delta.text === "string" ? event.delta.text : null;
21892
+ const endingReasoning = eventType === "thinking_end" || eventType === "reasoning_end";
21893
+ const endingText = eventType === "text_end";
21894
+ if ((endingReasoning || endingText) && typeof event.content === "string") {
21895
+ this.#ensureAssistantMessage(active, value.message);
21896
+ const stream = endingReasoning ? active.reasoningStream : active.textStream;
21897
+ this.#emitContent(active, endingReasoning, stream.complete(event.contentIndex, event.content));
21898
+ } else if ((isThinking || isText) && delta !== null && delta.length > 0) {
21899
+ this.#ensureAssistantMessage(active, value.message);
21900
+ if (isThinking)
21901
+ active.sawStreamedMessageReasoning = true;
21902
+ else
21903
+ active.sawStreamedMessageText = true;
21904
+ const stream = isThinking ? active.reasoningStream : active.textStream;
21905
+ this.#emitContent(active, isThinking, stream.append(event.contentIndex, delta));
20922
21906
  } else if (event.type === "error") {
20923
21907
  this.#ensureAssistantMessage(active, value.message);
20924
21908
  active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Pi assistant message failed");
@@ -20949,25 +21933,36 @@ var PiRpcSession = class {
20949
21933
  if (active.settlement !== "pending")
20950
21934
  return;
20951
21935
  active.settlement = "confirming";
20952
- void this.#confirmSettledTurn(active);
21936
+ void this.#confirmSettledTurn(active, active.runGeneration);
20953
21937
  }
20954
21938
  }
20955
- #startAutonomousTurn(value) {
21939
+ #startAutonomousTurn(value, generation) {
20956
21940
  const events = [];
21941
+ const runId = randomUUID6();
20957
21942
  const active = {
20958
21943
  origin: "autonomous",
21944
+ autonomousRunId: runId,
21945
+ runGeneration: generation,
20959
21946
  autonomousEvents: events,
20960
- ...isRecord8(value) ? { autonomousMessage: value } : {},
21947
+ ...isRecord9(value) ? { autonomousMessage: value } : {},
20961
21948
  nativeTurnKey: null,
20962
21949
  nativeCancellationObserved: false,
20963
21950
  text: "",
20964
21951
  assistantMessageId: null,
21952
+ assistantNativeMessageIdentity: void 0,
21953
+ textStream: new PiContentStream("text"),
21954
+ reasoningStream: new PiContentStream("reasoning"),
20965
21955
  sawStreamedMessageText: false,
20966
21956
  sawStreamedMessageReasoning: false,
20967
21957
  lastFinalizedMessageText: null,
20968
21958
  lastFinalizedMessageReasoning: null,
20969
21959
  reasoningMessageOpen: false,
20970
- onEvent: (event) => events.push(event),
21960
+ onEvent: (event) => {
21961
+ if (this.#autonomousLifecycleHandler)
21962
+ this.#autonomousLifecycleHandler({ type: "event", runId, event });
21963
+ else
21964
+ events.push(event);
21965
+ },
20971
21966
  resolve: () => void 0,
20972
21967
  reject: () => void 0,
20973
21968
  failure: null,
@@ -20980,19 +21975,109 @@ var PiRpcSession = class {
20980
21975
  abortPromise: null
20981
21976
  };
20982
21977
  this.#activeTurn = active;
21978
+ this.#autonomousLifecycleHandler?.({ type: "started", runId });
21979
+ this.#drainProgress(active.onEvent);
20983
21980
  return active;
20984
21981
  }
21982
+ #handleProgress(value) {
21983
+ if ((value.type === "message_start" || value.type === "message_end") && isRecord9(value.message) && value.message.role === "custom") {
21984
+ if (value.type !== "message_end" || !this.#state)
21985
+ return true;
21986
+ const key = piCustomNoticeKey(value.message);
21987
+ if (!key)
21988
+ return true;
21989
+ const timestamp = value.message.timestamp;
21990
+ if ((typeof timestamp === "number" || typeof timestamp === "string") && !this.#acceptNoticeFrame(JSON.stringify([key, timestamp])))
21991
+ return true;
21992
+ const progress = piCustomNotice(value.message, this.state.sessionId, this.#noticeOccurrences);
21993
+ if (progress)
21994
+ this.#publishProgress(progress);
21995
+ return true;
21996
+ }
21997
+ if (value.type === "extension_ui_request" && value.method === "setStatus") {
21998
+ if (typeof value.statusKey !== "string")
21999
+ return true;
22000
+ if (typeof value.statusText !== "string" || !value.statusText.trim()) {
22001
+ if (!this.#extensionStatuses.has(value.statusKey))
22002
+ return true;
22003
+ this.#extensionStatuses.delete(value.statusKey);
22004
+ } else {
22005
+ if (this.#extensionStatuses.get(value.statusKey) === value.statusText)
22006
+ return true;
22007
+ this.#extensionStatuses.set(value.statusKey, value.statusText);
22008
+ }
22009
+ return true;
22010
+ }
22011
+ const text4 = piStatusText(value);
22012
+ if (!text4)
22013
+ return false;
22014
+ if (value.type === "extension_ui_request" && typeof value.id === "string" && !this.#acceptNoticeFrame(JSON.stringify([value.type, value.id])))
22015
+ return true;
22016
+ this.#publishProgress({
22017
+ type: "progress.message",
22018
+ itemId: hostItemIdSchema.parse(`pi-progress-${randomUUID6()}`),
22019
+ text: text4
22020
+ }, value.method === "setStatus" && typeof value.statusKey === "string" ? value.statusKey : void 0);
22021
+ return true;
22022
+ }
22023
+ #acceptNoticeFrame(key) {
22024
+ if (this.#seenNoticeFrames.has(key))
22025
+ return false;
22026
+ this.#seenNoticeFrames.add(key);
22027
+ if (this.#seenNoticeFrames.size > 512)
22028
+ this.#seenNoticeFrames.delete(this.#seenNoticeFrames.values().next().value);
22029
+ return true;
22030
+ }
22031
+ #publishProgress(progress, statusKey) {
22032
+ if (this.#activeTurn?.settlement === "pending") {
22033
+ this.#activeTurn.onEvent(progress);
22034
+ return;
22035
+ }
22036
+ if (statusKey !== void 0) {
22037
+ const previous = this.#pendingProgress.findIndex((pending) => pending.statusKey === statusKey);
22038
+ if (previous >= 0)
22039
+ this.#pendingProgress.splice(previous, 1);
22040
+ }
22041
+ if (this.#pendingProgress.length >= 128) {
22042
+ this.#pendingProgress.shift();
22043
+ this.#omittedProgress += 1;
22044
+ }
22045
+ this.#pendingProgress.push({
22046
+ event: progress,
22047
+ ...statusKey !== void 0 ? { statusKey } : {}
22048
+ });
22049
+ }
22050
+ #drainProgress(onEvent) {
22051
+ if (this.#omittedProgress > 0) {
22052
+ onEvent({
22053
+ type: "progress.message",
22054
+ itemId: hostItemIdSchema.parse(`pi-progress-${randomUUID6()}`),
22055
+ text: `Pi notifications: ${this.#omittedProgress} earlier updates were not retained while idle. Persisted notifications remain available in conversation history.`
22056
+ });
22057
+ this.#omittedProgress = 0;
22058
+ }
22059
+ for (const pending of this.#pendingProgress.splice(0))
22060
+ onEvent(pending.event);
22061
+ }
20985
22062
  #emitAutonomousTurn(active, result) {
20986
22063
  const handler = this.#autonomousTurnHandler;
20987
- if (active.origin !== "autonomous" || !active.autonomousEvents || !handler) {
22064
+ if (active.origin !== "autonomous" || !active.autonomousEvents || !active.autonomousRunId) {
20988
22065
  return;
20989
22066
  }
20990
22067
  try {
20991
- handler({
22068
+ const turn = {
20992
22069
  nativeTurnKey: active.nativeTurnKey,
20993
22070
  events: [...active.autonomousEvents],
20994
22071
  result
20995
- });
22072
+ };
22073
+ if (this.#autonomousLifecycleHandler)
22074
+ this.#autonomousLifecycleHandler({
22075
+ type: "completed",
22076
+ runId: active.autonomousRunId,
22077
+ turn
22078
+ });
22079
+ else
22080
+ handler?.(turn);
20996
22081
  } catch (error51) {
20997
22082
  this.#fail(new PiRpcFaultError("protocolError", `Pi autonomous Turn handler failed: ${message2(error51)}`));
20998
22083
  }
@@ -21088,6 +22173,8 @@ var PiRpcSession = class {
21088
22173
  return;
21089
22174
  }
21090
22175
  const pending = this.#pending.get(id);
22176
+ if (!pending && this.#expired.delete(id))
22177
+ return;
21091
22178
  if (!pending) {
21092
22179
  this.#fail(new PiRpcFaultError("protocolError", "Pi RPC response id is not pending"));
21093
22180
  return;
@@ -21157,31 +22244,73 @@ var PiRpcSession = class {
21157
22244
  isError: value.isError === true
21158
22245
  });
21159
22246
  }
21160
- async #confirmSettledTurn(active) {
22247
+ #isSettlementCurrent(active, generation) {
22248
+ return this.#activeTurn === active && active.runGeneration === generation && active.settlement === "confirming";
22249
+ }
22250
+ #waitForNextRun(generation) {
22251
+ if (this.#runGeneration > generation)
22252
+ return Promise.resolve();
22253
+ return new Promise((resolve, reject) => {
22254
+ const finish = (error51) => {
22255
+ clearTimeout(timer);
22256
+ this.#runWaiters.delete(waiter);
22257
+ if (error51)
22258
+ reject(error51);
22259
+ else
22260
+ resolve();
22261
+ };
22262
+ const waiter = {
22263
+ check: () => {
22264
+ if (this.#runGeneration > generation)
22265
+ finish();
22266
+ },
22267
+ reject: (error51) => finish(error51)
22268
+ };
22269
+ const timer = setTimeout(() => finish(new PiRpcFaultError("protocolError", "Pi RPC agent_settled state is still Streaming without a subsequent agent_start")), this.#options.commandTimeoutMs);
22270
+ this.#runWaiters.add(waiter);
22271
+ });
22272
+ }
22273
+ #drainDeferredRunFrames() {
22274
+ const frames = this.#deferredRunFrames;
22275
+ this.#deferredRunFrames = [];
22276
+ this.#deferredRunBytes = 0;
22277
+ for (const frame of frames) {
22278
+ if (this.#closed || this.#failed)
22279
+ break;
22280
+ this.#handle(frame.value, frame.generation);
22281
+ }
22282
+ }
22283
+ async #confirmSettledTurn(active, generation) {
21161
22284
  try {
21162
22285
  const response = await this.#send("get_state", {});
21163
22286
  const state2 = parseSessionState(response);
21164
- if (parseSessionStreaming(response)) {
21165
- throw new PiRpcFaultError("protocolError", "Pi RPC agent_settled state is still Streaming");
21166
- }
21167
- if (this.#activeTurn !== active)
22287
+ if (!this.#isSettlementCurrent(active, generation))
21168
22288
  return;
21169
- if (active.origin === "autonomous") {
22289
+ if (parseSessionStreaming(response))
22290
+ await this.#waitForNextRun(generation);
22291
+ if (!this.#isSettlementCurrent(active, generation))
22292
+ return;
22293
+ if (active.origin === "autonomous" && active.autonomousMessage) {
21170
22294
  const history = await this.getEntries();
21171
22295
  const snapshot = mapPiSnapshot(history, { sessionId: state2.sessionId, model: null });
21172
- const turn = snapshot.turns.at(-1);
22296
+ if (!this.#isSettlementCurrent(active, generation))
22297
+ return;
21173
22298
  const entries = activePiEntries(history);
21174
- const start = entries.findIndex((entry) => entry.id === turn?.nativeTurnRef.nativeTurnKey);
21175
- const firstAssistant = entries.slice(start + 1).find((entry) => isRecord8(entry.message) && entry.message.role === "assistant")?.message;
21176
22299
  const live = active.autonomousMessage;
21177
22300
  const responseId = assistantMessageId(live);
21178
- const matches = isRecord8(firstAssistant) && (responseId ? assistantMessageId(firstAssistant) === responseId : typeof live?.timestamp === "number" && firstAssistant.timestamp === live.timestamp);
21179
- if (!turn || turn.input.length !== 0 || !matches) {
22301
+ const matches = snapshot.turns.filter((turn2) => {
22302
+ if (turn2.input.length !== 0)
22303
+ return false;
22304
+ const start = entries.findIndex((entry) => entry.id === turn2.nativeTurnRef.nativeTurnKey);
22305
+ const firstAssistant = entries.slice(start + 1).find((entry) => isRecord9(entry.message) && entry.message.role === "assistant")?.message;
22306
+ return isRecord9(firstAssistant) && (responseId ? assistantMessageId(firstAssistant) === responseId : typeof live?.timestamp === "number" && firstAssistant.timestamp === live.timestamp);
22307
+ });
22308
+ const turn = matches.length === 1 ? matches[0] : void 0;
22309
+ if (!turn)
21180
22310
  throw new PiRpcFaultError("protocolError", "Pi autonomous Turn has no matching persisted custom Entry");
21181
- }
21182
22311
  active.nativeTurnKey = turn.nativeTurnRef.nativeTurnKey;
21183
22312
  }
21184
- if (this.#activeTurn !== active)
22313
+ if (!this.#isSettlementCurrent(active, generation))
21185
22314
  return;
21186
22315
  this.#state = state2;
21187
22316
  active.settlement = "confirmed";
@@ -21207,7 +22336,13 @@ var PiRpcSession = class {
21207
22336
  }
21208
22337
  this.#activeTurn = null;
21209
22338
  if (active.origin === "autonomous") {
21210
- if (active.failure) {
22339
+ if (active.cancellation === "accepted") {
22340
+ this.#emitAutonomousTurn(active, {
22341
+ status: "cancelled",
22342
+ text: active.text,
22343
+ reason: "Cancelled by user"
22344
+ });
22345
+ } else if (active.failure) {
21211
22346
  this.#emitAutonomousTurn(active, active.nativeCancellationObserved ? {
21212
22347
  status: "cancelled",
21213
22348
  text: active.text,
@@ -21222,6 +22357,7 @@ var PiRpcSession = class {
21222
22357
  } else {
21223
22358
  this.#emitAutonomousTurn(active, { status: "succeeded", text: active.text });
21224
22359
  }
22360
+ this.#drainDeferredRunFrames();
21225
22361
  return;
21226
22362
  }
21227
22363
  if (active.cancellation === "accepted") {
@@ -21233,20 +22369,56 @@ var PiRpcSession = class {
21233
22369
  } else {
21234
22370
  active.resolve({ text: active.text, cancelled: false });
21235
22371
  }
22372
+ this.#drainDeferredRunFrames();
22373
+ }
22374
+ #emitContent(active, reasoning, delta) {
22375
+ if (delta.length === 0)
22376
+ return;
22377
+ const messageId = active.assistantMessageId;
22378
+ if (messageId === null)
22379
+ throw new Error("Pi content arrived outside an Assistant message");
22380
+ if (reasoning) {
22381
+ active.reasoningMessageOpen = true;
22382
+ active.sawStreamedMessageReasoning = true;
22383
+ } else {
22384
+ active.text += delta;
22385
+ active.sawStreamedMessageText = true;
22386
+ }
22387
+ active.onEvent({
22388
+ type: reasoning ? "reasoning.delta" : "text.delta",
22389
+ messageId,
22390
+ ...nativeMessageIdentity(active),
22391
+ delta
22392
+ });
21236
22393
  }
21237
22394
  #startAssistantMessage(active, value) {
22395
+ if (active.origin === "autonomous" && !active.autonomousMessage && isRecord9(value))
22396
+ active.autonomousMessage = value;
21238
22397
  if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
21239
22398
  active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
21240
22399
  }
21241
- const messageId = assistantMessageId(value) ?? randomUUID5();
22400
+ const nativeResponseId = assistantMessageId(value);
22401
+ const messageId = nativeResponseId ?? randomUUID6();
21242
22402
  active.assistantMessageId = messageId;
22403
+ active.assistantNativeMessageIdentity = piMessageIdentity(this.state.sessionId, value, this.#messageTimestampCounts);
22404
+ active.textStream = new PiContentStream("text");
22405
+ active.reasoningStream = new PiContentStream("reasoning");
21243
22406
  active.sawStreamedMessageText = false;
21244
22407
  active.sawStreamedMessageReasoning = false;
21245
22408
  active.reasoningMessageOpen = false;
21246
22409
  return messageId;
21247
22410
  }
21248
22411
  #ensureAssistantMessage(active, value) {
21249
- return active.assistantMessageId ?? this.#startAssistantMessage(active, value);
22412
+ if (active.assistantMessageId === null)
22413
+ return this.#startAssistantMessage(active, value);
22414
+ if (!active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
22415
+ const nativeResponseId = assistantMessageId(value);
22416
+ if (nativeResponseId) {
22417
+ active.assistantMessageId = nativeResponseId;
22418
+ active.assistantNativeMessageIdentity ??= { responseId: nativeResponseId };
22419
+ }
22420
+ }
22421
+ return active.assistantMessageId;
21250
22422
  }
21251
22423
  #finalizeAssistantMessage(active, value) {
21252
22424
  const finalText = assistantText(value);
@@ -21259,29 +22431,33 @@ var PiRpcSession = class {
21259
22431
  return;
21260
22432
  }
21261
22433
  active.failure = failure;
21262
- if (active.origin === "autonomous" && isRecord8(value) && value.stopReason === "aborted") {
22434
+ if (active.origin === "autonomous" && piAssistantWasAborted(value)) {
21263
22435
  active.nativeCancellationObserved = true;
21264
22436
  }
21265
22437
  this.#latestCacheHitRatePercent = cacheHitRatePercent;
21266
22438
  const messageId = this.#ensureAssistantMessage(active, value);
21267
- if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
21268
- active.reasoningMessageOpen = true;
21269
- active.onEvent({ type: "reasoning.delta", messageId, delta: finalReasoning });
22439
+ const content = value.content;
22440
+ if (failure === null || !active.sawStreamedMessageReasoning) {
22441
+ this.#emitContent(active, true, active.reasoningStream.finalize(content.flatMap((part, index) => {
22442
+ const text4 = extractReasoningText(part);
22443
+ return text4 === null ? [] : [{ index, text: text4 }];
22444
+ })));
21270
22445
  }
21271
22446
  if (active.reasoningMessageOpen && active.failure === null) {
21272
22447
  active.onEvent({ type: "reasoning.completed", messageId });
21273
22448
  }
21274
- if (!active.sawStreamedMessageText && finalText.length > 0) {
21275
- active.text += finalText;
21276
- active.onEvent({ type: "text.delta", messageId, delta: finalText });
22449
+ if (failure === null || !active.sawStreamedMessageText) {
22450
+ this.#emitContent(active, false, active.textStream.finalize(content.flatMap((part, index) => isRecord9(part) && part.type === "text" && typeof part.text === "string" ? [{ index, text: part.text }] : [])));
21277
22451
  }
21278
22452
  active.assistantMessageId = null;
22453
+ active.assistantNativeMessageIdentity = void 0;
21279
22454
  active.sawStreamedMessageText = false;
21280
22455
  active.sawStreamedMessageReasoning = false;
21281
22456
  active.reasoningMessageOpen = false;
21282
22457
  active.lastFinalizedMessageText = finalText;
21283
22458
  active.lastFinalizedMessageReasoning = finalReasoning;
21284
- active.onEvent({ type: "message.completed", messageId });
22459
+ const phase = piAssistantPhase(value);
22460
+ active.onEvent({ type: "message.completed", messageId, ...phase ? { phase } : {} });
21285
22461
  }
21286
22462
  #write(value) {
21287
22463
  const child = this.#child;
@@ -21299,7 +22475,7 @@ var PiRpcSession = class {
21299
22475
  if (!child?.stdin.writable || this.#closed || this.#failed) {
21300
22476
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
21301
22477
  }
21302
- const id = `codexhost-${randomUUID5()}`;
22478
+ const id = `codexhost-${randomUUID6()}`;
21303
22479
  return new Promise((resolve, reject) => {
21304
22480
  const pending = {
21305
22481
  command: type,
@@ -21332,6 +22508,12 @@ var PiRpcSession = class {
21332
22508
  const error51 = new Error(`Pi RPC '${pending.command}' command timed out`);
21333
22509
  if (pending.command !== "prompt") {
21334
22510
  this.#pending.delete(id);
22511
+ if (READ_ONLY_COMMANDS.has(pending.command)) {
22512
+ this.#expired.add(id);
22513
+ if (this.#expired.size > MAX_EXPIRED_IDS) {
22514
+ this.#expired.delete(this.#expired.values().next().value);
22515
+ }
22516
+ }
21335
22517
  pending.reject(error51);
21336
22518
  return;
21337
22519
  }
@@ -21383,9 +22565,16 @@ var PiRpcSession = class {
21383
22565
  } else {
21384
22566
  active.reject(error51);
21385
22567
  }
22568
+ this.#drainDeferredRunFrames();
21386
22569
  }
21387
22570
  #rejectAll(error51) {
22571
+ for (const waiter of this.#runWaiters)
22572
+ waiter.reject(error51);
22573
+ this.#deferredRunFrames = [];
22574
+ this.#deferredRunBytes = 0;
21388
22575
  this.#subagents.close(error51);
22576
+ this.#gotgenesHandler = void 0;
22577
+ this.#gotgenesLatest = void 0;
21389
22578
  for (const pending of this.#pending.values()) {
21390
22579
  if (pending.timeout)
21391
22580
  clearTimeout(pending.timeout);
@@ -21421,7 +22610,7 @@ var piCommandCatalog = harnessCommandCatalogSchema.parse({
21421
22610
  ]
21422
22611
  });
21423
22612
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
21424
- function isRecord9(value) {
22613
+ function isRecord10(value) {
21425
22614
  return typeof value === "object" && value !== null && !Array.isArray(value);
21426
22615
  }
21427
22616
  function errorMessage(error51) {
@@ -21436,7 +22625,9 @@ var PiAdapterFaultError = class extends Error {
21436
22625
  }
21437
22626
  };
21438
22627
  function normalizedError(error51, fallbackCode) {
21439
- if (isRecord9(error51) && error51.code === "ENOENT") {
22628
+ if (error51 instanceof PiRpcBusyError)
22629
+ return { code: "sessionBusy", message: error51.message, retryable: true };
22630
+ if (isRecord10(error51) && error51.code === "ENOENT") {
21440
22631
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
21441
22632
  }
21442
22633
  if (error51 instanceof PiAdapterFaultError)
@@ -21499,7 +22690,7 @@ function nativeModelForHistory(state2) {
21499
22690
  return nativeModelFromState(state2);
21500
22691
  }
21501
22692
  function sessionFileFromRef(ref) {
21502
- if (ref.harnessId !== piHarnessId2 || !isRecord9(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
22693
+ if (ref.harnessId !== piHarnessId2 || !isRecord10(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
21503
22694
  throw new Error("Pi Native Session Ref has no resumable Session file");
21504
22695
  }
21505
22696
  return ref.locator.sessionFile;
@@ -21514,82 +22705,28 @@ function toolFailure(toolName) {
21514
22705
  function nativeText(value) {
21515
22706
  if (typeof value === "string")
21516
22707
  return value;
21517
- if (!isRecord9(value) || !Array.isArray(value.content))
22708
+ if (!isRecord10(value) || !Array.isArray(value.content))
21518
22709
  return "";
21519
- return value.content.filter((content) => isRecord9(content) && content.type === "text" && typeof content.text === "string").map(({ text: text2 }) => text2).join("");
22710
+ return value.content.filter((content) => isRecord10(content) && content.type === "text" && typeof content.text === "string").map(({ text: text4 }) => text4).join("");
21520
22711
  }
21521
22712
  function boundedOutput(value, limit) {
21522
- const text2 = nativeText(value);
21523
- if (text2.length === 0)
22713
+ const text4 = nativeText(value);
22714
+ if (text4.length === 0)
21524
22715
  return void 0;
21525
- const truncated = text2.length > limit;
22716
+ const truncated = text4.length > limit;
21526
22717
  return {
21527
- content: [{ type: "text", text: truncated ? text2.slice(0, limit) : text2 }],
22718
+ content: [{ type: "text", text: truncated ? text4.slice(0, limit) : text4 }],
21528
22719
  ...truncated ? { truncated: true } : {}
21529
22720
  };
21530
22721
  }
21531
22722
  function outputText(output) {
21532
- return output?.content.filter((content) => content.type === "text").map(({ text: text2 }) => text2).join("") ?? "";
21533
- }
21534
- function stringField(value, key) {
21535
- if (!isRecord9(value))
21536
- return void 0;
21537
- const field = value[key];
21538
- if (typeof field === "string" && field.length > 0)
21539
- return field;
21540
- if (isRecord9(value.input)) {
21541
- const nested = value.input[key];
21542
- if (typeof nested === "string" && nested.length > 0)
21543
- return nested;
21544
- }
21545
- if (isRecord9(value.arguments)) {
21546
- const nested = value.arguments[key];
21547
- if (typeof nested === "string" && nested.length > 0)
21548
- return nested;
21549
- }
21550
- return void 0;
22723
+ return output?.content.filter((content) => content.type === "text").map(({ text: text4 }) => text4).join("") ?? "";
21551
22724
  }
21552
22725
  function numberField(value, key) {
21553
- if (!isRecord9(value))
22726
+ if (!isRecord10(value))
21554
22727
  return void 0;
21555
- const field = value[key];
21556
- return typeof field === "number" || field === null ? field : void 0;
21557
- }
21558
- function normalizeToolName(name) {
21559
- const lower = name.toLowerCase();
21560
- switch (lower) {
21561
- case "bash":
21562
- case "exec":
21563
- case "terminal":
21564
- case "run":
21565
- return "bash";
21566
- case "read":
21567
- case "read_file":
21568
- case "fileread":
21569
- return "Read";
21570
- case "edit":
21571
- case "edit_file":
21572
- case "fileedit":
21573
- return "Edit";
21574
- case "write":
21575
- case "write_file":
21576
- case "filewrite":
21577
- return "Write";
21578
- case "grep":
21579
- case "grep_search":
21580
- return "Grep";
21581
- case "find":
21582
- case "glob":
21583
- case "find_files":
21584
- return "Glob";
21585
- case "todo":
21586
- return "Todo";
21587
- case "web_search":
21588
- case "websearch":
21589
- return "WebSearch";
21590
- default:
21591
- return name.length > 0 ? `${name[0]?.toUpperCase() ?? ""}${name.slice(1)}` : name;
21592
- }
22728
+ const field2 = value[key];
22729
+ return typeof field2 === "number" || field2 === null ? field2 : void 0;
21593
22730
  }
21594
22731
  function delay(milliseconds) {
21595
22732
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
@@ -21618,6 +22755,8 @@ var PiHarnessSession = class {
21618
22755
  #configuring = false;
21619
22756
  #phase = "open";
21620
22757
  #pendingAutonomousTurns = [];
22758
+ #pendingAutonomousLifecycle = [];
22759
+ #pendingAutonomousLifecycleBytes = 0;
21621
22760
  #starting = null;
21622
22761
  #state = {};
21623
22762
  #transport = null;
@@ -21666,13 +22805,20 @@ var PiHarnessSession = class {
21666
22805
  return this.#transport?.state.sessionId === id;
21667
22806
  }
21668
22807
  async readSubagentHistory(cwd) {
21669
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22808
+ if (this.#phase !== "open" || path17.resolve(cwd) !== path17.resolve(this.#cwd)) {
21670
22809
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21671
22810
  }
21672
22811
  return (await this.#ensureTransport()).getEntries();
21673
22812
  }
22813
+ async readGotgenesChild(id, cwd) {
22814
+ const history = await this.readSubagentHistory(cwd);
22815
+ const transport = this.#transport;
22816
+ if (!transport)
22817
+ throw new Error("Pi parent Session is closed");
22818
+ return readGotgenesChild(history, transport.state.sessionId, id, this.#subagents.gotgenes.records.get(id));
22819
+ }
21674
22820
  async inspectSubagent(id, cwd) {
21675
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22821
+ if (this.#phase !== "open" || path17.resolve(cwd) !== path17.resolve(this.#cwd)) {
21676
22822
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21677
22823
  }
21678
22824
  const transport = await this.#ensureTransport();
@@ -21743,7 +22889,7 @@ var PiHarnessSession = class {
21743
22889
  }
21744
22890
  };
21745
22891
  }
21746
- if (this.#acceptingTurn || this.#active || this.#configuring) {
22892
+ if (this.#acceptingTurn || this.#active || this.#configuring || this.#transport?.isBusy) {
21747
22893
  return {
21748
22894
  ok: false,
21749
22895
  error: {
@@ -21753,8 +22899,8 @@ var PiHarnessSession = class {
21753
22899
  }
21754
22900
  };
21755
22901
  }
21756
- const text2 = command.input.filter((input) => input.type === "text").map((input) => input.text).join("\n");
21757
- if (text2.length === 0) {
22902
+ const text4 = command.input.filter((input) => input.type === "text").map((input) => input.text).join("\n");
22903
+ if (text4.length === 0) {
21758
22904
  return {
21759
22905
  ok: false,
21760
22906
  error: {
@@ -21784,6 +22930,9 @@ var PiHarnessSession = class {
21784
22930
  } catch (error51) {
21785
22931
  return { ok: false, error: normalizedError(error51, "protocolError") };
21786
22932
  }
22933
+ if (this.#active || transport.isBusy || this.#pendingAutonomousLifecycle.length > 0 || this.#pendingAutonomousTurns.length > 0) {
22934
+ return { ok: false, error: normalizedError(new PiRpcBusyError(), "sessionBusy") };
22935
+ }
21787
22936
  let resolveCompletion = () => void 0;
21788
22937
  const completion = new Promise((resolve) => {
21789
22938
  resolveCompletion = resolve;
@@ -21804,21 +22953,27 @@ var PiHarnessSession = class {
21804
22953
  interactions: /* @__PURE__ */ new Map(),
21805
22954
  interactionByNativeId: /* @__PURE__ */ new Map(),
21806
22955
  cancellationRequested: false,
22956
+ settling: false,
21807
22957
  beforeNativeTurnKeys: new Set(beforeHistory.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
22958
+ progressItems: /* @__PURE__ */ new Set(),
21808
22959
  completion,
21809
22960
  resolveCompletion
21810
22961
  };
21811
22962
  this.#active = active;
21812
22963
  this.#event({ type: "turn.started", turnId: command.turnId });
21813
22964
  this.#event({ type: "item.started", turnId: command.turnId, item });
21814
- void transport.runTurn(text2, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
22965
+ void transport.runTurn(text4, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
22966
+ active.settling = true;
21815
22967
  try {
21816
22968
  const identity = await this.#completedTurnIdentity(active, transport);
21817
22969
  this.#completeTurn(active, result.cancelled ? {
21818
22970
  status: "cancelled",
21819
22971
  reason: "Cancelled by user",
21820
- checkpoint: identity.checkpoint
21821
- } : { status: "succeeded", checkpoint: identity.checkpoint }, result.text, identity.nativeTurnRef);
22972
+ ...identity.checkpoint ? { checkpoint: identity.checkpoint } : {}
22973
+ } : {
22974
+ status: "succeeded",
22975
+ ...identity.checkpoint ? { checkpoint: identity.checkpoint } : {}
22976
+ }, result.text, identity.nativeTurnRef);
21822
22977
  } catch (error51) {
21823
22978
  this.#completeTurn(active, {
21824
22979
  status: "failed",
@@ -21826,6 +22981,7 @@ var PiHarnessSession = class {
21826
22981
  });
21827
22982
  }
21828
22983
  }).catch(async (error51) => {
22984
+ active.settling = true;
21829
22985
  let identity;
21830
22986
  try {
21831
22987
  identity = await this.#completedTurnIdentity(active, transport);
@@ -21834,12 +22990,14 @@ var PiHarnessSession = class {
21834
22990
  this.#completeTurn(active, {
21835
22991
  status: "failed",
21836
22992
  error: normalizedError(error51, "nativeFailure"),
21837
- ...identity ? { checkpoint: identity.checkpoint } : {}
22993
+ ...identity?.checkpoint ? { checkpoint: identity.checkpoint } : {}
21838
22994
  }, void 0, identity?.nativeTurnRef);
21839
22995
  });
21840
22996
  return { ok: true, value: { turnId: command.turnId } };
21841
22997
  } finally {
21842
22998
  this.#acceptingTurn = false;
22999
+ if (this.#transport)
23000
+ this.#drainPendingAutonomousTurns(this.#transport);
21843
23001
  }
21844
23002
  }
21845
23003
  close() {
@@ -21967,6 +23125,8 @@ var PiHarnessSession = class {
21967
23125
  return { ok: true, value: { completed: true } };
21968
23126
  } finally {
21969
23127
  this.#configuring = false;
23128
+ if (this.#transport)
23129
+ this.#drainPendingAutonomousTurns(this.#transport);
21970
23130
  }
21971
23131
  }
21972
23132
  async #selectThinking(command) {
@@ -22041,6 +23201,8 @@ var PiHarnessSession = class {
22041
23201
  return { ok: true, value: { completed: true } };
22042
23202
  } finally {
22043
23203
  this.#configuring = false;
23204
+ if (this.#transport)
23205
+ this.#drainPendingAutonomousTurns(this.#transport);
22044
23206
  }
22045
23207
  }
22046
23208
  async #cancel(command) {
@@ -22051,6 +23213,12 @@ var PiHarnessSession = class {
22051
23213
  error: invalidState("Pi Turn Cancel must reference the active Turn")
22052
23214
  };
22053
23215
  }
23216
+ if (active.settling) {
23217
+ return {
23218
+ ok: false,
23219
+ error: invalidState("Pi Turn has finished native execution and is recording its completion")
23220
+ };
23221
+ }
22054
23222
  if (active.cancellationRequested) {
22055
23223
  return { ok: true, value: { cancellationRequested: true } };
22056
23224
  }
@@ -22165,7 +23333,9 @@ var PiHarnessSession = class {
22165
23333
  interactions: /* @__PURE__ */ new Map(),
22166
23334
  interactionByNativeId: /* @__PURE__ */ new Map(),
22167
23335
  cancellationRequested: false,
23336
+ settling: false,
22168
23337
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23338
+ progressItems: /* @__PURE__ */ new Set(),
22169
23339
  completion,
22170
23340
  resolveCompletion
22171
23341
  };
@@ -22198,6 +23368,8 @@ var PiHarnessSession = class {
22198
23368
  return { ok: true, value: { turnId: command.turnId } };
22199
23369
  } finally {
22200
23370
  this.#acceptingTurn = false;
23371
+ if (this.#transport)
23372
+ this.#drainPendingAutonomousTurns(this.#transport);
22201
23373
  }
22202
23374
  }
22203
23375
  async #ensureTransport() {
@@ -22248,6 +23420,8 @@ var PiHarnessSession = class {
22248
23420
  return transport;
22249
23421
  }).catch(async (error51) => {
22250
23422
  this.#pendingAutonomousTurns = this.#pendingAutonomousTurns.filter((pending) => pending.transport !== transport);
23423
+ this.#pendingAutonomousLifecycle = this.#pendingAutonomousLifecycle.filter((pending) => pending.transport !== transport);
23424
+ this.#pendingAutonomousLifecycleBytes = this.#pendingAutonomousLifecycle.reduce((total, pending) => total + pending.bytes, 0);
22251
23425
  await transport.close().catch(() => void 0);
22252
23426
  if (this.#phase === "open")
22253
23427
  this.#fault(error51);
@@ -22260,6 +23434,11 @@ var PiHarnessSession = class {
22260
23434
  return starting;
22261
23435
  }
22262
23436
  #bindAutonomousTurnHandler(transport) {
23437
+ transport.setGotgenesStatusHandler?.((records, owner) => {
23438
+ if (this.#phase !== "open")
23439
+ return;
23440
+ this.#subagents.observeGotgenes(records, owner === "requested" && this.#active && !this.#active.settling ? { turnId: this.#active.command.turnId, nextItemId: () => this.#newItemId() } : void 0);
23441
+ });
22263
23442
  transport.setSubagentStatusHandler?.((runs) => {
22264
23443
  if (this.#phase !== "open")
22265
23444
  return;
@@ -22271,12 +23450,16 @@ var PiHarnessSession = class {
22271
23450
  transport.setUsageHandler?.((observation) => {
22272
23451
  if (this.#phase !== "open")
22273
23452
  return;
22274
- const record7 = piUsageRecord(observation.message, observation);
22275
- if (record7?.kind === "request")
22276
- this.#event({ type: "usage.request", request: record7.request });
22277
- else if (record7?.kind === "missing")
23453
+ const record9 = piUsageRecord(observation.message, observation);
23454
+ if (record9?.kind === "request")
23455
+ this.#event({ type: "usage.request", request: record9.request });
23456
+ else if (record9?.kind === "missing")
22278
23457
  this.#event({ type: "usage.history", complete: false });
22279
23458
  });
23459
+ if (transport.setAutonomousTurnLifecycleHandler) {
23460
+ transport.setAutonomousTurnLifecycleHandler((update) => this.#handleAutonomousLifecycle(transport, update));
23461
+ return;
23462
+ }
22280
23463
  transport.setAutonomousTurnHandler((turn) => {
22281
23464
  if (this.#phase !== "open")
22282
23465
  return;
@@ -22288,6 +23471,20 @@ var PiHarnessSession = class {
22288
23471
  });
22289
23472
  }
22290
23473
  #drainPendingAutonomousTurns(transport) {
23474
+ if (this.#phase !== "open" || this.#acceptingTurn || this.#configuring)
23475
+ return;
23476
+ for (; ; ) {
23477
+ const pending2 = this.#pendingAutonomousLifecycle[0];
23478
+ if (!pending2 || pending2.transport !== transport || this.#active && this.#active.autonomousRunId !== pending2.update.runId)
23479
+ break;
23480
+ this.#pendingAutonomousLifecycle.shift();
23481
+ this.#pendingAutonomousLifecycleBytes -= pending2.bytes;
23482
+ this.#applyAutonomousLifecycle(transport, pending2.update);
23483
+ if (this.#phase !== "open")
23484
+ return;
23485
+ }
23486
+ if (this.#active)
23487
+ return;
22291
23488
  if (this.#pendingSubagentStatus) {
22292
23489
  this.#subagents.observe(this.#pendingSubagentStatus);
22293
23490
  this.#pendingSubagentStatus = null;
@@ -22300,6 +23497,52 @@ var PiHarnessSession = class {
22300
23497
  this.#handleAutonomousTurn(transport, candidate.turn);
22301
23498
  }
22302
23499
  }
23500
+ #handleAutonomousLifecycle(transport, update) {
23501
+ if (this.#phase === "closing" && this.#transport === transport && update.type !== "started" && this.#active?.autonomousRunId === update.runId) {
23502
+ this.#applyAutonomousLifecycle(transport, update);
23503
+ return;
23504
+ }
23505
+ if (this.#phase !== "open")
23506
+ return;
23507
+ if (this.#transport !== transport || this.#acceptingTurn || this.#configuring || this.#pendingAutonomousLifecycle.length > 0 || this.#active && this.#active.autonomousRunId !== update.runId) {
23508
+ const bytes = Buffer.byteLength(JSON.stringify(update));
23509
+ if (this.#pendingAutonomousLifecycleBytes + bytes > 8 * 1024 * 1024) {
23510
+ this.#fault(new PiAdapterFaultError({
23511
+ code: "protocolError",
23512
+ message: "Pi autonomous lifecycle exceeded its ordered event buffer bound",
23513
+ retryable: false
23514
+ }));
23515
+ return;
23516
+ }
23517
+ this.#pendingAutonomousLifecycle.push({ transport, update, bytes });
23518
+ this.#pendingAutonomousLifecycleBytes += bytes;
23519
+ if (this.#transport === transport)
23520
+ this.#drainPendingAutonomousTurns(transport);
23521
+ return;
23522
+ }
23523
+ this.#applyAutonomousLifecycle(transport, update);
23524
+ }
23525
+ #applyAutonomousLifecycle(transport, update) {
23526
+ if (update.type === "started" && !this.#active) {
23527
+ this.#startAutonomousHostTurn(update.runId);
23528
+ return;
23529
+ }
23530
+ const active = this.#active;
23531
+ if (!active || active.autonomousRunId !== update.runId || update.type === "started") {
23532
+ this.#fault(new PiAdapterFaultError({
23533
+ code: "protocolError",
23534
+ message: "Pi autonomous event has no matching active run",
23535
+ retryable: false
23536
+ }));
23537
+ return;
23538
+ }
23539
+ if (update.type === "event")
23540
+ this.#handleTurnEvent(active, update.event);
23541
+ else {
23542
+ active.settling = true;
23543
+ this.#finishAutonomousHostTurn(transport, active, update.turn);
23544
+ }
23545
+ }
22303
23546
  #handleAutonomousTurn(transport, turn) {
22304
23547
  if (this.#phase !== "open")
22305
23548
  return;
@@ -22311,7 +23554,7 @@ var PiHarnessSession = class {
22311
23554
  }));
22312
23555
  return;
22313
23556
  }
22314
- if (this.#active || this.#acceptingTurn || this.#configuring) {
23557
+ if (this.#active && !this.#active.settling) {
22315
23558
  this.#fault(new PiAdapterFaultError({
22316
23559
  code: "protocolError",
22317
23560
  message: "Pi autonomous Turn overlapped another Host operation",
@@ -22319,7 +23562,22 @@ var PiHarnessSession = class {
22319
23562
  }));
22320
23563
  return;
22321
23564
  }
22322
- const turnId = hostTurnIdSchema.parse(randomUUID6());
23565
+ if (this.#active || this.#acceptingTurn || this.#configuring) {
23566
+ if (this.#pendingAutonomousTurns.length >= 128) {
23567
+ this.#fault(new PiAdapterFaultError({
23568
+ code: "protocolError",
23569
+ message: "Pi autonomous completion queue exceeded its bound",
23570
+ retryable: false
23571
+ }));
23572
+ } else
23573
+ this.#pendingAutonomousTurns.push({ transport, turn });
23574
+ return;
23575
+ }
23576
+ const active = this.#startAutonomousHostTurn();
23577
+ this.#finishAutonomousHostTurn(transport, active, turn);
23578
+ }
23579
+ #startAutonomousHostTurn(runId) {
23580
+ const turnId = hostTurnIdSchema.parse(randomUUID7());
22323
23581
  let resolveCompletion = () => void 0;
22324
23582
  const completion = new Promise((resolve) => {
22325
23583
  resolveCompletion = resolve;
@@ -22331,6 +23589,7 @@ var PiHarnessSession = class {
22331
23589
  };
22332
23590
  const active = {
22333
23591
  command: { type: "turn.start", turnId, input: [] },
23592
+ ...runId ? { autonomousRunId: runId } : {},
22334
23593
  agentItem: item,
22335
23594
  agentMessageId: null,
22336
23595
  compactionItem: null,
@@ -22340,10 +23599,19 @@ var PiHarnessSession = class {
22340
23599
  interactions: /* @__PURE__ */ new Map(),
22341
23600
  interactionByNativeId: /* @__PURE__ */ new Map(),
22342
23601
  cancellationRequested: false,
23602
+ settling: false,
22343
23603
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23604
+ progressItems: /* @__PURE__ */ new Set(),
22344
23605
  completion,
22345
23606
  resolveCompletion
22346
23607
  };
23608
+ this.#active = active;
23609
+ this.#event({ type: "turn.autonomous.started", turnId, input: [] });
23610
+ this.#event({ type: "turn.started", turnId });
23611
+ this.#event({ type: "item.started", turnId, item });
23612
+ return active;
23613
+ }
23614
+ #finishAutonomousHostTurn(transport, active, turn) {
22347
23615
  const nativeTurnRef = turn.nativeTurnKey ? nativeTurnRefSchema.parse({
22348
23616
  harnessId: this.harnessId,
22349
23617
  nativeSessionId: transport.state.sessionId,
@@ -22356,10 +23624,6 @@ var PiHarnessSession = class {
22356
23624
  checkpointId: nativeTurnRef.nativeTurnKey,
22357
23625
  formatVersion: 1
22358
23626
  }) : void 0;
22359
- this.#active = active;
22360
- this.#event({ type: "turn.autonomous.started", turnId, input: [] });
22361
- this.#event({ type: "turn.started", turnId });
22362
- this.#event({ type: "item.started", turnId, item });
22363
23627
  try {
22364
23628
  for (const event of turn.events)
22365
23629
  this.#handleTurnEvent(active, event);
@@ -22429,17 +23693,35 @@ var PiHarnessSession = class {
22429
23693
  if (this.#active !== active || this.#phase === "closed" || this.#phase === "faulted")
22430
23694
  return;
22431
23695
  switch (event.type) {
23696
+ case "progress.message": {
23697
+ if (active.progressItems.has(event.itemId))
23698
+ return;
23699
+ active.progressItems.add(event.itemId);
23700
+ const item = {
23701
+ type: "agentMessage",
23702
+ itemId: event.itemId,
23703
+ text: event.text,
23704
+ phase: "commentary"
23705
+ };
23706
+ this.#event({ type: "item.started", turnId: active.command.turnId, item });
23707
+ this.#completeItem(active, item, { status: "succeeded" });
23708
+ return;
23709
+ }
22432
23710
  case "text.delta":
22433
- this.#activateAgentMessage(active, event.messageId);
23711
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23712
+ active.sawAssistantMessage = true;
22434
23713
  this.#appendText(active, event.delta);
22435
23714
  return;
22436
23715
  case "reasoning.delta":
22437
- this.#appendReasoning(active, event.delta);
23716
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23717
+ this.#appendReasoning(active, event.delta, event.nativeMessageIdentity);
22438
23718
  return;
22439
23719
  case "reasoning.completed":
22440
23720
  this.#completeReasoning(active, { status: "succeeded" });
22441
23721
  return;
22442
23722
  case "message.completed":
23723
+ if (event.phase && active.agentMessageId === event.messageId && active.agentItem)
23724
+ active.agentItem = { ...active.agentItem, phase: event.phase };
22443
23725
  void this.#refreshUsage(active.command.turnId);
22444
23726
  return;
22445
23727
  case "compaction.started":
@@ -22497,7 +23779,7 @@ var PiHarnessSession = class {
22497
23779
  if (active.interactionByNativeId.has(request.requestId)) {
22498
23780
  throw new Error("Pi Interaction started more than once");
22499
23781
  }
22500
- const interactionId = hostInteractionIdSchema.parse(randomUUID6());
23782
+ const interactionId = hostInteractionIdSchema.parse(randomUUID7());
22501
23783
  const question = request.method === "select" ? {
22502
23784
  id: "answer",
22503
23785
  type: "choice",
@@ -22554,17 +23836,21 @@ var PiHarnessSession = class {
22554
23836
  reason
22555
23837
  });
22556
23838
  }
22557
- #activateAgentMessage(active, messageId) {
23839
+ #activateAgentMessage(active, messageId, nativeMessageIdentity2) {
22558
23840
  if (active.agentMessageId === messageId)
22559
23841
  return;
23842
+ const nativeItemId = piMessageItemId(nativeMessageIdentity2, "assistant");
23843
+ if (nativeItemId && active.agentMessageId === null && active.agentItem?.text === "") {
23844
+ this.#completeAgentItem(active, { status: "succeeded" }, true);
23845
+ }
22560
23846
  if (active.agentMessageId !== null) {
22561
23847
  this.#completeReasoning(active, { status: "succeeded" });
22562
- this.#completeAgentItem(active, { status: "succeeded" }, false);
23848
+ this.#completeAgentItem(active, { status: "succeeded" }, true);
22563
23849
  }
22564
23850
  if (!active.agentItem) {
22565
23851
  active.agentItem = {
22566
23852
  type: "agentMessage",
22567
- itemId: this.#newItemId(),
23853
+ itemId: nativeItemId ?? this.#newItemId(),
22568
23854
  text: ""
22569
23855
  };
22570
23856
  this.#event({
@@ -22574,18 +23860,17 @@ var PiHarnessSession = class {
22574
23860
  });
22575
23861
  }
22576
23862
  active.agentMessageId = messageId;
22577
- active.sawAssistantMessage = true;
22578
23863
  }
22579
- #appendText(active, text2) {
23864
+ #appendText(active, text4) {
22580
23865
  if (active.agentMessageId === null || !active.agentItem) {
22581
23866
  throw new Error("Pi Assistant text arrived outside an active message");
22582
23867
  }
22583
- active.agentItem = { ...active.agentItem, text: active.agentItem.text + text2 };
23868
+ active.agentItem = { ...active.agentItem, text: active.agentItem.text + text4 };
22584
23869
  this.#event({
22585
23870
  type: "item.updated",
22586
23871
  turnId: active.command.turnId,
22587
23872
  itemId: active.agentItem.itemId,
22588
- update: { type: "text.append", text: text2 }
23873
+ update: { type: "text.append", text: text4 }
22589
23874
  });
22590
23875
  }
22591
23876
  #completeAgentItem(active, outcome, completeEmpty) {
@@ -22596,13 +23881,13 @@ var PiHarnessSession = class {
22596
23881
  active.agentItem = null;
22597
23882
  this.#completeItem(active, item, outcome);
22598
23883
  }
22599
- #appendReasoning(active, text2) {
22600
- if (text2.length === 0)
23884
+ #appendReasoning(active, text4, nativeMessageIdentity2) {
23885
+ if (text4.length === 0)
22601
23886
  return;
22602
23887
  if (!active.reasoningItem) {
22603
23888
  active.reasoningItem = {
22604
23889
  type: "reasoning",
22605
- itemId: this.#newItemId(),
23890
+ itemId: piMessageItemId(nativeMessageIdentity2, "reasoning") ?? this.#newItemId(),
22606
23891
  text: ""
22607
23892
  };
22608
23893
  this.#event({
@@ -22613,13 +23898,13 @@ var PiHarnessSession = class {
22613
23898
  }
22614
23899
  active.reasoningItem = {
22615
23900
  ...active.reasoningItem,
22616
- text: active.reasoningItem.text + text2
23901
+ text: active.reasoningItem.text + text4
22617
23902
  };
22618
23903
  this.#event({
22619
23904
  type: "item.updated",
22620
23905
  turnId: active.command.turnId,
22621
23906
  itemId: active.reasoningItem.itemId,
22622
- update: { type: "text.append", text: text2 }
23907
+ update: { type: "text.append", text: text4 }
22623
23908
  });
22624
23909
  }
22625
23910
  #completeReasoning(active, outcome) {
@@ -22632,13 +23917,12 @@ var PiHarnessSession = class {
22632
23917
  #startTool(active, event) {
22633
23918
  if (active.tools.has(event.callId))
22634
23919
  throw new Error("Pi Tool started more than once");
22635
- const normalizedName = normalizeToolName(event.toolName);
22636
- const command = normalizedName === "bash" ? stringField(event.arguments, "command") ?? stringField(event.arguments, "cmd") ?? stringField(event.arguments, "script") ?? stringField(event.arguments, "commandLine") ?? stringField(event.arguments, "command_line") : void 0;
22637
- const item = command ? {
23920
+ const shell = piToolCommand(event.toolName, event.arguments);
23921
+ const item = shell ? {
22638
23922
  type: "commandExecution",
22639
23923
  itemId: this.#newItemId(),
22640
- command,
22641
- cwd: stringField(event.arguments, "cwd") ?? this.#cwd
23924
+ command: shell.command,
23925
+ cwd: shell.cwd ?? this.#cwd
22642
23926
  } : {
22643
23927
  type: "toolExecution",
22644
23928
  itemId: this.#newItemId(),
@@ -22756,14 +24040,17 @@ var PiHarnessSession = class {
22756
24040
  sessionId: transport.state.sessionId,
22757
24041
  model: nativeModelForHistory(transport.state)
22758
24042
  });
22759
- const created = snapshot.turns.filter((turn2) => !active.beforeNativeTurnKeys.has(turn2.nativeTurnRef.nativeTurnKey));
24043
+ const created = snapshot.turns.filter((turn2) => turn2.input.length > 0 && !active.beforeNativeTurnKeys.has(turn2.nativeTurnRef.nativeTurnKey));
22760
24044
  if (created.length !== 1) {
22761
24045
  throw new Error(`Pi Turn persisted ${created.length} new User Entries; exactly one is required`);
22762
24046
  }
22763
24047
  const turn = created[0];
22764
- if (!turn?.checkpoint)
22765
- throw new Error("Pi Turn has no terminal Checkpoint identity");
22766
- return { nativeTurnRef: turn.nativeTurnRef, checkpoint: turn.checkpoint };
24048
+ if (!turn)
24049
+ throw new Error("Pi Turn has no persisted User identity");
24050
+ return {
24051
+ nativeTurnRef: turn.nativeTurnRef,
24052
+ ...turn.checkpoint ? { checkpoint: turn.checkpoint } : {}
24053
+ };
22767
24054
  }
22768
24055
  #completeTurn(active, outcome, finalText, nativeTurnRef) {
22769
24056
  if (this.#active !== active)
@@ -22792,14 +24079,20 @@ var PiHarnessSession = class {
22792
24079
  });
22793
24080
  active.resolveCompletion();
22794
24081
  queueMicrotask(() => {
22795
- if (this.#phase === "open")
22796
- void this.#refreshUsage(active.command.turnId);
24082
+ if (this.#phase !== "open")
24083
+ return;
24084
+ if (this.#transport)
24085
+ this.#drainPendingAutonomousTurns(this.#transport);
24086
+ void this.#refreshUsage(active.command.turnId);
22797
24087
  });
22798
24088
  }
22799
24089
  #fault(error51) {
22800
24090
  if (this.#phase === "closed" || this.#phase === "faulted")
22801
24091
  return;
22802
24092
  const normalized = normalizedError(error51, "internalError");
24093
+ this.#pendingAutonomousTurns = [];
24094
+ this.#pendingAutonomousLifecycle = [];
24095
+ this.#pendingAutonomousLifecycleBytes = 0;
22803
24096
  if (this.#active) {
22804
24097
  this.#completeTurn(this.#active, { status: "failed", error: normalized });
22805
24098
  }
@@ -22808,6 +24101,9 @@ var PiHarnessSession = class {
22808
24101
  this.#channel.end();
22809
24102
  }
22810
24103
  async #close() {
24104
+ this.#pendingAutonomousTurns = [];
24105
+ this.#pendingAutonomousLifecycle = [];
24106
+ this.#pendingAutonomousLifecycleBytes = 0;
22811
24107
  if (this.#phase === "closed")
22812
24108
  return;
22813
24109
  const wasFaulted = this.#phase === "faulted";
@@ -22840,7 +24136,7 @@ var PiHarnessSession = class {
22840
24136
  this.#channel.emit({ kind: "event", event });
22841
24137
  }
22842
24138
  #newItemId() {
22843
- return hostItemIdSchema.parse(randomUUID6());
24139
+ return hostItemIdSchema.parse(randomUUID7());
22844
24140
  }
22845
24141
  };
22846
24142
  var PiAdapter = class {
@@ -22855,12 +24151,15 @@ var PiAdapter = class {
22855
24151
  if (this.#closePromise || parent.harnessId !== this.harnessId) {
22856
24152
  return { ok: false, error: invalidState("Pi Subagent parent is unavailable") };
22857
24153
  }
24154
+ const gotgenes = parseGotgenesId(nativeSubagentId);
22858
24155
  const workflow = parsePiWorkflowSubagentId(nativeSubagentId);
22859
- if (!workflow)
24156
+ if (!workflow && !gotgenes)
22860
24157
  parsePiSubagentId(nativeSubagentId);
22861
24158
  const live = [...this.#sessions].find((session) => session.ownsNativeSession(parent.nativeSessionId));
22862
24159
  let reply;
22863
24160
  if (live) {
24161
+ if (gotgenes)
24162
+ return await live.readGotgenesChild(gotgenes, cwd);
22864
24163
  if (workflow)
22865
24164
  return await readPiWorkflowChild(await live.readSubagentHistory(cwd), parent.nativeSessionId, workflow);
22866
24165
  reply = await live.inspectSubagent(nativeSubagentId, cwd);
@@ -22872,6 +24171,8 @@ var PiAdapter = class {
22872
24171
  if (transport.state.sessionId !== parent.nativeSessionId)
22873
24172
  throw new Error("Pi Subagent parent identity mismatch");
22874
24173
  await transport.verifySessionCwd(cwd);
24174
+ if (gotgenes)
24175
+ return await readGotgenesChild(await transport.getEntries(), parent.nativeSessionId, gotgenes);
22875
24176
  if (workflow)
22876
24177
  return await readPiWorkflowChild(await transport.getEntries(), parent.nativeSessionId, workflow);
22877
24178
  if (!transport.inspectSubagent)
@@ -23003,7 +24304,7 @@ var PiAdapter = class {
23003
24304
  stage = "capabilities";
23004
24305
  const thinkingLevels = await transport.getAvailableThinkingLevels();
23005
24306
  this.#thinkingSelectionSupported = thinkingLevels !== null;
23006
- const normalized = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel);
24307
+ const normalized = normalizePiModelCatalog(models, nativeModelFromState(transport.state), thinkingLevels, transport.state.thinkingLevel, transport.state.modelReasoning ?? null);
23007
24308
  const fastModels = await transport.supportsFastMode?.() ? piFastModelKeys(models) : /* @__PURE__ */ new Set();
23008
24309
  const catalog = withPiFast(normalized, fastModels);
23009
24310
  await transport.close();