@karlorz/codexhost-cli-win32-x64 0.16.1-2 → 0.17.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +86 -20
  5. package/app/console-web.js +76 -17
  6. package/app/cpa-live-voice-hook.js +62 -8
  7. package/app/desktop-controller.mjs +107 -31
  8. package/app/host-runtime.mjs +2560 -1634
  9. package/app/plugins/antigravity/plugin.mjs +66 -2
  10. package/app/plugins/claude-code/plugin.mjs +43 -6
  11. package/app/plugins/codebuddy/plugin.mjs +41 -0
  12. package/app/plugins/codex-usage/plugin.mjs +31 -0
  13. package/app/plugins/copilot/plugin.mjs +31 -0
  14. package/app/plugins/cursor-cli/plugin.mjs +40 -5
  15. package/app/plugins/deepseek-harness/plugin.mjs +490 -46
  16. package/app/plugins/devin/assets/icon.svg +1 -0
  17. package/app/plugins/devin/manifest.json +30 -0
  18. package/app/plugins/devin/plugin.mjs +23536 -0
  19. package/app/plugins/enabled.json +2 -0
  20. package/app/plugins/grok/plugin.mjs +1615 -495
  21. package/app/plugins/hermes/plugin.mjs +484 -196
  22. package/app/plugins/kimi-code/plugin.mjs +31 -0
  23. package/app/plugins/kiro-cli/plugin.mjs +31 -0
  24. package/app/plugins/omp/plugin.mjs +31 -0
  25. package/app/plugins/opencode/plugin.mjs +31 -0
  26. package/app/plugins/pi/plugin.mjs +1491 -411
  27. package/app/plugins/qoder/plugin.mjs +9555 -8654
  28. package/app/plugins/qoder-cn/plugin.mjs +9555 -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 +29471 -0
  32. package/app/plugins/workbuddy/plugin.mjs +41 -0
  33. package/app/plugins/zcode/plugin.mjs +31 -0
  34. package/app/renderer-extension.js +966 -233
  35. package/bin/codexhost.exe +0 -0
  36. package/libexec/codexhost-node-repl.exe +0 -0
  37. package/libexec/codexhost-shim.exe +0 -0
  38. package/libexec/codexhost-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, path17) {
1321
+ if (!path17)
1322
1322
  return obj;
1323
- return path16.reduce((acc, key) => acc?.[key], obj);
1323
+ return path17.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(path17, 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(path17);
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, path17 = []) => {
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 }, [...path17, ...issue2.path]));
1887
1887
  } else if (issue2.code === "invalid_key") {
1888
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1888
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1889
1889
  } else if (issue2.code === "invalid_element") {
1890
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1890
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1891
1891
  } else {
1892
- const fullpath = [...path16, ...issue2.path];
1892
+ const fullpath = [...path17, ...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, path17 = []) => {
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 }, [...path17, ...issue2.path]));
1924
1924
  } else if (issue2.code === "invalid_key") {
1925
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1925
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1926
1926
  } else if (issue2.code === "invalid_element") {
1927
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1927
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1928
1928
  } else {
1929
- const fullpath = [...path16, ...issue2.path];
1929
+ const fullpath = [...path17, ...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 path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1962
+ for (const seg of path17) {
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 = (text3) => {
8193
+ return text3.charAt(0).toUpperCase() + text3.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 path17 = ref.slice(1).split("/").filter(Boolean);
14655
+ if (path17.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 (path17[0] === defsKey) {
14660
+ const key = path17[1];
14661
14661
  if (!key || !ctx.defs[key]) {
14662
14662
  throw new Error(`Reference not found: ${ref}`);
14663
14663
  }
@@ -15173,7 +15173,7 @@ var harnessDisplaySetSchema = external_exports.strictObject({
15173
15173
 
15174
15174
  // ../../shared-contracts/dist/harness-presentation.js
15175
15175
  var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
15176
- var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text2) => text2.trim().length > 0);
15176
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text3) => text3.trim().length > 0);
15177
15177
  var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
15178
15178
  label: displayText(256).optional(),
15179
15179
  description: displayText(1024).optional()
@@ -15545,7 +15545,7 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
15545
15545
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15546
15546
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15547
15547
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15548
- var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text2) => text2.length <= maximum));
15548
+ var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text3) => text3.length <= maximum));
15549
15549
  var composerIndicatorsSchema = external_exports.array(external_exports.object({
15550
15550
  kind: external_exports.literal("countdown"),
15551
15551
  id: external_exports.string().min(1).max(64),
@@ -16684,6 +16684,37 @@ var voiceSettingsStateSchema = external_exports.strictObject({
16684
16684
  })
16685
16685
  });
16686
16686
 
16687
+ // ../../shared-contracts/dist/background-activity.js
16688
+ var backgroundActivitySchema = external_exports.strictObject({
16689
+ id: external_exports.string().min(1),
16690
+ kind: external_exports.enum(["task", "monitor", "loop", "subagent"]),
16691
+ label: external_exports.string(),
16692
+ status: external_exports.enum(["running", "scheduled", "completed", "failed", "cancelled", "unknown"]),
16693
+ canStop: external_exports.boolean(),
16694
+ /** Existing detached command Item presented by Desktop's native process UI. */
16695
+ commandItemId: hostItemIdSchema.optional(),
16696
+ schedule: external_exports.string().optional(),
16697
+ nextRunAt: external_exports.string().datetime({ offset: true }).optional(),
16698
+ relatedActivityId: external_exports.string().optional(),
16699
+ threadId: hostThreadIdSchema.optional()
16700
+ });
16701
+ var backgroundActivityDetailSchema = external_exports.strictObject({
16702
+ activity: backgroundActivitySchema,
16703
+ output: external_exports.string(),
16704
+ truncated: external_exports.boolean()
16705
+ });
16706
+ var threadActivityParamsSchema = external_exports.strictObject({ threadId: hostThreadIdSchema });
16707
+ var threadActivityItemParamsSchema = threadActivityParamsSchema.extend({
16708
+ activityId: external_exports.string().min(1)
16709
+ });
16710
+ var threadActivityListResultSchema = external_exports.strictObject({
16711
+ supported: external_exports.boolean(),
16712
+ activities: external_exports.array(backgroundActivitySchema)
16713
+ });
16714
+ var threadActivityStopResultSchema = external_exports.strictObject({
16715
+ outcome: external_exports.enum(["stopped", "alreadyStopped", "notFound"])
16716
+ });
16717
+
16687
16718
  // ../../shared-contracts/dist/index.js
16688
16719
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
16689
16720
 
@@ -16858,8 +16889,8 @@ async function readCandidate(file2, signal) {
16858
16889
  const message3 = isRecord(entry.message) ? entry.message : null;
16859
16890
  if (!firstMessage && entry.type === "message" && message3?.role === "user") {
16860
16891
  const content = message3.content;
16861
- 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(" ") : "";
16862
- firstMessage = sessionImportTitle(text2);
16892
+ const text3 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
16893
+ firstMessage = sessionImportTitle(text3);
16863
16894
  }
16864
16895
  hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
16865
16896
  entries.set(entry.id, hasUser);
@@ -17375,8 +17406,8 @@ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17375
17406
  const descriptor = catalog.commands.find(({ id }) => id === commandId);
17376
17407
  if (!descriptor)
17377
17408
  return null;
17378
- const text2 = typeof argumentText === "string" ? argumentText.trim() : "";
17379
- return text2 ? `${descriptor.invocation} ${text2}` : descriptor.invocation;
17409
+ const text3 = typeof argumentText === "string" ? argumentText.trim() : "";
17410
+ return text3 ? `${descriptor.invocation} ${text3}` : descriptor.invocation;
17380
17411
  }
17381
17412
  function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17382
17413
  if (!live)
@@ -17512,16 +17543,16 @@ var Diff = class {
17512
17543
  }
17513
17544
  }
17514
17545
  }
17515
- addToPath(path16, added, removed, oldPosInc, options) {
17516
- const last = path16.lastComponent;
17546
+ addToPath(path17, added, removed, oldPosInc, options) {
17547
+ const last = path17.lastComponent;
17517
17548
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17518
17549
  return {
17519
- oldPos: path16.oldPos + oldPosInc,
17550
+ oldPos: path17.oldPos + oldPosInc,
17520
17551
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17521
17552
  };
17522
17553
  } else {
17523
17554
  return {
17524
- oldPos: path16.oldPos + oldPosInc,
17555
+ oldPos: path17.oldPos + oldPosInc,
17525
17556
  lastComponent: { count: 1, added, removed, previousComponent: last }
17526
17557
  };
17527
17558
  }
@@ -17921,9 +17952,9 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader
17921
17952
  } }));
17922
17953
  }
17923
17954
  }
17924
- function splitLines(text2) {
17925
- const hasTrailingNl = text2.endsWith("\n");
17926
- const result = text2.split("\n").map((line) => line + "\n");
17955
+ function splitLines(text3) {
17956
+ const hasTrailingNl = text3.endsWith("\n");
17957
+ const result = text3.split("\n").map((line) => line + "\n");
17927
17958
  if (hasTrailingNl) {
17928
17959
  result.pop();
17929
17960
  } else {
@@ -18157,11 +18188,344 @@ function piNestedCallFileChanges(nestedCalls, cwd) {
18157
18188
  return projected;
18158
18189
  }
18159
18190
 
18160
- // dist/pi-subagents.js
18191
+ // dist/pi-message-item-id.js
18161
18192
  import { createHash } from "node:crypto";
18193
+ function piMessageIdentity(sessionId, message3, timestampCounts) {
18194
+ if (typeof message3 !== "object" || message3 === null || !("role" in message3) || message3.role !== "assistant")
18195
+ return void 0;
18196
+ if ("timestamp" in message3 && typeof message3.timestamp === "number" && Number.isSafeInteger(message3.timestamp) && message3.timestamp >= 0) {
18197
+ const occurrence = timestampCounts.get(message3.timestamp) ?? 0;
18198
+ timestampCounts.set(message3.timestamp, occurrence + 1);
18199
+ return { sessionId, timestamp: message3.timestamp, occurrence };
18200
+ }
18201
+ if ("responseId" in message3 && typeof message3.responseId === "string" && message3.responseId.trim().length > 0)
18202
+ return { responseId: message3.responseId };
18203
+ return void 0;
18204
+ }
18205
+ function piHistoryMessageIdentities(sessionId, entries) {
18206
+ const timestampCounts = /* @__PURE__ */ new Map();
18207
+ const identities = /* @__PURE__ */ new Map();
18208
+ for (const entry of entries) {
18209
+ const identity = piMessageIdentity(sessionId, entry.message, timestampCounts);
18210
+ if (identity)
18211
+ identities.set(entry.id, identity);
18212
+ }
18213
+ return { identities, timestampCounts };
18214
+ }
18215
+ function piMessageItemId(identity, kind) {
18216
+ if (!identity)
18217
+ return null;
18218
+ const timestampIdentity = "timestamp" in identity;
18219
+ const value = timestampIdentity ? JSON.stringify([identity.sessionId, identity.timestamp, identity.occurrence]) : identity.responseId;
18220
+ const digest = createHash("sha256").update(value).digest("hex");
18221
+ return hostItemIdSchema.parse(`pi-${timestampIdentity ? "message" : "response"}-v1-${digest}-${kind}`);
18222
+ }
18223
+
18224
+ // dist/pi-assistant-outcome.js
18225
+ function piAssistantWasAborted(value) {
18226
+ if (typeof value !== "object" || value === null || Array.isArray(value))
18227
+ return false;
18228
+ const message3 = value;
18229
+ return message3.role === "assistant" && (message3.stopReason === "aborted" || message3.stopReason === "error" && message3.errorMessage === "This operation was aborted");
18230
+ }
18231
+ function piAssistantPhase(value) {
18232
+ if (typeof value !== "object" || value === null || Array.isArray(value))
18233
+ return void 0;
18234
+ const message3 = value;
18235
+ if (message3.role !== "assistant")
18236
+ return void 0;
18237
+ 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;
18238
+ if (!lastText && !(typeof message3.content === "string" && message3.content.trim()))
18239
+ return void 0;
18240
+ if (typeof lastText?.textSignature === "string") {
18241
+ try {
18242
+ const signature = JSON.parse(lastText.textSignature);
18243
+ 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"))
18244
+ return signature.phase;
18245
+ } catch {
18246
+ }
18247
+ }
18248
+ if (message3.stopReason === "toolUse")
18249
+ return "commentary";
18250
+ if (message3.stopReason === "stop")
18251
+ return "final_answer";
18252
+ return void 0;
18253
+ }
18254
+
18255
+ // dist/pi-subagents.js
18256
+ import { createHash as createHash3 } from "node:crypto";
18257
+
18258
+ // dist/pi-gotgenes-extension.js
18259
+ import { createHash as createHash2, randomUUID } from "node:crypto";
18260
+ import { mkdir, readFile, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
18261
+ import { homedir as homedir2 } from "node:os";
18262
+ import path7 from "node:path";
18263
+ var GOTGENES_WIDGET = "codexhost-gotgenes-subagents";
18264
+ var GOTGENES_PREFIX = "CODEXHOST_GOTGENES_SUBAGENTS_V1:";
18265
+ var GOTGENES_EXTENSION = `export default function(pi) {
18266
+ let ctx, timer, service, previous = "";
18267
+ const publish = () => {
18268
+ if (!ctx) return;
18269
+ // Child SDK sessions can publish their own process-global service. Bind this parent once.
18270
+ if (!service) {
18271
+ const candidate = globalThis[Symbol.for("@gotgenes/pi-subagents:service")];
18272
+ if (typeof candidate?.listAgents !== "function") return;
18273
+ service = candidate;
18274
+ }
18275
+ const agents = service.listAgents().slice(0, 128).map((r) => ({
18276
+ id: r.id, type: r.type, description: r.description?.slice(0, 2048),
18277
+ status: r.status, isBackground: r.isBackground, outputFile: r.outputFile,
18278
+ toolUses: r.toolUses, startedAt: r.startedAt, completedAt: r.completedAt,
18279
+ result: r.result?.slice(0, 2048), error: r.error?.slice(0, 2048),
18280
+ turnBudget: r.turnBudget, lifetimeUsage: r.lifetimeUsage,
18281
+ }));
18282
+ const payload = JSON.stringify({version: 1, agents});
18283
+ if (payload === previous) return;
18284
+ previous = payload;
18285
+ ctx.ui.setWidget("${GOTGENES_WIDGET}", ["${GOTGENES_PREFIX}" + payload]);
18286
+ };
18287
+ const schedule = () => queueMicrotask(publish);
18288
+ for (const name of ["created", "started", "completed", "failed", "resuming", "resumed", "compacted", "steered", "update"]) {
18289
+ pi.events.on("subagents:" + name, schedule);
18290
+ }
18291
+ pi.on("session_start", (_event, context) => {
18292
+ // A session switch keeps this extension's manager/service; only reload creates a new instance.
18293
+ ctx = context; previous = ""; clearInterval(timer);
18294
+ schedule();
18295
+ // The public service publishes outputFile only after queued session creation and has no progress event.
18296
+ timer = setInterval(publish, 1000);
18297
+ timer.unref?.();
18298
+ });
18299
+ pi.on("session_shutdown", () => { clearInterval(timer); timer = undefined; ctx = undefined; service = undefined; });
18300
+ }
18301
+ `;
18302
+ async function ensureGotgenesExtension(environment) {
18303
+ const digest = createHash2("sha256").update(GOTGENES_EXTENSION).digest("hex").slice(0, 16);
18304
+ const root = environment.CODEXHOST_DATA_DIR ?? path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".codexhost");
18305
+ const directory = path7.resolve(root, "extensions", "pi-subagent-observer");
18306
+ const file2 = path7.join(directory, `${digest}.mjs`);
18307
+ if (await readFile(file2, "utf8").catch(() => "") === GOTGENES_EXTENSION)
18308
+ return file2;
18309
+ await mkdir(directory, { recursive: true });
18310
+ const temporary = `${file2}.${randomUUID()}.tmp`;
18311
+ try {
18312
+ await writeFile2(temporary, GOTGENES_EXTENSION, { mode: 384 });
18313
+ try {
18314
+ await rename(temporary, file2);
18315
+ } catch (error51) {
18316
+ if (await readFile(file2, "utf8").catch(() => "") !== GOTGENES_EXTENSION)
18317
+ throw error51;
18318
+ }
18319
+ } finally {
18320
+ await rm2(temporary, { force: true });
18321
+ }
18322
+ return file2;
18323
+ }
18324
+
18325
+ // dist/pi-gotgenes-subagents.js
18326
+ var PREFIX = "pi-gotgenes-v1:";
18327
+ var STATUSES = {
18328
+ queued: "pending",
18329
+ running: "running",
18330
+ background: "pending",
18331
+ completed: "completed",
18332
+ aborted: "interrupted",
18333
+ stopped: "interrupted",
18334
+ error: "failed"
18335
+ };
18336
+ function isRecord4(value) {
18337
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18338
+ }
18339
+ function text(value, limit = 2048) {
18340
+ return typeof value === "string" && value.length > 0 && value.length <= limit;
18341
+ }
18342
+ function gotgenesId(id) {
18343
+ return PREFIX + Buffer.from(id).toString("base64url");
18344
+ }
18345
+ function parseGotgenesId(value) {
18346
+ if (!value.startsWith(PREFIX))
18347
+ return null;
18348
+ const id = Buffer.from(value.slice(PREFIX.length), "base64url").toString("utf8");
18349
+ if (!text(id, 256) || /[\s/\\]/u.test(id) || gotgenesId(id) !== value)
18350
+ throw new Error("Invalid gotgenes subagent identity");
18351
+ return id;
18352
+ }
18353
+ function gotgenesRecord(value) {
18354
+ 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))
18355
+ return null;
18356
+ const status = STATUSES[value.status];
18357
+ if (!status)
18358
+ return null;
18359
+ const id = gotgenesId(value.id);
18360
+ const progress = typeof value.toolUses === "number" ? `${value.toolUses} tool uses` : void 0;
18361
+ const result = typeof value.error === "string" ? value.error : typeof value.result === "string" ? value.result : progress;
18362
+ return {
18363
+ id: value.id,
18364
+ roleKnown: value.roleKnown !== false,
18365
+ backgroundKnown: typeof value.isBackground === "boolean",
18366
+ child: {
18367
+ subagentId: id,
18368
+ nativeSubagentId: id,
18369
+ description: value.description,
18370
+ role: value.type,
18371
+ status,
18372
+ background: value.isBackground === true,
18373
+ ...text(value.modelName) ? { model: value.modelName } : {},
18374
+ ...result ? { resultSummary: result.slice(0, 2048) } : {}
18375
+ },
18376
+ ...text(value.outputFile, 8192) ? { outputFile: value.outputFile } : {},
18377
+ revision: JSON.stringify([
18378
+ value.toolUses,
18379
+ value.turnBudget,
18380
+ value.lifetimeUsage,
18381
+ value.outputFile
18382
+ ])
18383
+ };
18384
+ }
18385
+ function gotgenesToolRecord(toolName, result) {
18386
+ if (!["subagent", "get_subagent_result"].includes(toolName) || !isRecord4(result) || !isRecord4(result.details))
18387
+ return null;
18388
+ const d = result.details;
18389
+ if (!text(d.agentId, 256) || !text(d.displayName) || !text(d.description))
18390
+ return null;
18391
+ return gotgenesRecord({
18392
+ ...d,
18393
+ id: d.agentId,
18394
+ type: d.subagentType ?? d.displayName,
18395
+ roleKnown: text(d.subagentType),
18396
+ isBackground: toolName === "subagent" ? d.status === "background" || Array.isArray(d.tags) && d.tags.includes("background") : void 0,
18397
+ outputFile: d.transcriptPath,
18398
+ result: d.preview
18399
+ });
18400
+ }
18401
+ function parseGotgenesWidget(value) {
18402
+ if (!isRecord4(value) || value.type !== "extension_ui_request" || value.method !== "setWidget" || value.widgetKey !== GOTGENES_WIDGET || !Array.isArray(value.widgetLines))
18403
+ return null;
18404
+ const line = value.widgetLines.find((x) => typeof x === "string" && x.startsWith(GOTGENES_PREFIX));
18405
+ if (!line || Buffer.byteLength(line) > 1024 * 1024)
18406
+ return null;
18407
+ try {
18408
+ const payload = JSON.parse(line.slice(GOTGENES_PREFIX.length));
18409
+ if (!isRecord4(payload) || payload.version !== 1 || !Array.isArray(payload.agents) || payload.agents.length > 128)
18410
+ return null;
18411
+ const records = payload.agents.map(gotgenesRecord);
18412
+ return records.every((r) => r !== null) ? records : null;
18413
+ } catch {
18414
+ return null;
18415
+ }
18416
+ }
18417
+ function mergeGotgenesRecord(previous, record9) {
18418
+ const model2 = record9.child.model ?? previous?.child.model;
18419
+ const role = record9.roleKnown ? record9.child.role : previous?.child.role ?? record9.child.role;
18420
+ return {
18421
+ ...previous,
18422
+ ...record9,
18423
+ roleKnown: record9.roleKnown || previous?.roleKnown === true,
18424
+ backgroundKnown: record9.backgroundKnown || previous?.backgroundKnown === true,
18425
+ outputFile: record9.outputFile ?? previous?.outputFile,
18426
+ child: {
18427
+ ...previous?.child,
18428
+ ...record9.child,
18429
+ ...model2 ? { model: model2 } : {},
18430
+ ...role ? { role } : {},
18431
+ background: record9.backgroundKnown ? record9.child.background : previous?.child.background ?? record9.child.background
18432
+ }
18433
+ };
18434
+ }
18435
+ var GotgenesSubagents = class {
18436
+ emit;
18437
+ records = /* @__PURE__ */ new Map();
18438
+ #nativeObserved = /* @__PURE__ */ new Set();
18439
+ #active = /* @__PURE__ */ new Map();
18440
+ constructor(emit) {
18441
+ this.emit = emit;
18442
+ }
18443
+ observe(records, publish = true, activeTurn, nativeObservation = false) {
18444
+ for (const record9 of records) {
18445
+ if (!publish && this.#nativeObserved.has(record9.id))
18446
+ continue;
18447
+ if (nativeObservation)
18448
+ this.#nativeObserved.add(record9.id);
18449
+ const previous = this.records.get(record9.id);
18450
+ const merged = mergeGotgenesRecord(previous, record9);
18451
+ this.records.set(record9.id, merged);
18452
+ if (publish && !previous && activeTurn && !this.#active.has(record9.id)) {
18453
+ const item = {
18454
+ type: "subagentDelegation",
18455
+ itemId: activeTurn.nextItemId(),
18456
+ operation: "spawn",
18457
+ subagents: [merged.child]
18458
+ };
18459
+ this.#active.set(record9.id, { turnId: activeTurn.turnId, item });
18460
+ this.emit({ type: "item.started", turnId: activeTurn.turnId, item });
18461
+ }
18462
+ if (!publish || JSON.stringify(previous) === JSON.stringify(merged))
18463
+ continue;
18464
+ const active = this.#active.get(record9.id);
18465
+ if (active) {
18466
+ active.item = { ...active.item, subagents: [merged.child] };
18467
+ this.emit({
18468
+ type: "item.updated",
18469
+ turnId: active.turnId,
18470
+ itemId: active.item.itemId,
18471
+ update: { type: "subagents.replace", subagents: [merged.child] }
18472
+ });
18473
+ }
18474
+ this.emit({
18475
+ type: "subagent.state.changed",
18476
+ nativeSubagentId: merged.child.subagentId,
18477
+ status: merged.child.status
18478
+ });
18479
+ this.emit({ type: "subagent.transcript.changed", nativeSubagentId: merged.child.subagentId });
18480
+ }
18481
+ }
18482
+ project(toolName, result, itemId2) {
18483
+ const parsed = gotgenesToolRecord(toolName, result);
18484
+ if (!parsed || toolName !== "subagent")
18485
+ return null;
18486
+ const child = this.records.get(parsed.id)?.child ?? parsed.child;
18487
+ return { type: "subagentDelegation", itemId: itemId2, operation: "spawn", subagents: [child] };
18488
+ }
18489
+ start(turnId, toolName, result, itemId2) {
18490
+ const parsed = gotgenesToolRecord(toolName, result);
18491
+ if (!parsed)
18492
+ return false;
18493
+ const prior = this.records.get(parsed.id);
18494
+ if (!prior || !this.#nativeObserved.has(parsed.id))
18495
+ this.observe([parsed]);
18496
+ else {
18497
+ this.observe([
18498
+ {
18499
+ ...prior,
18500
+ child: { ...prior.child, ...parsed.child.model ? { model: parsed.child.model } : {} }
18501
+ }
18502
+ ]);
18503
+ }
18504
+ if (toolName === "subagent" && !this.#active.has(parsed.id)) {
18505
+ const item = this.project(toolName, result, itemId2);
18506
+ if (!item)
18507
+ return false;
18508
+ this.#active.set(parsed.id, { turnId, item });
18509
+ this.emit({ type: "item.started", turnId, item });
18510
+ }
18511
+ return true;
18512
+ }
18513
+ finish(turnId) {
18514
+ for (const [id, active] of this.#active) {
18515
+ if (active.turnId !== turnId)
18516
+ continue;
18517
+ this.#active.delete(id);
18518
+ this.emit({
18519
+ type: "item.completed",
18520
+ turnId,
18521
+ snapshot: { item: active.item, outcome: { status: "succeeded" } }
18522
+ });
18523
+ }
18524
+ }
18525
+ };
18162
18526
 
18163
18527
  // dist/pi-subagent-workflow.js
18164
- var PREFIX = "pi-subagents-workflow-v1:";
18528
+ var PREFIX2 = "pi-subagents-workflow-v1:";
18165
18529
  var STATES = {
18166
18530
  pending: "pending",
18167
18531
  running: "running",
@@ -18175,7 +18539,7 @@ var STATES = {
18175
18539
  function record2(value) {
18176
18540
  return typeof value === "object" && value !== null && !Array.isArray(value);
18177
18541
  }
18178
- function text(value, limit = 256) {
18542
+ function text2(value, limit = 256) {
18179
18543
  return typeof value === "string" && value.length > 0 && value.length <= limit;
18180
18544
  }
18181
18545
  function piWorkflowSummary(result) {
@@ -18183,15 +18547,15 @@ function piWorkflowSummary(result) {
18183
18547
  return null;
18184
18548
  const details = result.details;
18185
18549
  const summary = details.workflowChildren;
18186
- 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)
18550
+ 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)
18187
18551
  return null;
18188
18552
  const children = [];
18189
18553
  const seen = /* @__PURE__ */ new Set();
18190
18554
  for (const child of summary.children) {
18191
- if (!record2(child) || !text(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
18555
+ if (!record2(child) || !text2(child.childId) || seen.has(child.childId) || typeof child.state !== "string" || !Object.hasOwn(STATES, child.state))
18192
18556
  return null;
18193
18557
  for (const key of ["agent", "sessionName", "model", "thinking"]) {
18194
- if (child[key] !== void 0 && !text(child[key], 2048))
18558
+ if (child[key] !== void 0 && !text2(child[key], 2048))
18195
18559
  return null;
18196
18560
  }
18197
18561
  const mappedState = STATES[child.state];
@@ -18215,15 +18579,15 @@ function piWorkflowSummary(result) {
18215
18579
  };
18216
18580
  }
18217
18581
  function piWorkflowSubagentId(address) {
18218
- return PREFIX + Buffer.from(JSON.stringify([address.workflowRunId, address.childId])).toString("base64url");
18582
+ return PREFIX2 + Buffer.from(JSON.stringify([address.workflowRunId, address.childId])).toString("base64url");
18219
18583
  }
18220
18584
  function parsePiWorkflowSubagentId(id) {
18221
- if (!id.startsWith(PREFIX))
18585
+ if (!id.startsWith(PREFIX2))
18222
18586
  return null;
18223
18587
  if (id.length > 3e3)
18224
18588
  throw new Error("Invalid Pi workflow child identity");
18225
- const value = JSON.parse(Buffer.from(id.slice(PREFIX.length), "base64url").toString("utf8"));
18226
- if (!Array.isArray(value) || value.length !== 2 || !text(value[0]) || !text(value[1]))
18589
+ const value = JSON.parse(Buffer.from(id.slice(PREFIX2.length), "base64url").toString("utf8"));
18590
+ if (!Array.isArray(value) || value.length !== 2 || !text2(value[0]) || !text2(value[1]))
18227
18591
  throw new Error("Invalid Pi workflow child identity");
18228
18592
  const address = { workflowRunId: value[0], childId: value[1] };
18229
18593
  if (piWorkflowSubagentId(address) !== id)
@@ -18381,8 +18745,13 @@ var PiSubagents = class {
18381
18745
  #children = /* @__PURE__ */ new Map();
18382
18746
  #active = /* @__PURE__ */ new Map();
18383
18747
  #waiting = /* @__PURE__ */ new Map();
18748
+ gotgenes;
18384
18749
  constructor(emit) {
18385
18750
  this.emit = emit;
18751
+ this.gotgenes = new GotgenesSubagents(emit);
18752
+ }
18753
+ observeGotgenes(records, activeTurn) {
18754
+ this.gotgenes.observe(records, true, activeTurn, true);
18386
18755
  }
18387
18756
  observe(runs) {
18388
18757
  this.#apply(runs, true);
@@ -18436,6 +18805,9 @@ var PiSubagents = class {
18436
18805
  }
18437
18806
  }
18438
18807
  project(toolName, result, itemId2, callId) {
18808
+ const gotgenes = this.gotgenes.project(toolName, result, itemId2);
18809
+ if (gotgenes)
18810
+ return gotgenes;
18439
18811
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18440
18812
  if (workflow && (!callId || workflow.parentToolCallId === callId))
18441
18813
  return projectPiWorkflow(workflow, itemId2);
@@ -18446,6 +18818,8 @@ var PiSubagents = class {
18446
18818
  return children.length ? { type: "subagentDelegation", itemId: itemId2, operation: "spawn", subagents: children } : null;
18447
18819
  }
18448
18820
  start(turnId, toolName, result, itemId2, callId) {
18821
+ if (this.gotgenes.start(turnId, toolName, result, itemId2))
18822
+ return;
18449
18823
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18450
18824
  if (workflow && (!callId || workflow.parentToolCallId === callId)) {
18451
18825
  const key = `workflow:${workflow.workflowRunId}`;
@@ -18491,6 +18865,7 @@ var PiSubagents = class {
18491
18865
  this.emit({ type: "item.started", turnId, item });
18492
18866
  }
18493
18867
  finish(turnId) {
18868
+ this.gotgenes.finish(turnId);
18494
18869
  for (const [runId, waiting] of this.#waiting) {
18495
18870
  if (waiting.turnId === turnId)
18496
18871
  this.#waiting.delete(runId);
@@ -18538,15 +18913,15 @@ ${entry.text}`);
18538
18913
  nativeTurnRef: nativeTurnRefSchema.parse({
18539
18914
  harnessId: "pi",
18540
18915
  nativeSessionId: parentSessionId,
18541
- nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
18916
+ nativeTurnKey: `pi-subagent-${createHash3("sha256").update(id).digest("hex")}`,
18542
18917
  formatVersion: 1
18543
18918
  }),
18544
18919
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
18545
- items: texts.map((text2, index) => ({
18920
+ items: texts.map((text3, index) => ({
18546
18921
  item: {
18547
18922
  type: "agentMessage",
18548
- text: text2,
18549
- itemId: hostItemIdSchema.parse(`pi-subagent-${createHash("sha256").update(`${id}:${index}:${text2}`).digest("hex")}`)
18923
+ text: text3,
18924
+ itemId: hostItemIdSchema.parse(`pi-subagent-${createHash3("sha256").update(`${id}:${index}:${text3}`).digest("hex")}`)
18550
18925
  },
18551
18926
  outcome: { status: "succeeded" }
18552
18927
  })),
@@ -18694,22 +19069,149 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
18694
19069
  });
18695
19070
  }
18696
19071
 
19072
+ // dist/pi-progress.js
19073
+ import { createHash as createHash4 } from "node:crypto";
19074
+ function record4(value) {
19075
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19076
+ }
19077
+ function textContent(content) {
19078
+ if (typeof content === "string")
19079
+ return content;
19080
+ if (!Array.isArray(content))
19081
+ return "";
19082
+ return content.filter((part) => record4(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
19083
+ }
19084
+ function boundedPiProgress(text3) {
19085
+ const limit = 64e3;
19086
+ return text3.length <= limit ? text3 : `${text3.slice(0, limit)}
19087
+ [Pi notification truncated]`;
19088
+ }
19089
+ function visibleText(text3) {
19090
+ return text3.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
19091
+ }
19092
+ function noticeDisplay(value, fallback) {
19093
+ if (!record4(value) || !record4(value.details) || typeof value.details.summary !== "string")
19094
+ return visibleText(fallback);
19095
+ const details = value.details;
19096
+ const parts = [visibleText(details.summary)];
19097
+ if (typeof details.exitCode === "number")
19098
+ parts.push(`Exit code: ${details.exitCode}`);
19099
+ for (const key of ["signal", "error", "errorMessage"])
19100
+ if (typeof details[key] === "string" && details[key])
19101
+ parts.push(`${key}: ${visibleText(details[key])}`);
19102
+ if (record4(details.logMatch) && typeof details.logMatch.line === "string")
19103
+ parts.push(`Log: ${visibleText(details.logMatch.line)}`);
19104
+ if (typeof details.command === "string" && details.command)
19105
+ parts.push(`Command: ${visibleText(details.command)}`);
19106
+ return parts.join("\n\n");
19107
+ }
19108
+ function piCustomNoticeKey(value) {
19109
+ if (!record4(value) || value.type !== "custom_message" && value.role !== "custom" || value.display !== true || typeof value.customType !== "string")
19110
+ return null;
19111
+ const text3 = textContent(value.content);
19112
+ if (text3.trim().length === 0)
19113
+ return null;
19114
+ return JSON.stringify([value.customType, text3]);
19115
+ }
19116
+ function piCustomNotice(value, sessionId, occurrences) {
19117
+ const key = piCustomNoticeKey(value);
19118
+ if (!key)
19119
+ return null;
19120
+ const occurrence = occurrences.get(key) ?? 0;
19121
+ occurrences.set(key, occurrence + 1);
19122
+ const digest = createHash4("sha256").update(JSON.stringify([sessionId, key, occurrence])).digest("hex");
19123
+ const [customType, text3] = JSON.parse(key);
19124
+ return {
19125
+ type: "progress.message",
19126
+ itemId: hostItemIdSchema.parse(`pi-notice-v1-${digest}`),
19127
+ text: boundedPiProgress(`Pi notification (${visibleText(customType)})
19128
+
19129
+ ${noticeDisplay(value, text3)}`)
19130
+ };
19131
+ }
19132
+ function piHistoryNotices(sessionId, entries) {
19133
+ const occurrences = /* @__PURE__ */ new Map();
19134
+ const notices = /* @__PURE__ */ new Map();
19135
+ for (const entry of entries) {
19136
+ const notice = piCustomNotice(entry.message ?? entry, sessionId, occurrences);
19137
+ if (notice)
19138
+ notices.set(entry.id, notice);
19139
+ }
19140
+ return { notices, occurrences };
19141
+ }
19142
+ function piStatusText(value) {
19143
+ if (value.type === "auto_retry_start") {
19144
+ const attempt = typeof value.attempt === "number" ? ` ${value.attempt}` : "";
19145
+ const maximum = typeof value.maxAttempts === "number" ? `/${value.maxAttempts}` : "";
19146
+ const delay2 = typeof value.delayMs === "number" && value.delayMs >= 0 ? ` Waiting ${value.delayMs / 1e3} s before retrying.` : "";
19147
+ const reason = typeof value.errorMessage === "string" ? `
19148
+
19149
+ ${visibleText(value.errorMessage)}` : "";
19150
+ return boundedPiProgress(`Pi retry${attempt}${maximum}.${delay2}${reason}`);
19151
+ }
19152
+ if (value.type === "auto_retry_end") {
19153
+ if (typeof value.success !== "boolean")
19154
+ return null;
19155
+ const reason = typeof value.finalError === "string" ? `
19156
+
19157
+ ${visibleText(value.finalError)}` : "";
19158
+ return boundedPiProgress(`Pi retry ${value.success ? "succeeded" : "ended without success"}.${reason}`);
19159
+ }
19160
+ if (value.type !== "extension_ui_request")
19161
+ return null;
19162
+ if (value.method === "notify" && typeof value.message === "string" && value.message.trim()) {
19163
+ const level = typeof value.notifyType === "string" ? ` (${value.notifyType})` : "";
19164
+ return boundedPiProgress(`Pi notification${level}
19165
+
19166
+ ${visibleText(value.message)}`);
19167
+ }
19168
+ if (value.method === "setStatus" && typeof value.statusKey === "string") {
19169
+ return typeof value.statusText === "string" && value.statusText.trim() ? boundedPiProgress(`Pi status (${visibleText(value.statusKey)})
19170
+
19171
+ ${visibleText(value.statusText)}`) : `Pi status (${visibleText(value.statusKey)}) cleared.`;
19172
+ }
19173
+ return null;
19174
+ }
19175
+
19176
+ // dist/pi-tool-command.js
19177
+ function record5(value) {
19178
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19179
+ }
19180
+ function stringField(value, key) {
19181
+ if (!record5(value))
19182
+ return void 0;
19183
+ for (const source of [value, value.input, value.arguments]) {
19184
+ if (record5(source) && typeof source[key] === "string" && source[key].length > 0)
19185
+ return source[key];
19186
+ }
19187
+ return void 0;
19188
+ }
19189
+ function piToolCommand(name, arguments_) {
19190
+ if (!["bash", "exec", "terminal", "run"].includes(name.toLowerCase()))
19191
+ return null;
19192
+ const command = ["command", "cmd", "script", "commandLine", "command_line"].map((key) => stringField(arguments_, key)).find((value) => value !== void 0);
19193
+ if (!command)
19194
+ return null;
19195
+ const cwd = stringField(arguments_, "cwd");
19196
+ return { command, ...cwd ? { cwd } : {} };
19197
+ }
19198
+
18697
19199
  // dist/pi-history.js
18698
19200
  var piHarnessId = harnessIdSchema.parse("pi");
18699
- function isRecord4(value) {
19201
+ function isRecord5(value) {
18700
19202
  return typeof value === "object" && value !== null && !Array.isArray(value);
18701
19203
  }
18702
- function textContent(value) {
19204
+ function textContent2(value) {
18703
19205
  if (typeof value === "string")
18704
19206
  return value;
18705
19207
  if (!Array.isArray(value))
18706
19208
  return "";
18707
- return value.filter((part) => isRecord4(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
19209
+ return value.filter((part) => isRecord5(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
18708
19210
  }
18709
19211
  function thinkingContent(value) {
18710
19212
  if (!Array.isArray(value))
18711
19213
  return "";
18712
- return value.filter((part) => isRecord4(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
19214
+ return value.filter((part) => isRecord5(part) && part.type === "thinking" && typeof part.thinking === "string").map((part) => part.thinking).join("");
18713
19215
  }
18714
19216
  function validatedEntry(value) {
18715
19217
  if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
@@ -18740,7 +19242,7 @@ function activePiEntries(history) {
18740
19242
  return reversed.reverse();
18741
19243
  }
18742
19244
  function message(entry) {
18743
- return entry.type === "message" && isRecord4(entry.message) ? entry.message : null;
19245
+ return entry.type === "message" && isRecord5(entry.message) ? entry.message : null;
18744
19246
  }
18745
19247
  function messageRole(entry) {
18746
19248
  const value = message(entry)?.role;
@@ -18755,7 +19257,7 @@ function assistantOutcome(entries) {
18755
19257
  if (!final)
18756
19258
  return { status: "unknown", reason: "Pi history has no Assistant terminal" };
18757
19259
  const stopReason = final.stopReason;
18758
- if (stopReason === "aborted") {
19260
+ if (piAssistantWasAborted(final)) {
18759
19261
  return { status: "cancelled", reason: "Pi Assistant was aborted" };
18760
19262
  }
18761
19263
  if (stopReason === "error") {
@@ -18768,7 +19270,7 @@ function assistantOutcome(entries) {
18768
19270
  }
18769
19271
  };
18770
19272
  }
18771
- if (typeof stopReason === "string" || textContent(final.content).length > 0) {
19273
+ if (typeof stopReason === "string" || textContent2(final.content).length > 0) {
18772
19274
  return { status: "succeeded" };
18773
19275
  }
18774
19276
  return { status: "unknown", reason: "Pi Assistant terminal is not classifiable" };
@@ -18785,8 +19287,8 @@ function itemOutcome(outcome) {
18785
19287
  return { status: "succeeded" };
18786
19288
  }
18787
19289
  function toolOutput(value) {
18788
- const text2 = textContent(value);
18789
- return text2.length > 0 ? { content: [{ type: "text", text: text2 }] } : void 0;
19290
+ const text3 = textContent2(value);
19291
+ return text3.length > 0 ? { content: [{ type: "text", text: text3 }] } : void 0;
18790
19292
  }
18791
19293
  function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18792
19294
  const items = [];
@@ -18809,37 +19311,52 @@ function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18809
19311
  }
18810
19312
  return items;
18811
19313
  }
18812
- function snapshotItems(entries, outcome, subagents, cwd) {
19314
+ function snapshotItems(entries, messageIdentities, notices, outcome, subagents, cwd) {
18813
19315
  const snapshots = [];
18814
19316
  const toolCalls = /* @__PURE__ */ new Map();
18815
19317
  for (const entry of entries) {
19318
+ const notice = notices.get(entry.id);
19319
+ if (notice) {
19320
+ snapshots.push({
19321
+ item: {
19322
+ type: "agentMessage",
19323
+ itemId: notice.itemId,
19324
+ text: notice.text,
19325
+ phase: "commentary"
19326
+ },
19327
+ outcome: { status: "succeeded" }
19328
+ });
19329
+ continue;
19330
+ }
18816
19331
  const nativeMessage = message(entry);
18817
19332
  if (!nativeMessage)
18818
19333
  continue;
18819
19334
  const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
18820
19335
  if (nativeMessage.role === "assistant") {
18821
- const text2 = textContent(content);
19336
+ const text3 = textContent2(content);
18822
19337
  const reasoning = thinkingContent(content);
18823
19338
  let projectedText = false;
18824
19339
  let projectedReasoning = false;
18825
19340
  for (const [ordinal, part] of content.entries()) {
18826
- if (!isRecord4(part))
19341
+ if (!isRecord5(part))
18827
19342
  continue;
18828
19343
  if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
18829
19344
  const item2 = {
18830
19345
  type: "reasoning",
18831
- itemId: itemId(entry.id, "reasoning", 0),
19346
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "reasoning") ?? itemId(entry.id, "reasoning", 0),
18832
19347
  text: reasoning
18833
19348
  };
18834
19349
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18835
19350
  projectedReasoning = true;
18836
19351
  continue;
18837
19352
  }
18838
- if (part.type === "text" && !projectedText && text2.length > 0) {
19353
+ if (part.type === "text" && !projectedText && text3.length > 0) {
19354
+ const phase = piAssistantPhase(nativeMessage);
18839
19355
  const item2 = {
18840
19356
  type: "agentMessage",
18841
- itemId: itemId(entry.id, "assistant", 0),
18842
- text: text2
19357
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "assistant") ?? itemId(entry.id, "assistant", 0),
19358
+ text: text3,
19359
+ ...phase ? { phase } : {}
18843
19360
  };
18844
19361
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18845
19362
  projectedText = true;
@@ -18867,9 +19384,24 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18867
19384
  if (!call || call.name !== nativeMessage.toolName)
18868
19385
  continue;
18869
19386
  const output = toolOutput(nativeMessage.content);
18870
- const item = {
18871
- type: "toolExecution",
19387
+ const shell = piToolCommand(call.name, call.arguments);
19388
+ const commandCwd = shell?.cwd ?? cwd;
19389
+ const durationMs = typeof nativeMessage.durationMs === "number" && Number.isFinite(nativeMessage.durationMs) && nativeMessage.durationMs >= 0 ? nativeMessage.durationMs : void 0;
19390
+ const base = {
18872
19391
  itemId: itemId(call.entryId, "tool", call.ordinal),
19392
+ ...durationMs !== void 0 ? { durationMs } : {}
19393
+ };
19394
+ const exitCode = typeof nativeMessage.exitCode === "number" && Number.isInteger(nativeMessage.exitCode) ? nativeMessage.exitCode : void 0;
19395
+ const item = shell ? {
19396
+ ...base,
19397
+ type: "commandExecution",
19398
+ command: shell.command,
19399
+ ...commandCwd ? { cwd: commandCwd } : {},
19400
+ ...output ? { output: textContent2(nativeMessage.content) } : {},
19401
+ ...exitCode !== void 0 ? { exitCode } : {}
19402
+ } : {
19403
+ ...base,
19404
+ type: "toolExecution",
18873
19405
  toolName: call.name,
18874
19406
  arguments: call.arguments,
18875
19407
  ...output ? { output } : {}
@@ -18900,6 +19432,10 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18900
19432
  function modelChange(entry) {
18901
19433
  return entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string" ? { provider: entry.provider, id: entry.modelId } : null;
18902
19434
  }
19435
+ function isEmptyWakeup(entry) {
19436
+ const content = message(entry)?.content;
19437
+ return content === "" || Array.isArray(content) && content.every((part) => isRecord5(part) && part.type === "text" && part.text === "");
19438
+ }
18903
19439
  function turnStarts(active) {
18904
19440
  const starts = [];
18905
19441
  let terminal = true;
@@ -18907,6 +19443,8 @@ function turnStarts(active) {
18907
19443
  for (const [index, entry] of active.entries()) {
18908
19444
  const role = messageRole(entry);
18909
19445
  if (role === "user") {
19446
+ if (pending && isEmptyWakeup(entry))
19447
+ continue;
18910
19448
  starts.push({ entry, index });
18911
19449
  pending = null;
18912
19450
  terminal = false;
@@ -18923,6 +19461,8 @@ function turnStarts(active) {
18923
19461
  }
18924
19462
  function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0)) {
18925
19463
  const active = activePiEntries(history);
19464
+ const { identities } = piHistoryMessageIdentities(state2.sessionId, active);
19465
+ const { notices } = piHistoryNotices(state2.sessionId, active);
18926
19466
  const turns = [];
18927
19467
  const starts = turnStarts(active);
18928
19468
  const byIndex = new Map(starts.map((start, ordinal) => [start.index, ordinal]));
@@ -18944,7 +19484,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18944
19484
  const end = next?.index ?? active.length;
18945
19485
  const entries = active.slice(index, end);
18946
19486
  const outcome = assistantOutcome(entries);
18947
- const userText = textContent(message(user)?.content);
19487
+ const userText = textContent2(message(user)?.content);
18948
19488
  const nativeTurnRef = nativeTurnRefSchema.parse({
18949
19489
  harnessId: piHarnessId,
18950
19490
  nativeSessionId: state2.sessionId,
@@ -18961,7 +19501,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18961
19501
  nativeTurnRef,
18962
19502
  ...!next || messageRole(next.entry) === "user" ? { checkpoint } : {},
18963
19503
  input: messageRole(user) === "user" ? [{ type: "text", text: userText }] : [],
18964
- items: snapshotItems(entries, outcome, subagents, state2.cwd),
19504
+ items: snapshotItems(entries, identities, notices, outcome, subagents, state2.cwd),
18965
19505
  outcome,
18966
19506
  ...effectiveModel ? { model: encodePiModelRef(effectiveModel) } : {}
18967
19507
  });
@@ -18996,14 +19536,14 @@ function resolvePiForkBoundary(history, checkpointId) {
18996
19536
  }
18997
19537
 
18998
19538
  // dist/pi-usage.js
18999
- function isRecord5(value) {
19539
+ function isRecord6(value) {
19000
19540
  return typeof value === "object" && value !== null && !Array.isArray(value);
19001
19541
  }
19002
19542
  function nonNegativeSafeInteger(value) {
19003
19543
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
19004
19544
  }
19005
19545
  function optionalPiCacheHitRatePercent(value) {
19006
- if (!isRecord5(value) || value.role !== "assistant" || !isRecord5(value.usage))
19546
+ if (!isRecord6(value) || value.role !== "assistant" || !isRecord6(value.usage))
19007
19547
  return null;
19008
19548
  const input = nonNegativeSafeInteger(value.usage.input);
19009
19549
  const cacheRead = nonNegativeSafeInteger(value.usage.cacheRead);
@@ -19016,20 +19556,20 @@ function optionalPiCacheHitRatePercent(value) {
19016
19556
  function latestPiCacheHitRatePercent(history) {
19017
19557
  let latest = null;
19018
19558
  for (const entry of activePiEntries(history)) {
19019
- if (entry.type === "message" && isRecord5(entry.message) && entry.message.role === "assistant") {
19559
+ if (entry.type === "message" && isRecord6(entry.message) && entry.message.role === "assistant") {
19020
19560
  latest = optionalPiCacheHitRatePercent(entry.message);
19021
19561
  }
19022
19562
  }
19023
19563
  return latest;
19024
19564
  }
19025
19565
  function responseData(response, operation) {
19026
- if (!isRecord5(response.data)) {
19566
+ if (!isRecord6(response.data)) {
19027
19567
  throw new Error(`Pi RPC ${operation} response has no data`);
19028
19568
  }
19029
19569
  return response.data;
19030
19570
  }
19031
19571
  function contextUsage(value) {
19032
- if (!isRecord5(value))
19572
+ if (!isRecord6(value))
19033
19573
  throw new Error("Pi RPC context Usage is invalid");
19034
19574
  return parseHostUsage({
19035
19575
  contextUsedTokens: value.tokens,
@@ -19039,15 +19579,15 @@ function contextUsage(value) {
19039
19579
  function parsePiSessionUsage(response) {
19040
19580
  const data = responseData(response, "Session stats");
19041
19581
  const tokens = data.tokens;
19042
- if (tokens !== void 0 && !isRecord5(tokens)) {
19582
+ if (tokens !== void 0 && !isRecord6(tokens)) {
19043
19583
  throw new Error("Pi RPC Session stats tokens are invalid");
19044
19584
  }
19045
19585
  return parseHostUsage({
19046
- ...isRecord5(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
19047
- ...isRecord5(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
19048
- ...isRecord5(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
19049
- ...isRecord5(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
19050
- ...isRecord5(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
19586
+ ...isRecord6(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
19587
+ ...isRecord6(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
19588
+ ...isRecord6(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
19589
+ ...isRecord6(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
19590
+ ...isRecord6(tokens) && tokens.total !== void 0 ? { totalTokens: tokens.total } : {},
19051
19591
  ...data.cost !== void 0 ? { totalCostUsd: data.cost } : {},
19052
19592
  ...data.contextUsage !== void 0 ? contextUsage(data.contextUsage) : {}
19053
19593
  });
@@ -19066,9 +19606,9 @@ function optionalPiStateContextUsage(value) {
19066
19606
  }
19067
19607
  }
19068
19608
  function piUsageRecord(message3, extra = {}) {
19069
- if (!isRecord5(message3) || message3.role !== "assistant")
19609
+ if (!isRecord6(message3) || message3.role !== "assistant")
19070
19610
  return null;
19071
- const usage = isRecord5(message3.usage) ? message3.usage : null;
19611
+ const usage = isRecord6(message3.usage) ? message3.usage : null;
19072
19612
  const input = nonNegativeSafeInteger(usage?.input);
19073
19613
  const output = nonNegativeSafeInteger(usage?.output);
19074
19614
  const requestId2 = typeof message3.responseId === "string" && message3.responseId.length > 0 ? message3.responseId : typeof message3.timestamp === "number" && Number.isSafeInteger(message3.timestamp) ? `t${message3.timestamp}` : null;
@@ -19105,17 +19645,17 @@ function piUsageHistory(history) {
19105
19645
  for (const entry of history.entries) {
19106
19646
  if (entry.type !== "message")
19107
19647
  continue;
19108
- const record7 = piUsageRecord(entry.message, { historical: true });
19109
- if (record7?.kind === "request")
19110
- requests.push(record7.request);
19111
- else if (record7?.kind === "missing")
19648
+ const record9 = piUsageRecord(entry.message, { historical: true });
19649
+ if (record9?.kind === "request")
19650
+ requests.push(record9.request);
19651
+ else if (record9?.kind === "missing")
19112
19652
  complete = false;
19113
19653
  }
19114
19654
  return { requests, complete };
19115
19655
  }
19116
19656
 
19117
19657
  // dist/pi-usage-statistics.js
19118
- function isRecord6(value) {
19658
+ function isRecord7(value) {
19119
19659
  return typeof value === "object" && value !== null && !Array.isArray(value);
19120
19660
  }
19121
19661
  function piUserText(content) {
@@ -19123,11 +19663,11 @@ function piUserText(content) {
19123
19663
  return content;
19124
19664
  if (!Array.isArray(content))
19125
19665
  return void 0;
19126
- return content.filter((block) => isRecord6(block) && block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join(" ");
19666
+ return content.filter((block) => isRecord7(block) && block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join(" ");
19127
19667
  }
19128
19668
  async function readPiUsage(file2, signal) {
19129
19669
  const entries = [];
19130
- const header = await jsonlHeader(file2, (record7) => record7.type === "session", signal);
19670
+ const header = await jsonlHeader(file2, (record9) => record9.type === "session", signal);
19131
19671
  let name;
19132
19672
  const session = {
19133
19673
  sessionId: typeof header?.id === "string" ? header.id : void 0,
@@ -19144,11 +19684,11 @@ async function readPiUsage(file2, signal) {
19144
19684
  if (!name && message3?.role === "user") {
19145
19685
  name = usageSessionTitle(piUserText(message3.content));
19146
19686
  }
19147
- const record7 = piUsageRecord(line.message);
19148
- if (record7?.kind !== "request")
19687
+ const record9 = piUsageRecord(line.message);
19688
+ if (record9?.kind !== "request")
19149
19689
  continue;
19150
19690
  const at = nativeTimeMs(message3.timestamp) ?? nativeTimeMs(line.timestamp);
19151
- const entry = at !== null && usageEntryFromRequest(record7.request, at);
19691
+ const entry = at !== null && usageEntryFromRequest(record9.request, at);
19152
19692
  if (!entry)
19153
19693
  continue;
19154
19694
  if (!(typeof message3.responseId === "string" && message3.responseId.length > 0)) {
@@ -19169,9 +19709,9 @@ function createPiUsageStatistics(environment) {
19169
19709
  }
19170
19710
 
19171
19711
  // dist/account-balance.js
19172
- import { readFile } from "node:fs/promises";
19173
- import { homedir as homedir2 } from "node:os";
19174
- import path7 from "node:path";
19712
+ import { readFile as readFile2 } from "node:fs/promises";
19713
+ import { homedir as homedir3 } from "node:os";
19714
+ import path8 from "node:path";
19175
19715
  var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
19176
19716
  var SUB2API_USAGE_PATH = "/v1/usage";
19177
19717
  var REQUEST_TIMEOUT_MS = 1e4;
@@ -19180,18 +19720,18 @@ function agentDirectory(environment) {
19180
19720
  const configured = environment.PI_CODING_AGENT_DIR?.trim();
19181
19721
  if (configured)
19182
19722
  return configured;
19183
- return path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".pi", "agent");
19723
+ return path8.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".pi", "agent");
19184
19724
  }
19185
- var record4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
19725
+ var record6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
19186
19726
  async function deepSeekApiKey(environment) {
19187
- const auth = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "auth.json"), "utf8")));
19188
- const deepseek = record4(auth.deepseek);
19727
+ const auth = record6(JSON.parse(await readFile2(path8.join(agentDirectory(environment), "auth.json"), "utf8")));
19728
+ const deepseek = record6(auth.deepseek);
19189
19729
  if (deepseek.type !== "api_key")
19190
19730
  return void 0;
19191
19731
  return typeof deepseek.key === "string" && deepseek.key.trim() ? deepseek.key : void 0;
19192
19732
  }
19193
19733
  function projectSub2ApiUsage(payload, providerId) {
19194
- const data = record4(payload);
19734
+ const data = record6(payload);
19195
19735
  if (data.isValid === false)
19196
19736
  return null;
19197
19737
  if (data.mode !== "unrestricted" && data.mode !== "quota_limited")
@@ -19201,7 +19741,7 @@ function projectSub2ApiUsage(payload, providerId) {
19201
19741
  return null;
19202
19742
  const wallet = finiteAmount(data.balance);
19203
19743
  const remaining = finiteAmount(data.remaining);
19204
- const quotaRemaining = finiteAmount(record4(data.quota).remaining);
19744
+ const quotaRemaining = finiteAmount(record6(data.quota).remaining);
19205
19745
  const amount = wallet ?? remaining ?? quotaRemaining;
19206
19746
  if (amount === null)
19207
19747
  return null;
@@ -19221,10 +19761,10 @@ function finiteAmount(value) {
19221
19761
  return Number.isFinite(amount) && amount >= 0 ? amount : null;
19222
19762
  }
19223
19763
  function projectDeepSeekBalance(payload) {
19224
- const data = record4(payload);
19764
+ const data = record6(payload);
19225
19765
  if (!Array.isArray(data.balance_infos))
19226
19766
  return null;
19227
- const first = record4(data.balance_infos[0]);
19767
+ const first = record6(data.balance_infos[0]);
19228
19768
  const amount = finiteAmount(first.total_balance);
19229
19769
  const currency = typeof first.currency === "string" ? first.currency.trim() : "";
19230
19770
  if (amount === null || !currency)
@@ -19253,11 +19793,11 @@ function usageEndpoint(baseUrl) {
19253
19793
  }
19254
19794
  async function configuredSub2ApiProviders(environment) {
19255
19795
  try {
19256
- const models = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "models.json"), "utf8")));
19257
- const providers = record4(models.providers);
19796
+ const models = record6(JSON.parse(await readFile2(path8.join(agentDirectory(environment), "models.json"), "utf8")));
19797
+ const providers = record6(models.providers);
19258
19798
  const found = [];
19259
19799
  for (const [id, definition] of Object.entries(providers)) {
19260
- const provider = record4(definition);
19800
+ const provider = record6(definition);
19261
19801
  const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
19262
19802
  const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
19263
19803
  if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
@@ -19315,21 +19855,21 @@ async function fetchPiAccountBalance(input) {
19315
19855
  }
19316
19856
 
19317
19857
  // dist/pi-credential-imports.js
19318
- import { randomUUID } from "node:crypto";
19858
+ import { randomUUID as randomUUID2 } from "node:crypto";
19319
19859
  import { execFile as execFile2 } from "node:child_process";
19320
19860
  import { promisify } from "node:util";
19321
19861
  import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
19322
19862
  import { realpath as realpath2 } from "node:fs/promises";
19323
19863
  import os4 from "node:os";
19324
- import path9 from "node:path";
19864
+ import path10 from "node:path";
19325
19865
  import { pathToFileURL } from "node:url";
19326
19866
 
19327
19867
  // dist/command.js
19328
19868
  import fs2 from "node:fs";
19329
- import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
19330
- import path8 from "node:path";
19869
+ import { homedir as homedir4, tmpdir as tmpdir2 } from "node:os";
19870
+ import path9 from "node:path";
19331
19871
  var PI_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
19332
- var PI_PACKAGE_PATH = path8.join("node_modules", "@earendil-works", "pi-coding-agent");
19872
+ var PI_PACKAGE_PATH = path9.join("node_modules", "@earendil-works", "pi-coding-agent");
19333
19873
  var piDiscoverySpec = {
19334
19874
  id: "pi",
19335
19875
  command: "pi",
@@ -19355,18 +19895,18 @@ function resolvePiExecutable(input, dependencies = {}) {
19355
19895
  return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
19356
19896
  }
19357
19897
  function findPiPackageDirectory(executable) {
19358
- let directory = path8.dirname(executable);
19898
+ let directory = path9.dirname(executable);
19359
19899
  while (true) {
19360
- for (const candidate of [directory, path8.join(directory, PI_PACKAGE_PATH)]) {
19900
+ for (const candidate of [directory, path9.join(directory, PI_PACKAGE_PATH)]) {
19361
19901
  try {
19362
- const manifest = JSON.parse(fs2.readFileSync(path8.join(candidate, "package.json"), "utf8"));
19902
+ const manifest = JSON.parse(fs2.readFileSync(path9.join(candidate, "package.json"), "utf8"));
19363
19903
  if (typeof manifest === "object" && manifest !== null && "name" in manifest && manifest.name === PI_PACKAGE_NAME) {
19364
19904
  return candidate;
19365
19905
  }
19366
19906
  } catch {
19367
19907
  }
19368
19908
  }
19369
- const parent = path8.dirname(directory);
19909
+ const parent = path9.dirname(directory);
19370
19910
  if (parent === directory)
19371
19911
  return void 0;
19372
19912
  directory = parent;
@@ -19374,16 +19914,16 @@ function findPiPackageDirectory(executable) {
19374
19914
  }
19375
19915
  function findPiCliEntry(packageDirectory) {
19376
19916
  try {
19377
- const manifest = JSON.parse(fs2.readFileSync(path8.join(packageDirectory, "package.json"), "utf8"));
19917
+ const manifest = JSON.parse(fs2.readFileSync(path9.join(packageDirectory, "package.json"), "utf8"));
19378
19918
  if (typeof manifest !== "object" || manifest === null || !("bin" in manifest))
19379
19919
  return void 0;
19380
19920
  const bin = manifest.bin;
19381
19921
  const entry = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && "pi" in bin ? bin.pi : void 0;
19382
19922
  if (typeof entry !== "string" || !entry.trim())
19383
19923
  return void 0;
19384
- const resolved = path8.resolve(packageDirectory, entry);
19385
- const relative = path8.relative(packageDirectory, resolved);
19386
- if (relative === ".." || relative.startsWith(`..${path8.sep}`) || path8.isAbsolute(relative) || !fs2.statSync(resolved).isFile()) {
19924
+ const resolved = path9.resolve(packageDirectory, entry);
19925
+ const relative = path9.relative(packageDirectory, resolved);
19926
+ if (relative === ".." || relative.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative) || !fs2.statSync(resolved).isFile()) {
19387
19927
  return void 0;
19388
19928
  }
19389
19929
  return resolved;
@@ -19392,11 +19932,11 @@ function findPiCliEntry(packageDirectory) {
19392
19932
  }
19393
19933
  }
19394
19934
  function isFilesystemRoot(cwd) {
19395
- const resolved = path8.resolve(cwd);
19396
- return resolved === path8.parse(resolved).root;
19935
+ const resolved = path9.resolve(cwd);
19936
+ return resolved === path9.parse(resolved).root;
19397
19937
  }
19398
19938
  function writableDirectory(candidate) {
19399
- if (!candidate || !path8.isAbsolute(candidate) || isFilesystemRoot(candidate))
19939
+ if (!candidate || !path9.isAbsolute(candidate) || isFilesystemRoot(candidate))
19400
19940
  return void 0;
19401
19941
  try {
19402
19942
  if (!fs2.statSync(candidate).isDirectory())
@@ -19409,19 +19949,19 @@ function writableDirectory(candidate) {
19409
19949
  }
19410
19950
  function resolvePiInspectCwd(inputCwd, environment = process.env) {
19411
19951
  if (typeof inputCwd === "string" && inputCwd.length > 0 && !isFilesystemRoot(inputCwd)) {
19412
- return path8.resolve(inputCwd);
19952
+ return path9.resolve(inputCwd);
19413
19953
  }
19414
- const candidates = [environment.USERPROFILE, environment.HOME, homedir3(), tmpdir2()];
19954
+ const candidates = [environment.USERPROFILE, environment.HOME, homedir4(), tmpdir2()];
19415
19955
  for (const candidate of candidates) {
19416
19956
  const usable = writableDirectory(candidate);
19417
19957
  if (usable)
19418
19958
  return usable;
19419
19959
  }
19420
- return inputCwd && inputCwd.length > 0 ? path8.resolve(inputCwd) : process.cwd();
19960
+ return inputCwd && inputCwd.length > 0 ? path9.resolve(inputCwd) : process.cwd();
19421
19961
  }
19422
19962
 
19423
19963
  // dist/pi-credential-imports.js
19424
- var PREFIX2 = "codexhost-account-";
19964
+ var PREFIX3 = "codexhost-account-";
19425
19965
  function object2(value) {
19426
19966
  return typeof value === "object" && value !== null && !Array.isArray(value);
19427
19967
  }
@@ -19462,7 +20002,7 @@ function describeOauth(credential) {
19462
20002
  };
19463
20003
  }
19464
20004
  function writeAuth(filename, content) {
19465
- const temporary = `${filename}.${randomUUID()}.tmp`;
20005
+ const temporary = `${filename}.${randomUUID2()}.tmp`;
19466
20006
  try {
19467
20007
  writeFileSync(temporary, content, { flag: "wx", mode: 384 });
19468
20008
  renameSync(temporary, filename);
@@ -19471,8 +20011,8 @@ function writeAuth(filename, content) {
19471
20011
  }
19472
20012
  }
19473
20013
  function removeOwnedFiles(dir) {
19474
- rmSync(path9.join(dir, "index.ts"), { force: true });
19475
- rmSync(path9.join(dir, "import.json"), { force: true });
20014
+ rmSync(path10.join(dir, "index.ts"), { force: true });
20015
+ rmSync(path10.join(dir, "import.json"), { force: true });
19476
20016
  try {
19477
20017
  rmdirSync(dir);
19478
20018
  } catch {
@@ -19484,13 +20024,13 @@ async function installation(command, environment, authPath) {
19484
20024
  const cliEntry = directory ? findPiCliEntry(directory) : void 0;
19485
20025
  if (!directory || !cliEntry)
19486
20026
  throw new Error("Pi credential import requires a supported npm Pi installation");
19487
- const storage = await import(pathToFileURL(path9.join(directory, "dist/core/auth-storage.js")).href);
19488
- const ai = path9.join(directory, "node_modules/@earendil-works/pi-ai/dist");
19489
- const all = await import(pathToFileURL(path9.join(ai, "providers/all.js")).href);
20027
+ const storage = await import(pathToFileURL(path10.join(directory, "dist/core/auth-storage.js")).href);
20028
+ const ai = path10.join(directory, "node_modules/@earendil-works/pi-ai/dist");
20029
+ const all = await import(pathToFileURL(path10.join(ai, "providers/all.js")).href);
19490
20030
  const providers = all.getBuiltinProviders();
19491
20031
  const providerModules = {
19492
- "openai-codex": pathToFileURL(path9.join(ai, "providers/openai-codex.js")).href,
19493
- xai: pathToFileURL(path9.join(ai, "providers/xai.js")).href
20032
+ "openai-codex": pathToFileURL(path10.join(ai, "providers/openai-codex.js")).href,
20033
+ xai: pathToFileURL(path10.join(ai, "providers/xai.js")).href
19494
20034
  };
19495
20035
  for (const [id, url2] of Object.entries(providerModules)) {
19496
20036
  const module = await import(url2);
@@ -19504,8 +20044,8 @@ async function installation(command, environment, authPath) {
19504
20044
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
19505
20045
  async configuredProviderNames() {
19506
20046
  const { stdout } = await promisify(execFile2)(process.execPath, [cliEntry, "--offline", "--no-approve", "--list-models"], {
19507
- cwd: existsSync(path9.dirname(authPath)) ? path9.dirname(authPath) : os4.homedir(),
19508
- env: { ...environment, PI_CODING_AGENT_DIR: path9.dirname(authPath), PI_OFFLINE: "1" },
20047
+ cwd: existsSync(path10.dirname(authPath)) ? path10.dirname(authPath) : os4.homedir(),
20048
+ env: { ...environment, PI_CODING_AGENT_DIR: path10.dirname(authPath), PI_OFFLINE: "1" },
19509
20049
  timeout: 15e3,
19510
20050
  maxBuffer: 4 * 1024 * 1024
19511
20051
  });
@@ -19535,26 +20075,26 @@ export default async function (pi) {
19535
20075
  }
19536
20076
  function createPiCredentialImports(options = {}) {
19537
20077
  const env = { ...process.env, ...options.environment };
19538
- const agentDir = env.PI_CODING_AGENT_DIR ?? path9.join(env.HOME ?? os4.homedir(), ".pi/agent");
19539
- const authPath = path9.join(agentDir, "auth.json");
19540
- const extensionsDir = path9.join(agentDir, "extensions");
20078
+ const agentDir = env.PI_CODING_AGENT_DIR ?? path10.join(env.HOME ?? os4.homedir(), ".pi/agent");
20079
+ const authPath = path10.join(agentDir, "auth.json");
20080
+ const extensionsDir = path10.join(agentDir, "extensions");
19541
20081
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
19542
20082
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
19543
- const location = (name) => path9.join(extensionsDir, `${PREFIX2}${credentialImportNameSchema.parse(name)}`);
20083
+ const location = (name) => path10.join(extensionsDir, `${PREFIX3}${credentialImportNameSchema.parse(name)}`);
19544
20084
  const readRecord = (name) => {
19545
20085
  const dir = location(name);
19546
20086
  if (lstatSync(dir).isSymbolicLink())
19547
20087
  throw new Error("Imported configuration was changed; manage it in Pi");
19548
- const value = JSON.parse(readFileSync(path9.join(dir, "import.json"), "utf8"));
20088
+ const value = JSON.parse(readFileSync(path10.join(dir, "import.json"), "utf8"));
19549
20089
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
19550
20090
  throw new Error("Invalid import metadata");
19551
- const record7 = value.record;
19552
- if (!object2(record7))
20091
+ const record9 = value.record;
20092
+ if (!object2(record9))
19553
20093
  throw new Error("Invalid import metadata");
19554
20094
  value.record = credentialImportRecordSchema.parse({
19555
- name: record7.name,
19556
- source: record7.source,
19557
- importedAt: record7.importedAt
20095
+ name: record9.name,
20096
+ source: record9.source,
20097
+ importedAt: record9.importedAt
19558
20098
  });
19559
20099
  if (value.record.name !== name)
19560
20100
  throw new Error("Import identity mismatch");
@@ -19562,7 +20102,7 @@ function createPiCredentialImports(options = {}) {
19562
20102
  };
19563
20103
  const owned = (meta3, auth) => {
19564
20104
  const credential = auth[meta3.record.name];
19565
- const file2 = path9.join(location(meta3.record.name), "index.ts");
20105
+ const file2 = path10.join(location(meta3.record.name), "index.ts");
19566
20106
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
19567
20107
  };
19568
20108
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -19571,12 +20111,12 @@ function createPiCredentialImports(options = {}) {
19571
20111
  return [];
19572
20112
  const result = [];
19573
20113
  for (const entry of readdirSync(extensionsDir)) {
19574
- if (!entry.startsWith(PREFIX2))
20114
+ if (!entry.startsWith(PREFIX3))
19575
20115
  continue;
19576
- const name = entry.slice(PREFIX2.length);
20116
+ const name = entry.slice(PREFIX3.length);
19577
20117
  if (!credentialImportNameSchema.safeParse(name).success)
19578
20118
  continue;
19579
- if (!existsSync(path9.join(location(name), "import.json")))
20119
+ if (!existsSync(path10.join(location(name), "import.json")))
19580
20120
  continue;
19581
20121
  try {
19582
20122
  const meta3 = readRecord(name);
@@ -19597,7 +20137,7 @@ function createPiCredentialImports(options = {}) {
19597
20137
  },
19598
20138
  async listOthers() {
19599
20139
  const auth = readAuth();
19600
- const ours = new Set(ownedRecords(auth).map((record7) => record7.name));
20140
+ const ours = new Set(ownedRecords(auth).map((record9) => record9.name));
19601
20141
  const result = /* @__PURE__ */ new Map();
19602
20142
  const usable = (provider) => Boolean(provider) && provider.length <= 128 && !ours.has(provider) && !result.has(provider);
19603
20143
  for (const [provider, credential] of Object.entries(auth)) {
@@ -19610,7 +20150,7 @@ function createPiCredentialImports(options = {}) {
19610
20150
  ...describeOauth(credential)
19611
20151
  });
19612
20152
  }
19613
- const modelsPath = path9.join(agentDir, "models.json");
20153
+ const modelsPath = path10.join(agentDir, "models.json");
19614
20154
  if (existsSync(modelsPath)) {
19615
20155
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
19616
20156
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -19631,8 +20171,8 @@ function createPiCredentialImports(options = {}) {
19631
20171
  throw new Error("Unsupported credential source");
19632
20172
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
19633
20173
  throw new Error("Provider name already exists; choose another name");
19634
- const owner = randomUUID();
19635
- const record7 = credentialImportRecordSchema.parse({
20174
+ const owner = randomUUID2();
20175
+ const record9 = credentialImportRecordSchema.parse({
19636
20176
  name,
19637
20177
  source: transfer.source,
19638
20178
  importedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -19644,15 +20184,15 @@ function createPiCredentialImports(options = {}) {
19644
20184
  try {
19645
20185
  sdk.backend.withLock((current) => {
19646
20186
  const auth = parseAuth(current);
19647
- const modelsPath = path9.join(agentDir, "models.json");
20187
+ const modelsPath = path10.join(agentDir, "models.json");
19648
20188
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
19649
- if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path9.join(extensionsDir, `${name}-provider.ts`)))
20189
+ if (Object.hasOwn(auth, name) || Object.hasOwn(models.providers ?? {}, name) || existsSync(dir) || existsSync(path10.join(extensionsDir, `${name}-provider.ts`)))
19650
20190
  throw new Error("Provider name already exists; choose another name");
19651
20191
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
19652
20192
  mkdirSync(dir, { mode: 448 });
19653
20193
  created = true;
19654
- writeFileSync(path9.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record7, extension }), { flag: "wx", mode: 384 });
19655
- writeFileSync(path9.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
20194
+ writeFileSync(path10.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record9, extension }), { flag: "wx", mode: 384 });
20195
+ writeFileSync(path10.join(dir, "index.ts"), extension, { flag: "wx", mode: 384 });
19656
20196
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
19657
20197
  saveAuth(auth);
19658
20198
  committed = true;
@@ -19671,7 +20211,7 @@ function createPiCredentialImports(options = {}) {
19671
20211
  const auth = parseAuth(current);
19672
20212
  if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
19673
20213
  throw new Error("Import ownership or source account changed; refusing replacement");
19674
- const metadataPath = path9.join(location(name), "import.json");
20214
+ const metadataPath = path10.join(location(name), "import.json");
19675
20215
  const previous = readFileSync(metadataPath, "utf8");
19676
20216
  const updated = {
19677
20217
  ...meta3,
@@ -19706,10 +20246,10 @@ function createPiCredentialImports(options = {}) {
19706
20246
  }
19707
20247
 
19708
20248
  // dist/pi-fast-mode.js
19709
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
19710
- import { mkdir, readFile as readFile2, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
19711
- import { homedir as homedir4 } from "node:os";
19712
- import path10 from "node:path";
20249
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
20250
+ import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
20251
+ import { homedir as homedir5 } from "node:os";
20252
+ import path11 from "node:path";
19713
20253
  var PI_FAST_COMMAND = "codexhost-fast-mode";
19714
20254
  var PI_FAST_ACK = "codexhost-fast-mode:";
19715
20255
  var PI_FAST_EXTENSION = `export default function(pi) {
@@ -19759,24 +20299,24 @@ var PI_FAST_EXTENSION = `export default function(pi) {
19759
20299
  }
19760
20300
  `;
19761
20301
  async function ensurePiFastExtension(environment) {
19762
- const digest = createHash2("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
19763
- const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path10.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".codexhost");
19764
- const directory = path10.resolve(dataDirectory, "extensions", "pi-codex-fast");
19765
- const file2 = path10.join(directory, `${digest}.mjs`);
19766
- if (await readFile2(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
20302
+ const digest = createHash5("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
20303
+ const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path11.join(environment.HOME ?? environment.USERPROFILE ?? homedir5(), ".codexhost");
20304
+ const directory = path11.resolve(dataDirectory, "extensions", "pi-codex-fast");
20305
+ const file2 = path11.join(directory, `${digest}.mjs`);
20306
+ if (await readFile3(file2, "utf8").catch(() => "") === PI_FAST_EXTENSION)
19767
20307
  return file2;
19768
- await mkdir(directory, { recursive: true });
19769
- const temporary = `${file2}.${randomUUID2()}.tmp`;
20308
+ await mkdir2(directory, { recursive: true });
20309
+ const temporary = `${file2}.${randomUUID3()}.tmp`;
19770
20310
  try {
19771
- await writeFile2(temporary, PI_FAST_EXTENSION, { mode: 384 });
20311
+ await writeFile3(temporary, PI_FAST_EXTENSION, { mode: 384 });
19772
20312
  try {
19773
- await rename(temporary, file2);
20313
+ await rename2(temporary, file2);
19774
20314
  } catch (error51) {
19775
- if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
20315
+ if (await readFile3(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
19776
20316
  throw error51;
19777
20317
  }
19778
20318
  } finally {
19779
- await rm2(temporary, { force: true });
20319
+ await rm3(temporary, { force: true });
19780
20320
  }
19781
20321
  return file2;
19782
20322
  }
@@ -19793,15 +20333,15 @@ function withPiFast(catalog, supported) {
19793
20333
  // dist/pi-empty-session.js
19794
20334
  import { createReadStream as createReadStream3 } from "node:fs";
19795
20335
  import { createInterface as createInterface3 } from "node:readline";
19796
- import { randomUUID as randomUUID3 } from "node:crypto";
19797
- import { link, open as open2, rm as rm3 } from "node:fs/promises";
19798
- import path11 from "node:path";
20336
+ import { randomUUID as randomUUID4 } from "node:crypto";
20337
+ import { link, open as open2, rm as rm4 } from "node:fs/promises";
20338
+ import path12 from "node:path";
19799
20339
 
19800
20340
  // dist/pi-session-file.js
19801
20341
  import { open, realpath as realpath3 } from "node:fs/promises";
19802
20342
  var MAX_SESSION_HEADER_BYTES = 64 * 1024;
19803
20343
  var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
19804
- function isRecord7(value) {
20344
+ function isRecord8(value) {
19805
20345
  return typeof value === "object" && value !== null && !Array.isArray(value);
19806
20346
  }
19807
20347
  async function readPiSessionHeader(sessionFile) {
@@ -19821,7 +20361,7 @@ async function readPiSessionHeader(sessionFile) {
19821
20361
  } catch {
19822
20362
  throw new Error("Pi Session header is not valid JSON");
19823
20363
  }
19824
- if (!isRecord7(parsed) || parsed.type !== "session" || typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
20364
+ if (!isRecord8(parsed) || parsed.type !== "session" || typeof parsed.id !== "string" || parsed.id.length === 0 || typeof parsed.cwd !== "string" || parsed.cwd.length === 0) {
19825
20365
  throw new Error("Pi Session header is invalid");
19826
20366
  }
19827
20367
  return {
@@ -19854,7 +20394,7 @@ async function verifyPiSessionCwd(input) {
19854
20394
  async function persistEmptyPiSession(input) {
19855
20395
  const { state: state2, history, sourceSessionFile, sourceSessionId, cwd } = input;
19856
20396
  const destination = state2.sessionFile;
19857
- if (!destination || !path11.isAbsolute(destination) || path11.resolve(destination) === path11.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
20397
+ if (!destination || !path12.isAbsolute(destination) || path12.resolve(destination) === path12.resolve(sourceSessionFile) || state2.sessionId === sourceSessionId || mapPiSnapshot(history, { sessionId: state2.sessionId, model: null }).turns.length !== 0)
19858
20398
  throw new Error("Pi empty Session is not an independent empty native fork");
19859
20399
  await verifyPiSessionCwd({
19860
20400
  sessionFile: sourceSessionFile,
@@ -19878,7 +20418,7 @@ async function persistEmptyPiSession(input) {
19878
20418
  cwd,
19879
20419
  parentSession: sourceSessionFile
19880
20420
  };
19881
- const temporary = path11.join(path11.dirname(destination), `.codexhost-${randomUUID3()}.tmp`);
20421
+ const temporary = path12.join(path12.dirname(destination), `.codexhost-${randomUUID4()}.tmp`);
19882
20422
  try {
19883
20423
  const file2 = await open2(temporary, "wx", 384);
19884
20424
  try {
@@ -19889,7 +20429,7 @@ async function persistEmptyPiSession(input) {
19889
20429
  }
19890
20430
  await link(temporary, destination);
19891
20431
  if (process.platform !== "win32") {
19892
- const directory = await open2(path11.dirname(destination), "r");
20432
+ const directory = await open2(path12.dirname(destination), "r");
19893
20433
  try {
19894
20434
  await directory.sync();
19895
20435
  } finally {
@@ -19897,7 +20437,7 @@ async function persistEmptyPiSession(input) {
19897
20437
  }
19898
20438
  }
19899
20439
  } finally {
19900
- await rm3(temporary, { force: true });
20440
+ await rm4(temporary, { force: true });
19901
20441
  }
19902
20442
  }
19903
20443
  async function readPiEmptySessionConfiguration(sessionFile) {
@@ -19953,20 +20493,20 @@ async function readPiEmptySessionConfiguration(sessionFile) {
19953
20493
  }
19954
20494
 
19955
20495
  // dist/pi-adapter.js
19956
- import { randomUUID as randomUUID6 } from "node:crypto";
19957
- import path15 from "node:path";
20496
+ import { randomUUID as randomUUID7 } from "node:crypto";
20497
+ import path16 from "node:path";
19958
20498
 
19959
20499
  // dist/pi-workflow-child-history.js
19960
- import { createHash as createHash3 } from "node:crypto";
20500
+ import { createHash as createHash6 } from "node:crypto";
19961
20501
  import { constants } from "node:fs";
19962
20502
  import { open as open3 } from "node:fs/promises";
19963
- import path12 from "node:path";
19964
- function record5(value) {
20503
+ import path13 from "node:path";
20504
+ function record7(value) {
19965
20505
  return typeof value === "object" && value !== null && !Array.isArray(value);
19966
20506
  }
19967
20507
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
19968
- async function childHistory(file2, parentSessionId, identity) {
19969
- if (!path12.isAbsolute(file2))
20508
+ async function childHistory(file2, parentSessionId, identity, validateParent = false) {
20509
+ if (!path13.isAbsolute(file2))
19970
20510
  throw new Error("Pi child Session path is not absolute");
19971
20511
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
19972
20512
  try {
@@ -19979,12 +20519,14 @@ async function childHistory(file2, parentSessionId, identity) {
19979
20519
  throw new Error("Pi child Session exceeds read bounds");
19980
20520
  const values = buffer.subarray(0, bytesRead).toString("utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
19981
20521
  const header = values[0];
19982
- if (!record5(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
20522
+ if (!record7(header) || header.type !== "session" || typeof header.id !== "string" || header.version !== 3)
19983
20523
  throw new Error("Unsupported Pi child Session header");
20524
+ if (validateParent && header.parentSession !== parentSessionId)
20525
+ throw new Error("Pi child Session parent identity mismatch");
19984
20526
  const entries = [];
19985
20527
  for (const entry of values.slice(1)) {
19986
20528
  const parsed = jsonValueSchema.safeParse(entry);
19987
- if (!parsed.success || !record5(parsed.data) || typeof parsed.data.id !== "string")
20529
+ if (!parsed.success || !record7(parsed.data) || typeof parsed.data.id !== "string")
19988
20530
  throw new Error("Malformed Pi child Session entry");
19989
20531
  entries.push(parsed.data);
19990
20532
  }
@@ -19994,7 +20536,7 @@ async function childHistory(file2, parentSessionId, identity) {
19994
20536
  model: null,
19995
20537
  ...typeof header.cwd === "string" ? { cwd: header.cwd } : {}
19996
20538
  });
19997
- const prefix = createHash3("sha256").update(identity).digest("hex");
20539
+ const prefix = createHash6("sha256").update(identity).digest("hex");
19998
20540
  return {
19999
20541
  turns: snapshot.turns.map((turn) => {
20000
20542
  const readonlyTurn = {
@@ -20015,7 +20557,7 @@ async function childHistory(file2, parentSessionId, identity) {
20015
20557
  async function readPiWorkflowChild(history, parentSessionId, address) {
20016
20558
  for (const entry of activePiEntries(history).reverse()) {
20017
20559
  const message3 = entry.message;
20018
- if (!record5(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
20560
+ if (!record7(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
20019
20561
  continue;
20020
20562
  const summary = piWorkflowSummary(message3);
20021
20563
  if (!summary || summary.workflowRunId !== address.workflowRunId || summary.parentToolCallId !== message3.toolCallId)
@@ -20024,10 +20566,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
20024
20566
  if (!child)
20025
20567
  break;
20026
20568
  const details = message3.details;
20027
- if (!record5(details) || !Array.isArray(details.results))
20569
+ if (!record7(details) || !Array.isArray(details.results))
20028
20570
  break;
20029
- const result = details.results.findLast((candidate) => record5(candidate) && candidate.workflowKey === address.childId);
20030
- if (!record5(result))
20571
+ const result = details.results.findLast((candidate) => record7(candidate) && candidate.workflowKey === address.childId);
20572
+ if (!record7(result))
20031
20573
  break;
20032
20574
  const id = piWorkflowSubagentId(address);
20033
20575
  if (typeof result.sessionFile === "string") {
@@ -20070,25 +20612,69 @@ ${output}`,
20070
20612
  };
20071
20613
  }
20072
20614
 
20615
+ // dist/pi-gotgenes-history.js
20616
+ function gotgenesHistory(history) {
20617
+ const records = /* @__PURE__ */ new Map();
20618
+ for (const entry of activePiEntries(history)) {
20619
+ const message3 = entry.message;
20620
+ 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;
20621
+ if (!parsed)
20622
+ continue;
20623
+ records.set(parsed.id, mergeGotgenesRecord(records.get(parsed.id), parsed));
20624
+ }
20625
+ return [...records.values()];
20626
+ }
20627
+ function restoreGotgenes(history, observer) {
20628
+ observer.observe(gotgenesHistory(history), false);
20629
+ }
20630
+ async function readGotgenesChild(history, parentSessionId, id, live) {
20631
+ const saved = gotgenesHistory(history).find((entry) => entry.id === id);
20632
+ const record9 = live?.outputFile ? live : saved;
20633
+ if (!record9?.outputFile)
20634
+ return {
20635
+ ok: false,
20636
+ error: {
20637
+ code: "sessionNotFound",
20638
+ message: "Pi subagent has not published its Session transcript path",
20639
+ retryable: true
20640
+ }
20641
+ };
20642
+ try {
20643
+ return {
20644
+ ok: true,
20645
+ value: await childHistory(record9.outputFile, parentSessionId, gotgenesId(id), true)
20646
+ };
20647
+ } catch (error51) {
20648
+ return {
20649
+ ok: false,
20650
+ error: {
20651
+ code: "unavailable",
20652
+ message: error51 instanceof Error ? error51.message : "Pi child transcript unavailable",
20653
+ retryable: true
20654
+ }
20655
+ };
20656
+ }
20657
+ }
20658
+
20073
20659
  // dist/pi-subagent-history.js
20074
20660
  import { constants as constants2 } from "node:fs";
20075
20661
  import { open as open4 } from "node:fs/promises";
20076
- import path13 from "node:path";
20077
- function record6(value) {
20662
+ import path14 from "node:path";
20663
+ function record8(value) {
20078
20664
  return typeof value === "object" && value !== null && !Array.isArray(value);
20079
20665
  }
20080
20666
  function state(value) {
20081
20667
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
20082
20668
  }
20083
20669
  function piSubagentArtifact(value, runId, parentSessionId) {
20084
- if (!record6(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
20670
+ if (!record8(value) || value.lifecycleArtifactVersion !== 3 || value.runId !== runId || value.sessionId !== parentSessionId || !["single", "parallel", "chain", "workflow"].includes(String(value.mode)))
20085
20671
  return null;
20086
20672
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
20087
20673
  return null;
20088
20674
  const steps = Array.isArray(value.steps) ? value.steps : [];
20089
20675
  const children = [];
20090
20676
  for (const [index, step] of steps.entries()) {
20091
- if (!record6(step) || typeof step.agent !== "string")
20677
+ if (!record8(step) || typeof step.agent !== "string")
20092
20678
  return null;
20093
20679
  children.push({
20094
20680
  id: step.workflowKey ?? step.runId ?? `step:${index}`,
@@ -20119,19 +20705,20 @@ function piSubagentArtifact(value, runId, parentSessionId) {
20119
20705
  });
20120
20706
  }
20121
20707
  async function restorePiSubagents(history, parentSessionId, observer) {
20708
+ restoreGotgenes(history, observer.gotgenes);
20122
20709
  const receipts = /* @__PURE__ */ new Map();
20123
20710
  for (const entry of activePiEntries(history)) {
20124
- if (!record6(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record6(entry.message.details))
20711
+ if (!record8(entry.message) || entry.message.role !== "toolResult" || entry.message.toolName !== "subagent" || entry.message.isError !== false || !record8(entry.message.details))
20125
20712
  continue;
20126
20713
  const details = entry.message.details;
20127
- 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)
20714
+ 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)
20128
20715
  continue;
20129
20716
  receipts.set(details.asyncId, details.asyncDir);
20130
20717
  }
20131
20718
  for (const [id, directory] of [...receipts].slice(-128)) {
20132
20719
  let file2;
20133
20720
  try {
20134
- file2 = await open4(path13.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
20721
+ file2 = await open4(path14.join(directory, "status.json"), constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
20135
20722
  const stat2 = await file2.stat();
20136
20723
  if (!stat2.isFile() || stat2.size > 1024 * 1024)
20137
20724
  continue;
@@ -20213,8 +20800,8 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
20213
20800
 
20214
20801
  // dist/pi-rpc-session.js
20215
20802
  import { spawn, spawnSync } from "node:child_process";
20216
- import { randomUUID as randomUUID5 } from "node:crypto";
20217
- import path14 from "node:path";
20803
+ import { randomUUID as randomUUID6 } from "node:crypto";
20804
+ import path15 from "node:path";
20218
20805
 
20219
20806
  // dist/pi-slash-commands.js
20220
20807
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -20236,15 +20823,15 @@ function parsePiNativeCommands(response) {
20236
20823
  return data.commands.flatMap((entry) => {
20237
20824
  if (typeof entry !== "object" || entry === null)
20238
20825
  return [];
20239
- const record7 = entry;
20240
- const name = typeof record7.name === "string" ? record7.name.trim().replace(/^\//u, "") : "";
20826
+ const record9 = entry;
20827
+ const name = typeof record9.name === "string" ? record9.name.trim().replace(/^\//u, "") : "";
20241
20828
  if (!name)
20242
20829
  return [];
20243
20830
  return [
20244
20831
  {
20245
20832
  name,
20246
- ...typeof record7.description === "string" ? { description: record7.description } : {},
20247
- ...typeof record7.source === "string" ? { source: record7.source } : {}
20833
+ ...typeof record9.description === "string" ? { description: record9.description } : {},
20834
+ ...typeof record9.source === "string" ? { source: record9.source } : {}
20248
20835
  }
20249
20836
  ];
20250
20837
  });
@@ -20260,8 +20847,97 @@ function piDynamicCommandPrompt(catalog, commandId, argumentText) {
20260
20847
  return liveHarnessCommandPrompt(catalog, DYNAMIC_ID_PREFIX, commandId, argumentText);
20261
20848
  }
20262
20849
 
20850
+ // dist/pi-content-stream.js
20851
+ var PiContentStreamConflictError = class extends Error {
20852
+ };
20853
+ var PiContentStream = class {
20854
+ kind;
20855
+ #blocks = /* @__PURE__ */ new Map();
20856
+ #indexed;
20857
+ #legacyBlockIndex = 0;
20858
+ #lastEmittedIndex = -Infinity;
20859
+ constructor(kind) {
20860
+ this.kind = kind;
20861
+ }
20862
+ append(index, delta) {
20863
+ const block = this.#block(this.#key(index));
20864
+ if (block.ended && delta.length > 0)
20865
+ this.#conflict();
20866
+ block.received += delta;
20867
+ return this.#flush();
20868
+ }
20869
+ complete(index, content) {
20870
+ this.#finish(this.#key(index), content);
20871
+ if (this.#indexed === false)
20872
+ this.#legacyBlockIndex += 1;
20873
+ return this.#flush();
20874
+ }
20875
+ finalize(blocks) {
20876
+ if (this.#indexed !== true) {
20877
+ blocks = this.#legacyBlockIndex > 0 ? blocks.map(({ text: text3 }, index) => ({ index, text: text3 })) : [{ index: 0, text: blocks.map(({ text: text3 }) => text3).join("") }];
20878
+ }
20879
+ const indices = new Set(blocks.map(({ index }) => index));
20880
+ for (const [index, block] of this.#blocks) {
20881
+ if (indices.has(index))
20882
+ continue;
20883
+ if (block.emitted.length > 0)
20884
+ this.#conflict();
20885
+ this.#blocks.delete(index);
20886
+ }
20887
+ for (const { index, text: text3 } of blocks)
20888
+ this.#finish(index, text3);
20889
+ return this.#flush();
20890
+ }
20891
+ #key(index) {
20892
+ const indexed = typeof index === "number" && Number.isInteger(index) && index >= 0;
20893
+ this.#indexed ??= indexed;
20894
+ if (!this.#indexed)
20895
+ return this.#legacyBlockIndex;
20896
+ if (!indexed)
20897
+ this.#conflict();
20898
+ return index;
20899
+ }
20900
+ #block(index) {
20901
+ let block = this.#blocks.get(index);
20902
+ if (!block) {
20903
+ block = { received: "", emitted: "", ended: false };
20904
+ this.#blocks.set(index, block);
20905
+ }
20906
+ return block;
20907
+ }
20908
+ #finish(index, content) {
20909
+ const block = this.#block(index);
20910
+ if (!content.startsWith(block.emitted))
20911
+ this.#conflict();
20912
+ block.received = content;
20913
+ block.ended = true;
20914
+ }
20915
+ #flush() {
20916
+ let delta = "";
20917
+ for (const [index, block] of [...this.#blocks].sort(([left], [right]) => left - right)) {
20918
+ const visible = this.kind === "reasoning" && !block.ended ? block.received.replace(/[\r\n]+$/u, "") : block.received;
20919
+ if (!visible.startsWith(block.emitted))
20920
+ this.#conflict();
20921
+ const suffix = visible.slice(block.emitted.length);
20922
+ if (suffix.length > 0) {
20923
+ if (index < this.#lastEmittedIndex)
20924
+ this.#conflict();
20925
+ this.#lastEmittedIndex = index;
20926
+ block.emitted = visible;
20927
+ delta += suffix;
20928
+ }
20929
+ if (!block.ended)
20930
+ break;
20931
+ }
20932
+ return delta;
20933
+ }
20934
+ #conflict() {
20935
+ throw new PiContentStreamConflictError(`Pi ${this.kind} final content conflicts with already streamed content`);
20936
+ }
20937
+ };
20938
+
20263
20939
  // dist/pi-subagent-rpc.js
20264
- import { randomUUID as randomUUID4 } from "node:crypto";
20940
+ import { randomUUID as randomUUID5 } from "node:crypto";
20265
20941
  var PiSubagentRpc = class {
20266
20942
  send;
20267
20943
  timeoutMs;
@@ -20303,7 +20979,7 @@ var PiSubagentRpc = class {
20303
20979
  if (!Array.isArray(data?.commands) || !data.commands.some((command) => command?.name === "subagents-inspect-rpc" && command.source === "extension")) {
20304
20980
  throw new Error("Installed Pi has no pi-subagents Host inspection command");
20305
20981
  }
20306
- const requestId2 = randomUUID4();
20982
+ const requestId2 = randomUUID5();
20307
20983
  const reply = new Promise((resolve, reject) => {
20308
20984
  const timer = setTimeout(() => {
20309
20985
  this.#pending.delete(requestId2);
@@ -20337,6 +21013,12 @@ var PiSubagentRpc = class {
20337
21013
  };
20338
21014
 
20339
21015
  // dist/pi-rpc-session.js
21016
+ var PiRpcBusyError = class extends Error {
21017
+ constructor() {
21018
+ super("Pi is still running a native Turn; wait for completion or use the active Turn's stop/steer action");
21019
+ this.name = "PiRpcBusyError";
21020
+ }
21021
+ };
20340
21022
  var PiRpcFaultError = class extends Error {
20341
21023
  kind;
20342
21024
  diagnostic;
@@ -20364,8 +21046,11 @@ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
20364
21046
  "get_available_thinking_levels"
20365
21047
  ]);
20366
21048
  var MAX_EXPIRED_IDS = 64;
21049
+ function nativeMessageIdentity(active) {
21050
+ return active.assistantNativeMessageIdentity ? { nativeMessageIdentity: active.assistantNativeMessageIdentity } : {};
21051
+ }
20367
21052
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
20368
- function isRecord8(value) {
21053
+ function isRecord9(value) {
20369
21054
  return typeof value === "object" && value !== null && !Array.isArray(value);
20370
21055
  }
20371
21056
  function message2(value) {
@@ -20377,13 +21062,13 @@ function nonBlankString(value) {
20377
21062
  function parseNativeModel(value, context) {
20378
21063
  if (value === null || value === void 0)
20379
21064
  return null;
20380
- if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
21065
+ if (!isRecord9(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
20381
21066
  throw new PiRpcFaultError("protocolError", `Pi RPC returned an invalid ${context} Model`);
20382
21067
  }
20383
21068
  return { provider: value.provider, id: value.id };
20384
21069
  }
20385
21070
  function sessionStateData(response) {
20386
- const data = isRecord8(response.data) ? response.data : null;
21071
+ const data = isRecord9(response.data) ? response.data : null;
20387
21072
  if (!data)
20388
21073
  throw new PiRpcFaultError("protocolError", "Pi RPC state response has no data");
20389
21074
  return data;
@@ -20391,7 +21076,7 @@ function sessionStateData(response) {
20391
21076
  function parseSessionState(response) {
20392
21077
  const data = sessionStateData(response);
20393
21078
  const model2 = parseNativeModel(data.model, "state");
20394
- const modelReasoning = isRecord8(data.model) && typeof data.model.reasoning === "boolean" ? data.model.reasoning : null;
21079
+ const modelReasoning = isRecord9(data.model) && typeof data.model.reasoning === "boolean" ? data.model.reasoning : null;
20395
21080
  if (!nonBlankString(data.sessionId)) {
20396
21081
  throw new PiRpcFaultError("protocolError", "Pi RPC state has no stable Session identity");
20397
21082
  }
@@ -20417,13 +21102,13 @@ function parseSessionStreaming(response) {
20417
21102
  return isStreaming;
20418
21103
  }
20419
21104
  function parseSessionHistory(response) {
20420
- const data = isRecord8(response.data) ? response.data : null;
21105
+ const data = isRecord9(response.data) ? response.data : null;
20421
21106
  if (!data || !Array.isArray(data.entries)) {
20422
21107
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response has no Entries");
20423
21108
  }
20424
21109
  const entries = data.entries.map((entry) => {
20425
21110
  const parsed = jsonValueSchema.safeParse(entry);
20426
- if (!parsed.success || !isRecord8(parsed.data)) {
21111
+ if (!parsed.success || !isRecord9(parsed.data)) {
20427
21112
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response contains an invalid Entry");
20428
21113
  }
20429
21114
  return parsed.data;
@@ -20434,7 +21119,7 @@ function parseSessionHistory(response) {
20434
21119
  return { entries, leafId: data.leafId };
20435
21120
  }
20436
21121
  function parseAvailableThinkingLevels(response) {
20437
- const data = isRecord8(response.data) ? response.data : null;
21122
+ const data = isRecord9(response.data) ? response.data : null;
20438
21123
  if (!data || !Array.isArray(data.levels) || data.levels.length === 0) {
20439
21124
  throw new PiRpcFaultError("protocolError", "Pi RPC Thinking catalog response has no levels");
20440
21125
  }
@@ -20451,13 +21136,13 @@ function parseAvailableThinkingLevels(response) {
20451
21136
  return levels;
20452
21137
  }
20453
21138
  function parseAvailableModels(response) {
20454
- const data = isRecord8(response.data) ? response.data : null;
21139
+ const data = isRecord9(response.data) ? response.data : null;
20455
21140
  if (!data || !Array.isArray(data.models)) {
20456
21141
  throw new PiRpcFaultError("protocolError", "Pi RPC Model catalog response has no models");
20457
21142
  }
20458
21143
  return data.models.map((model2) => {
20459
21144
  const parsed = parseNativeModel(model2, "catalog");
20460
- if (!parsed || !isRecord8(model2) || typeof model2.reasoning !== "boolean") {
21145
+ if (!parsed || !isRecord9(model2) || typeof model2.reasoning !== "boolean") {
20461
21146
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
20462
21147
  }
20463
21148
  return {
@@ -20468,32 +21153,32 @@ function parseAvailableModels(response) {
20468
21153
  });
20469
21154
  }
20470
21155
  function assistantText(value) {
20471
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21156
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20472
21157
  return null;
20473
- return value.content.filter((content) => isRecord8(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
21158
+ return value.content.filter((content) => isRecord9(content) && content.type === "text" && typeof content.text === "string").map((content) => content.text).join("");
20474
21159
  }
20475
21160
  function assistantMessageId(value) {
20476
- if (!isRecord8(value) || value.role !== "assistant")
21161
+ if (!isRecord9(value) || value.role !== "assistant")
20477
21162
  return null;
20478
21163
  return nonBlankString(value.responseId) ? value.responseId : null;
20479
21164
  }
20480
21165
  function extractReasoningText(content) {
20481
- if (!isRecord8(content))
21166
+ if (!isRecord9(content))
20482
21167
  return null;
20483
21168
  const type = String(content.type ?? "");
20484
21169
  if (type === "thinking" || type === "reasoning" || type === "thought") {
20485
- const text2 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
20486
- return typeof text2 === "string" ? text2 : null;
21170
+ const text3 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
21171
+ return typeof text3 === "string" ? text3 : null;
20487
21172
  }
20488
21173
  return null;
20489
21174
  }
20490
21175
  function assistantReasoning(value) {
20491
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21176
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20492
21177
  return null;
20493
- return value.content.map(extractReasoningText).filter((text2) => typeof text2 === "string").join("");
21178
+ return value.content.map(extractReasoningText).filter((text3) => typeof text3 === "string").join("");
20494
21179
  }
20495
21180
  function assistantFailure(value) {
20496
- if (!isRecord8(value) || value.role !== "assistant")
21181
+ if (!isRecord9(value) || value.role !== "assistant")
20497
21182
  return void 0;
20498
21183
  if (value.stopReason !== "error" && value.stopReason !== "aborted")
20499
21184
  return null;
@@ -20513,7 +21198,7 @@ function signalProcessTree(child, signal) {
20513
21198
  try {
20514
21199
  process.kill(-child.pid, signal);
20515
21200
  } catch (error51) {
20516
- if (!isRecord8(error51) || error51.code !== "ESRCH")
21201
+ if (!isRecord9(error51) || error51.code !== "ESRCH")
20517
21202
  throw error51;
20518
21203
  }
20519
21204
  }
@@ -20550,13 +21235,14 @@ function piRpcProcessCommand(options, dependencies = {}) {
20550
21235
  const thinkingArguments = options.emptySessionConfiguration ? ["--thinking", options.emptySessionConfiguration.thinkingLevel] : [];
20551
21236
  const arguments_ = [
20552
21237
  ...options.fastExtension ? ["--extension", options.fastExtension] : [],
21238
+ ...options.subagentExtension ? ["--extension", options.subagentExtension] : [],
20553
21239
  "--mode",
20554
21240
  "rpc",
20555
21241
  ...modelArguments,
20556
21242
  ...thinkingArguments,
20557
21243
  ...sessionArguments
20558
21244
  ];
20559
- const extension = path14.win32.extname(command).toLowerCase();
21245
+ const extension = path15.win32.extname(command).toLowerCase();
20560
21246
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
20561
21247
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
20562
21248
  }
@@ -20585,7 +21271,13 @@ var PiRpcSession = class {
20585
21271
  #options;
20586
21272
  #processAdapter;
20587
21273
  #activeTurn = null;
21274
+ #runGeneration = 0;
21275
+ #deferredRunFrames = [];
21276
+ #deferredRunBytes = 0;
21277
+ #runWaiters = /* @__PURE__ */ new Set();
21278
+ #messageTimestampCounts = /* @__PURE__ */ new Map();
20588
21279
  #autonomousTurnHandler = null;
21280
+ #autonomousLifecycleHandler = null;
20589
21281
  #usageHandler = null;
20590
21282
  #usageRequestStartedAtMs = null;
20591
21283
  // Pieces of the unterminated frame; joined once at its newline so a large frame (a long
@@ -20605,8 +21297,15 @@ var PiRpcSession = class {
20605
21297
  #fastAcknowledgement = null;
20606
21298
  #latestCacheHitRatePercent;
20607
21299
  #manualCompaction = null;
21300
+ #noticeOccurrences = /* @__PURE__ */ new Map();
21301
+ #seenNoticeFrames = /* @__PURE__ */ new Set();
21302
+ #pendingProgress = [];
21303
+ #omittedProgress = 0;
21304
+ #extensionStatuses = /* @__PURE__ */ new Map();
20608
21305
  #stderrTail = "";
20609
21306
  #subagents;
21307
+ #gotgenesHandler;
21308
+ #gotgenesLatest;
20610
21309
  constructor(options, processAdapter = nodeProcessAdapter) {
20611
21310
  if (options.sessionFile && options.forkSessionFile) {
20612
21311
  throw new Error("Pi RPC cannot combine Session resume and Fork startup");
@@ -20636,9 +21335,17 @@ var PiRpcSession = class {
20636
21335
  get stderrTail() {
20637
21336
  return this.#stderrTail;
20638
21337
  }
21338
+ get isBusy() {
21339
+ return this.#activeTurn !== null || this.#manualCompaction !== null || this.#compactionActive || this.#deferredRunFrames.length > 0;
21340
+ }
20639
21341
  setSubagentStatusHandler(handler) {
20640
21342
  this.#subagents.setHandler(handler);
20641
21343
  }
21344
+ setGotgenesStatusHandler(handler) {
21345
+ this.#gotgenesHandler = handler;
21346
+ if (this.#gotgenesLatest)
21347
+ handler(this.#gotgenesLatest, "idle");
21348
+ }
20642
21349
  inspectSubagent(id) {
20643
21350
  return this.#subagents.inspect(id);
20644
21351
  }
@@ -20648,17 +21355,18 @@ var PiRpcSession = class {
20648
21355
  /** Every finished assistant message is one model request, with or without an active Turn. */
20649
21356
  #observeUsage(value) {
20650
21357
  if (value.type === "message_start") {
20651
- this.#usageRequestStartedAtMs = null;
21358
+ if (isRecord9(value.message) && value.message.role === "assistant")
21359
+ this.#usageRequestStartedAtMs = null;
20652
21360
  return;
20653
21361
  }
20654
21362
  if (value.type === "message_update") {
20655
21363
  const event = value.assistantMessageEvent;
20656
- if (this.#usageRequestStartedAtMs === null && isRecord8(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
21364
+ if (this.#usageRequestStartedAtMs === null && isRecord9(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
20657
21365
  this.#usageRequestStartedAtMs = Date.now();
20658
21366
  }
20659
21367
  return;
20660
21368
  }
20661
- if (value.type === "message_end" && isRecord8(value.message)) {
21369
+ if (value.type === "message_end" && isRecord9(value.message)) {
20662
21370
  if (value.message.role !== "assistant")
20663
21371
  return;
20664
21372
  const startedAtMs = this.#usageRequestStartedAtMs;
@@ -20672,14 +21380,21 @@ var PiRpcSession = class {
20672
21380
  }
20673
21381
  setAutonomousTurnHandler(handler) {
20674
21382
  this.#autonomousTurnHandler = handler;
21383
+ this.#autonomousLifecycleHandler = null;
21384
+ }
21385
+ setAutonomousTurnLifecycleHandler(handler) {
21386
+ this.#autonomousLifecycleHandler = handler;
21387
+ this.#autonomousTurnHandler = null;
20675
21388
  }
20676
21389
  async start() {
20677
21390
  if (this.#child || this.#closed)
20678
21391
  throw new Error("Pi RPC Session cannot be started twice");
20679
21392
  const fastExtension = this.#processAdapter === nodeProcessAdapter ? await ensurePiFastExtension({ ...process.env, ...this.#options.environment }) : void 0;
21393
+ const subagentExtension = this.#processAdapter === nodeProcessAdapter ? await ensureGotgenesExtension({ ...process.env, ...this.#options.environment }) : void 0;
20680
21394
  const child = this.#processAdapter.spawn({
20681
21395
  cwd: this.#options.cwd,
20682
21396
  ...fastExtension ? { fastExtension } : {},
21397
+ ...subagentExtension ? { subagentExtension } : {},
20683
21398
  ...this.#options.command ? { command: this.#options.command } : {},
20684
21399
  environment: withNodeRuntimeOnPath({
20685
21400
  ...process.env,
@@ -20703,7 +21418,7 @@ var PiRpcSession = class {
20703
21418
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
20704
21419
  });
20705
21420
  child.once("error", (error51) => {
20706
- const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
21421
+ const kind = isRecord9(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
20707
21422
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
20708
21423
  });
20709
21424
  child.once("exit", (code, signal) => {
@@ -20720,6 +21435,7 @@ var PiRpcSession = class {
20720
21435
  ]);
20721
21436
  try {
20722
21437
  this.#state = parseSessionState(await this.#send("get_state", {}));
21438
+ await this.getEntries();
20723
21439
  } catch (error51) {
20724
21440
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("unavailable", `Pi RPC state unavailable: ${message2(error51)}`);
20725
21441
  this.#fail(fault);
@@ -20733,7 +21449,12 @@ var PiRpcSession = class {
20733
21449
  }
20734
21450
  async getEntries() {
20735
21451
  try {
20736
- return parseSessionHistory(await this.#send("get_entries", {}));
21452
+ const history = parseSessionHistory(await this.#send("get_entries", {}));
21453
+ if (!this.#activeTurn && this.#state) {
21454
+ this.#messageTimestampCounts = piHistoryMessageIdentities(this.state.sessionId, activePiEntries(history)).timestampCounts;
21455
+ this.#noticeOccurrences = piHistoryNotices(this.state.sessionId, activePiEntries(history)).occurrences;
21456
+ }
21457
+ return history;
20737
21458
  } catch (error51) {
20738
21459
  if (error51 instanceof PiRpcFaultError)
20739
21460
  this.#fail(error51);
@@ -20793,11 +21514,15 @@ var PiRpcSession = class {
20793
21514
  if (entryId.length === 0)
20794
21515
  throw new Error("Pi Fork Entry ID must not be empty");
20795
21516
  await this.#send("fork", { entryId });
20796
- return this.#refreshState("Fork");
21517
+ const state2 = await this.#refreshState("Fork");
21518
+ await this.getEntries();
21519
+ return state2;
20797
21520
  }
20798
21521
  async clone() {
20799
21522
  await this.#send("clone", {});
20800
- return this.#refreshState("Clone");
21523
+ const state2 = await this.#refreshState("Clone");
21524
+ await this.getEntries();
21525
+ return state2;
20801
21526
  }
20802
21527
  verifySessionCwd(expectedCwd) {
20803
21528
  return verifyPiSessionCwd({
@@ -20834,7 +21559,7 @@ var PiRpcSession = class {
20834
21559
  return this.state;
20835
21560
  if (!await this.supportsFastMode())
20836
21561
  throw new Error("Installed Pi does not support the Host Fast extension");
20837
- const nonce = randomUUID5();
21562
+ const nonce = randomUUID6();
20838
21563
  const mode = enabled ? "on" : "off";
20839
21564
  const acknowledgement = { message: `${PI_FAST_ACK}${nonce}:${mode}`, received: false };
20840
21565
  this.#fastAcknowledgement = acknowledgement;
@@ -20874,22 +21599,27 @@ var PiRpcSession = class {
20874
21599
  throw fault;
20875
21600
  }
20876
21601
  }
20877
- async runTurn(text2, onEvent) {
21602
+ async runTurn(text3, onEvent) {
20878
21603
  if (!this.#child || !this.#state || this.#closed || this.#failed) {
20879
21604
  throw new Error("Pi RPC Session is unavailable");
20880
21605
  }
20881
- if (this.#activeTurn)
20882
- throw new Error("Pi RPC Session already has an active Turn");
20883
- if (text2.length === 0)
21606
+ if (this.isBusy)
21607
+ throw new PiRpcBusyError();
21608
+ if (text3.length === 0)
20884
21609
  throw new Error("Pi text Turn must not be empty");
20885
21610
  const settled = new Promise((resolve, reject) => {
20886
21611
  this.#activeTurn = {
20887
21612
  origin: "requested",
21613
+ autonomousRunId: null,
21614
+ runGeneration: this.#runGeneration,
20888
21615
  autonomousEvents: null,
20889
21616
  nativeTurnKey: null,
20890
21617
  nativeCancellationObserved: false,
20891
21618
  text: "",
20892
21619
  assistantMessageId: null,
21620
+ assistantNativeMessageIdentity: void 0,
21621
+ textStream: new PiContentStream("text"),
21622
+ reasoningStream: new PiContentStream("reasoning"),
20893
21623
  sawStreamedMessageText: false,
20894
21624
  sawStreamedMessageReasoning: false,
20895
21625
  lastFinalizedMessageText: null,
@@ -20909,7 +21639,8 @@ var PiRpcSession = class {
20909
21639
  };
20910
21640
  });
20911
21641
  try {
20912
- await this.#send("prompt", { message: text2 });
21642
+ this.#drainProgress(onEvent);
21643
+ await this.#send("prompt", { message: text3 });
20913
21644
  } catch (error51) {
20914
21645
  this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
20915
21646
  }
@@ -20981,6 +21712,10 @@ var PiRpcSession = class {
20981
21712
  void this.close().catch(() => void 0);
20982
21713
  }
20983
21714
  close() {
21715
+ this.#pendingProgress = [];
21716
+ this.#omittedProgress = 0;
21717
+ this.#seenNoticeFrames.clear();
21718
+ this.#extensionStatuses.clear();
20984
21719
  if (!this.#closed) {
20985
21720
  this.#closed = true;
20986
21721
  this.#rejectAll(new Error("Pi RPC Session closed"));
@@ -21014,19 +21749,25 @@ var PiRpcSession = class {
21014
21749
  rest = rest.subarray(newline + 1);
21015
21750
  try {
21016
21751
  const value = JSON.parse(textDecoder.decode(frame));
21017
- if (!isRecord8(value) || typeof value.type !== "string") {
21752
+ if (!isRecord9(value) || typeof value.type !== "string") {
21018
21753
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid envelope");
21019
21754
  }
21020
21755
  this.#handle(value);
21021
21756
  } catch (error51) {
21022
- this.#fail(error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", `Pi RPC returned invalid JSONL: ${message2(error51)}`));
21757
+ this.#fail(error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("protocolError", error51 instanceof PiContentStreamConflictError ? error51.message : `Pi RPC returned invalid JSONL: ${message2(error51)}`));
21023
21758
  }
21024
21759
  newline = rest.indexOf(10);
21025
21760
  }
21026
21761
  if (rest.length !== 0)
21027
21762
  this.#buffer.push(rest);
21028
21763
  }
21029
- #handle(value) {
21764
+ #handle(value, observedGeneration) {
21765
+ if (observedGeneration === void 0 && value.type === "agent_start") {
21766
+ this.#runGeneration += 1;
21767
+ for (const waiter of this.#runWaiters)
21768
+ waiter.check();
21769
+ }
21770
+ const generation = observedGeneration ?? this.#runGeneration;
21030
21771
  if (value.type === "extension_ui_request" && value.method === "notify" && typeof value.message === "string" && value.message.startsWith(PI_FAST_ACK)) {
21031
21772
  if (this.#fastAcknowledgement?.message === value.message)
21032
21773
  this.#fastAcknowledgement.received = true;
@@ -21040,6 +21781,33 @@ var PiRpcSession = class {
21040
21781
  }
21041
21782
  if (this.#subagents.handle(value))
21042
21783
  return;
21784
+ const settling = this.#activeTurn;
21785
+ if (settling && settling.settlement !== "pending" && generation > settling.runGeneration) {
21786
+ this.#deferredRunBytes += Buffer.byteLength(JSON.stringify(value));
21787
+ if (this.#deferredRunBytes > 8 * 1024 * 1024) {
21788
+ this.#fail(new PiRpcFaultError("protocolError", "Pi deferred run exceeded its event buffer bound"));
21789
+ return;
21790
+ }
21791
+ this.#deferredRunFrames.push({ value, generation });
21792
+ return;
21793
+ }
21794
+ if (value.type === "agent_start") {
21795
+ if (this.#activeTurn)
21796
+ this.#activeTurn.runGeneration = generation;
21797
+ else if (!this.#manualCompaction && !this.#compactionActive && (this.#autonomousTurnHandler || this.#autonomousLifecycleHandler))
21798
+ this.#startAutonomousTurn(void 0, generation);
21799
+ return;
21800
+ }
21801
+ if (value.type === "extension_ui_request" && value.method === "setWidget" && value.widgetKey === GOTGENES_WIDGET) {
21802
+ const records = parseGotgenesWidget(value);
21803
+ if (records) {
21804
+ this.#gotgenesLatest = records;
21805
+ this.#gotgenesHandler?.(records, this.#activeTurn?.origin ?? "idle");
21806
+ }
21807
+ return;
21808
+ }
21809
+ if (this.#handleProgress(value))
21810
+ return;
21043
21811
  this.#observeUsage(value);
21044
21812
  if (value.type === "compaction_start") {
21045
21813
  this.#compactionActive = true;
@@ -21063,7 +21831,7 @@ var PiRpcSession = class {
21063
21831
  this.#armCommandTimeout(id, pending);
21064
21832
  }
21065
21833
  }
21066
- const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
21834
+ const outcome = value.aborted === true ? "cancelled" : isRecord9(value.result) ? "succeeded" : "failed";
21067
21835
  const event = {
21068
21836
  type: "compaction.completed",
21069
21837
  outcome,
@@ -21080,8 +21848,8 @@ var PiRpcSession = class {
21080
21848
  return;
21081
21849
  }
21082
21850
  let active = this.#activeTurn;
21083
- if (!active && !this.#manualCompaction && !this.#compactionActive && this.#autonomousTurnHandler && value.type === "message_start" && assistantText(value.message) !== null) {
21084
- active = this.#startAutonomousTurn(value.message);
21851
+ if (!active && !this.#manualCompaction && !this.#compactionActive && (this.#autonomousTurnHandler || this.#autonomousLifecycleHandler) && value.type === "message_start" && assistantText(value.message) !== null) {
21852
+ active = this.#startAutonomousTurn(value.message, generation);
21085
21853
  }
21086
21854
  if (!active) {
21087
21855
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
@@ -21101,22 +21869,26 @@ var PiRpcSession = class {
21101
21869
  this.#startAssistantMessage(active, value.message);
21102
21870
  return;
21103
21871
  }
21104
- if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
21872
+ if (value.type === "message_update" && isRecord9(value.assistantMessageEvent)) {
21105
21873
  const event = value.assistantMessageEvent;
21106
21874
  const eventType = String(event.type ?? "");
21107
21875
  const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
21108
21876
  const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
21109
- 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;
21110
- if (isThinking && delta !== null && delta.length > 0) {
21111
- const messageId = this.#ensureAssistantMessage(active, value.message);
21112
- active.reasoningMessageOpen = true;
21113
- active.sawStreamedMessageReasoning = true;
21114
- active.onEvent({ type: "reasoning.delta", messageId, delta });
21115
- } else if (isText && delta !== null && delta.length > 0) {
21116
- const messageId = this.#ensureAssistantMessage(active, value.message);
21117
- active.text += delta;
21118
- active.sawStreamedMessageText = true;
21119
- active.onEvent({ type: "text.delta", messageId, delta });
21877
+ 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;
21878
+ const endingReasoning = eventType === "thinking_end" || eventType === "reasoning_end";
21879
+ const endingText = eventType === "text_end";
21880
+ if ((endingReasoning || endingText) && typeof event.content === "string") {
21881
+ this.#ensureAssistantMessage(active, value.message);
21882
+ const stream = endingReasoning ? active.reasoningStream : active.textStream;
21883
+ this.#emitContent(active, endingReasoning, stream.complete(event.contentIndex, event.content));
21884
+ } else if ((isThinking || isText) && delta !== null && delta.length > 0) {
21885
+ this.#ensureAssistantMessage(active, value.message);
21886
+ if (isThinking)
21887
+ active.sawStreamedMessageReasoning = true;
21888
+ else
21889
+ active.sawStreamedMessageText = true;
21890
+ const stream = isThinking ? active.reasoningStream : active.textStream;
21891
+ this.#emitContent(active, isThinking, stream.append(event.contentIndex, delta));
21120
21892
  } else if (event.type === "error") {
21121
21893
  this.#ensureAssistantMessage(active, value.message);
21122
21894
  active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Pi assistant message failed");
@@ -21147,25 +21919,36 @@ var PiRpcSession = class {
21147
21919
  if (active.settlement !== "pending")
21148
21920
  return;
21149
21921
  active.settlement = "confirming";
21150
- void this.#confirmSettledTurn(active);
21922
+ void this.#confirmSettledTurn(active, active.runGeneration);
21151
21923
  }
21152
21924
  }
21153
- #startAutonomousTurn(value) {
21925
+ #startAutonomousTurn(value, generation) {
21154
21926
  const events = [];
21927
+ const runId = randomUUID6();
21155
21928
  const active = {
21156
21929
  origin: "autonomous",
21930
+ autonomousRunId: runId,
21931
+ runGeneration: generation,
21157
21932
  autonomousEvents: events,
21158
- ...isRecord8(value) ? { autonomousMessage: value } : {},
21933
+ ...isRecord9(value) ? { autonomousMessage: value } : {},
21159
21934
  nativeTurnKey: null,
21160
21935
  nativeCancellationObserved: false,
21161
21936
  text: "",
21162
21937
  assistantMessageId: null,
21938
+ assistantNativeMessageIdentity: void 0,
21939
+ textStream: new PiContentStream("text"),
21940
+ reasoningStream: new PiContentStream("reasoning"),
21163
21941
  sawStreamedMessageText: false,
21164
21942
  sawStreamedMessageReasoning: false,
21165
21943
  lastFinalizedMessageText: null,
21166
21944
  lastFinalizedMessageReasoning: null,
21167
21945
  reasoningMessageOpen: false,
21168
- onEvent: (event) => events.push(event),
21946
+ onEvent: (event) => {
21947
+ if (this.#autonomousLifecycleHandler)
21948
+ this.#autonomousLifecycleHandler({ type: "event", runId, event });
21949
+ else
21950
+ events.push(event);
21951
+ },
21169
21952
  resolve: () => void 0,
21170
21953
  reject: () => void 0,
21171
21954
  failure: null,
@@ -21178,19 +21961,108 @@ var PiRpcSession = class {
21178
21961
  abortPromise: null
21179
21962
  };
21180
21963
  this.#activeTurn = active;
21964
+ this.#autonomousLifecycleHandler?.({ type: "started", runId });
21965
+ this.#drainProgress(active.onEvent);
21181
21966
  return active;
21182
21967
  }
21968
+ #handleProgress(value) {
21969
+ if ((value.type === "message_start" || value.type === "message_end") && isRecord9(value.message) && value.message.role === "custom") {
21970
+ if (value.type !== "message_end" || !this.#state)
21971
+ return true;
21972
+ const key = piCustomNoticeKey(value.message);
21973
+ if (!key)
21974
+ return true;
21975
+ const timestamp = value.message.timestamp;
21976
+ if ((typeof timestamp === "number" || typeof timestamp === "string") && !this.#acceptNoticeFrame(JSON.stringify([key, timestamp])))
21977
+ return true;
21978
+ const progress = piCustomNotice(value.message, this.state.sessionId, this.#noticeOccurrences);
21979
+ if (progress)
21980
+ this.#publishProgress(progress);
21981
+ return true;
21982
+ }
21983
+ if (value.type === "extension_ui_request" && value.method === "setStatus") {
21984
+ if (typeof value.statusKey !== "string")
21985
+ return true;
21986
+ if (typeof value.statusText !== "string" || !value.statusText.trim()) {
21987
+ if (!this.#extensionStatuses.has(value.statusKey))
21988
+ return true;
21989
+ this.#extensionStatuses.delete(value.statusKey);
21990
+ } else {
21991
+ if (this.#extensionStatuses.get(value.statusKey) === value.statusText)
21992
+ return true;
21993
+ this.#extensionStatuses.set(value.statusKey, value.statusText);
21994
+ }
21995
+ }
21996
+ const text3 = piStatusText(value);
21997
+ if (!text3)
21998
+ return false;
21999
+ if (value.type === "extension_ui_request" && typeof value.id === "string" && !this.#acceptNoticeFrame(JSON.stringify([value.type, value.id])))
22000
+ return true;
22001
+ this.#publishProgress({
22002
+ type: "progress.message",
22003
+ itemId: hostItemIdSchema.parse(`pi-progress-${randomUUID6()}`),
22004
+ text: text3
22005
+ }, value.method === "setStatus" && typeof value.statusKey === "string" ? value.statusKey : void 0);
22006
+ return true;
22007
+ }
22008
+ #acceptNoticeFrame(key) {
22009
+ if (this.#seenNoticeFrames.has(key))
22010
+ return false;
22011
+ this.#seenNoticeFrames.add(key);
22012
+ if (this.#seenNoticeFrames.size > 512)
22013
+ this.#seenNoticeFrames.delete(this.#seenNoticeFrames.values().next().value);
22014
+ return true;
22015
+ }
22016
+ #publishProgress(progress, statusKey) {
22017
+ if (this.#activeTurn?.settlement === "pending") {
22018
+ this.#activeTurn.onEvent(progress);
22019
+ return;
22020
+ }
22021
+ if (statusKey !== void 0) {
22022
+ const previous = this.#pendingProgress.findIndex((pending) => pending.statusKey === statusKey);
22023
+ if (previous >= 0)
22024
+ this.#pendingProgress.splice(previous, 1);
22025
+ }
22026
+ if (this.#pendingProgress.length >= 128) {
22027
+ this.#pendingProgress.shift();
22028
+ this.#omittedProgress += 1;
22029
+ }
22030
+ this.#pendingProgress.push({
22031
+ event: progress,
22032
+ ...statusKey !== void 0 ? { statusKey } : {}
22033
+ });
22034
+ }
22035
+ #drainProgress(onEvent) {
22036
+ if (this.#omittedProgress > 0) {
22037
+ onEvent({
22038
+ type: "progress.message",
22039
+ itemId: hostItemIdSchema.parse(`pi-progress-${randomUUID6()}`),
22040
+ text: `Pi notifications: ${this.#omittedProgress} earlier updates were not retained while idle. Persisted notifications remain available in conversation history.`
22041
+ });
22042
+ this.#omittedProgress = 0;
22043
+ }
22044
+ for (const pending of this.#pendingProgress.splice(0))
22045
+ onEvent(pending.event);
22046
+ }
21183
22047
  #emitAutonomousTurn(active, result) {
21184
22048
  const handler = this.#autonomousTurnHandler;
21185
- if (active.origin !== "autonomous" || !active.autonomousEvents || !handler) {
22049
+ if (active.origin !== "autonomous" || !active.autonomousEvents || !active.autonomousRunId) {
21186
22050
  return;
21187
22051
  }
21188
22052
  try {
21189
- handler({
22053
+ const turn = {
21190
22054
  nativeTurnKey: active.nativeTurnKey,
21191
22055
  events: [...active.autonomousEvents],
21192
22056
  result
21193
- });
22057
+ };
22058
+ if (this.#autonomousLifecycleHandler)
22059
+ this.#autonomousLifecycleHandler({
22060
+ type: "completed",
22061
+ runId: active.autonomousRunId,
22062
+ turn
22063
+ });
22064
+ else
22065
+ handler?.(turn);
21194
22066
  } catch (error51) {
21195
22067
  this.#fail(new PiRpcFaultError("protocolError", `Pi autonomous Turn handler failed: ${message2(error51)}`));
21196
22068
  }
@@ -21337,31 +22209,73 @@ var PiRpcSession = class {
21337
22209
  isError: value.isError
21338
22210
  });
21339
22211
  }
21340
- async #confirmSettledTurn(active) {
22212
+ #isSettlementCurrent(active, generation) {
22213
+ return this.#activeTurn === active && active.runGeneration === generation && active.settlement === "confirming";
22214
+ }
22215
+ #waitForNextRun(generation) {
22216
+ if (this.#runGeneration > generation)
22217
+ return Promise.resolve();
22218
+ return new Promise((resolve, reject) => {
22219
+ const finish = (error51) => {
22220
+ clearTimeout(timer);
22221
+ this.#runWaiters.delete(waiter);
22222
+ if (error51)
22223
+ reject(error51);
22224
+ else
22225
+ resolve();
22226
+ };
22227
+ const waiter = {
22228
+ check: () => {
22229
+ if (this.#runGeneration > generation)
22230
+ finish();
22231
+ },
22232
+ reject: (error51) => finish(error51)
22233
+ };
22234
+ const timer = setTimeout(() => finish(new PiRpcFaultError("protocolError", "Pi RPC agent_settled state is still Streaming without a subsequent agent_start")), this.#options.commandTimeoutMs);
22235
+ this.#runWaiters.add(waiter);
22236
+ });
22237
+ }
22238
+ #drainDeferredRunFrames() {
22239
+ const frames = this.#deferredRunFrames;
22240
+ this.#deferredRunFrames = [];
22241
+ this.#deferredRunBytes = 0;
22242
+ for (const frame of frames) {
22243
+ if (this.#closed || this.#failed)
22244
+ break;
22245
+ this.#handle(frame.value, frame.generation);
22246
+ }
22247
+ }
22248
+ async #confirmSettledTurn(active, generation) {
21341
22249
  try {
21342
22250
  const response = await this.#send("get_state", {});
21343
22251
  const state2 = parseSessionState(response);
21344
- if (parseSessionStreaming(response)) {
21345
- throw new PiRpcFaultError("protocolError", "Pi RPC agent_settled state is still Streaming");
21346
- }
21347
- if (this.#activeTurn !== active)
22252
+ if (!this.#isSettlementCurrent(active, generation))
21348
22253
  return;
21349
- if (active.origin === "autonomous") {
22254
+ if (parseSessionStreaming(response))
22255
+ await this.#waitForNextRun(generation);
22256
+ if (!this.#isSettlementCurrent(active, generation))
22257
+ return;
22258
+ if (active.origin === "autonomous" && active.autonomousMessage) {
21350
22259
  const history = await this.getEntries();
21351
22260
  const snapshot = mapPiSnapshot(history, { sessionId: state2.sessionId, model: null });
21352
- const turn = snapshot.turns.at(-1);
22261
+ if (!this.#isSettlementCurrent(active, generation))
22262
+ return;
21353
22263
  const entries = activePiEntries(history);
21354
- const start = entries.findIndex((entry) => entry.id === turn?.nativeTurnRef.nativeTurnKey);
21355
- const firstAssistant = entries.slice(start + 1).find((entry) => isRecord8(entry.message) && entry.message.role === "assistant")?.message;
21356
22264
  const live = active.autonomousMessage;
21357
22265
  const responseId = assistantMessageId(live);
21358
- const matches = isRecord8(firstAssistant) && (responseId ? assistantMessageId(firstAssistant) === responseId : typeof live?.timestamp === "number" && firstAssistant.timestamp === live.timestamp);
21359
- if (!turn || turn.input.length !== 0 || !matches) {
22266
+ const matches = snapshot.turns.filter((turn2) => {
22267
+ if (turn2.input.length !== 0)
22268
+ return false;
22269
+ const start = entries.findIndex((entry) => entry.id === turn2.nativeTurnRef.nativeTurnKey);
22270
+ const firstAssistant = entries.slice(start + 1).find((entry) => isRecord9(entry.message) && entry.message.role === "assistant")?.message;
22271
+ return isRecord9(firstAssistant) && (responseId ? assistantMessageId(firstAssistant) === responseId : typeof live?.timestamp === "number" && firstAssistant.timestamp === live.timestamp);
22272
+ });
22273
+ const turn = matches.length === 1 ? matches[0] : void 0;
22274
+ if (!turn)
21360
22275
  throw new PiRpcFaultError("protocolError", "Pi autonomous Turn has no matching persisted custom Entry");
21361
- }
21362
22276
  active.nativeTurnKey = turn.nativeTurnRef.nativeTurnKey;
21363
22277
  }
21364
- if (this.#activeTurn !== active)
22278
+ if (!this.#isSettlementCurrent(active, generation))
21365
22279
  return;
21366
22280
  this.#state = state2;
21367
22281
  active.settlement = "confirmed";
@@ -21387,7 +22301,13 @@ var PiRpcSession = class {
21387
22301
  }
21388
22302
  this.#activeTurn = null;
21389
22303
  if (active.origin === "autonomous") {
21390
- if (active.failure) {
22304
+ if (active.cancellation === "accepted") {
22305
+ this.#emitAutonomousTurn(active, {
22306
+ status: "cancelled",
22307
+ text: active.text,
22308
+ reason: "Cancelled by user"
22309
+ });
22310
+ } else if (active.failure) {
21391
22311
  this.#emitAutonomousTurn(active, active.nativeCancellationObserved ? {
21392
22312
  status: "cancelled",
21393
22313
  text: active.text,
@@ -21402,6 +22322,7 @@ var PiRpcSession = class {
21402
22322
  } else {
21403
22323
  this.#emitAutonomousTurn(active, { status: "succeeded", text: active.text });
21404
22324
  }
22325
+ this.#drainDeferredRunFrames();
21405
22326
  return;
21406
22327
  }
21407
22328
  if (active.cancellation === "accepted") {
@@ -21413,20 +22334,56 @@ var PiRpcSession = class {
21413
22334
  } else {
21414
22335
  active.resolve({ text: active.text, cancelled: false });
21415
22336
  }
22337
+ this.#drainDeferredRunFrames();
22338
+ }
22339
+ #emitContent(active, reasoning, delta) {
22340
+ if (delta.length === 0)
22341
+ return;
22342
+ const messageId = active.assistantMessageId;
22343
+ if (messageId === null)
22344
+ throw new Error("Pi content arrived outside an Assistant message");
22345
+ if (reasoning) {
22346
+ active.reasoningMessageOpen = true;
22347
+ active.sawStreamedMessageReasoning = true;
22348
+ } else {
22349
+ active.text += delta;
22350
+ active.sawStreamedMessageText = true;
22351
+ }
22352
+ active.onEvent({
22353
+ type: reasoning ? "reasoning.delta" : "text.delta",
22354
+ messageId,
22355
+ ...nativeMessageIdentity(active),
22356
+ delta
22357
+ });
21416
22358
  }
21417
22359
  #startAssistantMessage(active, value) {
22360
+ if (active.origin === "autonomous" && !active.autonomousMessage && isRecord9(value))
22361
+ active.autonomousMessage = value;
21418
22362
  if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
21419
22363
  active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
21420
22364
  }
21421
- const messageId = assistantMessageId(value) ?? randomUUID5();
22365
+ const nativeResponseId = assistantMessageId(value);
22366
+ const messageId = nativeResponseId ?? randomUUID6();
21422
22367
  active.assistantMessageId = messageId;
22368
+ active.assistantNativeMessageIdentity = piMessageIdentity(this.state.sessionId, value, this.#messageTimestampCounts);
22369
+ active.textStream = new PiContentStream("text");
22370
+ active.reasoningStream = new PiContentStream("reasoning");
21423
22371
  active.sawStreamedMessageText = false;
21424
22372
  active.sawStreamedMessageReasoning = false;
21425
22373
  active.reasoningMessageOpen = false;
21426
22374
  return messageId;
21427
22375
  }
21428
22376
  #ensureAssistantMessage(active, value) {
21429
- return active.assistantMessageId ?? this.#startAssistantMessage(active, value);
22377
+ if (active.assistantMessageId === null)
22378
+ return this.#startAssistantMessage(active, value);
22379
+ if (!active.sawStreamedMessageText && !active.sawStreamedMessageReasoning) {
22380
+ const nativeResponseId = assistantMessageId(value);
22381
+ if (nativeResponseId) {
22382
+ active.assistantMessageId = nativeResponseId;
22383
+ active.assistantNativeMessageIdentity ??= { responseId: nativeResponseId };
22384
+ }
22385
+ }
22386
+ return active.assistantMessageId;
21430
22387
  }
21431
22388
  #finalizeAssistantMessage(active, value) {
21432
22389
  const finalText = assistantText(value);
@@ -21439,29 +22396,33 @@ var PiRpcSession = class {
21439
22396
  return;
21440
22397
  }
21441
22398
  active.failure = failure;
21442
- if (active.origin === "autonomous" && isRecord8(value) && value.stopReason === "aborted") {
22399
+ if (active.origin === "autonomous" && piAssistantWasAborted(value)) {
21443
22400
  active.nativeCancellationObserved = true;
21444
22401
  }
21445
22402
  this.#latestCacheHitRatePercent = cacheHitRatePercent;
21446
22403
  const messageId = this.#ensureAssistantMessage(active, value);
21447
- if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
21448
- active.reasoningMessageOpen = true;
21449
- active.onEvent({ type: "reasoning.delta", messageId, delta: finalReasoning });
22404
+ const content = value.content;
22405
+ if (failure === null || !active.sawStreamedMessageReasoning) {
22406
+ this.#emitContent(active, true, active.reasoningStream.finalize(content.flatMap((part, index) => {
22407
+ const text3 = extractReasoningText(part);
22408
+ return text3 === null ? [] : [{ index, text: text3 }];
22409
+ })));
21450
22410
  }
21451
22411
  if (active.reasoningMessageOpen && active.failure === null) {
21452
22412
  active.onEvent({ type: "reasoning.completed", messageId });
21453
22413
  }
21454
- if (!active.sawStreamedMessageText && finalText.length > 0) {
21455
- active.text += finalText;
21456
- active.onEvent({ type: "text.delta", messageId, delta: finalText });
22414
+ if (failure === null || !active.sawStreamedMessageText) {
22415
+ this.#emitContent(active, false, active.textStream.finalize(content.flatMap((part, index) => isRecord9(part) && part.type === "text" && typeof part.text === "string" ? [{ index, text: part.text }] : [])));
21457
22416
  }
21458
22417
  active.assistantMessageId = null;
22418
+ active.assistantNativeMessageIdentity = void 0;
21459
22419
  active.sawStreamedMessageText = false;
21460
22420
  active.sawStreamedMessageReasoning = false;
21461
22421
  active.reasoningMessageOpen = false;
21462
22422
  active.lastFinalizedMessageText = finalText;
21463
22423
  active.lastFinalizedMessageReasoning = finalReasoning;
21464
- active.onEvent({ type: "message.completed", messageId });
22424
+ const phase = piAssistantPhase(value);
22425
+ active.onEvent({ type: "message.completed", messageId, ...phase ? { phase } : {} });
21465
22426
  }
21466
22427
  #write(value) {
21467
22428
  const child = this.#child;
@@ -21479,7 +22440,7 @@ var PiRpcSession = class {
21479
22440
  if (!child?.stdin.writable || this.#closed || this.#failed) {
21480
22441
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
21481
22442
  }
21482
- const id = `codexhost-${randomUUID5()}`;
22443
+ const id = `codexhost-${randomUUID6()}`;
21483
22444
  return new Promise((resolve, reject) => {
21484
22445
  const pending = {
21485
22446
  command: type,
@@ -21569,9 +22530,16 @@ var PiRpcSession = class {
21569
22530
  } else {
21570
22531
  active.reject(error51);
21571
22532
  }
22533
+ this.#drainDeferredRunFrames();
21572
22534
  }
21573
22535
  #rejectAll(error51) {
22536
+ for (const waiter of this.#runWaiters)
22537
+ waiter.reject(error51);
22538
+ this.#deferredRunFrames = [];
22539
+ this.#deferredRunBytes = 0;
21574
22540
  this.#subagents.close(error51);
22541
+ this.#gotgenesHandler = void 0;
22542
+ this.#gotgenesLatest = void 0;
21575
22543
  for (const pending of this.#pending.values()) {
21576
22544
  if (pending.timeout)
21577
22545
  clearTimeout(pending.timeout);
@@ -21607,7 +22575,7 @@ var piCommandCatalog = harnessCommandCatalogSchema.parse({
21607
22575
  ]
21608
22576
  });
21609
22577
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
21610
- function isRecord9(value) {
22578
+ function isRecord10(value) {
21611
22579
  return typeof value === "object" && value !== null && !Array.isArray(value);
21612
22580
  }
21613
22581
  function errorMessage(error51) {
@@ -21622,7 +22590,9 @@ var PiAdapterFaultError = class extends Error {
21622
22590
  }
21623
22591
  };
21624
22592
  function normalizedError(error51, fallbackCode) {
21625
- if (isRecord9(error51) && error51.code === "ENOENT") {
22593
+ if (error51 instanceof PiRpcBusyError)
22594
+ return { code: "sessionBusy", message: error51.message, retryable: true };
22595
+ if (isRecord10(error51) && error51.code === "ENOENT") {
21626
22596
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
21627
22597
  }
21628
22598
  if (error51 instanceof PiAdapterFaultError)
@@ -21685,7 +22655,7 @@ function nativeModelForHistory(state2) {
21685
22655
  return nativeModelFromState(state2);
21686
22656
  }
21687
22657
  function sessionFileFromRef(ref) {
21688
- if (ref.harnessId !== piHarnessId2 || !isRecord9(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
22658
+ if (ref.harnessId !== piHarnessId2 || !isRecord10(ref.locator) || typeof ref.locator.sessionFile !== "string" || ref.locator.sessionFile.length === 0) {
21689
22659
  throw new Error("Pi Native Session Ref has no resumable Session file");
21690
22660
  }
21691
22661
  return ref.locator.sessionFile;
@@ -21700,83 +22670,29 @@ function toolFailure(toolName) {
21700
22670
  function nativeText(value) {
21701
22671
  if (typeof value === "string")
21702
22672
  return value;
21703
- if (!isRecord9(value) || !Array.isArray(value.content))
22673
+ if (!isRecord10(value) || !Array.isArray(value.content))
21704
22674
  return "";
21705
- return value.content.filter((content) => isRecord9(content) && content.type === "text" && typeof content.text === "string").map(({ text: text2 }) => text2).join("");
22675
+ return value.content.filter((content) => isRecord10(content) && content.type === "text" && typeof content.text === "string").map(({ text: text3 }) => text3).join("");
21706
22676
  }
21707
22677
  function boundedOutput(value, limit) {
21708
- const text2 = nativeText(value);
21709
- if (text2.length === 0)
22678
+ const text3 = nativeText(value);
22679
+ if (text3.length === 0)
21710
22680
  return void 0;
21711
- const truncated = text2.length > limit;
22681
+ const truncated = text3.length > limit;
21712
22682
  return {
21713
- content: [{ type: "text", text: truncated ? text2.slice(0, limit) : text2 }],
22683
+ content: [{ type: "text", text: truncated ? text3.slice(0, limit) : text3 }],
21714
22684
  ...truncated ? { truncated: true } : {}
21715
22685
  };
21716
22686
  }
21717
22687
  function outputText(output) {
21718
- return output?.content.filter((content) => content.type === "text").map(({ text: text2 }) => text2).join("") ?? "";
21719
- }
21720
- function stringField(value, key) {
21721
- if (!isRecord9(value))
21722
- return void 0;
21723
- const field2 = value[key];
21724
- if (typeof field2 === "string" && field2.length > 0)
21725
- return field2;
21726
- if (isRecord9(value.input)) {
21727
- const nested = value.input[key];
21728
- if (typeof nested === "string" && nested.length > 0)
21729
- return nested;
21730
- }
21731
- if (isRecord9(value.arguments)) {
21732
- const nested = value.arguments[key];
21733
- if (typeof nested === "string" && nested.length > 0)
21734
- return nested;
21735
- }
21736
- return void 0;
22688
+ return output?.content.filter((content) => content.type === "text").map(({ text: text3 }) => text3).join("") ?? "";
21737
22689
  }
21738
22690
  function numberField(value, key) {
21739
- if (!isRecord9(value))
22691
+ if (!isRecord10(value))
21740
22692
  return void 0;
21741
22693
  const field2 = value[key];
21742
22694
  return typeof field2 === "number" || field2 === null ? field2 : void 0;
21743
22695
  }
21744
- function normalizeToolName(name) {
21745
- const lower = name.toLowerCase();
21746
- switch (lower) {
21747
- case "bash":
21748
- case "exec":
21749
- case "terminal":
21750
- case "run":
21751
- return "bash";
21752
- case "read":
21753
- case "read_file":
21754
- case "fileread":
21755
- return "Read";
21756
- case "edit":
21757
- case "edit_file":
21758
- case "fileedit":
21759
- return "Edit";
21760
- case "write":
21761
- case "write_file":
21762
- case "filewrite":
21763
- return "Write";
21764
- case "grep":
21765
- case "grep_search":
21766
- return "Grep";
21767
- case "find":
21768
- case "glob":
21769
- case "find_files":
21770
- return "Glob";
21771
- case "todo":
21772
- return "Todo";
21773
- case "web_search":
21774
- case "websearch":
21775
- return "WebSearch";
21776
- default:
21777
- return name.length > 0 ? `${name[0]?.toUpperCase() ?? ""}${name.slice(1)}` : name;
21778
- }
21779
- }
21780
22696
  function delay(milliseconds) {
21781
22697
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
21782
22698
  }
@@ -21804,6 +22720,8 @@ var PiHarnessSession = class {
21804
22720
  #configuring = false;
21805
22721
  #phase = "open";
21806
22722
  #pendingAutonomousTurns = [];
22723
+ #pendingAutonomousLifecycle = [];
22724
+ #pendingAutonomousLifecycleBytes = 0;
21807
22725
  #starting = null;
21808
22726
  #state = {};
21809
22727
  #transport = null;
@@ -21852,13 +22770,20 @@ var PiHarnessSession = class {
21852
22770
  return this.#transport?.state.sessionId === id;
21853
22771
  }
21854
22772
  async readSubagentHistory(cwd) {
21855
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22773
+ if (this.#phase !== "open" || path16.resolve(cwd) !== path16.resolve(this.#cwd)) {
21856
22774
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21857
22775
  }
21858
22776
  return (await this.#ensureTransport()).getEntries();
21859
22777
  }
22778
+ async readGotgenesChild(id, cwd) {
22779
+ const history = await this.readSubagentHistory(cwd);
22780
+ const transport = this.#transport;
22781
+ if (!transport)
22782
+ throw new Error("Pi parent Session is closed");
22783
+ return readGotgenesChild(history, transport.state.sessionId, id, this.#subagents.gotgenes.records.get(id));
22784
+ }
21860
22785
  async inspectSubagent(id, cwd) {
21861
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22786
+ if (this.#phase !== "open" || path16.resolve(cwd) !== path16.resolve(this.#cwd)) {
21862
22787
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21863
22788
  }
21864
22789
  const transport = await this.#ensureTransport();
@@ -21926,7 +22851,7 @@ var PiHarnessSession = class {
21926
22851
  }
21927
22852
  };
21928
22853
  }
21929
- if (this.#acceptingTurn || this.#active || this.#configuring) {
22854
+ if (this.#acceptingTurn || this.#active || this.#configuring || this.#transport?.isBusy) {
21930
22855
  return {
21931
22856
  ok: false,
21932
22857
  error: {
@@ -21936,8 +22861,8 @@ var PiHarnessSession = class {
21936
22861
  }
21937
22862
  };
21938
22863
  }
21939
- const text2 = command.input.map((input) => input.text).join("\n");
21940
- if (text2.length === 0) {
22864
+ const text3 = command.input.map((input) => input.text).join("\n");
22865
+ if (text3.length === 0) {
21941
22866
  return {
21942
22867
  ok: false,
21943
22868
  error: {
@@ -21967,6 +22892,9 @@ var PiHarnessSession = class {
21967
22892
  } catch (error51) {
21968
22893
  return { ok: false, error: normalizedError(error51, "protocolError") };
21969
22894
  }
22895
+ if (this.#active || transport.isBusy || this.#pendingAutonomousLifecycle.length > 0 || this.#pendingAutonomousTurns.length > 0) {
22896
+ return { ok: false, error: normalizedError(new PiRpcBusyError(), "sessionBusy") };
22897
+ }
21970
22898
  let resolveCompletion = () => void 0;
21971
22899
  const completion = new Promise((resolve) => {
21972
22900
  resolveCompletion = resolve;
@@ -21987,21 +22915,27 @@ var PiHarnessSession = class {
21987
22915
  interactions: /* @__PURE__ */ new Map(),
21988
22916
  interactionByNativeId: /* @__PURE__ */ new Map(),
21989
22917
  cancellationRequested: false,
22918
+ settling: false,
21990
22919
  beforeNativeTurnKeys: new Set(beforeHistory.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
22920
+ progressItems: /* @__PURE__ */ new Set(),
21991
22921
  completion,
21992
22922
  resolveCompletion
21993
22923
  };
21994
22924
  this.#active = active;
21995
22925
  this.#event({ type: "turn.started", turnId: command.turnId });
21996
22926
  this.#event({ type: "item.started", turnId: command.turnId, item });
21997
- void transport.runTurn(text2, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
22927
+ void transport.runTurn(text3, (event) => this.#handleTurnEvent(active, event)).then(async (result) => {
22928
+ active.settling = true;
21998
22929
  try {
21999
22930
  const identity = await this.#completedTurnIdentity(active, transport);
22000
22931
  this.#completeTurn(active, result.cancelled ? {
22001
22932
  status: "cancelled",
22002
22933
  reason: "Cancelled by user",
22003
- checkpoint: identity.checkpoint
22004
- } : { status: "succeeded", checkpoint: identity.checkpoint }, result.text, identity.nativeTurnRef);
22934
+ ...identity.checkpoint ? { checkpoint: identity.checkpoint } : {}
22935
+ } : {
22936
+ status: "succeeded",
22937
+ ...identity.checkpoint ? { checkpoint: identity.checkpoint } : {}
22938
+ }, result.text, identity.nativeTurnRef);
22005
22939
  } catch (error51) {
22006
22940
  this.#completeTurn(active, {
22007
22941
  status: "failed",
@@ -22009,6 +22943,7 @@ var PiHarnessSession = class {
22009
22943
  });
22010
22944
  }
22011
22945
  }).catch(async (error51) => {
22946
+ active.settling = true;
22012
22947
  let identity;
22013
22948
  try {
22014
22949
  identity = await this.#completedTurnIdentity(active, transport);
@@ -22017,12 +22952,14 @@ var PiHarnessSession = class {
22017
22952
  this.#completeTurn(active, {
22018
22953
  status: "failed",
22019
22954
  error: normalizedError(error51, "nativeFailure"),
22020
- ...identity ? { checkpoint: identity.checkpoint } : {}
22955
+ ...identity?.checkpoint ? { checkpoint: identity.checkpoint } : {}
22021
22956
  }, void 0, identity?.nativeTurnRef);
22022
22957
  });
22023
22958
  return { ok: true, value: { turnId: command.turnId } };
22024
22959
  } finally {
22025
22960
  this.#acceptingTurn = false;
22961
+ if (this.#transport)
22962
+ this.#drainPendingAutonomousTurns(this.#transport);
22026
22963
  }
22027
22964
  }
22028
22965
  close() {
@@ -22150,6 +23087,8 @@ var PiHarnessSession = class {
22150
23087
  return { ok: true, value: { completed: true } };
22151
23088
  } finally {
22152
23089
  this.#configuring = false;
23090
+ if (this.#transport)
23091
+ this.#drainPendingAutonomousTurns(this.#transport);
22153
23092
  }
22154
23093
  }
22155
23094
  async #selectThinking(command) {
@@ -22224,6 +23163,8 @@ var PiHarnessSession = class {
22224
23163
  return { ok: true, value: { completed: true } };
22225
23164
  } finally {
22226
23165
  this.#configuring = false;
23166
+ if (this.#transport)
23167
+ this.#drainPendingAutonomousTurns(this.#transport);
22227
23168
  }
22228
23169
  }
22229
23170
  async #cancel(command) {
@@ -22234,6 +23175,12 @@ var PiHarnessSession = class {
22234
23175
  error: invalidState("Pi Turn Cancel must reference the active Turn")
22235
23176
  };
22236
23177
  }
23178
+ if (active.settling) {
23179
+ return {
23180
+ ok: false,
23181
+ error: invalidState("Pi Turn has finished native execution and is recording its completion")
23182
+ };
23183
+ }
22237
23184
  if (active.cancellationRequested) {
22238
23185
  return { ok: true, value: { cancellationRequested: true } };
22239
23186
  }
@@ -22348,7 +23295,9 @@ var PiHarnessSession = class {
22348
23295
  interactions: /* @__PURE__ */ new Map(),
22349
23296
  interactionByNativeId: /* @__PURE__ */ new Map(),
22350
23297
  cancellationRequested: false,
23298
+ settling: false,
22351
23299
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23300
+ progressItems: /* @__PURE__ */ new Set(),
22352
23301
  completion,
22353
23302
  resolveCompletion
22354
23303
  };
@@ -22381,6 +23330,8 @@ var PiHarnessSession = class {
22381
23330
  return { ok: true, value: { turnId: command.turnId } };
22382
23331
  } finally {
22383
23332
  this.#acceptingTurn = false;
23333
+ if (this.#transport)
23334
+ this.#drainPendingAutonomousTurns(this.#transport);
22384
23335
  }
22385
23336
  }
22386
23337
  async #ensureTransport() {
@@ -22431,6 +23382,8 @@ var PiHarnessSession = class {
22431
23382
  return transport;
22432
23383
  }).catch(async (error51) => {
22433
23384
  this.#pendingAutonomousTurns = this.#pendingAutonomousTurns.filter((pending) => pending.transport !== transport);
23385
+ this.#pendingAutonomousLifecycle = this.#pendingAutonomousLifecycle.filter((pending) => pending.transport !== transport);
23386
+ this.#pendingAutonomousLifecycleBytes = this.#pendingAutonomousLifecycle.reduce((total, pending) => total + pending.bytes, 0);
22434
23387
  await transport.close().catch(() => void 0);
22435
23388
  if (this.#phase === "open")
22436
23389
  this.#fault(error51);
@@ -22443,6 +23396,11 @@ var PiHarnessSession = class {
22443
23396
  return starting;
22444
23397
  }
22445
23398
  #bindAutonomousTurnHandler(transport) {
23399
+ transport.setGotgenesStatusHandler?.((records, owner) => {
23400
+ if (this.#phase !== "open")
23401
+ return;
23402
+ this.#subagents.observeGotgenes(records, owner === "requested" && this.#active && !this.#active.settling ? { turnId: this.#active.command.turnId, nextItemId: () => this.#newItemId() } : void 0);
23403
+ });
22446
23404
  transport.setSubagentStatusHandler?.((runs) => {
22447
23405
  if (this.#phase !== "open")
22448
23406
  return;
@@ -22454,12 +23412,16 @@ var PiHarnessSession = class {
22454
23412
  transport.setUsageHandler?.((observation) => {
22455
23413
  if (this.#phase !== "open")
22456
23414
  return;
22457
- const record7 = piUsageRecord(observation.message, observation);
22458
- if (record7?.kind === "request")
22459
- this.#event({ type: "usage.request", request: record7.request });
22460
- else if (record7?.kind === "missing")
23415
+ const record9 = piUsageRecord(observation.message, observation);
23416
+ if (record9?.kind === "request")
23417
+ this.#event({ type: "usage.request", request: record9.request });
23418
+ else if (record9?.kind === "missing")
22461
23419
  this.#event({ type: "usage.history", complete: false });
22462
23420
  });
23421
+ if (transport.setAutonomousTurnLifecycleHandler) {
23422
+ transport.setAutonomousTurnLifecycleHandler((update) => this.#handleAutonomousLifecycle(transport, update));
23423
+ return;
23424
+ }
22463
23425
  transport.setAutonomousTurnHandler((turn) => {
22464
23426
  if (this.#phase !== "open")
22465
23427
  return;
@@ -22471,6 +23433,20 @@ var PiHarnessSession = class {
22471
23433
  });
22472
23434
  }
22473
23435
  #drainPendingAutonomousTurns(transport) {
23436
+ if (this.#phase !== "open" || this.#acceptingTurn || this.#configuring)
23437
+ return;
23438
+ for (; ; ) {
23439
+ const pending2 = this.#pendingAutonomousLifecycle[0];
23440
+ if (!pending2 || pending2.transport !== transport || this.#active && this.#active.autonomousRunId !== pending2.update.runId)
23441
+ break;
23442
+ this.#pendingAutonomousLifecycle.shift();
23443
+ this.#pendingAutonomousLifecycleBytes -= pending2.bytes;
23444
+ this.#applyAutonomousLifecycle(transport, pending2.update);
23445
+ if (this.#phase !== "open")
23446
+ return;
23447
+ }
23448
+ if (this.#active)
23449
+ return;
22474
23450
  if (this.#pendingSubagentStatus) {
22475
23451
  this.#subagents.observe(this.#pendingSubagentStatus);
22476
23452
  this.#pendingSubagentStatus = null;
@@ -22483,6 +23459,52 @@ var PiHarnessSession = class {
22483
23459
  this.#handleAutonomousTurn(transport, candidate.turn);
22484
23460
  }
22485
23461
  }
23462
+ #handleAutonomousLifecycle(transport, update) {
23463
+ if (this.#phase === "closing" && this.#transport === transport && update.type !== "started" && this.#active?.autonomousRunId === update.runId) {
23464
+ this.#applyAutonomousLifecycle(transport, update);
23465
+ return;
23466
+ }
23467
+ if (this.#phase !== "open")
23468
+ return;
23469
+ if (this.#transport !== transport || this.#acceptingTurn || this.#configuring || this.#pendingAutonomousLifecycle.length > 0 || this.#active && this.#active.autonomousRunId !== update.runId) {
23470
+ const bytes = Buffer.byteLength(JSON.stringify(update));
23471
+ if (this.#pendingAutonomousLifecycleBytes + bytes > 8 * 1024 * 1024) {
23472
+ this.#fault(new PiAdapterFaultError({
23473
+ code: "protocolError",
23474
+ message: "Pi autonomous lifecycle exceeded its ordered event buffer bound",
23475
+ retryable: false
23476
+ }));
23477
+ return;
23478
+ }
23479
+ this.#pendingAutonomousLifecycle.push({ transport, update, bytes });
23480
+ this.#pendingAutonomousLifecycleBytes += bytes;
23481
+ if (this.#transport === transport)
23482
+ this.#drainPendingAutonomousTurns(transport);
23483
+ return;
23484
+ }
23485
+ this.#applyAutonomousLifecycle(transport, update);
23486
+ }
23487
+ #applyAutonomousLifecycle(transport, update) {
23488
+ if (update.type === "started" && !this.#active) {
23489
+ this.#startAutonomousHostTurn(update.runId);
23490
+ return;
23491
+ }
23492
+ const active = this.#active;
23493
+ if (!active || active.autonomousRunId !== update.runId || update.type === "started") {
23494
+ this.#fault(new PiAdapterFaultError({
23495
+ code: "protocolError",
23496
+ message: "Pi autonomous event has no matching active run",
23497
+ retryable: false
23498
+ }));
23499
+ return;
23500
+ }
23501
+ if (update.type === "event")
23502
+ this.#handleTurnEvent(active, update.event);
23503
+ else {
23504
+ active.settling = true;
23505
+ this.#finishAutonomousHostTurn(transport, active, update.turn);
23506
+ }
23507
+ }
22486
23508
  #handleAutonomousTurn(transport, turn) {
22487
23509
  if (this.#phase !== "open")
22488
23510
  return;
@@ -22494,7 +23516,7 @@ var PiHarnessSession = class {
22494
23516
  }));
22495
23517
  return;
22496
23518
  }
22497
- if (this.#active || this.#acceptingTurn || this.#configuring) {
23519
+ if (this.#active && !this.#active.settling) {
22498
23520
  this.#fault(new PiAdapterFaultError({
22499
23521
  code: "protocolError",
22500
23522
  message: "Pi autonomous Turn overlapped another Host operation",
@@ -22502,7 +23524,22 @@ var PiHarnessSession = class {
22502
23524
  }));
22503
23525
  return;
22504
23526
  }
22505
- const turnId = hostTurnIdSchema.parse(randomUUID6());
23527
+ if (this.#active || this.#acceptingTurn || this.#configuring) {
23528
+ if (this.#pendingAutonomousTurns.length >= 128) {
23529
+ this.#fault(new PiAdapterFaultError({
23530
+ code: "protocolError",
23531
+ message: "Pi autonomous completion queue exceeded its bound",
23532
+ retryable: false
23533
+ }));
23534
+ } else
23535
+ this.#pendingAutonomousTurns.push({ transport, turn });
23536
+ return;
23537
+ }
23538
+ const active = this.#startAutonomousHostTurn();
23539
+ this.#finishAutonomousHostTurn(transport, active, turn);
23540
+ }
23541
+ #startAutonomousHostTurn(runId) {
23542
+ const turnId = hostTurnIdSchema.parse(randomUUID7());
22506
23543
  let resolveCompletion = () => void 0;
22507
23544
  const completion = new Promise((resolve) => {
22508
23545
  resolveCompletion = resolve;
@@ -22514,6 +23551,7 @@ var PiHarnessSession = class {
22514
23551
  };
22515
23552
  const active = {
22516
23553
  command: { type: "turn.start", turnId, input: [] },
23554
+ ...runId ? { autonomousRunId: runId } : {},
22517
23555
  agentItem: item,
22518
23556
  agentMessageId: null,
22519
23557
  compactionItem: null,
@@ -22523,10 +23561,19 @@ var PiHarnessSession = class {
22523
23561
  interactions: /* @__PURE__ */ new Map(),
22524
23562
  interactionByNativeId: /* @__PURE__ */ new Map(),
22525
23563
  cancellationRequested: false,
23564
+ settling: false,
22526
23565
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23566
+ progressItems: /* @__PURE__ */ new Set(),
22527
23567
  completion,
22528
23568
  resolveCompletion
22529
23569
  };
23570
+ this.#active = active;
23571
+ this.#event({ type: "turn.autonomous.started", turnId, input: [] });
23572
+ this.#event({ type: "turn.started", turnId });
23573
+ this.#event({ type: "item.started", turnId, item });
23574
+ return active;
23575
+ }
23576
+ #finishAutonomousHostTurn(transport, active, turn) {
22530
23577
  const nativeTurnRef = turn.nativeTurnKey ? nativeTurnRefSchema.parse({
22531
23578
  harnessId: this.harnessId,
22532
23579
  nativeSessionId: transport.state.sessionId,
@@ -22539,10 +23586,6 @@ var PiHarnessSession = class {
22539
23586
  checkpointId: nativeTurnRef.nativeTurnKey,
22540
23587
  formatVersion: 1
22541
23588
  }) : void 0;
22542
- this.#active = active;
22543
- this.#event({ type: "turn.autonomous.started", turnId, input: [] });
22544
- this.#event({ type: "turn.started", turnId });
22545
- this.#event({ type: "item.started", turnId, item });
22546
23589
  try {
22547
23590
  for (const event of turn.events)
22548
23591
  this.#handleTurnEvent(active, event);
@@ -22612,17 +23655,35 @@ var PiHarnessSession = class {
22612
23655
  if (this.#active !== active || this.#phase === "closed" || this.#phase === "faulted")
22613
23656
  return;
22614
23657
  switch (event.type) {
23658
+ case "progress.message": {
23659
+ if (active.progressItems.has(event.itemId))
23660
+ return;
23661
+ active.progressItems.add(event.itemId);
23662
+ const item = {
23663
+ type: "agentMessage",
23664
+ itemId: event.itemId,
23665
+ text: event.text,
23666
+ phase: "commentary"
23667
+ };
23668
+ this.#event({ type: "item.started", turnId: active.command.turnId, item });
23669
+ this.#completeItem(active, item, { status: "succeeded" });
23670
+ return;
23671
+ }
22615
23672
  case "text.delta":
22616
- this.#activateAgentMessage(active, event.messageId);
23673
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23674
+ active.sawAssistantMessage = true;
22617
23675
  this.#appendText(active, event.delta);
22618
23676
  return;
22619
23677
  case "reasoning.delta":
22620
- this.#appendReasoning(active, event.delta);
23678
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23679
+ this.#appendReasoning(active, event.delta, event.nativeMessageIdentity);
22621
23680
  return;
22622
23681
  case "reasoning.completed":
22623
23682
  this.#completeReasoning(active, { status: "succeeded" });
22624
23683
  return;
22625
23684
  case "message.completed":
23685
+ if (event.phase && active.agentMessageId === event.messageId && active.agentItem)
23686
+ active.agentItem = { ...active.agentItem, phase: event.phase };
22626
23687
  void this.#refreshUsage(active.command.turnId);
22627
23688
  return;
22628
23689
  case "compaction.started":
@@ -22680,7 +23741,7 @@ var PiHarnessSession = class {
22680
23741
  if (active.interactionByNativeId.has(request.requestId)) {
22681
23742
  throw new Error("Pi Interaction started more than once");
22682
23743
  }
22683
- const interactionId = hostInteractionIdSchema.parse(randomUUID6());
23744
+ const interactionId = hostInteractionIdSchema.parse(randomUUID7());
22684
23745
  const question = request.method === "select" ? {
22685
23746
  id: "answer",
22686
23747
  type: "choice",
@@ -22737,17 +23798,21 @@ var PiHarnessSession = class {
22737
23798
  reason
22738
23799
  });
22739
23800
  }
22740
- #activateAgentMessage(active, messageId) {
23801
+ #activateAgentMessage(active, messageId, nativeMessageIdentity2) {
22741
23802
  if (active.agentMessageId === messageId)
22742
23803
  return;
23804
+ const nativeItemId = piMessageItemId(nativeMessageIdentity2, "assistant");
23805
+ if (nativeItemId && active.agentMessageId === null && active.agentItem?.text === "") {
23806
+ this.#completeAgentItem(active, { status: "succeeded" }, true);
23807
+ }
22743
23808
  if (active.agentMessageId !== null) {
22744
23809
  this.#completeReasoning(active, { status: "succeeded" });
22745
- this.#completeAgentItem(active, { status: "succeeded" }, false);
23810
+ this.#completeAgentItem(active, { status: "succeeded" }, true);
22746
23811
  }
22747
23812
  if (!active.agentItem) {
22748
23813
  active.agentItem = {
22749
23814
  type: "agentMessage",
22750
- itemId: this.#newItemId(),
23815
+ itemId: nativeItemId ?? this.#newItemId(),
22751
23816
  text: ""
22752
23817
  };
22753
23818
  this.#event({
@@ -22757,18 +23822,17 @@ var PiHarnessSession = class {
22757
23822
  });
22758
23823
  }
22759
23824
  active.agentMessageId = messageId;
22760
- active.sawAssistantMessage = true;
22761
23825
  }
22762
- #appendText(active, text2) {
23826
+ #appendText(active, text3) {
22763
23827
  if (active.agentMessageId === null || !active.agentItem) {
22764
23828
  throw new Error("Pi Assistant text arrived outside an active message");
22765
23829
  }
22766
- active.agentItem = { ...active.agentItem, text: active.agentItem.text + text2 };
23830
+ active.agentItem = { ...active.agentItem, text: active.agentItem.text + text3 };
22767
23831
  this.#event({
22768
23832
  type: "item.updated",
22769
23833
  turnId: active.command.turnId,
22770
23834
  itemId: active.agentItem.itemId,
22771
- update: { type: "text.append", text: text2 }
23835
+ update: { type: "text.append", text: text3 }
22772
23836
  });
22773
23837
  }
22774
23838
  #completeAgentItem(active, outcome, completeEmpty) {
@@ -22779,13 +23843,13 @@ var PiHarnessSession = class {
22779
23843
  active.agentItem = null;
22780
23844
  this.#completeItem(active, item, outcome);
22781
23845
  }
22782
- #appendReasoning(active, text2) {
22783
- if (text2.length === 0)
23846
+ #appendReasoning(active, text3, nativeMessageIdentity2) {
23847
+ if (text3.length === 0)
22784
23848
  return;
22785
23849
  if (!active.reasoningItem) {
22786
23850
  active.reasoningItem = {
22787
23851
  type: "reasoning",
22788
- itemId: this.#newItemId(),
23852
+ itemId: piMessageItemId(nativeMessageIdentity2, "reasoning") ?? this.#newItemId(),
22789
23853
  text: ""
22790
23854
  };
22791
23855
  this.#event({
@@ -22796,13 +23860,13 @@ var PiHarnessSession = class {
22796
23860
  }
22797
23861
  active.reasoningItem = {
22798
23862
  ...active.reasoningItem,
22799
- text: active.reasoningItem.text + text2
23863
+ text: active.reasoningItem.text + text3
22800
23864
  };
22801
23865
  this.#event({
22802
23866
  type: "item.updated",
22803
23867
  turnId: active.command.turnId,
22804
23868
  itemId: active.reasoningItem.itemId,
22805
- update: { type: "text.append", text: text2 }
23869
+ update: { type: "text.append", text: text3 }
22806
23870
  });
22807
23871
  }
22808
23872
  #completeReasoning(active, outcome) {
@@ -22815,13 +23879,12 @@ var PiHarnessSession = class {
22815
23879
  #startTool(active, event) {
22816
23880
  if (active.tools.has(event.callId))
22817
23881
  throw new Error("Pi Tool started more than once");
22818
- const normalizedName = normalizeToolName(event.toolName);
22819
- 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;
22820
- const item = command ? {
23882
+ const shell = piToolCommand(event.toolName, event.arguments);
23883
+ const item = shell ? {
22821
23884
  type: "commandExecution",
22822
23885
  itemId: this.#newItemId(),
22823
- command,
22824
- cwd: stringField(event.arguments, "cwd") ?? this.#cwd
23886
+ command: shell.command,
23887
+ cwd: shell.cwd ?? this.#cwd
22825
23888
  } : {
22826
23889
  type: "toolExecution",
22827
23890
  itemId: this.#newItemId(),
@@ -22939,14 +24002,17 @@ var PiHarnessSession = class {
22939
24002
  sessionId: transport.state.sessionId,
22940
24003
  model: nativeModelForHistory(transport.state)
22941
24004
  });
22942
- const created = snapshot.turns.filter((turn2) => !active.beforeNativeTurnKeys.has(turn2.nativeTurnRef.nativeTurnKey));
24005
+ const created = snapshot.turns.filter((turn2) => turn2.input.length > 0 && !active.beforeNativeTurnKeys.has(turn2.nativeTurnRef.nativeTurnKey));
22943
24006
  if (created.length !== 1) {
22944
24007
  throw new Error(`Pi Turn persisted ${created.length} new User Entries; exactly one is required`);
22945
24008
  }
22946
24009
  const turn = created[0];
22947
- if (!turn?.checkpoint)
22948
- throw new Error("Pi Turn has no terminal Checkpoint identity");
22949
- return { nativeTurnRef: turn.nativeTurnRef, checkpoint: turn.checkpoint };
24010
+ if (!turn)
24011
+ throw new Error("Pi Turn has no persisted User identity");
24012
+ return {
24013
+ nativeTurnRef: turn.nativeTurnRef,
24014
+ ...turn.checkpoint ? { checkpoint: turn.checkpoint } : {}
24015
+ };
22950
24016
  }
22951
24017
  #completeTurn(active, outcome, finalText, nativeTurnRef) {
22952
24018
  if (this.#active !== active)
@@ -22975,14 +24041,20 @@ var PiHarnessSession = class {
22975
24041
  });
22976
24042
  active.resolveCompletion();
22977
24043
  queueMicrotask(() => {
22978
- if (this.#phase === "open")
22979
- void this.#refreshUsage(active.command.turnId);
24044
+ if (this.#phase !== "open")
24045
+ return;
24046
+ if (this.#transport)
24047
+ this.#drainPendingAutonomousTurns(this.#transport);
24048
+ void this.#refreshUsage(active.command.turnId);
22980
24049
  });
22981
24050
  }
22982
24051
  #fault(error51) {
22983
24052
  if (this.#phase === "closed" || this.#phase === "faulted")
22984
24053
  return;
22985
24054
  const normalized = normalizedError(error51, "internalError");
24055
+ this.#pendingAutonomousTurns = [];
24056
+ this.#pendingAutonomousLifecycle = [];
24057
+ this.#pendingAutonomousLifecycleBytes = 0;
22986
24058
  if (this.#active) {
22987
24059
  this.#completeTurn(this.#active, { status: "failed", error: normalized });
22988
24060
  }
@@ -22991,6 +24063,9 @@ var PiHarnessSession = class {
22991
24063
  this.#channel.end();
22992
24064
  }
22993
24065
  async #close() {
24066
+ this.#pendingAutonomousTurns = [];
24067
+ this.#pendingAutonomousLifecycle = [];
24068
+ this.#pendingAutonomousLifecycleBytes = 0;
22994
24069
  if (this.#phase === "closed")
22995
24070
  return;
22996
24071
  const wasFaulted = this.#phase === "faulted";
@@ -23023,7 +24098,7 @@ var PiHarnessSession = class {
23023
24098
  this.#channel.emit({ kind: "event", event });
23024
24099
  }
23025
24100
  #newItemId() {
23026
- return hostItemIdSchema.parse(randomUUID6());
24101
+ return hostItemIdSchema.parse(randomUUID7());
23027
24102
  }
23028
24103
  };
23029
24104
  var PiAdapter = class {
@@ -23038,12 +24113,15 @@ var PiAdapter = class {
23038
24113
  if (this.#closePromise || parent.harnessId !== this.harnessId) {
23039
24114
  return { ok: false, error: invalidState("Pi Subagent parent is unavailable") };
23040
24115
  }
24116
+ const gotgenes = parseGotgenesId(nativeSubagentId);
23041
24117
  const workflow = parsePiWorkflowSubagentId(nativeSubagentId);
23042
- if (!workflow)
24118
+ if (!workflow && !gotgenes)
23043
24119
  parsePiSubagentId(nativeSubagentId);
23044
24120
  const live = [...this.#sessions].find((session) => session.ownsNativeSession(parent.nativeSessionId));
23045
24121
  let reply;
23046
24122
  if (live) {
24123
+ if (gotgenes)
24124
+ return await live.readGotgenesChild(gotgenes, cwd);
23047
24125
  if (workflow)
23048
24126
  return await readPiWorkflowChild(await live.readSubagentHistory(cwd), parent.nativeSessionId, workflow);
23049
24127
  reply = await live.inspectSubagent(nativeSubagentId, cwd);
@@ -23055,6 +24133,8 @@ var PiAdapter = class {
23055
24133
  if (transport.state.sessionId !== parent.nativeSessionId)
23056
24134
  throw new Error("Pi Subagent parent identity mismatch");
23057
24135
  await transport.verifySessionCwd(cwd);
24136
+ if (gotgenes)
24137
+ return await readGotgenesChild(await transport.getEntries(), parent.nativeSessionId, gotgenes);
23058
24138
  if (workflow)
23059
24139
  return await readPiWorkflowChild(await transport.getEntries(), parent.nativeSessionId, workflow);
23060
24140
  if (!transport.inspectSubagent)