@karlorz/codexhost-cli-win32-x64 0.16.1-3 → 0.17.0-1

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.
@@ -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),
@@ -16889,8 +16889,8 @@ async function readCandidate(file2, signal) {
16889
16889
  const message3 = isRecord(entry.message) ? entry.message : null;
16890
16890
  if (!firstMessage && entry.type === "message" && message3?.role === "user") {
16891
16891
  const content = message3.content;
16892
- 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(" ") : "";
16893
- 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);
16894
16894
  }
16895
16895
  hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
16896
16896
  entries.set(entry.id, hasUser);
@@ -17406,8 +17406,8 @@ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17406
17406
  const descriptor = catalog.commands.find(({ id }) => id === commandId);
17407
17407
  if (!descriptor)
17408
17408
  return null;
17409
- const text2 = typeof argumentText === "string" ? argumentText.trim() : "";
17410
- return text2 ? `${descriptor.invocation} ${text2}` : descriptor.invocation;
17409
+ const text3 = typeof argumentText === "string" ? argumentText.trim() : "";
17410
+ return text3 ? `${descriptor.invocation} ${text3}` : descriptor.invocation;
17411
17411
  }
17412
17412
  function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17413
17413
  if (!live)
@@ -17543,16 +17543,16 @@ var Diff = class {
17543
17543
  }
17544
17544
  }
17545
17545
  }
17546
- addToPath(path16, added, removed, oldPosInc, options) {
17547
- const last = path16.lastComponent;
17546
+ addToPath(path17, added, removed, oldPosInc, options) {
17547
+ const last = path17.lastComponent;
17548
17548
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
17549
17549
  return {
17550
- oldPos: path16.oldPos + oldPosInc,
17550
+ oldPos: path17.oldPos + oldPosInc,
17551
17551
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
17552
17552
  };
17553
17553
  } else {
17554
17554
  return {
17555
- oldPos: path16.oldPos + oldPosInc,
17555
+ oldPos: path17.oldPos + oldPosInc,
17556
17556
  lastComponent: { count: 1, added, removed, previousComponent: last }
17557
17557
  };
17558
17558
  }
@@ -17952,9 +17952,9 @@ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader
17952
17952
  } }));
17953
17953
  }
17954
17954
  }
17955
- function splitLines(text2) {
17956
- const hasTrailingNl = text2.endsWith("\n");
17957
- 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");
17958
17958
  if (hasTrailingNl) {
17959
17959
  result.pop();
17960
17960
  } else {
@@ -18188,11 +18188,344 @@ function piNestedCallFileChanges(nestedCalls, cwd) {
18188
18188
  return projected;
18189
18189
  }
18190
18190
 
18191
- // dist/pi-subagents.js
18191
+ // dist/pi-message-item-id.js
18192
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
+ };
18193
18526
 
18194
18527
  // dist/pi-subagent-workflow.js
18195
- var PREFIX = "pi-subagents-workflow-v1:";
18528
+ var PREFIX2 = "pi-subagents-workflow-v1:";
18196
18529
  var STATES = {
18197
18530
  pending: "pending",
18198
18531
  running: "running",
@@ -18206,7 +18539,7 @@ var STATES = {
18206
18539
  function record2(value) {
18207
18540
  return typeof value === "object" && value !== null && !Array.isArray(value);
18208
18541
  }
18209
- function text(value, limit = 256) {
18542
+ function text2(value, limit = 256) {
18210
18543
  return typeof value === "string" && value.length > 0 && value.length <= limit;
18211
18544
  }
18212
18545
  function piWorkflowSummary(result) {
@@ -18214,15 +18547,15 @@ function piWorkflowSummary(result) {
18214
18547
  return null;
18215
18548
  const details = result.details;
18216
18549
  const summary = details.workflowChildren;
18217
- 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)
18218
18551
  return null;
18219
18552
  const children = [];
18220
18553
  const seen = /* @__PURE__ */ new Set();
18221
18554
  for (const child of summary.children) {
18222
- 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))
18223
18556
  return null;
18224
18557
  for (const key of ["agent", "sessionName", "model", "thinking"]) {
18225
- if (child[key] !== void 0 && !text(child[key], 2048))
18558
+ if (child[key] !== void 0 && !text2(child[key], 2048))
18226
18559
  return null;
18227
18560
  }
18228
18561
  const mappedState = STATES[child.state];
@@ -18246,15 +18579,15 @@ function piWorkflowSummary(result) {
18246
18579
  };
18247
18580
  }
18248
18581
  function piWorkflowSubagentId(address) {
18249
- 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");
18250
18583
  }
18251
18584
  function parsePiWorkflowSubagentId(id) {
18252
- if (!id.startsWith(PREFIX))
18585
+ if (!id.startsWith(PREFIX2))
18253
18586
  return null;
18254
18587
  if (id.length > 3e3)
18255
18588
  throw new Error("Invalid Pi workflow child identity");
18256
- const value = JSON.parse(Buffer.from(id.slice(PREFIX.length), "base64url").toString("utf8"));
18257
- 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]))
18258
18591
  throw new Error("Invalid Pi workflow child identity");
18259
18592
  const address = { workflowRunId: value[0], childId: value[1] };
18260
18593
  if (piWorkflowSubagentId(address) !== id)
@@ -18412,8 +18745,13 @@ var PiSubagents = class {
18412
18745
  #children = /* @__PURE__ */ new Map();
18413
18746
  #active = /* @__PURE__ */ new Map();
18414
18747
  #waiting = /* @__PURE__ */ new Map();
18748
+ gotgenes;
18415
18749
  constructor(emit) {
18416
18750
  this.emit = emit;
18751
+ this.gotgenes = new GotgenesSubagents(emit);
18752
+ }
18753
+ observeGotgenes(records, activeTurn) {
18754
+ this.gotgenes.observe(records, true, activeTurn, true);
18417
18755
  }
18418
18756
  observe(runs) {
18419
18757
  this.#apply(runs, true);
@@ -18467,6 +18805,9 @@ var PiSubagents = class {
18467
18805
  }
18468
18806
  }
18469
18807
  project(toolName, result, itemId2, callId) {
18808
+ const gotgenes = this.gotgenes.project(toolName, result, itemId2);
18809
+ if (gotgenes)
18810
+ return gotgenes;
18470
18811
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18471
18812
  if (workflow && (!callId || workflow.parentToolCallId === callId))
18472
18813
  return projectPiWorkflow(workflow, itemId2);
@@ -18477,6 +18818,8 @@ var PiSubagents = class {
18477
18818
  return children.length ? { type: "subagentDelegation", itemId: itemId2, operation: "spawn", subagents: children } : null;
18478
18819
  }
18479
18820
  start(turnId, toolName, result, itemId2, callId) {
18821
+ if (this.gotgenes.start(turnId, toolName, result, itemId2))
18822
+ return;
18480
18823
  const workflow = toolName === "subagent" ? piWorkflowSummary(result) : null;
18481
18824
  if (workflow && (!callId || workflow.parentToolCallId === callId)) {
18482
18825
  const key = `workflow:${workflow.workflowRunId}`;
@@ -18522,6 +18865,7 @@ var PiSubagents = class {
18522
18865
  this.emit({ type: "item.started", turnId, item });
18523
18866
  }
18524
18867
  finish(turnId) {
18868
+ this.gotgenes.finish(turnId);
18525
18869
  for (const [runId, waiting] of this.#waiting) {
18526
18870
  if (waiting.turnId === turnId)
18527
18871
  this.#waiting.delete(runId);
@@ -18569,15 +18913,15 @@ ${entry.text}`);
18569
18913
  nativeTurnRef: nativeTurnRefSchema.parse({
18570
18914
  harnessId: "pi",
18571
18915
  nativeSessionId: parentSessionId,
18572
- nativeTurnKey: `pi-subagent-${createHash("sha256").update(id).digest("hex")}`,
18916
+ nativeTurnKey: `pi-subagent-${createHash3("sha256").update(id).digest("hex")}`,
18573
18917
  formatVersion: 1
18574
18918
  }),
18575
18919
  input: reply.task ? [{ type: "text", text: reply.task }] : [],
18576
- items: texts.map((text2, index) => ({
18920
+ items: texts.map((text3, index) => ({
18577
18921
  item: {
18578
18922
  type: "agentMessage",
18579
- text: text2,
18580
- 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")}`)
18581
18925
  },
18582
18926
  outcome: { status: "succeeded" }
18583
18927
  })),
@@ -18725,22 +19069,149 @@ function normalizePiModelCatalog(nativeModels, effectiveModel, thinkingLevels, e
18725
19069
  });
18726
19070
  }
18727
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
+
18728
19199
  // dist/pi-history.js
18729
19200
  var piHarnessId = harnessIdSchema.parse("pi");
18730
- function isRecord4(value) {
19201
+ function isRecord5(value) {
18731
19202
  return typeof value === "object" && value !== null && !Array.isArray(value);
18732
19203
  }
18733
- function textContent(value) {
19204
+ function textContent2(value) {
18734
19205
  if (typeof value === "string")
18735
19206
  return value;
18736
19207
  if (!Array.isArray(value))
18737
19208
  return "";
18738
- 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("");
18739
19210
  }
18740
19211
  function thinkingContent(value) {
18741
19212
  if (!Array.isArray(value))
18742
19213
  return "";
18743
- 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("");
18744
19215
  }
18745
19216
  function validatedEntry(value) {
18746
19217
  if (typeof value.id !== "string" || value.id.length === 0 || value.parentId !== null && typeof value.parentId !== "string" || typeof value.type !== "string") {
@@ -18771,7 +19242,7 @@ function activePiEntries(history) {
18771
19242
  return reversed.reverse();
18772
19243
  }
18773
19244
  function message(entry) {
18774
- return entry.type === "message" && isRecord4(entry.message) ? entry.message : null;
19245
+ return entry.type === "message" && isRecord5(entry.message) ? entry.message : null;
18775
19246
  }
18776
19247
  function messageRole(entry) {
18777
19248
  const value = message(entry)?.role;
@@ -18786,7 +19257,7 @@ function assistantOutcome(entries) {
18786
19257
  if (!final)
18787
19258
  return { status: "unknown", reason: "Pi history has no Assistant terminal" };
18788
19259
  const stopReason = final.stopReason;
18789
- if (stopReason === "aborted") {
19260
+ if (piAssistantWasAborted(final)) {
18790
19261
  return { status: "cancelled", reason: "Pi Assistant was aborted" };
18791
19262
  }
18792
19263
  if (stopReason === "error") {
@@ -18799,7 +19270,7 @@ function assistantOutcome(entries) {
18799
19270
  }
18800
19271
  };
18801
19272
  }
18802
- if (typeof stopReason === "string" || textContent(final.content).length > 0) {
19273
+ if (typeof stopReason === "string" || textContent2(final.content).length > 0) {
18803
19274
  return { status: "succeeded" };
18804
19275
  }
18805
19276
  return { status: "unknown", reason: "Pi Assistant terminal is not classifiable" };
@@ -18816,8 +19287,8 @@ function itemOutcome(outcome) {
18816
19287
  return { status: "succeeded" };
18817
19288
  }
18818
19289
  function toolOutput(value) {
18819
- const text2 = textContent(value);
18820
- 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;
18821
19292
  }
18822
19293
  function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18823
19294
  const items = [];
@@ -18840,37 +19311,52 @@ function historicalFileChanges(call, nativeMessage, toolItemId, cwd) {
18840
19311
  }
18841
19312
  return items;
18842
19313
  }
18843
- function snapshotItems(entries, outcome, subagents, cwd) {
19314
+ function snapshotItems(entries, messageIdentities, notices, outcome, subagents, cwd) {
18844
19315
  const snapshots = [];
18845
19316
  const toolCalls = /* @__PURE__ */ new Map();
18846
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
+ }
18847
19331
  const nativeMessage = message(entry);
18848
19332
  if (!nativeMessage)
18849
19333
  continue;
18850
19334
  const content = Array.isArray(nativeMessage.content) ? nativeMessage.content : [];
18851
19335
  if (nativeMessage.role === "assistant") {
18852
- const text2 = textContent(content);
19336
+ const text3 = textContent2(content);
18853
19337
  const reasoning = thinkingContent(content);
18854
19338
  let projectedText = false;
18855
19339
  let projectedReasoning = false;
18856
19340
  for (const [ordinal, part] of content.entries()) {
18857
- if (!isRecord4(part))
19341
+ if (!isRecord5(part))
18858
19342
  continue;
18859
19343
  if (part.type === "thinking" && !projectedReasoning && reasoning.length > 0) {
18860
19344
  const item2 = {
18861
19345
  type: "reasoning",
18862
- itemId: itemId(entry.id, "reasoning", 0),
19346
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "reasoning") ?? itemId(entry.id, "reasoning", 0),
18863
19347
  text: reasoning
18864
19348
  };
18865
19349
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18866
19350
  projectedReasoning = true;
18867
19351
  continue;
18868
19352
  }
18869
- if (part.type === "text" && !projectedText && text2.length > 0) {
19353
+ if (part.type === "text" && !projectedText && text3.length > 0) {
19354
+ const phase = piAssistantPhase(nativeMessage);
18870
19355
  const item2 = {
18871
19356
  type: "agentMessage",
18872
- itemId: itemId(entry.id, "assistant", 0),
18873
- text: text2
19357
+ itemId: piMessageItemId(messageIdentities.get(entry.id), "assistant") ?? itemId(entry.id, "assistant", 0),
19358
+ text: text3,
19359
+ ...phase ? { phase } : {}
18874
19360
  };
18875
19361
  snapshots.push({ item: item2, outcome: itemOutcome(outcome) });
18876
19362
  projectedText = true;
@@ -18898,9 +19384,24 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18898
19384
  if (!call || call.name !== nativeMessage.toolName)
18899
19385
  continue;
18900
19386
  const output = toolOutput(nativeMessage.content);
18901
- const item = {
18902
- 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 = {
18903
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",
18904
19405
  toolName: call.name,
18905
19406
  arguments: call.arguments,
18906
19407
  ...output ? { output } : {}
@@ -18931,6 +19432,10 @@ function snapshotItems(entries, outcome, subagents, cwd) {
18931
19432
  function modelChange(entry) {
18932
19433
  return entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string" ? { provider: entry.provider, id: entry.modelId } : null;
18933
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
+ }
18934
19439
  function turnStarts(active) {
18935
19440
  const starts = [];
18936
19441
  let terminal = true;
@@ -18938,6 +19443,8 @@ function turnStarts(active) {
18938
19443
  for (const [index, entry] of active.entries()) {
18939
19444
  const role = messageRole(entry);
18940
19445
  if (role === "user") {
19446
+ if (pending && isEmptyWakeup(entry))
19447
+ continue;
18941
19448
  starts.push({ entry, index });
18942
19449
  pending = null;
18943
19450
  terminal = false;
@@ -18954,6 +19461,8 @@ function turnStarts(active) {
18954
19461
  }
18955
19462
  function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0)) {
18956
19463
  const active = activePiEntries(history);
19464
+ const { identities } = piHistoryMessageIdentities(state2.sessionId, active);
19465
+ const { notices } = piHistoryNotices(state2.sessionId, active);
18957
19466
  const turns = [];
18958
19467
  const starts = turnStarts(active);
18959
19468
  const byIndex = new Map(starts.map((start, ordinal) => [start.index, ordinal]));
@@ -18975,7 +19484,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18975
19484
  const end = next?.index ?? active.length;
18976
19485
  const entries = active.slice(index, end);
18977
19486
  const outcome = assistantOutcome(entries);
18978
- const userText = textContent(message(user)?.content);
19487
+ const userText = textContent2(message(user)?.content);
18979
19488
  const nativeTurnRef = nativeTurnRefSchema.parse({
18980
19489
  harnessId: piHarnessId,
18981
19490
  nativeSessionId: state2.sessionId,
@@ -18992,7 +19501,7 @@ function mapPiSnapshot(history, state2, subagents = new PiSubagents(() => void 0
18992
19501
  nativeTurnRef,
18993
19502
  ...!next || messageRole(next.entry) === "user" ? { checkpoint } : {},
18994
19503
  input: messageRole(user) === "user" ? [{ type: "text", text: userText }] : [],
18995
- items: snapshotItems(entries, outcome, subagents, state2.cwd),
19504
+ items: snapshotItems(entries, identities, notices, outcome, subagents, state2.cwd),
18996
19505
  outcome,
18997
19506
  ...effectiveModel ? { model: encodePiModelRef(effectiveModel) } : {}
18998
19507
  });
@@ -19027,14 +19536,14 @@ function resolvePiForkBoundary(history, checkpointId) {
19027
19536
  }
19028
19537
 
19029
19538
  // dist/pi-usage.js
19030
- function isRecord5(value) {
19539
+ function isRecord6(value) {
19031
19540
  return typeof value === "object" && value !== null && !Array.isArray(value);
19032
19541
  }
19033
19542
  function nonNegativeSafeInteger(value) {
19034
19543
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
19035
19544
  }
19036
19545
  function optionalPiCacheHitRatePercent(value) {
19037
- if (!isRecord5(value) || value.role !== "assistant" || !isRecord5(value.usage))
19546
+ if (!isRecord6(value) || value.role !== "assistant" || !isRecord6(value.usage))
19038
19547
  return null;
19039
19548
  const input = nonNegativeSafeInteger(value.usage.input);
19040
19549
  const cacheRead = nonNegativeSafeInteger(value.usage.cacheRead);
@@ -19047,20 +19556,20 @@ function optionalPiCacheHitRatePercent(value) {
19047
19556
  function latestPiCacheHitRatePercent(history) {
19048
19557
  let latest = null;
19049
19558
  for (const entry of activePiEntries(history)) {
19050
- if (entry.type === "message" && isRecord5(entry.message) && entry.message.role === "assistant") {
19559
+ if (entry.type === "message" && isRecord6(entry.message) && entry.message.role === "assistant") {
19051
19560
  latest = optionalPiCacheHitRatePercent(entry.message);
19052
19561
  }
19053
19562
  }
19054
19563
  return latest;
19055
19564
  }
19056
19565
  function responseData(response, operation) {
19057
- if (!isRecord5(response.data)) {
19566
+ if (!isRecord6(response.data)) {
19058
19567
  throw new Error(`Pi RPC ${operation} response has no data`);
19059
19568
  }
19060
19569
  return response.data;
19061
19570
  }
19062
19571
  function contextUsage(value) {
19063
- if (!isRecord5(value))
19572
+ if (!isRecord6(value))
19064
19573
  throw new Error("Pi RPC context Usage is invalid");
19065
19574
  return parseHostUsage({
19066
19575
  contextUsedTokens: value.tokens,
@@ -19070,15 +19579,15 @@ function contextUsage(value) {
19070
19579
  function parsePiSessionUsage(response) {
19071
19580
  const data = responseData(response, "Session stats");
19072
19581
  const tokens = data.tokens;
19073
- if (tokens !== void 0 && !isRecord5(tokens)) {
19582
+ if (tokens !== void 0 && !isRecord6(tokens)) {
19074
19583
  throw new Error("Pi RPC Session stats tokens are invalid");
19075
19584
  }
19076
19585
  return parseHostUsage({
19077
- ...isRecord5(tokens) && tokens.input !== void 0 ? { inputTokens: tokens.input } : {},
19078
- ...isRecord5(tokens) && tokens.cacheRead !== void 0 ? { cachedInputTokens: tokens.cacheRead } : {},
19079
- ...isRecord5(tokens) && tokens.cacheWrite !== void 0 ? { cacheWriteInputTokens: tokens.cacheWrite } : {},
19080
- ...isRecord5(tokens) && tokens.output !== void 0 ? { outputTokens: tokens.output } : {},
19081
- ...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 } : {},
19082
19591
  ...data.cost !== void 0 ? { totalCostUsd: data.cost } : {},
19083
19592
  ...data.contextUsage !== void 0 ? contextUsage(data.contextUsage) : {}
19084
19593
  });
@@ -19097,9 +19606,9 @@ function optionalPiStateContextUsage(value) {
19097
19606
  }
19098
19607
  }
19099
19608
  function piUsageRecord(message3, extra = {}) {
19100
- if (!isRecord5(message3) || message3.role !== "assistant")
19609
+ if (!isRecord6(message3) || message3.role !== "assistant")
19101
19610
  return null;
19102
- const usage = isRecord5(message3.usage) ? message3.usage : null;
19611
+ const usage = isRecord6(message3.usage) ? message3.usage : null;
19103
19612
  const input = nonNegativeSafeInteger(usage?.input);
19104
19613
  const output = nonNegativeSafeInteger(usage?.output);
19105
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;
@@ -19136,17 +19645,17 @@ function piUsageHistory(history) {
19136
19645
  for (const entry of history.entries) {
19137
19646
  if (entry.type !== "message")
19138
19647
  continue;
19139
- const record7 = piUsageRecord(entry.message, { historical: true });
19140
- if (record7?.kind === "request")
19141
- requests.push(record7.request);
19142
- 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")
19143
19652
  complete = false;
19144
19653
  }
19145
19654
  return { requests, complete };
19146
19655
  }
19147
19656
 
19148
19657
  // dist/pi-usage-statistics.js
19149
- function isRecord6(value) {
19658
+ function isRecord7(value) {
19150
19659
  return typeof value === "object" && value !== null && !Array.isArray(value);
19151
19660
  }
19152
19661
  function piUserText(content) {
@@ -19154,11 +19663,11 @@ function piUserText(content) {
19154
19663
  return content;
19155
19664
  if (!Array.isArray(content))
19156
19665
  return void 0;
19157
- 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(" ");
19158
19667
  }
19159
19668
  async function readPiUsage(file2, signal) {
19160
19669
  const entries = [];
19161
- const header = await jsonlHeader(file2, (record7) => record7.type === "session", signal);
19670
+ const header = await jsonlHeader(file2, (record9) => record9.type === "session", signal);
19162
19671
  let name;
19163
19672
  const session = {
19164
19673
  sessionId: typeof header?.id === "string" ? header.id : void 0,
@@ -19175,11 +19684,11 @@ async function readPiUsage(file2, signal) {
19175
19684
  if (!name && message3?.role === "user") {
19176
19685
  name = usageSessionTitle(piUserText(message3.content));
19177
19686
  }
19178
- const record7 = piUsageRecord(line.message);
19179
- if (record7?.kind !== "request")
19687
+ const record9 = piUsageRecord(line.message);
19688
+ if (record9?.kind !== "request")
19180
19689
  continue;
19181
19690
  const at = nativeTimeMs(message3.timestamp) ?? nativeTimeMs(line.timestamp);
19182
- const entry = at !== null && usageEntryFromRequest(record7.request, at);
19691
+ const entry = at !== null && usageEntryFromRequest(record9.request, at);
19183
19692
  if (!entry)
19184
19693
  continue;
19185
19694
  if (!(typeof message3.responseId === "string" && message3.responseId.length > 0)) {
@@ -19200,9 +19709,9 @@ function createPiUsageStatistics(environment) {
19200
19709
  }
19201
19710
 
19202
19711
  // dist/account-balance.js
19203
- import { readFile } from "node:fs/promises";
19204
- import { homedir as homedir2 } from "node:os";
19205
- 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";
19206
19715
  var DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
19207
19716
  var SUB2API_USAGE_PATH = "/v1/usage";
19208
19717
  var REQUEST_TIMEOUT_MS = 1e4;
@@ -19211,18 +19720,18 @@ function agentDirectory(environment) {
19211
19720
  const configured = environment.PI_CODING_AGENT_DIR?.trim();
19212
19721
  if (configured)
19213
19722
  return configured;
19214
- return path7.join(environment.HOME ?? environment.USERPROFILE ?? homedir2(), ".pi", "agent");
19723
+ return path8.join(environment.HOME ?? environment.USERPROFILE ?? homedir3(), ".pi", "agent");
19215
19724
  }
19216
- 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 : {};
19217
19726
  async function deepSeekApiKey(environment) {
19218
- const auth = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "auth.json"), "utf8")));
19219
- 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);
19220
19729
  if (deepseek.type !== "api_key")
19221
19730
  return void 0;
19222
19731
  return typeof deepseek.key === "string" && deepseek.key.trim() ? deepseek.key : void 0;
19223
19732
  }
19224
19733
  function projectSub2ApiUsage(payload, providerId) {
19225
- const data = record4(payload);
19734
+ const data = record6(payload);
19226
19735
  if (data.isValid === false)
19227
19736
  return null;
19228
19737
  if (data.mode !== "unrestricted" && data.mode !== "quota_limited")
@@ -19232,7 +19741,7 @@ function projectSub2ApiUsage(payload, providerId) {
19232
19741
  return null;
19233
19742
  const wallet = finiteAmount(data.balance);
19234
19743
  const remaining = finiteAmount(data.remaining);
19235
- const quotaRemaining = finiteAmount(record4(data.quota).remaining);
19744
+ const quotaRemaining = finiteAmount(record6(data.quota).remaining);
19236
19745
  const amount = wallet ?? remaining ?? quotaRemaining;
19237
19746
  if (amount === null)
19238
19747
  return null;
@@ -19252,10 +19761,10 @@ function finiteAmount(value) {
19252
19761
  return Number.isFinite(amount) && amount >= 0 ? amount : null;
19253
19762
  }
19254
19763
  function projectDeepSeekBalance(payload) {
19255
- const data = record4(payload);
19764
+ const data = record6(payload);
19256
19765
  if (!Array.isArray(data.balance_infos))
19257
19766
  return null;
19258
- const first = record4(data.balance_infos[0]);
19767
+ const first = record6(data.balance_infos[0]);
19259
19768
  const amount = finiteAmount(first.total_balance);
19260
19769
  const currency = typeof first.currency === "string" ? first.currency.trim() : "";
19261
19770
  if (amount === null || !currency)
@@ -19284,11 +19793,11 @@ function usageEndpoint(baseUrl) {
19284
19793
  }
19285
19794
  async function configuredSub2ApiProviders(environment) {
19286
19795
  try {
19287
- const models = record4(JSON.parse(await readFile(path7.join(agentDirectory(environment), "models.json"), "utf8")));
19288
- 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);
19289
19798
  const found = [];
19290
19799
  for (const [id, definition] of Object.entries(providers)) {
19291
- const provider = record4(definition);
19800
+ const provider = record6(definition);
19292
19801
  const apiKey = typeof provider.apiKey === "string" ? provider.apiKey.trim() : "";
19293
19802
  const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl.trim() : "";
19294
19803
  if (!id.trim() || id.length > 128 || !apiKey || !usageEndpoint(baseUrl))
@@ -19346,21 +19855,21 @@ async function fetchPiAccountBalance(input) {
19346
19855
  }
19347
19856
 
19348
19857
  // dist/pi-credential-imports.js
19349
- import { randomUUID } from "node:crypto";
19858
+ import { randomUUID as randomUUID2 } from "node:crypto";
19350
19859
  import { execFile as execFile2 } from "node:child_process";
19351
19860
  import { promisify } from "node:util";
19352
19861
  import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, lstatSync, renameSync, rmdirSync } from "node:fs";
19353
19862
  import { realpath as realpath2 } from "node:fs/promises";
19354
19863
  import os4 from "node:os";
19355
- import path9 from "node:path";
19864
+ import path10 from "node:path";
19356
19865
  import { pathToFileURL } from "node:url";
19357
19866
 
19358
19867
  // dist/command.js
19359
19868
  import fs2 from "node:fs";
19360
- import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
19361
- import path8 from "node:path";
19869
+ import { homedir as homedir4, tmpdir as tmpdir2 } from "node:os";
19870
+ import path9 from "node:path";
19362
19871
  var PI_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
19363
- 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");
19364
19873
  var piDiscoverySpec = {
19365
19874
  id: "pi",
19366
19875
  command: "pi",
@@ -19386,18 +19895,18 @@ function resolvePiExecutable(input, dependencies = {}) {
19386
19895
  return resolution?.executable ?? input.command ?? input.environment.PI_COMMAND ?? "pi";
19387
19896
  }
19388
19897
  function findPiPackageDirectory(executable) {
19389
- let directory = path8.dirname(executable);
19898
+ let directory = path9.dirname(executable);
19390
19899
  while (true) {
19391
- for (const candidate of [directory, path8.join(directory, PI_PACKAGE_PATH)]) {
19900
+ for (const candidate of [directory, path9.join(directory, PI_PACKAGE_PATH)]) {
19392
19901
  try {
19393
- 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"));
19394
19903
  if (typeof manifest === "object" && manifest !== null && "name" in manifest && manifest.name === PI_PACKAGE_NAME) {
19395
19904
  return candidate;
19396
19905
  }
19397
19906
  } catch {
19398
19907
  }
19399
19908
  }
19400
- const parent = path8.dirname(directory);
19909
+ const parent = path9.dirname(directory);
19401
19910
  if (parent === directory)
19402
19911
  return void 0;
19403
19912
  directory = parent;
@@ -19405,16 +19914,16 @@ function findPiPackageDirectory(executable) {
19405
19914
  }
19406
19915
  function findPiCliEntry(packageDirectory) {
19407
19916
  try {
19408
- 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"));
19409
19918
  if (typeof manifest !== "object" || manifest === null || !("bin" in manifest))
19410
19919
  return void 0;
19411
19920
  const bin = manifest.bin;
19412
19921
  const entry = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && "pi" in bin ? bin.pi : void 0;
19413
19922
  if (typeof entry !== "string" || !entry.trim())
19414
19923
  return void 0;
19415
- const resolved = path8.resolve(packageDirectory, entry);
19416
- const relative = path8.relative(packageDirectory, resolved);
19417
- 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()) {
19418
19927
  return void 0;
19419
19928
  }
19420
19929
  return resolved;
@@ -19423,11 +19932,11 @@ function findPiCliEntry(packageDirectory) {
19423
19932
  }
19424
19933
  }
19425
19934
  function isFilesystemRoot(cwd) {
19426
- const resolved = path8.resolve(cwd);
19427
- return resolved === path8.parse(resolved).root;
19935
+ const resolved = path9.resolve(cwd);
19936
+ return resolved === path9.parse(resolved).root;
19428
19937
  }
19429
19938
  function writableDirectory(candidate) {
19430
- if (!candidate || !path8.isAbsolute(candidate) || isFilesystemRoot(candidate))
19939
+ if (!candidate || !path9.isAbsolute(candidate) || isFilesystemRoot(candidate))
19431
19940
  return void 0;
19432
19941
  try {
19433
19942
  if (!fs2.statSync(candidate).isDirectory())
@@ -19440,19 +19949,19 @@ function writableDirectory(candidate) {
19440
19949
  }
19441
19950
  function resolvePiInspectCwd(inputCwd, environment = process.env) {
19442
19951
  if (typeof inputCwd === "string" && inputCwd.length > 0 && !isFilesystemRoot(inputCwd)) {
19443
- return path8.resolve(inputCwd);
19952
+ return path9.resolve(inputCwd);
19444
19953
  }
19445
- const candidates = [environment.USERPROFILE, environment.HOME, homedir3(), tmpdir2()];
19954
+ const candidates = [environment.USERPROFILE, environment.HOME, homedir4(), tmpdir2()];
19446
19955
  for (const candidate of candidates) {
19447
19956
  const usable = writableDirectory(candidate);
19448
19957
  if (usable)
19449
19958
  return usable;
19450
19959
  }
19451
- return inputCwd && inputCwd.length > 0 ? path8.resolve(inputCwd) : process.cwd();
19960
+ return inputCwd && inputCwd.length > 0 ? path9.resolve(inputCwd) : process.cwd();
19452
19961
  }
19453
19962
 
19454
19963
  // dist/pi-credential-imports.js
19455
- var PREFIX2 = "codexhost-account-";
19964
+ var PREFIX3 = "codexhost-account-";
19456
19965
  function object2(value) {
19457
19966
  return typeof value === "object" && value !== null && !Array.isArray(value);
19458
19967
  }
@@ -19493,7 +20002,7 @@ function describeOauth(credential) {
19493
20002
  };
19494
20003
  }
19495
20004
  function writeAuth(filename, content) {
19496
- const temporary = `${filename}.${randomUUID()}.tmp`;
20005
+ const temporary = `${filename}.${randomUUID2()}.tmp`;
19497
20006
  try {
19498
20007
  writeFileSync(temporary, content, { flag: "wx", mode: 384 });
19499
20008
  renameSync(temporary, filename);
@@ -19502,8 +20011,8 @@ function writeAuth(filename, content) {
19502
20011
  }
19503
20012
  }
19504
20013
  function removeOwnedFiles(dir) {
19505
- rmSync(path9.join(dir, "index.ts"), { force: true });
19506
- 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 });
19507
20016
  try {
19508
20017
  rmdirSync(dir);
19509
20018
  } catch {
@@ -19515,13 +20024,13 @@ async function installation(command, environment, authPath) {
19515
20024
  const cliEntry = directory ? findPiCliEntry(directory) : void 0;
19516
20025
  if (!directory || !cliEntry)
19517
20026
  throw new Error("Pi credential import requires a supported npm Pi installation");
19518
- const storage = await import(pathToFileURL(path9.join(directory, "dist/core/auth-storage.js")).href);
19519
- const ai = path9.join(directory, "node_modules/@earendil-works/pi-ai/dist");
19520
- 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);
19521
20030
  const providers = all.getBuiltinProviders();
19522
20031
  const providerModules = {
19523
- "openai-codex": pathToFileURL(path9.join(ai, "providers/openai-codex.js")).href,
19524
- 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
19525
20034
  };
19526
20035
  for (const [id, url2] of Object.entries(providerModules)) {
19527
20036
  const module = await import(url2);
@@ -19535,8 +20044,8 @@ async function installation(command, environment, authPath) {
19535
20044
  reservedNames: providers.map((p) => typeof p === "string" ? p : p.id),
19536
20045
  async configuredProviderNames() {
19537
20046
  const { stdout } = await promisify(execFile2)(process.execPath, [cliEntry, "--offline", "--no-approve", "--list-models"], {
19538
- cwd: existsSync(path9.dirname(authPath)) ? path9.dirname(authPath) : os4.homedir(),
19539
- 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" },
19540
20049
  timeout: 15e3,
19541
20050
  maxBuffer: 4 * 1024 * 1024
19542
20051
  });
@@ -19566,26 +20075,26 @@ export default async function (pi) {
19566
20075
  }
19567
20076
  function createPiCredentialImports(options = {}) {
19568
20077
  const env = { ...process.env, ...options.environment };
19569
- const agentDir = env.PI_CODING_AGENT_DIR ?? path9.join(env.HOME ?? os4.homedir(), ".pi/agent");
19570
- const authPath = path9.join(agentDir, "auth.json");
19571
- 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");
19572
20081
  const saveAuth = (auth) => (options.writeAuth ?? writeAuth)(authPath, JSON.stringify(auth, null, 2) + "\n");
19573
20082
  const resolve = () => options.resolveInstallation?.(authPath) ?? installation(options.command, env, authPath);
19574
- const location = (name) => path9.join(extensionsDir, `${PREFIX2}${credentialImportNameSchema.parse(name)}`);
20083
+ const location = (name) => path10.join(extensionsDir, `${PREFIX3}${credentialImportNameSchema.parse(name)}`);
19575
20084
  const readRecord = (name) => {
19576
20085
  const dir = location(name);
19577
20086
  if (lstatSync(dir).isSymbolicLink())
19578
20087
  throw new Error("Imported configuration was changed; manage it in Pi");
19579
- const value = JSON.parse(readFileSync(path9.join(dir, "import.json"), "utf8"));
20088
+ const value = JSON.parse(readFileSync(path10.join(dir, "import.json"), "utf8"));
19580
20089
  if (value.version !== 1 || typeof value.owner !== "string" || typeof value.extension !== "string")
19581
20090
  throw new Error("Invalid import metadata");
19582
- const record7 = value.record;
19583
- if (!object2(record7))
20091
+ const record9 = value.record;
20092
+ if (!object2(record9))
19584
20093
  throw new Error("Invalid import metadata");
19585
20094
  value.record = credentialImportRecordSchema.parse({
19586
- name: record7.name,
19587
- source: record7.source,
19588
- importedAt: record7.importedAt
20095
+ name: record9.name,
20096
+ source: record9.source,
20097
+ importedAt: record9.importedAt
19589
20098
  });
19590
20099
  if (value.record.name !== name)
19591
20100
  throw new Error("Import identity mismatch");
@@ -19593,7 +20102,7 @@ function createPiCredentialImports(options = {}) {
19593
20102
  };
19594
20103
  const owned = (meta3, auth) => {
19595
20104
  const credential = auth[meta3.record.name];
19596
- const file2 = path9.join(location(meta3.record.name), "index.ts");
20105
+ const file2 = path10.join(location(meta3.record.name), "index.ts");
19597
20106
  return existsSync(file2) && !lstatSync(file2).isSymbolicLink() && readFileSync(file2, "utf8") === meta3.extension && object2(credential) && credential.type === "oauth" && credential.codexhostImportId === meta3.owner;
19598
20107
  };
19599
20108
  const readAuth = () => existsSync(authPath) ? parseAuth(readFileSync(authPath, "utf8")) : {};
@@ -19602,12 +20111,12 @@ function createPiCredentialImports(options = {}) {
19602
20111
  return [];
19603
20112
  const result = [];
19604
20113
  for (const entry of readdirSync(extensionsDir)) {
19605
- if (!entry.startsWith(PREFIX2))
20114
+ if (!entry.startsWith(PREFIX3))
19606
20115
  continue;
19607
- const name = entry.slice(PREFIX2.length);
20116
+ const name = entry.slice(PREFIX3.length);
19608
20117
  if (!credentialImportNameSchema.safeParse(name).success)
19609
20118
  continue;
19610
- if (!existsSync(path9.join(location(name), "import.json")))
20119
+ if (!existsSync(path10.join(location(name), "import.json")))
19611
20120
  continue;
19612
20121
  try {
19613
20122
  const meta3 = readRecord(name);
@@ -19628,7 +20137,7 @@ function createPiCredentialImports(options = {}) {
19628
20137
  },
19629
20138
  async listOthers() {
19630
20139
  const auth = readAuth();
19631
- const ours = new Set(ownedRecords(auth).map((record7) => record7.name));
20140
+ const ours = new Set(ownedRecords(auth).map((record9) => record9.name));
19632
20141
  const result = /* @__PURE__ */ new Map();
19633
20142
  const usable = (provider) => Boolean(provider) && provider.length <= 128 && !ours.has(provider) && !result.has(provider);
19634
20143
  for (const [provider, credential] of Object.entries(auth)) {
@@ -19641,7 +20150,7 @@ function createPiCredentialImports(options = {}) {
19641
20150
  ...describeOauth(credential)
19642
20151
  });
19643
20152
  }
19644
- const modelsPath = path9.join(agentDir, "models.json");
20153
+ const modelsPath = path10.join(agentDir, "models.json");
19645
20154
  if (existsSync(modelsPath)) {
19646
20155
  const models = JSON.parse(readFileSync(modelsPath, "utf8"));
19647
20156
  const providers = object2(models) && object2(models.providers) ? models.providers : {};
@@ -19662,8 +20171,8 @@ function createPiCredentialImports(options = {}) {
19662
20171
  throw new Error("Unsupported credential source");
19663
20172
  if (sdk.reservedNames.includes(name) || (await sdk.configuredProviderNames?.())?.includes(name))
19664
20173
  throw new Error("Provider name already exists; choose another name");
19665
- const owner = randomUUID();
19666
- const record7 = credentialImportRecordSchema.parse({
20174
+ const owner = randomUUID2();
20175
+ const record9 = credentialImportRecordSchema.parse({
19667
20176
  name,
19668
20177
  source: transfer.source,
19669
20178
  importedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -19675,15 +20184,15 @@ function createPiCredentialImports(options = {}) {
19675
20184
  try {
19676
20185
  sdk.backend.withLock((current) => {
19677
20186
  const auth = parseAuth(current);
19678
- const modelsPath = path9.join(agentDir, "models.json");
20187
+ const modelsPath = path10.join(agentDir, "models.json");
19679
20188
  const models = existsSync(modelsPath) ? JSON.parse(readFileSync(modelsPath, "utf8")) : {};
19680
- 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`)))
19681
20190
  throw new Error("Provider name already exists; choose another name");
19682
20191
  mkdirSync(extensionsDir, { recursive: true, mode: 448 });
19683
20192
  mkdirSync(dir, { mode: 448 });
19684
20193
  created = true;
19685
- writeFileSync(path9.join(dir, "import.json"), JSON.stringify({ version: 1, owner, record: record7, extension }), { flag: "wx", mode: 384 });
19686
- 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 });
19687
20196
  auth[name] = { type: "oauth", ...transfer.oauth, codexhostImportId: owner };
19688
20197
  saveAuth(auth);
19689
20198
  committed = true;
@@ -19702,7 +20211,7 @@ function createPiCredentialImports(options = {}) {
19702
20211
  const auth = parseAuth(current);
19703
20212
  if (!owned(meta3, auth) || meta3.record.source.id !== transfer.source.id || meta3.record.source.provider !== transfer.source.provider)
19704
20213
  throw new Error("Import ownership or source account changed; refusing replacement");
19705
- const metadataPath = path9.join(location(name), "import.json");
20214
+ const metadataPath = path10.join(location(name), "import.json");
19706
20215
  const previous = readFileSync(metadataPath, "utf8");
19707
20216
  const updated = {
19708
20217
  ...meta3,
@@ -19737,10 +20246,10 @@ function createPiCredentialImports(options = {}) {
19737
20246
  }
19738
20247
 
19739
20248
  // dist/pi-fast-mode.js
19740
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
19741
- import { mkdir, readFile as readFile2, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
19742
- import { homedir as homedir4 } from "node:os";
19743
- 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";
19744
20253
  var PI_FAST_COMMAND = "codexhost-fast-mode";
19745
20254
  var PI_FAST_ACK = "codexhost-fast-mode:";
19746
20255
  var PI_FAST_EXTENSION = `export default function(pi) {
@@ -19790,24 +20299,24 @@ var PI_FAST_EXTENSION = `export default function(pi) {
19790
20299
  }
19791
20300
  `;
19792
20301
  async function ensurePiFastExtension(environment) {
19793
- const digest = createHash2("sha256").update(PI_FAST_EXTENSION).digest("hex").slice(0, 16);
19794
- const dataDirectory = environment.CODEXHOST_DATA_DIR ?? path10.join(environment.HOME ?? environment.USERPROFILE ?? homedir4(), ".codexhost");
19795
- const directory = path10.resolve(dataDirectory, "extensions", "pi-codex-fast");
19796
- const file2 = path10.join(directory, `${digest}.mjs`);
19797
- 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)
19798
20307
  return file2;
19799
- await mkdir(directory, { recursive: true });
19800
- const temporary = `${file2}.${randomUUID2()}.tmp`;
20308
+ await mkdir2(directory, { recursive: true });
20309
+ const temporary = `${file2}.${randomUUID3()}.tmp`;
19801
20310
  try {
19802
- await writeFile2(temporary, PI_FAST_EXTENSION, { mode: 384 });
20311
+ await writeFile3(temporary, PI_FAST_EXTENSION, { mode: 384 });
19803
20312
  try {
19804
- await rename(temporary, file2);
20313
+ await rename2(temporary, file2);
19805
20314
  } catch (error51) {
19806
- if (await readFile2(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
20315
+ if (await readFile3(file2, "utf8").catch(() => "") !== PI_FAST_EXTENSION)
19807
20316
  throw error51;
19808
20317
  }
19809
20318
  } finally {
19810
- await rm2(temporary, { force: true });
20319
+ await rm3(temporary, { force: true });
19811
20320
  }
19812
20321
  return file2;
19813
20322
  }
@@ -19824,15 +20333,15 @@ function withPiFast(catalog, supported) {
19824
20333
  // dist/pi-empty-session.js
19825
20334
  import { createReadStream as createReadStream3 } from "node:fs";
19826
20335
  import { createInterface as createInterface3 } from "node:readline";
19827
- import { randomUUID as randomUUID3 } from "node:crypto";
19828
- import { link, open as open2, rm as rm3 } from "node:fs/promises";
19829
- 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";
19830
20339
 
19831
20340
  // dist/pi-session-file.js
19832
20341
  import { open, realpath as realpath3 } from "node:fs/promises";
19833
20342
  var MAX_SESSION_HEADER_BYTES = 64 * 1024;
19834
20343
  var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
19835
- function isRecord7(value) {
20344
+ function isRecord8(value) {
19836
20345
  return typeof value === "object" && value !== null && !Array.isArray(value);
19837
20346
  }
19838
20347
  async function readPiSessionHeader(sessionFile) {
@@ -19852,7 +20361,7 @@ async function readPiSessionHeader(sessionFile) {
19852
20361
  } catch {
19853
20362
  throw new Error("Pi Session header is not valid JSON");
19854
20363
  }
19855
- 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) {
19856
20365
  throw new Error("Pi Session header is invalid");
19857
20366
  }
19858
20367
  return {
@@ -19885,7 +20394,7 @@ async function verifyPiSessionCwd(input) {
19885
20394
  async function persistEmptyPiSession(input) {
19886
20395
  const { state: state2, history, sourceSessionFile, sourceSessionId, cwd } = input;
19887
20396
  const destination = state2.sessionFile;
19888
- 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)
19889
20398
  throw new Error("Pi empty Session is not an independent empty native fork");
19890
20399
  await verifyPiSessionCwd({
19891
20400
  sessionFile: sourceSessionFile,
@@ -19909,7 +20418,7 @@ async function persistEmptyPiSession(input) {
19909
20418
  cwd,
19910
20419
  parentSession: sourceSessionFile
19911
20420
  };
19912
- const temporary = path11.join(path11.dirname(destination), `.codexhost-${randomUUID3()}.tmp`);
20421
+ const temporary = path12.join(path12.dirname(destination), `.codexhost-${randomUUID4()}.tmp`);
19913
20422
  try {
19914
20423
  const file2 = await open2(temporary, "wx", 384);
19915
20424
  try {
@@ -19920,7 +20429,7 @@ async function persistEmptyPiSession(input) {
19920
20429
  }
19921
20430
  await link(temporary, destination);
19922
20431
  if (process.platform !== "win32") {
19923
- const directory = await open2(path11.dirname(destination), "r");
20432
+ const directory = await open2(path12.dirname(destination), "r");
19924
20433
  try {
19925
20434
  await directory.sync();
19926
20435
  } finally {
@@ -19928,7 +20437,7 @@ async function persistEmptyPiSession(input) {
19928
20437
  }
19929
20438
  }
19930
20439
  } finally {
19931
- await rm3(temporary, { force: true });
20440
+ await rm4(temporary, { force: true });
19932
20441
  }
19933
20442
  }
19934
20443
  async function readPiEmptySessionConfiguration(sessionFile) {
@@ -19984,20 +20493,20 @@ async function readPiEmptySessionConfiguration(sessionFile) {
19984
20493
  }
19985
20494
 
19986
20495
  // dist/pi-adapter.js
19987
- import { randomUUID as randomUUID6 } from "node:crypto";
19988
- import path15 from "node:path";
20496
+ import { randomUUID as randomUUID7 } from "node:crypto";
20497
+ import path16 from "node:path";
19989
20498
 
19990
20499
  // dist/pi-workflow-child-history.js
19991
- import { createHash as createHash3 } from "node:crypto";
20500
+ import { createHash as createHash6 } from "node:crypto";
19992
20501
  import { constants } from "node:fs";
19993
20502
  import { open as open3 } from "node:fs/promises";
19994
- import path12 from "node:path";
19995
- function record5(value) {
20503
+ import path13 from "node:path";
20504
+ function record7(value) {
19996
20505
  return typeof value === "object" && value !== null && !Array.isArray(value);
19997
20506
  }
19998
20507
  var MAX_SESSION_BYTES = 8 * 1024 * 1024;
19999
- async function childHistory(file2, parentSessionId, identity) {
20000
- if (!path12.isAbsolute(file2))
20508
+ async function childHistory(file2, parentSessionId, identity, validateParent = false) {
20509
+ if (!path13.isAbsolute(file2))
20001
20510
  throw new Error("Pi child Session path is not absolute");
20002
20511
  const handle = await open3(file2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
20003
20512
  try {
@@ -20010,12 +20519,14 @@ async function childHistory(file2, parentSessionId, identity) {
20010
20519
  throw new Error("Pi child Session exceeds read bounds");
20011
20520
  const values = buffer.subarray(0, bytesRead).toString("utf8").split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
20012
20521
  const header = values[0];
20013
- 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)
20014
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");
20015
20526
  const entries = [];
20016
20527
  for (const entry of values.slice(1)) {
20017
20528
  const parsed = jsonValueSchema.safeParse(entry);
20018
- if (!parsed.success || !record5(parsed.data) || typeof parsed.data.id !== "string")
20529
+ if (!parsed.success || !record7(parsed.data) || typeof parsed.data.id !== "string")
20019
20530
  throw new Error("Malformed Pi child Session entry");
20020
20531
  entries.push(parsed.data);
20021
20532
  }
@@ -20025,7 +20536,7 @@ async function childHistory(file2, parentSessionId, identity) {
20025
20536
  model: null,
20026
20537
  ...typeof header.cwd === "string" ? { cwd: header.cwd } : {}
20027
20538
  });
20028
- const prefix = createHash3("sha256").update(identity).digest("hex");
20539
+ const prefix = createHash6("sha256").update(identity).digest("hex");
20029
20540
  return {
20030
20541
  turns: snapshot.turns.map((turn) => {
20031
20542
  const readonlyTurn = {
@@ -20046,7 +20557,7 @@ async function childHistory(file2, parentSessionId, identity) {
20046
20557
  async function readPiWorkflowChild(history, parentSessionId, address) {
20047
20558
  for (const entry of activePiEntries(history).reverse()) {
20048
20559
  const message3 = entry.message;
20049
- if (!record5(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
20560
+ if (!record7(message3) || message3.role !== "toolResult" || message3.toolName !== "subagent")
20050
20561
  continue;
20051
20562
  const summary = piWorkflowSummary(message3);
20052
20563
  if (!summary || summary.workflowRunId !== address.workflowRunId || summary.parentToolCallId !== message3.toolCallId)
@@ -20055,10 +20566,10 @@ async function readPiWorkflowChild(history, parentSessionId, address) {
20055
20566
  if (!child)
20056
20567
  break;
20057
20568
  const details = message3.details;
20058
- if (!record5(details) || !Array.isArray(details.results))
20569
+ if (!record7(details) || !Array.isArray(details.results))
20059
20570
  break;
20060
- const result = details.results.findLast((candidate) => record5(candidate) && candidate.workflowKey === address.childId);
20061
- if (!record5(result))
20571
+ const result = details.results.findLast((candidate) => record7(candidate) && candidate.workflowKey === address.childId);
20572
+ if (!record7(result))
20062
20573
  break;
20063
20574
  const id = piWorkflowSubagentId(address);
20064
20575
  if (typeof result.sessionFile === "string") {
@@ -20101,25 +20612,69 @@ ${output}`,
20101
20612
  };
20102
20613
  }
20103
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
+
20104
20659
  // dist/pi-subagent-history.js
20105
20660
  import { constants as constants2 } from "node:fs";
20106
20661
  import { open as open4 } from "node:fs/promises";
20107
- import path13 from "node:path";
20108
- function record6(value) {
20662
+ import path14 from "node:path";
20663
+ function record8(value) {
20109
20664
  return typeof value === "object" && value !== null && !Array.isArray(value);
20110
20665
  }
20111
20666
  function state(value) {
20112
20667
  return value === "pending" ? "queued" : value === "completed" ? "complete" : value;
20113
20668
  }
20114
20669
  function piSubagentArtifact(value, runId, parentSessionId) {
20115
- 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)))
20116
20671
  return null;
20117
20672
  if (value.steps !== void 0 && (!Array.isArray(value.steps) || value.steps.length > 128))
20118
20673
  return null;
20119
20674
  const steps = Array.isArray(value.steps) ? value.steps : [];
20120
20675
  const children = [];
20121
20676
  for (const [index, step] of steps.entries()) {
20122
- if (!record6(step) || typeof step.agent !== "string")
20677
+ if (!record8(step) || typeof step.agent !== "string")
20123
20678
  return null;
20124
20679
  children.push({
20125
20680
  id: step.workflowKey ?? step.runId ?? `step:${index}`,
@@ -20150,19 +20705,20 @@ function piSubagentArtifact(value, runId, parentSessionId) {
20150
20705
  });
20151
20706
  }
20152
20707
  async function restorePiSubagents(history, parentSessionId, observer) {
20708
+ restoreGotgenes(history, observer.gotgenes);
20153
20709
  const receipts = /* @__PURE__ */ new Map();
20154
20710
  for (const entry of activePiEntries(history)) {
20155
- 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))
20156
20712
  continue;
20157
20713
  const details = entry.message.details;
20158
- 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)
20159
20715
  continue;
20160
20716
  receipts.set(details.asyncId, details.asyncDir);
20161
20717
  }
20162
20718
  for (const [id, directory] of [...receipts].slice(-128)) {
20163
20719
  let file2;
20164
20720
  try {
20165
- 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));
20166
20722
  const stat2 = await file2.stat();
20167
20723
  if (!stat2.isFile() || stat2.size > 1024 * 1024)
20168
20724
  continue;
@@ -20244,8 +20800,8 @@ async function rollbackPiLastTurn(transport, sourceSessionId, cwd) {
20244
20800
 
20245
20801
  // dist/pi-rpc-session.js
20246
20802
  import { spawn, spawnSync } from "node:child_process";
20247
- import { randomUUID as randomUUID5 } from "node:crypto";
20248
- import path14 from "node:path";
20803
+ import { randomUUID as randomUUID6 } from "node:crypto";
20804
+ import path15 from "node:path";
20249
20805
 
20250
20806
  // dist/pi-slash-commands.js
20251
20807
  var DYNAMIC_ID_PREFIX = "pi.slash.";
@@ -20267,15 +20823,15 @@ function parsePiNativeCommands(response) {
20267
20823
  return data.commands.flatMap((entry) => {
20268
20824
  if (typeof entry !== "object" || entry === null)
20269
20825
  return [];
20270
- const record7 = entry;
20271
- 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, "") : "";
20272
20828
  if (!name)
20273
20829
  return [];
20274
20830
  return [
20275
20831
  {
20276
20832
  name,
20277
- ...typeof record7.description === "string" ? { description: record7.description } : {},
20278
- ...typeof record7.source === "string" ? { source: record7.source } : {}
20833
+ ...typeof record9.description === "string" ? { description: record9.description } : {},
20834
+ ...typeof record9.source === "string" ? { source: record9.source } : {}
20279
20835
  }
20280
20836
  ];
20281
20837
  });
@@ -20291,8 +20847,97 @@ function piDynamicCommandPrompt(catalog, commandId, argumentText) {
20291
20847
  return liveHarnessCommandPrompt(catalog, DYNAMIC_ID_PREFIX, commandId, argumentText);
20292
20848
  }
20293
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
+
20294
20939
  // dist/pi-subagent-rpc.js
20295
- import { randomUUID as randomUUID4 } from "node:crypto";
20940
+ import { randomUUID as randomUUID5 } from "node:crypto";
20296
20941
  var PiSubagentRpc = class {
20297
20942
  send;
20298
20943
  timeoutMs;
@@ -20334,7 +20979,7 @@ var PiSubagentRpc = class {
20334
20979
  if (!Array.isArray(data?.commands) || !data.commands.some((command) => command?.name === "subagents-inspect-rpc" && command.source === "extension")) {
20335
20980
  throw new Error("Installed Pi has no pi-subagents Host inspection command");
20336
20981
  }
20337
- const requestId2 = randomUUID4();
20982
+ const requestId2 = randomUUID5();
20338
20983
  const reply = new Promise((resolve, reject) => {
20339
20984
  const timer = setTimeout(() => {
20340
20985
  this.#pending.delete(requestId2);
@@ -20368,6 +21013,12 @@ var PiSubagentRpc = class {
20368
21013
  };
20369
21014
 
20370
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
+ };
20371
21022
  var PiRpcFaultError = class extends Error {
20372
21023
  kind;
20373
21024
  diagnostic;
@@ -20395,8 +21046,11 @@ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
20395
21046
  "get_available_thinking_levels"
20396
21047
  ]);
20397
21048
  var MAX_EXPIRED_IDS = 64;
21049
+ function nativeMessageIdentity(active) {
21050
+ return active.assistantNativeMessageIdentity ? { nativeMessageIdentity: active.assistantNativeMessageIdentity } : {};
21051
+ }
20398
21052
  var textDecoder = new TextDecoder("utf-8", { fatal: true });
20399
- function isRecord8(value) {
21053
+ function isRecord9(value) {
20400
21054
  return typeof value === "object" && value !== null && !Array.isArray(value);
20401
21055
  }
20402
21056
  function message2(value) {
@@ -20408,13 +21062,13 @@ function nonBlankString(value) {
20408
21062
  function parseNativeModel(value, context) {
20409
21063
  if (value === null || value === void 0)
20410
21064
  return null;
20411
- if (!isRecord8(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
21065
+ if (!isRecord9(value) || !nonBlankString(value.provider) || !nonBlankString(value.id)) {
20412
21066
  throw new PiRpcFaultError("protocolError", `Pi RPC returned an invalid ${context} Model`);
20413
21067
  }
20414
21068
  return { provider: value.provider, id: value.id };
20415
21069
  }
20416
21070
  function sessionStateData(response) {
20417
- const data = isRecord8(response.data) ? response.data : null;
21071
+ const data = isRecord9(response.data) ? response.data : null;
20418
21072
  if (!data)
20419
21073
  throw new PiRpcFaultError("protocolError", "Pi RPC state response has no data");
20420
21074
  return data;
@@ -20422,7 +21076,7 @@ function sessionStateData(response) {
20422
21076
  function parseSessionState(response) {
20423
21077
  const data = sessionStateData(response);
20424
21078
  const model2 = parseNativeModel(data.model, "state");
20425
- 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;
20426
21080
  if (!nonBlankString(data.sessionId)) {
20427
21081
  throw new PiRpcFaultError("protocolError", "Pi RPC state has no stable Session identity");
20428
21082
  }
@@ -20448,13 +21102,13 @@ function parseSessionStreaming(response) {
20448
21102
  return isStreaming;
20449
21103
  }
20450
21104
  function parseSessionHistory(response) {
20451
- const data = isRecord8(response.data) ? response.data : null;
21105
+ const data = isRecord9(response.data) ? response.data : null;
20452
21106
  if (!data || !Array.isArray(data.entries)) {
20453
21107
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response has no Entries");
20454
21108
  }
20455
21109
  const entries = data.entries.map((entry) => {
20456
21110
  const parsed = jsonValueSchema.safeParse(entry);
20457
- if (!parsed.success || !isRecord8(parsed.data)) {
21111
+ if (!parsed.success || !isRecord9(parsed.data)) {
20458
21112
  throw new PiRpcFaultError("protocolError", "Pi RPC entries response contains an invalid Entry");
20459
21113
  }
20460
21114
  return parsed.data;
@@ -20465,7 +21119,7 @@ function parseSessionHistory(response) {
20465
21119
  return { entries, leafId: data.leafId };
20466
21120
  }
20467
21121
  function parseAvailableThinkingLevels(response) {
20468
- const data = isRecord8(response.data) ? response.data : null;
21122
+ const data = isRecord9(response.data) ? response.data : null;
20469
21123
  if (!data || !Array.isArray(data.levels) || data.levels.length === 0) {
20470
21124
  throw new PiRpcFaultError("protocolError", "Pi RPC Thinking catalog response has no levels");
20471
21125
  }
@@ -20482,13 +21136,13 @@ function parseAvailableThinkingLevels(response) {
20482
21136
  return levels;
20483
21137
  }
20484
21138
  function parseAvailableModels(response) {
20485
- const data = isRecord8(response.data) ? response.data : null;
21139
+ const data = isRecord9(response.data) ? response.data : null;
20486
21140
  if (!data || !Array.isArray(data.models)) {
20487
21141
  throw new PiRpcFaultError("protocolError", "Pi RPC Model catalog response has no models");
20488
21142
  }
20489
21143
  return data.models.map((model2) => {
20490
21144
  const parsed = parseNativeModel(model2, "catalog");
20491
- if (!parsed || !isRecord8(model2) || typeof model2.reasoning !== "boolean") {
21145
+ if (!parsed || !isRecord9(model2) || typeof model2.reasoning !== "boolean") {
20492
21146
  throw new PiRpcFaultError("protocolError", "Pi RPC catalog contains a Model without reasoning capability");
20493
21147
  }
20494
21148
  return {
@@ -20499,32 +21153,32 @@ function parseAvailableModels(response) {
20499
21153
  });
20500
21154
  }
20501
21155
  function assistantText(value) {
20502
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21156
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20503
21157
  return null;
20504
- 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("");
20505
21159
  }
20506
21160
  function assistantMessageId(value) {
20507
- if (!isRecord8(value) || value.role !== "assistant")
21161
+ if (!isRecord9(value) || value.role !== "assistant")
20508
21162
  return null;
20509
21163
  return nonBlankString(value.responseId) ? value.responseId : null;
20510
21164
  }
20511
21165
  function extractReasoningText(content) {
20512
- if (!isRecord8(content))
21166
+ if (!isRecord9(content))
20513
21167
  return null;
20514
21168
  const type = String(content.type ?? "");
20515
21169
  if (type === "thinking" || type === "reasoning" || type === "thought") {
20516
- const text2 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
20517
- return typeof text2 === "string" ? text2 : null;
21170
+ const text3 = content.thinking ?? content.reasoning ?? content.text ?? content.delta;
21171
+ return typeof text3 === "string" ? text3 : null;
20518
21172
  }
20519
21173
  return null;
20520
21174
  }
20521
21175
  function assistantReasoning(value) {
20522
- if (!isRecord8(value) || value.role !== "assistant" || !Array.isArray(value.content))
21176
+ if (!isRecord9(value) || value.role !== "assistant" || !Array.isArray(value.content))
20523
21177
  return null;
20524
- return value.content.map(extractReasoningText).filter((text2) => typeof text2 === "string").join("");
21178
+ return value.content.map(extractReasoningText).filter((text3) => typeof text3 === "string").join("");
20525
21179
  }
20526
21180
  function assistantFailure(value) {
20527
- if (!isRecord8(value) || value.role !== "assistant")
21181
+ if (!isRecord9(value) || value.role !== "assistant")
20528
21182
  return void 0;
20529
21183
  if (value.stopReason !== "error" && value.stopReason !== "aborted")
20530
21184
  return null;
@@ -20544,7 +21198,7 @@ function signalProcessTree(child, signal) {
20544
21198
  try {
20545
21199
  process.kill(-child.pid, signal);
20546
21200
  } catch (error51) {
20547
- if (!isRecord8(error51) || error51.code !== "ESRCH")
21201
+ if (!isRecord9(error51) || error51.code !== "ESRCH")
20548
21202
  throw error51;
20549
21203
  }
20550
21204
  }
@@ -20581,13 +21235,14 @@ function piRpcProcessCommand(options, dependencies = {}) {
20581
21235
  const thinkingArguments = options.emptySessionConfiguration ? ["--thinking", options.emptySessionConfiguration.thinkingLevel] : [];
20582
21236
  const arguments_ = [
20583
21237
  ...options.fastExtension ? ["--extension", options.fastExtension] : [],
21238
+ ...options.subagentExtension ? ["--extension", options.subagentExtension] : [],
20584
21239
  "--mode",
20585
21240
  "rpc",
20586
21241
  ...modelArguments,
20587
21242
  ...thinkingArguments,
20588
21243
  ...sessionArguments
20589
21244
  ];
20590
- const extension = path14.win32.extname(command).toLowerCase();
21245
+ const extension = path15.win32.extname(command).toLowerCase();
20591
21246
  if (platform !== "win32" || ![".cmd", ".bat"].includes(extension)) {
20592
21247
  return { command, arguments: arguments_, windowsVerbatimArguments: false };
20593
21248
  }
@@ -20616,7 +21271,13 @@ var PiRpcSession = class {
20616
21271
  #options;
20617
21272
  #processAdapter;
20618
21273
  #activeTurn = null;
21274
+ #runGeneration = 0;
21275
+ #deferredRunFrames = [];
21276
+ #deferredRunBytes = 0;
21277
+ #runWaiters = /* @__PURE__ */ new Set();
21278
+ #messageTimestampCounts = /* @__PURE__ */ new Map();
20619
21279
  #autonomousTurnHandler = null;
21280
+ #autonomousLifecycleHandler = null;
20620
21281
  #usageHandler = null;
20621
21282
  #usageRequestStartedAtMs = null;
20622
21283
  // Pieces of the unterminated frame; joined once at its newline so a large frame (a long
@@ -20636,8 +21297,15 @@ var PiRpcSession = class {
20636
21297
  #fastAcknowledgement = null;
20637
21298
  #latestCacheHitRatePercent;
20638
21299
  #manualCompaction = null;
21300
+ #noticeOccurrences = /* @__PURE__ */ new Map();
21301
+ #seenNoticeFrames = /* @__PURE__ */ new Set();
21302
+ #pendingProgress = [];
21303
+ #omittedProgress = 0;
21304
+ #extensionStatuses = /* @__PURE__ */ new Map();
20639
21305
  #stderrTail = "";
20640
21306
  #subagents;
21307
+ #gotgenesHandler;
21308
+ #gotgenesLatest;
20641
21309
  constructor(options, processAdapter = nodeProcessAdapter) {
20642
21310
  if (options.sessionFile && options.forkSessionFile) {
20643
21311
  throw new Error("Pi RPC cannot combine Session resume and Fork startup");
@@ -20667,9 +21335,17 @@ var PiRpcSession = class {
20667
21335
  get stderrTail() {
20668
21336
  return this.#stderrTail;
20669
21337
  }
21338
+ get isBusy() {
21339
+ return this.#activeTurn !== null || this.#manualCompaction !== null || this.#compactionActive || this.#deferredRunFrames.length > 0;
21340
+ }
20670
21341
  setSubagentStatusHandler(handler) {
20671
21342
  this.#subagents.setHandler(handler);
20672
21343
  }
21344
+ setGotgenesStatusHandler(handler) {
21345
+ this.#gotgenesHandler = handler;
21346
+ if (this.#gotgenesLatest)
21347
+ handler(this.#gotgenesLatest, "idle");
21348
+ }
20673
21349
  inspectSubagent(id) {
20674
21350
  return this.#subagents.inspect(id);
20675
21351
  }
@@ -20679,17 +21355,18 @@ var PiRpcSession = class {
20679
21355
  /** Every finished assistant message is one model request, with or without an active Turn. */
20680
21356
  #observeUsage(value) {
20681
21357
  if (value.type === "message_start") {
20682
- this.#usageRequestStartedAtMs = null;
21358
+ if (isRecord9(value.message) && value.message.role === "assistant")
21359
+ this.#usageRequestStartedAtMs = null;
20683
21360
  return;
20684
21361
  }
20685
21362
  if (value.type === "message_update") {
20686
21363
  const event = value.assistantMessageEvent;
20687
- 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)) {
20688
21365
  this.#usageRequestStartedAtMs = Date.now();
20689
21366
  }
20690
21367
  return;
20691
21368
  }
20692
- if (value.type === "message_end" && isRecord8(value.message)) {
21369
+ if (value.type === "message_end" && isRecord9(value.message)) {
20693
21370
  if (value.message.role !== "assistant")
20694
21371
  return;
20695
21372
  const startedAtMs = this.#usageRequestStartedAtMs;
@@ -20703,14 +21380,21 @@ var PiRpcSession = class {
20703
21380
  }
20704
21381
  setAutonomousTurnHandler(handler) {
20705
21382
  this.#autonomousTurnHandler = handler;
21383
+ this.#autonomousLifecycleHandler = null;
21384
+ }
21385
+ setAutonomousTurnLifecycleHandler(handler) {
21386
+ this.#autonomousLifecycleHandler = handler;
21387
+ this.#autonomousTurnHandler = null;
20706
21388
  }
20707
21389
  async start() {
20708
21390
  if (this.#child || this.#closed)
20709
21391
  throw new Error("Pi RPC Session cannot be started twice");
20710
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;
20711
21394
  const child = this.#processAdapter.spawn({
20712
21395
  cwd: this.#options.cwd,
20713
21396
  ...fastExtension ? { fastExtension } : {},
21397
+ ...subagentExtension ? { subagentExtension } : {},
20714
21398
  ...this.#options.command ? { command: this.#options.command } : {},
20715
21399
  environment: withNodeRuntimeOnPath({
20716
21400
  ...process.env,
@@ -20734,7 +21418,7 @@ var PiRpcSession = class {
20734
21418
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
20735
21419
  });
20736
21420
  child.once("error", (error51) => {
20737
- const kind = isRecord8(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
21421
+ const kind = isRecord9(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
20738
21422
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
20739
21423
  });
20740
21424
  child.once("exit", (code, signal) => {
@@ -20751,6 +21435,7 @@ var PiRpcSession = class {
20751
21435
  ]);
20752
21436
  try {
20753
21437
  this.#state = parseSessionState(await this.#send("get_state", {}));
21438
+ await this.getEntries();
20754
21439
  } catch (error51) {
20755
21440
  const fault = error51 instanceof PiRpcFaultError ? error51 : new PiRpcFaultError("unavailable", `Pi RPC state unavailable: ${message2(error51)}`);
20756
21441
  this.#fail(fault);
@@ -20764,7 +21449,12 @@ var PiRpcSession = class {
20764
21449
  }
20765
21450
  async getEntries() {
20766
21451
  try {
20767
- 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;
20768
21458
  } catch (error51) {
20769
21459
  if (error51 instanceof PiRpcFaultError)
20770
21460
  this.#fail(error51);
@@ -20824,11 +21514,15 @@ var PiRpcSession = class {
20824
21514
  if (entryId.length === 0)
20825
21515
  throw new Error("Pi Fork Entry ID must not be empty");
20826
21516
  await this.#send("fork", { entryId });
20827
- return this.#refreshState("Fork");
21517
+ const state2 = await this.#refreshState("Fork");
21518
+ await this.getEntries();
21519
+ return state2;
20828
21520
  }
20829
21521
  async clone() {
20830
21522
  await this.#send("clone", {});
20831
- return this.#refreshState("Clone");
21523
+ const state2 = await this.#refreshState("Clone");
21524
+ await this.getEntries();
21525
+ return state2;
20832
21526
  }
20833
21527
  verifySessionCwd(expectedCwd) {
20834
21528
  return verifyPiSessionCwd({
@@ -20865,7 +21559,7 @@ var PiRpcSession = class {
20865
21559
  return this.state;
20866
21560
  if (!await this.supportsFastMode())
20867
21561
  throw new Error("Installed Pi does not support the Host Fast extension");
20868
- const nonce = randomUUID5();
21562
+ const nonce = randomUUID6();
20869
21563
  const mode = enabled ? "on" : "off";
20870
21564
  const acknowledgement = { message: `${PI_FAST_ACK}${nonce}:${mode}`, received: false };
20871
21565
  this.#fastAcknowledgement = acknowledgement;
@@ -20905,22 +21599,27 @@ var PiRpcSession = class {
20905
21599
  throw fault;
20906
21600
  }
20907
21601
  }
20908
- async runTurn(text2, onEvent) {
21602
+ async runTurn(text3, onEvent) {
20909
21603
  if (!this.#child || !this.#state || this.#closed || this.#failed) {
20910
21604
  throw new Error("Pi RPC Session is unavailable");
20911
21605
  }
20912
- if (this.#activeTurn)
20913
- throw new Error("Pi RPC Session already has an active Turn");
20914
- if (text2.length === 0)
21606
+ if (this.isBusy)
21607
+ throw new PiRpcBusyError();
21608
+ if (text3.length === 0)
20915
21609
  throw new Error("Pi text Turn must not be empty");
20916
21610
  const settled = new Promise((resolve, reject) => {
20917
21611
  this.#activeTurn = {
20918
21612
  origin: "requested",
21613
+ autonomousRunId: null,
21614
+ runGeneration: this.#runGeneration,
20919
21615
  autonomousEvents: null,
20920
21616
  nativeTurnKey: null,
20921
21617
  nativeCancellationObserved: false,
20922
21618
  text: "",
20923
21619
  assistantMessageId: null,
21620
+ assistantNativeMessageIdentity: void 0,
21621
+ textStream: new PiContentStream("text"),
21622
+ reasoningStream: new PiContentStream("reasoning"),
20924
21623
  sawStreamedMessageText: false,
20925
21624
  sawStreamedMessageReasoning: false,
20926
21625
  lastFinalizedMessageText: null,
@@ -20940,7 +21639,8 @@ var PiRpcSession = class {
20940
21639
  };
20941
21640
  });
20942
21641
  try {
20943
- await this.#send("prompt", { message: text2 });
21642
+ this.#drainProgress(onEvent);
21643
+ await this.#send("prompt", { message: text3 });
20944
21644
  } catch (error51) {
20945
21645
  this.#rejectActiveTurn(error51 instanceof Error ? error51 : new Error(message2(error51)));
20946
21646
  }
@@ -21012,6 +21712,10 @@ var PiRpcSession = class {
21012
21712
  void this.close().catch(() => void 0);
21013
21713
  }
21014
21714
  close() {
21715
+ this.#pendingProgress = [];
21716
+ this.#omittedProgress = 0;
21717
+ this.#seenNoticeFrames.clear();
21718
+ this.#extensionStatuses.clear();
21015
21719
  if (!this.#closed) {
21016
21720
  this.#closed = true;
21017
21721
  this.#rejectAll(new Error("Pi RPC Session closed"));
@@ -21045,19 +21749,25 @@ var PiRpcSession = class {
21045
21749
  rest = rest.subarray(newline + 1);
21046
21750
  try {
21047
21751
  const value = JSON.parse(textDecoder.decode(frame));
21048
- if (!isRecord8(value) || typeof value.type !== "string") {
21752
+ if (!isRecord9(value) || typeof value.type !== "string") {
21049
21753
  throw new PiRpcFaultError("protocolError", "Pi RPC returned an invalid envelope");
21050
21754
  }
21051
21755
  this.#handle(value);
21052
21756
  } catch (error51) {
21053
- 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)}`));
21054
21758
  }
21055
21759
  newline = rest.indexOf(10);
21056
21760
  }
21057
21761
  if (rest.length !== 0)
21058
21762
  this.#buffer.push(rest);
21059
21763
  }
21060
- #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;
21061
21771
  if (value.type === "extension_ui_request" && value.method === "notify" && typeof value.message === "string" && value.message.startsWith(PI_FAST_ACK)) {
21062
21772
  if (this.#fastAcknowledgement?.message === value.message)
21063
21773
  this.#fastAcknowledgement.received = true;
@@ -21071,6 +21781,33 @@ var PiRpcSession = class {
21071
21781
  }
21072
21782
  if (this.#subagents.handle(value))
21073
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;
21074
21811
  this.#observeUsage(value);
21075
21812
  if (value.type === "compaction_start") {
21076
21813
  this.#compactionActive = true;
@@ -21094,7 +21831,7 @@ var PiRpcSession = class {
21094
21831
  this.#armCommandTimeout(id, pending);
21095
21832
  }
21096
21833
  }
21097
- const outcome = value.aborted === true ? "cancelled" : isRecord8(value.result) ? "succeeded" : "failed";
21834
+ const outcome = value.aborted === true ? "cancelled" : isRecord9(value.result) ? "succeeded" : "failed";
21098
21835
  const event = {
21099
21836
  type: "compaction.completed",
21100
21837
  outcome,
@@ -21111,8 +21848,8 @@ var PiRpcSession = class {
21111
21848
  return;
21112
21849
  }
21113
21850
  let active = this.#activeTurn;
21114
- if (!active && !this.#manualCompaction && !this.#compactionActive && this.#autonomousTurnHandler && value.type === "message_start" && assistantText(value.message) !== null) {
21115
- 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);
21116
21853
  }
21117
21854
  if (!active) {
21118
21855
  if (value.type === "extension_ui_request" && this.#isBlockingInteraction(value)) {
@@ -21132,22 +21869,26 @@ var PiRpcSession = class {
21132
21869
  this.#startAssistantMessage(active, value.message);
21133
21870
  return;
21134
21871
  }
21135
- if (value.type === "message_update" && isRecord8(value.assistantMessageEvent)) {
21872
+ if (value.type === "message_update" && isRecord9(value.assistantMessageEvent)) {
21136
21873
  const event = value.assistantMessageEvent;
21137
21874
  const eventType = String(event.type ?? "");
21138
21875
  const isThinking = eventType === "thinking_delta" || eventType === "reasoning_delta" || eventType === "thought_delta" || eventType === "thinking" || eventType === "reasoning";
21139
21876
  const isText = eventType === "text_delta" || eventType === "text" || eventType === "content_block_delta";
21140
- 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;
21141
- if (isThinking && delta !== null && delta.length > 0) {
21142
- const messageId = this.#ensureAssistantMessage(active, value.message);
21143
- active.reasoningMessageOpen = true;
21144
- active.sawStreamedMessageReasoning = true;
21145
- active.onEvent({ type: "reasoning.delta", messageId, delta });
21146
- } else if (isText && delta !== null && delta.length > 0) {
21147
- const messageId = this.#ensureAssistantMessage(active, value.message);
21148
- active.text += delta;
21149
- active.sawStreamedMessageText = true;
21150
- 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));
21151
21892
  } else if (event.type === "error") {
21152
21893
  this.#ensureAssistantMessage(active, value.message);
21153
21894
  active.failure = assistantFailure(event.error) ?? assistantFailure(value.message) ?? new Error("Pi assistant message failed");
@@ -21178,25 +21919,36 @@ var PiRpcSession = class {
21178
21919
  if (active.settlement !== "pending")
21179
21920
  return;
21180
21921
  active.settlement = "confirming";
21181
- void this.#confirmSettledTurn(active);
21922
+ void this.#confirmSettledTurn(active, active.runGeneration);
21182
21923
  }
21183
21924
  }
21184
- #startAutonomousTurn(value) {
21925
+ #startAutonomousTurn(value, generation) {
21185
21926
  const events = [];
21927
+ const runId = randomUUID6();
21186
21928
  const active = {
21187
21929
  origin: "autonomous",
21930
+ autonomousRunId: runId,
21931
+ runGeneration: generation,
21188
21932
  autonomousEvents: events,
21189
- ...isRecord8(value) ? { autonomousMessage: value } : {},
21933
+ ...isRecord9(value) ? { autonomousMessage: value } : {},
21190
21934
  nativeTurnKey: null,
21191
21935
  nativeCancellationObserved: false,
21192
21936
  text: "",
21193
21937
  assistantMessageId: null,
21938
+ assistantNativeMessageIdentity: void 0,
21939
+ textStream: new PiContentStream("text"),
21940
+ reasoningStream: new PiContentStream("reasoning"),
21194
21941
  sawStreamedMessageText: false,
21195
21942
  sawStreamedMessageReasoning: false,
21196
21943
  lastFinalizedMessageText: null,
21197
21944
  lastFinalizedMessageReasoning: null,
21198
21945
  reasoningMessageOpen: false,
21199
- 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
+ },
21200
21952
  resolve: () => void 0,
21201
21953
  reject: () => void 0,
21202
21954
  failure: null,
@@ -21209,19 +21961,108 @@ var PiRpcSession = class {
21209
21961
  abortPromise: null
21210
21962
  };
21211
21963
  this.#activeTurn = active;
21964
+ this.#autonomousLifecycleHandler?.({ type: "started", runId });
21965
+ this.#drainProgress(active.onEvent);
21212
21966
  return active;
21213
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
+ }
21214
22047
  #emitAutonomousTurn(active, result) {
21215
22048
  const handler = this.#autonomousTurnHandler;
21216
- if (active.origin !== "autonomous" || !active.autonomousEvents || !handler) {
22049
+ if (active.origin !== "autonomous" || !active.autonomousEvents || !active.autonomousRunId) {
21217
22050
  return;
21218
22051
  }
21219
22052
  try {
21220
- handler({
22053
+ const turn = {
21221
22054
  nativeTurnKey: active.nativeTurnKey,
21222
22055
  events: [...active.autonomousEvents],
21223
22056
  result
21224
- });
22057
+ };
22058
+ if (this.#autonomousLifecycleHandler)
22059
+ this.#autonomousLifecycleHandler({
22060
+ type: "completed",
22061
+ runId: active.autonomousRunId,
22062
+ turn
22063
+ });
22064
+ else
22065
+ handler?.(turn);
21225
22066
  } catch (error51) {
21226
22067
  this.#fail(new PiRpcFaultError("protocolError", `Pi autonomous Turn handler failed: ${message2(error51)}`));
21227
22068
  }
@@ -21368,31 +22209,73 @@ var PiRpcSession = class {
21368
22209
  isError: value.isError
21369
22210
  });
21370
22211
  }
21371
- 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) {
21372
22249
  try {
21373
22250
  const response = await this.#send("get_state", {});
21374
22251
  const state2 = parseSessionState(response);
21375
- if (parseSessionStreaming(response)) {
21376
- throw new PiRpcFaultError("protocolError", "Pi RPC agent_settled state is still Streaming");
21377
- }
21378
- if (this.#activeTurn !== active)
22252
+ if (!this.#isSettlementCurrent(active, generation))
22253
+ return;
22254
+ if (parseSessionStreaming(response))
22255
+ await this.#waitForNextRun(generation);
22256
+ if (!this.#isSettlementCurrent(active, generation))
21379
22257
  return;
21380
- if (active.origin === "autonomous") {
22258
+ if (active.origin === "autonomous" && active.autonomousMessage) {
21381
22259
  const history = await this.getEntries();
21382
22260
  const snapshot = mapPiSnapshot(history, { sessionId: state2.sessionId, model: null });
21383
- const turn = snapshot.turns.at(-1);
22261
+ if (!this.#isSettlementCurrent(active, generation))
22262
+ return;
21384
22263
  const entries = activePiEntries(history);
21385
- const start = entries.findIndex((entry) => entry.id === turn?.nativeTurnRef.nativeTurnKey);
21386
- const firstAssistant = entries.slice(start + 1).find((entry) => isRecord8(entry.message) && entry.message.role === "assistant")?.message;
21387
22264
  const live = active.autonomousMessage;
21388
22265
  const responseId = assistantMessageId(live);
21389
- const matches = isRecord8(firstAssistant) && (responseId ? assistantMessageId(firstAssistant) === responseId : typeof live?.timestamp === "number" && firstAssistant.timestamp === live.timestamp);
21390
- 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)
21391
22275
  throw new PiRpcFaultError("protocolError", "Pi autonomous Turn has no matching persisted custom Entry");
21392
- }
21393
22276
  active.nativeTurnKey = turn.nativeTurnRef.nativeTurnKey;
21394
22277
  }
21395
- if (this.#activeTurn !== active)
22278
+ if (!this.#isSettlementCurrent(active, generation))
21396
22279
  return;
21397
22280
  this.#state = state2;
21398
22281
  active.settlement = "confirmed";
@@ -21418,7 +22301,13 @@ var PiRpcSession = class {
21418
22301
  }
21419
22302
  this.#activeTurn = null;
21420
22303
  if (active.origin === "autonomous") {
21421
- 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) {
21422
22311
  this.#emitAutonomousTurn(active, active.nativeCancellationObserved ? {
21423
22312
  status: "cancelled",
21424
22313
  text: active.text,
@@ -21433,6 +22322,7 @@ var PiRpcSession = class {
21433
22322
  } else {
21434
22323
  this.#emitAutonomousTurn(active, { status: "succeeded", text: active.text });
21435
22324
  }
22325
+ this.#drainDeferredRunFrames();
21436
22326
  return;
21437
22327
  }
21438
22328
  if (active.cancellation === "accepted") {
@@ -21444,20 +22334,56 @@ var PiRpcSession = class {
21444
22334
  } else {
21445
22335
  active.resolve({ text: active.text, cancelled: false });
21446
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
+ });
21447
22358
  }
21448
22359
  #startAssistantMessage(active, value) {
22360
+ if (active.origin === "autonomous" && !active.autonomousMessage && isRecord9(value))
22361
+ active.autonomousMessage = value;
21449
22362
  if (active.assistantMessageId !== null && active.reasoningMessageOpen) {
21450
22363
  active.onEvent({ type: "reasoning.completed", messageId: active.assistantMessageId });
21451
22364
  }
21452
- const messageId = assistantMessageId(value) ?? randomUUID5();
22365
+ const nativeResponseId = assistantMessageId(value);
22366
+ const messageId = nativeResponseId ?? randomUUID6();
21453
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");
21454
22371
  active.sawStreamedMessageText = false;
21455
22372
  active.sawStreamedMessageReasoning = false;
21456
22373
  active.reasoningMessageOpen = false;
21457
22374
  return messageId;
21458
22375
  }
21459
22376
  #ensureAssistantMessage(active, value) {
21460
- 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;
21461
22387
  }
21462
22388
  #finalizeAssistantMessage(active, value) {
21463
22389
  const finalText = assistantText(value);
@@ -21470,29 +22396,33 @@ var PiRpcSession = class {
21470
22396
  return;
21471
22397
  }
21472
22398
  active.failure = failure;
21473
- if (active.origin === "autonomous" && isRecord8(value) && value.stopReason === "aborted") {
22399
+ if (active.origin === "autonomous" && piAssistantWasAborted(value)) {
21474
22400
  active.nativeCancellationObserved = true;
21475
22401
  }
21476
22402
  this.#latestCacheHitRatePercent = cacheHitRatePercent;
21477
22403
  const messageId = this.#ensureAssistantMessage(active, value);
21478
- if (!active.sawStreamedMessageReasoning && finalReasoning.length > 0) {
21479
- active.reasoningMessageOpen = true;
21480
- 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
+ })));
21481
22410
  }
21482
22411
  if (active.reasoningMessageOpen && active.failure === null) {
21483
22412
  active.onEvent({ type: "reasoning.completed", messageId });
21484
22413
  }
21485
- if (!active.sawStreamedMessageText && finalText.length > 0) {
21486
- active.text += finalText;
21487
- 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 }] : [])));
21488
22416
  }
21489
22417
  active.assistantMessageId = null;
22418
+ active.assistantNativeMessageIdentity = void 0;
21490
22419
  active.sawStreamedMessageText = false;
21491
22420
  active.sawStreamedMessageReasoning = false;
21492
22421
  active.reasoningMessageOpen = false;
21493
22422
  active.lastFinalizedMessageText = finalText;
21494
22423
  active.lastFinalizedMessageReasoning = finalReasoning;
21495
- active.onEvent({ type: "message.completed", messageId });
22424
+ const phase = piAssistantPhase(value);
22425
+ active.onEvent({ type: "message.completed", messageId, ...phase ? { phase } : {} });
21496
22426
  }
21497
22427
  #write(value) {
21498
22428
  const child = this.#child;
@@ -21510,7 +22440,7 @@ var PiRpcSession = class {
21510
22440
  if (!child?.stdin.writable || this.#closed || this.#failed) {
21511
22441
  return Promise.reject(new Error("Pi RPC stdin is unavailable"));
21512
22442
  }
21513
- const id = `codexhost-${randomUUID5()}`;
22443
+ const id = `codexhost-${randomUUID6()}`;
21514
22444
  return new Promise((resolve, reject) => {
21515
22445
  const pending = {
21516
22446
  command: type,
@@ -21600,9 +22530,16 @@ var PiRpcSession = class {
21600
22530
  } else {
21601
22531
  active.reject(error51);
21602
22532
  }
22533
+ this.#drainDeferredRunFrames();
21603
22534
  }
21604
22535
  #rejectAll(error51) {
22536
+ for (const waiter of this.#runWaiters)
22537
+ waiter.reject(error51);
22538
+ this.#deferredRunFrames = [];
22539
+ this.#deferredRunBytes = 0;
21605
22540
  this.#subagents.close(error51);
22541
+ this.#gotgenesHandler = void 0;
22542
+ this.#gotgenesLatest = void 0;
21606
22543
  for (const pending of this.#pending.values()) {
21607
22544
  if (pending.timeout)
21608
22545
  clearTimeout(pending.timeout);
@@ -21638,7 +22575,7 @@ var piCommandCatalog = harnessCommandCatalogSchema.parse({
21638
22575
  ]
21639
22576
  });
21640
22577
  var DEFAULT_TOOL_OUTPUT_LIMIT = 64e3;
21641
- function isRecord9(value) {
22578
+ function isRecord10(value) {
21642
22579
  return typeof value === "object" && value !== null && !Array.isArray(value);
21643
22580
  }
21644
22581
  function errorMessage(error51) {
@@ -21653,7 +22590,9 @@ var PiAdapterFaultError = class extends Error {
21653
22590
  }
21654
22591
  };
21655
22592
  function normalizedError(error51, fallbackCode) {
21656
- 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") {
21657
22596
  return { code: "notInstalled", message: errorMessage(error51), retryable: false };
21658
22597
  }
21659
22598
  if (error51 instanceof PiAdapterFaultError)
@@ -21716,7 +22655,7 @@ function nativeModelForHistory(state2) {
21716
22655
  return nativeModelFromState(state2);
21717
22656
  }
21718
22657
  function sessionFileFromRef(ref) {
21719
- 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) {
21720
22659
  throw new Error("Pi Native Session Ref has no resumable Session file");
21721
22660
  }
21722
22661
  return ref.locator.sessionFile;
@@ -21731,83 +22670,29 @@ function toolFailure(toolName) {
21731
22670
  function nativeText(value) {
21732
22671
  if (typeof value === "string")
21733
22672
  return value;
21734
- if (!isRecord9(value) || !Array.isArray(value.content))
22673
+ if (!isRecord10(value) || !Array.isArray(value.content))
21735
22674
  return "";
21736
- 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("");
21737
22676
  }
21738
22677
  function boundedOutput(value, limit) {
21739
- const text2 = nativeText(value);
21740
- if (text2.length === 0)
22678
+ const text3 = nativeText(value);
22679
+ if (text3.length === 0)
21741
22680
  return void 0;
21742
- const truncated = text2.length > limit;
22681
+ const truncated = text3.length > limit;
21743
22682
  return {
21744
- content: [{ type: "text", text: truncated ? text2.slice(0, limit) : text2 }],
22683
+ content: [{ type: "text", text: truncated ? text3.slice(0, limit) : text3 }],
21745
22684
  ...truncated ? { truncated: true } : {}
21746
22685
  };
21747
22686
  }
21748
22687
  function outputText(output) {
21749
- return output?.content.filter((content) => content.type === "text").map(({ text: text2 }) => text2).join("") ?? "";
21750
- }
21751
- function stringField(value, key) {
21752
- if (!isRecord9(value))
21753
- return void 0;
21754
- const field2 = value[key];
21755
- if (typeof field2 === "string" && field2.length > 0)
21756
- return field2;
21757
- if (isRecord9(value.input)) {
21758
- const nested = value.input[key];
21759
- if (typeof nested === "string" && nested.length > 0)
21760
- return nested;
21761
- }
21762
- if (isRecord9(value.arguments)) {
21763
- const nested = value.arguments[key];
21764
- if (typeof nested === "string" && nested.length > 0)
21765
- return nested;
21766
- }
21767
- return void 0;
22688
+ return output?.content.filter((content) => content.type === "text").map(({ text: text3 }) => text3).join("") ?? "";
21768
22689
  }
21769
22690
  function numberField(value, key) {
21770
- if (!isRecord9(value))
22691
+ if (!isRecord10(value))
21771
22692
  return void 0;
21772
22693
  const field2 = value[key];
21773
22694
  return typeof field2 === "number" || field2 === null ? field2 : void 0;
21774
22695
  }
21775
- function normalizeToolName(name) {
21776
- const lower = name.toLowerCase();
21777
- switch (lower) {
21778
- case "bash":
21779
- case "exec":
21780
- case "terminal":
21781
- case "run":
21782
- return "bash";
21783
- case "read":
21784
- case "read_file":
21785
- case "fileread":
21786
- return "Read";
21787
- case "edit":
21788
- case "edit_file":
21789
- case "fileedit":
21790
- return "Edit";
21791
- case "write":
21792
- case "write_file":
21793
- case "filewrite":
21794
- return "Write";
21795
- case "grep":
21796
- case "grep_search":
21797
- return "Grep";
21798
- case "find":
21799
- case "glob":
21800
- case "find_files":
21801
- return "Glob";
21802
- case "todo":
21803
- return "Todo";
21804
- case "web_search":
21805
- case "websearch":
21806
- return "WebSearch";
21807
- default:
21808
- return name.length > 0 ? `${name[0]?.toUpperCase() ?? ""}${name.slice(1)}` : name;
21809
- }
21810
- }
21811
22696
  function delay(milliseconds) {
21812
22697
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
21813
22698
  }
@@ -21835,6 +22720,8 @@ var PiHarnessSession = class {
21835
22720
  #configuring = false;
21836
22721
  #phase = "open";
21837
22722
  #pendingAutonomousTurns = [];
22723
+ #pendingAutonomousLifecycle = [];
22724
+ #pendingAutonomousLifecycleBytes = 0;
21838
22725
  #starting = null;
21839
22726
  #state = {};
21840
22727
  #transport = null;
@@ -21883,13 +22770,20 @@ var PiHarnessSession = class {
21883
22770
  return this.#transport?.state.sessionId === id;
21884
22771
  }
21885
22772
  async readSubagentHistory(cwd) {
21886
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22773
+ if (this.#phase !== "open" || path16.resolve(cwd) !== path16.resolve(this.#cwd)) {
21887
22774
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21888
22775
  }
21889
22776
  return (await this.#ensureTransport()).getEntries();
21890
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
+ }
21891
22785
  async inspectSubagent(id, cwd) {
21892
- if (this.#phase !== "open" || path15.resolve(cwd) !== path15.resolve(this.#cwd)) {
22786
+ if (this.#phase !== "open" || path16.resolve(cwd) !== path16.resolve(this.#cwd)) {
21893
22787
  throw new Error("Pi Subagent parent workspace or Session is unavailable");
21894
22788
  }
21895
22789
  const transport = await this.#ensureTransport();
@@ -21957,7 +22851,7 @@ var PiHarnessSession = class {
21957
22851
  }
21958
22852
  };
21959
22853
  }
21960
- if (this.#acceptingTurn || this.#active || this.#configuring) {
22854
+ if (this.#acceptingTurn || this.#active || this.#configuring || this.#transport?.isBusy) {
21961
22855
  return {
21962
22856
  ok: false,
21963
22857
  error: {
@@ -21967,8 +22861,8 @@ var PiHarnessSession = class {
21967
22861
  }
21968
22862
  };
21969
22863
  }
21970
- const text2 = command.input.map((input) => input.text).join("\n");
21971
- if (text2.length === 0) {
22864
+ const text3 = command.input.map((input) => input.text).join("\n");
22865
+ if (text3.length === 0) {
21972
22866
  return {
21973
22867
  ok: false,
21974
22868
  error: {
@@ -21998,6 +22892,9 @@ var PiHarnessSession = class {
21998
22892
  } catch (error51) {
21999
22893
  return { ok: false, error: normalizedError(error51, "protocolError") };
22000
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
+ }
22001
22898
  let resolveCompletion = () => void 0;
22002
22899
  const completion = new Promise((resolve) => {
22003
22900
  resolveCompletion = resolve;
@@ -22018,21 +22915,27 @@ var PiHarnessSession = class {
22018
22915
  interactions: /* @__PURE__ */ new Map(),
22019
22916
  interactionByNativeId: /* @__PURE__ */ new Map(),
22020
22917
  cancellationRequested: false,
22918
+ settling: false,
22021
22919
  beforeNativeTurnKeys: new Set(beforeHistory.turns.map((turn) => turn.nativeTurnRef.nativeTurnKey)),
22920
+ progressItems: /* @__PURE__ */ new Set(),
22022
22921
  completion,
22023
22922
  resolveCompletion
22024
22923
  };
22025
22924
  this.#active = active;
22026
22925
  this.#event({ type: "turn.started", turnId: command.turnId });
22027
22926
  this.#event({ type: "item.started", turnId: command.turnId, item });
22028
- 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;
22029
22929
  try {
22030
22930
  const identity = await this.#completedTurnIdentity(active, transport);
22031
22931
  this.#completeTurn(active, result.cancelled ? {
22032
22932
  status: "cancelled",
22033
22933
  reason: "Cancelled by user",
22034
- checkpoint: identity.checkpoint
22035
- } : { 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);
22036
22939
  } catch (error51) {
22037
22940
  this.#completeTurn(active, {
22038
22941
  status: "failed",
@@ -22040,6 +22943,7 @@ var PiHarnessSession = class {
22040
22943
  });
22041
22944
  }
22042
22945
  }).catch(async (error51) => {
22946
+ active.settling = true;
22043
22947
  let identity;
22044
22948
  try {
22045
22949
  identity = await this.#completedTurnIdentity(active, transport);
@@ -22048,12 +22952,14 @@ var PiHarnessSession = class {
22048
22952
  this.#completeTurn(active, {
22049
22953
  status: "failed",
22050
22954
  error: normalizedError(error51, "nativeFailure"),
22051
- ...identity ? { checkpoint: identity.checkpoint } : {}
22955
+ ...identity?.checkpoint ? { checkpoint: identity.checkpoint } : {}
22052
22956
  }, void 0, identity?.nativeTurnRef);
22053
22957
  });
22054
22958
  return { ok: true, value: { turnId: command.turnId } };
22055
22959
  } finally {
22056
22960
  this.#acceptingTurn = false;
22961
+ if (this.#transport)
22962
+ this.#drainPendingAutonomousTurns(this.#transport);
22057
22963
  }
22058
22964
  }
22059
22965
  close() {
@@ -22181,6 +23087,8 @@ var PiHarnessSession = class {
22181
23087
  return { ok: true, value: { completed: true } };
22182
23088
  } finally {
22183
23089
  this.#configuring = false;
23090
+ if (this.#transport)
23091
+ this.#drainPendingAutonomousTurns(this.#transport);
22184
23092
  }
22185
23093
  }
22186
23094
  async #selectThinking(command) {
@@ -22255,6 +23163,8 @@ var PiHarnessSession = class {
22255
23163
  return { ok: true, value: { completed: true } };
22256
23164
  } finally {
22257
23165
  this.#configuring = false;
23166
+ if (this.#transport)
23167
+ this.#drainPendingAutonomousTurns(this.#transport);
22258
23168
  }
22259
23169
  }
22260
23170
  async #cancel(command) {
@@ -22265,6 +23175,12 @@ var PiHarnessSession = class {
22265
23175
  error: invalidState("Pi Turn Cancel must reference the active Turn")
22266
23176
  };
22267
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
+ }
22268
23184
  if (active.cancellationRequested) {
22269
23185
  return { ok: true, value: { cancellationRequested: true } };
22270
23186
  }
@@ -22379,7 +23295,9 @@ var PiHarnessSession = class {
22379
23295
  interactions: /* @__PURE__ */ new Map(),
22380
23296
  interactionByNativeId: /* @__PURE__ */ new Map(),
22381
23297
  cancellationRequested: false,
23298
+ settling: false,
22382
23299
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23300
+ progressItems: /* @__PURE__ */ new Set(),
22383
23301
  completion,
22384
23302
  resolveCompletion
22385
23303
  };
@@ -22412,6 +23330,8 @@ var PiHarnessSession = class {
22412
23330
  return { ok: true, value: { turnId: command.turnId } };
22413
23331
  } finally {
22414
23332
  this.#acceptingTurn = false;
23333
+ if (this.#transport)
23334
+ this.#drainPendingAutonomousTurns(this.#transport);
22415
23335
  }
22416
23336
  }
22417
23337
  async #ensureTransport() {
@@ -22462,6 +23382,8 @@ var PiHarnessSession = class {
22462
23382
  return transport;
22463
23383
  }).catch(async (error51) => {
22464
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);
22465
23387
  await transport.close().catch(() => void 0);
22466
23388
  if (this.#phase === "open")
22467
23389
  this.#fault(error51);
@@ -22474,6 +23396,11 @@ var PiHarnessSession = class {
22474
23396
  return starting;
22475
23397
  }
22476
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
+ });
22477
23404
  transport.setSubagentStatusHandler?.((runs) => {
22478
23405
  if (this.#phase !== "open")
22479
23406
  return;
@@ -22485,12 +23412,16 @@ var PiHarnessSession = class {
22485
23412
  transport.setUsageHandler?.((observation) => {
22486
23413
  if (this.#phase !== "open")
22487
23414
  return;
22488
- const record7 = piUsageRecord(observation.message, observation);
22489
- if (record7?.kind === "request")
22490
- this.#event({ type: "usage.request", request: record7.request });
22491
- 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")
22492
23419
  this.#event({ type: "usage.history", complete: false });
22493
23420
  });
23421
+ if (transport.setAutonomousTurnLifecycleHandler) {
23422
+ transport.setAutonomousTurnLifecycleHandler((update) => this.#handleAutonomousLifecycle(transport, update));
23423
+ return;
23424
+ }
22494
23425
  transport.setAutonomousTurnHandler((turn) => {
22495
23426
  if (this.#phase !== "open")
22496
23427
  return;
@@ -22502,6 +23433,20 @@ var PiHarnessSession = class {
22502
23433
  });
22503
23434
  }
22504
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;
22505
23450
  if (this.#pendingSubagentStatus) {
22506
23451
  this.#subagents.observe(this.#pendingSubagentStatus);
22507
23452
  this.#pendingSubagentStatus = null;
@@ -22514,6 +23459,52 @@ var PiHarnessSession = class {
22514
23459
  this.#handleAutonomousTurn(transport, candidate.turn);
22515
23460
  }
22516
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
+ }
22517
23508
  #handleAutonomousTurn(transport, turn) {
22518
23509
  if (this.#phase !== "open")
22519
23510
  return;
@@ -22525,7 +23516,7 @@ var PiHarnessSession = class {
22525
23516
  }));
22526
23517
  return;
22527
23518
  }
22528
- if (this.#active || this.#acceptingTurn || this.#configuring) {
23519
+ if (this.#active && !this.#active.settling) {
22529
23520
  this.#fault(new PiAdapterFaultError({
22530
23521
  code: "protocolError",
22531
23522
  message: "Pi autonomous Turn overlapped another Host operation",
@@ -22533,7 +23524,22 @@ var PiHarnessSession = class {
22533
23524
  }));
22534
23525
  return;
22535
23526
  }
22536
- 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());
22537
23543
  let resolveCompletion = () => void 0;
22538
23544
  const completion = new Promise((resolve) => {
22539
23545
  resolveCompletion = resolve;
@@ -22545,6 +23551,7 @@ var PiHarnessSession = class {
22545
23551
  };
22546
23552
  const active = {
22547
23553
  command: { type: "turn.start", turnId, input: [] },
23554
+ ...runId ? { autonomousRunId: runId } : {},
22548
23555
  agentItem: item,
22549
23556
  agentMessageId: null,
22550
23557
  compactionItem: null,
@@ -22554,10 +23561,19 @@ var PiHarnessSession = class {
22554
23561
  interactions: /* @__PURE__ */ new Map(),
22555
23562
  interactionByNativeId: /* @__PURE__ */ new Map(),
22556
23563
  cancellationRequested: false,
23564
+ settling: false,
22557
23565
  beforeNativeTurnKeys: /* @__PURE__ */ new Set(),
23566
+ progressItems: /* @__PURE__ */ new Set(),
22558
23567
  completion,
22559
23568
  resolveCompletion
22560
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) {
22561
23577
  const nativeTurnRef = turn.nativeTurnKey ? nativeTurnRefSchema.parse({
22562
23578
  harnessId: this.harnessId,
22563
23579
  nativeSessionId: transport.state.sessionId,
@@ -22570,10 +23586,6 @@ var PiHarnessSession = class {
22570
23586
  checkpointId: nativeTurnRef.nativeTurnKey,
22571
23587
  formatVersion: 1
22572
23588
  }) : void 0;
22573
- this.#active = active;
22574
- this.#event({ type: "turn.autonomous.started", turnId, input: [] });
22575
- this.#event({ type: "turn.started", turnId });
22576
- this.#event({ type: "item.started", turnId, item });
22577
23589
  try {
22578
23590
  for (const event of turn.events)
22579
23591
  this.#handleTurnEvent(active, event);
@@ -22643,17 +23655,35 @@ var PiHarnessSession = class {
22643
23655
  if (this.#active !== active || this.#phase === "closed" || this.#phase === "faulted")
22644
23656
  return;
22645
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
+ }
22646
23672
  case "text.delta":
22647
- this.#activateAgentMessage(active, event.messageId);
23673
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23674
+ active.sawAssistantMessage = true;
22648
23675
  this.#appendText(active, event.delta);
22649
23676
  return;
22650
23677
  case "reasoning.delta":
22651
- this.#appendReasoning(active, event.delta);
23678
+ this.#activateAgentMessage(active, event.messageId, event.nativeMessageIdentity);
23679
+ this.#appendReasoning(active, event.delta, event.nativeMessageIdentity);
22652
23680
  return;
22653
23681
  case "reasoning.completed":
22654
23682
  this.#completeReasoning(active, { status: "succeeded" });
22655
23683
  return;
22656
23684
  case "message.completed":
23685
+ if (event.phase && active.agentMessageId === event.messageId && active.agentItem)
23686
+ active.agentItem = { ...active.agentItem, phase: event.phase };
22657
23687
  void this.#refreshUsage(active.command.turnId);
22658
23688
  return;
22659
23689
  case "compaction.started":
@@ -22711,7 +23741,7 @@ var PiHarnessSession = class {
22711
23741
  if (active.interactionByNativeId.has(request.requestId)) {
22712
23742
  throw new Error("Pi Interaction started more than once");
22713
23743
  }
22714
- const interactionId = hostInteractionIdSchema.parse(randomUUID6());
23744
+ const interactionId = hostInteractionIdSchema.parse(randomUUID7());
22715
23745
  const question = request.method === "select" ? {
22716
23746
  id: "answer",
22717
23747
  type: "choice",
@@ -22768,17 +23798,21 @@ var PiHarnessSession = class {
22768
23798
  reason
22769
23799
  });
22770
23800
  }
22771
- #activateAgentMessage(active, messageId) {
23801
+ #activateAgentMessage(active, messageId, nativeMessageIdentity2) {
22772
23802
  if (active.agentMessageId === messageId)
22773
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
+ }
22774
23808
  if (active.agentMessageId !== null) {
22775
23809
  this.#completeReasoning(active, { status: "succeeded" });
22776
- this.#completeAgentItem(active, { status: "succeeded" }, false);
23810
+ this.#completeAgentItem(active, { status: "succeeded" }, true);
22777
23811
  }
22778
23812
  if (!active.agentItem) {
22779
23813
  active.agentItem = {
22780
23814
  type: "agentMessage",
22781
- itemId: this.#newItemId(),
23815
+ itemId: nativeItemId ?? this.#newItemId(),
22782
23816
  text: ""
22783
23817
  };
22784
23818
  this.#event({
@@ -22788,18 +23822,17 @@ var PiHarnessSession = class {
22788
23822
  });
22789
23823
  }
22790
23824
  active.agentMessageId = messageId;
22791
- active.sawAssistantMessage = true;
22792
23825
  }
22793
- #appendText(active, text2) {
23826
+ #appendText(active, text3) {
22794
23827
  if (active.agentMessageId === null || !active.agentItem) {
22795
23828
  throw new Error("Pi Assistant text arrived outside an active message");
22796
23829
  }
22797
- active.agentItem = { ...active.agentItem, text: active.agentItem.text + text2 };
23830
+ active.agentItem = { ...active.agentItem, text: active.agentItem.text + text3 };
22798
23831
  this.#event({
22799
23832
  type: "item.updated",
22800
23833
  turnId: active.command.turnId,
22801
23834
  itemId: active.agentItem.itemId,
22802
- update: { type: "text.append", text: text2 }
23835
+ update: { type: "text.append", text: text3 }
22803
23836
  });
22804
23837
  }
22805
23838
  #completeAgentItem(active, outcome, completeEmpty) {
@@ -22810,13 +23843,13 @@ var PiHarnessSession = class {
22810
23843
  active.agentItem = null;
22811
23844
  this.#completeItem(active, item, outcome);
22812
23845
  }
22813
- #appendReasoning(active, text2) {
22814
- if (text2.length === 0)
23846
+ #appendReasoning(active, text3, nativeMessageIdentity2) {
23847
+ if (text3.length === 0)
22815
23848
  return;
22816
23849
  if (!active.reasoningItem) {
22817
23850
  active.reasoningItem = {
22818
23851
  type: "reasoning",
22819
- itemId: this.#newItemId(),
23852
+ itemId: piMessageItemId(nativeMessageIdentity2, "reasoning") ?? this.#newItemId(),
22820
23853
  text: ""
22821
23854
  };
22822
23855
  this.#event({
@@ -22827,13 +23860,13 @@ var PiHarnessSession = class {
22827
23860
  }
22828
23861
  active.reasoningItem = {
22829
23862
  ...active.reasoningItem,
22830
- text: active.reasoningItem.text + text2
23863
+ text: active.reasoningItem.text + text3
22831
23864
  };
22832
23865
  this.#event({
22833
23866
  type: "item.updated",
22834
23867
  turnId: active.command.turnId,
22835
23868
  itemId: active.reasoningItem.itemId,
22836
- update: { type: "text.append", text: text2 }
23869
+ update: { type: "text.append", text: text3 }
22837
23870
  });
22838
23871
  }
22839
23872
  #completeReasoning(active, outcome) {
@@ -22846,13 +23879,12 @@ var PiHarnessSession = class {
22846
23879
  #startTool(active, event) {
22847
23880
  if (active.tools.has(event.callId))
22848
23881
  throw new Error("Pi Tool started more than once");
22849
- const normalizedName = normalizeToolName(event.toolName);
22850
- 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;
22851
- const item = command ? {
23882
+ const shell = piToolCommand(event.toolName, event.arguments);
23883
+ const item = shell ? {
22852
23884
  type: "commandExecution",
22853
23885
  itemId: this.#newItemId(),
22854
- command,
22855
- cwd: stringField(event.arguments, "cwd") ?? this.#cwd
23886
+ command: shell.command,
23887
+ cwd: shell.cwd ?? this.#cwd
22856
23888
  } : {
22857
23889
  type: "toolExecution",
22858
23890
  itemId: this.#newItemId(),
@@ -22970,14 +24002,17 @@ var PiHarnessSession = class {
22970
24002
  sessionId: transport.state.sessionId,
22971
24003
  model: nativeModelForHistory(transport.state)
22972
24004
  });
22973
- 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));
22974
24006
  if (created.length !== 1) {
22975
24007
  throw new Error(`Pi Turn persisted ${created.length} new User Entries; exactly one is required`);
22976
24008
  }
22977
24009
  const turn = created[0];
22978
- if (!turn?.checkpoint)
22979
- throw new Error("Pi Turn has no terminal Checkpoint identity");
22980
- 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
+ };
22981
24016
  }
22982
24017
  #completeTurn(active, outcome, finalText, nativeTurnRef) {
22983
24018
  if (this.#active !== active)
@@ -23006,14 +24041,20 @@ var PiHarnessSession = class {
23006
24041
  });
23007
24042
  active.resolveCompletion();
23008
24043
  queueMicrotask(() => {
23009
- if (this.#phase === "open")
23010
- 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);
23011
24049
  });
23012
24050
  }
23013
24051
  #fault(error51) {
23014
24052
  if (this.#phase === "closed" || this.#phase === "faulted")
23015
24053
  return;
23016
24054
  const normalized = normalizedError(error51, "internalError");
24055
+ this.#pendingAutonomousTurns = [];
24056
+ this.#pendingAutonomousLifecycle = [];
24057
+ this.#pendingAutonomousLifecycleBytes = 0;
23017
24058
  if (this.#active) {
23018
24059
  this.#completeTurn(this.#active, { status: "failed", error: normalized });
23019
24060
  }
@@ -23022,6 +24063,9 @@ var PiHarnessSession = class {
23022
24063
  this.#channel.end();
23023
24064
  }
23024
24065
  async #close() {
24066
+ this.#pendingAutonomousTurns = [];
24067
+ this.#pendingAutonomousLifecycle = [];
24068
+ this.#pendingAutonomousLifecycleBytes = 0;
23025
24069
  if (this.#phase === "closed")
23026
24070
  return;
23027
24071
  const wasFaulted = this.#phase === "faulted";
@@ -23054,7 +24098,7 @@ var PiHarnessSession = class {
23054
24098
  this.#channel.emit({ kind: "event", event });
23055
24099
  }
23056
24100
  #newItemId() {
23057
- return hostItemIdSchema.parse(randomUUID6());
24101
+ return hostItemIdSchema.parse(randomUUID7());
23058
24102
  }
23059
24103
  };
23060
24104
  var PiAdapter = class {
@@ -23069,12 +24113,15 @@ var PiAdapter = class {
23069
24113
  if (this.#closePromise || parent.harnessId !== this.harnessId) {
23070
24114
  return { ok: false, error: invalidState("Pi Subagent parent is unavailable") };
23071
24115
  }
24116
+ const gotgenes = parseGotgenesId(nativeSubagentId);
23072
24117
  const workflow = parsePiWorkflowSubagentId(nativeSubagentId);
23073
- if (!workflow)
24118
+ if (!workflow && !gotgenes)
23074
24119
  parsePiSubagentId(nativeSubagentId);
23075
24120
  const live = [...this.#sessions].find((session) => session.ownsNativeSession(parent.nativeSessionId));
23076
24121
  let reply;
23077
24122
  if (live) {
24123
+ if (gotgenes)
24124
+ return await live.readGotgenesChild(gotgenes, cwd);
23078
24125
  if (workflow)
23079
24126
  return await readPiWorkflowChild(await live.readSubagentHistory(cwd), parent.nativeSessionId, workflow);
23080
24127
  reply = await live.inspectSubagent(nativeSubagentId, cwd);
@@ -23086,6 +24133,8 @@ var PiAdapter = class {
23086
24133
  if (transport.state.sessionId !== parent.nativeSessionId)
23087
24134
  throw new Error("Pi Subagent parent identity mismatch");
23088
24135
  await transport.verifySessionCwd(cwd);
24136
+ if (gotgenes)
24137
+ return await readGotgenesChild(await transport.getEntries(), parent.nativeSessionId, gotgenes);
23089
24138
  if (workflow)
23090
24139
  return await readPiWorkflowChild(await transport.getEntries(), parent.nativeSessionId, workflow);
23091
24140
  if (!transport.inspectSubagent)