@liberseek/boft-cli-win32-arm64 0.8.5 → 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 +70 -20
  5. package/app/console-web.js +61 -18
  6. package/app/desktop-controller.mjs +1142 -69
  7. package/app/host-runtime.mjs +3804 -1949
  8. package/app/plugins/antigravity/plugin.mjs +77 -9
  9. package/app/plugins/claude-code/plugin.mjs +27 -6
  10. package/app/plugins/codebuddy/plugin.mjs +25 -0
  11. package/app/plugins/codex-usage/plugin.mjs +15 -0
  12. package/app/plugins/copilot/plugin.mjs +15 -0
  13. package/app/plugins/cursor-cli/plugin.mjs +43 -8
  14. package/app/plugins/deepseek-harness/plugin.mjs +472 -44
  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 +470 -387
  20. package/app/plugins/hermes/plugin.mjs +468 -196
  21. package/app/plugins/kimi-code/plugin.mjs +65 -3
  22. package/app/plugins/kiro-cli/plugin.mjs +15 -0
  23. package/app/plugins/muse/plugin.mjs +15 -0
  24. package/app/plugins/omp/plugin.mjs +15 -0
  25. package/app/plugins/opencode/plugin.mjs +15 -0
  26. package/app/plugins/pi/plugin.mjs +1595 -411
  27. package/app/plugins/qoder/plugin.mjs +9539 -8654
  28. package/app/plugins/qoder-cn/plugin.mjs +9539 -8654
  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 +25 -0
  33. package/app/plugins/zcode/plugin.mjs +157 -9
  34. package/app/renderer-extension.js +727 -274
  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")
@@ -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()
@@ -15558,7 +15558,7 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
15558
15558
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15559
15559
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15560
15560
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15561
- 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));
15562
15562
  var composerIndicatorsSchema = external_exports.array(external_exports.object({
15563
15563
  kind: external_exports.literal("countdown"),
15564
15564
  id: external_exports.string().min(1).max(64),
@@ -16136,6 +16136,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
16136
16136
  /** The text about to be steered; a Harness command always stops and restarts. */
16137
16137
  text: external_exports.string().optional()
16138
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);
16139
16154
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
16140
16155
  var threadSteeringInspectResultSchema = external_exports.object({
16141
16156
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -16766,8 +16781,8 @@ async function readCandidate(file2, signal) {
16766
16781
  const message3 = isRecord(entry.message) ? entry.message : null;
16767
16782
  if (!firstMessage && entry.type === "message" && message3?.role === "user") {
16768
16783
  const content = message3.content;
16769
- 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(" ") : "";
16770
- 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);
16771
16786
  }
16772
16787
  hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
16773
16788
  entries.set(entry.id, hasUser);
@@ -17286,8 +17301,8 @@ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17286
17301
  const descriptor = catalog.commands.find(({ id }) => id === commandId);
17287
17302
  if (!descriptor)
17288
17303
  return null;
17289
- const text2 = typeof argumentText === "string" ? argumentText.trim() : "";
17290
- return text2 ? `${descriptor.invocation} ${text2}` : descriptor.invocation;
17304
+ const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
17305
+ return text4 ? `${descriptor.invocation} ${text4}` : descriptor.invocation;
17291
17306
  }
17292
17307
  function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17293
17308
  if (!live)
@@ -17423,16 +17438,16 @@ var Diff = class {
17423
17438
  }
17424
17439
  }
17425
17440
  }
17426
- addToPath(path16, added, removed, oldPosInc, options) {
17427
- const last = path16.lastComponent;
17441
+ addToPath(path18, added, removed, oldPosInc, options) {
17442
+ const last = path18.lastComponent;
17428
17443
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17429
17444
  return {
17430
- oldPos: path16.oldPos + oldPosInc,
17445
+ oldPos: path18.oldPos + oldPosInc,
17431
17446
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17432
17447
  };
17433
17448
  } else {
17434
17449
  return {
17435
- oldPos: path16.oldPos + oldPosInc,
17450
+ oldPos: path18.oldPos + oldPosInc,
17436
17451
  lastComponent: { count: 1, added, removed, previousComponent: last }
17437
17452
  };
17438
17453
  }
@@ -17832,9 +17847,9 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader
17832
17847
  } }));
17833
17848
  }
17834
17849
  }
17835
- function splitLines(text2) {
17836
- const hasTrailingNl = text2.endsWith("\n");
17837
- 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");
17838
17853
  if (hasTrailingNl) {
17839
17854
  result.pop();
17840
17855
  } else {
@@ -18068,11 +18083,344 @@ function piNestedCallFileChanges(nestedCalls, cwd) {
18068
18083
  return projected;
18069
18084
  }
18070
18085
 
18071
- // dist/pi-subagents.js
18086
+ // dist/pi-message-item-id.js
18072
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
+ };
18073
18421
 
18074
18422
  // dist/pi-subagent-workflow.js
18075
- var PREFIX = "pi-subagents-workflow-v1:";
18423
+ var PREFIX2 = "pi-subagents-workflow-v1:";
18076
18424
  var STATES = {
18077
18425
  pending: "pending",
18078
18426
  running: "running",
@@ -18086,7 +18434,7 @@ var STATES = {
18086
18434
  function record2(value) {
18087
18435
  return typeof value === "object" && value !== null && !Array.isArray(value);
18088
18436
  }
18089
- function text(value, limit = 256) {
18437
+ function text2(value, limit = 256) {
18090
18438
  return typeof value === "string" && value.length > 0 && value.length <= limit;
18091
18439
  }
18092
18440
  function piWorkflowSummary(result) {
@@ -18094,15 +18442,15 @@ function piWorkflowSummary(result) {
18094
18442
  return null;
18095
18443
  const details = result.details;
18096
18444
  const summary = details.workflowChildren;
18097
- 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)
18098
18446
  return null;
18099
18447
  const children = [];
18100
18448
  const seen = /* @__PURE__ */ new Set();
18101
18449
  for (const child of summary.children) {
18102
- 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))
18103
18451
  return null;
18104
18452
  for (const key of ["agent", "sessionName", "model", "thinking"]) {
18105
- if (child[key] !== void 0 && !text(child[key], 2048))
18453
+ if (child[key] !== void 0 && !text2(child[key], 2048))
18106
18454
  return null;
18107
18455
  }
18108
18456
  const mappedState = STATES[child.state];
@@ -18126,15 +18474,15 @@ function piWorkflowSummary(result) {
18126
18474
  };
18127
18475
  }
18128
18476
  function piWorkflowSubagentId(address) {
18129
- 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");
18130
18478
  }
18131
18479
  function parsePiWorkflowSubagentId(id) {
18132
- if (!id.startsWith(PREFIX))
18480
+ if (!id.startsWith(PREFIX2))
18133
18481
  return null;
18134
18482
  if (id.length > 3e3)
18135
18483
  throw new Error("Invalid Pi workflow child identity");
18136
- const value = JSON.parse(Buffer.from(id.slice(PREFIX.length), "base64url").toString("utf8"));
18137
- 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]))
18138
18486
  throw new Error("Invalid Pi workflow child identity");
18139
18487
  const address = { workflowRunId: value[0], childId: value[1] };
18140
18488
  if (piWorkflowSubagentId(address) !== id)
@@ -18292,8 +18640,13 @@ var PiSubagents = class {
18292
18640
  #children = /* @__PURE__ */ new Map();
18293
18641
  #active = /* @__PURE__ */ new Map();
18294
18642
  #waiting = /* @__PURE__ */ new Map();
18643
+ gotgenes;
18295
18644
  constructor(emit) {
18296
18645
  this.emit = emit;
18646
+ this.gotgenes = new GotgenesSubagents(emit);
18647
+ }
18648
+ observeGotgenes(records, activeTurn) {
18649
+ this.gotgenes.observe(records, true, activeTurn, true);
18297
18650
  }
18298
18651
  observe(runs) {
18299
18652
  this.#apply(runs, true);
@@ -18347,6 +18700,9 @@ var PiSubagents = class {
18347
18700
  }
18348
18701
  }
18349
18702
  project(toolName, result, itemId2, callId) {
18703
+ const gotgenes = this.gotgenes.project(toolName, result, itemId2);
18704
+ if (gotgenes)
18705
+ return gotgenes;
18350
18706
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18351
18707
  if (workflow && (!callId || workflow.parentToolCallId === callId))
18352
18708
  return projectPiWorkflow(workflow, itemId2);
@@ -18357,6 +18713,8 @@ var PiSubagents = class {
18357
18713
  return children.length ? { type: "subagentDelegation", itemId: itemId2, operation: "spawn", subagents: children } : null;
18358
18714
  }
18359
18715
  start(turnId, toolName, result, itemId2, callId) {
18716
+ if (this.gotgenes.start(turnId, toolName, result, itemId2))
18717
+ return;
18360
18718
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18361
18719
  if (workflow && (!callId || workflow.parentToolCallId === callId)) {
18362
18720
  const key = `workflow:${workflow.workflowRunId}`;
@@ -18402,6 +18760,7 @@ var PiSubagents = class {
18402
18760
  this.emit({ type: "item.started", turnId, item });
18403
18761
  }
18404
18762
  finish(turnId) {
18763
+ this.gotgenes.finish(turnId);
18405
18764
  for (const [runId, waiting] of this.#waiting) {
18406
18765
  if (waiting.turnId === turnId)
18407
18766
  this.#waiting.delete(runId);
@@ -18449,15 +18808,15 @@ ${entry.text}`);
18449
18808
  nativeTurnRef: nativeTurnRefSchema.parse({
18450
18809
  harnessId: "pi",
18451
18810
  nativeSessionId: parentSessionId,
18452
- nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
18811
+ nativeTurnKey: `pi-subagent-${createHash3("sha256").update(id).digest("hex")}`,
18453
18812
  formatVersion: 1
18454
18813
  }),
18455
18814
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
18456
- items: texts.map((text2, index) => ({
18815
+ items: texts.map((text4, index) => ({
18457
18816
  item: {
18458
18817
  type: "agentMessage",
18459
- text: text2,
18460
- 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")}`)
18461
18820
  },
18462
18821
  outcome: { status: "succeeded" }
18463
18822
  })),
@@ -18605,22 +18964,149 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
18605
18964
  });
18606
18965
  }
18607
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
+
18608
19094
  // dist/pi-history.js
18609
19095
  var piHarnessId = harnessIdSchema.parse("pi");
18610
- function isRecord4(value) {
19096
+ function isRecord5(value) {
18611
19097
  return typeof value === "object" && value !== null && !Array.isArray(value);
18612
19098
  }
18613
- function textContent(value) {
19099
+ function textContent2(value) {
18614
19100
  if (typeof value === "string")
18615
19101
  return value;
18616
19102
  if (!Array.isArray(value))
18617
19103
  return "";
18618
- 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("");
18619
19105
  }
18620
19106
  function thinkingContent(value) {
18621
19107
  if (!Array.isArray(value))
18622
19108
  return "";
18623
- 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("");
18624
19110
  }
18625
19111
  function validatedEntry(value) {
18626
19112
  if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
@@ -18651,7 +19137,7 @@ function activePiEntries(history) {
18651
19137
  return reversed.reverse();
18652
19138
  }
18653
19139
  function message(entry) {
18654
- return entry.type === "message" && isRecord4(entry.message) ? entry.message : null;
19140
+ return entry.type === "message" && isRecord5(entry.message) ? entry.message : null;
18655
19141
  }
18656
19142
  function messageRole(entry) {
18657
19143
  const value = message(entry)?.role;
@@ -18666,7 +19152,7 @@ function assistantOutcome(entries) {
18666
19152
  if (!final)
18667
19153
  return { status: "unknown", reason: "Pi history has no Assistant terminal" };
18668
19154
  const stopReason = final.stopReason;
18669
- if (stopReason === "aborted") {
19155
+ if (piAssistantWasAborted(final)) {
18670
19156
  return { status: "cancelled", reason: "Pi Assistant was aborted" };
18671
19157
  }
18672
19158
  if (stopReason === "error") {
@@ -18679,7 +19165,7 @@ function assistantOutcome(entries) {
18679
19165
  }
18680
19166
  };
18681
19167
  }
18682
- if (typeof stopReason === "string" || textContent(final.content).length > 0) {
19168
+ if (typeof stopReason === "string" || textContent2(final.content).length > 0) {
18683
19169
  return { status: "succeeded" };
18684
19170
  }
18685
19171
  return { status: "unknown", reason: "Pi Assistant terminal is not classifiable" };
@@ -18696,8 +19182,8 @@ function itemOutcome(outcome) {
18696
19182
  return { status: "succeeded" };
18697
19183
  }
18698
19184
  function toolOutput(value) {
18699
- const text2 = textContent(value);
18700
- 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;
18701
19187
  }
18702
19188
  function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18703
19189
  const items = [];
@@ -18720,37 +19206,52 @@ function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18720
19206
  }
18721
19207
  return items;
18722
19208
  }
18723
- function snapshotItems(entries, outcome, subagents, cwd) {
19209
+ function snapshotItems(entries, messageIdentities, notices, outcome, subagents, cwd) {
18724
19210
  const snapshots = [];
18725
19211
  const toolCalls = /* @__PURE__ */ new Map();
18726
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
+ }
18727
19226
  const nativeMessage = message(entry);
18728
19227
  if (!nativeMessage)
18729
19228
  continue;
18730
19229
  const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
18731
19230
  if (nativeMessage.role === "assistant") {
18732
- const text2 = textContent(content);
19231
+ const text4 = textContent2(content);
18733
19232
  const reasoning = thinkingContent(content);
18734
19233
  let projectedText = false;
18735
19234
  let projectedReasoning = false;
18736
19235
  for (const [ordinal, part] of content.entries()) {
18737
- if (!isRecord4(part))
19236
+ if (!isRecord5(part))
18738
19237
  continue;
18739
19238
  if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
18740
19239
  const item2 = {
18741
19240
  type: "reasoning",
18742
- itemId: itemId(entry.id, "reasoning", 0),
19241
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "reasoning") ?? itemId(entry.id, "reasoning", 0),
18743
19242
  text: reasoning
18744
19243
  };
18745
19244
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18746
19245
  projectedReasoning = true;
18747
19246
  continue;
18748
19247
  }
18749
- if (part.type === "text" && !projectedText && text2.length > 0) {
19248
+ if (part.type === "text" && !projectedText && text4.length > 0) {
19249
+ const phase = piAssistantPhase(nativeMessage);
18750
19250
  const item2 = {
18751
19251
  type: "agentMessage",
18752
- itemId: itemId(entry.id, "assistant", 0),
18753
- text: text2
19252
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "assistant") ?? itemId(entry.id, "assistant", 0),
19253
+ text: text4,
19254
+ ...phase ? { phase } : {}
18754
19255
  };
18755
19256
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18756
19257
  projectedText = true;
@@ -18778,9 +19279,24 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18778
19279
  if (!call || call.name !== nativeMessage.toolName)
18779
19280
  continue;
18780
19281
  const output = toolOutput(nativeMessage.content);
18781
- const item = {
18782
- 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 = {
18783
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",
18784
19300
  toolName: call.name,
18785
19301
  arguments: call.arguments,
18786
19302
  ...output ? { output } : {}
@@ -18811,6 +19327,10 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18811
19327
  function modelChange(entry) {
18812
19328
  return entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string" ? { provider: entry.provider, id: entry.modelId } : null;
18813
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
+ }
18814
19334
  function turnStarts(active) {
18815
19335
  const starts = [];
18816
19336
  let terminal = true;
@@ -18818,6 +19338,8 @@ function turnStarts(active) {
18818
19338
  for (const [index, entry] of active.entries()) {
18819
19339
  const role = messageRole(entry);
18820
19340
  if (role === "user") {
19341
+ if (pending && isEmptyWakeup(entry))
19342
+ continue;
18821
19343
  starts.push({ entry, index });
18822
19344
  pending = null;
18823
19345
  terminal = false;
@@ -18834,6 +19356,8 @@ function turnStarts(active) {
18834
19356
  }
18835
19357
  function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0)) {
18836
19358
  const active = activePiEntries(history);
19359
+ const { identities } = piHistoryMessageIdentities(state2.sessionId, active);
19360
+ const { notices } = piHistoryNotices(state2.sessionId, active);
18837
19361
  const turns = [];
18838
19362
  const starts = turnStarts(active);
18839
19363
  const byIndex = new Map(starts.map((start, ordinal) => [start.index, ordinal]));
@@ -18855,7 +19379,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18855
19379
  const end = next?.index ?? active.length;
18856
19380
  const entries = active.slice(index, end);
18857
19381
  const outcome = assistantOutcome(entries);
18858
- const userText = textContent(message(user)?.content);
19382
+ const userText = textContent2(message(user)?.content);
18859
19383
  const nativeTurnRef = nativeTurnRefSchema.parse({
18860
19384
  harnessId: piHarnessId,
18861
19385
  nativeSessionId: state2.sessionId,
@@ -18872,7 +19396,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18872
19396
  nativeTurnRef,
18873
19397
  ...!next || messageRole(next.entry) === "user" ? { checkpoint } : {},
18874
19398
  input: messageRole(user) === "user" ? [{ type: "text", text: userText }] : [],
18875
- items: snapshotItems(entries, outcome, subagents, state2.cwd),
19399
+ items: snapshotItems(entries, identities, notices, outcome, subagents, state2.cwd),
18876
19400
  outcome,
18877
19401
  ...effectiveModel ? { model: encodePiModelRef(effectiveModel) } : {}
18878
19402
  });
@@ -18907,14 +19431,14 @@ function resolvePiForkBoundary(history, checkpointId) {
18907
19431
  }
18908
19432
 
18909
19433
  // dist/pi-usage.js
18910
- function isRecord5(value) {
19434
+ function isRecord6(value) {
18911
19435
  return typeof value === "object" && value !== null && !Array.isArray(value);
18912
19436
  }
18913
19437
  function nonNegativeSafeInteger(value) {
18914
19438
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
18915
19439
  }
18916
19440
  function optionalPiCacheHitRatePercent(value) {
18917
- if (!isRecord5(value) || value.role !== "assistant" || !isRecord5(value.usage))
19441
+ if (!isRecord6(value) || value.role !== "assistant" || !isRecord6(value.usage))
18918
19442
  return null;
18919
19443
  const input = nonNegativeSafeInteger(value.usage.input);
18920
19444
  const cacheRead = nonNegativeSafeInteger(value.usage.cacheRead);
@@ -18927,20 +19451,20 @@ function optionalPiCacheHitRatePercent(value) {
18927
19451
  function latestPiCacheHitRatePercent(history) {
18928
19452
  let latest = null;
18929
19453
  for (const entry of activePiEntries(history)) {
18930
- if (entry.type === "message" && isRecord5(entry.message) && entry.message.role === "assistant") {
19454
+ if (entry.type === "message" && isRecord6(entry.message) && entry.message.role === "assistant") {
18931
19455
  latest = optionalPiCacheHitRatePercent(entry.message);
18932
19456
  }
18933
19457
  }
18934
19458
  return latest;
18935
19459
  }
18936
19460
  function responseData(response, operation) {
18937
- if (!isRecord5(response.data)) {
19461
+ if (!isRecord6(response.data)) {
18938
19462
  throw new Error(`Pi RPC ${operation} response has no data`);
18939
19463
  }
18940
19464
  return response.data;
18941
19465
  }
18942
19466
  function contextUsage(value) {
18943
- if (!isRecord5(value))
19467
+ if (!isRecord6(value))
18944
19468
  throw new Error("Pi RPC context Usage is invalid");
18945
19469
  return parseHostUsage({
18946
19470
  contextUsedTokens: value.tokens,
@@ -18950,15 +19474,15 @@ function contextUsage(value) {
18950
19474
  function parsePiSessionUsage(response) {
18951
19475
  const data = responseData(response, "Session stats");
18952
19476
  const tokens = data.tokens;
18953
- if (tokens !== void 0 && !isRecord5(tokens)) {
19477
+ if (tokens !== void 0 && !isRecord6(tokens)) {
18954
19478
  throw new Error("Pi RPC Session stats tokens are invalid");
18955
19479
  }
18956
19480
  return parseHostUsage({
18957
- ...isRecord5(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
18958
- ...isRecord5(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
18959
- ...isRecord5(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
18960
- ...isRecord5(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
18961
- ...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 } : {},
18962
19486
  ...data.cost !== void 0 ? { totalCostUsd: data.cost } : {},
18963
19487
  ...data.contextUsage !== void 0 ? contextUsage(data.contextUsage) : {}
18964
19488
  });
@@ -18977,9 +19501,9 @@ function optionalPiStateContextUsage(value) {
18977
19501
  }
18978
19502
  }
18979
19503
  function piUsageRecord(message3, extra = {}) {
18980
- if (!isRecord5(message3) || message3.role !== "assistant")
19504
+ if (!isRecord6(message3) || message3.role !== "assistant")
18981
19505
  return null;
18982
- const usage = isRecord5(message3.usage) ? message3.usage : null;
19506
+ const usage = isRecord6(message3.usage) ? message3.usage : null;
18983
19507
  const input = nonNegativeSafeInteger(usage?.input);
18984
19508
  const output = nonNegativeSafeInteger(usage?.output);
18985
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;
@@ -19016,17 +19540,17 @@ function piUsageHistory(history) {
19016
19540
  for (const entry of history.entries) {
19017
19541
  if (entry.type !== "message")
19018
19542
  continue;
19019
- const record7 = piUsageRecord(entry.message, { historical: true });
19020
- if (record7?.kind === "request")
19021
- requests.push(record7.request);
19022
- 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")
19023
19547
  complete = false;
19024
19548
  }
19025
19549
  return { requests, complete };
19026
19550
  }
19027
19551
 
19028
19552
  // dist/pi-usage-statistics.js
19029
- function isRecord6(value) {
19553
+ function isRecord7(value) {
19030
19554
  return typeof value === "object" && value !== null && !Array.isArray(value);
19031
19555
  }
19032
19556
  function piUserText(content) {
@@ -19034,11 +19558,11 @@ function piUserText(content) {
19034
19558
  return content;
19035
19559
  if (!Array.isArray(content))
19036
19560
  return void 0;
19037
- 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(" ");
19038
19562
  }
19039
19563
  async function readPiUsage(file2, signal) {
19040
19564
  const entries = [];
19041
- const header = await jsonlHeader(file2, (record7) => record7.type === "session", signal);
19565
+ const header = await jsonlHeader(file2, (record9) => record9.type === "session", signal);
19042
19566
  let name;
19043
19567
  const session = {
19044
19568
  sessionId: typeof header?.id === "string" ? header.id : void 0,
@@ -19055,11 +19579,11 @@ async function readPiUsage(file2, signal) {
19055
19579
  if (!name && message3?.role === "user") {
19056
19580
  name = usageSessionTitle(piUserText(message3.content));
19057
19581
  }
19058
- const record7 = piUsageRecord(line.message);
19059
- if (record7?.kind !== "request")
19582
+ const record9 = piUsageRecord(line.message);
19583
+ if (record9?.kind !== "request")
19060
19584
  continue;
19061
19585
  const at = nativeTimeMs(message3.timestamp) ?? nativeTimeMs(line.timestamp);
19062
- const entry = at !== null && usageEntryFromRequest(record7.request, at);
19586
+ const entry = at !== null && usageEntryFromRequest(record9.request, at);
19063
19587
  if (!entry)
19064
19588
  continue;
19065
19589
  if (!(typeof message3.responseId === "string" && message3.responseId.length > 0)) {
@@ -19080,9 +19604,9 @@ function createPiUsageStatistics(environment) {
19080
19604
  }
19081
19605
 
19082
19606
  // dist/account-balance.js
19083
- import { readFile } from "node:fs/promises";
19084
- import { homedir as homedir2 } from "node:os";
19085
- 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";
19086
19610
  var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
19087
19611
  var SUB2API_USAGE_PATH = "/v1/usage";
19088
19612
  var REQUEST_TIMEOUT_MS = 1e4;
@@ -19091,18 +19615,18 @@ function agentDirectory(environment) {
19091
19615
  const configured = environment.PI_CODING_AGENT_DIR?.trim();
19092
19616
  if (configured)
19093
19617
  return configured;
19094
- return path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".pi", "agent");
19618
+ return path8.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".pi", "agent");
19095
19619
  }
19096
- 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 : {};
19097
19621
  async function deepSeekApiKey(environment) {
19098
- const auth = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "auth.json"), "utf8")));
19099
- 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);
19100
19624
  if (deepseek.type !== "api_key")
19101
19625
  return void 0;
19102
19626
  return typeof deepseek.key === "string" && deepseek.key.trim() ? deepseek.key : void 0;
19103
19627
  }
19104
19628
  function projectSub2ApiUsage(payload, providerId) {
19105
- const data = record4(payload);
19629
+ const data = record6(payload);
19106
19630
  if (data.isValid === false)
19107
19631
  return null;
19108
19632
  if (data.mode !== "unrestricted" && data.mode !== "quota_limited")
@@ -19112,7 +19636,7 @@ function projectSub2ApiUsage(payload, providerId) {
19112
19636
  return null;
19113
19637
  const wallet = finiteAmount(data.balance);
19114
19638
  const remaining = finiteAmount(data.remaining);
19115
- const quotaRemaining = finiteAmount(record4(data.quota).remaining);
19639
+ const quotaRemaining = finiteAmount(record6(data.quota).remaining);
19116
19640
  const amount = wallet ?? remaining ?? quotaRemaining;
19117
19641
  if (amount === null)
19118
19642
  return null;
@@ -19132,10 +19656,10 @@ function finiteAmount(value) {
19132
19656
  return Number.isFinite(amount) && amount >= 0 ? amount : null;
19133
19657
  }
19134
19658
  function projectDeepSeekBalance(payload) {
19135
- const data = record4(payload);
19659
+ const data = record6(payload);
19136
19660
  if (!Array.isArray(data.balance_infos))
19137
19661
  return null;
19138
- const first = record4(data.balance_infos[0]);
19662
+ const first = record6(data.balance_infos[0]);
19139
19663
  const amount = finiteAmount(first.total_balance);
19140
19664
  const currency = typeof first.currency === "string" ? first.currency.trim() : "";
19141
19665
  if (amount === null || !currency)
@@ -19164,11 +19688,11 @@ function usageEndpoint(baseUrl) {
19164
19688
  }
19165
19689
  async function configuredSub2ApiProviders(environment) {
19166
19690
  try {
19167
- const models = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "models.json"), "utf8")));
19168
- 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);
19169
19693
  const found = [];
19170
19694
  for (const [id, definition] of Object.entries(providers)) {
19171
- const provider = record4(definition);
19695
+ const provider = record6(definition);
19172
19696
  const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
19173
19697
  const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
19174
19698
  if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
@@ -19226,21 +19750,21 @@ async function fetchPiAccountBalance(input) {
19226
19750
  }
19227
19751
 
19228
19752
  // dist/pi-credential-imports.js
19229
- import { randomUUID } from "node:crypto";
19753
+ import { randomUUID as randomUUID2 } from "node:crypto";
19230
19754
  import { execFile as execFile2 } from "node:child_process";
19231
19755
  import { promisify } from "node:util";
19232
19756
  import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
19233
19757
  import { realpath as realpath2 } from "node:fs/promises";
19234
19758
  import os4 from "node:os";
19235
- import path9 from "node:path";
19759
+ import path10 from "node:path";
19236
19760
  import { pathToFileURL } from "node:url";
19237
19761
 
19238
19762
  // dist/command.js
19239
19763
  import fs2 from "node:fs";
19240
- import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
19241
- import path8 from "node:path";
19764
+ import { homedir as homedir4, tmpdir as tmpdir2 } from "node:os";
19765
+ import path9 from "node:path";
19242
19766
  var PI_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
19243
- var PI_PACKAGE_PATH = path8.join("node_modules", "@earendil-works", "pi-coding-agent");
19767
+ var PI_PACKAGE_PATH = path9.join("node_modules", "@earendil-works", "pi-coding-agent");
19244
19768
  var piDiscoverySpec = {
19245
19769
  id: "pi",
19246
19770
  command: "pi",
@@ -19266,18 +19790,18 @@ function resolvePiExecutable(input, dependencies = {}) {
19266
19790
  return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
19267
19791
  }
19268
19792
  function findPiPackageDirectory(executable) {
19269
- let directory = path8.dirname(executable);
19793
+ let directory = path9.dirname(executable);
19270
19794
  while (true) {
19271
- for (const candidate of [directory, path8.join(directory, PI_PACKAGE_PATH)]) {
19795
+ for (const candidate of [directory, path9.join(directory, PI_PACKAGE_PATH)]) {
19272
19796
  try {
19273
- const manifest = JSON.parse(fs2.readFileSync(path8.join(candidate, "package.json"), "utf8"));
19797
+ const manifest = JSON.parse(fs2.readFileSync(path9.join(candidate, "package.json"), "utf8"));
19274
19798
  if (typeof manifest === "object" && manifest !== null && "name" in manifest && manifest.name === PI_PACKAGE_NAME) {
19275
19799
  return candidate;
19276
19800
  }
19277
19801
  } catch {
19278
19802
  }
19279
19803
  }
19280
- const parent = path8.dirname(directory);
19804
+ const parent = path9.dirname(directory);
19281
19805
  if (parent === directory)
19282
19806
  return void 0;
19283
19807
  directory = parent;
@@ -19285,16 +19809,16 @@ function findPiPackageDirectory(executable) {
19285
19809
  }
19286
19810
  function findPiCliEntry(packageDirectory) {
19287
19811
  try {
19288
- const manifest = JSON.parse(fs2.readFileSync(path8.join(packageDirectory, "package.json"), "utf8"));
19812
+ const manifest = JSON.parse(fs2.readFileSync(path9.join(packageDirectory, "package.json"), "utf8"));
19289
19813
  if (typeof manifest !== "object" || manifest === null || !("bin" in manifest))
19290
19814
  return void 0;
19291
19815
  const bin = manifest.bin;
19292
19816
  const entry = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && "pi" in bin ? bin.pi : void 0;
19293
19817
  if (typeof entry !== "string" || !entry.trim())
19294
19818
  return void 0;
19295
- const resolved = path8.resolve(packageDirectory, entry);
19296
- const relative = path8.relative(packageDirectory, resolved);
19297
- if (relative === ".." || relative.startsWith(`..${path8.sep}`) || path8.isAbsolute(relative) || !fs2.statSync(resolved).isFile()) {
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()) {
19298
19822
  return void 0;
19299
19823
  }
19300
19824
  return resolved;
@@ -19303,11 +19827,11 @@ function findPiCliEntry(packageDirectory) {
19303
19827
  }
19304
19828
  }
19305
19829
  function isFilesystemRoot(cwd) {
19306
- const resolved = path8.resolve(cwd);
19307
- return resolved === path8.parse(resolved).root;
19830
+ const resolved = path9.resolve(cwd);
19831
+ return resolved === path9.parse(resolved).root;
19308
19832
  }
19309
19833
  function writableDirectory(candidate) {
19310
- if (!candidate || !path8.isAbsolute(candidate) || isFilesystemRoot(candidate))
19834
+ if (!candidate || !path9.isAbsolute(candidate) || isFilesystemRoot(candidate))
19311
19835
  return void 0;
19312
19836
  try {
19313
19837
  if (!fs2.statSync(candidate).isDirectory())
@@ -19320,19 +19844,19 @@ function writableDirectory(candidate) {
19320
19844
  }
19321
19845
  function resolvePiInspectCwd(inputCwd, environment = process.env) {
19322
19846
  if (typeof inputCwd === "string" && inputCwd.length > 0 && !isFilesystemRoot(inputCwd)) {
19323
- return path8.resolve(inputCwd);
19847
+ return path9.resolve(inputCwd);
19324
19848
  }
19325
- const candidates = [environment.USERPROFILE, environment.HOME, homedir3(), tmpdir2()];
19849
+ const candidates = [environment.USERPROFILE, environment.HOME, homedir4(), tmpdir2()];
19326
19850
  for (const candidate of candidates) {
19327
19851
  const usable = writableDirectory(candidate);
19328
19852
  if (usable)
19329
19853
  return usable;
19330
19854
  }
19331
- return inputCwd && inputCwd.length > 0 ? path8.resolve(inputCwd) : process.cwd();
19855
+ return inputCwd && inputCwd.length > 0 ? path9.resolve(inputCwd) : process.cwd();
19332
19856
  }
19333
19857
 
19334
19858
  // dist/pi-credential-imports.js
19335
- var PREFIX2 = "codexhost-account-";
19859
+ var PREFIX3 = "codexhost-account-";
19336
19860
  function object2(value) {
19337
19861
  return typeof value === "object" && value !== null && !Array.isArray(value);
19338
19862
  }
@@ -19373,7 +19897,7 @@ function describeOauth(credential) {
19373
19897
  };
19374
19898
  }
19375
19899
  function writeAuth(filename, content) {
19376
- const temporary = `${filename}.${randomUUID()}.tmp`;
19900
+ const temporary = `${filename}.${randomUUID2()}.tmp`;
19377
19901
  try {
19378
19902
  writeFileSync(temporary, content, { flag: "wx", mode: 384 });
19379
19903
  renameSync(temporary, filename);
@@ -19382,8 +19906,8 @@ function writeAuth(filename, content) {
19382
19906
  }
19383
19907
  }
19384
19908
  function removeOwnedFiles(dir) {
19385
- rmSync(path9.join(dir, "index.ts"), { force: true });
19386
- 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 });
19387
19911
  try {
19388
19912
  rmdirSync(dir);
19389
19913
  } catch {
@@ -19395,13 +19919,13 @@ async function installation(command, environment, authPath) {
19395
19919
  const cliEntry = directory ? findPiCliEntry(directory) : void 0;
19396
19920
  if (!directory || !cliEntry)
19397
19921
  throw new Error("Pi credential import requires a supported npm Pi installation");
19398
- const storage = await import(pathToFileURL(path9.join(directory, "dist/core/auth-storage.js")).href);
19399
- const ai = path9.join(directory, "node_modules/@earendil-works/pi-ai/dist");
19400
- const all = await import(pathToFileURL(path9.join(ai, "providers/all.js")).href);
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);
19401
19925
  const providers = all.getBuiltinProviders();
19402
19926
  const providerModules = {
19403
- "openai-codex": pathToFileURL(path9.join(ai, "providers/openai-codex.js")).href,
19404
- 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
19405
19929
  };
19406
19930
  for (const [id, url2] of Object.entries(providerModules)) {
19407
19931
  const module = await import(url2);
@@ -19415,8 +19939,8 @@ async function installation(command, environment, authPath) {
19415
19939
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
19416
19940
  async configuredProviderNames() {
19417
19941
  const { stdout } = await promisify(execFile2)(process.execPath, [cliEntry, "--offline", "--no-approve", "--list-models"], {
19418
- cwd: existsSync(path9.dirname(authPath)) ? path9.dirname(authPath) : os4.homedir(),
19419
- env: { ...environment, PI_CODING_AGENT_DIR: path9.dirname(authPath), PI_OFFLINE: "1" },
19942
+ cwd: existsSync(path10.dirname(authPath)) ? path10.dirname(authPath) : os4.homedir(),
19943
+ env: { ...environment, PI_CODING_AGENT_DIR: path10.dirname(authPath), PI_OFFLINE: "1" },
19420
19944
  timeout: 15e3,
19421
19945
  maxBuffer: 4 * 1024 * 1024
19422
19946
  });
@@ -19446,26 +19970,26 @@ export default async function (pi) {
19446
19970
  }
19447
19971
  function createPiCredentialImports(options = {}) {
19448
19972
  const env = { ...process.env, ...options.environment };
19449
- const agentDir = env.PI_CODING_AGENT_DIR ?? path9.join(env.HOME ?? os4.homedir(), ".pi/agent");
19450
- const authPath = path9.join(agentDir, "auth.json");
19451
- 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");
19452
19976
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
19453
19977
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
19454
- const location = (name) => path9.join(extensionsDir, `${PREFIX2}${credentialImportNameSchema.parse(name)}`);
19978
+ const location = (name) => path10.join(extensionsDir, `${PREFIX3}${credentialImportNameSchema.parse(name)}`);
19455
19979
  const readRecord = (name) => {
19456
19980
  const dir = location(name);
19457
19981
  if (lstatSync(dir).isSymbolicLink())
19458
19982
  throw new Error("Imported configuration was changed; manage it in Pi");
19459
- const value = JSON.parse(readFileSync(path9.join(dir, "import.json"), "utf8"));
19983
+ const value = JSON.parse(readFileSync(path10.join(dir, "import.json"), "utf8"));
19460
19984
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
19461
19985
  throw new Error("Invalid import metadata");
19462
- const record7 = value.record;
19463
- if (!object2(record7))
19986
+ const record9 = value.record;
19987
+ if (!object2(record9))
19464
19988
  throw new Error("Invalid import metadata");
19465
19989
  value.record = credentialImportRecordSchema.parse({
19466
- name: record7.name,
19467
- source: record7.source,
19468
- importedAt: record7.importedAt
19990
+ name: record9.name,
19991
+ source: record9.source,
19992
+ importedAt: record9.importedAt
19469
19993
  });
19470
19994
  if (value.record.name !== name)
19471
19995
  throw new Error("Import identity mismatch");
@@ -19473,7 +19997,7 @@ function createPiCredentialImports(options = {}) {
19473
19997
  };
19474
19998
  const owned = (meta3, auth) => {
19475
19999
  const credential = auth[meta3.record.name];
19476
- const file2 = path9.join(location(meta3.record.name), "index.ts");
20000
+ const file2 = path10.join(location(meta3.record.name), "index.ts");
19477
20001
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
19478
20002
  };
19479
20003
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -19482,12 +20006,12 @@ function createPiCredentialImports(options = {}) {
19482
20006
  return [];
19483
20007
  const result = [];
19484
20008
  for (const entry of readdirSync(extensionsDir)) {
19485
- if (!entry.startsWith(PREFIX2))
20009
+ if (!entry.startsWith(PREFIX3))
19486
20010
  continue;
19487
- const name = entry.slice(PREFIX2.length);
20011
+ const name = entry.slice(PREFIX3.length);
19488
20012
  if (!credentialImportNameSchema.safeParse(name).success)
19489
20013
  continue;
19490
- if (!existsSync(path9.join(location(name), "import.json")))
20014
+ if (!existsSync(path10.join(location(name), "import.json")))
19491
20015
  continue;
19492
20016
  try {
19493
20017
  const meta3 = readRecord(name);
@@ -19508,7 +20032,7 @@ function createPiCredentialImports(options = {}) {
19508
20032
  },
19509
20033
  async listOthers() {
19510
20034
  const auth = readAuth();
19511
- const ours = new Set(ownedRecords(auth).map((record7) => record7.name));
20035
+ const ours = new Set(ownedRecords(auth).map((record9) => record9.name));
19512
20036
  const result = /* @__PURE__ */ new Map();
19513
20037
  const usable = (provider) => Boolean(provider) && provider.length <= 128 && !ours.has(provider) && !result.has(provider);
19514
20038
  for (const [provider, credential] of Object.entries(auth)) {
@@ -19521,7 +20045,7 @@ function createPiCredentialImports(options = {}) {
19521
20045
  ...describeOauth(credential)
19522
20046
  });
19523
20047
  }
19524
- const modelsPath = path9.join(agentDir, "models.json");
20048
+ const modelsPath = path10.join(agentDir, "models.json");
19525
20049
  if (existsSync(modelsPath)) {
19526
20050
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
19527
20051
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -19542,8 +20066,8 @@ function createPiCredentialImports(options = {}) {
19542
20066
  throw new Error("Unsupported credential source");
19543
20067
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
19544
20068
  throw new Error("Provider name already exists; choose another name");
19545
- const owner = randomUUID();
19546
- const record7 = credentialImportRecordSchema.parse({
20069
+ const owner = randomUUID2();
20070
+ const record9 = credentialImportRecordSchema.parse({
19547
20071
  name,
19548
20072
  source: transfer.source,
19549
20073
  importedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -19555,15 +20079,15 @@ function createPiCredentialImports(options = {}) {
19555
20079
  try {
19556
20080
  sdk.backend.withLock((current) => {
19557
20081
  const auth = parseAuth(current);
19558
- const modelsPath = path9.join(agentDir, "models.json");
20082
+ const modelsPath = path10.join(agentDir, "models.json");
19559
20083
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
19560
- 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`)))
19561
20085
  throw new Error("Provider name already exists; choose another name");
19562
20086
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
19563
20087
  mkdirSync(dir, { mode: 448 });
19564
20088
  created = true;
19565
- writeFileSync(path9.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record7, extension }), { flag: "wx", mode: 384 });
19566
- 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 });
19567
20091
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
19568
20092
  saveAuth(auth);
19569
20093
  committed = true;
@@ -19582,7 +20106,7 @@ function createPiCredentialImports(options = {}) {
19582
20106
  const auth = parseAuth(current);
19583
20107
  if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
19584
20108
  throw new Error("Import ownership or source account changed; refusing replacement");
19585
- const metadataPath = path9.join(location(name), "import.json");
20109
+ const metadataPath = path10.join(location(name), "import.json");
19586
20110
  const previous = readFileSync(metadataPath, "utf8");
19587
20111
  const updated = {
19588
20112
  ...meta3,
@@ -19617,10 +20141,10 @@ function createPiCredentialImports(options = {}) {
19617
20141
  }
19618
20142
 
19619
20143
  // dist/pi-fast-mode.js
19620
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
19621
- import { mkdir, readFile as readFile2, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
19622
- import { homedir as homedir4 } from "node:os";
19623
- 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";
19624
20148
  var PI_FAST_COMMAND = "codexhost-fast-mode";
19625
20149
  var PI_FAST_ACK = "codexhost-fast-mode:";
19626
20150
  var PI_FAST_EXTENSION = `export default function(pi) {
@@ -19670,24 +20194,24 @@ var PI_FAST_EXTENSION = `export default function(pi) {
19670
20194
  }
19671
20195
  `;
19672
20196
  async function ensurePiFastExtension(environment) {
19673
- const digest = createHash2("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
19674
- const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path10.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".codexhost");
19675
- const directory = path10.resolve(dataDirectory, "extensions", "pi-codex-fast");
19676
- const file2 = path10.join(directory, `${digest}.mjs`);
19677
- 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)
19678
20202
  return file2;
19679
- await mkdir(directory, { recursive: true });
19680
- const temporary = `${file2}.${randomUUID2()}.tmp`;
20203
+ await mkdir2(directory, { recursive: true });
20204
+ const temporary = `${file2}.${randomUUID3()}.tmp`;
19681
20205
  try {
19682
- await writeFile2(temporary, PI_FAST_EXTENSION, { mode: 384 });
20206
+ await writeFile3(temporary, PI_FAST_EXTENSION, { mode: 384 });
19683
20207
  try {
19684
- await rename(temporary, file2);
20208
+ await rename2(temporary, file2);
19685
20209
  } catch (error51) {
19686
- if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
20210
+ if (await readFile3(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
19687
20211
  throw error51;
19688
20212
  }
19689
20213
  } finally {
19690
- await rm2(temporary, { force: true });
20214
+ await rm3(temporary, { force: true });
19691
20215
  }
19692
20216
  return file2;
19693
20217
  }
@@ -19704,15 +20228,15 @@ function withPiFast(catalog, supported) {
19704
20228
  // dist/pi-empty-session.js
19705
20229
  import { createReadStream as createReadStream3 } from "node:fs";
19706
20230
  import { createInterface as createInterface3 } from "node:readline";
19707
- import { randomUUID as randomUUID3 } from "node:crypto";
19708
- import { link, open as open2, rm as rm3 } from "node:fs/promises";
19709
- 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";
19710
20234
 
19711
20235
  // dist/pi-session-file.js
19712
20236
  import { open, realpath as realpath3 } from "node:fs/promises";
19713
20237
  var MAX_SESSION_HEADER_BYTES = 64 * 1024;
19714
20238
  var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
19715
- function isRecord7(value) {
20239
+ function isRecord8(value) {
19716
20240
  return typeof value === "object" && value !== null && !Array.isArray(value);
19717
20241
  }
19718
20242
  async function readPiSessionHeader(sessionFile) {
@@ -19732,7 +20256,7 @@ async function readPiSessionHeader(sessionFile) {
19732
20256
  } catch {
19733
20257
  throw new Error("Pi Session header is not valid JSON");
19734
20258
  }
19735
- 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) {
19736
20260
  throw new Error("Pi Session header is invalid");
19737
20261
  }
19738
20262
  return {
@@ -19765,7 +20289,7 @@ async function verifyPiSessionCwd(input) {
19765
20289
  async function persistEmptyPiSession(input) {
19766
20290
  const { state: state2, history, sourceSessionFile, sourceSessionId, cwd } = input;
19767
20291
  const destination = state2.sessionFile;
19768
- 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)
19769
20293
  throw new Error("Pi empty Session is not an independent empty native fork");
19770
20294
  await verifyPiSessionCwd({
19771
20295
  sessionFile: sourceSessionFile,
@@ -19789,7 +20313,7 @@ async function persistEmptyPiSession(input) {
19789
20313
  cwd,
19790
20314
  parentSession: sourceSessionFile
19791
20315
  };
19792
- const temporary = path11.join(path11.dirname(destination), `.codexhost-${randomUUID3()}.tmp`);
20316
+ const temporary = path12.join(path12.dirname(destination), `.codexhost-${randomUUID4()}.tmp`);
19793
20317
  try {
19794
20318
  const file2 = await open2(temporary, "wx", 384);
19795
20319
  try {
@@ -19800,7 +20324,7 @@ async function persistEmptyPiSession(input) {
19800
20324
  }
19801
20325
  await link(temporary, destination);
19802
20326
  if (process.platform !== "win32") {
19803
- const directory = await open2(path11.dirname(destination), "r");
20327
+ const directory = await open2(path12.dirname(destination), "r");
19804
20328
  try {
19805
20329
  await directory.sync();
19806
20330
  } finally {
@@ -19808,7 +20332,7 @@ async function persistEmptyPiSession(input) {
19808
20332
  }
19809
20333
  }
19810
20334
  } finally {
19811
- await rm3(temporary, { force: true });
20335
+ await rm4(temporary, { force: true });
19812
20336
  }
19813
20337
  }
19814
20338
  async function readPiEmptySessionConfiguration(sessionFile) {
@@ -19864,20 +20388,20 @@ async function readPiEmptySessionConfiguration(sessionFile) {
19864
20388
  }
19865
20389
 
19866
20390
  // dist/pi-adapter.js
19867
- import { randomUUID as randomUUID6 } from "node:crypto";
19868
- import path15 from "node:path";
20391
+ import { randomUUID as randomUUID7 } from "node:crypto";
20392
+ import path17 from "node:path";
19869
20393
 
19870
20394
  // dist/pi-workflow-child-history.js
19871
- import { createHash as createHash3 } from "node:crypto";
20395
+ import { createHash as createHash6 } from "node:crypto";
19872
20396
  import { constants } from "node:fs";
19873
20397
  import { open as open3 } from "node:fs/promises";
19874
- import path12 from "node:path";
19875
- function record5(value) {
20398
+ import path13 from "node:path";
20399
+ function record7(value) {
19876
20400
  return typeof value === "object" && value !== null && !Array.isArray(value);
19877
20401
  }
19878
20402
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
19879
- async function childHistory(file2, parentSessionId, identity) {
19880
- if (!path12.isAbsolute(file2))
20403
+ async function childHistory(file2, parentSessionId, identity, validateParent = false) {
20404
+ if (!path13.isAbsolute(file2))
19881
20405
  throw new Error("Pi child Session path is not absolute");
19882
20406
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
19883
20407
  try {
@@ -19890,12 +20414,14 @@ async function childHistory(file2, parentSessionId, identity) {
19890
20414
  throw new Error("Pi child Session exceeds read bounds");
19891
20415
  const values = buffer.subarray(0, bytesRead).toString("utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
19892
20416
  const header = values[0];
19893
- 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)
19894
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");
19895
20421
  const entries = [];
19896
20422
  for (const entry of values.slice(1)) {
19897
20423
  const parsed = jsonValueSchema.safeParse(entry);
19898
- if (!parsed.success || !record5(parsed.data) || typeof parsed.data.id !== "string")
20424
+ if (!parsed.success || !record7(parsed.data) || typeof parsed.data.id !== "string")
19899
20425
  throw new Error("Malformed Pi child Session entry");
19900
20426
  entries.push(parsed.data);
19901
20427
  }
@@ -19905,7 +20431,7 @@ async function childHistory(file2, parentSessionId, identity) {
19905
20431
  model: null,
19906
20432
  ...typeof header.cwd === "string" ? { cwd: header.cwd } : {}
19907
20433
  });
19908
- const prefix = createHash3("sha256").update(identity).digest("hex");
20434
+ const prefix = createHash6("sha256").update(identity).digest("hex");
19909
20435
  return {
19910
20436
  turns: snapshot.turns.map((turn) => {
19911
20437
  const readonlyTurn = {
@@ -19926,7 +20452,7 @@ async function childHistory(file2, parentSessionId, identity) {
19926
20452
  async function readPiWorkflowChild(history, parentSessionId, address) {
19927
20453
  for (const entry of activePiEntries(history).reverse()) {
19928
20454
  const message3 = entry.message;
19929
- if (!record5(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
20455
+ if (!record7(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
19930
20456
  continue;
19931
20457
  const summary = piWorkflowSummary(message3);
19932
20458
  if (!summary || summary.workflowRunId !== address.workflowRunId || summary.parentToolCallId !== message3.toolCallId)
@@ -19935,10 +20461,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
19935
20461
  if (!child)
19936
20462
  break;
19937
20463
  const details = message3.details;
19938
- if (!record5(details) || !Array.isArray(details.results))
20464
+ if (!record7(details) || !Array.isArray(details.results))
19939
20465
  break;
19940
- const result = details.results.findLast((candidate) => record5(candidate) && candidate.workflowKey === address.childId);
19941
- if (!record5(result))
20466
+ const result = details.results.findLast((candidate) => record7(candidate) && candidate.workflowKey === address.childId);
20467
+ if (!record7(result))
19942
20468
  break;
19943
20469
  const id = piWorkflowSubagentId(address);
19944
20470
  if (typeof result.sessionFile === "string") {
@@ -19981,25 +20507,69 @@ ${output}`,
19981
20507
  };
19982
20508
  }
19983
20509
 
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
+
19984
20554
  // dist/pi-subagent-history.js
19985
20555
  import { constants as constants2 } from "node:fs";
19986
20556
  import { open as open4 } from "node:fs/promises";
19987
- import path13 from "node:path";
19988
- function record6(value) {
20557
+ import path14 from "node:path";
20558
+ function record8(value) {
19989
20559
  return typeof value === "object" && value !== null && !Array.isArray(value);
19990
20560
  }
19991
20561
  function state(value) {
19992
20562
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
19993
20563
  }
19994
20564
  function piSubagentArtifact(value, runId, parentSessionId) {
19995
- 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)))
19996
20566
  return null;
19997
20567
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
19998
20568
  return null;
19999
20569
  const steps = Array.isArray(value.steps) ? value.steps : [];
20000
20570
  const children = [];
20001
20571
  for (const [index, step] of steps.entries()) {
20002
- if (!record6(step) || typeof step.agent !== "string")
20572
+ if (!record8(step) || typeof step.agent !== "string")
20003
20573
  return null;
20004
20574
  children.push({
20005
20575
  id: step.workflowKey ?? step.runId ?? `step:${index}`,
@@ -20030,19 +20600,20 @@ function piSubagentArtifact(value, runId, parentSessionId) {
20030
20600
  });
20031
20601
  }
20032
20602
  async function restorePiSubagents(history, parentSessionId, observer) {
20603
+ restoreGotgenes(history, observer.gotgenes);
20033
20604
  const receipts = /* @__PURE__ */ new Map();
20034
20605
  for (const entry of activePiEntries(history)) {
20035
- 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))
20036
20607
  continue;
20037
20608
  const details = entry.message.details;
20038
- 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)
20039
20610
  continue;
20040
20611
  receipts.set(details.asyncId, details.asyncDir);
20041
20612
  }
20042
20613
  for (const [id, directory] of [...receipts].slice(-128)) {
20043
20614
  let file2;
20044
20615
  try {
20045
- 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));
20046
20617
  const stat2 = await file2.stat();
20047
20618
  if (!stat2.isFile() || stat2.size > 1024 * 1024)
20048
20619
  continue;
@@ -20124,8 +20695,8 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
20124
20695
 
20125
20696
  // dist/pi-rpc-session.js
20126
20697
  import { spawn, spawnSync } from "node:child_process";
20127
- import { randomUUID as randomUUID5 } from "node:crypto";
20128
- import path14 from "node:path";
20698
+ import { randomUUID as randomUUID6 } from "node:crypto";
20699
+ import path16 from "node:path";
20129
20700
 
20130
20701
  // dist/pi-slash-commands.js
20131
20702
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -20147,15 +20718,15 @@ function parsePiNativeCommands(response) {
20147
20718
  return data.commands.flatMap((entry) => {
20148
20719
  if (typeof entry !== "object" || entry === null)
20149
20720
  return [];
20150
- const record7 = entry;
20151
- 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, "") : "";
20152
20723
  if (!name)
20153
20724
  return [];
20154
20725
  return [
20155
20726
  {
20156
20727
  name,
20157
- ...typeof record7.description === "string" ? { description: record7.description } : {},
20158
- ...typeof record7.source === "string" ? { source: record7.source } : {}
20728
+ ...typeof record9.description === "string" ? { description: record9.description } : {},
20729
+ ...typeof record9.source === "string" ? { source: record9.source } : {}
20159
20730
  }
20160
20731
  ];
20161
20732
  });
@@ -20171,8 +20742,209 @@ function piDynamicCommandPrompt(catalog, commandId, argumentText) {
20171
20742
  return liveHarnessCommandPrompt(catalog, DYNAMIC_ID_PREFIX, commandId, argumentText);
20172
20743
  }
20173
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
+
20174
20946
  // dist/pi-subagent-rpc.js
20175
- import { randomUUID as randomUUID4 } from "node:crypto";
20947
+ import { randomUUID as randomUUID5 } from "node:crypto";
20176
20948
  var PiSubagentRpc = class {
20177
20949
  send;
20178
20950
  timeoutMs;
@@ -20214,7 +20986,7 @@ var PiSubagentRpc = class {
20214
20986
  if (!Array.isArray(data?.commands) || !data.commands.some((command) => command?.name === "subagents-inspect-rpc" && command.source === "extension")) {
20215
20987
  throw new Error("Installed Pi has no pi-subagents Host inspection command");
20216
20988
  }
20217
- const requestId = randomUUID4();
20989
+ const requestId = randomUUID5();
20218
20990
  const reply = new Promise((resolve, reject) => {
20219
20991
  const timer = setTimeout(() => {
20220
20992
  this.#pending.delete(requestId);
@@ -20248,6 +21020,12 @@ var PiSubagentRpc = class {
20248
21020
  };
20249
21021
 
20250
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
+ };
20251
21029
  var PiRpcFaultError = class extends Error {
20252
21030
  kind;
20253
21031
  diagnostic;
@@ -20275,8 +21053,11 @@ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
20275
21053
  "get_available_thinking_levels"
20276
21054
  ]);
20277
21055
  var MAX_EXPIRED_IDS = 64;
21056
+ function nativeMessageIdentity(active) {
21057
+ return active.assistantNativeMessageIdentity ? { nativeMessageIdentity: active.assistantNativeMessageIdentity } : {};
21058
+ }
20278
21059
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
20279
- function isRecord8(value) {
21060
+ function isRecord9(value) {
20280
21061
  return typeof value === "object" && value !== null && !Array.isArray(value);
20281
21062
  }
20282
21063
  function message2(value) {
@@ -20288,13 +21069,13 @@ function nonBlankString(value) {
20288
21069
  function parseNativeModel(value, context) {
20289
21070
  if (value === null || value === void 0)
20290
21071
  return null;
20291
- if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
21072
+ if (!isRecord9(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
20292
21073
  throw new PiRpcFaultError("protocolError", `Pi RPC returned an invalid ${context} Model`);
20293
21074
  }
20294
21075
  return { provider: value.provider, id: value.id };
20295
21076
  }
20296
21077
  function sessionStateData(response) {
20297
- const data = isRecord8(response.data) ? response.data : null;
21078
+ const data = isRecord9(response.data) ? response.data : null;
20298
21079
  if (!data)
20299
21080
  throw new PiRpcFaultError("protocolError", "Pi RPC state response has no data");
20300
21081
  return data;
@@ -20302,7 +21083,7 @@ function sessionStateData(response) {
20302
21083
  function parseSessionState(response) {
20303
21084
  const data = sessionStateData(response);
20304
21085
  const model2 = parseNativeModel(data.model, "state");
20305
- const modelReasoning = isRecord8(data.model) && typeof data.model.reasoning === "boolean" ? data.model.reasoning : null;
21086
+ const modelReasoning = isRecord9(data.model) && typeof data.model.reasoning === "boolean" ? data.model.reasoning : null;
20306
21087
  if (!nonBlankString(data.sessionId)) {
20307
21088
  throw new PiRpcFaultError("protocolError", "Pi RPC state has no stable Session identity");
20308
21089
  }
@@ -20328,13 +21109,13 @@ function parseSessionStreaming(response) {
20328
21109
  return isStreaming;
20329
21110
  }
20330
21111
  function parseSessionHistory(response) {
20331
- const data = isRecord8(response.data) ? response.data : null;
21112
+ const data = isRecord9(response.data) ? response.data : null;
20332
21113
  if (!data || !Array.isArray(data.entries)) {
20333
21114
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response has no Entries");
20334
21115
  }
20335
21116
  const entries = data.entries.map((entry) => {
20336
21117
  const parsed = jsonValueSchema.safeParse(entry);
20337
- if (!parsed.success || !isRecord8(parsed.data)) {
21118
+ if (!parsed.success || !isRecord9(parsed.data)) {
20338
21119
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response contains an invalid Entry");
20339
21120
  }
20340
21121
  return parsed.data;
@@ -20345,7 +21126,7 @@ function parseSessionHistory(response) {
20345
21126
  return { entries, leafId: data.leafId };
20346
21127
  }
20347
21128
  function parseAvailableThinkingLevels(response) {
20348
- const data = isRecord8(response.data) ? response.data : null;
21129
+ const data = isRecord9(response.data) ? response.data : null;
20349
21130
  if (!data || !Array.isArray(data.levels) || data.levels.length === 0) {
20350
21131
  throw new PiRpcFaultError("protocolError", "Pi RPC Thinking catalog response has no levels");
20351
21132
  }
@@ -20362,13 +21143,13 @@ function parseAvailableThinkingLevels(response) {
20362
21143
  return levels;
20363
21144
  }
20364
21145
  function parseAvailableModels(response) {
20365
- const data = isRecord8(response.data) ? response.data : null;
21146
+ const data = isRecord9(response.data) ? response.data : null;
20366
21147
  if (!data || !Array.isArray(data.models)) {
20367
21148
  throw new PiRpcFaultError("protocolError", "Pi RPC Model catalog response has no models");
20368
21149
  }
20369
21150
  return data.models.map((model2) => {
20370
21151
  const parsed = parseNativeModel(model2, "catalog");
20371
- if (!parsed || !isRecord8(model2) || typeof model2.reasoning !== "boolean") {
21152
+ if (!parsed || !isRecord9(model2) || typeof model2.reasoning !== "boolean") {
20372
21153
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
20373
21154
  }
20374
21155
  return {
@@ -20379,32 +21160,32 @@ function parseAvailableModels(response) {
20379
21160
  });
20380
21161
  }
20381
21162
  function assistantText(value) {
20382
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21163
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20383
21164
  return null;
20384
- 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("");
20385
21166
  }
20386
21167
  function assistantMessageId(value) {
20387
- if (!isRecord8(value) || value.role !== "assistant")
21168
+ if (!isRecord9(value) || value.role !== "assistant")
20388
21169
  return null;
20389
21170
  return nonBlankString(value.responseId) ? value.responseId : null;
20390
21171
  }
20391
21172
  function extractReasoningText(content) {
20392
- if (!isRecord8(content))
21173
+ if (!isRecord9(content))
20393
21174
  return null;
20394
21175
  const type = String(content.type ?? "");
20395
21176
  if (type === "thinking" || type === "reasoning" || type === "thought") {
20396
- const text2 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
20397
- return typeof text2 === "string" ? text2 : null;
21177
+ const text4 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
21178
+ return typeof text4 === "string" ? text4 : null;
20398
21179
  }
20399
21180
  return null;
20400
21181
  }
20401
21182
  function assistantReasoning(value) {
20402
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21183
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20403
21184
  return null;
20404
- return value.content.map(extractReasoningText).filter((text2) => typeof text2 === "string").join("");
21185
+ return value.content.map(extractReasoningText).filter((text4) => typeof text4 === "string").join("");
20405
21186
  }
20406
21187
  function assistantFailure(value) {
20407
- if (!isRecord8(value) || value.role !== "assistant")
21188
+ if (!isRecord9(value) || value.role !== "assistant")
20408
21189
  return void 0;
20409
21190
  if (value.stopReason !== "error" && value.stopReason !== "aborted")
20410
21191
  return null;
@@ -20424,7 +21205,7 @@ function signalProcessTree(child, signal) {
20424
21205
  try {
20425
21206
  process.kill(-child.pid, signal);
20426
21207
  } catch (error51) {
20427
- if (!isRecord8(error51) || error51.code !== "ESRCH")
21208
+ if (!isRecord9(error51) || error51.code !== "ESRCH")
20428
21209
  throw error51;
20429
21210
  }
20430
21211
  }
@@ -20461,16 +21242,24 @@ function piRpcProcessCommand(options, dependencies = {}) {
20461
21242
  const thinkingArguments = options.emptySessionConfiguration ? ["--thinking", options.emptySessionConfiguration.thinkingLevel] : [];
20462
21243
  const arguments_ = [
20463
21244
  ...options.fastExtension ? ["--extension", options.fastExtension] : [],
21245
+ ...options.subagentExtension ? ["--extension", options.subagentExtension] : [],
20464
21246
  "--mode",
20465
21247
  "rpc",
20466
21248
  ...modelArguments,
20467
21249
  ...thinkingArguments,
20468
21250
  ...sessionArguments
20469
21251
  ];
20470
- const extension = path14.win32.extname(command).toLowerCase();
21252
+ const extension = path16.win32.extname(command).toLowerCase();
20471
21253
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
20472
21254
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
20473
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
+ }
20474
21263
  const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
20475
21264
  const commandLine = [command, ...arguments_].map(quote).join(" ");
20476
21265
  return {
@@ -20496,7 +21285,13 @@ var PiRpcSession = class {
20496
21285
  #options;
20497
21286
  #processAdapter;
20498
21287
  #activeTurn = null;
21288
+ #runGeneration = 0;
21289
+ #deferredRunFrames = [];
21290
+ #deferredRunBytes = 0;
21291
+ #runWaiters = /* @__PURE__ */ new Set();
21292
+ #messageTimestampCounts = /* @__PURE__ */ new Map();
20499
21293
  #autonomousTurnHandler = null;
21294
+ #autonomousLifecycleHandler = null;
20500
21295
  #usageHandler = null;
20501
21296
  #usageRequestStartedAtMs = null;
20502
21297
  // Pieces of the unterminated frame; joined once at its newline so a large frame (a long
@@ -20516,8 +21311,15 @@ var PiRpcSession = class {
20516
21311
  #fastAcknowledgement = null;
20517
21312
  #latestCacheHitRatePercent;
20518
21313
  #manualCompaction = null;
21314
+ #noticeOccurrences = /* @__PURE__ */ new Map();
21315
+ #seenNoticeFrames = /* @__PURE__ */ new Set();
21316
+ #pendingProgress = [];
21317
+ #omittedProgress = 0;
21318
+ #extensionStatuses = /* @__PURE__ */ new Map();
20519
21319
  #stderrTail = "";
20520
21320
  #subagents;
21321
+ #gotgenesHandler;
21322
+ #gotgenesLatest;
20521
21323
  constructor(options, processAdapter = nodeProcessAdapter) {
20522
21324
  if (options.sessionFile && options.forkSessionFile) {
20523
21325
  throw new Error("Pi RPC cannot combine Session resume and Fork startup");
@@ -20547,9 +21349,17 @@ var PiRpcSession = class {
20547
21349
  get stderrTail() {
20548
21350
  return this.#stderrTail;
20549
21351
  }
21352
+ get isBusy() {
21353
+ return this.#activeTurn !== null || this.#manualCompaction !== null || this.#compactionActive || this.#deferredRunFrames.length > 0;
21354
+ }
20550
21355
  setSubagentStatusHandler(handler) {
20551
21356
  this.#subagents.setHandler(handler);
20552
21357
  }
21358
+ setGotgenesStatusHandler(handler) {
21359
+ this.#gotgenesHandler = handler;
21360
+ if (this.#gotgenesLatest)
21361
+ handler(this.#gotgenesLatest, "idle");
21362
+ }
20553
21363
  inspectSubagent(id) {
20554
21364
  return this.#subagents.inspect(id);
20555
21365
  }
@@ -20559,17 +21369,18 @@ var PiRpcSession = class {
20559
21369
  /** Every finished assistant message is one model request, with or without an active Turn. */
20560
21370
  #observeUsage(value) {
20561
21371
  if (value.type === "message_start") {
20562
- this.#usageRequestStartedAtMs = null;
21372
+ if (isRecord9(value.message) && value.message.role === "assistant")
21373
+ this.#usageRequestStartedAtMs = null;
20563
21374
  return;
20564
21375
  }
20565
21376
  if (value.type === "message_update") {
20566
21377
  const event = value.assistantMessageEvent;
20567
- 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)) {
20568
21379
  this.#usageRequestStartedAtMs = Date.now();
20569
21380
  }
20570
21381
  return;
20571
21382
  }
20572
- if (value.type === "message_end" && isRecord8(value.message)) {
21383
+ if (value.type === "message_end" && isRecord9(value.message)) {
20573
21384
  if (value.message.role !== "assistant")
20574
21385
  return;
20575
21386
  const startedAtMs = this.#usageRequestStartedAtMs;
@@ -20583,14 +21394,21 @@ var PiRpcSession = class {
20583
21394
  }
20584
21395
  setAutonomousTurnHandler(handler) {
20585
21396
  this.#autonomousTurnHandler = handler;
21397
+ this.#autonomousLifecycleHandler = null;
21398
+ }
21399
+ setAutonomousTurnLifecycleHandler(handler) {
21400
+ this.#autonomousLifecycleHandler = handler;
21401
+ this.#autonomousTurnHandler = null;
20586
21402
  }
20587
21403
  async start() {
20588
21404
  if (this.#child || this.#closed)
20589
21405
  throw new Error("Pi RPC Session cannot be started twice");
20590
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;
20591
21408
  const child = this.#processAdapter.spawn({
20592
21409
  cwd: this.#options.cwd,
20593
21410
  ...fastExtension ? { fastExtension } : {},
21411
+ ...subagentExtension ? { subagentExtension } : {},
20594
21412
  ...this.#options.command ? { command: this.#options.command } : {},
20595
21413
  environment: withNodeRuntimeOnPath({
20596
21414
  ...process.env,
@@ -20614,7 +21432,7 @@ var PiRpcSession = class {
20614
21432
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
20615
21433
  });
20616
21434
  child.once("error", (error51) => {
20617
- const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
21435
+ const kind = isRecord9(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
20618
21436
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
20619
21437
  });
20620
21438
  child.once("exit", (code, signal) => {
@@ -20631,6 +21449,7 @@ var PiRpcSession = class {
20631
21449
  ]);
20632
21450
  try {
20633
21451
  this.#state = parseSessionState(await this.#send("get_state", {}));
21452
+ await this.getEntries();
20634
21453
  } catch (error51) {
20635
21454
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("unavailable", `Pi RPC state unavailable: ${message2(error51)}`);
20636
21455
  this.#fail(fault);
@@ -20644,7 +21463,12 @@ var PiRpcSession = class {
20644
21463
  }
20645
21464
  async getEntries() {
20646
21465
  try {
20647
- 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;
20648
21472
  } catch (error51) {
20649
21473
  if (error51 instanceof PiRpcFaultError)
20650
21474
  this.#fail(error51);
@@ -20704,11 +21528,15 @@ var PiRpcSession = class {
20704
21528
  if (entryId.length === 0)
20705
21529
  throw new Error("Pi Fork Entry ID must not be empty");
20706
21530
  await this.#send("fork", { entryId });
20707
- return this.#refreshState("Fork");
21531
+ const state2 = await this.#refreshState("Fork");
21532
+ await this.getEntries();
21533
+ return state2;
20708
21534
  }
20709
21535
  async clone() {
20710
21536
  await this.#send("clone", {});
20711
- return this.#refreshState("Clone");
21537
+ const state2 = await this.#refreshState("Clone");
21538
+ await this.getEntries();
21539
+ return state2;
20712
21540
  }
20713
21541
  verifySessionCwd(expectedCwd) {
20714
21542
  return verifyPiSessionCwd({
@@ -20745,7 +21573,7 @@ var PiRpcSession = class {
20745
21573
  return this.state;
20746
21574
  if (!await this.supportsFastMode())
20747
21575
  throw new Error("Installed Pi does not support the Host Fast extension");
20748
- const nonce = randomUUID5();
21576
+ const nonce = randomUUID6();
20749
21577
  const mode = enabled ? "on" : "off";
20750
21578
  const acknowledgement = { message: `${PI_FAST_ACK}${nonce}:${mode}`, received: false };
20751
21579
  this.#fastAcknowledgement = acknowledgement;
@@ -20785,22 +21613,27 @@ var PiRpcSession = class {
20785
21613
  throw fault;
20786
21614
  }
20787
21615
  }
20788
- async runTurn(text2, onEvent) {
21616
+ async runTurn(text4, onEvent) {
20789
21617
  if (!this.#child || !this.#state || this.#closed || this.#failed) {
20790
21618
  throw new Error("Pi RPC Session is unavailable");
20791
21619
  }
20792
- if (this.#activeTurn)
20793
- throw new Error("Pi RPC Session already has an active Turn");
20794
- if (text2.length === 0)
21620
+ if (this.isBusy)
21621
+ throw new PiRpcBusyError();
21622
+ if (text4.length === 0)
20795
21623
  throw new Error("Pi text Turn must not be empty");
20796
21624
  const settled = new Promise((resolve, reject) => {
20797
21625
  this.#activeTurn = {
20798
21626
  origin: "requested",
21627
+ autonomousRunId: null,
21628
+ runGeneration: this.#runGeneration,
20799
21629
  autonomousEvents: null,
20800
21630
  nativeTurnKey: null,
20801
21631
  nativeCancellationObserved: false,
20802
21632
  text: "",
20803
21633
  assistantMessageId: null,
21634
+ assistantNativeMessageIdentity: void 0,
21635
+ textStream: new PiContentStream("text"),
21636
+ reasoningStream: new PiContentStream("reasoning"),
20804
21637
  sawStreamedMessageText: false,
20805
21638
  sawStreamedMessageReasoning: false,
20806
21639
  lastFinalizedMessageText: null,
@@ -20820,7 +21653,8 @@ var PiRpcSession = class {
20820
21653
  };
20821
21654
  });
20822
21655
  try {
20823
- await this.#send("prompt", { message: text2 });
21656
+ this.#drainProgress(onEvent);
21657
+ await this.#send("prompt", { message: text4 });
20824
21658
  } catch (error51) {
20825
21659
  this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
20826
21660
  }
@@ -20892,6 +21726,10 @@ var PiRpcSession = class {
20892
21726
  void this.close().catch(() => void 0);
20893
21727
  }
20894
21728
  close() {
21729
+ this.#pendingProgress = [];
21730
+ this.#omittedProgress = 0;
21731
+ this.#seenNoticeFrames.clear();
21732
+ this.#extensionStatuses.clear();
20895
21733
  if (!this.#closed) {
20896
21734
  this.#closed = true;
20897
21735
  this.#rejectAll(new Error("Pi RPC Session closed"));
@@ -20925,19 +21763,25 @@ var PiRpcSession = class {
20925
21763
  rest = rest.subarray(newline + 1);
20926
21764
  try {
20927
21765
  const value = JSON.parse(textDecoder.decode(frame));
20928
- if (!isRecord8(value) || typeof value.type !== "string") {
21766
+ if (!isRecord9(value) || typeof value.type !== "string") {
20929
21767
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid envelope");
20930
21768
  }
20931
21769
  this.#handle(value);
20932
21770
  } catch (error51) {
20933
- 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)}`));
20934
21772
  }
20935
21773
  newline = rest.indexOf(10);
20936
21774
  }
20937
21775
  if (rest.length !== 0)
20938
21776
  this.#buffer.push(rest);
20939
21777
  }
20940
- #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;
20941
21785
  if (value.type === "extension_ui_request" && value.method === "notify" && typeof value.message === "string" && value.message.startsWith(PI_FAST_ACK)) {
20942
21786
  if (this.#fastAcknowledgement?.message === value.message)
20943
21787
  this.#fastAcknowledgement.received = true;
@@ -20951,6 +21795,33 @@ var PiRpcSession = class {
20951
21795
  }
20952
21796
  if (this.#subagents.handle(value))
20953
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;
20954
21825
  this.#observeUsage(value);
20955
21826
  if (value.type === "compaction_start") {
20956
21827
  this.#compactionActive = true;
@@ -20974,7 +21845,7 @@ var PiRpcSession = class {
20974
21845
  this.#armCommandTimeout(id, pending);
20975
21846
  }
20976
21847
  }
20977
- const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
21848
+ const outcome = value.aborted === true ? "cancelled" : isRecord9(value.result) ? "succeeded" : "failed";
20978
21849
  const event = {
20979
21850
  type: "compaction.completed",
20980
21851
  outcome,
@@ -20991,8 +21862,8 @@ var PiRpcSession = class {
20991
21862
  return;
20992
21863
  }
20993
21864
  let active = this.#activeTurn;
20994
- if (!active && !this.#manualCompaction && !this.#compactionActive && this.#autonomousTurnHandler && value.type === "message_start" && assistantText(value.message) !== null) {
20995
- 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);
20996
21867
  }
20997
21868
  if (!active) {
20998
21869
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
@@ -21012,22 +21883,26 @@ var PiRpcSession = class {
21012
21883
  this.#startAssistantMessage(active, value.message);
21013
21884
  return;
21014
21885
  }
21015
- if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
21886
+ if (value.type === "message_update" && isRecord9(value.assistantMessageEvent)) {
21016
21887
  const event = value.assistantMessageEvent;
21017
21888
  const eventType = String(event.type ?? "");
21018
21889
  const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
21019
21890
  const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
21020
- 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;
21021
- if (isThinking && delta !== null && delta.length > 0) {
21022
- const messageId = this.#ensureAssistantMessage(active, value.message);
21023
- active.reasoningMessageOpen = true;
21024
- active.sawStreamedMessageReasoning = true;
21025
- active.onEvent({ type: "reasoning.delta", messageId, delta });
21026
- } else if (isText && delta !== null && delta.length > 0) {
21027
- const messageId = this.#ensureAssistantMessage(active, value.message);
21028
- active.text += delta;
21029
- active.sawStreamedMessageText = true;
21030
- 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));
21031
21906
  } else if (event.type === "error") {
21032
21907
  this.#ensureAssistantMessage(active, value.message);
21033
21908
  active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Pi assistant message failed");
@@ -21058,25 +21933,36 @@ var PiRpcSession = class {
21058
21933
  if (active.settlement !== "pending")
21059
21934
  return;
21060
21935
  active.settlement = "confirming";
21061
- void this.#confirmSettledTurn(active);
21936
+ void this.#confirmSettledTurn(active, active.runGeneration);
21062
21937
  }
21063
21938
  }
21064
- #startAutonomousTurn(value) {
21939
+ #startAutonomousTurn(value, generation) {
21065
21940
  const events = [];
21941
+ const runId = randomUUID6();
21066
21942
  const active = {
21067
21943
  origin: "autonomous",
21944
+ autonomousRunId: runId,
21945
+ runGeneration: generation,
21068
21946
  autonomousEvents: events,
21069
- ...isRecord8(value) ? { autonomousMessage: value } : {},
21947
+ ...isRecord9(value) ? { autonomousMessage: value } : {},
21070
21948
  nativeTurnKey: null,
21071
21949
  nativeCancellationObserved: false,
21072
21950
  text: "",
21073
21951
  assistantMessageId: null,
21952
+ assistantNativeMessageIdentity: void 0,
21953
+ textStream: new PiContentStream("text"),
21954
+ reasoningStream: new PiContentStream("reasoning"),
21074
21955
  sawStreamedMessageText: false,
21075
21956
  sawStreamedMessageReasoning: false,
21076
21957
  lastFinalizedMessageText: null,
21077
21958
  lastFinalizedMessageReasoning: null,
21078
21959
  reasoningMessageOpen: false,
21079
- 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
+ },
21080
21966
  resolve: () => void 0,
21081
21967
  reject: () => void 0,
21082
21968
  failure: null,
@@ -21089,19 +21975,109 @@ var PiRpcSession = class {
21089
21975
  abortPromise: null
21090
21976
  };
21091
21977
  this.#activeTurn = active;
21978
+ this.#autonomousLifecycleHandler?.({ type: "started", runId });
21979
+ this.#drainProgress(active.onEvent);
21092
21980
  return active;
21093
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
+ }
21094
22062
  #emitAutonomousTurn(active, result) {
21095
22063
  const handler = this.#autonomousTurnHandler;
21096
- if (active.origin !== "autonomous" || !active.autonomousEvents || !handler) {
22064
+ if (active.origin !== "autonomous" || !active.autonomousEvents || !active.autonomousRunId) {
21097
22065
  return;
21098
22066
  }
21099
22067
  try {
21100
- handler({
22068
+ const turn = {
21101
22069
  nativeTurnKey: active.nativeTurnKey,
21102
22070
  events: [...active.autonomousEvents],
21103
22071
  result
21104
- });
22072
+ };
22073
+ if (this.#autonomousLifecycleHandler)
22074
+ this.#autonomousLifecycleHandler({
22075
+ type: "completed",
22076
+ runId: active.autonomousRunId,
22077
+ turn
22078
+ });
22079
+ else
22080
+ handler?.(turn);
21105
22081
  } catch (error51) {
21106
22082
  this.#fail(new PiRpcFaultError("protocolError", `Pi autonomous Turn handler failed: ${message2(error51)}`));
21107
22083
  }
@@ -21268,31 +22244,73 @@ var PiRpcSession = class {
21268
22244
  isError: value.isError === true
21269
22245
  });
21270
22246
  }
21271
- 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) {
21272
22284
  try {
21273
22285
  const response = await this.#send("get_state", {});
21274
22286
  const state2 = parseSessionState(response);
21275
- if (parseSessionStreaming(response)) {
21276
- throw new PiRpcFaultError("protocolError", "Pi RPC agent_settled state is still Streaming");
21277
- }
21278
- if (this.#activeTurn !== active)
22287
+ if (!this.#isSettlementCurrent(active, generation))
22288
+ return;
22289
+ if (parseSessionStreaming(response))
22290
+ await this.#waitForNextRun(generation);
22291
+ if (!this.#isSettlementCurrent(active, generation))
21279
22292
  return;
21280
- if (active.origin === "autonomous") {
22293
+ if (active.origin === "autonomous" && active.autonomousMessage) {
21281
22294
  const history = await this.getEntries();
21282
22295
  const snapshot = mapPiSnapshot(history, { sessionId: state2.sessionId, model: null });
21283
- const turn = snapshot.turns.at(-1);
22296
+ if (!this.#isSettlementCurrent(active, generation))
22297
+ return;
21284
22298
  const entries = activePiEntries(history);
21285
- const start = entries.findIndex((entry) => entry.id === turn?.nativeTurnRef.nativeTurnKey);
21286
- const firstAssistant = entries.slice(start + 1).find((entry) => isRecord8(entry.message) && entry.message.role === "assistant")?.message;
21287
22299
  const live = active.autonomousMessage;
21288
22300
  const responseId = assistantMessageId(live);
21289
- const matches = isRecord8(firstAssistant) && (responseId ? assistantMessageId(firstAssistant) === responseId : typeof live?.timestamp === "number" && firstAssistant.timestamp === live.timestamp);
21290
- 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)
21291
22310
  throw new PiRpcFaultError("protocolError", "Pi autonomous Turn has no matching persisted custom Entry");
21292
- }
21293
22311
  active.nativeTurnKey = turn.nativeTurnRef.nativeTurnKey;
21294
22312
  }
21295
- if (this.#activeTurn !== active)
22313
+ if (!this.#isSettlementCurrent(active, generation))
21296
22314
  return;
21297
22315
  this.#state = state2;
21298
22316
  active.settlement = "confirmed";
@@ -21318,7 +22336,13 @@ var PiRpcSession = class {
21318
22336
  }
21319
22337
  this.#activeTurn = null;
21320
22338
  if (active.origin === "autonomous") {
21321
- 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) {
21322
22346
  this.#emitAutonomousTurn(active, active.nativeCancellationObserved ? {
21323
22347
  status: "cancelled",
21324
22348
  text: active.text,
@@ -21333,6 +22357,7 @@ var PiRpcSession = class {
21333
22357
  } else {
21334
22358
  this.#emitAutonomousTurn(active, { status: "succeeded", text: active.text });
21335
22359
  }
22360
+ this.#drainDeferredRunFrames();
21336
22361
  return;
21337
22362
  }
21338
22363
  if (active.cancellation === "accepted") {
@@ -21344,20 +22369,56 @@ var PiRpcSession = class {
21344
22369
  } else {
21345
22370
  active.resolve({ text: active.text, cancelled: false });
21346
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
+ });
21347
22393
  }
21348
22394
  #startAssistantMessage(active, value) {
22395
+ if (active.origin === "autonomous" && !active.autonomousMessage && isRecord9(value))
22396
+ active.autonomousMessage = value;
21349
22397
  if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
21350
22398
  active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
21351
22399
  }
21352
- const messageId = assistantMessageId(value) ?? randomUUID5();
22400
+ const nativeResponseId = assistantMessageId(value);
22401
+ const messageId = nativeResponseId ?? randomUUID6();
21353
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");
21354
22406
  active.sawStreamedMessageText = false;
21355
22407
  active.sawStreamedMessageReasoning = false;
21356
22408
  active.reasoningMessageOpen = false;
21357
22409
  return messageId;
21358
22410
  }
21359
22411
  #ensureAssistantMessage(active, value) {
21360
- 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;
21361
22422
  }
21362
22423
  #finalizeAssistantMessage(active, value) {
21363
22424
  const finalText = assistantText(value);
@@ -21370,29 +22431,33 @@ var PiRpcSession = class {
21370
22431
  return;
21371
22432
  }
21372
22433
  active.failure = failure;
21373
- if (active.origin === "autonomous" && isRecord8(value) && value.stopReason === "aborted") {
22434
+ if (active.origin === "autonomous" && piAssistantWasAborted(value)) {
21374
22435
  active.nativeCancellationObserved = true;
21375
22436
  }
21376
22437
  this.#latestCacheHitRatePercent = cacheHitRatePercent;
21377
22438
  const messageId = this.#ensureAssistantMessage(active, value);
21378
- if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
21379
- active.reasoningMessageOpen = true;
21380
- 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
+ })));
21381
22445
  }
21382
22446
  if (active.reasoningMessageOpen && active.failure === null) {
21383
22447
  active.onEvent({ type: "reasoning.completed", messageId });
21384
22448
  }
21385
- if (!active.sawStreamedMessageText && finalText.length > 0) {
21386
- active.text += finalText;
21387
- 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 }] : [])));
21388
22451
  }
21389
22452
  active.assistantMessageId = null;
22453
+ active.assistantNativeMessageIdentity = void 0;
21390
22454
  active.sawStreamedMessageText = false;
21391
22455
  active.sawStreamedMessageReasoning = false;
21392
22456
  active.reasoningMessageOpen = false;
21393
22457
  active.lastFinalizedMessageText = finalText;
21394
22458
  active.lastFinalizedMessageReasoning = finalReasoning;
21395
- active.onEvent({ type: "message.completed", messageId });
22459
+ const phase = piAssistantPhase(value);
22460
+ active.onEvent({ type: "message.completed", messageId, ...phase ? { phase } : {} });
21396
22461
  }
21397
22462
  #write(value) {
21398
22463
  const child = this.#child;
@@ -21410,7 +22475,7 @@ var PiRpcSession = class {
21410
22475
  if (!child?.stdin.writable || this.#closed || this.#failed) {
21411
22476
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
21412
22477
  }
21413
- const id = `codexhost-${randomUUID5()}`;
22478
+ const id = `codexhost-${randomUUID6()}`;
21414
22479
  return new Promise((resolve, reject) => {
21415
22480
  const pending = {
21416
22481
  command: type,
@@ -21500,9 +22565,16 @@ var PiRpcSession = class {
21500
22565
  } else {
21501
22566
  active.reject(error51);
21502
22567
  }
22568
+ this.#drainDeferredRunFrames();
21503
22569
  }
21504
22570
  #rejectAll(error51) {
22571
+ for (const waiter of this.#runWaiters)
22572
+ waiter.reject(error51);
22573
+ this.#deferredRunFrames = [];
22574
+ this.#deferredRunBytes = 0;
21505
22575
  this.#subagents.close(error51);
22576
+ this.#gotgenesHandler = void 0;
22577
+ this.#gotgenesLatest = void 0;
21506
22578
  for (const pending of this.#pending.values()) {
21507
22579
  if (pending.timeout)
21508
22580
  clearTimeout(pending.timeout);
@@ -21538,7 +22610,7 @@ var piCommandCatalog = harnessCommandCatalogSchema.parse({
21538
22610
  ]
21539
22611
  });
21540
22612
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
21541
- function isRecord9(value) {
22613
+ function isRecord10(value) {
21542
22614
  return typeof value === "object" && value !== null && !Array.isArray(value);
21543
22615
  }
21544
22616
  function errorMessage(error51) {
@@ -21553,7 +22625,9 @@ var PiAdapterFaultError = class extends Error {
21553
22625
  }
21554
22626
  };
21555
22627
  function normalizedError(error51, fallbackCode) {
21556
- 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") {
21557
22631
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
21558
22632
  }
21559
22633
  if (error51 instanceof PiAdapterFaultError)
@@ -21616,7 +22690,7 @@ function nativeModelForHistory(state2) {
21616
22690
  return nativeModelFromState(state2);
21617
22691
  }
21618
22692
  function sessionFileFromRef(ref) {
21619
- 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) {
21620
22694
  throw new Error("Pi Native Session Ref has no resumable Session file");
21621
22695
  }
21622
22696
  return ref.locator.sessionFile;
@@ -21631,83 +22705,29 @@ function toolFailure(toolName) {
21631
22705
  function nativeText(value) {
21632
22706
  if (typeof value === "string")
21633
22707
  return value;
21634
- if (!isRecord9(value) || !Array.isArray(value.content))
22708
+ if (!isRecord10(value) || !Array.isArray(value.content))
21635
22709
  return "";
21636
- 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("");
21637
22711
  }
21638
22712
  function boundedOutput(value, limit) {
21639
- const text2 = nativeText(value);
21640
- if (text2.length === 0)
22713
+ const text4 = nativeText(value);
22714
+ if (text4.length === 0)
21641
22715
  return void 0;
21642
- const truncated = text2.length > limit;
22716
+ const truncated = text4.length > limit;
21643
22717
  return {
21644
- content: [{ type: "text", text: truncated ? text2.slice(0, limit) : text2 }],
22718
+ content: [{ type: "text", text: truncated ? text4.slice(0, limit) : text4 }],
21645
22719
  ...truncated ? { truncated: true } : {}
21646
22720
  };
21647
22721
  }
21648
22722
  function outputText(output) {
21649
- return output?.content.filter((content) => content.type === "text").map(({ text: text2 }) => text2).join("") ?? "";
21650
- }
21651
- function stringField(value, key) {
21652
- if (!isRecord9(value))
21653
- return void 0;
21654
- const field2 = value[key];
21655
- if (typeof field2 === "string" && field2.length > 0)
21656
- return field2;
21657
- if (isRecord9(value.input)) {
21658
- const nested = value.input[key];
21659
- if (typeof nested === "string" && nested.length > 0)
21660
- return nested;
21661
- }
21662
- if (isRecord9(value.arguments)) {
21663
- const nested = value.arguments[key];
21664
- if (typeof nested === "string" && nested.length > 0)
21665
- return nested;
21666
- }
21667
- return void 0;
22723
+ return output?.content.filter((content) => content.type === "text").map(({ text: text4 }) => text4).join("") ?? "";
21668
22724
  }
21669
22725
  function numberField(value, key) {
21670
- if (!isRecord9(value))
22726
+ if (!isRecord10(value))
21671
22727
  return void 0;
21672
22728
  const field2 = value[key];
21673
22729
  return typeof field2 === "number" || field2 === null ? field2 : void 0;
21674
22730
  }
21675
- function normalizeToolName(name) {
21676
- const lower = name.toLowerCase();
21677
- switch (lower) {
21678
- case "bash":
21679
- case "exec":
21680
- case "terminal":
21681
- case "run":
21682
- return "bash";
21683
- case "read":
21684
- case "read_file":
21685
- case "fileread":
21686
- return "Read";
21687
- case "edit":
21688
- case "edit_file":
21689
- case "fileedit":
21690
- return "Edit";
21691
- case "write":
21692
- case "write_file":
21693
- case "filewrite":
21694
- return "Write";
21695
- case "grep":
21696
- case "grep_search":
21697
- return "Grep";
21698
- case "find":
21699
- case "glob":
21700
- case "find_files":
21701
- return "Glob";
21702
- case "todo":
21703
- return "Todo";
21704
- case "web_search":
21705
- case "websearch":
21706
- return "WebSearch";
21707
- default:
21708
- return name.length > 0 ? `${name[0]?.toUpperCase() ?? ""}${name.slice(1)}` : name;
21709
- }
21710
- }
21711
22731
  function delay(milliseconds) {
21712
22732
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
21713
22733
  }
@@ -21735,6 +22755,8 @@ var PiHarnessSession = class {
21735
22755
  #configuring = false;
21736
22756
  #phase = "open";
21737
22757
  #pendingAutonomousTurns = [];
22758
+ #pendingAutonomousLifecycle = [];
22759
+ #pendingAutonomousLifecycleBytes = 0;
21738
22760
  #starting = null;
21739
22761
  #state = {};
21740
22762
  #transport = null;
@@ -21783,13 +22805,20 @@ var PiHarnessSession = class {
21783
22805
  return this.#transport?.state.sessionId === id;
21784
22806
  }
21785
22807
  async readSubagentHistory(cwd) {
21786
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22808
+ if (this.#phase !== "open" || path17.resolve(cwd) !== path17.resolve(this.#cwd)) {
21787
22809
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21788
22810
  }
21789
22811
  return (await this.#ensureTransport()).getEntries();
21790
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
+ }
21791
22820
  async inspectSubagent(id, cwd) {
21792
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22821
+ if (this.#phase !== "open" || path17.resolve(cwd) !== path17.resolve(this.#cwd)) {
21793
22822
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21794
22823
  }
21795
22824
  const transport = await this.#ensureTransport();
@@ -21860,7 +22889,7 @@ var PiHarnessSession = class {
21860
22889
  }
21861
22890
  };
21862
22891
  }
21863
- if (this.#acceptingTurn || this.#active || this.#configuring) {
22892
+ if (this.#acceptingTurn || this.#active || this.#configuring || this.#transport?.isBusy) {
21864
22893
  return {
21865
22894
  ok: false,
21866
22895
  error: {
@@ -21870,8 +22899,8 @@ var PiHarnessSession = class {
21870
22899
  }
21871
22900
  };
21872
22901
  }
21873
- const text2 = command.input.filter((input) => input.type === "text").map((input) => input.text).join("\n");
21874
- 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) {
21875
22904
  return {
21876
22905
  ok: false,
21877
22906
  error: {
@@ -21901,6 +22930,9 @@ var PiHarnessSession = class {
21901
22930
  } catch (error51) {
21902
22931
  return { ok: false, error: normalizedError(error51, "protocolError") };
21903
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
+ }
21904
22936
  let resolveCompletion = () => void 0;
21905
22937
  const completion = new Promise((resolve) => {
21906
22938
  resolveCompletion = resolve;
@@ -21921,21 +22953,27 @@ var PiHarnessSession = class {
21921
22953
  interactions: /* @__PURE__ */ new Map(),
21922
22954
  interactionByNativeId: /* @__PURE__ */ new Map(),
21923
22955
  cancellationRequested: false,
22956
+ settling: false,
21924
22957
  beforeNativeTurnKeys: new Set(beforeHistory.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
22958
+ progressItems: /* @__PURE__ */ new Set(),
21925
22959
  completion,
21926
22960
  resolveCompletion
21927
22961
  };
21928
22962
  this.#active = active;
21929
22963
  this.#event({ type: "turn.started", turnId: command.turnId });
21930
22964
  this.#event({ type: "item.started", turnId: command.turnId, item });
21931
- 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;
21932
22967
  try {
21933
22968
  const identity = await this.#completedTurnIdentity(active, transport);
21934
22969
  this.#completeTurn(active, result.cancelled ? {
21935
22970
  status: "cancelled",
21936
22971
  reason: "Cancelled by user",
21937
- checkpoint: identity.checkpoint
21938
- } : { 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);
21939
22977
  } catch (error51) {
21940
22978
  this.#completeTurn(active, {
21941
22979
  status: "failed",
@@ -21943,6 +22981,7 @@ var PiHarnessSession = class {
21943
22981
  });
21944
22982
  }
21945
22983
  }).catch(async (error51) => {
22984
+ active.settling = true;
21946
22985
  let identity;
21947
22986
  try {
21948
22987
  identity = await this.#completedTurnIdentity(active, transport);
@@ -21951,12 +22990,14 @@ var PiHarnessSession = class {
21951
22990
  this.#completeTurn(active, {
21952
22991
  status: "failed",
21953
22992
  error: normalizedError(error51, "nativeFailure"),
21954
- ...identity ? { checkpoint: identity.checkpoint } : {}
22993
+ ...identity?.checkpoint ? { checkpoint: identity.checkpoint } : {}
21955
22994
  }, void 0, identity?.nativeTurnRef);
21956
22995
  });
21957
22996
  return { ok: true, value: { turnId: command.turnId } };
21958
22997
  } finally {
21959
22998
  this.#acceptingTurn = false;
22999
+ if (this.#transport)
23000
+ this.#drainPendingAutonomousTurns(this.#transport);
21960
23001
  }
21961
23002
  }
21962
23003
  close() {
@@ -22084,6 +23125,8 @@ var PiHarnessSession = class {
22084
23125
  return { ok: true, value: { completed: true } };
22085
23126
  } finally {
22086
23127
  this.#configuring = false;
23128
+ if (this.#transport)
23129
+ this.#drainPendingAutonomousTurns(this.#transport);
22087
23130
  }
22088
23131
  }
22089
23132
  async #selectThinking(command) {
@@ -22158,6 +23201,8 @@ var PiHarnessSession = class {
22158
23201
  return { ok: true, value: { completed: true } };
22159
23202
  } finally {
22160
23203
  this.#configuring = false;
23204
+ if (this.#transport)
23205
+ this.#drainPendingAutonomousTurns(this.#transport);
22161
23206
  }
22162
23207
  }
22163
23208
  async #cancel(command) {
@@ -22168,6 +23213,12 @@ var PiHarnessSession = class {
22168
23213
  error: invalidState("Pi Turn Cancel must reference the active Turn")
22169
23214
  };
22170
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
+ }
22171
23222
  if (active.cancellationRequested) {
22172
23223
  return { ok: true, value: { cancellationRequested: true } };
22173
23224
  }
@@ -22282,7 +23333,9 @@ var PiHarnessSession = class {
22282
23333
  interactions: /* @__PURE__ */ new Map(),
22283
23334
  interactionByNativeId: /* @__PURE__ */ new Map(),
22284
23335
  cancellationRequested: false,
23336
+ settling: false,
22285
23337
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23338
+ progressItems: /* @__PURE__ */ new Set(),
22286
23339
  completion,
22287
23340
  resolveCompletion
22288
23341
  };
@@ -22315,6 +23368,8 @@ var PiHarnessSession = class {
22315
23368
  return { ok: true, value: { turnId: command.turnId } };
22316
23369
  } finally {
22317
23370
  this.#acceptingTurn = false;
23371
+ if (this.#transport)
23372
+ this.#drainPendingAutonomousTurns(this.#transport);
22318
23373
  }
22319
23374
  }
22320
23375
  async #ensureTransport() {
@@ -22365,6 +23420,8 @@ var PiHarnessSession = class {
22365
23420
  return transport;
22366
23421
  }).catch(async (error51) => {
22367
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);
22368
23425
  await transport.close().catch(() => void 0);
22369
23426
  if (this.#phase === "open")
22370
23427
  this.#fault(error51);
@@ -22377,6 +23434,11 @@ var PiHarnessSession = class {
22377
23434
  return starting;
22378
23435
  }
22379
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
+ });
22380
23442
  transport.setSubagentStatusHandler?.((runs) => {
22381
23443
  if (this.#phase !== "open")
22382
23444
  return;
@@ -22388,12 +23450,16 @@ var PiHarnessSession = class {
22388
23450
  transport.setUsageHandler?.((observation) => {
22389
23451
  if (this.#phase !== "open")
22390
23452
  return;
22391
- const record7 = piUsageRecord(observation.message, observation);
22392
- if (record7?.kind === "request")
22393
- this.#event({ type: "usage.request", request: record7.request });
22394
- 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")
22395
23457
  this.#event({ type: "usage.history", complete: false });
22396
23458
  });
23459
+ if (transport.setAutonomousTurnLifecycleHandler) {
23460
+ transport.setAutonomousTurnLifecycleHandler((update) => this.#handleAutonomousLifecycle(transport, update));
23461
+ return;
23462
+ }
22397
23463
  transport.setAutonomousTurnHandler((turn) => {
22398
23464
  if (this.#phase !== "open")
22399
23465
  return;
@@ -22405,6 +23471,20 @@ var PiHarnessSession = class {
22405
23471
  });
22406
23472
  }
22407
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;
22408
23488
  if (this.#pendingSubagentStatus) {
22409
23489
  this.#subagents.observe(this.#pendingSubagentStatus);
22410
23490
  this.#pendingSubagentStatus = null;
@@ -22417,6 +23497,52 @@ var PiHarnessSession = class {
22417
23497
  this.#handleAutonomousTurn(transport, candidate.turn);
22418
23498
  }
22419
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
+ }
22420
23546
  #handleAutonomousTurn(transport, turn) {
22421
23547
  if (this.#phase !== "open")
22422
23548
  return;
@@ -22428,7 +23554,7 @@ var PiHarnessSession = class {
22428
23554
  }));
22429
23555
  return;
22430
23556
  }
22431
- if (this.#active || this.#acceptingTurn || this.#configuring) {
23557
+ if (this.#active && !this.#active.settling) {
22432
23558
  this.#fault(new PiAdapterFaultError({
22433
23559
  code: "protocolError",
22434
23560
  message: "Pi autonomous Turn overlapped another Host operation",
@@ -22436,7 +23562,22 @@ var PiHarnessSession = class {
22436
23562
  }));
22437
23563
  return;
22438
23564
  }
22439
- 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());
22440
23581
  let resolveCompletion = () => void 0;
22441
23582
  const completion = new Promise((resolve) => {
22442
23583
  resolveCompletion = resolve;
@@ -22448,6 +23589,7 @@ var PiHarnessSession = class {
22448
23589
  };
22449
23590
  const active = {
22450
23591
  command: { type: "turn.start", turnId, input: [] },
23592
+ ...runId ? { autonomousRunId: runId } : {},
22451
23593
  agentItem: item,
22452
23594
  agentMessageId: null,
22453
23595
  compactionItem: null,
@@ -22457,10 +23599,19 @@ var PiHarnessSession = class {
22457
23599
  interactions: /* @__PURE__ */ new Map(),
22458
23600
  interactionByNativeId: /* @__PURE__ */ new Map(),
22459
23601
  cancellationRequested: false,
23602
+ settling: false,
22460
23603
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23604
+ progressItems: /* @__PURE__ */ new Set(),
22461
23605
  completion,
22462
23606
  resolveCompletion
22463
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) {
22464
23615
  const nativeTurnRef = turn.nativeTurnKey ? nativeTurnRefSchema.parse({
22465
23616
  harnessId: this.harnessId,
22466
23617
  nativeSessionId: transport.state.sessionId,
@@ -22473,10 +23624,6 @@ var PiHarnessSession = class {
22473
23624
  checkpointId: nativeTurnRef.nativeTurnKey,
22474
23625
  formatVersion: 1
22475
23626
  }) : void 0;
22476
- this.#active = active;
22477
- this.#event({ type: "turn.autonomous.started", turnId, input: [] });
22478
- this.#event({ type: "turn.started", turnId });
22479
- this.#event({ type: "item.started", turnId, item });
22480
23627
  try {
22481
23628
  for (const event of turn.events)
22482
23629
  this.#handleTurnEvent(active, event);
@@ -22546,17 +23693,35 @@ var PiHarnessSession = class {
22546
23693
  if (this.#active !== active || this.#phase === "closed" || this.#phase === "faulted")
22547
23694
  return;
22548
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
+ }
22549
23710
  case "text.delta":
22550
- this.#activateAgentMessage(active, event.messageId);
23711
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23712
+ active.sawAssistantMessage = true;
22551
23713
  this.#appendText(active, event.delta);
22552
23714
  return;
22553
23715
  case "reasoning.delta":
22554
- this.#appendReasoning(active, event.delta);
23716
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23717
+ this.#appendReasoning(active, event.delta, event.nativeMessageIdentity);
22555
23718
  return;
22556
23719
  case "reasoning.completed":
22557
23720
  this.#completeReasoning(active, { status: "succeeded" });
22558
23721
  return;
22559
23722
  case "message.completed":
23723
+ if (event.phase && active.agentMessageId === event.messageId && active.agentItem)
23724
+ active.agentItem = { ...active.agentItem, phase: event.phase };
22560
23725
  void this.#refreshUsage(active.command.turnId);
22561
23726
  return;
22562
23727
  case "compaction.started":
@@ -22614,7 +23779,7 @@ var PiHarnessSession = class {
22614
23779
  if (active.interactionByNativeId.has(request.requestId)) {
22615
23780
  throw new Error("Pi Interaction started more than once");
22616
23781
  }
22617
- const interactionId = hostInteractionIdSchema.parse(randomUUID6());
23782
+ const interactionId = hostInteractionIdSchema.parse(randomUUID7());
22618
23783
  const question = request.method === "select" ? {
22619
23784
  id: "answer",
22620
23785
  type: "choice",
@@ -22671,17 +23836,21 @@ var PiHarnessSession = class {
22671
23836
  reason
22672
23837
  });
22673
23838
  }
22674
- #activateAgentMessage(active, messageId) {
23839
+ #activateAgentMessage(active, messageId, nativeMessageIdentity2) {
22675
23840
  if (active.agentMessageId === messageId)
22676
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
+ }
22677
23846
  if (active.agentMessageId !== null) {
22678
23847
  this.#completeReasoning(active, { status: "succeeded" });
22679
- this.#completeAgentItem(active, { status: "succeeded" }, false);
23848
+ this.#completeAgentItem(active, { status: "succeeded" }, true);
22680
23849
  }
22681
23850
  if (!active.agentItem) {
22682
23851
  active.agentItem = {
22683
23852
  type: "agentMessage",
22684
- itemId: this.#newItemId(),
23853
+ itemId: nativeItemId ?? this.#newItemId(),
22685
23854
  text: ""
22686
23855
  };
22687
23856
  this.#event({
@@ -22691,18 +23860,17 @@ var PiHarnessSession = class {
22691
23860
  });
22692
23861
  }
22693
23862
  active.agentMessageId = messageId;
22694
- active.sawAssistantMessage = true;
22695
23863
  }
22696
- #appendText(active, text2) {
23864
+ #appendText(active, text4) {
22697
23865
  if (active.agentMessageId === null || !active.agentItem) {
22698
23866
  throw new Error("Pi Assistant text arrived outside an active message");
22699
23867
  }
22700
- active.agentItem = { ...active.agentItem, text: active.agentItem.text + text2 };
23868
+ active.agentItem = { ...active.agentItem, text: active.agentItem.text + text4 };
22701
23869
  this.#event({
22702
23870
  type: "item.updated",
22703
23871
  turnId: active.command.turnId,
22704
23872
  itemId: active.agentItem.itemId,
22705
- update: { type: "text.append", text: text2 }
23873
+ update: { type: "text.append", text: text4 }
22706
23874
  });
22707
23875
  }
22708
23876
  #completeAgentItem(active, outcome, completeEmpty) {
@@ -22713,13 +23881,13 @@ var PiHarnessSession = class {
22713
23881
  active.agentItem = null;
22714
23882
  this.#completeItem(active, item, outcome);
22715
23883
  }
22716
- #appendReasoning(active, text2) {
22717
- if (text2.length === 0)
23884
+ #appendReasoning(active, text4, nativeMessageIdentity2) {
23885
+ if (text4.length === 0)
22718
23886
  return;
22719
23887
  if (!active.reasoningItem) {
22720
23888
  active.reasoningItem = {
22721
23889
  type: "reasoning",
22722
- itemId: this.#newItemId(),
23890
+ itemId: piMessageItemId(nativeMessageIdentity2, "reasoning") ?? this.#newItemId(),
22723
23891
  text: ""
22724
23892
  };
22725
23893
  this.#event({
@@ -22730,13 +23898,13 @@ var PiHarnessSession = class {
22730
23898
  }
22731
23899
  active.reasoningItem = {
22732
23900
  ...active.reasoningItem,
22733
- text: active.reasoningItem.text + text2
23901
+ text: active.reasoningItem.text + text4
22734
23902
  };
22735
23903
  this.#event({
22736
23904
  type: "item.updated",
22737
23905
  turnId: active.command.turnId,
22738
23906
  itemId: active.reasoningItem.itemId,
22739
- update: { type: "text.append", text: text2 }
23907
+ update: { type: "text.append", text: text4 }
22740
23908
  });
22741
23909
  }
22742
23910
  #completeReasoning(active, outcome) {
@@ -22749,13 +23917,12 @@ var PiHarnessSession = class {
22749
23917
  #startTool(active, event) {
22750
23918
  if (active.tools.has(event.callId))
22751
23919
  throw new Error("Pi Tool started more than once");
22752
- const normalizedName = normalizeToolName(event.toolName);
22753
- 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;
22754
- const item = command ? {
23920
+ const shell = piToolCommand(event.toolName, event.arguments);
23921
+ const item = shell ? {
22755
23922
  type: "commandExecution",
22756
23923
  itemId: this.#newItemId(),
22757
- command,
22758
- cwd: stringField(event.arguments, "cwd") ?? this.#cwd
23924
+ command: shell.command,
23925
+ cwd: shell.cwd ?? this.#cwd
22759
23926
  } : {
22760
23927
  type: "toolExecution",
22761
23928
  itemId: this.#newItemId(),
@@ -22873,14 +24040,17 @@ var PiHarnessSession = class {
22873
24040
  sessionId: transport.state.sessionId,
22874
24041
  model: nativeModelForHistory(transport.state)
22875
24042
  });
22876
- 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));
22877
24044
  if (created.length !== 1) {
22878
24045
  throw new Error(`Pi Turn persisted ${created.length} new User Entries; exactly one is required`);
22879
24046
  }
22880
24047
  const turn = created[0];
22881
- if (!turn?.checkpoint)
22882
- throw new Error("Pi Turn has no terminal Checkpoint identity");
22883
- 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
+ };
22884
24054
  }
22885
24055
  #completeTurn(active, outcome, finalText, nativeTurnRef) {
22886
24056
  if (this.#active !== active)
@@ -22909,14 +24079,20 @@ var PiHarnessSession = class {
22909
24079
  });
22910
24080
  active.resolveCompletion();
22911
24081
  queueMicrotask(() => {
22912
- if (this.#phase === "open")
22913
- 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);
22914
24087
  });
22915
24088
  }
22916
24089
  #fault(error51) {
22917
24090
  if (this.#phase === "closed" || this.#phase === "faulted")
22918
24091
  return;
22919
24092
  const normalized = normalizedError(error51, "internalError");
24093
+ this.#pendingAutonomousTurns = [];
24094
+ this.#pendingAutonomousLifecycle = [];
24095
+ this.#pendingAutonomousLifecycleBytes = 0;
22920
24096
  if (this.#active) {
22921
24097
  this.#completeTurn(this.#active, { status: "failed", error: normalized });
22922
24098
  }
@@ -22925,6 +24101,9 @@ var PiHarnessSession = class {
22925
24101
  this.#channel.end();
22926
24102
  }
22927
24103
  async #close() {
24104
+ this.#pendingAutonomousTurns = [];
24105
+ this.#pendingAutonomousLifecycle = [];
24106
+ this.#pendingAutonomousLifecycleBytes = 0;
22928
24107
  if (this.#phase === "closed")
22929
24108
  return;
22930
24109
  const wasFaulted = this.#phase === "faulted";
@@ -22957,7 +24136,7 @@ var PiHarnessSession = class {
22957
24136
  this.#channel.emit({ kind: "event", event });
22958
24137
  }
22959
24138
  #newItemId() {
22960
- return hostItemIdSchema.parse(randomUUID6());
24139
+ return hostItemIdSchema.parse(randomUUID7());
22961
24140
  }
22962
24141
  };
22963
24142
  var PiAdapter = class {
@@ -22972,12 +24151,15 @@ var PiAdapter = class {
22972
24151
  if (this.#closePromise || parent.harnessId !== this.harnessId) {
22973
24152
  return { ok: false, error: invalidState("Pi Subagent parent is unavailable") };
22974
24153
  }
24154
+ const gotgenes = parseGotgenesId(nativeSubagentId);
22975
24155
  const workflow = parsePiWorkflowSubagentId(nativeSubagentId);
22976
- if (!workflow)
24156
+ if (!workflow && !gotgenes)
22977
24157
  parsePiSubagentId(nativeSubagentId);
22978
24158
  const live = [...this.#sessions].find((session) => session.ownsNativeSession(parent.nativeSessionId));
22979
24159
  let reply;
22980
24160
  if (live) {
24161
+ if (gotgenes)
24162
+ return await live.readGotgenesChild(gotgenes, cwd);
22981
24163
  if (workflow)
22982
24164
  return await readPiWorkflowChild(await live.readSubagentHistory(cwd), parent.nativeSessionId, workflow);
22983
24165
  reply = await live.inspectSubagent(nativeSubagentId, cwd);
@@ -22989,6 +24171,8 @@ var PiAdapter = class {
22989
24171
  if (transport.state.sessionId !== parent.nativeSessionId)
22990
24172
  throw new Error("Pi Subagent parent identity mismatch");
22991
24173
  await transport.verifySessionCwd(cwd);
24174
+ if (gotgenes)
24175
+ return await readGotgenesChild(await transport.getEntries(), parent.nativeSessionId, gotgenes);
22992
24176
  if (workflow)
22993
24177
  return await readPiWorkflowChild(await transport.getEntries(), parent.nativeSessionId, workflow);
22994
24178
  if (!transport.inspectSubagent)