@codexhost/cli-darwin-x64 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +83 -5
  4. package/app/console-web.js +1172 -687
  5. package/app/desktop-controller.mjs +314 -15
  6. package/app/host-runtime.mjs +13158 -2853
  7. package/app/plugins/antigravity/plugin.mjs +8861 -3944
  8. package/app/plugins/claude-code/plugin.mjs +164 -14
  9. package/app/plugins/codebuddy/plugin.mjs +193 -25
  10. package/app/plugins/codex-usage/plugin.mjs +85 -5
  11. package/app/plugins/copilot/plugin.mjs +85 -5
  12. package/app/plugins/cursor-cli/plugin.mjs +160 -15
  13. package/app/plugins/deepseek-harness/manifest.json +2 -2
  14. package/app/plugins/deepseek-harness/plugin.mjs +112 -10
  15. package/app/plugins/devin/plugin.mjs +84 -5
  16. package/app/plugins/grok/plugin.mjs +418 -272
  17. package/app/plugins/hermes/plugin.mjs +163 -17
  18. package/app/plugins/kimi-code/plugin.mjs +85 -5
  19. package/app/plugins/kiro-cli/plugin.mjs +313 -21
  20. package/app/plugins/omp/plugin.mjs +1018 -819
  21. package/app/plugins/opencode/plugin.mjs +85 -5
  22. package/app/plugins/pi/plugin.mjs +828 -663
  23. package/app/plugins/qoder/plugin.mjs +109 -10
  24. package/app/plugins/qoder-cn/plugin.mjs +109 -10
  25. package/app/plugins/qwen-code/plugin.mjs +194 -97
  26. package/app/plugins/workbuddy/plugin.mjs +197 -28
  27. package/app/plugins/zcode/plugin.mjs +158 -8
  28. package/app/renderer-extension.js +2065 -1004
  29. package/app/web/assets/index-D6-hvggd.css +1 -0
  30. package/app/web/assets/index-D85gPBbQ.js +201 -0
  31. package/app/web/assets/langs/{graphql-B8vkg11W.js → graphql-ChAeyPkT.js} +1 -1
  32. package/app/web/assets/langs/{http-DmoDEjMt.js → http-BvreBIbD.js} +1 -1
  33. package/app/web/assets/langs/{php-DJ5ovfAM.js → php-D8omCIuJ.js} +1 -1
  34. package/app/web/assets/langs/{rst-U5-R5x3p.js → rst-Do7RLLCS.js} +1 -1
  35. package/app/web/assets/langs/{ruby-VKVsnS0H.js → ruby-rH_O_vse.js} +1 -1
  36. package/app/web/assets/langs/{svelte-C20lOv9V.js → svelte-xZy73wAj.js} +1 -1
  37. package/app/web/assets/langs/{vue-z6Y-lzP-.js → vue-C4DW8agZ.js} +1 -1
  38. package/app/web/assets/{vendor-dSL872WO.js → vendor-C9g2bw8s.js} +3 -3
  39. package/app/web/codexhost-settings.js +1178 -689
  40. package/app/web/index.html +4 -3
  41. package/app/web/plugins/deepseek-ai__dsh-api-gateway/client.js +2 -2
  42. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  43. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  44. package/app/web/plugins/deepseek-ai__dsh-client-connection/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +3 -3
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +134 -8
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +65 -63
  50. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +95 -93
  51. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  52. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  53. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +1 -1
  54. package/app/web/plugins/deepseek-ai__dsh-client-ui-session/client.js +1 -1
  55. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  56. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.excel.js +1 -1
  57. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  58. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  59. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  60. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +11 -11
  61. package/app/web-modules/server.mjs +2468 -1575
  62. package/bin/codexhost +0 -0
  63. package/libexec/codexhost-shim +0 -0
  64. package/libexec/codexhost-updater +0 -0
  65. package/package.json +1 -1
  66. package/app/web/assets/index-C0aXz2jD.js +0 -199
  67. package/app/web/assets/index-C3lniEH1.css +0 -1
@@ -408,149 +408,6 @@ function createHarnessInstaller(environment, source) {
408
408
  };
409
409
  }
410
410
 
411
- // ../../harness-adapter/dist/usage-statistics.js
412
- import { createReadStream } from "node:fs";
413
- import { lstat, opendir } from "node:fs/promises";
414
- import path4 from "node:path";
415
- import { createInterface } from "node:readline";
416
- var MAX_SESSION_ID_LENGTH = 512;
417
- var MAX_CWD_LENGTH = 4096;
418
- var MAX_SESSION_TITLE_LENGTH = 200;
419
- function usageSessionTitle(value) {
420
- if (typeof value !== "string")
421
- return void 0;
422
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
423
- if (!normalized)
424
- return void 0;
425
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
426
- return normalized;
427
- let title = "";
428
- for (const character of normalized) {
429
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
430
- break;
431
- title += character;
432
- }
433
- return `${title.trimEnd()}…`;
434
- }
435
- function sessionIdOk(value) {
436
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
437
- }
438
- function cwdOk(value) {
439
- return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
440
- }
441
- function withUsageSession(entry, session) {
442
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
443
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
444
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
445
- if (sessionId === void 0 && cwd === void 0)
446
- return entry;
447
- return {
448
- ...entry,
449
- ...sessionId !== void 0 ? { sessionId } : {},
450
- ...cwd !== void 0 ? { cwd } : {},
451
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
452
- };
453
- }
454
- function usageEntryFromRequest(request, occurredAtMs) {
455
- if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
456
- return null;
457
- return {
458
- id: request.requestId,
459
- occurredAtMs,
460
- ...request.model !== void 0 ? { model: request.model } : {},
461
- inputTokens: request.inputTokens,
462
- ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
463
- ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
464
- ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
465
- outputTokens: request.outputTokens,
466
- ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
467
- };
468
- }
469
- async function jsonlUsageSources(root, maxDepth, signal) {
470
- const sources = [];
471
- const visit = async (directory, depth) => {
472
- signal.throwIfAborted();
473
- const entries = await opendir(directory).catch((error51) => {
474
- if (error51.code === "ENOENT")
475
- return null;
476
- throw error51;
477
- });
478
- if (!entries)
479
- return;
480
- for await (const entry of entries) {
481
- signal.throwIfAborted();
482
- const file2 = path4.join(directory, entry.name);
483
- if (entry.isDirectory()) {
484
- if (depth < maxDepth)
485
- await visit(file2, depth + 1);
486
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
487
- const info = await lstat(file2).catch(() => null);
488
- if (info?.isFile() && info.size > 0) {
489
- sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
490
- }
491
- }
492
- }
493
- };
494
- await visit(root, 0);
495
- return sources;
496
- }
497
- async function* jsonlRecords(file2, marker, signal) {
498
- const lines = createInterface({
499
- input: createReadStream(file2, { encoding: "utf8", signal }),
500
- crlfDelay: Infinity
501
- });
502
- for await (const line of lines) {
503
- if (!line.includes(marker))
504
- continue;
505
- let value;
506
- try {
507
- value = JSON.parse(line);
508
- } catch {
509
- continue;
510
- }
511
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
512
- yield value;
513
- }
514
- }
515
- }
516
- async function jsonlHeader(file2, match, signal, maxLines = 4) {
517
- const stream = createReadStream(file2, { encoding: "utf8", signal });
518
- const lines = createInterface({ input: stream, crlfDelay: Infinity });
519
- let seen = 0;
520
- try {
521
- for await (const line of lines) {
522
- if (++seen > maxLines)
523
- break;
524
- let value;
525
- try {
526
- value = JSON.parse(line);
527
- } catch {
528
- continue;
529
- }
530
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
531
- const record10 = value;
532
- if (match(record10))
533
- return record10;
534
- }
535
- }
536
- return null;
537
- } finally {
538
- lines.close();
539
- stream.destroy();
540
- }
541
- }
542
- function nativeTimeMs(value) {
543
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
544
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
545
- }
546
-
547
- // dist/pi-session-import.js
548
- import { createReadStream as createReadStream2 } from "node:fs";
549
- import { opendir as opendir2, realpath, stat } from "node:fs/promises";
550
- import os2 from "node:os";
551
- import path5 from "node:path";
552
- import { createInterface as createInterface2 } from "node:readline";
553
-
554
411
  // ../../../node_modules/zod/v4/classic/external.js
555
412
  var external_exports = {};
556
413
  __export(external_exports, {
@@ -15202,13 +15059,25 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
15202
15059
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
15203
15060
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
15204
15061
  var cacheHitRatePercentSchema = external_exports.number().finite().min(0).max(100);
15062
+ var usageOutputTimingSchema = external_exports.object({
15063
+ version: external_exports.literal(3).optional(),
15064
+ requestId: external_exports.string().min(1),
15065
+ turnId: external_exports.string().min(1).max(1024),
15066
+ outputTokens: nonNegativeSafeIntegerSchema,
15067
+ startedAtMs: nonNegativeSafeIntegerSchema,
15068
+ completedAtMs: nonNegativeSafeIntegerSchema
15069
+ }).strict().refine((value) => value.completedAtMs > value.startedAtMs);
15205
15070
  var usageMeasurementSchema = external_exports.object({
15071
+ version: external_exports.union([external_exports.literal(2), external_exports.literal(3)]).optional(),
15206
15072
  value: finiteNonNegativeNumberSchema,
15207
15073
  turnId: external_exports.string().min(1).max(1024),
15208
15074
  at: nonNegativeSafeIntegerSchema
15209
15075
  }).strict();
15210
15076
  var usageMeasurementsSchema = external_exports.object({
15211
- outputTokensPerSecond: usageMeasurementSchema.optional(),
15077
+ // Unversioned intervals can omit hidden thinking time; do not restore them into averages.
15078
+ outputTimings: external_exports.array(usageOutputTimingSchema).transform((values) => values.filter((value) => value.version === 3)).optional(),
15079
+ // Retain independent TTFT facts when dropping incompatible speed measurements.
15080
+ outputTokensPerSecond: usageMeasurementSchema.refine((value) => value.version === 3).optional().catch(void 0),
15212
15081
  timeToFirstOutputMs: usageMeasurementSchema.extend({ value: nonNegativeSafeIntegerSchema }).optional()
15213
15082
  }).strict();
15214
15083
  var indicatorTextSchema = (maximum) => harnessLocalizedTextSchema.refine((entries) => Object.values(entries).every((text4) => text4.length <= maximum));
@@ -15228,6 +15097,7 @@ var threadUsageSnapshotSchema = external_exports.object({
15228
15097
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
15229
15098
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
15230
15099
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15100
+ sessionOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15231
15101
  apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
15232
15102
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
15233
15103
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
@@ -15639,11 +15509,19 @@ var threadSteeringInspectResultSchema = external_exports.object({
15639
15509
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15640
15510
  }).strict();
15641
15511
 
15512
+ // ../../shared-contracts/dist/thread-archive-confirm.js
15513
+ var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
15514
+ var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
15515
+
15642
15516
  // ../../shared-contracts/dist/client-channel.js
15643
15517
  var CLIENT_CHANNEL_VERSION = 1;
15644
15518
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15645
15519
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15646
15520
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15521
+ var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
15522
+ var clientThreadTreeSchema = external_exports.object({
15523
+ parents: external_exports.record(external_exports.string().min(1), external_exports.string().min(1))
15524
+ }).strict();
15647
15525
  var clientProjectlessWorkspaceSchema = external_exports.object({
15648
15526
  prompt: external_exports.string().max(16384).optional()
15649
15527
  }).strict();
@@ -15660,6 +15538,11 @@ var clientChannelCursorSchema = external_exports.object({
15660
15538
  sequence: external_exports.number().int().nonnegative()
15661
15539
  });
15662
15540
  var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15541
+ external_exports.object({
15542
+ type: external_exports.literal("skills-changed"),
15543
+ cursor: clientChannelCursorSchema,
15544
+ cwd: external_exports.string().optional()
15545
+ }),
15663
15546
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15664
15547
  external_exports.object({
15665
15548
  type: external_exports.literal("preferences-changed"),
@@ -15769,7 +15652,12 @@ var clientThreadSnapshotSchema = external_exports.object({
15769
15652
  /** Current interruptible Host Turn, including command Turns omitted from client history. */
15770
15653
  activeTurnId: external_exports.string().min(1).nullable().optional(),
15771
15654
  /** Most recent explicit command in this Host process; not native conversation history. */
15772
- command: external_exports.object({ name: external_exports.string().min(1), turn: clientTurnSchema }).optional(),
15655
+ command: external_exports.object({
15656
+ name: external_exports.string().min(1),
15657
+ turn: clientTurnSchema,
15658
+ /** First ordinary Turn started after this command; its retained result is not a new event. */
15659
+ subsequentTurnId: external_exports.string().min(1).optional()
15660
+ }).optional(),
15773
15661
  thread: external_exports.object({
15774
15662
  id: external_exports.string().min(1),
15775
15663
  cwd: external_exports.string(),
@@ -15857,6 +15745,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
15857
15745
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
15858
15746
  ]);
15859
15747
 
15748
+ // ../../shared-contracts/dist/skills.js
15749
+ var skillsListParamsSchema = external_exports.object({
15750
+ threadId: hostThreadIdSchema.optional(),
15751
+ cwd: external_exports.string().min(1).optional()
15752
+ }).strict().refine((params) => !(params.threadId && params.cwd), {
15753
+ message: "Specify threadId or cwd, not both"
15754
+ });
15755
+ var librarySkillSchema = external_exports.object({
15756
+ name: external_exports.string().min(1).regex(/^[^\s[\]]+$/u),
15757
+ description: external_exports.string().optional(),
15758
+ path: external_exports.string().min(1),
15759
+ scope: external_exports.enum(["project", "global"]),
15760
+ source: external_exports.string().min(1)
15761
+ }).strict();
15762
+ var skillsListResultSchema = external_exports.object({
15763
+ revision: external_exports.number().int().nonnegative(),
15764
+ complete: external_exports.boolean(),
15765
+ skills: external_exports.array(librarySkillSchema),
15766
+ warnings: external_exports.array(external_exports.string()).optional()
15767
+ }).strict();
15768
+ var skillsChangedParamsSchema = external_exports.object({ cwd: external_exports.string().min(1).optional() }).strict();
15769
+
15860
15770
  // ../../shared-contracts/dist/web-access-tokens.js
15861
15771
  var webNetworkAccessUrlSchema = external_exports.object({
15862
15772
  /**
@@ -15955,15 +15865,14 @@ var webAccessStateSchema = external_exports.object({
15955
15865
  quotaUntil: external_exports.string().optional()
15956
15866
  }).strict().optional()
15957
15867
  }).strict();
15958
- var webLocalAccessRequiredDetailsSchema = external_exports.object({ url: external_exports.string() }).strict();
15959
15868
 
15960
15869
  // ../../shared-contracts/dist/delegation-read.js
15961
15870
  var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
15962
15871
  var delegationReadParamsSchema = external_exports.strictObject({
15963
15872
  threadId: external_exports.string().min(1).max(1024),
15964
15873
  view: external_exports.enum(["result", "messages"]),
15965
- cursor: external_exports.string().min(1).max(8192).optional(),
15966
- limit: external_exports.number().int().min(1).max(100).optional()
15874
+ from: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
15875
+ to: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional()
15967
15876
  });
15968
15877
 
15969
15878
  // ../../shared-contracts/dist/credential-imports.js
@@ -16916,6 +16825,17 @@ var updateStatusResultSchema = external_exports.strictObject({
16916
16825
  status: updateStatusSchema.nullable()
16917
16826
  });
16918
16827
 
16828
+ // ../../shared-contracts/dist/thread-watch-notice.js
16829
+ var THREAD_WATCH_NOTICE_OUTCOMES = [
16830
+ "completed",
16831
+ "failed",
16832
+ "interrupted",
16833
+ "timedOut",
16834
+ "unreadable",
16835
+ "notFound"
16836
+ ];
16837
+ var ENTRY_PATTERN = new RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): ` + `(${THREAD_WATCH_NOTICE_OUTCOMES.join("|")})(?:. (.+))?$`, "u");
16838
+
16919
16839
  // ../../shared-contracts/dist/remote-runtime.js
16920
16840
  var remoteUpdatePhaseSchema = external_exports.enum([
16921
16841
  "idle",
@@ -16963,6 +16883,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16963
16883
  archived: external_exports.boolean()
16964
16884
  }),
16965
16885
  external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
16886
+ external_exports.strictObject({
16887
+ kind: external_exports.literal("configure"),
16888
+ ...thread,
16889
+ epoch: identity,
16890
+ modelId: identity.optional(),
16891
+ thinkingOptionId: identity.optional(),
16892
+ permissionModeId: identity.optional()
16893
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
16966
16894
  external_exports.strictObject({
16967
16895
  kind: external_exports.literal("prompt"),
16968
16896
  ...thread,
@@ -17035,6 +16963,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17035
16963
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17036
16964
  ]);
17037
16965
 
16966
+ // ../../shared-contracts/dist/thread-title.js
16967
+ var threadTitleInputSchema = external_exports.strictObject({
16968
+ prompt: external_exports.string().trim().min(1).max(2e3),
16969
+ cwd: external_exports.string().max(4096).nullable()
16970
+ });
16971
+ var threadTitleResultSchema = external_exports.string().trim().min(1).max(60).nullable();
16972
+
17038
16973
  // ../../shared-contracts/dist/web-ui-extensions.js
17039
16974
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17040
16975
  var localizedTextSchema2 = external_exports.union([
@@ -17078,336 +17013,28 @@ var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdS
17078
17013
  // ../../shared-contracts/dist/index.js
17079
17014
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17080
17015
 
17081
- // ../../harness-adapter/dist/session-import.js
17082
- var SessionImportChangedError = class extends Error {
17083
- constructor(message3 = "Native Session changed during discovery; refresh and retry") {
17084
- super(message3);
17085
- this.name = "SessionImportChangedError";
17086
- }
17087
- };
17088
- function isMissingFileError(error51) {
17089
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17090
- }
17091
- function sameFileFingerprint(left, right) {
17092
- return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
17093
- }
17094
- function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
17095
- if (typeof value !== "string")
17096
- return null;
17097
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17098
- if (!normalized)
17099
- return null;
17100
- if (normalized.length <= maxLength)
17101
- return normalized;
17102
- const characters = [...normalized];
17103
- if (characters.length <= maxLength)
17104
- return normalized;
17105
- return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
17106
- }
17107
- function sessionImportCandidate(input) {
17108
- const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
17109
- const parsed = harnessSessionImportCandidateSchema.safeParse({
17110
- nativeSessionId: input.nativeSessionId,
17111
- cwd: input.cwd,
17112
- title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
17113
- updatedAt: Math.floor(time3),
17114
- // Unknown must stay unknown; only an explicit boolean is a native statement.
17115
- running: typeof input.running === "boolean" ? input.running : null
17116
- });
17117
- return parsed.success ? parsed.data : null;
17016
+ // ../../harness-adapter/dist/question.js
17017
+ function invalidRequest(message3) {
17018
+ return { code: "invalidRequest", message: message3, retryable: false };
17118
17019
  }
17119
- var SessionImportScope = class {
17120
- #abort = new AbortController();
17121
- #options;
17122
- #pending = /* @__PURE__ */ new Set();
17123
- constructor(options) {
17124
- this.#options = options;
17020
+ function validateHostQuestionResponse(interaction, response) {
17021
+ const questionIds = new Set(interaction.questions.map(({ id }) => id));
17022
+ if (response.cancelled) {
17023
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest("Cancelled Question Response must not contain answers");
17125
17024
  }
17126
- #closed() {
17127
- return {
17128
- ok: false,
17129
- error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
17130
- };
17025
+ for (const answerId of Object.keys(response.answers)) {
17026
+ if (!questionIds.has(answerId)) {
17027
+ return invalidRequest("Question Response contains an unknown Question ID");
17028
+ }
17131
17029
  }
17132
- read(operation) {
17133
- const signal = this.#abort.signal;
17134
- if (signal.aborted)
17135
- return Promise.resolve(this.#closed());
17136
- let started;
17137
- try {
17138
- started = operation(signal);
17139
- } catch (error51) {
17140
- started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17030
+ for (const question of interaction.questions) {
17031
+ const answers = response.answers[question.id] ?? [];
17032
+ if (!question.optional && answers.length === 0) {
17033
+ return invalidRequest("Question Response omits a required answer");
17141
17034
  }
17142
- const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
17143
- ok: false,
17144
- error: {
17145
- code: "unavailable",
17146
- message: this.#options.unavailableMessage,
17147
- retryable: true
17148
- }
17149
- }).finally(() => this.#pending.delete(request));
17150
- this.#pending.add(request);
17151
- return request;
17152
- }
17153
- /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
17154
- async resolve(operation) {
17155
- const result = await this.read(operation);
17156
- if (!result.ok)
17157
- return result;
17158
- return result.value ? { ok: true, value: result.value } : {
17159
- ok: false,
17160
- error: {
17161
- code: "sessionNotFound",
17162
- message: this.#options.notFoundMessage,
17163
- retryable: false
17164
- }
17165
- };
17166
- }
17167
- /** Idempotent. Resolves after every started read has settled. */
17168
- async close() {
17169
- this.#abort.abort();
17170
- await Promise.allSettled(this.#pending);
17171
- }
17172
- };
17173
-
17174
- // dist/pi-session-import.js
17175
- var PI_SESSION_CHANGED = "Pi Session changed during discovery; refresh and retry";
17176
- function isRecord(value) {
17177
- return typeof value === "object" && value !== null && !Array.isArray(value);
17178
- }
17179
- function expandDirectory(value, home) {
17180
- return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
17181
- }
17182
- function piSessionImportDirectory(environment) {
17183
- const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
17184
- const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
17185
- if (custom2)
17186
- return { directory: expandDirectory(custom2, home), flat: true };
17187
- const agent = environment.PI_CODING_AGENT_DIR;
17188
- return {
17189
- directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".pi", "agent"), "sessions"),
17190
- flat: false
17191
- };
17192
- }
17193
- async function sessionFiles(directory, flat, signal) {
17194
- const files = [];
17195
- const visit = async (dir, projectLevel) => {
17196
- signal.throwIfAborted();
17197
- const entries = await opendir2(dir).catch((error51) => {
17198
- if (isMissingFileError(error51))
17199
- return null;
17200
- throw error51;
17201
- });
17202
- if (!entries)
17203
- return;
17204
- for await (const entry of entries) {
17205
- signal.throwIfAborted();
17206
- if (projectLevel && entry.isDirectory())
17207
- await visit(path5.join(dir, entry.name), false);
17208
- else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl")) {
17209
- files.push(path5.join(dir, entry.name));
17210
- }
17211
- }
17212
- };
17213
- await visit(directory, !flat);
17214
- return files;
17215
- }
17216
- async function readCandidate(file2, signal) {
17217
- const before = await stat(file2);
17218
- if (!before.isFile() || before.size === 0)
17219
- return null;
17220
- const stream = createReadStream2(file2, { encoding: "utf8", signal, end: before.size - 1 });
17221
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17222
- let header;
17223
- let name = null;
17224
- let firstMessage = null;
17225
- let hasUser = false;
17226
- let updatedAt = before.mtimeMs;
17227
- const entries = /* @__PURE__ */ new Map();
17228
- try {
17229
- for await (const line of lines) {
17230
- signal.throwIfAborted();
17231
- if (!line.trim())
17232
- continue;
17233
- let entry;
17234
- try {
17235
- entry = JSON.parse(line);
17236
- } catch {
17237
- return null;
17238
- }
17239
- if (!isRecord(entry))
17240
- return null;
17241
- if (!header) {
17242
- if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
17243
- return null;
17244
- header = entry;
17245
- continue;
17246
- }
17247
- if (typeof entry.id !== "string" || entry.id.length === 0 || entries.has(entry.id) || entry.parentId !== null && (typeof entry.parentId !== "string" || !entries.has(entry.parentId)))
17248
- return null;
17249
- const message3 = isRecord(entry.message) ? entry.message : null;
17250
- if (!firstMessage && entry.type === "message" && message3?.role === "user") {
17251
- const content = message3.content;
17252
- const text4 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
17253
- firstMessage = sessionImportTitle(text4);
17254
- }
17255
- hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
17256
- entries.set(entry.id, hasUser);
17257
- if (entry.type === "session_info")
17258
- name = sessionImportTitle(entry.name);
17259
- if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
17260
- const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
17261
- if (Number.isFinite(time3))
17262
- updatedAt = time3;
17263
- }
17264
- }
17265
- } finally {
17266
- lines.close();
17267
- stream.destroy();
17268
- }
17269
- if (!header)
17270
- return null;
17271
- if (!hasUser)
17272
- return null;
17273
- const after = await stat(file2);
17274
- if (!sameFileFingerprint(before, after))
17275
- throw new SessionImportChangedError(PI_SESSION_CHANGED);
17276
- const cwd = await realpath(String(header.cwd));
17277
- if (!(await stat(cwd)).isDirectory())
17278
- return null;
17279
- const nativeRef = nativeSessionRefSchema.safeParse({
17280
- harnessId: "pi",
17281
- nativeSessionId: header.id,
17282
- locator: { sessionFile: await realpath(file2) },
17283
- formatVersion: 1
17284
- });
17285
- const candidate = sessionImportCandidate({
17286
- nativeSessionId: header.id,
17287
- cwd,
17288
- title: name ?? firstMessage,
17289
- updatedAt
17290
- });
17291
- return candidate && nativeRef.success ? { candidate, nativeRef: nativeRef.data } : null;
17292
- }
17293
- async function readIdentity(file2, signal) {
17294
- const stream = createReadStream2(file2, { encoding: "utf8", signal });
17295
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17296
- try {
17297
- for await (const line of lines) {
17298
- signal.throwIfAborted();
17299
- if (!line.trim())
17300
- continue;
17301
- let header;
17302
- try {
17303
- header = JSON.parse(line);
17304
- } catch {
17305
- return null;
17306
- }
17307
- return isRecord(header) && header.type === "session" && header.version === 3 && typeof header.id === "string" ? header.id : null;
17308
- }
17309
- return null;
17310
- } finally {
17311
- lines.close();
17312
- stream.destroy();
17313
- }
17314
- }
17315
- var PiSessionImportIndex = class {
17316
- #location;
17317
- #cache = /* @__PURE__ */ new Map();
17318
- #listing;
17319
- constructor(environment) {
17320
- this.#location = piSessionImportDirectory(environment);
17321
- }
17322
- list(signal) {
17323
- this.#listing ??= this.#scan(signal).finally(() => {
17324
- this.#listing = void 0;
17325
- });
17326
- return this.#listing;
17327
- }
17328
- async #scan(signal) {
17329
- const { directory, flat } = this.#location;
17330
- const files = await sessionFiles(directory, flat, signal);
17331
- const next = /* @__PURE__ */ new Map();
17332
- const identities = /* @__PURE__ */ new Set();
17333
- const sources = [];
17334
- for (const file2 of files) {
17335
- signal.throwIfAborted();
17336
- try {
17337
- const fingerprint = await stat(file2);
17338
- const cached2 = this.#cache.get(file2);
17339
- const source = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source : await readCandidate(file2, signal);
17340
- if (!source)
17341
- continue;
17342
- if (!(await stat(source.candidate.cwd)).isDirectory())
17343
- continue;
17344
- if (identities.has(source.nativeRef.nativeSessionId))
17345
- throw new Error("Pi Session identity is ambiguous across files");
17346
- identities.add(source.nativeRef.nativeSessionId);
17347
- next.set(file2, { fingerprint, source });
17348
- sources.push(source);
17349
- } catch (error51) {
17350
- if (!isMissingFileError(error51) && !(error51 instanceof SessionImportChangedError))
17351
- throw error51;
17352
- }
17353
- }
17354
- this.#cache = next;
17355
- return structuredClone(sources.sort((left, right) => right.candidate.updatedAt - left.candidate.updatedAt));
17356
- }
17357
- async resolve(nativeSessionId, signal) {
17358
- const { directory, flat } = this.#location;
17359
- let selected;
17360
- for (const file2 of await sessionFiles(directory, flat, signal)) {
17361
- signal.throwIfAborted();
17362
- try {
17363
- const fingerprint = await stat(file2);
17364
- const cached2 = this.#cache.get(file2);
17365
- const id = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source.nativeRef.nativeSessionId : await readIdentity(file2, signal);
17366
- if (id !== nativeSessionId)
17367
- continue;
17368
- if (selected)
17369
- throw new Error("Pi Session identity is ambiguous across files");
17370
- selected = file2;
17371
- } catch (error51) {
17372
- if (!isMissingFileError(error51))
17373
- throw error51;
17374
- }
17375
- }
17376
- if (!selected)
17377
- return null;
17378
- try {
17379
- const source = await readCandidate(selected, signal);
17380
- return source?.nativeRef.nativeSessionId === nativeSessionId ? source : null;
17381
- } catch (error51) {
17382
- if (isMissingFileError(error51))
17383
- return null;
17384
- throw error51;
17385
- }
17386
- }
17387
- };
17388
-
17389
- // ../../harness-adapter/dist/question.js
17390
- function invalidRequest(message3) {
17391
- return { code: "invalidRequest", message: message3, retryable: false };
17392
- }
17393
- function validateHostQuestionResponse(interaction, response) {
17394
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17395
- if (response.cancelled) {
17396
- return Object.keys(response.answers).length === 0 ? null : invalidRequest("Cancelled Question Response must not contain answers");
17397
- }
17398
- for (const answerId of Object.keys(response.answers)) {
17399
- if (!questionIds.has(answerId)) {
17400
- return invalidRequest("Question Response contains an unknown Question ID");
17401
- }
17402
- }
17403
- for (const question of interaction.questions) {
17404
- const answers = response.answers[question.id] ?? [];
17405
- if (!question.optional && answers.length === 0) {
17406
- return invalidRequest("Question Response omits a required answer");
17407
- }
17408
- if (question.type === "text") {
17409
- if (answers.length > 1) {
17410
- return invalidRequest("Text Question accepts at most one answer");
17035
+ if (question.type === "text") {
17036
+ if (answers.length > 1) {
17037
+ return invalidRequest("Text Question accepts at most one answer");
17411
17038
  }
17412
17039
  continue;
17413
17040
  }
@@ -17524,15 +17151,16 @@ var usageFields = /* @__PURE__ */ new Set([
17524
17151
  "totalCredits",
17525
17152
  "contextUsagePercent",
17526
17153
  "outputTokensPerSecond",
17154
+ "sessionOutputTokensPerSecond",
17527
17155
  "apiOutputTokensPerSecond",
17528
17156
  "costSource",
17529
17157
  "unpricedModels"
17530
17158
  ]);
17531
- function isRecord2(value) {
17159
+ function isRecord(value) {
17532
17160
  return typeof value === "object" && value !== null && !Array.isArray(value);
17533
17161
  }
17534
17162
  function parseHostUsage(value) {
17535
- if (!isRecord2(value))
17163
+ if (!isRecord(value))
17536
17164
  throw new Error("Harness Usage must be an object");
17537
17165
  const keys = Object.keys(value);
17538
17166
  if (keys.length === 0)
@@ -17546,6 +17174,7 @@ function parseHostUsage(value) {
17546
17174
  for (const field2 of [
17547
17175
  "totalCredits",
17548
17176
  "contextUsagePercent",
17177
+ "sessionOutputTokensPerSecond",
17549
17178
  "apiOutputTokensPerSecond"
17550
17179
  ]) {
17551
17180
  const candidate = value[field2];
@@ -17579,7 +17208,7 @@ function parseHostUsage(value) {
17579
17208
  }
17580
17209
  if (value.sessionCacheUsage !== void 0) {
17581
17210
  const totals2 = value.sessionCacheUsage;
17582
- if (!isRecord2(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
17211
+ if (!isRecord(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
17583
17212
  throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
17584
17213
  }
17585
17214
  }
@@ -17613,192 +17242,694 @@ function parseHostUsage(value) {
17613
17242
  if (value.costSource !== "publicPrice") {
17614
17243
  throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
17615
17244
  }
17616
- return { ...value, ...indicators, unpricedModels: [...models] };
17245
+ return { ...value, ...indicators, unpricedModels: [...models] };
17246
+ }
17247
+ return { ...value, ...indicators };
17248
+ }
17249
+ var requestTokenFields = [
17250
+ "inputTokens",
17251
+ "cachedInputTokens",
17252
+ "cacheWriteInputTokens",
17253
+ "cacheWrite1hInputTokens",
17254
+ "outputTokens",
17255
+ "reasoningOutputTokens",
17256
+ "startedAtMs",
17257
+ "completedAtMs"
17258
+ ];
17259
+ var requestFields = /* @__PURE__ */ new Set([
17260
+ ...requestTokenFields,
17261
+ "requestId",
17262
+ "historical",
17263
+ "model",
17264
+ "provider"
17265
+ ]);
17266
+ function parseHostUsageRequest(value) {
17267
+ if (!isRecord(value))
17268
+ throw new Error("Harness Usage request must be an object");
17269
+ for (const key of Object.keys(value)) {
17270
+ if (!requestFields.has(key)) {
17271
+ throw new Error(`Harness Usage request contains unknown field '${key}'`);
17272
+ }
17273
+ }
17274
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17275
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17276
+ }
17277
+ for (const field2 of ["model", "provider"]) {
17278
+ const candidate = value[field2];
17279
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17280
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
17281
+ }
17282
+ }
17283
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17284
+ throw new Error("Harness Usage request 'historical' must be a boolean");
17285
+ }
17286
+ for (const field2 of requestTokenFields) {
17287
+ const candidate = value[field2];
17288
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17289
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
17290
+ }
17291
+ }
17292
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17293
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17294
+ }
17295
+ const request = value;
17296
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17297
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17298
+ }
17299
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17300
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17301
+ }
17302
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17303
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17304
+ }
17305
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17306
+ throw new Error("Harness Usage request timing fields must be provided together");
17307
+ }
17308
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17309
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17310
+ }
17311
+ return { ...request };
17312
+ }
17313
+
17314
+ // ../../harness-adapter/dist/live-command-catalog.js
17315
+ var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17316
+ // Session lifecycle
17317
+ "branch",
17318
+ "clear",
17319
+ "exit",
17320
+ "fork",
17321
+ "fresh",
17322
+ "new",
17323
+ "quit",
17324
+ "rename",
17325
+ "rename-chat",
17326
+ "reset",
17327
+ "resume",
17328
+ "rewind",
17329
+ "session",
17330
+ "sessions",
17331
+ // Desktop-owned configuration
17332
+ "autocompact",
17333
+ "color",
17334
+ "config",
17335
+ "effort",
17336
+ "fast",
17337
+ "keybindings",
17338
+ "model",
17339
+ "models",
17340
+ "output-style",
17341
+ "permissions",
17342
+ "settings",
17343
+ "statusline",
17344
+ "terminal-setup",
17345
+ "theme",
17346
+ "vim",
17347
+ // Trust and approval policy
17348
+ "always-approve",
17349
+ "auto-mode-setup",
17350
+ // Native login
17351
+ "login",
17352
+ "logout",
17353
+ // Work outliving the Turn
17354
+ "autopilot",
17355
+ "background",
17356
+ "bg",
17357
+ "goal",
17358
+ "jobs",
17359
+ "loop",
17360
+ "multitask",
17361
+ "queue",
17362
+ "remote-control",
17363
+ "schedule",
17364
+ "steer",
17365
+ // Native terminal UI
17366
+ "copy",
17367
+ "debug",
17368
+ "feedback",
17369
+ "heapdump",
17370
+ "share",
17371
+ "shell",
17372
+ // Plugin and MCP management
17373
+ "marketplace",
17374
+ "mcp",
17375
+ "plugins",
17376
+ "reload-plugins"
17377
+ ]);
17378
+ var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
17379
+ function isExcludedLiveCommand(name, extra = {}) {
17380
+ const normalized = name.trim().replace(/^\//u, "");
17381
+ if (new Set(extra.names ?? []).has(normalized))
17382
+ return true;
17383
+ if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
17384
+ return true;
17385
+ return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
17386
+ }
17387
+ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17388
+ if (!commandId.startsWith(idPrefix))
17389
+ return null;
17390
+ const descriptor = catalog.commands.find(({ id }) => id === commandId);
17391
+ if (!descriptor)
17392
+ return null;
17393
+ const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
17394
+ return text4 ? `${descriptor.invocation} ${text4}` : descriptor.invocation;
17395
+ }
17396
+ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17397
+ if (!live)
17398
+ return builtIns;
17399
+ const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17400
+ const ids = new Set(builtIns.commands.map(({ id }) => id));
17401
+ const dynamic = [];
17402
+ for (const command of live) {
17403
+ const name = command.name.trim().replace(/^\//u, "");
17404
+ if (!name || /\s/u.test(name))
17405
+ continue;
17406
+ if (isExcludedLiveCommand(name, exclusions))
17407
+ continue;
17408
+ const invocation = `/${name}`;
17409
+ const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17410
+ if (invocations.has(invocation) || ids.has(id))
17411
+ continue;
17412
+ const description = command.description?.trim().slice(0, 512);
17413
+ const parsed = harnessCommandDescriptorSchema.safeParse({
17414
+ id,
17415
+ invocation,
17416
+ label: name.slice(0, 128),
17417
+ ...description ? { description } : {},
17418
+ argumentMode: "text"
17419
+ });
17420
+ if (!parsed.success)
17421
+ continue;
17422
+ invocations.add(invocation);
17423
+ ids.add(id);
17424
+ dynamic.push(parsed.data);
17425
+ }
17426
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17427
+ }
17428
+
17429
+ // ../../harness-adapter/dist/subagent-configuration.js
17430
+ function subagentConfiguration(value) {
17431
+ if (typeof value !== "object" || value === null || Array.isArray(value))
17432
+ return {};
17433
+ const row = value;
17434
+ const text4 = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
17435
+ const model2 = row.model === "inherit" ? void 0 : text4(row.model);
17436
+ const reasoningEffort = text4(row.reasoningEffort) ?? text4(row.reasoning_effort) ?? text4(row.thinking);
17437
+ return { ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17438
+ }
17439
+ function inheritSubagentConfiguration(child, parent) {
17440
+ const native = subagentConfiguration(child);
17441
+ const model2 = native.model ?? parent.model;
17442
+ const reasoningEffort = native.reasoningEffort ?? parent.reasoningEffort;
17443
+ const next = { ...child };
17444
+ delete next.model;
17445
+ delete next.reasoningEffort;
17446
+ return { ...next, ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17447
+ }
17448
+ function configureSubagentEvent(event, parent) {
17449
+ const children = (states2) => states2.map((child) => inheritSubagentConfiguration(child, parent));
17450
+ if (event.type === "item.started" && event.item.type === "subagentDelegation")
17451
+ return { ...event, item: { ...event.item, subagents: children(event.item.subagents) } };
17452
+ if (event.type === "item.updated" && event.update.type === "subagents.replace")
17453
+ return { ...event, update: { ...event.update, subagents: children(event.update.subagents) } };
17454
+ if (event.type === "item.completed" && event.snapshot.item.type === "subagentDelegation")
17455
+ return {
17456
+ ...event,
17457
+ snapshot: {
17458
+ ...event.snapshot,
17459
+ item: {
17460
+ ...event.snapshot.item,
17461
+ subagents: children(event.snapshot.item.subagents)
17462
+ }
17463
+ }
17464
+ };
17465
+ return event;
17466
+ }
17467
+ function configureSubagentSnapshot(snapshot, parent) {
17468
+ return {
17469
+ ...snapshot,
17470
+ turns: snapshot.turns.map((turn) => ({
17471
+ ...turn,
17472
+ items: turn.items.map((entry) => entry.item.type === "subagentDelegation" ? {
17473
+ ...entry,
17474
+ item: {
17475
+ ...entry.item,
17476
+ subagents: entry.item.subagents.map((child) => inheritSubagentConfiguration(child, parent))
17477
+ }
17478
+ } : entry)
17479
+ }))
17480
+ };
17481
+ }
17482
+
17483
+ // ../../harness-adapter/dist/usage-statistics.js
17484
+ import { createReadStream } from "node:fs";
17485
+ import { lstat, opendir } from "node:fs/promises";
17486
+ import path4 from "node:path";
17487
+ import { createInterface } from "node:readline";
17488
+ var MAX_SESSION_ID_LENGTH = 512;
17489
+ var MAX_CWD_LENGTH = 4096;
17490
+ var MAX_SESSION_TITLE_LENGTH = 200;
17491
+ function usageSessionTitle(value) {
17492
+ if (typeof value !== "string")
17493
+ return void 0;
17494
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17495
+ if (!normalized)
17496
+ return void 0;
17497
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17498
+ return normalized;
17499
+ let title = "";
17500
+ for (const character of normalized) {
17501
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17502
+ break;
17503
+ title += character;
17504
+ }
17505
+ return `${title.trimEnd()}…`;
17506
+ }
17507
+ function sessionIdOk(value) {
17508
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17509
+ }
17510
+ function cwdOk(value) {
17511
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
17512
+ }
17513
+ function withUsageSession(entry, session) {
17514
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
17515
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
17516
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
17517
+ if (sessionId === void 0 && cwd === void 0)
17518
+ return entry;
17519
+ return {
17520
+ ...entry,
17521
+ ...sessionId !== void 0 ? { sessionId } : {},
17522
+ ...cwd !== void 0 ? { cwd } : {},
17523
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
17524
+ };
17525
+ }
17526
+ function usageEntryFromRequest(request, occurredAtMs) {
17527
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
17528
+ return null;
17529
+ return {
17530
+ id: request.requestId,
17531
+ occurredAtMs,
17532
+ ...request.model !== void 0 ? { model: request.model } : {},
17533
+ inputTokens: request.inputTokens,
17534
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
17535
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
17536
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
17537
+ outputTokens: request.outputTokens,
17538
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
17539
+ };
17540
+ }
17541
+ async function jsonlUsageSources(root, maxDepth, signal) {
17542
+ const sources = [];
17543
+ const visit = async (directory, depth) => {
17544
+ signal.throwIfAborted();
17545
+ const entries = await opendir(directory).catch((error51) => {
17546
+ if (error51.code === "ENOENT")
17547
+ return null;
17548
+ throw error51;
17549
+ });
17550
+ if (!entries)
17551
+ return;
17552
+ for await (const entry of entries) {
17553
+ signal.throwIfAborted();
17554
+ const file2 = path4.join(directory, entry.name);
17555
+ if (entry.isDirectory()) {
17556
+ if (depth < maxDepth)
17557
+ await visit(file2, depth + 1);
17558
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
17559
+ const info = await lstat(file2).catch(() => null);
17560
+ if (info?.isFile() && info.size > 0) {
17561
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
17562
+ }
17563
+ }
17564
+ }
17565
+ };
17566
+ await visit(root, 0);
17567
+ return sources;
17568
+ }
17569
+ async function* jsonlRecords(file2, marker, signal) {
17570
+ const lines = createInterface({
17571
+ input: createReadStream(file2, { encoding: "utf8", signal }),
17572
+ crlfDelay: Infinity
17573
+ });
17574
+ for await (const line of lines) {
17575
+ if (!line.includes(marker))
17576
+ continue;
17577
+ let value;
17578
+ try {
17579
+ value = JSON.parse(line);
17580
+ } catch {
17581
+ continue;
17582
+ }
17583
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17584
+ yield value;
17585
+ }
17586
+ }
17587
+ }
17588
+ async function jsonlHeader(file2, match, signal, maxLines = 4) {
17589
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
17590
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
17591
+ let seen = 0;
17592
+ try {
17593
+ for await (const line of lines) {
17594
+ if (++seen > maxLines)
17595
+ break;
17596
+ let value;
17597
+ try {
17598
+ value = JSON.parse(line);
17599
+ } catch {
17600
+ continue;
17601
+ }
17602
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
17603
+ const record10 = value;
17604
+ if (match(record10))
17605
+ return record10;
17606
+ }
17607
+ }
17608
+ return null;
17609
+ } finally {
17610
+ lines.close();
17611
+ stream.destroy();
17612
+ }
17613
+ }
17614
+ function nativeTimeMs(value) {
17615
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
17616
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
17617
+ }
17618
+
17619
+ // dist/pi-session-import.js
17620
+ import { createReadStream as createReadStream2 } from "node:fs";
17621
+ import { opendir as opendir2, realpath, stat } from "node:fs/promises";
17622
+ import os2 from "node:os";
17623
+ import path5 from "node:path";
17624
+ import { createInterface as createInterface2 } from "node:readline";
17625
+
17626
+ // ../../harness-adapter/dist/session-import.js
17627
+ var SessionImportChangedError = class extends Error {
17628
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
17629
+ super(message3);
17630
+ this.name = "SessionImportChangedError";
17631
+ }
17632
+ };
17633
+ function isMissingFileError(error51) {
17634
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17635
+ }
17636
+ function sameFileFingerprint(left, right) {
17637
+ return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
17638
+ }
17639
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
17640
+ if (typeof value !== "string")
17641
+ return null;
17642
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17643
+ if (!normalized)
17644
+ return null;
17645
+ if (normalized.length <= maxLength)
17646
+ return normalized;
17647
+ const characters = [...normalized];
17648
+ if (characters.length <= maxLength)
17649
+ return normalized;
17650
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
17651
+ }
17652
+ function sessionImportCandidate(input) {
17653
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
17654
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
17655
+ nativeSessionId: input.nativeSessionId,
17656
+ cwd: input.cwd,
17657
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
17658
+ updatedAt: Math.floor(time3),
17659
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
17660
+ running: typeof input.running === "boolean" ? input.running : null
17661
+ });
17662
+ return parsed.success ? parsed.data : null;
17663
+ }
17664
+ var SessionImportScope = class {
17665
+ #abort = new AbortController();
17666
+ #options;
17667
+ #pending = /* @__PURE__ */ new Set();
17668
+ constructor(options) {
17669
+ this.#options = options;
17670
+ }
17671
+ #closed() {
17672
+ return {
17673
+ ok: false,
17674
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
17675
+ };
17676
+ }
17677
+ read(operation) {
17678
+ const signal = this.#abort.signal;
17679
+ if (signal.aborted)
17680
+ return Promise.resolve(this.#closed());
17681
+ let started;
17682
+ try {
17683
+ started = operation(signal);
17684
+ } catch (error51) {
17685
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17686
+ }
17687
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
17688
+ ok: false,
17689
+ error: {
17690
+ code: "unavailable",
17691
+ message: this.#options.unavailableMessage,
17692
+ retryable: true
17693
+ }
17694
+ }).finally(() => this.#pending.delete(request));
17695
+ this.#pending.add(request);
17696
+ return request;
17697
+ }
17698
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
17699
+ async resolve(operation) {
17700
+ const result = await this.read(operation);
17701
+ if (!result.ok)
17702
+ return result;
17703
+ return result.value ? { ok: true, value: result.value } : {
17704
+ ok: false,
17705
+ error: {
17706
+ code: "sessionNotFound",
17707
+ message: this.#options.notFoundMessage,
17708
+ retryable: false
17709
+ }
17710
+ };
17711
+ }
17712
+ /** Idempotent. Resolves after every started read has settled. */
17713
+ async close() {
17714
+ this.#abort.abort();
17715
+ await Promise.allSettled(this.#pending);
17716
+ }
17717
+ };
17718
+
17719
+ // dist/pi-session-import.js
17720
+ var PI_SESSION_CHANGED = "Pi Session changed during discovery; refresh and retry";
17721
+ function isRecord2(value) {
17722
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17723
+ }
17724
+ function expandDirectory(value, home) {
17725
+ return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
17726
+ }
17727
+ function piSessionImportDirectory(environment) {
17728
+ const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
17729
+ const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
17730
+ if (custom2)
17731
+ return { directory: expandDirectory(custom2, home), flat: true };
17732
+ const agent = environment.PI_CODING_AGENT_DIR;
17733
+ return {
17734
+ directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".pi", "agent"), "sessions"),
17735
+ flat: false
17736
+ };
17737
+ }
17738
+ async function sessionFiles(directory, flat, signal) {
17739
+ const files = [];
17740
+ const visit = async (dir, projectLevel) => {
17741
+ signal.throwIfAborted();
17742
+ const entries = await opendir2(dir).catch((error51) => {
17743
+ if (isMissingFileError(error51))
17744
+ return null;
17745
+ throw error51;
17746
+ });
17747
+ if (!entries)
17748
+ return;
17749
+ for await (const entry of entries) {
17750
+ signal.throwIfAborted();
17751
+ if (projectLevel && entry.isDirectory())
17752
+ await visit(path5.join(dir, entry.name), false);
17753
+ else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl")) {
17754
+ files.push(path5.join(dir, entry.name));
17755
+ }
17756
+ }
17757
+ };
17758
+ await visit(directory, !flat);
17759
+ return files;
17760
+ }
17761
+ async function readCandidate(file2, signal) {
17762
+ const before = await stat(file2);
17763
+ if (!before.isFile() || before.size === 0)
17764
+ return null;
17765
+ const stream = createReadStream2(file2, { encoding: "utf8", signal, end: before.size - 1 });
17766
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17767
+ let header;
17768
+ let name = null;
17769
+ let firstMessage = null;
17770
+ let hasUser = false;
17771
+ let updatedAt = before.mtimeMs;
17772
+ const entries = /* @__PURE__ */ new Map();
17773
+ try {
17774
+ for await (const line of lines) {
17775
+ signal.throwIfAborted();
17776
+ if (!line.trim())
17777
+ continue;
17778
+ let entry;
17779
+ try {
17780
+ entry = JSON.parse(line);
17781
+ } catch {
17782
+ return null;
17783
+ }
17784
+ if (!isRecord2(entry))
17785
+ return null;
17786
+ if (!header) {
17787
+ if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
17788
+ return null;
17789
+ header = entry;
17790
+ continue;
17791
+ }
17792
+ if (typeof entry.id !== "string" || entry.id.length === 0 || entries.has(entry.id) || entry.parentId !== null && (typeof entry.parentId !== "string" || !entries.has(entry.parentId)))
17793
+ return null;
17794
+ const message3 = isRecord2(entry.message) ? entry.message : null;
17795
+ if (!firstMessage && entry.type === "message" && message3?.role === "user") {
17796
+ const content = message3.content;
17797
+ const text4 = typeof content === "string" ? content : Array.isArray(content) ? content.filter((block) => isRecord2(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ") : "";
17798
+ firstMessage = sessionImportTitle(text4);
17799
+ }
17800
+ hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
17801
+ entries.set(entry.id, hasUser);
17802
+ if (entry.type === "session_info")
17803
+ name = sessionImportTitle(entry.name);
17804
+ if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
17805
+ const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
17806
+ if (Number.isFinite(time3))
17807
+ updatedAt = time3;
17808
+ }
17809
+ }
17810
+ } finally {
17811
+ lines.close();
17812
+ stream.destroy();
17813
+ }
17814
+ if (!header)
17815
+ return null;
17816
+ if (!hasUser)
17817
+ return null;
17818
+ const after = await stat(file2);
17819
+ if (!sameFileFingerprint(before, after))
17820
+ throw new SessionImportChangedError(PI_SESSION_CHANGED);
17821
+ const cwd = await realpath(String(header.cwd));
17822
+ if (!(await stat(cwd)).isDirectory())
17823
+ return null;
17824
+ const nativeRef = nativeSessionRefSchema.safeParse({
17825
+ harnessId: "pi",
17826
+ nativeSessionId: header.id,
17827
+ locator: { sessionFile: await realpath(file2) },
17828
+ formatVersion: 1
17829
+ });
17830
+ const candidate = sessionImportCandidate({
17831
+ nativeSessionId: header.id,
17832
+ cwd,
17833
+ title: name ?? firstMessage,
17834
+ updatedAt
17835
+ });
17836
+ return candidate && nativeRef.success ? { candidate, nativeRef: nativeRef.data } : null;
17837
+ }
17838
+ async function readIdentity(file2, signal) {
17839
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
17840
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17841
+ try {
17842
+ for await (const line of lines) {
17843
+ signal.throwIfAborted();
17844
+ if (!line.trim())
17845
+ continue;
17846
+ let header;
17847
+ try {
17848
+ header = JSON.parse(line);
17849
+ } catch {
17850
+ return null;
17851
+ }
17852
+ return isRecord2(header) && header.type === "session" && header.version === 3 && typeof header.id === "string" ? header.id : null;
17853
+ }
17854
+ return null;
17855
+ } finally {
17856
+ lines.close();
17857
+ stream.destroy();
17617
17858
  }
17618
- return { ...value, ...indicators };
17619
17859
  }
17620
- var requestTokenFields = [
17621
- "inputTokens",
17622
- "cachedInputTokens",
17623
- "cacheWriteInputTokens",
17624
- "cacheWrite1hInputTokens",
17625
- "outputTokens",
17626
- "reasoningOutputTokens",
17627
- "startedAtMs",
17628
- "completedAtMs"
17629
- ];
17630
- var requestFields = /* @__PURE__ */ new Set([
17631
- ...requestTokenFields,
17632
- "requestId",
17633
- "historical",
17634
- "model",
17635
- "provider"
17636
- ]);
17637
- function parseHostUsageRequest(value) {
17638
- if (!isRecord2(value))
17639
- throw new Error("Harness Usage request must be an object");
17640
- for (const key of Object.keys(value)) {
17641
- if (!requestFields.has(key)) {
17642
- throw new Error(`Harness Usage request contains unknown field '${key}'`);
17643
- }
17860
+ var PiSessionImportIndex = class {
17861
+ #location;
17862
+ #cache = /* @__PURE__ */ new Map();
17863
+ #listing;
17864
+ constructor(environment) {
17865
+ this.#location = piSessionImportDirectory(environment);
17644
17866
  }
17645
- if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17646
- throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17867
+ list(signal) {
17868
+ this.#listing ??= this.#scan(signal).finally(() => {
17869
+ this.#listing = void 0;
17870
+ });
17871
+ return this.#listing;
17647
17872
  }
17648
- for (const field2 of ["model", "provider"]) {
17649
- const candidate = value[field2];
17650
- if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17651
- throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
17873
+ async #scan(signal) {
17874
+ const { directory, flat } = this.#location;
17875
+ const files = await sessionFiles(directory, flat, signal);
17876
+ const next = /* @__PURE__ */ new Map();
17877
+ const identities = /* @__PURE__ */ new Set();
17878
+ const sources = [];
17879
+ for (const file2 of files) {
17880
+ signal.throwIfAborted();
17881
+ try {
17882
+ const fingerprint = await stat(file2);
17883
+ const cached2 = this.#cache.get(file2);
17884
+ const source = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source : await readCandidate(file2, signal);
17885
+ if (!source)
17886
+ continue;
17887
+ if (!(await stat(source.candidate.cwd)).isDirectory())
17888
+ continue;
17889
+ if (identities.has(source.nativeRef.nativeSessionId))
17890
+ throw new Error("Pi Session identity is ambiguous across files");
17891
+ identities.add(source.nativeRef.nativeSessionId);
17892
+ next.set(file2, { fingerprint, source });
17893
+ sources.push(source);
17894
+ } catch (error51) {
17895
+ if (!isMissingFileError(error51) && !(error51 instanceof SessionImportChangedError))
17896
+ throw error51;
17897
+ }
17652
17898
  }
17899
+ this.#cache = next;
17900
+ return structuredClone(sources.sort((left, right) => right.candidate.updatedAt - left.candidate.updatedAt));
17653
17901
  }
17654
- if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17655
- throw new Error("Harness Usage request 'historical' must be a boolean");
17656
- }
17657
- for (const field2 of requestTokenFields) {
17658
- const candidate = value[field2];
17659
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17660
- throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
17902
+ async resolve(nativeSessionId, signal) {
17903
+ const { directory, flat } = this.#location;
17904
+ let selected;
17905
+ for (const file2 of await sessionFiles(directory, flat, signal)) {
17906
+ signal.throwIfAborted();
17907
+ try {
17908
+ const fingerprint = await stat(file2);
17909
+ const cached2 = this.#cache.get(file2);
17910
+ const id = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source.nativeRef.nativeSessionId : await readIdentity(file2, signal);
17911
+ if (id !== nativeSessionId)
17912
+ continue;
17913
+ if (selected)
17914
+ throw new Error("Pi Session identity is ambiguous across files");
17915
+ selected = file2;
17916
+ } catch (error51) {
17917
+ if (!isMissingFileError(error51))
17918
+ throw error51;
17919
+ }
17920
+ }
17921
+ if (!selected)
17922
+ return null;
17923
+ try {
17924
+ const source = await readCandidate(selected, signal);
17925
+ return source?.nativeRef.nativeSessionId === nativeSessionId ? source : null;
17926
+ } catch (error51) {
17927
+ if (isMissingFileError(error51))
17928
+ return null;
17929
+ throw error51;
17661
17930
  }
17662
17931
  }
17663
- if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17664
- throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17665
- }
17666
- const request = value;
17667
- if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17668
- throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17669
- }
17670
- if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17671
- throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17672
- }
17673
- if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17674
- throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17675
- }
17676
- if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17677
- throw new Error("Harness Usage request timing fields must be provided together");
17678
- }
17679
- if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17680
- throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17681
- }
17682
- return { ...request };
17683
- }
17684
-
17685
- // ../../harness-adapter/dist/live-command-catalog.js
17686
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17687
- // Session lifecycle
17688
- "branch",
17689
- "clear",
17690
- "exit",
17691
- "fork",
17692
- "fresh",
17693
- "new",
17694
- "quit",
17695
- "rename",
17696
- "rename-chat",
17697
- "reset",
17698
- "resume",
17699
- "rewind",
17700
- "session",
17701
- "sessions",
17702
- // Desktop-owned configuration
17703
- "autocompact",
17704
- "color",
17705
- "config",
17706
- "effort",
17707
- "fast",
17708
- "keybindings",
17709
- "model",
17710
- "models",
17711
- "output-style",
17712
- "permissions",
17713
- "settings",
17714
- "statusline",
17715
- "terminal-setup",
17716
- "theme",
17717
- "vim",
17718
- // Trust and approval policy
17719
- "always-approve",
17720
- "auto-mode-setup",
17721
- // Native login
17722
- "login",
17723
- "logout",
17724
- // Work outliving the Turn
17725
- "autopilot",
17726
- "background",
17727
- "bg",
17728
- "goal",
17729
- "jobs",
17730
- "loop",
17731
- "multitask",
17732
- "queue",
17733
- "remote-control",
17734
- "schedule",
17735
- "steer",
17736
- // Native terminal UI
17737
- "copy",
17738
- "debug",
17739
- "feedback",
17740
- "heapdump",
17741
- "share",
17742
- "shell",
17743
- // Plugin and MCP management
17744
- "marketplace",
17745
- "mcp",
17746
- "plugins",
17747
- "reload-plugins"
17748
- ]);
17749
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
17750
- function isExcludedLiveCommand(name, kind, extra = {}) {
17751
- const normalized = name.trim().replace(/^\//u, "");
17752
- if (new Set(extra.names ?? []).has(normalized))
17753
- return true;
17754
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
17755
- return true;
17756
- if (kind === "skill")
17757
- return false;
17758
- return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
17759
- }
17760
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17761
- if (!commandId.startsWith(idPrefix))
17762
- return null;
17763
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
17764
- if (!descriptor)
17765
- return null;
17766
- const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
17767
- return text4 ? `${descriptor.invocation} ${text4}` : descriptor.invocation;
17768
- }
17769
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17770
- if (!live)
17771
- return builtIns;
17772
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17773
- const ids = new Set(builtIns.commands.map(({ id }) => id));
17774
- const dynamic = [];
17775
- for (const command of live) {
17776
- const name = command.name.trim().replace(/^\//u, "");
17777
- if (!name || /\s/u.test(name))
17778
- continue;
17779
- if (isExcludedLiveCommand(name, command.kind, exclusions))
17780
- continue;
17781
- const invocation = `/${name}`;
17782
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17783
- if (invocations.has(invocation) || ids.has(id))
17784
- continue;
17785
- const description = command.description?.trim().slice(0, 512);
17786
- const parsed = harnessCommandDescriptorSchema.safeParse({
17787
- id,
17788
- invocation,
17789
- label: name.slice(0, 128),
17790
- ...description ? { description } : {},
17791
- argumentMode: "text",
17792
- kind: command.kind
17793
- });
17794
- if (!parsed.success)
17795
- continue;
17796
- invocations.add(invocation);
17797
- ids.add(id);
17798
- dynamic.push(parsed.data);
17799
- }
17800
- return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17801
- }
17932
+ };
17802
17933
 
17803
17934
  // ../../../node_modules/diff/libesm/diff/base.js
17804
17935
  var Diff = class {
@@ -18727,6 +18858,7 @@ function gotgenesRecord(value) {
18727
18858
  role: value.type,
18728
18859
  status,
18729
18860
  background: value.isBackground === true,
18861
+ ...subagentConfiguration(value),
18730
18862
  ...text(value.modelName) ? { model: value.modelName } : {},
18731
18863
  ...result ? { resultSummary: result.slice(0, 2048) } : {}
18732
18864
  },
@@ -18854,7 +18986,7 @@ var GotgenesSubagents = class {
18854
18986
  this.observe([
18855
18987
  {
18856
18988
  ...prior,
18857
- child: { ...prior.child, ...parsed.child.model ? { model: parsed.child.model } : {} }
18989
+ child: { ...prior.child, ...subagentConfiguration(parsed.child) }
18858
18990
  }
18859
18991
  ]);
18860
18992
  }
@@ -19017,6 +19149,7 @@ function node(value, depth, budget) {
19017
19149
  kind: value.kind,
19018
19150
  label: value.label,
19019
19151
  state: value.state,
19152
+ ...subagentConfiguration(value),
19020
19153
  ...children.length ? { children } : {}
19021
19154
  };
19022
19155
  }
@@ -19075,6 +19208,7 @@ function states(run) {
19075
19208
  subagentId: id,
19076
19209
  nativeSubagentId: id,
19077
19210
  description: entry.label,
19211
+ ...subagentConfiguration(entry),
19078
19212
  background: true,
19079
19213
  status: statuses[entry.state] ?? "running"
19080
19214
  });
@@ -19121,7 +19255,7 @@ var PiSubagents = class {
19121
19255
  const observed = states(run);
19122
19256
  const retained = this.#children.get(run.id) ?? /* @__PURE__ */ new Map();
19123
19257
  for (const child of observed)
19124
- retained.set(child.subagentId, child);
19258
+ retained.set(child.subagentId, { ...retained.get(child.subagentId), ...child });
19125
19259
  this.#children.set(run.id, retained);
19126
19260
  const children = [...retained.values()];
19127
19261
  if (!publish)
@@ -21207,10 +21341,9 @@ function parsePiNativeCommands(response) {
21207
21341
  });
21208
21342
  }
21209
21343
  function piLiveCommandCatalog(builtIns, native) {
21210
- return mergeLiveHarnessCommands(builtIns, DYNAMIC_ID_PREFIX, native?.map((command) => ({
21344
+ return mergeLiveHarnessCommands(builtIns, DYNAMIC_ID_PREFIX, native?.filter((command) => command.source !== "skill").map((command) => ({
21211
21345
  name: command.name,
21212
- ...command.description ? { description: command.description } : {},
21213
- kind: command.source === "skill" ? "skill" : "command"
21346
+ ...command.description ? { description: command.description } : {}
21214
21347
  })) ?? null, { names: PI_EXCLUDED_COMMANDS });
21215
21348
  }
21216
21349
  function piDynamicCommandPrompt(catalog, commandId, argumentText) {
@@ -21769,6 +21902,7 @@ var PiRpcSession = class {
21769
21902
  #autonomousLifecycleHandler = null;
21770
21903
  #usageHandler = null;
21771
21904
  #usageRequestStartedAtMs = null;
21905
+ #usageRequestTimingUnavailable = false;
21772
21906
  // Pieces of the unterminated frame; joined once at its newline so a large frame (a long
21773
21907
  // Session's get_entries) costs linear rather than quadratic copying on the Host event loop.
21774
21908
  #buffer = [];
@@ -21844,14 +21978,29 @@ var PiRpcSession = class {
21844
21978
  /** Every finished assistant message is one model request, with or without an active Turn. */
21845
21979
  #observeUsage(value) {
21846
21980
  if (value.type === "message_start") {
21847
- if (isRecord9(value.message) && value.message.role === "assistant")
21981
+ if (isRecord9(value.message) && value.message.role === "assistant") {
21848
21982
  this.#usageRequestStartedAtMs = null;
21983
+ this.#usageRequestTimingUnavailable = false;
21984
+ }
21849
21985
  return;
21850
21986
  }
21851
21987
  if (value.type === "message_update") {
21852
21988
  const event = value.assistantMessageEvent;
21853
- if (this.#usageRequestStartedAtMs === null && isRecord9(event) && typeof event.type === "string" && /^(text|thinking|reasoning|thought|toolcall)_(start|delta)$/u.test(event.type)) {
21854
- this.#usageRequestStartedAtMs = Date.now();
21989
+ if (this.#usageRequestStartedAtMs === null && !this.#usageRequestTimingUnavailable && isRecord9(event) && typeof event.type === "string") {
21990
+ if (
21991
+ // Native thinking starts can precede visible text by seconds; output usage includes it.
21992
+ /^(thinking|reasoning|thought)_start$/u.test(event.type) || /^(text|thinking|reasoning|thought)_delta$/u.test(event.type) && typeof event.delta === "string" && event.delta.length > 0
21993
+ )
21994
+ this.#usageRequestStartedAtMs = Date.now();
21995
+ else if (event.type === "toolcall_delta" && typeof event.delta === "string" && event.delta.length > 0) {
21996
+ try {
21997
+ JSON.parse(event.delta);
21998
+ this.#usageRequestTimingUnavailable = true;
21999
+ } catch {
22000
+ this.#usageRequestStartedAtMs = Date.now();
22001
+ }
22002
+ } else if (event.type === "toolcall_end")
22003
+ this.#usageRequestTimingUnavailable = true;
21855
22004
  }
21856
22005
  return;
21857
22006
  }
@@ -21906,6 +22055,9 @@ var PiRpcSession = class {
21906
22055
  child.stderr.on("data", (chunk) => {
21907
22056
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
21908
22057
  });
22058
+ child.stdin.on("error", (error51) => {
22059
+ this.#fail(new PiRpcFaultError("processExited", `Pi RPC stdin closed: ${error51.message}`, this.stderrTail));
22060
+ });
21909
22061
  child.once("error", (error51) => {
21910
22062
  const kind = isRecord9(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
21911
22063
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
@@ -23284,7 +23436,19 @@ var PiHarnessSession = class {
23284
23436
  handleTransportFault(error51) {
23285
23437
  queueMicrotask(() => this.#fault(error51));
23286
23438
  }
23439
+ #subagentConfiguration() {
23440
+ const state2 = this.#state;
23441
+ const model2 = state2.effectiveModel ? decodePiModelRef(state2.effectiveModel).id : void 0;
23442
+ return {
23443
+ ...model2 ? { model: model2 } : {},
23444
+ ...state2.effectiveThinkingOptionId ? { reasoningEffort: state2.effectiveThinkingOptionId } : {}
23445
+ };
23446
+ }
23287
23447
  async readSnapshot() {
23448
+ const result = await this.#readSnapshot();
23449
+ return result.ok ? { ok: true, value: configureSubagentSnapshot(result.value, this.#subagentConfiguration()) } : result;
23450
+ }
23451
+ async #readSnapshot() {
23288
23452
  if (this.#phase !== "open") {
23289
23453
  return { ok: false, error: invalidState("Pi Session is not open") };
23290
23454
  }
@@ -24589,6 +24753,7 @@ var PiHarnessSession = class {
24589
24753
  }
24590
24754
  }
24591
24755
  #event(event) {
24756
+ event = configureSubagentEvent(event, this.#subagentConfiguration());
24592
24757
  this.#channel.emit({ kind: "event", event });
24593
24758
  }
24594
24759
  #newItemId() {