@karlorz/codexhost-cli-win32-x64 0.18.0-1 → 0.19.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.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +59 -2
  4. package/app/console-web.js +98 -8
  5. package/app/cpa-live-voice-hook.js +59 -2
  6. package/app/desktop-controller.mjs +290 -12
  7. package/app/host-runtime.mjs +12896 -2966
  8. package/app/plugins/antigravity/plugin.mjs +654 -216
  9. package/app/plugins/claude-code/plugin.mjs +138 -11
  10. package/app/plugins/codebuddy/plugin.mjs +152 -20
  11. package/app/plugins/codex-usage/plugin.mjs +59 -2
  12. package/app/plugins/copilot/plugin.mjs +59 -2
  13. package/app/plugins/cursor-cli/plugin.mjs +134 -12
  14. package/app/plugins/deepseek-harness/manifest.json +2 -2
  15. package/app/plugins/deepseek-harness/plugin.mjs +86 -7
  16. package/app/plugins/devin/plugin.mjs +59 -2
  17. package/app/plugins/grok/plugin.mjs +1093 -970
  18. package/app/plugins/hermes/plugin.mjs +138 -14
  19. package/app/plugins/kimi-code/plugin.mjs +59 -2
  20. package/app/plugins/kiro-cli/plugin.mjs +287 -18
  21. package/app/plugins/omp/plugin.mjs +789 -628
  22. package/app/plugins/opencode/plugin.mjs +59 -2
  23. package/app/plugins/pi/plugin.mjs +786 -660
  24. package/app/plugins/qoder/plugin.mjs +61 -6
  25. package/app/plugins/qoder-cn/plugin.mjs +61 -6
  26. package/app/plugins/qwen-code/plugin.mjs +168 -94
  27. package/app/plugins/workbuddy/plugin.mjs +152 -20
  28. package/app/plugins/zcode/plugin.mjs +132 -5
  29. package/app/renderer-extension.js +434 -39
  30. package/app/web/assets/{index-py6Ho-Dy.js → index-BCyiiDDL.js} +62 -62
  31. package/app/web/assets/index-BNQIOOHE.css +1 -0
  32. package/app/web/codexhost-settings.js +84 -4
  33. package/app/web/index.html +2 -2
  34. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  36. package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
  37. package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +3 -3
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +129 -8
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +8 -6
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +95 -93
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.excel.js +1 -1
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +16 -16
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  50. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +11 -11
  51. package/app/web-modules/server.mjs +2345 -1518
  52. package/bin/codexhost.exe +0 -0
  53. package/libexec/codexhost-node-repl.exe +0 -0
  54. package/libexec/codexhost-shim.exe +0 -0
  55. package/libexec/codexhost-updater.exe +0 -0
  56. package/package.json +1 -1
  57. 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, {
@@ -16062,6 +15919,10 @@ var CLIENT_CHANNEL_VERSION = 1;
16062
15919
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
16063
15920
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
16064
15921
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15922
+ var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
15923
+ var clientThreadTreeSchema = external_exports.object({
15924
+ parents: external_exports.record(external_exports.string().min(1), external_exports.string().min(1))
15925
+ }).strict();
16065
15926
  var clientProjectlessWorkspaceSchema = external_exports.object({
16066
15927
  prompt: external_exports.string().max(16384).optional()
16067
15928
  }).strict();
@@ -16078,6 +15939,11 @@ var clientChannelCursorSchema = external_exports.object({
16078
15939
  sequence: external_exports.number().int().nonnegative()
16079
15940
  });
16080
15941
  var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
15942
+ external_exports.object({
15943
+ type: external_exports.literal("skills-changed"),
15944
+ cursor: clientChannelCursorSchema,
15945
+ cwd: external_exports.string().optional()
15946
+ }),
16081
15947
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
16082
15948
  external_exports.object({
16083
15949
  type: external_exports.literal("preferences-changed"),
@@ -16275,6 +16141,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
16275
16141
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
16276
16142
  ]);
16277
16143
 
16144
+ // ../../shared-contracts/dist/skills.js
16145
+ var skillsListParamsSchema = external_exports.object({
16146
+ threadId: hostThreadIdSchema.optional(),
16147
+ cwd: external_exports.string().min(1).optional()
16148
+ }).strict().refine((params) => !(params.threadId && params.cwd), {
16149
+ message: "Specify threadId or cwd, not both"
16150
+ });
16151
+ var librarySkillSchema = external_exports.object({
16152
+ name: external_exports.string().min(1).regex(/^[^\s[\]]+$/u),
16153
+ description: external_exports.string().optional(),
16154
+ path: external_exports.string().min(1),
16155
+ scope: external_exports.enum(["project", "global"]),
16156
+ source: external_exports.string().min(1)
16157
+ }).strict();
16158
+ var skillsListResultSchema = external_exports.object({
16159
+ revision: external_exports.number().int().nonnegative(),
16160
+ complete: external_exports.boolean(),
16161
+ skills: external_exports.array(librarySkillSchema),
16162
+ warnings: external_exports.array(external_exports.string()).optional()
16163
+ }).strict();
16164
+ var skillsChangedParamsSchema = external_exports.object({ cwd: external_exports.string().min(1).optional() }).strict();
16165
+
16278
16166
  // ../../shared-contracts/dist/web-access-tokens.js
16279
16167
  var webNetworkAccessUrlSchema = external_exports.object({
16280
16168
  /**
@@ -16380,8 +16268,8 @@ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
16380
16268
  var delegationReadParamsSchema = external_exports.strictObject({
16381
16269
  threadId: external_exports.string().min(1).max(1024),
16382
16270
  view: external_exports.enum(["result", "messages"]),
16383
- cursor: external_exports.string().min(1).max(8192).optional(),
16384
- limit: external_exports.number().int().min(1).max(100).optional()
16271
+ from: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
16272
+ to: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional()
16385
16273
  });
16386
16274
 
16387
16275
  // ../../shared-contracts/dist/credential-imports.js
@@ -17383,6 +17271,17 @@ var updateStatusResultSchema = external_exports.strictObject({
17383
17271
  status: updateStatusSchema.nullable()
17384
17272
  });
17385
17273
 
17274
+ // ../../shared-contracts/dist/thread-watch-notice.js
17275
+ var THREAD_WATCH_NOTICE_OUTCOMES = [
17276
+ "completed",
17277
+ "failed",
17278
+ "interrupted",
17279
+ "timedOut",
17280
+ "unreadable",
17281
+ "notFound"
17282
+ ];
17283
+ var ENTRY_PATTERN = new RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): ` + `(${THREAD_WATCH_NOTICE_OUTCOMES.join("|")})(?:. (.+))?$`, "u");
17284
+
17386
17285
  // ../../shared-contracts/dist/remote-runtime.js
17387
17286
  var remoteUpdatePhaseSchema = external_exports.enum([
17388
17287
  "idle",
@@ -17430,6 +17329,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17430
17329
  archived: external_exports.boolean()
17431
17330
  }),
17432
17331
  external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
17332
+ external_exports.strictObject({
17333
+ kind: external_exports.literal("configure"),
17334
+ ...thread,
17335
+ epoch: identity,
17336
+ modelId: identity.optional(),
17337
+ thinkingOptionId: identity.optional(),
17338
+ permissionModeId: identity.optional()
17339
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17433
17340
  external_exports.strictObject({
17434
17341
  kind: external_exports.literal("prompt"),
17435
17342
  ...thread,
@@ -17502,6 +17409,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17502
17409
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17503
17410
  ]);
17504
17411
 
17412
+ // ../../shared-contracts/dist/thread-title.js
17413
+ var threadTitleInputSchema = external_exports.strictObject({
17414
+ prompt: external_exports.string().trim().min(1).max(2e3),
17415
+ cwd: external_exports.string().max(4096).nullable()
17416
+ });
17417
+ var threadTitleResultSchema = external_exports.string().trim().min(1).max(60).nullable();
17418
+
17505
17419
  // ../../shared-contracts/dist/web-ui-extensions.js
17506
17420
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17507
17421
  var localizedTextSchema2 = external_exports.union([
@@ -17576,339 +17490,31 @@ var threadActivityStopResultSchema = external_exports.strictObject({
17576
17490
  // ../../shared-contracts/dist/index.js
17577
17491
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17578
17492
 
17579
- // ../../harness-adapter/dist/session-import.js
17580
- var SessionImportChangedError = class extends Error {
17581
- constructor(message3 = "Native Session changed during discovery; refresh and retry") {
17582
- super(message3);
17583
- this.name = "SessionImportChangedError";
17584
- }
17585
- };
17586
- function isMissingFileError(error51) {
17587
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
17588
- }
17589
- function sameFileFingerprint(left, right) {
17590
- 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;
17591
- }
17592
- function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
17593
- if (typeof value !== "string")
17594
- return null;
17595
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17596
- if (!normalized)
17597
- return null;
17598
- if (normalized.length <= maxLength)
17599
- return normalized;
17600
- const characters = [...normalized];
17601
- if (characters.length <= maxLength)
17602
- return normalized;
17603
- return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
17604
- }
17605
- function sessionImportCandidate(input) {
17606
- const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
17607
- const parsed = harnessSessionImportCandidateSchema.safeParse({
17608
- nativeSessionId: input.nativeSessionId,
17609
- cwd: input.cwd,
17610
- title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
17611
- updatedAt: Math.floor(time3),
17612
- // Unknown must stay unknown; only an explicit boolean is a native statement.
17613
- running: typeof input.running === "boolean" ? input.running : null
17614
- });
17615
- return parsed.success ? parsed.data : null;
17493
+ // ../../harness-adapter/dist/question.js
17494
+ function invalidRequest(message3) {
17495
+ return { code: "invalidRequest", message: message3, retryable: false };
17616
17496
  }
17617
- var SessionImportScope = class {
17618
- #abort = new AbortController();
17619
- #options;
17620
- #pending = /* @__PURE__ */ new Set();
17621
- constructor(options) {
17622
- this.#options = options;
17497
+ function validateHostQuestionResponse(interaction, response) {
17498
+ const questionIds = new Set(interaction.questions.map(({ id }) => id));
17499
+ if (response.cancelled) {
17500
+ return Object.keys(response.answers).length === 0 ? null : invalidRequest("Cancelled Question Response must not contain answers");
17623
17501
  }
17624
- #closed() {
17625
- return {
17626
- ok: false,
17627
- error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
17628
- };
17502
+ for (const answerId of Object.keys(response.answers)) {
17503
+ if (!questionIds.has(answerId)) {
17504
+ return invalidRequest("Question Response contains an unknown Question ID");
17505
+ }
17629
17506
  }
17630
- read(operation) {
17631
- const signal = this.#abort.signal;
17632
- if (signal.aborted)
17633
- return Promise.resolve(this.#closed());
17634
- let started;
17635
- try {
17636
- started = operation(signal);
17637
- } catch (error51) {
17638
- started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
17507
+ for (const question of interaction.questions) {
17508
+ const answers = response.answers[question.id] ?? [];
17509
+ if (new Set(answers).size !== answers.length) {
17510
+ return invalidRequest("Question Response contains duplicate answers");
17639
17511
  }
17640
- const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
17641
- ok: false,
17642
- error: {
17643
- code: "unavailable",
17644
- message: this.#options.unavailableMessage,
17645
- retryable: true
17646
- }
17647
- }).finally(() => this.#pending.delete(request));
17648
- this.#pending.add(request);
17649
- return request;
17650
- }
17651
- /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
17652
- async resolve(operation) {
17653
- const result = await this.read(operation);
17654
- if (!result.ok)
17655
- return result;
17656
- return result.value ? { ok: true, value: result.value } : {
17657
- ok: false,
17658
- error: {
17659
- code: "sessionNotFound",
17660
- message: this.#options.notFoundMessage,
17661
- retryable: false
17662
- }
17663
- };
17664
- }
17665
- /** Idempotent. Resolves after every started read has settled. */
17666
- async close() {
17667
- this.#abort.abort();
17668
- await Promise.allSettled(this.#pending);
17669
- }
17670
- };
17671
-
17672
- // dist/pi-session-import.js
17673
- var PI_SESSION_CHANGED = "Pi Session changed during discovery; refresh and retry";
17674
- function isRecord(value) {
17675
- return typeof value === "object" && value !== null && !Array.isArray(value);
17676
- }
17677
- function expandDirectory(value, home) {
17678
- return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
17679
- }
17680
- function piSessionImportDirectory(environment) {
17681
- const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
17682
- const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
17683
- if (custom2)
17684
- return { directory: expandDirectory(custom2, home), flat: true };
17685
- const agent = environment.PI_CODING_AGENT_DIR;
17686
- return {
17687
- directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".pi", "agent"), "sessions"),
17688
- flat: false
17689
- };
17690
- }
17691
- async function sessionFiles(directory, flat, signal) {
17692
- const files = [];
17693
- const visit = async (dir, projectLevel) => {
17694
- signal.throwIfAborted();
17695
- const entries = await opendir2(dir).catch((error51) => {
17696
- if (isMissingFileError(error51))
17697
- return null;
17698
- throw error51;
17699
- });
17700
- if (!entries)
17701
- return;
17702
- for await (const entry of entries) {
17703
- signal.throwIfAborted();
17704
- if (projectLevel && entry.isDirectory())
17705
- await visit(path5.join(dir, entry.name), false);
17706
- else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl")) {
17707
- files.push(path5.join(dir, entry.name));
17708
- }
17709
- }
17710
- };
17711
- await visit(directory, !flat);
17712
- return files;
17713
- }
17714
- async function readCandidate(file2, signal) {
17715
- const before = await stat(file2);
17716
- if (!before.isFile() || before.size === 0)
17717
- return null;
17718
- const stream = createReadStream2(file2, { encoding: "utf8", signal, end: before.size - 1 });
17719
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17720
- let header;
17721
- let name = null;
17722
- let firstMessage = null;
17723
- let hasUser = false;
17724
- let updatedAt = before.mtimeMs;
17725
- const entries = /* @__PURE__ */ new Map();
17726
- try {
17727
- for await (const line of lines) {
17728
- signal.throwIfAborted();
17729
- if (!line.trim())
17730
- continue;
17731
- let entry;
17732
- try {
17733
- entry = JSON.parse(line);
17734
- } catch {
17735
- return null;
17736
- }
17737
- if (!isRecord(entry))
17738
- return null;
17739
- if (!header) {
17740
- if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
17741
- return null;
17742
- header = entry;
17743
- continue;
17744
- }
17745
- if (typeof entry.id !== "string" || entry.id.length === 0 || entries.has(entry.id) || entry.parentId !== null && (typeof entry.parentId !== "string" || !entries.has(entry.parentId)))
17746
- return null;
17747
- const message3 = isRecord(entry.message) ? entry.message : null;
17748
- if (!firstMessage && entry.type === "message" && message3?.role === "user") {
17749
- const content = message3.content;
17750
- 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(" ") : "";
17751
- firstMessage = sessionImportTitle(text4);
17752
- }
17753
- hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
17754
- entries.set(entry.id, hasUser);
17755
- if (entry.type === "session_info")
17756
- name = sessionImportTitle(entry.name);
17757
- if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
17758
- const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
17759
- if (Number.isFinite(time3))
17760
- updatedAt = time3;
17761
- }
17762
- }
17763
- } finally {
17764
- lines.close();
17765
- stream.destroy();
17766
- }
17767
- if (!header)
17768
- return null;
17769
- if (!hasUser)
17770
- return null;
17771
- const after = await stat(file2);
17772
- if (!sameFileFingerprint(before, after))
17773
- throw new SessionImportChangedError(PI_SESSION_CHANGED);
17774
- const cwd = await realpath(String(header.cwd));
17775
- if (!(await stat(cwd)).isDirectory())
17776
- return null;
17777
- const nativeRef = nativeSessionRefSchema.safeParse({
17778
- harnessId: "pi",
17779
- nativeSessionId: header.id,
17780
- locator: { sessionFile: await realpath(file2) },
17781
- formatVersion: 1
17782
- });
17783
- const candidate = sessionImportCandidate({
17784
- nativeSessionId: header.id,
17785
- cwd,
17786
- title: name ?? firstMessage,
17787
- updatedAt
17788
- });
17789
- return candidate && nativeRef.success ? { candidate, nativeRef: nativeRef.data } : null;
17790
- }
17791
- async function readIdentity(file2, signal) {
17792
- const stream = createReadStream2(file2, { encoding: "utf8", signal });
17793
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
17794
- try {
17795
- for await (const line of lines) {
17796
- signal.throwIfAborted();
17797
- if (!line.trim())
17798
- continue;
17799
- let header;
17800
- try {
17801
- header = JSON.parse(line);
17802
- } catch {
17803
- return null;
17804
- }
17805
- return isRecord(header) && header.type === "session" && header.version === 3 && typeof header.id === "string" ? header.id : null;
17806
- }
17807
- return null;
17808
- } finally {
17809
- lines.close();
17810
- stream.destroy();
17811
- }
17812
- }
17813
- var PiSessionImportIndex = class {
17814
- #location;
17815
- #cache = /* @__PURE__ */ new Map();
17816
- #listing;
17817
- constructor(environment) {
17818
- this.#location = piSessionImportDirectory(environment);
17819
- }
17820
- list(signal) {
17821
- this.#listing ??= this.#scan(signal).finally(() => {
17822
- this.#listing = void 0;
17823
- });
17824
- return this.#listing;
17825
- }
17826
- async #scan(signal) {
17827
- const { directory, flat } = this.#location;
17828
- const files = await sessionFiles(directory, flat, signal);
17829
- const next = /* @__PURE__ */ new Map();
17830
- const identities = /* @__PURE__ */ new Set();
17831
- const sources = [];
17832
- for (const file2 of files) {
17833
- signal.throwIfAborted();
17834
- try {
17835
- const fingerprint = await stat(file2);
17836
- const cached2 = this.#cache.get(file2);
17837
- const source = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source : await readCandidate(file2, signal);
17838
- if (!source)
17839
- continue;
17840
- if (!(await stat(source.candidate.cwd)).isDirectory())
17841
- continue;
17842
- if (identities.has(source.nativeRef.nativeSessionId))
17843
- throw new Error("Pi Session identity is ambiguous across files");
17844
- identities.add(source.nativeRef.nativeSessionId);
17845
- next.set(file2, { fingerprint, source });
17846
- sources.push(source);
17847
- } catch (error51) {
17848
- if (!isMissingFileError(error51) && !(error51 instanceof SessionImportChangedError))
17849
- throw error51;
17850
- }
17851
- }
17852
- this.#cache = next;
17853
- return structuredClone(sources.sort((left, right) => right.candidate.updatedAt - left.candidate.updatedAt));
17854
- }
17855
- async resolve(nativeSessionId, signal) {
17856
- const { directory, flat } = this.#location;
17857
- let selected;
17858
- for (const file2 of await sessionFiles(directory, flat, signal)) {
17859
- signal.throwIfAborted();
17860
- try {
17861
- const fingerprint = await stat(file2);
17862
- const cached2 = this.#cache.get(file2);
17863
- const id = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source.nativeRef.nativeSessionId : await readIdentity(file2, signal);
17864
- if (id !== nativeSessionId)
17865
- continue;
17866
- if (selected)
17867
- throw new Error("Pi Session identity is ambiguous across files");
17868
- selected = file2;
17869
- } catch (error51) {
17870
- if (!isMissingFileError(error51))
17871
- throw error51;
17872
- }
17873
- }
17874
- if (!selected)
17875
- return null;
17876
- try {
17877
- const source = await readCandidate(selected, signal);
17878
- return source?.nativeRef.nativeSessionId === nativeSessionId ? source : null;
17879
- } catch (error51) {
17880
- if (isMissingFileError(error51))
17881
- return null;
17882
- throw error51;
17883
- }
17884
- }
17885
- };
17886
-
17887
- // ../../harness-adapter/dist/question.js
17888
- function invalidRequest(message3) {
17889
- return { code: "invalidRequest", message: message3, retryable: false };
17890
- }
17891
- function validateHostQuestionResponse(interaction, response) {
17892
- const questionIds = new Set(interaction.questions.map(({ id }) => id));
17893
- if (response.cancelled) {
17894
- return Object.keys(response.answers).length === 0 ? null : invalidRequest("Cancelled Question Response must not contain answers");
17895
- }
17896
- for (const answerId of Object.keys(response.answers)) {
17897
- if (!questionIds.has(answerId)) {
17898
- return invalidRequest("Question Response contains an unknown Question ID");
17899
- }
17900
- }
17901
- for (const question of interaction.questions) {
17902
- const answers = response.answers[question.id] ?? [];
17903
- if (new Set(answers).size !== answers.length) {
17904
- return invalidRequest("Question Response contains duplicate answers");
17905
- }
17906
- if (!question.optional && answers.length === 0) {
17907
- return invalidRequest("Question Response omits a required answer");
17908
- }
17909
- if (question.type === "text") {
17910
- if (answers.length > 1) {
17911
- return invalidRequest("Text Question accepts at most one answer");
17512
+ if (!question.optional && answers.length === 0) {
17513
+ return invalidRequest("Question Response omits a required answer");
17514
+ }
17515
+ if (question.type === "text") {
17516
+ if (answers.length > 1) {
17517
+ return invalidRequest("Text Question accepts at most one answer");
17912
17518
  }
17913
17519
  continue;
17914
17520
  }
@@ -18029,11 +17635,11 @@ var usageFields = /* @__PURE__ */ new Set([
18029
17635
  "costSource",
18030
17636
  "unpricedModels"
18031
17637
  ]);
18032
- function isRecord2(value) {
17638
+ function isRecord(value) {
18033
17639
  return typeof value === "object" && value !== null && !Array.isArray(value);
18034
17640
  }
18035
17641
  function parseHostUsage(value) {
18036
- if (!isRecord2(value))
17642
+ if (!isRecord(value))
18037
17643
  throw new Error("Harness Usage must be an object");
18038
17644
  const keys = Object.keys(value);
18039
17645
  if (keys.length === 0)
@@ -18080,7 +17686,7 @@ function parseHostUsage(value) {
18080
17686
  }
18081
17687
  if (value.sessionCacheUsage !== void 0) {
18082
17688
  const totals2 = value.sessionCacheUsage;
18083
- 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) {
17689
+ 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) {
18084
17690
  throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
18085
17691
  }
18086
17692
  }
@@ -18114,192 +17720,694 @@ function parseHostUsage(value) {
18114
17720
  if (value.costSource !== "publicPrice") {
18115
17721
  throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
18116
17722
  }
18117
- return { ...value, ...indicators, unpricedModels: [...models] };
17723
+ return { ...value, ...indicators, unpricedModels: [...models] };
17724
+ }
17725
+ return { ...value, ...indicators };
17726
+ }
17727
+ var requestTokenFields = [
17728
+ "inputTokens",
17729
+ "cachedInputTokens",
17730
+ "cacheWriteInputTokens",
17731
+ "cacheWrite1hInputTokens",
17732
+ "outputTokens",
17733
+ "reasoningOutputTokens",
17734
+ "startedAtMs",
17735
+ "completedAtMs"
17736
+ ];
17737
+ var requestFields = /* @__PURE__ */ new Set([
17738
+ ...requestTokenFields,
17739
+ "requestId",
17740
+ "historical",
17741
+ "model",
17742
+ "provider"
17743
+ ]);
17744
+ function parseHostUsageRequest(value) {
17745
+ if (!isRecord(value))
17746
+ throw new Error("Harness Usage request must be an object");
17747
+ for (const key of Object.keys(value)) {
17748
+ if (!requestFields.has(key)) {
17749
+ throw new Error(`Harness Usage request contains unknown field '${key}'`);
17750
+ }
17751
+ }
17752
+ if (typeof value.requestId !== "string" || value.requestId.length === 0) {
17753
+ throw new Error("Harness Usage request 'requestId' must be a non-empty string");
17754
+ }
17755
+ for (const field2 of ["model", "provider"]) {
17756
+ const candidate = value[field2];
17757
+ if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
17758
+ throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
17759
+ }
17760
+ }
17761
+ if (value.historical !== void 0 && typeof value.historical !== "boolean") {
17762
+ throw new Error("Harness Usage request 'historical' must be a boolean");
17763
+ }
17764
+ for (const field2 of requestTokenFields) {
17765
+ const candidate = value[field2];
17766
+ if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
17767
+ throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
17768
+ }
17769
+ }
17770
+ if (value.inputTokens === void 0 || value.outputTokens === void 0) {
17771
+ throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
17772
+ }
17773
+ const request = value;
17774
+ if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
17775
+ throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
17776
+ }
17777
+ if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
17778
+ throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
17779
+ }
17780
+ if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
17781
+ throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
17782
+ }
17783
+ if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
17784
+ throw new Error("Harness Usage request timing fields must be provided together");
17785
+ }
17786
+ if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
17787
+ throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
17788
+ }
17789
+ return { ...request };
17790
+ }
17791
+
17792
+ // ../../harness-adapter/dist/live-command-catalog.js
17793
+ var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
17794
+ // Session lifecycle
17795
+ "branch",
17796
+ "clear",
17797
+ "exit",
17798
+ "fork",
17799
+ "fresh",
17800
+ "new",
17801
+ "quit",
17802
+ "rename",
17803
+ "rename-chat",
17804
+ "reset",
17805
+ "resume",
17806
+ "rewind",
17807
+ "session",
17808
+ "sessions",
17809
+ // Desktop-owned configuration
17810
+ "autocompact",
17811
+ "color",
17812
+ "config",
17813
+ "effort",
17814
+ "fast",
17815
+ "keybindings",
17816
+ "model",
17817
+ "models",
17818
+ "output-style",
17819
+ "permissions",
17820
+ "settings",
17821
+ "statusline",
17822
+ "terminal-setup",
17823
+ "theme",
17824
+ "vim",
17825
+ // Trust and approval policy
17826
+ "always-approve",
17827
+ "auto-mode-setup",
17828
+ // Native login
17829
+ "login",
17830
+ "logout",
17831
+ // Work outliving the Turn
17832
+ "autopilot",
17833
+ "background",
17834
+ "bg",
17835
+ "goal",
17836
+ "jobs",
17837
+ "loop",
17838
+ "multitask",
17839
+ "queue",
17840
+ "remote-control",
17841
+ "schedule",
17842
+ "steer",
17843
+ // Native terminal UI
17844
+ "copy",
17845
+ "debug",
17846
+ "feedback",
17847
+ "heapdump",
17848
+ "share",
17849
+ "shell",
17850
+ // Plugin and MCP management
17851
+ "marketplace",
17852
+ "mcp",
17853
+ "plugins",
17854
+ "reload-plugins"
17855
+ ]);
17856
+ var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
17857
+ function isExcludedLiveCommand(name, extra = {}) {
17858
+ const normalized = name.trim().replace(/^\//u, "");
17859
+ if (new Set(extra.names ?? []).has(normalized))
17860
+ return true;
17861
+ if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
17862
+ return true;
17863
+ return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
17864
+ }
17865
+ function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
17866
+ if (!commandId.startsWith(idPrefix))
17867
+ return null;
17868
+ const descriptor = catalog.commands.find(({ id }) => id === commandId);
17869
+ if (!descriptor)
17870
+ return null;
17871
+ const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
17872
+ return text4 ? `${descriptor.invocation} ${text4}` : descriptor.invocation;
17873
+ }
17874
+ function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
17875
+ if (!live)
17876
+ return builtIns;
17877
+ const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
17878
+ const ids = new Set(builtIns.commands.map(({ id }) => id));
17879
+ const dynamic = [];
17880
+ for (const command of live) {
17881
+ const name = command.name.trim().replace(/^\//u, "");
17882
+ if (!name || /\s/u.test(name))
17883
+ continue;
17884
+ if (isExcludedLiveCommand(name, exclusions))
17885
+ continue;
17886
+ const invocation = `/${name}`;
17887
+ const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
17888
+ if (invocations.has(invocation) || ids.has(id))
17889
+ continue;
17890
+ const description = command.description?.trim().slice(0, 512);
17891
+ const parsed = harnessCommandDescriptorSchema.safeParse({
17892
+ id,
17893
+ invocation,
17894
+ label: name.slice(0, 128),
17895
+ ...description ? { description } : {},
17896
+ argumentMode: "text"
17897
+ });
17898
+ if (!parsed.success)
17899
+ continue;
17900
+ invocations.add(invocation);
17901
+ ids.add(id);
17902
+ dynamic.push(parsed.data);
17903
+ }
17904
+ return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
17905
+ }
17906
+
17907
+ // ../../harness-adapter/dist/subagent-configuration.js
17908
+ function subagentConfiguration(value) {
17909
+ if (typeof value !== "object" || value === null || Array.isArray(value))
17910
+ return {};
17911
+ const row = value;
17912
+ const text4 = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
17913
+ const model2 = row.model === "inherit" ? void 0 : text4(row.model);
17914
+ const reasoningEffort = text4(row.reasoningEffort) ?? text4(row.reasoning_effort) ?? text4(row.thinking);
17915
+ return { ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17916
+ }
17917
+ function inheritSubagentConfiguration(child, parent) {
17918
+ const native = subagentConfiguration(child);
17919
+ const model2 = native.model ?? parent.model;
17920
+ const reasoningEffort = native.reasoningEffort ?? parent.reasoningEffort;
17921
+ const next = { ...child };
17922
+ delete next.model;
17923
+ delete next.reasoningEffort;
17924
+ return { ...next, ...model2 ? { model: model2 } : {}, ...reasoningEffort ? { reasoningEffort } : {} };
17925
+ }
17926
+ function configureSubagentEvent(event, parent) {
17927
+ const children = (states2) => states2.map((child) => inheritSubagentConfiguration(child, parent));
17928
+ if (event.type === "item.started" && event.item.type === "subagentDelegation")
17929
+ return { ...event, item: { ...event.item, subagents: children(event.item.subagents) } };
17930
+ if (event.type === "item.updated" && event.update.type === "subagents.replace")
17931
+ return { ...event, update: { ...event.update, subagents: children(event.update.subagents) } };
17932
+ if (event.type === "item.completed" && event.snapshot.item.type === "subagentDelegation")
17933
+ return {
17934
+ ...event,
17935
+ snapshot: {
17936
+ ...event.snapshot,
17937
+ item: {
17938
+ ...event.snapshot.item,
17939
+ subagents: children(event.snapshot.item.subagents)
17940
+ }
17941
+ }
17942
+ };
17943
+ return event;
17944
+ }
17945
+ function configureSubagentSnapshot(snapshot, parent) {
17946
+ return {
17947
+ ...snapshot,
17948
+ turns: snapshot.turns.map((turn) => ({
17949
+ ...turn,
17950
+ items: turn.items.map((entry) => entry.item.type === "subagentDelegation" ? {
17951
+ ...entry,
17952
+ item: {
17953
+ ...entry.item,
17954
+ subagents: entry.item.subagents.map((child) => inheritSubagentConfiguration(child, parent))
17955
+ }
17956
+ } : entry)
17957
+ }))
17958
+ };
17959
+ }
17960
+
17961
+ // ../../harness-adapter/dist/usage-statistics.js
17962
+ import { createReadStream } from "node:fs";
17963
+ import { lstat, opendir } from "node:fs/promises";
17964
+ import path4 from "node:path";
17965
+ import { createInterface } from "node:readline";
17966
+ var MAX_SESSION_ID_LENGTH = 512;
17967
+ var MAX_CWD_LENGTH = 4096;
17968
+ var MAX_SESSION_TITLE_LENGTH = 200;
17969
+ function usageSessionTitle(value) {
17970
+ if (typeof value !== "string")
17971
+ return void 0;
17972
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
17973
+ if (!normalized)
17974
+ return void 0;
17975
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
17976
+ return normalized;
17977
+ let title = "";
17978
+ for (const character of normalized) {
17979
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
17980
+ break;
17981
+ title += character;
17982
+ }
17983
+ return `${title.trimEnd()}…`;
17984
+ }
17985
+ function sessionIdOk(value) {
17986
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
17987
+ }
17988
+ function cwdOk(value) {
17989
+ 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("\\\\"));
17990
+ }
17991
+ function withUsageSession(entry, session) {
17992
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
17993
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
17994
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
17995
+ if (sessionId === void 0 && cwd === void 0)
17996
+ return entry;
17997
+ return {
17998
+ ...entry,
17999
+ ...sessionId !== void 0 ? { sessionId } : {},
18000
+ ...cwd !== void 0 ? { cwd } : {},
18001
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
18002
+ };
18003
+ }
18004
+ function usageEntryFromRequest(request, occurredAtMs) {
18005
+ if (!Number.isSafeInteger(occurredAtMs) || occurredAtMs <= 0)
18006
+ return null;
18007
+ return {
18008
+ id: request.requestId,
18009
+ occurredAtMs,
18010
+ ...request.model !== void 0 ? { model: request.model } : {},
18011
+ inputTokens: request.inputTokens,
18012
+ ...request.cachedInputTokens !== void 0 ? { cachedInputTokens: request.cachedInputTokens } : {},
18013
+ ...request.cacheWriteInputTokens !== void 0 ? { cacheWriteInputTokens: request.cacheWriteInputTokens } : {},
18014
+ ...request.cacheWrite1hInputTokens !== void 0 ? { cacheWrite1hInputTokens: request.cacheWrite1hInputTokens } : {},
18015
+ outputTokens: request.outputTokens,
18016
+ ...request.reasoningOutputTokens !== void 0 ? { reasoningOutputTokens: request.reasoningOutputTokens } : {}
18017
+ };
18018
+ }
18019
+ async function jsonlUsageSources(root, maxDepth, signal) {
18020
+ const sources = [];
18021
+ const visit = async (directory, depth) => {
18022
+ signal.throwIfAborted();
18023
+ const entries = await opendir(directory).catch((error51) => {
18024
+ if (error51.code === "ENOENT")
18025
+ return null;
18026
+ throw error51;
18027
+ });
18028
+ if (!entries)
18029
+ return;
18030
+ for await (const entry of entries) {
18031
+ signal.throwIfAborted();
18032
+ const file2 = path4.join(directory, entry.name);
18033
+ if (entry.isDirectory()) {
18034
+ if (depth < maxDepth)
18035
+ await visit(file2, depth + 1);
18036
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
18037
+ const info = await lstat(file2).catch(() => null);
18038
+ if (info?.isFile() && info.size > 0) {
18039
+ sources.push({ id: file2, fingerprint: `${info.ino}:${info.size}:${info.mtimeMs}` });
18040
+ }
18041
+ }
18042
+ }
18043
+ };
18044
+ await visit(root, 0);
18045
+ return sources;
18046
+ }
18047
+ async function* jsonlRecords(file2, marker, signal) {
18048
+ const lines = createInterface({
18049
+ input: createReadStream(file2, { encoding: "utf8", signal }),
18050
+ crlfDelay: Infinity
18051
+ });
18052
+ for await (const line of lines) {
18053
+ if (!line.includes(marker))
18054
+ continue;
18055
+ let value;
18056
+ try {
18057
+ value = JSON.parse(line);
18058
+ } catch {
18059
+ continue;
18060
+ }
18061
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
18062
+ yield value;
18063
+ }
18064
+ }
18065
+ }
18066
+ async function jsonlHeader(file2, match, signal, maxLines = 4) {
18067
+ const stream = createReadStream(file2, { encoding: "utf8", signal });
18068
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
18069
+ let seen = 0;
18070
+ try {
18071
+ for await (const line of lines) {
18072
+ if (++seen > maxLines)
18073
+ break;
18074
+ let value;
18075
+ try {
18076
+ value = JSON.parse(line);
18077
+ } catch {
18078
+ continue;
18079
+ }
18080
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
18081
+ const record10 = value;
18082
+ if (match(record10))
18083
+ return record10;
18084
+ }
18085
+ }
18086
+ return null;
18087
+ } finally {
18088
+ lines.close();
18089
+ stream.destroy();
18090
+ }
18091
+ }
18092
+ function nativeTimeMs(value) {
18093
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
18094
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
18095
+ }
18096
+
18097
+ // dist/pi-session-import.js
18098
+ import { createReadStream as createReadStream2 } from "node:fs";
18099
+ import { opendir as opendir2, realpath, stat } from "node:fs/promises";
18100
+ import os2 from "node:os";
18101
+ import path5 from "node:path";
18102
+ import { createInterface as createInterface2 } from "node:readline";
18103
+
18104
+ // ../../harness-adapter/dist/session-import.js
18105
+ var SessionImportChangedError = class extends Error {
18106
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
18107
+ super(message3);
18108
+ this.name = "SessionImportChangedError";
18109
+ }
18110
+ };
18111
+ function isMissingFileError(error51) {
18112
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
18113
+ }
18114
+ function sameFileFingerprint(left, right) {
18115
+ 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;
18116
+ }
18117
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
18118
+ if (typeof value !== "string")
18119
+ return null;
18120
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
18121
+ if (!normalized)
18122
+ return null;
18123
+ if (normalized.length <= maxLength)
18124
+ return normalized;
18125
+ const characters = [...normalized];
18126
+ if (characters.length <= maxLength)
18127
+ return normalized;
18128
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
18129
+ }
18130
+ function sessionImportCandidate(input) {
18131
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
18132
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
18133
+ nativeSessionId: input.nativeSessionId,
18134
+ cwd: input.cwd,
18135
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
18136
+ updatedAt: Math.floor(time3),
18137
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
18138
+ running: typeof input.running === "boolean" ? input.running : null
18139
+ });
18140
+ return parsed.success ? parsed.data : null;
18141
+ }
18142
+ var SessionImportScope = class {
18143
+ #abort = new AbortController();
18144
+ #options;
18145
+ #pending = /* @__PURE__ */ new Set();
18146
+ constructor(options) {
18147
+ this.#options = options;
18148
+ }
18149
+ #closed() {
18150
+ return {
18151
+ ok: false,
18152
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
18153
+ };
18154
+ }
18155
+ read(operation) {
18156
+ const signal = this.#abort.signal;
18157
+ if (signal.aborted)
18158
+ return Promise.resolve(this.#closed());
18159
+ let started;
18160
+ try {
18161
+ started = operation(signal);
18162
+ } catch (error51) {
18163
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
18164
+ }
18165
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
18166
+ ok: false,
18167
+ error: {
18168
+ code: "unavailable",
18169
+ message: this.#options.unavailableMessage,
18170
+ retryable: true
18171
+ }
18172
+ }).finally(() => this.#pending.delete(request));
18173
+ this.#pending.add(request);
18174
+ return request;
18175
+ }
18176
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
18177
+ async resolve(operation) {
18178
+ const result = await this.read(operation);
18179
+ if (!result.ok)
18180
+ return result;
18181
+ return result.value ? { ok: true, value: result.value } : {
18182
+ ok: false,
18183
+ error: {
18184
+ code: "sessionNotFound",
18185
+ message: this.#options.notFoundMessage,
18186
+ retryable: false
18187
+ }
18188
+ };
18189
+ }
18190
+ /** Idempotent. Resolves after every started read has settled. */
18191
+ async close() {
18192
+ this.#abort.abort();
18193
+ await Promise.allSettled(this.#pending);
18194
+ }
18195
+ };
18196
+
18197
+ // dist/pi-session-import.js
18198
+ var PI_SESSION_CHANGED = "Pi Session changed during discovery; refresh and retry";
18199
+ function isRecord2(value) {
18200
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18201
+ }
18202
+ function expandDirectory(value, home) {
18203
+ return path5.resolve(value === "~" ? home : value.startsWith(`~${path5.sep}`) || value.startsWith("~/") ? path5.join(home, value.slice(2)) : value);
18204
+ }
18205
+ function piSessionImportDirectory(environment) {
18206
+ const home = (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
18207
+ const custom2 = environment.PI_CODING_AGENT_SESSION_DIR;
18208
+ if (custom2)
18209
+ return { directory: expandDirectory(custom2, home), flat: true };
18210
+ const agent = environment.PI_CODING_AGENT_DIR;
18211
+ return {
18212
+ directory: path5.join(agent ? expandDirectory(agent, home) : path5.join(home, ".pi", "agent"), "sessions"),
18213
+ flat: false
18214
+ };
18215
+ }
18216
+ async function sessionFiles(directory, flat, signal) {
18217
+ const files = [];
18218
+ const visit = async (dir, projectLevel) => {
18219
+ signal.throwIfAborted();
18220
+ const entries = await opendir2(dir).catch((error51) => {
18221
+ if (isMissingFileError(error51))
18222
+ return null;
18223
+ throw error51;
18224
+ });
18225
+ if (!entries)
18226
+ return;
18227
+ for await (const entry of entries) {
18228
+ signal.throwIfAborted();
18229
+ if (projectLevel && entry.isDirectory())
18230
+ await visit(path5.join(dir, entry.name), false);
18231
+ else if (!projectLevel && entry.isFile() && entry.name.endsWith(".jsonl")) {
18232
+ files.push(path5.join(dir, entry.name));
18233
+ }
18234
+ }
18235
+ };
18236
+ await visit(directory, !flat);
18237
+ return files;
18238
+ }
18239
+ async function readCandidate(file2, signal) {
18240
+ const before = await stat(file2);
18241
+ if (!before.isFile() || before.size === 0)
18242
+ return null;
18243
+ const stream = createReadStream2(file2, { encoding: "utf8", signal, end: before.size - 1 });
18244
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
18245
+ let header;
18246
+ let name = null;
18247
+ let firstMessage = null;
18248
+ let hasUser = false;
18249
+ let updatedAt = before.mtimeMs;
18250
+ const entries = /* @__PURE__ */ new Map();
18251
+ try {
18252
+ for await (const line of lines) {
18253
+ signal.throwIfAborted();
18254
+ if (!line.trim())
18255
+ continue;
18256
+ let entry;
18257
+ try {
18258
+ entry = JSON.parse(line);
18259
+ } catch {
18260
+ return null;
18261
+ }
18262
+ if (!isRecord2(entry))
18263
+ return null;
18264
+ if (!header) {
18265
+ if (entry.type !== "session" || entry.version !== 3 || typeof entry.id !== "string" || typeof entry.cwd !== "string" || !path5.isAbsolute(entry.cwd))
18266
+ return null;
18267
+ header = entry;
18268
+ continue;
18269
+ }
18270
+ if (typeof entry.id !== "string" || entry.id.length === 0 || entries.has(entry.id) || entry.parentId !== null && (typeof entry.parentId !== "string" || !entries.has(entry.parentId)))
18271
+ return null;
18272
+ const message3 = isRecord2(entry.message) ? entry.message : null;
18273
+ if (!firstMessage && entry.type === "message" && message3?.role === "user") {
18274
+ const content = message3.content;
18275
+ 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(" ") : "";
18276
+ firstMessage = sessionImportTitle(text4);
18277
+ }
18278
+ hasUser = entry.type === "message" && message3?.role === "user" || typeof entry.parentId === "string" && entries.get(entry.parentId) === true;
18279
+ entries.set(entry.id, hasUser);
18280
+ if (entry.type === "session_info")
18281
+ name = sessionImportTitle(entry.name);
18282
+ if (entry.type === "message" && (message3?.role === "user" || message3?.role === "assistant")) {
18283
+ const time3 = typeof message3.timestamp === "number" ? message3.timestamp : typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
18284
+ if (Number.isFinite(time3))
18285
+ updatedAt = time3;
18286
+ }
18287
+ }
18288
+ } finally {
18289
+ lines.close();
18290
+ stream.destroy();
18291
+ }
18292
+ if (!header)
18293
+ return null;
18294
+ if (!hasUser)
18295
+ return null;
18296
+ const after = await stat(file2);
18297
+ if (!sameFileFingerprint(before, after))
18298
+ throw new SessionImportChangedError(PI_SESSION_CHANGED);
18299
+ const cwd = await realpath(String(header.cwd));
18300
+ if (!(await stat(cwd)).isDirectory())
18301
+ return null;
18302
+ const nativeRef = nativeSessionRefSchema.safeParse({
18303
+ harnessId: "pi",
18304
+ nativeSessionId: header.id,
18305
+ locator: { sessionFile: await realpath(file2) },
18306
+ formatVersion: 1
18307
+ });
18308
+ const candidate = sessionImportCandidate({
18309
+ nativeSessionId: header.id,
18310
+ cwd,
18311
+ title: name ?? firstMessage,
18312
+ updatedAt
18313
+ });
18314
+ return candidate && nativeRef.success ? { candidate, nativeRef: nativeRef.data } : null;
18315
+ }
18316
+ async function readIdentity(file2, signal) {
18317
+ const stream = createReadStream2(file2, { encoding: "utf8", signal });
18318
+ const lines = createInterface2({ input: stream, crlfDelay: Infinity });
18319
+ try {
18320
+ for await (const line of lines) {
18321
+ signal.throwIfAborted();
18322
+ if (!line.trim())
18323
+ continue;
18324
+ let header;
18325
+ try {
18326
+ header = JSON.parse(line);
18327
+ } catch {
18328
+ return null;
18329
+ }
18330
+ return isRecord2(header) && header.type === "session" && header.version === 3 && typeof header.id === "string" ? header.id : null;
18331
+ }
18332
+ return null;
18333
+ } finally {
18334
+ lines.close();
18335
+ stream.destroy();
18118
18336
  }
18119
- return { ...value, ...indicators };
18120
18337
  }
18121
- var requestTokenFields = [
18122
- "inputTokens",
18123
- "cachedInputTokens",
18124
- "cacheWriteInputTokens",
18125
- "cacheWrite1hInputTokens",
18126
- "outputTokens",
18127
- "reasoningOutputTokens",
18128
- "startedAtMs",
18129
- "completedAtMs"
18130
- ];
18131
- var requestFields = /* @__PURE__ */ new Set([
18132
- ...requestTokenFields,
18133
- "requestId",
18134
- "historical",
18135
- "model",
18136
- "provider"
18137
- ]);
18138
- function parseHostUsageRequest(value) {
18139
- if (!isRecord2(value))
18140
- throw new Error("Harness Usage request must be an object");
18141
- for (const key of Object.keys(value)) {
18142
- if (!requestFields.has(key)) {
18143
- throw new Error(`Harness Usage request contains unknown field '${key}'`);
18144
- }
18338
+ var PiSessionImportIndex = class {
18339
+ #location;
18340
+ #cache = /* @__PURE__ */ new Map();
18341
+ #listing;
18342
+ constructor(environment) {
18343
+ this.#location = piSessionImportDirectory(environment);
18145
18344
  }
18146
- if (typeof value.requestId !== "string" || value.requestId.length === 0) {
18147
- throw new Error("Harness Usage request 'requestId' must be a non-empty string");
18345
+ list(signal) {
18346
+ this.#listing ??= this.#scan(signal).finally(() => {
18347
+ this.#listing = void 0;
18348
+ });
18349
+ return this.#listing;
18148
18350
  }
18149
- for (const field2 of ["model", "provider"]) {
18150
- const candidate = value[field2];
18151
- if (candidate !== void 0 && (typeof candidate !== "string" || candidate.length === 0)) {
18152
- throw new Error(`Harness Usage request '${field2}' must be a non-empty string`);
18351
+ async #scan(signal) {
18352
+ const { directory, flat } = this.#location;
18353
+ const files = await sessionFiles(directory, flat, signal);
18354
+ const next = /* @__PURE__ */ new Map();
18355
+ const identities = /* @__PURE__ */ new Set();
18356
+ const sources = [];
18357
+ for (const file2 of files) {
18358
+ signal.throwIfAborted();
18359
+ try {
18360
+ const fingerprint = await stat(file2);
18361
+ const cached2 = this.#cache.get(file2);
18362
+ const source = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source : await readCandidate(file2, signal);
18363
+ if (!source)
18364
+ continue;
18365
+ if (!(await stat(source.candidate.cwd)).isDirectory())
18366
+ continue;
18367
+ if (identities.has(source.nativeRef.nativeSessionId))
18368
+ throw new Error("Pi Session identity is ambiguous across files");
18369
+ identities.add(source.nativeRef.nativeSessionId);
18370
+ next.set(file2, { fingerprint, source });
18371
+ sources.push(source);
18372
+ } catch (error51) {
18373
+ if (!isMissingFileError(error51) && !(error51 instanceof SessionImportChangedError))
18374
+ throw error51;
18375
+ }
18153
18376
  }
18377
+ this.#cache = next;
18378
+ return structuredClone(sources.sort((left, right) => right.candidate.updatedAt - left.candidate.updatedAt));
18154
18379
  }
18155
- if (value.historical !== void 0 && typeof value.historical !== "boolean") {
18156
- throw new Error("Harness Usage request 'historical' must be a boolean");
18157
- }
18158
- for (const field2 of requestTokenFields) {
18159
- const candidate = value[field2];
18160
- if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isSafeInteger(candidate) || candidate < 0)) {
18161
- throw new Error(`Harness Usage request '${field2}' must be a non-negative safe integer`);
18380
+ async resolve(nativeSessionId, signal) {
18381
+ const { directory, flat } = this.#location;
18382
+ let selected;
18383
+ for (const file2 of await sessionFiles(directory, flat, signal)) {
18384
+ signal.throwIfAborted();
18385
+ try {
18386
+ const fingerprint = await stat(file2);
18387
+ const cached2 = this.#cache.get(file2);
18388
+ const id = cached2 && sameFileFingerprint(cached2.fingerprint, fingerprint) ? cached2.source.nativeRef.nativeSessionId : await readIdentity(file2, signal);
18389
+ if (id !== nativeSessionId)
18390
+ continue;
18391
+ if (selected)
18392
+ throw new Error("Pi Session identity is ambiguous across files");
18393
+ selected = file2;
18394
+ } catch (error51) {
18395
+ if (!isMissingFileError(error51))
18396
+ throw error51;
18397
+ }
18398
+ }
18399
+ if (!selected)
18400
+ return null;
18401
+ try {
18402
+ const source = await readCandidate(selected, signal);
18403
+ return source?.nativeRef.nativeSessionId === nativeSessionId ? source : null;
18404
+ } catch (error51) {
18405
+ if (isMissingFileError(error51))
18406
+ return null;
18407
+ throw error51;
18162
18408
  }
18163
18409
  }
18164
- if (value.inputTokens === void 0 || value.outputTokens === void 0) {
18165
- throw new Error("Harness Usage request must contain 'inputTokens' and 'outputTokens'");
18166
- }
18167
- const request = value;
18168
- if ((request.cachedInputTokens ?? 0) + (request.cacheWriteInputTokens ?? 0) > request.inputTokens) {
18169
- throw new Error("Harness Usage request cache Tokens must not exceed 'inputTokens'");
18170
- }
18171
- if ((request.reasoningOutputTokens ?? 0) > request.outputTokens) {
18172
- throw new Error("Harness Usage request 'reasoningOutputTokens' must not exceed 'outputTokens'");
18173
- }
18174
- if (request.cacheWrite1hInputTokens !== void 0 && request.cacheWrite1hInputTokens > (request.cacheWriteInputTokens ?? -1)) {
18175
- throw new Error("Harness Usage request 'cacheWrite1hInputTokens' must not exceed 'cacheWriteInputTokens'");
18176
- }
18177
- if (request.startedAtMs === void 0 !== (request.completedAtMs === void 0)) {
18178
- throw new Error("Harness Usage request timing fields must be provided together");
18179
- }
18180
- if (request.startedAtMs !== void 0 && request.completedAtMs !== void 0 && request.completedAtMs < request.startedAtMs) {
18181
- throw new Error("Harness Usage request 'completedAtMs' must not precede 'startedAtMs'");
18182
- }
18183
- return { ...request };
18184
- }
18185
-
18186
- // ../../harness-adapter/dist/live-command-catalog.js
18187
- var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
18188
- // Session lifecycle
18189
- "branch",
18190
- "clear",
18191
- "exit",
18192
- "fork",
18193
- "fresh",
18194
- "new",
18195
- "quit",
18196
- "rename",
18197
- "rename-chat",
18198
- "reset",
18199
- "resume",
18200
- "rewind",
18201
- "session",
18202
- "sessions",
18203
- // Desktop-owned configuration
18204
- "autocompact",
18205
- "color",
18206
- "config",
18207
- "effort",
18208
- "fast",
18209
- "keybindings",
18210
- "model",
18211
- "models",
18212
- "output-style",
18213
- "permissions",
18214
- "settings",
18215
- "statusline",
18216
- "terminal-setup",
18217
- "theme",
18218
- "vim",
18219
- // Trust and approval policy
18220
- "always-approve",
18221
- "auto-mode-setup",
18222
- // Native login
18223
- "login",
18224
- "logout",
18225
- // Work outliving the Turn
18226
- "autopilot",
18227
- "background",
18228
- "bg",
18229
- "goal",
18230
- "jobs",
18231
- "loop",
18232
- "multitask",
18233
- "queue",
18234
- "remote-control",
18235
- "schedule",
18236
- "steer",
18237
- // Native terminal UI
18238
- "copy",
18239
- "debug",
18240
- "feedback",
18241
- "heapdump",
18242
- "share",
18243
- "shell",
18244
- // Plugin and MCP management
18245
- "marketplace",
18246
- "mcp",
18247
- "plugins",
18248
- "reload-plugins"
18249
- ]);
18250
- var COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES = ["__", "hooks-"];
18251
- function isExcludedLiveCommand(name, kind, extra = {}) {
18252
- const normalized = name.trim().replace(/^\//u, "");
18253
- if (new Set(extra.names ?? []).has(normalized))
18254
- return true;
18255
- if (extra.prefixes?.some((prefix) => normalized.startsWith(prefix)))
18256
- return true;
18257
- if (kind === "skill")
18258
- return false;
18259
- return COMMON_EXCLUDED_LIVE_COMMANDS.has(normalized) || COMMON_EXCLUDED_LIVE_COMMAND_PREFIXES.some((prefix) => normalized.startsWith(prefix));
18260
- }
18261
- function liveHarnessCommandPrompt(catalog, idPrefix, commandId, argumentText) {
18262
- if (!commandId.startsWith(idPrefix))
18263
- return null;
18264
- const descriptor = catalog.commands.find(({ id }) => id === commandId);
18265
- if (!descriptor)
18266
- return null;
18267
- const text4 = typeof argumentText === "string" ? argumentText.trim() : "";
18268
- return text4 ? `${descriptor.invocation} ${text4}` : descriptor.invocation;
18269
- }
18270
- function mergeLiveHarnessCommands(builtIns, idPrefix, live, exclusions = {}) {
18271
- if (!live)
18272
- return builtIns;
18273
- const invocations = new Set(builtIns.commands.map(({ invocation }) => invocation));
18274
- const ids = new Set(builtIns.commands.map(({ id }) => id));
18275
- const dynamic = [];
18276
- for (const command of live) {
18277
- const name = command.name.trim().replace(/^\//u, "");
18278
- if (!name || /\s/u.test(name))
18279
- continue;
18280
- if (isExcludedLiveCommand(name, command.kind, exclusions))
18281
- continue;
18282
- const invocation = `/${name}`;
18283
- const id = `${idPrefix}${name.replace(/[^A-Za-z0-9._:-]/gu, "-")}`.slice(0, 128);
18284
- if (invocations.has(invocation) || ids.has(id))
18285
- continue;
18286
- const description = command.description?.trim().slice(0, 512);
18287
- const parsed = harnessCommandDescriptorSchema.safeParse({
18288
- id,
18289
- invocation,
18290
- label: name.slice(0, 128),
18291
- ...description ? { description } : {},
18292
- argumentMode: "text",
18293
- kind: command.kind
18294
- });
18295
- if (!parsed.success)
18296
- continue;
18297
- invocations.add(invocation);
18298
- ids.add(id);
18299
- dynamic.push(parsed.data);
18300
- }
18301
- return harnessCommandCatalogSchema.parse({ commands: [...builtIns.commands, ...dynamic] });
18302
- }
18410
+ };
18303
18411
 
18304
18412
  // ../../../node_modules/diff/libesm/diff/base.js
18305
18413
  var Diff = class {
@@ -19228,6 +19336,7 @@ function gotgenesRecord(value) {
19228
19336
  role: value.type,
19229
19337
  status,
19230
19338
  background: value.isBackground === true,
19339
+ ...subagentConfiguration(value),
19231
19340
  ...text(value.modelName) ? { model: value.modelName } : {},
19232
19341
  ...result ? { resultSummary: result.slice(0, 2048) } : {}
19233
19342
  },
@@ -19355,7 +19464,7 @@ var GotgenesSubagents = class {
19355
19464
  this.observe([
19356
19465
  {
19357
19466
  ...prior,
19358
- child: { ...prior.child, ...parsed.child.model ? { model: parsed.child.model } : {} }
19467
+ child: { ...prior.child, ...subagentConfiguration(parsed.child) }
19359
19468
  }
19360
19469
  ]);
19361
19470
  }
@@ -19518,6 +19627,7 @@ function node(value, depth, budget) {
19518
19627
  kind: value.kind,
19519
19628
  label: value.label,
19520
19629
  state: value.state,
19630
+ ...subagentConfiguration(value),
19521
19631
  ...children.length ? { children } : {}
19522
19632
  };
19523
19633
  }
@@ -19576,6 +19686,7 @@ function states(run) {
19576
19686
  subagentId: id,
19577
19687
  nativeSubagentId: id,
19578
19688
  description: entry.label,
19689
+ ...subagentConfiguration(entry),
19579
19690
  background: true,
19580
19691
  status: statuses[entry.state] ?? "running"
19581
19692
  });
@@ -19622,7 +19733,7 @@ var PiSubagents = class {
19622
19733
  const observed = states(run);
19623
19734
  const retained = this.#children.get(run.id) ?? /* @__PURE__ */ new Map();
19624
19735
  for (const child of observed)
19625
- retained.set(child.subagentId, child);
19736
+ retained.set(child.subagentId, { ...retained.get(child.subagentId), ...child });
19626
19737
  this.#children.set(run.id, retained);
19627
19738
  const children = [...retained.values()];
19628
19739
  if (!publish)
@@ -21708,10 +21819,9 @@ function parsePiNativeCommands(response) {
21708
21819
  });
21709
21820
  }
21710
21821
  function piLiveCommandCatalog(builtIns, native) {
21711
- return mergeLiveHarnessCommands(builtIns, DYNAMIC_ID_PREFIX, native?.map((command) => ({
21822
+ return mergeLiveHarnessCommands(builtIns, DYNAMIC_ID_PREFIX, native?.filter((command) => command.source !== "skill").map((command) => ({
21712
21823
  name: command.name,
21713
- ...command.description ? { description: command.description } : {},
21714
- kind: command.source === "skill" ? "skill" : "command"
21824
+ ...command.description ? { description: command.description } : {}
21715
21825
  })) ?? null, { names: PI_EXCLUDED_COMMANDS });
21716
21826
  }
21717
21827
  function piDynamicCommandPrompt(catalog, commandId, argumentText) {
@@ -22407,6 +22517,9 @@ var PiRpcSession = class {
22407
22517
  child.stderr.on("data", (chunk) => {
22408
22518
  this.#stderrTail = sanitizeDiagnosticTail(`${this.#stderrTail}${chunk.toString()}`);
22409
22519
  });
22520
+ child.stdin.on("error", (error51) => {
22521
+ this.#fail(new PiRpcFaultError("processExited", `Pi RPC stdin closed: ${error51.message}`, this.stderrTail));
22522
+ });
22410
22523
  child.once("error", (error51) => {
22411
22524
  const kind = isRecord9(error51) && error51.code === "ENOENT" ? "notInstalled" : "unavailable";
22412
22525
  this.#fail(new PiRpcFaultError(kind, `Pi RPC failed to start: ${error51.message}`, this.stderrTail));
@@ -23785,7 +23898,19 @@ var PiHarnessSession = class {
23785
23898
  handleTransportFault(error51) {
23786
23899
  queueMicrotask(() => this.#fault(error51));
23787
23900
  }
23901
+ #subagentConfiguration() {
23902
+ const state2 = this.#state;
23903
+ const model2 = state2.effectiveModel ? decodePiModelRef(state2.effectiveModel).id : void 0;
23904
+ return {
23905
+ ...model2 ? { model: model2 } : {},
23906
+ ...state2.effectiveThinkingOptionId ? { reasoningEffort: state2.effectiveThinkingOptionId } : {}
23907
+ };
23908
+ }
23788
23909
  async readSnapshot() {
23910
+ const result = await this.#readSnapshot();
23911
+ return result.ok ? { ok: true, value: configureSubagentSnapshot(result.value, this.#subagentConfiguration()) } : result;
23912
+ }
23913
+ async #readSnapshot() {
23789
23914
  if (this.#phase !== "open") {
23790
23915
  return { ok: false, error: invalidState("Pi Session is not open") };
23791
23916
  }
@@ -25090,6 +25215,7 @@ var PiHarnessSession = class {
25090
25215
  }
25091
25216
  }
25092
25217
  #event(event) {
25218
+ event = configureSubagentEvent(event, this.#subagentConfiguration());
25093
25219
  this.#channel.emit({ kind: "event", event });
25094
25220
  }
25095
25221
  #newItemId() {